1 //===--- SemaCoroutines.cpp - Semantic Analysis for Coroutines ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements semantic analysis for C++ Coroutines.
12 //===----------------------------------------------------------------------===//
14 #include "CoroutineStmtBuilder.h"
15 #include "clang/AST/Decl.h"
16 #include "clang/AST/ExprCXX.h"
17 #include "clang/AST/StmtCXX.h"
18 #include "clang/Lex/Preprocessor.h"
19 #include "clang/Sema/Initialization.h"
20 #include "clang/Sema/Overload.h"
21 #include "clang/Sema/SemaInternal.h"
23 using namespace clang;
26 static LookupResult lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD,
27 SourceLocation Loc, bool &Res) {
28 DeclarationName DN = S.PP.getIdentifierInfo(Name);
29 LookupResult LR(S, DN, Loc, Sema::LookupMemberName);
30 // Suppress diagnostics when a private member is selected. The same warnings
31 // will be produced again when building the call.
32 LR.suppressDiagnostics();
33 Res = S.LookupQualifiedName(LR, RD);
37 static bool lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD,
40 lookupMember(S, Name, RD, Loc, Res);
44 /// Look up the std::coroutine_traits<...>::promise_type for the given
46 static QualType lookupPromiseType(Sema &S, const FunctionDecl *FD,
47 SourceLocation KwLoc) {
48 const FunctionProtoType *FnType = FD->getType()->castAs<FunctionProtoType>();
49 const SourceLocation FuncLoc = FD->getLocation();
50 // FIXME: Cache std::coroutine_traits once we've found it.
51 NamespaceDecl *StdExp = S.lookupStdExperimentalNamespace();
53 S.Diag(KwLoc, diag::err_implied_coroutine_type_not_found)
54 << "std::experimental::coroutine_traits";
58 LookupResult Result(S, &S.PP.getIdentifierTable().get("coroutine_traits"),
59 FuncLoc, Sema::LookupOrdinaryName);
60 if (!S.LookupQualifiedName(Result, StdExp)) {
61 S.Diag(KwLoc, diag::err_implied_coroutine_type_not_found)
62 << "std::experimental::coroutine_traits";
66 ClassTemplateDecl *CoroTraits = Result.getAsSingle<ClassTemplateDecl>();
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);
75 // Form template argument list for coroutine_traits<R, P1, P2, ...> according
76 // to [dcl.fct.def.coroutine]3
77 TemplateArgumentListInfo Args(KwLoc, KwLoc);
78 auto AddArg = [&](QualType T) {
79 Args.addArgument(TemplateArgumentLoc(
80 TemplateArgument(T), S.Context.getTrivialTypeSourceInfo(T, KwLoc)));
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
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 &&
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);
102 for (QualType T : FnType->getParamTypes())
105 // Build the template-id.
107 S.CheckTemplateIdType(TemplateName(CoroTraits), KwLoc, Args);
108 if (CoroTrait.isNull())
110 if (S.RequireCompleteType(KwLoc, CoroTrait,
111 diag::err_coroutine_type_missing_specialization))
114 auto *RD = CoroTrait->getAsCXXRecordDecl();
115 assert(RD && "specialization of class template is not a class?");
117 // Look up the ::promise_type member.
118 LookupResult R(S, &S.PP.getIdentifierTable().get("promise_type"), KwLoc,
119 Sema::LookupOrdinaryName);
120 S.LookupQualifiedName(R, RD);
121 auto *Promise = R.getAsSingle<TypeDecl>();
124 diag::err_implied_std_coroutine_traits_promise_type_not_found)
128 // The promise type is required to be a class type.
129 QualType PromiseType = S.Context.getTypeDeclType(Promise);
131 auto buildElaboratedType = [&]() {
132 auto *NNS = NestedNameSpecifier::Create(S.Context, nullptr, StdExp);
133 NNS = NestedNameSpecifier::Create(S.Context, NNS, false,
134 CoroTrait.getTypePtr());
135 return S.Context.getElaboratedType(ETK_None, NNS, PromiseType);
138 if (!PromiseType->getAsCXXRecordDecl()) {
140 diag::err_implied_std_coroutine_traits_promise_type_not_class)
141 << buildElaboratedType();
144 if (S.RequireCompleteType(FuncLoc, buildElaboratedType(),
145 diag::err_coroutine_promise_type_incomplete))
151 /// Look up the std::experimental::coroutine_handle<PromiseType>.
152 static QualType lookupCoroutineHandleType(Sema &S, QualType PromiseType,
153 SourceLocation Loc) {
154 if (PromiseType.isNull())
157 NamespaceDecl *StdExp = S.lookupStdExperimentalNamespace();
158 assert(StdExp && "Should already be diagnosed");
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";
168 ClassTemplateDecl *CoroHandle = Result.getAsSingle<ClassTemplateDecl>();
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);
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)));
183 // Build the template-id.
184 QualType CoroHandleType =
185 S.CheckTemplateIdType(TemplateName(CoroHandle), Loc, Args);
186 if (CoroHandleType.isNull())
188 if (S.RequireCompleteType(Loc, CoroHandleType,
189 diag::err_coroutine_type_missing_specialization))
192 return CoroHandleType;
195 static bool isValidCoroutineContext(Sema &S, SourceLocation Loc,
197 // '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;
203 // Any other usage must be within a function.
204 auto *FD = dyn_cast<FunctionDecl>(S.CurContext);
206 S.Diag(Loc, isa<ObjCMethodDecl>(S.CurContext)
207 ? diag::err_coroutine_objc_method
208 : diag::err_coroutine_outside_function) << Keyword;
212 // An enumeration for mapping the diagnostic type to the correct diagnostic
214 enum InvalidFuncDiag {
224 bool Diagnosed = false;
225 auto DiagInvalid = [&](InvalidFuncDiag ID) {
226 S.Diag(Loc, diag::err_coroutine_invalid_func_context) << ID << Keyword;
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);
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);
256 static 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);
264 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
265 const auto &Functions = Operators.asUnresolvedSet();
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());
277 /// Build a call to 'operator co_await' if there is a suitable operator for
278 /// the given expression.
279 static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, SourceLocation Loc,
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);
287 static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, Scope *S,
288 SourceLocation Loc, Expr *E) {
289 ExprResult R = buildOperatorCoawaitLookupExpr(SemaRef, S, Loc);
292 return buildOperatorCoawaitCall(SemaRef, Loc, E,
293 cast<UnresolvedLookupExpr>(R.get()));
296 static Expr *buildBuiltinCall(Sema &S, SourceLocation Loc, Builtin::ID Id,
297 MultiExprArg CallArgs) {
298 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);
302 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
303 assert(BuiltInDecl && "failed to find builtin declaration");
306 S.BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
307 assert(DeclRef.isUsable() && "Builtin reference cannot fail");
310 S.ActOnCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
312 assert(!Call.isInvalid() && "Call to builtin cannot fail!");
316 static ExprResult buildCoroutineHandle(Sema &S, QualType PromiseType,
317 SourceLocation Loc) {
318 QualType CoroHandleType = lookupCoroutineHandleType(S, PromiseType, Loc);
319 if (CoroHandleType.isNull())
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)
332 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_frame, {});
335 ExprResult FromAddr =
336 S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
337 if (FromAddr.isInvalid())
340 return S.ActOnCallExpr(nullptr, FromAddr.get(), Loc, FramePtr, Loc);
343 struct ReadySuspendResumeResult {
344 enum AwaitCallType { ACT_Ready, ACT_Suspend, ACT_Resume };
346 OpaqueValueExpr *OpaqueValue;
350 static ExprResult buildMemberCall(Sema &S, Expr *Base, SourceLocation Loc,
351 StringRef Name, MultiExprArg Args) {
352 DeclarationNameInfo NameInfo(&S.PP.getIdentifierTable().get(Name), Loc);
354 // FIXME: Fix BuildMemberReferenceExpr to take a const CXXScopeSpec&.
356 ExprResult Result = S.BuildMemberReferenceExpr(
357 Base, Base->getType(), Loc, /*IsPtr=*/false, SS,
358 SourceLocation(), nullptr, NameInfo, /*TemplateArgs=*/nullptr,
360 if (Result.isInvalid())
363 return S.ActOnCallExpr(nullptr, Result.get(), Loc, Args, Loc, nullptr);
366 /// Build calls to await_ready, await_suspend, and await_resume for a co_await
368 static ReadySuspendResumeResult buildCoawaitCalls(Sema &S, VarDecl *CoroPromise,
369 SourceLocation Loc, Expr *E) {
370 OpaqueValueExpr *Operand = new (S.Context)
371 OpaqueValueExpr(Loc, E->getType(), VK_LValue, E->getObjectKind(), E);
373 // Assume invalid until we see otherwise.
374 ReadySuspendResumeResult Calls = {{}, Operand, /*IsInvalid=*/true};
376 ExprResult CoroHandleRes = buildCoroutineHandle(S, CoroPromise->getType(), Loc);
377 if (CoroHandleRes.isInvalid())
379 Expr *CoroHandle = CoroHandleRes.get();
381 const StringRef Funcs[] = {"await_ready", "await_suspend", "await_resume"};
382 MultiExprArg Args[] = {None, CoroHandle, None};
383 for (size_t I = 0, N = llvm::array_lengthof(Funcs); I != N; ++I) {
384 ExprResult Result = buildMemberCall(S, Operand, Loc, Funcs[I], Args[I]);
385 if (Result.isInvalid())
387 Calls.Results[I] = Result.get();
390 // Assume the calls are valid; all further checking should make them invalid.
391 Calls.IsInvalid = false;
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
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;
407 Calls.Results[ACT::ACT_Ready] = Conv.get();
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.
414 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)) {
419 S.Diag(AwaitSuspend->getCalleeDecl()->getLocation(),
420 diag::err_await_suspend_invalid_return_type)
422 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
423 << AwaitSuspend->getDirectCallee();
424 Calls.IsInvalid = true;
431 static ExprResult buildPromiseCall(Sema &S, VarDecl *Promise,
432 SourceLocation Loc, StringRef Name,
435 // Form a reference to the promise.
436 ExprResult PromiseRef = S.BuildDeclRefExpr(
437 Promise, Promise->getType().getNonReferenceType(), VK_LValue, Loc);
438 if (PromiseRef.isInvalid())
441 return buildMemberCall(S, PromiseRef.get(), Loc, Name, Args);
444 VarDecl *Sema::buildCoroutinePromise(SourceLocation Loc) {
445 assert(isa<FunctionDecl>(CurContext) && "not in a function scope");
446 auto *FD = cast<FunctionDecl>(CurContext);
447 bool IsThisDependentType = [&] {
448 if (auto *MD = dyn_cast_or_null<CXXMethodDecl>(FD))
449 return MD->isInstance() && MD->getThisType(Context)->isDependentType();
454 QualType T = FD->getType()->isDependentType() || IsThisDependentType
455 ? Context.DependentTy
456 : lookupPromiseType(*this, FD, Loc);
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())
466 ActOnUninitializedDecl(VD);
468 assert(!VD->isInvalidDecl());
472 /// Check that this is a context in which a coroutine suspension can appear.
473 static FunctionScopeInfo *checkCoroutineContext(Sema &S, SourceLocation Loc,
475 bool IsImplicit = false) {
476 if (!isValidCoroutineContext(S, Loc, Keyword))
479 assert(isa<FunctionDecl>(S.CurContext) && "not in a function scope");
481 auto *ScopeInfo = S.getCurFunction();
482 assert(ScopeInfo && "missing function scope for function");
484 if (ScopeInfo->FirstCoroutineStmtLoc.isInvalid() && !IsImplicit)
485 ScopeInfo->setFirstCoroutineStmt(Loc, Keyword);
487 if (ScopeInfo->CoroutinePromise)
490 ScopeInfo->CoroutinePromise = S.buildCoroutinePromise(Loc);
491 if (!ScopeInfo->CoroutinePromise)
497 bool Sema::ActOnCoroutineBodyStart(Scope *SC, SourceLocation KWLoc,
499 if (!checkCoroutineContext(*this, KWLoc, Keyword))
501 auto *ScopeInfo = getCurFunction();
502 assert(ScopeInfo->CoroutinePromise);
504 // If we have existing coroutine statements then we have already built
505 // the initial and final suspend points.
506 if (!ScopeInfo->NeedsCoroutineSuspends)
509 ScopeInfo->setNeedsCoroutineSuspends(false);
511 auto *Fn = cast<FunctionDecl>(CurContext);
512 SourceLocation Loc = Fn->getLocation();
513 // Build the initial suspend point
514 auto buildSuspends = [&](StringRef Name) mutable -> StmtResult {
516 buildPromiseCall(*this, ScopeInfo->CoroutinePromise, Loc, Name, None);
517 if (Suspend.isInvalid())
519 Suspend = buildOperatorCoawaitCall(*this, SC, Loc, Suspend.get());
520 if (Suspend.isInvalid())
522 Suspend = BuildResolvedCoawaitExpr(Loc, Suspend.get(),
523 /*IsImplicit*/ true);
524 Suspend = ActOnFinishFullExpr(Suspend.get());
525 if (Suspend.isInvalid()) {
526 Diag(Loc, diag::note_coroutine_promise_suspend_implicitly_required)
527 << ((Name == "initial_suspend") ? 0 : 1);
528 Diag(KWLoc, diag::note_declared_coroutine_here) << Keyword;
531 return cast<Stmt>(Suspend.get());
534 StmtResult InitSuspend = buildSuspends("initial_suspend");
535 if (InitSuspend.isInvalid())
538 StmtResult FinalSuspend = buildSuspends("final_suspend");
539 if (FinalSuspend.isInvalid())
542 ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());
547 ExprResult Sema::ActOnCoawaitExpr(Scope *S, SourceLocation Loc, Expr *E) {
548 if (!ActOnCoroutineBodyStart(S, Loc, "co_await")) {
549 CorrectDelayedTyposInExpr(E);
553 if (E->getType()->isPlaceholderType()) {
554 ExprResult R = CheckPlaceholderExpr(E);
555 if (R.isInvalid()) return ExprError();
558 ExprResult Lookup = buildOperatorCoawaitLookupExpr(*this, S, Loc);
559 if (Lookup.isInvalid())
561 return BuildUnresolvedCoawaitExpr(Loc, E,
562 cast<UnresolvedLookupExpr>(Lookup.get()));
565 ExprResult Sema::BuildUnresolvedCoawaitExpr(SourceLocation Loc, Expr *E,
566 UnresolvedLookupExpr *Lookup) {
567 auto *FSI = checkCoroutineContext(*this, Loc, "co_await");
571 if (E->getType()->isPlaceholderType()) {
572 ExprResult R = CheckPlaceholderExpr(E);
578 auto *Promise = FSI->CoroutinePromise;
579 if (Promise->getType()->isDependentType()) {
581 new (Context) DependentCoawaitExpr(Loc, Context.DependentTy, E, Lookup);
585 auto *RD = Promise->getType()->getAsCXXRecordDecl();
586 if (lookupMember(*this, "await_transform", RD, Loc)) {
587 ExprResult R = buildPromiseCall(*this, Promise, Loc, "await_transform", E);
590 diag::note_coroutine_promise_implicit_await_transform_required_here)
591 << E->getSourceRange();
596 ExprResult Awaitable = buildOperatorCoawaitCall(*this, Loc, E, Lookup);
597 if (Awaitable.isInvalid())
600 return BuildResolvedCoawaitExpr(Loc, Awaitable.get());
603 ExprResult Sema::BuildResolvedCoawaitExpr(SourceLocation Loc, Expr *E,
605 auto *Coroutine = checkCoroutineContext(*this, Loc, "co_await", IsImplicit);
609 if (E->getType()->isPlaceholderType()) {
610 ExprResult R = CheckPlaceholderExpr(E);
611 if (R.isInvalid()) return ExprError();
615 if (E->getType()->isDependentType()) {
616 Expr *Res = new (Context)
617 CoawaitExpr(Loc, Context.DependentTy, E, IsImplicit);
621 // 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)
624 E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
626 // Build the await_ready, await_suspend, await_resume calls.
627 ReadySuspendResumeResult RSS =
628 buildCoawaitCalls(*this, Coroutine->CoroutinePromise, Loc, E);
633 new (Context) CoawaitExpr(Loc, E, RSS.Results[0], RSS.Results[1],
634 RSS.Results[2], RSS.OpaqueValue, IsImplicit);
639 ExprResult Sema::ActOnCoyieldExpr(Scope *S, SourceLocation Loc, Expr *E) {
640 if (!ActOnCoroutineBodyStart(S, Loc, "co_yield")) {
641 CorrectDelayedTyposInExpr(E);
645 // Build yield_value call.
646 ExprResult Awaitable = buildPromiseCall(
647 *this, getCurFunction()->CoroutinePromise, Loc, "yield_value", E);
648 if (Awaitable.isInvalid())
651 // Build 'operator co_await' call.
652 Awaitable = buildOperatorCoawaitCall(*this, S, Loc, Awaitable.get());
653 if (Awaitable.isInvalid())
656 return BuildCoyieldExpr(Loc, Awaitable.get());
658 ExprResult Sema::BuildCoyieldExpr(SourceLocation Loc, Expr *E) {
659 auto *Coroutine = checkCoroutineContext(*this, Loc, "co_yield");
663 if (E->getType()->isPlaceholderType()) {
664 ExprResult R = CheckPlaceholderExpr(E);
665 if (R.isInvalid()) return ExprError();
669 if (E->getType()->isDependentType()) {
670 Expr *Res = new (Context) CoyieldExpr(Loc, Context.DependentTy, E);
674 // 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)
677 E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
679 // Build the await_ready, await_suspend, await_resume calls.
680 ReadySuspendResumeResult RSS =
681 buildCoawaitCalls(*this, Coroutine->CoroutinePromise, Loc, E);
686 new (Context) CoyieldExpr(Loc, E, RSS.Results[0], RSS.Results[1],
687 RSS.Results[2], RSS.OpaqueValue);
692 StmtResult Sema::ActOnCoreturnStmt(Scope *S, SourceLocation Loc, Expr *E) {
693 if (!ActOnCoroutineBodyStart(S, Loc, "co_return")) {
694 CorrectDelayedTyposInExpr(E);
697 return BuildCoreturnStmt(Loc, E);
700 StmtResult Sema::BuildCoreturnStmt(SourceLocation Loc, Expr *E,
702 auto *FSI = checkCoroutineContext(*this, Loc, "co_return", IsImplicit);
706 if (E && E->getType()->isPlaceholderType() &&
707 !E->getType()->isSpecificPlaceholderType(BuiltinType::Overload)) {
708 ExprResult R = CheckPlaceholderExpr(E);
709 if (R.isInvalid()) return StmtError();
713 // FIXME: If the operand is a reference to a variable that's about to go out
714 // of scope, we should treat the operand as an xvalue for this overload
716 VarDecl *Promise = FSI->CoroutinePromise;
718 if (E && (isa<InitListExpr>(E) || !E->getType()->isVoidType())) {
719 PC = buildPromiseCall(*this, Promise, Loc, "return_value", E);
721 E = MakeFullDiscardedValueExpr(E).get();
722 PC = buildPromiseCall(*this, Promise, Loc, "return_void", None);
727 Expr *PCE = ActOnFinishFullExpr(PC.get()).get();
729 Stmt *Res = new (Context) CoreturnStmt(Loc, E, PCE, IsImplicit);
733 /// Look up the std::nothrow object.
734 static Expr *buildStdNoThrowDeclRef(Sema &S, SourceLocation Loc) {
735 NamespaceDecl *Std = S.getStdNamespace();
736 assert(Std && "Should already be diagnosed");
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
744 S.Diag(Loc, diag::err_implicit_coroutine_std_nothrow_type_not_found);
748 auto *VD = Result.getAsSingle<VarDecl>();
750 Result.suppressDiagnostics();
751 // We found something weird. Complain about the first thing we found.
752 NamedDecl *Found = *Result.begin();
753 S.Diag(Found->getLocation(), diag::err_malformed_std_nothrow);
757 ExprResult DR = S.BuildDeclRefExpr(VD, VD->getType(), VK_LValue, Loc);
764 // Find an appropriate delete for the promise.
765 static FunctionDecl *findDeleteForPromise(Sema &S, SourceLocation Loc,
766 QualType PromiseType) {
767 FunctionDecl *OperatorDelete = nullptr;
769 DeclarationName DeleteName =
770 S.Context.DeclarationNames.getCXXOperatorName(OO_Delete);
772 auto *PointeeRD = PromiseType->getAsCXXRecordDecl();
773 assert(PointeeRD && "PromiseType must be a CxxRecordDecl type");
775 if (S.FindDeallocationFunction(Loc, PointeeRD, DeleteName, OperatorDelete))
778 if (!OperatorDelete) {
779 // Look for a global declaration.
780 const bool CanProvideSize = S.isCompleteType(Loc, PromiseType);
781 const bool Overaligned = false;
782 OperatorDelete = S.FindUsualDeallocationFunction(Loc, CanProvideSize,
783 Overaligned, DeleteName);
785 S.MarkFunctionReferenced(Loc, OperatorDelete);
786 return OperatorDelete;
790 void Sema::CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body) {
791 FunctionScopeInfo *Fn = getCurFunction();
792 assert(Fn && Fn->isCoroutine() && "not a coroutine");
794 assert(FD->isInvalidDecl() &&
795 "a null body is only allowed for invalid declarations");
798 // We have a function that uses coroutine keywords, but we failed to build
800 if (!Fn->CoroutinePromise)
801 return FD->setInvalidDecl();
803 if (isa<CoroutineBodyStmt>(Body)) {
804 // Nothing todo. the body is already a transformed coroutine body statement.
808 // Coroutines [stmt.return]p1:
809 // A return statement shall not appear in a coroutine.
810 if (Fn->FirstReturnLoc.isValid()) {
811 assert(Fn->FirstCoroutineStmtLoc.isValid() &&
812 "first coroutine location not set");
813 Diag(Fn->FirstReturnLoc, diag::err_return_in_coroutine);
814 Diag(Fn->FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
815 << Fn->getFirstCoroutineStmtKeyword();
817 CoroutineStmtBuilder Builder(*this, *FD, *Fn, Body);
818 if (Builder.isInvalid() || !Builder.buildStatements())
819 return FD->setInvalidDecl();
821 // Build body for the coroutine wrapper statement.
822 Body = CoroutineBodyStmt::Create(Context, Builder);
825 CoroutineStmtBuilder::CoroutineStmtBuilder(Sema &S, FunctionDecl &FD,
826 sema::FunctionScopeInfo &Fn,
828 : S(S), FD(FD), Fn(Fn), Loc(FD.getLocation()),
829 IsPromiseDependentType(
830 !Fn.CoroutinePromise ||
831 Fn.CoroutinePromise->getType()->isDependentType()) {
833 if (!IsPromiseDependentType) {
834 PromiseRecordDecl = Fn.CoroutinePromise->getType()->getAsCXXRecordDecl();
835 assert(PromiseRecordDecl && "Type should have already been checked");
837 this->IsValid = makePromiseStmt() && makeInitialAndFinalSuspend();
840 bool CoroutineStmtBuilder::buildStatements() {
841 assert(this->IsValid && "coroutine already invalid");
842 this->IsValid = makeReturnObject() && makeParamMoves();
843 if (this->IsValid && !IsPromiseDependentType)
844 buildDependentStatements();
845 return this->IsValid;
848 bool CoroutineStmtBuilder::buildDependentStatements() {
849 assert(this->IsValid && "coroutine already invalid");
850 assert(!this->IsPromiseDependentType &&
851 "coroutine cannot have a dependent promise type");
852 this->IsValid = makeOnException() && makeOnFallthrough() &&
853 makeGroDeclAndReturnStmt() && makeReturnOnAllocFailure() &&
854 makeNewAndDeleteExpr();
855 return this->IsValid;
858 bool CoroutineStmtBuilder::buildParameterMoves() {
859 assert(this->IsValid && "coroutine already invalid");
860 assert(this->ParamMoves.empty() && "param moves already built");
861 return this->IsValid = makeParamMoves();
864 bool CoroutineStmtBuilder::makePromiseStmt() {
865 // Form a declaration statement for the promise declaration, so that AST
866 // visitors can more easily find it.
867 StmtResult PromiseStmt =
868 S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(Fn.CoroutinePromise), Loc, Loc);
869 if (PromiseStmt.isInvalid())
872 this->Promise = PromiseStmt.get();
876 bool CoroutineStmtBuilder::makeInitialAndFinalSuspend() {
877 if (Fn.hasInvalidCoroutineSuspends())
879 this->InitialSuspend = cast<Expr>(Fn.CoroutineSuspends.first);
880 this->FinalSuspend = cast<Expr>(Fn.CoroutineSuspends.second);
884 static bool diagReturnOnAllocFailure(Sema &S, Expr *E,
885 CXXRecordDecl *PromiseRecordDecl,
886 FunctionScopeInfo &Fn) {
887 auto Loc = E->getExprLoc();
888 if (auto *DeclRef = dyn_cast_or_null<DeclRefExpr>(E)) {
889 auto *Decl = DeclRef->getDecl();
890 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Decl)) {
891 if (Method->isStatic())
894 Loc = Decl->getLocation();
900 diag::err_coroutine_promise_get_return_object_on_allocation_failure)
901 << PromiseRecordDecl;
902 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
903 << Fn.getFirstCoroutineStmtKeyword();
907 bool CoroutineStmtBuilder::makeReturnOnAllocFailure() {
908 assert(!IsPromiseDependentType &&
909 "cannot make statement while the promise type is dependent");
911 // [dcl.fct.def.coroutine]/8
912 // The unqualified-id get_return_object_on_allocation_failure is looked up in
913 // the scope of class P by class member access lookup (3.4.5). ...
914 // If an allocation function returns nullptr, ... the coroutine return value
915 // is obtained by a call to ... get_return_object_on_allocation_failure().
918 S.PP.getIdentifierInfo("get_return_object_on_allocation_failure");
919 LookupResult Found(S, DN, Loc, Sema::LookupMemberName);
920 if (!S.LookupQualifiedName(Found, PromiseRecordDecl))
924 ExprResult DeclNameExpr =
925 S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
926 if (DeclNameExpr.isInvalid())
929 if (!diagReturnOnAllocFailure(S, DeclNameExpr.get(), PromiseRecordDecl, Fn))
932 ExprResult ReturnObjectOnAllocationFailure =
933 S.ActOnCallExpr(nullptr, DeclNameExpr.get(), Loc, {}, Loc);
934 if (ReturnObjectOnAllocationFailure.isInvalid())
937 StmtResult ReturnStmt =
938 S.BuildReturnStmt(Loc, ReturnObjectOnAllocationFailure.get());
939 if (ReturnStmt.isInvalid()) {
940 S.Diag(Found.getFoundDecl()->getLocation(), diag::note_member_declared_here)
942 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
943 << Fn.getFirstCoroutineStmtKeyword();
947 this->ReturnStmtOnAllocFailure = ReturnStmt.get();
951 bool CoroutineStmtBuilder::makeNewAndDeleteExpr() {
952 // Form and check allocation and deallocation calls.
953 assert(!IsPromiseDependentType &&
954 "cannot make statement while the promise type is dependent");
955 QualType PromiseType = Fn.CoroutinePromise->getType();
957 if (S.RequireCompleteType(Loc, PromiseType, diag::err_incomplete_type))
960 const bool RequiresNoThrowAlloc = ReturnStmtOnAllocFailure != nullptr;
962 // FIXME: Add support for stateful allocators.
964 FunctionDecl *OperatorNew = nullptr;
965 FunctionDecl *OperatorDelete = nullptr;
966 FunctionDecl *UnusedResult = nullptr;
967 bool PassAlignment = false;
968 SmallVector<Expr *, 1> PlacementArgs;
970 S.FindAllocationFunctions(Loc, SourceRange(),
971 /*UseGlobal*/ false, PromiseType,
972 /*isArray*/ false, PassAlignment, PlacementArgs,
973 OperatorNew, UnusedResult);
975 bool IsGlobalOverload =
976 OperatorNew && !isa<CXXRecordDecl>(OperatorNew->getDeclContext());
977 // If we didn't find a class-local new declaration and non-throwing new
978 // was is required then we need to lookup the non-throwing global operator
980 if (RequiresNoThrowAlloc && (!OperatorNew || IsGlobalOverload)) {
981 auto *StdNoThrow = buildStdNoThrowDeclRef(S, Loc);
984 PlacementArgs = {StdNoThrow};
985 OperatorNew = nullptr;
986 S.FindAllocationFunctions(Loc, SourceRange(),
987 /*UseGlobal*/ true, PromiseType,
988 /*isArray*/ false, PassAlignment, PlacementArgs,
989 OperatorNew, UnusedResult);
992 assert(OperatorNew && "expected definition of operator new to be found");
994 if (RequiresNoThrowAlloc) {
995 const auto *FT = OperatorNew->getType()->getAs<FunctionProtoType>();
996 if (!FT->isNothrow(S.Context, /*ResultIfDependent*/ false)) {
997 S.Diag(OperatorNew->getLocation(),
998 diag::err_coroutine_promise_new_requires_nothrow)
1000 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
1006 if ((OperatorDelete = findDeleteForPromise(S, Loc, PromiseType)) == nullptr)
1010 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_frame, {});
1013 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_size, {});
1018 S.BuildDeclRefExpr(OperatorNew, OperatorNew->getType(), VK_LValue, Loc);
1019 if (NewRef.isInvalid())
1022 SmallVector<Expr *, 2> NewArgs(1, FrameSize);
1023 for (auto Arg : PlacementArgs)
1024 NewArgs.push_back(Arg);
1026 ExprResult NewExpr =
1027 S.ActOnCallExpr(S.getCurScope(), NewRef.get(), Loc, NewArgs, Loc);
1028 NewExpr = S.ActOnFinishFullExpr(NewExpr.get());
1029 if (NewExpr.isInvalid())
1032 // Make delete call.
1034 QualType OpDeleteQualType = OperatorDelete->getType();
1036 ExprResult DeleteRef =
1037 S.BuildDeclRefExpr(OperatorDelete, OpDeleteQualType, VK_LValue, Loc);
1038 if (DeleteRef.isInvalid())
1042 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_free, {FramePtr});
1044 SmallVector<Expr *, 2> DeleteArgs{CoroFree};
1046 // Check if we need to pass the size.
1047 const auto *OpDeleteType =
1048 OpDeleteQualType.getTypePtr()->getAs<FunctionProtoType>();
1049 if (OpDeleteType->getNumParams() > 1)
1050 DeleteArgs.push_back(FrameSize);
1052 ExprResult DeleteExpr =
1053 S.ActOnCallExpr(S.getCurScope(), DeleteRef.get(), Loc, DeleteArgs, Loc);
1054 DeleteExpr = S.ActOnFinishFullExpr(DeleteExpr.get());
1055 if (DeleteExpr.isInvalid())
1058 this->Allocate = NewExpr.get();
1059 this->Deallocate = DeleteExpr.get();
1064 bool CoroutineStmtBuilder::makeOnFallthrough() {
1065 assert(!IsPromiseDependentType &&
1066 "cannot make statement while the promise type is dependent");
1068 // [dcl.fct.def.coroutine]/4
1069 // The unqualified-ids 'return_void' and 'return_value' are looked up in
1070 // the scope of class P. If both are found, the program is ill-formed.
1071 bool HasRVoid, HasRValue;
1072 LookupResult LRVoid =
1073 lookupMember(S, "return_void", PromiseRecordDecl, Loc, HasRVoid);
1074 LookupResult LRValue =
1075 lookupMember(S, "return_value", PromiseRecordDecl, Loc, HasRValue);
1077 StmtResult Fallthrough;
1078 if (HasRVoid && HasRValue) {
1079 // FIXME Improve this diagnostic
1080 S.Diag(FD.getLocation(),
1081 diag::err_coroutine_promise_incompatible_return_functions)
1082 << PromiseRecordDecl;
1083 S.Diag(LRVoid.getRepresentativeDecl()->getLocation(),
1084 diag::note_member_first_declared_here)
1085 << LRVoid.getLookupName();
1086 S.Diag(LRValue.getRepresentativeDecl()->getLocation(),
1087 diag::note_member_first_declared_here)
1088 << LRValue.getLookupName();
1090 } else if (!HasRVoid && !HasRValue) {
1091 // FIXME: The PDTS currently specifies this case as UB, not ill-formed.
1092 // However we still diagnose this as an error since until the PDTS is fixed.
1093 S.Diag(FD.getLocation(),
1094 diag::err_coroutine_promise_requires_return_function)
1095 << PromiseRecordDecl;
1096 S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here)
1097 << PromiseRecordDecl;
1099 } else if (HasRVoid) {
1100 // If the unqualified-id return_void is found, flowing off the end of a
1101 // coroutine is equivalent to a co_return with no operand. Otherwise,
1102 // flowing off the end of a coroutine results in undefined behavior.
1103 Fallthrough = S.BuildCoreturnStmt(FD.getLocation(), nullptr,
1104 /*IsImplicit*/false);
1105 Fallthrough = S.ActOnFinishFullStmt(Fallthrough.get());
1106 if (Fallthrough.isInvalid())
1110 this->OnFallthrough = Fallthrough.get();
1114 bool CoroutineStmtBuilder::makeOnException() {
1115 // Try to form 'p.unhandled_exception();'
1116 assert(!IsPromiseDependentType &&
1117 "cannot make statement while the promise type is dependent");
1119 const bool RequireUnhandledException = S.getLangOpts().CXXExceptions;
1121 if (!lookupMember(S, "unhandled_exception", PromiseRecordDecl, Loc)) {
1123 RequireUnhandledException
1124 ? diag::err_coroutine_promise_unhandled_exception_required
1126 warn_coroutine_promise_unhandled_exception_required_with_exceptions;
1127 S.Diag(Loc, DiagID) << PromiseRecordDecl;
1128 S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here)
1129 << PromiseRecordDecl;
1130 return !RequireUnhandledException;
1133 // If exceptions are disabled, don't try to build OnException.
1134 if (!S.getLangOpts().CXXExceptions)
1137 ExprResult UnhandledException = buildPromiseCall(S, Fn.CoroutinePromise, Loc,
1138 "unhandled_exception", None);
1139 UnhandledException = S.ActOnFinishFullExpr(UnhandledException.get(), Loc);
1140 if (UnhandledException.isInvalid())
1143 // Since the body of the coroutine will be wrapped in try-catch, it will
1144 // be incompatible with SEH __try if present in a function.
1145 if (!S.getLangOpts().Borland && Fn.FirstSEHTryLoc.isValid()) {
1146 S.Diag(Fn.FirstSEHTryLoc, diag::err_seh_in_a_coroutine_with_cxx_exceptions);
1147 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1148 << Fn.getFirstCoroutineStmtKeyword();
1152 this->OnException = UnhandledException.get();
1156 bool CoroutineStmtBuilder::makeReturnObject() {
1157 // Build implicit 'p.get_return_object()' expression and form initialization
1158 // of return type from it.
1159 ExprResult ReturnObject =
1160 buildPromiseCall(S, Fn.CoroutinePromise, Loc, "get_return_object", None);
1161 if (ReturnObject.isInvalid())
1164 this->ReturnValue = ReturnObject.get();
1168 static void noteMemberDeclaredHere(Sema &S, Expr *E, FunctionScopeInfo &Fn) {
1169 if (auto *MbrRef = dyn_cast<CXXMemberCallExpr>(E)) {
1170 auto *MethodDecl = MbrRef->getMethodDecl();
1171 S.Diag(MethodDecl->getLocation(), diag::note_member_declared_here)
1174 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1175 << Fn.getFirstCoroutineStmtKeyword();
1178 bool CoroutineStmtBuilder::makeGroDeclAndReturnStmt() {
1179 assert(!IsPromiseDependentType &&
1180 "cannot make statement while the promise type is dependent");
1181 assert(this->ReturnValue && "ReturnValue must be already formed");
1183 QualType const GroType = this->ReturnValue->getType();
1184 assert(!GroType->isDependentType() &&
1185 "get_return_object type must no longer be dependent");
1187 QualType const FnRetType = FD.getReturnType();
1188 assert(!FnRetType->isDependentType() &&
1189 "get_return_object type must no longer be dependent");
1191 if (FnRetType->isVoidType()) {
1192 ExprResult Res = S.ActOnFinishFullExpr(this->ReturnValue, Loc);
1193 if (Res.isInvalid())
1196 this->ResultDecl = Res.get();
1200 if (GroType->isVoidType()) {
1201 // Trigger a nice error message.
1202 InitializedEntity Entity =
1203 InitializedEntity::InitializeResult(Loc, FnRetType, false);
1204 S.PerformMoveOrCopyInitialization(Entity, nullptr, FnRetType, ReturnValue);
1205 noteMemberDeclaredHere(S, ReturnValue, Fn);
1209 auto *GroDecl = VarDecl::Create(
1210 S.Context, &FD, FD.getLocation(), FD.getLocation(),
1211 &S.PP.getIdentifierTable().get("__coro_gro"), GroType,
1212 S.Context.getTrivialTypeSourceInfo(GroType, Loc), SC_None);
1214 S.CheckVariableDeclarationType(GroDecl);
1215 if (GroDecl->isInvalidDecl())
1218 InitializedEntity Entity = InitializedEntity::InitializeVariable(GroDecl);
1219 ExprResult Res = S.PerformMoveOrCopyInitialization(Entity, nullptr, GroType,
1221 if (Res.isInvalid())
1224 Res = S.ActOnFinishFullExpr(Res.get());
1225 if (Res.isInvalid())
1228 if (GroType == FnRetType) {
1229 GroDecl->setNRVOVariable(true);
1232 S.AddInitializerToDecl(GroDecl, Res.get(),
1233 /*DirectInit=*/false);
1235 S.FinalizeDeclaration(GroDecl);
1237 // Form a declaration statement for the return declaration, so that AST
1238 // visitors can more easily find it.
1239 StmtResult GroDeclStmt =
1240 S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(GroDecl), Loc, Loc);
1241 if (GroDeclStmt.isInvalid())
1244 this->ResultDecl = GroDeclStmt.get();
1246 ExprResult declRef = S.BuildDeclRefExpr(GroDecl, GroType, VK_LValue, Loc);
1247 if (declRef.isInvalid())
1250 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, declRef.get());
1251 if (ReturnStmt.isInvalid()) {
1252 noteMemberDeclaredHere(S, ReturnValue, Fn);
1256 this->ReturnStmt = ReturnStmt.get();
1260 // Create a static_cast\<T&&>(expr).
1261 static Expr *castForMoving(Sema &S, Expr *E, QualType T = QualType()) {
1264 QualType TargetType = S.BuildReferenceType(
1265 T, /*SpelledAsLValue*/ false, SourceLocation(), DeclarationName());
1266 SourceLocation ExprLoc = E->getLocStart();
1267 TypeSourceInfo *TargetLoc =
1268 S.Context.getTrivialTypeSourceInfo(TargetType, ExprLoc);
1271 .BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
1272 SourceRange(ExprLoc, ExprLoc), E->getSourceRange())
1277 /// \brief Build a variable declaration for move parameter.
1278 static VarDecl *buildVarDecl(Sema &S, SourceLocation Loc, QualType Type,
1279 IdentifierInfo *II) {
1280 TypeSourceInfo *TInfo = S.Context.getTrivialTypeSourceInfo(Type, Loc);
1282 VarDecl::Create(S.Context, S.CurContext, Loc, Loc, II, Type, TInfo, SC_None);
1283 Decl->setImplicit();
1287 bool CoroutineStmtBuilder::makeParamMoves() {
1288 for (auto *paramDecl : FD.parameters()) {
1289 auto Ty = paramDecl->getType();
1290 if (Ty->isDependentType())
1293 // No need to copy scalars, llvm will take care of them.
1294 if (Ty->getAsCXXRecordDecl()) {
1295 ExprResult ParamRef =
1296 S.BuildDeclRefExpr(paramDecl, paramDecl->getType(),
1297 ExprValueKind::VK_LValue, Loc); // FIXME: scope?
1298 if (ParamRef.isInvalid())
1301 Expr *RCast = castForMoving(S, ParamRef.get());
1303 auto D = buildVarDecl(S, Loc, Ty, paramDecl->getIdentifier());
1304 S.AddInitializerToDecl(D, RCast, /*DirectInit=*/true);
1306 // Convert decl to a statement.
1307 StmtResult Stmt = S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(D), Loc, Loc);
1308 if (Stmt.isInvalid())
1311 ParamMovesVector.push_back(Stmt.get());
1315 // Convert to ArrayRef in CtorArgs structure that builder inherits from.
1316 ParamMoves = ParamMovesVector;
1320 StmtResult Sema::BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
1321 CoroutineBodyStmt *Res = CoroutineBodyStmt::Create(Context, Args);