blob: 658bdcbafcc48181f3a09b5a19d6e8b880d48e41 [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//
Brian Gesiakc1b173a2018-06-23 18:01:02 +000012// This file contains references to sections of the Coroutines TS, which
13// can be found at http://wg21.link/coroutines.
14//
Richard Smithcfd53b42015-10-22 06:13:50 +000015//===----------------------------------------------------------------------===//
16
Eric Fiselierbee782b2017-04-03 19:21:00 +000017#include "CoroutineStmtBuilder.h"
Brian Gesiak98606222018-02-15 20:37:22 +000018#include "clang/AST/ASTLambda.h"
Richard Smith9f690bd2015-10-27 06:02:45 +000019#include "clang/AST/Decl.h"
20#include "clang/AST/ExprCXX.h"
21#include "clang/AST/StmtCXX.h"
22#include "clang/Lex/Preprocessor.h"
Richard Smith2af65c42015-11-24 02:34:39 +000023#include "clang/Sema/Initialization.h"
Richard Smith9f690bd2015-10-27 06:02:45 +000024#include "clang/Sema/Overload.h"
Reid Kleckner04f9bca2018-03-07 22:48:35 +000025#include "clang/Sema/ScopeInfo.h"
Eric Fiselierbee782b2017-04-03 19:21:00 +000026#include "clang/Sema/SemaInternal.h"
27
Richard Smithcfd53b42015-10-22 06:13:50 +000028using namespace clang;
29using namespace sema;
30
Eric Fiselierfc50f622017-05-25 14:59:39 +000031static LookupResult lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD,
32 SourceLocation Loc, bool &Res) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +000033 DeclarationName DN = S.PP.getIdentifierInfo(Name);
34 LookupResult LR(S, DN, Loc, Sema::LookupMemberName);
35 // Suppress diagnostics when a private member is selected. The same warnings
36 // will be produced again when building the call.
37 LR.suppressDiagnostics();
Eric Fiselierfc50f622017-05-25 14:59:39 +000038 Res = S.LookupQualifiedName(LR, RD);
39 return LR;
40}
41
42static bool lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD,
43 SourceLocation Loc) {
44 bool Res;
45 lookupMember(S, Name, RD, Loc, Res);
46 return Res;
Eric Fiselier20f25cb2017-03-06 23:38:15 +000047}
48
Richard Smith9f690bd2015-10-27 06:02:45 +000049/// Look up the std::coroutine_traits<...>::promise_type for the given
50/// function type.
Eric Fiselier166c6e62017-07-10 01:27:22 +000051static QualType lookupPromiseType(Sema &S, const FunctionDecl *FD,
52 SourceLocation KwLoc) {
53 const FunctionProtoType *FnType = FD->getType()->castAs<FunctionProtoType>();
54 const SourceLocation FuncLoc = FD->getLocation();
Richard Smith9f690bd2015-10-27 06:02:45 +000055 // FIXME: Cache std::coroutine_traits once we've found it.
Gor Nishanov3e048bb2016-10-04 00:31:16 +000056 NamespaceDecl *StdExp = S.lookupStdExperimentalNamespace();
57 if (!StdExp) {
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +000058 S.Diag(KwLoc, diag::err_implied_coroutine_type_not_found)
59 << "std::experimental::coroutine_traits";
Richard Smith9f690bd2015-10-27 06:02:45 +000060 return QualType();
61 }
62
63 LookupResult Result(S, &S.PP.getIdentifierTable().get("coroutine_traits"),
Eric Fiselier89bf0e72017-03-06 22:52:28 +000064 FuncLoc, Sema::LookupOrdinaryName);
Gor Nishanov3e048bb2016-10-04 00:31:16 +000065 if (!S.LookupQualifiedName(Result, StdExp)) {
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +000066 S.Diag(KwLoc, diag::err_implied_coroutine_type_not_found)
67 << "std::experimental::coroutine_traits";
Richard Smith9f690bd2015-10-27 06:02:45 +000068 return QualType();
69 }
70
71 ClassTemplateDecl *CoroTraits = Result.getAsSingle<ClassTemplateDecl>();
72 if (!CoroTraits) {
73 Result.suppressDiagnostics();
74 // We found something weird. Complain about the first thing we found.
75 NamedDecl *Found = *Result.begin();
76 S.Diag(Found->getLocation(), diag::err_malformed_std_coroutine_traits);
77 return QualType();
78 }
79
Eric Fiselier166c6e62017-07-10 01:27:22 +000080 // Form template argument list for coroutine_traits<R, P1, P2, ...> according
81 // to [dcl.fct.def.coroutine]3
Eric Fiselier89bf0e72017-03-06 22:52:28 +000082 TemplateArgumentListInfo Args(KwLoc, KwLoc);
Eric Fiselier166c6e62017-07-10 01:27:22 +000083 auto AddArg = [&](QualType T) {
Richard Smith9f690bd2015-10-27 06:02:45 +000084 Args.addArgument(TemplateArgumentLoc(
Eric Fiselier89bf0e72017-03-06 22:52:28 +000085 TemplateArgument(T), S.Context.getTrivialTypeSourceInfo(T, KwLoc)));
Eric Fiselier166c6e62017-07-10 01:27:22 +000086 };
87 AddArg(FnType->getReturnType());
88 // If the function is a non-static member function, add the type
89 // of the implicit object parameter before the formal parameters.
90 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
91 if (MD->isInstance()) {
92 // [over.match.funcs]4
93 // For non-static member functions, the type of the implicit object
94 // parameter is
Eric Fiselierbf166ce2017-07-10 02:52:34 +000095 // -- "lvalue reference to cv X" for functions declared without a
96 // ref-qualifier or with the & ref-qualifier
97 // -- "rvalue reference to cv X" for functions declared with the &&
98 // ref-qualifier
Eric Fiselier166c6e62017-07-10 01:27:22 +000099 QualType T =
100 MD->getThisType(S.Context)->getAs<PointerType>()->getPointeeType();
101 T = FnType->getRefQualifier() == RQ_RValue
102 ? S.Context.getRValueReferenceType(T)
103 : S.Context.getLValueReferenceType(T, /*SpelledAsLValue*/ true);
104 AddArg(T);
105 }
106 }
107 for (QualType T : FnType->getParamTypes())
108 AddArg(T);
Richard Smith9f690bd2015-10-27 06:02:45 +0000109
110 // Build the template-id.
111 QualType CoroTrait =
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000112 S.CheckTemplateIdType(TemplateName(CoroTraits), KwLoc, Args);
Richard Smith9f690bd2015-10-27 06:02:45 +0000113 if (CoroTrait.isNull())
114 return QualType();
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000115 if (S.RequireCompleteType(KwLoc, CoroTrait,
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000116 diag::err_coroutine_type_missing_specialization))
Richard Smith9f690bd2015-10-27 06:02:45 +0000117 return QualType();
118
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000119 auto *RD = CoroTrait->getAsCXXRecordDecl();
Richard Smith9f690bd2015-10-27 06:02:45 +0000120 assert(RD && "specialization of class template is not a class?");
121
122 // Look up the ::promise_type member.
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000123 LookupResult R(S, &S.PP.getIdentifierTable().get("promise_type"), KwLoc,
Richard Smith9f690bd2015-10-27 06:02:45 +0000124 Sema::LookupOrdinaryName);
125 S.LookupQualifiedName(R, RD);
126 auto *Promise = R.getAsSingle<TypeDecl>();
127 if (!Promise) {
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000128 S.Diag(FuncLoc,
129 diag::err_implied_std_coroutine_traits_promise_type_not_found)
Gor Nishanov8df64e92016-10-27 16:28:31 +0000130 << RD;
Richard Smith9f690bd2015-10-27 06:02:45 +0000131 return QualType();
132 }
Richard Smith9f690bd2015-10-27 06:02:45 +0000133 // The promise type is required to be a class type.
134 QualType PromiseType = S.Context.getTypeDeclType(Promise);
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000135
136 auto buildElaboratedType = [&]() {
Gor Nishanov3e048bb2016-10-04 00:31:16 +0000137 auto *NNS = NestedNameSpecifier::Create(S.Context, nullptr, StdExp);
Richard Smith9b2f53e2015-11-19 02:36:35 +0000138 NNS = NestedNameSpecifier::Create(S.Context, NNS, false,
139 CoroTrait.getTypePtr());
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000140 return S.Context.getElaboratedType(ETK_None, NNS, PromiseType);
141 };
Richard Smith9b2f53e2015-11-19 02:36:35 +0000142
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000143 if (!PromiseType->getAsCXXRecordDecl()) {
144 S.Diag(FuncLoc,
145 diag::err_implied_std_coroutine_traits_promise_type_not_class)
146 << buildElaboratedType();
Richard Smith9f690bd2015-10-27 06:02:45 +0000147 return QualType();
148 }
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000149 if (S.RequireCompleteType(FuncLoc, buildElaboratedType(),
150 diag::err_coroutine_promise_type_incomplete))
151 return QualType();
Richard Smith9f690bd2015-10-27 06:02:45 +0000152
153 return PromiseType;
154}
155
Gor Nishanov29ff6382017-05-24 14:34:19 +0000156/// Look up the std::experimental::coroutine_handle<PromiseType>.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000157static QualType lookupCoroutineHandleType(Sema &S, QualType PromiseType,
158 SourceLocation Loc) {
159 if (PromiseType.isNull())
160 return QualType();
161
162 NamespaceDecl *StdExp = S.lookupStdExperimentalNamespace();
163 assert(StdExp && "Should already be diagnosed");
164
165 LookupResult Result(S, &S.PP.getIdentifierTable().get("coroutine_handle"),
166 Loc, Sema::LookupOrdinaryName);
167 if (!S.LookupQualifiedName(Result, StdExp)) {
168 S.Diag(Loc, diag::err_implied_coroutine_type_not_found)
169 << "std::experimental::coroutine_handle";
170 return QualType();
171 }
172
173 ClassTemplateDecl *CoroHandle = Result.getAsSingle<ClassTemplateDecl>();
174 if (!CoroHandle) {
175 Result.suppressDiagnostics();
176 // We found something weird. Complain about the first thing we found.
177 NamedDecl *Found = *Result.begin();
178 S.Diag(Found->getLocation(), diag::err_malformed_std_coroutine_handle);
179 return QualType();
180 }
181
182 // Form template argument list for coroutine_handle<Promise>.
183 TemplateArgumentListInfo Args(Loc, Loc);
184 Args.addArgument(TemplateArgumentLoc(
185 TemplateArgument(PromiseType),
186 S.Context.getTrivialTypeSourceInfo(PromiseType, Loc)));
187
188 // Build the template-id.
189 QualType CoroHandleType =
190 S.CheckTemplateIdType(TemplateName(CoroHandle), Loc, Args);
191 if (CoroHandleType.isNull())
192 return QualType();
193 if (S.RequireCompleteType(Loc, CoroHandleType,
194 diag::err_coroutine_type_missing_specialization))
195 return QualType();
196
197 return CoroHandleType;
198}
199
Eric Fiselierc8efda72016-10-27 18:43:28 +0000200static bool isValidCoroutineContext(Sema &S, SourceLocation Loc,
201 StringRef Keyword) {
Brian Gesiakc1b173a2018-06-23 18:01:02 +0000202 // 'co_await' and 'co_yield' are not permitted in unevaluated operands,
203 // such as subexpressions of \c sizeof.
204 //
205 // [expr.await]p2, emphasis added: "An await-expression shall appear only in
206 // a *potentially evaluated* expression within the compound-statement of a
207 // function-body outside of a handler [...] A context within a function where
208 // an await-expression can appear is called a suspension context of the
209 // function." And per [expr.yield]p1: "A yield-expression shall appear only
210 // within a suspension context of a function."
Richard Smith744b2242015-11-20 02:54:01 +0000211 if (S.isUnevaluatedContext()) {
212 S.Diag(Loc, diag::err_coroutine_unevaluated_context) << Keyword;
Eric Fiselierc8efda72016-10-27 18:43:28 +0000213 return false;
Richard Smith744b2242015-11-20 02:54:01 +0000214 }
Richard Smithcfd53b42015-10-22 06:13:50 +0000215
Brian Gesiakc1b173a2018-06-23 18:01:02 +0000216 // Per [expr.await]p2, any other usage must be within a function.
217 // FIXME: This also covers [expr.await]p2: "An await-expression shall not
218 // appear in a default argument." But the diagnostic QoI here could be
219 // improved to inform the user that default arguments specifically are not
220 // allowed.
Richard Smithcfd53b42015-10-22 06:13:50 +0000221 auto *FD = dyn_cast<FunctionDecl>(S.CurContext);
222 if (!FD) {
223 S.Diag(Loc, isa<ObjCMethodDecl>(S.CurContext)
224 ? diag::err_coroutine_objc_method
225 : diag::err_coroutine_outside_function) << Keyword;
Eric Fiselierc8efda72016-10-27 18:43:28 +0000226 return false;
Richard Smithcfd53b42015-10-22 06:13:50 +0000227 }
228
Eric Fiselierc8efda72016-10-27 18:43:28 +0000229 // An enumeration for mapping the diagnostic type to the correct diagnostic
230 // selection index.
231 enum InvalidFuncDiag {
232 DiagCtor = 0,
233 DiagDtor,
234 DiagCopyAssign,
235 DiagMoveAssign,
236 DiagMain,
237 DiagConstexpr,
238 DiagAutoRet,
239 DiagVarargs,
240 };
241 bool Diagnosed = false;
242 auto DiagInvalid = [&](InvalidFuncDiag ID) {
243 S.Diag(Loc, diag::err_coroutine_invalid_func_context) << ID << Keyword;
244 Diagnosed = true;
245 return false;
246 };
247
248 // Diagnose when a constructor, destructor, copy/move assignment operator,
249 // or the function 'main' are declared as a coroutine.
250 auto *MD = dyn_cast<CXXMethodDecl>(FD);
Brian Gesiakc1b173a2018-06-23 18:01:02 +0000251 // [class.ctor]p6: "A constructor shall not be a coroutine."
Eric Fiselierc8efda72016-10-27 18:43:28 +0000252 if (MD && isa<CXXConstructorDecl>(MD))
253 return DiagInvalid(DiagCtor);
Brian Gesiakc1b173a2018-06-23 18:01:02 +0000254 // [class.dtor]p17: "A destructor shall not be a coroutine."
Eric Fiselierc8efda72016-10-27 18:43:28 +0000255 else if (MD && isa<CXXDestructorDecl>(MD))
256 return DiagInvalid(DiagDtor);
Brian Gesiakc1b173a2018-06-23 18:01:02 +0000257 // N4499 [special]p6: "A special member function shall not be a coroutine."
258 // Per C++ [special]p1, special member functions are the "default constructor,
259 // copy constructor and copy assignment operator, move constructor and move
260 // assignment operator, and destructor."
Eric Fiselierc8efda72016-10-27 18:43:28 +0000261 else if (MD && MD->isCopyAssignmentOperator())
262 return DiagInvalid(DiagCopyAssign);
263 else if (MD && MD->isMoveAssignmentOperator())
264 return DiagInvalid(DiagMoveAssign);
Brian Gesiakc1b173a2018-06-23 18:01:02 +0000265 // [basic.start.main]p3: "The function main shall not be a coroutine."
Eric Fiselierc8efda72016-10-27 18:43:28 +0000266 else if (FD->isMain())
267 return DiagInvalid(DiagMain);
268
269 // Emit a diagnostics for each of the following conditions which is not met.
Brian Gesiakc1b173a2018-06-23 18:01:02 +0000270 // [expr.const]p2: "An expression e is a core constant expression unless the
271 // evaluation of e [...] would evaluate one of the following expressions:
272 // [...] an await-expression [...] a yield-expression."
Eric Fiselierc8efda72016-10-27 18:43:28 +0000273 if (FD->isConstexpr())
274 DiagInvalid(DiagConstexpr);
Brian Gesiakc1b173a2018-06-23 18:01:02 +0000275 // [dcl.spec.auto]p15: "A function declared with a return type that uses a
276 // placeholder type shall not be a coroutine."
Eric Fiselierc8efda72016-10-27 18:43:28 +0000277 if (FD->getReturnType()->isUndeducedType())
278 DiagInvalid(DiagAutoRet);
Brian Gesiakc1b173a2018-06-23 18:01:02 +0000279 // [dcl.fct.def.coroutine]p1: "The parameter-declaration-clause of the
280 // coroutine shall not terminate with an ellipsis that is not part of a
281 // parameter-declaration."
Eric Fiselierc8efda72016-10-27 18:43:28 +0000282 if (FD->isVariadic())
283 DiagInvalid(DiagVarargs);
284
285 return !Diagnosed;
286}
287
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000288static ExprResult buildOperatorCoawaitLookupExpr(Sema &SemaRef, Scope *S,
289 SourceLocation Loc) {
290 DeclarationName OpName =
291 SemaRef.Context.DeclarationNames.getCXXOperatorName(OO_Coawait);
292 LookupResult Operators(SemaRef, OpName, SourceLocation(),
293 Sema::LookupOperatorName);
294 SemaRef.LookupName(Operators, S);
Eric Fiselierc8efda72016-10-27 18:43:28 +0000295
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000296 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
297 const auto &Functions = Operators.asUnresolvedSet();
298 bool IsOverloaded =
299 Functions.size() > 1 ||
300 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
301 Expr *CoawaitOp = UnresolvedLookupExpr::Create(
302 SemaRef.Context, /*NamingClass*/ nullptr, NestedNameSpecifierLoc(),
303 DeclarationNameInfo(OpName, Loc), /*RequiresADL*/ true, IsOverloaded,
304 Functions.begin(), Functions.end());
305 assert(CoawaitOp);
306 return CoawaitOp;
307}
Eric Fiselierc8efda72016-10-27 18:43:28 +0000308
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000309/// Build a call to 'operator co_await' if there is a suitable operator for
310/// the given expression.
311static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, SourceLocation Loc,
312 Expr *E,
313 UnresolvedLookupExpr *Lookup) {
314 UnresolvedSet<16> Functions;
315 Functions.append(Lookup->decls_begin(), Lookup->decls_end());
316 return SemaRef.CreateOverloadedUnaryOp(Loc, UO_Coawait, Functions, E);
317}
Eric Fiselierc8efda72016-10-27 18:43:28 +0000318
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000319static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, Scope *S,
320 SourceLocation Loc, Expr *E) {
321 ExprResult R = buildOperatorCoawaitLookupExpr(SemaRef, S, Loc);
322 if (R.isInvalid())
323 return ExprError();
324 return buildOperatorCoawaitCall(SemaRef, Loc, E,
325 cast<UnresolvedLookupExpr>(R.get()));
Richard Smithcfd53b42015-10-22 06:13:50 +0000326}
327
Gor Nishanov8df64e92016-10-27 16:28:31 +0000328static Expr *buildBuiltinCall(Sema &S, SourceLocation Loc, Builtin::ID Id,
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000329 MultiExprArg CallArgs) {
Gor Nishanov8df64e92016-10-27 16:28:31 +0000330 StringRef Name = S.Context.BuiltinInfo.getName(Id);
331 LookupResult R(S, &S.Context.Idents.get(Name), Loc, Sema::LookupOrdinaryName);
332 S.LookupName(R, S.TUScope, /*AllowBuiltinCreation=*/true);
333
334 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
335 assert(BuiltInDecl && "failed to find builtin declaration");
336
337 ExprResult DeclRef =
338 S.BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
339 assert(DeclRef.isUsable() && "Builtin reference cannot fail");
340
341 ExprResult Call =
342 S.ActOnCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
343
344 assert(!Call.isInvalid() && "Call to builtin cannot fail!");
345 return Call.get();
346}
347
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000348static ExprResult buildCoroutineHandle(Sema &S, QualType PromiseType,
349 SourceLocation Loc) {
350 QualType CoroHandleType = lookupCoroutineHandleType(S, PromiseType, Loc);
351 if (CoroHandleType.isNull())
352 return ExprError();
353
354 DeclContext *LookupCtx = S.computeDeclContext(CoroHandleType);
355 LookupResult Found(S, &S.PP.getIdentifierTable().get("from_address"), Loc,
356 Sema::LookupOrdinaryName);
357 if (!S.LookupQualifiedName(Found, LookupCtx)) {
358 S.Diag(Loc, diag::err_coroutine_handle_missing_member)
359 << "from_address";
360 return ExprError();
361 }
362
363 Expr *FramePtr =
364 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_frame, {});
365
366 CXXScopeSpec SS;
367 ExprResult FromAddr =
368 S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
369 if (FromAddr.isInvalid())
370 return ExprError();
371
372 return S.ActOnCallExpr(nullptr, FromAddr.get(), Loc, FramePtr, Loc);
373}
Richard Smithcfd53b42015-10-22 06:13:50 +0000374
Richard Smith9f690bd2015-10-27 06:02:45 +0000375struct ReadySuspendResumeResult {
Eric Fiselierd978e532017-05-28 18:21:12 +0000376 enum AwaitCallType { ACT_Ready, ACT_Suspend, ACT_Resume };
Richard Smith9f690bd2015-10-27 06:02:45 +0000377 Expr *Results[3];
Gor Nishanovce43bd22017-03-11 01:30:17 +0000378 OpaqueValueExpr *OpaqueValue;
379 bool IsInvalid;
Richard Smith9f690bd2015-10-27 06:02:45 +0000380};
381
Richard Smith23da82c2015-11-20 22:40:06 +0000382static ExprResult buildMemberCall(Sema &S, Expr *Base, SourceLocation Loc,
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000383 StringRef Name, MultiExprArg Args) {
Richard Smith23da82c2015-11-20 22:40:06 +0000384 DeclarationNameInfo NameInfo(&S.PP.getIdentifierTable().get(Name), Loc);
385
386 // FIXME: Fix BuildMemberReferenceExpr to take a const CXXScopeSpec&.
387 CXXScopeSpec SS;
388 ExprResult Result = S.BuildMemberReferenceExpr(
389 Base, Base->getType(), Loc, /*IsPtr=*/false, SS,
390 SourceLocation(), nullptr, NameInfo, /*TemplateArgs=*/nullptr,
391 /*Scope=*/nullptr);
392 if (Result.isInvalid())
393 return ExprError();
394
Gor Nishanovd4507262018-03-27 20:38:19 +0000395 // We meant exactly what we asked for. No need for typo correction.
396 if (auto *TE = dyn_cast<TypoExpr>(Result.get())) {
397 S.clearDelayedTypo(TE);
398 S.Diag(Loc, diag::err_no_member)
399 << NameInfo.getName() << Base->getType()->getAsCXXRecordDecl()
400 << Base->getSourceRange();
401 return ExprError();
402 }
403
Richard Smith23da82c2015-11-20 22:40:06 +0000404 return S.ActOnCallExpr(nullptr, Result.get(), Loc, Args, Loc, nullptr);
405}
406
Gor Nishanov0f333002017-08-25 04:46:54 +0000407// See if return type is coroutine-handle and if so, invoke builtin coro-resume
408// on its address. This is to enable experimental support for coroutine-handle
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000409// returning await_suspend that results in a guaranteed tail call to the target
Gor Nishanov0f333002017-08-25 04:46:54 +0000410// coroutine.
411static Expr *maybeTailCall(Sema &S, QualType RetType, Expr *E,
412 SourceLocation Loc) {
413 if (RetType->isReferenceType())
414 return nullptr;
415 Type const *T = RetType.getTypePtr();
416 if (!T->isClassType() && !T->isStructureType())
417 return nullptr;
418
419 // FIXME: Add convertability check to coroutine_handle<>. Possibly via
420 // EvaluateBinaryTypeTrait(BTT_IsConvertible, ...) which is at the moment
421 // a private function in SemaExprCXX.cpp
422
423 ExprResult AddressExpr = buildMemberCall(S, E, Loc, "address", None);
424 if (AddressExpr.isInvalid())
425 return nullptr;
426
427 Expr *JustAddress = AddressExpr.get();
428 // FIXME: Check that the type of AddressExpr is void*
429 return buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_resume,
430 JustAddress);
431}
432
Richard Smith9f690bd2015-10-27 06:02:45 +0000433/// Build calls to await_ready, await_suspend, and await_resume for a co_await
434/// expression.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000435static ReadySuspendResumeResult buildCoawaitCalls(Sema &S, VarDecl *CoroPromise,
436 SourceLocation Loc, Expr *E) {
Gor Nishanovce43bd22017-03-11 01:30:17 +0000437 OpaqueValueExpr *Operand = new (S.Context)
438 OpaqueValueExpr(Loc, E->getType(), VK_LValue, E->getObjectKind(), E);
439
Richard Smith9f690bd2015-10-27 06:02:45 +0000440 // Assume invalid until we see otherwise.
Gor Nishanovce43bd22017-03-11 01:30:17 +0000441 ReadySuspendResumeResult Calls = {{}, Operand, /*IsInvalid=*/true};
Richard Smith9f690bd2015-10-27 06:02:45 +0000442
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000443 ExprResult CoroHandleRes = buildCoroutineHandle(S, CoroPromise->getType(), Loc);
444 if (CoroHandleRes.isInvalid())
445 return Calls;
446 Expr *CoroHandle = CoroHandleRes.get();
447
Richard Smith9f690bd2015-10-27 06:02:45 +0000448 const StringRef Funcs[] = {"await_ready", "await_suspend", "await_resume"};
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000449 MultiExprArg Args[] = {None, CoroHandle, None};
Richard Smith9f690bd2015-10-27 06:02:45 +0000450 for (size_t I = 0, N = llvm::array_lengthof(Funcs); I != N; ++I) {
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000451 ExprResult Result = buildMemberCall(S, Operand, Loc, Funcs[I], Args[I]);
Richard Smith9f690bd2015-10-27 06:02:45 +0000452 if (Result.isInvalid())
453 return Calls;
454 Calls.Results[I] = Result.get();
455 }
456
Eric Fiselierd978e532017-05-28 18:21:12 +0000457 // Assume the calls are valid; all further checking should make them invalid.
Richard Smith9f690bd2015-10-27 06:02:45 +0000458 Calls.IsInvalid = false;
Eric Fiselierd978e532017-05-28 18:21:12 +0000459
460 using ACT = ReadySuspendResumeResult::AwaitCallType;
461 CallExpr *AwaitReady = cast<CallExpr>(Calls.Results[ACT::ACT_Ready]);
462 if (!AwaitReady->getType()->isDependentType()) {
463 // [expr.await]p3 [...]
464 // — await-ready is the expression e.await_ready(), contextually converted
465 // to bool.
466 ExprResult Conv = S.PerformContextuallyConvertToBool(AwaitReady);
467 if (Conv.isInvalid()) {
468 S.Diag(AwaitReady->getDirectCallee()->getLocStart(),
469 diag::note_await_ready_no_bool_conversion);
470 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
471 << AwaitReady->getDirectCallee() << E->getSourceRange();
472 Calls.IsInvalid = true;
473 }
474 Calls.Results[ACT::ACT_Ready] = Conv.get();
475 }
476 CallExpr *AwaitSuspend = cast<CallExpr>(Calls.Results[ACT::ACT_Suspend]);
477 if (!AwaitSuspend->getType()->isDependentType()) {
478 // [expr.await]p3 [...]
479 // - await-suspend is the expression e.await_suspend(h), which shall be
480 // a prvalue of type void or bool.
Eric Fiselier84ee7ff2017-05-31 23:41:11 +0000481 QualType RetType = AwaitSuspend->getCallReturnType(S.Context);
Gor Nishanovdb419a62017-09-05 19:31:52 +0000482
Gor Nishanov0f333002017-08-25 04:46:54 +0000483 // Experimental support for coroutine_handle returning await_suspend.
484 if (Expr *TailCallSuspend = maybeTailCall(S, RetType, AwaitSuspend, Loc))
485 Calls.Results[ACT::ACT_Suspend] = TailCallSuspend;
486 else {
487 // non-class prvalues always have cv-unqualified types
Gor Nishanov0f333002017-08-25 04:46:54 +0000488 if (RetType->isReferenceType() ||
Gor Nishanovdb419a62017-09-05 19:31:52 +0000489 (!RetType->isBooleanType() && !RetType->isVoidType())) {
Gor Nishanov0f333002017-08-25 04:46:54 +0000490 S.Diag(AwaitSuspend->getCalleeDecl()->getLocation(),
491 diag::err_await_suspend_invalid_return_type)
492 << RetType;
493 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
494 << AwaitSuspend->getDirectCallee();
495 Calls.IsInvalid = true;
496 }
Eric Fiselierd978e532017-05-28 18:21:12 +0000497 }
498 }
499
Richard Smith9f690bd2015-10-27 06:02:45 +0000500 return Calls;
501}
502
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000503static ExprResult buildPromiseCall(Sema &S, VarDecl *Promise,
504 SourceLocation Loc, StringRef Name,
505 MultiExprArg Args) {
506
507 // Form a reference to the promise.
508 ExprResult PromiseRef = S.BuildDeclRefExpr(
509 Promise, Promise->getType().getNonReferenceType(), VK_LValue, Loc);
510 if (PromiseRef.isInvalid())
511 return ExprError();
512
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000513 return buildMemberCall(S, PromiseRef.get(), Loc, Name, Args);
514}
515
516VarDecl *Sema::buildCoroutinePromise(SourceLocation Loc) {
517 assert(isa<FunctionDecl>(CurContext) && "not in a function scope");
518 auto *FD = cast<FunctionDecl>(CurContext);
Eric Fiselier166c6e62017-07-10 01:27:22 +0000519 bool IsThisDependentType = [&] {
520 if (auto *MD = dyn_cast_or_null<CXXMethodDecl>(FD))
521 return MD->isInstance() && MD->getThisType(Context)->isDependentType();
522 else
523 return false;
524 }();
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000525
Eric Fiselier166c6e62017-07-10 01:27:22 +0000526 QualType T = FD->getType()->isDependentType() || IsThisDependentType
527 ? Context.DependentTy
528 : lookupPromiseType(*this, FD, Loc);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000529 if (T.isNull())
530 return nullptr;
531
532 auto *VD = VarDecl::Create(Context, FD, FD->getLocation(), FD->getLocation(),
533 &PP.getIdentifierTable().get("__promise"), T,
534 Context.getTrivialTypeSourceInfo(T, Loc), SC_None);
535 CheckVariableDeclarationType(VD);
536 if (VD->isInvalidDecl())
537 return nullptr;
Brian Gesiak61f4ac92018-01-24 22:15:42 +0000538
539 auto *ScopeInfo = getCurFunction();
540 // Build a list of arguments, based on the coroutine functions arguments,
541 // that will be passed to the promise type's constructor.
542 llvm::SmallVector<Expr *, 4> CtorArgExprs;
Gor Nishanov07ac63f2018-05-28 18:08:47 +0000543
544 // Add implicit object parameter.
545 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
546 if (MD->isInstance() && !isLambdaCallOperator(MD)) {
547 ExprResult ThisExpr = ActOnCXXThis(Loc);
548 if (ThisExpr.isInvalid())
549 return nullptr;
550 ThisExpr = CreateBuiltinUnaryOp(Loc, UO_Deref, ThisExpr.get());
551 if (ThisExpr.isInvalid())
552 return nullptr;
553 CtorArgExprs.push_back(ThisExpr.get());
554 }
555 }
556
Brian Gesiak61f4ac92018-01-24 22:15:42 +0000557 auto &Moves = ScopeInfo->CoroutineParameterMoves;
558 for (auto *PD : FD->parameters()) {
559 if (PD->getType()->isDependentType())
560 continue;
561
562 auto RefExpr = ExprEmpty();
563 auto Move = Moves.find(PD);
Brian Gesiak98606222018-02-15 20:37:22 +0000564 assert(Move != Moves.end() &&
565 "Coroutine function parameter not inserted into move map");
566 // If a reference to the function parameter exists in the coroutine
567 // frame, use that reference.
568 auto *MoveDecl =
569 cast<VarDecl>(cast<DeclStmt>(Move->second)->getSingleDecl());
570 RefExpr =
571 BuildDeclRefExpr(MoveDecl, MoveDecl->getType().getNonReferenceType(),
572 ExprValueKind::VK_LValue, FD->getLocation());
Brian Gesiak61f4ac92018-01-24 22:15:42 +0000573 if (RefExpr.isInvalid())
574 return nullptr;
575 CtorArgExprs.push_back(RefExpr.get());
576 }
577
578 // Create an initialization sequence for the promise type using the
579 // constructor arguments, wrapped in a parenthesized list expression.
580 Expr *PLE = new (Context) ParenListExpr(Context, FD->getLocation(),
581 CtorArgExprs, FD->getLocation());
582 InitializedEntity Entity = InitializedEntity::InitializeVariable(VD);
583 InitializationKind Kind = InitializationKind::CreateForInit(
584 VD->getLocation(), /*DirectInit=*/true, PLE);
585 InitializationSequence InitSeq(*this, Entity, Kind, CtorArgExprs,
586 /*TopLevelOfInitList=*/false,
587 /*TreatUnavailableAsInvalid=*/false);
588
589 // Attempt to initialize the promise type with the arguments.
590 // If that fails, fall back to the promise type's default constructor.
591 if (InitSeq) {
592 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, CtorArgExprs);
593 if (Result.isInvalid()) {
594 VD->setInvalidDecl();
595 } else if (Result.get()) {
596 VD->setInit(MaybeCreateExprWithCleanups(Result.get()));
597 VD->setInitStyle(VarDecl::CallInit);
598 CheckCompleteVariableDeclaration(VD);
599 }
600 } else
601 ActOnUninitializedDecl(VD);
602
Eric Fiselier37b8a372017-05-31 19:36:59 +0000603 FD->addDecl(VD);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000604 return VD;
605}
606
607/// Check that this is a context in which a coroutine suspension can appear.
608static FunctionScopeInfo *checkCoroutineContext(Sema &S, SourceLocation Loc,
Eric Fiseliercac0a592017-03-11 02:35:37 +0000609 StringRef Keyword,
610 bool IsImplicit = false) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000611 if (!isValidCoroutineContext(S, Loc, Keyword))
612 return nullptr;
613
614 assert(isa<FunctionDecl>(S.CurContext) && "not in a function scope");
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000615
616 auto *ScopeInfo = S.getCurFunction();
617 assert(ScopeInfo && "missing function scope for function");
618
Eric Fiseliercac0a592017-03-11 02:35:37 +0000619 if (ScopeInfo->FirstCoroutineStmtLoc.isInvalid() && !IsImplicit)
620 ScopeInfo->setFirstCoroutineStmt(Loc, Keyword);
621
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000622 if (ScopeInfo->CoroutinePromise)
623 return ScopeInfo;
624
Brian Gesiak61f4ac92018-01-24 22:15:42 +0000625 if (!S.buildCoroutineParameterMoves(Loc))
626 return nullptr;
627
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000628 ScopeInfo->CoroutinePromise = S.buildCoroutinePromise(Loc);
629 if (!ScopeInfo->CoroutinePromise)
630 return nullptr;
631
632 return ScopeInfo;
633}
634
Eric Fiselierb936a392017-06-14 03:24:55 +0000635bool Sema::ActOnCoroutineBodyStart(Scope *SC, SourceLocation KWLoc,
636 StringRef Keyword) {
637 if (!checkCoroutineContext(*this, KWLoc, Keyword))
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000638 return false;
Eric Fiselierb936a392017-06-14 03:24:55 +0000639 auto *ScopeInfo = getCurFunction();
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000640 assert(ScopeInfo->CoroutinePromise);
641
642 // If we have existing coroutine statements then we have already built
643 // the initial and final suspend points.
644 if (!ScopeInfo->NeedsCoroutineSuspends)
645 return true;
646
647 ScopeInfo->setNeedsCoroutineSuspends(false);
648
Eric Fiselierb936a392017-06-14 03:24:55 +0000649 auto *Fn = cast<FunctionDecl>(CurContext);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000650 SourceLocation Loc = Fn->getLocation();
651 // Build the initial suspend point
652 auto buildSuspends = [&](StringRef Name) mutable -> StmtResult {
653 ExprResult Suspend =
Eric Fiselierb936a392017-06-14 03:24:55 +0000654 buildPromiseCall(*this, ScopeInfo->CoroutinePromise, Loc, Name, None);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000655 if (Suspend.isInvalid())
656 return StmtError();
Eric Fiselierb936a392017-06-14 03:24:55 +0000657 Suspend = buildOperatorCoawaitCall(*this, SC, Loc, Suspend.get());
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000658 if (Suspend.isInvalid())
659 return StmtError();
Eric Fiselierb936a392017-06-14 03:24:55 +0000660 Suspend = BuildResolvedCoawaitExpr(Loc, Suspend.get(),
661 /*IsImplicit*/ true);
662 Suspend = ActOnFinishFullExpr(Suspend.get());
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000663 if (Suspend.isInvalid()) {
Eric Fiselierb936a392017-06-14 03:24:55 +0000664 Diag(Loc, diag::note_coroutine_promise_suspend_implicitly_required)
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000665 << ((Name == "initial_suspend") ? 0 : 1);
Eric Fiselierb936a392017-06-14 03:24:55 +0000666 Diag(KWLoc, diag::note_declared_coroutine_here) << Keyword;
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000667 return StmtError();
668 }
669 return cast<Stmt>(Suspend.get());
670 };
671
672 StmtResult InitSuspend = buildSuspends("initial_suspend");
673 if (InitSuspend.isInvalid())
674 return true;
675
676 StmtResult FinalSuspend = buildSuspends("final_suspend");
677 if (FinalSuspend.isInvalid())
678 return true;
679
680 ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());
681
682 return true;
683}
684
Richard Smith9f690bd2015-10-27 06:02:45 +0000685ExprResult Sema::ActOnCoawaitExpr(Scope *S, SourceLocation Loc, Expr *E) {
Eric Fiselierb936a392017-06-14 03:24:55 +0000686 if (!ActOnCoroutineBodyStart(S, Loc, "co_await")) {
Eric Fiseliera5465282016-09-29 21:47:39 +0000687 CorrectDelayedTyposInExpr(E);
688 return ExprError();
689 }
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000690
Richard Smith10610f72015-11-20 22:57:24 +0000691 if (E->getType()->isPlaceholderType()) {
692 ExprResult R = CheckPlaceholderExpr(E);
693 if (R.isInvalid()) return ExprError();
694 E = R.get();
695 }
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000696 ExprResult Lookup = buildOperatorCoawaitLookupExpr(*this, S, Loc);
697 if (Lookup.isInvalid())
698 return ExprError();
699 return BuildUnresolvedCoawaitExpr(Loc, E,
700 cast<UnresolvedLookupExpr>(Lookup.get()));
701}
Richard Smith10610f72015-11-20 22:57:24 +0000702
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000703ExprResult Sema::BuildUnresolvedCoawaitExpr(SourceLocation Loc, Expr *E,
Eric Fiseliercac0a592017-03-11 02:35:37 +0000704 UnresolvedLookupExpr *Lookup) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000705 auto *FSI = checkCoroutineContext(*this, Loc, "co_await");
706 if (!FSI)
707 return ExprError();
708
709 if (E->getType()->isPlaceholderType()) {
710 ExprResult R = CheckPlaceholderExpr(E);
711 if (R.isInvalid())
712 return ExprError();
713 E = R.get();
714 }
715
716 auto *Promise = FSI->CoroutinePromise;
717 if (Promise->getType()->isDependentType()) {
718 Expr *Res =
719 new (Context) DependentCoawaitExpr(Loc, Context.DependentTy, E, Lookup);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000720 return Res;
721 }
722
723 auto *RD = Promise->getType()->getAsCXXRecordDecl();
724 if (lookupMember(*this, "await_transform", RD, Loc)) {
725 ExprResult R = buildPromiseCall(*this, Promise, Loc, "await_transform", E);
726 if (R.isInvalid()) {
727 Diag(Loc,
728 diag::note_coroutine_promise_implicit_await_transform_required_here)
729 << E->getSourceRange();
730 return ExprError();
731 }
732 E = R.get();
733 }
734 ExprResult Awaitable = buildOperatorCoawaitCall(*this, Loc, E, Lookup);
Richard Smith9f690bd2015-10-27 06:02:45 +0000735 if (Awaitable.isInvalid())
736 return ExprError();
Eric Fiseliera5465282016-09-29 21:47:39 +0000737
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000738 return BuildResolvedCoawaitExpr(Loc, Awaitable.get());
Richard Smith9f690bd2015-10-27 06:02:45 +0000739}
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000740
741ExprResult Sema::BuildResolvedCoawaitExpr(SourceLocation Loc, Expr *E,
742 bool IsImplicit) {
Eric Fiseliercac0a592017-03-11 02:35:37 +0000743 auto *Coroutine = checkCoroutineContext(*this, Loc, "co_await", IsImplicit);
Richard Smith744b2242015-11-20 02:54:01 +0000744 if (!Coroutine)
745 return ExprError();
Richard Smith9f690bd2015-10-27 06:02:45 +0000746
Richard Smith9f690bd2015-10-27 06:02:45 +0000747 if (E->getType()->isPlaceholderType()) {
748 ExprResult R = CheckPlaceholderExpr(E);
749 if (R.isInvalid()) return ExprError();
750 E = R.get();
751 }
752
Richard Smith10610f72015-11-20 22:57:24 +0000753 if (E->getType()->isDependentType()) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000754 Expr *Res = new (Context)
755 CoawaitExpr(Loc, Context.DependentTy, E, IsImplicit);
Richard Smith10610f72015-11-20 22:57:24 +0000756 return Res;
757 }
758
Richard Smith1f38edd2015-11-22 03:13:02 +0000759 // If the expression is a temporary, materialize it as an lvalue so that we
760 // can use it multiple times.
761 if (E->getValueKind() == VK_RValue)
Tim Shen4a05bb82016-06-21 20:29:17 +0000762 E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
Richard Smith9f690bd2015-10-27 06:02:45 +0000763
Eric Fiselierd2e30d32018-03-27 03:15:46 +0000764 // The location of the `co_await` token cannot be used when constructing
765 // the member call expressions since it's before the location of `Expr`, which
766 // is used as the start of the member call expression.
767 SourceLocation CallLoc = E->getExprLoc();
768
Richard Smith9f690bd2015-10-27 06:02:45 +0000769 // Build the await_ready, await_suspend, await_resume calls.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000770 ReadySuspendResumeResult RSS =
Eric Fiselierd2e30d32018-03-27 03:15:46 +0000771 buildCoawaitCalls(*this, Coroutine->CoroutinePromise, CallLoc, E);
Richard Smith9f690bd2015-10-27 06:02:45 +0000772 if (RSS.IsInvalid)
773 return ExprError();
774
Gor Nishanovce43bd22017-03-11 01:30:17 +0000775 Expr *Res =
776 new (Context) CoawaitExpr(Loc, E, RSS.Results[0], RSS.Results[1],
777 RSS.Results[2], RSS.OpaqueValue, IsImplicit);
Eric Fiseliercac0a592017-03-11 02:35:37 +0000778
Richard Smithcfd53b42015-10-22 06:13:50 +0000779 return Res;
780}
781
Richard Smith9f690bd2015-10-27 06:02:45 +0000782ExprResult Sema::ActOnCoyieldExpr(Scope *S, SourceLocation Loc, Expr *E) {
Eric Fiselierb936a392017-06-14 03:24:55 +0000783 if (!ActOnCoroutineBodyStart(S, Loc, "co_yield")) {
Eric Fiseliera5465282016-09-29 21:47:39 +0000784 CorrectDelayedTyposInExpr(E);
Richard Smith23da82c2015-11-20 22:40:06 +0000785 return ExprError();
Eric Fiseliera5465282016-09-29 21:47:39 +0000786 }
Richard Smith23da82c2015-11-20 22:40:06 +0000787
788 // Build yield_value call.
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000789 ExprResult Awaitable = buildPromiseCall(
790 *this, getCurFunction()->CoroutinePromise, Loc, "yield_value", E);
Richard Smith9f690bd2015-10-27 06:02:45 +0000791 if (Awaitable.isInvalid())
792 return ExprError();
Richard Smith23da82c2015-11-20 22:40:06 +0000793
794 // Build 'operator co_await' call.
795 Awaitable = buildOperatorCoawaitCall(*this, S, Loc, Awaitable.get());
796 if (Awaitable.isInvalid())
797 return ExprError();
798
Richard Smith9f690bd2015-10-27 06:02:45 +0000799 return BuildCoyieldExpr(Loc, Awaitable.get());
800}
801ExprResult Sema::BuildCoyieldExpr(SourceLocation Loc, Expr *E) {
802 auto *Coroutine = checkCoroutineContext(*this, Loc, "co_yield");
Richard Smith744b2242015-11-20 02:54:01 +0000803 if (!Coroutine)
804 return ExprError();
Richard Smithcfd53b42015-10-22 06:13:50 +0000805
Richard Smith10610f72015-11-20 22:57:24 +0000806 if (E->getType()->isPlaceholderType()) {
807 ExprResult R = CheckPlaceholderExpr(E);
808 if (R.isInvalid()) return ExprError();
809 E = R.get();
810 }
811
Richard Smithd7bed4d2015-11-22 02:57:17 +0000812 if (E->getType()->isDependentType()) {
813 Expr *Res = new (Context) CoyieldExpr(Loc, Context.DependentTy, E);
Richard Smithd7bed4d2015-11-22 02:57:17 +0000814 return Res;
815 }
816
Richard Smith1f38edd2015-11-22 03:13:02 +0000817 // If the expression is a temporary, materialize it as an lvalue so that we
818 // can use it multiple times.
819 if (E->getValueKind() == VK_RValue)
Tim Shen4a05bb82016-06-21 20:29:17 +0000820 E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
Richard Smithd7bed4d2015-11-22 02:57:17 +0000821
822 // Build the await_ready, await_suspend, await_resume calls.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000823 ReadySuspendResumeResult RSS =
824 buildCoawaitCalls(*this, Coroutine->CoroutinePromise, Loc, E);
Richard Smithd7bed4d2015-11-22 02:57:17 +0000825 if (RSS.IsInvalid)
826 return ExprError();
827
Eric Fiselierb936a392017-06-14 03:24:55 +0000828 Expr *Res =
829 new (Context) CoyieldExpr(Loc, E, RSS.Results[0], RSS.Results[1],
830 RSS.Results[2], RSS.OpaqueValue);
Eric Fiseliercac0a592017-03-11 02:35:37 +0000831
Richard Smithcfd53b42015-10-22 06:13:50 +0000832 return Res;
833}
834
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000835StmtResult Sema::ActOnCoreturnStmt(Scope *S, SourceLocation Loc, Expr *E) {
Eric Fiselierb936a392017-06-14 03:24:55 +0000836 if (!ActOnCoroutineBodyStart(S, Loc, "co_return")) {
Eric Fiseliera5465282016-09-29 21:47:39 +0000837 CorrectDelayedTyposInExpr(E);
838 return StmtError();
839 }
Richard Smith9f690bd2015-10-27 06:02:45 +0000840 return BuildCoreturnStmt(Loc, E);
841}
Gor Nishanov3e048bb2016-10-04 00:31:16 +0000842
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000843StmtResult Sema::BuildCoreturnStmt(SourceLocation Loc, Expr *E,
844 bool IsImplicit) {
Eric Fiseliercac0a592017-03-11 02:35:37 +0000845 auto *FSI = checkCoroutineContext(*this, Loc, "co_return", IsImplicit);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000846 if (!FSI)
Richard Smith71d403e2015-11-22 07:33:28 +0000847 return StmtError();
848
849 if (E && E->getType()->isPlaceholderType() &&
850 !E->getType()->isSpecificPlaceholderType(BuiltinType::Overload)) {
Richard Smith10610f72015-11-20 22:57:24 +0000851 ExprResult R = CheckPlaceholderExpr(E);
852 if (R.isInvalid()) return StmtError();
853 E = R.get();
854 }
855
Richard Smith4ba66602015-11-22 07:05:16 +0000856 // FIXME: If the operand is a reference to a variable that's about to go out
Richard Smith2af65c42015-11-24 02:34:39 +0000857 // of scope, we should treat the operand as an xvalue for this overload
Richard Smith4ba66602015-11-22 07:05:16 +0000858 // resolution.
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000859 VarDecl *Promise = FSI->CoroutinePromise;
Richard Smith4ba66602015-11-22 07:05:16 +0000860 ExprResult PC;
Eric Fiselier98131312016-10-06 21:23:38 +0000861 if (E && (isa<InitListExpr>(E) || !E->getType()->isVoidType())) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000862 PC = buildPromiseCall(*this, Promise, Loc, "return_value", E);
Richard Smith4ba66602015-11-22 07:05:16 +0000863 } else {
864 E = MakeFullDiscardedValueExpr(E).get();
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000865 PC = buildPromiseCall(*this, Promise, Loc, "return_void", None);
Richard Smith4ba66602015-11-22 07:05:16 +0000866 }
867 if (PC.isInvalid())
868 return StmtError();
869
870 Expr *PCE = ActOnFinishFullExpr(PC.get()).get();
871
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000872 Stmt *Res = new (Context) CoreturnStmt(Loc, E, PCE, IsImplicit);
Richard Smithcfd53b42015-10-22 06:13:50 +0000873 return Res;
874}
875
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000876/// Look up the std::nothrow object.
877static Expr *buildStdNoThrowDeclRef(Sema &S, SourceLocation Loc) {
878 NamespaceDecl *Std = S.getStdNamespace();
879 assert(Std && "Should already be diagnosed");
880
881 LookupResult Result(S, &S.PP.getIdentifierTable().get("nothrow"), Loc,
882 Sema::LookupOrdinaryName);
883 if (!S.LookupQualifiedName(Result, Std)) {
884 // FIXME: <experimental/coroutine> should have been included already.
885 // If we require it to include <new> then this diagnostic is no longer
886 // needed.
887 S.Diag(Loc, diag::err_implicit_coroutine_std_nothrow_type_not_found);
888 return nullptr;
889 }
890
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000891 auto *VD = Result.getAsSingle<VarDecl>();
892 if (!VD) {
893 Result.suppressDiagnostics();
894 // We found something weird. Complain about the first thing we found.
895 NamedDecl *Found = *Result.begin();
896 S.Diag(Found->getLocation(), diag::err_malformed_std_nothrow);
897 return nullptr;
898 }
899
900 ExprResult DR = S.BuildDeclRefExpr(VD, VD->getType(), VK_LValue, Loc);
901 if (DR.isInvalid())
902 return nullptr;
903
904 return DR.get();
905}
906
Gor Nishanov8df64e92016-10-27 16:28:31 +0000907// Find an appropriate delete for the promise.
908static FunctionDecl *findDeleteForPromise(Sema &S, SourceLocation Loc,
909 QualType PromiseType) {
910 FunctionDecl *OperatorDelete = nullptr;
911
912 DeclarationName DeleteName =
913 S.Context.DeclarationNames.getCXXOperatorName(OO_Delete);
914
915 auto *PointeeRD = PromiseType->getAsCXXRecordDecl();
916 assert(PointeeRD && "PromiseType must be a CxxRecordDecl type");
917
918 if (S.FindDeallocationFunction(Loc, PointeeRD, DeleteName, OperatorDelete))
919 return nullptr;
920
921 if (!OperatorDelete) {
922 // Look for a global declaration.
923 const bool CanProvideSize = S.isCompleteType(Loc, PromiseType);
924 const bool Overaligned = false;
925 OperatorDelete = S.FindUsualDeallocationFunction(Loc, CanProvideSize,
926 Overaligned, DeleteName);
927 }
928 S.MarkFunctionReferenced(Loc, OperatorDelete);
929 return OperatorDelete;
930}
931
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000932
933void Sema::CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body) {
934 FunctionScopeInfo *Fn = getCurFunction();
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000935 assert(Fn && Fn->isCoroutine() && "not a coroutine");
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000936 if (!Body) {
937 assert(FD->isInvalidDecl() &&
938 "a null body is only allowed for invalid declarations");
939 return;
940 }
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000941 // We have a function that uses coroutine keywords, but we failed to build
942 // the promise type.
943 if (!Fn->CoroutinePromise)
944 return FD->setInvalidDecl();
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000945
946 if (isa<CoroutineBodyStmt>(Body)) {
Gor Nishanov29ff6382017-05-24 14:34:19 +0000947 // Nothing todo. the body is already a transformed coroutine body statement.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000948 return;
949 }
950
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000951 // Coroutines [stmt.return]p1:
952 // A return statement shall not appear in a coroutine.
953 if (Fn->FirstReturnLoc.isValid()) {
Eric Fiseliercac0a592017-03-11 02:35:37 +0000954 assert(Fn->FirstCoroutineStmtLoc.isValid() &&
955 "first coroutine location not set");
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000956 Diag(Fn->FirstReturnLoc, diag::err_return_in_coroutine);
Eric Fiseliercac0a592017-03-11 02:35:37 +0000957 Diag(Fn->FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
958 << Fn->getFirstCoroutineStmtKeyword();
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000959 }
Eric Fiselierbee782b2017-04-03 19:21:00 +0000960 CoroutineStmtBuilder Builder(*this, *FD, *Fn, Body);
961 if (Builder.isInvalid() || !Builder.buildStatements())
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000962 return FD->setInvalidDecl();
963
964 // Build body for the coroutine wrapper statement.
965 Body = CoroutineBodyStmt::Create(Context, Builder);
966}
967
Eric Fiselierbee782b2017-04-03 19:21:00 +0000968CoroutineStmtBuilder::CoroutineStmtBuilder(Sema &S, FunctionDecl &FD,
969 sema::FunctionScopeInfo &Fn,
970 Stmt *Body)
971 : S(S), FD(FD), Fn(Fn), Loc(FD.getLocation()),
972 IsPromiseDependentType(
973 !Fn.CoroutinePromise ||
974 Fn.CoroutinePromise->getType()->isDependentType()) {
975 this->Body = Body;
Brian Gesiak61f4ac92018-01-24 22:15:42 +0000976
977 for (auto KV : Fn.CoroutineParameterMoves)
978 this->ParamMovesVector.push_back(KV.second);
979 this->ParamMoves = this->ParamMovesVector;
980
Eric Fiselierbee782b2017-04-03 19:21:00 +0000981 if (!IsPromiseDependentType) {
982 PromiseRecordDecl = Fn.CoroutinePromise->getType()->getAsCXXRecordDecl();
983 assert(PromiseRecordDecl && "Type should have already been checked");
984 }
985 this->IsValid = makePromiseStmt() && makeInitialAndFinalSuspend();
986}
987
988bool CoroutineStmtBuilder::buildStatements() {
989 assert(this->IsValid && "coroutine already invalid");
Brian Gesiak61f4ac92018-01-24 22:15:42 +0000990 this->IsValid = makeReturnObject();
Eric Fiselierbee782b2017-04-03 19:21:00 +0000991 if (this->IsValid && !IsPromiseDependentType)
992 buildDependentStatements();
993 return this->IsValid;
994}
995
996bool CoroutineStmtBuilder::buildDependentStatements() {
997 assert(this->IsValid && "coroutine already invalid");
998 assert(!this->IsPromiseDependentType &&
999 "coroutine cannot have a dependent promise type");
1000 this->IsValid = makeOnException() && makeOnFallthrough() &&
Gor Nishanov6a470682017-05-22 20:22:23 +00001001 makeGroDeclAndReturnStmt() && makeReturnOnAllocFailure() &&
1002 makeNewAndDeleteExpr();
Eric Fiselierbee782b2017-04-03 19:21:00 +00001003 return this->IsValid;
1004}
1005
1006bool CoroutineStmtBuilder::makePromiseStmt() {
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001007 // Form a declaration statement for the promise declaration, so that AST
1008 // visitors can more easily find it.
1009 StmtResult PromiseStmt =
1010 S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(Fn.CoroutinePromise), Loc, Loc);
1011 if (PromiseStmt.isInvalid())
1012 return false;
1013
1014 this->Promise = PromiseStmt.get();
1015 return true;
1016}
1017
Eric Fiselierbee782b2017-04-03 19:21:00 +00001018bool CoroutineStmtBuilder::makeInitialAndFinalSuspend() {
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001019 if (Fn.hasInvalidCoroutineSuspends())
1020 return false;
1021 this->InitialSuspend = cast<Expr>(Fn.CoroutineSuspends.first);
1022 this->FinalSuspend = cast<Expr>(Fn.CoroutineSuspends.second);
1023 return true;
1024}
1025
Gor Nishanov3aa9eb32017-03-27 23:36:59 +00001026static bool diagReturnOnAllocFailure(Sema &S, Expr *E,
1027 CXXRecordDecl *PromiseRecordDecl,
1028 FunctionScopeInfo &Fn) {
1029 auto Loc = E->getExprLoc();
1030 if (auto *DeclRef = dyn_cast_or_null<DeclRefExpr>(E)) {
1031 auto *Decl = DeclRef->getDecl();
1032 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Decl)) {
1033 if (Method->isStatic())
1034 return true;
1035 else
1036 Loc = Decl->getLocation();
1037 }
1038 }
1039
1040 S.Diag(
1041 Loc,
1042 diag::err_coroutine_promise_get_return_object_on_allocation_failure)
1043 << PromiseRecordDecl;
1044 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1045 << Fn.getFirstCoroutineStmtKeyword();
1046 return false;
1047}
1048
Eric Fiselierbee782b2017-04-03 19:21:00 +00001049bool CoroutineStmtBuilder::makeReturnOnAllocFailure() {
1050 assert(!IsPromiseDependentType &&
1051 "cannot make statement while the promise type is dependent");
Gor Nishanov3aa9eb32017-03-27 23:36:59 +00001052
1053 // [dcl.fct.def.coroutine]/8
1054 // The unqualified-id get_return_object_on_allocation_failure is looked up in
1055 // the scope of class P by class member access lookup (3.4.5). ...
1056 // If an allocation function returns nullptr, ... the coroutine return value
1057 // is obtained by a call to ... get_return_object_on_allocation_failure().
1058
1059 DeclarationName DN =
1060 S.PP.getIdentifierInfo("get_return_object_on_allocation_failure");
1061 LookupResult Found(S, DN, Loc, Sema::LookupMemberName);
Eric Fiselierbee782b2017-04-03 19:21:00 +00001062 if (!S.LookupQualifiedName(Found, PromiseRecordDecl))
1063 return true;
Gor Nishanov3aa9eb32017-03-27 23:36:59 +00001064
1065 CXXScopeSpec SS;
1066 ExprResult DeclNameExpr =
1067 S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
Eric Fiselierbee782b2017-04-03 19:21:00 +00001068 if (DeclNameExpr.isInvalid())
1069 return false;
Gor Nishanov3aa9eb32017-03-27 23:36:59 +00001070
1071 if (!diagReturnOnAllocFailure(S, DeclNameExpr.get(), PromiseRecordDecl, Fn))
1072 return false;
1073
1074 ExprResult ReturnObjectOnAllocationFailure =
1075 S.ActOnCallExpr(nullptr, DeclNameExpr.get(), Loc, {}, Loc);
Eric Fiselierbee782b2017-04-03 19:21:00 +00001076 if (ReturnObjectOnAllocationFailure.isInvalid())
1077 return false;
Gor Nishanov3aa9eb32017-03-27 23:36:59 +00001078
Gor Nishanovc4a19082017-03-28 02:51:45 +00001079 StmtResult ReturnStmt =
1080 S.BuildReturnStmt(Loc, ReturnObjectOnAllocationFailure.get());
Gor Nishanov6a470682017-05-22 20:22:23 +00001081 if (ReturnStmt.isInvalid()) {
Eric Fiselierfc50f622017-05-25 14:59:39 +00001082 S.Diag(Found.getFoundDecl()->getLocation(), diag::note_member_declared_here)
1083 << DN;
Gor Nishanov6a470682017-05-22 20:22:23 +00001084 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1085 << Fn.getFirstCoroutineStmtKeyword();
Eric Fiselierbee782b2017-04-03 19:21:00 +00001086 return false;
Gor Nishanov6a470682017-05-22 20:22:23 +00001087 }
Gor Nishanov3aa9eb32017-03-27 23:36:59 +00001088
1089 this->ReturnStmtOnAllocFailure = ReturnStmt.get();
1090 return true;
1091}
1092
Eric Fiselierbee782b2017-04-03 19:21:00 +00001093bool CoroutineStmtBuilder::makeNewAndDeleteExpr() {
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001094 // Form and check allocation and deallocation calls.
Eric Fiselierbee782b2017-04-03 19:21:00 +00001095 assert(!IsPromiseDependentType &&
1096 "cannot make statement while the promise type is dependent");
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001097 QualType PromiseType = Fn.CoroutinePromise->getType();
Gor Nishanov8df64e92016-10-27 16:28:31 +00001098
1099 if (S.RequireCompleteType(Loc, PromiseType, diag::err_incomplete_type))
1100 return false;
1101
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001102 const bool RequiresNoThrowAlloc = ReturnStmtOnAllocFailure != nullptr;
1103
Brian Gesiak98606222018-02-15 20:37:22 +00001104 // [dcl.fct.def.coroutine]/7
1105 // Lookup allocation functions using a parameter list composed of the
1106 // requested size of the coroutine state being allocated, followed by
1107 // the coroutine function's arguments. If a matching allocation function
1108 // exists, use it. Otherwise, use an allocation function that just takes
1109 // the requested size.
Gor Nishanov8df64e92016-10-27 16:28:31 +00001110
1111 FunctionDecl *OperatorNew = nullptr;
1112 FunctionDecl *OperatorDelete = nullptr;
1113 FunctionDecl *UnusedResult = nullptr;
1114 bool PassAlignment = false;
Eric Fiselierf747f532017-04-18 05:08:08 +00001115 SmallVector<Expr *, 1> PlacementArgs;
Gor Nishanov8df64e92016-10-27 16:28:31 +00001116
Brian Gesiak98606222018-02-15 20:37:22 +00001117 // [dcl.fct.def.coroutine]/7
1118 // "The allocation function’s name is looked up in the scope of P.
1119 // [...] If the lookup finds an allocation function in the scope of P,
1120 // overload resolution is performed on a function call created by assembling
1121 // an argument list. The first argument is the amount of space requested,
1122 // and has type std::size_t. The lvalues p1 ... pn are the succeeding
1123 // arguments."
1124 //
1125 // ...where "p1 ... pn" are defined earlier as:
1126 //
1127 // [dcl.fct.def.coroutine]/3
1128 // "For a coroutine f that is a non-static member function, let P1 denote the
1129 // type of the implicit object parameter (13.3.1) and P2 ... Pn be the types
1130 // of the function parameters; otherwise let P1 ... Pn be the types of the
1131 // function parameters. Let p1 ... pn be lvalues denoting those objects."
1132 if (auto *MD = dyn_cast<CXXMethodDecl>(&FD)) {
1133 if (MD->isInstance() && !isLambdaCallOperator(MD)) {
1134 ExprResult ThisExpr = S.ActOnCXXThis(Loc);
1135 if (ThisExpr.isInvalid())
1136 return false;
1137 ThisExpr = S.CreateBuiltinUnaryOp(Loc, UO_Deref, ThisExpr.get());
1138 if (ThisExpr.isInvalid())
1139 return false;
1140 PlacementArgs.push_back(ThisExpr.get());
1141 }
1142 }
1143 for (auto *PD : FD.parameters()) {
1144 if (PD->getType()->isDependentType())
1145 continue;
1146
1147 // Build a reference to the parameter.
1148 auto PDLoc = PD->getLocation();
1149 ExprResult PDRefExpr =
1150 S.BuildDeclRefExpr(PD, PD->getOriginalType().getNonReferenceType(),
1151 ExprValueKind::VK_LValue, PDLoc);
1152 if (PDRefExpr.isInvalid())
1153 return false;
1154
1155 PlacementArgs.push_back(PDRefExpr.get());
1156 }
Brian Gesiakcb024022018-04-01 22:59:22 +00001157 S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Class,
1158 /*DeleteScope*/ Sema::AFS_Both, PromiseType,
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001159 /*isArray*/ false, PassAlignment, PlacementArgs,
Brian Gesiak98606222018-02-15 20:37:22 +00001160 OperatorNew, UnusedResult, /*Diagnose*/ false);
1161
1162 // [dcl.fct.def.coroutine]/7
1163 // "If no matching function is found, overload resolution is performed again
1164 // on a function call created by passing just the amount of space required as
1165 // an argument of type std::size_t."
1166 if (!OperatorNew && !PlacementArgs.empty()) {
1167 PlacementArgs.clear();
Brian Gesiakcb024022018-04-01 22:59:22 +00001168 S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Class,
1169 /*DeleteScope*/ Sema::AFS_Both, PromiseType,
1170 /*isArray*/ false, PassAlignment, PlacementArgs,
1171 OperatorNew, UnusedResult, /*Diagnose*/ false);
1172 }
1173
1174 // [dcl.fct.def.coroutine]/7
1175 // "The allocation function’s name is looked up in the scope of P. If this
1176 // lookup fails, the allocation function’s name is looked up in the global
1177 // scope."
1178 if (!OperatorNew) {
1179 S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Global,
1180 /*DeleteScope*/ Sema::AFS_Both, PromiseType,
1181 /*isArray*/ false, PassAlignment, PlacementArgs,
1182 OperatorNew, UnusedResult);
Brian Gesiak98606222018-02-15 20:37:22 +00001183 }
Gor Nishanov8df64e92016-10-27 16:28:31 +00001184
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001185 bool IsGlobalOverload =
1186 OperatorNew && !isa<CXXRecordDecl>(OperatorNew->getDeclContext());
1187 // If we didn't find a class-local new declaration and non-throwing new
1188 // was is required then we need to lookup the non-throwing global operator
1189 // instead.
1190 if (RequiresNoThrowAlloc && (!OperatorNew || IsGlobalOverload)) {
1191 auto *StdNoThrow = buildStdNoThrowDeclRef(S, Loc);
1192 if (!StdNoThrow)
1193 return false;
Eric Fiselierf747f532017-04-18 05:08:08 +00001194 PlacementArgs = {StdNoThrow};
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001195 OperatorNew = nullptr;
Brian Gesiakcb024022018-04-01 22:59:22 +00001196 S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Both,
1197 /*DeleteScope*/ Sema::AFS_Both, PromiseType,
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001198 /*isArray*/ false, PassAlignment, PlacementArgs,
1199 OperatorNew, UnusedResult);
1200 }
Gor Nishanov8df64e92016-10-27 16:28:31 +00001201
Brian Gesiak98606222018-02-15 20:37:22 +00001202 if (!OperatorNew)
1203 return false;
Eric Fiselierc5128752017-04-18 05:30:39 +00001204
1205 if (RequiresNoThrowAlloc) {
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001206 const auto *FT = OperatorNew->getType()->getAs<FunctionProtoType>();
Richard Smitheaf11ad2018-05-03 03:58:32 +00001207 if (!FT->isNothrow(/*ResultIfDependent*/ false)) {
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001208 S.Diag(OperatorNew->getLocation(),
1209 diag::err_coroutine_promise_new_requires_nothrow)
1210 << OperatorNew;
1211 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
1212 << OperatorNew;
1213 return false;
1214 }
1215 }
1216
1217 if ((OperatorDelete = findDeleteForPromise(S, Loc, PromiseType)) == nullptr)
Gor Nishanov8df64e92016-10-27 16:28:31 +00001218 return false;
1219
1220 Expr *FramePtr =
1221 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_frame, {});
1222
1223 Expr *FrameSize =
1224 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_size, {});
1225
1226 // Make new call.
1227
1228 ExprResult NewRef =
1229 S.BuildDeclRefExpr(OperatorNew, OperatorNew->getType(), VK_LValue, Loc);
1230 if (NewRef.isInvalid())
1231 return false;
1232
Eric Fiselierf747f532017-04-18 05:08:08 +00001233 SmallVector<Expr *, 2> NewArgs(1, FrameSize);
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001234 for (auto Arg : PlacementArgs)
1235 NewArgs.push_back(Arg);
1236
Gor Nishanov8df64e92016-10-27 16:28:31 +00001237 ExprResult NewExpr =
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001238 S.ActOnCallExpr(S.getCurScope(), NewRef.get(), Loc, NewArgs, Loc);
1239 NewExpr = S.ActOnFinishFullExpr(NewExpr.get());
Gor Nishanov8df64e92016-10-27 16:28:31 +00001240 if (NewExpr.isInvalid())
1241 return false;
1242
Gor Nishanov8df64e92016-10-27 16:28:31 +00001243 // Make delete call.
1244
1245 QualType OpDeleteQualType = OperatorDelete->getType();
1246
1247 ExprResult DeleteRef =
1248 S.BuildDeclRefExpr(OperatorDelete, OpDeleteQualType, VK_LValue, Loc);
1249 if (DeleteRef.isInvalid())
1250 return false;
1251
1252 Expr *CoroFree =
1253 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_free, {FramePtr});
1254
1255 SmallVector<Expr *, 2> DeleteArgs{CoroFree};
1256
1257 // Check if we need to pass the size.
1258 const auto *OpDeleteType =
1259 OpDeleteQualType.getTypePtr()->getAs<FunctionProtoType>();
1260 if (OpDeleteType->getNumParams() > 1)
1261 DeleteArgs.push_back(FrameSize);
1262
1263 ExprResult DeleteExpr =
1264 S.ActOnCallExpr(S.getCurScope(), DeleteRef.get(), Loc, DeleteArgs, Loc);
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001265 DeleteExpr = S.ActOnFinishFullExpr(DeleteExpr.get());
Gor Nishanov8df64e92016-10-27 16:28:31 +00001266 if (DeleteExpr.isInvalid())
1267 return false;
1268
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001269 this->Allocate = NewExpr.get();
1270 this->Deallocate = DeleteExpr.get();
Gor Nishanov8df64e92016-10-27 16:28:31 +00001271
1272 return true;
1273}
1274
Eric Fiselierbee782b2017-04-03 19:21:00 +00001275bool CoroutineStmtBuilder::makeOnFallthrough() {
1276 assert(!IsPromiseDependentType &&
1277 "cannot make statement while the promise type is dependent");
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001278
1279 // [dcl.fct.def.coroutine]/4
1280 // The unqualified-ids 'return_void' and 'return_value' are looked up in
1281 // the scope of class P. If both are found, the program is ill-formed.
Eric Fiselierfc50f622017-05-25 14:59:39 +00001282 bool HasRVoid, HasRValue;
1283 LookupResult LRVoid =
1284 lookupMember(S, "return_void", PromiseRecordDecl, Loc, HasRVoid);
1285 LookupResult LRValue =
1286 lookupMember(S, "return_value", PromiseRecordDecl, Loc, HasRValue);
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001287
Eric Fiselier709d1b32016-10-27 07:30:31 +00001288 StmtResult Fallthrough;
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001289 if (HasRVoid && HasRValue) {
1290 // FIXME Improve this diagnostic
Eric Fiselierfc50f622017-05-25 14:59:39 +00001291 S.Diag(FD.getLocation(),
1292 diag::err_coroutine_promise_incompatible_return_functions)
1293 << PromiseRecordDecl;
1294 S.Diag(LRVoid.getRepresentativeDecl()->getLocation(),
1295 diag::note_member_first_declared_here)
1296 << LRVoid.getLookupName();
1297 S.Diag(LRValue.getRepresentativeDecl()->getLocation(),
1298 diag::note_member_first_declared_here)
1299 << LRValue.getLookupName();
1300 return false;
1301 } else if (!HasRVoid && !HasRValue) {
1302 // FIXME: The PDTS currently specifies this case as UB, not ill-formed.
1303 // However we still diagnose this as an error since until the PDTS is fixed.
1304 S.Diag(FD.getLocation(),
1305 diag::err_coroutine_promise_requires_return_function)
1306 << PromiseRecordDecl;
1307 S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here)
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001308 << PromiseRecordDecl;
1309 return false;
1310 } else if (HasRVoid) {
1311 // If the unqualified-id return_void is found, flowing off the end of a
1312 // coroutine is equivalent to a co_return with no operand. Otherwise,
1313 // flowing off the end of a coroutine results in undefined behavior.
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001314 Fallthrough = S.BuildCoreturnStmt(FD.getLocation(), nullptr,
1315 /*IsImplicit*/false);
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001316 Fallthrough = S.ActOnFinishFullStmt(Fallthrough.get());
1317 if (Fallthrough.isInvalid())
1318 return false;
Eric Fiselier709d1b32016-10-27 07:30:31 +00001319 }
Richard Smith2af65c42015-11-24 02:34:39 +00001320
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001321 this->OnFallthrough = Fallthrough.get();
1322 return true;
1323}
1324
Eric Fiselierbee782b2017-04-03 19:21:00 +00001325bool CoroutineStmtBuilder::makeOnException() {
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001326 // Try to form 'p.unhandled_exception();'
Eric Fiselierbee782b2017-04-03 19:21:00 +00001327 assert(!IsPromiseDependentType &&
1328 "cannot make statement while the promise type is dependent");
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001329
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001330 const bool RequireUnhandledException = S.getLangOpts().CXXExceptions;
1331
1332 if (!lookupMember(S, "unhandled_exception", PromiseRecordDecl, Loc)) {
1333 auto DiagID =
1334 RequireUnhandledException
1335 ? diag::err_coroutine_promise_unhandled_exception_required
1336 : diag::
1337 warn_coroutine_promise_unhandled_exception_required_with_exceptions;
1338 S.Diag(Loc, DiagID) << PromiseRecordDecl;
Gor Nishanov29ff6382017-05-24 14:34:19 +00001339 S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here)
1340 << PromiseRecordDecl;
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001341 return !RequireUnhandledException;
1342 }
1343
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001344 // If exceptions are disabled, don't try to build OnException.
1345 if (!S.getLangOpts().CXXExceptions)
1346 return true;
1347
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001348 ExprResult UnhandledException = buildPromiseCall(S, Fn.CoroutinePromise, Loc,
1349 "unhandled_exception", None);
1350 UnhandledException = S.ActOnFinishFullExpr(UnhandledException.get(), Loc);
1351 if (UnhandledException.isInvalid())
1352 return false;
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001353
Gor Nishanov5b050e42017-05-22 22:33:17 +00001354 // Since the body of the coroutine will be wrapped in try-catch, it will
1355 // be incompatible with SEH __try if present in a function.
1356 if (!S.getLangOpts().Borland && Fn.FirstSEHTryLoc.isValid()) {
1357 S.Diag(Fn.FirstSEHTryLoc, diag::err_seh_in_a_coroutine_with_cxx_exceptions);
1358 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1359 << Fn.getFirstCoroutineStmtKeyword();
1360 return false;
1361 }
1362
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001363 this->OnException = UnhandledException.get();
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001364 return true;
1365}
1366
Eric Fiselierbee782b2017-04-03 19:21:00 +00001367bool CoroutineStmtBuilder::makeReturnObject() {
Richard Smith2af65c42015-11-24 02:34:39 +00001368 // Build implicit 'p.get_return_object()' expression and form initialization
1369 // of return type from it.
1370 ExprResult ReturnObject =
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001371 buildPromiseCall(S, Fn.CoroutinePromise, Loc, "get_return_object", None);
Richard Smith2af65c42015-11-24 02:34:39 +00001372 if (ReturnObject.isInvalid())
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001373 return false;
Richard Smith2af65c42015-11-24 02:34:39 +00001374
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001375 this->ReturnValue = ReturnObject.get();
1376 return true;
1377}
1378
Gor Nishanov6a470682017-05-22 20:22:23 +00001379static void noteMemberDeclaredHere(Sema &S, Expr *E, FunctionScopeInfo &Fn) {
1380 if (auto *MbrRef = dyn_cast<CXXMemberCallExpr>(E)) {
1381 auto *MethodDecl = MbrRef->getMethodDecl();
Eric Fiselierfc50f622017-05-25 14:59:39 +00001382 S.Diag(MethodDecl->getLocation(), diag::note_member_declared_here)
1383 << MethodDecl;
Gor Nishanov6a470682017-05-22 20:22:23 +00001384 }
1385 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1386 << Fn.getFirstCoroutineStmtKeyword();
1387}
1388
1389bool CoroutineStmtBuilder::makeGroDeclAndReturnStmt() {
1390 assert(!IsPromiseDependentType &&
1391 "cannot make statement while the promise type is dependent");
1392 assert(this->ReturnValue && "ReturnValue must be already formed");
1393
1394 QualType const GroType = this->ReturnValue->getType();
1395 assert(!GroType->isDependentType() &&
1396 "get_return_object type must no longer be dependent");
1397
1398 QualType const FnRetType = FD.getReturnType();
1399 assert(!FnRetType->isDependentType() &&
1400 "get_return_object type must no longer be dependent");
1401
1402 if (FnRetType->isVoidType()) {
1403 ExprResult Res = S.ActOnFinishFullExpr(this->ReturnValue, Loc);
1404 if (Res.isInvalid())
1405 return false;
1406
1407 this->ResultDecl = Res.get();
1408 return true;
1409 }
1410
1411 if (GroType->isVoidType()) {
1412 // Trigger a nice error message.
1413 InitializedEntity Entity =
1414 InitializedEntity::InitializeResult(Loc, FnRetType, false);
1415 S.PerformMoveOrCopyInitialization(Entity, nullptr, FnRetType, ReturnValue);
1416 noteMemberDeclaredHere(S, ReturnValue, Fn);
1417 return false;
1418 }
1419
1420 auto *GroDecl = VarDecl::Create(
1421 S.Context, &FD, FD.getLocation(), FD.getLocation(),
1422 &S.PP.getIdentifierTable().get("__coro_gro"), GroType,
1423 S.Context.getTrivialTypeSourceInfo(GroType, Loc), SC_None);
1424
1425 S.CheckVariableDeclarationType(GroDecl);
1426 if (GroDecl->isInvalidDecl())
1427 return false;
1428
1429 InitializedEntity Entity = InitializedEntity::InitializeVariable(GroDecl);
1430 ExprResult Res = S.PerformMoveOrCopyInitialization(Entity, nullptr, GroType,
1431 this->ReturnValue);
1432 if (Res.isInvalid())
1433 return false;
1434
1435 Res = S.ActOnFinishFullExpr(Res.get());
1436 if (Res.isInvalid())
1437 return false;
1438
Gor Nishanov6a470682017-05-22 20:22:23 +00001439 S.AddInitializerToDecl(GroDecl, Res.get(),
1440 /*DirectInit=*/false);
1441
1442 S.FinalizeDeclaration(GroDecl);
1443
1444 // Form a declaration statement for the return declaration, so that AST
1445 // visitors can more easily find it.
1446 StmtResult GroDeclStmt =
1447 S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(GroDecl), Loc, Loc);
1448 if (GroDeclStmt.isInvalid())
1449 return false;
1450
1451 this->ResultDecl = GroDeclStmt.get();
1452
1453 ExprResult declRef = S.BuildDeclRefExpr(GroDecl, GroType, VK_LValue, Loc);
1454 if (declRef.isInvalid())
1455 return false;
1456
1457 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, declRef.get());
1458 if (ReturnStmt.isInvalid()) {
1459 noteMemberDeclaredHere(S, ReturnValue, Fn);
1460 return false;
1461 }
Eric Fiselier8ed97272018-02-01 23:47:54 +00001462 if (cast<clang::ReturnStmt>(ReturnStmt.get())->getNRVOCandidate() == GroDecl)
1463 GroDecl->setNRVOVariable(true);
Gor Nishanov6a470682017-05-22 20:22:23 +00001464
1465 this->ReturnStmt = ReturnStmt.get();
1466 return true;
1467}
1468
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001469// Create a static_cast\<T&&>(expr).
1470static Expr *castForMoving(Sema &S, Expr *E, QualType T = QualType()) {
1471 if (T.isNull())
1472 T = E->getType();
1473 QualType TargetType = S.BuildReferenceType(
1474 T, /*SpelledAsLValue*/ false, SourceLocation(), DeclarationName());
1475 SourceLocation ExprLoc = E->getLocStart();
1476 TypeSourceInfo *TargetLoc =
1477 S.Context.getTrivialTypeSourceInfo(TargetType, ExprLoc);
1478
1479 return S
1480 .BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
1481 SourceRange(ExprLoc, ExprLoc), E->getSourceRange())
1482 .get();
1483}
1484
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001485/// Build a variable declaration for move parameter.
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001486static VarDecl *buildVarDecl(Sema &S, SourceLocation Loc, QualType Type,
Eric Fiselierde7943b2017-06-03 00:22:18 +00001487 IdentifierInfo *II) {
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001488 TypeSourceInfo *TInfo = S.Context.getTrivialTypeSourceInfo(Type, Loc);
Brian Gesiak61f4ac92018-01-24 22:15:42 +00001489 VarDecl *Decl = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, II, Type,
1490 TInfo, SC_None);
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001491 Decl->setImplicit();
1492 return Decl;
1493}
1494
Brian Gesiak61f4ac92018-01-24 22:15:42 +00001495// Build statements that move coroutine function parameters to the coroutine
1496// frame, and store them on the function scope info.
1497bool Sema::buildCoroutineParameterMoves(SourceLocation Loc) {
1498 assert(isa<FunctionDecl>(CurContext) && "not in a function scope");
1499 auto *FD = cast<FunctionDecl>(CurContext);
1500
1501 auto *ScopeInfo = getCurFunction();
1502 assert(ScopeInfo->CoroutineParameterMoves.empty() &&
1503 "Should not build parameter moves twice");
1504
1505 for (auto *PD : FD->parameters()) {
1506 if (PD->getType()->isDependentType())
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001507 continue;
1508
Brian Gesiak98606222018-02-15 20:37:22 +00001509 ExprResult PDRefExpr =
1510 BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
1511 ExprValueKind::VK_LValue, Loc); // FIXME: scope?
1512 if (PDRefExpr.isInvalid())
1513 return false;
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001514
Brian Gesiak98606222018-02-15 20:37:22 +00001515 Expr *CExpr = nullptr;
1516 if (PD->getType()->getAsCXXRecordDecl() ||
1517 PD->getType()->isRValueReferenceType())
1518 CExpr = castForMoving(*this, PDRefExpr.get());
1519 else
1520 CExpr = PDRefExpr.get();
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001521
Brian Gesiak98606222018-02-15 20:37:22 +00001522 auto D = buildVarDecl(*this, Loc, PD->getType(), PD->getIdentifier());
1523 AddInitializerToDecl(D, CExpr, /*DirectInit=*/true);
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001524
Brian Gesiak98606222018-02-15 20:37:22 +00001525 // Convert decl to a statement.
1526 StmtResult Stmt = ActOnDeclStmt(ConvertDeclToDeclGroup(D), Loc, Loc);
1527 if (Stmt.isInvalid())
1528 return false;
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001529
Brian Gesiak98606222018-02-15 20:37:22 +00001530 ScopeInfo->CoroutineParameterMoves.insert(std::make_pair(PD, Stmt.get()));
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001531 }
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001532 return true;
Richard Smithcfd53b42015-10-22 06:13:50 +00001533}
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001534
1535StmtResult Sema::BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
1536 CoroutineBodyStmt *Res = CoroutineBodyStmt::Create(Context, Args);
1537 if (!Res)
1538 return StmtError();
1539 return Res;
1540}