blob: b4ba6e385b1ee468077c8d13df49a1277d9bf541 [file] [log] [blame]
Richard Smithcfd53b42015-10-22 06:13:50 +00001//===--- SemaCoroutines.cpp - Semantic Analysis for Coroutines ------------===//
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 file implements semantic analysis for C++ Coroutines.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Sema/SemaInternal.h"
Richard Smith9f690bd2015-10-27 06:02:45 +000015#include "clang/AST/Decl.h"
16#include "clang/AST/ExprCXX.h"
17#include "clang/AST/StmtCXX.h"
18#include "clang/Lex/Preprocessor.h"
19#include "clang/Sema/Overload.h"
Richard Smithcfd53b42015-10-22 06:13:50 +000020using namespace clang;
21using namespace sema;
22
Richard Smith9f690bd2015-10-27 06:02:45 +000023/// Look up the std::coroutine_traits<...>::promise_type for the given
24/// function type.
25static QualType lookupPromiseType(Sema &S, const FunctionProtoType *FnType,
26 SourceLocation Loc) {
27 // FIXME: Cache std::coroutine_traits once we've found it.
28 NamespaceDecl *Std = S.getStdNamespace();
29 if (!Std) {
30 S.Diag(Loc, diag::err_implied_std_coroutine_traits_not_found);
31 return QualType();
32 }
33
34 LookupResult Result(S, &S.PP.getIdentifierTable().get("coroutine_traits"),
35 Loc, Sema::LookupOrdinaryName);
36 if (!S.LookupQualifiedName(Result, Std)) {
37 S.Diag(Loc, diag::err_implied_std_coroutine_traits_not_found);
38 return QualType();
39 }
40
41 ClassTemplateDecl *CoroTraits = Result.getAsSingle<ClassTemplateDecl>();
42 if (!CoroTraits) {
43 Result.suppressDiagnostics();
44 // We found something weird. Complain about the first thing we found.
45 NamedDecl *Found = *Result.begin();
46 S.Diag(Found->getLocation(), diag::err_malformed_std_coroutine_traits);
47 return QualType();
48 }
49
50 // Form template argument list for coroutine_traits<R, P1, P2, ...>.
51 TemplateArgumentListInfo Args(Loc, Loc);
52 Args.addArgument(TemplateArgumentLoc(
53 TemplateArgument(FnType->getReturnType()),
54 S.Context.getTrivialTypeSourceInfo(FnType->getReturnType(), Loc)));
55 for (QualType T : FnType->getParamTypes())
56 Args.addArgument(TemplateArgumentLoc(
57 TemplateArgument(T), S.Context.getTrivialTypeSourceInfo(T, Loc)));
58
59 // Build the template-id.
60 QualType CoroTrait =
61 S.CheckTemplateIdType(TemplateName(CoroTraits), Loc, Args);
62 if (CoroTrait.isNull())
63 return QualType();
64 if (S.RequireCompleteType(Loc, CoroTrait,
65 diag::err_coroutine_traits_missing_specialization))
66 return QualType();
67
68 CXXRecordDecl *RD = CoroTrait->getAsCXXRecordDecl();
69 assert(RD && "specialization of class template is not a class?");
70
71 // Look up the ::promise_type member.
72 LookupResult R(S, &S.PP.getIdentifierTable().get("promise_type"), Loc,
73 Sema::LookupOrdinaryName);
74 S.LookupQualifiedName(R, RD);
75 auto *Promise = R.getAsSingle<TypeDecl>();
76 if (!Promise) {
77 S.Diag(Loc, diag::err_implied_std_coroutine_traits_promise_type_not_found)
78 << RD;
79 return QualType();
80 }
81
82 // The promise type is required to be a class type.
83 QualType PromiseType = S.Context.getTypeDeclType(Promise);
84 if (!PromiseType->getAsCXXRecordDecl()) {
Richard Smith9b2f53e2015-11-19 02:36:35 +000085 // Use the fully-qualified name of the type.
86 auto *NNS = NestedNameSpecifier::Create(S.Context, nullptr, Std);
87 NNS = NestedNameSpecifier::Create(S.Context, NNS, false,
88 CoroTrait.getTypePtr());
89 PromiseType = S.Context.getElaboratedType(ETK_None, NNS, PromiseType);
90
Richard Smith9f690bd2015-10-27 06:02:45 +000091 S.Diag(Loc, diag::err_implied_std_coroutine_traits_promise_type_not_class)
92 << PromiseType;
93 return QualType();
94 }
95
96 return PromiseType;
97}
98
99/// Check that this is a context in which a coroutine suspension can appear.
Richard Smithcfd53b42015-10-22 06:13:50 +0000100static FunctionScopeInfo *
101checkCoroutineContext(Sema &S, SourceLocation Loc, StringRef Keyword) {
Richard Smith744b2242015-11-20 02:54:01 +0000102 // 'co_await' and 'co_yield' are not permitted in unevaluated operands.
103 if (S.isUnevaluatedContext()) {
104 S.Diag(Loc, diag::err_coroutine_unevaluated_context) << Keyword;
Richard Smithcfd53b42015-10-22 06:13:50 +0000105 return nullptr;
Richard Smith744b2242015-11-20 02:54:01 +0000106 }
Richard Smithcfd53b42015-10-22 06:13:50 +0000107
108 // Any other usage must be within a function.
109 auto *FD = dyn_cast<FunctionDecl>(S.CurContext);
110 if (!FD) {
111 S.Diag(Loc, isa<ObjCMethodDecl>(S.CurContext)
112 ? diag::err_coroutine_objc_method
113 : diag::err_coroutine_outside_function) << Keyword;
114 } else if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD)) {
115 // Coroutines TS [special]/6:
116 // A special member function shall not be a coroutine.
117 //
118 // FIXME: We assume that this really means that a coroutine cannot
119 // be a constructor or destructor.
120 S.Diag(Loc, diag::err_coroutine_ctor_dtor)
121 << isa<CXXDestructorDecl>(FD) << Keyword;
122 } else if (FD->isConstexpr()) {
123 S.Diag(Loc, diag::err_coroutine_constexpr) << Keyword;
124 } else if (FD->isVariadic()) {
125 S.Diag(Loc, diag::err_coroutine_varargs) << Keyword;
126 } else {
127 auto *ScopeInfo = S.getCurFunction();
128 assert(ScopeInfo && "missing function scope for function");
Richard Smith9f690bd2015-10-27 06:02:45 +0000129
130 // If we don't have a promise variable, build one now.
131 if (!ScopeInfo->CoroutinePromise && !FD->getType()->isDependentType()) {
132 QualType T =
133 lookupPromiseType(S, FD->getType()->castAs<FunctionProtoType>(), Loc);
134 if (T.isNull())
135 return nullptr;
136
137 // Create and default-initialize the promise.
138 ScopeInfo->CoroutinePromise =
139 VarDecl::Create(S.Context, FD, FD->getLocation(), FD->getLocation(),
140 &S.PP.getIdentifierTable().get("__promise"), T,
141 S.Context.getTrivialTypeSourceInfo(T, Loc), SC_None);
142 S.CheckVariableDeclarationType(ScopeInfo->CoroutinePromise);
143 if (!ScopeInfo->CoroutinePromise->isInvalidDecl())
144 S.ActOnUninitializedDecl(ScopeInfo->CoroutinePromise, false);
145 }
146
Richard Smithcfd53b42015-10-22 06:13:50 +0000147 return ScopeInfo;
148 }
149
150 return nullptr;
151}
152
Richard Smith9f690bd2015-10-27 06:02:45 +0000153/// Build a call to 'operator co_await' if there is a suitable operator for
154/// the given expression.
155static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, Scope *S,
156 SourceLocation Loc, Expr *E) {
157 UnresolvedSet<16> Functions;
158 SemaRef.LookupOverloadedOperatorName(OO_Coawait, S, E->getType(), QualType(),
159 Functions);
160 return SemaRef.CreateOverloadedUnaryOp(Loc, UO_Coawait, Functions, E);
161}
Richard Smithcfd53b42015-10-22 06:13:50 +0000162
Richard Smith9f690bd2015-10-27 06:02:45 +0000163struct ReadySuspendResumeResult {
164 bool IsInvalid;
165 Expr *Results[3];
166};
167
168/// Build calls to await_ready, await_suspend, and await_resume for a co_await
169/// expression.
170static ReadySuspendResumeResult buildCoawaitCalls(Sema &S, SourceLocation Loc,
171 Expr *E) {
172 // Assume invalid until we see otherwise.
173 ReadySuspendResumeResult Calls = {true, {}};
174
175 const StringRef Funcs[] = {"await_ready", "await_suspend", "await_resume"};
176 for (size_t I = 0, N = llvm::array_lengthof(Funcs); I != N; ++I) {
177 DeclarationNameInfo NameInfo(&S.PP.getIdentifierTable().get(Funcs[I]), Loc);
178
179 Expr *Operand = new (S.Context) OpaqueValueExpr(
180 Loc, E->getType(), E->getValueKind(), E->getObjectKind(), E);
181
182 // FIXME: Fix BuildMemberReferenceExpr to take a const CXXScopeSpec&.
183 CXXScopeSpec SS;
184 ExprResult Result = S.BuildMemberReferenceExpr(
185 Operand, Operand->getType(), Loc, /*IsPtr=*/false, SS,
186 SourceLocation(), nullptr, NameInfo, /*TemplateArgs=*/nullptr,
187 /*Scope=*/nullptr);
188 if (Result.isInvalid())
189 return Calls;
190
191 // FIXME: Pass coroutine handle to await_suspend.
192 Result = S.ActOnCallExpr(nullptr, Result.get(), Loc, None, Loc, nullptr);
193 if (Result.isInvalid())
194 return Calls;
195 Calls.Results[I] = Result.get();
196 }
197
198 Calls.IsInvalid = false;
199 return Calls;
200}
201
202ExprResult Sema::ActOnCoawaitExpr(Scope *S, SourceLocation Loc, Expr *E) {
203 ExprResult Awaitable = buildOperatorCoawaitCall(*this, S, Loc, E);
204 if (Awaitable.isInvalid())
205 return ExprError();
206 return BuildCoawaitExpr(Loc, Awaitable.get());
207}
208ExprResult Sema::BuildCoawaitExpr(SourceLocation Loc, Expr *E) {
209 auto *Coroutine = checkCoroutineContext(*this, Loc, "co_await");
Richard Smith744b2242015-11-20 02:54:01 +0000210 if (!Coroutine)
211 return ExprError();
Richard Smith9f690bd2015-10-27 06:02:45 +0000212
213 if (E->getType()->isDependentType()) {
214 Expr *Res = new (Context) CoawaitExpr(Loc, Context.DependentTy, E);
Richard Smith744b2242015-11-20 02:54:01 +0000215 Coroutine->CoroutineStmts.push_back(Res);
Richard Smith9f690bd2015-10-27 06:02:45 +0000216 return Res;
217 }
218
219 if (E->getType()->isPlaceholderType()) {
220 ExprResult R = CheckPlaceholderExpr(E);
221 if (R.isInvalid()) return ExprError();
222 E = R.get();
223 }
224
225 // FIXME: If E is a prvalue, create a temporary.
226 // FIXME: If E is an xvalue, convert to lvalue.
227
228 // Build the await_ready, await_suspend, await_resume calls.
229 ReadySuspendResumeResult RSS = buildCoawaitCalls(*this, Loc, E);
230 if (RSS.IsInvalid)
231 return ExprError();
232
233 Expr *Res = new (Context) CoawaitExpr(Loc, E, RSS.Results[0], RSS.Results[1],
234 RSS.Results[2]);
Richard Smith744b2242015-11-20 02:54:01 +0000235 Coroutine->CoroutineStmts.push_back(Res);
Richard Smithcfd53b42015-10-22 06:13:50 +0000236 return Res;
237}
238
Richard Smith9f690bd2015-10-27 06:02:45 +0000239ExprResult Sema::ActOnCoyieldExpr(Scope *S, SourceLocation Loc, Expr *E) {
240 // FIXME: Build yield_value call.
241 ExprResult Awaitable = buildOperatorCoawaitCall(*this, S, Loc, E);
242 if (Awaitable.isInvalid())
243 return ExprError();
244 return BuildCoyieldExpr(Loc, Awaitable.get());
245}
246ExprResult Sema::BuildCoyieldExpr(SourceLocation Loc, Expr *E) {
247 auto *Coroutine = checkCoroutineContext(*this, Loc, "co_yield");
Richard Smith744b2242015-11-20 02:54:01 +0000248 if (!Coroutine)
249 return ExprError();
Richard Smithcfd53b42015-10-22 06:13:50 +0000250
Richard Smith9f690bd2015-10-27 06:02:45 +0000251 // FIXME: Build await_* calls.
252 Expr *Res = new (Context) CoyieldExpr(Loc, Context.VoidTy, E);
Richard Smith744b2242015-11-20 02:54:01 +0000253 Coroutine->CoroutineStmts.push_back(Res);
Richard Smithcfd53b42015-10-22 06:13:50 +0000254 return Res;
255}
256
257StmtResult Sema::ActOnCoreturnStmt(SourceLocation Loc, Expr *E) {
Richard Smith9f690bd2015-10-27 06:02:45 +0000258 return BuildCoreturnStmt(Loc, E);
259}
260StmtResult Sema::BuildCoreturnStmt(SourceLocation Loc, Expr *E) {
261 auto *Coroutine = checkCoroutineContext(*this, Loc, "co_return");
Richard Smith744b2242015-11-20 02:54:01 +0000262 if (!Coroutine)
263 return StmtError();
Richard Smithcfd53b42015-10-22 06:13:50 +0000264
Richard Smith9f690bd2015-10-27 06:02:45 +0000265 // FIXME: Build return_* calls.
266 Stmt *Res = new (Context) CoreturnStmt(Loc, E);
Richard Smith744b2242015-11-20 02:54:01 +0000267 Coroutine->CoroutineStmts.push_back(Res);
Richard Smithcfd53b42015-10-22 06:13:50 +0000268 return Res;
269}
270
271void Sema::CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *Body) {
272 FunctionScopeInfo *Fn = getCurFunction();
273 assert(Fn && !Fn->CoroutineStmts.empty() && "not a coroutine");
274
275 // Coroutines [stmt.return]p1:
276 // A return statement shall not appear in a coroutine.
Richard Smith9f690bd2015-10-27 06:02:45 +0000277 if (Fn->FirstReturnLoc.isValid()) {
278 Diag(Fn->FirstReturnLoc, diag::err_return_in_coroutine);
Richard Smithcfd53b42015-10-22 06:13:50 +0000279 auto *First = Fn->CoroutineStmts[0];
280 Diag(First->getLocStart(), diag::note_declared_coroutine_here)
Richard Smith9f690bd2015-10-27 06:02:45 +0000281 << (isa<CoawaitExpr>(First) ? 0 :
282 isa<CoyieldExpr>(First) ? 1 : 2);
Richard Smithcfd53b42015-10-22 06:13:50 +0000283 }
284
285 bool AnyCoawaits = false;
286 bool AnyCoyields = false;
287 for (auto *CoroutineStmt : Fn->CoroutineStmts) {
Richard Smith9f690bd2015-10-27 06:02:45 +0000288 AnyCoawaits |= isa<CoawaitExpr>(CoroutineStmt);
289 AnyCoyields |= isa<CoyieldExpr>(CoroutineStmt);
Richard Smithcfd53b42015-10-22 06:13:50 +0000290 }
291
292 if (!AnyCoawaits && !AnyCoyields)
293 Diag(Fn->CoroutineStmts.front()->getLocStart(),
Richard Smith9f690bd2015-10-27 06:02:45 +0000294 diag::ext_coroutine_without_co_await_co_yield);
Richard Smithcfd53b42015-10-22 06:13:50 +0000295
Richard Smith9f690bd2015-10-27 06:02:45 +0000296 // FIXME: Perform analysis of initial and final suspend,
297 // and set_exception call.
Richard Smithcfd53b42015-10-22 06:13:50 +0000298}