blob: 1836345e98167749fa69d5b29ede82a8126bb67b [file] [log] [blame]
Richard Smithcfd53b42015-10-22 06:13:50 +00001//===--- SemaCoroutines.cpp - Semantic Analysis for Coroutines ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ Coroutines.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Sema/SemaInternal.h"
Richard Smith9f690bd2015-10-27 06:02:45 +000015#include "clang/AST/Decl.h"
16#include "clang/AST/ExprCXX.h"
17#include "clang/AST/StmtCXX.h"
18#include "clang/Lex/Preprocessor.h"
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"
Richard Smithcfd53b42015-10-22 06:13:50 +000021using namespace clang;
22using namespace sema;
23
Eric Fiselier20f25cb2017-03-06 23:38:15 +000024static bool lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD,
25 SourceLocation Loc) {
26 DeclarationName DN = S.PP.getIdentifierInfo(Name);
27 LookupResult LR(S, DN, Loc, Sema::LookupMemberName);
28 // Suppress diagnostics when a private member is selected. The same warnings
29 // will be produced again when building the call.
30 LR.suppressDiagnostics();
31 return S.LookupQualifiedName(LR, RD);
32}
33
Richard Smith9f690bd2015-10-27 06:02:45 +000034/// Look up the std::coroutine_traits<...>::promise_type for the given
35/// function type.
36static QualType lookupPromiseType(Sema &S, const FunctionProtoType *FnType,
Eric Fiselier89bf0e72017-03-06 22:52:28 +000037 SourceLocation KwLoc,
38 SourceLocation FuncLoc) {
Richard Smith9f690bd2015-10-27 06:02:45 +000039 // FIXME: Cache std::coroutine_traits once we've found it.
Gor Nishanov3e048bb2016-10-04 00:31:16 +000040 NamespaceDecl *StdExp = S.lookupStdExperimentalNamespace();
41 if (!StdExp) {
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +000042 S.Diag(KwLoc, diag::err_implied_coroutine_type_not_found)
43 << "std::experimental::coroutine_traits";
Richard Smith9f690bd2015-10-27 06:02:45 +000044 return QualType();
45 }
46
47 LookupResult Result(S, &S.PP.getIdentifierTable().get("coroutine_traits"),
Eric Fiselier89bf0e72017-03-06 22:52:28 +000048 FuncLoc, Sema::LookupOrdinaryName);
Gor Nishanov3e048bb2016-10-04 00:31:16 +000049 if (!S.LookupQualifiedName(Result, StdExp)) {
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +000050 S.Diag(KwLoc, diag::err_implied_coroutine_type_not_found)
51 << "std::experimental::coroutine_traits";
Richard Smith9f690bd2015-10-27 06:02:45 +000052 return QualType();
53 }
54
55 ClassTemplateDecl *CoroTraits = Result.getAsSingle<ClassTemplateDecl>();
56 if (!CoroTraits) {
57 Result.suppressDiagnostics();
58 // We found something weird. Complain about the first thing we found.
59 NamedDecl *Found = *Result.begin();
60 S.Diag(Found->getLocation(), diag::err_malformed_std_coroutine_traits);
61 return QualType();
62 }
63
64 // Form template argument list for coroutine_traits<R, P1, P2, ...>.
Eric Fiselier89bf0e72017-03-06 22:52:28 +000065 TemplateArgumentListInfo Args(KwLoc, KwLoc);
Richard Smith9f690bd2015-10-27 06:02:45 +000066 Args.addArgument(TemplateArgumentLoc(
67 TemplateArgument(FnType->getReturnType()),
Eric Fiselier89bf0e72017-03-06 22:52:28 +000068 S.Context.getTrivialTypeSourceInfo(FnType->getReturnType(), KwLoc)));
Richard Smith71d403e2015-11-22 07:33:28 +000069 // FIXME: If the function is a non-static member function, add the type
70 // of the implicit object parameter before the formal parameters.
Richard Smith9f690bd2015-10-27 06:02:45 +000071 for (QualType T : FnType->getParamTypes())
72 Args.addArgument(TemplateArgumentLoc(
Eric Fiselier89bf0e72017-03-06 22:52:28 +000073 TemplateArgument(T), S.Context.getTrivialTypeSourceInfo(T, KwLoc)));
Richard Smith9f690bd2015-10-27 06:02:45 +000074
75 // Build the template-id.
76 QualType CoroTrait =
Eric Fiselier89bf0e72017-03-06 22:52:28 +000077 S.CheckTemplateIdType(TemplateName(CoroTraits), KwLoc, Args);
Richard Smith9f690bd2015-10-27 06:02:45 +000078 if (CoroTrait.isNull())
79 return QualType();
Eric Fiselier89bf0e72017-03-06 22:52:28 +000080 if (S.RequireCompleteType(KwLoc, CoroTrait,
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +000081 diag::err_coroutine_type_missing_specialization))
Richard Smith9f690bd2015-10-27 06:02:45 +000082 return QualType();
83
Eric Fiselier89bf0e72017-03-06 22:52:28 +000084 auto *RD = CoroTrait->getAsCXXRecordDecl();
Richard Smith9f690bd2015-10-27 06:02:45 +000085 assert(RD && "specialization of class template is not a class?");
86
87 // Look up the ::promise_type member.
Eric Fiselier89bf0e72017-03-06 22:52:28 +000088 LookupResult R(S, &S.PP.getIdentifierTable().get("promise_type"), KwLoc,
Richard Smith9f690bd2015-10-27 06:02:45 +000089 Sema::LookupOrdinaryName);
90 S.LookupQualifiedName(R, RD);
91 auto *Promise = R.getAsSingle<TypeDecl>();
92 if (!Promise) {
Eric Fiselier89bf0e72017-03-06 22:52:28 +000093 S.Diag(FuncLoc,
94 diag::err_implied_std_coroutine_traits_promise_type_not_found)
Gor Nishanov8df64e92016-10-27 16:28:31 +000095 << RD;
Richard Smith9f690bd2015-10-27 06:02:45 +000096 return QualType();
97 }
Richard Smith9f690bd2015-10-27 06:02:45 +000098 // The promise type is required to be a class type.
99 QualType PromiseType = S.Context.getTypeDeclType(Promise);
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000100
101 auto buildElaboratedType = [&]() {
Gor Nishanov3e048bb2016-10-04 00:31:16 +0000102 auto *NNS = NestedNameSpecifier::Create(S.Context, nullptr, StdExp);
Richard Smith9b2f53e2015-11-19 02:36:35 +0000103 NNS = NestedNameSpecifier::Create(S.Context, NNS, false,
104 CoroTrait.getTypePtr());
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000105 return S.Context.getElaboratedType(ETK_None, NNS, PromiseType);
106 };
Richard Smith9b2f53e2015-11-19 02:36:35 +0000107
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000108 if (!PromiseType->getAsCXXRecordDecl()) {
109 S.Diag(FuncLoc,
110 diag::err_implied_std_coroutine_traits_promise_type_not_class)
111 << buildElaboratedType();
Richard Smith9f690bd2015-10-27 06:02:45 +0000112 return QualType();
113 }
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000114 if (S.RequireCompleteType(FuncLoc, buildElaboratedType(),
115 diag::err_coroutine_promise_type_incomplete))
116 return QualType();
Richard Smith9f690bd2015-10-27 06:02:45 +0000117
118 return PromiseType;
119}
120
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000121/// Look up the std::coroutine_traits<...>::promise_type for the given
122/// function type.
123static QualType lookupCoroutineHandleType(Sema &S, QualType PromiseType,
124 SourceLocation Loc) {
125 if (PromiseType.isNull())
126 return QualType();
127
128 NamespaceDecl *StdExp = S.lookupStdExperimentalNamespace();
129 assert(StdExp && "Should already be diagnosed");
130
131 LookupResult Result(S, &S.PP.getIdentifierTable().get("coroutine_handle"),
132 Loc, Sema::LookupOrdinaryName);
133 if (!S.LookupQualifiedName(Result, StdExp)) {
134 S.Diag(Loc, diag::err_implied_coroutine_type_not_found)
135 << "std::experimental::coroutine_handle";
136 return QualType();
137 }
138
139 ClassTemplateDecl *CoroHandle = Result.getAsSingle<ClassTemplateDecl>();
140 if (!CoroHandle) {
141 Result.suppressDiagnostics();
142 // We found something weird. Complain about the first thing we found.
143 NamedDecl *Found = *Result.begin();
144 S.Diag(Found->getLocation(), diag::err_malformed_std_coroutine_handle);
145 return QualType();
146 }
147
148 // Form template argument list for coroutine_handle<Promise>.
149 TemplateArgumentListInfo Args(Loc, Loc);
150 Args.addArgument(TemplateArgumentLoc(
151 TemplateArgument(PromiseType),
152 S.Context.getTrivialTypeSourceInfo(PromiseType, Loc)));
153
154 // Build the template-id.
155 QualType CoroHandleType =
156 S.CheckTemplateIdType(TemplateName(CoroHandle), Loc, Args);
157 if (CoroHandleType.isNull())
158 return QualType();
159 if (S.RequireCompleteType(Loc, CoroHandleType,
160 diag::err_coroutine_type_missing_specialization))
161 return QualType();
162
163 return CoroHandleType;
164}
165
Eric Fiselierc8efda72016-10-27 18:43:28 +0000166static bool isValidCoroutineContext(Sema &S, SourceLocation Loc,
167 StringRef Keyword) {
Richard Smith744b2242015-11-20 02:54:01 +0000168 // 'co_await' and 'co_yield' are not permitted in unevaluated operands.
169 if (S.isUnevaluatedContext()) {
170 S.Diag(Loc, diag::err_coroutine_unevaluated_context) << Keyword;
Eric Fiselierc8efda72016-10-27 18:43:28 +0000171 return false;
Richard Smith744b2242015-11-20 02:54:01 +0000172 }
Richard Smithcfd53b42015-10-22 06:13:50 +0000173
174 // Any other usage must be within a function.
175 auto *FD = dyn_cast<FunctionDecl>(S.CurContext);
176 if (!FD) {
177 S.Diag(Loc, isa<ObjCMethodDecl>(S.CurContext)
178 ? diag::err_coroutine_objc_method
179 : diag::err_coroutine_outside_function) << Keyword;
Eric Fiselierc8efda72016-10-27 18:43:28 +0000180 return false;
Richard Smithcfd53b42015-10-22 06:13:50 +0000181 }
182
Eric Fiselierc8efda72016-10-27 18:43:28 +0000183 // An enumeration for mapping the diagnostic type to the correct diagnostic
184 // selection index.
185 enum InvalidFuncDiag {
186 DiagCtor = 0,
187 DiagDtor,
188 DiagCopyAssign,
189 DiagMoveAssign,
190 DiagMain,
191 DiagConstexpr,
192 DiagAutoRet,
193 DiagVarargs,
194 };
195 bool Diagnosed = false;
196 auto DiagInvalid = [&](InvalidFuncDiag ID) {
197 S.Diag(Loc, diag::err_coroutine_invalid_func_context) << ID << Keyword;
198 Diagnosed = true;
199 return false;
200 };
201
202 // Diagnose when a constructor, destructor, copy/move assignment operator,
203 // or the function 'main' are declared as a coroutine.
204 auto *MD = dyn_cast<CXXMethodDecl>(FD);
205 if (MD && isa<CXXConstructorDecl>(MD))
206 return DiagInvalid(DiagCtor);
207 else if (MD && isa<CXXDestructorDecl>(MD))
208 return DiagInvalid(DiagDtor);
209 else if (MD && MD->isCopyAssignmentOperator())
210 return DiagInvalid(DiagCopyAssign);
211 else if (MD && MD->isMoveAssignmentOperator())
212 return DiagInvalid(DiagMoveAssign);
213 else if (FD->isMain())
214 return DiagInvalid(DiagMain);
215
216 // Emit a diagnostics for each of the following conditions which is not met.
217 if (FD->isConstexpr())
218 DiagInvalid(DiagConstexpr);
219 if (FD->getReturnType()->isUndeducedType())
220 DiagInvalid(DiagAutoRet);
221 if (FD->isVariadic())
222 DiagInvalid(DiagVarargs);
223
224 return !Diagnosed;
225}
226
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000227static ExprResult buildOperatorCoawaitLookupExpr(Sema &SemaRef, Scope *S,
228 SourceLocation Loc) {
229 DeclarationName OpName =
230 SemaRef.Context.DeclarationNames.getCXXOperatorName(OO_Coawait);
231 LookupResult Operators(SemaRef, OpName, SourceLocation(),
232 Sema::LookupOperatorName);
233 SemaRef.LookupName(Operators, S);
Eric Fiselierc8efda72016-10-27 18:43:28 +0000234
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000235 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
236 const auto &Functions = Operators.asUnresolvedSet();
237 bool IsOverloaded =
238 Functions.size() > 1 ||
239 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
240 Expr *CoawaitOp = UnresolvedLookupExpr::Create(
241 SemaRef.Context, /*NamingClass*/ nullptr, NestedNameSpecifierLoc(),
242 DeclarationNameInfo(OpName, Loc), /*RequiresADL*/ true, IsOverloaded,
243 Functions.begin(), Functions.end());
244 assert(CoawaitOp);
245 return CoawaitOp;
246}
Eric Fiselierc8efda72016-10-27 18:43:28 +0000247
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000248/// Build a call to 'operator co_await' if there is a suitable operator for
249/// the given expression.
250static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, SourceLocation Loc,
251 Expr *E,
252 UnresolvedLookupExpr *Lookup) {
253 UnresolvedSet<16> Functions;
254 Functions.append(Lookup->decls_begin(), Lookup->decls_end());
255 return SemaRef.CreateOverloadedUnaryOp(Loc, UO_Coawait, Functions, E);
256}
Eric Fiselierc8efda72016-10-27 18:43:28 +0000257
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000258static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, Scope *S,
259 SourceLocation Loc, Expr *E) {
260 ExprResult R = buildOperatorCoawaitLookupExpr(SemaRef, S, Loc);
261 if (R.isInvalid())
262 return ExprError();
263 return buildOperatorCoawaitCall(SemaRef, Loc, E,
264 cast<UnresolvedLookupExpr>(R.get()));
Richard Smithcfd53b42015-10-22 06:13:50 +0000265}
266
Gor Nishanov8df64e92016-10-27 16:28:31 +0000267static Expr *buildBuiltinCall(Sema &S, SourceLocation Loc, Builtin::ID Id,
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000268 MultiExprArg CallArgs) {
Gor Nishanov8df64e92016-10-27 16:28:31 +0000269 StringRef Name = S.Context.BuiltinInfo.getName(Id);
270 LookupResult R(S, &S.Context.Idents.get(Name), Loc, Sema::LookupOrdinaryName);
271 S.LookupName(R, S.TUScope, /*AllowBuiltinCreation=*/true);
272
273 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
274 assert(BuiltInDecl && "failed to find builtin declaration");
275
276 ExprResult DeclRef =
277 S.BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
278 assert(DeclRef.isUsable() && "Builtin reference cannot fail");
279
280 ExprResult Call =
281 S.ActOnCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
282
283 assert(!Call.isInvalid() && "Call to builtin cannot fail!");
284 return Call.get();
285}
286
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000287static ExprResult buildCoroutineHandle(Sema &S, QualType PromiseType,
288 SourceLocation Loc) {
289 QualType CoroHandleType = lookupCoroutineHandleType(S, PromiseType, Loc);
290 if (CoroHandleType.isNull())
291 return ExprError();
292
293 DeclContext *LookupCtx = S.computeDeclContext(CoroHandleType);
294 LookupResult Found(S, &S.PP.getIdentifierTable().get("from_address"), Loc,
295 Sema::LookupOrdinaryName);
296 if (!S.LookupQualifiedName(Found, LookupCtx)) {
297 S.Diag(Loc, diag::err_coroutine_handle_missing_member)
298 << "from_address";
299 return ExprError();
300 }
301
302 Expr *FramePtr =
303 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_frame, {});
304
305 CXXScopeSpec SS;
306 ExprResult FromAddr =
307 S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
308 if (FromAddr.isInvalid())
309 return ExprError();
310
311 return S.ActOnCallExpr(nullptr, FromAddr.get(), Loc, FramePtr, Loc);
312}
Richard Smithcfd53b42015-10-22 06:13:50 +0000313
Richard Smith9f690bd2015-10-27 06:02:45 +0000314struct ReadySuspendResumeResult {
315 bool IsInvalid;
316 Expr *Results[3];
317};
318
Richard Smith23da82c2015-11-20 22:40:06 +0000319static ExprResult buildMemberCall(Sema &S, Expr *Base, SourceLocation Loc,
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000320 StringRef Name, MultiExprArg Args) {
Richard Smith23da82c2015-11-20 22:40:06 +0000321 DeclarationNameInfo NameInfo(&S.PP.getIdentifierTable().get(Name), Loc);
322
323 // FIXME: Fix BuildMemberReferenceExpr to take a const CXXScopeSpec&.
324 CXXScopeSpec SS;
325 ExprResult Result = S.BuildMemberReferenceExpr(
326 Base, Base->getType(), Loc, /*IsPtr=*/false, SS,
327 SourceLocation(), nullptr, NameInfo, /*TemplateArgs=*/nullptr,
328 /*Scope=*/nullptr);
329 if (Result.isInvalid())
330 return ExprError();
331
332 return S.ActOnCallExpr(nullptr, Result.get(), Loc, Args, Loc, nullptr);
333}
334
Richard Smith9f690bd2015-10-27 06:02:45 +0000335/// Build calls to await_ready, await_suspend, and await_resume for a co_await
336/// expression.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000337static ReadySuspendResumeResult buildCoawaitCalls(Sema &S, VarDecl *CoroPromise,
338 SourceLocation Loc, Expr *E) {
Richard Smith9f690bd2015-10-27 06:02:45 +0000339 // Assume invalid until we see otherwise.
340 ReadySuspendResumeResult Calls = {true, {}};
341
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000342 ExprResult CoroHandleRes = buildCoroutineHandle(S, CoroPromise->getType(), Loc);
343 if (CoroHandleRes.isInvalid())
344 return Calls;
345 Expr *CoroHandle = CoroHandleRes.get();
346
Richard Smith9f690bd2015-10-27 06:02:45 +0000347 const StringRef Funcs[] = {"await_ready", "await_suspend", "await_resume"};
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000348 MultiExprArg Args[] = {None, CoroHandle, None};
Richard Smith9f690bd2015-10-27 06:02:45 +0000349 for (size_t I = 0, N = llvm::array_lengthof(Funcs); I != N; ++I) {
Richard Smith9f690bd2015-10-27 06:02:45 +0000350 Expr *Operand = new (S.Context) OpaqueValueExpr(
Gor Nishanov8df64e92016-10-27 16:28:31 +0000351 Loc, E->getType(), VK_LValue, E->getObjectKind(), E);
Richard Smith9f690bd2015-10-27 06:02:45 +0000352
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000353 ExprResult Result = buildMemberCall(S, Operand, Loc, Funcs[I], Args[I]);
Richard Smith9f690bd2015-10-27 06:02:45 +0000354 if (Result.isInvalid())
355 return Calls;
356 Calls.Results[I] = Result.get();
357 }
358
359 Calls.IsInvalid = false;
360 return Calls;
361}
362
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000363static ExprResult buildPromiseCall(Sema &S, VarDecl *Promise,
364 SourceLocation Loc, StringRef Name,
365 MultiExprArg Args) {
366
367 // Form a reference to the promise.
368 ExprResult PromiseRef = S.BuildDeclRefExpr(
369 Promise, Promise->getType().getNonReferenceType(), VK_LValue, Loc);
370 if (PromiseRef.isInvalid())
371 return ExprError();
372
373 // Call 'yield_value', passing in E.
374 return buildMemberCall(S, PromiseRef.get(), Loc, Name, Args);
375}
376
377VarDecl *Sema::buildCoroutinePromise(SourceLocation Loc) {
378 assert(isa<FunctionDecl>(CurContext) && "not in a function scope");
379 auto *FD = cast<FunctionDecl>(CurContext);
380
381 QualType T =
382 FD->getType()->isDependentType()
383 ? Context.DependentTy
384 : lookupPromiseType(*this, FD->getType()->castAs<FunctionProtoType>(),
385 Loc, FD->getLocation());
386 if (T.isNull())
387 return nullptr;
388
389 auto *VD = VarDecl::Create(Context, FD, FD->getLocation(), FD->getLocation(),
390 &PP.getIdentifierTable().get("__promise"), T,
391 Context.getTrivialTypeSourceInfo(T, Loc), SC_None);
392 CheckVariableDeclarationType(VD);
393 if (VD->isInvalidDecl())
394 return nullptr;
395 ActOnUninitializedDecl(VD);
396 assert(!VD->isInvalidDecl());
397 return VD;
398}
399
400/// Check that this is a context in which a coroutine suspension can appear.
401static FunctionScopeInfo *checkCoroutineContext(Sema &S, SourceLocation Loc,
402 StringRef Keyword) {
403 if (!isValidCoroutineContext(S, Loc, Keyword))
404 return nullptr;
405
406 assert(isa<FunctionDecl>(S.CurContext) && "not in a function scope");
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000407
408 auto *ScopeInfo = S.getCurFunction();
409 assert(ScopeInfo && "missing function scope for function");
410
411 if (ScopeInfo->CoroutinePromise)
412 return ScopeInfo;
413
414 ScopeInfo->CoroutinePromise = S.buildCoroutinePromise(Loc);
415 if (!ScopeInfo->CoroutinePromise)
416 return nullptr;
417
418 return ScopeInfo;
419}
420
421static bool actOnCoroutineBodyStart(Sema &S, Scope *SC, SourceLocation KWLoc,
422 StringRef Keyword) {
423 if (!checkCoroutineContext(S, KWLoc, Keyword))
424 return false;
425 auto *ScopeInfo = S.getCurFunction();
426 assert(ScopeInfo->CoroutinePromise);
427
428 // If we have existing coroutine statements then we have already built
429 // the initial and final suspend points.
430 if (!ScopeInfo->NeedsCoroutineSuspends)
431 return true;
432
433 ScopeInfo->setNeedsCoroutineSuspends(false);
434
435 auto *Fn = cast<FunctionDecl>(S.CurContext);
436 SourceLocation Loc = Fn->getLocation();
437 // Build the initial suspend point
438 auto buildSuspends = [&](StringRef Name) mutable -> StmtResult {
439 ExprResult Suspend =
440 buildPromiseCall(S, ScopeInfo->CoroutinePromise, Loc, Name, None);
441 if (Suspend.isInvalid())
442 return StmtError();
443 Suspend = buildOperatorCoawaitCall(S, SC, Loc, Suspend.get());
444 if (Suspend.isInvalid())
445 return StmtError();
446 Suspend = S.BuildResolvedCoawaitExpr(Loc, Suspend.get(),
447 /*IsImplicit*/ true);
448 Suspend = S.ActOnFinishFullExpr(Suspend.get());
449 if (Suspend.isInvalid()) {
450 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
451 << ((Name == "initial_suspend") ? 0 : 1);
452 S.Diag(KWLoc, diag::note_declared_coroutine_here) << Keyword;
453 return StmtError();
454 }
455 return cast<Stmt>(Suspend.get());
456 };
457
458 StmtResult InitSuspend = buildSuspends("initial_suspend");
459 if (InitSuspend.isInvalid())
460 return true;
461
462 StmtResult FinalSuspend = buildSuspends("final_suspend");
463 if (FinalSuspend.isInvalid())
464 return true;
465
466 ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());
467
468 return true;
469}
470
Richard Smith9f690bd2015-10-27 06:02:45 +0000471ExprResult Sema::ActOnCoawaitExpr(Scope *S, SourceLocation Loc, Expr *E) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000472 if (!actOnCoroutineBodyStart(*this, S, Loc, "co_await")) {
Eric Fiseliera5465282016-09-29 21:47:39 +0000473 CorrectDelayedTyposInExpr(E);
474 return ExprError();
475 }
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000476
Richard Smith10610f72015-11-20 22:57:24 +0000477 if (E->getType()->isPlaceholderType()) {
478 ExprResult R = CheckPlaceholderExpr(E);
479 if (R.isInvalid()) return ExprError();
480 E = R.get();
481 }
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000482 ExprResult Lookup = buildOperatorCoawaitLookupExpr(*this, S, Loc);
483 if (Lookup.isInvalid())
484 return ExprError();
485 return BuildUnresolvedCoawaitExpr(Loc, E,
486 cast<UnresolvedLookupExpr>(Lookup.get()));
487}
Richard Smith10610f72015-11-20 22:57:24 +0000488
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000489ExprResult Sema::BuildUnresolvedCoawaitExpr(SourceLocation Loc, Expr *E,
490 UnresolvedLookupExpr *Lookup) {
491 auto *FSI = checkCoroutineContext(*this, Loc, "co_await");
492 if (!FSI)
493 return ExprError();
494
495 if (E->getType()->isPlaceholderType()) {
496 ExprResult R = CheckPlaceholderExpr(E);
497 if (R.isInvalid())
498 return ExprError();
499 E = R.get();
500 }
501
502 auto *Promise = FSI->CoroutinePromise;
503 if (Promise->getType()->isDependentType()) {
504 Expr *Res =
505 new (Context) DependentCoawaitExpr(Loc, Context.DependentTy, E, Lookup);
506 FSI->CoroutineStmts.push_back(Res);
507 return Res;
508 }
509
510 auto *RD = Promise->getType()->getAsCXXRecordDecl();
511 if (lookupMember(*this, "await_transform", RD, Loc)) {
512 ExprResult R = buildPromiseCall(*this, Promise, Loc, "await_transform", E);
513 if (R.isInvalid()) {
514 Diag(Loc,
515 diag::note_coroutine_promise_implicit_await_transform_required_here)
516 << E->getSourceRange();
517 return ExprError();
518 }
519 E = R.get();
520 }
521 ExprResult Awaitable = buildOperatorCoawaitCall(*this, Loc, E, Lookup);
Richard Smith9f690bd2015-10-27 06:02:45 +0000522 if (Awaitable.isInvalid())
523 return ExprError();
Eric Fiseliera5465282016-09-29 21:47:39 +0000524
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000525 return BuildResolvedCoawaitExpr(Loc, Awaitable.get());
Richard Smith9f690bd2015-10-27 06:02:45 +0000526}
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000527
528ExprResult Sema::BuildResolvedCoawaitExpr(SourceLocation Loc, Expr *E,
529 bool IsImplicit) {
Richard Smith9f690bd2015-10-27 06:02:45 +0000530 auto *Coroutine = checkCoroutineContext(*this, Loc, "co_await");
Richard Smith744b2242015-11-20 02:54:01 +0000531 if (!Coroutine)
532 return ExprError();
Richard Smith9f690bd2015-10-27 06:02:45 +0000533
Richard Smith9f690bd2015-10-27 06:02:45 +0000534 if (E->getType()->isPlaceholderType()) {
535 ExprResult R = CheckPlaceholderExpr(E);
536 if (R.isInvalid()) return ExprError();
537 E = R.get();
538 }
539
Richard Smith10610f72015-11-20 22:57:24 +0000540 if (E->getType()->isDependentType()) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000541 Expr *Res = new (Context)
542 CoawaitExpr(Loc, Context.DependentTy, E, IsImplicit);
543 if (!IsImplicit)
544 Coroutine->CoroutineStmts.push_back(Res);
Richard Smith10610f72015-11-20 22:57:24 +0000545 return Res;
546 }
547
Richard Smith1f38edd2015-11-22 03:13:02 +0000548 // If the expression is a temporary, materialize it as an lvalue so that we
549 // can use it multiple times.
550 if (E->getValueKind() == VK_RValue)
Tim Shen4a05bb82016-06-21 20:29:17 +0000551 E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
Richard Smith9f690bd2015-10-27 06:02:45 +0000552
553 // Build the await_ready, await_suspend, await_resume calls.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000554 ReadySuspendResumeResult RSS =
555 buildCoawaitCalls(*this, Coroutine->CoroutinePromise, Loc, E);
Richard Smith9f690bd2015-10-27 06:02:45 +0000556 if (RSS.IsInvalid)
557 return ExprError();
558
559 Expr *Res = new (Context) CoawaitExpr(Loc, E, RSS.Results[0], RSS.Results[1],
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000560 RSS.Results[2], IsImplicit);
561 if (!IsImplicit)
562 Coroutine->CoroutineStmts.push_back(Res);
Richard Smithcfd53b42015-10-22 06:13:50 +0000563 return Res;
564}
565
Richard Smith9f690bd2015-10-27 06:02:45 +0000566ExprResult Sema::ActOnCoyieldExpr(Scope *S, SourceLocation Loc, Expr *E) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000567 if (!actOnCoroutineBodyStart(*this, S, Loc, "co_yield")) {
Eric Fiseliera5465282016-09-29 21:47:39 +0000568 CorrectDelayedTyposInExpr(E);
Richard Smith23da82c2015-11-20 22:40:06 +0000569 return ExprError();
Eric Fiseliera5465282016-09-29 21:47:39 +0000570 }
Richard Smith23da82c2015-11-20 22:40:06 +0000571
572 // Build yield_value call.
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000573 ExprResult Awaitable = buildPromiseCall(
574 *this, getCurFunction()->CoroutinePromise, Loc, "yield_value", E);
Richard Smith9f690bd2015-10-27 06:02:45 +0000575 if (Awaitable.isInvalid())
576 return ExprError();
Richard Smith23da82c2015-11-20 22:40:06 +0000577
578 // Build 'operator co_await' call.
579 Awaitable = buildOperatorCoawaitCall(*this, S, Loc, Awaitable.get());
580 if (Awaitable.isInvalid())
581 return ExprError();
582
Richard Smith9f690bd2015-10-27 06:02:45 +0000583 return BuildCoyieldExpr(Loc, Awaitable.get());
584}
585ExprResult Sema::BuildCoyieldExpr(SourceLocation Loc, Expr *E) {
586 auto *Coroutine = checkCoroutineContext(*this, Loc, "co_yield");
Richard Smith744b2242015-11-20 02:54:01 +0000587 if (!Coroutine)
588 return ExprError();
Richard Smithcfd53b42015-10-22 06:13:50 +0000589
Richard Smith10610f72015-11-20 22:57:24 +0000590 if (E->getType()->isPlaceholderType()) {
591 ExprResult R = CheckPlaceholderExpr(E);
592 if (R.isInvalid()) return ExprError();
593 E = R.get();
594 }
595
Richard Smithd7bed4d2015-11-22 02:57:17 +0000596 if (E->getType()->isDependentType()) {
597 Expr *Res = new (Context) CoyieldExpr(Loc, Context.DependentTy, E);
598 Coroutine->CoroutineStmts.push_back(Res);
599 return Res;
600 }
601
Richard Smith1f38edd2015-11-22 03:13:02 +0000602 // If the expression is a temporary, materialize it as an lvalue so that we
603 // can use it multiple times.
604 if (E->getValueKind() == VK_RValue)
Tim Shen4a05bb82016-06-21 20:29:17 +0000605 E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
Richard Smithd7bed4d2015-11-22 02:57:17 +0000606
607 // Build the await_ready, await_suspend, await_resume calls.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000608 ReadySuspendResumeResult RSS =
609 buildCoawaitCalls(*this, Coroutine->CoroutinePromise, Loc, E);
Richard Smithd7bed4d2015-11-22 02:57:17 +0000610 if (RSS.IsInvalid)
611 return ExprError();
612
613 Expr *Res = new (Context) CoyieldExpr(Loc, E, RSS.Results[0], RSS.Results[1],
614 RSS.Results[2]);
Richard Smith744b2242015-11-20 02:54:01 +0000615 Coroutine->CoroutineStmts.push_back(Res);
Richard Smithcfd53b42015-10-22 06:13:50 +0000616 return Res;
617}
618
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000619StmtResult Sema::ActOnCoreturnStmt(Scope *S, SourceLocation Loc, Expr *E) {
620 if (!actOnCoroutineBodyStart(*this, S, Loc, "co_return")) {
Eric Fiseliera5465282016-09-29 21:47:39 +0000621 CorrectDelayedTyposInExpr(E);
622 return StmtError();
623 }
Richard Smith9f690bd2015-10-27 06:02:45 +0000624 return BuildCoreturnStmt(Loc, E);
625}
Gor Nishanov3e048bb2016-10-04 00:31:16 +0000626
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000627StmtResult Sema::BuildCoreturnStmt(SourceLocation Loc, Expr *E,
628 bool IsImplicit) {
629 auto *FSI = checkCoroutineContext(*this, Loc, "co_return");
630 if (!FSI)
Richard Smith71d403e2015-11-22 07:33:28 +0000631 return StmtError();
632
633 if (E && E->getType()->isPlaceholderType() &&
634 !E->getType()->isSpecificPlaceholderType(BuiltinType::Overload)) {
Richard Smith10610f72015-11-20 22:57:24 +0000635 ExprResult R = CheckPlaceholderExpr(E);
636 if (R.isInvalid()) return StmtError();
637 E = R.get();
638 }
639
Richard Smith4ba66602015-11-22 07:05:16 +0000640 // FIXME: If the operand is a reference to a variable that's about to go out
Richard Smith2af65c42015-11-24 02:34:39 +0000641 // of scope, we should treat the operand as an xvalue for this overload
Richard Smith4ba66602015-11-22 07:05:16 +0000642 // resolution.
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000643 VarDecl *Promise = FSI->CoroutinePromise;
Richard Smith4ba66602015-11-22 07:05:16 +0000644 ExprResult PC;
Eric Fiselier98131312016-10-06 21:23:38 +0000645 if (E && (isa<InitListExpr>(E) || !E->getType()->isVoidType())) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000646 PC = buildPromiseCall(*this, Promise, Loc, "return_value", E);
Richard Smith4ba66602015-11-22 07:05:16 +0000647 } else {
648 E = MakeFullDiscardedValueExpr(E).get();
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000649 PC = buildPromiseCall(*this, Promise, Loc, "return_void", None);
Richard Smith4ba66602015-11-22 07:05:16 +0000650 }
651 if (PC.isInvalid())
652 return StmtError();
653
654 Expr *PCE = ActOnFinishFullExpr(PC.get()).get();
655
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000656 Stmt *Res = new (Context) CoreturnStmt(Loc, E, PCE, IsImplicit);
657 if (!IsImplicit)
658 FSI->CoroutineStmts.push_back(Res);
Richard Smithcfd53b42015-10-22 06:13:50 +0000659 return Res;
660}
661
Eric Fiselier709d1b32016-10-27 07:30:31 +0000662static ExprResult buildStdCurrentExceptionCall(Sema &S, SourceLocation Loc) {
663 NamespaceDecl *Std = S.getStdNamespace();
664 if (!Std) {
665 S.Diag(Loc, diag::err_implied_std_current_exception_not_found);
666 return ExprError();
667 }
668 LookupResult Result(S, &S.PP.getIdentifierTable().get("current_exception"),
669 Loc, Sema::LookupOrdinaryName);
670 if (!S.LookupQualifiedName(Result, Std)) {
671 S.Diag(Loc, diag::err_implied_std_current_exception_not_found);
672 return ExprError();
673 }
674
675 // FIXME The STL is free to provide more than one overload.
676 FunctionDecl *FD = Result.getAsSingle<FunctionDecl>();
677 if (!FD) {
678 S.Diag(Loc, diag::err_malformed_std_current_exception);
679 return ExprError();
680 }
681 ExprResult Res = S.BuildDeclRefExpr(FD, FD->getType(), VK_LValue, Loc);
682 Res = S.ActOnCallExpr(/*Scope*/ nullptr, Res.get(), Loc, None, Loc);
683 if (Res.isInvalid()) {
684 S.Diag(Loc, diag::err_malformed_std_current_exception);
685 return ExprError();
686 }
687 return Res;
688}
689
Gor Nishanov8df64e92016-10-27 16:28:31 +0000690// Find an appropriate delete for the promise.
691static FunctionDecl *findDeleteForPromise(Sema &S, SourceLocation Loc,
692 QualType PromiseType) {
693 FunctionDecl *OperatorDelete = nullptr;
694
695 DeclarationName DeleteName =
696 S.Context.DeclarationNames.getCXXOperatorName(OO_Delete);
697
698 auto *PointeeRD = PromiseType->getAsCXXRecordDecl();
699 assert(PointeeRD && "PromiseType must be a CxxRecordDecl type");
700
701 if (S.FindDeallocationFunction(Loc, PointeeRD, DeleteName, OperatorDelete))
702 return nullptr;
703
704 if (!OperatorDelete) {
705 // Look for a global declaration.
706 const bool CanProvideSize = S.isCompleteType(Loc, PromiseType);
707 const bool Overaligned = false;
708 OperatorDelete = S.FindUsualDeallocationFunction(Loc, CanProvideSize,
709 Overaligned, DeleteName);
710 }
711 S.MarkFunctionReferenced(Loc, OperatorDelete);
712 return OperatorDelete;
713}
714
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000715namespace {
716class SubStmtBuilder : public CoroutineBodyStmt::CtorArgs {
717 Sema &S;
718 FunctionDecl &FD;
719 FunctionScopeInfo &Fn;
720 bool IsValid;
721 SourceLocation Loc;
722 QualType RetType;
723 SmallVector<Stmt *, 4> ParamMovesVector;
724 const bool IsPromiseDependentType;
725 CXXRecordDecl *PromiseRecordDecl = nullptr;
726
727public:
728 SubStmtBuilder(Sema &S, FunctionDecl &FD, FunctionScopeInfo &Fn, Stmt *Body)
729 : S(S), FD(FD), Fn(Fn), Loc(FD.getLocation()),
730 IsPromiseDependentType(
731 !Fn.CoroutinePromise ||
732 Fn.CoroutinePromise->getType()->isDependentType()) {
733 this->Body = Body;
734 if (!IsPromiseDependentType) {
735 PromiseRecordDecl = Fn.CoroutinePromise->getType()->getAsCXXRecordDecl();
736 assert(PromiseRecordDecl && "Type should have already been checked");
737 }
738 this->IsValid = makePromiseStmt() && makeInitialAndFinalSuspend() &&
739 makeOnException() && makeOnFallthrough() &&
740 makeNewAndDeleteExpr() && makeReturnObject() &&
741 makeParamMoves();
742 }
743
744 bool isInvalid() const { return !this->IsValid; }
745
746 bool makePromiseStmt();
747 bool makeInitialAndFinalSuspend();
748 bool makeNewAndDeleteExpr();
749 bool makeOnFallthrough();
750 bool makeOnException();
751 bool makeReturnObject();
752 bool makeParamMoves();
753};
754}
755
756void Sema::CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body) {
757 FunctionScopeInfo *Fn = getCurFunction();
758 assert(Fn && Fn->CoroutinePromise && "not a coroutine");
759
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000760 if (!Body) {
761 assert(FD->isInvalidDecl() &&
762 "a null body is only allowed for invalid declarations");
763 return;
764 }
765
766 if (isa<CoroutineBodyStmt>(Body)) {
767 // FIXME(EricWF): Nothing todo. the body is already a transformed coroutine
768 // body statement.
769 return;
770 }
771
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000772 // Coroutines [stmt.return]p1:
773 // A return statement shall not appear in a coroutine.
774 if (Fn->FirstReturnLoc.isValid()) {
775 Diag(Fn->FirstReturnLoc, diag::err_return_in_coroutine);
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000776 // FIXME: Every Coroutine statement may be invalid and therefore not added
777 // to CoroutineStmts. Find another way to provide location information.
778 if (!Fn->CoroutineStmts.empty()) {
779 auto *First = Fn->CoroutineStmts[0];
780 Diag(First->getLocStart(), diag::note_declared_coroutine_here)
781 << (isa<CoawaitExpr>(First) ? "co_await" :
782 isa<CoyieldExpr>(First) ? "co_yield" : "co_return");
783 }
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000784 }
785 SubStmtBuilder Builder(*this, *FD, *Fn, Body);
786 if (Builder.isInvalid())
787 return FD->setInvalidDecl();
788
789 // Build body for the coroutine wrapper statement.
790 Body = CoroutineBodyStmt::Create(Context, Builder);
791}
792
793bool SubStmtBuilder::makePromiseStmt() {
794 // Form a declaration statement for the promise declaration, so that AST
795 // visitors can more easily find it.
796 StmtResult PromiseStmt =
797 S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(Fn.CoroutinePromise), Loc, Loc);
798 if (PromiseStmt.isInvalid())
799 return false;
800
801 this->Promise = PromiseStmt.get();
802 return true;
803}
804
805bool SubStmtBuilder::makeInitialAndFinalSuspend() {
806 if (Fn.hasInvalidCoroutineSuspends())
807 return false;
808 this->InitialSuspend = cast<Expr>(Fn.CoroutineSuspends.first);
809 this->FinalSuspend = cast<Expr>(Fn.CoroutineSuspends.second);
810 return true;
811}
812
813bool SubStmtBuilder::makeNewAndDeleteExpr() {
814 // Form and check allocation and deallocation calls.
815 QualType PromiseType = Fn.CoroutinePromise->getType();
Gor Nishanov8df64e92016-10-27 16:28:31 +0000816 if (PromiseType->isDependentType())
817 return true;
818
819 if (S.RequireCompleteType(Loc, PromiseType, diag::err_incomplete_type))
820 return false;
821
822 // FIXME: Add support for get_return_object_on_allocation failure.
823 // FIXME: Add support for stateful allocators.
824
825 FunctionDecl *OperatorNew = nullptr;
826 FunctionDecl *OperatorDelete = nullptr;
827 FunctionDecl *UnusedResult = nullptr;
828 bool PassAlignment = false;
829
830 S.FindAllocationFunctions(Loc, SourceRange(),
831 /*UseGlobal*/ false, PromiseType,
832 /*isArray*/ false, PassAlignment,
833 /*PlacementArgs*/ None, OperatorNew, UnusedResult);
834
835 OperatorDelete = findDeleteForPromise(S, Loc, PromiseType);
836
837 if (!OperatorDelete || !OperatorNew)
838 return false;
839
840 Expr *FramePtr =
841 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_frame, {});
842
843 Expr *FrameSize =
844 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_size, {});
845
846 // Make new call.
847
848 ExprResult NewRef =
849 S.BuildDeclRefExpr(OperatorNew, OperatorNew->getType(), VK_LValue, Loc);
850 if (NewRef.isInvalid())
851 return false;
852
853 ExprResult NewExpr =
854 S.ActOnCallExpr(S.getCurScope(), NewRef.get(), Loc, FrameSize, Loc);
855 if (NewExpr.isInvalid())
856 return false;
857
Gor Nishanov8df64e92016-10-27 16:28:31 +0000858 // Make delete call.
859
860 QualType OpDeleteQualType = OperatorDelete->getType();
861
862 ExprResult DeleteRef =
863 S.BuildDeclRefExpr(OperatorDelete, OpDeleteQualType, VK_LValue, Loc);
864 if (DeleteRef.isInvalid())
865 return false;
866
867 Expr *CoroFree =
868 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_free, {FramePtr});
869
870 SmallVector<Expr *, 2> DeleteArgs{CoroFree};
871
872 // Check if we need to pass the size.
873 const auto *OpDeleteType =
874 OpDeleteQualType.getTypePtr()->getAs<FunctionProtoType>();
875 if (OpDeleteType->getNumParams() > 1)
876 DeleteArgs.push_back(FrameSize);
877
878 ExprResult DeleteExpr =
879 S.ActOnCallExpr(S.getCurScope(), DeleteRef.get(), Loc, DeleteArgs, Loc);
880 if (DeleteExpr.isInvalid())
881 return false;
882
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000883 this->Allocate = NewExpr.get();
884 this->Deallocate = DeleteExpr.get();
Gor Nishanov8df64e92016-10-27 16:28:31 +0000885
886 return true;
887}
888
Gor Nishanovbbe1c072017-02-13 05:05:02 +0000889bool SubStmtBuilder::makeOnFallthrough() {
890 if (!PromiseRecordDecl)
891 return true;
892
893 // [dcl.fct.def.coroutine]/4
894 // The unqualified-ids 'return_void' and 'return_value' are looked up in
895 // the scope of class P. If both are found, the program is ill-formed.
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000896 const bool HasRVoid = lookupMember(S, "return_void", PromiseRecordDecl, Loc);
897 const bool HasRValue = lookupMember(S, "return_value", PromiseRecordDecl, Loc);
Gor Nishanovbbe1c072017-02-13 05:05:02 +0000898
Eric Fiselier709d1b32016-10-27 07:30:31 +0000899 StmtResult Fallthrough;
Gor Nishanovbbe1c072017-02-13 05:05:02 +0000900 if (HasRVoid && HasRValue) {
901 // FIXME Improve this diagnostic
902 S.Diag(FD.getLocation(), diag::err_coroutine_promise_return_ill_formed)
903 << PromiseRecordDecl;
904 return false;
905 } else if (HasRVoid) {
906 // If the unqualified-id return_void is found, flowing off the end of a
907 // coroutine is equivalent to a co_return with no operand. Otherwise,
908 // flowing off the end of a coroutine results in undefined behavior.
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000909 Fallthrough = S.BuildCoreturnStmt(FD.getLocation(), nullptr,
910 /*IsImplicit*/false);
Gor Nishanovbbe1c072017-02-13 05:05:02 +0000911 Fallthrough = S.ActOnFinishFullStmt(Fallthrough.get());
912 if (Fallthrough.isInvalid())
913 return false;
Eric Fiselier709d1b32016-10-27 07:30:31 +0000914 }
Richard Smith2af65c42015-11-24 02:34:39 +0000915
Gor Nishanovbbe1c072017-02-13 05:05:02 +0000916 this->OnFallthrough = Fallthrough.get();
917 return true;
918}
919
920bool SubStmtBuilder::makeOnException() {
921 // Try to form 'p.set_exception(std::current_exception());' to handle
922 // uncaught exceptions.
923 // TODO: Post WG21 Issaquah 2016 renamed set_exception to unhandled_exception
924 // TODO: and dropped exception_ptr parameter. Make it so.
925
926 if (!PromiseRecordDecl)
927 return true;
928
929 // If exceptions are disabled, don't try to build OnException.
930 if (!S.getLangOpts().CXXExceptions)
931 return true;
932
933 ExprResult SetException;
934
935 // [dcl.fct.def.coroutine]/3
936 // The unqualified-id set_exception is found in the scope of P by class
937 // member access lookup (3.4.5).
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000938 if (lookupMember(S, "set_exception", PromiseRecordDecl, Loc)) {
Gor Nishanovbbe1c072017-02-13 05:05:02 +0000939 // Form the call 'p.set_exception(std::current_exception())'
940 SetException = buildStdCurrentExceptionCall(S, Loc);
941 if (SetException.isInvalid())
942 return false;
943 Expr *E = SetException.get();
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000944 SetException = buildPromiseCall(S, Fn.CoroutinePromise, Loc, "set_exception", E);
Gor Nishanovbbe1c072017-02-13 05:05:02 +0000945 SetException = S.ActOnFinishFullExpr(SetException.get(), Loc);
946 if (SetException.isInvalid())
947 return false;
948 }
949
950 this->OnException = SetException.get();
951 return true;
952}
953
954bool SubStmtBuilder::makeReturnObject() {
955
Richard Smith2af65c42015-11-24 02:34:39 +0000956 // Build implicit 'p.get_return_object()' expression and form initialization
957 // of return type from it.
958 ExprResult ReturnObject =
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000959 buildPromiseCall(S, Fn.CoroutinePromise, Loc, "get_return_object", None);
Richard Smith2af65c42015-11-24 02:34:39 +0000960 if (ReturnObject.isInvalid())
Gor Nishanovbbe1c072017-02-13 05:05:02 +0000961 return false;
962 QualType RetType = FD.getReturnType();
Richard Smith2af65c42015-11-24 02:34:39 +0000963 if (!RetType->isDependentType()) {
964 InitializedEntity Entity =
965 InitializedEntity::InitializeResult(Loc, RetType, false);
Gor Nishanovbbe1c072017-02-13 05:05:02 +0000966 ReturnObject = S.PerformMoveOrCopyInitialization(Entity, nullptr, RetType,
Richard Smith2af65c42015-11-24 02:34:39 +0000967 ReturnObject.get());
968 if (ReturnObject.isInvalid())
Gor Nishanovbbe1c072017-02-13 05:05:02 +0000969 return false;
Richard Smith2af65c42015-11-24 02:34:39 +0000970 }
Gor Nishanovbbe1c072017-02-13 05:05:02 +0000971 ReturnObject = S.ActOnFinishFullExpr(ReturnObject.get(), Loc);
Richard Smith2af65c42015-11-24 02:34:39 +0000972 if (ReturnObject.isInvalid())
Gor Nishanovbbe1c072017-02-13 05:05:02 +0000973 return false;
Richard Smith2af65c42015-11-24 02:34:39 +0000974
Gor Nishanovbbe1c072017-02-13 05:05:02 +0000975 this->ReturnValue = ReturnObject.get();
976 return true;
977}
978
979bool SubStmtBuilder::makeParamMoves() {
Richard Smith2af65c42015-11-24 02:34:39 +0000980 // FIXME: Perform move-initialization of parameters into frame-local copies.
Gor Nishanovbbe1c072017-02-13 05:05:02 +0000981 return true;
Richard Smithcfd53b42015-10-22 06:13:50 +0000982}
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000983
984StmtResult Sema::BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
985 CoroutineBodyStmt *Res = CoroutineBodyStmt::Create(Context, Args);
986 if (!Res)
987 return StmtError();
988 return Res;
989}