1 //===-- SemaCoroutine.cpp - Semantic Analysis for Coroutines --------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for C++ Coroutines.
10 //
11 //  This file contains references to sections of the Coroutines TS, which
12 //  can be found at http://wg21.link/coroutines.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "CoroutineStmtBuilder.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/Decl.h"
19 #include "clang/AST/ExprCXX.h"
20 #include "clang/AST/StmtCXX.h"
21 #include "clang/Lex/Preprocessor.h"
22 #include "clang/Sema/Initialization.h"
23 #include "clang/Sema/Overload.h"
24 #include "clang/Sema/ScopeInfo.h"
25 #include "clang/Sema/SemaInternal.h"
26 
27 using namespace clang;
28 using namespace sema;
29 
30 static LookupResult lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD,
31                                  SourceLocation Loc, bool &Res) {
32   DeclarationName DN = S.PP.getIdentifierInfo(Name);
33   LookupResult LR(S, DN, Loc, Sema::LookupMemberName);
34   // Suppress diagnostics when a private member is selected. The same warnings
35   // will be produced again when building the call.
36   LR.suppressDiagnostics();
37   Res = S.LookupQualifiedName(LR, RD);
38   return LR;
39 }
40 
41 static bool lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD,
42                          SourceLocation Loc) {
43   bool Res;
44   lookupMember(S, Name, RD, Loc, Res);
45   return Res;
46 }
47 
48 /// Look up the std::coroutine_traits<...>::promise_type for the given
49 /// function type.
50 static QualType lookupPromiseType(Sema &S, const FunctionDecl *FD,
51                                   SourceLocation KwLoc) {
52   const FunctionProtoType *FnType = FD->getType()->castAs<FunctionProtoType>();
53   const SourceLocation FuncLoc = FD->getLocation();
54   // FIXME: Cache std::coroutine_traits once we've found it.
55   NamespaceDecl *StdExp = S.lookupStdExperimentalNamespace();
56   if (!StdExp) {
57     S.Diag(KwLoc, diag::err_implied_coroutine_type_not_found)
58         << "std::experimental::coroutine_traits";
59     return QualType();
60   }
61 
62   ClassTemplateDecl *CoroTraits = S.lookupCoroutineTraits(KwLoc, FuncLoc);
63   if (!CoroTraits) {
64     return QualType();
65   }
66 
67   // Form template argument list for coroutine_traits<R, P1, P2, ...> according
68   // to [dcl.fct.def.coroutine]3
69   TemplateArgumentListInfo Args(KwLoc, KwLoc);
70   auto AddArg = [&](QualType T) {
71     Args.addArgument(TemplateArgumentLoc(
72         TemplateArgument(T), S.Context.getTrivialTypeSourceInfo(T, KwLoc)));
73   };
74   AddArg(FnType->getReturnType());
75   // If the function is a non-static member function, add the type
76   // of the implicit object parameter before the formal parameters.
77   if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
78     if (MD->isInstance()) {
79       // [over.match.funcs]4
80       // For non-static member functions, the type of the implicit object
81       // parameter is
82       //  -- "lvalue reference to cv X" for functions declared without a
83       //      ref-qualifier or with the & ref-qualifier
84       //  -- "rvalue reference to cv X" for functions declared with the &&
85       //      ref-qualifier
86       QualType T = MD->getThisType()->getAs<PointerType>()->getPointeeType();
87       T = FnType->getRefQualifier() == RQ_RValue
88               ? S.Context.getRValueReferenceType(T)
89               : S.Context.getLValueReferenceType(T, /*SpelledAsLValue*/ true);
90       AddArg(T);
91     }
92   }
93   for (QualType T : FnType->getParamTypes())
94     AddArg(T);
95 
96   // Build the template-id.
97   QualType CoroTrait =
98       S.CheckTemplateIdType(TemplateName(CoroTraits), KwLoc, Args);
99   if (CoroTrait.isNull())
100     return QualType();
101   if (S.RequireCompleteType(KwLoc, CoroTrait,
102                             diag::err_coroutine_type_missing_specialization))
103     return QualType();
104 
105   auto *RD = CoroTrait->getAsCXXRecordDecl();
106   assert(RD && "specialization of class template is not a class?");
107 
108   // Look up the ::promise_type member.
109   LookupResult R(S, &S.PP.getIdentifierTable().get("promise_type"), KwLoc,
110                  Sema::LookupOrdinaryName);
111   S.LookupQualifiedName(R, RD);
112   auto *Promise = R.getAsSingle<TypeDecl>();
113   if (!Promise) {
114     S.Diag(FuncLoc,
115            diag::err_implied_std_coroutine_traits_promise_type_not_found)
116         << RD;
117     return QualType();
118   }
119   // The promise type is required to be a class type.
120   QualType PromiseType = S.Context.getTypeDeclType(Promise);
121 
122   auto buildElaboratedType = [&]() {
123     auto *NNS = NestedNameSpecifier::Create(S.Context, nullptr, StdExp);
124     NNS = NestedNameSpecifier::Create(S.Context, NNS, false,
125                                       CoroTrait.getTypePtr());
126     return S.Context.getElaboratedType(ETK_None, NNS, PromiseType);
127   };
128 
129   if (!PromiseType->getAsCXXRecordDecl()) {
130     S.Diag(FuncLoc,
131            diag::err_implied_std_coroutine_traits_promise_type_not_class)
132         << buildElaboratedType();
133     return QualType();
134   }
135   if (S.RequireCompleteType(FuncLoc, buildElaboratedType(),
136                             diag::err_coroutine_promise_type_incomplete))
137     return QualType();
138 
139   return PromiseType;
140 }
141 
142 /// Look up the std::experimental::coroutine_handle<PromiseType>.
143 static QualType lookupCoroutineHandleType(Sema &S, QualType PromiseType,
144                                           SourceLocation Loc) {
145   if (PromiseType.isNull())
146     return QualType();
147 
148   NamespaceDecl *StdExp = S.lookupStdExperimentalNamespace();
149   assert(StdExp && "Should already be diagnosed");
150 
151   LookupResult Result(S, &S.PP.getIdentifierTable().get("coroutine_handle"),
152                       Loc, Sema::LookupOrdinaryName);
153   if (!S.LookupQualifiedName(Result, StdExp)) {
154     S.Diag(Loc, diag::err_implied_coroutine_type_not_found)
155         << "std::experimental::coroutine_handle";
156     return QualType();
157   }
158 
159   ClassTemplateDecl *CoroHandle = Result.getAsSingle<ClassTemplateDecl>();
160   if (!CoroHandle) {
161     Result.suppressDiagnostics();
162     // We found something weird. Complain about the first thing we found.
163     NamedDecl *Found = *Result.begin();
164     S.Diag(Found->getLocation(), diag::err_malformed_std_coroutine_handle);
165     return QualType();
166   }
167 
168   // Form template argument list for coroutine_handle<Promise>.
169   TemplateArgumentListInfo Args(Loc, Loc);
170   Args.addArgument(TemplateArgumentLoc(
171       TemplateArgument(PromiseType),
172       S.Context.getTrivialTypeSourceInfo(PromiseType, Loc)));
173 
174   // Build the template-id.
175   QualType CoroHandleType =
176       S.CheckTemplateIdType(TemplateName(CoroHandle), Loc, Args);
177   if (CoroHandleType.isNull())
178     return QualType();
179   if (S.RequireCompleteType(Loc, CoroHandleType,
180                             diag::err_coroutine_type_missing_specialization))
181     return QualType();
182 
183   return CoroHandleType;
184 }
185 
186 static bool isValidCoroutineContext(Sema &S, SourceLocation Loc,
187                                     StringRef Keyword) {
188   // 'co_await' and 'co_yield' are not permitted in unevaluated operands,
189   // such as subexpressions of \c sizeof.
190   //
191   // [expr.await]p2, emphasis added: "An await-expression shall appear only in
192   // a *potentially evaluated* expression within the compound-statement of a
193   // function-body outside of a handler [...] A context within a function where
194   // an await-expression can appear is called a suspension context of the
195   // function." And per [expr.yield]p1: "A yield-expression shall appear only
196   // within a suspension context of a function."
197   if (S.isUnevaluatedContext()) {
198     S.Diag(Loc, diag::err_coroutine_unevaluated_context) << Keyword;
199     return false;
200   }
201 
202   // Per [expr.await]p2, any other usage must be within a function.
203   // FIXME: This also covers [expr.await]p2: "An await-expression shall not
204   // appear in a default argument." But the diagnostic QoI here could be
205   // improved to inform the user that default arguments specifically are not
206   // allowed.
207   auto *FD = dyn_cast<FunctionDecl>(S.CurContext);
208   if (!FD) {
209     S.Diag(Loc, isa<ObjCMethodDecl>(S.CurContext)
210                     ? diag::err_coroutine_objc_method
211                     : diag::err_coroutine_outside_function) << Keyword;
212     return false;
213   }
214 
215   // An enumeration for mapping the diagnostic type to the correct diagnostic
216   // selection index.
217   enum InvalidFuncDiag {
218     DiagCtor = 0,
219     DiagDtor,
220     DiagCopyAssign,
221     DiagMoveAssign,
222     DiagMain,
223     DiagConstexpr,
224     DiagAutoRet,
225     DiagVarargs,
226   };
227   bool Diagnosed = false;
228   auto DiagInvalid = [&](InvalidFuncDiag ID) {
229     S.Diag(Loc, diag::err_coroutine_invalid_func_context) << ID << Keyword;
230     Diagnosed = true;
231     return false;
232   };
233 
234   // Diagnose when a constructor, destructor, copy/move assignment operator,
235   // or the function 'main' are declared as a coroutine.
236   auto *MD = dyn_cast<CXXMethodDecl>(FD);
237   // [class.ctor]p6: "A constructor shall not be a coroutine."
238   if (MD && isa<CXXConstructorDecl>(MD))
239     return DiagInvalid(DiagCtor);
240   // [class.dtor]p17: "A destructor shall not be a coroutine."
241   else if (MD && isa<CXXDestructorDecl>(MD))
242     return DiagInvalid(DiagDtor);
243   // N4499 [special]p6: "A special member function shall not be a coroutine."
244   // Per C++ [special]p1, special member functions are the "default constructor,
245   // copy constructor and copy assignment operator, move constructor and move
246   // assignment operator, and destructor."
247   else if (MD && MD->isCopyAssignmentOperator())
248     return DiagInvalid(DiagCopyAssign);
249   else if (MD && MD->isMoveAssignmentOperator())
250     return DiagInvalid(DiagMoveAssign);
251   // [basic.start.main]p3: "The function main shall not be a coroutine."
252   else if (FD->isMain())
253     return DiagInvalid(DiagMain);
254 
255   // Emit a diagnostics for each of the following conditions which is not met.
256   // [expr.const]p2: "An expression e is a core constant expression unless the
257   // evaluation of e [...] would evaluate one of the following expressions:
258   // [...] an await-expression [...] a yield-expression."
259   if (FD->isConstexpr())
260     DiagInvalid(DiagConstexpr);
261   // [dcl.spec.auto]p15: "A function declared with a return type that uses a
262   // placeholder type shall not be a coroutine."
263   if (FD->getReturnType()->isUndeducedType())
264     DiagInvalid(DiagAutoRet);
265   // [dcl.fct.def.coroutine]p1: "The parameter-declaration-clause of the
266   // coroutine shall not terminate with an ellipsis that is not part of a
267   // parameter-declaration."
268   if (FD->isVariadic())
269     DiagInvalid(DiagVarargs);
270 
271   return !Diagnosed;
272 }
273 
274 static ExprResult buildOperatorCoawaitLookupExpr(Sema &SemaRef, Scope *S,
275                                                  SourceLocation Loc) {
276   DeclarationName OpName =
277       SemaRef.Context.DeclarationNames.getCXXOperatorName(OO_Coawait);
278   LookupResult Operators(SemaRef, OpName, SourceLocation(),
279                          Sema::LookupOperatorName);
280   SemaRef.LookupName(Operators, S);
281 
282   assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
283   const auto &Functions = Operators.asUnresolvedSet();
284   bool IsOverloaded =
285       Functions.size() > 1 ||
286       (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
287   Expr *CoawaitOp = UnresolvedLookupExpr::Create(
288       SemaRef.Context, /*NamingClass*/ nullptr, NestedNameSpecifierLoc(),
289       DeclarationNameInfo(OpName, Loc), /*RequiresADL*/ true, IsOverloaded,
290       Functions.begin(), Functions.end());
291   assert(CoawaitOp);
292   return CoawaitOp;
293 }
294 
295 /// Build a call to 'operator co_await' if there is a suitable operator for
296 /// the given expression.
297 static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, SourceLocation Loc,
298                                            Expr *E,
299                                            UnresolvedLookupExpr *Lookup) {
300   UnresolvedSet<16> Functions;
301   Functions.append(Lookup->decls_begin(), Lookup->decls_end());
302   return SemaRef.CreateOverloadedUnaryOp(Loc, UO_Coawait, Functions, E);
303 }
304 
305 static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, Scope *S,
306                                            SourceLocation Loc, Expr *E) {
307   ExprResult R = buildOperatorCoawaitLookupExpr(SemaRef, S, Loc);
308   if (R.isInvalid())
309     return ExprError();
310   return buildOperatorCoawaitCall(SemaRef, Loc, E,
311                                   cast<UnresolvedLookupExpr>(R.get()));
312 }
313 
314 static Expr *buildBuiltinCall(Sema &S, SourceLocation Loc, Builtin::ID Id,
315                               MultiExprArg CallArgs) {
316   StringRef Name = S.Context.BuiltinInfo.getName(Id);
317   LookupResult R(S, &S.Context.Idents.get(Name), Loc, Sema::LookupOrdinaryName);
318   S.LookupName(R, S.TUScope, /*AllowBuiltinCreation=*/true);
319 
320   auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
321   assert(BuiltInDecl && "failed to find builtin declaration");
322 
323   ExprResult DeclRef =
324       S.BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
325   assert(DeclRef.isUsable() && "Builtin reference cannot fail");
326 
327   ExprResult Call =
328       S.ActOnCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
329 
330   assert(!Call.isInvalid() && "Call to builtin cannot fail!");
331   return Call.get();
332 }
333 
334 static ExprResult buildCoroutineHandle(Sema &S, QualType PromiseType,
335                                        SourceLocation Loc) {
336   QualType CoroHandleType = lookupCoroutineHandleType(S, PromiseType, Loc);
337   if (CoroHandleType.isNull())
338     return ExprError();
339 
340   DeclContext *LookupCtx = S.computeDeclContext(CoroHandleType);
341   LookupResult Found(S, &S.PP.getIdentifierTable().get("from_address"), Loc,
342                      Sema::LookupOrdinaryName);
343   if (!S.LookupQualifiedName(Found, LookupCtx)) {
344     S.Diag(Loc, diag::err_coroutine_handle_missing_member)
345         << "from_address";
346     return ExprError();
347   }
348 
349   Expr *FramePtr =
350       buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_frame, {});
351 
352   CXXScopeSpec SS;
353   ExprResult FromAddr =
354       S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
355   if (FromAddr.isInvalid())
356     return ExprError();
357 
358   return S.ActOnCallExpr(nullptr, FromAddr.get(), Loc, FramePtr, Loc);
359 }
360 
361 struct ReadySuspendResumeResult {
362   enum AwaitCallType { ACT_Ready, ACT_Suspend, ACT_Resume };
363   Expr *Results[3];
364   OpaqueValueExpr *OpaqueValue;
365   bool IsInvalid;
366 };
367 
368 static ExprResult buildMemberCall(Sema &S, Expr *Base, SourceLocation Loc,
369                                   StringRef Name, MultiExprArg Args) {
370   DeclarationNameInfo NameInfo(&S.PP.getIdentifierTable().get(Name), Loc);
371 
372   // FIXME: Fix BuildMemberReferenceExpr to take a const CXXScopeSpec&.
373   CXXScopeSpec SS;
374   ExprResult Result = S.BuildMemberReferenceExpr(
375       Base, Base->getType(), Loc, /*IsPtr=*/false, SS,
376       SourceLocation(), nullptr, NameInfo, /*TemplateArgs=*/nullptr,
377       /*Scope=*/nullptr);
378   if (Result.isInvalid())
379     return ExprError();
380 
381   // We meant exactly what we asked for. No need for typo correction.
382   if (auto *TE = dyn_cast<TypoExpr>(Result.get())) {
383     S.clearDelayedTypo(TE);
384     S.Diag(Loc, diag::err_no_member)
385         << NameInfo.getName() << Base->getType()->getAsCXXRecordDecl()
386         << Base->getSourceRange();
387     return ExprError();
388   }
389 
390   return S.ActOnCallExpr(nullptr, Result.get(), Loc, Args, Loc, nullptr);
391 }
392 
393 // See if return type is coroutine-handle and if so, invoke builtin coro-resume
394 // on its address. This is to enable experimental support for coroutine-handle
395 // returning await_suspend that results in a guaranteed tail call to the target
396 // coroutine.
397 static Expr *maybeTailCall(Sema &S, QualType RetType, Expr *E,
398                            SourceLocation Loc) {
399   if (RetType->isReferenceType())
400     return nullptr;
401   Type const *T = RetType.getTypePtr();
402   if (!T->isClassType() && !T->isStructureType())
403     return nullptr;
404 
405   // FIXME: Add convertability check to coroutine_handle<>. Possibly via
406   // EvaluateBinaryTypeTrait(BTT_IsConvertible, ...) which is at the moment
407   // a private function in SemaExprCXX.cpp
408 
409   ExprResult AddressExpr = buildMemberCall(S, E, Loc, "address", None);
410   if (AddressExpr.isInvalid())
411     return nullptr;
412 
413   Expr *JustAddress = AddressExpr.get();
414   // FIXME: Check that the type of AddressExpr is void*
415   return buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_resume,
416                           JustAddress);
417 }
418 
419 /// Build calls to await_ready, await_suspend, and await_resume for a co_await
420 /// expression.
421 static ReadySuspendResumeResult buildCoawaitCalls(Sema &S, VarDecl *CoroPromise,
422                                                   SourceLocation Loc, Expr *E) {
423   OpaqueValueExpr *Operand = new (S.Context)
424       OpaqueValueExpr(Loc, E->getType(), VK_LValue, E->getObjectKind(), E);
425 
426   // Assume invalid until we see otherwise.
427   ReadySuspendResumeResult Calls = {{}, Operand, /*IsInvalid=*/true};
428 
429   ExprResult CoroHandleRes = buildCoroutineHandle(S, CoroPromise->getType(), Loc);
430   if (CoroHandleRes.isInvalid())
431     return Calls;
432   Expr *CoroHandle = CoroHandleRes.get();
433 
434   const StringRef Funcs[] = {"await_ready", "await_suspend", "await_resume"};
435   MultiExprArg Args[] = {None, CoroHandle, None};
436   for (size_t I = 0, N = llvm::array_lengthof(Funcs); I != N; ++I) {
437     ExprResult Result = buildMemberCall(S, Operand, Loc, Funcs[I], Args[I]);
438     if (Result.isInvalid())
439       return Calls;
440     Calls.Results[I] = Result.get();
441   }
442 
443   // Assume the calls are valid; all further checking should make them invalid.
444   Calls.IsInvalid = false;
445 
446   using ACT = ReadySuspendResumeResult::AwaitCallType;
447   CallExpr *AwaitReady = cast<CallExpr>(Calls.Results[ACT::ACT_Ready]);
448   if (!AwaitReady->getType()->isDependentType()) {
449     // [expr.await]p3 [...]
450     // — await-ready is the expression e.await_ready(), contextually converted
451     // to bool.
452     ExprResult Conv = S.PerformContextuallyConvertToBool(AwaitReady);
453     if (Conv.isInvalid()) {
454       S.Diag(AwaitReady->getDirectCallee()->getBeginLoc(),
455              diag::note_await_ready_no_bool_conversion);
456       S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
457           << AwaitReady->getDirectCallee() << E->getSourceRange();
458       Calls.IsInvalid = true;
459     }
460     Calls.Results[ACT::ACT_Ready] = Conv.get();
461   }
462   CallExpr *AwaitSuspend = cast<CallExpr>(Calls.Results[ACT::ACT_Suspend]);
463   if (!AwaitSuspend->getType()->isDependentType()) {
464     // [expr.await]p3 [...]
465     //   - await-suspend is the expression e.await_suspend(h), which shall be
466     //     a prvalue of type void or bool.
467     QualType RetType = AwaitSuspend->getCallReturnType(S.Context);
468 
469     // Experimental support for coroutine_handle returning await_suspend.
470     if (Expr *TailCallSuspend = maybeTailCall(S, RetType, AwaitSuspend, Loc))
471       Calls.Results[ACT::ACT_Suspend] = TailCallSuspend;
472     else {
473       // non-class prvalues always have cv-unqualified types
474       if (RetType->isReferenceType() ||
475           (!RetType->isBooleanType() && !RetType->isVoidType())) {
476         S.Diag(AwaitSuspend->getCalleeDecl()->getLocation(),
477                diag::err_await_suspend_invalid_return_type)
478             << RetType;
479         S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
480             << AwaitSuspend->getDirectCallee();
481         Calls.IsInvalid = true;
482       }
483     }
484   }
485 
486   return Calls;
487 }
488 
489 static ExprResult buildPromiseCall(Sema &S, VarDecl *Promise,
490                                    SourceLocation Loc, StringRef Name,
491                                    MultiExprArg Args) {
492 
493   // Form a reference to the promise.
494   ExprResult PromiseRef = S.BuildDeclRefExpr(
495       Promise, Promise->getType().getNonReferenceType(), VK_LValue, Loc);
496   if (PromiseRef.isInvalid())
497     return ExprError();
498 
499   return buildMemberCall(S, PromiseRef.get(), Loc, Name, Args);
500 }
501 
502 VarDecl *Sema::buildCoroutinePromise(SourceLocation Loc) {
503   assert(isa<FunctionDecl>(CurContext) && "not in a function scope");
504   auto *FD = cast<FunctionDecl>(CurContext);
505   bool IsThisDependentType = [&] {
506     if (auto *MD = dyn_cast_or_null<CXXMethodDecl>(FD))
507       return MD->isInstance() && MD->getThisType()->isDependentType();
508     else
509       return false;
510   }();
511 
512   QualType T = FD->getType()->isDependentType() || IsThisDependentType
513                    ? Context.DependentTy
514                    : lookupPromiseType(*this, FD, Loc);
515   if (T.isNull())
516     return nullptr;
517 
518   auto *VD = VarDecl::Create(Context, FD, FD->getLocation(), FD->getLocation(),
519                              &PP.getIdentifierTable().get("__promise"), T,
520                              Context.getTrivialTypeSourceInfo(T, Loc), SC_None);
521   CheckVariableDeclarationType(VD);
522   if (VD->isInvalidDecl())
523     return nullptr;
524 
525   auto *ScopeInfo = getCurFunction();
526   // Build a list of arguments, based on the coroutine functions arguments,
527   // that will be passed to the promise type's constructor.
528   llvm::SmallVector<Expr *, 4> CtorArgExprs;
529 
530   // Add implicit object parameter.
531   if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
532     if (MD->isInstance() && !isLambdaCallOperator(MD)) {
533       ExprResult ThisExpr = ActOnCXXThis(Loc);
534       if (ThisExpr.isInvalid())
535         return nullptr;
536       ThisExpr = CreateBuiltinUnaryOp(Loc, UO_Deref, ThisExpr.get());
537       if (ThisExpr.isInvalid())
538         return nullptr;
539       CtorArgExprs.push_back(ThisExpr.get());
540     }
541   }
542 
543   auto &Moves = ScopeInfo->CoroutineParameterMoves;
544   for (auto *PD : FD->parameters()) {
545     if (PD->getType()->isDependentType())
546       continue;
547 
548     auto RefExpr = ExprEmpty();
549     auto Move = Moves.find(PD);
550     assert(Move != Moves.end() &&
551            "Coroutine function parameter not inserted into move map");
552     // If a reference to the function parameter exists in the coroutine
553     // frame, use that reference.
554     auto *MoveDecl =
555         cast<VarDecl>(cast<DeclStmt>(Move->second)->getSingleDecl());
556     RefExpr =
557         BuildDeclRefExpr(MoveDecl, MoveDecl->getType().getNonReferenceType(),
558                          ExprValueKind::VK_LValue, FD->getLocation());
559     if (RefExpr.isInvalid())
560       return nullptr;
561     CtorArgExprs.push_back(RefExpr.get());
562   }
563 
564   // Create an initialization sequence for the promise type using the
565   // constructor arguments, wrapped in a parenthesized list expression.
566   Expr *PLE = ParenListExpr::Create(Context, FD->getLocation(),
567                                     CtorArgExprs, FD->getLocation());
568   InitializedEntity Entity = InitializedEntity::InitializeVariable(VD);
569   InitializationKind Kind = InitializationKind::CreateForInit(
570       VD->getLocation(), /*DirectInit=*/true, PLE);
571   InitializationSequence InitSeq(*this, Entity, Kind, CtorArgExprs,
572                                  /*TopLevelOfInitList=*/false,
573                                  /*TreatUnavailableAsInvalid=*/false);
574 
575   // Attempt to initialize the promise type with the arguments.
576   // If that fails, fall back to the promise type's default constructor.
577   if (InitSeq) {
578     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, CtorArgExprs);
579     if (Result.isInvalid()) {
580       VD->setInvalidDecl();
581     } else if (Result.get()) {
582       VD->setInit(MaybeCreateExprWithCleanups(Result.get()));
583       VD->setInitStyle(VarDecl::CallInit);
584       CheckCompleteVariableDeclaration(VD);
585     }
586   } else
587     ActOnUninitializedDecl(VD);
588 
589   FD->addDecl(VD);
590   return VD;
591 }
592 
593 /// Check that this is a context in which a coroutine suspension can appear.
594 static FunctionScopeInfo *checkCoroutineContext(Sema &S, SourceLocation Loc,
595                                                 StringRef Keyword,
596                                                 bool IsImplicit = false) {
597   if (!isValidCoroutineContext(S, Loc, Keyword))
598     return nullptr;
599 
600   assert(isa<FunctionDecl>(S.CurContext) && "not in a function scope");
601 
602   auto *ScopeInfo = S.getCurFunction();
603   assert(ScopeInfo && "missing function scope for function");
604 
605   if (ScopeInfo->FirstCoroutineStmtLoc.isInvalid() && !IsImplicit)
606     ScopeInfo->setFirstCoroutineStmt(Loc, Keyword);
607 
608   if (ScopeInfo->CoroutinePromise)
609     return ScopeInfo;
610 
611   if (!S.buildCoroutineParameterMoves(Loc))
612     return nullptr;
613 
614   ScopeInfo->CoroutinePromise = S.buildCoroutinePromise(Loc);
615   if (!ScopeInfo->CoroutinePromise)
616     return nullptr;
617 
618   return ScopeInfo;
619 }
620 
621 bool Sema::ActOnCoroutineBodyStart(Scope *SC, SourceLocation KWLoc,
622                                    StringRef Keyword) {
623   if (!checkCoroutineContext(*this, KWLoc, Keyword))
624     return false;
625   auto *ScopeInfo = getCurFunction();
626   assert(ScopeInfo->CoroutinePromise);
627 
628   // If we have existing coroutine statements then we have already built
629   // the initial and final suspend points.
630   if (!ScopeInfo->NeedsCoroutineSuspends)
631     return true;
632 
633   ScopeInfo->setNeedsCoroutineSuspends(false);
634 
635   auto *Fn = cast<FunctionDecl>(CurContext);
636   SourceLocation Loc = Fn->getLocation();
637   // Build the initial suspend point
638   auto buildSuspends = [&](StringRef Name) mutable -> StmtResult {
639     ExprResult Suspend =
640         buildPromiseCall(*this, ScopeInfo->CoroutinePromise, Loc, Name, None);
641     if (Suspend.isInvalid())
642       return StmtError();
643     Suspend = buildOperatorCoawaitCall(*this, SC, Loc, Suspend.get());
644     if (Suspend.isInvalid())
645       return StmtError();
646     Suspend = BuildResolvedCoawaitExpr(Loc, Suspend.get(),
647                                        /*IsImplicit*/ true);
648     Suspend = ActOnFinishFullExpr(Suspend.get(), /*DiscardedValue*/ false);
649     if (Suspend.isInvalid()) {
650       Diag(Loc, diag::note_coroutine_promise_suspend_implicitly_required)
651           << ((Name == "initial_suspend") ? 0 : 1);
652       Diag(KWLoc, diag::note_declared_coroutine_here) << Keyword;
653       return StmtError();
654     }
655     return cast<Stmt>(Suspend.get());
656   };
657 
658   StmtResult InitSuspend = buildSuspends("initial_suspend");
659   if (InitSuspend.isInvalid())
660     return true;
661 
662   StmtResult FinalSuspend = buildSuspends("final_suspend");
663   if (FinalSuspend.isInvalid())
664     return true;
665 
666   ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());
667 
668   return true;
669 }
670 
671 ExprResult Sema::ActOnCoawaitExpr(Scope *S, SourceLocation Loc, Expr *E) {
672   if (!ActOnCoroutineBodyStart(S, Loc, "co_await")) {
673     CorrectDelayedTyposInExpr(E);
674     return ExprError();
675   }
676 
677   if (E->getType()->isPlaceholderType()) {
678     ExprResult R = CheckPlaceholderExpr(E);
679     if (R.isInvalid()) return ExprError();
680     E = R.get();
681   }
682   ExprResult Lookup = buildOperatorCoawaitLookupExpr(*this, S, Loc);
683   if (Lookup.isInvalid())
684     return ExprError();
685   return BuildUnresolvedCoawaitExpr(Loc, E,
686                                    cast<UnresolvedLookupExpr>(Lookup.get()));
687 }
688 
689 ExprResult Sema::BuildUnresolvedCoawaitExpr(SourceLocation Loc, Expr *E,
690                                             UnresolvedLookupExpr *Lookup) {
691   auto *FSI = checkCoroutineContext(*this, Loc, "co_await");
692   if (!FSI)
693     return ExprError();
694 
695   if (E->getType()->isPlaceholderType()) {
696     ExprResult R = CheckPlaceholderExpr(E);
697     if (R.isInvalid())
698       return ExprError();
699     E = R.get();
700   }
701 
702   auto *Promise = FSI->CoroutinePromise;
703   if (Promise->getType()->isDependentType()) {
704     Expr *Res =
705         new (Context) DependentCoawaitExpr(Loc, Context.DependentTy, E, Lookup);
706     return Res;
707   }
708 
709   auto *RD = Promise->getType()->getAsCXXRecordDecl();
710   if (lookupMember(*this, "await_transform", RD, Loc)) {
711     ExprResult R = buildPromiseCall(*this, Promise, Loc, "await_transform", E);
712     if (R.isInvalid()) {
713       Diag(Loc,
714            diag::note_coroutine_promise_implicit_await_transform_required_here)
715           << E->getSourceRange();
716       return ExprError();
717     }
718     E = R.get();
719   }
720   ExprResult Awaitable = buildOperatorCoawaitCall(*this, Loc, E, Lookup);
721   if (Awaitable.isInvalid())
722     return ExprError();
723 
724   return BuildResolvedCoawaitExpr(Loc, Awaitable.get());
725 }
726 
727 ExprResult Sema::BuildResolvedCoawaitExpr(SourceLocation Loc, Expr *E,
728                                   bool IsImplicit) {
729   auto *Coroutine = checkCoroutineContext(*this, Loc, "co_await", IsImplicit);
730   if (!Coroutine)
731     return ExprError();
732 
733   if (E->getType()->isPlaceholderType()) {
734     ExprResult R = CheckPlaceholderExpr(E);
735     if (R.isInvalid()) return ExprError();
736     E = R.get();
737   }
738 
739   if (E->getType()->isDependentType()) {
740     Expr *Res = new (Context)
741         CoawaitExpr(Loc, Context.DependentTy, E, IsImplicit);
742     return Res;
743   }
744 
745   // If the expression is a temporary, materialize it as an lvalue so that we
746   // can use it multiple times.
747   if (E->getValueKind() == VK_RValue)
748     E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
749 
750   // The location of the `co_await` token cannot be used when constructing
751   // the member call expressions since it's before the location of `Expr`, which
752   // is used as the start of the member call expression.
753   SourceLocation CallLoc = E->getExprLoc();
754 
755   // Build the await_ready, await_suspend, await_resume calls.
756   ReadySuspendResumeResult RSS =
757       buildCoawaitCalls(*this, Coroutine->CoroutinePromise, CallLoc, E);
758   if (RSS.IsInvalid)
759     return ExprError();
760 
761   Expr *Res =
762       new (Context) CoawaitExpr(Loc, E, RSS.Results[0], RSS.Results[1],
763                                 RSS.Results[2], RSS.OpaqueValue, IsImplicit);
764 
765   return Res;
766 }
767 
768 ExprResult Sema::ActOnCoyieldExpr(Scope *S, SourceLocation Loc, Expr *E) {
769   if (!ActOnCoroutineBodyStart(S, Loc, "co_yield")) {
770     CorrectDelayedTyposInExpr(E);
771     return ExprError();
772   }
773 
774   // Build yield_value call.
775   ExprResult Awaitable = buildPromiseCall(
776       *this, getCurFunction()->CoroutinePromise, Loc, "yield_value", E);
777   if (Awaitable.isInvalid())
778     return ExprError();
779 
780   // Build 'operator co_await' call.
781   Awaitable = buildOperatorCoawaitCall(*this, S, Loc, Awaitable.get());
782   if (Awaitable.isInvalid())
783     return ExprError();
784 
785   return BuildCoyieldExpr(Loc, Awaitable.get());
786 }
787 ExprResult Sema::BuildCoyieldExpr(SourceLocation Loc, Expr *E) {
788   auto *Coroutine = checkCoroutineContext(*this, Loc, "co_yield");
789   if (!Coroutine)
790     return ExprError();
791 
792   if (E->getType()->isPlaceholderType()) {
793     ExprResult R = CheckPlaceholderExpr(E);
794     if (R.isInvalid()) return ExprError();
795     E = R.get();
796   }
797 
798   if (E->getType()->isDependentType()) {
799     Expr *Res = new (Context) CoyieldExpr(Loc, Context.DependentTy, E);
800     return Res;
801   }
802 
803   // If the expression is a temporary, materialize it as an lvalue so that we
804   // can use it multiple times.
805   if (E->getValueKind() == VK_RValue)
806     E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
807 
808   // Build the await_ready, await_suspend, await_resume calls.
809   ReadySuspendResumeResult RSS =
810       buildCoawaitCalls(*this, Coroutine->CoroutinePromise, Loc, E);
811   if (RSS.IsInvalid)
812     return ExprError();
813 
814   Expr *Res =
815       new (Context) CoyieldExpr(Loc, E, RSS.Results[0], RSS.Results[1],
816                                 RSS.Results[2], RSS.OpaqueValue);
817 
818   return Res;
819 }
820 
821 StmtResult Sema::ActOnCoreturnStmt(Scope *S, SourceLocation Loc, Expr *E) {
822   if (!ActOnCoroutineBodyStart(S, Loc, "co_return")) {
823     CorrectDelayedTyposInExpr(E);
824     return StmtError();
825   }
826   return BuildCoreturnStmt(Loc, E);
827 }
828 
829 StmtResult Sema::BuildCoreturnStmt(SourceLocation Loc, Expr *E,
830                                    bool IsImplicit) {
831   auto *FSI = checkCoroutineContext(*this, Loc, "co_return", IsImplicit);
832   if (!FSI)
833     return StmtError();
834 
835   if (E && E->getType()->isPlaceholderType() &&
836       !E->getType()->isSpecificPlaceholderType(BuiltinType::Overload)) {
837     ExprResult R = CheckPlaceholderExpr(E);
838     if (R.isInvalid()) return StmtError();
839     E = R.get();
840   }
841 
842   // Move the return value if we can
843   if (E) {
844     auto NRVOCandidate = this->getCopyElisionCandidate(E->getType(), E, CES_AsIfByStdMove);
845     if (NRVOCandidate) {
846       InitializedEntity Entity =
847           InitializedEntity::InitializeResult(Loc, E->getType(), NRVOCandidate);
848       ExprResult MoveResult = this->PerformMoveOrCopyInitialization(
849           Entity, NRVOCandidate, E->getType(), E);
850       if (MoveResult.get())
851         E = MoveResult.get();
852     }
853   }
854 
855   // FIXME: If the operand is a reference to a variable that's about to go out
856   // of scope, we should treat the operand as an xvalue for this overload
857   // resolution.
858   VarDecl *Promise = FSI->CoroutinePromise;
859   ExprResult PC;
860   if (E && (isa<InitListExpr>(E) || !E->getType()->isVoidType())) {
861     PC = buildPromiseCall(*this, Promise, Loc, "return_value", E);
862   } else {
863     E = MakeFullDiscardedValueExpr(E).get();
864     PC = buildPromiseCall(*this, Promise, Loc, "return_void", None);
865   }
866   if (PC.isInvalid())
867     return StmtError();
868 
869   Expr *PCE = ActOnFinishFullExpr(PC.get(), /*DiscardedValue*/ false).get();
870 
871   Stmt *Res = new (Context) CoreturnStmt(Loc, E, PCE, IsImplicit);
872   return Res;
873 }
874 
875 /// Look up the std::nothrow object.
876 static Expr *buildStdNoThrowDeclRef(Sema &S, SourceLocation Loc) {
877   NamespaceDecl *Std = S.getStdNamespace();
878   assert(Std && "Should already be diagnosed");
879 
880   LookupResult Result(S, &S.PP.getIdentifierTable().get("nothrow"), Loc,
881                       Sema::LookupOrdinaryName);
882   if (!S.LookupQualifiedName(Result, Std)) {
883     // FIXME: <experimental/coroutine> should have been included already.
884     // If we require it to include <new> then this diagnostic is no longer
885     // needed.
886     S.Diag(Loc, diag::err_implicit_coroutine_std_nothrow_type_not_found);
887     return nullptr;
888   }
889 
890   auto *VD = Result.getAsSingle<VarDecl>();
891   if (!VD) {
892     Result.suppressDiagnostics();
893     // We found something weird. Complain about the first thing we found.
894     NamedDecl *Found = *Result.begin();
895     S.Diag(Found->getLocation(), diag::err_malformed_std_nothrow);
896     return nullptr;
897   }
898 
899   ExprResult DR = S.BuildDeclRefExpr(VD, VD->getType(), VK_LValue, Loc);
900   if (DR.isInvalid())
901     return nullptr;
902 
903   return DR.get();
904 }
905 
906 // Find an appropriate delete for the promise.
907 static FunctionDecl *findDeleteForPromise(Sema &S, SourceLocation Loc,
908                                           QualType PromiseType) {
909   FunctionDecl *OperatorDelete = nullptr;
910 
911   DeclarationName DeleteName =
912       S.Context.DeclarationNames.getCXXOperatorName(OO_Delete);
913 
914   auto *PointeeRD = PromiseType->getAsCXXRecordDecl();
915   assert(PointeeRD && "PromiseType must be a CxxRecordDecl type");
916 
917   if (S.FindDeallocationFunction(Loc, PointeeRD, DeleteName, OperatorDelete))
918     return nullptr;
919 
920   if (!OperatorDelete) {
921     // Look for a global declaration.
922     const bool CanProvideSize = S.isCompleteType(Loc, PromiseType);
923     const bool Overaligned = false;
924     OperatorDelete = S.FindUsualDeallocationFunction(Loc, CanProvideSize,
925                                                      Overaligned, DeleteName);
926   }
927   S.MarkFunctionReferenced(Loc, OperatorDelete);
928   return OperatorDelete;
929 }
930 
931 
932 void Sema::CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body) {
933   FunctionScopeInfo *Fn = getCurFunction();
934   assert(Fn && Fn->isCoroutine() && "not a coroutine");
935   if (!Body) {
936     assert(FD->isInvalidDecl() &&
937            "a null body is only allowed for invalid declarations");
938     return;
939   }
940   // We have a function that uses coroutine keywords, but we failed to build
941   // the promise type.
942   if (!Fn->CoroutinePromise)
943     return FD->setInvalidDecl();
944 
945   if (isa<CoroutineBodyStmt>(Body)) {
946     // Nothing todo. the body is already a transformed coroutine body statement.
947     return;
948   }
949 
950   // Coroutines [stmt.return]p1:
951   //   A return statement shall not appear in a coroutine.
952   if (Fn->FirstReturnLoc.isValid()) {
953     assert(Fn->FirstCoroutineStmtLoc.isValid() &&
954                    "first coroutine location not set");
955     Diag(Fn->FirstReturnLoc, diag::err_return_in_coroutine);
956     Diag(Fn->FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
957             << Fn->getFirstCoroutineStmtKeyword();
958   }
959   CoroutineStmtBuilder Builder(*this, *FD, *Fn, Body);
960   if (Builder.isInvalid() || !Builder.buildStatements())
961     return FD->setInvalidDecl();
962 
963   // Build body for the coroutine wrapper statement.
964   Body = CoroutineBodyStmt::Create(Context, Builder);
965 }
966 
967 CoroutineStmtBuilder::CoroutineStmtBuilder(Sema &S, FunctionDecl &FD,
968                                            sema::FunctionScopeInfo &Fn,
969                                            Stmt *Body)
970     : S(S), FD(FD), Fn(Fn), Loc(FD.getLocation()),
971       IsPromiseDependentType(
972           !Fn.CoroutinePromise ||
973           Fn.CoroutinePromise->getType()->isDependentType()) {
974   this->Body = Body;
975 
976   for (auto KV : Fn.CoroutineParameterMoves)
977     this->ParamMovesVector.push_back(KV.second);
978   this->ParamMoves = this->ParamMovesVector;
979 
980   if (!IsPromiseDependentType) {
981     PromiseRecordDecl = Fn.CoroutinePromise->getType()->getAsCXXRecordDecl();
982     assert(PromiseRecordDecl && "Type should have already been checked");
983   }
984   this->IsValid = makePromiseStmt() && makeInitialAndFinalSuspend();
985 }
986 
987 bool CoroutineStmtBuilder::buildStatements() {
988   assert(this->IsValid && "coroutine already invalid");
989   this->IsValid = makeReturnObject();
990   if (this->IsValid && !IsPromiseDependentType)
991     buildDependentStatements();
992   return this->IsValid;
993 }
994 
995 bool CoroutineStmtBuilder::buildDependentStatements() {
996   assert(this->IsValid && "coroutine already invalid");
997   assert(!this->IsPromiseDependentType &&
998          "coroutine cannot have a dependent promise type");
999   this->IsValid = makeOnException() && makeOnFallthrough() &&
1000                   makeGroDeclAndReturnStmt() && makeReturnOnAllocFailure() &&
1001                   makeNewAndDeleteExpr();
1002   return this->IsValid;
1003 }
1004 
1005 bool CoroutineStmtBuilder::makePromiseStmt() {
1006   // Form a declaration statement for the promise declaration, so that AST
1007   // visitors can more easily find it.
1008   StmtResult PromiseStmt =
1009       S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(Fn.CoroutinePromise), Loc, Loc);
1010   if (PromiseStmt.isInvalid())
1011     return false;
1012 
1013   this->Promise = PromiseStmt.get();
1014   return true;
1015 }
1016 
1017 bool CoroutineStmtBuilder::makeInitialAndFinalSuspend() {
1018   if (Fn.hasInvalidCoroutineSuspends())
1019     return false;
1020   this->InitialSuspend = cast<Expr>(Fn.CoroutineSuspends.first);
1021   this->FinalSuspend = cast<Expr>(Fn.CoroutineSuspends.second);
1022   return true;
1023 }
1024 
1025 static bool diagReturnOnAllocFailure(Sema &S, Expr *E,
1026                                      CXXRecordDecl *PromiseRecordDecl,
1027                                      FunctionScopeInfo &Fn) {
1028   auto Loc = E->getExprLoc();
1029   if (auto *DeclRef = dyn_cast_or_null<DeclRefExpr>(E)) {
1030     auto *Decl = DeclRef->getDecl();
1031     if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Decl)) {
1032       if (Method->isStatic())
1033         return true;
1034       else
1035         Loc = Decl->getLocation();
1036     }
1037   }
1038 
1039   S.Diag(
1040       Loc,
1041       diag::err_coroutine_promise_get_return_object_on_allocation_failure)
1042       << PromiseRecordDecl;
1043   S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1044       << Fn.getFirstCoroutineStmtKeyword();
1045   return false;
1046 }
1047 
1048 bool CoroutineStmtBuilder::makeReturnOnAllocFailure() {
1049   assert(!IsPromiseDependentType &&
1050          "cannot make statement while the promise type is dependent");
1051 
1052   // [dcl.fct.def.coroutine]/8
1053   // The unqualified-id get_return_object_on_allocation_failure is looked up in
1054   // the scope of class P by class member access lookup (3.4.5). ...
1055   // If an allocation function returns nullptr, ... the coroutine return value
1056   // is obtained by a call to ... get_return_object_on_allocation_failure().
1057 
1058   DeclarationName DN =
1059       S.PP.getIdentifierInfo("get_return_object_on_allocation_failure");
1060   LookupResult Found(S, DN, Loc, Sema::LookupMemberName);
1061   if (!S.LookupQualifiedName(Found, PromiseRecordDecl))
1062     return true;
1063 
1064   CXXScopeSpec SS;
1065   ExprResult DeclNameExpr =
1066       S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
1067   if (DeclNameExpr.isInvalid())
1068     return false;
1069 
1070   if (!diagReturnOnAllocFailure(S, DeclNameExpr.get(), PromiseRecordDecl, Fn))
1071     return false;
1072 
1073   ExprResult ReturnObjectOnAllocationFailure =
1074       S.ActOnCallExpr(nullptr, DeclNameExpr.get(), Loc, {}, Loc);
1075   if (ReturnObjectOnAllocationFailure.isInvalid())
1076     return false;
1077 
1078   StmtResult ReturnStmt =
1079       S.BuildReturnStmt(Loc, ReturnObjectOnAllocationFailure.get());
1080   if (ReturnStmt.isInvalid()) {
1081     S.Diag(Found.getFoundDecl()->getLocation(), diag::note_member_declared_here)
1082         << DN;
1083     S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1084         << Fn.getFirstCoroutineStmtKeyword();
1085     return false;
1086   }
1087 
1088   this->ReturnStmtOnAllocFailure = ReturnStmt.get();
1089   return true;
1090 }
1091 
1092 bool CoroutineStmtBuilder::makeNewAndDeleteExpr() {
1093   // Form and check allocation and deallocation calls.
1094   assert(!IsPromiseDependentType &&
1095          "cannot make statement while the promise type is dependent");
1096   QualType PromiseType = Fn.CoroutinePromise->getType();
1097 
1098   if (S.RequireCompleteType(Loc, PromiseType, diag::err_incomplete_type))
1099     return false;
1100 
1101   const bool RequiresNoThrowAlloc = ReturnStmtOnAllocFailure != nullptr;
1102 
1103   // [dcl.fct.def.coroutine]/7
1104   // Lookup allocation functions using a parameter list composed of the
1105   // requested size of the coroutine state being allocated, followed by
1106   // the coroutine function's arguments. If a matching allocation function
1107   // exists, use it. Otherwise, use an allocation function that just takes
1108   // the requested size.
1109 
1110   FunctionDecl *OperatorNew = nullptr;
1111   FunctionDecl *OperatorDelete = nullptr;
1112   FunctionDecl *UnusedResult = nullptr;
1113   bool PassAlignment = false;
1114   SmallVector<Expr *, 1> PlacementArgs;
1115 
1116   // [dcl.fct.def.coroutine]/7
1117   // "The allocation function’s name is looked up in the scope of P.
1118   // [...] If the lookup finds an allocation function in the scope of P,
1119   // overload resolution is performed on a function call created by assembling
1120   // an argument list. The first argument is the amount of space requested,
1121   // and has type std::size_t. The lvalues p1 ... pn are the succeeding
1122   // arguments."
1123   //
1124   // ...where "p1 ... pn" are defined earlier as:
1125   //
1126   // [dcl.fct.def.coroutine]/3
1127   // "For a coroutine f that is a non-static member function, let P1 denote the
1128   // type of the implicit object parameter (13.3.1) and P2 ... Pn be the types
1129   // of the function parameters; otherwise let P1 ... Pn be the types of the
1130   // function parameters. Let p1 ... pn be lvalues denoting those objects."
1131   if (auto *MD = dyn_cast<CXXMethodDecl>(&FD)) {
1132     if (MD->isInstance() && !isLambdaCallOperator(MD)) {
1133       ExprResult ThisExpr = S.ActOnCXXThis(Loc);
1134       if (ThisExpr.isInvalid())
1135         return false;
1136       ThisExpr = S.CreateBuiltinUnaryOp(Loc, UO_Deref, ThisExpr.get());
1137       if (ThisExpr.isInvalid())
1138         return false;
1139       PlacementArgs.push_back(ThisExpr.get());
1140     }
1141   }
1142   for (auto *PD : FD.parameters()) {
1143     if (PD->getType()->isDependentType())
1144       continue;
1145 
1146     // Build a reference to the parameter.
1147     auto PDLoc = PD->getLocation();
1148     ExprResult PDRefExpr =
1149         S.BuildDeclRefExpr(PD, PD->getOriginalType().getNonReferenceType(),
1150                            ExprValueKind::VK_LValue, PDLoc);
1151     if (PDRefExpr.isInvalid())
1152       return false;
1153 
1154     PlacementArgs.push_back(PDRefExpr.get());
1155   }
1156   S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Class,
1157                             /*DeleteScope*/ Sema::AFS_Both, PromiseType,
1158                             /*isArray*/ false, PassAlignment, PlacementArgs,
1159                             OperatorNew, UnusedResult, /*Diagnose*/ false);
1160 
1161   // [dcl.fct.def.coroutine]/7
1162   // "If no matching function is found, overload resolution is performed again
1163   // on a function call created by passing just the amount of space required as
1164   // an argument of type std::size_t."
1165   if (!OperatorNew && !PlacementArgs.empty()) {
1166     PlacementArgs.clear();
1167     S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Class,
1168                               /*DeleteScope*/ Sema::AFS_Both, PromiseType,
1169                               /*isArray*/ false, PassAlignment, PlacementArgs,
1170                               OperatorNew, UnusedResult, /*Diagnose*/ false);
1171   }
1172 
1173   // [dcl.fct.def.coroutine]/7
1174   // "The allocation function’s name is looked up in the scope of P. If this
1175   // lookup fails, the allocation function’s name is looked up in the global
1176   // scope."
1177   if (!OperatorNew) {
1178     S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Global,
1179                               /*DeleteScope*/ Sema::AFS_Both, PromiseType,
1180                               /*isArray*/ false, PassAlignment, PlacementArgs,
1181                               OperatorNew, UnusedResult);
1182   }
1183 
1184   bool IsGlobalOverload =
1185       OperatorNew && !isa<CXXRecordDecl>(OperatorNew->getDeclContext());
1186   // If we didn't find a class-local new declaration and non-throwing new
1187   // was is required then we need to lookup the non-throwing global operator
1188   // instead.
1189   if (RequiresNoThrowAlloc && (!OperatorNew || IsGlobalOverload)) {
1190     auto *StdNoThrow = buildStdNoThrowDeclRef(S, Loc);
1191     if (!StdNoThrow)
1192       return false;
1193     PlacementArgs = {StdNoThrow};
1194     OperatorNew = nullptr;
1195     S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Both,
1196                               /*DeleteScope*/ Sema::AFS_Both, PromiseType,
1197                               /*isArray*/ false, PassAlignment, PlacementArgs,
1198                               OperatorNew, UnusedResult);
1199   }
1200 
1201   if (!OperatorNew)
1202     return false;
1203 
1204   if (RequiresNoThrowAlloc) {
1205     const auto *FT = OperatorNew->getType()->getAs<FunctionProtoType>();
1206     if (!FT->isNothrow(/*ResultIfDependent*/ false)) {
1207       S.Diag(OperatorNew->getLocation(),
1208              diag::err_coroutine_promise_new_requires_nothrow)
1209           << OperatorNew;
1210       S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
1211           << OperatorNew;
1212       return false;
1213     }
1214   }
1215 
1216   if ((OperatorDelete = findDeleteForPromise(S, Loc, PromiseType)) == nullptr)
1217     return false;
1218 
1219   Expr *FramePtr =
1220       buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_frame, {});
1221 
1222   Expr *FrameSize =
1223       buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_size, {});
1224 
1225   // Make new call.
1226 
1227   ExprResult NewRef =
1228       S.BuildDeclRefExpr(OperatorNew, OperatorNew->getType(), VK_LValue, Loc);
1229   if (NewRef.isInvalid())
1230     return false;
1231 
1232   SmallVector<Expr *, 2> NewArgs(1, FrameSize);
1233   for (auto Arg : PlacementArgs)
1234     NewArgs.push_back(Arg);
1235 
1236   ExprResult NewExpr =
1237       S.ActOnCallExpr(S.getCurScope(), NewRef.get(), Loc, NewArgs, Loc);
1238   NewExpr = S.ActOnFinishFullExpr(NewExpr.get(), /*DiscardedValue*/ false);
1239   if (NewExpr.isInvalid())
1240     return false;
1241 
1242   // Make delete call.
1243 
1244   QualType OpDeleteQualType = OperatorDelete->getType();
1245 
1246   ExprResult DeleteRef =
1247       S.BuildDeclRefExpr(OperatorDelete, OpDeleteQualType, VK_LValue, Loc);
1248   if (DeleteRef.isInvalid())
1249     return false;
1250 
1251   Expr *CoroFree =
1252       buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_free, {FramePtr});
1253 
1254   SmallVector<Expr *, 2> DeleteArgs{CoroFree};
1255 
1256   // Check if we need to pass the size.
1257   const auto *OpDeleteType =
1258       OpDeleteQualType.getTypePtr()->getAs<FunctionProtoType>();
1259   if (OpDeleteType->getNumParams() > 1)
1260     DeleteArgs.push_back(FrameSize);
1261 
1262   ExprResult DeleteExpr =
1263       S.ActOnCallExpr(S.getCurScope(), DeleteRef.get(), Loc, DeleteArgs, Loc);
1264   DeleteExpr =
1265       S.ActOnFinishFullExpr(DeleteExpr.get(), /*DiscardedValue*/ false);
1266   if (DeleteExpr.isInvalid())
1267     return false;
1268 
1269   this->Allocate = NewExpr.get();
1270   this->Deallocate = DeleteExpr.get();
1271 
1272   return true;
1273 }
1274 
1275 bool CoroutineStmtBuilder::makeOnFallthrough() {
1276   assert(!IsPromiseDependentType &&
1277          "cannot make statement while the promise type is dependent");
1278 
1279   // [dcl.fct.def.coroutine]/4
1280   // The unqualified-ids 'return_void' and 'return_value' are looked up in
1281   // the scope of class P. If both are found, the program is ill-formed.
1282   bool HasRVoid, HasRValue;
1283   LookupResult LRVoid =
1284       lookupMember(S, "return_void", PromiseRecordDecl, Loc, HasRVoid);
1285   LookupResult LRValue =
1286       lookupMember(S, "return_value", PromiseRecordDecl, Loc, HasRValue);
1287 
1288   StmtResult Fallthrough;
1289   if (HasRVoid && HasRValue) {
1290     // FIXME Improve this diagnostic
1291     S.Diag(FD.getLocation(),
1292            diag::err_coroutine_promise_incompatible_return_functions)
1293         << PromiseRecordDecl;
1294     S.Diag(LRVoid.getRepresentativeDecl()->getLocation(),
1295            diag::note_member_first_declared_here)
1296         << LRVoid.getLookupName();
1297     S.Diag(LRValue.getRepresentativeDecl()->getLocation(),
1298            diag::note_member_first_declared_here)
1299         << LRValue.getLookupName();
1300     return false;
1301   } else if (!HasRVoid && !HasRValue) {
1302     // FIXME: The PDTS currently specifies this case as UB, not ill-formed.
1303     // However we still diagnose this as an error since until the PDTS is fixed.
1304     S.Diag(FD.getLocation(),
1305            diag::err_coroutine_promise_requires_return_function)
1306         << PromiseRecordDecl;
1307     S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here)
1308         << PromiseRecordDecl;
1309     return false;
1310   } else if (HasRVoid) {
1311     // If the unqualified-id return_void is found, flowing off the end of a
1312     // coroutine is equivalent to a co_return with no operand. Otherwise,
1313     // flowing off the end of a coroutine results in undefined behavior.
1314     Fallthrough = S.BuildCoreturnStmt(FD.getLocation(), nullptr,
1315                                       /*IsImplicit*/false);
1316     Fallthrough = S.ActOnFinishFullStmt(Fallthrough.get());
1317     if (Fallthrough.isInvalid())
1318       return false;
1319   }
1320 
1321   this->OnFallthrough = Fallthrough.get();
1322   return true;
1323 }
1324 
1325 bool CoroutineStmtBuilder::makeOnException() {
1326   // Try to form 'p.unhandled_exception();'
1327   assert(!IsPromiseDependentType &&
1328          "cannot make statement while the promise type is dependent");
1329 
1330   const bool RequireUnhandledException = S.getLangOpts().CXXExceptions;
1331 
1332   if (!lookupMember(S, "unhandled_exception", PromiseRecordDecl, Loc)) {
1333     auto DiagID =
1334         RequireUnhandledException
1335             ? diag::err_coroutine_promise_unhandled_exception_required
1336             : diag::
1337                   warn_coroutine_promise_unhandled_exception_required_with_exceptions;
1338     S.Diag(Loc, DiagID) << PromiseRecordDecl;
1339     S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here)
1340         << PromiseRecordDecl;
1341     return !RequireUnhandledException;
1342   }
1343 
1344   // If exceptions are disabled, don't try to build OnException.
1345   if (!S.getLangOpts().CXXExceptions)
1346     return true;
1347 
1348   ExprResult UnhandledException = buildPromiseCall(S, Fn.CoroutinePromise, Loc,
1349                                                    "unhandled_exception", None);
1350   UnhandledException = S.ActOnFinishFullExpr(UnhandledException.get(), Loc,
1351                                              /*DiscardedValue*/ false);
1352   if (UnhandledException.isInvalid())
1353     return false;
1354 
1355   // Since the body of the coroutine will be wrapped in try-catch, it will
1356   // be incompatible with SEH __try if present in a function.
1357   if (!S.getLangOpts().Borland && Fn.FirstSEHTryLoc.isValid()) {
1358     S.Diag(Fn.FirstSEHTryLoc, diag::err_seh_in_a_coroutine_with_cxx_exceptions);
1359     S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1360         << Fn.getFirstCoroutineStmtKeyword();
1361     return false;
1362   }
1363 
1364   this->OnException = UnhandledException.get();
1365   return true;
1366 }
1367 
1368 bool CoroutineStmtBuilder::makeReturnObject() {
1369   // Build implicit 'p.get_return_object()' expression and form initialization
1370   // of return type from it.
1371   ExprResult ReturnObject =
1372       buildPromiseCall(S, Fn.CoroutinePromise, Loc, "get_return_object", None);
1373   if (ReturnObject.isInvalid())
1374     return false;
1375 
1376   this->ReturnValue = ReturnObject.get();
1377   return true;
1378 }
1379 
1380 static void noteMemberDeclaredHere(Sema &S, Expr *E, FunctionScopeInfo &Fn) {
1381   if (auto *MbrRef = dyn_cast<CXXMemberCallExpr>(E)) {
1382     auto *MethodDecl = MbrRef->getMethodDecl();
1383     S.Diag(MethodDecl->getLocation(), diag::note_member_declared_here)
1384         << MethodDecl;
1385   }
1386   S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1387       << Fn.getFirstCoroutineStmtKeyword();
1388 }
1389 
1390 bool CoroutineStmtBuilder::makeGroDeclAndReturnStmt() {
1391   assert(!IsPromiseDependentType &&
1392          "cannot make statement while the promise type is dependent");
1393   assert(this->ReturnValue && "ReturnValue must be already formed");
1394 
1395   QualType const GroType = this->ReturnValue->getType();
1396   assert(!GroType->isDependentType() &&
1397          "get_return_object type must no longer be dependent");
1398 
1399   QualType const FnRetType = FD.getReturnType();
1400   assert(!FnRetType->isDependentType() &&
1401          "get_return_object type must no longer be dependent");
1402 
1403   if (FnRetType->isVoidType()) {
1404     ExprResult Res =
1405         S.ActOnFinishFullExpr(this->ReturnValue, Loc, /*DiscardedValue*/ false);
1406     if (Res.isInvalid())
1407       return false;
1408 
1409     this->ResultDecl = Res.get();
1410     return true;
1411   }
1412 
1413   if (GroType->isVoidType()) {
1414     // Trigger a nice error message.
1415     InitializedEntity Entity =
1416         InitializedEntity::InitializeResult(Loc, FnRetType, false);
1417     S.PerformMoveOrCopyInitialization(Entity, nullptr, FnRetType, ReturnValue);
1418     noteMemberDeclaredHere(S, ReturnValue, Fn);
1419     return false;
1420   }
1421 
1422   auto *GroDecl = VarDecl::Create(
1423       S.Context, &FD, FD.getLocation(), FD.getLocation(),
1424       &S.PP.getIdentifierTable().get("__coro_gro"), GroType,
1425       S.Context.getTrivialTypeSourceInfo(GroType, Loc), SC_None);
1426 
1427   S.CheckVariableDeclarationType(GroDecl);
1428   if (GroDecl->isInvalidDecl())
1429     return false;
1430 
1431   InitializedEntity Entity = InitializedEntity::InitializeVariable(GroDecl);
1432   ExprResult Res = S.PerformMoveOrCopyInitialization(Entity, nullptr, GroType,
1433                                                      this->ReturnValue);
1434   if (Res.isInvalid())
1435     return false;
1436 
1437   Res = S.ActOnFinishFullExpr(Res.get(), /*DiscardedValue*/ false);
1438   if (Res.isInvalid())
1439     return false;
1440 
1441   S.AddInitializerToDecl(GroDecl, Res.get(),
1442                          /*DirectInit=*/false);
1443 
1444   S.FinalizeDeclaration(GroDecl);
1445 
1446   // Form a declaration statement for the return declaration, so that AST
1447   // visitors can more easily find it.
1448   StmtResult GroDeclStmt =
1449       S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(GroDecl), Loc, Loc);
1450   if (GroDeclStmt.isInvalid())
1451     return false;
1452 
1453   this->ResultDecl = GroDeclStmt.get();
1454 
1455   ExprResult declRef = S.BuildDeclRefExpr(GroDecl, GroType, VK_LValue, Loc);
1456   if (declRef.isInvalid())
1457     return false;
1458 
1459   StmtResult ReturnStmt = S.BuildReturnStmt(Loc, declRef.get());
1460   if (ReturnStmt.isInvalid()) {
1461     noteMemberDeclaredHere(S, ReturnValue, Fn);
1462     return false;
1463   }
1464   if (cast<clang::ReturnStmt>(ReturnStmt.get())->getNRVOCandidate() == GroDecl)
1465     GroDecl->setNRVOVariable(true);
1466 
1467   this->ReturnStmt = ReturnStmt.get();
1468   return true;
1469 }
1470 
1471 // Create a static_cast\<T&&>(expr).
1472 static Expr *castForMoving(Sema &S, Expr *E, QualType T = QualType()) {
1473   if (T.isNull())
1474     T = E->getType();
1475   QualType TargetType = S.BuildReferenceType(
1476       T, /*SpelledAsLValue*/ false, SourceLocation(), DeclarationName());
1477   SourceLocation ExprLoc = E->getBeginLoc();
1478   TypeSourceInfo *TargetLoc =
1479       S.Context.getTrivialTypeSourceInfo(TargetType, ExprLoc);
1480 
1481   return S
1482       .BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
1483                          SourceRange(ExprLoc, ExprLoc), E->getSourceRange())
1484       .get();
1485 }
1486 
1487 /// Build a variable declaration for move parameter.
1488 static VarDecl *buildVarDecl(Sema &S, SourceLocation Loc, QualType Type,
1489                              IdentifierInfo *II) {
1490   TypeSourceInfo *TInfo = S.Context.getTrivialTypeSourceInfo(Type, Loc);
1491   VarDecl *Decl = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, II, Type,
1492                                   TInfo, SC_None);
1493   Decl->setImplicit();
1494   return Decl;
1495 }
1496 
1497 // Build statements that move coroutine function parameters to the coroutine
1498 // frame, and store them on the function scope info.
1499 bool Sema::buildCoroutineParameterMoves(SourceLocation Loc) {
1500   assert(isa<FunctionDecl>(CurContext) && "not in a function scope");
1501   auto *FD = cast<FunctionDecl>(CurContext);
1502 
1503   auto *ScopeInfo = getCurFunction();
1504   assert(ScopeInfo->CoroutineParameterMoves.empty() &&
1505          "Should not build parameter moves twice");
1506 
1507   for (auto *PD : FD->parameters()) {
1508     if (PD->getType()->isDependentType())
1509       continue;
1510 
1511     ExprResult PDRefExpr =
1512         BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
1513                          ExprValueKind::VK_LValue, Loc); // FIXME: scope?
1514     if (PDRefExpr.isInvalid())
1515       return false;
1516 
1517     Expr *CExpr = nullptr;
1518     if (PD->getType()->getAsCXXRecordDecl() ||
1519         PD->getType()->isRValueReferenceType())
1520       CExpr = castForMoving(*this, PDRefExpr.get());
1521     else
1522       CExpr = PDRefExpr.get();
1523 
1524     auto D = buildVarDecl(*this, Loc, PD->getType(), PD->getIdentifier());
1525     AddInitializerToDecl(D, CExpr, /*DirectInit=*/true);
1526 
1527     // Convert decl to a statement.
1528     StmtResult Stmt = ActOnDeclStmt(ConvertDeclToDeclGroup(D), Loc, Loc);
1529     if (Stmt.isInvalid())
1530       return false;
1531 
1532     ScopeInfo->CoroutineParameterMoves.insert(std::make_pair(PD, Stmt.get()));
1533   }
1534   return true;
1535 }
1536 
1537 StmtResult Sema::BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
1538   CoroutineBodyStmt *Res = CoroutineBodyStmt::Create(Context, Args);
1539   if (!Res)
1540     return StmtError();
1541   return Res;
1542 }
1543 
1544 ClassTemplateDecl *Sema::lookupCoroutineTraits(SourceLocation KwLoc,
1545                                                SourceLocation FuncLoc) {
1546   if (!StdCoroutineTraitsCache) {
1547     if (auto StdExp = lookupStdExperimentalNamespace()) {
1548       LookupResult Result(*this,
1549                           &PP.getIdentifierTable().get("coroutine_traits"),
1550                           FuncLoc, LookupOrdinaryName);
1551       if (!LookupQualifiedName(Result, StdExp)) {
1552         Diag(KwLoc, diag::err_implied_coroutine_type_not_found)
1553             << "std::experimental::coroutine_traits";
1554         return nullptr;
1555       }
1556       if (!(StdCoroutineTraitsCache =
1557                 Result.getAsSingle<ClassTemplateDecl>())) {
1558         Result.suppressDiagnostics();
1559         NamedDecl *Found = *Result.begin();
1560         Diag(Found->getLocation(), diag::err_malformed_std_coroutine_traits);
1561         return nullptr;
1562       }
1563     }
1564   }
1565   return StdCoroutineTraitsCache;
1566 }
1567