blob: 05bf5319a5094fbf0a61a709023a8e4d03ac63df [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 Fiselierfc50f622017-05-25 14:59:39 +000026static LookupResult lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD,
27 SourceLocation Loc, bool &Res) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +000028 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();
Eric Fiselierfc50f622017-05-25 14:59:39 +000033 Res = S.LookupQualifiedName(LR, RD);
34 return LR;
35}
36
37static bool lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD,
38 SourceLocation Loc) {
39 bool Res;
40 lookupMember(S, Name, RD, Loc, Res);
41 return Res;
Eric Fiselier20f25cb2017-03-06 23:38:15 +000042}
43
Richard Smith9f690bd2015-10-27 06:02:45 +000044/// Look up the std::coroutine_traits<...>::promise_type for the given
45/// function type.
Eric Fiselier166c6e62017-07-10 01:27:22 +000046static QualType lookupPromiseType(Sema &S, const FunctionDecl *FD,
47 SourceLocation KwLoc) {
48 const FunctionProtoType *FnType = FD->getType()->castAs<FunctionProtoType>();
49 const SourceLocation FuncLoc = FD->getLocation();
Richard Smith9f690bd2015-10-27 06:02:45 +000050 // FIXME: Cache std::coroutine_traits once we've found it.
Gor Nishanov3e048bb2016-10-04 00:31:16 +000051 NamespaceDecl *StdExp = S.lookupStdExperimentalNamespace();
52 if (!StdExp) {
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +000053 S.Diag(KwLoc, diag::err_implied_coroutine_type_not_found)
54 << "std::experimental::coroutine_traits";
Richard Smith9f690bd2015-10-27 06:02:45 +000055 return QualType();
56 }
57
58 LookupResult Result(S, &S.PP.getIdentifierTable().get("coroutine_traits"),
Eric Fiselier89bf0e72017-03-06 22:52:28 +000059 FuncLoc, Sema::LookupOrdinaryName);
Gor Nishanov3e048bb2016-10-04 00:31:16 +000060 if (!S.LookupQualifiedName(Result, StdExp)) {
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +000061 S.Diag(KwLoc, diag::err_implied_coroutine_type_not_found)
62 << "std::experimental::coroutine_traits";
Richard Smith9f690bd2015-10-27 06:02:45 +000063 return QualType();
64 }
65
66 ClassTemplateDecl *CoroTraits = Result.getAsSingle<ClassTemplateDecl>();
67 if (!CoroTraits) {
68 Result.suppressDiagnostics();
69 // We found something weird. Complain about the first thing we found.
70 NamedDecl *Found = *Result.begin();
71 S.Diag(Found->getLocation(), diag::err_malformed_std_coroutine_traits);
72 return QualType();
73 }
74
Eric Fiselier166c6e62017-07-10 01:27:22 +000075 // Form template argument list for coroutine_traits<R, P1, P2, ...> according
76 // to [dcl.fct.def.coroutine]3
Eric Fiselier89bf0e72017-03-06 22:52:28 +000077 TemplateArgumentListInfo Args(KwLoc, KwLoc);
Eric Fiselier166c6e62017-07-10 01:27:22 +000078 auto AddArg = [&](QualType T) {
Richard Smith9f690bd2015-10-27 06:02:45 +000079 Args.addArgument(TemplateArgumentLoc(
Eric Fiselier89bf0e72017-03-06 22:52:28 +000080 TemplateArgument(T), S.Context.getTrivialTypeSourceInfo(T, KwLoc)));
Eric Fiselier166c6e62017-07-10 01:27:22 +000081 };
82 AddArg(FnType->getReturnType());
83 // If the function is a non-static member function, add the type
84 // of the implicit object parameter before the formal parameters.
85 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
86 if (MD->isInstance()) {
87 // [over.match.funcs]4
88 // For non-static member functions, the type of the implicit object
89 // parameter is
90 // — “lvalue reference to cv X” for functions declared without a
91 // ref-qualifier or with the & ref-qualifier
92 // — “rvalue reference to cv X” for functions declared with the &&
93 // ref-qualifier
94 QualType T =
95 MD->getThisType(S.Context)->getAs<PointerType>()->getPointeeType();
96 T = FnType->getRefQualifier() == RQ_RValue
97 ? S.Context.getRValueReferenceType(T)
98 : S.Context.getLValueReferenceType(T, /*SpelledAsLValue*/ true);
99 AddArg(T);
100 }
101 }
102 for (QualType T : FnType->getParamTypes())
103 AddArg(T);
Richard Smith9f690bd2015-10-27 06:02:45 +0000104
105 // Build the template-id.
106 QualType CoroTrait =
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000107 S.CheckTemplateIdType(TemplateName(CoroTraits), KwLoc, Args);
Richard Smith9f690bd2015-10-27 06:02:45 +0000108 if (CoroTrait.isNull())
109 return QualType();
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000110 if (S.RequireCompleteType(KwLoc, CoroTrait,
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000111 diag::err_coroutine_type_missing_specialization))
Richard Smith9f690bd2015-10-27 06:02:45 +0000112 return QualType();
113
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000114 auto *RD = CoroTrait->getAsCXXRecordDecl();
Richard Smith9f690bd2015-10-27 06:02:45 +0000115 assert(RD && "specialization of class template is not a class?");
116
117 // Look up the ::promise_type member.
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000118 LookupResult R(S, &S.PP.getIdentifierTable().get("promise_type"), KwLoc,
Richard Smith9f690bd2015-10-27 06:02:45 +0000119 Sema::LookupOrdinaryName);
120 S.LookupQualifiedName(R, RD);
121 auto *Promise = R.getAsSingle<TypeDecl>();
122 if (!Promise) {
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000123 S.Diag(FuncLoc,
124 diag::err_implied_std_coroutine_traits_promise_type_not_found)
Gor Nishanov8df64e92016-10-27 16:28:31 +0000125 << RD;
Richard Smith9f690bd2015-10-27 06:02:45 +0000126 return QualType();
127 }
Richard Smith9f690bd2015-10-27 06:02:45 +0000128 // The promise type is required to be a class type.
129 QualType PromiseType = S.Context.getTypeDeclType(Promise);
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000130
131 auto buildElaboratedType = [&]() {
Gor Nishanov3e048bb2016-10-04 00:31:16 +0000132 auto *NNS = NestedNameSpecifier::Create(S.Context, nullptr, StdExp);
Richard Smith9b2f53e2015-11-19 02:36:35 +0000133 NNS = NestedNameSpecifier::Create(S.Context, NNS, false,
134 CoroTrait.getTypePtr());
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000135 return S.Context.getElaboratedType(ETK_None, NNS, PromiseType);
136 };
Richard Smith9b2f53e2015-11-19 02:36:35 +0000137
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000138 if (!PromiseType->getAsCXXRecordDecl()) {
139 S.Diag(FuncLoc,
140 diag::err_implied_std_coroutine_traits_promise_type_not_class)
141 << buildElaboratedType();
Richard Smith9f690bd2015-10-27 06:02:45 +0000142 return QualType();
143 }
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000144 if (S.RequireCompleteType(FuncLoc, buildElaboratedType(),
145 diag::err_coroutine_promise_type_incomplete))
146 return QualType();
Richard Smith9f690bd2015-10-27 06:02:45 +0000147
148 return PromiseType;
149}
150
Gor Nishanov29ff6382017-05-24 14:34:19 +0000151/// Look up the std::experimental::coroutine_handle<PromiseType>.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000152static QualType lookupCoroutineHandleType(Sema &S, QualType PromiseType,
153 SourceLocation Loc) {
154 if (PromiseType.isNull())
155 return QualType();
156
157 NamespaceDecl *StdExp = S.lookupStdExperimentalNamespace();
158 assert(StdExp && "Should already be diagnosed");
159
160 LookupResult Result(S, &S.PP.getIdentifierTable().get("coroutine_handle"),
161 Loc, Sema::LookupOrdinaryName);
162 if (!S.LookupQualifiedName(Result, StdExp)) {
163 S.Diag(Loc, diag::err_implied_coroutine_type_not_found)
164 << "std::experimental::coroutine_handle";
165 return QualType();
166 }
167
168 ClassTemplateDecl *CoroHandle = Result.getAsSingle<ClassTemplateDecl>();
169 if (!CoroHandle) {
170 Result.suppressDiagnostics();
171 // We found something weird. Complain about the first thing we found.
172 NamedDecl *Found = *Result.begin();
173 S.Diag(Found->getLocation(), diag::err_malformed_std_coroutine_handle);
174 return QualType();
175 }
176
177 // Form template argument list for coroutine_handle<Promise>.
178 TemplateArgumentListInfo Args(Loc, Loc);
179 Args.addArgument(TemplateArgumentLoc(
180 TemplateArgument(PromiseType),
181 S.Context.getTrivialTypeSourceInfo(PromiseType, Loc)));
182
183 // Build the template-id.
184 QualType CoroHandleType =
185 S.CheckTemplateIdType(TemplateName(CoroHandle), Loc, Args);
186 if (CoroHandleType.isNull())
187 return QualType();
188 if (S.RequireCompleteType(Loc, CoroHandleType,
189 diag::err_coroutine_type_missing_specialization))
190 return QualType();
191
192 return CoroHandleType;
193}
194
Eric Fiselierc8efda72016-10-27 18:43:28 +0000195static bool isValidCoroutineContext(Sema &S, SourceLocation Loc,
196 StringRef Keyword) {
Richard Smith744b2242015-11-20 02:54:01 +0000197 // 'co_await' and 'co_yield' are not permitted in unevaluated operands.
198 if (S.isUnevaluatedContext()) {
199 S.Diag(Loc, diag::err_coroutine_unevaluated_context) << Keyword;
Eric Fiselierc8efda72016-10-27 18:43:28 +0000200 return false;
Richard Smith744b2242015-11-20 02:54:01 +0000201 }
Richard Smithcfd53b42015-10-22 06:13:50 +0000202
203 // Any other usage must be within a function.
204 auto *FD = dyn_cast<FunctionDecl>(S.CurContext);
205 if (!FD) {
206 S.Diag(Loc, isa<ObjCMethodDecl>(S.CurContext)
207 ? diag::err_coroutine_objc_method
208 : diag::err_coroutine_outside_function) << Keyword;
Eric Fiselierc8efda72016-10-27 18:43:28 +0000209 return false;
Richard Smithcfd53b42015-10-22 06:13:50 +0000210 }
211
Eric Fiselierc8efda72016-10-27 18:43:28 +0000212 // An enumeration for mapping the diagnostic type to the correct diagnostic
213 // selection index.
214 enum InvalidFuncDiag {
215 DiagCtor = 0,
216 DiagDtor,
217 DiagCopyAssign,
218 DiagMoveAssign,
219 DiagMain,
220 DiagConstexpr,
221 DiagAutoRet,
222 DiagVarargs,
223 };
224 bool Diagnosed = false;
225 auto DiagInvalid = [&](InvalidFuncDiag ID) {
226 S.Diag(Loc, diag::err_coroutine_invalid_func_context) << ID << Keyword;
227 Diagnosed = true;
228 return false;
229 };
230
231 // Diagnose when a constructor, destructor, copy/move assignment operator,
232 // or the function 'main' are declared as a coroutine.
233 auto *MD = dyn_cast<CXXMethodDecl>(FD);
234 if (MD && isa<CXXConstructorDecl>(MD))
235 return DiagInvalid(DiagCtor);
236 else if (MD && isa<CXXDestructorDecl>(MD))
237 return DiagInvalid(DiagDtor);
238 else if (MD && MD->isCopyAssignmentOperator())
239 return DiagInvalid(DiagCopyAssign);
240 else if (MD && MD->isMoveAssignmentOperator())
241 return DiagInvalid(DiagMoveAssign);
242 else if (FD->isMain())
243 return DiagInvalid(DiagMain);
244
245 // Emit a diagnostics for each of the following conditions which is not met.
246 if (FD->isConstexpr())
247 DiagInvalid(DiagConstexpr);
248 if (FD->getReturnType()->isUndeducedType())
249 DiagInvalid(DiagAutoRet);
250 if (FD->isVariadic())
251 DiagInvalid(DiagVarargs);
252
253 return !Diagnosed;
254}
255
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000256static ExprResult buildOperatorCoawaitLookupExpr(Sema &SemaRef, Scope *S,
257 SourceLocation Loc) {
258 DeclarationName OpName =
259 SemaRef.Context.DeclarationNames.getCXXOperatorName(OO_Coawait);
260 LookupResult Operators(SemaRef, OpName, SourceLocation(),
261 Sema::LookupOperatorName);
262 SemaRef.LookupName(Operators, S);
Eric Fiselierc8efda72016-10-27 18:43:28 +0000263
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000264 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
265 const auto &Functions = Operators.asUnresolvedSet();
266 bool IsOverloaded =
267 Functions.size() > 1 ||
268 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
269 Expr *CoawaitOp = UnresolvedLookupExpr::Create(
270 SemaRef.Context, /*NamingClass*/ nullptr, NestedNameSpecifierLoc(),
271 DeclarationNameInfo(OpName, Loc), /*RequiresADL*/ true, IsOverloaded,
272 Functions.begin(), Functions.end());
273 assert(CoawaitOp);
274 return CoawaitOp;
275}
Eric Fiselierc8efda72016-10-27 18:43:28 +0000276
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000277/// Build a call to 'operator co_await' if there is a suitable operator for
278/// the given expression.
279static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, SourceLocation Loc,
280 Expr *E,
281 UnresolvedLookupExpr *Lookup) {
282 UnresolvedSet<16> Functions;
283 Functions.append(Lookup->decls_begin(), Lookup->decls_end());
284 return SemaRef.CreateOverloadedUnaryOp(Loc, UO_Coawait, Functions, E);
285}
Eric Fiselierc8efda72016-10-27 18:43:28 +0000286
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000287static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, Scope *S,
288 SourceLocation Loc, Expr *E) {
289 ExprResult R = buildOperatorCoawaitLookupExpr(SemaRef, S, Loc);
290 if (R.isInvalid())
291 return ExprError();
292 return buildOperatorCoawaitCall(SemaRef, Loc, E,
293 cast<UnresolvedLookupExpr>(R.get()));
Richard Smithcfd53b42015-10-22 06:13:50 +0000294}
295
Gor Nishanov8df64e92016-10-27 16:28:31 +0000296static Expr *buildBuiltinCall(Sema &S, SourceLocation Loc, Builtin::ID Id,
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000297 MultiExprArg CallArgs) {
Gor Nishanov8df64e92016-10-27 16:28:31 +0000298 StringRef Name = S.Context.BuiltinInfo.getName(Id);
299 LookupResult R(S, &S.Context.Idents.get(Name), Loc, Sema::LookupOrdinaryName);
300 S.LookupName(R, S.TUScope, /*AllowBuiltinCreation=*/true);
301
302 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
303 assert(BuiltInDecl && "failed to find builtin declaration");
304
305 ExprResult DeclRef =
306 S.BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
307 assert(DeclRef.isUsable() && "Builtin reference cannot fail");
308
309 ExprResult Call =
310 S.ActOnCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
311
312 assert(!Call.isInvalid() && "Call to builtin cannot fail!");
313 return Call.get();
314}
315
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000316static ExprResult buildCoroutineHandle(Sema &S, QualType PromiseType,
317 SourceLocation Loc) {
318 QualType CoroHandleType = lookupCoroutineHandleType(S, PromiseType, Loc);
319 if (CoroHandleType.isNull())
320 return ExprError();
321
322 DeclContext *LookupCtx = S.computeDeclContext(CoroHandleType);
323 LookupResult Found(S, &S.PP.getIdentifierTable().get("from_address"), Loc,
324 Sema::LookupOrdinaryName);
325 if (!S.LookupQualifiedName(Found, LookupCtx)) {
326 S.Diag(Loc, diag::err_coroutine_handle_missing_member)
327 << "from_address";
328 return ExprError();
329 }
330
331 Expr *FramePtr =
332 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_frame, {});
333
334 CXXScopeSpec SS;
335 ExprResult FromAddr =
336 S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
337 if (FromAddr.isInvalid())
338 return ExprError();
339
340 return S.ActOnCallExpr(nullptr, FromAddr.get(), Loc, FramePtr, Loc);
341}
Richard Smithcfd53b42015-10-22 06:13:50 +0000342
Richard Smith9f690bd2015-10-27 06:02:45 +0000343struct ReadySuspendResumeResult {
Eric Fiselierd978e532017-05-28 18:21:12 +0000344 enum AwaitCallType { ACT_Ready, ACT_Suspend, ACT_Resume };
Richard Smith9f690bd2015-10-27 06:02:45 +0000345 Expr *Results[3];
Gor Nishanovce43bd22017-03-11 01:30:17 +0000346 OpaqueValueExpr *OpaqueValue;
347 bool IsInvalid;
Richard Smith9f690bd2015-10-27 06:02:45 +0000348};
349
Richard Smith23da82c2015-11-20 22:40:06 +0000350static ExprResult buildMemberCall(Sema &S, Expr *Base, SourceLocation Loc,
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000351 StringRef Name, MultiExprArg Args) {
Richard Smith23da82c2015-11-20 22:40:06 +0000352 DeclarationNameInfo NameInfo(&S.PP.getIdentifierTable().get(Name), Loc);
353
354 // FIXME: Fix BuildMemberReferenceExpr to take a const CXXScopeSpec&.
355 CXXScopeSpec SS;
356 ExprResult Result = S.BuildMemberReferenceExpr(
357 Base, Base->getType(), Loc, /*IsPtr=*/false, SS,
358 SourceLocation(), nullptr, NameInfo, /*TemplateArgs=*/nullptr,
359 /*Scope=*/nullptr);
360 if (Result.isInvalid())
361 return ExprError();
362
363 return S.ActOnCallExpr(nullptr, Result.get(), Loc, Args, Loc, nullptr);
364}
365
Richard Smith9f690bd2015-10-27 06:02:45 +0000366/// Build calls to await_ready, await_suspend, and await_resume for a co_await
367/// expression.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000368static ReadySuspendResumeResult buildCoawaitCalls(Sema &S, VarDecl *CoroPromise,
369 SourceLocation Loc, Expr *E) {
Gor Nishanovce43bd22017-03-11 01:30:17 +0000370 OpaqueValueExpr *Operand = new (S.Context)
371 OpaqueValueExpr(Loc, E->getType(), VK_LValue, E->getObjectKind(), E);
372
Richard Smith9f690bd2015-10-27 06:02:45 +0000373 // Assume invalid until we see otherwise.
Gor Nishanovce43bd22017-03-11 01:30:17 +0000374 ReadySuspendResumeResult Calls = {{}, Operand, /*IsInvalid=*/true};
Richard Smith9f690bd2015-10-27 06:02:45 +0000375
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000376 ExprResult CoroHandleRes = buildCoroutineHandle(S, CoroPromise->getType(), Loc);
377 if (CoroHandleRes.isInvalid())
378 return Calls;
379 Expr *CoroHandle = CoroHandleRes.get();
380
Richard Smith9f690bd2015-10-27 06:02:45 +0000381 const StringRef Funcs[] = {"await_ready", "await_suspend", "await_resume"};
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000382 MultiExprArg Args[] = {None, CoroHandle, None};
Richard Smith9f690bd2015-10-27 06:02:45 +0000383 for (size_t I = 0, N = llvm::array_lengthof(Funcs); I != N; ++I) {
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000384 ExprResult Result = buildMemberCall(S, Operand, Loc, Funcs[I], Args[I]);
Richard Smith9f690bd2015-10-27 06:02:45 +0000385 if (Result.isInvalid())
386 return Calls;
387 Calls.Results[I] = Result.get();
388 }
389
Eric Fiselierd978e532017-05-28 18:21:12 +0000390 // Assume the calls are valid; all further checking should make them invalid.
Richard Smith9f690bd2015-10-27 06:02:45 +0000391 Calls.IsInvalid = false;
Eric Fiselierd978e532017-05-28 18:21:12 +0000392
393 using ACT = ReadySuspendResumeResult::AwaitCallType;
394 CallExpr *AwaitReady = cast<CallExpr>(Calls.Results[ACT::ACT_Ready]);
395 if (!AwaitReady->getType()->isDependentType()) {
396 // [expr.await]p3 [...]
397 // — await-ready is the expression e.await_ready(), contextually converted
398 // to bool.
399 ExprResult Conv = S.PerformContextuallyConvertToBool(AwaitReady);
400 if (Conv.isInvalid()) {
401 S.Diag(AwaitReady->getDirectCallee()->getLocStart(),
402 diag::note_await_ready_no_bool_conversion);
403 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
404 << AwaitReady->getDirectCallee() << E->getSourceRange();
405 Calls.IsInvalid = true;
406 }
407 Calls.Results[ACT::ACT_Ready] = Conv.get();
408 }
409 CallExpr *AwaitSuspend = cast<CallExpr>(Calls.Results[ACT::ACT_Suspend]);
410 if (!AwaitSuspend->getType()->isDependentType()) {
411 // [expr.await]p3 [...]
412 // - await-suspend is the expression e.await_suspend(h), which shall be
413 // a prvalue of type void or bool.
Eric Fiselier84ee7ff2017-05-31 23:41:11 +0000414 QualType RetType = AwaitSuspend->getCallReturnType(S.Context);
415 // non-class prvalues always have cv-unqualified types
416 QualType AdjRetType = RetType.getUnqualifiedType();
417 if (RetType->isReferenceType() ||
418 (AdjRetType != S.Context.BoolTy && AdjRetType != S.Context.VoidTy)) {
Eric Fiselierd978e532017-05-28 18:21:12 +0000419 S.Diag(AwaitSuspend->getCalleeDecl()->getLocation(),
420 diag::err_await_suspend_invalid_return_type)
421 << RetType;
422 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
423 << AwaitSuspend->getDirectCallee();
424 Calls.IsInvalid = true;
425 }
426 }
427
Richard Smith9f690bd2015-10-27 06:02:45 +0000428 return Calls;
429}
430
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000431static ExprResult buildPromiseCall(Sema &S, VarDecl *Promise,
432 SourceLocation Loc, StringRef Name,
433 MultiExprArg Args) {
434
435 // Form a reference to the promise.
436 ExprResult PromiseRef = S.BuildDeclRefExpr(
437 Promise, Promise->getType().getNonReferenceType(), VK_LValue, Loc);
438 if (PromiseRef.isInvalid())
439 return ExprError();
440
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000441 return buildMemberCall(S, PromiseRef.get(), Loc, Name, Args);
442}
443
444VarDecl *Sema::buildCoroutinePromise(SourceLocation Loc) {
445 assert(isa<FunctionDecl>(CurContext) && "not in a function scope");
446 auto *FD = cast<FunctionDecl>(CurContext);
Eric Fiselier166c6e62017-07-10 01:27:22 +0000447 bool IsThisDependentType = [&] {
448 if (auto *MD = dyn_cast_or_null<CXXMethodDecl>(FD))
449 return MD->isInstance() && MD->getThisType(Context)->isDependentType();
450 else
451 return false;
452 }();
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000453
Eric Fiselier166c6e62017-07-10 01:27:22 +0000454 QualType T = FD->getType()->isDependentType() || IsThisDependentType
455 ? Context.DependentTy
456 : lookupPromiseType(*this, FD, Loc);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000457 if (T.isNull())
458 return nullptr;
459
460 auto *VD = VarDecl::Create(Context, FD, FD->getLocation(), FD->getLocation(),
461 &PP.getIdentifierTable().get("__promise"), T,
462 Context.getTrivialTypeSourceInfo(T, Loc), SC_None);
463 CheckVariableDeclarationType(VD);
464 if (VD->isInvalidDecl())
465 return nullptr;
466 ActOnUninitializedDecl(VD);
Eric Fiselier37b8a372017-05-31 19:36:59 +0000467 FD->addDecl(VD);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000468 assert(!VD->isInvalidDecl());
469 return VD;
470}
471
472/// Check that this is a context in which a coroutine suspension can appear.
473static FunctionScopeInfo *checkCoroutineContext(Sema &S, SourceLocation Loc,
Eric Fiseliercac0a592017-03-11 02:35:37 +0000474 StringRef Keyword,
475 bool IsImplicit = false) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000476 if (!isValidCoroutineContext(S, Loc, Keyword))
477 return nullptr;
478
479 assert(isa<FunctionDecl>(S.CurContext) && "not in a function scope");
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000480
481 auto *ScopeInfo = S.getCurFunction();
482 assert(ScopeInfo && "missing function scope for function");
483
Eric Fiseliercac0a592017-03-11 02:35:37 +0000484 if (ScopeInfo->FirstCoroutineStmtLoc.isInvalid() && !IsImplicit)
485 ScopeInfo->setFirstCoroutineStmt(Loc, Keyword);
486
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000487 if (ScopeInfo->CoroutinePromise)
488 return ScopeInfo;
489
490 ScopeInfo->CoroutinePromise = S.buildCoroutinePromise(Loc);
491 if (!ScopeInfo->CoroutinePromise)
492 return nullptr;
493
494 return ScopeInfo;
495}
496
Eric Fiselierb936a392017-06-14 03:24:55 +0000497bool Sema::ActOnCoroutineBodyStart(Scope *SC, SourceLocation KWLoc,
498 StringRef Keyword) {
499 if (!checkCoroutineContext(*this, KWLoc, Keyword))
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000500 return false;
Eric Fiselierb936a392017-06-14 03:24:55 +0000501 auto *ScopeInfo = getCurFunction();
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000502 assert(ScopeInfo->CoroutinePromise);
503
504 // If we have existing coroutine statements then we have already built
505 // the initial and final suspend points.
506 if (!ScopeInfo->NeedsCoroutineSuspends)
507 return true;
508
509 ScopeInfo->setNeedsCoroutineSuspends(false);
510
Eric Fiselierb936a392017-06-14 03:24:55 +0000511 auto *Fn = cast<FunctionDecl>(CurContext);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000512 SourceLocation Loc = Fn->getLocation();
513 // Build the initial suspend point
514 auto buildSuspends = [&](StringRef Name) mutable -> StmtResult {
515 ExprResult Suspend =
Eric Fiselierb936a392017-06-14 03:24:55 +0000516 buildPromiseCall(*this, ScopeInfo->CoroutinePromise, Loc, Name, None);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000517 if (Suspend.isInvalid())
518 return StmtError();
Eric Fiselierb936a392017-06-14 03:24:55 +0000519 Suspend = buildOperatorCoawaitCall(*this, SC, Loc, Suspend.get());
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000520 if (Suspend.isInvalid())
521 return StmtError();
Eric Fiselierb936a392017-06-14 03:24:55 +0000522 Suspend = BuildResolvedCoawaitExpr(Loc, Suspend.get(),
523 /*IsImplicit*/ true);
524 Suspend = ActOnFinishFullExpr(Suspend.get());
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000525 if (Suspend.isInvalid()) {
Eric Fiselierb936a392017-06-14 03:24:55 +0000526 Diag(Loc, diag::note_coroutine_promise_suspend_implicitly_required)
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000527 << ((Name == "initial_suspend") ? 0 : 1);
Eric Fiselierb936a392017-06-14 03:24:55 +0000528 Diag(KWLoc, diag::note_declared_coroutine_here) << Keyword;
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000529 return StmtError();
530 }
531 return cast<Stmt>(Suspend.get());
532 };
533
534 StmtResult InitSuspend = buildSuspends("initial_suspend");
535 if (InitSuspend.isInvalid())
536 return true;
537
538 StmtResult FinalSuspend = buildSuspends("final_suspend");
539 if (FinalSuspend.isInvalid())
540 return true;
541
542 ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());
543
544 return true;
545}
546
Richard Smith9f690bd2015-10-27 06:02:45 +0000547ExprResult Sema::ActOnCoawaitExpr(Scope *S, SourceLocation Loc, Expr *E) {
Eric Fiselierb936a392017-06-14 03:24:55 +0000548 if (!ActOnCoroutineBodyStart(S, Loc, "co_await")) {
Eric Fiseliera5465282016-09-29 21:47:39 +0000549 CorrectDelayedTyposInExpr(E);
550 return ExprError();
551 }
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000552
Richard Smith10610f72015-11-20 22:57:24 +0000553 if (E->getType()->isPlaceholderType()) {
554 ExprResult R = CheckPlaceholderExpr(E);
555 if (R.isInvalid()) return ExprError();
556 E = R.get();
557 }
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000558 ExprResult Lookup = buildOperatorCoawaitLookupExpr(*this, S, Loc);
559 if (Lookup.isInvalid())
560 return ExprError();
561 return BuildUnresolvedCoawaitExpr(Loc, E,
562 cast<UnresolvedLookupExpr>(Lookup.get()));
563}
Richard Smith10610f72015-11-20 22:57:24 +0000564
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000565ExprResult Sema::BuildUnresolvedCoawaitExpr(SourceLocation Loc, Expr *E,
Eric Fiseliercac0a592017-03-11 02:35:37 +0000566 UnresolvedLookupExpr *Lookup) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000567 auto *FSI = checkCoroutineContext(*this, Loc, "co_await");
568 if (!FSI)
569 return ExprError();
570
571 if (E->getType()->isPlaceholderType()) {
572 ExprResult R = CheckPlaceholderExpr(E);
573 if (R.isInvalid())
574 return ExprError();
575 E = R.get();
576 }
577
578 auto *Promise = FSI->CoroutinePromise;
579 if (Promise->getType()->isDependentType()) {
580 Expr *Res =
581 new (Context) DependentCoawaitExpr(Loc, Context.DependentTy, E, Lookup);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000582 return Res;
583 }
584
585 auto *RD = Promise->getType()->getAsCXXRecordDecl();
586 if (lookupMember(*this, "await_transform", RD, Loc)) {
587 ExprResult R = buildPromiseCall(*this, Promise, Loc, "await_transform", E);
588 if (R.isInvalid()) {
589 Diag(Loc,
590 diag::note_coroutine_promise_implicit_await_transform_required_here)
591 << E->getSourceRange();
592 return ExprError();
593 }
594 E = R.get();
595 }
596 ExprResult Awaitable = buildOperatorCoawaitCall(*this, Loc, E, Lookup);
Richard Smith9f690bd2015-10-27 06:02:45 +0000597 if (Awaitable.isInvalid())
598 return ExprError();
Eric Fiseliera5465282016-09-29 21:47:39 +0000599
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000600 return BuildResolvedCoawaitExpr(Loc, Awaitable.get());
Richard Smith9f690bd2015-10-27 06:02:45 +0000601}
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000602
603ExprResult Sema::BuildResolvedCoawaitExpr(SourceLocation Loc, Expr *E,
604 bool IsImplicit) {
Eric Fiseliercac0a592017-03-11 02:35:37 +0000605 auto *Coroutine = checkCoroutineContext(*this, Loc, "co_await", IsImplicit);
Richard Smith744b2242015-11-20 02:54:01 +0000606 if (!Coroutine)
607 return ExprError();
Richard Smith9f690bd2015-10-27 06:02:45 +0000608
Richard Smith9f690bd2015-10-27 06:02:45 +0000609 if (E->getType()->isPlaceholderType()) {
610 ExprResult R = CheckPlaceholderExpr(E);
611 if (R.isInvalid()) return ExprError();
612 E = R.get();
613 }
614
Richard Smith10610f72015-11-20 22:57:24 +0000615 if (E->getType()->isDependentType()) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000616 Expr *Res = new (Context)
617 CoawaitExpr(Loc, Context.DependentTy, E, IsImplicit);
Richard Smith10610f72015-11-20 22:57:24 +0000618 return Res;
619 }
620
Richard Smith1f38edd2015-11-22 03:13:02 +0000621 // If the expression is a temporary, materialize it as an lvalue so that we
622 // can use it multiple times.
623 if (E->getValueKind() == VK_RValue)
Tim Shen4a05bb82016-06-21 20:29:17 +0000624 E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
Richard Smith9f690bd2015-10-27 06:02:45 +0000625
626 // Build the await_ready, await_suspend, await_resume calls.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000627 ReadySuspendResumeResult RSS =
628 buildCoawaitCalls(*this, Coroutine->CoroutinePromise, Loc, E);
Richard Smith9f690bd2015-10-27 06:02:45 +0000629 if (RSS.IsInvalid)
630 return ExprError();
631
Gor Nishanovce43bd22017-03-11 01:30:17 +0000632 Expr *Res =
633 new (Context) CoawaitExpr(Loc, E, RSS.Results[0], RSS.Results[1],
634 RSS.Results[2], RSS.OpaqueValue, IsImplicit);
Eric Fiseliercac0a592017-03-11 02:35:37 +0000635
Richard Smithcfd53b42015-10-22 06:13:50 +0000636 return Res;
637}
638
Richard Smith9f690bd2015-10-27 06:02:45 +0000639ExprResult Sema::ActOnCoyieldExpr(Scope *S, SourceLocation Loc, Expr *E) {
Eric Fiselierb936a392017-06-14 03:24:55 +0000640 if (!ActOnCoroutineBodyStart(S, Loc, "co_yield")) {
Eric Fiseliera5465282016-09-29 21:47:39 +0000641 CorrectDelayedTyposInExpr(E);
Richard Smith23da82c2015-11-20 22:40:06 +0000642 return ExprError();
Eric Fiseliera5465282016-09-29 21:47:39 +0000643 }
Richard Smith23da82c2015-11-20 22:40:06 +0000644
645 // Build yield_value call.
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000646 ExprResult Awaitable = buildPromiseCall(
647 *this, getCurFunction()->CoroutinePromise, Loc, "yield_value", E);
Richard Smith9f690bd2015-10-27 06:02:45 +0000648 if (Awaitable.isInvalid())
649 return ExprError();
Richard Smith23da82c2015-11-20 22:40:06 +0000650
651 // Build 'operator co_await' call.
652 Awaitable = buildOperatorCoawaitCall(*this, S, Loc, Awaitable.get());
653 if (Awaitable.isInvalid())
654 return ExprError();
655
Richard Smith9f690bd2015-10-27 06:02:45 +0000656 return BuildCoyieldExpr(Loc, Awaitable.get());
657}
658ExprResult Sema::BuildCoyieldExpr(SourceLocation Loc, Expr *E) {
659 auto *Coroutine = checkCoroutineContext(*this, Loc, "co_yield");
Richard Smith744b2242015-11-20 02:54:01 +0000660 if (!Coroutine)
661 return ExprError();
Richard Smithcfd53b42015-10-22 06:13:50 +0000662
Richard Smith10610f72015-11-20 22:57:24 +0000663 if (E->getType()->isPlaceholderType()) {
664 ExprResult R = CheckPlaceholderExpr(E);
665 if (R.isInvalid()) return ExprError();
666 E = R.get();
667 }
668
Richard Smithd7bed4d2015-11-22 02:57:17 +0000669 if (E->getType()->isDependentType()) {
670 Expr *Res = new (Context) CoyieldExpr(Loc, Context.DependentTy, E);
Richard Smithd7bed4d2015-11-22 02:57:17 +0000671 return Res;
672 }
673
Richard Smith1f38edd2015-11-22 03:13:02 +0000674 // If the expression is a temporary, materialize it as an lvalue so that we
675 // can use it multiple times.
676 if (E->getValueKind() == VK_RValue)
Tim Shen4a05bb82016-06-21 20:29:17 +0000677 E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
Richard Smithd7bed4d2015-11-22 02:57:17 +0000678
679 // Build the await_ready, await_suspend, await_resume calls.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000680 ReadySuspendResumeResult RSS =
681 buildCoawaitCalls(*this, Coroutine->CoroutinePromise, Loc, E);
Richard Smithd7bed4d2015-11-22 02:57:17 +0000682 if (RSS.IsInvalid)
683 return ExprError();
684
Eric Fiselierb936a392017-06-14 03:24:55 +0000685 Expr *Res =
686 new (Context) CoyieldExpr(Loc, E, RSS.Results[0], RSS.Results[1],
687 RSS.Results[2], RSS.OpaqueValue);
Eric Fiseliercac0a592017-03-11 02:35:37 +0000688
Richard Smithcfd53b42015-10-22 06:13:50 +0000689 return Res;
690}
691
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000692StmtResult Sema::ActOnCoreturnStmt(Scope *S, SourceLocation Loc, Expr *E) {
Eric Fiselierb936a392017-06-14 03:24:55 +0000693 if (!ActOnCoroutineBodyStart(S, Loc, "co_return")) {
Eric Fiseliera5465282016-09-29 21:47:39 +0000694 CorrectDelayedTyposInExpr(E);
695 return StmtError();
696 }
Richard Smith9f690bd2015-10-27 06:02:45 +0000697 return BuildCoreturnStmt(Loc, E);
698}
Gor Nishanov3e048bb2016-10-04 00:31:16 +0000699
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000700StmtResult Sema::BuildCoreturnStmt(SourceLocation Loc, Expr *E,
701 bool IsImplicit) {
Eric Fiseliercac0a592017-03-11 02:35:37 +0000702 auto *FSI = checkCoroutineContext(*this, Loc, "co_return", IsImplicit);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000703 if (!FSI)
Richard Smith71d403e2015-11-22 07:33:28 +0000704 return StmtError();
705
706 if (E && E->getType()->isPlaceholderType() &&
707 !E->getType()->isSpecificPlaceholderType(BuiltinType::Overload)) {
Richard Smith10610f72015-11-20 22:57:24 +0000708 ExprResult R = CheckPlaceholderExpr(E);
709 if (R.isInvalid()) return StmtError();
710 E = R.get();
711 }
712
Richard Smith4ba66602015-11-22 07:05:16 +0000713 // FIXME: If the operand is a reference to a variable that's about to go out
Richard Smith2af65c42015-11-24 02:34:39 +0000714 // of scope, we should treat the operand as an xvalue for this overload
Richard Smith4ba66602015-11-22 07:05:16 +0000715 // resolution.
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000716 VarDecl *Promise = FSI->CoroutinePromise;
Richard Smith4ba66602015-11-22 07:05:16 +0000717 ExprResult PC;
Eric Fiselier98131312016-10-06 21:23:38 +0000718 if (E && (isa<InitListExpr>(E) || !E->getType()->isVoidType())) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000719 PC = buildPromiseCall(*this, Promise, Loc, "return_value", E);
Richard Smith4ba66602015-11-22 07:05:16 +0000720 } else {
721 E = MakeFullDiscardedValueExpr(E).get();
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000722 PC = buildPromiseCall(*this, Promise, Loc, "return_void", None);
Richard Smith4ba66602015-11-22 07:05:16 +0000723 }
724 if (PC.isInvalid())
725 return StmtError();
726
727 Expr *PCE = ActOnFinishFullExpr(PC.get()).get();
728
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000729 Stmt *Res = new (Context) CoreturnStmt(Loc, E, PCE, IsImplicit);
Richard Smithcfd53b42015-10-22 06:13:50 +0000730 return Res;
731}
732
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000733/// Look up the std::nothrow object.
734static Expr *buildStdNoThrowDeclRef(Sema &S, SourceLocation Loc) {
735 NamespaceDecl *Std = S.getStdNamespace();
736 assert(Std && "Should already be diagnosed");
737
738 LookupResult Result(S, &S.PP.getIdentifierTable().get("nothrow"), Loc,
739 Sema::LookupOrdinaryName);
740 if (!S.LookupQualifiedName(Result, Std)) {
741 // FIXME: <experimental/coroutine> should have been included already.
742 // If we require it to include <new> then this diagnostic is no longer
743 // needed.
744 S.Diag(Loc, diag::err_implicit_coroutine_std_nothrow_type_not_found);
745 return nullptr;
746 }
747
748 // FIXME: Mark the variable as ODR used. This currently does not work
749 // likely due to the scope at in which this function is called.
750 auto *VD = Result.getAsSingle<VarDecl>();
751 if (!VD) {
752 Result.suppressDiagnostics();
753 // We found something weird. Complain about the first thing we found.
754 NamedDecl *Found = *Result.begin();
755 S.Diag(Found->getLocation(), diag::err_malformed_std_nothrow);
756 return nullptr;
757 }
758
759 ExprResult DR = S.BuildDeclRefExpr(VD, VD->getType(), VK_LValue, Loc);
760 if (DR.isInvalid())
761 return nullptr;
762
763 return DR.get();
764}
765
Gor Nishanov8df64e92016-10-27 16:28:31 +0000766// Find an appropriate delete for the promise.
767static FunctionDecl *findDeleteForPromise(Sema &S, SourceLocation Loc,
768 QualType PromiseType) {
769 FunctionDecl *OperatorDelete = nullptr;
770
771 DeclarationName DeleteName =
772 S.Context.DeclarationNames.getCXXOperatorName(OO_Delete);
773
774 auto *PointeeRD = PromiseType->getAsCXXRecordDecl();
775 assert(PointeeRD && "PromiseType must be a CxxRecordDecl type");
776
777 if (S.FindDeallocationFunction(Loc, PointeeRD, DeleteName, OperatorDelete))
778 return nullptr;
779
780 if (!OperatorDelete) {
781 // Look for a global declaration.
782 const bool CanProvideSize = S.isCompleteType(Loc, PromiseType);
783 const bool Overaligned = false;
784 OperatorDelete = S.FindUsualDeallocationFunction(Loc, CanProvideSize,
785 Overaligned, DeleteName);
786 }
787 S.MarkFunctionReferenced(Loc, OperatorDelete);
788 return OperatorDelete;
789}
790
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000791
792void Sema::CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body) {
793 FunctionScopeInfo *Fn = getCurFunction();
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000794 assert(Fn && Fn->isCoroutine() && "not a coroutine");
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000795 if (!Body) {
796 assert(FD->isInvalidDecl() &&
797 "a null body is only allowed for invalid declarations");
798 return;
799 }
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000800 // We have a function that uses coroutine keywords, but we failed to build
801 // the promise type.
802 if (!Fn->CoroutinePromise)
803 return FD->setInvalidDecl();
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000804
805 if (isa<CoroutineBodyStmt>(Body)) {
Gor Nishanov29ff6382017-05-24 14:34:19 +0000806 // Nothing todo. the body is already a transformed coroutine body statement.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000807 return;
808 }
809
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000810 // Coroutines [stmt.return]p1:
811 // A return statement shall not appear in a coroutine.
812 if (Fn->FirstReturnLoc.isValid()) {
Eric Fiseliercac0a592017-03-11 02:35:37 +0000813 assert(Fn->FirstCoroutineStmtLoc.isValid() &&
814 "first coroutine location not set");
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000815 Diag(Fn->FirstReturnLoc, diag::err_return_in_coroutine);
Eric Fiseliercac0a592017-03-11 02:35:37 +0000816 Diag(Fn->FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
817 << Fn->getFirstCoroutineStmtKeyword();
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000818 }
Eric Fiselierbee782b2017-04-03 19:21:00 +0000819 CoroutineStmtBuilder Builder(*this, *FD, *Fn, Body);
820 if (Builder.isInvalid() || !Builder.buildStatements())
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000821 return FD->setInvalidDecl();
822
823 // Build body for the coroutine wrapper statement.
824 Body = CoroutineBodyStmt::Create(Context, Builder);
825}
826
Eric Fiselierbee782b2017-04-03 19:21:00 +0000827CoroutineStmtBuilder::CoroutineStmtBuilder(Sema &S, FunctionDecl &FD,
828 sema::FunctionScopeInfo &Fn,
829 Stmt *Body)
830 : S(S), FD(FD), Fn(Fn), Loc(FD.getLocation()),
831 IsPromiseDependentType(
832 !Fn.CoroutinePromise ||
833 Fn.CoroutinePromise->getType()->isDependentType()) {
834 this->Body = Body;
835 if (!IsPromiseDependentType) {
836 PromiseRecordDecl = Fn.CoroutinePromise->getType()->getAsCXXRecordDecl();
837 assert(PromiseRecordDecl && "Type should have already been checked");
838 }
839 this->IsValid = makePromiseStmt() && makeInitialAndFinalSuspend();
840}
841
842bool CoroutineStmtBuilder::buildStatements() {
843 assert(this->IsValid && "coroutine already invalid");
844 this->IsValid = makeReturnObject() && makeParamMoves();
845 if (this->IsValid && !IsPromiseDependentType)
846 buildDependentStatements();
847 return this->IsValid;
848}
849
850bool CoroutineStmtBuilder::buildDependentStatements() {
851 assert(this->IsValid && "coroutine already invalid");
852 assert(!this->IsPromiseDependentType &&
853 "coroutine cannot have a dependent promise type");
854 this->IsValid = makeOnException() && makeOnFallthrough() &&
Gor Nishanov6a470682017-05-22 20:22:23 +0000855 makeGroDeclAndReturnStmt() && makeReturnOnAllocFailure() &&
856 makeNewAndDeleteExpr();
Eric Fiselierbee782b2017-04-03 19:21:00 +0000857 return this->IsValid;
858}
859
Eric Fiselierde7943b2017-06-03 00:22:18 +0000860bool CoroutineStmtBuilder::buildParameterMoves() {
861 assert(this->IsValid && "coroutine already invalid");
862 assert(this->ParamMoves.empty() && "param moves already built");
863 return this->IsValid = makeParamMoves();
864}
865
Eric Fiselierbee782b2017-04-03 19:21:00 +0000866bool CoroutineStmtBuilder::makePromiseStmt() {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000867 // Form a declaration statement for the promise declaration, so that AST
868 // visitors can more easily find it.
869 StmtResult PromiseStmt =
870 S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(Fn.CoroutinePromise), Loc, Loc);
871 if (PromiseStmt.isInvalid())
872 return false;
873
874 this->Promise = PromiseStmt.get();
875 return true;
876}
877
Eric Fiselierbee782b2017-04-03 19:21:00 +0000878bool CoroutineStmtBuilder::makeInitialAndFinalSuspend() {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000879 if (Fn.hasInvalidCoroutineSuspends())
880 return false;
881 this->InitialSuspend = cast<Expr>(Fn.CoroutineSuspends.first);
882 this->FinalSuspend = cast<Expr>(Fn.CoroutineSuspends.second);
883 return true;
884}
885
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000886static bool diagReturnOnAllocFailure(Sema &S, Expr *E,
887 CXXRecordDecl *PromiseRecordDecl,
888 FunctionScopeInfo &Fn) {
889 auto Loc = E->getExprLoc();
890 if (auto *DeclRef = dyn_cast_or_null<DeclRefExpr>(E)) {
891 auto *Decl = DeclRef->getDecl();
892 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Decl)) {
893 if (Method->isStatic())
894 return true;
895 else
896 Loc = Decl->getLocation();
897 }
898 }
899
900 S.Diag(
901 Loc,
902 diag::err_coroutine_promise_get_return_object_on_allocation_failure)
903 << PromiseRecordDecl;
904 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
905 << Fn.getFirstCoroutineStmtKeyword();
906 return false;
907}
908
Eric Fiselierbee782b2017-04-03 19:21:00 +0000909bool CoroutineStmtBuilder::makeReturnOnAllocFailure() {
910 assert(!IsPromiseDependentType &&
911 "cannot make statement while the promise type is dependent");
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000912
913 // [dcl.fct.def.coroutine]/8
914 // The unqualified-id get_return_object_on_allocation_failure is looked up in
915 // the scope of class P by class member access lookup (3.4.5). ...
916 // If an allocation function returns nullptr, ... the coroutine return value
917 // is obtained by a call to ... get_return_object_on_allocation_failure().
918
919 DeclarationName DN =
920 S.PP.getIdentifierInfo("get_return_object_on_allocation_failure");
921 LookupResult Found(S, DN, Loc, Sema::LookupMemberName);
Eric Fiselierbee782b2017-04-03 19:21:00 +0000922 if (!S.LookupQualifiedName(Found, PromiseRecordDecl))
923 return true;
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000924
925 CXXScopeSpec SS;
926 ExprResult DeclNameExpr =
927 S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
Eric Fiselierbee782b2017-04-03 19:21:00 +0000928 if (DeclNameExpr.isInvalid())
929 return false;
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000930
931 if (!diagReturnOnAllocFailure(S, DeclNameExpr.get(), PromiseRecordDecl, Fn))
932 return false;
933
934 ExprResult ReturnObjectOnAllocationFailure =
935 S.ActOnCallExpr(nullptr, DeclNameExpr.get(), Loc, {}, Loc);
Eric Fiselierbee782b2017-04-03 19:21:00 +0000936 if (ReturnObjectOnAllocationFailure.isInvalid())
937 return false;
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000938
Gor Nishanovc4a19082017-03-28 02:51:45 +0000939 StmtResult ReturnStmt =
940 S.BuildReturnStmt(Loc, ReturnObjectOnAllocationFailure.get());
Gor Nishanov6a470682017-05-22 20:22:23 +0000941 if (ReturnStmt.isInvalid()) {
Eric Fiselierfc50f622017-05-25 14:59:39 +0000942 S.Diag(Found.getFoundDecl()->getLocation(), diag::note_member_declared_here)
943 << DN;
Gor Nishanov6a470682017-05-22 20:22:23 +0000944 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
945 << Fn.getFirstCoroutineStmtKeyword();
Eric Fiselierbee782b2017-04-03 19:21:00 +0000946 return false;
Gor Nishanov6a470682017-05-22 20:22:23 +0000947 }
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000948
949 this->ReturnStmtOnAllocFailure = ReturnStmt.get();
950 return true;
951}
952
Eric Fiselierbee782b2017-04-03 19:21:00 +0000953bool CoroutineStmtBuilder::makeNewAndDeleteExpr() {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000954 // Form and check allocation and deallocation calls.
Eric Fiselierbee782b2017-04-03 19:21:00 +0000955 assert(!IsPromiseDependentType &&
956 "cannot make statement while the promise type is dependent");
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000957 QualType PromiseType = Fn.CoroutinePromise->getType();
Gor Nishanov8df64e92016-10-27 16:28:31 +0000958
959 if (S.RequireCompleteType(Loc, PromiseType, diag::err_incomplete_type))
960 return false;
961
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000962 const bool RequiresNoThrowAlloc = ReturnStmtOnAllocFailure != nullptr;
963
Gor Nishanov8df64e92016-10-27 16:28:31 +0000964 // FIXME: Add support for stateful allocators.
965
966 FunctionDecl *OperatorNew = nullptr;
967 FunctionDecl *OperatorDelete = nullptr;
968 FunctionDecl *UnusedResult = nullptr;
969 bool PassAlignment = false;
Eric Fiselierf747f532017-04-18 05:08:08 +0000970 SmallVector<Expr *, 1> PlacementArgs;
Gor Nishanov8df64e92016-10-27 16:28:31 +0000971
972 S.FindAllocationFunctions(Loc, SourceRange(),
973 /*UseGlobal*/ false, PromiseType,
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000974 /*isArray*/ false, PassAlignment, PlacementArgs,
975 OperatorNew, UnusedResult);
Gor Nishanov8df64e92016-10-27 16:28:31 +0000976
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000977 bool IsGlobalOverload =
978 OperatorNew && !isa<CXXRecordDecl>(OperatorNew->getDeclContext());
979 // If we didn't find a class-local new declaration and non-throwing new
980 // was is required then we need to lookup the non-throwing global operator
981 // instead.
982 if (RequiresNoThrowAlloc && (!OperatorNew || IsGlobalOverload)) {
983 auto *StdNoThrow = buildStdNoThrowDeclRef(S, Loc);
984 if (!StdNoThrow)
985 return false;
Eric Fiselierf747f532017-04-18 05:08:08 +0000986 PlacementArgs = {StdNoThrow};
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000987 OperatorNew = nullptr;
988 S.FindAllocationFunctions(Loc, SourceRange(),
989 /*UseGlobal*/ true, PromiseType,
990 /*isArray*/ false, PassAlignment, PlacementArgs,
991 OperatorNew, UnusedResult);
992 }
Gor Nishanov8df64e92016-10-27 16:28:31 +0000993
Eric Fiselierc5128752017-04-18 05:30:39 +0000994 assert(OperatorNew && "expected definition of operator new to be found");
995
996 if (RequiresNoThrowAlloc) {
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000997 const auto *FT = OperatorNew->getType()->getAs<FunctionProtoType>();
998 if (!FT->isNothrow(S.Context, /*ResultIfDependent*/ false)) {
999 S.Diag(OperatorNew->getLocation(),
1000 diag::err_coroutine_promise_new_requires_nothrow)
1001 << OperatorNew;
1002 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
1003 << OperatorNew;
1004 return false;
1005 }
1006 }
1007
1008 if ((OperatorDelete = findDeleteForPromise(S, Loc, PromiseType)) == nullptr)
Gor Nishanov8df64e92016-10-27 16:28:31 +00001009 return false;
1010
1011 Expr *FramePtr =
1012 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_frame, {});
1013
1014 Expr *FrameSize =
1015 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_size, {});
1016
1017 // Make new call.
1018
1019 ExprResult NewRef =
1020 S.BuildDeclRefExpr(OperatorNew, OperatorNew->getType(), VK_LValue, Loc);
1021 if (NewRef.isInvalid())
1022 return false;
1023
Eric Fiselierf747f532017-04-18 05:08:08 +00001024 SmallVector<Expr *, 2> NewArgs(1, FrameSize);
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001025 for (auto Arg : PlacementArgs)
1026 NewArgs.push_back(Arg);
1027
Gor Nishanov8df64e92016-10-27 16:28:31 +00001028 ExprResult NewExpr =
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001029 S.ActOnCallExpr(S.getCurScope(), NewRef.get(), Loc, NewArgs, Loc);
1030 NewExpr = S.ActOnFinishFullExpr(NewExpr.get());
Gor Nishanov8df64e92016-10-27 16:28:31 +00001031 if (NewExpr.isInvalid())
1032 return false;
1033
Gor Nishanov8df64e92016-10-27 16:28:31 +00001034 // Make delete call.
1035
1036 QualType OpDeleteQualType = OperatorDelete->getType();
1037
1038 ExprResult DeleteRef =
1039 S.BuildDeclRefExpr(OperatorDelete, OpDeleteQualType, VK_LValue, Loc);
1040 if (DeleteRef.isInvalid())
1041 return false;
1042
1043 Expr *CoroFree =
1044 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_free, {FramePtr});
1045
1046 SmallVector<Expr *, 2> DeleteArgs{CoroFree};
1047
1048 // Check if we need to pass the size.
1049 const auto *OpDeleteType =
1050 OpDeleteQualType.getTypePtr()->getAs<FunctionProtoType>();
1051 if (OpDeleteType->getNumParams() > 1)
1052 DeleteArgs.push_back(FrameSize);
1053
1054 ExprResult DeleteExpr =
1055 S.ActOnCallExpr(S.getCurScope(), DeleteRef.get(), Loc, DeleteArgs, Loc);
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001056 DeleteExpr = S.ActOnFinishFullExpr(DeleteExpr.get());
Gor Nishanov8df64e92016-10-27 16:28:31 +00001057 if (DeleteExpr.isInvalid())
1058 return false;
1059
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001060 this->Allocate = NewExpr.get();
1061 this->Deallocate = DeleteExpr.get();
Gor Nishanov8df64e92016-10-27 16:28:31 +00001062
1063 return true;
1064}
1065
Eric Fiselierbee782b2017-04-03 19:21:00 +00001066bool CoroutineStmtBuilder::makeOnFallthrough() {
1067 assert(!IsPromiseDependentType &&
1068 "cannot make statement while the promise type is dependent");
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001069
1070 // [dcl.fct.def.coroutine]/4
1071 // The unqualified-ids 'return_void' and 'return_value' are looked up in
1072 // the scope of class P. If both are found, the program is ill-formed.
Eric Fiselierfc50f622017-05-25 14:59:39 +00001073 bool HasRVoid, HasRValue;
1074 LookupResult LRVoid =
1075 lookupMember(S, "return_void", PromiseRecordDecl, Loc, HasRVoid);
1076 LookupResult LRValue =
1077 lookupMember(S, "return_value", PromiseRecordDecl, Loc, HasRValue);
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001078
Eric Fiselier709d1b32016-10-27 07:30:31 +00001079 StmtResult Fallthrough;
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001080 if (HasRVoid && HasRValue) {
1081 // FIXME Improve this diagnostic
Eric Fiselierfc50f622017-05-25 14:59:39 +00001082 S.Diag(FD.getLocation(),
1083 diag::err_coroutine_promise_incompatible_return_functions)
1084 << PromiseRecordDecl;
1085 S.Diag(LRVoid.getRepresentativeDecl()->getLocation(),
1086 diag::note_member_first_declared_here)
1087 << LRVoid.getLookupName();
1088 S.Diag(LRValue.getRepresentativeDecl()->getLocation(),
1089 diag::note_member_first_declared_here)
1090 << LRValue.getLookupName();
1091 return false;
1092 } else if (!HasRVoid && !HasRValue) {
1093 // FIXME: The PDTS currently specifies this case as UB, not ill-formed.
1094 // However we still diagnose this as an error since until the PDTS is fixed.
1095 S.Diag(FD.getLocation(),
1096 diag::err_coroutine_promise_requires_return_function)
1097 << PromiseRecordDecl;
1098 S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here)
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001099 << PromiseRecordDecl;
1100 return false;
1101 } else if (HasRVoid) {
1102 // If the unqualified-id return_void is found, flowing off the end of a
1103 // coroutine is equivalent to a co_return with no operand. Otherwise,
1104 // flowing off the end of a coroutine results in undefined behavior.
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001105 Fallthrough = S.BuildCoreturnStmt(FD.getLocation(), nullptr,
1106 /*IsImplicit*/false);
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001107 Fallthrough = S.ActOnFinishFullStmt(Fallthrough.get());
1108 if (Fallthrough.isInvalid())
1109 return false;
Eric Fiselier709d1b32016-10-27 07:30:31 +00001110 }
Richard Smith2af65c42015-11-24 02:34:39 +00001111
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001112 this->OnFallthrough = Fallthrough.get();
1113 return true;
1114}
1115
Eric Fiselierbee782b2017-04-03 19:21:00 +00001116bool CoroutineStmtBuilder::makeOnException() {
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001117 // Try to form 'p.unhandled_exception();'
Eric Fiselierbee782b2017-04-03 19:21:00 +00001118 assert(!IsPromiseDependentType &&
1119 "cannot make statement while the promise type is dependent");
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001120
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001121 const bool RequireUnhandledException = S.getLangOpts().CXXExceptions;
1122
1123 if (!lookupMember(S, "unhandled_exception", PromiseRecordDecl, Loc)) {
1124 auto DiagID =
1125 RequireUnhandledException
1126 ? diag::err_coroutine_promise_unhandled_exception_required
1127 : diag::
1128 warn_coroutine_promise_unhandled_exception_required_with_exceptions;
1129 S.Diag(Loc, DiagID) << PromiseRecordDecl;
Gor Nishanov29ff6382017-05-24 14:34:19 +00001130 S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here)
1131 << PromiseRecordDecl;
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001132 return !RequireUnhandledException;
1133 }
1134
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001135 // If exceptions are disabled, don't try to build OnException.
1136 if (!S.getLangOpts().CXXExceptions)
1137 return true;
1138
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001139 ExprResult UnhandledException = buildPromiseCall(S, Fn.CoroutinePromise, Loc,
1140 "unhandled_exception", None);
1141 UnhandledException = S.ActOnFinishFullExpr(UnhandledException.get(), Loc);
1142 if (UnhandledException.isInvalid())
1143 return false;
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001144
Gor Nishanov5b050e42017-05-22 22:33:17 +00001145 // Since the body of the coroutine will be wrapped in try-catch, it will
1146 // be incompatible with SEH __try if present in a function.
1147 if (!S.getLangOpts().Borland && Fn.FirstSEHTryLoc.isValid()) {
1148 S.Diag(Fn.FirstSEHTryLoc, diag::err_seh_in_a_coroutine_with_cxx_exceptions);
1149 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1150 << Fn.getFirstCoroutineStmtKeyword();
1151 return false;
1152 }
1153
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001154 this->OnException = UnhandledException.get();
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001155 return true;
1156}
1157
Eric Fiselierbee782b2017-04-03 19:21:00 +00001158bool CoroutineStmtBuilder::makeReturnObject() {
Richard Smith2af65c42015-11-24 02:34:39 +00001159 // Build implicit 'p.get_return_object()' expression and form initialization
1160 // of return type from it.
1161 ExprResult ReturnObject =
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001162 buildPromiseCall(S, Fn.CoroutinePromise, Loc, "get_return_object", None);
Richard Smith2af65c42015-11-24 02:34:39 +00001163 if (ReturnObject.isInvalid())
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001164 return false;
Richard Smith2af65c42015-11-24 02:34:39 +00001165
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001166 this->ReturnValue = ReturnObject.get();
1167 return true;
1168}
1169
Gor Nishanov6a470682017-05-22 20:22:23 +00001170static void noteMemberDeclaredHere(Sema &S, Expr *E, FunctionScopeInfo &Fn) {
1171 if (auto *MbrRef = dyn_cast<CXXMemberCallExpr>(E)) {
1172 auto *MethodDecl = MbrRef->getMethodDecl();
Eric Fiselierfc50f622017-05-25 14:59:39 +00001173 S.Diag(MethodDecl->getLocation(), diag::note_member_declared_here)
1174 << MethodDecl;
Gor Nishanov6a470682017-05-22 20:22:23 +00001175 }
1176 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1177 << Fn.getFirstCoroutineStmtKeyword();
1178}
1179
1180bool CoroutineStmtBuilder::makeGroDeclAndReturnStmt() {
1181 assert(!IsPromiseDependentType &&
1182 "cannot make statement while the promise type is dependent");
1183 assert(this->ReturnValue && "ReturnValue must be already formed");
1184
1185 QualType const GroType = this->ReturnValue->getType();
1186 assert(!GroType->isDependentType() &&
1187 "get_return_object type must no longer be dependent");
1188
1189 QualType const FnRetType = FD.getReturnType();
1190 assert(!FnRetType->isDependentType() &&
1191 "get_return_object type must no longer be dependent");
1192
1193 if (FnRetType->isVoidType()) {
1194 ExprResult Res = S.ActOnFinishFullExpr(this->ReturnValue, Loc);
1195 if (Res.isInvalid())
1196 return false;
1197
1198 this->ResultDecl = Res.get();
1199 return true;
1200 }
1201
1202 if (GroType->isVoidType()) {
1203 // Trigger a nice error message.
1204 InitializedEntity Entity =
1205 InitializedEntity::InitializeResult(Loc, FnRetType, false);
1206 S.PerformMoveOrCopyInitialization(Entity, nullptr, FnRetType, ReturnValue);
1207 noteMemberDeclaredHere(S, ReturnValue, Fn);
1208 return false;
1209 }
1210
1211 auto *GroDecl = VarDecl::Create(
1212 S.Context, &FD, FD.getLocation(), FD.getLocation(),
1213 &S.PP.getIdentifierTable().get("__coro_gro"), GroType,
1214 S.Context.getTrivialTypeSourceInfo(GroType, Loc), SC_None);
1215
1216 S.CheckVariableDeclarationType(GroDecl);
1217 if (GroDecl->isInvalidDecl())
1218 return false;
1219
1220 InitializedEntity Entity = InitializedEntity::InitializeVariable(GroDecl);
1221 ExprResult Res = S.PerformMoveOrCopyInitialization(Entity, nullptr, GroType,
1222 this->ReturnValue);
1223 if (Res.isInvalid())
1224 return false;
1225
1226 Res = S.ActOnFinishFullExpr(Res.get());
1227 if (Res.isInvalid())
1228 return false;
1229
1230 if (GroType == FnRetType) {
1231 GroDecl->setNRVOVariable(true);
1232 }
1233
1234 S.AddInitializerToDecl(GroDecl, Res.get(),
1235 /*DirectInit=*/false);
1236
1237 S.FinalizeDeclaration(GroDecl);
1238
1239 // Form a declaration statement for the return declaration, so that AST
1240 // visitors can more easily find it.
1241 StmtResult GroDeclStmt =
1242 S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(GroDecl), Loc, Loc);
1243 if (GroDeclStmt.isInvalid())
1244 return false;
1245
1246 this->ResultDecl = GroDeclStmt.get();
1247
1248 ExprResult declRef = S.BuildDeclRefExpr(GroDecl, GroType, VK_LValue, Loc);
1249 if (declRef.isInvalid())
1250 return false;
1251
1252 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, declRef.get());
1253 if (ReturnStmt.isInvalid()) {
1254 noteMemberDeclaredHere(S, ReturnValue, Fn);
1255 return false;
1256 }
1257
1258 this->ReturnStmt = ReturnStmt.get();
1259 return true;
1260}
1261
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001262// Create a static_cast\<T&&>(expr).
1263static Expr *castForMoving(Sema &S, Expr *E, QualType T = QualType()) {
1264 if (T.isNull())
1265 T = E->getType();
1266 QualType TargetType = S.BuildReferenceType(
1267 T, /*SpelledAsLValue*/ false, SourceLocation(), DeclarationName());
1268 SourceLocation ExprLoc = E->getLocStart();
1269 TypeSourceInfo *TargetLoc =
1270 S.Context.getTrivialTypeSourceInfo(TargetType, ExprLoc);
1271
1272 return S
1273 .BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
1274 SourceRange(ExprLoc, ExprLoc), E->getSourceRange())
1275 .get();
1276}
1277
Eric Fiselierde7943b2017-06-03 00:22:18 +00001278
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001279/// \brief Build a variable declaration for move parameter.
1280static VarDecl *buildVarDecl(Sema &S, SourceLocation Loc, QualType Type,
Eric Fiselierde7943b2017-06-03 00:22:18 +00001281 IdentifierInfo *II) {
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001282 TypeSourceInfo *TInfo = S.Context.getTrivialTypeSourceInfo(Type, Loc);
1283 VarDecl *Decl =
Eric Fiselierde7943b2017-06-03 00:22:18 +00001284 VarDecl::Create(S.Context, S.CurContext, Loc, Loc, II, Type, TInfo, SC_None);
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001285 Decl->setImplicit();
1286 return Decl;
1287}
1288
Eric Fiselierbee782b2017-04-03 19:21:00 +00001289bool CoroutineStmtBuilder::makeParamMoves() {
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001290 for (auto *paramDecl : FD.parameters()) {
1291 auto Ty = paramDecl->getType();
1292 if (Ty->isDependentType())
1293 continue;
1294
1295 // No need to copy scalars, llvm will take care of them.
1296 if (Ty->getAsCXXRecordDecl()) {
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001297 ExprResult ParamRef =
1298 S.BuildDeclRefExpr(paramDecl, paramDecl->getType(),
1299 ExprValueKind::VK_LValue, Loc); // FIXME: scope?
1300 if (ParamRef.isInvalid())
1301 return false;
1302
1303 Expr *RCast = castForMoving(S, ParamRef.get());
1304
Eric Fiselierde7943b2017-06-03 00:22:18 +00001305 auto D = buildVarDecl(S, Loc, Ty, paramDecl->getIdentifier());
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001306 S.AddInitializerToDecl(D, RCast, /*DirectInit=*/true);
1307
1308 // Convert decl to a statement.
1309 StmtResult Stmt = S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(D), Loc, Loc);
1310 if (Stmt.isInvalid())
1311 return false;
1312
1313 ParamMovesVector.push_back(Stmt.get());
1314 }
1315 }
1316
1317 // Convert to ArrayRef in CtorArgs structure that builder inherits from.
1318 ParamMoves = ParamMovesVector;
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001319 return true;
Richard Smithcfd53b42015-10-22 06:13:50 +00001320}
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001321
1322StmtResult Sema::BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
1323 CoroutineBodyStmt *Res = CoroutineBodyStmt::Create(Context, Args);
1324 if (!Res)
1325 return StmtError();
1326 return Res;
1327}