blob: b05c0998d3dd70031d6d9bade8a40eda0ca4c915 [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.
46static QualType lookupPromiseType(Sema &S, const FunctionProtoType *FnType,
Eric Fiselier89bf0e72017-03-06 22:52:28 +000047 SourceLocation KwLoc,
48 SourceLocation FuncLoc) {
Richard Smith9f690bd2015-10-27 06:02:45 +000049 // FIXME: Cache std::coroutine_traits once we've found it.
Gor Nishanov3e048bb2016-10-04 00:31:16 +000050 NamespaceDecl *StdExp = S.lookupStdExperimentalNamespace();
51 if (!StdExp) {
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +000052 S.Diag(KwLoc, diag::err_implied_coroutine_type_not_found)
53 << "std::experimental::coroutine_traits";
Richard Smith9f690bd2015-10-27 06:02:45 +000054 return QualType();
55 }
56
57 LookupResult Result(S, &S.PP.getIdentifierTable().get("coroutine_traits"),
Eric Fiselier89bf0e72017-03-06 22:52:28 +000058 FuncLoc, Sema::LookupOrdinaryName);
Gor Nishanov3e048bb2016-10-04 00:31:16 +000059 if (!S.LookupQualifiedName(Result, StdExp)) {
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +000060 S.Diag(KwLoc, diag::err_implied_coroutine_type_not_found)
61 << "std::experimental::coroutine_traits";
Richard Smith9f690bd2015-10-27 06:02:45 +000062 return QualType();
63 }
64
65 ClassTemplateDecl *CoroTraits = Result.getAsSingle<ClassTemplateDecl>();
66 if (!CoroTraits) {
67 Result.suppressDiagnostics();
68 // We found something weird. Complain about the first thing we found.
69 NamedDecl *Found = *Result.begin();
70 S.Diag(Found->getLocation(), diag::err_malformed_std_coroutine_traits);
71 return QualType();
72 }
73
74 // Form template argument list for coroutine_traits<R, P1, P2, ...>.
Eric Fiselier89bf0e72017-03-06 22:52:28 +000075 TemplateArgumentListInfo Args(KwLoc, KwLoc);
Richard Smith9f690bd2015-10-27 06:02:45 +000076 Args.addArgument(TemplateArgumentLoc(
77 TemplateArgument(FnType->getReturnType()),
Eric Fiselier89bf0e72017-03-06 22:52:28 +000078 S.Context.getTrivialTypeSourceInfo(FnType->getReturnType(), KwLoc)));
Richard Smith71d403e2015-11-22 07:33:28 +000079 // FIXME: If the function is a non-static member function, add the type
80 // of the implicit object parameter before the formal parameters.
Richard Smith9f690bd2015-10-27 06:02:45 +000081 for (QualType T : FnType->getParamTypes())
82 Args.addArgument(TemplateArgumentLoc(
Eric Fiselier89bf0e72017-03-06 22:52:28 +000083 TemplateArgument(T), S.Context.getTrivialTypeSourceInfo(T, KwLoc)));
Richard Smith9f690bd2015-10-27 06:02:45 +000084
85 // Build the template-id.
86 QualType CoroTrait =
Eric Fiselier89bf0e72017-03-06 22:52:28 +000087 S.CheckTemplateIdType(TemplateName(CoroTraits), KwLoc, Args);
Richard Smith9f690bd2015-10-27 06:02:45 +000088 if (CoroTrait.isNull())
89 return QualType();
Eric Fiselier89bf0e72017-03-06 22:52:28 +000090 if (S.RequireCompleteType(KwLoc, CoroTrait,
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +000091 diag::err_coroutine_type_missing_specialization))
Richard Smith9f690bd2015-10-27 06:02:45 +000092 return QualType();
93
Eric Fiselier89bf0e72017-03-06 22:52:28 +000094 auto *RD = CoroTrait->getAsCXXRecordDecl();
Richard Smith9f690bd2015-10-27 06:02:45 +000095 assert(RD && "specialization of class template is not a class?");
96
97 // Look up the ::promise_type member.
Eric Fiselier89bf0e72017-03-06 22:52:28 +000098 LookupResult R(S, &S.PP.getIdentifierTable().get("promise_type"), KwLoc,
Richard Smith9f690bd2015-10-27 06:02:45 +000099 Sema::LookupOrdinaryName);
100 S.LookupQualifiedName(R, RD);
101 auto *Promise = R.getAsSingle<TypeDecl>();
102 if (!Promise) {
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000103 S.Diag(FuncLoc,
104 diag::err_implied_std_coroutine_traits_promise_type_not_found)
Gor Nishanov8df64e92016-10-27 16:28:31 +0000105 << RD;
Richard Smith9f690bd2015-10-27 06:02:45 +0000106 return QualType();
107 }
Richard Smith9f690bd2015-10-27 06:02:45 +0000108 // The promise type is required to be a class type.
109 QualType PromiseType = S.Context.getTypeDeclType(Promise);
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000110
111 auto buildElaboratedType = [&]() {
Gor Nishanov3e048bb2016-10-04 00:31:16 +0000112 auto *NNS = NestedNameSpecifier::Create(S.Context, nullptr, StdExp);
Richard Smith9b2f53e2015-11-19 02:36:35 +0000113 NNS = NestedNameSpecifier::Create(S.Context, NNS, false,
114 CoroTrait.getTypePtr());
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000115 return S.Context.getElaboratedType(ETK_None, NNS, PromiseType);
116 };
Richard Smith9b2f53e2015-11-19 02:36:35 +0000117
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000118 if (!PromiseType->getAsCXXRecordDecl()) {
119 S.Diag(FuncLoc,
120 diag::err_implied_std_coroutine_traits_promise_type_not_class)
121 << buildElaboratedType();
Richard Smith9f690bd2015-10-27 06:02:45 +0000122 return QualType();
123 }
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000124 if (S.RequireCompleteType(FuncLoc, buildElaboratedType(),
125 diag::err_coroutine_promise_type_incomplete))
126 return QualType();
Richard Smith9f690bd2015-10-27 06:02:45 +0000127
128 return PromiseType;
129}
130
Gor Nishanov29ff6382017-05-24 14:34:19 +0000131/// Look up the std::experimental::coroutine_handle<PromiseType>.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000132static QualType lookupCoroutineHandleType(Sema &S, QualType PromiseType,
133 SourceLocation Loc) {
134 if (PromiseType.isNull())
135 return QualType();
136
137 NamespaceDecl *StdExp = S.lookupStdExperimentalNamespace();
138 assert(StdExp && "Should already be diagnosed");
139
140 LookupResult Result(S, &S.PP.getIdentifierTable().get("coroutine_handle"),
141 Loc, Sema::LookupOrdinaryName);
142 if (!S.LookupQualifiedName(Result, StdExp)) {
143 S.Diag(Loc, diag::err_implied_coroutine_type_not_found)
144 << "std::experimental::coroutine_handle";
145 return QualType();
146 }
147
148 ClassTemplateDecl *CoroHandle = Result.getAsSingle<ClassTemplateDecl>();
149 if (!CoroHandle) {
150 Result.suppressDiagnostics();
151 // We found something weird. Complain about the first thing we found.
152 NamedDecl *Found = *Result.begin();
153 S.Diag(Found->getLocation(), diag::err_malformed_std_coroutine_handle);
154 return QualType();
155 }
156
157 // Form template argument list for coroutine_handle<Promise>.
158 TemplateArgumentListInfo Args(Loc, Loc);
159 Args.addArgument(TemplateArgumentLoc(
160 TemplateArgument(PromiseType),
161 S.Context.getTrivialTypeSourceInfo(PromiseType, Loc)));
162
163 // Build the template-id.
164 QualType CoroHandleType =
165 S.CheckTemplateIdType(TemplateName(CoroHandle), Loc, Args);
166 if (CoroHandleType.isNull())
167 return QualType();
168 if (S.RequireCompleteType(Loc, CoroHandleType,
169 diag::err_coroutine_type_missing_specialization))
170 return QualType();
171
172 return CoroHandleType;
173}
174
Eric Fiselierc8efda72016-10-27 18:43:28 +0000175static bool isValidCoroutineContext(Sema &S, SourceLocation Loc,
176 StringRef Keyword) {
Richard Smith744b2242015-11-20 02:54:01 +0000177 // 'co_await' and 'co_yield' are not permitted in unevaluated operands.
178 if (S.isUnevaluatedContext()) {
179 S.Diag(Loc, diag::err_coroutine_unevaluated_context) << Keyword;
Eric Fiselierc8efda72016-10-27 18:43:28 +0000180 return false;
Richard Smith744b2242015-11-20 02:54:01 +0000181 }
Richard Smithcfd53b42015-10-22 06:13:50 +0000182
183 // Any other usage must be within a function.
184 auto *FD = dyn_cast<FunctionDecl>(S.CurContext);
185 if (!FD) {
186 S.Diag(Loc, isa<ObjCMethodDecl>(S.CurContext)
187 ? diag::err_coroutine_objc_method
188 : diag::err_coroutine_outside_function) << Keyword;
Eric Fiselierc8efda72016-10-27 18:43:28 +0000189 return false;
Richard Smithcfd53b42015-10-22 06:13:50 +0000190 }
191
Eric Fiselierc8efda72016-10-27 18:43:28 +0000192 // An enumeration for mapping the diagnostic type to the correct diagnostic
193 // selection index.
194 enum InvalidFuncDiag {
195 DiagCtor = 0,
196 DiagDtor,
197 DiagCopyAssign,
198 DiagMoveAssign,
199 DiagMain,
200 DiagConstexpr,
201 DiagAutoRet,
202 DiagVarargs,
203 };
204 bool Diagnosed = false;
205 auto DiagInvalid = [&](InvalidFuncDiag ID) {
206 S.Diag(Loc, diag::err_coroutine_invalid_func_context) << ID << Keyword;
207 Diagnosed = true;
208 return false;
209 };
210
211 // Diagnose when a constructor, destructor, copy/move assignment operator,
212 // or the function 'main' are declared as a coroutine.
213 auto *MD = dyn_cast<CXXMethodDecl>(FD);
214 if (MD && isa<CXXConstructorDecl>(MD))
215 return DiagInvalid(DiagCtor);
216 else if (MD && isa<CXXDestructorDecl>(MD))
217 return DiagInvalid(DiagDtor);
218 else if (MD && MD->isCopyAssignmentOperator())
219 return DiagInvalid(DiagCopyAssign);
220 else if (MD && MD->isMoveAssignmentOperator())
221 return DiagInvalid(DiagMoveAssign);
222 else if (FD->isMain())
223 return DiagInvalid(DiagMain);
224
225 // Emit a diagnostics for each of the following conditions which is not met.
226 if (FD->isConstexpr())
227 DiagInvalid(DiagConstexpr);
228 if (FD->getReturnType()->isUndeducedType())
229 DiagInvalid(DiagAutoRet);
230 if (FD->isVariadic())
231 DiagInvalid(DiagVarargs);
232
233 return !Diagnosed;
234}
235
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000236static ExprResult buildOperatorCoawaitLookupExpr(Sema &SemaRef, Scope *S,
237 SourceLocation Loc) {
238 DeclarationName OpName =
239 SemaRef.Context.DeclarationNames.getCXXOperatorName(OO_Coawait);
240 LookupResult Operators(SemaRef, OpName, SourceLocation(),
241 Sema::LookupOperatorName);
242 SemaRef.LookupName(Operators, S);
Eric Fiselierc8efda72016-10-27 18:43:28 +0000243
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000244 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
245 const auto &Functions = Operators.asUnresolvedSet();
246 bool IsOverloaded =
247 Functions.size() > 1 ||
248 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
249 Expr *CoawaitOp = UnresolvedLookupExpr::Create(
250 SemaRef.Context, /*NamingClass*/ nullptr, NestedNameSpecifierLoc(),
251 DeclarationNameInfo(OpName, Loc), /*RequiresADL*/ true, IsOverloaded,
252 Functions.begin(), Functions.end());
253 assert(CoawaitOp);
254 return CoawaitOp;
255}
Eric Fiselierc8efda72016-10-27 18:43:28 +0000256
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000257/// Build a call to 'operator co_await' if there is a suitable operator for
258/// the given expression.
259static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, SourceLocation Loc,
260 Expr *E,
261 UnresolvedLookupExpr *Lookup) {
262 UnresolvedSet<16> Functions;
263 Functions.append(Lookup->decls_begin(), Lookup->decls_end());
264 return SemaRef.CreateOverloadedUnaryOp(Loc, UO_Coawait, Functions, E);
265}
Eric Fiselierc8efda72016-10-27 18:43:28 +0000266
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000267static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, Scope *S,
268 SourceLocation Loc, Expr *E) {
269 ExprResult R = buildOperatorCoawaitLookupExpr(SemaRef, S, Loc);
270 if (R.isInvalid())
271 return ExprError();
272 return buildOperatorCoawaitCall(SemaRef, Loc, E,
273 cast<UnresolvedLookupExpr>(R.get()));
Richard Smithcfd53b42015-10-22 06:13:50 +0000274}
275
Gor Nishanov8df64e92016-10-27 16:28:31 +0000276static Expr *buildBuiltinCall(Sema &S, SourceLocation Loc, Builtin::ID Id,
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000277 MultiExprArg CallArgs) {
Gor Nishanov8df64e92016-10-27 16:28:31 +0000278 StringRef Name = S.Context.BuiltinInfo.getName(Id);
279 LookupResult R(S, &S.Context.Idents.get(Name), Loc, Sema::LookupOrdinaryName);
280 S.LookupName(R, S.TUScope, /*AllowBuiltinCreation=*/true);
281
282 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
283 assert(BuiltInDecl && "failed to find builtin declaration");
284
285 ExprResult DeclRef =
286 S.BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
287 assert(DeclRef.isUsable() && "Builtin reference cannot fail");
288
289 ExprResult Call =
290 S.ActOnCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
291
292 assert(!Call.isInvalid() && "Call to builtin cannot fail!");
293 return Call.get();
294}
295
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000296static ExprResult buildCoroutineHandle(Sema &S, QualType PromiseType,
297 SourceLocation Loc) {
298 QualType CoroHandleType = lookupCoroutineHandleType(S, PromiseType, Loc);
299 if (CoroHandleType.isNull())
300 return ExprError();
301
302 DeclContext *LookupCtx = S.computeDeclContext(CoroHandleType);
303 LookupResult Found(S, &S.PP.getIdentifierTable().get("from_address"), Loc,
304 Sema::LookupOrdinaryName);
305 if (!S.LookupQualifiedName(Found, LookupCtx)) {
306 S.Diag(Loc, diag::err_coroutine_handle_missing_member)
307 << "from_address";
308 return ExprError();
309 }
310
311 Expr *FramePtr =
312 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_frame, {});
313
314 CXXScopeSpec SS;
315 ExprResult FromAddr =
316 S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
317 if (FromAddr.isInvalid())
318 return ExprError();
319
320 return S.ActOnCallExpr(nullptr, FromAddr.get(), Loc, FramePtr, Loc);
321}
Richard Smithcfd53b42015-10-22 06:13:50 +0000322
Richard Smith9f690bd2015-10-27 06:02:45 +0000323struct ReadySuspendResumeResult {
Eric Fiselierd978e532017-05-28 18:21:12 +0000324 enum AwaitCallType { ACT_Ready, ACT_Suspend, ACT_Resume };
Richard Smith9f690bd2015-10-27 06:02:45 +0000325 Expr *Results[3];
Gor Nishanovce43bd22017-03-11 01:30:17 +0000326 OpaqueValueExpr *OpaqueValue;
327 bool IsInvalid;
Richard Smith9f690bd2015-10-27 06:02:45 +0000328};
329
Richard Smith23da82c2015-11-20 22:40:06 +0000330static ExprResult buildMemberCall(Sema &S, Expr *Base, SourceLocation Loc,
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000331 StringRef Name, MultiExprArg Args) {
Richard Smith23da82c2015-11-20 22:40:06 +0000332 DeclarationNameInfo NameInfo(&S.PP.getIdentifierTable().get(Name), Loc);
333
334 // FIXME: Fix BuildMemberReferenceExpr to take a const CXXScopeSpec&.
335 CXXScopeSpec SS;
336 ExprResult Result = S.BuildMemberReferenceExpr(
337 Base, Base->getType(), Loc, /*IsPtr=*/false, SS,
338 SourceLocation(), nullptr, NameInfo, /*TemplateArgs=*/nullptr,
339 /*Scope=*/nullptr);
340 if (Result.isInvalid())
341 return ExprError();
342
343 return S.ActOnCallExpr(nullptr, Result.get(), Loc, Args, Loc, nullptr);
344}
345
Richard Smith9f690bd2015-10-27 06:02:45 +0000346/// Build calls to await_ready, await_suspend, and await_resume for a co_await
347/// expression.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000348static ReadySuspendResumeResult buildCoawaitCalls(Sema &S, VarDecl *CoroPromise,
349 SourceLocation Loc, Expr *E) {
Gor Nishanovce43bd22017-03-11 01:30:17 +0000350 OpaqueValueExpr *Operand = new (S.Context)
351 OpaqueValueExpr(Loc, E->getType(), VK_LValue, E->getObjectKind(), E);
352
Richard Smith9f690bd2015-10-27 06:02:45 +0000353 // Assume invalid until we see otherwise.
Gor Nishanovce43bd22017-03-11 01:30:17 +0000354 ReadySuspendResumeResult Calls = {{}, Operand, /*IsInvalid=*/true};
Richard Smith9f690bd2015-10-27 06:02:45 +0000355
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000356 ExprResult CoroHandleRes = buildCoroutineHandle(S, CoroPromise->getType(), Loc);
357 if (CoroHandleRes.isInvalid())
358 return Calls;
359 Expr *CoroHandle = CoroHandleRes.get();
360
Richard Smith9f690bd2015-10-27 06:02:45 +0000361 const StringRef Funcs[] = {"await_ready", "await_suspend", "await_resume"};
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000362 MultiExprArg Args[] = {None, CoroHandle, None};
Richard Smith9f690bd2015-10-27 06:02:45 +0000363 for (size_t I = 0, N = llvm::array_lengthof(Funcs); I != N; ++I) {
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000364 ExprResult Result = buildMemberCall(S, Operand, Loc, Funcs[I], Args[I]);
Richard Smith9f690bd2015-10-27 06:02:45 +0000365 if (Result.isInvalid())
366 return Calls;
367 Calls.Results[I] = Result.get();
368 }
369
Eric Fiselierd978e532017-05-28 18:21:12 +0000370 // Assume the calls are valid; all further checking should make them invalid.
Richard Smith9f690bd2015-10-27 06:02:45 +0000371 Calls.IsInvalid = false;
Eric Fiselierd978e532017-05-28 18:21:12 +0000372
373 using ACT = ReadySuspendResumeResult::AwaitCallType;
374 CallExpr *AwaitReady = cast<CallExpr>(Calls.Results[ACT::ACT_Ready]);
375 if (!AwaitReady->getType()->isDependentType()) {
376 // [expr.await]p3 [...]
377 // — await-ready is the expression e.await_ready(), contextually converted
378 // to bool.
379 ExprResult Conv = S.PerformContextuallyConvertToBool(AwaitReady);
380 if (Conv.isInvalid()) {
381 S.Diag(AwaitReady->getDirectCallee()->getLocStart(),
382 diag::note_await_ready_no_bool_conversion);
383 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
384 << AwaitReady->getDirectCallee() << E->getSourceRange();
385 Calls.IsInvalid = true;
386 }
387 Calls.Results[ACT::ACT_Ready] = Conv.get();
388 }
389 CallExpr *AwaitSuspend = cast<CallExpr>(Calls.Results[ACT::ACT_Suspend]);
390 if (!AwaitSuspend->getType()->isDependentType()) {
391 // [expr.await]p3 [...]
392 // - await-suspend is the expression e.await_suspend(h), which shall be
393 // a prvalue of type void or bool.
Eric Fiselier84ee7ff2017-05-31 23:41:11 +0000394 QualType RetType = AwaitSuspend->getCallReturnType(S.Context);
395 // non-class prvalues always have cv-unqualified types
396 QualType AdjRetType = RetType.getUnqualifiedType();
397 if (RetType->isReferenceType() ||
398 (AdjRetType != S.Context.BoolTy && AdjRetType != S.Context.VoidTy)) {
Eric Fiselierd978e532017-05-28 18:21:12 +0000399 S.Diag(AwaitSuspend->getCalleeDecl()->getLocation(),
400 diag::err_await_suspend_invalid_return_type)
401 << RetType;
402 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
403 << AwaitSuspend->getDirectCallee();
404 Calls.IsInvalid = true;
405 }
406 }
407
Richard Smith9f690bd2015-10-27 06:02:45 +0000408 return Calls;
409}
410
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000411static ExprResult buildPromiseCall(Sema &S, VarDecl *Promise,
412 SourceLocation Loc, StringRef Name,
413 MultiExprArg Args) {
414
415 // Form a reference to the promise.
416 ExprResult PromiseRef = S.BuildDeclRefExpr(
417 Promise, Promise->getType().getNonReferenceType(), VK_LValue, Loc);
418 if (PromiseRef.isInvalid())
419 return ExprError();
420
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000421 return buildMemberCall(S, PromiseRef.get(), Loc, Name, Args);
422}
423
424VarDecl *Sema::buildCoroutinePromise(SourceLocation Loc) {
425 assert(isa<FunctionDecl>(CurContext) && "not in a function scope");
426 auto *FD = cast<FunctionDecl>(CurContext);
427
428 QualType T =
429 FD->getType()->isDependentType()
430 ? Context.DependentTy
431 : lookupPromiseType(*this, FD->getType()->castAs<FunctionProtoType>(),
432 Loc, FD->getLocation());
433 if (T.isNull())
434 return nullptr;
435
436 auto *VD = VarDecl::Create(Context, FD, FD->getLocation(), FD->getLocation(),
437 &PP.getIdentifierTable().get("__promise"), T,
438 Context.getTrivialTypeSourceInfo(T, Loc), SC_None);
439 CheckVariableDeclarationType(VD);
440 if (VD->isInvalidDecl())
441 return nullptr;
442 ActOnUninitializedDecl(VD);
Eric Fiselier37b8a372017-05-31 19:36:59 +0000443 FD->addDecl(VD);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000444 assert(!VD->isInvalidDecl());
445 return VD;
446}
447
448/// Check that this is a context in which a coroutine suspension can appear.
449static FunctionScopeInfo *checkCoroutineContext(Sema &S, SourceLocation Loc,
Eric Fiseliercac0a592017-03-11 02:35:37 +0000450 StringRef Keyword,
451 bool IsImplicit = false) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000452 if (!isValidCoroutineContext(S, Loc, Keyword))
453 return nullptr;
454
455 assert(isa<FunctionDecl>(S.CurContext) && "not in a function scope");
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000456
457 auto *ScopeInfo = S.getCurFunction();
458 assert(ScopeInfo && "missing function scope for function");
459
Eric Fiseliercac0a592017-03-11 02:35:37 +0000460 if (ScopeInfo->FirstCoroutineStmtLoc.isInvalid() && !IsImplicit)
461 ScopeInfo->setFirstCoroutineStmt(Loc, Keyword);
462
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000463 if (ScopeInfo->CoroutinePromise)
464 return ScopeInfo;
465
466 ScopeInfo->CoroutinePromise = S.buildCoroutinePromise(Loc);
467 if (!ScopeInfo->CoroutinePromise)
468 return nullptr;
469
470 return ScopeInfo;
471}
472
Eric Fiselierb936a392017-06-14 03:24:55 +0000473bool Sema::ActOnCoroutineBodyStart(Scope *SC, SourceLocation KWLoc,
474 StringRef Keyword) {
475 if (!checkCoroutineContext(*this, KWLoc, Keyword))
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000476 return false;
Eric Fiselierb936a392017-06-14 03:24:55 +0000477 auto *ScopeInfo = getCurFunction();
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000478 assert(ScopeInfo->CoroutinePromise);
479
480 // If we have existing coroutine statements then we have already built
481 // the initial and final suspend points.
482 if (!ScopeInfo->NeedsCoroutineSuspends)
483 return true;
484
485 ScopeInfo->setNeedsCoroutineSuspends(false);
486
Eric Fiselierb936a392017-06-14 03:24:55 +0000487 auto *Fn = cast<FunctionDecl>(CurContext);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000488 SourceLocation Loc = Fn->getLocation();
489 // Build the initial suspend point
490 auto buildSuspends = [&](StringRef Name) mutable -> StmtResult {
491 ExprResult Suspend =
Eric Fiselierb936a392017-06-14 03:24:55 +0000492 buildPromiseCall(*this, ScopeInfo->CoroutinePromise, Loc, Name, None);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000493 if (Suspend.isInvalid())
494 return StmtError();
Eric Fiselierb936a392017-06-14 03:24:55 +0000495 Suspend = buildOperatorCoawaitCall(*this, SC, Loc, Suspend.get());
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000496 if (Suspend.isInvalid())
497 return StmtError();
Eric Fiselierb936a392017-06-14 03:24:55 +0000498 Suspend = BuildResolvedCoawaitExpr(Loc, Suspend.get(),
499 /*IsImplicit*/ true);
500 Suspend = ActOnFinishFullExpr(Suspend.get());
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000501 if (Suspend.isInvalid()) {
Eric Fiselierb936a392017-06-14 03:24:55 +0000502 Diag(Loc, diag::note_coroutine_promise_suspend_implicitly_required)
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000503 << ((Name == "initial_suspend") ? 0 : 1);
Eric Fiselierb936a392017-06-14 03:24:55 +0000504 Diag(KWLoc, diag::note_declared_coroutine_here) << Keyword;
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000505 return StmtError();
506 }
507 return cast<Stmt>(Suspend.get());
508 };
509
510 StmtResult InitSuspend = buildSuspends("initial_suspend");
511 if (InitSuspend.isInvalid())
512 return true;
513
514 StmtResult FinalSuspend = buildSuspends("final_suspend");
515 if (FinalSuspend.isInvalid())
516 return true;
517
518 ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());
519
520 return true;
521}
522
Richard Smith9f690bd2015-10-27 06:02:45 +0000523ExprResult Sema::ActOnCoawaitExpr(Scope *S, SourceLocation Loc, Expr *E) {
Eric Fiselierb936a392017-06-14 03:24:55 +0000524 if (!ActOnCoroutineBodyStart(S, Loc, "co_await")) {
Eric Fiseliera5465282016-09-29 21:47:39 +0000525 CorrectDelayedTyposInExpr(E);
526 return ExprError();
527 }
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000528
Richard Smith10610f72015-11-20 22:57:24 +0000529 if (E->getType()->isPlaceholderType()) {
530 ExprResult R = CheckPlaceholderExpr(E);
531 if (R.isInvalid()) return ExprError();
532 E = R.get();
533 }
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000534 ExprResult Lookup = buildOperatorCoawaitLookupExpr(*this, S, Loc);
535 if (Lookup.isInvalid())
536 return ExprError();
537 return BuildUnresolvedCoawaitExpr(Loc, E,
538 cast<UnresolvedLookupExpr>(Lookup.get()));
539}
Richard Smith10610f72015-11-20 22:57:24 +0000540
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000541ExprResult Sema::BuildUnresolvedCoawaitExpr(SourceLocation Loc, Expr *E,
Eric Fiseliercac0a592017-03-11 02:35:37 +0000542 UnresolvedLookupExpr *Lookup) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000543 auto *FSI = checkCoroutineContext(*this, Loc, "co_await");
544 if (!FSI)
545 return ExprError();
546
547 if (E->getType()->isPlaceholderType()) {
548 ExprResult R = CheckPlaceholderExpr(E);
549 if (R.isInvalid())
550 return ExprError();
551 E = R.get();
552 }
553
554 auto *Promise = FSI->CoroutinePromise;
555 if (Promise->getType()->isDependentType()) {
556 Expr *Res =
557 new (Context) DependentCoawaitExpr(Loc, Context.DependentTy, E, Lookup);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000558 return Res;
559 }
560
561 auto *RD = Promise->getType()->getAsCXXRecordDecl();
562 if (lookupMember(*this, "await_transform", RD, Loc)) {
563 ExprResult R = buildPromiseCall(*this, Promise, Loc, "await_transform", E);
564 if (R.isInvalid()) {
565 Diag(Loc,
566 diag::note_coroutine_promise_implicit_await_transform_required_here)
567 << E->getSourceRange();
568 return ExprError();
569 }
570 E = R.get();
571 }
572 ExprResult Awaitable = buildOperatorCoawaitCall(*this, Loc, E, Lookup);
Richard Smith9f690bd2015-10-27 06:02:45 +0000573 if (Awaitable.isInvalid())
574 return ExprError();
Eric Fiseliera5465282016-09-29 21:47:39 +0000575
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000576 return BuildResolvedCoawaitExpr(Loc, Awaitable.get());
Richard Smith9f690bd2015-10-27 06:02:45 +0000577}
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000578
579ExprResult Sema::BuildResolvedCoawaitExpr(SourceLocation Loc, Expr *E,
580 bool IsImplicit) {
Eric Fiseliercac0a592017-03-11 02:35:37 +0000581 auto *Coroutine = checkCoroutineContext(*this, Loc, "co_await", IsImplicit);
Richard Smith744b2242015-11-20 02:54:01 +0000582 if (!Coroutine)
583 return ExprError();
Richard Smith9f690bd2015-10-27 06:02:45 +0000584
Richard Smith9f690bd2015-10-27 06:02:45 +0000585 if (E->getType()->isPlaceholderType()) {
586 ExprResult R = CheckPlaceholderExpr(E);
587 if (R.isInvalid()) return ExprError();
588 E = R.get();
589 }
590
Richard Smith10610f72015-11-20 22:57:24 +0000591 if (E->getType()->isDependentType()) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000592 Expr *Res = new (Context)
593 CoawaitExpr(Loc, Context.DependentTy, E, IsImplicit);
Richard Smith10610f72015-11-20 22:57:24 +0000594 return Res;
595 }
596
Richard Smith1f38edd2015-11-22 03:13:02 +0000597 // If the expression is a temporary, materialize it as an lvalue so that we
598 // can use it multiple times.
599 if (E->getValueKind() == VK_RValue)
Tim Shen4a05bb82016-06-21 20:29:17 +0000600 E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
Richard Smith9f690bd2015-10-27 06:02:45 +0000601
602 // Build the await_ready, await_suspend, await_resume calls.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000603 ReadySuspendResumeResult RSS =
604 buildCoawaitCalls(*this, Coroutine->CoroutinePromise, Loc, E);
Richard Smith9f690bd2015-10-27 06:02:45 +0000605 if (RSS.IsInvalid)
606 return ExprError();
607
Gor Nishanovce43bd22017-03-11 01:30:17 +0000608 Expr *Res =
609 new (Context) CoawaitExpr(Loc, E, RSS.Results[0], RSS.Results[1],
610 RSS.Results[2], RSS.OpaqueValue, IsImplicit);
Eric Fiseliercac0a592017-03-11 02:35:37 +0000611
Richard Smithcfd53b42015-10-22 06:13:50 +0000612 return Res;
613}
614
Richard Smith9f690bd2015-10-27 06:02:45 +0000615ExprResult Sema::ActOnCoyieldExpr(Scope *S, SourceLocation Loc, Expr *E) {
Eric Fiselierb936a392017-06-14 03:24:55 +0000616 if (!ActOnCoroutineBodyStart(S, Loc, "co_yield")) {
Eric Fiseliera5465282016-09-29 21:47:39 +0000617 CorrectDelayedTyposInExpr(E);
Richard Smith23da82c2015-11-20 22:40:06 +0000618 return ExprError();
Eric Fiseliera5465282016-09-29 21:47:39 +0000619 }
Richard Smith23da82c2015-11-20 22:40:06 +0000620
621 // Build yield_value call.
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000622 ExprResult Awaitable = buildPromiseCall(
623 *this, getCurFunction()->CoroutinePromise, Loc, "yield_value", E);
Richard Smith9f690bd2015-10-27 06:02:45 +0000624 if (Awaitable.isInvalid())
625 return ExprError();
Richard Smith23da82c2015-11-20 22:40:06 +0000626
627 // Build 'operator co_await' call.
628 Awaitable = buildOperatorCoawaitCall(*this, S, Loc, Awaitable.get());
629 if (Awaitable.isInvalid())
630 return ExprError();
631
Richard Smith9f690bd2015-10-27 06:02:45 +0000632 return BuildCoyieldExpr(Loc, Awaitable.get());
633}
634ExprResult Sema::BuildCoyieldExpr(SourceLocation Loc, Expr *E) {
635 auto *Coroutine = checkCoroutineContext(*this, Loc, "co_yield");
Richard Smith744b2242015-11-20 02:54:01 +0000636 if (!Coroutine)
637 return ExprError();
Richard Smithcfd53b42015-10-22 06:13:50 +0000638
Richard Smith10610f72015-11-20 22:57:24 +0000639 if (E->getType()->isPlaceholderType()) {
640 ExprResult R = CheckPlaceholderExpr(E);
641 if (R.isInvalid()) return ExprError();
642 E = R.get();
643 }
644
Richard Smithd7bed4d2015-11-22 02:57:17 +0000645 if (E->getType()->isDependentType()) {
646 Expr *Res = new (Context) CoyieldExpr(Loc, Context.DependentTy, E);
Richard Smithd7bed4d2015-11-22 02:57:17 +0000647 return Res;
648 }
649
Richard Smith1f38edd2015-11-22 03:13:02 +0000650 // If the expression is a temporary, materialize it as an lvalue so that we
651 // can use it multiple times.
652 if (E->getValueKind() == VK_RValue)
Tim Shen4a05bb82016-06-21 20:29:17 +0000653 E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
Richard Smithd7bed4d2015-11-22 02:57:17 +0000654
655 // Build the await_ready, await_suspend, await_resume calls.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000656 ReadySuspendResumeResult RSS =
657 buildCoawaitCalls(*this, Coroutine->CoroutinePromise, Loc, E);
Richard Smithd7bed4d2015-11-22 02:57:17 +0000658 if (RSS.IsInvalid)
659 return ExprError();
660
Eric Fiselierb936a392017-06-14 03:24:55 +0000661 Expr *Res =
662 new (Context) CoyieldExpr(Loc, E, RSS.Results[0], RSS.Results[1],
663 RSS.Results[2], RSS.OpaqueValue);
Eric Fiseliercac0a592017-03-11 02:35:37 +0000664
Richard Smithcfd53b42015-10-22 06:13:50 +0000665 return Res;
666}
667
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000668StmtResult Sema::ActOnCoreturnStmt(Scope *S, SourceLocation Loc, Expr *E) {
Eric Fiselierb936a392017-06-14 03:24:55 +0000669 if (!ActOnCoroutineBodyStart(S, Loc, "co_return")) {
Eric Fiseliera5465282016-09-29 21:47:39 +0000670 CorrectDelayedTyposInExpr(E);
671 return StmtError();
672 }
Richard Smith9f690bd2015-10-27 06:02:45 +0000673 return BuildCoreturnStmt(Loc, E);
674}
Gor Nishanov3e048bb2016-10-04 00:31:16 +0000675
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000676StmtResult Sema::BuildCoreturnStmt(SourceLocation Loc, Expr *E,
677 bool IsImplicit) {
Eric Fiseliercac0a592017-03-11 02:35:37 +0000678 auto *FSI = checkCoroutineContext(*this, Loc, "co_return", IsImplicit);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000679 if (!FSI)
Richard Smith71d403e2015-11-22 07:33:28 +0000680 return StmtError();
681
682 if (E && E->getType()->isPlaceholderType() &&
683 !E->getType()->isSpecificPlaceholderType(BuiltinType::Overload)) {
Richard Smith10610f72015-11-20 22:57:24 +0000684 ExprResult R = CheckPlaceholderExpr(E);
685 if (R.isInvalid()) return StmtError();
686 E = R.get();
687 }
688
Richard Smith4ba66602015-11-22 07:05:16 +0000689 // FIXME: If the operand is a reference to a variable that's about to go out
Richard Smith2af65c42015-11-24 02:34:39 +0000690 // of scope, we should treat the operand as an xvalue for this overload
Richard Smith4ba66602015-11-22 07:05:16 +0000691 // resolution.
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000692 VarDecl *Promise = FSI->CoroutinePromise;
Richard Smith4ba66602015-11-22 07:05:16 +0000693 ExprResult PC;
Eric Fiselier98131312016-10-06 21:23:38 +0000694 if (E && (isa<InitListExpr>(E) || !E->getType()->isVoidType())) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000695 PC = buildPromiseCall(*this, Promise, Loc, "return_value", E);
Richard Smith4ba66602015-11-22 07:05:16 +0000696 } else {
697 E = MakeFullDiscardedValueExpr(E).get();
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000698 PC = buildPromiseCall(*this, Promise, Loc, "return_void", None);
Richard Smith4ba66602015-11-22 07:05:16 +0000699 }
700 if (PC.isInvalid())
701 return StmtError();
702
703 Expr *PCE = ActOnFinishFullExpr(PC.get()).get();
704
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000705 Stmt *Res = new (Context) CoreturnStmt(Loc, E, PCE, IsImplicit);
Richard Smithcfd53b42015-10-22 06:13:50 +0000706 return Res;
707}
708
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000709/// Look up the std::nothrow object.
710static Expr *buildStdNoThrowDeclRef(Sema &S, SourceLocation Loc) {
711 NamespaceDecl *Std = S.getStdNamespace();
712 assert(Std && "Should already be diagnosed");
713
714 LookupResult Result(S, &S.PP.getIdentifierTable().get("nothrow"), Loc,
715 Sema::LookupOrdinaryName);
716 if (!S.LookupQualifiedName(Result, Std)) {
717 // FIXME: <experimental/coroutine> should have been included already.
718 // If we require it to include <new> then this diagnostic is no longer
719 // needed.
720 S.Diag(Loc, diag::err_implicit_coroutine_std_nothrow_type_not_found);
721 return nullptr;
722 }
723
724 // FIXME: Mark the variable as ODR used. This currently does not work
725 // likely due to the scope at in which this function is called.
726 auto *VD = Result.getAsSingle<VarDecl>();
727 if (!VD) {
728 Result.suppressDiagnostics();
729 // We found something weird. Complain about the first thing we found.
730 NamedDecl *Found = *Result.begin();
731 S.Diag(Found->getLocation(), diag::err_malformed_std_nothrow);
732 return nullptr;
733 }
734
735 ExprResult DR = S.BuildDeclRefExpr(VD, VD->getType(), VK_LValue, Loc);
736 if (DR.isInvalid())
737 return nullptr;
738
739 return DR.get();
740}
741
Gor Nishanov8df64e92016-10-27 16:28:31 +0000742// Find an appropriate delete for the promise.
743static FunctionDecl *findDeleteForPromise(Sema &S, SourceLocation Loc,
744 QualType PromiseType) {
745 FunctionDecl *OperatorDelete = nullptr;
746
747 DeclarationName DeleteName =
748 S.Context.DeclarationNames.getCXXOperatorName(OO_Delete);
749
750 auto *PointeeRD = PromiseType->getAsCXXRecordDecl();
751 assert(PointeeRD && "PromiseType must be a CxxRecordDecl type");
752
753 if (S.FindDeallocationFunction(Loc, PointeeRD, DeleteName, OperatorDelete))
754 return nullptr;
755
756 if (!OperatorDelete) {
757 // Look for a global declaration.
758 const bool CanProvideSize = S.isCompleteType(Loc, PromiseType);
759 const bool Overaligned = false;
760 OperatorDelete = S.FindUsualDeallocationFunction(Loc, CanProvideSize,
761 Overaligned, DeleteName);
762 }
763 S.MarkFunctionReferenced(Loc, OperatorDelete);
764 return OperatorDelete;
765}
766
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000767
768void Sema::CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body) {
769 FunctionScopeInfo *Fn = getCurFunction();
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000770 assert(Fn && Fn->isCoroutine() && "not a coroutine");
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000771 if (!Body) {
772 assert(FD->isInvalidDecl() &&
773 "a null body is only allowed for invalid declarations");
774 return;
775 }
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000776 // We have a function that uses coroutine keywords, but we failed to build
777 // the promise type.
778 if (!Fn->CoroutinePromise)
779 return FD->setInvalidDecl();
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000780
781 if (isa<CoroutineBodyStmt>(Body)) {
Gor Nishanov29ff6382017-05-24 14:34:19 +0000782 // Nothing todo. the body is already a transformed coroutine body statement.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000783 return;
784 }
785
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000786 // Coroutines [stmt.return]p1:
787 // A return statement shall not appear in a coroutine.
788 if (Fn->FirstReturnLoc.isValid()) {
Eric Fiseliercac0a592017-03-11 02:35:37 +0000789 assert(Fn->FirstCoroutineStmtLoc.isValid() &&
790 "first coroutine location not set");
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000791 Diag(Fn->FirstReturnLoc, diag::err_return_in_coroutine);
Eric Fiseliercac0a592017-03-11 02:35:37 +0000792 Diag(Fn->FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
793 << Fn->getFirstCoroutineStmtKeyword();
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000794 }
Eric Fiselierbee782b2017-04-03 19:21:00 +0000795 CoroutineStmtBuilder Builder(*this, *FD, *Fn, Body);
796 if (Builder.isInvalid() || !Builder.buildStatements())
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000797 return FD->setInvalidDecl();
798
799 // Build body for the coroutine wrapper statement.
800 Body = CoroutineBodyStmt::Create(Context, Builder);
801}
802
Eric Fiselierbee782b2017-04-03 19:21:00 +0000803CoroutineStmtBuilder::CoroutineStmtBuilder(Sema &S, FunctionDecl &FD,
804 sema::FunctionScopeInfo &Fn,
805 Stmt *Body)
806 : S(S), FD(FD), Fn(Fn), Loc(FD.getLocation()),
807 IsPromiseDependentType(
808 !Fn.CoroutinePromise ||
809 Fn.CoroutinePromise->getType()->isDependentType()) {
810 this->Body = Body;
811 if (!IsPromiseDependentType) {
812 PromiseRecordDecl = Fn.CoroutinePromise->getType()->getAsCXXRecordDecl();
813 assert(PromiseRecordDecl && "Type should have already been checked");
814 }
815 this->IsValid = makePromiseStmt() && makeInitialAndFinalSuspend();
816}
817
818bool CoroutineStmtBuilder::buildStatements() {
819 assert(this->IsValid && "coroutine already invalid");
820 this->IsValid = makeReturnObject() && makeParamMoves();
821 if (this->IsValid && !IsPromiseDependentType)
822 buildDependentStatements();
823 return this->IsValid;
824}
825
826bool CoroutineStmtBuilder::buildDependentStatements() {
827 assert(this->IsValid && "coroutine already invalid");
828 assert(!this->IsPromiseDependentType &&
829 "coroutine cannot have a dependent promise type");
830 this->IsValid = makeOnException() && makeOnFallthrough() &&
Gor Nishanov6a470682017-05-22 20:22:23 +0000831 makeGroDeclAndReturnStmt() && makeReturnOnAllocFailure() &&
832 makeNewAndDeleteExpr();
Eric Fiselierbee782b2017-04-03 19:21:00 +0000833 return this->IsValid;
834}
835
Eric Fiselierde7943b2017-06-03 00:22:18 +0000836bool CoroutineStmtBuilder::buildParameterMoves() {
837 assert(this->IsValid && "coroutine already invalid");
838 assert(this->ParamMoves.empty() && "param moves already built");
839 return this->IsValid = makeParamMoves();
840}
841
Eric Fiselierbee782b2017-04-03 19:21:00 +0000842bool CoroutineStmtBuilder::makePromiseStmt() {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000843 // Form a declaration statement for the promise declaration, so that AST
844 // visitors can more easily find it.
845 StmtResult PromiseStmt =
846 S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(Fn.CoroutinePromise), Loc, Loc);
847 if (PromiseStmt.isInvalid())
848 return false;
849
850 this->Promise = PromiseStmt.get();
851 return true;
852}
853
Eric Fiselierbee782b2017-04-03 19:21:00 +0000854bool CoroutineStmtBuilder::makeInitialAndFinalSuspend() {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000855 if (Fn.hasInvalidCoroutineSuspends())
856 return false;
857 this->InitialSuspend = cast<Expr>(Fn.CoroutineSuspends.first);
858 this->FinalSuspend = cast<Expr>(Fn.CoroutineSuspends.second);
859 return true;
860}
861
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000862static bool diagReturnOnAllocFailure(Sema &S, Expr *E,
863 CXXRecordDecl *PromiseRecordDecl,
864 FunctionScopeInfo &Fn) {
865 auto Loc = E->getExprLoc();
866 if (auto *DeclRef = dyn_cast_or_null<DeclRefExpr>(E)) {
867 auto *Decl = DeclRef->getDecl();
868 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Decl)) {
869 if (Method->isStatic())
870 return true;
871 else
872 Loc = Decl->getLocation();
873 }
874 }
875
876 S.Diag(
877 Loc,
878 diag::err_coroutine_promise_get_return_object_on_allocation_failure)
879 << PromiseRecordDecl;
880 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
881 << Fn.getFirstCoroutineStmtKeyword();
882 return false;
883}
884
Eric Fiselierbee782b2017-04-03 19:21:00 +0000885bool CoroutineStmtBuilder::makeReturnOnAllocFailure() {
886 assert(!IsPromiseDependentType &&
887 "cannot make statement while the promise type is dependent");
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000888
889 // [dcl.fct.def.coroutine]/8
890 // The unqualified-id get_return_object_on_allocation_failure is looked up in
891 // the scope of class P by class member access lookup (3.4.5). ...
892 // If an allocation function returns nullptr, ... the coroutine return value
893 // is obtained by a call to ... get_return_object_on_allocation_failure().
894
895 DeclarationName DN =
896 S.PP.getIdentifierInfo("get_return_object_on_allocation_failure");
897 LookupResult Found(S, DN, Loc, Sema::LookupMemberName);
Eric Fiselierbee782b2017-04-03 19:21:00 +0000898 if (!S.LookupQualifiedName(Found, PromiseRecordDecl))
899 return true;
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000900
901 CXXScopeSpec SS;
902 ExprResult DeclNameExpr =
903 S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
Eric Fiselierbee782b2017-04-03 19:21:00 +0000904 if (DeclNameExpr.isInvalid())
905 return false;
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000906
907 if (!diagReturnOnAllocFailure(S, DeclNameExpr.get(), PromiseRecordDecl, Fn))
908 return false;
909
910 ExprResult ReturnObjectOnAllocationFailure =
911 S.ActOnCallExpr(nullptr, DeclNameExpr.get(), Loc, {}, Loc);
Eric Fiselierbee782b2017-04-03 19:21:00 +0000912 if (ReturnObjectOnAllocationFailure.isInvalid())
913 return false;
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000914
Gor Nishanovc4a19082017-03-28 02:51:45 +0000915 StmtResult ReturnStmt =
916 S.BuildReturnStmt(Loc, ReturnObjectOnAllocationFailure.get());
Gor Nishanov6a470682017-05-22 20:22:23 +0000917 if (ReturnStmt.isInvalid()) {
Eric Fiselierfc50f622017-05-25 14:59:39 +0000918 S.Diag(Found.getFoundDecl()->getLocation(), diag::note_member_declared_here)
919 << DN;
Gor Nishanov6a470682017-05-22 20:22:23 +0000920 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
921 << Fn.getFirstCoroutineStmtKeyword();
Eric Fiselierbee782b2017-04-03 19:21:00 +0000922 return false;
Gor Nishanov6a470682017-05-22 20:22:23 +0000923 }
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000924
925 this->ReturnStmtOnAllocFailure = ReturnStmt.get();
926 return true;
927}
928
Eric Fiselierbee782b2017-04-03 19:21:00 +0000929bool CoroutineStmtBuilder::makeNewAndDeleteExpr() {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000930 // Form and check allocation and deallocation calls.
Eric Fiselierbee782b2017-04-03 19:21:00 +0000931 assert(!IsPromiseDependentType &&
932 "cannot make statement while the promise type is dependent");
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000933 QualType PromiseType = Fn.CoroutinePromise->getType();
Gor Nishanov8df64e92016-10-27 16:28:31 +0000934
935 if (S.RequireCompleteType(Loc, PromiseType, diag::err_incomplete_type))
936 return false;
937
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000938 const bool RequiresNoThrowAlloc = ReturnStmtOnAllocFailure != nullptr;
939
Gor Nishanov8df64e92016-10-27 16:28:31 +0000940 // FIXME: Add support for stateful allocators.
941
942 FunctionDecl *OperatorNew = nullptr;
943 FunctionDecl *OperatorDelete = nullptr;
944 FunctionDecl *UnusedResult = nullptr;
945 bool PassAlignment = false;
Eric Fiselierf747f532017-04-18 05:08:08 +0000946 SmallVector<Expr *, 1> PlacementArgs;
Gor Nishanov8df64e92016-10-27 16:28:31 +0000947
948 S.FindAllocationFunctions(Loc, SourceRange(),
949 /*UseGlobal*/ false, PromiseType,
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000950 /*isArray*/ false, PassAlignment, PlacementArgs,
951 OperatorNew, UnusedResult);
Gor Nishanov8df64e92016-10-27 16:28:31 +0000952
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000953 bool IsGlobalOverload =
954 OperatorNew && !isa<CXXRecordDecl>(OperatorNew->getDeclContext());
955 // If we didn't find a class-local new declaration and non-throwing new
956 // was is required then we need to lookup the non-throwing global operator
957 // instead.
958 if (RequiresNoThrowAlloc && (!OperatorNew || IsGlobalOverload)) {
959 auto *StdNoThrow = buildStdNoThrowDeclRef(S, Loc);
960 if (!StdNoThrow)
961 return false;
Eric Fiselierf747f532017-04-18 05:08:08 +0000962 PlacementArgs = {StdNoThrow};
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000963 OperatorNew = nullptr;
964 S.FindAllocationFunctions(Loc, SourceRange(),
965 /*UseGlobal*/ true, PromiseType,
966 /*isArray*/ false, PassAlignment, PlacementArgs,
967 OperatorNew, UnusedResult);
968 }
Gor Nishanov8df64e92016-10-27 16:28:31 +0000969
Eric Fiselierc5128752017-04-18 05:30:39 +0000970 assert(OperatorNew && "expected definition of operator new to be found");
971
972 if (RequiresNoThrowAlloc) {
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000973 const auto *FT = OperatorNew->getType()->getAs<FunctionProtoType>();
974 if (!FT->isNothrow(S.Context, /*ResultIfDependent*/ false)) {
975 S.Diag(OperatorNew->getLocation(),
976 diag::err_coroutine_promise_new_requires_nothrow)
977 << OperatorNew;
978 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
979 << OperatorNew;
980 return false;
981 }
982 }
983
984 if ((OperatorDelete = findDeleteForPromise(S, Loc, PromiseType)) == nullptr)
Gor Nishanov8df64e92016-10-27 16:28:31 +0000985 return false;
986
987 Expr *FramePtr =
988 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_frame, {});
989
990 Expr *FrameSize =
991 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_size, {});
992
993 // Make new call.
994
995 ExprResult NewRef =
996 S.BuildDeclRefExpr(OperatorNew, OperatorNew->getType(), VK_LValue, Loc);
997 if (NewRef.isInvalid())
998 return false;
999
Eric Fiselierf747f532017-04-18 05:08:08 +00001000 SmallVector<Expr *, 2> NewArgs(1, FrameSize);
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001001 for (auto Arg : PlacementArgs)
1002 NewArgs.push_back(Arg);
1003
Gor Nishanov8df64e92016-10-27 16:28:31 +00001004 ExprResult NewExpr =
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001005 S.ActOnCallExpr(S.getCurScope(), NewRef.get(), Loc, NewArgs, Loc);
1006 NewExpr = S.ActOnFinishFullExpr(NewExpr.get());
Gor Nishanov8df64e92016-10-27 16:28:31 +00001007 if (NewExpr.isInvalid())
1008 return false;
1009
Gor Nishanov8df64e92016-10-27 16:28:31 +00001010 // Make delete call.
1011
1012 QualType OpDeleteQualType = OperatorDelete->getType();
1013
1014 ExprResult DeleteRef =
1015 S.BuildDeclRefExpr(OperatorDelete, OpDeleteQualType, VK_LValue, Loc);
1016 if (DeleteRef.isInvalid())
1017 return false;
1018
1019 Expr *CoroFree =
1020 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_free, {FramePtr});
1021
1022 SmallVector<Expr *, 2> DeleteArgs{CoroFree};
1023
1024 // Check if we need to pass the size.
1025 const auto *OpDeleteType =
1026 OpDeleteQualType.getTypePtr()->getAs<FunctionProtoType>();
1027 if (OpDeleteType->getNumParams() > 1)
1028 DeleteArgs.push_back(FrameSize);
1029
1030 ExprResult DeleteExpr =
1031 S.ActOnCallExpr(S.getCurScope(), DeleteRef.get(), Loc, DeleteArgs, Loc);
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001032 DeleteExpr = S.ActOnFinishFullExpr(DeleteExpr.get());
Gor Nishanov8df64e92016-10-27 16:28:31 +00001033 if (DeleteExpr.isInvalid())
1034 return false;
1035
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001036 this->Allocate = NewExpr.get();
1037 this->Deallocate = DeleteExpr.get();
Gor Nishanov8df64e92016-10-27 16:28:31 +00001038
1039 return true;
1040}
1041
Eric Fiselierbee782b2017-04-03 19:21:00 +00001042bool CoroutineStmtBuilder::makeOnFallthrough() {
1043 assert(!IsPromiseDependentType &&
1044 "cannot make statement while the promise type is dependent");
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001045
1046 // [dcl.fct.def.coroutine]/4
1047 // The unqualified-ids 'return_void' and 'return_value' are looked up in
1048 // the scope of class P. If both are found, the program is ill-formed.
Eric Fiselierfc50f622017-05-25 14:59:39 +00001049 bool HasRVoid, HasRValue;
1050 LookupResult LRVoid =
1051 lookupMember(S, "return_void", PromiseRecordDecl, Loc, HasRVoid);
1052 LookupResult LRValue =
1053 lookupMember(S, "return_value", PromiseRecordDecl, Loc, HasRValue);
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001054
Eric Fiselier709d1b32016-10-27 07:30:31 +00001055 StmtResult Fallthrough;
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001056 if (HasRVoid && HasRValue) {
1057 // FIXME Improve this diagnostic
Eric Fiselierfc50f622017-05-25 14:59:39 +00001058 S.Diag(FD.getLocation(),
1059 diag::err_coroutine_promise_incompatible_return_functions)
1060 << PromiseRecordDecl;
1061 S.Diag(LRVoid.getRepresentativeDecl()->getLocation(),
1062 diag::note_member_first_declared_here)
1063 << LRVoid.getLookupName();
1064 S.Diag(LRValue.getRepresentativeDecl()->getLocation(),
1065 diag::note_member_first_declared_here)
1066 << LRValue.getLookupName();
1067 return false;
1068 } else if (!HasRVoid && !HasRValue) {
1069 // FIXME: The PDTS currently specifies this case as UB, not ill-formed.
1070 // However we still diagnose this as an error since until the PDTS is fixed.
1071 S.Diag(FD.getLocation(),
1072 diag::err_coroutine_promise_requires_return_function)
1073 << PromiseRecordDecl;
1074 S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here)
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001075 << PromiseRecordDecl;
1076 return false;
1077 } else if (HasRVoid) {
1078 // If the unqualified-id return_void is found, flowing off the end of a
1079 // coroutine is equivalent to a co_return with no operand. Otherwise,
1080 // flowing off the end of a coroutine results in undefined behavior.
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001081 Fallthrough = S.BuildCoreturnStmt(FD.getLocation(), nullptr,
1082 /*IsImplicit*/false);
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001083 Fallthrough = S.ActOnFinishFullStmt(Fallthrough.get());
1084 if (Fallthrough.isInvalid())
1085 return false;
Eric Fiselier709d1b32016-10-27 07:30:31 +00001086 }
Richard Smith2af65c42015-11-24 02:34:39 +00001087
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001088 this->OnFallthrough = Fallthrough.get();
1089 return true;
1090}
1091
Eric Fiselierbee782b2017-04-03 19:21:00 +00001092bool CoroutineStmtBuilder::makeOnException() {
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001093 // Try to form 'p.unhandled_exception();'
Eric Fiselierbee782b2017-04-03 19:21:00 +00001094 assert(!IsPromiseDependentType &&
1095 "cannot make statement while the promise type is dependent");
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001096
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001097 const bool RequireUnhandledException = S.getLangOpts().CXXExceptions;
1098
1099 if (!lookupMember(S, "unhandled_exception", PromiseRecordDecl, Loc)) {
1100 auto DiagID =
1101 RequireUnhandledException
1102 ? diag::err_coroutine_promise_unhandled_exception_required
1103 : diag::
1104 warn_coroutine_promise_unhandled_exception_required_with_exceptions;
1105 S.Diag(Loc, DiagID) << PromiseRecordDecl;
Gor Nishanov29ff6382017-05-24 14:34:19 +00001106 S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here)
1107 << PromiseRecordDecl;
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001108 return !RequireUnhandledException;
1109 }
1110
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001111 // If exceptions are disabled, don't try to build OnException.
1112 if (!S.getLangOpts().CXXExceptions)
1113 return true;
1114
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001115 ExprResult UnhandledException = buildPromiseCall(S, Fn.CoroutinePromise, Loc,
1116 "unhandled_exception", None);
1117 UnhandledException = S.ActOnFinishFullExpr(UnhandledException.get(), Loc);
1118 if (UnhandledException.isInvalid())
1119 return false;
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001120
Gor Nishanov5b050e42017-05-22 22:33:17 +00001121 // Since the body of the coroutine will be wrapped in try-catch, it will
1122 // be incompatible with SEH __try if present in a function.
1123 if (!S.getLangOpts().Borland && Fn.FirstSEHTryLoc.isValid()) {
1124 S.Diag(Fn.FirstSEHTryLoc, diag::err_seh_in_a_coroutine_with_cxx_exceptions);
1125 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1126 << Fn.getFirstCoroutineStmtKeyword();
1127 return false;
1128 }
1129
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001130 this->OnException = UnhandledException.get();
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001131 return true;
1132}
1133
Eric Fiselierbee782b2017-04-03 19:21:00 +00001134bool CoroutineStmtBuilder::makeReturnObject() {
Richard Smith2af65c42015-11-24 02:34:39 +00001135 // Build implicit 'p.get_return_object()' expression and form initialization
1136 // of return type from it.
1137 ExprResult ReturnObject =
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001138 buildPromiseCall(S, Fn.CoroutinePromise, Loc, "get_return_object", None);
Richard Smith2af65c42015-11-24 02:34:39 +00001139 if (ReturnObject.isInvalid())
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001140 return false;
Richard Smith2af65c42015-11-24 02:34:39 +00001141
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001142 this->ReturnValue = ReturnObject.get();
1143 return true;
1144}
1145
Gor Nishanov6a470682017-05-22 20:22:23 +00001146static void noteMemberDeclaredHere(Sema &S, Expr *E, FunctionScopeInfo &Fn) {
1147 if (auto *MbrRef = dyn_cast<CXXMemberCallExpr>(E)) {
1148 auto *MethodDecl = MbrRef->getMethodDecl();
Eric Fiselierfc50f622017-05-25 14:59:39 +00001149 S.Diag(MethodDecl->getLocation(), diag::note_member_declared_here)
1150 << MethodDecl;
Gor Nishanov6a470682017-05-22 20:22:23 +00001151 }
1152 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1153 << Fn.getFirstCoroutineStmtKeyword();
1154}
1155
1156bool CoroutineStmtBuilder::makeGroDeclAndReturnStmt() {
1157 assert(!IsPromiseDependentType &&
1158 "cannot make statement while the promise type is dependent");
1159 assert(this->ReturnValue && "ReturnValue must be already formed");
1160
1161 QualType const GroType = this->ReturnValue->getType();
1162 assert(!GroType->isDependentType() &&
1163 "get_return_object type must no longer be dependent");
1164
1165 QualType const FnRetType = FD.getReturnType();
1166 assert(!FnRetType->isDependentType() &&
1167 "get_return_object type must no longer be dependent");
1168
1169 if (FnRetType->isVoidType()) {
1170 ExprResult Res = S.ActOnFinishFullExpr(this->ReturnValue, Loc);
1171 if (Res.isInvalid())
1172 return false;
1173
1174 this->ResultDecl = Res.get();
1175 return true;
1176 }
1177
1178 if (GroType->isVoidType()) {
1179 // Trigger a nice error message.
1180 InitializedEntity Entity =
1181 InitializedEntity::InitializeResult(Loc, FnRetType, false);
1182 S.PerformMoveOrCopyInitialization(Entity, nullptr, FnRetType, ReturnValue);
1183 noteMemberDeclaredHere(S, ReturnValue, Fn);
1184 return false;
1185 }
1186
1187 auto *GroDecl = VarDecl::Create(
1188 S.Context, &FD, FD.getLocation(), FD.getLocation(),
1189 &S.PP.getIdentifierTable().get("__coro_gro"), GroType,
1190 S.Context.getTrivialTypeSourceInfo(GroType, Loc), SC_None);
1191
1192 S.CheckVariableDeclarationType(GroDecl);
1193 if (GroDecl->isInvalidDecl())
1194 return false;
1195
1196 InitializedEntity Entity = InitializedEntity::InitializeVariable(GroDecl);
1197 ExprResult Res = S.PerformMoveOrCopyInitialization(Entity, nullptr, GroType,
1198 this->ReturnValue);
1199 if (Res.isInvalid())
1200 return false;
1201
1202 Res = S.ActOnFinishFullExpr(Res.get());
1203 if (Res.isInvalid())
1204 return false;
1205
1206 if (GroType == FnRetType) {
1207 GroDecl->setNRVOVariable(true);
1208 }
1209
1210 S.AddInitializerToDecl(GroDecl, Res.get(),
1211 /*DirectInit=*/false);
1212
1213 S.FinalizeDeclaration(GroDecl);
1214
1215 // Form a declaration statement for the return declaration, so that AST
1216 // visitors can more easily find it.
1217 StmtResult GroDeclStmt =
1218 S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(GroDecl), Loc, Loc);
1219 if (GroDeclStmt.isInvalid())
1220 return false;
1221
1222 this->ResultDecl = GroDeclStmt.get();
1223
1224 ExprResult declRef = S.BuildDeclRefExpr(GroDecl, GroType, VK_LValue, Loc);
1225 if (declRef.isInvalid())
1226 return false;
1227
1228 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, declRef.get());
1229 if (ReturnStmt.isInvalid()) {
1230 noteMemberDeclaredHere(S, ReturnValue, Fn);
1231 return false;
1232 }
1233
1234 this->ReturnStmt = ReturnStmt.get();
1235 return true;
1236}
1237
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001238// Create a static_cast\<T&&>(expr).
1239static Expr *castForMoving(Sema &S, Expr *E, QualType T = QualType()) {
1240 if (T.isNull())
1241 T = E->getType();
1242 QualType TargetType = S.BuildReferenceType(
1243 T, /*SpelledAsLValue*/ false, SourceLocation(), DeclarationName());
1244 SourceLocation ExprLoc = E->getLocStart();
1245 TypeSourceInfo *TargetLoc =
1246 S.Context.getTrivialTypeSourceInfo(TargetType, ExprLoc);
1247
1248 return S
1249 .BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
1250 SourceRange(ExprLoc, ExprLoc), E->getSourceRange())
1251 .get();
1252}
1253
Eric Fiselierde7943b2017-06-03 00:22:18 +00001254
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001255/// \brief Build a variable declaration for move parameter.
1256static VarDecl *buildVarDecl(Sema &S, SourceLocation Loc, QualType Type,
Eric Fiselierde7943b2017-06-03 00:22:18 +00001257 IdentifierInfo *II) {
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001258 TypeSourceInfo *TInfo = S.Context.getTrivialTypeSourceInfo(Type, Loc);
1259 VarDecl *Decl =
Eric Fiselierde7943b2017-06-03 00:22:18 +00001260 VarDecl::Create(S.Context, S.CurContext, Loc, Loc, II, Type, TInfo, SC_None);
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001261 Decl->setImplicit();
1262 return Decl;
1263}
1264
Eric Fiselierbee782b2017-04-03 19:21:00 +00001265bool CoroutineStmtBuilder::makeParamMoves() {
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001266 for (auto *paramDecl : FD.parameters()) {
1267 auto Ty = paramDecl->getType();
1268 if (Ty->isDependentType())
1269 continue;
1270
1271 // No need to copy scalars, llvm will take care of them.
1272 if (Ty->getAsCXXRecordDecl()) {
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001273 ExprResult ParamRef =
1274 S.BuildDeclRefExpr(paramDecl, paramDecl->getType(),
1275 ExprValueKind::VK_LValue, Loc); // FIXME: scope?
1276 if (ParamRef.isInvalid())
1277 return false;
1278
1279 Expr *RCast = castForMoving(S, ParamRef.get());
1280
Eric Fiselierde7943b2017-06-03 00:22:18 +00001281 auto D = buildVarDecl(S, Loc, Ty, paramDecl->getIdentifier());
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001282 S.AddInitializerToDecl(D, RCast, /*DirectInit=*/true);
1283
1284 // Convert decl to a statement.
1285 StmtResult Stmt = S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(D), Loc, Loc);
1286 if (Stmt.isInvalid())
1287 return false;
1288
1289 ParamMovesVector.push_back(Stmt.get());
1290 }
1291 }
1292
1293 // Convert to ArrayRef in CtorArgs structure that builder inherits from.
1294 ParamMoves = ParamMovesVector;
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001295 return true;
Richard Smithcfd53b42015-10-22 06:13:50 +00001296}
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001297
1298StmtResult Sema::BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
1299 CoroutineBodyStmt *Res = CoroutineBodyStmt::Create(Context, Args);
1300 if (!Res)
1301 return StmtError();
1302 return Res;
1303}