blob: ad177b752db11976e5c0035429bb976a27c9aeba [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) {
Alexey Bataevc2e88a82017-12-04 21:30:42 +0000124 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataeve83b3e82017-12-08 20:18:58 +0000125 for (auto *E : S.counters()) {
126 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
127 (void)PreCondScope.addPrivate(VD, [&CGF, VD]() {
128 return CGF.CreateMemTemp(VD->getType().getNonReferenceType());
129 });
130 }
Alexey Bataevc2e88a82017-12-04 21:30:42 +0000131 (void)PreCondScope.Privatize();
Alexey Bataev5a3af132016-03-29 08:58:54 +0000132 if (auto *LD = dyn_cast<OMPLoopDirective>(&S)) {
133 if (auto *PreInits = cast_or_null<DeclStmt>(LD->getPreInits())) {
134 for (const auto *I : PreInits->decls())
135 CGF.EmitVarDecl(cast<VarDecl>(*I));
136 }
137 }
138 }
139
140public:
141 OMPLoopScope(CodeGenFunction &CGF, const OMPLoopDirective &S)
142 : CodeGenFunction::RunCleanupsScope(CGF) {
143 emitPreInitStmt(CGF, S);
144 }
145};
146
Alexey Bataev3392d762016-02-16 11:18:12 +0000147} // namespace
148
Alexey Bataevf8365372017-11-17 17:57:25 +0000149static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
150 const OMPExecutableDirective &S,
151 const RegionCodeGenTy &CodeGen);
152
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000153LValue CodeGenFunction::EmitOMPSharedLValue(const Expr *E) {
154 if (auto *OrigDRE = dyn_cast<DeclRefExpr>(E)) {
155 if (auto *OrigVD = dyn_cast<VarDecl>(OrigDRE->getDecl())) {
156 OrigVD = OrigVD->getCanonicalDecl();
157 bool IsCaptured =
158 LambdaCaptureFields.lookup(OrigVD) ||
159 (CapturedStmtInfo && CapturedStmtInfo->lookup(OrigVD)) ||
160 (CurCodeDecl && isa<BlockDecl>(CurCodeDecl));
161 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD), IsCaptured,
162 OrigDRE->getType(), VK_LValue, OrigDRE->getExprLoc());
163 return EmitLValue(&DRE);
164 }
165 }
166 return EmitLValue(E);
167}
168
Alexey Bataev1189bd02016-01-26 12:20:39 +0000169llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) {
170 auto &C = getContext();
171 llvm::Value *Size = nullptr;
172 auto SizeInChars = C.getTypeSizeInChars(Ty);
173 if (SizeInChars.isZero()) {
174 // getTypeSizeInChars() returns 0 for a VLA.
175 while (auto *VAT = C.getAsVariableArrayType(Ty)) {
176 llvm::Value *ArraySize;
177 std::tie(ArraySize, Ty) = getVLASize(VAT);
178 Size = Size ? Builder.CreateNUWMul(Size, ArraySize) : ArraySize;
179 }
180 SizeInChars = C.getTypeSizeInChars(Ty);
181 if (SizeInChars.isZero())
182 return llvm::ConstantInt::get(SizeTy, /*V=*/0);
183 Size = Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars));
184 } else
185 Size = CGM.getSize(SizeInChars);
186 return Size;
187}
188
Alexey Bataev2377fe92015-09-10 08:12:02 +0000189void CodeGenFunction::GenerateOpenMPCapturedVars(
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000190 const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000191 const RecordDecl *RD = S.getCapturedRecordDecl();
192 auto CurField = RD->field_begin();
193 auto CurCap = S.captures().begin();
194 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
195 E = S.capture_init_end();
196 I != E; ++I, ++CurField, ++CurCap) {
197 if (CurField->hasCapturedVLAType()) {
198 auto VAT = CurField->getCapturedVLAType();
Samuel Antaobed3c462015-10-02 16:14:20 +0000199 auto *Val = VLASizeMap[VAT->getSizeExpr()];
Samuel Antaobed3c462015-10-02 16:14:20 +0000200 CapturedVars.push_back(Val);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000201 } else if (CurCap->capturesThis())
202 CapturedVars.push_back(CXXThisValue);
Samuel Antao6d004262016-06-16 18:39:34 +0000203 else if (CurCap->capturesVariableByCopy()) {
204 llvm::Value *CV =
205 EmitLoadOfLValue(EmitLValue(*I), SourceLocation()).getScalarVal();
206
207 // If the field is not a pointer, we need to save the actual value
208 // and load it as a void pointer.
209 if (!CurField->getType()->isAnyPointerType()) {
210 auto &Ctx = getContext();
211 auto DstAddr = CreateMemTemp(
212 Ctx.getUIntPtrType(),
213 Twine(CurCap->getCapturedVar()->getName()) + ".casted");
214 LValue DstLV = MakeAddrLValue(DstAddr, Ctx.getUIntPtrType());
215
216 auto *SrcAddrVal = EmitScalarConversion(
217 DstAddr.getPointer(), Ctx.getPointerType(Ctx.getUIntPtrType()),
218 Ctx.getPointerType(CurField->getType()), SourceLocation());
219 LValue SrcLV =
220 MakeNaturalAlignAddrLValue(SrcAddrVal, CurField->getType());
221
222 // Store the value using the source type pointer.
223 EmitStoreThroughLValue(RValue::get(CV), SrcLV);
224
225 // Load the value using the destination type pointer.
226 CV = EmitLoadOfLValue(DstLV, SourceLocation()).getScalarVal();
227 }
228 CapturedVars.push_back(CV);
229 } else {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000230 assert(CurCap->capturesVariable() && "Expected capture by reference.");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000231 CapturedVars.push_back(EmitLValue(*I).getAddress().getPointer());
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000232 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000233 }
234}
235
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000236static Address castValueFromUintptr(CodeGenFunction &CGF, QualType DstType,
237 StringRef Name, LValue AddrLV,
238 bool isReferenceType = false) {
239 ASTContext &Ctx = CGF.getContext();
240
241 auto *CastedPtr = CGF.EmitScalarConversion(
242 AddrLV.getAddress().getPointer(), Ctx.getUIntPtrType(),
243 Ctx.getPointerType(DstType), SourceLocation());
244 auto TmpAddr =
245 CGF.MakeNaturalAlignAddrLValue(CastedPtr, Ctx.getPointerType(DstType))
246 .getAddress();
247
248 // If we are dealing with references we need to return the address of the
249 // reference instead of the reference of the value.
250 if (isReferenceType) {
251 QualType RefType = Ctx.getLValueReferenceType(DstType);
252 auto *RefVal = TmpAddr.getPointer();
253 TmpAddr = CGF.CreateMemTemp(RefType, Twine(Name) + ".ref");
254 auto TmpLVal = CGF.MakeAddrLValue(TmpAddr, RefType);
Akira Hatanaka642f7992016-10-18 19:05:41 +0000255 CGF.EmitStoreThroughLValue(RValue::get(RefVal), TmpLVal, /*isInit*/ true);
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000256 }
257
258 return TmpAddr;
259}
260
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000261static QualType getCanonicalParamType(ASTContext &C, QualType T) {
262 if (T->isLValueReferenceType()) {
263 return C.getLValueReferenceType(
264 getCanonicalParamType(C, T.getNonReferenceType()),
265 /*SpelledAsLValue=*/false);
266 }
267 if (T->isPointerType())
268 return C.getPointerType(getCanonicalParamType(C, T->getPointeeType()));
Alexey Bataev1b48c5e2017-10-24 19:52:31 +0000269 if (auto *A = T->getAsArrayTypeUnsafe()) {
270 if (auto *VLA = dyn_cast<VariableArrayType>(A))
271 return getCanonicalParamType(C, VLA->getElementType());
272 else if (!A->isVariablyModifiedType())
273 return C.getCanonicalType(T);
274 }
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000275 return C.getCanonicalParamType(T);
276}
277
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000278namespace {
279 /// Contains required data for proper outlined function codegen.
280 struct FunctionOptions {
281 /// Captured statement for which the function is generated.
282 const CapturedStmt *S = nullptr;
283 /// true if cast to/from UIntPtr is required for variables captured by
284 /// value.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000285 const bool UIntPtrCastRequired = true;
Alexey Bataeve754b182017-08-09 19:38:53 +0000286 /// true if only casted arguments must be registered as local args or VLA
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000287 /// sizes.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000288 const bool RegisterCastedArgsOnly = false;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000289 /// Name of the generated function.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000290 const StringRef FunctionName;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000291 explicit FunctionOptions(const CapturedStmt *S, bool UIntPtrCastRequired,
292 bool RegisterCastedArgsOnly,
Alexey Bataev4aa19052017-08-08 16:45:36 +0000293 StringRef FunctionName)
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000294 : S(S), UIntPtrCastRequired(UIntPtrCastRequired),
295 RegisterCastedArgsOnly(UIntPtrCastRequired && RegisterCastedArgsOnly),
Alexey Bataev4aa19052017-08-08 16:45:36 +0000296 FunctionName(FunctionName) {}
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000297 };
298}
299
Alexey Bataeve754b182017-08-09 19:38:53 +0000300static llvm::Function *emitOutlinedFunctionPrologue(
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000301 CodeGenFunction &CGF, FunctionArgList &Args,
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000302 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>>
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000303 &LocalAddrs,
304 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>>
305 &VLASizes,
306 llvm::Value *&CXXThisValue, const FunctionOptions &FO) {
307 const CapturedDecl *CD = FO.S->getCapturedDecl();
308 const RecordDecl *RD = FO.S->getCapturedRecordDecl();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000309 assert(CD->hasBody() && "missing CapturedDecl body");
310
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000311 CXXThisValue = nullptr;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000312 // Build the argument list.
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000313 CodeGenModule &CGM = CGF.CGM;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000314 ASTContext &Ctx = CGM.getContext();
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000315 FunctionArgList TargetArgs;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000316 Args.append(CD->param_begin(),
317 std::next(CD->param_begin(), CD->getContextParamPosition()));
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000318 TargetArgs.append(
319 CD->param_begin(),
320 std::next(CD->param_begin(), CD->getContextParamPosition()));
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000321 auto I = FO.S->captures().begin();
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000322 FunctionDecl *DebugFunctionDecl = nullptr;
323 if (!FO.UIntPtrCastRequired) {
324 FunctionProtoType::ExtProtoInfo EPI;
325 DebugFunctionDecl = FunctionDecl::Create(
326 Ctx, Ctx.getTranslationUnitDecl(), FO.S->getLocStart(),
327 SourceLocation(), DeclarationName(), Ctx.VoidTy,
328 Ctx.getTrivialTypeSourceInfo(
329 Ctx.getFunctionType(Ctx.VoidTy, llvm::None, EPI)),
330 SC_Static, /*isInlineSpecified=*/false, /*hasWrittenPrototype=*/false);
331 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000332 for (auto *FD : RD->fields()) {
333 QualType ArgType = FD->getType();
334 IdentifierInfo *II = nullptr;
335 VarDecl *CapVar = nullptr;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000336
337 // If this is a capture by copy and the type is not a pointer, the outlined
338 // function argument type should be uintptr and the value properly casted to
339 // uintptr. This is necessary given that the runtime library is only able to
340 // deal with pointers. We can pass in the same way the VLA type sizes to the
341 // outlined function.
Samuel Antao6d004262016-06-16 18:39:34 +0000342 if ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000343 I->capturesVariableArrayType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000344 if (FO.UIntPtrCastRequired)
345 ArgType = Ctx.getUIntPtrType();
346 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000347
348 if (I->capturesVariable() || I->capturesVariableByCopy()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000349 CapVar = I->getCapturedVar();
350 II = CapVar->getIdentifier();
351 } else if (I->capturesThis())
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000352 II = &Ctx.Idents.get("this");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000353 else {
354 assert(I->capturesVariableArrayType());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000355 II = &Ctx.Idents.get("vla");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000356 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000357 if (ArgType->isVariablyModifiedType())
Alexey Bataev1b48c5e2017-10-24 19:52:31 +0000358 ArgType = getCanonicalParamType(Ctx, ArgType);
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000359 VarDecl *Arg;
360 if (DebugFunctionDecl && (CapVar || I->capturesThis())) {
361 Arg = ParmVarDecl::Create(
362 Ctx, DebugFunctionDecl,
363 CapVar ? CapVar->getLocStart() : FD->getLocStart(),
364 CapVar ? CapVar->getLocation() : FD->getLocation(), II, ArgType,
365 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
366 } else {
367 Arg = ImplicitParamDecl::Create(Ctx, /*DC=*/nullptr, FD->getLocation(),
368 II, ArgType, ImplicitParamDecl::Other);
369 }
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000370 Args.emplace_back(Arg);
371 // Do not cast arguments if we emit function with non-original types.
372 TargetArgs.emplace_back(
373 FO.UIntPtrCastRequired
374 ? Arg
375 : CGM.getOpenMPRuntime().translateParameter(FD, Arg));
Alexey Bataev2377fe92015-09-10 08:12:02 +0000376 ++I;
377 }
378 Args.append(
379 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
380 CD->param_end());
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000381 TargetArgs.append(
382 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
383 CD->param_end());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000384
385 // Create the function declaration.
Alexey Bataev2377fe92015-09-10 08:12:02 +0000386 const CGFunctionInfo &FuncInfo =
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000387 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, TargetArgs);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000388 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
389
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000390 llvm::Function *F =
391 llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
392 FO.FunctionName, &CGM.getModule());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000393 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
394 if (CD->isNothrow())
Alexey Bataev2c7eee52017-08-04 19:10:54 +0000395 F->setDoesNotThrow();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000396
397 // Generate the function.
Alexey Bataev6e01dc12017-08-14 16:03:47 +0000398 CGF.StartFunction(CD, Ctx.VoidTy, F, FuncInfo, TargetArgs,
399 FO.S->getLocStart(), CD->getBody()->getLocStart());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000400 unsigned Cnt = CD->getContextParamPosition();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000401 I = FO.S->captures().begin();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000402 for (auto *FD : RD->fields()) {
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000403 // Do not map arguments if we emit function with non-original types.
404 Address LocalAddr(Address::invalid());
405 if (!FO.UIntPtrCastRequired && Args[Cnt] != TargetArgs[Cnt]) {
406 LocalAddr = CGM.getOpenMPRuntime().getParameterAddress(CGF, Args[Cnt],
407 TargetArgs[Cnt]);
408 } else {
409 LocalAddr = CGF.GetAddrOfLocalVar(Args[Cnt]);
410 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000411 // If we are capturing a pointer by copy we don't need to do anything, just
412 // use the value that we get from the arguments.
413 if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
Samuel Antao403ffd42016-07-27 22:49:49 +0000414 const VarDecl *CurVD = I->getCapturedVar();
Samuel Antao403ffd42016-07-27 22:49:49 +0000415 // If the variable is a reference we need to materialize it here.
416 if (CurVD->getType()->isReferenceType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000417 Address RefAddr = CGF.CreateMemTemp(
418 CurVD->getType(), CGM.getPointerAlign(), ".materialized_ref");
419 CGF.EmitStoreOfScalar(LocalAddr.getPointer(), RefAddr,
420 /*Volatile=*/false, CurVD->getType());
Samuel Antao403ffd42016-07-27 22:49:49 +0000421 LocalAddr = RefAddr;
422 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000423 if (!FO.RegisterCastedArgsOnly)
424 LocalAddrs.insert({Args[Cnt], {CurVD, LocalAddr}});
Richard Trieucc3949d2016-02-18 22:34:54 +0000425 ++Cnt;
426 ++I;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000427 continue;
428 }
429
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000430 LValue ArgLVal = CGF.MakeAddrLValue(LocalAddr, Args[Cnt]->getType(),
431 AlignmentSource::Decl);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000432 if (FD->hasCapturedVLAType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000433 if (FO.UIntPtrCastRequired) {
434 ArgLVal = CGF.MakeAddrLValue(castValueFromUintptr(CGF, FD->getType(),
435 Args[Cnt]->getName(),
436 ArgLVal),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000437 FD->getType(), AlignmentSource::Decl);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000438 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000439 auto *ExprArg =
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000440 CGF.EmitLoadOfLValue(ArgLVal, SourceLocation()).getScalarVal();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000441 auto VAT = FD->getCapturedVLAType();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000442 VLASizes.insert({Args[Cnt], {VAT->getSizeExpr(), ExprArg}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000443 } else if (I->capturesVariable()) {
444 auto *Var = I->getCapturedVar();
445 QualType VarTy = Var->getType();
446 Address ArgAddr = ArgLVal.getAddress();
447 if (!VarTy->isReferenceType()) {
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000448 if (ArgLVal.getType()->isLValueReferenceType()) {
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +0000449 ArgAddr = CGF.EmitLoadOfReference(ArgLVal);
Alexey Bataevac5eabb2016-11-07 11:16:04 +0000450 } else if (!VarTy->isVariablyModifiedType() || !VarTy->isPointerType()) {
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000451 assert(ArgLVal.getType()->isPointerType());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000452 ArgAddr = CGF.EmitLoadOfPointer(
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000453 ArgAddr, ArgLVal.getType()->castAs<PointerType>());
454 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000455 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000456 if (!FO.RegisterCastedArgsOnly) {
457 LocalAddrs.insert(
458 {Args[Cnt],
459 {Var, Address(ArgAddr.getPointer(), Ctx.getDeclAlign(Var))}});
460 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000461 } else if (I->capturesVariableByCopy()) {
462 assert(!FD->getType()->isAnyPointerType() &&
463 "Not expecting a captured pointer.");
464 auto *Var = I->getCapturedVar();
465 QualType VarTy = Var->getType();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000466 LocalAddrs.insert(
467 {Args[Cnt],
468 {Var,
469 FO.UIntPtrCastRequired
470 ? castValueFromUintptr(CGF, FD->getType(), Args[Cnt]->getName(),
471 ArgLVal, VarTy->isReferenceType())
472 : ArgLVal.getAddress()}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000473 } else {
474 // If 'this' is captured, load it into CXXThisValue.
475 assert(I->capturesThis());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000476 CXXThisValue = CGF.EmitLoadOfLValue(ArgLVal, Args[Cnt]->getLocation())
477 .getScalarVal();
478 LocalAddrs.insert({Args[Cnt], {nullptr, ArgLVal.getAddress()}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000479 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000480 ++Cnt;
481 ++I;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000482 }
483
Alexey Bataeve754b182017-08-09 19:38:53 +0000484 return F;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000485}
486
487llvm::Function *
488CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) {
489 assert(
490 CapturedStmtInfo &&
491 "CapturedStmtInfo should be set when generating the captured function");
492 const CapturedDecl *CD = S.getCapturedDecl();
493 // Build the argument list.
494 bool NeedWrapperFunction =
495 getDebugInfo() &&
496 CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo;
497 FunctionArgList Args;
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000498 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>> LocalAddrs;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000499 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>> VLASizes;
Alexey Bataeve754b182017-08-09 19:38:53 +0000500 SmallString<256> Buffer;
501 llvm::raw_svector_ostream Out(Buffer);
502 Out << CapturedStmtInfo->getHelperName();
503 if (NeedWrapperFunction)
504 Out << "_debug__";
Alexey Bataev4aa19052017-08-08 16:45:36 +0000505 FunctionOptions FO(&S, !NeedWrapperFunction, /*RegisterCastedArgsOnly=*/false,
Alexey Bataeve754b182017-08-09 19:38:53 +0000506 Out.str());
507 llvm::Function *F = emitOutlinedFunctionPrologue(*this, Args, LocalAddrs,
508 VLASizes, CXXThisValue, FO);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000509 for (const auto &LocalAddrPair : LocalAddrs) {
510 if (LocalAddrPair.second.first) {
511 setAddrOfLocalVar(LocalAddrPair.second.first,
512 LocalAddrPair.second.second);
513 }
514 }
515 for (const auto &VLASizePair : VLASizes)
516 VLASizeMap[VLASizePair.second.first] = VLASizePair.second.second;
Serge Pavlov3a561452015-12-06 14:32:39 +0000517 PGO.assignRegionCounters(GlobalDecl(CD), F);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000518 CapturedStmtInfo->EmitBody(*this, CD->getBody());
519 FinishFunction(CD->getBodyRBrace());
Alexey Bataeve754b182017-08-09 19:38:53 +0000520 if (!NeedWrapperFunction)
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000521 return F;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000522
Alexey Bataevefd884d2017-08-04 21:26:25 +0000523 FunctionOptions WrapperFO(&S, /*UIntPtrCastRequired=*/true,
Alexey Bataeve754b182017-08-09 19:38:53 +0000524 /*RegisterCastedArgsOnly=*/true,
525 CapturedStmtInfo->getHelperName());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000526 CodeGenFunction WrapperCGF(CGM, /*suppressNewContext=*/true);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000527 Args.clear();
528 LocalAddrs.clear();
529 VLASizes.clear();
530 llvm::Function *WrapperF =
531 emitOutlinedFunctionPrologue(WrapperCGF, Args, LocalAddrs, VLASizes,
Alexey Bataeve754b182017-08-09 19:38:53 +0000532 WrapperCGF.CXXThisValue, WrapperFO);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000533 llvm::SmallVector<llvm::Value *, 4> CallArgs;
534 for (const auto *Arg : Args) {
535 llvm::Value *CallArg;
536 auto I = LocalAddrs.find(Arg);
537 if (I != LocalAddrs.end()) {
Alexey Bataev7ba57af2017-10-17 16:47:34 +0000538 LValue LV = WrapperCGF.MakeAddrLValue(
539 I->second.second,
540 I->second.first ? I->second.first->getType() : Arg->getType(),
541 AlignmentSource::Decl);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000542 CallArg = WrapperCGF.EmitLoadOfScalar(LV, SourceLocation());
543 } else {
544 auto EI = VLASizes.find(Arg);
545 if (EI != VLASizes.end())
546 CallArg = EI->second.second;
547 else {
548 LValue LV = WrapperCGF.MakeAddrLValue(WrapperCGF.GetAddrOfLocalVar(Arg),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000549 Arg->getType(),
550 AlignmentSource::Decl);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000551 CallArg = WrapperCGF.EmitLoadOfScalar(LV, SourceLocation());
552 }
553 }
Alexey Bataev7ba57af2017-10-17 16:47:34 +0000554 CallArgs.emplace_back(WrapperCGF.EmitFromMemory(CallArg, Arg->getType()));
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000555 }
Alexey Bataev3c595a62017-08-14 15:01:03 +0000556 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(WrapperCGF, S.getLocStart(),
557 F, CallArgs);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000558 WrapperCGF.FinishFunction();
559 return WrapperF;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000560}
561
Alexey Bataev9959db52014-05-06 10:08:46 +0000562//===----------------------------------------------------------------------===//
563// OpenMP Directive Emission
564//===----------------------------------------------------------------------===//
Alexey Bataev420d45b2015-04-14 05:11:24 +0000565void CodeGenFunction::EmitOMPAggregateAssign(
John McCall7f416cc2015-09-08 08:05:57 +0000566 Address DestAddr, Address SrcAddr, QualType OriginalType,
567 const llvm::function_ref<void(Address, Address)> &CopyGen) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000568 // Perform element-by-element initialization.
569 QualType ElementTy;
John McCall7f416cc2015-09-08 08:05:57 +0000570
571 // Drill down to the base element type on both arrays.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000572 auto ArrayTy = OriginalType->getAsArrayTypeUnsafe();
John McCall7f416cc2015-09-08 08:05:57 +0000573 auto NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
574 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
575
576 auto SrcBegin = SrcAddr.getPointer();
577 auto DestBegin = DestAddr.getPointer();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000578 // Cast from pointer to array type to pointer to single element.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000579 auto DestEnd = Builder.CreateGEP(DestBegin, NumElements);
580 // The basic structure here is a while-do loop.
581 auto BodyBB = createBasicBlock("omp.arraycpy.body");
582 auto DoneBB = createBasicBlock("omp.arraycpy.done");
583 auto IsEmpty =
584 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
585 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000586
Alexey Bataev420d45b2015-04-14 05:11:24 +0000587 // Enter the loop body, making that address the current address.
588 auto EntryBB = Builder.GetInsertBlock();
589 EmitBlock(BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000590
591 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
592
593 llvm::PHINode *SrcElementPHI =
594 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
595 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
596 Address SrcElementCurrent =
597 Address(SrcElementPHI,
598 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
599
600 llvm::PHINode *DestElementPHI =
601 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
602 DestElementPHI->addIncoming(DestBegin, EntryBB);
603 Address DestElementCurrent =
604 Address(DestElementPHI,
605 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000606
Alexey Bataev420d45b2015-04-14 05:11:24 +0000607 // Emit copy.
608 CopyGen(DestElementCurrent, SrcElementCurrent);
609
610 // Shift the address forward by one element.
611 auto DestElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000612 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000613 auto SrcElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000614 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000615 // Check whether we've reached the end.
616 auto Done =
617 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
618 Builder.CreateCondBr(Done, DoneBB, BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000619 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
620 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
Alexey Bataev420d45b2015-04-14 05:11:24 +0000621
622 // Done.
623 EmitBlock(DoneBB, /*IsFinished=*/true);
624}
625
John McCall7f416cc2015-09-08 08:05:57 +0000626void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
627 Address SrcAddr, const VarDecl *DestVD,
Alexey Bataev420d45b2015-04-14 05:11:24 +0000628 const VarDecl *SrcVD, const Expr *Copy) {
629 if (OriginalType->isArrayType()) {
630 auto *BO = dyn_cast<BinaryOperator>(Copy);
631 if (BO && BO->getOpcode() == BO_Assign) {
632 // Perform simple memcpy for simple copying.
John McCall7f416cc2015-09-08 08:05:57 +0000633 EmitAggregateAssign(DestAddr, SrcAddr, OriginalType);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000634 } else {
635 // For arrays with complex element types perform element by element
636 // copying.
John McCall7f416cc2015-09-08 08:05:57 +0000637 EmitOMPAggregateAssign(
Alexey Bataev420d45b2015-04-14 05:11:24 +0000638 DestAddr, SrcAddr, OriginalType,
John McCall7f416cc2015-09-08 08:05:57 +0000639 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000640 // Working with the single array element, so have to remap
641 // destination and source variables to corresponding array
642 // elements.
John McCall7f416cc2015-09-08 08:05:57 +0000643 CodeGenFunction::OMPPrivateScope Remap(*this);
644 Remap.addPrivate(DestVD, [DestElement]() -> Address {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000645 return DestElement;
646 });
647 Remap.addPrivate(
John McCall7f416cc2015-09-08 08:05:57 +0000648 SrcVD, [SrcElement]() -> Address { return SrcElement; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000649 (void)Remap.Privatize();
John McCall7f416cc2015-09-08 08:05:57 +0000650 EmitIgnoredExpr(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000651 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000652 }
Alexey Bataev420d45b2015-04-14 05:11:24 +0000653 } else {
654 // Remap pseudo source variable to private copy.
John McCall7f416cc2015-09-08 08:05:57 +0000655 CodeGenFunction::OMPPrivateScope Remap(*this);
656 Remap.addPrivate(SrcVD, [SrcAddr]() -> Address { return SrcAddr; });
657 Remap.addPrivate(DestVD, [DestAddr]() -> Address { return DestAddr; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000658 (void)Remap.Privatize();
659 // Emit copying of the whole variable.
John McCall7f416cc2015-09-08 08:05:57 +0000660 EmitIgnoredExpr(Copy);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000661 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000662}
663
Alexey Bataev69c62a92015-04-15 04:52:20 +0000664bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
665 OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000666 if (!HaveInsertPoint())
667 return false;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000668 bool FirstprivateIsLastprivate = false;
669 llvm::DenseSet<const VarDecl *> Lastprivates;
670 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
671 for (const auto *D : C->varlists())
672 Lastprivates.insert(
673 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
674 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000675 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
Alexey Bataev9afe5752016-05-24 07:40:12 +0000676 CGCapturedStmtInfo CapturesInfo(cast<CapturedStmt>(*D.getAssociatedStmt()));
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000677 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000678 auto IRef = C->varlist_begin();
679 auto InitsRef = C->inits().begin();
680 for (auto IInit : C->private_copies()) {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000681 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000682 bool ThisFirstprivateIsLastprivate =
683 Lastprivates.count(OrigVD->getCanonicalDecl()) > 0;
Alexey Bataev9afe5752016-05-24 07:40:12 +0000684 auto *CapFD = CapturesInfo.lookup(OrigVD);
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000685 auto *FD = CapturedStmtInfo->lookup(OrigVD);
Alexey Bataev9afe5752016-05-24 07:40:12 +0000686 if (!ThisFirstprivateIsLastprivate && FD && (FD == CapFD) &&
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000687 !FD->getType()->isReferenceType()) {
688 EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl());
689 ++IRef;
690 ++InitsRef;
691 continue;
692 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000693 FirstprivateIsLastprivate =
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000694 FirstprivateIsLastprivate || ThisFirstprivateIsLastprivate;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000695 if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000696 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
697 auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
698 bool IsRegistered;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000699 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
700 /*RefersToEnclosingVariableOrCapture=*/FD != nullptr,
701 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +0000702 Address OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataevfeddd642016-04-22 09:05:03 +0000703 QualType Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000704 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000705 // Emit VarDecl with copy init for arrays.
706 // Get the address of the original variable captured in current
707 // captured region.
John McCall7f416cc2015-09-08 08:05:57 +0000708 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000709 auto Emission = EmitAutoVarAlloca(*VD);
710 auto *Init = VD->getInit();
711 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
712 // Perform simple memcpy.
713 EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr,
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000714 Type);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000715 } else {
716 EmitOMPAggregateAssign(
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000717 Emission.getAllocatedAddress(), OriginalAddr, Type,
John McCall7f416cc2015-09-08 08:05:57 +0000718 [this, VDInit, Init](Address DestElement,
719 Address SrcElement) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000720 // Clean up any temporaries needed by the initialization.
721 RunCleanupsScope InitScope(*this);
722 // Emit initialization for single element.
John McCall7f416cc2015-09-08 08:05:57 +0000723 setAddrOfLocalVar(VDInit, SrcElement);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000724 EmitAnyExprToMem(Init, DestElement,
725 Init->getType().getQualifiers(),
726 /*IsInitializer*/ false);
727 LocalDeclMap.erase(VDInit);
728 });
729 }
730 EmitAutoVarCleanups(Emission);
731 return Emission.getAllocatedAddress();
732 });
733 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000734 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000735 // Emit private VarDecl with copy init.
736 // Remap temp VDInit variable to the address of the original
737 // variable
738 // (for proper handling of captured global variables).
John McCall7f416cc2015-09-08 08:05:57 +0000739 setAddrOfLocalVar(VDInit, OriginalAddr);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000740 EmitDecl(*VD);
741 LocalDeclMap.erase(VDInit);
742 return GetAddrOfLocalVar(VD);
743 });
744 }
745 assert(IsRegistered &&
746 "firstprivate var already registered as private");
747 // Silence the warning about unused variable.
748 (void)IsRegistered;
749 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000750 ++IRef;
751 ++InitsRef;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000752 }
753 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000754 return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000755}
756
Alexey Bataev03b340a2014-10-21 03:16:40 +0000757void CodeGenFunction::EmitOMPPrivateClause(
758 const OMPExecutableDirective &D,
759 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000760 if (!HaveInsertPoint())
761 return;
Alexey Bataev50a64582015-04-22 12:24:45 +0000762 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000763 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000764 auto IRef = C->varlist_begin();
765 for (auto IInit : C->private_copies()) {
766 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000767 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
768 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
769 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000770 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev50a64582015-04-22 12:24:45 +0000771 // Emit private VarDecl with copy init.
772 EmitDecl(*VD);
773 return GetAddrOfLocalVar(VD);
774 });
775 assert(IsRegistered && "private var already registered as private");
776 // Silence the warning about unused variable.
777 (void)IsRegistered;
778 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000779 ++IRef;
780 }
781 }
782}
783
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000784bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000785 if (!HaveInsertPoint())
786 return false;
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000787 // threadprivate_var1 = master_threadprivate_var1;
788 // operator=(threadprivate_var2, master_threadprivate_var2);
789 // ...
790 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000791 llvm::DenseSet<const VarDecl *> CopiedVars;
792 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000793 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000794 auto IRef = C->varlist_begin();
795 auto ISrcRef = C->source_exprs().begin();
796 auto IDestRef = C->destination_exprs().begin();
797 for (auto *AssignOp : C->assignment_ops()) {
798 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000799 QualType Type = VD->getType();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000800 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000801 // Get the address of the master variable. If we are emitting code with
802 // TLS support, the address is passed from the master as field in the
803 // captured declaration.
John McCall7f416cc2015-09-08 08:05:57 +0000804 Address MasterAddr = Address::invalid();
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000805 if (getLangOpts().OpenMPUseTLS &&
806 getContext().getTargetInfo().isTLSSupported()) {
807 assert(CapturedStmtInfo->lookup(VD) &&
808 "Copyin threadprivates should have been captured!");
809 DeclRefExpr DRE(const_cast<VarDecl *>(VD), true, (*IRef)->getType(),
810 VK_LValue, (*IRef)->getExprLoc());
811 MasterAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000812 LocalDeclMap.erase(VD);
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000813 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000814 MasterAddr =
815 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
816 : CGM.GetAddrOfGlobal(VD),
817 getContext().getDeclAlign(VD));
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000818 }
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000819 // Get the address of the threadprivate variable.
John McCall7f416cc2015-09-08 08:05:57 +0000820 Address PrivateAddr = EmitLValue(*IRef).getAddress();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000821 if (CopiedVars.size() == 1) {
822 // At first check if current thread is a master thread. If it is, no
823 // need to copy data.
824 CopyBegin = createBasicBlock("copyin.not.master");
825 CopyEnd = createBasicBlock("copyin.not.master.end");
826 Builder.CreateCondBr(
827 Builder.CreateICmpNE(
John McCall7f416cc2015-09-08 08:05:57 +0000828 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
829 Builder.CreatePtrToInt(PrivateAddr.getPointer(), CGM.IntPtrTy)),
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000830 CopyBegin, CopyEnd);
831 EmitBlock(CopyBegin);
832 }
833 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
834 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000835 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000836 }
837 ++IRef;
838 ++ISrcRef;
839 ++IDestRef;
840 }
841 }
842 if (CopyEnd) {
843 // Exit out of copying procedure for non-master thread.
844 EmitBlock(CopyEnd, /*IsFinished=*/true);
845 return true;
846 }
847 return false;
848}
849
Alexey Bataev38e89532015-04-16 04:54:05 +0000850bool CodeGenFunction::EmitOMPLastprivateClauseInit(
851 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000852 if (!HaveInsertPoint())
853 return false;
Alexey Bataev38e89532015-04-16 04:54:05 +0000854 bool HasAtLeastOneLastprivate = false;
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000855 llvm::DenseSet<const VarDecl *> SIMDLCVs;
856 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
857 auto *LoopDirective = cast<OMPLoopDirective>(&D);
858 for (auto *C : LoopDirective->counters()) {
859 SIMDLCVs.insert(
860 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
861 }
862 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000863 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000864 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000865 HasAtLeastOneLastprivate = true;
Alexey Bataevf93095a2016-05-05 08:46:22 +0000866 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()))
867 break;
Alexey Bataev38e89532015-04-16 04:54:05 +0000868 auto IRef = C->varlist_begin();
869 auto IDestRef = C->destination_exprs().begin();
870 for (auto *IInit : C->private_copies()) {
871 // Keep the address of the original variable for future update at the end
872 // of the loop.
873 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000874 // Taskloops do not require additional initialization, it is done in
875 // runtime support library.
Alexey Bataev38e89532015-04-16 04:54:05 +0000876 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
877 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000878 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> Address {
Alexey Bataev38e89532015-04-16 04:54:05 +0000879 DeclRefExpr DRE(
880 const_cast<VarDecl *>(OrigVD),
881 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
882 OrigVD) != nullptr,
883 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
884 return EmitLValue(&DRE).getAddress();
885 });
886 // Check if the variable is also a firstprivate: in this case IInit is
887 // not generated. Initialization of this variable will happen in codegen
888 // for 'firstprivate' clause.
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000889 if (IInit && !SIMDLCVs.count(OrigVD->getCanonicalDecl())) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000890 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000891 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
892 // Emit private VarDecl with copy init.
893 EmitDecl(*VD);
894 return GetAddrOfLocalVar(VD);
895 });
Alexey Bataevd130fd12015-05-13 10:23:02 +0000896 assert(IsRegistered &&
897 "lastprivate var already registered as private");
898 (void)IsRegistered;
899 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000900 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000901 ++IRef;
902 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000903 }
904 }
905 return HasAtLeastOneLastprivate;
906}
907
908void CodeGenFunction::EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000909 const OMPExecutableDirective &D, bool NoFinals,
910 llvm::Value *IsLastIterCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000911 if (!HaveInsertPoint())
912 return;
Alexey Bataev38e89532015-04-16 04:54:05 +0000913 // Emit following code:
914 // if (<IsLastIterCond>) {
915 // orig_var1 = private_orig_var1;
916 // ...
917 // orig_varn = private_orig_varn;
918 // }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000919 llvm::BasicBlock *ThenBB = nullptr;
920 llvm::BasicBlock *DoneBB = nullptr;
921 if (IsLastIterCond) {
922 ThenBB = createBasicBlock(".omp.lastprivate.then");
923 DoneBB = createBasicBlock(".omp.lastprivate.done");
924 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
925 EmitBlock(ThenBB);
926 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000927 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
928 llvm::DenseMap<const VarDecl *, const Expr *> LoopCountersAndUpdates;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000929 if (auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000930 auto IC = LoopDirective->counters().begin();
931 for (auto F : LoopDirective->finals()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000932 auto *D =
933 cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl())->getCanonicalDecl();
934 if (NoFinals)
935 AlreadyEmittedVars.insert(D);
936 else
937 LoopCountersAndUpdates[D] = F;
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000938 ++IC;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000939 }
940 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000941 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
942 auto IRef = C->varlist_begin();
943 auto ISrcRef = C->source_exprs().begin();
944 auto IDestRef = C->destination_exprs().begin();
945 for (auto *AssignOp : C->assignment_ops()) {
946 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
947 QualType Type = PrivateVD->getType();
948 auto *CanonicalVD = PrivateVD->getCanonicalDecl();
949 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
950 // If lastprivate variable is a loop control variable for loop-based
951 // directive, update its value before copyin back to original
952 // variable.
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000953 if (auto *FinalExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
954 EmitIgnoredExpr(FinalExpr);
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000955 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
956 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
957 // Get the address of the original variable.
958 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
959 // Get the address of the private variable.
960 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
961 if (auto RefTy = PrivateVD->getType()->getAs<ReferenceType>())
962 PrivateAddr =
John McCall7f416cc2015-09-08 08:05:57 +0000963 Address(Builder.CreateLoad(PrivateAddr),
964 getNaturalTypeAlignment(RefTy->getPointeeType()));
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000965 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +0000966 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000967 ++IRef;
968 ++ISrcRef;
969 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000970 }
Alexey Bataev005248a2016-02-25 05:25:57 +0000971 if (auto *PostUpdate = C->getPostUpdateExpr())
972 EmitIgnoredExpr(PostUpdate);
Alexey Bataev38e89532015-04-16 04:54:05 +0000973 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000974 if (IsLastIterCond)
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000975 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev38e89532015-04-16 04:54:05 +0000976}
977
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000978void CodeGenFunction::EmitOMPReductionClauseInit(
979 const OMPExecutableDirective &D,
980 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000981 if (!HaveInsertPoint())
982 return;
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000983 SmallVector<const Expr *, 4> Shareds;
984 SmallVector<const Expr *, 4> Privates;
985 SmallVector<const Expr *, 4> ReductionOps;
986 SmallVector<const Expr *, 4> LHSs;
987 SmallVector<const Expr *, 4> RHSs;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000988 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000989 auto IPriv = C->privates().begin();
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000990 auto IRed = C->reduction_ops().begin();
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000991 auto ILHS = C->lhs_exprs().begin();
992 auto IRHS = C->rhs_exprs().begin();
993 for (const auto *Ref : C->varlists()) {
994 Shareds.emplace_back(Ref);
995 Privates.emplace_back(*IPriv);
996 ReductionOps.emplace_back(*IRed);
997 LHSs.emplace_back(*ILHS);
998 RHSs.emplace_back(*IRHS);
999 std::advance(IPriv, 1);
1000 std::advance(IRed, 1);
1001 std::advance(ILHS, 1);
1002 std::advance(IRHS, 1);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001003 }
1004 }
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001005 ReductionCodeGen RedCG(Shareds, Privates, ReductionOps);
1006 unsigned Count = 0;
1007 auto ILHS = LHSs.begin();
1008 auto IRHS = RHSs.begin();
1009 auto IPriv = Privates.begin();
1010 for (const auto *IRef : Shareds) {
1011 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
1012 // Emit private VarDecl with reduction init.
1013 RedCG.emitSharedLValue(*this, Count);
1014 RedCG.emitAggregateType(*this, Count);
1015 auto Emission = EmitAutoVarAlloca(*PrivateVD);
1016 RedCG.emitInitialization(*this, Count, Emission.getAllocatedAddress(),
1017 RedCG.getSharedLValue(Count),
1018 [&Emission](CodeGenFunction &CGF) {
1019 CGF.EmitAutoVarInit(Emission);
1020 return true;
1021 });
1022 EmitAutoVarCleanups(Emission);
1023 Address BaseAddr = RedCG.adjustPrivateAddress(
1024 *this, Count, Emission.getAllocatedAddress());
1025 bool IsRegistered = PrivateScope.addPrivate(
1026 RedCG.getBaseDecl(Count), [BaseAddr]() -> Address { return BaseAddr; });
1027 assert(IsRegistered && "private var already registered as private");
1028 // Silence the warning about unused variable.
1029 (void)IsRegistered;
1030
1031 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
1032 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001033 QualType Type = PrivateVD->getType();
1034 bool isaOMPArraySectionExpr = isa<OMPArraySectionExpr>(IRef);
1035 if (isaOMPArraySectionExpr && Type->isVariablyModifiedType()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001036 // Store the address of the original variable associated with the LHS
1037 // implicit variable.
1038 PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() -> Address {
1039 return RedCG.getSharedLValue(Count).getAddress();
1040 });
1041 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
1042 return GetAddrOfLocalVar(PrivateVD);
1043 });
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001044 } else if ((isaOMPArraySectionExpr && Type->isScalarType()) ||
1045 isa<ArraySubscriptExpr>(IRef)) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001046 // Store the address of the original variable associated with the LHS
1047 // implicit variable.
1048 PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() -> Address {
1049 return RedCG.getSharedLValue(Count).getAddress();
1050 });
1051 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
1052 return Builder.CreateElementBitCast(GetAddrOfLocalVar(PrivateVD),
1053 ConvertTypeForMem(RHSVD->getType()),
1054 "rhs.begin");
1055 });
1056 } else {
1057 QualType Type = PrivateVD->getType();
1058 bool IsArray = getContext().getAsArrayType(Type) != nullptr;
1059 Address OriginalAddr = RedCG.getSharedLValue(Count).getAddress();
1060 // Store the address of the original variable associated with the LHS
1061 // implicit variable.
1062 if (IsArray) {
1063 OriginalAddr = Builder.CreateElementBitCast(
1064 OriginalAddr, ConvertTypeForMem(LHSVD->getType()), "lhs.begin");
1065 }
1066 PrivateScope.addPrivate(
1067 LHSVD, [OriginalAddr]() -> Address { return OriginalAddr; });
1068 PrivateScope.addPrivate(
1069 RHSVD, [this, PrivateVD, RHSVD, IsArray]() -> Address {
1070 return IsArray
1071 ? Builder.CreateElementBitCast(
1072 GetAddrOfLocalVar(PrivateVD),
1073 ConvertTypeForMem(RHSVD->getType()), "rhs.begin")
1074 : GetAddrOfLocalVar(PrivateVD);
1075 });
1076 }
1077 ++ILHS;
1078 ++IRHS;
1079 ++IPriv;
1080 ++Count;
1081 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001082}
1083
1084void CodeGenFunction::EmitOMPReductionClauseFinal(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001085 const OMPExecutableDirective &D, const OpenMPDirectiveKind ReductionKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001086 if (!HaveInsertPoint())
1087 return;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001088 llvm::SmallVector<const Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001089 llvm::SmallVector<const Expr *, 8> LHSExprs;
1090 llvm::SmallVector<const Expr *, 8> RHSExprs;
1091 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001092 bool HasAtLeastOneReduction = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001093 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001094 HasAtLeastOneReduction = true;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001095 Privates.append(C->privates().begin(), C->privates().end());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001096 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
1097 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
1098 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
1099 }
1100 if (HasAtLeastOneReduction) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001101 bool WithNowait = D.getSingleClause<OMPNowaitClause>() ||
1102 isOpenMPParallelDirective(D.getDirectiveKind()) ||
1103 D.getDirectiveKind() == OMPD_simd;
Alexey Bataev617db5f2017-12-04 15:38:33 +00001104 bool SimpleReduction = D.getDirectiveKind() == OMPD_simd ||
1105 D.getDirectiveKind() == OMPD_distribute_simd;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001106 // Emit nowait reduction if nowait clause is present or directive is a
1107 // parallel directive (it always has implicit barrier).
1108 CGM.getOpenMPRuntime().emitReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001109 *this, D.getLocEnd(), Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001110 {WithNowait, SimpleReduction, ReductionKind});
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001111 }
1112}
1113
Alexey Bataev61205072016-03-02 04:57:40 +00001114static void emitPostUpdateForReductionClause(
1115 CodeGenFunction &CGF, const OMPExecutableDirective &D,
1116 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
1117 if (!CGF.HaveInsertPoint())
1118 return;
1119 llvm::BasicBlock *DoneBB = nullptr;
1120 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1121 if (auto *PostUpdate = C->getPostUpdateExpr()) {
1122 if (!DoneBB) {
1123 if (auto *Cond = CondGen(CGF)) {
1124 // If the first post-update expression is found, emit conditional
1125 // block if it was requested.
1126 auto *ThenBB = CGF.createBasicBlock(".omp.reduction.pu");
1127 DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done");
1128 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1129 CGF.EmitBlock(ThenBB);
1130 }
1131 }
1132 CGF.EmitIgnoredExpr(PostUpdate);
1133 }
1134 }
1135 if (DoneBB)
1136 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
1137}
1138
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001139namespace {
1140/// Codegen lambda for appending distribute lower and upper bounds to outlined
1141/// parallel function. This is necessary for combined constructs such as
1142/// 'distribute parallel for'
1143typedef llvm::function_ref<void(CodeGenFunction &,
1144 const OMPExecutableDirective &,
1145 llvm::SmallVectorImpl<llvm::Value *> &)>
1146 CodeGenBoundParametersTy;
1147} // anonymous namespace
1148
1149static void emitCommonOMPParallelDirective(
1150 CodeGenFunction &CGF, const OMPExecutableDirective &S,
1151 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1152 const CodeGenBoundParametersTy &CodeGenBoundParameters) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001153 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
1154 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
1155 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001156 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
Alexey Bataev1d677132015-04-22 13:57:31 +00001157 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00001158 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
1159 /*IgnoreResultAssign*/ true);
1160 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
1161 CGF, NumThreads, NumThreadsClause->getLocStart());
1162 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001163 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001164 CodeGenFunction::RunCleanupsScope ProcBindScope(CGF);
Alexey Bataev7f210c62015-06-18 13:40:03 +00001165 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
1166 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getLocStart());
1167 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001168 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00001169 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1170 if (C->getNameModifier() == OMPD_unknown ||
1171 C->getNameModifier() == OMPD_parallel) {
1172 IfCond = C->getCondition();
1173 break;
1174 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001175 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001176
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001177 OMPParallelScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001178 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001179 // Combining 'distribute' with 'for' requires sharing each 'distribute' chunk
1180 // lower and upper bounds with the pragma 'for' chunking mechanism.
1181 // The following lambda takes care of appending the lower and upper bound
1182 // parameters when necessary
1183 CodeGenBoundParameters(CGF, S, CapturedVars);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001184 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Alexey Bataev1d677132015-04-22 13:57:31 +00001185 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001186 CapturedVars, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001187}
1188
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001189static void emitEmptyBoundParameters(CodeGenFunction &,
1190 const OMPExecutableDirective &,
1191 llvm::SmallVectorImpl<llvm::Value *> &) {}
1192
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001193void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001194 // Emit parallel region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001195 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001196 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001197 bool Copyins = CGF.EmitOMPCopyinClause(S);
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001198 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
1199 if (Copyins) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00001200 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001201 // propagation master's thread values of threadprivate variables to local
1202 // instances of that variables of all other implicit threads.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001203 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1204 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1205 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001206 }
1207 CGF.EmitOMPPrivateClause(S, PrivateScope);
1208 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
1209 (void)PrivateScope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001210 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001211 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001212 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001213 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen,
1214 emitEmptyBoundParameters);
Alexey Bataev61205072016-03-02 04:57:40 +00001215 emitPostUpdateForReductionClause(
1216 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev9959db52014-05-06 10:08:46 +00001217}
Alexander Musman515ad8c2014-05-22 08:54:05 +00001218
Alexey Bataev0f34da12015-07-02 04:17:07 +00001219void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
1220 JumpDest LoopExit) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001221 RunCleanupsScope BodyScope(*this);
1222 // Update counters values on current iteration.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001223 for (auto I : D.updates()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001224 EmitIgnoredExpr(I);
1225 }
Alexander Musman3276a272015-03-21 10:12:56 +00001226 // Update the linear variables.
Alexey Bataev617db5f2017-12-04 15:38:33 +00001227 // In distribute directives only loop counters may be marked as linear, no
1228 // need to generate the code for them.
1229 if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
1230 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
1231 for (auto *U : C->updates())
1232 EmitIgnoredExpr(U);
1233 }
Alexander Musman3276a272015-03-21 10:12:56 +00001234 }
1235
Alexander Musmana5f070a2014-10-01 06:03:56 +00001236 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +00001237 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexey Bataev0f34da12015-07-02 04:17:07 +00001238 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001239 // Emit loop body.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001240 EmitStmt(D.getBody());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001241 // The end (updates/cleanups).
1242 EmitBlock(Continue.getBlock());
1243 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +00001244}
1245
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001246void CodeGenFunction::EmitOMPInnerLoop(
1247 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
1248 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001249 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
1250 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +00001251 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001252
1253 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +00001254 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001255 EmitBlock(CondBlock);
Amara Emerson652795d2016-11-10 14:44:30 +00001256 const SourceRange &R = S.getSourceRange();
1257 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1258 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001259
1260 // If there are any cleanups between here and the loop-exit scope,
1261 // create a block to stage a loop exit along.
1262 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +00001263 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +00001264 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001265
Alexander Musmand196ef22014-10-07 08:57:09 +00001266 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001267
Alexey Bataev2df54a02015-03-12 08:53:29 +00001268 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +00001269 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001270 if (ExitBlock != LoopExit.getBlock()) {
1271 EmitBlock(ExitBlock);
1272 EmitBranchThroughCleanup(LoopExit);
1273 }
1274
1275 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +00001276 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001277
1278 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +00001279 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001280 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1281
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001282 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001283
1284 // Emit "IV = IV + 1" and a back-edge to the condition block.
1285 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +00001286 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001287 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001288 BreakContinueStack.pop_back();
1289 EmitBranch(CondBlock);
1290 LoopStack.pop();
1291 // Emit the fall-through block.
1292 EmitBlock(LoopExit.getBlock());
1293}
1294
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001295bool CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001296 if (!HaveInsertPoint())
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001297 return false;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001298 // Emit inits for the linear variables.
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001299 bool HasLinears = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001300 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001301 for (auto *Init : C->inits()) {
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001302 HasLinears = true;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001303 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
Alexey Bataevef549a82016-03-09 09:49:09 +00001304 if (auto *Ref = dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) {
1305 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
1306 auto *OrigVD = cast<VarDecl>(Ref->getDecl());
1307 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1308 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1309 VD->getInit()->getType(), VK_LValue,
1310 VD->getInit()->getExprLoc());
1311 EmitExprAsInit(&DRE, VD, MakeAddrLValue(Emission.getAllocatedAddress(),
1312 VD->getType()),
1313 /*capturedByInit=*/false);
1314 EmitAutoVarCleanups(Emission);
1315 } else
1316 EmitVarDecl(*VD);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001317 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001318 // Emit the linear steps for the linear clauses.
1319 // If a step is not constant, it is pre-calculated before the loop.
1320 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
1321 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001322 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001323 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001324 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001325 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001326 }
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001327 return HasLinears;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001328}
1329
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001330void CodeGenFunction::EmitOMPLinearClauseFinal(
1331 const OMPLoopDirective &D,
Alexey Bataevef549a82016-03-09 09:49:09 +00001332 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001333 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001334 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001335 llvm::BasicBlock *DoneBB = nullptr;
Alexander Musman3276a272015-03-21 10:12:56 +00001336 // Emit the final values of the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001337 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001338 auto IC = C->varlist_begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001339 for (auto *F : C->finals()) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001340 if (!DoneBB) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001341 if (auto *Cond = CondGen(*this)) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001342 // If the first post-update expression is found, emit conditional
1343 // block if it was requested.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001344 auto *ThenBB = createBasicBlock(".omp.linear.pu");
1345 DoneBB = createBasicBlock(".omp.linear.pu.done");
1346 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1347 EmitBlock(ThenBB);
Alexey Bataevef549a82016-03-09 09:49:09 +00001348 }
1349 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00001350 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
1351 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001352 CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +00001353 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001354 Address OrigAddr = EmitLValue(&DRE).getAddress();
1355 CodeGenFunction::OMPPrivateScope VarScope(*this);
1356 VarScope.addPrivate(OrigVD, [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev39f915b82015-05-08 10:41:21 +00001357 (void)VarScope.Privatize();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001358 EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001359 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +00001360 }
Alexey Bataev78849fb2016-03-09 09:49:00 +00001361 if (auto *PostUpdate = C->getPostUpdateExpr())
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001362 EmitIgnoredExpr(PostUpdate);
Alexander Musman3276a272015-03-21 10:12:56 +00001363 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001364 if (DoneBB)
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001365 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001366}
1367
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001368static void emitAlignedClause(CodeGenFunction &CGF,
1369 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001370 if (!CGF.HaveInsertPoint())
1371 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001372 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001373 unsigned ClauseAlignment = 0;
1374 if (auto AlignmentExpr = Clause->getAlignment()) {
1375 auto AlignmentCI =
1376 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
1377 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
Alexander Musman09184fe2014-09-30 05:29:28 +00001378 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001379 for (auto E : Clause->varlists()) {
1380 unsigned Alignment = ClauseAlignment;
1381 if (Alignment == 0) {
1382 // OpenMP [2.8.1, Description]
1383 // If no optional parameter is specified, implementation-defined default
1384 // alignments for SIMD instructions on the target platforms are assumed.
1385 Alignment =
Alexey Bataev00396512015-07-02 03:40:19 +00001386 CGF.getContext()
1387 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
1388 E->getType()->getPointeeType()))
1389 .getQuantity();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001390 }
1391 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
1392 "alignment is not power of 2");
1393 if (Alignment != 0) {
1394 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
1395 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
1396 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001397 }
1398 }
1399}
1400
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001401void CodeGenFunction::EmitOMPPrivateLoopCounters(
1402 const OMPLoopDirective &S, CodeGenFunction::OMPPrivateScope &LoopScope) {
1403 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001404 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001405 auto I = S.private_counters().begin();
1406 for (auto *E : S.counters()) {
Alexey Bataeva8899172015-08-06 12:30:57 +00001407 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1408 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001409 (void)LoopScope.addPrivate(VD, [&]() -> Address {
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001410 // Emit var without initialization.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001411 if (!LocalDeclMap.count(PrivateVD)) {
1412 auto VarEmission = EmitAutoVarAlloca(*PrivateVD);
1413 EmitAutoVarCleanups(VarEmission);
1414 }
1415 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1416 /*RefersToEnclosingVariableOrCapture=*/false,
1417 (*I)->getType(), VK_LValue, (*I)->getExprLoc());
1418 return EmitLValue(&DRE).getAddress();
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001419 });
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001420 if (LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD) ||
1421 VD->hasGlobalStorage()) {
1422 (void)LoopScope.addPrivate(PrivateVD, [&]() -> Address {
1423 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
1424 LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD),
1425 E->getType(), VK_LValue, E->getExprLoc());
1426 return EmitLValue(&DRE).getAddress();
1427 });
1428 }
Alexey Bataeva8899172015-08-06 12:30:57 +00001429 ++I;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001430 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001431}
1432
Alexey Bataev62dbb972015-04-22 11:59:37 +00001433static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1434 const Expr *Cond, llvm::BasicBlock *TrueBlock,
1435 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001436 if (!CGF.HaveInsertPoint())
1437 return;
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001438 {
1439 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001440 CGF.EmitOMPPrivateLoopCounters(S, PreCondScope);
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001441 (void)PreCondScope.Privatize();
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001442 // Get initial values of real counters.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00001443 for (auto I : S.inits()) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001444 CGF.EmitIgnoredExpr(I);
1445 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00001446 }
1447 // Check that loop is executed at least one time.
1448 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
1449}
1450
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001451void CodeGenFunction::EmitOMPLinearClause(
1452 const OMPLoopDirective &D, CodeGenFunction::OMPPrivateScope &PrivateScope) {
1453 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001454 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001455 llvm::DenseSet<const VarDecl *> SIMDLCVs;
1456 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
1457 auto *LoopDirective = cast<OMPLoopDirective>(&D);
1458 for (auto *C : LoopDirective->counters()) {
1459 SIMDLCVs.insert(
1460 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
1461 }
1462 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001463 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001464 auto CurPrivate = C->privates().begin();
Alexey Bataevc925aa32015-04-27 08:00:32 +00001465 for (auto *E : C->varlists()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001466 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1467 auto *PrivateVD =
1468 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001469 if (!SIMDLCVs.count(VD->getCanonicalDecl())) {
1470 bool IsRegistered = PrivateScope.addPrivate(VD, [&]() -> Address {
1471 // Emit private VarDecl with copy init.
1472 EmitVarDecl(*PrivateVD);
1473 return GetAddrOfLocalVar(PrivateVD);
1474 });
1475 assert(IsRegistered && "linear var already registered as private");
1476 // Silence the warning about unused variable.
1477 (void)IsRegistered;
1478 } else
1479 EmitVarDecl(*PrivateVD);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001480 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00001481 }
1482 }
1483}
1484
Alexey Bataev45bfad52015-08-21 12:19:04 +00001485static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001486 const OMPExecutableDirective &D,
1487 bool IsMonotonic) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001488 if (!CGF.HaveInsertPoint())
1489 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001490 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
Alexey Bataev45bfad52015-08-21 12:19:04 +00001491 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1492 /*ignoreResult=*/true);
1493 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
1494 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1495 // In presence of finite 'safelen', it may be unsafe to mark all
1496 // the memory instructions parallel, because loop-carried
1497 // dependences of 'safelen' iterations are possible.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001498 if (!IsMonotonic)
1499 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001500 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001501 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1502 /*ignoreResult=*/true);
1503 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001504 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001505 // In presence of finite 'safelen', it may be unsafe to mark all
1506 // the memory instructions parallel, because loop-carried
1507 // dependences of 'safelen' iterations are possible.
1508 CGF.LoopStack.setParallel(false);
1509 }
1510}
1511
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001512void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
1513 bool IsMonotonic) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001514 // Walk clauses and process safelen/lastprivate.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001515 LoopStack.setParallel(!IsMonotonic);
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001516 LoopStack.setVectorizeEnable(true);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001517 emitSimdlenSafelenClause(*this, D, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001518}
1519
Alexey Bataevef549a82016-03-09 09:49:09 +00001520void CodeGenFunction::EmitOMPSimdFinal(
1521 const OMPLoopDirective &D,
1522 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001523 if (!HaveInsertPoint())
1524 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001525 llvm::BasicBlock *DoneBB = nullptr;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001526 auto IC = D.counters().begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001527 auto IPC = D.private_counters().begin();
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001528 for (auto F : D.finals()) {
1529 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001530 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>((*IPC))->getDecl());
1531 auto *CED = dyn_cast<OMPCapturedExprDecl>(OrigVD);
1532 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD) ||
1533 OrigVD->hasGlobalStorage() || CED) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001534 if (!DoneBB) {
1535 if (auto *Cond = CondGen(*this)) {
1536 // If the first post-update expression is found, emit conditional
1537 // block if it was requested.
1538 auto *ThenBB = createBasicBlock(".omp.final.then");
1539 DoneBB = createBasicBlock(".omp.final.done");
1540 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1541 EmitBlock(ThenBB);
1542 }
1543 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001544 Address OrigAddr = Address::invalid();
1545 if (CED)
1546 OrigAddr = EmitLValue(CED->getInit()->IgnoreImpCasts()).getAddress();
1547 else {
1548 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1549 /*RefersToEnclosingVariableOrCapture=*/false,
1550 (*IPC)->getType(), VK_LValue, (*IPC)->getExprLoc());
1551 OrigAddr = EmitLValue(&DRE).getAddress();
1552 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001553 OMPPrivateScope VarScope(*this);
1554 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001555 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001556 (void)VarScope.Privatize();
1557 EmitIgnoredExpr(F);
1558 }
1559 ++IC;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001560 ++IPC;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001561 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001562 if (DoneBB)
1563 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001564}
1565
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001566static void emitOMPLoopBodyWithStopPoint(CodeGenFunction &CGF,
1567 const OMPLoopDirective &S,
1568 CodeGenFunction::JumpDest LoopExit) {
1569 CGF.EmitOMPLoopBody(S, LoopExit);
1570 CGF.EmitStopPoint(&S);
Hans Wennborged129ae2017-04-27 17:02:25 +00001571}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001572
Alexey Bataevf8365372017-11-17 17:57:25 +00001573static void emitOMPSimdRegion(CodeGenFunction &CGF, const OMPLoopDirective &S,
1574 PrePostActionTy &Action) {
1575 Action.Enter(CGF);
1576 assert(isOpenMPSimdDirective(S.getDirectiveKind()) &&
1577 "Expected simd directive");
1578 OMPLoopScope PreInitScope(CGF, S);
1579 // if (PreCond) {
1580 // for (IV in 0..LastIteration) BODY;
1581 // <Final counter/linear vars updates>;
1582 // }
1583 //
Alexander Musmana5f070a2014-10-01 06:03:56 +00001584
Alexey Bataevf8365372017-11-17 17:57:25 +00001585 // Emit: if (PreCond) - begin.
1586 // If the condition constant folds and can be elided, avoid emitting the
1587 // whole loop.
1588 bool CondConstant;
1589 llvm::BasicBlock *ContBlock = nullptr;
1590 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1591 if (!CondConstant)
1592 return;
1593 } else {
1594 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
1595 ContBlock = CGF.createBasicBlock("simd.if.end");
1596 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
1597 CGF.getProfileCount(&S));
1598 CGF.EmitBlock(ThenBlock);
1599 CGF.incrementProfileCounter(&S);
1600 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001601
Alexey Bataevf8365372017-11-17 17:57:25 +00001602 // Emit the loop iteration variable.
1603 const Expr *IVExpr = S.getIterationVariable();
1604 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
1605 CGF.EmitVarDecl(*IVDecl);
1606 CGF.EmitIgnoredExpr(S.getInit());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001607
Alexey Bataevf8365372017-11-17 17:57:25 +00001608 // Emit the iterations count variable.
1609 // If it is not a variable, Sema decided to calculate iterations count on
1610 // each iteration (e.g., it is foldable into a constant).
1611 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1612 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1613 // Emit calculation of the iterations count.
1614 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
1615 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001616
Alexey Bataevf8365372017-11-17 17:57:25 +00001617 CGF.EmitOMPSimdInit(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001618
Alexey Bataevf8365372017-11-17 17:57:25 +00001619 emitAlignedClause(CGF, S);
1620 (void)CGF.EmitOMPLinearClauseInit(S);
1621 {
1622 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
1623 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
1624 CGF.EmitOMPLinearClause(S, LoopScope);
1625 CGF.EmitOMPPrivateClause(S, LoopScope);
1626 CGF.EmitOMPReductionClauseInit(S, LoopScope);
1627 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
1628 (void)LoopScope.Privatize();
1629 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1630 S.getInc(),
1631 [&S](CodeGenFunction &CGF) {
1632 CGF.EmitOMPLoopBody(S, CodeGenFunction::JumpDest());
1633 CGF.EmitStopPoint(&S);
1634 },
1635 [](CodeGenFunction &) {});
1636 CGF.EmitOMPSimdFinal(
Alexey Bataevef549a82016-03-09 09:49:09 +00001637 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataevf8365372017-11-17 17:57:25 +00001638 // Emit final copy of the lastprivate variables at the end of loops.
1639 if (HasLastprivateClause)
1640 CGF.EmitOMPLastprivateClauseFinal(S, /*NoFinals=*/true);
1641 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_simd);
1642 emitPostUpdateForReductionClause(
1643 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
1644 }
1645 CGF.EmitOMPLinearClauseFinal(
1646 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
1647 // Emit: if (PreCond) - end.
1648 if (ContBlock) {
1649 CGF.EmitBranch(ContBlock);
1650 CGF.EmitBlock(ContBlock, true);
1651 }
1652}
1653
1654void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
1655 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
1656 emitOMPSimdRegion(CGF, S, Action);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001657 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00001658 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001659 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +00001660}
1661
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001662void CodeGenFunction::EmitOMPOuterLoop(
1663 bool DynamicOrOrdered, bool IsMonotonic, const OMPLoopDirective &S,
1664 CodeGenFunction::OMPPrivateScope &LoopScope,
1665 const CodeGenFunction::OMPLoopArguments &LoopArgs,
1666 const CodeGenFunction::CodeGenLoopTy &CodeGenLoop,
1667 const CodeGenFunction::CodeGenOrderedTy &CodeGenOrdered) {
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001668 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +00001669
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001670 const Expr *IVExpr = S.getIterationVariable();
1671 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1672 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1673
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001674 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
1675
1676 // Start the loop with a block that tests the condition.
1677 auto CondBlock = createBasicBlock("omp.dispatch.cond");
1678 EmitBlock(CondBlock);
Amara Emerson652795d2016-11-10 14:44:30 +00001679 const SourceRange &R = S.getSourceRange();
1680 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1681 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001682
1683 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001684 if (!DynamicOrOrdered) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001685 // UB = min(UB, GlobalUB) or
1686 // UB = min(UB, PrevUB) for combined loop sharing constructs (e.g.
1687 // 'distribute parallel for')
1688 EmitIgnoredExpr(LoopArgs.EUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001689 // IV = LB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001690 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001691 // IV < UB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001692 BoolCondVal = EvaluateExprAsBool(LoopArgs.Cond);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001693 } else {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001694 BoolCondVal =
1695 RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned, LoopArgs.IL,
1696 LoopArgs.LB, LoopArgs.UB, LoopArgs.ST);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001697 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001698
1699 // If there are any cleanups between here and the loop-exit scope,
1700 // create a block to stage a loop exit along.
1701 auto ExitBlock = LoopExit.getBlock();
1702 if (LoopScope.requiresCleanups())
1703 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
1704
1705 auto LoopBody = createBasicBlock("omp.dispatch.body");
1706 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
1707 if (ExitBlock != LoopExit.getBlock()) {
1708 EmitBlock(ExitBlock);
1709 EmitBranchThroughCleanup(LoopExit);
1710 }
1711 EmitBlock(LoopBody);
1712
Alexander Musman92bdaab2015-03-12 13:37:50 +00001713 // Emit "IV = LB" (in case of static schedule, we have already calculated new
1714 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001715 if (DynamicOrOrdered)
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001716 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001717
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001718 // Create a block for the increment.
1719 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
1720 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1721
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001722 // Generate !llvm.loop.parallel metadata for loads and stores for loops
1723 // with dynamic/guided scheduling and without ordered clause.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001724 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
1725 LoopStack.setParallel(!IsMonotonic);
1726 else
1727 EmitOMPSimdInit(S, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001728
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001729 SourceLocation Loc = S.getLocStart();
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001730
1731 // when 'distribute' is not combined with a 'for':
1732 // while (idx <= UB) { BODY; ++idx; }
1733 // when 'distribute' is combined with a 'for'
1734 // (e.g. 'distribute parallel for')
1735 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
1736 EmitOMPInnerLoop(
1737 S, LoopScope.requiresCleanups(), LoopArgs.Cond, LoopArgs.IncExpr,
1738 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
1739 CodeGenLoop(CGF, S, LoopExit);
1740 },
1741 [IVSize, IVSigned, Loc, &CodeGenOrdered](CodeGenFunction &CGF) {
1742 CodeGenOrdered(CGF, Loc, IVSize, IVSigned);
1743 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001744
1745 EmitBlock(Continue.getBlock());
1746 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001747 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001748 // Emit "LB = LB + Stride", "UB = UB + Stride".
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001749 EmitIgnoredExpr(LoopArgs.NextLB);
1750 EmitIgnoredExpr(LoopArgs.NextUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001751 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001752
1753 EmitBranch(CondBlock);
1754 LoopStack.pop();
1755 // Emit the fall-through block.
1756 EmitBlock(LoopExit.getBlock());
1757
1758 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00001759 auto &&CodeGen = [DynamicOrOrdered, &S](CodeGenFunction &CGF) {
1760 if (!DynamicOrOrdered)
Alexey Bataevf43f7142017-09-06 16:17:35 +00001761 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd(),
1762 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00001763 };
1764 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001765}
1766
1767void CodeGenFunction::EmitOMPForOuterLoop(
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001768 const OpenMPScheduleTy &ScheduleKind, bool IsMonotonic,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001769 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001770 const OMPLoopArguments &LoopArgs,
1771 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001772 auto &RT = CGM.getOpenMPRuntime();
1773
1774 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001775 const bool DynamicOrOrdered =
1776 Ordered || RT.isDynamic(ScheduleKind.Schedule);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001777
1778 assert((Ordered ||
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001779 !RT.isStaticNonchunked(ScheduleKind.Schedule,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001780 LoopArgs.Chunk != nullptr)) &&
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001781 "static non-chunked schedule does not need outer loop");
1782
1783 // Emit outer loop.
1784 //
1785 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1786 // When schedule(dynamic,chunk_size) is specified, the iterations are
1787 // distributed to threads in the team in chunks as the threads request them.
1788 // Each thread executes a chunk of iterations, then requests another chunk,
1789 // until no chunks remain to be distributed. Each chunk contains chunk_size
1790 // iterations, except for the last chunk to be distributed, which may have
1791 // fewer iterations. When no chunk_size is specified, it defaults to 1.
1792 //
1793 // When schedule(guided,chunk_size) is specified, the iterations are assigned
1794 // to threads in the team in chunks as the executing threads request them.
1795 // Each thread executes a chunk of iterations, then requests another chunk,
1796 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
1797 // each chunk is proportional to the number of unassigned iterations divided
1798 // by the number of threads in the team, decreasing to 1. For a chunk_size
1799 // with value k (greater than 1), the size of each chunk is determined in the
1800 // same way, with the restriction that the chunks do not contain fewer than k
1801 // iterations (except for the last chunk to be assigned, which may have fewer
1802 // than k iterations).
1803 //
1804 // When schedule(auto) is specified, the decision regarding scheduling is
1805 // delegated to the compiler and/or runtime system. The programmer gives the
1806 // implementation the freedom to choose any possible mapping of iterations to
1807 // threads in the team.
1808 //
1809 // When schedule(runtime) is specified, the decision regarding scheduling is
1810 // deferred until run time, and the schedule and chunk size are taken from the
1811 // run-sched-var ICV. If the ICV is set to auto, the schedule is
1812 // implementation defined
1813 //
1814 // while(__kmpc_dispatch_next(&LB, &UB)) {
1815 // idx = LB;
1816 // while (idx <= UB) { BODY; ++idx;
1817 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
1818 // } // inner loop
1819 // }
1820 //
1821 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1822 // When schedule(static, chunk_size) is specified, iterations are divided into
1823 // chunks of size chunk_size, and the chunks are assigned to the threads in
1824 // the team in a round-robin fashion in the order of the thread number.
1825 //
1826 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
1827 // while (idx <= UB) { BODY; ++idx; } // inner loop
1828 // LB = LB + ST;
1829 // UB = UB + ST;
1830 // }
1831 //
1832
1833 const Expr *IVExpr = S.getIterationVariable();
1834 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1835 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1836
1837 if (DynamicOrOrdered) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001838 auto DispatchBounds = CGDispatchBounds(*this, S, LoopArgs.LB, LoopArgs.UB);
1839 llvm::Value *LBVal = DispatchBounds.first;
1840 llvm::Value *UBVal = DispatchBounds.second;
1841 CGOpenMPRuntime::DispatchRTInput DipatchRTInputValues = {LBVal, UBVal,
1842 LoopArgs.Chunk};
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001843 RT.emitForDispatchInit(*this, S.getLocStart(), ScheduleKind, IVSize,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001844 IVSigned, Ordered, DipatchRTInputValues);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001845 } else {
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00001846 CGOpenMPRuntime::StaticRTInput StaticInit(
1847 IVSize, IVSigned, Ordered, LoopArgs.IL, LoopArgs.LB, LoopArgs.UB,
1848 LoopArgs.ST, LoopArgs.Chunk);
1849 RT.emitForStaticInit(*this, S.getLocStart(), S.getDirectiveKind(),
1850 ScheduleKind, StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001851 }
1852
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001853 auto &&CodeGenOrdered = [Ordered](CodeGenFunction &CGF, SourceLocation Loc,
1854 const unsigned IVSize,
1855 const bool IVSigned) {
1856 if (Ordered) {
1857 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(CGF, Loc, IVSize,
1858 IVSigned);
1859 }
1860 };
1861
1862 OMPLoopArguments OuterLoopArgs(LoopArgs.LB, LoopArgs.UB, LoopArgs.ST,
1863 LoopArgs.IL, LoopArgs.Chunk, LoopArgs.EUB);
1864 OuterLoopArgs.IncExpr = S.getInc();
1865 OuterLoopArgs.Init = S.getInit();
1866 OuterLoopArgs.Cond = S.getCond();
1867 OuterLoopArgs.NextLB = S.getNextLowerBound();
1868 OuterLoopArgs.NextUB = S.getNextUpperBound();
1869 EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, OuterLoopArgs,
1870 emitOMPLoopBodyWithStopPoint, CodeGenOrdered);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001871}
1872
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001873static void emitEmptyOrdered(CodeGenFunction &, SourceLocation Loc,
1874 const unsigned IVSize, const bool IVSigned) {}
1875
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001876void CodeGenFunction::EmitOMPDistributeOuterLoop(
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001877 OpenMPDistScheduleClauseKind ScheduleKind, const OMPLoopDirective &S,
1878 OMPPrivateScope &LoopScope, const OMPLoopArguments &LoopArgs,
1879 const CodeGenLoopTy &CodeGenLoopContent) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001880
1881 auto &RT = CGM.getOpenMPRuntime();
1882
1883 // Emit outer loop.
1884 // Same behavior as a OMPForOuterLoop, except that schedule cannot be
1885 // dynamic
1886 //
1887
1888 const Expr *IVExpr = S.getIterationVariable();
1889 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1890 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1891
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00001892 CGOpenMPRuntime::StaticRTInput StaticInit(
1893 IVSize, IVSigned, /* Ordered = */ false, LoopArgs.IL, LoopArgs.LB,
1894 LoopArgs.UB, LoopArgs.ST, LoopArgs.Chunk);
1895 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind, StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001896
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001897 // for combined 'distribute' and 'for' the increment expression of distribute
1898 // is store in DistInc. For 'distribute' alone, it is in Inc.
1899 Expr *IncExpr;
1900 if (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()))
1901 IncExpr = S.getDistInc();
1902 else
1903 IncExpr = S.getInc();
1904
1905 // this routine is shared by 'omp distribute parallel for' and
1906 // 'omp distribute': select the right EUB expression depending on the
1907 // directive
1908 OMPLoopArguments OuterLoopArgs;
1909 OuterLoopArgs.LB = LoopArgs.LB;
1910 OuterLoopArgs.UB = LoopArgs.UB;
1911 OuterLoopArgs.ST = LoopArgs.ST;
1912 OuterLoopArgs.IL = LoopArgs.IL;
1913 OuterLoopArgs.Chunk = LoopArgs.Chunk;
1914 OuterLoopArgs.EUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1915 ? S.getCombinedEnsureUpperBound()
1916 : S.getEnsureUpperBound();
1917 OuterLoopArgs.IncExpr = IncExpr;
1918 OuterLoopArgs.Init = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1919 ? S.getCombinedInit()
1920 : S.getInit();
1921 OuterLoopArgs.Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1922 ? S.getCombinedCond()
1923 : S.getCond();
1924 OuterLoopArgs.NextLB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1925 ? S.getCombinedNextLowerBound()
1926 : S.getNextLowerBound();
1927 OuterLoopArgs.NextUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1928 ? S.getCombinedNextUpperBound()
1929 : S.getNextUpperBound();
1930
1931 EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false, S,
1932 LoopScope, OuterLoopArgs, CodeGenLoopContent,
1933 emitEmptyOrdered);
1934}
1935
1936/// Emit a helper variable and return corresponding lvalue.
1937static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1938 const DeclRefExpr *Helper) {
1939 auto VDecl = cast<VarDecl>(Helper->getDecl());
1940 CGF.EmitVarDecl(*VDecl);
1941 return CGF.EmitLValue(Helper);
1942}
1943
1944static std::pair<LValue, LValue>
1945emitDistributeParallelForInnerBounds(CodeGenFunction &CGF,
1946 const OMPExecutableDirective &S) {
1947 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
1948 LValue LB =
1949 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
1950 LValue UB =
1951 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
1952
1953 // When composing 'distribute' with 'for' (e.g. as in 'distribute
1954 // parallel for') we need to use the 'distribute'
1955 // chunk lower and upper bounds rather than the whole loop iteration
1956 // space. These are parameters to the outlined function for 'parallel'
1957 // and we copy the bounds of the previous schedule into the
1958 // the current ones.
1959 LValue PrevLB = CGF.EmitLValue(LS.getPrevLowerBoundVariable());
1960 LValue PrevUB = CGF.EmitLValue(LS.getPrevUpperBoundVariable());
1961 llvm::Value *PrevLBVal = CGF.EmitLoadOfScalar(PrevLB, SourceLocation());
1962 PrevLBVal = CGF.EmitScalarConversion(
1963 PrevLBVal, LS.getPrevLowerBoundVariable()->getType(),
1964 LS.getIterationVariable()->getType(), SourceLocation());
1965 llvm::Value *PrevUBVal = CGF.EmitLoadOfScalar(PrevUB, SourceLocation());
1966 PrevUBVal = CGF.EmitScalarConversion(
1967 PrevUBVal, LS.getPrevUpperBoundVariable()->getType(),
1968 LS.getIterationVariable()->getType(), SourceLocation());
1969
1970 CGF.EmitStoreOfScalar(PrevLBVal, LB);
1971 CGF.EmitStoreOfScalar(PrevUBVal, UB);
1972
1973 return {LB, UB};
1974}
1975
1976/// if the 'for' loop has a dispatch schedule (e.g. dynamic, guided) then
1977/// we need to use the LB and UB expressions generated by the worksharing
1978/// code generation support, whereas in non combined situations we would
1979/// just emit 0 and the LastIteration expression
1980/// This function is necessary due to the difference of the LB and UB
1981/// types for the RT emission routines for 'for_static_init' and
1982/// 'for_dispatch_init'
1983static std::pair<llvm::Value *, llvm::Value *>
1984emitDistributeParallelForDispatchBounds(CodeGenFunction &CGF,
1985 const OMPExecutableDirective &S,
1986 Address LB, Address UB) {
1987 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
1988 const Expr *IVExpr = LS.getIterationVariable();
1989 // when implementing a dynamic schedule for a 'for' combined with a
1990 // 'distribute' (e.g. 'distribute parallel for'), the 'for' loop
1991 // is not normalized as each team only executes its own assigned
1992 // distribute chunk
1993 QualType IteratorTy = IVExpr->getType();
1994 llvm::Value *LBVal = CGF.EmitLoadOfScalar(LB, /*Volatile=*/false, IteratorTy,
1995 SourceLocation());
1996 llvm::Value *UBVal = CGF.EmitLoadOfScalar(UB, /*Volatile=*/false, IteratorTy,
1997 SourceLocation());
1998 return {LBVal, UBVal};
Hans Wennborged129ae2017-04-27 17:02:25 +00001999}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002000
2001static void emitDistributeParallelForDistributeInnerBoundParams(
2002 CodeGenFunction &CGF, const OMPExecutableDirective &S,
2003 llvm::SmallVectorImpl<llvm::Value *> &CapturedVars) {
2004 const auto &Dir = cast<OMPLoopDirective>(S);
2005 LValue LB =
2006 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedLowerBoundVariable()));
2007 auto LBCast = CGF.Builder.CreateIntCast(
2008 CGF.Builder.CreateLoad(LB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
2009 CapturedVars.push_back(LBCast);
2010 LValue UB =
2011 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedUpperBoundVariable()));
2012
2013 auto UBCast = CGF.Builder.CreateIntCast(
2014 CGF.Builder.CreateLoad(UB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
2015 CapturedVars.push_back(UBCast);
Hans Wennborged129ae2017-04-27 17:02:25 +00002016}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002017
2018static void
2019emitInnerParallelForWhenCombined(CodeGenFunction &CGF,
2020 const OMPLoopDirective &S,
2021 CodeGenFunction::JumpDest LoopExit) {
2022 auto &&CGInlinedWorksharingLoop = [&S](CodeGenFunction &CGF,
2023 PrePostActionTy &) {
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002024 bool HasCancel = false;
2025 if (!isOpenMPSimdDirective(S.getDirectiveKind())) {
2026 if (const auto *D = dyn_cast<OMPTeamsDistributeParallelForDirective>(&S))
2027 HasCancel = D->hasCancel();
2028 else if (const auto *D = dyn_cast<OMPDistributeParallelForDirective>(&S))
2029 HasCancel = D->hasCancel();
Alexey Bataev16e79882017-11-22 21:12:03 +00002030 else if (const auto *D =
2031 dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&S))
2032 HasCancel = D->hasCancel();
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002033 }
2034 CodeGenFunction::OMPCancelStackRAII CancelRegion(CGF, S.getDirectiveKind(),
2035 HasCancel);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002036 CGF.EmitOMPWorksharingLoop(S, S.getPrevEnsureUpperBound(),
2037 emitDistributeParallelForInnerBounds,
2038 emitDistributeParallelForDispatchBounds);
2039 };
2040
2041 emitCommonOMPParallelDirective(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002042 CGF, S,
2043 isOpenMPSimdDirective(S.getDirectiveKind()) ? OMPD_for_simd : OMPD_for,
2044 CGInlinedWorksharingLoop,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002045 emitDistributeParallelForDistributeInnerBoundParams);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002046}
2047
Carlo Bertolli9925f152016-06-27 14:55:37 +00002048void CodeGenFunction::EmitOMPDistributeParallelForDirective(
2049 const OMPDistributeParallelForDirective &S) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002050 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2051 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
2052 S.getDistInc());
2053 };
Carlo Bertolli9925f152016-06-27 14:55:37 +00002054 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev10a54312017-11-27 16:54:08 +00002055 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Carlo Bertolli9925f152016-06-27 14:55:37 +00002056}
2057
Kelvin Li4a39add2016-07-05 05:00:15 +00002058void CodeGenFunction::EmitOMPDistributeParallelForSimdDirective(
2059 const OMPDistributeParallelForSimdDirective &S) {
Alexey Bataev0b49f9e2017-11-27 19:38:58 +00002060 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2061 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
2062 S.getDistInc());
2063 };
Kelvin Li4a39add2016-07-05 05:00:15 +00002064 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev0b49f9e2017-11-27 19:38:58 +00002065 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Kelvin Li4a39add2016-07-05 05:00:15 +00002066}
Kelvin Li787f3fc2016-07-06 04:45:38 +00002067
2068void CodeGenFunction::EmitOMPDistributeSimdDirective(
2069 const OMPDistributeSimdDirective &S) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00002070 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2071 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
2072 };
Kelvin Li787f3fc2016-07-06 04:45:38 +00002073 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev617db5f2017-12-04 15:38:33 +00002074 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Kelvin Li787f3fc2016-07-06 04:45:38 +00002075}
2076
Alexey Bataevf8365372017-11-17 17:57:25 +00002077void CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
2078 CodeGenModule &CGM, StringRef ParentName, const OMPTargetSimdDirective &S) {
2079 // Emit SPMD target parallel for region as a standalone region.
2080 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2081 emitOMPSimdRegion(CGF, S, Action);
2082 };
2083 llvm::Function *Fn;
2084 llvm::Constant *Addr;
2085 // Emit target region as a standalone region.
2086 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
2087 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
2088 assert(Fn && Addr && "Target device function emission failed.");
2089}
2090
Kelvin Li986330c2016-07-20 22:57:10 +00002091void CodeGenFunction::EmitOMPTargetSimdDirective(
2092 const OMPTargetSimdDirective &S) {
Alexey Bataevf8365372017-11-17 17:57:25 +00002093 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2094 emitOMPSimdRegion(CGF, S, Action);
2095 };
2096 emitCommonOMPTargetDirective(*this, S, CodeGen);
Kelvin Li986330c2016-07-20 22:57:10 +00002097}
2098
Kelvin Li80e8f562016-12-29 22:16:30 +00002099void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDirective(
2100 const OMPTargetTeamsDistributeParallelForDirective &S) {
Alexey Bataev931e19b2017-10-02 16:32:39 +00002101 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Kelvin Li80e8f562016-12-29 22:16:30 +00002102 CGM.getOpenMPRuntime().emitInlinedDirective(
2103 *this, OMPD_target_teams_distribute_parallel_for,
2104 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2105 CGF.EmitStmt(
2106 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2107 });
2108}
2109
Kelvin Li1851df52017-01-03 05:23:48 +00002110void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDirective(
2111 const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
Alexey Bataev931e19b2017-10-02 16:32:39 +00002112 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Kelvin Li1851df52017-01-03 05:23:48 +00002113 CGM.getOpenMPRuntime().emitInlinedDirective(
2114 *this, OMPD_target_teams_distribute_parallel_for_simd,
2115 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2116 CGF.EmitStmt(
2117 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2118 });
2119}
2120
Kelvin Lida681182017-01-10 18:08:18 +00002121void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDirective(
2122 const OMPTargetTeamsDistributeSimdDirective &S) {
Alexey Bataev931e19b2017-10-02 16:32:39 +00002123 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Kelvin Lida681182017-01-10 18:08:18 +00002124 CGM.getOpenMPRuntime().emitInlinedDirective(
2125 *this, OMPD_target_teams_distribute_simd,
2126 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2127 CGF.EmitStmt(
2128 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2129 });
2130}
2131
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002132namespace {
2133 struct ScheduleKindModifiersTy {
2134 OpenMPScheduleClauseKind Kind;
2135 OpenMPScheduleClauseModifier M1;
2136 OpenMPScheduleClauseModifier M2;
2137 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
2138 OpenMPScheduleClauseModifier M1,
2139 OpenMPScheduleClauseModifier M2)
2140 : Kind(Kind), M1(M1), M2(M2) {}
2141 };
2142} // namespace
2143
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002144bool CodeGenFunction::EmitOMPWorksharingLoop(
2145 const OMPLoopDirective &S, Expr *EUB,
2146 const CodeGenLoopBoundsTy &CodeGenLoopBounds,
2147 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002148 // Emit the loop iteration variable.
2149 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
2150 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
2151 EmitVarDecl(*IVDecl);
2152
2153 // Emit the iterations count variable.
2154 // If it is not a variable, Sema decided to calculate iterations count on each
2155 // iteration (e.g., it is foldable into a constant).
2156 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
2157 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2158 // Emit calculation of the iterations count.
2159 EmitIgnoredExpr(S.getCalcLastIteration());
2160 }
2161
2162 auto &RT = CGM.getOpenMPRuntime();
2163
Alexey Bataev38e89532015-04-16 04:54:05 +00002164 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002165 // Check pre-condition.
2166 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002167 OMPLoopScope PreInitScope(*this, S);
Alexander Musmanc6388682014-12-15 07:07:06 +00002168 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002169 // If the condition constant folds and can be elided, avoid emitting the
2170 // whole loop.
2171 bool CondConstant;
2172 llvm::BasicBlock *ContBlock = nullptr;
2173 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2174 if (!CondConstant)
2175 return false;
2176 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00002177 auto *ThenBlock = createBasicBlock("omp.precond.then");
2178 ContBlock = createBasicBlock("omp.precond.end");
2179 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00002180 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00002181 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00002182 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00002183 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002184
Alexey Bataev8b427062016-05-25 12:36:08 +00002185 bool Ordered = false;
2186 if (auto *OrderedClause = S.getSingleClause<OMPOrderedClause>()) {
2187 if (OrderedClause->getNumForLoops())
2188 RT.emitDoacrossInit(*this, S);
2189 else
2190 Ordered = true;
2191 }
2192
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002193 llvm::DenseSet<const Expr *> EmittedFinals;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002194 emitAlignedClause(*this, S);
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00002195 bool HasLinears = EmitOMPLinearClauseInit(S);
Alexey Bataevef549a82016-03-09 09:49:09 +00002196 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002197
2198 std::pair<LValue, LValue> Bounds = CodeGenLoopBounds(*this, S);
2199 LValue LB = Bounds.first;
2200 LValue UB = Bounds.second;
Alexey Bataevef549a82016-03-09 09:49:09 +00002201 LValue ST =
2202 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
2203 LValue IL =
2204 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
2205
Alexander Musmanc6388682014-12-15 07:07:06 +00002206 // Emit 'then' code.
2207 {
Alexander Musmanc6388682014-12-15 07:07:06 +00002208 OMPPrivateScope LoopScope(*this);
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00002209 if (EmitOMPFirstprivateClause(S, LoopScope) || HasLinears) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00002210 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002211 // initialization of firstprivate variables and post-update of
2212 // lastprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00002213 CGM.getOpenMPRuntime().emitBarrierCall(
2214 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2215 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00002216 }
Alexey Bataev50a64582015-04-22 12:24:45 +00002217 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00002218 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00002219 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002220 EmitOMPPrivateLoopCounters(S, LoopScope);
2221 EmitOMPLinearClause(S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00002222 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00002223
2224 // Detect the loop schedule kind and chunk.
Alexey Bataev3392d762016-02-16 11:18:12 +00002225 llvm::Value *Chunk = nullptr;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002226 OpenMPScheduleTy ScheduleKind;
Alexey Bataev3392d762016-02-16 11:18:12 +00002227 if (auto *C = S.getSingleClause<OMPScheduleClause>()) {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002228 ScheduleKind.Schedule = C->getScheduleKind();
2229 ScheduleKind.M1 = C->getFirstScheduleModifier();
2230 ScheduleKind.M2 = C->getSecondScheduleModifier();
Alexey Bataev3392d762016-02-16 11:18:12 +00002231 if (const auto *Ch = C->getChunkSize()) {
2232 Chunk = EmitScalarExpr(Ch);
2233 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
2234 S.getIterationVariable()->getType(),
2235 S.getLocStart());
2236 }
2237 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002238 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2239 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002240 // OpenMP 4.5, 2.7.1 Loop Construct, Description.
2241 // If the static schedule kind is specified or if the ordered clause is
2242 // specified, and if no monotonic modifier is specified, the effect will
2243 // be as if the monotonic modifier was specified.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002244 if (RT.isStaticNonchunked(ScheduleKind.Schedule,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002245 /* Chunked */ Chunk != nullptr) &&
2246 !Ordered) {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002247 if (isOpenMPSimdDirective(S.getDirectiveKind()))
2248 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexander Musmanc6388682014-12-15 07:07:06 +00002249 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
2250 // When no chunk_size is specified, the iteration space is divided into
2251 // chunks that are approximately equal in size, and at most one chunk is
2252 // distributed to each thread. Note that the size of the chunks is
2253 // unspecified in this case.
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002254 CGOpenMPRuntime::StaticRTInput StaticInit(
2255 IVSize, IVSigned, Ordered, IL.getAddress(), LB.getAddress(),
2256 UB.getAddress(), ST.getAddress());
2257 RT.emitForStaticInit(*this, S.getLocStart(), S.getDirectiveKind(),
2258 ScheduleKind, StaticInit);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002259 auto LoopExit =
2260 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
Alexander Musmanc6388682014-12-15 07:07:06 +00002261 // UB = min(UB, GlobalUB);
2262 EmitIgnoredExpr(S.getEnsureUpperBound());
2263 // IV = LB;
2264 EmitIgnoredExpr(S.getInit());
2265 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataevae05c292015-06-16 11:59:36 +00002266 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
2267 S.getInc(),
Alexey Bataev0f34da12015-07-02 04:17:07 +00002268 [&S, LoopExit](CodeGenFunction &CGF) {
2269 CGF.EmitOMPLoopBody(S, LoopExit);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002270 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002271 },
2272 [](CodeGenFunction &) {});
Alexey Bataev0f34da12015-07-02 04:17:07 +00002273 EmitBlock(LoopExit.getBlock());
Alexander Musmanc6388682014-12-15 07:07:06 +00002274 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002275 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataevf43f7142017-09-06 16:17:35 +00002276 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd(),
2277 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00002278 };
2279 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002280 } else {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002281 const bool IsMonotonic =
2282 Ordered || ScheduleKind.Schedule == OMPC_SCHEDULE_static ||
2283 ScheduleKind.Schedule == OMPC_SCHEDULE_unknown ||
2284 ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
2285 ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002286 // Emit the outer loop, which requests its work chunk [LB..UB] from
2287 // runtime and runs the inner loop to process it.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002288 const OMPLoopArguments LoopArguments(LB.getAddress(), UB.getAddress(),
2289 ST.getAddress(), IL.getAddress(),
2290 Chunk, EUB);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002291 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002292 LoopArguments, CGDispatchBounds);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002293 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002294 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
2295 EmitOMPSimdFinal(S,
2296 [&](CodeGenFunction &CGF) -> llvm::Value * {
2297 return CGF.Builder.CreateIsNotNull(
2298 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2299 });
2300 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002301 EmitOMPReductionClauseFinal(
2302 S, /*ReductionKind=*/isOpenMPSimdDirective(S.getDirectiveKind())
2303 ? /*Parallel and Simd*/ OMPD_parallel_for_simd
2304 : /*Parallel only*/ OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002305 // Emit post-update of the reduction variables if IsLastIter != 0.
2306 emitPostUpdateForReductionClause(
2307 *this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2308 return CGF.Builder.CreateIsNotNull(
2309 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2310 });
Alexey Bataev38e89532015-04-16 04:54:05 +00002311 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2312 if (HasLastprivateClause)
2313 EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002314 S, isOpenMPSimdDirective(S.getDirectiveKind()),
2315 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00002316 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002317 EmitOMPLinearClauseFinal(S, [&](CodeGenFunction &CGF) -> llvm::Value * {
Alexey Bataevef549a82016-03-09 09:49:09 +00002318 return CGF.Builder.CreateIsNotNull(
2319 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2320 });
Alexander Musmanc6388682014-12-15 07:07:06 +00002321 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002322 if (ContBlock) {
2323 EmitBranch(ContBlock);
2324 EmitBlock(ContBlock, true);
2325 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002326 }
Alexey Bataev38e89532015-04-16 04:54:05 +00002327 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002328}
2329
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002330/// The following two functions generate expressions for the loop lower
2331/// and upper bounds in case of static and dynamic (dispatch) schedule
2332/// of the associated 'for' or 'distribute' loop.
2333static std::pair<LValue, LValue>
2334emitForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
2335 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2336 LValue LB =
2337 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2338 LValue UB =
2339 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2340 return {LB, UB};
2341}
2342
2343/// When dealing with dispatch schedules (e.g. dynamic, guided) we do not
2344/// consider the lower and upper bound expressions generated by the
2345/// worksharing loop support, but we use 0 and the iteration space size as
2346/// constants
2347static std::pair<llvm::Value *, llvm::Value *>
2348emitDispatchForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S,
2349 Address LB, Address UB) {
2350 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2351 const Expr *IVExpr = LS.getIterationVariable();
2352 const unsigned IVSize = CGF.getContext().getTypeSize(IVExpr->getType());
2353 llvm::Value *LBVal = CGF.Builder.getIntN(IVSize, 0);
2354 llvm::Value *UBVal = CGF.EmitScalarExpr(LS.getLastIteration());
2355 return {LBVal, UBVal};
2356}
2357
Alexander Musmanc6388682014-12-15 07:07:06 +00002358void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002359 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002360 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2361 PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002362 OMPCancelStackRAII CancelRegion(CGF, OMPD_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002363 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2364 emitForLoopBounds,
2365 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002366 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002367 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002368 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002369 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
2370 S.hasCancel());
2371 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002372
2373 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002374 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002375 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2376 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00002377}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002378
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002379void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002380 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002381 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2382 PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002383 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2384 emitForLoopBounds,
2385 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002386 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002387 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002388 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002389 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
2390 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002391
2392 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002393 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002394 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2395 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00002396}
2397
Alexey Bataev2df54a02015-03-12 08:53:29 +00002398static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
2399 const Twine &Name,
2400 llvm::Value *Init = nullptr) {
John McCall7f416cc2015-09-08 08:05:57 +00002401 auto LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002402 if (Init)
Akira Hatanaka642f7992016-10-18 19:05:41 +00002403 CGF.EmitStoreThroughLValue(RValue::get(Init), LVal, /*isInit*/ true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002404 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002405}
2406
Alexey Bataev3392d762016-02-16 11:18:12 +00002407void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataev2df54a02015-03-12 08:53:29 +00002408 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
2409 auto *CS = dyn_cast<CompoundStmt>(Stmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002410 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002411 auto &&CodeGen = [&S, Stmt, CS, &HasLastprivates](CodeGenFunction &CGF,
2412 PrePostActionTy &) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002413 auto &C = CGF.CGM.getContext();
2414 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2415 // Emit helper vars inits.
2416 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
2417 CGF.Builder.getInt32(0));
2418 auto *GlobalUBVal = CS != nullptr ? CGF.Builder.getInt32(CS->size() - 1)
2419 : CGF.Builder.getInt32(0);
2420 LValue UB =
2421 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
2422 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
2423 CGF.Builder.getInt32(1));
2424 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
2425 CGF.Builder.getInt32(0));
2426 // Loop counter.
2427 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
2428 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2429 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
2430 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2431 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
2432 // Generate condition for loop.
2433 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
Adam Nemet484aa452017-03-27 19:17:25 +00002434 OK_Ordinary, S.getLocStart(), FPOptions());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002435 // Increment for loop counter.
2436 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
2437 S.getLocStart());
2438 auto BodyGen = [Stmt, CS, &S, &IV](CodeGenFunction &CGF) {
2439 // Iterate through all sections and emit a switch construct:
2440 // switch (IV) {
2441 // case 0:
2442 // <SectionStmt[0]>;
2443 // break;
2444 // ...
2445 // case <NumSection> - 1:
2446 // <SectionStmt[<NumSection> - 1]>;
2447 // break;
2448 // }
2449 // .omp.sections.exit:
2450 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
2451 auto *SwitchStmt = CGF.Builder.CreateSwitch(
2452 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
2453 CS == nullptr ? 1 : CS->size());
2454 if (CS) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002455 unsigned CaseNumber = 0;
Benjamin Kramer642f1732015-07-02 21:03:14 +00002456 for (auto *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002457 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2458 CGF.EmitBlock(CaseBB);
2459 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002460 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002461 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002462 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002463 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002464 } else {
2465 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2466 CGF.EmitBlock(CaseBB);
2467 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
2468 CGF.EmitStmt(Stmt);
2469 CGF.EmitBranch(ExitBB);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002470 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002471 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002472 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002473
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002474 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
2475 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002476 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002477 // initialization of firstprivate variables and post-update of lastprivate
2478 // variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002479 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
2480 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2481 /*ForceSimpleCall=*/true);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002482 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002483 CGF.EmitOMPPrivateClause(S, LoopScope);
2484 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
2485 CGF.EmitOMPReductionClauseInit(S, LoopScope);
2486 (void)LoopScope.Privatize();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002487
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002488 // Emit static non-chunked loop.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002489 OpenMPScheduleTy ScheduleKind;
2490 ScheduleKind.Schedule = OMPC_SCHEDULE_static;
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002491 CGOpenMPRuntime::StaticRTInput StaticInit(
2492 /*IVSize=*/32, /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(),
2493 LB.getAddress(), UB.getAddress(), ST.getAddress());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002494 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002495 CGF, S.getLocStart(), S.getDirectiveKind(), ScheduleKind, StaticInit);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002496 // UB = min(UB, GlobalUB);
2497 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
2498 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
2499 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
2500 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
2501 // IV = LB;
2502 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
2503 // while (idx <= UB) { BODY; ++idx; }
2504 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
2505 [](CodeGenFunction &) {});
2506 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002507 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataevf43f7142017-09-06 16:17:35 +00002508 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd(),
2509 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00002510 };
2511 CGF.OMPCancelStack.emitExit(CGF, S.getDirectiveKind(), CodeGen);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002512 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002513 // Emit post-update of the reduction variables if IsLastIter != 0.
2514 emitPostUpdateForReductionClause(
2515 CGF, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2516 return CGF.Builder.CreateIsNotNull(
2517 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2518 });
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002519
2520 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2521 if (HasLastprivates)
2522 CGF.EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002523 S, /*NoFinals=*/false,
2524 CGF.Builder.CreateIsNotNull(
2525 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002526 };
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002527
2528 bool HasCancel = false;
2529 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
2530 HasCancel = OSD->hasCancel();
2531 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
2532 HasCancel = OPSD->hasCancel();
Alexey Bataev957d8562016-11-17 15:12:05 +00002533 OMPCancelStackRAII CancelRegion(*this, S.getDirectiveKind(), HasCancel);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002534 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
2535 HasCancel);
2536 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
2537 // clause. Otherwise the barrier will be generated by the codegen for the
2538 // directive.
2539 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002540 // Emit implicit barrier to synchronize threads and avoid data races on
2541 // initialization of firstprivate variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002542 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2543 OMPD_unknown);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002544 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002545}
Alexey Bataev2df54a02015-03-12 08:53:29 +00002546
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002547void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002548 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002549 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002550 EmitSections(S);
2551 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002552 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002553 if (!S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002554 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2555 OMPD_sections);
Alexey Bataevf2685682015-03-30 04:30:22 +00002556 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002557}
2558
2559void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002560 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002561 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002562 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002563 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002564 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
2565 S.hasCancel());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002566}
2567
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002568void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002569 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00002570 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002571 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002572 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002573 // Check if there are any 'copyprivate' clauses associated with this
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002574 // 'single' construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00002575 // Build a list of copyprivate variables along with helper expressions
2576 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002577 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002578 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00002579 DestExprs.append(C->destination_exprs().begin(),
2580 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002581 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002582 AssignmentOps.append(C->assignment_ops().begin(),
2583 C->assignment_ops().end());
2584 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002585 // Emit code for 'single' region along with 'copyprivate' clauses
2586 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2587 Action.Enter(CGF);
2588 OMPPrivateScope SingleScope(CGF);
2589 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
2590 CGF.EmitOMPPrivateClause(S, SingleScope);
2591 (void)SingleScope.Privatize();
2592 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2593 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002594 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002595 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002596 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
2597 CopyprivateVars, DestExprs,
2598 SrcExprs, AssignmentOps);
2599 }
2600 // Emit an implicit barrier at the end (to avoid data race on firstprivate
2601 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
Alexey Bataev417089f2016-02-17 13:19:37 +00002602 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
Alexey Bataev5521d782015-04-24 04:21:15 +00002603 CGM.getOpenMPRuntime().emitBarrierCall(
2604 *this, S.getLocStart(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002605 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00002606 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002607}
2608
Alexey Bataev8d690652014-12-04 07:23:53 +00002609void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002610 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2611 Action.Enter(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002612 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002613 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002614 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002615 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00002616}
2617
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002618void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002619 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2620 Action.Enter(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002621 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002622 };
Alexey Bataevfc57d162015-12-15 10:55:09 +00002623 Expr *Hint = nullptr;
2624 if (auto *HintClause = S.getSingleClause<OMPHintClause>())
2625 Hint = HintClause->getHint();
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002626 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002627 CGM.getOpenMPRuntime().emitCriticalRegion(*this,
2628 S.getDirectiveName().getAsString(),
2629 CodeGen, S.getLocStart(), Hint);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002630}
2631
Alexey Bataev671605e2015-04-13 05:28:11 +00002632void CodeGenFunction::EmitOMPParallelForDirective(
2633 const OMPParallelForDirective &S) {
2634 // Emit directive as a combined directive that consists of two implicit
2635 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002636 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002637 OMPCancelStackRAII CancelRegion(CGF, OMPD_parallel_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002638 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2639 emitDispatchForLoopBounds);
Alexey Bataev671605e2015-04-13 05:28:11 +00002640 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002641 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen,
2642 emitEmptyBoundParameters);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002643}
2644
Alexander Musmane4e893b2014-09-23 09:33:00 +00002645void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002646 const OMPParallelForSimdDirective &S) {
2647 // Emit directive as a combined directive that consists of two implicit
2648 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002649 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002650 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2651 emitDispatchForLoopBounds);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002652 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002653 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen,
2654 emitEmptyBoundParameters);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002655}
2656
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002657void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002658 const OMPParallelSectionsDirective &S) {
2659 // Emit directive as a combined directive that consists of two implicit
2660 // directives: 'parallel' with 'sections' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002661 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2662 CGF.EmitSections(S);
2663 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002664 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen,
2665 emitEmptyBoundParameters);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002666}
2667
Alexey Bataev7292c292016-04-25 12:22:29 +00002668void CodeGenFunction::EmitOMPTaskBasedDirective(const OMPExecutableDirective &S,
2669 const RegionCodeGenTy &BodyGen,
2670 const TaskGenTy &TaskGen,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002671 OMPTaskDataTy &Data) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002672 // Emit outlined function for task construct.
2673 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Alexey Bataev62b63b12015-03-10 07:28:44 +00002674 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002675 auto *PartId = std::next(I);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002676 auto *TaskT = std::next(I, 4);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002677 // Check if the task is final
2678 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
2679 // If the condition constant folds and can be elided, try to avoid emitting
2680 // the condition and the dead arm of the if/else.
2681 auto *Cond = Clause->getCondition();
2682 bool CondConstant;
2683 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
2684 Data.Final.setInt(CondConstant);
2685 else
2686 Data.Final.setPointer(EvaluateExprAsBool(Cond));
2687 } else {
2688 // By default the task is not final.
2689 Data.Final.setInt(/*IntVal=*/false);
2690 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002691 // Check if the task has 'priority' clause.
2692 if (const auto *Clause = S.getSingleClause<OMPPriorityClause>()) {
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002693 auto *Prio = Clause->getPriority();
Alexey Bataev5140e742016-07-19 04:21:09 +00002694 Data.Priority.setInt(/*IntVal=*/true);
Alexey Bataevad537bb2016-05-30 09:06:50 +00002695 Data.Priority.setPointer(EmitScalarConversion(
2696 EmitScalarExpr(Prio), Prio->getType(),
2697 getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2698 Prio->getExprLoc()));
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002699 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002700 // The first function argument for tasks is a thread id, the second one is a
2701 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002702 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
2703 // Get list of private variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002704 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002705 auto IRef = C->varlist_begin();
2706 for (auto *IInit : C->private_copies()) {
2707 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2708 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002709 Data.PrivateVars.push_back(*IRef);
2710 Data.PrivateCopies.push_back(IInit);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002711 }
2712 ++IRef;
2713 }
2714 }
2715 EmittedAsPrivate.clear();
2716 // Get list of firstprivate variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002717 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002718 auto IRef = C->varlist_begin();
2719 auto IElemInitRef = C->inits().begin();
2720 for (auto *IInit : C->private_copies()) {
2721 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2722 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002723 Data.FirstprivateVars.push_back(*IRef);
2724 Data.FirstprivateCopies.push_back(IInit);
2725 Data.FirstprivateInits.push_back(*IElemInitRef);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002726 }
Richard Trieucc3949d2016-02-18 22:34:54 +00002727 ++IRef;
2728 ++IElemInitRef;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002729 }
2730 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002731 // Get list of lastprivate variables (for taskloops).
2732 llvm::DenseMap<const VarDecl *, const DeclRefExpr *> LastprivateDstsOrigs;
2733 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
2734 auto IRef = C->varlist_begin();
2735 auto ID = C->destination_exprs().begin();
2736 for (auto *IInit : C->private_copies()) {
2737 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2738 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2739 Data.LastprivateVars.push_back(*IRef);
2740 Data.LastprivateCopies.push_back(IInit);
2741 }
2742 LastprivateDstsOrigs.insert(
2743 {cast<VarDecl>(cast<DeclRefExpr>(*ID)->getDecl()),
2744 cast<DeclRefExpr>(*IRef)});
2745 ++IRef;
2746 ++ID;
2747 }
2748 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002749 SmallVector<const Expr *, 4> LHSs;
2750 SmallVector<const Expr *, 4> RHSs;
2751 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
2752 auto IPriv = C->privates().begin();
2753 auto IRed = C->reduction_ops().begin();
2754 auto ILHS = C->lhs_exprs().begin();
2755 auto IRHS = C->rhs_exprs().begin();
2756 for (const auto *Ref : C->varlists()) {
2757 Data.ReductionVars.emplace_back(Ref);
2758 Data.ReductionCopies.emplace_back(*IPriv);
2759 Data.ReductionOps.emplace_back(*IRed);
2760 LHSs.emplace_back(*ILHS);
2761 RHSs.emplace_back(*IRHS);
2762 std::advance(IPriv, 1);
2763 std::advance(IRed, 1);
2764 std::advance(ILHS, 1);
2765 std::advance(IRHS, 1);
2766 }
2767 }
2768 Data.Reductions = CGM.getOpenMPRuntime().emitTaskReductionInit(
2769 *this, S.getLocStart(), LHSs, RHSs, Data);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002770 // Build list of dependences.
Alexey Bataev7292c292016-04-25 12:22:29 +00002771 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
2772 for (auto *IRef : C->varlists())
2773 Data.Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002774 auto &&CodeGen = [&Data, &S, CS, &BodyGen, &LastprivateDstsOrigs](
Alexey Bataevf93095a2016-05-05 08:46:22 +00002775 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002776 // Set proper addresses for generated private copies.
Alexey Bataev7292c292016-04-25 12:22:29 +00002777 OMPPrivateScope Scope(CGF);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002778 if (!Data.PrivateVars.empty() || !Data.FirstprivateVars.empty() ||
2779 !Data.LastprivateVars.empty()) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00002780 enum { PrivatesParam = 2, CopyFnParam = 3 };
Alexey Bataev48591dd2016-04-20 04:01:36 +00002781 auto *CopyFn = CGF.Builder.CreateLoad(
2782 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
2783 auto *PrivatesPtr = CGF.Builder.CreateLoad(
2784 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
2785 // Map privates.
2786 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
2787 llvm::SmallVector<llvm::Value *, 16> CallArgs;
2788 CallArgs.push_back(PrivatesPtr);
Alexey Bataev7292c292016-04-25 12:22:29 +00002789 for (auto *E : Data.PrivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002790 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2791 Address PrivatePtr = CGF.CreateMemTemp(
2792 CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr");
2793 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2794 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002795 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002796 for (auto *E : Data.FirstprivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002797 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2798 Address PrivatePtr =
2799 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2800 ".firstpriv.ptr.addr");
2801 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2802 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002803 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002804 for (auto *E : Data.LastprivateVars) {
2805 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2806 Address PrivatePtr =
2807 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2808 ".lastpriv.ptr.addr");
2809 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2810 CallArgs.push_back(PrivatePtr.getPointer());
2811 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00002812 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getLocStart(),
2813 CopyFn, CallArgs);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002814 for (auto &&Pair : LastprivateDstsOrigs) {
2815 auto *OrigVD = cast<VarDecl>(Pair.second->getDecl());
2816 DeclRefExpr DRE(
2817 const_cast<VarDecl *>(OrigVD),
2818 /*RefersToEnclosingVariableOrCapture=*/CGF.CapturedStmtInfo->lookup(
2819 OrigVD) != nullptr,
2820 Pair.second->getType(), VK_LValue, Pair.second->getExprLoc());
2821 Scope.addPrivate(Pair.first, [&CGF, &DRE]() {
2822 return CGF.EmitLValue(&DRE).getAddress();
2823 });
2824 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00002825 for (auto &&Pair : PrivatePtrs) {
2826 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
2827 CGF.getContext().getDeclAlign(Pair.first));
2828 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
2829 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002830 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002831 if (Data.Reductions) {
2832 OMPLexicalScope LexScope(CGF, S, /*AsInlined=*/true);
2833 ReductionCodeGen RedCG(Data.ReductionVars, Data.ReductionCopies,
2834 Data.ReductionOps);
2835 llvm::Value *ReductionsPtr = CGF.Builder.CreateLoad(
2836 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(9)));
2837 for (unsigned Cnt = 0, E = Data.ReductionVars.size(); Cnt < E; ++Cnt) {
2838 RedCG.emitSharedLValue(CGF, Cnt);
2839 RedCG.emitAggregateType(CGF, Cnt);
2840 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
2841 CGF, S.getLocStart(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
2842 Replacement =
2843 Address(CGF.EmitScalarConversion(
2844 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
2845 CGF.getContext().getPointerType(
2846 Data.ReductionCopies[Cnt]->getType()),
2847 SourceLocation()),
2848 Replacement.getAlignment());
2849 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
2850 Scope.addPrivate(RedCG.getBaseDecl(Cnt),
2851 [Replacement]() { return Replacement; });
2852 // FIXME: This must removed once the runtime library is fixed.
2853 // Emit required threadprivate variables for
2854 // initilizer/combiner/finalizer.
2855 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getLocStart(),
2856 RedCG, Cnt);
2857 }
2858 }
Alexey Bataev88202be2017-07-27 13:20:36 +00002859 // Privatize all private variables except for in_reduction items.
Alexey Bataev48591dd2016-04-20 04:01:36 +00002860 (void)Scope.Privatize();
Alexey Bataev88202be2017-07-27 13:20:36 +00002861 SmallVector<const Expr *, 4> InRedVars;
2862 SmallVector<const Expr *, 4> InRedPrivs;
2863 SmallVector<const Expr *, 4> InRedOps;
2864 SmallVector<const Expr *, 4> TaskgroupDescriptors;
2865 for (const auto *C : S.getClausesOfKind<OMPInReductionClause>()) {
2866 auto IPriv = C->privates().begin();
2867 auto IRed = C->reduction_ops().begin();
2868 auto ITD = C->taskgroup_descriptors().begin();
2869 for (const auto *Ref : C->varlists()) {
2870 InRedVars.emplace_back(Ref);
2871 InRedPrivs.emplace_back(*IPriv);
2872 InRedOps.emplace_back(*IRed);
2873 TaskgroupDescriptors.emplace_back(*ITD);
2874 std::advance(IPriv, 1);
2875 std::advance(IRed, 1);
2876 std::advance(ITD, 1);
2877 }
2878 }
2879 // Privatize in_reduction items here, because taskgroup descriptors must be
2880 // privatized earlier.
2881 OMPPrivateScope InRedScope(CGF);
2882 if (!InRedVars.empty()) {
2883 ReductionCodeGen RedCG(InRedVars, InRedPrivs, InRedOps);
2884 for (unsigned Cnt = 0, E = InRedVars.size(); Cnt < E; ++Cnt) {
2885 RedCG.emitSharedLValue(CGF, Cnt);
2886 RedCG.emitAggregateType(CGF, Cnt);
2887 // The taskgroup descriptor variable is always implicit firstprivate and
2888 // privatized already during procoessing of the firstprivates.
2889 llvm::Value *ReductionsPtr = CGF.EmitLoadOfScalar(
2890 CGF.EmitLValue(TaskgroupDescriptors[Cnt]), SourceLocation());
2891 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
2892 CGF, S.getLocStart(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
2893 Replacement = Address(
2894 CGF.EmitScalarConversion(
2895 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
2896 CGF.getContext().getPointerType(InRedPrivs[Cnt]->getType()),
2897 SourceLocation()),
2898 Replacement.getAlignment());
2899 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
2900 InRedScope.addPrivate(RedCG.getBaseDecl(Cnt),
2901 [Replacement]() { return Replacement; });
2902 // FIXME: This must removed once the runtime library is fixed.
2903 // Emit required threadprivate variables for
2904 // initilizer/combiner/finalizer.
2905 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getLocStart(),
2906 RedCG, Cnt);
2907 }
2908 }
2909 (void)InRedScope.Privatize();
Alexey Bataev48591dd2016-04-20 04:01:36 +00002910
2911 Action.Enter(CGF);
Alexey Bataev7292c292016-04-25 12:22:29 +00002912 BodyGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002913 };
Alexey Bataev7292c292016-04-25 12:22:29 +00002914 auto *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
2915 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, Data.Tied,
2916 Data.NumberOfParts);
2917 OMPLexicalScope Scope(*this, S);
2918 TaskGen(*this, OutlinedFn, Data);
2919}
2920
2921void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
2922 // Emit outlined function for task construct.
2923 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2924 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002925 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00002926 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00002927 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
2928 if (C->getNameModifier() == OMPD_unknown ||
2929 C->getNameModifier() == OMPD_task) {
2930 IfCond = C->getCondition();
2931 break;
2932 }
Alexey Bataev1d677132015-04-22 13:57:31 +00002933 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002934
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002935 OMPTaskDataTy Data;
2936 // Check if we should emit tied or untied task.
2937 Data.Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00002938 auto &&BodyGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
2939 CGF.EmitStmt(CS->getCapturedStmt());
2940 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002941 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
Alexey Bataev7292c292016-04-25 12:22:29 +00002942 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002943 const OMPTaskDataTy &Data) {
2944 CGF.CGM.getOpenMPRuntime().emitTaskCall(CGF, S.getLocStart(), S, OutlinedFn,
2945 SharedsTy, CapturedStruct, IfCond,
2946 Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00002947 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002948 EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002949}
2950
Alexey Bataev9f797f32015-02-05 05:57:51 +00002951void CodeGenFunction::EmitOMPTaskyieldDirective(
2952 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002953 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00002954}
2955
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002956void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002957 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002958}
2959
Alexey Bataev8b8e2022015-04-27 05:22:09 +00002960void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
2961 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00002962}
2963
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002964void CodeGenFunction::EmitOMPTaskgroupDirective(
2965 const OMPTaskgroupDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002966 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2967 Action.Enter(CGF);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00002968 if (const Expr *E = S.getReductionRef()) {
2969 SmallVector<const Expr *, 4> LHSs;
2970 SmallVector<const Expr *, 4> RHSs;
2971 OMPTaskDataTy Data;
2972 for (const auto *C : S.getClausesOfKind<OMPTaskReductionClause>()) {
2973 auto IPriv = C->privates().begin();
2974 auto IRed = C->reduction_ops().begin();
2975 auto ILHS = C->lhs_exprs().begin();
2976 auto IRHS = C->rhs_exprs().begin();
2977 for (const auto *Ref : C->varlists()) {
2978 Data.ReductionVars.emplace_back(Ref);
2979 Data.ReductionCopies.emplace_back(*IPriv);
2980 Data.ReductionOps.emplace_back(*IRed);
2981 LHSs.emplace_back(*ILHS);
2982 RHSs.emplace_back(*IRHS);
2983 std::advance(IPriv, 1);
2984 std::advance(IRed, 1);
2985 std::advance(ILHS, 1);
2986 std::advance(IRHS, 1);
2987 }
2988 }
2989 llvm::Value *ReductionDesc =
2990 CGF.CGM.getOpenMPRuntime().emitTaskReductionInit(CGF, S.getLocStart(),
2991 LHSs, RHSs, Data);
2992 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2993 CGF.EmitVarDecl(*VD);
2994 CGF.EmitStoreOfScalar(ReductionDesc, CGF.GetAddrOfLocalVar(VD),
2995 /*Volatile=*/false, E->getType());
2996 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002997 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002998 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002999 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003000 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getLocStart());
3001}
3002
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003003void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003004 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003005 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003006 return llvm::makeArrayRef(FlushClause->varlist_begin(),
3007 FlushClause->varlist_end());
3008 }
3009 return llvm::None;
3010 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00003011}
3012
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003013void CodeGenFunction::EmitOMPDistributeLoop(const OMPLoopDirective &S,
3014 const CodeGenLoopTy &CodeGenLoop,
3015 Expr *IncExpr) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003016 // Emit the loop iteration variable.
3017 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
3018 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
3019 EmitVarDecl(*IVDecl);
3020
3021 // Emit the iterations count variable.
3022 // If it is not a variable, Sema decided to calculate iterations count on each
3023 // iteration (e.g., it is foldable into a constant).
3024 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
3025 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
3026 // Emit calculation of the iterations count.
3027 EmitIgnoredExpr(S.getCalcLastIteration());
3028 }
3029
3030 auto &RT = CGM.getOpenMPRuntime();
3031
Carlo Bertolli962bb802017-01-03 18:24:42 +00003032 bool HasLastprivateClause = false;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003033 // Check pre-condition.
3034 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003035 OMPLoopScope PreInitScope(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003036 // Skip the entire loop if we don't meet the precondition.
3037 // If the condition constant folds and can be elided, avoid emitting the
3038 // whole loop.
3039 bool CondConstant;
3040 llvm::BasicBlock *ContBlock = nullptr;
3041 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
3042 if (!CondConstant)
3043 return;
3044 } else {
3045 auto *ThenBlock = createBasicBlock("omp.precond.then");
3046 ContBlock = createBasicBlock("omp.precond.end");
3047 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
3048 getProfileCount(&S));
3049 EmitBlock(ThenBlock);
3050 incrementProfileCounter(&S);
3051 }
3052
Alexey Bataev617db5f2017-12-04 15:38:33 +00003053 emitAlignedClause(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003054 // Emit 'then' code.
3055 {
3056 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003057
3058 LValue LB = EmitOMPHelperVar(
3059 *this, cast<DeclRefExpr>(
3060 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3061 ? S.getCombinedLowerBoundVariable()
3062 : S.getLowerBoundVariable())));
3063 LValue UB = EmitOMPHelperVar(
3064 *this, cast<DeclRefExpr>(
3065 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3066 ? S.getCombinedUpperBoundVariable()
3067 : S.getUpperBoundVariable())));
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003068 LValue ST =
3069 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
3070 LValue IL =
3071 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
3072
3073 OMPPrivateScope LoopScope(*this);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003074 if (EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00003075 // Emit implicit barrier to synchronize threads and avoid data races
3076 // on initialization of firstprivate variables and post-update of
Carlo Bertolli962bb802017-01-03 18:24:42 +00003077 // lastprivate variables.
3078 CGM.getOpenMPRuntime().emitBarrierCall(
Alexey Bataev617db5f2017-12-04 15:38:33 +00003079 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
3080 /*ForceSimpleCall=*/true);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003081 }
3082 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev617db5f2017-12-04 15:38:33 +00003083 if (isOpenMPSimdDirective(S.getDirectiveKind()) &&
Alexey Bataev999277a2017-12-06 14:31:09 +00003084 !isOpenMPParallelDirective(S.getDirectiveKind()) &&
3085 !isOpenMPTeamsDirective(S.getDirectiveKind()))
Alexey Bataev617db5f2017-12-04 15:38:33 +00003086 EmitOMPReductionClauseInit(S, LoopScope);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003087 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003088 EmitOMPPrivateLoopCounters(S, LoopScope);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003089 (void)LoopScope.Privatize();
3090
3091 // Detect the distribute schedule kind and chunk.
3092 llvm::Value *Chunk = nullptr;
3093 OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown;
3094 if (auto *C = S.getSingleClause<OMPDistScheduleClause>()) {
3095 ScheduleKind = C->getDistScheduleKind();
3096 if (const auto *Ch = C->getChunkSize()) {
3097 Chunk = EmitScalarExpr(Ch);
3098 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
Alexey Bataev617db5f2017-12-04 15:38:33 +00003099 S.getIterationVariable()->getType(),
3100 S.getLocStart());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003101 }
3102 }
3103 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
3104 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
3105
3106 // OpenMP [2.10.8, distribute Construct, Description]
3107 // If dist_schedule is specified, kind must be static. If specified,
3108 // iterations are divided into chunks of size chunk_size, chunks are
3109 // assigned to the teams of the league in a round-robin fashion in the
3110 // order of the team number. When no chunk_size is specified, the
3111 // iteration space is divided into chunks that are approximately equal
3112 // in size, and at most one chunk is distributed to each team of the
3113 // league. The size of the chunks is unspecified in this case.
3114 if (RT.isStaticNonchunked(ScheduleKind,
3115 /* Chunked */ Chunk != nullptr)) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00003116 if (isOpenMPSimdDirective(S.getDirectiveKind()))
3117 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003118 CGOpenMPRuntime::StaticRTInput StaticInit(
3119 IVSize, IVSigned, /* Ordered = */ false, IL.getAddress(),
3120 LB.getAddress(), UB.getAddress(), ST.getAddress());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003121 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003122 StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003123 auto LoopExit =
3124 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
3125 // UB = min(UB, GlobalUB);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003126 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3127 ? S.getCombinedEnsureUpperBound()
3128 : S.getEnsureUpperBound());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003129 // IV = LB;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003130 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3131 ? S.getCombinedInit()
3132 : S.getInit());
3133
3134 Expr *Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3135 ? S.getCombinedCond()
3136 : S.getCond();
3137
3138 // for distribute alone, codegen
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003139 // while (idx <= UB) { BODY; ++idx; }
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003140 // when combined with 'for' (e.g. as in 'distribute parallel for')
3141 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
3142 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), Cond, IncExpr,
3143 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
3144 CodeGenLoop(CGF, S, LoopExit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003145 },
3146 [](CodeGenFunction &) {});
3147 EmitBlock(LoopExit.getBlock());
3148 // Tell the runtime we are done.
Alexey Bataevf43f7142017-09-06 16:17:35 +00003149 RT.emitForStaticFinish(*this, S.getLocStart(), S.getDirectiveKind());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003150 } else {
3151 // Emit the outer loop, which requests its work chunk [LB..UB] from
3152 // runtime and runs the inner loop to process it.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003153 const OMPLoopArguments LoopArguments = {
3154 LB.getAddress(), UB.getAddress(), ST.getAddress(), IL.getAddress(),
3155 Chunk};
3156 EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope, LoopArguments,
3157 CodeGenLoop);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003158 }
Alexey Bataev617db5f2017-12-04 15:38:33 +00003159 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
3160 EmitOMPSimdFinal(S, [&](CodeGenFunction &CGF) -> llvm::Value * {
3161 return CGF.Builder.CreateIsNotNull(
3162 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
3163 });
3164 }
3165 OpenMPDirectiveKind ReductionKind = OMPD_unknown;
3166 if (isOpenMPParallelDirective(S.getDirectiveKind()) &&
3167 isOpenMPSimdDirective(S.getDirectiveKind())) {
3168 ReductionKind = OMPD_parallel_for_simd;
3169 } else if (isOpenMPParallelDirective(S.getDirectiveKind())) {
3170 ReductionKind = OMPD_parallel_for;
3171 } else if (isOpenMPSimdDirective(S.getDirectiveKind())) {
3172 ReductionKind = OMPD_simd;
3173 } else if (!isOpenMPTeamsDirective(S.getDirectiveKind()) &&
3174 S.hasClausesOfKind<OMPReductionClause>()) {
3175 llvm_unreachable(
3176 "No reduction clauses is allowed in distribute directive.");
3177 }
3178 EmitOMPReductionClauseFinal(S, ReductionKind);
3179 // Emit post-update of the reduction variables if IsLastIter != 0.
3180 emitPostUpdateForReductionClause(
3181 *this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
3182 return CGF.Builder.CreateIsNotNull(
3183 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
3184 });
Carlo Bertolli962bb802017-01-03 18:24:42 +00003185 // Emit final copy of the lastprivate variables if IsLastIter != 0.
Alexey Bataev617db5f2017-12-04 15:38:33 +00003186 if (HasLastprivateClause) {
Carlo Bertolli962bb802017-01-03 18:24:42 +00003187 EmitOMPLastprivateClauseFinal(
3188 S, /*NoFinals=*/false,
Alexey Bataev617db5f2017-12-04 15:38:33 +00003189 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
3190 }
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003191 }
3192
3193 // We're now done with the loop, so jump to the continuation block.
3194 if (ContBlock) {
3195 EmitBranch(ContBlock);
3196 EmitBlock(ContBlock, true);
3197 }
3198 }
3199}
3200
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003201void CodeGenFunction::EmitOMPDistributeDirective(
3202 const OMPDistributeDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003203 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003204
3205 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003206 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00003207 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev10a54312017-11-27 16:54:08 +00003208 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003209}
3210
Alexey Bataev5f600d62015-09-29 03:48:57 +00003211static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
3212 const CapturedStmt *S) {
3213 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
3214 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
3215 CGF.CapturedStmtInfo = &CapStmtInfo;
3216 auto *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
3217 Fn->addFnAttr(llvm::Attribute::NoInline);
3218 return Fn;
3219}
3220
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003221void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
Alexey Bataev8b427062016-05-25 12:36:08 +00003222 if (!S.getAssociatedStmt()) {
3223 for (const auto *DC : S.getClausesOfKind<OMPDependClause>())
3224 CGM.getOpenMPRuntime().emitDoacrossOrdered(*this, DC);
Alexey Bataev8ef31412015-12-18 07:58:25 +00003225 return;
Alexey Bataev8b427062016-05-25 12:36:08 +00003226 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00003227 auto *C = S.getSingleClause<OMPSIMDClause>();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003228 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF,
3229 PrePostActionTy &Action) {
Alexey Bataev5f600d62015-09-29 03:48:57 +00003230 if (C) {
3231 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
3232 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3233 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
3234 auto *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
Alexey Bataev3c595a62017-08-14 15:01:03 +00003235 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getLocStart(),
3236 OutlinedFn, CapturedVars);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003237 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003238 Action.Enter(CGF);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003239 CGF.EmitStmt(
3240 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3241 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003242 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00003243 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003244 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart(), !C);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003245}
3246
Alexey Bataevb57056f2015-01-22 06:17:56 +00003247static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003248 QualType SrcType, QualType DestType,
3249 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003250 assert(CGF.hasScalarEvaluationKind(DestType) &&
3251 "DestType must have scalar evaluation kind.");
3252 assert(!Val.isAggregate() && "Must be a scalar or complex.");
3253 return Val.isScalar()
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003254 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType,
3255 Loc)
Alexey Bataevb57056f2015-01-22 06:17:56 +00003256 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003257 DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003258}
3259
3260static CodeGenFunction::ComplexPairTy
3261convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003262 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003263 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
3264 "DestType must have complex evaluation kind.");
3265 CodeGenFunction::ComplexPairTy ComplexVal;
3266 if (Val.isScalar()) {
3267 // Convert the input element to the element type of the complex.
3268 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003269 auto ScalarVal = CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
3270 DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003271 ComplexVal = CodeGenFunction::ComplexPairTy(
3272 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
3273 } else {
3274 assert(Val.isComplex() && "Must be a scalar or complex.");
3275 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
3276 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
3277 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003278 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003279 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003280 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003281 }
3282 return ComplexVal;
3283}
3284
Alexey Bataev5e018f92015-04-23 06:35:10 +00003285static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
3286 LValue LVal, RValue RVal) {
3287 if (LVal.isGlobalReg()) {
3288 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
3289 } else {
JF Bastien92f4ef12016-04-06 17:26:42 +00003290 CGF.EmitAtomicStore(RVal, LVal,
3291 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3292 : llvm::AtomicOrdering::Monotonic,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003293 LVal.isVolatile(), /*IsInit=*/false);
3294 }
3295}
3296
Alexey Bataev8524d152016-01-21 12:35:58 +00003297void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
3298 QualType RValTy, SourceLocation Loc) {
3299 switch (getEvaluationKind(LVal.getType())) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003300 case TEK_Scalar:
Alexey Bataev8524d152016-01-21 12:35:58 +00003301 EmitStoreThroughLValue(RValue::get(convertToScalarValue(
3302 *this, RVal, RValTy, LVal.getType(), Loc)),
3303 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003304 break;
3305 case TEK_Complex:
Alexey Bataev8524d152016-01-21 12:35:58 +00003306 EmitStoreOfComplex(
3307 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003308 /*isInit=*/false);
3309 break;
3310 case TEK_Aggregate:
3311 llvm_unreachable("Must be a scalar or complex.");
3312 }
3313}
3314
Alexey Bataevb57056f2015-01-22 06:17:56 +00003315static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
3316 const Expr *X, const Expr *V,
3317 SourceLocation Loc) {
3318 // v = x;
3319 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
3320 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
3321 LValue XLValue = CGF.EmitLValue(X);
3322 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00003323 RValue Res = XLValue.isGlobalReg()
3324 ? CGF.EmitLoadOfLValue(XLValue, Loc)
JF Bastien92f4ef12016-04-06 17:26:42 +00003325 : CGF.EmitAtomicLoad(
3326 XLValue, Loc,
3327 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3328 : llvm::AtomicOrdering::Monotonic,
3329 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00003330 // OpenMP, 2.12.6, atomic Construct
3331 // Any atomic construct with a seq_cst clause forces the atomically
3332 // performed operation to include an implicit flush operation without a
3333 // list.
3334 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003335 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev8524d152016-01-21 12:35:58 +00003336 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003337}
3338
Alexey Bataevb8329262015-02-27 06:33:30 +00003339static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
3340 const Expr *X, const Expr *E,
3341 SourceLocation Loc) {
3342 // x = expr;
3343 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00003344 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00003345 // OpenMP, 2.12.6, atomic Construct
3346 // Any atomic construct with a seq_cst clause forces the atomically
3347 // performed operation to include an implicit flush operation without a
3348 // list.
3349 if (IsSeqCst)
3350 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3351}
3352
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003353static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
3354 RValue Update,
3355 BinaryOperatorKind BO,
3356 llvm::AtomicOrdering AO,
3357 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003358 auto &Context = CGF.CGM.getContext();
3359 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00003360 // expression is simple and atomic is allowed for the given type for the
3361 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003362 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00003363 !Update.getScalarVal()->getType()->isIntegerTy() ||
3364 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
3365 (Update.getScalarVal()->getType() !=
John McCall7f416cc2015-09-08 08:05:57 +00003366 X.getAddress().getElementType())) ||
3367 !X.getAddress().getElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003368 !Context.getTargetInfo().hasBuiltinAtomic(
3369 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00003370 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003371
3372 llvm::AtomicRMWInst::BinOp RMWOp;
3373 switch (BO) {
3374 case BO_Add:
3375 RMWOp = llvm::AtomicRMWInst::Add;
3376 break;
3377 case BO_Sub:
3378 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00003379 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003380 RMWOp = llvm::AtomicRMWInst::Sub;
3381 break;
3382 case BO_And:
3383 RMWOp = llvm::AtomicRMWInst::And;
3384 break;
3385 case BO_Or:
3386 RMWOp = llvm::AtomicRMWInst::Or;
3387 break;
3388 case BO_Xor:
3389 RMWOp = llvm::AtomicRMWInst::Xor;
3390 break;
3391 case BO_LT:
3392 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3393 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
3394 : llvm::AtomicRMWInst::Max)
3395 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
3396 : llvm::AtomicRMWInst::UMax);
3397 break;
3398 case BO_GT:
3399 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3400 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
3401 : llvm::AtomicRMWInst::Min)
3402 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
3403 : llvm::AtomicRMWInst::UMin);
3404 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003405 case BO_Assign:
3406 RMWOp = llvm::AtomicRMWInst::Xchg;
3407 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003408 case BO_Mul:
3409 case BO_Div:
3410 case BO_Rem:
3411 case BO_Shl:
3412 case BO_Shr:
3413 case BO_LAnd:
3414 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003415 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003416 case BO_PtrMemD:
3417 case BO_PtrMemI:
3418 case BO_LE:
3419 case BO_GE:
3420 case BO_EQ:
3421 case BO_NE:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003422 case BO_AddAssign:
3423 case BO_SubAssign:
3424 case BO_AndAssign:
3425 case BO_OrAssign:
3426 case BO_XorAssign:
3427 case BO_MulAssign:
3428 case BO_DivAssign:
3429 case BO_RemAssign:
3430 case BO_ShlAssign:
3431 case BO_ShrAssign:
3432 case BO_Comma:
3433 llvm_unreachable("Unsupported atomic update operation");
3434 }
3435 auto *UpdateVal = Update.getScalarVal();
3436 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
3437 UpdateVal = CGF.Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00003438 IC, X.getAddress().getElementType(),
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003439 X.getType()->hasSignedIntegerRepresentation());
3440 }
John McCall7f416cc2015-09-08 08:05:57 +00003441 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003442 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003443}
3444
Alexey Bataev5e018f92015-04-23 06:35:10 +00003445std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003446 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
3447 llvm::AtomicOrdering AO, SourceLocation Loc,
3448 const llvm::function_ref<RValue(RValue)> &CommonGen) {
3449 // Update expressions are allowed to have the following forms:
3450 // x binop= expr; -> xrval + expr;
3451 // x++, ++x -> xrval + 1;
3452 // x--, --x -> xrval - 1;
3453 // x = x binop expr; -> xrval binop expr
3454 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003455 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
3456 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003457 if (X.isGlobalReg()) {
3458 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
3459 // 'xrval'.
3460 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
3461 } else {
3462 // Perform compare-and-swap procedure.
3463 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00003464 }
3465 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00003466 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003467}
3468
3469static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
3470 const Expr *X, const Expr *E,
3471 const Expr *UE, bool IsXLHSInRHSPart,
3472 SourceLocation Loc) {
3473 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3474 "Update expr in 'atomic update' must be a binary operator.");
3475 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3476 // Update expressions are allowed to have the following forms:
3477 // x binop= expr; -> xrval + expr;
3478 // x++, ++x -> xrval + 1;
3479 // x--, --x -> xrval - 1;
3480 // x = x binop expr; -> xrval binop expr
3481 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003482 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00003483 LValue XLValue = CGF.EmitLValue(X);
3484 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00003485 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3486 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003487 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3488 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3489 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3490 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3491 auto Gen =
3492 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
3493 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3494 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3495 return CGF.EmitAnyExpr(UE);
3496 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00003497 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
3498 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3499 // OpenMP, 2.12.6, atomic Construct
3500 // Any atomic construct with a seq_cst clause forces the atomically
3501 // performed operation to include an implicit flush operation without a
3502 // list.
3503 if (IsSeqCst)
3504 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3505}
3506
3507static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003508 QualType SourceType, QualType ResType,
3509 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003510 switch (CGF.getEvaluationKind(ResType)) {
3511 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003512 return RValue::get(
3513 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00003514 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003515 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003516 return RValue::getComplex(Res.first, Res.second);
3517 }
3518 case TEK_Aggregate:
3519 break;
3520 }
3521 llvm_unreachable("Must be a scalar or complex.");
3522}
3523
3524static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
3525 bool IsPostfixUpdate, const Expr *V,
3526 const Expr *X, const Expr *E,
3527 const Expr *UE, bool IsXLHSInRHSPart,
3528 SourceLocation Loc) {
3529 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
3530 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
3531 RValue NewVVal;
3532 LValue VLValue = CGF.EmitLValue(V);
3533 LValue XLValue = CGF.EmitLValue(X);
3534 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00003535 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3536 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003537 QualType NewVValType;
3538 if (UE) {
3539 // 'x' is updated with some additional value.
3540 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3541 "Update expr in 'atomic capture' must be a binary operator.");
3542 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3543 // Update expressions are allowed to have the following forms:
3544 // x binop= expr; -> xrval + expr;
3545 // x++, ++x -> xrval + 1;
3546 // x--, --x -> xrval - 1;
3547 // x = x binop expr; -> xrval binop expr
3548 // x = expr Op x; - > expr binop xrval;
3549 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3550 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3551 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3552 NewVValType = XRValExpr->getType();
3553 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3554 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00003555 IsPostfixUpdate](RValue XRValue) -> RValue {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003556 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3557 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3558 RValue Res = CGF.EmitAnyExpr(UE);
3559 NewVVal = IsPostfixUpdate ? XRValue : Res;
3560 return Res;
3561 };
3562 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3563 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3564 if (Res.first) {
3565 // 'atomicrmw' instruction was generated.
3566 if (IsPostfixUpdate) {
3567 // Use old value from 'atomicrmw'.
3568 NewVVal = Res.second;
3569 } else {
3570 // 'atomicrmw' does not provide new value, so evaluate it using old
3571 // value of 'x'.
3572 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3573 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
3574 NewVVal = CGF.EmitAnyExpr(UE);
3575 }
3576 }
3577 } else {
3578 // 'x' is simply rewritten with some 'expr'.
3579 NewVValType = X->getType().getNonReferenceType();
3580 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003581 X->getType().getNonReferenceType(), Loc);
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00003582 auto &&Gen = [&NewVVal, ExprRValue](RValue XRValue) -> RValue {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003583 NewVVal = XRValue;
3584 return ExprRValue;
3585 };
3586 // Try to perform atomicrmw xchg, otherwise simple exchange.
3587 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3588 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
3589 Loc, Gen);
3590 if (Res.first) {
3591 // 'atomicrmw' instruction was generated.
3592 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
3593 }
3594 }
3595 // Emit post-update store to 'v' of old/new 'x' value.
Alexey Bataev8524d152016-01-21 12:35:58 +00003596 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00003597 // OpenMP, 2.12.6, atomic Construct
3598 // Any atomic construct with a seq_cst clause forces the atomically
3599 // performed operation to include an implicit flush operation without a
3600 // list.
3601 if (IsSeqCst)
3602 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3603}
3604
Alexey Bataevb57056f2015-01-22 06:17:56 +00003605static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003606 bool IsSeqCst, bool IsPostfixUpdate,
3607 const Expr *X, const Expr *V, const Expr *E,
3608 const Expr *UE, bool IsXLHSInRHSPart,
3609 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003610 switch (Kind) {
3611 case OMPC_read:
3612 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
3613 break;
3614 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00003615 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
3616 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003617 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003618 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00003619 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
3620 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003621 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003622 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
3623 IsXLHSInRHSPart, Loc);
3624 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003625 case OMPC_if:
3626 case OMPC_final:
3627 case OMPC_num_threads:
3628 case OMPC_private:
3629 case OMPC_firstprivate:
3630 case OMPC_lastprivate:
3631 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00003632 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00003633 case OMPC_in_reduction:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003634 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00003635 case OMPC_simdlen:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003636 case OMPC_collapse:
3637 case OMPC_default:
3638 case OMPC_seq_cst:
3639 case OMPC_shared:
3640 case OMPC_linear:
3641 case OMPC_aligned:
3642 case OMPC_copyin:
3643 case OMPC_copyprivate:
3644 case OMPC_flush:
3645 case OMPC_proc_bind:
3646 case OMPC_schedule:
3647 case OMPC_ordered:
3648 case OMPC_nowait:
3649 case OMPC_untied:
3650 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00003651 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003652 case OMPC_mergeable:
Michael Wonge710d542015-08-07 16:16:36 +00003653 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00003654 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003655 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00003656 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00003657 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00003658 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00003659 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00003660 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00003661 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00003662 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00003663 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00003664 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00003665 case OMPC_defaultmap:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003666 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00003667 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00003668 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00003669 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00003670 case OMPC_is_device_ptr:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003671 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
3672 }
3673}
3674
3675void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003676 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
Alexey Bataevb57056f2015-01-22 06:17:56 +00003677 OpenMPClauseKind Kind = OMPC_unknown;
3678 for (auto *C : S.clauses()) {
3679 // Find first clause (skip seq_cst clause, if it is first).
3680 if (C->getClauseKind() != OMPC_seq_cst) {
3681 Kind = C->getClauseKind();
3682 break;
3683 }
3684 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003685
3686 const auto *CS =
3687 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003688 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00003689 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003690 }
3691 // Processing for statements under 'atomic capture'.
3692 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
3693 for (const auto *C : Compound->body()) {
3694 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
3695 enterFullExpression(EWC);
3696 }
3697 }
3698 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003699
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003700 auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF,
3701 PrePostActionTy &) {
Alexey Bataev33c56402015-12-14 09:26:19 +00003702 CGF.EmitStopPoint(CS);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003703 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
3704 S.getV(), S.getExpr(), S.getUpdateExpr(),
3705 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003706 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00003707 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003708 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00003709}
3710
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003711static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
3712 const OMPExecutableDirective &S,
3713 const RegionCodeGenTy &CodeGen) {
3714 assert(isOpenMPTargetExecutionDirective(S.getDirectiveKind()));
3715 CodeGenModule &CGM = CGF.CGM;
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00003716 const CapturedStmt &CS = *S.getCapturedStmt(OMPD_target);
Samuel Antaobed3c462015-10-02 16:14:20 +00003717
Samuel Antaoee8fb302016-01-06 13:42:12 +00003718 llvm::Function *Fn = nullptr;
3719 llvm::Constant *FnID = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00003720
Samuel Antaobed3c462015-10-02 16:14:20 +00003721 const Expr *IfCond = nullptr;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003722 // Check for the at most one if clause associated with the target region.
3723 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3724 if (C->getNameModifier() == OMPD_unknown ||
3725 C->getNameModifier() == OMPD_target) {
3726 IfCond = C->getCondition();
3727 break;
3728 }
Samuel Antaobed3c462015-10-02 16:14:20 +00003729 }
3730
3731 // Check if we have any device clause associated with the directive.
3732 const Expr *Device = nullptr;
3733 if (auto *C = S.getSingleClause<OMPDeviceClause>()) {
3734 Device = C->getDevice();
3735 }
3736
Samuel Antaoee8fb302016-01-06 13:42:12 +00003737 // Check if we have an if clause whose conditional always evaluates to false
3738 // or if we do not have any targets specified. If so the target region is not
3739 // an offload entry point.
3740 bool IsOffloadEntry = true;
3741 if (IfCond) {
3742 bool Val;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003743 if (CGF.ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
Samuel Antaoee8fb302016-01-06 13:42:12 +00003744 IsOffloadEntry = false;
3745 }
3746 if (CGM.getLangOpts().OMPTargetTriples.empty())
3747 IsOffloadEntry = false;
3748
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003749 assert(CGF.CurFuncDecl && "No parent declaration for target region!");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003750 StringRef ParentName;
3751 // In case we have Ctors/Dtors we use the complete type variant to produce
3752 // the mangling of the device outlined kernel.
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003753 if (auto *D = dyn_cast<CXXConstructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00003754 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003755 else if (auto *D = dyn_cast<CXXDestructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00003756 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
3757 else
3758 ParentName =
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003759 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CGF.CurFuncDecl)));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003760
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003761 // Emit target region as a standalone region.
3762 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
3763 IsOffloadEntry, CodeGen);
3764 OMPLexicalScope Scope(CGF, S);
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003765 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3766 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003767 CGM.getOpenMPRuntime().emitTargetCall(CGF, S, Fn, FnID, IfCond, Device,
Samuel Antaobed3c462015-10-02 16:14:20 +00003768 CapturedVars);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003769}
3770
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003771static void emitTargetRegion(CodeGenFunction &CGF, const OMPTargetDirective &S,
3772 PrePostActionTy &Action) {
3773 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
3774 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3775 CGF.EmitOMPPrivateClause(S, PrivateScope);
3776 (void)PrivateScope.Privatize();
3777
3778 Action.Enter(CGF);
3779 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3780}
3781
3782void CodeGenFunction::EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
3783 StringRef ParentName,
3784 const OMPTargetDirective &S) {
3785 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3786 emitTargetRegion(CGF, S, Action);
3787 };
3788 llvm::Function *Fn;
3789 llvm::Constant *Addr;
3790 // Emit target region as a standalone region.
3791 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3792 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
3793 assert(Fn && Addr && "Target device function emission failed.");
3794}
3795
3796void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
3797 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3798 emitTargetRegion(CGF, S, Action);
3799 };
3800 emitCommonOMPTargetDirective(*this, S, CodeGen);
3801}
3802
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003803static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF,
3804 const OMPExecutableDirective &S,
3805 OpenMPDirectiveKind InnermostKind,
3806 const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003807 const CapturedStmt *CS = S.getCapturedStmt(OMPD_teams);
3808 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitTeamsOutlinedFunction(
3809 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Samuel Antaob68e2db2016-03-03 16:20:23 +00003810
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003811 const OMPNumTeamsClause *NT = S.getSingleClause<OMPNumTeamsClause>();
3812 const OMPThreadLimitClause *TL = S.getSingleClause<OMPThreadLimitClause>();
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003813 if (NT || TL) {
Carlo Bertollic6872252016-04-04 15:55:02 +00003814 Expr *NumTeams = (NT) ? NT->getNumTeams() : nullptr;
3815 Expr *ThreadLimit = (TL) ? TL->getThreadLimit() : nullptr;
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003816
Carlo Bertollic6872252016-04-04 15:55:02 +00003817 CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit,
3818 S.getLocStart());
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003819 }
3820
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003821 OMPTeamsScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003822 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3823 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003824 CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getLocStart(), OutlinedFn,
3825 CapturedVars);
3826}
3827
3828void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
Kelvin Li51336dd2016-12-15 17:55:32 +00003829 // Emit teams region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003830 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003831 OMPPrivateScope PrivateScope(CGF);
Carlo Bertolli6ad7b5a2016-03-03 22:09:40 +00003832 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3833 CGF.EmitOMPPrivateClause(S, PrivateScope);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003834 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003835 (void)PrivateScope.Privatize();
3836 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003837 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003838 };
Alexey Bataev2139ed62017-11-16 18:20:21 +00003839 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003840 emitPostUpdateForReductionClause(
3841 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev13314bf2014-10-09 04:18:56 +00003842}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003843
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003844static void emitTargetTeamsRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
3845 const OMPTargetTeamsDirective &S) {
3846 auto *CS = S.getCapturedStmt(OMPD_teams);
3847 Action.Enter(CGF);
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00003848 // Emit teams region as a standalone region.
3849 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) {
3850 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
3851 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3852 CGF.EmitOMPPrivateClause(S, PrivateScope);
3853 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
3854 (void)PrivateScope.Privatize();
3855 Action.Enter(CGF);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003856 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00003857 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003858 };
3859 emitCommonOMPTeamsDirective(CGF, S, OMPD_teams, CodeGen);
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00003860 emitPostUpdateForReductionClause(
3861 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003862}
3863
3864void CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
3865 CodeGenModule &CGM, StringRef ParentName,
3866 const OMPTargetTeamsDirective &S) {
3867 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3868 emitTargetTeamsRegion(CGF, Action, S);
3869 };
3870 llvm::Function *Fn;
3871 llvm::Constant *Addr;
3872 // Emit target region as a standalone region.
3873 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3874 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
3875 assert(Fn && Addr && "Target device function emission failed.");
3876}
3877
3878void CodeGenFunction::EmitOMPTargetTeamsDirective(
3879 const OMPTargetTeamsDirective &S) {
3880 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3881 emitTargetTeamsRegion(CGF, Action, S);
3882 };
3883 emitCommonOMPTargetDirective(*this, S, CodeGen);
3884}
3885
Alexey Bataevdfa430f2017-12-08 15:03:50 +00003886static void
3887emitTargetTeamsDistributeRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
3888 const OMPTargetTeamsDistributeDirective &S) {
3889 Action.Enter(CGF);
3890 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3891 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
3892 };
3893
3894 // Emit teams region as a standalone region.
3895 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
3896 PrePostActionTy &) {
3897 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
3898 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
3899 (void)PrivateScope.Privatize();
3900 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
3901 CodeGenDistribute);
3902 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
3903 };
3904 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute, CodeGen);
3905 emitPostUpdateForReductionClause(CGF, S,
3906 [](CodeGenFunction &) { return nullptr; });
3907}
3908
3909void CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
3910 CodeGenModule &CGM, StringRef ParentName,
3911 const OMPTargetTeamsDistributeDirective &S) {
3912 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3913 emitTargetTeamsDistributeRegion(CGF, Action, S);
3914 };
3915 llvm::Function *Fn;
3916 llvm::Constant *Addr;
3917 // Emit target region as a standalone region.
3918 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3919 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
3920 assert(Fn && Addr && "Target device function emission failed.");
3921}
3922
3923void CodeGenFunction::EmitOMPTargetTeamsDistributeDirective(
3924 const OMPTargetTeamsDistributeDirective &S) {
3925 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3926 emitTargetTeamsDistributeRegion(CGF, Action, S);
3927 };
3928 emitCommonOMPTargetDirective(*this, S, CodeGen);
3929}
3930
Carlo Bertolliba1487b2017-10-04 14:12:09 +00003931void CodeGenFunction::EmitOMPTeamsDistributeDirective(
3932 const OMPTeamsDistributeDirective &S) {
3933
3934 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3935 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
3936 };
3937
3938 // Emit teams region as a standalone region.
3939 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
3940 PrePostActionTy &) {
3941 OMPPrivateScope PrivateScope(CGF);
3942 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
3943 (void)PrivateScope.Privatize();
3944 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
3945 CodeGenDistribute);
3946 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
3947 };
Alexey Bataev95c6dd42017-11-29 15:14:16 +00003948 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
Carlo Bertolliba1487b2017-10-04 14:12:09 +00003949 emitPostUpdateForReductionClause(*this, S,
3950 [](CodeGenFunction &) { return nullptr; });
3951}
3952
Alexey Bataev999277a2017-12-06 14:31:09 +00003953void CodeGenFunction::EmitOMPTeamsDistributeSimdDirective(
3954 const OMPTeamsDistributeSimdDirective &S) {
3955 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3956 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
3957 };
3958
3959 // Emit teams region as a standalone region.
3960 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
3961 PrePostActionTy &) {
3962 OMPPrivateScope PrivateScope(CGF);
3963 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
3964 (void)PrivateScope.Privatize();
3965 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_simd,
3966 CodeGenDistribute);
3967 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
3968 };
3969 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_simd, CodeGen);
3970 emitPostUpdateForReductionClause(*this, S,
3971 [](CodeGenFunction &) { return nullptr; });
3972}
3973
Carlo Bertolli62fae152017-11-20 20:46:39 +00003974void CodeGenFunction::EmitOMPTeamsDistributeParallelForDirective(
3975 const OMPTeamsDistributeParallelForDirective &S) {
3976 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3977 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
3978 S.getDistInc());
3979 };
3980
3981 // Emit teams region as a standalone region.
3982 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
3983 PrePostActionTy &) {
3984 OMPPrivateScope PrivateScope(CGF);
3985 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
3986 (void)PrivateScope.Privatize();
Alexey Bataev10a54312017-11-27 16:54:08 +00003987 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
3988 CodeGenDistribute);
Carlo Bertolli62fae152017-11-20 20:46:39 +00003989 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
3990 };
3991 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
3992 emitPostUpdateForReductionClause(*this, S,
3993 [](CodeGenFunction &) { return nullptr; });
3994}
3995
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00003996void CodeGenFunction::EmitOMPTeamsDistributeParallelForSimdDirective(
3997 const OMPTeamsDistributeParallelForSimdDirective &S) {
3998 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3999 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4000 S.getDistInc());
4001 };
4002
4003 // Emit teams region as a standalone region.
4004 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4005 PrePostActionTy &) {
4006 OMPPrivateScope PrivateScope(CGF);
4007 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4008 (void)PrivateScope.Privatize();
4009 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4010 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4011 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4012 };
4013 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
4014 emitPostUpdateForReductionClause(*this, S,
4015 [](CodeGenFunction &) { return nullptr; });
4016}
4017
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004018void CodeGenFunction::EmitOMPCancellationPointDirective(
4019 const OMPCancellationPointDirective &S) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00004020 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getLocStart(),
4021 S.getCancelRegion());
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004022}
4023
Alexey Bataev80909872015-07-02 11:25:17 +00004024void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
Alexey Bataev87933c72015-09-18 08:07:34 +00004025 const Expr *IfCond = nullptr;
4026 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4027 if (C->getNameModifier() == OMPD_unknown ||
4028 C->getNameModifier() == OMPD_cancel) {
4029 IfCond = C->getCondition();
4030 break;
4031 }
4032 }
4033 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getLocStart(), IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004034 S.getCancelRegion());
Alexey Bataev80909872015-07-02 11:25:17 +00004035}
4036
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004037CodeGenFunction::JumpDest
4038CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
Alexey Bataev957d8562016-11-17 15:12:05 +00004039 if (Kind == OMPD_parallel || Kind == OMPD_task ||
4040 Kind == OMPD_target_parallel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004041 return ReturnBlock;
Alexey Bataev25e5b442015-09-15 12:52:43 +00004042 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
Alexey Bataev957d8562016-11-17 15:12:05 +00004043 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for ||
4044 Kind == OMPD_distribute_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00004045 Kind == OMPD_target_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00004046 Kind == OMPD_teams_distribute_parallel_for ||
4047 Kind == OMPD_target_teams_distribute_parallel_for);
Alexey Bataev957d8562016-11-17 15:12:05 +00004048 return OMPCancelStack.getExitBlock();
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004049}
Michael Wong65f367f2015-07-21 13:44:28 +00004050
Samuel Antaocc10b852016-07-28 14:23:26 +00004051void CodeGenFunction::EmitOMPUseDevicePtrClause(
4052 const OMPClause &NC, OMPPrivateScope &PrivateScope,
4053 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap) {
4054 const auto &C = cast<OMPUseDevicePtrClause>(NC);
4055 auto OrigVarIt = C.varlist_begin();
4056 auto InitIt = C.inits().begin();
4057 for (auto PvtVarIt : C.private_copies()) {
4058 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*OrigVarIt)->getDecl());
4059 auto *InitVD = cast<VarDecl>(cast<DeclRefExpr>(*InitIt)->getDecl());
4060 auto *PvtVD = cast<VarDecl>(cast<DeclRefExpr>(PvtVarIt)->getDecl());
4061
4062 // In order to identify the right initializer we need to match the
4063 // declaration used by the mapping logic. In some cases we may get
4064 // OMPCapturedExprDecl that refers to the original declaration.
4065 const ValueDecl *MatchingVD = OrigVD;
4066 if (auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) {
4067 // OMPCapturedExprDecl are used to privative fields of the current
4068 // structure.
4069 auto *ME = cast<MemberExpr>(OED->getInit());
4070 assert(isa<CXXThisExpr>(ME->getBase()) &&
4071 "Base should be the current struct!");
4072 MatchingVD = ME->getMemberDecl();
4073 }
4074
4075 // If we don't have information about the current list item, move on to
4076 // the next one.
4077 auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD);
4078 if (InitAddrIt == CaptureDeviceAddrMap.end())
4079 continue;
4080
4081 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
4082 // Initialize the temporary initialization variable with the address we
4083 // get from the runtime library. We have to cast the source address
4084 // because it is always a void *. References are materialized in the
4085 // privatization scope, so the initialization here disregards the fact
4086 // the original variable is a reference.
4087 QualType AddrQTy =
4088 getContext().getPointerType(OrigVD->getType().getNonReferenceType());
4089 llvm::Type *AddrTy = ConvertTypeForMem(AddrQTy);
4090 Address InitAddr = Builder.CreateBitCast(InitAddrIt->second, AddrTy);
4091 setAddrOfLocalVar(InitVD, InitAddr);
4092
4093 // Emit private declaration, it will be initialized by the value we
4094 // declaration we just added to the local declarations map.
4095 EmitDecl(*PvtVD);
4096
4097 // The initialization variables reached its purpose in the emission
4098 // ofthe previous declaration, so we don't need it anymore.
4099 LocalDeclMap.erase(InitVD);
4100
4101 // Return the address of the private variable.
4102 return GetAddrOfLocalVar(PvtVD);
4103 });
4104 assert(IsRegistered && "firstprivate var already registered as private");
4105 // Silence the warning about unused variable.
4106 (void)IsRegistered;
4107
4108 ++OrigVarIt;
4109 ++InitIt;
4110 }
4111}
4112
Michael Wong65f367f2015-07-21 13:44:28 +00004113// Generate the instructions for '#pragma omp target data' directive.
4114void CodeGenFunction::EmitOMPTargetDataDirective(
4115 const OMPTargetDataDirective &S) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004116 CGOpenMPRuntime::TargetDataInfo Info(/*RequiresDevicePointerInfo=*/true);
4117
4118 // Create a pre/post action to signal the privatization of the device pointer.
4119 // This action can be replaced by the OpenMP runtime code generation to
4120 // deactivate privatization.
4121 bool PrivatizeDevicePointers = false;
4122 class DevicePointerPrivActionTy : public PrePostActionTy {
4123 bool &PrivatizeDevicePointers;
4124
4125 public:
4126 explicit DevicePointerPrivActionTy(bool &PrivatizeDevicePointers)
4127 : PrePostActionTy(), PrivatizeDevicePointers(PrivatizeDevicePointers) {}
4128 void Enter(CodeGenFunction &CGF) override {
4129 PrivatizeDevicePointers = true;
4130 }
Samuel Antaodf158d52016-04-27 22:58:19 +00004131 };
Samuel Antaocc10b852016-07-28 14:23:26 +00004132 DevicePointerPrivActionTy PrivAction(PrivatizeDevicePointers);
4133
4134 auto &&CodeGen = [&S, &Info, &PrivatizeDevicePointers](
4135 CodeGenFunction &CGF, PrePostActionTy &Action) {
4136 auto &&InnermostCodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4137 CGF.EmitStmt(
4138 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
4139 };
4140
4141 // Codegen that selects wheather to generate the privatization code or not.
4142 auto &&PrivCodeGen = [&S, &Info, &PrivatizeDevicePointers,
4143 &InnermostCodeGen](CodeGenFunction &CGF,
4144 PrePostActionTy &Action) {
4145 RegionCodeGenTy RCG(InnermostCodeGen);
4146 PrivatizeDevicePointers = false;
4147
4148 // Call the pre-action to change the status of PrivatizeDevicePointers if
4149 // needed.
4150 Action.Enter(CGF);
4151
4152 if (PrivatizeDevicePointers) {
4153 OMPPrivateScope PrivateScope(CGF);
4154 // Emit all instances of the use_device_ptr clause.
4155 for (const auto *C : S.getClausesOfKind<OMPUseDevicePtrClause>())
4156 CGF.EmitOMPUseDevicePtrClause(*C, PrivateScope,
4157 Info.CaptureDeviceAddrMap);
4158 (void)PrivateScope.Privatize();
4159 RCG(CGF);
4160 } else
4161 RCG(CGF);
4162 };
4163
4164 // Forward the provided action to the privatization codegen.
4165 RegionCodeGenTy PrivRCG(PrivCodeGen);
4166 PrivRCG.setAction(Action);
4167
4168 // Notwithstanding the body of the region is emitted as inlined directive,
4169 // we don't use an inline scope as changes in the references inside the
4170 // region are expected to be visible outside, so we do not privative them.
4171 OMPLexicalScope Scope(CGF, S);
4172 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_target_data,
4173 PrivRCG);
4174 };
4175
4176 RegionCodeGenTy RCG(CodeGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00004177
4178 // If we don't have target devices, don't bother emitting the data mapping
4179 // code.
4180 if (CGM.getLangOpts().OMPTargetTriples.empty()) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004181 RCG(*this);
Samuel Antaodf158d52016-04-27 22:58:19 +00004182 return;
4183 }
4184
4185 // Check if we have any if clause associated with the directive.
4186 const Expr *IfCond = nullptr;
4187 if (auto *C = S.getSingleClause<OMPIfClause>())
4188 IfCond = C->getCondition();
4189
4190 // Check if we have any device clause associated with the directive.
4191 const Expr *Device = nullptr;
4192 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4193 Device = C->getDevice();
4194
Samuel Antaocc10b852016-07-28 14:23:26 +00004195 // Set the action to signal privatization of device pointers.
4196 RCG.setAction(PrivAction);
4197
4198 // Emit region code.
4199 CGM.getOpenMPRuntime().emitTargetDataCalls(*this, S, IfCond, Device, RCG,
4200 Info);
Michael Wong65f367f2015-07-21 13:44:28 +00004201}
Alexey Bataev49f6e782015-12-01 04:18:41 +00004202
Samuel Antaodf67fc42016-01-19 19:15:56 +00004203void CodeGenFunction::EmitOMPTargetEnterDataDirective(
4204 const OMPTargetEnterDataDirective &S) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00004205 // If we don't have target devices, don't bother emitting the data mapping
4206 // code.
4207 if (CGM.getLangOpts().OMPTargetTriples.empty())
4208 return;
4209
4210 // Check if we have any if clause associated with the directive.
4211 const Expr *IfCond = nullptr;
4212 if (auto *C = S.getSingleClause<OMPIfClause>())
4213 IfCond = C->getCondition();
4214
4215 // Check if we have any device clause associated with the directive.
4216 const Expr *Device = nullptr;
4217 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4218 Device = C->getDevice();
4219
Alexey Bataev7828b252017-11-21 17:08:48 +00004220 auto &&CodeGen = [&S, IfCond, Device](CodeGenFunction &CGF,
4221 PrePostActionTy &) {
4222 CGF.CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(CGF, S, IfCond,
4223 Device);
4224 };
4225 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
4226 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_target_enter_data,
4227 CodeGen);
Samuel Antaodf67fc42016-01-19 19:15:56 +00004228}
4229
Samuel Antao72590762016-01-19 20:04:50 +00004230void CodeGenFunction::EmitOMPTargetExitDataDirective(
4231 const OMPTargetExitDataDirective &S) {
Samuel Antao8dd66282016-04-27 23:14:30 +00004232 // If we don't have target devices, don't bother emitting the data mapping
4233 // code.
4234 if (CGM.getLangOpts().OMPTargetTriples.empty())
4235 return;
4236
4237 // Check if we have any if clause associated with the directive.
4238 const Expr *IfCond = nullptr;
4239 if (auto *C = S.getSingleClause<OMPIfClause>())
4240 IfCond = C->getCondition();
4241
4242 // Check if we have any device clause associated with the directive.
4243 const Expr *Device = nullptr;
4244 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4245 Device = C->getDevice();
4246
Alexey Bataev7828b252017-11-21 17:08:48 +00004247 auto &&CodeGen = [&S, IfCond, Device](CodeGenFunction &CGF,
4248 PrePostActionTy &) {
4249 CGF.CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(CGF, S, IfCond,
4250 Device);
4251 };
4252 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
4253 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_target_exit_data,
4254 CodeGen);
Samuel Antao72590762016-01-19 20:04:50 +00004255}
4256
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004257static void emitTargetParallelRegion(CodeGenFunction &CGF,
4258 const OMPTargetParallelDirective &S,
4259 PrePostActionTy &Action) {
4260 // Get the captured statement associated with the 'parallel' region.
4261 auto *CS = S.getCapturedStmt(OMPD_parallel);
4262 Action.Enter(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004263 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &) {
4264 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4265 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4266 CGF.EmitOMPPrivateClause(S, PrivateScope);
4267 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4268 (void)PrivateScope.Privatize();
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004269 // TODO: Add support for clauses.
4270 CGF.EmitStmt(CS->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004271 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004272 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00004273 emitCommonOMPParallelDirective(CGF, S, OMPD_parallel, CodeGen,
4274 emitEmptyBoundParameters);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004275 emitPostUpdateForReductionClause(
4276 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004277}
4278
4279void CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
4280 CodeGenModule &CGM, StringRef ParentName,
4281 const OMPTargetParallelDirective &S) {
4282 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4283 emitTargetParallelRegion(CGF, S, Action);
4284 };
4285 llvm::Function *Fn;
4286 llvm::Constant *Addr;
4287 // Emit target region as a standalone region.
4288 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4289 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4290 assert(Fn && Addr && "Target device function emission failed.");
4291}
4292
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004293void CodeGenFunction::EmitOMPTargetParallelDirective(
4294 const OMPTargetParallelDirective &S) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004295 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4296 emitTargetParallelRegion(CGF, S, Action);
4297 };
4298 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004299}
4300
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004301static void emitTargetParallelForRegion(CodeGenFunction &CGF,
4302 const OMPTargetParallelForDirective &S,
4303 PrePostActionTy &Action) {
4304 Action.Enter(CGF);
4305 // Emit directive as a combined directive that consists of two implicit
4306 // directives: 'parallel' with 'for' directive.
4307 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev2139ed62017-11-16 18:20:21 +00004308 CodeGenFunction::OMPCancelStackRAII CancelRegion(
4309 CGF, OMPD_target_parallel_for, S.hasCancel());
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004310 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
4311 emitDispatchForLoopBounds);
4312 };
4313 emitCommonOMPParallelDirective(CGF, S, OMPD_for, CodeGen,
4314 emitEmptyBoundParameters);
4315}
4316
4317void CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
4318 CodeGenModule &CGM, StringRef ParentName,
4319 const OMPTargetParallelForDirective &S) {
4320 // Emit SPMD target parallel for region as a standalone region.
4321 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4322 emitTargetParallelForRegion(CGF, S, Action);
4323 };
4324 llvm::Function *Fn;
4325 llvm::Constant *Addr;
4326 // Emit target region as a standalone region.
4327 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4328 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4329 assert(Fn && Addr && "Target device function emission failed.");
4330}
4331
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004332void CodeGenFunction::EmitOMPTargetParallelForDirective(
4333 const OMPTargetParallelForDirective &S) {
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004334 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4335 emitTargetParallelForRegion(CGF, S, Action);
4336 };
4337 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004338}
4339
Alexey Bataev5d7edca2017-11-09 17:32:15 +00004340static void
4341emitTargetParallelForSimdRegion(CodeGenFunction &CGF,
4342 const OMPTargetParallelForSimdDirective &S,
4343 PrePostActionTy &Action) {
4344 Action.Enter(CGF);
4345 // Emit directive as a combined directive that consists of two implicit
4346 // directives: 'parallel' with 'for' directive.
4347 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4348 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
4349 emitDispatchForLoopBounds);
4350 };
4351 emitCommonOMPParallelDirective(CGF, S, OMPD_simd, CodeGen,
4352 emitEmptyBoundParameters);
4353}
4354
4355void CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
4356 CodeGenModule &CGM, StringRef ParentName,
4357 const OMPTargetParallelForSimdDirective &S) {
4358 // Emit SPMD target parallel for region as a standalone region.
4359 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4360 emitTargetParallelForSimdRegion(CGF, S, Action);
4361 };
4362 llvm::Function *Fn;
4363 llvm::Constant *Addr;
4364 // Emit target region as a standalone region.
4365 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4366 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4367 assert(Fn && Addr && "Target device function emission failed.");
4368}
4369
4370void CodeGenFunction::EmitOMPTargetParallelForSimdDirective(
4371 const OMPTargetParallelForSimdDirective &S) {
4372 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4373 emitTargetParallelForSimdRegion(CGF, S, Action);
4374 };
4375 emitCommonOMPTargetDirective(*this, S, CodeGen);
4376}
4377
Alexey Bataev7292c292016-04-25 12:22:29 +00004378/// Emit a helper variable and return corresponding lvalue.
4379static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper,
4380 const ImplicitParamDecl *PVD,
4381 CodeGenFunction::OMPPrivateScope &Privates) {
4382 auto *VDecl = cast<VarDecl>(Helper->getDecl());
4383 Privates.addPrivate(
4384 VDecl, [&CGF, PVD]() -> Address { return CGF.GetAddrOfLocalVar(PVD); });
4385}
4386
4387void CodeGenFunction::EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S) {
4388 assert(isOpenMPTaskLoopDirective(S.getDirectiveKind()));
4389 // Emit outlined function for task construct.
4390 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
4391 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
4392 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
4393 const Expr *IfCond = nullptr;
4394 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4395 if (C->getNameModifier() == OMPD_unknown ||
4396 C->getNameModifier() == OMPD_taskloop) {
4397 IfCond = C->getCondition();
4398 break;
4399 }
4400 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004401
4402 OMPTaskDataTy Data;
4403 // Check if taskloop must be emitted without taskgroup.
4404 Data.Nogroup = S.getSingleClause<OMPNogroupClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00004405 // TODO: Check if we should emit tied or untied task.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004406 Data.Tied = true;
4407 // Set scheduling for taskloop
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004408 if (const auto* Clause = S.getSingleClause<OMPGrainsizeClause>()) {
4409 // grainsize clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004410 Data.Schedule.setInt(/*IntVal=*/false);
4411 Data.Schedule.setPointer(EmitScalarExpr(Clause->getGrainsize()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004412 } else if (const auto* Clause = S.getSingleClause<OMPNumTasksClause>()) {
4413 // num_tasks clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004414 Data.Schedule.setInt(/*IntVal=*/true);
4415 Data.Schedule.setPointer(EmitScalarExpr(Clause->getNumTasks()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004416 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004417
4418 auto &&BodyGen = [CS, &S](CodeGenFunction &CGF, PrePostActionTy &) {
4419 // if (PreCond) {
4420 // for (IV in 0..LastIteration) BODY;
4421 // <Final counter/linear vars updates>;
4422 // }
4423 //
4424
4425 // Emit: if (PreCond) - begin.
4426 // If the condition constant folds and can be elided, avoid emitting the
4427 // whole loop.
4428 bool CondConstant;
4429 llvm::BasicBlock *ContBlock = nullptr;
4430 OMPLoopScope PreInitScope(CGF, S);
4431 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
4432 if (!CondConstant)
4433 return;
4434 } else {
4435 auto *ThenBlock = CGF.createBasicBlock("taskloop.if.then");
4436 ContBlock = CGF.createBasicBlock("taskloop.if.end");
4437 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
4438 CGF.getProfileCount(&S));
4439 CGF.EmitBlock(ThenBlock);
4440 CGF.incrementProfileCounter(&S);
4441 }
4442
Alexey Bataev1e73ef32016-04-28 12:14:51 +00004443 if (isOpenMPSimdDirective(S.getDirectiveKind()))
4444 CGF.EmitOMPSimdInit(S);
4445
Alexey Bataev7292c292016-04-25 12:22:29 +00004446 OMPPrivateScope LoopScope(CGF);
4447 // Emit helper vars inits.
4448 enum { LowerBound = 5, UpperBound, Stride, LastIter };
4449 auto *I = CS->getCapturedDecl()->param_begin();
4450 auto *LBP = std::next(I, LowerBound);
4451 auto *UBP = std::next(I, UpperBound);
4452 auto *STP = std::next(I, Stride);
4453 auto *LIP = std::next(I, LastIter);
4454 mapParam(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()), *LBP,
4455 LoopScope);
4456 mapParam(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()), *UBP,
4457 LoopScope);
4458 mapParam(CGF, cast<DeclRefExpr>(S.getStrideVariable()), *STP, LoopScope);
4459 mapParam(CGF, cast<DeclRefExpr>(S.getIsLastIterVariable()), *LIP,
4460 LoopScope);
4461 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004462 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7292c292016-04-25 12:22:29 +00004463 (void)LoopScope.Privatize();
4464 // Emit the loop iteration variable.
4465 const Expr *IVExpr = S.getIterationVariable();
4466 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
4467 CGF.EmitVarDecl(*IVDecl);
4468 CGF.EmitIgnoredExpr(S.getInit());
4469
4470 // Emit the iterations count variable.
4471 // If it is not a variable, Sema decided to calculate iterations count on
4472 // each iteration (e.g., it is foldable into a constant).
4473 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
4474 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
4475 // Emit calculation of the iterations count.
4476 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
4477 }
4478
4479 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
4480 S.getInc(),
4481 [&S](CodeGenFunction &CGF) {
4482 CGF.EmitOMPLoopBody(S, JumpDest());
4483 CGF.EmitStopPoint(&S);
4484 },
4485 [](CodeGenFunction &) {});
4486 // Emit: if (PreCond) - end.
4487 if (ContBlock) {
4488 CGF.EmitBranch(ContBlock);
4489 CGF.EmitBlock(ContBlock, true);
4490 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004491 // Emit final copy of the lastprivate variables if IsLastIter != 0.
4492 if (HasLastprivateClause) {
4493 CGF.EmitOMPLastprivateClauseFinal(
4494 S, isOpenMPSimdDirective(S.getDirectiveKind()),
4495 CGF.Builder.CreateIsNotNull(CGF.EmitLoadOfScalar(
4496 CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
4497 (*LIP)->getType(), S.getLocStart())));
4498 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004499 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004500 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
4501 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
4502 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004503 auto &&CodeGen = [&](CodeGenFunction &CGF, PrePostActionTy &) {
4504 OMPLoopScope PreInitScope(CGF, S);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004505 CGF.CGM.getOpenMPRuntime().emitTaskLoopCall(CGF, S.getLocStart(), S,
4506 OutlinedFn, SharedsTy,
4507 CapturedStruct, IfCond, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00004508 };
4509 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_taskloop,
4510 CodeGen);
4511 };
Alexey Bataev33446032017-07-12 18:09:32 +00004512 if (Data.Nogroup)
4513 EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
4514 else {
4515 CGM.getOpenMPRuntime().emitTaskgroupRegion(
4516 *this,
4517 [&S, &BodyGen, &TaskGen, &Data](CodeGenFunction &CGF,
4518 PrePostActionTy &Action) {
4519 Action.Enter(CGF);
4520 CGF.EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
4521 },
4522 S.getLocStart());
4523 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004524}
4525
Alexey Bataev49f6e782015-12-01 04:18:41 +00004526void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004527 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev49f6e782015-12-01 04:18:41 +00004528}
4529
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004530void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
4531 const OMPTaskLoopSimdDirective &S) {
Alexey Bataev1e73ef32016-04-28 12:14:51 +00004532 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004533}
Samuel Antao686c70c2016-05-26 17:30:50 +00004534
4535// Generate the instructions for '#pragma omp target update' directive.
4536void CodeGenFunction::EmitOMPTargetUpdateDirective(
4537 const OMPTargetUpdateDirective &S) {
Samuel Antao8d2d7302016-05-26 18:30:22 +00004538 // If we don't have target devices, don't bother emitting the data mapping
4539 // code.
4540 if (CGM.getLangOpts().OMPTargetTriples.empty())
4541 return;
4542
4543 // Check if we have any if clause associated with the directive.
4544 const Expr *IfCond = nullptr;
4545 if (auto *C = S.getSingleClause<OMPIfClause>())
4546 IfCond = C->getCondition();
4547
4548 // Check if we have any device clause associated with the directive.
4549 const Expr *Device = nullptr;
4550 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4551 Device = C->getDevice();
4552
Alexey Bataev7828b252017-11-21 17:08:48 +00004553 auto &&CodeGen = [&S, IfCond, Device](CodeGenFunction &CGF,
4554 PrePostActionTy &) {
4555 CGF.CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(CGF, S, IfCond,
4556 Device);
4557 };
4558 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
4559 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_target_update,
4560 CodeGen);
Samuel Antao686c70c2016-05-26 17:30:50 +00004561}