blob: 857dcda4e6e4d22d293397729e0fe37e9cb72159 [file] [log] [blame]
Richard Smithcfd53b42015-10-22 06:13:50 +00001//===--- SemaCoroutines.cpp - Semantic Analysis for Coroutines ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ Coroutines.
11//
12//===----------------------------------------------------------------------===//
13
Eric Fiselierbee782b2017-04-03 19:21:00 +000014#include "CoroutineStmtBuilder.h"
Richard Smith9f690bd2015-10-27 06:02:45 +000015#include "clang/AST/Decl.h"
16#include "clang/AST/ExprCXX.h"
17#include "clang/AST/StmtCXX.h"
18#include "clang/Lex/Preprocessor.h"
Richard Smith2af65c42015-11-24 02:34:39 +000019#include "clang/Sema/Initialization.h"
Richard Smith9f690bd2015-10-27 06:02:45 +000020#include "clang/Sema/Overload.h"
Eric Fiselierbee782b2017-04-03 19:21:00 +000021#include "clang/Sema/SemaInternal.h"
22
Richard Smithcfd53b42015-10-22 06:13:50 +000023using namespace clang;
24using namespace sema;
25
Eric Fiselier20f25cb2017-03-06 23:38:15 +000026static bool lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD,
27 SourceLocation Loc) {
28 DeclarationName DN = S.PP.getIdentifierInfo(Name);
29 LookupResult LR(S, DN, Loc, Sema::LookupMemberName);
30 // Suppress diagnostics when a private member is selected. The same warnings
31 // will be produced again when building the call.
32 LR.suppressDiagnostics();
33 return S.LookupQualifiedName(LR, RD);
34}
35
Richard Smith9f690bd2015-10-27 06:02:45 +000036/// Look up the std::coroutine_traits<...>::promise_type for the given
37/// function type.
38static QualType lookupPromiseType(Sema &S, const FunctionProtoType *FnType,
Eric Fiselier89bf0e72017-03-06 22:52:28 +000039 SourceLocation KwLoc,
40 SourceLocation FuncLoc) {
Richard Smith9f690bd2015-10-27 06:02:45 +000041 // FIXME: Cache std::coroutine_traits once we've found it.
Gor Nishanov3e048bb2016-10-04 00:31:16 +000042 NamespaceDecl *StdExp = S.lookupStdExperimentalNamespace();
43 if (!StdExp) {
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +000044 S.Diag(KwLoc, diag::err_implied_coroutine_type_not_found)
45 << "std::experimental::coroutine_traits";
Richard Smith9f690bd2015-10-27 06:02:45 +000046 return QualType();
47 }
48
49 LookupResult Result(S, &S.PP.getIdentifierTable().get("coroutine_traits"),
Eric Fiselier89bf0e72017-03-06 22:52:28 +000050 FuncLoc, Sema::LookupOrdinaryName);
Gor Nishanov3e048bb2016-10-04 00:31:16 +000051 if (!S.LookupQualifiedName(Result, StdExp)) {
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +000052 S.Diag(KwLoc, diag::err_implied_coroutine_type_not_found)
53 << "std::experimental::coroutine_traits";
Richard Smith9f690bd2015-10-27 06:02:45 +000054 return QualType();
55 }
56
57 ClassTemplateDecl *CoroTraits = Result.getAsSingle<ClassTemplateDecl>();
58 if (!CoroTraits) {
59 Result.suppressDiagnostics();
60 // We found something weird. Complain about the first thing we found.
61 NamedDecl *Found = *Result.begin();
62 S.Diag(Found->getLocation(), diag::err_malformed_std_coroutine_traits);
63 return QualType();
64 }
65
66 // Form template argument list for coroutine_traits<R, P1, P2, ...>.
Eric Fiselier89bf0e72017-03-06 22:52:28 +000067 TemplateArgumentListInfo Args(KwLoc, KwLoc);
Richard Smith9f690bd2015-10-27 06:02:45 +000068 Args.addArgument(TemplateArgumentLoc(
69 TemplateArgument(FnType->getReturnType()),
Eric Fiselier89bf0e72017-03-06 22:52:28 +000070 S.Context.getTrivialTypeSourceInfo(FnType->getReturnType(), KwLoc)));
Richard Smith71d403e2015-11-22 07:33:28 +000071 // FIXME: If the function is a non-static member function, add the type
72 // of the implicit object parameter before the formal parameters.
Richard Smith9f690bd2015-10-27 06:02:45 +000073 for (QualType T : FnType->getParamTypes())
74 Args.addArgument(TemplateArgumentLoc(
Eric Fiselier89bf0e72017-03-06 22:52:28 +000075 TemplateArgument(T), S.Context.getTrivialTypeSourceInfo(T, KwLoc)));
Richard Smith9f690bd2015-10-27 06:02:45 +000076
77 // Build the template-id.
78 QualType CoroTrait =
Eric Fiselier89bf0e72017-03-06 22:52:28 +000079 S.CheckTemplateIdType(TemplateName(CoroTraits), KwLoc, Args);
Richard Smith9f690bd2015-10-27 06:02:45 +000080 if (CoroTrait.isNull())
81 return QualType();
Eric Fiselier89bf0e72017-03-06 22:52:28 +000082 if (S.RequireCompleteType(KwLoc, CoroTrait,
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +000083 diag::err_coroutine_type_missing_specialization))
Richard Smith9f690bd2015-10-27 06:02:45 +000084 return QualType();
85
Eric Fiselier89bf0e72017-03-06 22:52:28 +000086 auto *RD = CoroTrait->getAsCXXRecordDecl();
Richard Smith9f690bd2015-10-27 06:02:45 +000087 assert(RD && "specialization of class template is not a class?");
88
89 // Look up the ::promise_type member.
Eric Fiselier89bf0e72017-03-06 22:52:28 +000090 LookupResult R(S, &S.PP.getIdentifierTable().get("promise_type"), KwLoc,
Richard Smith9f690bd2015-10-27 06:02:45 +000091 Sema::LookupOrdinaryName);
92 S.LookupQualifiedName(R, RD);
93 auto *Promise = R.getAsSingle<TypeDecl>();
94 if (!Promise) {
Eric Fiselier89bf0e72017-03-06 22:52:28 +000095 S.Diag(FuncLoc,
96 diag::err_implied_std_coroutine_traits_promise_type_not_found)
Gor Nishanov8df64e92016-10-27 16:28:31 +000097 << RD;
Richard Smith9f690bd2015-10-27 06:02:45 +000098 return QualType();
99 }
Richard Smith9f690bd2015-10-27 06:02:45 +0000100 // The promise type is required to be a class type.
101 QualType PromiseType = S.Context.getTypeDeclType(Promise);
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000102
103 auto buildElaboratedType = [&]() {
Gor Nishanov3e048bb2016-10-04 00:31:16 +0000104 auto *NNS = NestedNameSpecifier::Create(S.Context, nullptr, StdExp);
Richard Smith9b2f53e2015-11-19 02:36:35 +0000105 NNS = NestedNameSpecifier::Create(S.Context, NNS, false,
106 CoroTrait.getTypePtr());
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000107 return S.Context.getElaboratedType(ETK_None, NNS, PromiseType);
108 };
Richard Smith9b2f53e2015-11-19 02:36:35 +0000109
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000110 if (!PromiseType->getAsCXXRecordDecl()) {
111 S.Diag(FuncLoc,
112 diag::err_implied_std_coroutine_traits_promise_type_not_class)
113 << buildElaboratedType();
Richard Smith9f690bd2015-10-27 06:02:45 +0000114 return QualType();
115 }
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000116 if (S.RequireCompleteType(FuncLoc, buildElaboratedType(),
117 diag::err_coroutine_promise_type_incomplete))
118 return QualType();
Richard Smith9f690bd2015-10-27 06:02:45 +0000119
120 return PromiseType;
121}
122
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000123/// Look up the std::coroutine_traits<...>::promise_type for the given
124/// function type.
125static QualType lookupCoroutineHandleType(Sema &S, QualType PromiseType,
126 SourceLocation Loc) {
127 if (PromiseType.isNull())
128 return QualType();
129
130 NamespaceDecl *StdExp = S.lookupStdExperimentalNamespace();
131 assert(StdExp && "Should already be diagnosed");
132
133 LookupResult Result(S, &S.PP.getIdentifierTable().get("coroutine_handle"),
134 Loc, Sema::LookupOrdinaryName);
135 if (!S.LookupQualifiedName(Result, StdExp)) {
136 S.Diag(Loc, diag::err_implied_coroutine_type_not_found)
137 << "std::experimental::coroutine_handle";
138 return QualType();
139 }
140
141 ClassTemplateDecl *CoroHandle = Result.getAsSingle<ClassTemplateDecl>();
142 if (!CoroHandle) {
143 Result.suppressDiagnostics();
144 // We found something weird. Complain about the first thing we found.
145 NamedDecl *Found = *Result.begin();
146 S.Diag(Found->getLocation(), diag::err_malformed_std_coroutine_handle);
147 return QualType();
148 }
149
150 // Form template argument list for coroutine_handle<Promise>.
151 TemplateArgumentListInfo Args(Loc, Loc);
152 Args.addArgument(TemplateArgumentLoc(
153 TemplateArgument(PromiseType),
154 S.Context.getTrivialTypeSourceInfo(PromiseType, Loc)));
155
156 // Build the template-id.
157 QualType CoroHandleType =
158 S.CheckTemplateIdType(TemplateName(CoroHandle), Loc, Args);
159 if (CoroHandleType.isNull())
160 return QualType();
161 if (S.RequireCompleteType(Loc, CoroHandleType,
162 diag::err_coroutine_type_missing_specialization))
163 return QualType();
164
165 return CoroHandleType;
166}
167
Eric Fiselierc8efda72016-10-27 18:43:28 +0000168static bool isValidCoroutineContext(Sema &S, SourceLocation Loc,
169 StringRef Keyword) {
Richard Smith744b2242015-11-20 02:54:01 +0000170 // 'co_await' and 'co_yield' are not permitted in unevaluated operands.
171 if (S.isUnevaluatedContext()) {
172 S.Diag(Loc, diag::err_coroutine_unevaluated_context) << Keyword;
Eric Fiselierc8efda72016-10-27 18:43:28 +0000173 return false;
Richard Smith744b2242015-11-20 02:54:01 +0000174 }
Richard Smithcfd53b42015-10-22 06:13:50 +0000175
176 // Any other usage must be within a function.
177 auto *FD = dyn_cast<FunctionDecl>(S.CurContext);
178 if (!FD) {
179 S.Diag(Loc, isa<ObjCMethodDecl>(S.CurContext)
180 ? diag::err_coroutine_objc_method
181 : diag::err_coroutine_outside_function) << Keyword;
Eric Fiselierc8efda72016-10-27 18:43:28 +0000182 return false;
Richard Smithcfd53b42015-10-22 06:13:50 +0000183 }
184
Eric Fiselierc8efda72016-10-27 18:43:28 +0000185 // An enumeration for mapping the diagnostic type to the correct diagnostic
186 // selection index.
187 enum InvalidFuncDiag {
188 DiagCtor = 0,
189 DiagDtor,
190 DiagCopyAssign,
191 DiagMoveAssign,
192 DiagMain,
193 DiagConstexpr,
194 DiagAutoRet,
195 DiagVarargs,
196 };
197 bool Diagnosed = false;
198 auto DiagInvalid = [&](InvalidFuncDiag ID) {
199 S.Diag(Loc, diag::err_coroutine_invalid_func_context) << ID << Keyword;
200 Diagnosed = true;
201 return false;
202 };
203
204 // Diagnose when a constructor, destructor, copy/move assignment operator,
205 // or the function 'main' are declared as a coroutine.
206 auto *MD = dyn_cast<CXXMethodDecl>(FD);
207 if (MD && isa<CXXConstructorDecl>(MD))
208 return DiagInvalid(DiagCtor);
209 else if (MD && isa<CXXDestructorDecl>(MD))
210 return DiagInvalid(DiagDtor);
211 else if (MD && MD->isCopyAssignmentOperator())
212 return DiagInvalid(DiagCopyAssign);
213 else if (MD && MD->isMoveAssignmentOperator())
214 return DiagInvalid(DiagMoveAssign);
215 else if (FD->isMain())
216 return DiagInvalid(DiagMain);
217
218 // Emit a diagnostics for each of the following conditions which is not met.
219 if (FD->isConstexpr())
220 DiagInvalid(DiagConstexpr);
221 if (FD->getReturnType()->isUndeducedType())
222 DiagInvalid(DiagAutoRet);
223 if (FD->isVariadic())
224 DiagInvalid(DiagVarargs);
225
226 return !Diagnosed;
227}
228
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000229static ExprResult buildOperatorCoawaitLookupExpr(Sema &SemaRef, Scope *S,
230 SourceLocation Loc) {
231 DeclarationName OpName =
232 SemaRef.Context.DeclarationNames.getCXXOperatorName(OO_Coawait);
233 LookupResult Operators(SemaRef, OpName, SourceLocation(),
234 Sema::LookupOperatorName);
235 SemaRef.LookupName(Operators, S);
Eric Fiselierc8efda72016-10-27 18:43:28 +0000236
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000237 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
238 const auto &Functions = Operators.asUnresolvedSet();
239 bool IsOverloaded =
240 Functions.size() > 1 ||
241 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
242 Expr *CoawaitOp = UnresolvedLookupExpr::Create(
243 SemaRef.Context, /*NamingClass*/ nullptr, NestedNameSpecifierLoc(),
244 DeclarationNameInfo(OpName, Loc), /*RequiresADL*/ true, IsOverloaded,
245 Functions.begin(), Functions.end());
246 assert(CoawaitOp);
247 return CoawaitOp;
248}
Eric Fiselierc8efda72016-10-27 18:43:28 +0000249
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000250/// Build a call to 'operator co_await' if there is a suitable operator for
251/// the given expression.
252static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, SourceLocation Loc,
253 Expr *E,
254 UnresolvedLookupExpr *Lookup) {
255 UnresolvedSet<16> Functions;
256 Functions.append(Lookup->decls_begin(), Lookup->decls_end());
257 return SemaRef.CreateOverloadedUnaryOp(Loc, UO_Coawait, Functions, E);
258}
Eric Fiselierc8efda72016-10-27 18:43:28 +0000259
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000260static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, Scope *S,
261 SourceLocation Loc, Expr *E) {
262 ExprResult R = buildOperatorCoawaitLookupExpr(SemaRef, S, Loc);
263 if (R.isInvalid())
264 return ExprError();
265 return buildOperatorCoawaitCall(SemaRef, Loc, E,
266 cast<UnresolvedLookupExpr>(R.get()));
Richard Smithcfd53b42015-10-22 06:13:50 +0000267}
268
Gor Nishanov8df64e92016-10-27 16:28:31 +0000269static Expr *buildBuiltinCall(Sema &S, SourceLocation Loc, Builtin::ID Id,
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000270 MultiExprArg CallArgs) {
Gor Nishanov8df64e92016-10-27 16:28:31 +0000271 StringRef Name = S.Context.BuiltinInfo.getName(Id);
272 LookupResult R(S, &S.Context.Idents.get(Name), Loc, Sema::LookupOrdinaryName);
273 S.LookupName(R, S.TUScope, /*AllowBuiltinCreation=*/true);
274
275 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
276 assert(BuiltInDecl && "failed to find builtin declaration");
277
278 ExprResult DeclRef =
279 S.BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
280 assert(DeclRef.isUsable() && "Builtin reference cannot fail");
281
282 ExprResult Call =
283 S.ActOnCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
284
285 assert(!Call.isInvalid() && "Call to builtin cannot fail!");
286 return Call.get();
287}
288
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000289static ExprResult buildCoroutineHandle(Sema &S, QualType PromiseType,
290 SourceLocation Loc) {
291 QualType CoroHandleType = lookupCoroutineHandleType(S, PromiseType, Loc);
292 if (CoroHandleType.isNull())
293 return ExprError();
294
295 DeclContext *LookupCtx = S.computeDeclContext(CoroHandleType);
296 LookupResult Found(S, &S.PP.getIdentifierTable().get("from_address"), Loc,
297 Sema::LookupOrdinaryName);
298 if (!S.LookupQualifiedName(Found, LookupCtx)) {
299 S.Diag(Loc, diag::err_coroutine_handle_missing_member)
300 << "from_address";
301 return ExprError();
302 }
303
304 Expr *FramePtr =
305 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_frame, {});
306
307 CXXScopeSpec SS;
308 ExprResult FromAddr =
309 S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
310 if (FromAddr.isInvalid())
311 return ExprError();
312
313 return S.ActOnCallExpr(nullptr, FromAddr.get(), Loc, FramePtr, Loc);
314}
Richard Smithcfd53b42015-10-22 06:13:50 +0000315
Richard Smith9f690bd2015-10-27 06:02:45 +0000316struct ReadySuspendResumeResult {
Richard Smith9f690bd2015-10-27 06:02:45 +0000317 Expr *Results[3];
Gor Nishanovce43bd22017-03-11 01:30:17 +0000318 OpaqueValueExpr *OpaqueValue;
319 bool IsInvalid;
Richard Smith9f690bd2015-10-27 06:02:45 +0000320};
321
Richard Smith23da82c2015-11-20 22:40:06 +0000322static ExprResult buildMemberCall(Sema &S, Expr *Base, SourceLocation Loc,
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000323 StringRef Name, MultiExprArg Args) {
Richard Smith23da82c2015-11-20 22:40:06 +0000324 DeclarationNameInfo NameInfo(&S.PP.getIdentifierTable().get(Name), Loc);
325
326 // FIXME: Fix BuildMemberReferenceExpr to take a const CXXScopeSpec&.
327 CXXScopeSpec SS;
328 ExprResult Result = S.BuildMemberReferenceExpr(
329 Base, Base->getType(), Loc, /*IsPtr=*/false, SS,
330 SourceLocation(), nullptr, NameInfo, /*TemplateArgs=*/nullptr,
331 /*Scope=*/nullptr);
332 if (Result.isInvalid())
333 return ExprError();
334
335 return S.ActOnCallExpr(nullptr, Result.get(), Loc, Args, Loc, nullptr);
336}
337
Richard Smith9f690bd2015-10-27 06:02:45 +0000338/// Build calls to await_ready, await_suspend, and await_resume for a co_await
339/// expression.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000340static ReadySuspendResumeResult buildCoawaitCalls(Sema &S, VarDecl *CoroPromise,
341 SourceLocation Loc, Expr *E) {
Gor Nishanovce43bd22017-03-11 01:30:17 +0000342 OpaqueValueExpr *Operand = new (S.Context)
343 OpaqueValueExpr(Loc, E->getType(), VK_LValue, E->getObjectKind(), E);
344
Richard Smith9f690bd2015-10-27 06:02:45 +0000345 // Assume invalid until we see otherwise.
Gor Nishanovce43bd22017-03-11 01:30:17 +0000346 ReadySuspendResumeResult Calls = {{}, Operand, /*IsInvalid=*/true};
Richard Smith9f690bd2015-10-27 06:02:45 +0000347
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000348 ExprResult CoroHandleRes = buildCoroutineHandle(S, CoroPromise->getType(), Loc);
349 if (CoroHandleRes.isInvalid())
350 return Calls;
351 Expr *CoroHandle = CoroHandleRes.get();
352
Richard Smith9f690bd2015-10-27 06:02:45 +0000353 const StringRef Funcs[] = {"await_ready", "await_suspend", "await_resume"};
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000354 MultiExprArg Args[] = {None, CoroHandle, None};
Richard Smith9f690bd2015-10-27 06:02:45 +0000355 for (size_t I = 0, N = llvm::array_lengthof(Funcs); I != N; ++I) {
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000356 ExprResult Result = buildMemberCall(S, Operand, Loc, Funcs[I], Args[I]);
Richard Smith9f690bd2015-10-27 06:02:45 +0000357 if (Result.isInvalid())
358 return Calls;
359 Calls.Results[I] = Result.get();
360 }
361
362 Calls.IsInvalid = false;
363 return Calls;
364}
365
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000366static ExprResult buildPromiseCall(Sema &S, VarDecl *Promise,
367 SourceLocation Loc, StringRef Name,
368 MultiExprArg Args) {
369
370 // Form a reference to the promise.
371 ExprResult PromiseRef = S.BuildDeclRefExpr(
372 Promise, Promise->getType().getNonReferenceType(), VK_LValue, Loc);
373 if (PromiseRef.isInvalid())
374 return ExprError();
375
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000376 return buildMemberCall(S, PromiseRef.get(), Loc, Name, Args);
377}
378
379VarDecl *Sema::buildCoroutinePromise(SourceLocation Loc) {
380 assert(isa<FunctionDecl>(CurContext) && "not in a function scope");
381 auto *FD = cast<FunctionDecl>(CurContext);
382
383 QualType T =
384 FD->getType()->isDependentType()
385 ? Context.DependentTy
386 : lookupPromiseType(*this, FD->getType()->castAs<FunctionProtoType>(),
387 Loc, FD->getLocation());
388 if (T.isNull())
389 return nullptr;
390
391 auto *VD = VarDecl::Create(Context, FD, FD->getLocation(), FD->getLocation(),
392 &PP.getIdentifierTable().get("__promise"), T,
393 Context.getTrivialTypeSourceInfo(T, Loc), SC_None);
394 CheckVariableDeclarationType(VD);
395 if (VD->isInvalidDecl())
396 return nullptr;
397 ActOnUninitializedDecl(VD);
398 assert(!VD->isInvalidDecl());
399 return VD;
400}
401
402/// Check that this is a context in which a coroutine suspension can appear.
403static FunctionScopeInfo *checkCoroutineContext(Sema &S, SourceLocation Loc,
Eric Fiseliercac0a592017-03-11 02:35:37 +0000404 StringRef Keyword,
405 bool IsImplicit = false) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000406 if (!isValidCoroutineContext(S, Loc, Keyword))
407 return nullptr;
408
409 assert(isa<FunctionDecl>(S.CurContext) && "not in a function scope");
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000410
411 auto *ScopeInfo = S.getCurFunction();
412 assert(ScopeInfo && "missing function scope for function");
413
Eric Fiseliercac0a592017-03-11 02:35:37 +0000414 if (ScopeInfo->FirstCoroutineStmtLoc.isInvalid() && !IsImplicit)
415 ScopeInfo->setFirstCoroutineStmt(Loc, Keyword);
416
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000417 if (ScopeInfo->CoroutinePromise)
418 return ScopeInfo;
419
420 ScopeInfo->CoroutinePromise = S.buildCoroutinePromise(Loc);
421 if (!ScopeInfo->CoroutinePromise)
422 return nullptr;
423
424 return ScopeInfo;
425}
426
427static bool actOnCoroutineBodyStart(Sema &S, Scope *SC, SourceLocation KWLoc,
428 StringRef Keyword) {
429 if (!checkCoroutineContext(S, KWLoc, Keyword))
430 return false;
431 auto *ScopeInfo = S.getCurFunction();
432 assert(ScopeInfo->CoroutinePromise);
433
434 // If we have existing coroutine statements then we have already built
435 // the initial and final suspend points.
436 if (!ScopeInfo->NeedsCoroutineSuspends)
437 return true;
438
439 ScopeInfo->setNeedsCoroutineSuspends(false);
440
441 auto *Fn = cast<FunctionDecl>(S.CurContext);
442 SourceLocation Loc = Fn->getLocation();
443 // Build the initial suspend point
444 auto buildSuspends = [&](StringRef Name) mutable -> StmtResult {
445 ExprResult Suspend =
446 buildPromiseCall(S, ScopeInfo->CoroutinePromise, Loc, Name, None);
447 if (Suspend.isInvalid())
448 return StmtError();
449 Suspend = buildOperatorCoawaitCall(S, SC, Loc, Suspend.get());
450 if (Suspend.isInvalid())
451 return StmtError();
452 Suspend = S.BuildResolvedCoawaitExpr(Loc, Suspend.get(),
453 /*IsImplicit*/ true);
454 Suspend = S.ActOnFinishFullExpr(Suspend.get());
455 if (Suspend.isInvalid()) {
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000456 S.Diag(Loc, diag::note_coroutine_promise_suspend_implicitly_required)
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000457 << ((Name == "initial_suspend") ? 0 : 1);
458 S.Diag(KWLoc, diag::note_declared_coroutine_here) << Keyword;
459 return StmtError();
460 }
461 return cast<Stmt>(Suspend.get());
462 };
463
464 StmtResult InitSuspend = buildSuspends("initial_suspend");
465 if (InitSuspend.isInvalid())
466 return true;
467
468 StmtResult FinalSuspend = buildSuspends("final_suspend");
469 if (FinalSuspend.isInvalid())
470 return true;
471
472 ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());
473
474 return true;
475}
476
Richard Smith9f690bd2015-10-27 06:02:45 +0000477ExprResult Sema::ActOnCoawaitExpr(Scope *S, SourceLocation Loc, Expr *E) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000478 if (!actOnCoroutineBodyStart(*this, S, Loc, "co_await")) {
Eric Fiseliera5465282016-09-29 21:47:39 +0000479 CorrectDelayedTyposInExpr(E);
480 return ExprError();
481 }
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000482
Richard Smith10610f72015-11-20 22:57:24 +0000483 if (E->getType()->isPlaceholderType()) {
484 ExprResult R = CheckPlaceholderExpr(E);
485 if (R.isInvalid()) return ExprError();
486 E = R.get();
487 }
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000488 ExprResult Lookup = buildOperatorCoawaitLookupExpr(*this, S, Loc);
489 if (Lookup.isInvalid())
490 return ExprError();
491 return BuildUnresolvedCoawaitExpr(Loc, E,
492 cast<UnresolvedLookupExpr>(Lookup.get()));
493}
Richard Smith10610f72015-11-20 22:57:24 +0000494
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000495ExprResult Sema::BuildUnresolvedCoawaitExpr(SourceLocation Loc, Expr *E,
Eric Fiseliercac0a592017-03-11 02:35:37 +0000496 UnresolvedLookupExpr *Lookup) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000497 auto *FSI = checkCoroutineContext(*this, Loc, "co_await");
498 if (!FSI)
499 return ExprError();
500
501 if (E->getType()->isPlaceholderType()) {
502 ExprResult R = CheckPlaceholderExpr(E);
503 if (R.isInvalid())
504 return ExprError();
505 E = R.get();
506 }
507
508 auto *Promise = FSI->CoroutinePromise;
509 if (Promise->getType()->isDependentType()) {
510 Expr *Res =
511 new (Context) DependentCoawaitExpr(Loc, Context.DependentTy, E, Lookup);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000512 return Res;
513 }
514
515 auto *RD = Promise->getType()->getAsCXXRecordDecl();
516 if (lookupMember(*this, "await_transform", RD, Loc)) {
517 ExprResult R = buildPromiseCall(*this, Promise, Loc, "await_transform", E);
518 if (R.isInvalid()) {
519 Diag(Loc,
520 diag::note_coroutine_promise_implicit_await_transform_required_here)
521 << E->getSourceRange();
522 return ExprError();
523 }
524 E = R.get();
525 }
526 ExprResult Awaitable = buildOperatorCoawaitCall(*this, Loc, E, Lookup);
Richard Smith9f690bd2015-10-27 06:02:45 +0000527 if (Awaitable.isInvalid())
528 return ExprError();
Eric Fiseliera5465282016-09-29 21:47:39 +0000529
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000530 return BuildResolvedCoawaitExpr(Loc, Awaitable.get());
Richard Smith9f690bd2015-10-27 06:02:45 +0000531}
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000532
533ExprResult Sema::BuildResolvedCoawaitExpr(SourceLocation Loc, Expr *E,
534 bool IsImplicit) {
Eric Fiseliercac0a592017-03-11 02:35:37 +0000535 auto *Coroutine = checkCoroutineContext(*this, Loc, "co_await", IsImplicit);
Richard Smith744b2242015-11-20 02:54:01 +0000536 if (!Coroutine)
537 return ExprError();
Richard Smith9f690bd2015-10-27 06:02:45 +0000538
Richard Smith9f690bd2015-10-27 06:02:45 +0000539 if (E->getType()->isPlaceholderType()) {
540 ExprResult R = CheckPlaceholderExpr(E);
541 if (R.isInvalid()) return ExprError();
542 E = R.get();
543 }
544
Richard Smith10610f72015-11-20 22:57:24 +0000545 if (E->getType()->isDependentType()) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000546 Expr *Res = new (Context)
547 CoawaitExpr(Loc, Context.DependentTy, E, IsImplicit);
Richard Smith10610f72015-11-20 22:57:24 +0000548 return Res;
549 }
550
Richard Smith1f38edd2015-11-22 03:13:02 +0000551 // If the expression is a temporary, materialize it as an lvalue so that we
552 // can use it multiple times.
553 if (E->getValueKind() == VK_RValue)
Tim Shen4a05bb82016-06-21 20:29:17 +0000554 E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
Richard Smith9f690bd2015-10-27 06:02:45 +0000555
556 // Build the await_ready, await_suspend, await_resume calls.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000557 ReadySuspendResumeResult RSS =
558 buildCoawaitCalls(*this, Coroutine->CoroutinePromise, Loc, E);
Richard Smith9f690bd2015-10-27 06:02:45 +0000559 if (RSS.IsInvalid)
560 return ExprError();
561
Gor Nishanovce43bd22017-03-11 01:30:17 +0000562 Expr *Res =
563 new (Context) CoawaitExpr(Loc, E, RSS.Results[0], RSS.Results[1],
564 RSS.Results[2], RSS.OpaqueValue, IsImplicit);
Eric Fiseliercac0a592017-03-11 02:35:37 +0000565
Richard Smithcfd53b42015-10-22 06:13:50 +0000566 return Res;
567}
568
Richard Smith9f690bd2015-10-27 06:02:45 +0000569ExprResult Sema::ActOnCoyieldExpr(Scope *S, SourceLocation Loc, Expr *E) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000570 if (!actOnCoroutineBodyStart(*this, S, Loc, "co_yield")) {
Eric Fiseliera5465282016-09-29 21:47:39 +0000571 CorrectDelayedTyposInExpr(E);
Richard Smith23da82c2015-11-20 22:40:06 +0000572 return ExprError();
Eric Fiseliera5465282016-09-29 21:47:39 +0000573 }
Richard Smith23da82c2015-11-20 22:40:06 +0000574
575 // Build yield_value call.
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000576 ExprResult Awaitable = buildPromiseCall(
577 *this, getCurFunction()->CoroutinePromise, Loc, "yield_value", E);
Richard Smith9f690bd2015-10-27 06:02:45 +0000578 if (Awaitable.isInvalid())
579 return ExprError();
Richard Smith23da82c2015-11-20 22:40:06 +0000580
581 // Build 'operator co_await' call.
582 Awaitable = buildOperatorCoawaitCall(*this, S, Loc, Awaitable.get());
583 if (Awaitable.isInvalid())
584 return ExprError();
585
Richard Smith9f690bd2015-10-27 06:02:45 +0000586 return BuildCoyieldExpr(Loc, Awaitable.get());
587}
588ExprResult Sema::BuildCoyieldExpr(SourceLocation Loc, Expr *E) {
589 auto *Coroutine = checkCoroutineContext(*this, Loc, "co_yield");
Richard Smith744b2242015-11-20 02:54:01 +0000590 if (!Coroutine)
591 return ExprError();
Richard Smithcfd53b42015-10-22 06:13:50 +0000592
Richard Smith10610f72015-11-20 22:57:24 +0000593 if (E->getType()->isPlaceholderType()) {
594 ExprResult R = CheckPlaceholderExpr(E);
595 if (R.isInvalid()) return ExprError();
596 E = R.get();
597 }
598
Richard Smithd7bed4d2015-11-22 02:57:17 +0000599 if (E->getType()->isDependentType()) {
600 Expr *Res = new (Context) CoyieldExpr(Loc, Context.DependentTy, E);
Richard Smithd7bed4d2015-11-22 02:57:17 +0000601 return Res;
602 }
603
Richard Smith1f38edd2015-11-22 03:13:02 +0000604 // If the expression is a temporary, materialize it as an lvalue so that we
605 // can use it multiple times.
606 if (E->getValueKind() == VK_RValue)
Tim Shen4a05bb82016-06-21 20:29:17 +0000607 E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
Richard Smithd7bed4d2015-11-22 02:57:17 +0000608
609 // Build the await_ready, await_suspend, await_resume calls.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000610 ReadySuspendResumeResult RSS =
611 buildCoawaitCalls(*this, Coroutine->CoroutinePromise, Loc, E);
Richard Smithd7bed4d2015-11-22 02:57:17 +0000612 if (RSS.IsInvalid)
613 return ExprError();
614
615 Expr *Res = new (Context) CoyieldExpr(Loc, E, RSS.Results[0], RSS.Results[1],
Gor Nishanovce43bd22017-03-11 01:30:17 +0000616 RSS.Results[2], RSS.OpaqueValue);
Eric Fiseliercac0a592017-03-11 02:35:37 +0000617
Richard Smithcfd53b42015-10-22 06:13:50 +0000618 return Res;
619}
620
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000621StmtResult Sema::ActOnCoreturnStmt(Scope *S, SourceLocation Loc, Expr *E) {
622 if (!actOnCoroutineBodyStart(*this, S, Loc, "co_return")) {
Eric Fiseliera5465282016-09-29 21:47:39 +0000623 CorrectDelayedTyposInExpr(E);
624 return StmtError();
625 }
Richard Smith9f690bd2015-10-27 06:02:45 +0000626 return BuildCoreturnStmt(Loc, E);
627}
Gor Nishanov3e048bb2016-10-04 00:31:16 +0000628
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000629StmtResult Sema::BuildCoreturnStmt(SourceLocation Loc, Expr *E,
630 bool IsImplicit) {
Eric Fiseliercac0a592017-03-11 02:35:37 +0000631 auto *FSI = checkCoroutineContext(*this, Loc, "co_return", IsImplicit);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000632 if (!FSI)
Richard Smith71d403e2015-11-22 07:33:28 +0000633 return StmtError();
634
635 if (E && E->getType()->isPlaceholderType() &&
636 !E->getType()->isSpecificPlaceholderType(BuiltinType::Overload)) {
Richard Smith10610f72015-11-20 22:57:24 +0000637 ExprResult R = CheckPlaceholderExpr(E);
638 if (R.isInvalid()) return StmtError();
639 E = R.get();
640 }
641
Richard Smith4ba66602015-11-22 07:05:16 +0000642 // FIXME: If the operand is a reference to a variable that's about to go out
Richard Smith2af65c42015-11-24 02:34:39 +0000643 // of scope, we should treat the operand as an xvalue for this overload
Richard Smith4ba66602015-11-22 07:05:16 +0000644 // resolution.
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000645 VarDecl *Promise = FSI->CoroutinePromise;
Richard Smith4ba66602015-11-22 07:05:16 +0000646 ExprResult PC;
Eric Fiselier98131312016-10-06 21:23:38 +0000647 if (E && (isa<InitListExpr>(E) || !E->getType()->isVoidType())) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000648 PC = buildPromiseCall(*this, Promise, Loc, "return_value", E);
Richard Smith4ba66602015-11-22 07:05:16 +0000649 } else {
650 E = MakeFullDiscardedValueExpr(E).get();
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000651 PC = buildPromiseCall(*this, Promise, Loc, "return_void", None);
Richard Smith4ba66602015-11-22 07:05:16 +0000652 }
653 if (PC.isInvalid())
654 return StmtError();
655
656 Expr *PCE = ActOnFinishFullExpr(PC.get()).get();
657
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000658 Stmt *Res = new (Context) CoreturnStmt(Loc, E, PCE, IsImplicit);
Richard Smithcfd53b42015-10-22 06:13:50 +0000659 return Res;
660}
661
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000662/// Look up the std::nothrow object.
663static Expr *buildStdNoThrowDeclRef(Sema &S, SourceLocation Loc) {
664 NamespaceDecl *Std = S.getStdNamespace();
665 assert(Std && "Should already be diagnosed");
666
667 LookupResult Result(S, &S.PP.getIdentifierTable().get("nothrow"), Loc,
668 Sema::LookupOrdinaryName);
669 if (!S.LookupQualifiedName(Result, Std)) {
670 // FIXME: <experimental/coroutine> should have been included already.
671 // If we require it to include <new> then this diagnostic is no longer
672 // needed.
673 S.Diag(Loc, diag::err_implicit_coroutine_std_nothrow_type_not_found);
674 return nullptr;
675 }
676
677 // FIXME: Mark the variable as ODR used. This currently does not work
678 // likely due to the scope at in which this function is called.
679 auto *VD = Result.getAsSingle<VarDecl>();
680 if (!VD) {
681 Result.suppressDiagnostics();
682 // We found something weird. Complain about the first thing we found.
683 NamedDecl *Found = *Result.begin();
684 S.Diag(Found->getLocation(), diag::err_malformed_std_nothrow);
685 return nullptr;
686 }
687
688 ExprResult DR = S.BuildDeclRefExpr(VD, VD->getType(), VK_LValue, Loc);
689 if (DR.isInvalid())
690 return nullptr;
691
692 return DR.get();
693}
694
Gor Nishanov8df64e92016-10-27 16:28:31 +0000695// Find an appropriate delete for the promise.
696static FunctionDecl *findDeleteForPromise(Sema &S, SourceLocation Loc,
697 QualType PromiseType) {
698 FunctionDecl *OperatorDelete = nullptr;
699
700 DeclarationName DeleteName =
701 S.Context.DeclarationNames.getCXXOperatorName(OO_Delete);
702
703 auto *PointeeRD = PromiseType->getAsCXXRecordDecl();
704 assert(PointeeRD && "PromiseType must be a CxxRecordDecl type");
705
706 if (S.FindDeallocationFunction(Loc, PointeeRD, DeleteName, OperatorDelete))
707 return nullptr;
708
709 if (!OperatorDelete) {
710 // Look for a global declaration.
711 const bool CanProvideSize = S.isCompleteType(Loc, PromiseType);
712 const bool Overaligned = false;
713 OperatorDelete = S.FindUsualDeallocationFunction(Loc, CanProvideSize,
714 Overaligned, DeleteName);
715 }
716 S.MarkFunctionReferenced(Loc, OperatorDelete);
717 return OperatorDelete;
718}
719
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000720
721void Sema::CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body) {
722 FunctionScopeInfo *Fn = getCurFunction();
723 assert(Fn && Fn->CoroutinePromise && "not a coroutine");
724
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000725 if (!Body) {
726 assert(FD->isInvalidDecl() &&
727 "a null body is only allowed for invalid declarations");
728 return;
729 }
730
731 if (isa<CoroutineBodyStmt>(Body)) {
732 // FIXME(EricWF): Nothing todo. the body is already a transformed coroutine
733 // body statement.
734 return;
735 }
736
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000737 // Coroutines [stmt.return]p1:
738 // A return statement shall not appear in a coroutine.
739 if (Fn->FirstReturnLoc.isValid()) {
Eric Fiseliercac0a592017-03-11 02:35:37 +0000740 assert(Fn->FirstCoroutineStmtLoc.isValid() &&
741 "first coroutine location not set");
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000742 Diag(Fn->FirstReturnLoc, diag::err_return_in_coroutine);
Eric Fiseliercac0a592017-03-11 02:35:37 +0000743 Diag(Fn->FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
744 << Fn->getFirstCoroutineStmtKeyword();
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000745 }
Eric Fiselierbee782b2017-04-03 19:21:00 +0000746 CoroutineStmtBuilder Builder(*this, *FD, *Fn, Body);
747 if (Builder.isInvalid() || !Builder.buildStatements())
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000748 return FD->setInvalidDecl();
749
750 // Build body for the coroutine wrapper statement.
751 Body = CoroutineBodyStmt::Create(Context, Builder);
752}
753
Eric Fiselierbee782b2017-04-03 19:21:00 +0000754CoroutineStmtBuilder::CoroutineStmtBuilder(Sema &S, FunctionDecl &FD,
755 sema::FunctionScopeInfo &Fn,
756 Stmt *Body)
757 : S(S), FD(FD), Fn(Fn), Loc(FD.getLocation()),
758 IsPromiseDependentType(
759 !Fn.CoroutinePromise ||
760 Fn.CoroutinePromise->getType()->isDependentType()) {
761 this->Body = Body;
762 if (!IsPromiseDependentType) {
763 PromiseRecordDecl = Fn.CoroutinePromise->getType()->getAsCXXRecordDecl();
764 assert(PromiseRecordDecl && "Type should have already been checked");
765 }
766 this->IsValid = makePromiseStmt() && makeInitialAndFinalSuspend();
767}
768
769bool CoroutineStmtBuilder::buildStatements() {
770 assert(this->IsValid && "coroutine already invalid");
771 this->IsValid = makeReturnObject() && makeParamMoves();
772 if (this->IsValid && !IsPromiseDependentType)
773 buildDependentStatements();
774 return this->IsValid;
775}
776
777bool CoroutineStmtBuilder::buildDependentStatements() {
778 assert(this->IsValid && "coroutine already invalid");
779 assert(!this->IsPromiseDependentType &&
780 "coroutine cannot have a dependent promise type");
781 this->IsValid = makeOnException() && makeOnFallthrough() &&
Gor Nishanov6a470682017-05-22 20:22:23 +0000782 makeGroDeclAndReturnStmt() && makeReturnOnAllocFailure() &&
783 makeNewAndDeleteExpr();
Eric Fiselierbee782b2017-04-03 19:21:00 +0000784 return this->IsValid;
785}
786
787bool CoroutineStmtBuilder::makePromiseStmt() {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000788 // Form a declaration statement for the promise declaration, so that AST
789 // visitors can more easily find it.
790 StmtResult PromiseStmt =
791 S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(Fn.CoroutinePromise), Loc, Loc);
792 if (PromiseStmt.isInvalid())
793 return false;
794
795 this->Promise = PromiseStmt.get();
796 return true;
797}
798
Eric Fiselierbee782b2017-04-03 19:21:00 +0000799bool CoroutineStmtBuilder::makeInitialAndFinalSuspend() {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000800 if (Fn.hasInvalidCoroutineSuspends())
801 return false;
802 this->InitialSuspend = cast<Expr>(Fn.CoroutineSuspends.first);
803 this->FinalSuspend = cast<Expr>(Fn.CoroutineSuspends.second);
804 return true;
805}
806
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000807static bool diagReturnOnAllocFailure(Sema &S, Expr *E,
808 CXXRecordDecl *PromiseRecordDecl,
809 FunctionScopeInfo &Fn) {
810 auto Loc = E->getExprLoc();
811 if (auto *DeclRef = dyn_cast_or_null<DeclRefExpr>(E)) {
812 auto *Decl = DeclRef->getDecl();
813 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Decl)) {
814 if (Method->isStatic())
815 return true;
816 else
817 Loc = Decl->getLocation();
818 }
819 }
820
821 S.Diag(
822 Loc,
823 diag::err_coroutine_promise_get_return_object_on_allocation_failure)
824 << PromiseRecordDecl;
825 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
826 << Fn.getFirstCoroutineStmtKeyword();
827 return false;
828}
829
Eric Fiselierbee782b2017-04-03 19:21:00 +0000830bool CoroutineStmtBuilder::makeReturnOnAllocFailure() {
831 assert(!IsPromiseDependentType &&
832 "cannot make statement while the promise type is dependent");
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000833
834 // [dcl.fct.def.coroutine]/8
835 // The unqualified-id get_return_object_on_allocation_failure is looked up in
836 // the scope of class P by class member access lookup (3.4.5). ...
837 // If an allocation function returns nullptr, ... the coroutine return value
838 // is obtained by a call to ... get_return_object_on_allocation_failure().
839
840 DeclarationName DN =
841 S.PP.getIdentifierInfo("get_return_object_on_allocation_failure");
842 LookupResult Found(S, DN, Loc, Sema::LookupMemberName);
Eric Fiselierbee782b2017-04-03 19:21:00 +0000843 if (!S.LookupQualifiedName(Found, PromiseRecordDecl))
844 return true;
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000845
846 CXXScopeSpec SS;
847 ExprResult DeclNameExpr =
848 S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
Eric Fiselierbee782b2017-04-03 19:21:00 +0000849 if (DeclNameExpr.isInvalid())
850 return false;
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000851
852 if (!diagReturnOnAllocFailure(S, DeclNameExpr.get(), PromiseRecordDecl, Fn))
853 return false;
854
855 ExprResult ReturnObjectOnAllocationFailure =
856 S.ActOnCallExpr(nullptr, DeclNameExpr.get(), Loc, {}, Loc);
Eric Fiselierbee782b2017-04-03 19:21:00 +0000857 if (ReturnObjectOnAllocationFailure.isInvalid())
858 return false;
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000859
Gor Nishanovc4a19082017-03-28 02:51:45 +0000860 StmtResult ReturnStmt =
861 S.BuildReturnStmt(Loc, ReturnObjectOnAllocationFailure.get());
Gor Nishanov6a470682017-05-22 20:22:23 +0000862 if (ReturnStmt.isInvalid()) {
863 S.Diag(Found.getFoundDecl()->getLocation(),
864 diag::note_promise_member_declared_here)
865 << DN.getAsString();
866 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
867 << Fn.getFirstCoroutineStmtKeyword();
Eric Fiselierbee782b2017-04-03 19:21:00 +0000868 return false;
Gor Nishanov6a470682017-05-22 20:22:23 +0000869 }
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000870
871 this->ReturnStmtOnAllocFailure = ReturnStmt.get();
872 return true;
873}
874
Eric Fiselierbee782b2017-04-03 19:21:00 +0000875bool CoroutineStmtBuilder::makeNewAndDeleteExpr() {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000876 // Form and check allocation and deallocation calls.
Eric Fiselierbee782b2017-04-03 19:21:00 +0000877 assert(!IsPromiseDependentType &&
878 "cannot make statement while the promise type is dependent");
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000879 QualType PromiseType = Fn.CoroutinePromise->getType();
Gor Nishanov8df64e92016-10-27 16:28:31 +0000880
881 if (S.RequireCompleteType(Loc, PromiseType, diag::err_incomplete_type))
882 return false;
883
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000884 const bool RequiresNoThrowAlloc = ReturnStmtOnAllocFailure != nullptr;
885
Gor Nishanov8df64e92016-10-27 16:28:31 +0000886 // FIXME: Add support for stateful allocators.
887
888 FunctionDecl *OperatorNew = nullptr;
889 FunctionDecl *OperatorDelete = nullptr;
890 FunctionDecl *UnusedResult = nullptr;
891 bool PassAlignment = false;
Eric Fiselierf747f532017-04-18 05:08:08 +0000892 SmallVector<Expr *, 1> PlacementArgs;
Gor Nishanov8df64e92016-10-27 16:28:31 +0000893
894 S.FindAllocationFunctions(Loc, SourceRange(),
895 /*UseGlobal*/ false, PromiseType,
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000896 /*isArray*/ false, PassAlignment, PlacementArgs,
897 OperatorNew, UnusedResult);
Gor Nishanov8df64e92016-10-27 16:28:31 +0000898
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000899 bool IsGlobalOverload =
900 OperatorNew && !isa<CXXRecordDecl>(OperatorNew->getDeclContext());
901 // If we didn't find a class-local new declaration and non-throwing new
902 // was is required then we need to lookup the non-throwing global operator
903 // instead.
904 if (RequiresNoThrowAlloc && (!OperatorNew || IsGlobalOverload)) {
905 auto *StdNoThrow = buildStdNoThrowDeclRef(S, Loc);
906 if (!StdNoThrow)
907 return false;
Eric Fiselierf747f532017-04-18 05:08:08 +0000908 PlacementArgs = {StdNoThrow};
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000909 OperatorNew = nullptr;
910 S.FindAllocationFunctions(Loc, SourceRange(),
911 /*UseGlobal*/ true, PromiseType,
912 /*isArray*/ false, PassAlignment, PlacementArgs,
913 OperatorNew, UnusedResult);
914 }
Gor Nishanov8df64e92016-10-27 16:28:31 +0000915
Eric Fiselierc5128752017-04-18 05:30:39 +0000916 assert(OperatorNew && "expected definition of operator new to be found");
917
918 if (RequiresNoThrowAlloc) {
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000919 const auto *FT = OperatorNew->getType()->getAs<FunctionProtoType>();
920 if (!FT->isNothrow(S.Context, /*ResultIfDependent*/ false)) {
921 S.Diag(OperatorNew->getLocation(),
922 diag::err_coroutine_promise_new_requires_nothrow)
923 << OperatorNew;
924 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
925 << OperatorNew;
926 return false;
927 }
928 }
929
930 if ((OperatorDelete = findDeleteForPromise(S, Loc, PromiseType)) == nullptr)
Gor Nishanov8df64e92016-10-27 16:28:31 +0000931 return false;
932
933 Expr *FramePtr =
934 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_frame, {});
935
936 Expr *FrameSize =
937 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_size, {});
938
939 // Make new call.
940
941 ExprResult NewRef =
942 S.BuildDeclRefExpr(OperatorNew, OperatorNew->getType(), VK_LValue, Loc);
943 if (NewRef.isInvalid())
944 return false;
945
Eric Fiselierf747f532017-04-18 05:08:08 +0000946 SmallVector<Expr *, 2> NewArgs(1, FrameSize);
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000947 for (auto Arg : PlacementArgs)
948 NewArgs.push_back(Arg);
949
Gor Nishanov8df64e92016-10-27 16:28:31 +0000950 ExprResult NewExpr =
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000951 S.ActOnCallExpr(S.getCurScope(), NewRef.get(), Loc, NewArgs, Loc);
952 NewExpr = S.ActOnFinishFullExpr(NewExpr.get());
Gor Nishanov8df64e92016-10-27 16:28:31 +0000953 if (NewExpr.isInvalid())
954 return false;
955
Gor Nishanov8df64e92016-10-27 16:28:31 +0000956 // Make delete call.
957
958 QualType OpDeleteQualType = OperatorDelete->getType();
959
960 ExprResult DeleteRef =
961 S.BuildDeclRefExpr(OperatorDelete, OpDeleteQualType, VK_LValue, Loc);
962 if (DeleteRef.isInvalid())
963 return false;
964
965 Expr *CoroFree =
966 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_free, {FramePtr});
967
968 SmallVector<Expr *, 2> DeleteArgs{CoroFree};
969
970 // Check if we need to pass the size.
971 const auto *OpDeleteType =
972 OpDeleteQualType.getTypePtr()->getAs<FunctionProtoType>();
973 if (OpDeleteType->getNumParams() > 1)
974 DeleteArgs.push_back(FrameSize);
975
976 ExprResult DeleteExpr =
977 S.ActOnCallExpr(S.getCurScope(), DeleteRef.get(), Loc, DeleteArgs, Loc);
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000978 DeleteExpr = S.ActOnFinishFullExpr(DeleteExpr.get());
Gor Nishanov8df64e92016-10-27 16:28:31 +0000979 if (DeleteExpr.isInvalid())
980 return false;
981
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000982 this->Allocate = NewExpr.get();
983 this->Deallocate = DeleteExpr.get();
Gor Nishanov8df64e92016-10-27 16:28:31 +0000984
985 return true;
986}
987
Eric Fiselierbee782b2017-04-03 19:21:00 +0000988bool CoroutineStmtBuilder::makeOnFallthrough() {
989 assert(!IsPromiseDependentType &&
990 "cannot make statement while the promise type is dependent");
Gor Nishanovbbe1c072017-02-13 05:05:02 +0000991
992 // [dcl.fct.def.coroutine]/4
993 // The unqualified-ids 'return_void' and 'return_value' are looked up in
994 // the scope of class P. If both are found, the program is ill-formed.
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000995 const bool HasRVoid = lookupMember(S, "return_void", PromiseRecordDecl, Loc);
996 const bool HasRValue = lookupMember(S, "return_value", PromiseRecordDecl, Loc);
Gor Nishanovbbe1c072017-02-13 05:05:02 +0000997
Eric Fiselier709d1b32016-10-27 07:30:31 +0000998 StmtResult Fallthrough;
Gor Nishanovbbe1c072017-02-13 05:05:02 +0000999 if (HasRVoid && HasRValue) {
1000 // FIXME Improve this diagnostic
1001 S.Diag(FD.getLocation(), diag::err_coroutine_promise_return_ill_formed)
1002 << PromiseRecordDecl;
1003 return false;
1004 } else if (HasRVoid) {
1005 // If the unqualified-id return_void is found, flowing off the end of a
1006 // coroutine is equivalent to a co_return with no operand. Otherwise,
1007 // flowing off the end of a coroutine results in undefined behavior.
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001008 Fallthrough = S.BuildCoreturnStmt(FD.getLocation(), nullptr,
1009 /*IsImplicit*/false);
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001010 Fallthrough = S.ActOnFinishFullStmt(Fallthrough.get());
1011 if (Fallthrough.isInvalid())
1012 return false;
Eric Fiselier709d1b32016-10-27 07:30:31 +00001013 }
Richard Smith2af65c42015-11-24 02:34:39 +00001014
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001015 this->OnFallthrough = Fallthrough.get();
1016 return true;
1017}
1018
Eric Fiselierbee782b2017-04-03 19:21:00 +00001019bool CoroutineStmtBuilder::makeOnException() {
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001020 // Try to form 'p.unhandled_exception();'
Eric Fiselierbee782b2017-04-03 19:21:00 +00001021 assert(!IsPromiseDependentType &&
1022 "cannot make statement while the promise type is dependent");
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001023
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001024 const bool RequireUnhandledException = S.getLangOpts().CXXExceptions;
1025
1026 if (!lookupMember(S, "unhandled_exception", PromiseRecordDecl, Loc)) {
1027 auto DiagID =
1028 RequireUnhandledException
1029 ? diag::err_coroutine_promise_unhandled_exception_required
1030 : diag::
1031 warn_coroutine_promise_unhandled_exception_required_with_exceptions;
1032 S.Diag(Loc, DiagID) << PromiseRecordDecl;
1033 return !RequireUnhandledException;
1034 }
1035
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001036 // If exceptions are disabled, don't try to build OnException.
1037 if (!S.getLangOpts().CXXExceptions)
1038 return true;
1039
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001040 ExprResult UnhandledException = buildPromiseCall(S, Fn.CoroutinePromise, Loc,
1041 "unhandled_exception", None);
1042 UnhandledException = S.ActOnFinishFullExpr(UnhandledException.get(), Loc);
1043 if (UnhandledException.isInvalid())
1044 return false;
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001045
Gor Nishanov5b050e42017-05-22 22:33:17 +00001046 // Since the body of the coroutine will be wrapped in try-catch, it will
1047 // be incompatible with SEH __try if present in a function.
1048 if (!S.getLangOpts().Borland && Fn.FirstSEHTryLoc.isValid()) {
1049 S.Diag(Fn.FirstSEHTryLoc, diag::err_seh_in_a_coroutine_with_cxx_exceptions);
1050 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1051 << Fn.getFirstCoroutineStmtKeyword();
1052 return false;
1053 }
1054
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001055 this->OnException = UnhandledException.get();
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001056 return true;
1057}
1058
Eric Fiselierbee782b2017-04-03 19:21:00 +00001059bool CoroutineStmtBuilder::makeReturnObject() {
Richard Smith2af65c42015-11-24 02:34:39 +00001060 // Build implicit 'p.get_return_object()' expression and form initialization
1061 // of return type from it.
1062 ExprResult ReturnObject =
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001063 buildPromiseCall(S, Fn.CoroutinePromise, Loc, "get_return_object", None);
Richard Smith2af65c42015-11-24 02:34:39 +00001064 if (ReturnObject.isInvalid())
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001065 return false;
Richard Smith2af65c42015-11-24 02:34:39 +00001066
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001067 this->ReturnValue = ReturnObject.get();
1068 return true;
1069}
1070
Gor Nishanov6a470682017-05-22 20:22:23 +00001071static void noteMemberDeclaredHere(Sema &S, Expr *E, FunctionScopeInfo &Fn) {
1072 if (auto *MbrRef = dyn_cast<CXXMemberCallExpr>(E)) {
1073 auto *MethodDecl = MbrRef->getMethodDecl();
1074 S.Diag(MethodDecl->getLocation(), diag::note_promise_member_declared_here)
1075 << MethodDecl->getName();
1076 }
1077 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1078 << Fn.getFirstCoroutineStmtKeyword();
1079}
1080
1081bool CoroutineStmtBuilder::makeGroDeclAndReturnStmt() {
1082 assert(!IsPromiseDependentType &&
1083 "cannot make statement while the promise type is dependent");
1084 assert(this->ReturnValue && "ReturnValue must be already formed");
1085
1086 QualType const GroType = this->ReturnValue->getType();
1087 assert(!GroType->isDependentType() &&
1088 "get_return_object type must no longer be dependent");
1089
1090 QualType const FnRetType = FD.getReturnType();
1091 assert(!FnRetType->isDependentType() &&
1092 "get_return_object type must no longer be dependent");
1093
1094 if (FnRetType->isVoidType()) {
1095 ExprResult Res = S.ActOnFinishFullExpr(this->ReturnValue, Loc);
1096 if (Res.isInvalid())
1097 return false;
1098
1099 this->ResultDecl = Res.get();
1100 return true;
1101 }
1102
1103 if (GroType->isVoidType()) {
1104 // Trigger a nice error message.
1105 InitializedEntity Entity =
1106 InitializedEntity::InitializeResult(Loc, FnRetType, false);
1107 S.PerformMoveOrCopyInitialization(Entity, nullptr, FnRetType, ReturnValue);
1108 noteMemberDeclaredHere(S, ReturnValue, Fn);
1109 return false;
1110 }
1111
1112 auto *GroDecl = VarDecl::Create(
1113 S.Context, &FD, FD.getLocation(), FD.getLocation(),
1114 &S.PP.getIdentifierTable().get("__coro_gro"), GroType,
1115 S.Context.getTrivialTypeSourceInfo(GroType, Loc), SC_None);
1116
1117 S.CheckVariableDeclarationType(GroDecl);
1118 if (GroDecl->isInvalidDecl())
1119 return false;
1120
1121 InitializedEntity Entity = InitializedEntity::InitializeVariable(GroDecl);
1122 ExprResult Res = S.PerformMoveOrCopyInitialization(Entity, nullptr, GroType,
1123 this->ReturnValue);
1124 if (Res.isInvalid())
1125 return false;
1126
1127 Res = S.ActOnFinishFullExpr(Res.get());
1128 if (Res.isInvalid())
1129 return false;
1130
1131 if (GroType == FnRetType) {
1132 GroDecl->setNRVOVariable(true);
1133 }
1134
1135 S.AddInitializerToDecl(GroDecl, Res.get(),
1136 /*DirectInit=*/false);
1137
1138 S.FinalizeDeclaration(GroDecl);
1139
1140 // Form a declaration statement for the return declaration, so that AST
1141 // visitors can more easily find it.
1142 StmtResult GroDeclStmt =
1143 S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(GroDecl), Loc, Loc);
1144 if (GroDeclStmt.isInvalid())
1145 return false;
1146
1147 this->ResultDecl = GroDeclStmt.get();
1148
1149 ExprResult declRef = S.BuildDeclRefExpr(GroDecl, GroType, VK_LValue, Loc);
1150 if (declRef.isInvalid())
1151 return false;
1152
1153 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, declRef.get());
1154 if (ReturnStmt.isInvalid()) {
1155 noteMemberDeclaredHere(S, ReturnValue, Fn);
1156 return false;
1157 }
1158
1159 this->ReturnStmt = ReturnStmt.get();
1160 return true;
1161}
1162
Eric Fiselierbee782b2017-04-03 19:21:00 +00001163bool CoroutineStmtBuilder::makeParamMoves() {
Richard Smith2af65c42015-11-24 02:34:39 +00001164 // FIXME: Perform move-initialization of parameters into frame-local copies.
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001165 return true;
Richard Smithcfd53b42015-10-22 06:13:50 +00001166}
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001167
1168StmtResult Sema::BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
1169 CoroutineBodyStmt *Res = CoroutineBodyStmt::Create(Context, Args);
1170 if (!Res)
1171 return StmtError();
1172 return Res;
1173}