1 //===--- SemaCoroutines.cpp - Semantic Analysis for Coroutines ------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for C++ Coroutines.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "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"
22 
23 using namespace clang;
24 using namespace sema;
25 
26 static bool lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD,
27                          SourceLocation Loc) {
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   return S.LookupQualifiedName(LR, RD);
34 }
35 
36 /// Look up the std::coroutine_traits<...>::promise_type for the given
37 /// function type.
38 static QualType lookupPromiseType(Sema &S, const FunctionProtoType *FnType,
39                                   SourceLocation KwLoc,
40                                   SourceLocation FuncLoc) {
41   // FIXME: Cache std::coroutine_traits once we've found it.
42   NamespaceDecl *StdExp = S.lookupStdExperimentalNamespace();
43   if (!StdExp) {
44     S.Diag(KwLoc, diag::err_implied_coroutine_type_not_found)
45         << "std::experimental::coroutine_traits";
46     return QualType();
47   }
48 
49   LookupResult Result(S, &S.PP.getIdentifierTable().get("coroutine_traits"),
50                       FuncLoc, Sema::LookupOrdinaryName);
51   if (!S.LookupQualifiedName(Result, StdExp)) {
52     S.Diag(KwLoc, diag::err_implied_coroutine_type_not_found)
53         << "std::experimental::coroutine_traits";
54     return QualType();
55   }
56 
57   ClassTemplateDecl *CoroTraits = Result.getAsSingle<ClassTemplateDecl>();
58   if (!CoroTraits) {
59     Result.suppressDiagnostics();
60     // We found something weird. Complain about the first thing we found.
61     NamedDecl *Found = *Result.begin();
62     S.Diag(Found->getLocation(), diag::err_malformed_std_coroutine_traits);
63     return QualType();
64   }
65 
66   // Form template argument list for coroutine_traits<R, P1, P2, ...>.
67   TemplateArgumentListInfo Args(KwLoc, KwLoc);
68   Args.addArgument(TemplateArgumentLoc(
69       TemplateArgument(FnType->getReturnType()),
70       S.Context.getTrivialTypeSourceInfo(FnType->getReturnType(), KwLoc)));
71   // FIXME: If the function is a non-static member function, add the type
72   // of the implicit object parameter before the formal parameters.
73   for (QualType T : FnType->getParamTypes())
74     Args.addArgument(TemplateArgumentLoc(
75         TemplateArgument(T), S.Context.getTrivialTypeSourceInfo(T, KwLoc)));
76 
77   // Build the template-id.
78   QualType CoroTrait =
79       S.CheckTemplateIdType(TemplateName(CoroTraits), KwLoc, Args);
80   if (CoroTrait.isNull())
81     return QualType();
82   if (S.RequireCompleteType(KwLoc, CoroTrait,
83                             diag::err_coroutine_type_missing_specialization))
84     return QualType();
85 
86   auto *RD = CoroTrait->getAsCXXRecordDecl();
87   assert(RD && "specialization of class template is not a class?");
88 
89   // Look up the ::promise_type member.
90   LookupResult R(S, &S.PP.getIdentifierTable().get("promise_type"), KwLoc,
91                  Sema::LookupOrdinaryName);
92   S.LookupQualifiedName(R, RD);
93   auto *Promise = R.getAsSingle<TypeDecl>();
94   if (!Promise) {
95     S.Diag(FuncLoc,
96            diag::err_implied_std_coroutine_traits_promise_type_not_found)
97         << RD;
98     return QualType();
99   }
100   // The promise type is required to be a class type.
101   QualType PromiseType = S.Context.getTypeDeclType(Promise);
102 
103   auto buildElaboratedType = [&]() {
104     auto *NNS = NestedNameSpecifier::Create(S.Context, nullptr, StdExp);
105     NNS = NestedNameSpecifier::Create(S.Context, NNS, false,
106                                       CoroTrait.getTypePtr());
107     return S.Context.getElaboratedType(ETK_None, NNS, PromiseType);
108   };
109 
110   if (!PromiseType->getAsCXXRecordDecl()) {
111     S.Diag(FuncLoc,
112            diag::err_implied_std_coroutine_traits_promise_type_not_class)
113         << buildElaboratedType();
114     return QualType();
115   }
116   if (S.RequireCompleteType(FuncLoc, buildElaboratedType(),
117                             diag::err_coroutine_promise_type_incomplete))
118     return QualType();
119 
120   return PromiseType;
121 }
122 
123 /// Look up the std::coroutine_traits<...>::promise_type for the given
124 /// function type.
125 static QualType lookupCoroutineHandleType(Sema &S, QualType PromiseType,
126                                           SourceLocation Loc) {
127   if (PromiseType.isNull())
128     return QualType();
129 
130   NamespaceDecl *StdExp = S.lookupStdExperimentalNamespace();
131   assert(StdExp && "Should already be diagnosed");
132 
133   LookupResult Result(S, &S.PP.getIdentifierTable().get("coroutine_handle"),
134                       Loc, Sema::LookupOrdinaryName);
135   if (!S.LookupQualifiedName(Result, StdExp)) {
136     S.Diag(Loc, diag::err_implied_coroutine_type_not_found)
137         << "std::experimental::coroutine_handle";
138     return QualType();
139   }
140 
141   ClassTemplateDecl *CoroHandle = Result.getAsSingle<ClassTemplateDecl>();
142   if (!CoroHandle) {
143     Result.suppressDiagnostics();
144     // We found something weird. Complain about the first thing we found.
145     NamedDecl *Found = *Result.begin();
146     S.Diag(Found->getLocation(), diag::err_malformed_std_coroutine_handle);
147     return QualType();
148   }
149 
150   // Form template argument list for coroutine_handle<Promise>.
151   TemplateArgumentListInfo Args(Loc, Loc);
152   Args.addArgument(TemplateArgumentLoc(
153       TemplateArgument(PromiseType),
154       S.Context.getTrivialTypeSourceInfo(PromiseType, Loc)));
155 
156   // Build the template-id.
157   QualType CoroHandleType =
158       S.CheckTemplateIdType(TemplateName(CoroHandle), Loc, Args);
159   if (CoroHandleType.isNull())
160     return QualType();
161   if (S.RequireCompleteType(Loc, CoroHandleType,
162                             diag::err_coroutine_type_missing_specialization))
163     return QualType();
164 
165   return CoroHandleType;
166 }
167 
168 static bool isValidCoroutineContext(Sema &S, SourceLocation Loc,
169                                     StringRef Keyword) {
170   // 'co_await' and 'co_yield' are not permitted in unevaluated operands.
171   if (S.isUnevaluatedContext()) {
172     S.Diag(Loc, diag::err_coroutine_unevaluated_context) << Keyword;
173     return false;
174   }
175 
176   // Any other usage must be within a function.
177   auto *FD = dyn_cast<FunctionDecl>(S.CurContext);
178   if (!FD) {
179     S.Diag(Loc, isa<ObjCMethodDecl>(S.CurContext)
180                     ? diag::err_coroutine_objc_method
181                     : diag::err_coroutine_outside_function) << Keyword;
182     return false;
183   }
184 
185   // An enumeration for mapping the diagnostic type to the correct diagnostic
186   // selection index.
187   enum InvalidFuncDiag {
188     DiagCtor = 0,
189     DiagDtor,
190     DiagCopyAssign,
191     DiagMoveAssign,
192     DiagMain,
193     DiagConstexpr,
194     DiagAutoRet,
195     DiagVarargs,
196   };
197   bool Diagnosed = false;
198   auto DiagInvalid = [&](InvalidFuncDiag ID) {
199     S.Diag(Loc, diag::err_coroutine_invalid_func_context) << ID << Keyword;
200     Diagnosed = true;
201     return false;
202   };
203 
204   // Diagnose when a constructor, destructor, copy/move assignment operator,
205   // or the function 'main' are declared as a coroutine.
206   auto *MD = dyn_cast<CXXMethodDecl>(FD);
207   if (MD && isa<CXXConstructorDecl>(MD))
208     return DiagInvalid(DiagCtor);
209   else if (MD && isa<CXXDestructorDecl>(MD))
210     return DiagInvalid(DiagDtor);
211   else if (MD && MD->isCopyAssignmentOperator())
212     return DiagInvalid(DiagCopyAssign);
213   else if (MD && MD->isMoveAssignmentOperator())
214     return DiagInvalid(DiagMoveAssign);
215   else if (FD->isMain())
216     return DiagInvalid(DiagMain);
217 
218   // Emit a diagnostics for each of the following conditions which is not met.
219   if (FD->isConstexpr())
220     DiagInvalid(DiagConstexpr);
221   if (FD->getReturnType()->isUndeducedType())
222     DiagInvalid(DiagAutoRet);
223   if (FD->isVariadic())
224     DiagInvalid(DiagVarargs);
225 
226   return !Diagnosed;
227 }
228 
229 static ExprResult buildOperatorCoawaitLookupExpr(Sema &SemaRef, Scope *S,
230                                                  SourceLocation Loc) {
231   DeclarationName OpName =
232       SemaRef.Context.DeclarationNames.getCXXOperatorName(OO_Coawait);
233   LookupResult Operators(SemaRef, OpName, SourceLocation(),
234                          Sema::LookupOperatorName);
235   SemaRef.LookupName(Operators, S);
236 
237   assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
238   const auto &Functions = Operators.asUnresolvedSet();
239   bool IsOverloaded =
240       Functions.size() > 1 ||
241       (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
242   Expr *CoawaitOp = UnresolvedLookupExpr::Create(
243       SemaRef.Context, /*NamingClass*/ nullptr, NestedNameSpecifierLoc(),
244       DeclarationNameInfo(OpName, Loc), /*RequiresADL*/ true, IsOverloaded,
245       Functions.begin(), Functions.end());
246   assert(CoawaitOp);
247   return CoawaitOp;
248 }
249 
250 /// Build a call to 'operator co_await' if there is a suitable operator for
251 /// the given expression.
252 static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, SourceLocation Loc,
253                                            Expr *E,
254                                            UnresolvedLookupExpr *Lookup) {
255   UnresolvedSet<16> Functions;
256   Functions.append(Lookup->decls_begin(), Lookup->decls_end());
257   return SemaRef.CreateOverloadedUnaryOp(Loc, UO_Coawait, Functions, E);
258 }
259 
260 static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, Scope *S,
261                                            SourceLocation Loc, Expr *E) {
262   ExprResult R = buildOperatorCoawaitLookupExpr(SemaRef, S, Loc);
263   if (R.isInvalid())
264     return ExprError();
265   return buildOperatorCoawaitCall(SemaRef, Loc, E,
266                                   cast<UnresolvedLookupExpr>(R.get()));
267 }
268 
269 static Expr *buildBuiltinCall(Sema &S, SourceLocation Loc, Builtin::ID Id,
270                               MultiExprArg CallArgs) {
271   StringRef Name = S.Context.BuiltinInfo.getName(Id);
272   LookupResult R(S, &S.Context.Idents.get(Name), Loc, Sema::LookupOrdinaryName);
273   S.LookupName(R, S.TUScope, /*AllowBuiltinCreation=*/true);
274 
275   auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
276   assert(BuiltInDecl && "failed to find builtin declaration");
277 
278   ExprResult DeclRef =
279       S.BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
280   assert(DeclRef.isUsable() && "Builtin reference cannot fail");
281 
282   ExprResult Call =
283       S.ActOnCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
284 
285   assert(!Call.isInvalid() && "Call to builtin cannot fail!");
286   return Call.get();
287 }
288 
289 static ExprResult buildCoroutineHandle(Sema &S, QualType PromiseType,
290                                        SourceLocation Loc) {
291   QualType CoroHandleType = lookupCoroutineHandleType(S, PromiseType, Loc);
292   if (CoroHandleType.isNull())
293     return ExprError();
294 
295   DeclContext *LookupCtx = S.computeDeclContext(CoroHandleType);
296   LookupResult Found(S, &S.PP.getIdentifierTable().get("from_address"), Loc,
297                      Sema::LookupOrdinaryName);
298   if (!S.LookupQualifiedName(Found, LookupCtx)) {
299     S.Diag(Loc, diag::err_coroutine_handle_missing_member)
300         << "from_address";
301     return ExprError();
302   }
303 
304   Expr *FramePtr =
305       buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_frame, {});
306 
307   CXXScopeSpec SS;
308   ExprResult FromAddr =
309       S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
310   if (FromAddr.isInvalid())
311     return ExprError();
312 
313   return S.ActOnCallExpr(nullptr, FromAddr.get(), Loc, FramePtr, Loc);
314 }
315 
316 struct ReadySuspendResumeResult {
317   Expr *Results[3];
318   OpaqueValueExpr *OpaqueValue;
319   bool IsInvalid;
320 };
321 
322 static ExprResult buildMemberCall(Sema &S, Expr *Base, SourceLocation Loc,
323                                   StringRef Name, MultiExprArg Args) {
324   DeclarationNameInfo NameInfo(&S.PP.getIdentifierTable().get(Name), Loc);
325 
326   // FIXME: Fix BuildMemberReferenceExpr to take a const CXXScopeSpec&.
327   CXXScopeSpec SS;
328   ExprResult Result = S.BuildMemberReferenceExpr(
329       Base, Base->getType(), Loc, /*IsPtr=*/false, SS,
330       SourceLocation(), nullptr, NameInfo, /*TemplateArgs=*/nullptr,
331       /*Scope=*/nullptr);
332   if (Result.isInvalid())
333     return ExprError();
334 
335   return S.ActOnCallExpr(nullptr, Result.get(), Loc, Args, Loc, nullptr);
336 }
337 
338 /// Build calls to await_ready, await_suspend, and await_resume for a co_await
339 /// expression.
340 static ReadySuspendResumeResult buildCoawaitCalls(Sema &S, VarDecl *CoroPromise,
341                                                   SourceLocation Loc, Expr *E) {
342   OpaqueValueExpr *Operand = new (S.Context)
343       OpaqueValueExpr(Loc, E->getType(), VK_LValue, E->getObjectKind(), E);
344 
345   // Assume invalid until we see otherwise.
346   ReadySuspendResumeResult Calls = {{}, Operand, /*IsInvalid=*/true};
347 
348   ExprResult CoroHandleRes = buildCoroutineHandle(S, CoroPromise->getType(), Loc);
349   if (CoroHandleRes.isInvalid())
350     return Calls;
351   Expr *CoroHandle = CoroHandleRes.get();
352 
353   const StringRef Funcs[] = {"await_ready", "await_suspend", "await_resume"};
354   MultiExprArg Args[] = {None, CoroHandle, None};
355   for (size_t I = 0, N = llvm::array_lengthof(Funcs); I != N; ++I) {
356     ExprResult Result = buildMemberCall(S, Operand, Loc, Funcs[I], Args[I]);
357     if (Result.isInvalid())
358       return Calls;
359     Calls.Results[I] = Result.get();
360   }
361 
362   Calls.IsInvalid = false;
363   return Calls;
364 }
365 
366 static ExprResult buildPromiseCall(Sema &S, VarDecl *Promise,
367                                    SourceLocation Loc, StringRef Name,
368                                    MultiExprArg Args) {
369 
370   // Form a reference to the promise.
371   ExprResult PromiseRef = S.BuildDeclRefExpr(
372       Promise, Promise->getType().getNonReferenceType(), VK_LValue, Loc);
373   if (PromiseRef.isInvalid())
374     return ExprError();
375 
376   return buildMemberCall(S, PromiseRef.get(), Loc, Name, Args);
377 }
378 
379 VarDecl *Sema::buildCoroutinePromise(SourceLocation Loc) {
380   assert(isa<FunctionDecl>(CurContext) && "not in a function scope");
381   auto *FD = cast<FunctionDecl>(CurContext);
382 
383   QualType T =
384       FD->getType()->isDependentType()
385           ? Context.DependentTy
386           : lookupPromiseType(*this, FD->getType()->castAs<FunctionProtoType>(),
387                               Loc, FD->getLocation());
388   if (T.isNull())
389     return nullptr;
390 
391   auto *VD = VarDecl::Create(Context, FD, FD->getLocation(), FD->getLocation(),
392                              &PP.getIdentifierTable().get("__promise"), T,
393                              Context.getTrivialTypeSourceInfo(T, Loc), SC_None);
394   CheckVariableDeclarationType(VD);
395   if (VD->isInvalidDecl())
396     return nullptr;
397   ActOnUninitializedDecl(VD);
398   assert(!VD->isInvalidDecl());
399   return VD;
400 }
401 
402 /// Check that this is a context in which a coroutine suspension can appear.
403 static FunctionScopeInfo *checkCoroutineContext(Sema &S, SourceLocation Loc,
404                                                 StringRef Keyword,
405                                                 bool IsImplicit = false) {
406   if (!isValidCoroutineContext(S, Loc, Keyword))
407     return nullptr;
408 
409   assert(isa<FunctionDecl>(S.CurContext) && "not in a function scope");
410 
411   auto *ScopeInfo = S.getCurFunction();
412   assert(ScopeInfo && "missing function scope for function");
413 
414   if (ScopeInfo->FirstCoroutineStmtLoc.isInvalid() && !IsImplicit)
415     ScopeInfo->setFirstCoroutineStmt(Loc, Keyword);
416 
417   if (ScopeInfo->CoroutinePromise)
418     return ScopeInfo;
419 
420   ScopeInfo->CoroutinePromise = S.buildCoroutinePromise(Loc);
421   if (!ScopeInfo->CoroutinePromise)
422     return nullptr;
423 
424   return ScopeInfo;
425 }
426 
427 static bool actOnCoroutineBodyStart(Sema &S, Scope *SC, SourceLocation KWLoc,
428                                     StringRef Keyword) {
429   if (!checkCoroutineContext(S, KWLoc, Keyword))
430     return false;
431   auto *ScopeInfo = S.getCurFunction();
432   assert(ScopeInfo->CoroutinePromise);
433 
434   // If we have existing coroutine statements then we have already built
435   // the initial and final suspend points.
436   if (!ScopeInfo->NeedsCoroutineSuspends)
437     return true;
438 
439   ScopeInfo->setNeedsCoroutineSuspends(false);
440 
441   auto *Fn = cast<FunctionDecl>(S.CurContext);
442   SourceLocation Loc = Fn->getLocation();
443   // Build the initial suspend point
444   auto buildSuspends = [&](StringRef Name) mutable -> StmtResult {
445     ExprResult Suspend =
446         buildPromiseCall(S, ScopeInfo->CoroutinePromise, Loc, Name, None);
447     if (Suspend.isInvalid())
448       return StmtError();
449     Suspend = buildOperatorCoawaitCall(S, SC, Loc, Suspend.get());
450     if (Suspend.isInvalid())
451       return StmtError();
452     Suspend = S.BuildResolvedCoawaitExpr(Loc, Suspend.get(),
453                                          /*IsImplicit*/ true);
454     Suspend = S.ActOnFinishFullExpr(Suspend.get());
455     if (Suspend.isInvalid()) {
456       S.Diag(Loc, diag::note_coroutine_promise_suspend_implicitly_required)
457           << ((Name == "initial_suspend") ? 0 : 1);
458       S.Diag(KWLoc, diag::note_declared_coroutine_here) << Keyword;
459       return StmtError();
460     }
461     return cast<Stmt>(Suspend.get());
462   };
463 
464   StmtResult InitSuspend = buildSuspends("initial_suspend");
465   if (InitSuspend.isInvalid())
466     return true;
467 
468   StmtResult FinalSuspend = buildSuspends("final_suspend");
469   if (FinalSuspend.isInvalid())
470     return true;
471 
472   ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());
473 
474   return true;
475 }
476 
477 ExprResult Sema::ActOnCoawaitExpr(Scope *S, SourceLocation Loc, Expr *E) {
478   if (!actOnCoroutineBodyStart(*this, S, Loc, "co_await")) {
479     CorrectDelayedTyposInExpr(E);
480     return ExprError();
481   }
482 
483   if (E->getType()->isPlaceholderType()) {
484     ExprResult R = CheckPlaceholderExpr(E);
485     if (R.isInvalid()) return ExprError();
486     E = R.get();
487   }
488   ExprResult Lookup = buildOperatorCoawaitLookupExpr(*this, S, Loc);
489   if (Lookup.isInvalid())
490     return ExprError();
491   return BuildUnresolvedCoawaitExpr(Loc, E,
492                                    cast<UnresolvedLookupExpr>(Lookup.get()));
493 }
494 
495 ExprResult Sema::BuildUnresolvedCoawaitExpr(SourceLocation Loc, Expr *E,
496                                             UnresolvedLookupExpr *Lookup) {
497   auto *FSI = checkCoroutineContext(*this, Loc, "co_await");
498   if (!FSI)
499     return ExprError();
500 
501   if (E->getType()->isPlaceholderType()) {
502     ExprResult R = CheckPlaceholderExpr(E);
503     if (R.isInvalid())
504       return ExprError();
505     E = R.get();
506   }
507 
508   auto *Promise = FSI->CoroutinePromise;
509   if (Promise->getType()->isDependentType()) {
510     Expr *Res =
511         new (Context) DependentCoawaitExpr(Loc, Context.DependentTy, E, Lookup);
512     return Res;
513   }
514 
515   auto *RD = Promise->getType()->getAsCXXRecordDecl();
516   if (lookupMember(*this, "await_transform", RD, Loc)) {
517     ExprResult R = buildPromiseCall(*this, Promise, Loc, "await_transform", E);
518     if (R.isInvalid()) {
519       Diag(Loc,
520            diag::note_coroutine_promise_implicit_await_transform_required_here)
521           << E->getSourceRange();
522       return ExprError();
523     }
524     E = R.get();
525   }
526   ExprResult Awaitable = buildOperatorCoawaitCall(*this, Loc, E, Lookup);
527   if (Awaitable.isInvalid())
528     return ExprError();
529 
530   return BuildResolvedCoawaitExpr(Loc, Awaitable.get());
531 }
532 
533 ExprResult Sema::BuildResolvedCoawaitExpr(SourceLocation Loc, Expr *E,
534                                   bool IsImplicit) {
535   auto *Coroutine = checkCoroutineContext(*this, Loc, "co_await", IsImplicit);
536   if (!Coroutine)
537     return ExprError();
538 
539   if (E->getType()->isPlaceholderType()) {
540     ExprResult R = CheckPlaceholderExpr(E);
541     if (R.isInvalid()) return ExprError();
542     E = R.get();
543   }
544 
545   if (E->getType()->isDependentType()) {
546     Expr *Res = new (Context)
547         CoawaitExpr(Loc, Context.DependentTy, E, IsImplicit);
548     return Res;
549   }
550 
551   // If the expression is a temporary, materialize it as an lvalue so that we
552   // can use it multiple times.
553   if (E->getValueKind() == VK_RValue)
554     E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
555 
556   // Build the await_ready, await_suspend, await_resume calls.
557   ReadySuspendResumeResult RSS =
558       buildCoawaitCalls(*this, Coroutine->CoroutinePromise, Loc, E);
559   if (RSS.IsInvalid)
560     return ExprError();
561 
562   Expr *Res =
563       new (Context) CoawaitExpr(Loc, E, RSS.Results[0], RSS.Results[1],
564                                 RSS.Results[2], RSS.OpaqueValue, IsImplicit);
565 
566   return Res;
567 }
568 
569 ExprResult Sema::ActOnCoyieldExpr(Scope *S, SourceLocation Loc, Expr *E) {
570   if (!actOnCoroutineBodyStart(*this, S, Loc, "co_yield")) {
571     CorrectDelayedTyposInExpr(E);
572     return ExprError();
573   }
574 
575   // Build yield_value call.
576   ExprResult Awaitable = buildPromiseCall(
577       *this, getCurFunction()->CoroutinePromise, Loc, "yield_value", E);
578   if (Awaitable.isInvalid())
579     return ExprError();
580 
581   // Build 'operator co_await' call.
582   Awaitable = buildOperatorCoawaitCall(*this, S, Loc, Awaitable.get());
583   if (Awaitable.isInvalid())
584     return ExprError();
585 
586   return BuildCoyieldExpr(Loc, Awaitable.get());
587 }
588 ExprResult Sema::BuildCoyieldExpr(SourceLocation Loc, Expr *E) {
589   auto *Coroutine = checkCoroutineContext(*this, Loc, "co_yield");
590   if (!Coroutine)
591     return ExprError();
592 
593   if (E->getType()->isPlaceholderType()) {
594     ExprResult R = CheckPlaceholderExpr(E);
595     if (R.isInvalid()) return ExprError();
596     E = R.get();
597   }
598 
599   if (E->getType()->isDependentType()) {
600     Expr *Res = new (Context) CoyieldExpr(Loc, Context.DependentTy, E);
601     return Res;
602   }
603 
604   // If the expression is a temporary, materialize it as an lvalue so that we
605   // can use it multiple times.
606   if (E->getValueKind() == VK_RValue)
607     E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
608 
609   // Build the await_ready, await_suspend, await_resume calls.
610   ReadySuspendResumeResult RSS =
611       buildCoawaitCalls(*this, Coroutine->CoroutinePromise, Loc, E);
612   if (RSS.IsInvalid)
613     return ExprError();
614 
615   Expr *Res = new (Context) CoyieldExpr(Loc, E, RSS.Results[0], RSS.Results[1],
616                                         RSS.Results[2], RSS.OpaqueValue);
617 
618   return Res;
619 }
620 
621 StmtResult Sema::ActOnCoreturnStmt(Scope *S, SourceLocation Loc, Expr *E) {
622   if (!actOnCoroutineBodyStart(*this, S, Loc, "co_return")) {
623     CorrectDelayedTyposInExpr(E);
624     return StmtError();
625   }
626   return BuildCoreturnStmt(Loc, E);
627 }
628 
629 StmtResult Sema::BuildCoreturnStmt(SourceLocation Loc, Expr *E,
630                                    bool IsImplicit) {
631   auto *FSI = checkCoroutineContext(*this, Loc, "co_return", IsImplicit);
632   if (!FSI)
633     return StmtError();
634 
635   if (E && E->getType()->isPlaceholderType() &&
636       !E->getType()->isSpecificPlaceholderType(BuiltinType::Overload)) {
637     ExprResult R = CheckPlaceholderExpr(E);
638     if (R.isInvalid()) return StmtError();
639     E = R.get();
640   }
641 
642   // FIXME: If the operand is a reference to a variable that's about to go out
643   // of scope, we should treat the operand as an xvalue for this overload
644   // resolution.
645   VarDecl *Promise = FSI->CoroutinePromise;
646   ExprResult PC;
647   if (E && (isa<InitListExpr>(E) || !E->getType()->isVoidType())) {
648     PC = buildPromiseCall(*this, Promise, Loc, "return_value", E);
649   } else {
650     E = MakeFullDiscardedValueExpr(E).get();
651     PC = buildPromiseCall(*this, Promise, Loc, "return_void", None);
652   }
653   if (PC.isInvalid())
654     return StmtError();
655 
656   Expr *PCE = ActOnFinishFullExpr(PC.get()).get();
657 
658   Stmt *Res = new (Context) CoreturnStmt(Loc, E, PCE, IsImplicit);
659   return Res;
660 }
661 
662 /// Look up the std::nothrow object.
663 static Expr *buildStdNoThrowDeclRef(Sema &S, SourceLocation Loc) {
664   NamespaceDecl *Std = S.getStdNamespace();
665   assert(Std && "Should already be diagnosed");
666 
667   LookupResult Result(S, &S.PP.getIdentifierTable().get("nothrow"), Loc,
668                       Sema::LookupOrdinaryName);
669   if (!S.LookupQualifiedName(Result, Std)) {
670     // FIXME: <experimental/coroutine> should have been included already.
671     // If we require it to include <new> then this diagnostic is no longer
672     // needed.
673     S.Diag(Loc, diag::err_implicit_coroutine_std_nothrow_type_not_found);
674     return nullptr;
675   }
676 
677   // FIXME: Mark the variable as ODR used. This currently does not work
678   // likely due to the scope at in which this function is called.
679   auto *VD = Result.getAsSingle<VarDecl>();
680   if (!VD) {
681     Result.suppressDiagnostics();
682     // We found something weird. Complain about the first thing we found.
683     NamedDecl *Found = *Result.begin();
684     S.Diag(Found->getLocation(), diag::err_malformed_std_nothrow);
685     return nullptr;
686   }
687 
688   ExprResult DR = S.BuildDeclRefExpr(VD, VD->getType(), VK_LValue, Loc);
689   if (DR.isInvalid())
690     return nullptr;
691 
692   return DR.get();
693 }
694 
695 // Find an appropriate delete for the promise.
696 static FunctionDecl *findDeleteForPromise(Sema &S, SourceLocation Loc,
697                                           QualType PromiseType) {
698   FunctionDecl *OperatorDelete = nullptr;
699 
700   DeclarationName DeleteName =
701       S.Context.DeclarationNames.getCXXOperatorName(OO_Delete);
702 
703   auto *PointeeRD = PromiseType->getAsCXXRecordDecl();
704   assert(PointeeRD && "PromiseType must be a CxxRecordDecl type");
705 
706   if (S.FindDeallocationFunction(Loc, PointeeRD, DeleteName, OperatorDelete))
707     return nullptr;
708 
709   if (!OperatorDelete) {
710     // Look for a global declaration.
711     const bool CanProvideSize = S.isCompleteType(Loc, PromiseType);
712     const bool Overaligned = false;
713     OperatorDelete = S.FindUsualDeallocationFunction(Loc, CanProvideSize,
714                                                      Overaligned, DeleteName);
715   }
716   S.MarkFunctionReferenced(Loc, OperatorDelete);
717   return OperatorDelete;
718 }
719 
720 
721 void Sema::CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body) {
722   FunctionScopeInfo *Fn = getCurFunction();
723   assert(Fn && Fn->CoroutinePromise && "not a coroutine");
724 
725   if (!Body) {
726     assert(FD->isInvalidDecl() &&
727            "a null body is only allowed for invalid declarations");
728     return;
729   }
730 
731   if (isa<CoroutineBodyStmt>(Body)) {
732     // FIXME(EricWF): Nothing todo. the body is already a transformed coroutine
733     // body statement.
734     return;
735   }
736 
737   // Coroutines [stmt.return]p1:
738   //   A return statement shall not appear in a coroutine.
739   if (Fn->FirstReturnLoc.isValid()) {
740     assert(Fn->FirstCoroutineStmtLoc.isValid() &&
741                    "first coroutine location not set");
742     Diag(Fn->FirstReturnLoc, diag::err_return_in_coroutine);
743     Diag(Fn->FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
744             << Fn->getFirstCoroutineStmtKeyword();
745   }
746   CoroutineStmtBuilder Builder(*this, *FD, *Fn, Body);
747   if (Builder.isInvalid() || !Builder.buildStatements())
748     return FD->setInvalidDecl();
749 
750   // Build body for the coroutine wrapper statement.
751   Body = CoroutineBodyStmt::Create(Context, Builder);
752 }
753 
754 CoroutineStmtBuilder::CoroutineStmtBuilder(Sema &S, FunctionDecl &FD,
755                                            sema::FunctionScopeInfo &Fn,
756                                            Stmt *Body)
757     : S(S), FD(FD), Fn(Fn), Loc(FD.getLocation()),
758       IsPromiseDependentType(
759           !Fn.CoroutinePromise ||
760           Fn.CoroutinePromise->getType()->isDependentType()) {
761   this->Body = Body;
762   if (!IsPromiseDependentType) {
763     PromiseRecordDecl = Fn.CoroutinePromise->getType()->getAsCXXRecordDecl();
764     assert(PromiseRecordDecl && "Type should have already been checked");
765   }
766   this->IsValid = makePromiseStmt() && makeInitialAndFinalSuspend();
767 }
768 
769 bool CoroutineStmtBuilder::buildStatements() {
770   assert(this->IsValid && "coroutine already invalid");
771   this->IsValid = makeReturnObject() && makeParamMoves();
772   if (this->IsValid && !IsPromiseDependentType)
773     buildDependentStatements();
774   return this->IsValid;
775 }
776 
777 bool CoroutineStmtBuilder::buildDependentStatements() {
778   assert(this->IsValid && "coroutine already invalid");
779   assert(!this->IsPromiseDependentType &&
780          "coroutine cannot have a dependent promise type");
781   this->IsValid = makeOnException() && makeOnFallthrough() &&
782                   makeGroDeclAndReturnStmt() && makeReturnOnAllocFailure() &&
783                   makeNewAndDeleteExpr();
784   return this->IsValid;
785 }
786 
787 bool CoroutineStmtBuilder::makePromiseStmt() {
788   // Form a declaration statement for the promise declaration, so that AST
789   // visitors can more easily find it.
790   StmtResult PromiseStmt =
791       S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(Fn.CoroutinePromise), Loc, Loc);
792   if (PromiseStmt.isInvalid())
793     return false;
794 
795   this->Promise = PromiseStmt.get();
796   return true;
797 }
798 
799 bool CoroutineStmtBuilder::makeInitialAndFinalSuspend() {
800   if (Fn.hasInvalidCoroutineSuspends())
801     return false;
802   this->InitialSuspend = cast<Expr>(Fn.CoroutineSuspends.first);
803   this->FinalSuspend = cast<Expr>(Fn.CoroutineSuspends.second);
804   return true;
805 }
806 
807 static bool diagReturnOnAllocFailure(Sema &S, Expr *E,
808                                      CXXRecordDecl *PromiseRecordDecl,
809                                      FunctionScopeInfo &Fn) {
810   auto Loc = E->getExprLoc();
811   if (auto *DeclRef = dyn_cast_or_null<DeclRefExpr>(E)) {
812     auto *Decl = DeclRef->getDecl();
813     if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Decl)) {
814       if (Method->isStatic())
815         return true;
816       else
817         Loc = Decl->getLocation();
818     }
819   }
820 
821   S.Diag(
822       Loc,
823       diag::err_coroutine_promise_get_return_object_on_allocation_failure)
824       << PromiseRecordDecl;
825   S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
826       << Fn.getFirstCoroutineStmtKeyword();
827   return false;
828 }
829 
830 bool CoroutineStmtBuilder::makeReturnOnAllocFailure() {
831   assert(!IsPromiseDependentType &&
832          "cannot make statement while the promise type is dependent");
833 
834   // [dcl.fct.def.coroutine]/8
835   // The unqualified-id get_return_object_on_allocation_failure is looked up in
836   // the scope of class P by class member access lookup (3.4.5). ...
837   // If an allocation function returns nullptr, ... the coroutine return value
838   // is obtained by a call to ... get_return_object_on_allocation_failure().
839 
840   DeclarationName DN =
841       S.PP.getIdentifierInfo("get_return_object_on_allocation_failure");
842   LookupResult Found(S, DN, Loc, Sema::LookupMemberName);
843   if (!S.LookupQualifiedName(Found, PromiseRecordDecl))
844     return true;
845 
846   CXXScopeSpec SS;
847   ExprResult DeclNameExpr =
848       S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
849   if (DeclNameExpr.isInvalid())
850     return false;
851 
852   if (!diagReturnOnAllocFailure(S, DeclNameExpr.get(), PromiseRecordDecl, Fn))
853     return false;
854 
855   ExprResult ReturnObjectOnAllocationFailure =
856       S.ActOnCallExpr(nullptr, DeclNameExpr.get(), Loc, {}, Loc);
857   if (ReturnObjectOnAllocationFailure.isInvalid())
858     return false;
859 
860   StmtResult ReturnStmt =
861       S.BuildReturnStmt(Loc, ReturnObjectOnAllocationFailure.get());
862   if (ReturnStmt.isInvalid()) {
863     S.Diag(Found.getFoundDecl()->getLocation(),
864            diag::note_promise_member_declared_here)
865         << DN.getAsString();
866     S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
867         << Fn.getFirstCoroutineStmtKeyword();
868     return false;
869   }
870 
871   this->ReturnStmtOnAllocFailure = ReturnStmt.get();
872   return true;
873 }
874 
875 bool CoroutineStmtBuilder::makeNewAndDeleteExpr() {
876   // Form and check allocation and deallocation calls.
877   assert(!IsPromiseDependentType &&
878          "cannot make statement while the promise type is dependent");
879   QualType PromiseType = Fn.CoroutinePromise->getType();
880 
881   if (S.RequireCompleteType(Loc, PromiseType, diag::err_incomplete_type))
882     return false;
883 
884   const bool RequiresNoThrowAlloc = ReturnStmtOnAllocFailure != nullptr;
885 
886   // FIXME: Add support for stateful allocators.
887 
888   FunctionDecl *OperatorNew = nullptr;
889   FunctionDecl *OperatorDelete = nullptr;
890   FunctionDecl *UnusedResult = nullptr;
891   bool PassAlignment = false;
892   SmallVector<Expr *, 1> PlacementArgs;
893 
894   S.FindAllocationFunctions(Loc, SourceRange(),
895                             /*UseGlobal*/ false, PromiseType,
896                             /*isArray*/ false, PassAlignment, PlacementArgs,
897                             OperatorNew, UnusedResult);
898 
899   bool IsGlobalOverload =
900       OperatorNew && !isa<CXXRecordDecl>(OperatorNew->getDeclContext());
901   // If we didn't find a class-local new declaration and non-throwing new
902   // was is required then we need to lookup the non-throwing global operator
903   // instead.
904   if (RequiresNoThrowAlloc && (!OperatorNew || IsGlobalOverload)) {
905     auto *StdNoThrow = buildStdNoThrowDeclRef(S, Loc);
906     if (!StdNoThrow)
907       return false;
908     PlacementArgs = {StdNoThrow};
909     OperatorNew = nullptr;
910     S.FindAllocationFunctions(Loc, SourceRange(),
911                               /*UseGlobal*/ true, PromiseType,
912                               /*isArray*/ false, PassAlignment, PlacementArgs,
913                               OperatorNew, UnusedResult);
914   }
915 
916   assert(OperatorNew && "expected definition of operator new to be found");
917 
918   if (RequiresNoThrowAlloc) {
919     const auto *FT = OperatorNew->getType()->getAs<FunctionProtoType>();
920     if (!FT->isNothrow(S.Context, /*ResultIfDependent*/ false)) {
921       S.Diag(OperatorNew->getLocation(),
922              diag::err_coroutine_promise_new_requires_nothrow)
923           << OperatorNew;
924       S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
925           << OperatorNew;
926       return false;
927     }
928   }
929 
930   if ((OperatorDelete = findDeleteForPromise(S, Loc, PromiseType)) == nullptr)
931     return false;
932 
933   Expr *FramePtr =
934       buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_frame, {});
935 
936   Expr *FrameSize =
937       buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_size, {});
938 
939   // Make new call.
940 
941   ExprResult NewRef =
942       S.BuildDeclRefExpr(OperatorNew, OperatorNew->getType(), VK_LValue, Loc);
943   if (NewRef.isInvalid())
944     return false;
945 
946   SmallVector<Expr *, 2> NewArgs(1, FrameSize);
947   for (auto Arg : PlacementArgs)
948     NewArgs.push_back(Arg);
949 
950   ExprResult NewExpr =
951       S.ActOnCallExpr(S.getCurScope(), NewRef.get(), Loc, NewArgs, Loc);
952   NewExpr = S.ActOnFinishFullExpr(NewExpr.get());
953   if (NewExpr.isInvalid())
954     return false;
955 
956   // Make delete call.
957 
958   QualType OpDeleteQualType = OperatorDelete->getType();
959 
960   ExprResult DeleteRef =
961       S.BuildDeclRefExpr(OperatorDelete, OpDeleteQualType, VK_LValue, Loc);
962   if (DeleteRef.isInvalid())
963     return false;
964 
965   Expr *CoroFree =
966       buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_free, {FramePtr});
967 
968   SmallVector<Expr *, 2> DeleteArgs{CoroFree};
969 
970   // Check if we need to pass the size.
971   const auto *OpDeleteType =
972       OpDeleteQualType.getTypePtr()->getAs<FunctionProtoType>();
973   if (OpDeleteType->getNumParams() > 1)
974     DeleteArgs.push_back(FrameSize);
975 
976   ExprResult DeleteExpr =
977       S.ActOnCallExpr(S.getCurScope(), DeleteRef.get(), Loc, DeleteArgs, Loc);
978   DeleteExpr = S.ActOnFinishFullExpr(DeleteExpr.get());
979   if (DeleteExpr.isInvalid())
980     return false;
981 
982   this->Allocate = NewExpr.get();
983   this->Deallocate = DeleteExpr.get();
984 
985   return true;
986 }
987 
988 bool CoroutineStmtBuilder::makeOnFallthrough() {
989   assert(!IsPromiseDependentType &&
990          "cannot make statement while the promise type is dependent");
991 
992   // [dcl.fct.def.coroutine]/4
993   // The unqualified-ids 'return_void' and 'return_value' are looked up in
994   // the scope of class P. If both are found, the program is ill-formed.
995   const bool HasRVoid = lookupMember(S, "return_void", PromiseRecordDecl, Loc);
996   const bool HasRValue = lookupMember(S, "return_value", PromiseRecordDecl, Loc);
997 
998   StmtResult Fallthrough;
999   if (HasRVoid && HasRValue) {
1000     // FIXME Improve this diagnostic
1001     S.Diag(FD.getLocation(), diag::err_coroutine_promise_return_ill_formed)
1002         << PromiseRecordDecl;
1003     return false;
1004   } else if (HasRVoid) {
1005     // If the unqualified-id return_void is found, flowing off the end of a
1006     // coroutine is equivalent to a co_return with no operand. Otherwise,
1007     // flowing off the end of a coroutine results in undefined behavior.
1008     Fallthrough = S.BuildCoreturnStmt(FD.getLocation(), nullptr,
1009                                       /*IsImplicit*/false);
1010     Fallthrough = S.ActOnFinishFullStmt(Fallthrough.get());
1011     if (Fallthrough.isInvalid())
1012       return false;
1013   }
1014 
1015   this->OnFallthrough = Fallthrough.get();
1016   return true;
1017 }
1018 
1019 bool CoroutineStmtBuilder::makeOnException() {
1020   // Try to form 'p.unhandled_exception();'
1021   assert(!IsPromiseDependentType &&
1022          "cannot make statement while the promise type is dependent");
1023 
1024   const bool RequireUnhandledException = S.getLangOpts().CXXExceptions;
1025 
1026   if (!lookupMember(S, "unhandled_exception", PromiseRecordDecl, Loc)) {
1027     auto DiagID =
1028         RequireUnhandledException
1029             ? diag::err_coroutine_promise_unhandled_exception_required
1030             : diag::
1031                   warn_coroutine_promise_unhandled_exception_required_with_exceptions;
1032     S.Diag(Loc, DiagID) << PromiseRecordDecl;
1033     return !RequireUnhandledException;
1034   }
1035 
1036   // If exceptions are disabled, don't try to build OnException.
1037   if (!S.getLangOpts().CXXExceptions)
1038     return true;
1039 
1040   ExprResult UnhandledException = buildPromiseCall(S, Fn.CoroutinePromise, Loc,
1041                                                    "unhandled_exception", None);
1042   UnhandledException = S.ActOnFinishFullExpr(UnhandledException.get(), Loc);
1043   if (UnhandledException.isInvalid())
1044     return false;
1045 
1046   // Since the body of the coroutine will be wrapped in try-catch, it will
1047   // be incompatible with SEH __try if present in a function.
1048   if (!S.getLangOpts().Borland && Fn.FirstSEHTryLoc.isValid()) {
1049     S.Diag(Fn.FirstSEHTryLoc, diag::err_seh_in_a_coroutine_with_cxx_exceptions);
1050     S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1051         << Fn.getFirstCoroutineStmtKeyword();
1052     return false;
1053   }
1054 
1055   this->OnException = UnhandledException.get();
1056   return true;
1057 }
1058 
1059 bool CoroutineStmtBuilder::makeReturnObject() {
1060   // Build implicit 'p.get_return_object()' expression and form initialization
1061   // of return type from it.
1062   ExprResult ReturnObject =
1063       buildPromiseCall(S, Fn.CoroutinePromise, Loc, "get_return_object", None);
1064   if (ReturnObject.isInvalid())
1065     return false;
1066 
1067   this->ReturnValue = ReturnObject.get();
1068   return true;
1069 }
1070 
1071 static void noteMemberDeclaredHere(Sema &S, Expr *E, FunctionScopeInfo &Fn) {
1072   if (auto *MbrRef = dyn_cast<CXXMemberCallExpr>(E)) {
1073     auto *MethodDecl = MbrRef->getMethodDecl();
1074     S.Diag(MethodDecl->getLocation(), diag::note_promise_member_declared_here)
1075         << MethodDecl->getName();
1076   }
1077   S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1078       << Fn.getFirstCoroutineStmtKeyword();
1079 }
1080 
1081 bool CoroutineStmtBuilder::makeGroDeclAndReturnStmt() {
1082   assert(!IsPromiseDependentType &&
1083          "cannot make statement while the promise type is dependent");
1084   assert(this->ReturnValue && "ReturnValue must be already formed");
1085 
1086   QualType const GroType = this->ReturnValue->getType();
1087   assert(!GroType->isDependentType() &&
1088          "get_return_object type must no longer be dependent");
1089 
1090   QualType const FnRetType = FD.getReturnType();
1091   assert(!FnRetType->isDependentType() &&
1092          "get_return_object type must no longer be dependent");
1093 
1094   if (FnRetType->isVoidType()) {
1095     ExprResult Res = S.ActOnFinishFullExpr(this->ReturnValue, Loc);
1096     if (Res.isInvalid())
1097       return false;
1098 
1099     this->ResultDecl = Res.get();
1100     return true;
1101   }
1102 
1103   if (GroType->isVoidType()) {
1104     // Trigger a nice error message.
1105     InitializedEntity Entity =
1106         InitializedEntity::InitializeResult(Loc, FnRetType, false);
1107     S.PerformMoveOrCopyInitialization(Entity, nullptr, FnRetType, ReturnValue);
1108     noteMemberDeclaredHere(S, ReturnValue, Fn);
1109     return false;
1110   }
1111 
1112   auto *GroDecl = VarDecl::Create(
1113       S.Context, &FD, FD.getLocation(), FD.getLocation(),
1114       &S.PP.getIdentifierTable().get("__coro_gro"), GroType,
1115       S.Context.getTrivialTypeSourceInfo(GroType, Loc), SC_None);
1116 
1117   S.CheckVariableDeclarationType(GroDecl);
1118   if (GroDecl->isInvalidDecl())
1119     return false;
1120 
1121   InitializedEntity Entity = InitializedEntity::InitializeVariable(GroDecl);
1122   ExprResult Res = S.PerformMoveOrCopyInitialization(Entity, nullptr, GroType,
1123                                                      this->ReturnValue);
1124   if (Res.isInvalid())
1125     return false;
1126 
1127   Res = S.ActOnFinishFullExpr(Res.get());
1128   if (Res.isInvalid())
1129     return false;
1130 
1131   if (GroType == FnRetType) {
1132     GroDecl->setNRVOVariable(true);
1133   }
1134 
1135   S.AddInitializerToDecl(GroDecl, Res.get(),
1136                          /*DirectInit=*/false);
1137 
1138   S.FinalizeDeclaration(GroDecl);
1139 
1140   // Form a declaration statement for the return declaration, so that AST
1141   // visitors can more easily find it.
1142   StmtResult GroDeclStmt =
1143       S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(GroDecl), Loc, Loc);
1144   if (GroDeclStmt.isInvalid())
1145     return false;
1146 
1147   this->ResultDecl = GroDeclStmt.get();
1148 
1149   ExprResult declRef = S.BuildDeclRefExpr(GroDecl, GroType, VK_LValue, Loc);
1150   if (declRef.isInvalid())
1151     return false;
1152 
1153   StmtResult ReturnStmt = S.BuildReturnStmt(Loc, declRef.get());
1154   if (ReturnStmt.isInvalid()) {
1155     noteMemberDeclaredHere(S, ReturnValue, Fn);
1156     return false;
1157   }
1158 
1159   this->ReturnStmt = ReturnStmt.get();
1160   return true;
1161 }
1162 
1163 bool CoroutineStmtBuilder::makeParamMoves() {
1164   // FIXME: Perform move-initialization of parameters into frame-local copies.
1165   return true;
1166 }
1167 
1168 StmtResult Sema::BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
1169   CoroutineBodyStmt *Res = CoroutineBodyStmt::Create(Context, Args);
1170   if (!Res)
1171     return StmtError();
1172   return Res;
1173 }
1174