blob: a84116c1bcc5696765297f966451925158dd9555 [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
Brian Gesiak3e65d9a2018-07-14 18:21:44 +000063 ClassTemplateDecl *CoroTraits = S.lookupCoroutineTraits(KwLoc, FuncLoc);
Richard Smith9f690bd2015-10-27 06:02:45 +000064 if (!CoroTraits) {
Richard Smith9f690bd2015-10-27 06:02:45 +000065 return QualType();
66 }
67
Eric Fiselier166c6e62017-07-10 01:27:22 +000068 // Form template argument list for coroutine_traits<R, P1, P2, ...> according
69 // to [dcl.fct.def.coroutine]3
Eric Fiselier89bf0e72017-03-06 22:52:28 +000070 TemplateArgumentListInfo Args(KwLoc, KwLoc);
Eric Fiselier166c6e62017-07-10 01:27:22 +000071 auto AddArg = [&](QualType T) {
Richard Smith9f690bd2015-10-27 06:02:45 +000072 Args.addArgument(TemplateArgumentLoc(
Eric Fiselier89bf0e72017-03-06 22:52:28 +000073 TemplateArgument(T), S.Context.getTrivialTypeSourceInfo(T, KwLoc)));
Eric Fiselier166c6e62017-07-10 01:27:22 +000074 };
75 AddArg(FnType->getReturnType());
76 // If the function is a non-static member function, add the type
77 // of the implicit object parameter before the formal parameters.
78 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
79 if (MD->isInstance()) {
80 // [over.match.funcs]4
81 // For non-static member functions, the type of the implicit object
82 // parameter is
Eric Fiselierbf166ce2017-07-10 02:52:34 +000083 // -- "lvalue reference to cv X" for functions declared without a
84 // ref-qualifier or with the & ref-qualifier
85 // -- "rvalue reference to cv X" for functions declared with the &&
86 // ref-qualifier
Eric Fiselier166c6e62017-07-10 01:27:22 +000087 QualType T =
88 MD->getThisType(S.Context)->getAs<PointerType>()->getPointeeType();
89 T = FnType->getRefQualifier() == RQ_RValue
90 ? S.Context.getRValueReferenceType(T)
91 : S.Context.getLValueReferenceType(T, /*SpelledAsLValue*/ true);
92 AddArg(T);
93 }
94 }
95 for (QualType T : FnType->getParamTypes())
96 AddArg(T);
Richard Smith9f690bd2015-10-27 06:02:45 +000097
98 // Build the template-id.
99 QualType CoroTrait =
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000100 S.CheckTemplateIdType(TemplateName(CoroTraits), KwLoc, Args);
Richard Smith9f690bd2015-10-27 06:02:45 +0000101 if (CoroTrait.isNull())
102 return QualType();
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000103 if (S.RequireCompleteType(KwLoc, CoroTrait,
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000104 diag::err_coroutine_type_missing_specialization))
Richard Smith9f690bd2015-10-27 06:02:45 +0000105 return QualType();
106
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000107 auto *RD = CoroTrait->getAsCXXRecordDecl();
Richard Smith9f690bd2015-10-27 06:02:45 +0000108 assert(RD && "specialization of class template is not a class?");
109
110 // Look up the ::promise_type member.
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000111 LookupResult R(S, &S.PP.getIdentifierTable().get("promise_type"), KwLoc,
Richard Smith9f690bd2015-10-27 06:02:45 +0000112 Sema::LookupOrdinaryName);
113 S.LookupQualifiedName(R, RD);
114 auto *Promise = R.getAsSingle<TypeDecl>();
115 if (!Promise) {
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000116 S.Diag(FuncLoc,
117 diag::err_implied_std_coroutine_traits_promise_type_not_found)
Gor Nishanov8df64e92016-10-27 16:28:31 +0000118 << RD;
Richard Smith9f690bd2015-10-27 06:02:45 +0000119 return QualType();
120 }
Richard Smith9f690bd2015-10-27 06:02:45 +0000121 // The promise type is required to be a class type.
122 QualType PromiseType = S.Context.getTypeDeclType(Promise);
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000123
124 auto buildElaboratedType = [&]() {
Gor Nishanov3e048bb2016-10-04 00:31:16 +0000125 auto *NNS = NestedNameSpecifier::Create(S.Context, nullptr, StdExp);
Richard Smith9b2f53e2015-11-19 02:36:35 +0000126 NNS = NestedNameSpecifier::Create(S.Context, NNS, false,
127 CoroTrait.getTypePtr());
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000128 return S.Context.getElaboratedType(ETK_None, NNS, PromiseType);
129 };
Richard Smith9b2f53e2015-11-19 02:36:35 +0000130
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000131 if (!PromiseType->getAsCXXRecordDecl()) {
132 S.Diag(FuncLoc,
133 diag::err_implied_std_coroutine_traits_promise_type_not_class)
134 << buildElaboratedType();
Richard Smith9f690bd2015-10-27 06:02:45 +0000135 return QualType();
136 }
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000137 if (S.RequireCompleteType(FuncLoc, buildElaboratedType(),
138 diag::err_coroutine_promise_type_incomplete))
139 return QualType();
Richard Smith9f690bd2015-10-27 06:02:45 +0000140
141 return PromiseType;
142}
143
Gor Nishanov29ff6382017-05-24 14:34:19 +0000144/// Look up the std::experimental::coroutine_handle<PromiseType>.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000145static QualType lookupCoroutineHandleType(Sema &S, QualType PromiseType,
146 SourceLocation Loc) {
147 if (PromiseType.isNull())
148 return QualType();
149
150 NamespaceDecl *StdExp = S.lookupStdExperimentalNamespace();
151 assert(StdExp && "Should already be diagnosed");
152
153 LookupResult Result(S, &S.PP.getIdentifierTable().get("coroutine_handle"),
154 Loc, Sema::LookupOrdinaryName);
155 if (!S.LookupQualifiedName(Result, StdExp)) {
156 S.Diag(Loc, diag::err_implied_coroutine_type_not_found)
157 << "std::experimental::coroutine_handle";
158 return QualType();
159 }
160
161 ClassTemplateDecl *CoroHandle = Result.getAsSingle<ClassTemplateDecl>();
162 if (!CoroHandle) {
163 Result.suppressDiagnostics();
164 // We found something weird. Complain about the first thing we found.
165 NamedDecl *Found = *Result.begin();
166 S.Diag(Found->getLocation(), diag::err_malformed_std_coroutine_handle);
167 return QualType();
168 }
169
170 // Form template argument list for coroutine_handle<Promise>.
171 TemplateArgumentListInfo Args(Loc, Loc);
172 Args.addArgument(TemplateArgumentLoc(
173 TemplateArgument(PromiseType),
174 S.Context.getTrivialTypeSourceInfo(PromiseType, Loc)));
175
176 // Build the template-id.
177 QualType CoroHandleType =
178 S.CheckTemplateIdType(TemplateName(CoroHandle), Loc, Args);
179 if (CoroHandleType.isNull())
180 return QualType();
181 if (S.RequireCompleteType(Loc, CoroHandleType,
182 diag::err_coroutine_type_missing_specialization))
183 return QualType();
184
185 return CoroHandleType;
186}
187
Eric Fiselierc8efda72016-10-27 18:43:28 +0000188static bool isValidCoroutineContext(Sema &S, SourceLocation Loc,
189 StringRef Keyword) {
Brian Gesiakc1b173a2018-06-23 18:01:02 +0000190 // 'co_await' and 'co_yield' are not permitted in unevaluated operands,
191 // such as subexpressions of \c sizeof.
192 //
193 // [expr.await]p2, emphasis added: "An await-expression shall appear only in
194 // a *potentially evaluated* expression within the compound-statement of a
195 // function-body outside of a handler [...] A context within a function where
196 // an await-expression can appear is called a suspension context of the
197 // function." And per [expr.yield]p1: "A yield-expression shall appear only
198 // within a suspension context of a function."
Richard Smith744b2242015-11-20 02:54:01 +0000199 if (S.isUnevaluatedContext()) {
200 S.Diag(Loc, diag::err_coroutine_unevaluated_context) << Keyword;
Eric Fiselierc8efda72016-10-27 18:43:28 +0000201 return false;
Richard Smith744b2242015-11-20 02:54:01 +0000202 }
Richard Smithcfd53b42015-10-22 06:13:50 +0000203
Brian Gesiakc1b173a2018-06-23 18:01:02 +0000204 // Per [expr.await]p2, any other usage must be within a function.
205 // FIXME: This also covers [expr.await]p2: "An await-expression shall not
206 // appear in a default argument." But the diagnostic QoI here could be
207 // improved to inform the user that default arguments specifically are not
208 // allowed.
Richard Smithcfd53b42015-10-22 06:13:50 +0000209 auto *FD = dyn_cast<FunctionDecl>(S.CurContext);
210 if (!FD) {
211 S.Diag(Loc, isa<ObjCMethodDecl>(S.CurContext)
212 ? diag::err_coroutine_objc_method
213 : diag::err_coroutine_outside_function) << Keyword;
Eric Fiselierc8efda72016-10-27 18:43:28 +0000214 return false;
Richard Smithcfd53b42015-10-22 06:13:50 +0000215 }
216
Eric Fiselierc8efda72016-10-27 18:43:28 +0000217 // An enumeration for mapping the diagnostic type to the correct diagnostic
218 // selection index.
219 enum InvalidFuncDiag {
220 DiagCtor = 0,
221 DiagDtor,
222 DiagCopyAssign,
223 DiagMoveAssign,
224 DiagMain,
225 DiagConstexpr,
226 DiagAutoRet,
227 DiagVarargs,
228 };
229 bool Diagnosed = false;
230 auto DiagInvalid = [&](InvalidFuncDiag ID) {
231 S.Diag(Loc, diag::err_coroutine_invalid_func_context) << ID << Keyword;
232 Diagnosed = true;
233 return false;
234 };
235
236 // Diagnose when a constructor, destructor, copy/move assignment operator,
237 // or the function 'main' are declared as a coroutine.
238 auto *MD = dyn_cast<CXXMethodDecl>(FD);
Brian Gesiakc1b173a2018-06-23 18:01:02 +0000239 // [class.ctor]p6: "A constructor shall not be a coroutine."
Eric Fiselierc8efda72016-10-27 18:43:28 +0000240 if (MD && isa<CXXConstructorDecl>(MD))
241 return DiagInvalid(DiagCtor);
Brian Gesiakc1b173a2018-06-23 18:01:02 +0000242 // [class.dtor]p17: "A destructor shall not be a coroutine."
Eric Fiselierc8efda72016-10-27 18:43:28 +0000243 else if (MD && isa<CXXDestructorDecl>(MD))
244 return DiagInvalid(DiagDtor);
Brian Gesiakc1b173a2018-06-23 18:01:02 +0000245 // N4499 [special]p6: "A special member function shall not be a coroutine."
246 // Per C++ [special]p1, special member functions are the "default constructor,
247 // copy constructor and copy assignment operator, move constructor and move
248 // assignment operator, and destructor."
Eric Fiselierc8efda72016-10-27 18:43:28 +0000249 else if (MD && MD->isCopyAssignmentOperator())
250 return DiagInvalid(DiagCopyAssign);
251 else if (MD && MD->isMoveAssignmentOperator())
252 return DiagInvalid(DiagMoveAssign);
Brian Gesiakc1b173a2018-06-23 18:01:02 +0000253 // [basic.start.main]p3: "The function main shall not be a coroutine."
Eric Fiselierc8efda72016-10-27 18:43:28 +0000254 else if (FD->isMain())
255 return DiagInvalid(DiagMain);
256
257 // Emit a diagnostics for each of the following conditions which is not met.
Brian Gesiakc1b173a2018-06-23 18:01:02 +0000258 // [expr.const]p2: "An expression e is a core constant expression unless the
259 // evaluation of e [...] would evaluate one of the following expressions:
260 // [...] an await-expression [...] a yield-expression."
Eric Fiselierc8efda72016-10-27 18:43:28 +0000261 if (FD->isConstexpr())
262 DiagInvalid(DiagConstexpr);
Brian Gesiakc1b173a2018-06-23 18:01:02 +0000263 // [dcl.spec.auto]p15: "A function declared with a return type that uses a
264 // placeholder type shall not be a coroutine."
Eric Fiselierc8efda72016-10-27 18:43:28 +0000265 if (FD->getReturnType()->isUndeducedType())
266 DiagInvalid(DiagAutoRet);
Brian Gesiakc1b173a2018-06-23 18:01:02 +0000267 // [dcl.fct.def.coroutine]p1: "The parameter-declaration-clause of the
268 // coroutine shall not terminate with an ellipsis that is not part of a
269 // parameter-declaration."
Eric Fiselierc8efda72016-10-27 18:43:28 +0000270 if (FD->isVariadic())
271 DiagInvalid(DiagVarargs);
272
273 return !Diagnosed;
274}
275
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000276static ExprResult buildOperatorCoawaitLookupExpr(Sema &SemaRef, Scope *S,
277 SourceLocation Loc) {
278 DeclarationName OpName =
279 SemaRef.Context.DeclarationNames.getCXXOperatorName(OO_Coawait);
280 LookupResult Operators(SemaRef, OpName, SourceLocation(),
281 Sema::LookupOperatorName);
282 SemaRef.LookupName(Operators, S);
Eric Fiselierc8efda72016-10-27 18:43:28 +0000283
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000284 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
285 const auto &Functions = Operators.asUnresolvedSet();
286 bool IsOverloaded =
287 Functions.size() > 1 ||
288 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
289 Expr *CoawaitOp = UnresolvedLookupExpr::Create(
290 SemaRef.Context, /*NamingClass*/ nullptr, NestedNameSpecifierLoc(),
291 DeclarationNameInfo(OpName, Loc), /*RequiresADL*/ true, IsOverloaded,
292 Functions.begin(), Functions.end());
293 assert(CoawaitOp);
294 return CoawaitOp;
295}
Eric Fiselierc8efda72016-10-27 18:43:28 +0000296
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000297/// Build a call to 'operator co_await' if there is a suitable operator for
298/// the given expression.
299static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, SourceLocation Loc,
300 Expr *E,
301 UnresolvedLookupExpr *Lookup) {
302 UnresolvedSet<16> Functions;
303 Functions.append(Lookup->decls_begin(), Lookup->decls_end());
304 return SemaRef.CreateOverloadedUnaryOp(Loc, UO_Coawait, Functions, E);
305}
Eric Fiselierc8efda72016-10-27 18:43:28 +0000306
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000307static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, Scope *S,
308 SourceLocation Loc, Expr *E) {
309 ExprResult R = buildOperatorCoawaitLookupExpr(SemaRef, S, Loc);
310 if (R.isInvalid())
311 return ExprError();
312 return buildOperatorCoawaitCall(SemaRef, Loc, E,
313 cast<UnresolvedLookupExpr>(R.get()));
Richard Smithcfd53b42015-10-22 06:13:50 +0000314}
315
Gor Nishanov8df64e92016-10-27 16:28:31 +0000316static Expr *buildBuiltinCall(Sema &S, SourceLocation Loc, Builtin::ID Id,
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000317 MultiExprArg CallArgs) {
Gor Nishanov8df64e92016-10-27 16:28:31 +0000318 StringRef Name = S.Context.BuiltinInfo.getName(Id);
319 LookupResult R(S, &S.Context.Idents.get(Name), Loc, Sema::LookupOrdinaryName);
320 S.LookupName(R, S.TUScope, /*AllowBuiltinCreation=*/true);
321
322 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
323 assert(BuiltInDecl && "failed to find builtin declaration");
324
325 ExprResult DeclRef =
326 S.BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
327 assert(DeclRef.isUsable() && "Builtin reference cannot fail");
328
329 ExprResult Call =
330 S.ActOnCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
331
332 assert(!Call.isInvalid() && "Call to builtin cannot fail!");
333 return Call.get();
334}
335
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000336static ExprResult buildCoroutineHandle(Sema &S, QualType PromiseType,
337 SourceLocation Loc) {
338 QualType CoroHandleType = lookupCoroutineHandleType(S, PromiseType, Loc);
339 if (CoroHandleType.isNull())
340 return ExprError();
341
342 DeclContext *LookupCtx = S.computeDeclContext(CoroHandleType);
343 LookupResult Found(S, &S.PP.getIdentifierTable().get("from_address"), Loc,
344 Sema::LookupOrdinaryName);
345 if (!S.LookupQualifiedName(Found, LookupCtx)) {
346 S.Diag(Loc, diag::err_coroutine_handle_missing_member)
347 << "from_address";
348 return ExprError();
349 }
350
351 Expr *FramePtr =
352 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_frame, {});
353
354 CXXScopeSpec SS;
355 ExprResult FromAddr =
356 S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
357 if (FromAddr.isInvalid())
358 return ExprError();
359
360 return S.ActOnCallExpr(nullptr, FromAddr.get(), Loc, FramePtr, Loc);
361}
Richard Smithcfd53b42015-10-22 06:13:50 +0000362
Richard Smith9f690bd2015-10-27 06:02:45 +0000363struct ReadySuspendResumeResult {
Eric Fiselierd978e532017-05-28 18:21:12 +0000364 enum AwaitCallType { ACT_Ready, ACT_Suspend, ACT_Resume };
Richard Smith9f690bd2015-10-27 06:02:45 +0000365 Expr *Results[3];
Gor Nishanovce43bd22017-03-11 01:30:17 +0000366 OpaqueValueExpr *OpaqueValue;
367 bool IsInvalid;
Richard Smith9f690bd2015-10-27 06:02:45 +0000368};
369
Richard Smith23da82c2015-11-20 22:40:06 +0000370static ExprResult buildMemberCall(Sema &S, Expr *Base, SourceLocation Loc,
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000371 StringRef Name, MultiExprArg Args) {
Richard Smith23da82c2015-11-20 22:40:06 +0000372 DeclarationNameInfo NameInfo(&S.PP.getIdentifierTable().get(Name), Loc);
373
374 // FIXME: Fix BuildMemberReferenceExpr to take a const CXXScopeSpec&.
375 CXXScopeSpec SS;
376 ExprResult Result = S.BuildMemberReferenceExpr(
377 Base, Base->getType(), Loc, /*IsPtr=*/false, SS,
378 SourceLocation(), nullptr, NameInfo, /*TemplateArgs=*/nullptr,
379 /*Scope=*/nullptr);
380 if (Result.isInvalid())
381 return ExprError();
382
Gor Nishanovd4507262018-03-27 20:38:19 +0000383 // We meant exactly what we asked for. No need for typo correction.
384 if (auto *TE = dyn_cast<TypoExpr>(Result.get())) {
385 S.clearDelayedTypo(TE);
386 S.Diag(Loc, diag::err_no_member)
387 << NameInfo.getName() << Base->getType()->getAsCXXRecordDecl()
388 << Base->getSourceRange();
389 return ExprError();
390 }
391
Richard Smith23da82c2015-11-20 22:40:06 +0000392 return S.ActOnCallExpr(nullptr, Result.get(), Loc, Args, Loc, nullptr);
393}
394
Gor Nishanov0f333002017-08-25 04:46:54 +0000395// See if return type is coroutine-handle and if so, invoke builtin coro-resume
396// on its address. This is to enable experimental support for coroutine-handle
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000397// returning await_suspend that results in a guaranteed tail call to the target
Gor Nishanov0f333002017-08-25 04:46:54 +0000398// coroutine.
399static Expr *maybeTailCall(Sema &S, QualType RetType, Expr *E,
400 SourceLocation Loc) {
401 if (RetType->isReferenceType())
402 return nullptr;
403 Type const *T = RetType.getTypePtr();
404 if (!T->isClassType() && !T->isStructureType())
405 return nullptr;
406
407 // FIXME: Add convertability check to coroutine_handle<>. Possibly via
408 // EvaluateBinaryTypeTrait(BTT_IsConvertible, ...) which is at the moment
409 // a private function in SemaExprCXX.cpp
410
411 ExprResult AddressExpr = buildMemberCall(S, E, Loc, "address", None);
412 if (AddressExpr.isInvalid())
413 return nullptr;
414
415 Expr *JustAddress = AddressExpr.get();
416 // FIXME: Check that the type of AddressExpr is void*
417 return buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_resume,
418 JustAddress);
419}
420
Richard Smith9f690bd2015-10-27 06:02:45 +0000421/// Build calls to await_ready, await_suspend, and await_resume for a co_await
422/// expression.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000423static ReadySuspendResumeResult buildCoawaitCalls(Sema &S, VarDecl *CoroPromise,
424 SourceLocation Loc, Expr *E) {
Gor Nishanovce43bd22017-03-11 01:30:17 +0000425 OpaqueValueExpr *Operand = new (S.Context)
426 OpaqueValueExpr(Loc, E->getType(), VK_LValue, E->getObjectKind(), E);
427
Richard Smith9f690bd2015-10-27 06:02:45 +0000428 // Assume invalid until we see otherwise.
Gor Nishanovce43bd22017-03-11 01:30:17 +0000429 ReadySuspendResumeResult Calls = {{}, Operand, /*IsInvalid=*/true};
Richard Smith9f690bd2015-10-27 06:02:45 +0000430
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000431 ExprResult CoroHandleRes = buildCoroutineHandle(S, CoroPromise->getType(), Loc);
432 if (CoroHandleRes.isInvalid())
433 return Calls;
434 Expr *CoroHandle = CoroHandleRes.get();
435
Richard Smith9f690bd2015-10-27 06:02:45 +0000436 const StringRef Funcs[] = {"await_ready", "await_suspend", "await_resume"};
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000437 MultiExprArg Args[] = {None, CoroHandle, None};
Richard Smith9f690bd2015-10-27 06:02:45 +0000438 for (size_t I = 0, N = llvm::array_lengthof(Funcs); I != N; ++I) {
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000439 ExprResult Result = buildMemberCall(S, Operand, Loc, Funcs[I], Args[I]);
Richard Smith9f690bd2015-10-27 06:02:45 +0000440 if (Result.isInvalid())
441 return Calls;
442 Calls.Results[I] = Result.get();
443 }
444
Eric Fiselierd978e532017-05-28 18:21:12 +0000445 // Assume the calls are valid; all further checking should make them invalid.
Richard Smith9f690bd2015-10-27 06:02:45 +0000446 Calls.IsInvalid = false;
Eric Fiselierd978e532017-05-28 18:21:12 +0000447
448 using ACT = ReadySuspendResumeResult::AwaitCallType;
449 CallExpr *AwaitReady = cast<CallExpr>(Calls.Results[ACT::ACT_Ready]);
450 if (!AwaitReady->getType()->isDependentType()) {
451 // [expr.await]p3 [...]
452 // — await-ready is the expression e.await_ready(), contextually converted
453 // to bool.
454 ExprResult Conv = S.PerformContextuallyConvertToBool(AwaitReady);
455 if (Conv.isInvalid()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000456 S.Diag(AwaitReady->getDirectCallee()->getBeginLoc(),
Eric Fiselierd978e532017-05-28 18:21:12 +0000457 diag::note_await_ready_no_bool_conversion);
458 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
459 << AwaitReady->getDirectCallee() << E->getSourceRange();
460 Calls.IsInvalid = true;
461 }
462 Calls.Results[ACT::ACT_Ready] = Conv.get();
463 }
464 CallExpr *AwaitSuspend = cast<CallExpr>(Calls.Results[ACT::ACT_Suspend]);
465 if (!AwaitSuspend->getType()->isDependentType()) {
466 // [expr.await]p3 [...]
467 // - await-suspend is the expression e.await_suspend(h), which shall be
468 // a prvalue of type void or bool.
Eric Fiselier84ee7ff2017-05-31 23:41:11 +0000469 QualType RetType = AwaitSuspend->getCallReturnType(S.Context);
Gor Nishanovdb419a62017-09-05 19:31:52 +0000470
Gor Nishanov0f333002017-08-25 04:46:54 +0000471 // Experimental support for coroutine_handle returning await_suspend.
472 if (Expr *TailCallSuspend = maybeTailCall(S, RetType, AwaitSuspend, Loc))
473 Calls.Results[ACT::ACT_Suspend] = TailCallSuspend;
474 else {
475 // non-class prvalues always have cv-unqualified types
Gor Nishanov0f333002017-08-25 04:46:54 +0000476 if (RetType->isReferenceType() ||
Gor Nishanovdb419a62017-09-05 19:31:52 +0000477 (!RetType->isBooleanType() && !RetType->isVoidType())) {
Gor Nishanov0f333002017-08-25 04:46:54 +0000478 S.Diag(AwaitSuspend->getCalleeDecl()->getLocation(),
479 diag::err_await_suspend_invalid_return_type)
480 << RetType;
481 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
482 << AwaitSuspend->getDirectCallee();
483 Calls.IsInvalid = true;
484 }
Eric Fiselierd978e532017-05-28 18:21:12 +0000485 }
486 }
487
Richard Smith9f690bd2015-10-27 06:02:45 +0000488 return Calls;
489}
490
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000491static ExprResult buildPromiseCall(Sema &S, VarDecl *Promise,
492 SourceLocation Loc, StringRef Name,
493 MultiExprArg Args) {
494
495 // Form a reference to the promise.
496 ExprResult PromiseRef = S.BuildDeclRefExpr(
497 Promise, Promise->getType().getNonReferenceType(), VK_LValue, Loc);
498 if (PromiseRef.isInvalid())
499 return ExprError();
500
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000501 return buildMemberCall(S, PromiseRef.get(), Loc, Name, Args);
502}
503
504VarDecl *Sema::buildCoroutinePromise(SourceLocation Loc) {
505 assert(isa<FunctionDecl>(CurContext) && "not in a function scope");
506 auto *FD = cast<FunctionDecl>(CurContext);
Eric Fiselier166c6e62017-07-10 01:27:22 +0000507 bool IsThisDependentType = [&] {
508 if (auto *MD = dyn_cast_or_null<CXXMethodDecl>(FD))
509 return MD->isInstance() && MD->getThisType(Context)->isDependentType();
510 else
511 return false;
512 }();
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000513
Eric Fiselier166c6e62017-07-10 01:27:22 +0000514 QualType T = FD->getType()->isDependentType() || IsThisDependentType
515 ? Context.DependentTy
516 : lookupPromiseType(*this, FD, Loc);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000517 if (T.isNull())
518 return nullptr;
519
520 auto *VD = VarDecl::Create(Context, FD, FD->getLocation(), FD->getLocation(),
521 &PP.getIdentifierTable().get("__promise"), T,
522 Context.getTrivialTypeSourceInfo(T, Loc), SC_None);
523 CheckVariableDeclarationType(VD);
524 if (VD->isInvalidDecl())
525 return nullptr;
Brian Gesiak61f4ac92018-01-24 22:15:42 +0000526
527 auto *ScopeInfo = getCurFunction();
528 // Build a list of arguments, based on the coroutine functions arguments,
529 // that will be passed to the promise type's constructor.
530 llvm::SmallVector<Expr *, 4> CtorArgExprs;
Gor Nishanov07ac63f2018-05-28 18:08:47 +0000531
532 // Add implicit object parameter.
533 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
534 if (MD->isInstance() && !isLambdaCallOperator(MD)) {
535 ExprResult ThisExpr = ActOnCXXThis(Loc);
536 if (ThisExpr.isInvalid())
537 return nullptr;
538 ThisExpr = CreateBuiltinUnaryOp(Loc, UO_Deref, ThisExpr.get());
539 if (ThisExpr.isInvalid())
540 return nullptr;
541 CtorArgExprs.push_back(ThisExpr.get());
542 }
543 }
544
Brian Gesiak61f4ac92018-01-24 22:15:42 +0000545 auto &Moves = ScopeInfo->CoroutineParameterMoves;
546 for (auto *PD : FD->parameters()) {
547 if (PD->getType()->isDependentType())
548 continue;
549
550 auto RefExpr = ExprEmpty();
551 auto Move = Moves.find(PD);
Brian Gesiak98606222018-02-15 20:37:22 +0000552 assert(Move != Moves.end() &&
553 "Coroutine function parameter not inserted into move map");
554 // If a reference to the function parameter exists in the coroutine
555 // frame, use that reference.
556 auto *MoveDecl =
557 cast<VarDecl>(cast<DeclStmt>(Move->second)->getSingleDecl());
558 RefExpr =
559 BuildDeclRefExpr(MoveDecl, MoveDecl->getType().getNonReferenceType(),
560 ExprValueKind::VK_LValue, FD->getLocation());
Brian Gesiak61f4ac92018-01-24 22:15:42 +0000561 if (RefExpr.isInvalid())
562 return nullptr;
563 CtorArgExprs.push_back(RefExpr.get());
564 }
565
566 // Create an initialization sequence for the promise type using the
567 // constructor arguments, wrapped in a parenthesized list expression.
Bruno Riccif49e1ca2018-11-20 16:20:40 +0000568 Expr *PLE = ParenListExpr::Create(Context, FD->getLocation(),
569 CtorArgExprs, FD->getLocation());
Brian Gesiak61f4ac92018-01-24 22:15:42 +0000570 InitializedEntity Entity = InitializedEntity::InitializeVariable(VD);
571 InitializationKind Kind = InitializationKind::CreateForInit(
572 VD->getLocation(), /*DirectInit=*/true, PLE);
573 InitializationSequence InitSeq(*this, Entity, Kind, CtorArgExprs,
574 /*TopLevelOfInitList=*/false,
575 /*TreatUnavailableAsInvalid=*/false);
576
577 // Attempt to initialize the promise type with the arguments.
578 // If that fails, fall back to the promise type's default constructor.
579 if (InitSeq) {
580 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, CtorArgExprs);
581 if (Result.isInvalid()) {
582 VD->setInvalidDecl();
583 } else if (Result.get()) {
584 VD->setInit(MaybeCreateExprWithCleanups(Result.get()));
585 VD->setInitStyle(VarDecl::CallInit);
586 CheckCompleteVariableDeclaration(VD);
587 }
588 } else
589 ActOnUninitializedDecl(VD);
590
Eric Fiselier37b8a372017-05-31 19:36:59 +0000591 FD->addDecl(VD);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000592 return VD;
593}
594
595/// Check that this is a context in which a coroutine suspension can appear.
596static FunctionScopeInfo *checkCoroutineContext(Sema &S, SourceLocation Loc,
Eric Fiseliercac0a592017-03-11 02:35:37 +0000597 StringRef Keyword,
598 bool IsImplicit = false) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000599 if (!isValidCoroutineContext(S, Loc, Keyword))
600 return nullptr;
601
602 assert(isa<FunctionDecl>(S.CurContext) && "not in a function scope");
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000603
604 auto *ScopeInfo = S.getCurFunction();
605 assert(ScopeInfo && "missing function scope for function");
606
Eric Fiseliercac0a592017-03-11 02:35:37 +0000607 if (ScopeInfo->FirstCoroutineStmtLoc.isInvalid() && !IsImplicit)
608 ScopeInfo->setFirstCoroutineStmt(Loc, Keyword);
609
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000610 if (ScopeInfo->CoroutinePromise)
611 return ScopeInfo;
612
Brian Gesiak61f4ac92018-01-24 22:15:42 +0000613 if (!S.buildCoroutineParameterMoves(Loc))
614 return nullptr;
615
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000616 ScopeInfo->CoroutinePromise = S.buildCoroutinePromise(Loc);
617 if (!ScopeInfo->CoroutinePromise)
618 return nullptr;
619
620 return ScopeInfo;
621}
622
Eric Fiselierb936a392017-06-14 03:24:55 +0000623bool Sema::ActOnCoroutineBodyStart(Scope *SC, SourceLocation KWLoc,
624 StringRef Keyword) {
625 if (!checkCoroutineContext(*this, KWLoc, Keyword))
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000626 return false;
Eric Fiselierb936a392017-06-14 03:24:55 +0000627 auto *ScopeInfo = getCurFunction();
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000628 assert(ScopeInfo->CoroutinePromise);
629
630 // If we have existing coroutine statements then we have already built
631 // the initial and final suspend points.
632 if (!ScopeInfo->NeedsCoroutineSuspends)
633 return true;
634
635 ScopeInfo->setNeedsCoroutineSuspends(false);
636
Eric Fiselierb936a392017-06-14 03:24:55 +0000637 auto *Fn = cast<FunctionDecl>(CurContext);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000638 SourceLocation Loc = Fn->getLocation();
639 // Build the initial suspend point
640 auto buildSuspends = [&](StringRef Name) mutable -> StmtResult {
641 ExprResult Suspend =
Eric Fiselierb936a392017-06-14 03:24:55 +0000642 buildPromiseCall(*this, ScopeInfo->CoroutinePromise, Loc, Name, None);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000643 if (Suspend.isInvalid())
644 return StmtError();
Eric Fiselierb936a392017-06-14 03:24:55 +0000645 Suspend = buildOperatorCoawaitCall(*this, SC, Loc, Suspend.get());
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000646 if (Suspend.isInvalid())
647 return StmtError();
Eric Fiselierb936a392017-06-14 03:24:55 +0000648 Suspend = BuildResolvedCoawaitExpr(Loc, Suspend.get(),
649 /*IsImplicit*/ true);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +0000650 Suspend = ActOnFinishFullExpr(Suspend.get(), /*DiscardedValue*/ false);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000651 if (Suspend.isInvalid()) {
Eric Fiselierb936a392017-06-14 03:24:55 +0000652 Diag(Loc, diag::note_coroutine_promise_suspend_implicitly_required)
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000653 << ((Name == "initial_suspend") ? 0 : 1);
Eric Fiselierb936a392017-06-14 03:24:55 +0000654 Diag(KWLoc, diag::note_declared_coroutine_here) << Keyword;
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000655 return StmtError();
656 }
657 return cast<Stmt>(Suspend.get());
658 };
659
660 StmtResult InitSuspend = buildSuspends("initial_suspend");
661 if (InitSuspend.isInvalid())
662 return true;
663
664 StmtResult FinalSuspend = buildSuspends("final_suspend");
665 if (FinalSuspend.isInvalid())
666 return true;
667
668 ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());
669
670 return true;
671}
672
Richard Smith9f690bd2015-10-27 06:02:45 +0000673ExprResult Sema::ActOnCoawaitExpr(Scope *S, SourceLocation Loc, Expr *E) {
Eric Fiselierb936a392017-06-14 03:24:55 +0000674 if (!ActOnCoroutineBodyStart(S, Loc, "co_await")) {
Eric Fiseliera5465282016-09-29 21:47:39 +0000675 CorrectDelayedTyposInExpr(E);
676 return ExprError();
677 }
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000678
Richard Smith10610f72015-11-20 22:57:24 +0000679 if (E->getType()->isPlaceholderType()) {
680 ExprResult R = CheckPlaceholderExpr(E);
681 if (R.isInvalid()) return ExprError();
682 E = R.get();
683 }
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000684 ExprResult Lookup = buildOperatorCoawaitLookupExpr(*this, S, Loc);
685 if (Lookup.isInvalid())
686 return ExprError();
687 return BuildUnresolvedCoawaitExpr(Loc, E,
688 cast<UnresolvedLookupExpr>(Lookup.get()));
689}
Richard Smith10610f72015-11-20 22:57:24 +0000690
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000691ExprResult Sema::BuildUnresolvedCoawaitExpr(SourceLocation Loc, Expr *E,
Eric Fiseliercac0a592017-03-11 02:35:37 +0000692 UnresolvedLookupExpr *Lookup) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000693 auto *FSI = checkCoroutineContext(*this, Loc, "co_await");
694 if (!FSI)
695 return ExprError();
696
697 if (E->getType()->isPlaceholderType()) {
698 ExprResult R = CheckPlaceholderExpr(E);
699 if (R.isInvalid())
700 return ExprError();
701 E = R.get();
702 }
703
704 auto *Promise = FSI->CoroutinePromise;
705 if (Promise->getType()->isDependentType()) {
706 Expr *Res =
707 new (Context) DependentCoawaitExpr(Loc, Context.DependentTy, E, Lookup);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000708 return Res;
709 }
710
711 auto *RD = Promise->getType()->getAsCXXRecordDecl();
712 if (lookupMember(*this, "await_transform", RD, Loc)) {
713 ExprResult R = buildPromiseCall(*this, Promise, Loc, "await_transform", E);
714 if (R.isInvalid()) {
715 Diag(Loc,
716 diag::note_coroutine_promise_implicit_await_transform_required_here)
717 << E->getSourceRange();
718 return ExprError();
719 }
720 E = R.get();
721 }
722 ExprResult Awaitable = buildOperatorCoawaitCall(*this, Loc, E, Lookup);
Richard Smith9f690bd2015-10-27 06:02:45 +0000723 if (Awaitable.isInvalid())
724 return ExprError();
Eric Fiseliera5465282016-09-29 21:47:39 +0000725
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000726 return BuildResolvedCoawaitExpr(Loc, Awaitable.get());
Richard Smith9f690bd2015-10-27 06:02:45 +0000727}
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000728
729ExprResult Sema::BuildResolvedCoawaitExpr(SourceLocation Loc, Expr *E,
730 bool IsImplicit) {
Eric Fiseliercac0a592017-03-11 02:35:37 +0000731 auto *Coroutine = checkCoroutineContext(*this, Loc, "co_await", IsImplicit);
Richard Smith744b2242015-11-20 02:54:01 +0000732 if (!Coroutine)
733 return ExprError();
Richard Smith9f690bd2015-10-27 06:02:45 +0000734
Richard Smith9f690bd2015-10-27 06:02:45 +0000735 if (E->getType()->isPlaceholderType()) {
736 ExprResult R = CheckPlaceholderExpr(E);
737 if (R.isInvalid()) return ExprError();
738 E = R.get();
739 }
740
Richard Smith10610f72015-11-20 22:57:24 +0000741 if (E->getType()->isDependentType()) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000742 Expr *Res = new (Context)
743 CoawaitExpr(Loc, Context.DependentTy, E, IsImplicit);
Richard Smith10610f72015-11-20 22:57:24 +0000744 return Res;
745 }
746
Richard Smith1f38edd2015-11-22 03:13:02 +0000747 // If the expression is a temporary, materialize it as an lvalue so that we
748 // can use it multiple times.
749 if (E->getValueKind() == VK_RValue)
Tim Shen4a05bb82016-06-21 20:29:17 +0000750 E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
Richard Smith9f690bd2015-10-27 06:02:45 +0000751
Eric Fiselierd2e30d32018-03-27 03:15:46 +0000752 // The location of the `co_await` token cannot be used when constructing
753 // the member call expressions since it's before the location of `Expr`, which
754 // is used as the start of the member call expression.
755 SourceLocation CallLoc = E->getExprLoc();
756
Richard Smith9f690bd2015-10-27 06:02:45 +0000757 // Build the await_ready, await_suspend, await_resume calls.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000758 ReadySuspendResumeResult RSS =
Eric Fiselierd2e30d32018-03-27 03:15:46 +0000759 buildCoawaitCalls(*this, Coroutine->CoroutinePromise, CallLoc, E);
Richard Smith9f690bd2015-10-27 06:02:45 +0000760 if (RSS.IsInvalid)
761 return ExprError();
762
Gor Nishanovce43bd22017-03-11 01:30:17 +0000763 Expr *Res =
764 new (Context) CoawaitExpr(Loc, E, RSS.Results[0], RSS.Results[1],
765 RSS.Results[2], RSS.OpaqueValue, IsImplicit);
Eric Fiseliercac0a592017-03-11 02:35:37 +0000766
Richard Smithcfd53b42015-10-22 06:13:50 +0000767 return Res;
768}
769
Richard Smith9f690bd2015-10-27 06:02:45 +0000770ExprResult Sema::ActOnCoyieldExpr(Scope *S, SourceLocation Loc, Expr *E) {
Eric Fiselierb936a392017-06-14 03:24:55 +0000771 if (!ActOnCoroutineBodyStart(S, Loc, "co_yield")) {
Eric Fiseliera5465282016-09-29 21:47:39 +0000772 CorrectDelayedTyposInExpr(E);
Richard Smith23da82c2015-11-20 22:40:06 +0000773 return ExprError();
Eric Fiseliera5465282016-09-29 21:47:39 +0000774 }
Richard Smith23da82c2015-11-20 22:40:06 +0000775
776 // Build yield_value call.
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000777 ExprResult Awaitable = buildPromiseCall(
778 *this, getCurFunction()->CoroutinePromise, Loc, "yield_value", E);
Richard Smith9f690bd2015-10-27 06:02:45 +0000779 if (Awaitable.isInvalid())
780 return ExprError();
Richard Smith23da82c2015-11-20 22:40:06 +0000781
782 // Build 'operator co_await' call.
783 Awaitable = buildOperatorCoawaitCall(*this, S, Loc, Awaitable.get());
784 if (Awaitable.isInvalid())
785 return ExprError();
786
Richard Smith9f690bd2015-10-27 06:02:45 +0000787 return BuildCoyieldExpr(Loc, Awaitable.get());
788}
789ExprResult Sema::BuildCoyieldExpr(SourceLocation Loc, Expr *E) {
790 auto *Coroutine = checkCoroutineContext(*this, Loc, "co_yield");
Richard Smith744b2242015-11-20 02:54:01 +0000791 if (!Coroutine)
792 return ExprError();
Richard Smithcfd53b42015-10-22 06:13:50 +0000793
Richard Smith10610f72015-11-20 22:57:24 +0000794 if (E->getType()->isPlaceholderType()) {
795 ExprResult R = CheckPlaceholderExpr(E);
796 if (R.isInvalid()) return ExprError();
797 E = R.get();
798 }
799
Richard Smithd7bed4d2015-11-22 02:57:17 +0000800 if (E->getType()->isDependentType()) {
801 Expr *Res = new (Context) CoyieldExpr(Loc, Context.DependentTy, E);
Richard Smithd7bed4d2015-11-22 02:57:17 +0000802 return Res;
803 }
804
Richard Smith1f38edd2015-11-22 03:13:02 +0000805 // If the expression is a temporary, materialize it as an lvalue so that we
806 // can use it multiple times.
807 if (E->getValueKind() == VK_RValue)
Tim Shen4a05bb82016-06-21 20:29:17 +0000808 E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
Richard Smithd7bed4d2015-11-22 02:57:17 +0000809
810 // Build the await_ready, await_suspend, await_resume calls.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000811 ReadySuspendResumeResult RSS =
812 buildCoawaitCalls(*this, Coroutine->CoroutinePromise, Loc, E);
Richard Smithd7bed4d2015-11-22 02:57:17 +0000813 if (RSS.IsInvalid)
814 return ExprError();
815
Eric Fiselierb936a392017-06-14 03:24:55 +0000816 Expr *Res =
817 new (Context) CoyieldExpr(Loc, E, RSS.Results[0], RSS.Results[1],
818 RSS.Results[2], RSS.OpaqueValue);
Eric Fiseliercac0a592017-03-11 02:35:37 +0000819
Richard Smithcfd53b42015-10-22 06:13:50 +0000820 return Res;
821}
822
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000823StmtResult Sema::ActOnCoreturnStmt(Scope *S, SourceLocation Loc, Expr *E) {
Eric Fiselierb936a392017-06-14 03:24:55 +0000824 if (!ActOnCoroutineBodyStart(S, Loc, "co_return")) {
Eric Fiseliera5465282016-09-29 21:47:39 +0000825 CorrectDelayedTyposInExpr(E);
826 return StmtError();
827 }
Richard Smith9f690bd2015-10-27 06:02:45 +0000828 return BuildCoreturnStmt(Loc, E);
829}
Gor Nishanov3e048bb2016-10-04 00:31:16 +0000830
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000831StmtResult Sema::BuildCoreturnStmt(SourceLocation Loc, Expr *E,
832 bool IsImplicit) {
Eric Fiseliercac0a592017-03-11 02:35:37 +0000833 auto *FSI = checkCoroutineContext(*this, Loc, "co_return", IsImplicit);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000834 if (!FSI)
Richard Smith71d403e2015-11-22 07:33:28 +0000835 return StmtError();
836
837 if (E && E->getType()->isPlaceholderType() &&
838 !E->getType()->isSpecificPlaceholderType(BuiltinType::Overload)) {
Richard Smith10610f72015-11-20 22:57:24 +0000839 ExprResult R = CheckPlaceholderExpr(E);
840 if (R.isInvalid()) return StmtError();
841 E = R.get();
842 }
843
Brian Gesiak0b568302018-10-08 03:08:39 +0000844 // Move the return value if we can
845 if (E) {
846 auto NRVOCandidate = this->getCopyElisionCandidate(E->getType(), E, CES_AsIfByStdMove);
847 if (NRVOCandidate) {
848 InitializedEntity Entity =
849 InitializedEntity::InitializeResult(Loc, E->getType(), NRVOCandidate);
850 ExprResult MoveResult = this->PerformMoveOrCopyInitialization(
851 Entity, NRVOCandidate, E->getType(), E);
852 if (MoveResult.get())
853 E = MoveResult.get();
854 }
855 }
856
Richard Smith4ba66602015-11-22 07:05:16 +0000857 // FIXME: If the operand is a reference to a variable that's about to go out
Richard Smith2af65c42015-11-24 02:34:39 +0000858 // of scope, we should treat the operand as an xvalue for this overload
Richard Smith4ba66602015-11-22 07:05:16 +0000859 // resolution.
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000860 VarDecl *Promise = FSI->CoroutinePromise;
Richard Smith4ba66602015-11-22 07:05:16 +0000861 ExprResult PC;
Eric Fiselier98131312016-10-06 21:23:38 +0000862 if (E && (isa<InitListExpr>(E) || !E->getType()->isVoidType())) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000863 PC = buildPromiseCall(*this, Promise, Loc, "return_value", E);
Richard Smith4ba66602015-11-22 07:05:16 +0000864 } else {
865 E = MakeFullDiscardedValueExpr(E).get();
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000866 PC = buildPromiseCall(*this, Promise, Loc, "return_void", None);
Richard Smith4ba66602015-11-22 07:05:16 +0000867 }
868 if (PC.isInvalid())
869 return StmtError();
870
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +0000871 Expr *PCE = ActOnFinishFullExpr(PC.get(), /*DiscardedValue*/ false).get();
Richard Smith4ba66602015-11-22 07:05:16 +0000872
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000873 Stmt *Res = new (Context) CoreturnStmt(Loc, E, PCE, IsImplicit);
Richard Smithcfd53b42015-10-22 06:13:50 +0000874 return Res;
875}
876
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000877/// Look up the std::nothrow object.
878static Expr *buildStdNoThrowDeclRef(Sema &S, SourceLocation Loc) {
879 NamespaceDecl *Std = S.getStdNamespace();
880 assert(Std && "Should already be diagnosed");
881
882 LookupResult Result(S, &S.PP.getIdentifierTable().get("nothrow"), Loc,
883 Sema::LookupOrdinaryName);
884 if (!S.LookupQualifiedName(Result, Std)) {
885 // FIXME: <experimental/coroutine> should have been included already.
886 // If we require it to include <new> then this diagnostic is no longer
887 // needed.
888 S.Diag(Loc, diag::err_implicit_coroutine_std_nothrow_type_not_found);
889 return nullptr;
890 }
891
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000892 auto *VD = Result.getAsSingle<VarDecl>();
893 if (!VD) {
894 Result.suppressDiagnostics();
895 // We found something weird. Complain about the first thing we found.
896 NamedDecl *Found = *Result.begin();
897 S.Diag(Found->getLocation(), diag::err_malformed_std_nothrow);
898 return nullptr;
899 }
900
901 ExprResult DR = S.BuildDeclRefExpr(VD, VD->getType(), VK_LValue, Loc);
902 if (DR.isInvalid())
903 return nullptr;
904
905 return DR.get();
906}
907
Gor Nishanov8df64e92016-10-27 16:28:31 +0000908// Find an appropriate delete for the promise.
909static FunctionDecl *findDeleteForPromise(Sema &S, SourceLocation Loc,
910 QualType PromiseType) {
911 FunctionDecl *OperatorDelete = nullptr;
912
913 DeclarationName DeleteName =
914 S.Context.DeclarationNames.getCXXOperatorName(OO_Delete);
915
916 auto *PointeeRD = PromiseType->getAsCXXRecordDecl();
917 assert(PointeeRD && "PromiseType must be a CxxRecordDecl type");
918
919 if (S.FindDeallocationFunction(Loc, PointeeRD, DeleteName, OperatorDelete))
920 return nullptr;
921
922 if (!OperatorDelete) {
923 // Look for a global declaration.
924 const bool CanProvideSize = S.isCompleteType(Loc, PromiseType);
925 const bool Overaligned = false;
926 OperatorDelete = S.FindUsualDeallocationFunction(Loc, CanProvideSize,
927 Overaligned, DeleteName);
928 }
929 S.MarkFunctionReferenced(Loc, OperatorDelete);
930 return OperatorDelete;
931}
932
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000933
934void Sema::CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body) {
935 FunctionScopeInfo *Fn = getCurFunction();
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000936 assert(Fn && Fn->isCoroutine() && "not a coroutine");
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000937 if (!Body) {
938 assert(FD->isInvalidDecl() &&
939 "a null body is only allowed for invalid declarations");
940 return;
941 }
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000942 // We have a function that uses coroutine keywords, but we failed to build
943 // the promise type.
944 if (!Fn->CoroutinePromise)
945 return FD->setInvalidDecl();
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000946
947 if (isa<CoroutineBodyStmt>(Body)) {
Gor Nishanov29ff6382017-05-24 14:34:19 +0000948 // Nothing todo. the body is already a transformed coroutine body statement.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000949 return;
950 }
951
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000952 // Coroutines [stmt.return]p1:
953 // A return statement shall not appear in a coroutine.
954 if (Fn->FirstReturnLoc.isValid()) {
Eric Fiseliercac0a592017-03-11 02:35:37 +0000955 assert(Fn->FirstCoroutineStmtLoc.isValid() &&
956 "first coroutine location not set");
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000957 Diag(Fn->FirstReturnLoc, diag::err_return_in_coroutine);
Eric Fiseliercac0a592017-03-11 02:35:37 +0000958 Diag(Fn->FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
959 << Fn->getFirstCoroutineStmtKeyword();
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000960 }
Eric Fiselierbee782b2017-04-03 19:21:00 +0000961 CoroutineStmtBuilder Builder(*this, *FD, *Fn, Body);
962 if (Builder.isInvalid() || !Builder.buildStatements())
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000963 return FD->setInvalidDecl();
964
965 // Build body for the coroutine wrapper statement.
966 Body = CoroutineBodyStmt::Create(Context, Builder);
967}
968
Eric Fiselierbee782b2017-04-03 19:21:00 +0000969CoroutineStmtBuilder::CoroutineStmtBuilder(Sema &S, FunctionDecl &FD,
970 sema::FunctionScopeInfo &Fn,
971 Stmt *Body)
972 : S(S), FD(FD), Fn(Fn), Loc(FD.getLocation()),
973 IsPromiseDependentType(
974 !Fn.CoroutinePromise ||
975 Fn.CoroutinePromise->getType()->isDependentType()) {
976 this->Body = Body;
Brian Gesiak61f4ac92018-01-24 22:15:42 +0000977
978 for (auto KV : Fn.CoroutineParameterMoves)
979 this->ParamMovesVector.push_back(KV.second);
980 this->ParamMoves = this->ParamMovesVector;
981
Eric Fiselierbee782b2017-04-03 19:21:00 +0000982 if (!IsPromiseDependentType) {
983 PromiseRecordDecl = Fn.CoroutinePromise->getType()->getAsCXXRecordDecl();
984 assert(PromiseRecordDecl && "Type should have already been checked");
985 }
986 this->IsValid = makePromiseStmt() && makeInitialAndFinalSuspend();
987}
988
989bool CoroutineStmtBuilder::buildStatements() {
990 assert(this->IsValid && "coroutine already invalid");
Brian Gesiak61f4ac92018-01-24 22:15:42 +0000991 this->IsValid = makeReturnObject();
Eric Fiselierbee782b2017-04-03 19:21:00 +0000992 if (this->IsValid && !IsPromiseDependentType)
993 buildDependentStatements();
994 return this->IsValid;
995}
996
997bool CoroutineStmtBuilder::buildDependentStatements() {
998 assert(this->IsValid && "coroutine already invalid");
999 assert(!this->IsPromiseDependentType &&
1000 "coroutine cannot have a dependent promise type");
1001 this->IsValid = makeOnException() && makeOnFallthrough() &&
Gor Nishanov6a470682017-05-22 20:22:23 +00001002 makeGroDeclAndReturnStmt() && makeReturnOnAllocFailure() &&
1003 makeNewAndDeleteExpr();
Eric Fiselierbee782b2017-04-03 19:21:00 +00001004 return this->IsValid;
1005}
1006
1007bool CoroutineStmtBuilder::makePromiseStmt() {
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001008 // Form a declaration statement for the promise declaration, so that AST
1009 // visitors can more easily find it.
1010 StmtResult PromiseStmt =
1011 S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(Fn.CoroutinePromise), Loc, Loc);
1012 if (PromiseStmt.isInvalid())
1013 return false;
1014
1015 this->Promise = PromiseStmt.get();
1016 return true;
1017}
1018
Eric Fiselierbee782b2017-04-03 19:21:00 +00001019bool CoroutineStmtBuilder::makeInitialAndFinalSuspend() {
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001020 if (Fn.hasInvalidCoroutineSuspends())
1021 return false;
1022 this->InitialSuspend = cast<Expr>(Fn.CoroutineSuspends.first);
1023 this->FinalSuspend = cast<Expr>(Fn.CoroutineSuspends.second);
1024 return true;
1025}
1026
Gor Nishanov3aa9eb32017-03-27 23:36:59 +00001027static bool diagReturnOnAllocFailure(Sema &S, Expr *E,
1028 CXXRecordDecl *PromiseRecordDecl,
1029 FunctionScopeInfo &Fn) {
1030 auto Loc = E->getExprLoc();
1031 if (auto *DeclRef = dyn_cast_or_null<DeclRefExpr>(E)) {
1032 auto *Decl = DeclRef->getDecl();
1033 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Decl)) {
1034 if (Method->isStatic())
1035 return true;
1036 else
1037 Loc = Decl->getLocation();
1038 }
1039 }
1040
1041 S.Diag(
1042 Loc,
1043 diag::err_coroutine_promise_get_return_object_on_allocation_failure)
1044 << PromiseRecordDecl;
1045 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1046 << Fn.getFirstCoroutineStmtKeyword();
1047 return false;
1048}
1049
Eric Fiselierbee782b2017-04-03 19:21:00 +00001050bool CoroutineStmtBuilder::makeReturnOnAllocFailure() {
1051 assert(!IsPromiseDependentType &&
1052 "cannot make statement while the promise type is dependent");
Gor Nishanov3aa9eb32017-03-27 23:36:59 +00001053
1054 // [dcl.fct.def.coroutine]/8
1055 // The unqualified-id get_return_object_on_allocation_failure is looked up in
1056 // the scope of class P by class member access lookup (3.4.5). ...
1057 // If an allocation function returns nullptr, ... the coroutine return value
1058 // is obtained by a call to ... get_return_object_on_allocation_failure().
1059
1060 DeclarationName DN =
1061 S.PP.getIdentifierInfo("get_return_object_on_allocation_failure");
1062 LookupResult Found(S, DN, Loc, Sema::LookupMemberName);
Eric Fiselierbee782b2017-04-03 19:21:00 +00001063 if (!S.LookupQualifiedName(Found, PromiseRecordDecl))
1064 return true;
Gor Nishanov3aa9eb32017-03-27 23:36:59 +00001065
1066 CXXScopeSpec SS;
1067 ExprResult DeclNameExpr =
1068 S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
Eric Fiselierbee782b2017-04-03 19:21:00 +00001069 if (DeclNameExpr.isInvalid())
1070 return false;
Gor Nishanov3aa9eb32017-03-27 23:36:59 +00001071
1072 if (!diagReturnOnAllocFailure(S, DeclNameExpr.get(), PromiseRecordDecl, Fn))
1073 return false;
1074
1075 ExprResult ReturnObjectOnAllocationFailure =
1076 S.ActOnCallExpr(nullptr, DeclNameExpr.get(), Loc, {}, Loc);
Eric Fiselierbee782b2017-04-03 19:21:00 +00001077 if (ReturnObjectOnAllocationFailure.isInvalid())
1078 return false;
Gor Nishanov3aa9eb32017-03-27 23:36:59 +00001079
Gor Nishanovc4a19082017-03-28 02:51:45 +00001080 StmtResult ReturnStmt =
1081 S.BuildReturnStmt(Loc, ReturnObjectOnAllocationFailure.get());
Gor Nishanov6a470682017-05-22 20:22:23 +00001082 if (ReturnStmt.isInvalid()) {
Eric Fiselierfc50f622017-05-25 14:59:39 +00001083 S.Diag(Found.getFoundDecl()->getLocation(), diag::note_member_declared_here)
1084 << DN;
Gor Nishanov6a470682017-05-22 20:22:23 +00001085 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1086 << Fn.getFirstCoroutineStmtKeyword();
Eric Fiselierbee782b2017-04-03 19:21:00 +00001087 return false;
Gor Nishanov6a470682017-05-22 20:22:23 +00001088 }
Gor Nishanov3aa9eb32017-03-27 23:36:59 +00001089
1090 this->ReturnStmtOnAllocFailure = ReturnStmt.get();
1091 return true;
1092}
1093
Eric Fiselierbee782b2017-04-03 19:21:00 +00001094bool CoroutineStmtBuilder::makeNewAndDeleteExpr() {
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001095 // Form and check allocation and deallocation calls.
Eric Fiselierbee782b2017-04-03 19:21:00 +00001096 assert(!IsPromiseDependentType &&
1097 "cannot make statement while the promise type is dependent");
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001098 QualType PromiseType = Fn.CoroutinePromise->getType();
Gor Nishanov8df64e92016-10-27 16:28:31 +00001099
1100 if (S.RequireCompleteType(Loc, PromiseType, diag::err_incomplete_type))
1101 return false;
1102
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001103 const bool RequiresNoThrowAlloc = ReturnStmtOnAllocFailure != nullptr;
1104
Brian Gesiak98606222018-02-15 20:37:22 +00001105 // [dcl.fct.def.coroutine]/7
1106 // Lookup allocation functions using a parameter list composed of the
1107 // requested size of the coroutine state being allocated, followed by
1108 // the coroutine function's arguments. If a matching allocation function
1109 // exists, use it. Otherwise, use an allocation function that just takes
1110 // the requested size.
Gor Nishanov8df64e92016-10-27 16:28:31 +00001111
1112 FunctionDecl *OperatorNew = nullptr;
1113 FunctionDecl *OperatorDelete = nullptr;
1114 FunctionDecl *UnusedResult = nullptr;
1115 bool PassAlignment = false;
Eric Fiselierf747f532017-04-18 05:08:08 +00001116 SmallVector<Expr *, 1> PlacementArgs;
Gor Nishanov8df64e92016-10-27 16:28:31 +00001117
Brian Gesiak98606222018-02-15 20:37:22 +00001118 // [dcl.fct.def.coroutine]/7
1119 // "The allocation function’s name is looked up in the scope of P.
1120 // [...] If the lookup finds an allocation function in the scope of P,
1121 // overload resolution is performed on a function call created by assembling
1122 // an argument list. The first argument is the amount of space requested,
1123 // and has type std::size_t. The lvalues p1 ... pn are the succeeding
1124 // arguments."
1125 //
1126 // ...where "p1 ... pn" are defined earlier as:
1127 //
1128 // [dcl.fct.def.coroutine]/3
1129 // "For a coroutine f that is a non-static member function, let P1 denote the
1130 // type of the implicit object parameter (13.3.1) and P2 ... Pn be the types
1131 // of the function parameters; otherwise let P1 ... Pn be the types of the
1132 // function parameters. Let p1 ... pn be lvalues denoting those objects."
1133 if (auto *MD = dyn_cast<CXXMethodDecl>(&FD)) {
1134 if (MD->isInstance() && !isLambdaCallOperator(MD)) {
1135 ExprResult ThisExpr = S.ActOnCXXThis(Loc);
1136 if (ThisExpr.isInvalid())
1137 return false;
1138 ThisExpr = S.CreateBuiltinUnaryOp(Loc, UO_Deref, ThisExpr.get());
1139 if (ThisExpr.isInvalid())
1140 return false;
1141 PlacementArgs.push_back(ThisExpr.get());
1142 }
1143 }
1144 for (auto *PD : FD.parameters()) {
1145 if (PD->getType()->isDependentType())
1146 continue;
1147
1148 // Build a reference to the parameter.
1149 auto PDLoc = PD->getLocation();
1150 ExprResult PDRefExpr =
1151 S.BuildDeclRefExpr(PD, PD->getOriginalType().getNonReferenceType(),
1152 ExprValueKind::VK_LValue, PDLoc);
1153 if (PDRefExpr.isInvalid())
1154 return false;
1155
1156 PlacementArgs.push_back(PDRefExpr.get());
1157 }
Brian Gesiakcb024022018-04-01 22:59:22 +00001158 S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Class,
1159 /*DeleteScope*/ Sema::AFS_Both, PromiseType,
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001160 /*isArray*/ false, PassAlignment, PlacementArgs,
Brian Gesiak98606222018-02-15 20:37:22 +00001161 OperatorNew, UnusedResult, /*Diagnose*/ false);
1162
1163 // [dcl.fct.def.coroutine]/7
1164 // "If no matching function is found, overload resolution is performed again
1165 // on a function call created by passing just the amount of space required as
1166 // an argument of type std::size_t."
1167 if (!OperatorNew && !PlacementArgs.empty()) {
1168 PlacementArgs.clear();
Brian Gesiakcb024022018-04-01 22:59:22 +00001169 S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Class,
1170 /*DeleteScope*/ Sema::AFS_Both, PromiseType,
1171 /*isArray*/ false, PassAlignment, PlacementArgs,
1172 OperatorNew, UnusedResult, /*Diagnose*/ false);
1173 }
1174
1175 // [dcl.fct.def.coroutine]/7
1176 // "The allocation function’s name is looked up in the scope of P. If this
1177 // lookup fails, the allocation function’s name is looked up in the global
1178 // scope."
1179 if (!OperatorNew) {
1180 S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Global,
1181 /*DeleteScope*/ Sema::AFS_Both, PromiseType,
1182 /*isArray*/ false, PassAlignment, PlacementArgs,
1183 OperatorNew, UnusedResult);
Brian Gesiak98606222018-02-15 20:37:22 +00001184 }
Gor Nishanov8df64e92016-10-27 16:28:31 +00001185
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001186 bool IsGlobalOverload =
1187 OperatorNew && !isa<CXXRecordDecl>(OperatorNew->getDeclContext());
1188 // If we didn't find a class-local new declaration and non-throwing new
1189 // was is required then we need to lookup the non-throwing global operator
1190 // instead.
1191 if (RequiresNoThrowAlloc && (!OperatorNew || IsGlobalOverload)) {
1192 auto *StdNoThrow = buildStdNoThrowDeclRef(S, Loc);
1193 if (!StdNoThrow)
1194 return false;
Eric Fiselierf747f532017-04-18 05:08:08 +00001195 PlacementArgs = {StdNoThrow};
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001196 OperatorNew = nullptr;
Brian Gesiakcb024022018-04-01 22:59:22 +00001197 S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Both,
1198 /*DeleteScope*/ Sema::AFS_Both, PromiseType,
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001199 /*isArray*/ false, PassAlignment, PlacementArgs,
1200 OperatorNew, UnusedResult);
1201 }
Gor Nishanov8df64e92016-10-27 16:28:31 +00001202
Brian Gesiak98606222018-02-15 20:37:22 +00001203 if (!OperatorNew)
1204 return false;
Eric Fiselierc5128752017-04-18 05:30:39 +00001205
1206 if (RequiresNoThrowAlloc) {
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001207 const auto *FT = OperatorNew->getType()->getAs<FunctionProtoType>();
Richard Smitheaf11ad2018-05-03 03:58:32 +00001208 if (!FT->isNothrow(/*ResultIfDependent*/ false)) {
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001209 S.Diag(OperatorNew->getLocation(),
1210 diag::err_coroutine_promise_new_requires_nothrow)
1211 << OperatorNew;
1212 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
1213 << OperatorNew;
1214 return false;
1215 }
1216 }
1217
1218 if ((OperatorDelete = findDeleteForPromise(S, Loc, PromiseType)) == nullptr)
Gor Nishanov8df64e92016-10-27 16:28:31 +00001219 return false;
1220
1221 Expr *FramePtr =
1222 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_frame, {});
1223
1224 Expr *FrameSize =
1225 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_size, {});
1226
1227 // Make new call.
1228
1229 ExprResult NewRef =
1230 S.BuildDeclRefExpr(OperatorNew, OperatorNew->getType(), VK_LValue, Loc);
1231 if (NewRef.isInvalid())
1232 return false;
1233
Eric Fiselierf747f532017-04-18 05:08:08 +00001234 SmallVector<Expr *, 2> NewArgs(1, FrameSize);
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001235 for (auto Arg : PlacementArgs)
1236 NewArgs.push_back(Arg);
1237
Gor Nishanov8df64e92016-10-27 16:28:31 +00001238 ExprResult NewExpr =
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001239 S.ActOnCallExpr(S.getCurScope(), NewRef.get(), Loc, NewArgs, Loc);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00001240 NewExpr = S.ActOnFinishFullExpr(NewExpr.get(), /*DiscardedValue*/ false);
Gor Nishanov8df64e92016-10-27 16:28:31 +00001241 if (NewExpr.isInvalid())
1242 return false;
1243
Gor Nishanov8df64e92016-10-27 16:28:31 +00001244 // Make delete call.
1245
1246 QualType OpDeleteQualType = OperatorDelete->getType();
1247
1248 ExprResult DeleteRef =
1249 S.BuildDeclRefExpr(OperatorDelete, OpDeleteQualType, VK_LValue, Loc);
1250 if (DeleteRef.isInvalid())
1251 return false;
1252
1253 Expr *CoroFree =
1254 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_free, {FramePtr});
1255
1256 SmallVector<Expr *, 2> DeleteArgs{CoroFree};
1257
1258 // Check if we need to pass the size.
1259 const auto *OpDeleteType =
1260 OpDeleteQualType.getTypePtr()->getAs<FunctionProtoType>();
1261 if (OpDeleteType->getNumParams() > 1)
1262 DeleteArgs.push_back(FrameSize);
1263
1264 ExprResult DeleteExpr =
1265 S.ActOnCallExpr(S.getCurScope(), DeleteRef.get(), Loc, DeleteArgs, Loc);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00001266 DeleteExpr =
1267 S.ActOnFinishFullExpr(DeleteExpr.get(), /*DiscardedValue*/ false);
Gor Nishanov8df64e92016-10-27 16:28:31 +00001268 if (DeleteExpr.isInvalid())
1269 return false;
1270
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001271 this->Allocate = NewExpr.get();
1272 this->Deallocate = DeleteExpr.get();
Gor Nishanov8df64e92016-10-27 16:28:31 +00001273
1274 return true;
1275}
1276
Eric Fiselierbee782b2017-04-03 19:21:00 +00001277bool CoroutineStmtBuilder::makeOnFallthrough() {
1278 assert(!IsPromiseDependentType &&
1279 "cannot make statement while the promise type is dependent");
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001280
1281 // [dcl.fct.def.coroutine]/4
1282 // The unqualified-ids 'return_void' and 'return_value' are looked up in
1283 // the scope of class P. If both are found, the program is ill-formed.
Eric Fiselierfc50f622017-05-25 14:59:39 +00001284 bool HasRVoid, HasRValue;
1285 LookupResult LRVoid =
1286 lookupMember(S, "return_void", PromiseRecordDecl, Loc, HasRVoid);
1287 LookupResult LRValue =
1288 lookupMember(S, "return_value", PromiseRecordDecl, Loc, HasRValue);
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001289
Eric Fiselier709d1b32016-10-27 07:30:31 +00001290 StmtResult Fallthrough;
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001291 if (HasRVoid && HasRValue) {
1292 // FIXME Improve this diagnostic
Eric Fiselierfc50f622017-05-25 14:59:39 +00001293 S.Diag(FD.getLocation(),
1294 diag::err_coroutine_promise_incompatible_return_functions)
1295 << PromiseRecordDecl;
1296 S.Diag(LRVoid.getRepresentativeDecl()->getLocation(),
1297 diag::note_member_first_declared_here)
1298 << LRVoid.getLookupName();
1299 S.Diag(LRValue.getRepresentativeDecl()->getLocation(),
1300 diag::note_member_first_declared_here)
1301 << LRValue.getLookupName();
1302 return false;
1303 } else if (!HasRVoid && !HasRValue) {
1304 // FIXME: The PDTS currently specifies this case as UB, not ill-formed.
1305 // However we still diagnose this as an error since until the PDTS is fixed.
1306 S.Diag(FD.getLocation(),
1307 diag::err_coroutine_promise_requires_return_function)
1308 << PromiseRecordDecl;
1309 S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here)
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001310 << PromiseRecordDecl;
1311 return false;
1312 } else if (HasRVoid) {
1313 // If the unqualified-id return_void is found, flowing off the end of a
1314 // coroutine is equivalent to a co_return with no operand. Otherwise,
1315 // flowing off the end of a coroutine results in undefined behavior.
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001316 Fallthrough = S.BuildCoreturnStmt(FD.getLocation(), nullptr,
1317 /*IsImplicit*/false);
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001318 Fallthrough = S.ActOnFinishFullStmt(Fallthrough.get());
1319 if (Fallthrough.isInvalid())
1320 return false;
Eric Fiselier709d1b32016-10-27 07:30:31 +00001321 }
Richard Smith2af65c42015-11-24 02:34:39 +00001322
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001323 this->OnFallthrough = Fallthrough.get();
1324 return true;
1325}
1326
Eric Fiselierbee782b2017-04-03 19:21:00 +00001327bool CoroutineStmtBuilder::makeOnException() {
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001328 // Try to form 'p.unhandled_exception();'
Eric Fiselierbee782b2017-04-03 19:21:00 +00001329 assert(!IsPromiseDependentType &&
1330 "cannot make statement while the promise type is dependent");
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001331
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001332 const bool RequireUnhandledException = S.getLangOpts().CXXExceptions;
1333
1334 if (!lookupMember(S, "unhandled_exception", PromiseRecordDecl, Loc)) {
1335 auto DiagID =
1336 RequireUnhandledException
1337 ? diag::err_coroutine_promise_unhandled_exception_required
1338 : diag::
1339 warn_coroutine_promise_unhandled_exception_required_with_exceptions;
1340 S.Diag(Loc, DiagID) << PromiseRecordDecl;
Gor Nishanov29ff6382017-05-24 14:34:19 +00001341 S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here)
1342 << PromiseRecordDecl;
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001343 return !RequireUnhandledException;
1344 }
1345
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001346 // If exceptions are disabled, don't try to build OnException.
1347 if (!S.getLangOpts().CXXExceptions)
1348 return true;
1349
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001350 ExprResult UnhandledException = buildPromiseCall(S, Fn.CoroutinePromise, Loc,
1351 "unhandled_exception", None);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00001352 UnhandledException = S.ActOnFinishFullExpr(UnhandledException.get(), Loc,
1353 /*DiscardedValue*/ false);
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001354 if (UnhandledException.isInvalid())
1355 return false;
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001356
Gor Nishanov5b050e42017-05-22 22:33:17 +00001357 // Since the body of the coroutine will be wrapped in try-catch, it will
1358 // be incompatible with SEH __try if present in a function.
1359 if (!S.getLangOpts().Borland && Fn.FirstSEHTryLoc.isValid()) {
1360 S.Diag(Fn.FirstSEHTryLoc, diag::err_seh_in_a_coroutine_with_cxx_exceptions);
1361 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1362 << Fn.getFirstCoroutineStmtKeyword();
1363 return false;
1364 }
1365
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001366 this->OnException = UnhandledException.get();
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001367 return true;
1368}
1369
Eric Fiselierbee782b2017-04-03 19:21:00 +00001370bool CoroutineStmtBuilder::makeReturnObject() {
Richard Smith2af65c42015-11-24 02:34:39 +00001371 // Build implicit 'p.get_return_object()' expression and form initialization
1372 // of return type from it.
1373 ExprResult ReturnObject =
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001374 buildPromiseCall(S, Fn.CoroutinePromise, Loc, "get_return_object", None);
Richard Smith2af65c42015-11-24 02:34:39 +00001375 if (ReturnObject.isInvalid())
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001376 return false;
Richard Smith2af65c42015-11-24 02:34:39 +00001377
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001378 this->ReturnValue = ReturnObject.get();
1379 return true;
1380}
1381
Gor Nishanov6a470682017-05-22 20:22:23 +00001382static void noteMemberDeclaredHere(Sema &S, Expr *E, FunctionScopeInfo &Fn) {
1383 if (auto *MbrRef = dyn_cast<CXXMemberCallExpr>(E)) {
1384 auto *MethodDecl = MbrRef->getMethodDecl();
Eric Fiselierfc50f622017-05-25 14:59:39 +00001385 S.Diag(MethodDecl->getLocation(), diag::note_member_declared_here)
1386 << MethodDecl;
Gor Nishanov6a470682017-05-22 20:22:23 +00001387 }
1388 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1389 << Fn.getFirstCoroutineStmtKeyword();
1390}
1391
1392bool CoroutineStmtBuilder::makeGroDeclAndReturnStmt() {
1393 assert(!IsPromiseDependentType &&
1394 "cannot make statement while the promise type is dependent");
1395 assert(this->ReturnValue && "ReturnValue must be already formed");
1396
1397 QualType const GroType = this->ReturnValue->getType();
1398 assert(!GroType->isDependentType() &&
1399 "get_return_object type must no longer be dependent");
1400
1401 QualType const FnRetType = FD.getReturnType();
1402 assert(!FnRetType->isDependentType() &&
1403 "get_return_object type must no longer be dependent");
1404
1405 if (FnRetType->isVoidType()) {
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00001406 ExprResult Res =
1407 S.ActOnFinishFullExpr(this->ReturnValue, Loc, /*DiscardedValue*/ false);
Gor Nishanov6a470682017-05-22 20:22:23 +00001408 if (Res.isInvalid())
1409 return false;
1410
1411 this->ResultDecl = Res.get();
1412 return true;
1413 }
1414
1415 if (GroType->isVoidType()) {
1416 // Trigger a nice error message.
1417 InitializedEntity Entity =
1418 InitializedEntity::InitializeResult(Loc, FnRetType, false);
1419 S.PerformMoveOrCopyInitialization(Entity, nullptr, FnRetType, ReturnValue);
1420 noteMemberDeclaredHere(S, ReturnValue, Fn);
1421 return false;
1422 }
1423
1424 auto *GroDecl = VarDecl::Create(
1425 S.Context, &FD, FD.getLocation(), FD.getLocation(),
1426 &S.PP.getIdentifierTable().get("__coro_gro"), GroType,
1427 S.Context.getTrivialTypeSourceInfo(GroType, Loc), SC_None);
1428
1429 S.CheckVariableDeclarationType(GroDecl);
1430 if (GroDecl->isInvalidDecl())
1431 return false;
1432
1433 InitializedEntity Entity = InitializedEntity::InitializeVariable(GroDecl);
1434 ExprResult Res = S.PerformMoveOrCopyInitialization(Entity, nullptr, GroType,
1435 this->ReturnValue);
1436 if (Res.isInvalid())
1437 return false;
1438
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00001439 Res = S.ActOnFinishFullExpr(Res.get(), /*DiscardedValue*/ false);
Gor Nishanov6a470682017-05-22 20:22:23 +00001440 if (Res.isInvalid())
1441 return false;
1442
Gor Nishanov6a470682017-05-22 20:22:23 +00001443 S.AddInitializerToDecl(GroDecl, Res.get(),
1444 /*DirectInit=*/false);
1445
1446 S.FinalizeDeclaration(GroDecl);
1447
1448 // Form a declaration statement for the return declaration, so that AST
1449 // visitors can more easily find it.
1450 StmtResult GroDeclStmt =
1451 S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(GroDecl), Loc, Loc);
1452 if (GroDeclStmt.isInvalid())
1453 return false;
1454
1455 this->ResultDecl = GroDeclStmt.get();
1456
1457 ExprResult declRef = S.BuildDeclRefExpr(GroDecl, GroType, VK_LValue, Loc);
1458 if (declRef.isInvalid())
1459 return false;
1460
1461 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, declRef.get());
1462 if (ReturnStmt.isInvalid()) {
1463 noteMemberDeclaredHere(S, ReturnValue, Fn);
1464 return false;
1465 }
Eric Fiselier8ed97272018-02-01 23:47:54 +00001466 if (cast<clang::ReturnStmt>(ReturnStmt.get())->getNRVOCandidate() == GroDecl)
1467 GroDecl->setNRVOVariable(true);
Gor Nishanov6a470682017-05-22 20:22:23 +00001468
1469 this->ReturnStmt = ReturnStmt.get();
1470 return true;
1471}
1472
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001473// Create a static_cast\<T&&>(expr).
1474static Expr *castForMoving(Sema &S, Expr *E, QualType T = QualType()) {
1475 if (T.isNull())
1476 T = E->getType();
1477 QualType TargetType = S.BuildReferenceType(
1478 T, /*SpelledAsLValue*/ false, SourceLocation(), DeclarationName());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001479 SourceLocation ExprLoc = E->getBeginLoc();
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001480 TypeSourceInfo *TargetLoc =
1481 S.Context.getTrivialTypeSourceInfo(TargetType, ExprLoc);
1482
1483 return S
1484 .BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
1485 SourceRange(ExprLoc, ExprLoc), E->getSourceRange())
1486 .get();
1487}
1488
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001489/// Build a variable declaration for move parameter.
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001490static VarDecl *buildVarDecl(Sema &S, SourceLocation Loc, QualType Type,
Eric Fiselierde7943b2017-06-03 00:22:18 +00001491 IdentifierInfo *II) {
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001492 TypeSourceInfo *TInfo = S.Context.getTrivialTypeSourceInfo(Type, Loc);
Brian Gesiak61f4ac92018-01-24 22:15:42 +00001493 VarDecl *Decl = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, II, Type,
1494 TInfo, SC_None);
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001495 Decl->setImplicit();
1496 return Decl;
1497}
1498
Brian Gesiak61f4ac92018-01-24 22:15:42 +00001499// Build statements that move coroutine function parameters to the coroutine
1500// frame, and store them on the function scope info.
1501bool Sema::buildCoroutineParameterMoves(SourceLocation Loc) {
1502 assert(isa<FunctionDecl>(CurContext) && "not in a function scope");
1503 auto *FD = cast<FunctionDecl>(CurContext);
1504
1505 auto *ScopeInfo = getCurFunction();
1506 assert(ScopeInfo->CoroutineParameterMoves.empty() &&
1507 "Should not build parameter moves twice");
1508
1509 for (auto *PD : FD->parameters()) {
1510 if (PD->getType()->isDependentType())
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001511 continue;
1512
Brian Gesiak98606222018-02-15 20:37:22 +00001513 ExprResult PDRefExpr =
1514 BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
1515 ExprValueKind::VK_LValue, Loc); // FIXME: scope?
1516 if (PDRefExpr.isInvalid())
1517 return false;
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001518
Brian Gesiak98606222018-02-15 20:37:22 +00001519 Expr *CExpr = nullptr;
1520 if (PD->getType()->getAsCXXRecordDecl() ||
1521 PD->getType()->isRValueReferenceType())
1522 CExpr = castForMoving(*this, PDRefExpr.get());
1523 else
1524 CExpr = PDRefExpr.get();
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001525
Brian Gesiak98606222018-02-15 20:37:22 +00001526 auto D = buildVarDecl(*this, Loc, PD->getType(), PD->getIdentifier());
1527 AddInitializerToDecl(D, CExpr, /*DirectInit=*/true);
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001528
Brian Gesiak98606222018-02-15 20:37:22 +00001529 // Convert decl to a statement.
1530 StmtResult Stmt = ActOnDeclStmt(ConvertDeclToDeclGroup(D), Loc, Loc);
1531 if (Stmt.isInvalid())
1532 return false;
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001533
Brian Gesiak98606222018-02-15 20:37:22 +00001534 ScopeInfo->CoroutineParameterMoves.insert(std::make_pair(PD, Stmt.get()));
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001535 }
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001536 return true;
Richard Smithcfd53b42015-10-22 06:13:50 +00001537}
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001538
1539StmtResult Sema::BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
1540 CoroutineBodyStmt *Res = CoroutineBodyStmt::Create(Context, Args);
1541 if (!Res)
1542 return StmtError();
1543 return Res;
1544}
Brian Gesiak3e65d9a2018-07-14 18:21:44 +00001545
1546ClassTemplateDecl *Sema::lookupCoroutineTraits(SourceLocation KwLoc,
1547 SourceLocation FuncLoc) {
1548 if (!StdCoroutineTraitsCache) {
1549 if (auto StdExp = lookupStdExperimentalNamespace()) {
1550 LookupResult Result(*this,
1551 &PP.getIdentifierTable().get("coroutine_traits"),
1552 FuncLoc, LookupOrdinaryName);
1553 if (!LookupQualifiedName(Result, StdExp)) {
1554 Diag(KwLoc, diag::err_implied_coroutine_type_not_found)
1555 << "std::experimental::coroutine_traits";
1556 return nullptr;
1557 }
1558 if (!(StdCoroutineTraitsCache =
1559 Result.getAsSingle<ClassTemplateDecl>())) {
1560 Result.suppressDiagnostics();
1561 NamedDecl *Found = *Result.begin();
1562 Diag(Found->getLocation(), diag::err_malformed_std_coroutine_traits);
1563 return nullptr;
1564 }
1565 }
1566 }
1567 return StdCoroutineTraitsCache;
1568}