blob: 309194f396d64c8566ea1035b9862595a7dfddc0 [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 {
Richard Smith9f690bd2015-10-27 06:02:45 +0000315 Expr *Results[3];
Gor Nishanovce43bd22017-03-11 01:30:17 +0000316 OpaqueValueExpr *OpaqueValue;
317 bool IsInvalid;
Richard Smith9f690bd2015-10-27 06:02:45 +0000318};
319
Richard Smith23da82c2015-11-20 22:40:06 +0000320static ExprResult buildMemberCall(Sema &S, Expr *Base, SourceLocation Loc,
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000321 StringRef Name, MultiExprArg Args) {
Richard Smith23da82c2015-11-20 22:40:06 +0000322 DeclarationNameInfo NameInfo(&S.PP.getIdentifierTable().get(Name), Loc);
323
324 // FIXME: Fix BuildMemberReferenceExpr to take a const CXXScopeSpec&.
325 CXXScopeSpec SS;
326 ExprResult Result = S.BuildMemberReferenceExpr(
327 Base, Base->getType(), Loc, /*IsPtr=*/false, SS,
328 SourceLocation(), nullptr, NameInfo, /*TemplateArgs=*/nullptr,
329 /*Scope=*/nullptr);
330 if (Result.isInvalid())
331 return ExprError();
332
333 return S.ActOnCallExpr(nullptr, Result.get(), Loc, Args, Loc, nullptr);
334}
335
Richard Smith9f690bd2015-10-27 06:02:45 +0000336/// Build calls to await_ready, await_suspend, and await_resume for a co_await
337/// expression.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000338static ReadySuspendResumeResult buildCoawaitCalls(Sema &S, VarDecl *CoroPromise,
339 SourceLocation Loc, Expr *E) {
Gor Nishanovce43bd22017-03-11 01:30:17 +0000340 OpaqueValueExpr *Operand = new (S.Context)
341 OpaqueValueExpr(Loc, E->getType(), VK_LValue, E->getObjectKind(), E);
342
Richard Smith9f690bd2015-10-27 06:02:45 +0000343 // Assume invalid until we see otherwise.
Gor Nishanovce43bd22017-03-11 01:30:17 +0000344 ReadySuspendResumeResult Calls = {{}, Operand, /*IsInvalid=*/true};
Richard Smith9f690bd2015-10-27 06:02:45 +0000345
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000346 ExprResult CoroHandleRes = buildCoroutineHandle(S, CoroPromise->getType(), Loc);
347 if (CoroHandleRes.isInvalid())
348 return Calls;
349 Expr *CoroHandle = CoroHandleRes.get();
350
Richard Smith9f690bd2015-10-27 06:02:45 +0000351 const StringRef Funcs[] = {"await_ready", "await_suspend", "await_resume"};
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000352 MultiExprArg Args[] = {None, CoroHandle, None};
Richard Smith9f690bd2015-10-27 06:02:45 +0000353 for (size_t I = 0, N = llvm::array_lengthof(Funcs); I != N; ++I) {
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000354 ExprResult Result = buildMemberCall(S, Operand, Loc, Funcs[I], Args[I]);
Richard Smith9f690bd2015-10-27 06:02:45 +0000355 if (Result.isInvalid())
356 return Calls;
357 Calls.Results[I] = Result.get();
358 }
359
360 Calls.IsInvalid = false;
361 return Calls;
362}
363
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000364static ExprResult buildPromiseCall(Sema &S, VarDecl *Promise,
365 SourceLocation Loc, StringRef Name,
366 MultiExprArg Args) {
367
368 // Form a reference to the promise.
369 ExprResult PromiseRef = S.BuildDeclRefExpr(
370 Promise, Promise->getType().getNonReferenceType(), VK_LValue, Loc);
371 if (PromiseRef.isInvalid())
372 return ExprError();
373
374 // Call 'yield_value', passing in E.
375 return buildMemberCall(S, PromiseRef.get(), Loc, Name, Args);
376}
377
378VarDecl *Sema::buildCoroutinePromise(SourceLocation Loc) {
379 assert(isa<FunctionDecl>(CurContext) && "not in a function scope");
380 auto *FD = cast<FunctionDecl>(CurContext);
381
382 QualType T =
383 FD->getType()->isDependentType()
384 ? Context.DependentTy
385 : lookupPromiseType(*this, FD->getType()->castAs<FunctionProtoType>(),
386 Loc, FD->getLocation());
387 if (T.isNull())
388 return nullptr;
389
390 auto *VD = VarDecl::Create(Context, FD, FD->getLocation(), FD->getLocation(),
391 &PP.getIdentifierTable().get("__promise"), T,
392 Context.getTrivialTypeSourceInfo(T, Loc), SC_None);
393 CheckVariableDeclarationType(VD);
394 if (VD->isInvalidDecl())
395 return nullptr;
396 ActOnUninitializedDecl(VD);
397 assert(!VD->isInvalidDecl());
398 return VD;
399}
400
401/// Check that this is a context in which a coroutine suspension can appear.
402static FunctionScopeInfo *checkCoroutineContext(Sema &S, SourceLocation Loc,
Eric Fiseliercac0a592017-03-11 02:35:37 +0000403 StringRef Keyword,
404 bool IsImplicit = false) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000405 if (!isValidCoroutineContext(S, Loc, Keyword))
406 return nullptr;
407
408 assert(isa<FunctionDecl>(S.CurContext) && "not in a function scope");
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000409
410 auto *ScopeInfo = S.getCurFunction();
411 assert(ScopeInfo && "missing function scope for function");
412
Eric Fiseliercac0a592017-03-11 02:35:37 +0000413 if (ScopeInfo->FirstCoroutineStmtLoc.isInvalid() && !IsImplicit)
414 ScopeInfo->setFirstCoroutineStmt(Loc, Keyword);
415
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000416 if (ScopeInfo->CoroutinePromise)
417 return ScopeInfo;
418
419 ScopeInfo->CoroutinePromise = S.buildCoroutinePromise(Loc);
420 if (!ScopeInfo->CoroutinePromise)
421 return nullptr;
422
423 return ScopeInfo;
424}
425
426static bool actOnCoroutineBodyStart(Sema &S, Scope *SC, SourceLocation KWLoc,
427 StringRef Keyword) {
428 if (!checkCoroutineContext(S, KWLoc, Keyword))
429 return false;
430 auto *ScopeInfo = S.getCurFunction();
431 assert(ScopeInfo->CoroutinePromise);
432
433 // If we have existing coroutine statements then we have already built
434 // the initial and final suspend points.
435 if (!ScopeInfo->NeedsCoroutineSuspends)
436 return true;
437
438 ScopeInfo->setNeedsCoroutineSuspends(false);
439
440 auto *Fn = cast<FunctionDecl>(S.CurContext);
441 SourceLocation Loc = Fn->getLocation();
442 // Build the initial suspend point
443 auto buildSuspends = [&](StringRef Name) mutable -> StmtResult {
444 ExprResult Suspend =
445 buildPromiseCall(S, ScopeInfo->CoroutinePromise, Loc, Name, None);
446 if (Suspend.isInvalid())
447 return StmtError();
448 Suspend = buildOperatorCoawaitCall(S, SC, Loc, Suspend.get());
449 if (Suspend.isInvalid())
450 return StmtError();
451 Suspend = S.BuildResolvedCoawaitExpr(Loc, Suspend.get(),
452 /*IsImplicit*/ true);
453 Suspend = S.ActOnFinishFullExpr(Suspend.get());
454 if (Suspend.isInvalid()) {
455 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
456 << ((Name == "initial_suspend") ? 0 : 1);
457 S.Diag(KWLoc, diag::note_declared_coroutine_here) << Keyword;
458 return StmtError();
459 }
460 return cast<Stmt>(Suspend.get());
461 };
462
463 StmtResult InitSuspend = buildSuspends("initial_suspend");
464 if (InitSuspend.isInvalid())
465 return true;
466
467 StmtResult FinalSuspend = buildSuspends("final_suspend");
468 if (FinalSuspend.isInvalid())
469 return true;
470
471 ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());
472
473 return true;
474}
475
Richard Smith9f690bd2015-10-27 06:02:45 +0000476ExprResult Sema::ActOnCoawaitExpr(Scope *S, SourceLocation Loc, Expr *E) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000477 if (!actOnCoroutineBodyStart(*this, S, Loc, "co_await")) {
Eric Fiseliera5465282016-09-29 21:47:39 +0000478 CorrectDelayedTyposInExpr(E);
479 return ExprError();
480 }
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000481
Richard Smith10610f72015-11-20 22:57:24 +0000482 if (E->getType()->isPlaceholderType()) {
483 ExprResult R = CheckPlaceholderExpr(E);
484 if (R.isInvalid()) return ExprError();
485 E = R.get();
486 }
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000487 ExprResult Lookup = buildOperatorCoawaitLookupExpr(*this, S, Loc);
488 if (Lookup.isInvalid())
489 return ExprError();
490 return BuildUnresolvedCoawaitExpr(Loc, E,
491 cast<UnresolvedLookupExpr>(Lookup.get()));
492}
Richard Smith10610f72015-11-20 22:57:24 +0000493
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000494ExprResult Sema::BuildUnresolvedCoawaitExpr(SourceLocation Loc, Expr *E,
Eric Fiseliercac0a592017-03-11 02:35:37 +0000495 UnresolvedLookupExpr *Lookup) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000496 auto *FSI = checkCoroutineContext(*this, Loc, "co_await");
497 if (!FSI)
498 return ExprError();
499
500 if (E->getType()->isPlaceholderType()) {
501 ExprResult R = CheckPlaceholderExpr(E);
502 if (R.isInvalid())
503 return ExprError();
504 E = R.get();
505 }
506
507 auto *Promise = FSI->CoroutinePromise;
508 if (Promise->getType()->isDependentType()) {
509 Expr *Res =
510 new (Context) DependentCoawaitExpr(Loc, Context.DependentTy, E, Lookup);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000511 return Res;
512 }
513
514 auto *RD = Promise->getType()->getAsCXXRecordDecl();
515 if (lookupMember(*this, "await_transform", RD, Loc)) {
516 ExprResult R = buildPromiseCall(*this, Promise, Loc, "await_transform", E);
517 if (R.isInvalid()) {
518 Diag(Loc,
519 diag::note_coroutine_promise_implicit_await_transform_required_here)
520 << E->getSourceRange();
521 return ExprError();
522 }
523 E = R.get();
524 }
525 ExprResult Awaitable = buildOperatorCoawaitCall(*this, Loc, E, Lookup);
Richard Smith9f690bd2015-10-27 06:02:45 +0000526 if (Awaitable.isInvalid())
527 return ExprError();
Eric Fiseliera5465282016-09-29 21:47:39 +0000528
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000529 return BuildResolvedCoawaitExpr(Loc, Awaitable.get());
Richard Smith9f690bd2015-10-27 06:02:45 +0000530}
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000531
532ExprResult Sema::BuildResolvedCoawaitExpr(SourceLocation Loc, Expr *E,
533 bool IsImplicit) {
Eric Fiseliercac0a592017-03-11 02:35:37 +0000534 auto *Coroutine = checkCoroutineContext(*this, Loc, "co_await", IsImplicit);
Richard Smith744b2242015-11-20 02:54:01 +0000535 if (!Coroutine)
536 return ExprError();
Richard Smith9f690bd2015-10-27 06:02:45 +0000537
Richard Smith9f690bd2015-10-27 06:02:45 +0000538 if (E->getType()->isPlaceholderType()) {
539 ExprResult R = CheckPlaceholderExpr(E);
540 if (R.isInvalid()) return ExprError();
541 E = R.get();
542 }
543
Richard Smith10610f72015-11-20 22:57:24 +0000544 if (E->getType()->isDependentType()) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000545 Expr *Res = new (Context)
546 CoawaitExpr(Loc, Context.DependentTy, E, IsImplicit);
Richard Smith10610f72015-11-20 22:57:24 +0000547 return Res;
548 }
549
Richard Smith1f38edd2015-11-22 03:13:02 +0000550 // If the expression is a temporary, materialize it as an lvalue so that we
551 // can use it multiple times.
552 if (E->getValueKind() == VK_RValue)
Tim Shen4a05bb82016-06-21 20:29:17 +0000553 E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
Richard Smith9f690bd2015-10-27 06:02:45 +0000554
555 // Build the await_ready, await_suspend, await_resume calls.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000556 ReadySuspendResumeResult RSS =
557 buildCoawaitCalls(*this, Coroutine->CoroutinePromise, Loc, E);
Richard Smith9f690bd2015-10-27 06:02:45 +0000558 if (RSS.IsInvalid)
559 return ExprError();
560
Gor Nishanovce43bd22017-03-11 01:30:17 +0000561 Expr *Res =
562 new (Context) CoawaitExpr(Loc, E, RSS.Results[0], RSS.Results[1],
563 RSS.Results[2], RSS.OpaqueValue, IsImplicit);
Eric Fiseliercac0a592017-03-11 02:35:37 +0000564
Richard Smithcfd53b42015-10-22 06:13:50 +0000565 return Res;
566}
567
Richard Smith9f690bd2015-10-27 06:02:45 +0000568ExprResult Sema::ActOnCoyieldExpr(Scope *S, SourceLocation Loc, Expr *E) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000569 if (!actOnCoroutineBodyStart(*this, S, Loc, "co_yield")) {
Eric Fiseliera5465282016-09-29 21:47:39 +0000570 CorrectDelayedTyposInExpr(E);
Richard Smith23da82c2015-11-20 22:40:06 +0000571 return ExprError();
Eric Fiseliera5465282016-09-29 21:47:39 +0000572 }
Richard Smith23da82c2015-11-20 22:40:06 +0000573
574 // Build yield_value call.
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000575 ExprResult Awaitable = buildPromiseCall(
576 *this, getCurFunction()->CoroutinePromise, Loc, "yield_value", E);
Richard Smith9f690bd2015-10-27 06:02:45 +0000577 if (Awaitable.isInvalid())
578 return ExprError();
Richard Smith23da82c2015-11-20 22:40:06 +0000579
580 // Build 'operator co_await' call.
581 Awaitable = buildOperatorCoawaitCall(*this, S, Loc, Awaitable.get());
582 if (Awaitable.isInvalid())
583 return ExprError();
584
Richard Smith9f690bd2015-10-27 06:02:45 +0000585 return BuildCoyieldExpr(Loc, Awaitable.get());
586}
587ExprResult Sema::BuildCoyieldExpr(SourceLocation Loc, Expr *E) {
588 auto *Coroutine = checkCoroutineContext(*this, Loc, "co_yield");
Richard Smith744b2242015-11-20 02:54:01 +0000589 if (!Coroutine)
590 return ExprError();
Richard Smithcfd53b42015-10-22 06:13:50 +0000591
Richard Smith10610f72015-11-20 22:57:24 +0000592 if (E->getType()->isPlaceholderType()) {
593 ExprResult R = CheckPlaceholderExpr(E);
594 if (R.isInvalid()) return ExprError();
595 E = R.get();
596 }
597
Richard Smithd7bed4d2015-11-22 02:57:17 +0000598 if (E->getType()->isDependentType()) {
599 Expr *Res = new (Context) CoyieldExpr(Loc, Context.DependentTy, E);
Richard Smithd7bed4d2015-11-22 02:57:17 +0000600 return Res;
601 }
602
Richard Smith1f38edd2015-11-22 03:13:02 +0000603 // If the expression is a temporary, materialize it as an lvalue so that we
604 // can use it multiple times.
605 if (E->getValueKind() == VK_RValue)
Tim Shen4a05bb82016-06-21 20:29:17 +0000606 E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
Richard Smithd7bed4d2015-11-22 02:57:17 +0000607
608 // Build the await_ready, await_suspend, await_resume calls.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000609 ReadySuspendResumeResult RSS =
610 buildCoawaitCalls(*this, Coroutine->CoroutinePromise, Loc, E);
Richard Smithd7bed4d2015-11-22 02:57:17 +0000611 if (RSS.IsInvalid)
612 return ExprError();
613
614 Expr *Res = new (Context) CoyieldExpr(Loc, E, RSS.Results[0], RSS.Results[1],
Gor Nishanovce43bd22017-03-11 01:30:17 +0000615 RSS.Results[2], RSS.OpaqueValue);
Eric Fiseliercac0a592017-03-11 02:35:37 +0000616
Richard Smithcfd53b42015-10-22 06:13:50 +0000617 return Res;
618}
619
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000620StmtResult Sema::ActOnCoreturnStmt(Scope *S, SourceLocation Loc, Expr *E) {
621 if (!actOnCoroutineBodyStart(*this, S, Loc, "co_return")) {
Eric Fiseliera5465282016-09-29 21:47:39 +0000622 CorrectDelayedTyposInExpr(E);
623 return StmtError();
624 }
Richard Smith9f690bd2015-10-27 06:02:45 +0000625 return BuildCoreturnStmt(Loc, E);
626}
Gor Nishanov3e048bb2016-10-04 00:31:16 +0000627
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000628StmtResult Sema::BuildCoreturnStmt(SourceLocation Loc, Expr *E,
629 bool IsImplicit) {
Eric Fiseliercac0a592017-03-11 02:35:37 +0000630 auto *FSI = checkCoroutineContext(*this, Loc, "co_return", IsImplicit);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000631 if (!FSI)
Richard Smith71d403e2015-11-22 07:33:28 +0000632 return StmtError();
633
634 if (E && E->getType()->isPlaceholderType() &&
635 !E->getType()->isSpecificPlaceholderType(BuiltinType::Overload)) {
Richard Smith10610f72015-11-20 22:57:24 +0000636 ExprResult R = CheckPlaceholderExpr(E);
637 if (R.isInvalid()) return StmtError();
638 E = R.get();
639 }
640
Richard Smith4ba66602015-11-22 07:05:16 +0000641 // FIXME: If the operand is a reference to a variable that's about to go out
Richard Smith2af65c42015-11-24 02:34:39 +0000642 // of scope, we should treat the operand as an xvalue for this overload
Richard Smith4ba66602015-11-22 07:05:16 +0000643 // resolution.
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000644 VarDecl *Promise = FSI->CoroutinePromise;
Richard Smith4ba66602015-11-22 07:05:16 +0000645 ExprResult PC;
Eric Fiselier98131312016-10-06 21:23:38 +0000646 if (E && (isa<InitListExpr>(E) || !E->getType()->isVoidType())) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000647 PC = buildPromiseCall(*this, Promise, Loc, "return_value", E);
Richard Smith4ba66602015-11-22 07:05:16 +0000648 } else {
649 E = MakeFullDiscardedValueExpr(E).get();
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000650 PC = buildPromiseCall(*this, Promise, Loc, "return_void", None);
Richard Smith4ba66602015-11-22 07:05:16 +0000651 }
652 if (PC.isInvalid())
653 return StmtError();
654
655 Expr *PCE = ActOnFinishFullExpr(PC.get()).get();
656
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000657 Stmt *Res = new (Context) CoreturnStmt(Loc, E, PCE, IsImplicit);
Richard Smithcfd53b42015-10-22 06:13:50 +0000658 return Res;
659}
660
Gor Nishanov8df64e92016-10-27 16:28:31 +0000661// Find an appropriate delete for the promise.
662static FunctionDecl *findDeleteForPromise(Sema &S, SourceLocation Loc,
663 QualType PromiseType) {
664 FunctionDecl *OperatorDelete = nullptr;
665
666 DeclarationName DeleteName =
667 S.Context.DeclarationNames.getCXXOperatorName(OO_Delete);
668
669 auto *PointeeRD = PromiseType->getAsCXXRecordDecl();
670 assert(PointeeRD && "PromiseType must be a CxxRecordDecl type");
671
672 if (S.FindDeallocationFunction(Loc, PointeeRD, DeleteName, OperatorDelete))
673 return nullptr;
674
675 if (!OperatorDelete) {
676 // Look for a global declaration.
677 const bool CanProvideSize = S.isCompleteType(Loc, PromiseType);
678 const bool Overaligned = false;
679 OperatorDelete = S.FindUsualDeallocationFunction(Loc, CanProvideSize,
680 Overaligned, DeleteName);
681 }
682 S.MarkFunctionReferenced(Loc, OperatorDelete);
683 return OperatorDelete;
684}
685
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000686namespace {
687class SubStmtBuilder : public CoroutineBodyStmt::CtorArgs {
688 Sema &S;
689 FunctionDecl &FD;
690 FunctionScopeInfo &Fn;
691 bool IsValid;
692 SourceLocation Loc;
693 QualType RetType;
694 SmallVector<Stmt *, 4> ParamMovesVector;
695 const bool IsPromiseDependentType;
696 CXXRecordDecl *PromiseRecordDecl = nullptr;
697
698public:
699 SubStmtBuilder(Sema &S, FunctionDecl &FD, FunctionScopeInfo &Fn, Stmt *Body)
700 : S(S), FD(FD), Fn(Fn), Loc(FD.getLocation()),
701 IsPromiseDependentType(
702 !Fn.CoroutinePromise ||
703 Fn.CoroutinePromise->getType()->isDependentType()) {
704 this->Body = Body;
705 if (!IsPromiseDependentType) {
706 PromiseRecordDecl = Fn.CoroutinePromise->getType()->getAsCXXRecordDecl();
707 assert(PromiseRecordDecl && "Type should have already been checked");
708 }
709 this->IsValid = makePromiseStmt() && makeInitialAndFinalSuspend() &&
710 makeOnException() && makeOnFallthrough() &&
711 makeNewAndDeleteExpr() && makeReturnObject() &&
712 makeParamMoves();
713 }
714
715 bool isInvalid() const { return !this->IsValid; }
716
717 bool makePromiseStmt();
718 bool makeInitialAndFinalSuspend();
719 bool makeNewAndDeleteExpr();
720 bool makeOnFallthrough();
721 bool makeOnException();
722 bool makeReturnObject();
723 bool makeParamMoves();
724};
725}
726
727void Sema::CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body) {
728 FunctionScopeInfo *Fn = getCurFunction();
729 assert(Fn && Fn->CoroutinePromise && "not a coroutine");
730
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000731 if (!Body) {
732 assert(FD->isInvalidDecl() &&
733 "a null body is only allowed for invalid declarations");
734 return;
735 }
736
737 if (isa<CoroutineBodyStmt>(Body)) {
738 // FIXME(EricWF): Nothing todo. the body is already a transformed coroutine
739 // body statement.
740 return;
741 }
742
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000743 // Coroutines [stmt.return]p1:
744 // A return statement shall not appear in a coroutine.
745 if (Fn->FirstReturnLoc.isValid()) {
Eric Fiseliercac0a592017-03-11 02:35:37 +0000746 assert(Fn->FirstCoroutineStmtLoc.isValid() &&
747 "first coroutine location not set");
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000748 Diag(Fn->FirstReturnLoc, diag::err_return_in_coroutine);
Eric Fiseliercac0a592017-03-11 02:35:37 +0000749 Diag(Fn->FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
750 << Fn->getFirstCoroutineStmtKeyword();
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000751 }
752 SubStmtBuilder Builder(*this, *FD, *Fn, Body);
753 if (Builder.isInvalid())
754 return FD->setInvalidDecl();
755
756 // Build body for the coroutine wrapper statement.
757 Body = CoroutineBodyStmt::Create(Context, Builder);
758}
759
760bool SubStmtBuilder::makePromiseStmt() {
761 // Form a declaration statement for the promise declaration, so that AST
762 // visitors can more easily find it.
763 StmtResult PromiseStmt =
764 S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(Fn.CoroutinePromise), Loc, Loc);
765 if (PromiseStmt.isInvalid())
766 return false;
767
768 this->Promise = PromiseStmt.get();
769 return true;
770}
771
772bool SubStmtBuilder::makeInitialAndFinalSuspend() {
773 if (Fn.hasInvalidCoroutineSuspends())
774 return false;
775 this->InitialSuspend = cast<Expr>(Fn.CoroutineSuspends.first);
776 this->FinalSuspend = cast<Expr>(Fn.CoroutineSuspends.second);
777 return true;
778}
779
780bool SubStmtBuilder::makeNewAndDeleteExpr() {
781 // Form and check allocation and deallocation calls.
782 QualType PromiseType = Fn.CoroutinePromise->getType();
Gor Nishanov8df64e92016-10-27 16:28:31 +0000783 if (PromiseType->isDependentType())
784 return true;
785
786 if (S.RequireCompleteType(Loc, PromiseType, diag::err_incomplete_type))
787 return false;
788
789 // FIXME: Add support for get_return_object_on_allocation failure.
790 // FIXME: Add support for stateful allocators.
791
792 FunctionDecl *OperatorNew = nullptr;
793 FunctionDecl *OperatorDelete = nullptr;
794 FunctionDecl *UnusedResult = nullptr;
795 bool PassAlignment = false;
796
797 S.FindAllocationFunctions(Loc, SourceRange(),
798 /*UseGlobal*/ false, PromiseType,
799 /*isArray*/ false, PassAlignment,
800 /*PlacementArgs*/ None, OperatorNew, UnusedResult);
801
802 OperatorDelete = findDeleteForPromise(S, Loc, PromiseType);
803
804 if (!OperatorDelete || !OperatorNew)
805 return false;
806
807 Expr *FramePtr =
808 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_frame, {});
809
810 Expr *FrameSize =
811 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_size, {});
812
813 // Make new call.
814
815 ExprResult NewRef =
816 S.BuildDeclRefExpr(OperatorNew, OperatorNew->getType(), VK_LValue, Loc);
817 if (NewRef.isInvalid())
818 return false;
819
820 ExprResult NewExpr =
821 S.ActOnCallExpr(S.getCurScope(), NewRef.get(), Loc, FrameSize, Loc);
822 if (NewExpr.isInvalid())
823 return false;
824
Gor Nishanov8df64e92016-10-27 16:28:31 +0000825 // Make delete call.
826
827 QualType OpDeleteQualType = OperatorDelete->getType();
828
829 ExprResult DeleteRef =
830 S.BuildDeclRefExpr(OperatorDelete, OpDeleteQualType, VK_LValue, Loc);
831 if (DeleteRef.isInvalid())
832 return false;
833
834 Expr *CoroFree =
835 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_free, {FramePtr});
836
837 SmallVector<Expr *, 2> DeleteArgs{CoroFree};
838
839 // Check if we need to pass the size.
840 const auto *OpDeleteType =
841 OpDeleteQualType.getTypePtr()->getAs<FunctionProtoType>();
842 if (OpDeleteType->getNumParams() > 1)
843 DeleteArgs.push_back(FrameSize);
844
845 ExprResult DeleteExpr =
846 S.ActOnCallExpr(S.getCurScope(), DeleteRef.get(), Loc, DeleteArgs, Loc);
847 if (DeleteExpr.isInvalid())
848 return false;
849
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000850 this->Allocate = NewExpr.get();
851 this->Deallocate = DeleteExpr.get();
Gor Nishanov8df64e92016-10-27 16:28:31 +0000852
853 return true;
854}
855
Gor Nishanovbbe1c072017-02-13 05:05:02 +0000856bool SubStmtBuilder::makeOnFallthrough() {
857 if (!PromiseRecordDecl)
858 return true;
859
860 // [dcl.fct.def.coroutine]/4
861 // The unqualified-ids 'return_void' and 'return_value' are looked up in
862 // the scope of class P. If both are found, the program is ill-formed.
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000863 const bool HasRVoid = lookupMember(S, "return_void", PromiseRecordDecl, Loc);
864 const bool HasRValue = lookupMember(S, "return_value", PromiseRecordDecl, Loc);
Gor Nishanovbbe1c072017-02-13 05:05:02 +0000865
Eric Fiselier709d1b32016-10-27 07:30:31 +0000866 StmtResult Fallthrough;
Gor Nishanovbbe1c072017-02-13 05:05:02 +0000867 if (HasRVoid && HasRValue) {
868 // FIXME Improve this diagnostic
869 S.Diag(FD.getLocation(), diag::err_coroutine_promise_return_ill_formed)
870 << PromiseRecordDecl;
871 return false;
872 } else if (HasRVoid) {
873 // If the unqualified-id return_void is found, flowing off the end of a
874 // coroutine is equivalent to a co_return with no operand. Otherwise,
875 // flowing off the end of a coroutine results in undefined behavior.
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000876 Fallthrough = S.BuildCoreturnStmt(FD.getLocation(), nullptr,
877 /*IsImplicit*/false);
Gor Nishanovbbe1c072017-02-13 05:05:02 +0000878 Fallthrough = S.ActOnFinishFullStmt(Fallthrough.get());
879 if (Fallthrough.isInvalid())
880 return false;
Eric Fiselier709d1b32016-10-27 07:30:31 +0000881 }
Richard Smith2af65c42015-11-24 02:34:39 +0000882
Gor Nishanovbbe1c072017-02-13 05:05:02 +0000883 this->OnFallthrough = Fallthrough.get();
884 return true;
885}
886
887bool SubStmtBuilder::makeOnException() {
Eric Fiseliera9fdb342017-03-23 00:33:33 +0000888 // Try to form 'p.unhandled_exception();'
Gor Nishanovbbe1c072017-02-13 05:05:02 +0000889
890 if (!PromiseRecordDecl)
891 return true;
892
Eric Fiseliera9fdb342017-03-23 00:33:33 +0000893 const bool RequireUnhandledException = S.getLangOpts().CXXExceptions;
894
895 if (!lookupMember(S, "unhandled_exception", PromiseRecordDecl, Loc)) {
896 auto DiagID =
897 RequireUnhandledException
898 ? diag::err_coroutine_promise_unhandled_exception_required
899 : diag::
900 warn_coroutine_promise_unhandled_exception_required_with_exceptions;
901 S.Diag(Loc, DiagID) << PromiseRecordDecl;
902 return !RequireUnhandledException;
903 }
904
Gor Nishanovbbe1c072017-02-13 05:05:02 +0000905 // If exceptions are disabled, don't try to build OnException.
906 if (!S.getLangOpts().CXXExceptions)
907 return true;
908
Eric Fiseliera9fdb342017-03-23 00:33:33 +0000909 ExprResult UnhandledException = buildPromiseCall(S, Fn.CoroutinePromise, Loc,
910 "unhandled_exception", None);
911 UnhandledException = S.ActOnFinishFullExpr(UnhandledException.get(), Loc);
912 if (UnhandledException.isInvalid())
913 return false;
Gor Nishanovbbe1c072017-02-13 05:05:02 +0000914
Eric Fiseliera9fdb342017-03-23 00:33:33 +0000915 this->OnException = UnhandledException.get();
Gor Nishanovbbe1c072017-02-13 05:05:02 +0000916 return true;
917}
918
919bool SubStmtBuilder::makeReturnObject() {
920
Richard Smith2af65c42015-11-24 02:34:39 +0000921 // Build implicit 'p.get_return_object()' expression and form initialization
922 // of return type from it.
923 ExprResult ReturnObject =
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000924 buildPromiseCall(S, Fn.CoroutinePromise, Loc, "get_return_object", None);
Richard Smith2af65c42015-11-24 02:34:39 +0000925 if (ReturnObject.isInvalid())
Gor Nishanovbbe1c072017-02-13 05:05:02 +0000926 return false;
927 QualType RetType = FD.getReturnType();
Richard Smith2af65c42015-11-24 02:34:39 +0000928 if (!RetType->isDependentType()) {
929 InitializedEntity Entity =
930 InitializedEntity::InitializeResult(Loc, RetType, false);
Gor Nishanovbbe1c072017-02-13 05:05:02 +0000931 ReturnObject = S.PerformMoveOrCopyInitialization(Entity, nullptr, RetType,
Richard Smith2af65c42015-11-24 02:34:39 +0000932 ReturnObject.get());
933 if (ReturnObject.isInvalid())
Gor Nishanovbbe1c072017-02-13 05:05:02 +0000934 return false;
Richard Smith2af65c42015-11-24 02:34:39 +0000935 }
Gor Nishanovbbe1c072017-02-13 05:05:02 +0000936 ReturnObject = S.ActOnFinishFullExpr(ReturnObject.get(), Loc);
Richard Smith2af65c42015-11-24 02:34:39 +0000937 if (ReturnObject.isInvalid())
Gor Nishanovbbe1c072017-02-13 05:05:02 +0000938 return false;
Richard Smith2af65c42015-11-24 02:34:39 +0000939
Gor Nishanovbbe1c072017-02-13 05:05:02 +0000940 this->ReturnValue = ReturnObject.get();
941 return true;
942}
943
944bool SubStmtBuilder::makeParamMoves() {
Richard Smith2af65c42015-11-24 02:34:39 +0000945 // FIXME: Perform move-initialization of parameters into frame-local copies.
Gor Nishanovbbe1c072017-02-13 05:05:02 +0000946 return true;
Richard Smithcfd53b42015-10-22 06:13:50 +0000947}
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000948
949StmtResult Sema::BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
950 CoroutineBodyStmt *Res = CoroutineBodyStmt::Create(Context, Args);
951 if (!Res)
952 return StmtError();
953 return Res;
954}