xref: /freebsd/contrib/llvm-project/clang/lib/Sema/SemaCoroutine.cpp (revision c8e7f78a3d28ff6e6223ed136ada8e1e2f34965e)
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/Basic/Builtins.h"
22 #include "clang/Lex/Preprocessor.h"
23 #include "clang/Sema/Initialization.h"
24 #include "clang/Sema/Overload.h"
25 #include "clang/Sema/ScopeInfo.h"
26 #include "clang/Sema/SemaInternal.h"
27 #include "llvm/ADT/SmallSet.h"
28 
29 using namespace clang;
30 using namespace sema;
31 
32 static LookupResult lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD,
33                                  SourceLocation Loc, bool &Res) {
34   DeclarationName DN = S.PP.getIdentifierInfo(Name);
35   LookupResult LR(S, DN, Loc, Sema::LookupMemberName);
36   // Suppress diagnostics when a private member is selected. The same warnings
37   // will be produced again when building the call.
38   LR.suppressDiagnostics();
39   Res = S.LookupQualifiedName(LR, RD);
40   return LR;
41 }
42 
43 static bool lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD,
44                          SourceLocation Loc) {
45   bool Res;
46   lookupMember(S, Name, RD, Loc, Res);
47   return Res;
48 }
49 
50 /// Look up the std::coroutine_traits<...>::promise_type for the given
51 /// function type.
52 static QualType lookupPromiseType(Sema &S, const FunctionDecl *FD,
53                                   SourceLocation KwLoc) {
54   const FunctionProtoType *FnType = FD->getType()->castAs<FunctionProtoType>();
55   const SourceLocation FuncLoc = FD->getLocation();
56 
57   ClassTemplateDecl *CoroTraits =
58       S.lookupCoroutineTraits(KwLoc, FuncLoc);
59   if (!CoroTraits)
60     return QualType();
61 
62   // Form template argument list for coroutine_traits<R, P1, P2, ...> according
63   // to [dcl.fct.def.coroutine]3
64   TemplateArgumentListInfo Args(KwLoc, KwLoc);
65   auto AddArg = [&](QualType T) {
66     Args.addArgument(TemplateArgumentLoc(
67         TemplateArgument(T), S.Context.getTrivialTypeSourceInfo(T, KwLoc)));
68   };
69   AddArg(FnType->getReturnType());
70   // If the function is a non-static member function, add the type
71   // of the implicit object parameter before the formal parameters.
72   if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
73     if (MD->isInstance()) {
74       // [over.match.funcs]4
75       // For non-static member functions, the type of the implicit object
76       // parameter is
77       //  -- "lvalue reference to cv X" for functions declared without a
78       //      ref-qualifier or with the & ref-qualifier
79       //  -- "rvalue reference to cv X" for functions declared with the &&
80       //      ref-qualifier
81       QualType T = MD->getThisType()->castAs<PointerType>()->getPointeeType();
82       T = FnType->getRefQualifier() == RQ_RValue
83               ? S.Context.getRValueReferenceType(T)
84               : S.Context.getLValueReferenceType(T, /*SpelledAsLValue*/ true);
85       AddArg(T);
86     }
87   }
88   for (QualType T : FnType->getParamTypes())
89     AddArg(T);
90 
91   // Build the template-id.
92   QualType CoroTrait =
93       S.CheckTemplateIdType(TemplateName(CoroTraits), KwLoc, Args);
94   if (CoroTrait.isNull())
95     return QualType();
96   if (S.RequireCompleteType(KwLoc, CoroTrait,
97                             diag::err_coroutine_type_missing_specialization))
98     return QualType();
99 
100   auto *RD = CoroTrait->getAsCXXRecordDecl();
101   assert(RD && "specialization of class template is not a class?");
102 
103   // Look up the ::promise_type member.
104   LookupResult R(S, &S.PP.getIdentifierTable().get("promise_type"), KwLoc,
105                  Sema::LookupOrdinaryName);
106   S.LookupQualifiedName(R, RD);
107   auto *Promise = R.getAsSingle<TypeDecl>();
108   if (!Promise) {
109     S.Diag(FuncLoc,
110            diag::err_implied_std_coroutine_traits_promise_type_not_found)
111         << RD;
112     return QualType();
113   }
114   // The promise type is required to be a class type.
115   QualType PromiseType = S.Context.getTypeDeclType(Promise);
116 
117   auto buildElaboratedType = [&]() {
118     auto *NNS = NestedNameSpecifier::Create(S.Context, nullptr, S.getStdNamespace());
119     NNS = NestedNameSpecifier::Create(S.Context, NNS, false,
120                                       CoroTrait.getTypePtr());
121     return S.Context.getElaboratedType(ETK_None, NNS, PromiseType);
122   };
123 
124   if (!PromiseType->getAsCXXRecordDecl()) {
125     S.Diag(FuncLoc,
126            diag::err_implied_std_coroutine_traits_promise_type_not_class)
127         << buildElaboratedType();
128     return QualType();
129   }
130   if (S.RequireCompleteType(FuncLoc, buildElaboratedType(),
131                             diag::err_coroutine_promise_type_incomplete))
132     return QualType();
133 
134   return PromiseType;
135 }
136 
137 /// Look up the std::coroutine_handle<PromiseType>.
138 static QualType lookupCoroutineHandleType(Sema &S, QualType PromiseType,
139                                           SourceLocation Loc) {
140   if (PromiseType.isNull())
141     return QualType();
142 
143   NamespaceDecl *CoroNamespace = S.getStdNamespace();
144   assert(CoroNamespace && "Should already be diagnosed");
145 
146   LookupResult Result(S, &S.PP.getIdentifierTable().get("coroutine_handle"),
147                       Loc, Sema::LookupOrdinaryName);
148   if (!S.LookupQualifiedName(Result, CoroNamespace)) {
149     S.Diag(Loc, diag::err_implied_coroutine_type_not_found)
150         << "std::coroutine_handle";
151     return QualType();
152   }
153 
154   ClassTemplateDecl *CoroHandle = Result.getAsSingle<ClassTemplateDecl>();
155   if (!CoroHandle) {
156     Result.suppressDiagnostics();
157     // We found something weird. Complain about the first thing we found.
158     NamedDecl *Found = *Result.begin();
159     S.Diag(Found->getLocation(), diag::err_malformed_std_coroutine_handle);
160     return QualType();
161   }
162 
163   // Form template argument list for coroutine_handle<Promise>.
164   TemplateArgumentListInfo Args(Loc, Loc);
165   Args.addArgument(TemplateArgumentLoc(
166       TemplateArgument(PromiseType),
167       S.Context.getTrivialTypeSourceInfo(PromiseType, Loc)));
168 
169   // Build the template-id.
170   QualType CoroHandleType =
171       S.CheckTemplateIdType(TemplateName(CoroHandle), Loc, Args);
172   if (CoroHandleType.isNull())
173     return QualType();
174   if (S.RequireCompleteType(Loc, CoroHandleType,
175                             diag::err_coroutine_type_missing_specialization))
176     return QualType();
177 
178   return CoroHandleType;
179 }
180 
181 static bool isValidCoroutineContext(Sema &S, SourceLocation Loc,
182                                     StringRef Keyword) {
183   // [expr.await]p2 dictates that 'co_await' and 'co_yield' must be used within
184   // a function body.
185   // FIXME: This also covers [expr.await]p2: "An await-expression shall not
186   // appear in a default argument." But the diagnostic QoI here could be
187   // improved to inform the user that default arguments specifically are not
188   // allowed.
189   auto *FD = dyn_cast<FunctionDecl>(S.CurContext);
190   if (!FD) {
191     S.Diag(Loc, isa<ObjCMethodDecl>(S.CurContext)
192                     ? diag::err_coroutine_objc_method
193                     : diag::err_coroutine_outside_function) << Keyword;
194     return false;
195   }
196 
197   // An enumeration for mapping the diagnostic type to the correct diagnostic
198   // selection index.
199   enum InvalidFuncDiag {
200     DiagCtor = 0,
201     DiagDtor,
202     DiagMain,
203     DiagConstexpr,
204     DiagAutoRet,
205     DiagVarargs,
206     DiagConsteval,
207   };
208   bool Diagnosed = false;
209   auto DiagInvalid = [&](InvalidFuncDiag ID) {
210     S.Diag(Loc, diag::err_coroutine_invalid_func_context) << ID << Keyword;
211     Diagnosed = true;
212     return false;
213   };
214 
215   // Diagnose when a constructor, destructor
216   // or the function 'main' are declared as a coroutine.
217   auto *MD = dyn_cast<CXXMethodDecl>(FD);
218   // [class.ctor]p11: "A constructor shall not be a coroutine."
219   if (MD && isa<CXXConstructorDecl>(MD))
220     return DiagInvalid(DiagCtor);
221   // [class.dtor]p17: "A destructor shall not be a coroutine."
222   else if (MD && isa<CXXDestructorDecl>(MD))
223     return DiagInvalid(DiagDtor);
224   // [basic.start.main]p3: "The function main shall not be a coroutine."
225   else if (FD->isMain())
226     return DiagInvalid(DiagMain);
227 
228   // Emit a diagnostics for each of the following conditions which is not met.
229   // [expr.const]p2: "An expression e is a core constant expression unless the
230   // evaluation of e [...] would evaluate one of the following expressions:
231   // [...] an await-expression [...] a yield-expression."
232   if (FD->isConstexpr())
233     DiagInvalid(FD->isConsteval() ? DiagConsteval : DiagConstexpr);
234   // [dcl.spec.auto]p15: "A function declared with a return type that uses a
235   // placeholder type shall not be a coroutine."
236   if (FD->getReturnType()->isUndeducedType())
237     DiagInvalid(DiagAutoRet);
238   // [dcl.fct.def.coroutine]p1
239   // The parameter-declaration-clause of the coroutine shall not terminate with
240   // an ellipsis that is not part of a parameter-declaration.
241   if (FD->isVariadic())
242     DiagInvalid(DiagVarargs);
243 
244   return !Diagnosed;
245 }
246 
247 /// Build a call to 'operator co_await' if there is a suitable operator for
248 /// the given expression.
249 ExprResult Sema::BuildOperatorCoawaitCall(SourceLocation Loc, Expr *E,
250                                           UnresolvedLookupExpr *Lookup) {
251   UnresolvedSet<16> Functions;
252   Functions.append(Lookup->decls_begin(), Lookup->decls_end());
253   return CreateOverloadedUnaryOp(Loc, UO_Coawait, Functions, E);
254 }
255 
256 static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, Scope *S,
257                                            SourceLocation Loc, Expr *E) {
258   ExprResult R = SemaRef.BuildOperatorCoawaitLookupExpr(S, Loc);
259   if (R.isInvalid())
260     return ExprError();
261   return SemaRef.BuildOperatorCoawaitCall(Loc, E,
262                                           cast<UnresolvedLookupExpr>(R.get()));
263 }
264 
265 static ExprResult buildCoroutineHandle(Sema &S, QualType PromiseType,
266                                        SourceLocation Loc) {
267   QualType CoroHandleType = lookupCoroutineHandleType(S, PromiseType, Loc);
268   if (CoroHandleType.isNull())
269     return ExprError();
270 
271   DeclContext *LookupCtx = S.computeDeclContext(CoroHandleType);
272   LookupResult Found(S, &S.PP.getIdentifierTable().get("from_address"), Loc,
273                      Sema::LookupOrdinaryName);
274   if (!S.LookupQualifiedName(Found, LookupCtx)) {
275     S.Diag(Loc, diag::err_coroutine_handle_missing_member)
276         << "from_address";
277     return ExprError();
278   }
279 
280   Expr *FramePtr =
281       S.BuildBuiltinCallExpr(Loc, Builtin::BI__builtin_coro_frame, {});
282 
283   CXXScopeSpec SS;
284   ExprResult FromAddr =
285       S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
286   if (FromAddr.isInvalid())
287     return ExprError();
288 
289   return S.BuildCallExpr(nullptr, FromAddr.get(), Loc, FramePtr, Loc);
290 }
291 
292 struct ReadySuspendResumeResult {
293   enum AwaitCallType { ACT_Ready, ACT_Suspend, ACT_Resume };
294   Expr *Results[3];
295   OpaqueValueExpr *OpaqueValue;
296   bool IsInvalid;
297 };
298 
299 static ExprResult buildMemberCall(Sema &S, Expr *Base, SourceLocation Loc,
300                                   StringRef Name, MultiExprArg Args) {
301   DeclarationNameInfo NameInfo(&S.PP.getIdentifierTable().get(Name), Loc);
302 
303   // FIXME: Fix BuildMemberReferenceExpr to take a const CXXScopeSpec&.
304   CXXScopeSpec SS;
305   ExprResult Result = S.BuildMemberReferenceExpr(
306       Base, Base->getType(), Loc, /*IsPtr=*/false, SS,
307       SourceLocation(), nullptr, NameInfo, /*TemplateArgs=*/nullptr,
308       /*Scope=*/nullptr);
309   if (Result.isInvalid())
310     return ExprError();
311 
312   // We meant exactly what we asked for. No need for typo correction.
313   if (auto *TE = dyn_cast<TypoExpr>(Result.get())) {
314     S.clearDelayedTypo(TE);
315     S.Diag(Loc, diag::err_no_member)
316         << NameInfo.getName() << Base->getType()->getAsCXXRecordDecl()
317         << Base->getSourceRange();
318     return ExprError();
319   }
320 
321   return S.BuildCallExpr(nullptr, Result.get(), Loc, Args, Loc, nullptr);
322 }
323 
324 // See if return type is coroutine-handle and if so, invoke builtin coro-resume
325 // on its address. This is to enable the support for coroutine-handle
326 // returning await_suspend that results in a guaranteed tail call to the target
327 // coroutine.
328 static Expr *maybeTailCall(Sema &S, QualType RetType, Expr *E,
329                            SourceLocation Loc) {
330   if (RetType->isReferenceType())
331     return nullptr;
332   Type const *T = RetType.getTypePtr();
333   if (!T->isClassType() && !T->isStructureType())
334     return nullptr;
335 
336   // FIXME: Add convertability check to coroutine_handle<>. Possibly via
337   // EvaluateBinaryTypeTrait(BTT_IsConvertible, ...) which is at the moment
338   // a private function in SemaExprCXX.cpp
339 
340   ExprResult AddressExpr = buildMemberCall(S, E, Loc, "address", std::nullopt);
341   if (AddressExpr.isInvalid())
342     return nullptr;
343 
344   Expr *JustAddress = AddressExpr.get();
345 
346   // Check that the type of AddressExpr is void*
347   if (!JustAddress->getType().getTypePtr()->isVoidPointerType())
348     S.Diag(cast<CallExpr>(JustAddress)->getCalleeDecl()->getLocation(),
349            diag::warn_coroutine_handle_address_invalid_return_type)
350         << JustAddress->getType();
351 
352   // Clean up temporary objects so that they don't live across suspension points
353   // unnecessarily. We choose to clean up before the call to
354   // __builtin_coro_resume so that the cleanup code are not inserted in-between
355   // the resume call and return instruction, which would interfere with the
356   // musttail call contract.
357   JustAddress = S.MaybeCreateExprWithCleanups(JustAddress);
358   return S.BuildBuiltinCallExpr(Loc, Builtin::BI__builtin_coro_resume,
359                                 JustAddress);
360 }
361 
362 /// Build calls to await_ready, await_suspend, and await_resume for a co_await
363 /// expression.
364 /// The generated AST tries to clean up temporary objects as early as
365 /// possible so that they don't live across suspension points if possible.
366 /// Having temporary objects living across suspension points unnecessarily can
367 /// lead to large frame size, and also lead to memory corruptions if the
368 /// coroutine frame is destroyed after coming back from suspension. This is done
369 /// by wrapping both the await_ready call and the await_suspend call with
370 /// ExprWithCleanups. In the end of this function, we also need to explicitly
371 /// set cleanup state so that the CoawaitExpr is also wrapped with an
372 /// ExprWithCleanups to clean up the awaiter associated with the co_await
373 /// expression.
374 static ReadySuspendResumeResult buildCoawaitCalls(Sema &S, VarDecl *CoroPromise,
375                                                   SourceLocation Loc, Expr *E) {
376   OpaqueValueExpr *Operand = new (S.Context)
377       OpaqueValueExpr(Loc, E->getType(), VK_LValue, E->getObjectKind(), E);
378 
379   // Assume valid until we see otherwise.
380   // Further operations are responsible for setting IsInalid to true.
381   ReadySuspendResumeResult Calls = {{}, Operand, /*IsInvalid=*/false};
382 
383   using ACT = ReadySuspendResumeResult::AwaitCallType;
384 
385   auto BuildSubExpr = [&](ACT CallType, StringRef Func,
386                           MultiExprArg Arg) -> Expr * {
387     ExprResult Result = buildMemberCall(S, Operand, Loc, Func, Arg);
388     if (Result.isInvalid()) {
389       Calls.IsInvalid = true;
390       return nullptr;
391     }
392     Calls.Results[CallType] = Result.get();
393     return Result.get();
394   };
395 
396   CallExpr *AwaitReady = cast_or_null<CallExpr>(
397       BuildSubExpr(ACT::ACT_Ready, "await_ready", std::nullopt));
398   if (!AwaitReady)
399     return Calls;
400   if (!AwaitReady->getType()->isDependentType()) {
401     // [expr.await]p3 [...]
402     // — await-ready is the expression e.await_ready(), contextually converted
403     // to bool.
404     ExprResult Conv = S.PerformContextuallyConvertToBool(AwaitReady);
405     if (Conv.isInvalid()) {
406       S.Diag(AwaitReady->getDirectCallee()->getBeginLoc(),
407              diag::note_await_ready_no_bool_conversion);
408       S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
409           << AwaitReady->getDirectCallee() << E->getSourceRange();
410       Calls.IsInvalid = true;
411     } else
412       Calls.Results[ACT::ACT_Ready] = S.MaybeCreateExprWithCleanups(Conv.get());
413   }
414 
415   ExprResult CoroHandleRes =
416       buildCoroutineHandle(S, CoroPromise->getType(), Loc);
417   if (CoroHandleRes.isInvalid()) {
418     Calls.IsInvalid = true;
419     return Calls;
420   }
421   Expr *CoroHandle = CoroHandleRes.get();
422   CallExpr *AwaitSuspend = cast_or_null<CallExpr>(
423       BuildSubExpr(ACT::ACT_Suspend, "await_suspend", CoroHandle));
424   if (!AwaitSuspend)
425     return Calls;
426   if (!AwaitSuspend->getType()->isDependentType()) {
427     // [expr.await]p3 [...]
428     //   - await-suspend is the expression e.await_suspend(h), which shall be
429     //     a prvalue of type void, bool, or std::coroutine_handle<Z> for some
430     //     type Z.
431     QualType RetType = AwaitSuspend->getCallReturnType(S.Context);
432 
433     // Support for coroutine_handle returning await_suspend.
434     if (Expr *TailCallSuspend =
435             maybeTailCall(S, RetType, AwaitSuspend, Loc))
436       // Note that we don't wrap the expression with ExprWithCleanups here
437       // because that might interfere with tailcall contract (e.g. inserting
438       // clean up instructions in-between tailcall and return). Instead
439       // ExprWithCleanups is wrapped within maybeTailCall() prior to the resume
440       // call.
441       Calls.Results[ACT::ACT_Suspend] = TailCallSuspend;
442     else {
443       // non-class prvalues always have cv-unqualified types
444       if (RetType->isReferenceType() ||
445           (!RetType->isBooleanType() && !RetType->isVoidType())) {
446         S.Diag(AwaitSuspend->getCalleeDecl()->getLocation(),
447                diag::err_await_suspend_invalid_return_type)
448             << RetType;
449         S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
450             << AwaitSuspend->getDirectCallee();
451         Calls.IsInvalid = true;
452       } else
453         Calls.Results[ACT::ACT_Suspend] =
454             S.MaybeCreateExprWithCleanups(AwaitSuspend);
455     }
456   }
457 
458   BuildSubExpr(ACT::ACT_Resume, "await_resume", std::nullopt);
459 
460   // Make sure the awaiter object gets a chance to be cleaned up.
461   S.Cleanup.setExprNeedsCleanups(true);
462 
463   return Calls;
464 }
465 
466 static ExprResult buildPromiseCall(Sema &S, VarDecl *Promise,
467                                    SourceLocation Loc, StringRef Name,
468                                    MultiExprArg Args) {
469 
470   // Form a reference to the promise.
471   ExprResult PromiseRef = S.BuildDeclRefExpr(
472       Promise, Promise->getType().getNonReferenceType(), VK_LValue, Loc);
473   if (PromiseRef.isInvalid())
474     return ExprError();
475 
476   return buildMemberCall(S, PromiseRef.get(), Loc, Name, Args);
477 }
478 
479 VarDecl *Sema::buildCoroutinePromise(SourceLocation Loc) {
480   assert(isa<FunctionDecl>(CurContext) && "not in a function scope");
481   auto *FD = cast<FunctionDecl>(CurContext);
482   bool IsThisDependentType = [&] {
483     if (auto *MD = dyn_cast_or_null<CXXMethodDecl>(FD))
484       return MD->isInstance() && MD->getThisType()->isDependentType();
485     else
486       return false;
487   }();
488 
489   QualType T = FD->getType()->isDependentType() || IsThisDependentType
490                    ? Context.DependentTy
491                    : lookupPromiseType(*this, FD, Loc);
492   if (T.isNull())
493     return nullptr;
494 
495   auto *VD = VarDecl::Create(Context, FD, FD->getLocation(), FD->getLocation(),
496                              &PP.getIdentifierTable().get("__promise"), T,
497                              Context.getTrivialTypeSourceInfo(T, Loc), SC_None);
498   VD->setImplicit();
499   CheckVariableDeclarationType(VD);
500   if (VD->isInvalidDecl())
501     return nullptr;
502 
503   auto *ScopeInfo = getCurFunction();
504 
505   // Build a list of arguments, based on the coroutine function's arguments,
506   // that if present will be passed to the promise type's constructor.
507   llvm::SmallVector<Expr *, 4> CtorArgExprs;
508 
509   // Add implicit object parameter.
510   if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
511     if (MD->isInstance() && !isLambdaCallOperator(MD)) {
512       ExprResult ThisExpr = ActOnCXXThis(Loc);
513       if (ThisExpr.isInvalid())
514         return nullptr;
515       ThisExpr = CreateBuiltinUnaryOp(Loc, UO_Deref, ThisExpr.get());
516       if (ThisExpr.isInvalid())
517         return nullptr;
518       CtorArgExprs.push_back(ThisExpr.get());
519     }
520   }
521 
522   // Add the coroutine function's parameters.
523   auto &Moves = ScopeInfo->CoroutineParameterMoves;
524   for (auto *PD : FD->parameters()) {
525     if (PD->getType()->isDependentType())
526       continue;
527 
528     auto RefExpr = ExprEmpty();
529     auto Move = Moves.find(PD);
530     assert(Move != Moves.end() &&
531            "Coroutine function parameter not inserted into move map");
532     // If a reference to the function parameter exists in the coroutine
533     // frame, use that reference.
534     auto *MoveDecl =
535         cast<VarDecl>(cast<DeclStmt>(Move->second)->getSingleDecl());
536     RefExpr =
537         BuildDeclRefExpr(MoveDecl, MoveDecl->getType().getNonReferenceType(),
538                          ExprValueKind::VK_LValue, FD->getLocation());
539     if (RefExpr.isInvalid())
540       return nullptr;
541     CtorArgExprs.push_back(RefExpr.get());
542   }
543 
544   // If we have a non-zero number of constructor arguments, try to use them.
545   // Otherwise, fall back to the promise type's default constructor.
546   if (!CtorArgExprs.empty()) {
547     // Create an initialization sequence for the promise type using the
548     // constructor arguments, wrapped in a parenthesized list expression.
549     Expr *PLE = ParenListExpr::Create(Context, FD->getLocation(),
550                                       CtorArgExprs, FD->getLocation());
551     InitializedEntity Entity = InitializedEntity::InitializeVariable(VD);
552     InitializationKind Kind = InitializationKind::CreateForInit(
553         VD->getLocation(), /*DirectInit=*/true, PLE);
554     InitializationSequence InitSeq(*this, Entity, Kind, CtorArgExprs,
555                                    /*TopLevelOfInitList=*/false,
556                                    /*TreatUnavailableAsInvalid=*/false);
557 
558     // [dcl.fct.def.coroutine]5.7
559     // promise-constructor-arguments is determined as follows: overload
560     // resolution is performed on a promise constructor call created by
561     // assembling an argument list  q_1 ... q_n . If a viable constructor is
562     // found ([over.match.viable]), then promise-constructor-arguments is ( q_1
563     // , ...,  q_n ), otherwise promise-constructor-arguments is empty.
564     if (InitSeq) {
565       ExprResult Result = InitSeq.Perform(*this, Entity, Kind, CtorArgExprs);
566       if (Result.isInvalid()) {
567         VD->setInvalidDecl();
568       } else if (Result.get()) {
569         VD->setInit(MaybeCreateExprWithCleanups(Result.get()));
570         VD->setInitStyle(VarDecl::CallInit);
571         CheckCompleteVariableDeclaration(VD);
572       }
573     } else
574       ActOnUninitializedDecl(VD);
575   } else
576     ActOnUninitializedDecl(VD);
577 
578   FD->addDecl(VD);
579   return VD;
580 }
581 
582 /// Check that this is a context in which a coroutine suspension can appear.
583 static FunctionScopeInfo *checkCoroutineContext(Sema &S, SourceLocation Loc,
584                                                 StringRef Keyword,
585                                                 bool IsImplicit = false) {
586   if (!isValidCoroutineContext(S, Loc, Keyword))
587     return nullptr;
588 
589   assert(isa<FunctionDecl>(S.CurContext) && "not in a function scope");
590 
591   auto *ScopeInfo = S.getCurFunction();
592   assert(ScopeInfo && "missing function scope for function");
593 
594   if (ScopeInfo->FirstCoroutineStmtLoc.isInvalid() && !IsImplicit)
595     ScopeInfo->setFirstCoroutineStmt(Loc, Keyword);
596 
597   if (ScopeInfo->CoroutinePromise)
598     return ScopeInfo;
599 
600   if (!S.buildCoroutineParameterMoves(Loc))
601     return nullptr;
602 
603   ScopeInfo->CoroutinePromise = S.buildCoroutinePromise(Loc);
604   if (!ScopeInfo->CoroutinePromise)
605     return nullptr;
606 
607   return ScopeInfo;
608 }
609 
610 /// Recursively check \p E and all its children to see if any call target
611 /// (including constructor call) is declared noexcept. Also any value returned
612 /// from the call has a noexcept destructor.
613 static void checkNoThrow(Sema &S, const Stmt *E,
614                          llvm::SmallPtrSetImpl<const Decl *> &ThrowingDecls) {
615   auto checkDeclNoexcept = [&](const Decl *D, bool IsDtor = false) {
616     // In the case of dtor, the call to dtor is implicit and hence we should
617     // pass nullptr to canCalleeThrow.
618     if (Sema::canCalleeThrow(S, IsDtor ? nullptr : cast<Expr>(E), D)) {
619       if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
620         // co_await promise.final_suspend() could end up calling
621         // __builtin_coro_resume for symmetric transfer if await_suspend()
622         // returns a handle. In that case, even __builtin_coro_resume is not
623         // declared as noexcept and may throw, it does not throw _into_ the
624         // coroutine that just suspended, but rather throws back out from
625         // whoever called coroutine_handle::resume(), hence we claim that
626         // logically it does not throw.
627         if (FD->getBuiltinID() == Builtin::BI__builtin_coro_resume)
628           return;
629       }
630       if (ThrowingDecls.empty()) {
631         // [dcl.fct.def.coroutine]p15
632         //   The expression co_await promise.final_suspend() shall not be
633         //   potentially-throwing ([except.spec]).
634         //
635         // First time seeing an error, emit the error message.
636         S.Diag(cast<FunctionDecl>(S.CurContext)->getLocation(),
637                diag::err_coroutine_promise_final_suspend_requires_nothrow);
638       }
639       ThrowingDecls.insert(D);
640     }
641   };
642 
643   if (auto *CE = dyn_cast<CXXConstructExpr>(E)) {
644     CXXConstructorDecl *Ctor = CE->getConstructor();
645     checkDeclNoexcept(Ctor);
646     // Check the corresponding destructor of the constructor.
647     checkDeclNoexcept(Ctor->getParent()->getDestructor(), /*IsDtor=*/true);
648   } else if (auto *CE = dyn_cast<CallExpr>(E)) {
649     if (CE->isTypeDependent())
650       return;
651 
652     checkDeclNoexcept(CE->getCalleeDecl());
653     QualType ReturnType = CE->getCallReturnType(S.getASTContext());
654     // Check the destructor of the call return type, if any.
655     if (ReturnType.isDestructedType() ==
656         QualType::DestructionKind::DK_cxx_destructor) {
657       const auto *T =
658           cast<RecordType>(ReturnType.getCanonicalType().getTypePtr());
659       checkDeclNoexcept(cast<CXXRecordDecl>(T->getDecl())->getDestructor(),
660                         /*IsDtor=*/true);
661     }
662   } else
663     for (const auto *Child : E->children()) {
664       if (!Child)
665         continue;
666       checkNoThrow(S, Child, ThrowingDecls);
667     }
668 }
669 
670 bool Sema::checkFinalSuspendNoThrow(const Stmt *FinalSuspend) {
671   llvm::SmallPtrSet<const Decl *, 4> ThrowingDecls;
672   // We first collect all declarations that should not throw but not declared
673   // with noexcept. We then sort them based on the location before printing.
674   // This is to avoid emitting the same note multiple times on the same
675   // declaration, and also provide a deterministic order for the messages.
676   checkNoThrow(*this, FinalSuspend, ThrowingDecls);
677   auto SortedDecls = llvm::SmallVector<const Decl *, 4>{ThrowingDecls.begin(),
678                                                         ThrowingDecls.end()};
679   sort(SortedDecls, [](const Decl *A, const Decl *B) {
680     return A->getEndLoc() < B->getEndLoc();
681   });
682   for (const auto *D : SortedDecls) {
683     Diag(D->getEndLoc(), diag::note_coroutine_function_declare_noexcept);
684   }
685   return ThrowingDecls.empty();
686 }
687 
688 bool Sema::ActOnCoroutineBodyStart(Scope *SC, SourceLocation KWLoc,
689                                    StringRef Keyword) {
690   if (!checkCoroutineContext(*this, KWLoc, Keyword))
691     return false;
692   auto *ScopeInfo = getCurFunction();
693   assert(ScopeInfo->CoroutinePromise);
694 
695   // If we have existing coroutine statements then we have already built
696   // the initial and final suspend points.
697   if (!ScopeInfo->NeedsCoroutineSuspends)
698     return true;
699 
700   ScopeInfo->setNeedsCoroutineSuspends(false);
701 
702   auto *Fn = cast<FunctionDecl>(CurContext);
703   SourceLocation Loc = Fn->getLocation();
704   // Build the initial suspend point
705   auto buildSuspends = [&](StringRef Name) mutable -> StmtResult {
706     ExprResult Operand = buildPromiseCall(*this, ScopeInfo->CoroutinePromise,
707                                           Loc, Name, std::nullopt);
708     if (Operand.isInvalid())
709       return StmtError();
710     ExprResult Suspend =
711         buildOperatorCoawaitCall(*this, SC, Loc, Operand.get());
712     if (Suspend.isInvalid())
713       return StmtError();
714     Suspend = BuildResolvedCoawaitExpr(Loc, Operand.get(), Suspend.get(),
715                                        /*IsImplicit*/ true);
716     Suspend = ActOnFinishFullExpr(Suspend.get(), /*DiscardedValue*/ false);
717     if (Suspend.isInvalid()) {
718       Diag(Loc, diag::note_coroutine_promise_suspend_implicitly_required)
719           << ((Name == "initial_suspend") ? 0 : 1);
720       Diag(KWLoc, diag::note_declared_coroutine_here) << Keyword;
721       return StmtError();
722     }
723     return cast<Stmt>(Suspend.get());
724   };
725 
726   StmtResult InitSuspend = buildSuspends("initial_suspend");
727   if (InitSuspend.isInvalid())
728     return true;
729 
730   StmtResult FinalSuspend = buildSuspends("final_suspend");
731   if (FinalSuspend.isInvalid() || !checkFinalSuspendNoThrow(FinalSuspend.get()))
732     return true;
733 
734   ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());
735 
736   return true;
737 }
738 
739 // Recursively walks up the scope hierarchy until either a 'catch' or a function
740 // scope is found, whichever comes first.
741 static bool isWithinCatchScope(Scope *S) {
742   // 'co_await' and 'co_yield' keywords are disallowed within catch blocks, but
743   // lambdas that use 'co_await' are allowed. The loop below ends when a
744   // function scope is found in order to ensure the following behavior:
745   //
746   // void foo() {      // <- function scope
747   //   try {           //
748   //     co_await x;   // <- 'co_await' is OK within a function scope
749   //   } catch {       // <- catch scope
750   //     co_await x;   // <- 'co_await' is not OK within a catch scope
751   //     []() {        // <- function scope
752   //       co_await x; // <- 'co_await' is OK within a function scope
753   //     }();
754   //   }
755   // }
756   while (S && !S->isFunctionScope()) {
757     if (S->isCatchScope())
758       return true;
759     S = S->getParent();
760   }
761   return false;
762 }
763 
764 // [expr.await]p2, emphasis added: "An await-expression shall appear only in
765 // a *potentially evaluated* expression within the compound-statement of a
766 // function-body *outside of a handler* [...] A context within a function
767 // where an await-expression can appear is called a suspension context of the
768 // function."
769 static bool checkSuspensionContext(Sema &S, SourceLocation Loc,
770                                    StringRef Keyword) {
771   // First emphasis of [expr.await]p2: must be a potentially evaluated context.
772   // That is, 'co_await' and 'co_yield' cannot appear in subexpressions of
773   // \c sizeof.
774   if (S.isUnevaluatedContext()) {
775     S.Diag(Loc, diag::err_coroutine_unevaluated_context) << Keyword;
776     return false;
777   }
778 
779   // Second emphasis of [expr.await]p2: must be outside of an exception handler.
780   if (isWithinCatchScope(S.getCurScope())) {
781     S.Diag(Loc, diag::err_coroutine_within_handler) << Keyword;
782     return false;
783   }
784 
785   return true;
786 }
787 
788 ExprResult Sema::ActOnCoawaitExpr(Scope *S, SourceLocation Loc, Expr *E) {
789   if (!checkSuspensionContext(*this, Loc, "co_await"))
790     return ExprError();
791 
792   if (!ActOnCoroutineBodyStart(S, Loc, "co_await")) {
793     CorrectDelayedTyposInExpr(E);
794     return ExprError();
795   }
796 
797   if (E->hasPlaceholderType()) {
798     ExprResult R = CheckPlaceholderExpr(E);
799     if (R.isInvalid()) return ExprError();
800     E = R.get();
801   }
802   ExprResult Lookup = BuildOperatorCoawaitLookupExpr(S, Loc);
803   if (Lookup.isInvalid())
804     return ExprError();
805   return BuildUnresolvedCoawaitExpr(Loc, E,
806                                    cast<UnresolvedLookupExpr>(Lookup.get()));
807 }
808 
809 ExprResult Sema::BuildOperatorCoawaitLookupExpr(Scope *S, SourceLocation Loc) {
810   DeclarationName OpName =
811       Context.DeclarationNames.getCXXOperatorName(OO_Coawait);
812   LookupResult Operators(*this, OpName, SourceLocation(),
813                          Sema::LookupOperatorName);
814   LookupName(Operators, S);
815 
816   assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
817   const auto &Functions = Operators.asUnresolvedSet();
818   bool IsOverloaded =
819       Functions.size() > 1 ||
820       (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
821   Expr *CoawaitOp = UnresolvedLookupExpr::Create(
822       Context, /*NamingClass*/ nullptr, NestedNameSpecifierLoc(),
823       DeclarationNameInfo(OpName, Loc), /*RequiresADL*/ true, IsOverloaded,
824       Functions.begin(), Functions.end());
825   assert(CoawaitOp);
826   return CoawaitOp;
827 }
828 
829 // Attempts to resolve and build a CoawaitExpr from "raw" inputs, bailing out to
830 // DependentCoawaitExpr if needed.
831 ExprResult Sema::BuildUnresolvedCoawaitExpr(SourceLocation Loc, Expr *Operand,
832                                             UnresolvedLookupExpr *Lookup) {
833   auto *FSI = checkCoroutineContext(*this, Loc, "co_await");
834   if (!FSI)
835     return ExprError();
836 
837   if (Operand->hasPlaceholderType()) {
838     ExprResult R = CheckPlaceholderExpr(Operand);
839     if (R.isInvalid())
840       return ExprError();
841     Operand = R.get();
842   }
843 
844   auto *Promise = FSI->CoroutinePromise;
845   if (Promise->getType()->isDependentType()) {
846     Expr *Res = new (Context)
847         DependentCoawaitExpr(Loc, Context.DependentTy, Operand, Lookup);
848     return Res;
849   }
850 
851   auto *RD = Promise->getType()->getAsCXXRecordDecl();
852   auto *Transformed = Operand;
853   if (lookupMember(*this, "await_transform", RD, Loc)) {
854     ExprResult R =
855         buildPromiseCall(*this, Promise, Loc, "await_transform", Operand);
856     if (R.isInvalid()) {
857       Diag(Loc,
858            diag::note_coroutine_promise_implicit_await_transform_required_here)
859           << Operand->getSourceRange();
860       return ExprError();
861     }
862     Transformed = R.get();
863   }
864   ExprResult Awaiter = BuildOperatorCoawaitCall(Loc, Transformed, Lookup);
865   if (Awaiter.isInvalid())
866     return ExprError();
867 
868   return BuildResolvedCoawaitExpr(Loc, Operand, Awaiter.get());
869 }
870 
871 ExprResult Sema::BuildResolvedCoawaitExpr(SourceLocation Loc, Expr *Operand,
872                                           Expr *Awaiter, bool IsImplicit) {
873   auto *Coroutine = checkCoroutineContext(*this, Loc, "co_await", IsImplicit);
874   if (!Coroutine)
875     return ExprError();
876 
877   if (Awaiter->hasPlaceholderType()) {
878     ExprResult R = CheckPlaceholderExpr(Awaiter);
879     if (R.isInvalid()) return ExprError();
880     Awaiter = R.get();
881   }
882 
883   if (Awaiter->getType()->isDependentType()) {
884     Expr *Res = new (Context)
885         CoawaitExpr(Loc, Context.DependentTy, Operand, Awaiter, IsImplicit);
886     return Res;
887   }
888 
889   // If the expression is a temporary, materialize it as an lvalue so that we
890   // can use it multiple times.
891   if (Awaiter->isPRValue())
892     Awaiter = CreateMaterializeTemporaryExpr(Awaiter->getType(), Awaiter, true);
893 
894   // The location of the `co_await` token cannot be used when constructing
895   // the member call expressions since it's before the location of `Expr`, which
896   // is used as the start of the member call expression.
897   SourceLocation CallLoc = Awaiter->getExprLoc();
898 
899   // Build the await_ready, await_suspend, await_resume calls.
900   ReadySuspendResumeResult RSS =
901       buildCoawaitCalls(*this, Coroutine->CoroutinePromise, CallLoc, Awaiter);
902   if (RSS.IsInvalid)
903     return ExprError();
904 
905   Expr *Res = new (Context)
906       CoawaitExpr(Loc, Operand, Awaiter, RSS.Results[0], RSS.Results[1],
907                   RSS.Results[2], RSS.OpaqueValue, IsImplicit);
908 
909   return Res;
910 }
911 
912 ExprResult Sema::ActOnCoyieldExpr(Scope *S, SourceLocation Loc, Expr *E) {
913   if (!checkSuspensionContext(*this, Loc, "co_yield"))
914     return ExprError();
915 
916   if (!ActOnCoroutineBodyStart(S, Loc, "co_yield")) {
917     CorrectDelayedTyposInExpr(E);
918     return ExprError();
919   }
920 
921   // Build yield_value call.
922   ExprResult Awaitable = buildPromiseCall(
923       *this, getCurFunction()->CoroutinePromise, Loc, "yield_value", E);
924   if (Awaitable.isInvalid())
925     return ExprError();
926 
927   // Build 'operator co_await' call.
928   Awaitable = buildOperatorCoawaitCall(*this, S, Loc, Awaitable.get());
929   if (Awaitable.isInvalid())
930     return ExprError();
931 
932   return BuildCoyieldExpr(Loc, Awaitable.get());
933 }
934 ExprResult Sema::BuildCoyieldExpr(SourceLocation Loc, Expr *E) {
935   auto *Coroutine = checkCoroutineContext(*this, Loc, "co_yield");
936   if (!Coroutine)
937     return ExprError();
938 
939   if (E->hasPlaceholderType()) {
940     ExprResult R = CheckPlaceholderExpr(E);
941     if (R.isInvalid()) return ExprError();
942     E = R.get();
943   }
944 
945   Expr *Operand = E;
946 
947   if (E->getType()->isDependentType()) {
948     Expr *Res = new (Context) CoyieldExpr(Loc, Context.DependentTy, Operand, E);
949     return Res;
950   }
951 
952   // If the expression is a temporary, materialize it as an lvalue so that we
953   // can use it multiple times.
954   if (E->isPRValue())
955     E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
956 
957   // Build the await_ready, await_suspend, await_resume calls.
958   ReadySuspendResumeResult RSS = buildCoawaitCalls(
959       *this, Coroutine->CoroutinePromise, Loc, E);
960   if (RSS.IsInvalid)
961     return ExprError();
962 
963   Expr *Res =
964       new (Context) CoyieldExpr(Loc, Operand, E, RSS.Results[0], RSS.Results[1],
965                                 RSS.Results[2], RSS.OpaqueValue);
966 
967   return Res;
968 }
969 
970 StmtResult Sema::ActOnCoreturnStmt(Scope *S, SourceLocation Loc, Expr *E) {
971   if (!ActOnCoroutineBodyStart(S, Loc, "co_return")) {
972     CorrectDelayedTyposInExpr(E);
973     return StmtError();
974   }
975   return BuildCoreturnStmt(Loc, E);
976 }
977 
978 StmtResult Sema::BuildCoreturnStmt(SourceLocation Loc, Expr *E,
979                                    bool IsImplicit) {
980   auto *FSI = checkCoroutineContext(*this, Loc, "co_return", IsImplicit);
981   if (!FSI)
982     return StmtError();
983 
984   if (E && E->hasPlaceholderType() &&
985       !E->hasPlaceholderType(BuiltinType::Overload)) {
986     ExprResult R = CheckPlaceholderExpr(E);
987     if (R.isInvalid()) return StmtError();
988     E = R.get();
989   }
990 
991   VarDecl *Promise = FSI->CoroutinePromise;
992   ExprResult PC;
993   if (E && (isa<InitListExpr>(E) || !E->getType()->isVoidType())) {
994     getNamedReturnInfo(E, SimplerImplicitMoveMode::ForceOn);
995     PC = buildPromiseCall(*this, Promise, Loc, "return_value", E);
996   } else {
997     E = MakeFullDiscardedValueExpr(E).get();
998     PC = buildPromiseCall(*this, Promise, Loc, "return_void", std::nullopt);
999   }
1000   if (PC.isInvalid())
1001     return StmtError();
1002 
1003   Expr *PCE = ActOnFinishFullExpr(PC.get(), /*DiscardedValue*/ false).get();
1004 
1005   Stmt *Res = new (Context) CoreturnStmt(Loc, E, PCE, IsImplicit);
1006   return Res;
1007 }
1008 
1009 /// Look up the std::nothrow object.
1010 static Expr *buildStdNoThrowDeclRef(Sema &S, SourceLocation Loc) {
1011   NamespaceDecl *Std = S.getStdNamespace();
1012   assert(Std && "Should already be diagnosed");
1013 
1014   LookupResult Result(S, &S.PP.getIdentifierTable().get("nothrow"), Loc,
1015                       Sema::LookupOrdinaryName);
1016   if (!S.LookupQualifiedName(Result, Std)) {
1017     // <coroutine> is not requred to include <new>, so we couldn't omit
1018     // the check here.
1019     S.Diag(Loc, diag::err_implicit_coroutine_std_nothrow_type_not_found);
1020     return nullptr;
1021   }
1022 
1023   auto *VD = Result.getAsSingle<VarDecl>();
1024   if (!VD) {
1025     Result.suppressDiagnostics();
1026     // We found something weird. Complain about the first thing we found.
1027     NamedDecl *Found = *Result.begin();
1028     S.Diag(Found->getLocation(), diag::err_malformed_std_nothrow);
1029     return nullptr;
1030   }
1031 
1032   ExprResult DR = S.BuildDeclRefExpr(VD, VD->getType(), VK_LValue, Loc);
1033   if (DR.isInvalid())
1034     return nullptr;
1035 
1036   return DR.get();
1037 }
1038 
1039 static TypeSourceInfo *getTypeSourceInfoForStdAlignValT(Sema &S,
1040                                                         SourceLocation Loc) {
1041   EnumDecl *StdAlignValT = S.getStdAlignValT();
1042   QualType StdAlignValDecl = S.Context.getTypeDeclType(StdAlignValT);
1043   return S.Context.getTrivialTypeSourceInfo(StdAlignValDecl);
1044 }
1045 
1046 // Find an appropriate delete for the promise.
1047 static bool findDeleteForPromise(Sema &S, SourceLocation Loc, QualType PromiseType,
1048                                  FunctionDecl *&OperatorDelete) {
1049   DeclarationName DeleteName =
1050       S.Context.DeclarationNames.getCXXOperatorName(OO_Delete);
1051 
1052   auto *PointeeRD = PromiseType->getAsCXXRecordDecl();
1053   assert(PointeeRD && "PromiseType must be a CxxRecordDecl type");
1054 
1055   const bool Overaligned = S.getLangOpts().CoroAlignedAllocation;
1056 
1057   // [dcl.fct.def.coroutine]p12
1058   // The deallocation function's name is looked up by searching for it in the
1059   // scope of the promise type. If nothing is found, a search is performed in
1060   // the global scope.
1061   if (S.FindDeallocationFunction(Loc, PointeeRD, DeleteName, OperatorDelete,
1062                                  /*Diagnose*/ true, /*WantSize*/ true,
1063                                  /*WantAligned*/ Overaligned))
1064     return false;
1065 
1066   // [dcl.fct.def.coroutine]p12
1067   //   If both a usual deallocation function with only a pointer parameter and a
1068   //   usual deallocation function with both a pointer parameter and a size
1069   //   parameter are found, then the selected deallocation function shall be the
1070   //   one with two parameters. Otherwise, the selected deallocation function
1071   //   shall be the function with one parameter.
1072   if (!OperatorDelete) {
1073     // Look for a global declaration.
1074     // Coroutines can always provide their required size.
1075     const bool CanProvideSize = true;
1076     // Sema::FindUsualDeallocationFunction will try to find the one with two
1077     // parameters first. It will return the deallocation function with one
1078     // parameter if failed.
1079     OperatorDelete = S.FindUsualDeallocationFunction(Loc, CanProvideSize,
1080                                                      Overaligned, DeleteName);
1081 
1082     if (!OperatorDelete)
1083       return false;
1084   }
1085 
1086   S.MarkFunctionReferenced(Loc, OperatorDelete);
1087   return true;
1088 }
1089 
1090 
1091 void Sema::CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body) {
1092   FunctionScopeInfo *Fn = getCurFunction();
1093   assert(Fn && Fn->isCoroutine() && "not a coroutine");
1094   if (!Body) {
1095     assert(FD->isInvalidDecl() &&
1096            "a null body is only allowed for invalid declarations");
1097     return;
1098   }
1099   // We have a function that uses coroutine keywords, but we failed to build
1100   // the promise type.
1101   if (!Fn->CoroutinePromise)
1102     return FD->setInvalidDecl();
1103 
1104   if (isa<CoroutineBodyStmt>(Body)) {
1105     // Nothing todo. the body is already a transformed coroutine body statement.
1106     return;
1107   }
1108 
1109   // The always_inline attribute doesn't reliably apply to a coroutine,
1110   // because the coroutine will be split into pieces and some pieces
1111   // might be called indirectly, as in a virtual call. Even the ramp
1112   // function cannot be inlined at -O0, due to pipeline ordering
1113   // problems (see https://llvm.org/PR53413). Tell the user about it.
1114   if (FD->hasAttr<AlwaysInlineAttr>())
1115     Diag(FD->getLocation(), diag::warn_always_inline_coroutine);
1116 
1117   // [stmt.return.coroutine]p1:
1118   //   A coroutine shall not enclose a return statement ([stmt.return]).
1119   if (Fn->FirstReturnLoc.isValid()) {
1120     assert(Fn->FirstCoroutineStmtLoc.isValid() &&
1121                    "first coroutine location not set");
1122     Diag(Fn->FirstReturnLoc, diag::err_return_in_coroutine);
1123     Diag(Fn->FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1124             << Fn->getFirstCoroutineStmtKeyword();
1125   }
1126 
1127   // Coroutines will get splitted into pieces. The GNU address of label
1128   // extension wouldn't be meaningful in coroutines.
1129   for (AddrLabelExpr *ALE : Fn->AddrLabels)
1130     Diag(ALE->getBeginLoc(), diag::err_coro_invalid_addr_of_label);
1131 
1132   CoroutineStmtBuilder Builder(*this, *FD, *Fn, Body);
1133   if (Builder.isInvalid() || !Builder.buildStatements())
1134     return FD->setInvalidDecl();
1135 
1136   // Build body for the coroutine wrapper statement.
1137   Body = CoroutineBodyStmt::Create(Context, Builder);
1138 }
1139 
1140 static CompoundStmt *buildCoroutineBody(Stmt *Body, ASTContext &Context) {
1141   if (auto *CS = dyn_cast<CompoundStmt>(Body))
1142     return CS;
1143 
1144   // The body of the coroutine may be a try statement if it is in
1145   // 'function-try-block' syntax. Here we wrap it into a compound
1146   // statement for consistency.
1147   assert(isa<CXXTryStmt>(Body) && "Unimaged coroutine body type");
1148   return CompoundStmt::Create(Context, {Body}, FPOptionsOverride(),
1149                               SourceLocation(), SourceLocation());
1150 }
1151 
1152 CoroutineStmtBuilder::CoroutineStmtBuilder(Sema &S, FunctionDecl &FD,
1153                                            sema::FunctionScopeInfo &Fn,
1154                                            Stmt *Body)
1155     : S(S), FD(FD), Fn(Fn), Loc(FD.getLocation()),
1156       IsPromiseDependentType(
1157           !Fn.CoroutinePromise ||
1158           Fn.CoroutinePromise->getType()->isDependentType()) {
1159   this->Body = buildCoroutineBody(Body, S.getASTContext());
1160 
1161   for (auto KV : Fn.CoroutineParameterMoves)
1162     this->ParamMovesVector.push_back(KV.second);
1163   this->ParamMoves = this->ParamMovesVector;
1164 
1165   if (!IsPromiseDependentType) {
1166     PromiseRecordDecl = Fn.CoroutinePromise->getType()->getAsCXXRecordDecl();
1167     assert(PromiseRecordDecl && "Type should have already been checked");
1168   }
1169   this->IsValid = makePromiseStmt() && makeInitialAndFinalSuspend();
1170 }
1171 
1172 bool CoroutineStmtBuilder::buildStatements() {
1173   assert(this->IsValid && "coroutine already invalid");
1174   this->IsValid = makeReturnObject();
1175   if (this->IsValid && !IsPromiseDependentType)
1176     buildDependentStatements();
1177   return this->IsValid;
1178 }
1179 
1180 bool CoroutineStmtBuilder::buildDependentStatements() {
1181   assert(this->IsValid && "coroutine already invalid");
1182   assert(!this->IsPromiseDependentType &&
1183          "coroutine cannot have a dependent promise type");
1184   this->IsValid = makeOnException() && makeOnFallthrough() &&
1185                   makeGroDeclAndReturnStmt() && makeReturnOnAllocFailure() &&
1186                   makeNewAndDeleteExpr();
1187   return this->IsValid;
1188 }
1189 
1190 bool CoroutineStmtBuilder::makePromiseStmt() {
1191   // Form a declaration statement for the promise declaration, so that AST
1192   // visitors can more easily find it.
1193   StmtResult PromiseStmt =
1194       S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(Fn.CoroutinePromise), Loc, Loc);
1195   if (PromiseStmt.isInvalid())
1196     return false;
1197 
1198   this->Promise = PromiseStmt.get();
1199   return true;
1200 }
1201 
1202 bool CoroutineStmtBuilder::makeInitialAndFinalSuspend() {
1203   if (Fn.hasInvalidCoroutineSuspends())
1204     return false;
1205   this->InitialSuspend = cast<Expr>(Fn.CoroutineSuspends.first);
1206   this->FinalSuspend = cast<Expr>(Fn.CoroutineSuspends.second);
1207   return true;
1208 }
1209 
1210 static bool diagReturnOnAllocFailure(Sema &S, Expr *E,
1211                                      CXXRecordDecl *PromiseRecordDecl,
1212                                      FunctionScopeInfo &Fn) {
1213   auto Loc = E->getExprLoc();
1214   if (auto *DeclRef = dyn_cast_or_null<DeclRefExpr>(E)) {
1215     auto *Decl = DeclRef->getDecl();
1216     if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Decl)) {
1217       if (Method->isStatic())
1218         return true;
1219       else
1220         Loc = Decl->getLocation();
1221     }
1222   }
1223 
1224   S.Diag(
1225       Loc,
1226       diag::err_coroutine_promise_get_return_object_on_allocation_failure)
1227       << PromiseRecordDecl;
1228   S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1229       << Fn.getFirstCoroutineStmtKeyword();
1230   return false;
1231 }
1232 
1233 bool CoroutineStmtBuilder::makeReturnOnAllocFailure() {
1234   assert(!IsPromiseDependentType &&
1235          "cannot make statement while the promise type is dependent");
1236 
1237   // [dcl.fct.def.coroutine]p10
1238   //   If a search for the name get_return_object_on_allocation_failure in
1239   // the scope of the promise type ([class.member.lookup]) finds any
1240   // declarations, then the result of a call to an allocation function used to
1241   // obtain storage for the coroutine state is assumed to return nullptr if it
1242   // fails to obtain storage, ... If the allocation function returns nullptr,
1243   // ... and the return value is obtained by a call to
1244   // T::get_return_object_on_allocation_failure(), where T is the
1245   // promise type.
1246   DeclarationName DN =
1247       S.PP.getIdentifierInfo("get_return_object_on_allocation_failure");
1248   LookupResult Found(S, DN, Loc, Sema::LookupMemberName);
1249   if (!S.LookupQualifiedName(Found, PromiseRecordDecl))
1250     return true;
1251 
1252   CXXScopeSpec SS;
1253   ExprResult DeclNameExpr =
1254       S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
1255   if (DeclNameExpr.isInvalid())
1256     return false;
1257 
1258   if (!diagReturnOnAllocFailure(S, DeclNameExpr.get(), PromiseRecordDecl, Fn))
1259     return false;
1260 
1261   ExprResult ReturnObjectOnAllocationFailure =
1262       S.BuildCallExpr(nullptr, DeclNameExpr.get(), Loc, {}, Loc);
1263   if (ReturnObjectOnAllocationFailure.isInvalid())
1264     return false;
1265 
1266   StmtResult ReturnStmt =
1267       S.BuildReturnStmt(Loc, ReturnObjectOnAllocationFailure.get());
1268   if (ReturnStmt.isInvalid()) {
1269     S.Diag(Found.getFoundDecl()->getLocation(), diag::note_member_declared_here)
1270         << DN;
1271     S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1272         << Fn.getFirstCoroutineStmtKeyword();
1273     return false;
1274   }
1275 
1276   this->ReturnStmtOnAllocFailure = ReturnStmt.get();
1277   return true;
1278 }
1279 
1280 // Collect placement arguments for allocation function of coroutine FD.
1281 // Return true if we collect placement arguments succesfully. Return false,
1282 // otherwise.
1283 static bool collectPlacementArgs(Sema &S, FunctionDecl &FD, SourceLocation Loc,
1284                                  SmallVectorImpl<Expr *> &PlacementArgs) {
1285   if (auto *MD = dyn_cast<CXXMethodDecl>(&FD)) {
1286     if (MD->isInstance() && !isLambdaCallOperator(MD)) {
1287       ExprResult ThisExpr = S.ActOnCXXThis(Loc);
1288       if (ThisExpr.isInvalid())
1289         return false;
1290       ThisExpr = S.CreateBuiltinUnaryOp(Loc, UO_Deref, ThisExpr.get());
1291       if (ThisExpr.isInvalid())
1292         return false;
1293       PlacementArgs.push_back(ThisExpr.get());
1294     }
1295   }
1296 
1297   for (auto *PD : FD.parameters()) {
1298     if (PD->getType()->isDependentType())
1299       continue;
1300 
1301     // Build a reference to the parameter.
1302     auto PDLoc = PD->getLocation();
1303     ExprResult PDRefExpr =
1304         S.BuildDeclRefExpr(PD, PD->getOriginalType().getNonReferenceType(),
1305                            ExprValueKind::VK_LValue, PDLoc);
1306     if (PDRefExpr.isInvalid())
1307       return false;
1308 
1309     PlacementArgs.push_back(PDRefExpr.get());
1310   }
1311 
1312   return true;
1313 }
1314 
1315 bool CoroutineStmtBuilder::makeNewAndDeleteExpr() {
1316   // Form and check allocation and deallocation calls.
1317   assert(!IsPromiseDependentType &&
1318          "cannot make statement while the promise type is dependent");
1319   QualType PromiseType = Fn.CoroutinePromise->getType();
1320 
1321   if (S.RequireCompleteType(Loc, PromiseType, diag::err_incomplete_type))
1322     return false;
1323 
1324   const bool RequiresNoThrowAlloc = ReturnStmtOnAllocFailure != nullptr;
1325 
1326   // According to [dcl.fct.def.coroutine]p9, Lookup allocation functions using a
1327   // parameter list composed of the requested size of the coroutine state being
1328   // allocated, followed by the coroutine function's arguments. If a matching
1329   // allocation function exists, use it. Otherwise, use an allocation function
1330   // that just takes the requested size.
1331   //
1332   // [dcl.fct.def.coroutine]p9
1333   //   An implementation may need to allocate additional storage for a
1334   //   coroutine.
1335   // This storage is known as the coroutine state and is obtained by calling a
1336   // non-array allocation function ([basic.stc.dynamic.allocation]). The
1337   // allocation function's name is looked up by searching for it in the scope of
1338   // the promise type.
1339   // - If any declarations are found, overload resolution is performed on a
1340   // function call created by assembling an argument list. The first argument is
1341   // the amount of space requested, and has type std::size_t. The
1342   // lvalues p1 ... pn are the succeeding arguments.
1343   //
1344   // ...where "p1 ... pn" are defined earlier as:
1345   //
1346   // [dcl.fct.def.coroutine]p3
1347   //   The promise type of a coroutine is `std::coroutine_traits<R, P1, ...,
1348   //   Pn>`
1349   // , where R is the return type of the function, and `P1, ..., Pn` are the
1350   // sequence of types of the non-object function parameters, preceded by the
1351   // type of the object parameter ([dcl.fct]) if the coroutine is a non-static
1352   // member function. [dcl.fct.def.coroutine]p4 In the following, p_i is an
1353   // lvalue of type P_i, where p1 denotes the object parameter and p_i+1 denotes
1354   // the i-th non-object function parameter for a non-static member function,
1355   // and p_i denotes the i-th function parameter otherwise. For a non-static
1356   // member function, q_1 is an lvalue that denotes *this; any other q_i is an
1357   // lvalue that denotes the parameter copy corresponding to p_i.
1358 
1359   FunctionDecl *OperatorNew = nullptr;
1360   SmallVector<Expr *, 1> PlacementArgs;
1361 
1362   const bool PromiseContainsNew = [this, &PromiseType]() -> bool {
1363     DeclarationName NewName =
1364         S.getASTContext().DeclarationNames.getCXXOperatorName(OO_New);
1365     LookupResult R(S, NewName, Loc, Sema::LookupOrdinaryName);
1366 
1367     if (PromiseType->isRecordType())
1368       S.LookupQualifiedName(R, PromiseType->getAsCXXRecordDecl());
1369 
1370     return !R.empty() && !R.isAmbiguous();
1371   }();
1372 
1373   // Helper function to indicate whether the last lookup found the aligned
1374   // allocation function.
1375   bool PassAlignment = S.getLangOpts().CoroAlignedAllocation;
1376   auto LookupAllocationFunction = [&](Sema::AllocationFunctionScope NewScope =
1377                                           Sema::AFS_Both,
1378                                       bool WithoutPlacementArgs = false,
1379                                       bool ForceNonAligned = false) {
1380     // [dcl.fct.def.coroutine]p9
1381     //   The allocation function's name is looked up by searching for it in the
1382     // scope of the promise type.
1383     // - If any declarations are found, ...
1384     // - If no declarations are found in the scope of the promise type, a search
1385     // is performed in the global scope.
1386     if (NewScope == Sema::AFS_Both)
1387       NewScope = PromiseContainsNew ? Sema::AFS_Class : Sema::AFS_Global;
1388 
1389     PassAlignment = !ForceNonAligned && S.getLangOpts().CoroAlignedAllocation;
1390     FunctionDecl *UnusedResult = nullptr;
1391     S.FindAllocationFunctions(Loc, SourceRange(), NewScope,
1392                               /*DeleteScope*/ Sema::AFS_Both, PromiseType,
1393                               /*isArray*/ false, PassAlignment,
1394                               WithoutPlacementArgs ? MultiExprArg{}
1395                                                    : PlacementArgs,
1396                               OperatorNew, UnusedResult, /*Diagnose*/ false);
1397   };
1398 
1399   // We don't expect to call to global operator new with (size, p0, …, pn).
1400   // So if we choose to lookup the allocation function in global scope, we
1401   // shouldn't lookup placement arguments.
1402   if (PromiseContainsNew && !collectPlacementArgs(S, FD, Loc, PlacementArgs))
1403     return false;
1404 
1405   LookupAllocationFunction();
1406 
1407   if (PromiseContainsNew && !PlacementArgs.empty()) {
1408     // [dcl.fct.def.coroutine]p9
1409     //   If no viable function is found ([over.match.viable]), overload
1410     //   resolution
1411     // is performed again on a function call created by passing just the amount
1412     // of space required as an argument of type std::size_t.
1413     //
1414     // Proposed Change of [dcl.fct.def.coroutine]p9 in P2014R0:
1415     //   Otherwise, overload resolution is performed again on a function call
1416     //   created
1417     // by passing the amount of space requested as an argument of type
1418     // std::size_t as the first argument, and the requested alignment as
1419     // an argument of type std:align_val_t as the second argument.
1420     if (!OperatorNew ||
1421         (S.getLangOpts().CoroAlignedAllocation && !PassAlignment))
1422       LookupAllocationFunction(/*NewScope*/ Sema::AFS_Class,
1423                                /*WithoutPlacementArgs*/ true);
1424   }
1425 
1426   // Proposed Change of [dcl.fct.def.coroutine]p12 in P2014R0:
1427   //   Otherwise, overload resolution is performed again on a function call
1428   //   created
1429   // by passing the amount of space requested as an argument of type
1430   // std::size_t as the first argument, and the lvalues p1 ... pn as the
1431   // succeeding arguments. Otherwise, overload resolution is performed again
1432   // on a function call created by passing just the amount of space required as
1433   // an argument of type std::size_t.
1434   //
1435   // So within the proposed change in P2014RO, the priority order of aligned
1436   // allocation functions wiht promise_type is:
1437   //
1438   //    void* operator new( std::size_t, std::align_val_t, placement_args... );
1439   //    void* operator new( std::size_t, std::align_val_t);
1440   //    void* operator new( std::size_t, placement_args... );
1441   //    void* operator new( std::size_t);
1442 
1443   // Helper variable to emit warnings.
1444   bool FoundNonAlignedInPromise = false;
1445   if (PromiseContainsNew && S.getLangOpts().CoroAlignedAllocation)
1446     if (!OperatorNew || !PassAlignment) {
1447       FoundNonAlignedInPromise = OperatorNew;
1448 
1449       LookupAllocationFunction(/*NewScope*/ Sema::AFS_Class,
1450                                /*WithoutPlacementArgs*/ false,
1451                                /*ForceNonAligned*/ true);
1452 
1453       if (!OperatorNew && !PlacementArgs.empty())
1454         LookupAllocationFunction(/*NewScope*/ Sema::AFS_Class,
1455                                  /*WithoutPlacementArgs*/ true,
1456                                  /*ForceNonAligned*/ true);
1457     }
1458 
1459   bool IsGlobalOverload =
1460       OperatorNew && !isa<CXXRecordDecl>(OperatorNew->getDeclContext());
1461   // If we didn't find a class-local new declaration and non-throwing new
1462   // was is required then we need to lookup the non-throwing global operator
1463   // instead.
1464   if (RequiresNoThrowAlloc && (!OperatorNew || IsGlobalOverload)) {
1465     auto *StdNoThrow = buildStdNoThrowDeclRef(S, Loc);
1466     if (!StdNoThrow)
1467       return false;
1468     PlacementArgs = {StdNoThrow};
1469     OperatorNew = nullptr;
1470     LookupAllocationFunction(Sema::AFS_Global);
1471   }
1472 
1473   // If we found a non-aligned allocation function in the promise_type,
1474   // it indicates the user forgot to update the allocation function. Let's emit
1475   // a warning here.
1476   if (FoundNonAlignedInPromise) {
1477     S.Diag(OperatorNew->getLocation(),
1478            diag::warn_non_aligned_allocation_function)
1479         << &FD;
1480   }
1481 
1482   if (!OperatorNew) {
1483     if (PromiseContainsNew)
1484       S.Diag(Loc, diag::err_coroutine_unusable_new) << PromiseType << &FD;
1485     else if (RequiresNoThrowAlloc)
1486       S.Diag(Loc, diag::err_coroutine_unfound_nothrow_new)
1487           << &FD << S.getLangOpts().CoroAlignedAllocation;
1488 
1489     return false;
1490   }
1491 
1492   if (RequiresNoThrowAlloc) {
1493     const auto *FT = OperatorNew->getType()->castAs<FunctionProtoType>();
1494     if (!FT->isNothrow(/*ResultIfDependent*/ false)) {
1495       S.Diag(OperatorNew->getLocation(),
1496              diag::err_coroutine_promise_new_requires_nothrow)
1497           << OperatorNew;
1498       S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
1499           << OperatorNew;
1500       return false;
1501     }
1502   }
1503 
1504   FunctionDecl *OperatorDelete = nullptr;
1505   if (!findDeleteForPromise(S, Loc, PromiseType, OperatorDelete)) {
1506     // FIXME: We should add an error here. According to:
1507     // [dcl.fct.def.coroutine]p12
1508     //   If no usual deallocation function is found, the program is ill-formed.
1509     return false;
1510   }
1511 
1512   Expr *FramePtr =
1513       S.BuildBuiltinCallExpr(Loc, Builtin::BI__builtin_coro_frame, {});
1514 
1515   Expr *FrameSize =
1516       S.BuildBuiltinCallExpr(Loc, Builtin::BI__builtin_coro_size, {});
1517 
1518   Expr *FrameAlignment = nullptr;
1519 
1520   if (S.getLangOpts().CoroAlignedAllocation) {
1521     FrameAlignment =
1522         S.BuildBuiltinCallExpr(Loc, Builtin::BI__builtin_coro_align, {});
1523 
1524     TypeSourceInfo *AlignValTy = getTypeSourceInfoForStdAlignValT(S, Loc);
1525     if (!AlignValTy)
1526       return false;
1527 
1528     FrameAlignment = S.BuildCXXNamedCast(Loc, tok::kw_static_cast, AlignValTy,
1529                                          FrameAlignment, SourceRange(Loc, Loc),
1530                                          SourceRange(Loc, Loc))
1531                          .get();
1532   }
1533 
1534   // Make new call.
1535   ExprResult NewRef =
1536       S.BuildDeclRefExpr(OperatorNew, OperatorNew->getType(), VK_LValue, Loc);
1537   if (NewRef.isInvalid())
1538     return false;
1539 
1540   SmallVector<Expr *, 2> NewArgs(1, FrameSize);
1541   if (S.getLangOpts().CoroAlignedAllocation && PassAlignment)
1542     NewArgs.push_back(FrameAlignment);
1543 
1544   if (OperatorNew->getNumParams() > NewArgs.size())
1545     llvm::append_range(NewArgs, PlacementArgs);
1546 
1547   ExprResult NewExpr =
1548       S.BuildCallExpr(S.getCurScope(), NewRef.get(), Loc, NewArgs, Loc);
1549   NewExpr = S.ActOnFinishFullExpr(NewExpr.get(), /*DiscardedValue*/ false);
1550   if (NewExpr.isInvalid())
1551     return false;
1552 
1553   // Make delete call.
1554 
1555   QualType OpDeleteQualType = OperatorDelete->getType();
1556 
1557   ExprResult DeleteRef =
1558       S.BuildDeclRefExpr(OperatorDelete, OpDeleteQualType, VK_LValue, Loc);
1559   if (DeleteRef.isInvalid())
1560     return false;
1561 
1562   Expr *CoroFree =
1563       S.BuildBuiltinCallExpr(Loc, Builtin::BI__builtin_coro_free, {FramePtr});
1564 
1565   SmallVector<Expr *, 2> DeleteArgs{CoroFree};
1566 
1567   // [dcl.fct.def.coroutine]p12
1568   //   The selected deallocation function shall be called with the address of
1569   //   the block of storage to be reclaimed as its first argument. If a
1570   //   deallocation function with a parameter of type std::size_t is
1571   //   used, the size of the block is passed as the corresponding argument.
1572   const auto *OpDeleteType =
1573       OpDeleteQualType.getTypePtr()->castAs<FunctionProtoType>();
1574   if (OpDeleteType->getNumParams() > DeleteArgs.size() &&
1575       S.getASTContext().hasSameUnqualifiedType(
1576           OpDeleteType->getParamType(DeleteArgs.size()), FrameSize->getType()))
1577     DeleteArgs.push_back(FrameSize);
1578 
1579   // Proposed Change of [dcl.fct.def.coroutine]p12 in P2014R0:
1580   //   If deallocation function lookup finds a usual deallocation function with
1581   //   a pointer parameter, size parameter and alignment parameter then this
1582   //   will be the selected deallocation function, otherwise if lookup finds a
1583   //   usual deallocation function with both a pointer parameter and a size
1584   //   parameter, then this will be the selected deallocation function.
1585   //   Otherwise, if lookup finds a usual deallocation function with only a
1586   //   pointer parameter, then this will be the selected deallocation
1587   //   function.
1588   //
1589   // So we are not forced to pass alignment to the deallocation function.
1590   if (S.getLangOpts().CoroAlignedAllocation &&
1591       OpDeleteType->getNumParams() > DeleteArgs.size() &&
1592       S.getASTContext().hasSameUnqualifiedType(
1593           OpDeleteType->getParamType(DeleteArgs.size()),
1594           FrameAlignment->getType()))
1595     DeleteArgs.push_back(FrameAlignment);
1596 
1597   ExprResult DeleteExpr =
1598       S.BuildCallExpr(S.getCurScope(), DeleteRef.get(), Loc, DeleteArgs, Loc);
1599   DeleteExpr =
1600       S.ActOnFinishFullExpr(DeleteExpr.get(), /*DiscardedValue*/ false);
1601   if (DeleteExpr.isInvalid())
1602     return false;
1603 
1604   this->Allocate = NewExpr.get();
1605   this->Deallocate = DeleteExpr.get();
1606 
1607   return true;
1608 }
1609 
1610 bool CoroutineStmtBuilder::makeOnFallthrough() {
1611   assert(!IsPromiseDependentType &&
1612          "cannot make statement while the promise type is dependent");
1613 
1614   // [dcl.fct.def.coroutine]/p6
1615   // If searches for the names return_void and return_value in the scope of
1616   // the promise type each find any declarations, the program is ill-formed.
1617   // [Note 1: If return_void is found, flowing off the end of a coroutine is
1618   // equivalent to a co_return with no operand. Otherwise, flowing off the end
1619   // of a coroutine results in undefined behavior ([stmt.return.coroutine]). —
1620   // end note]
1621   bool HasRVoid, HasRValue;
1622   LookupResult LRVoid =
1623       lookupMember(S, "return_void", PromiseRecordDecl, Loc, HasRVoid);
1624   LookupResult LRValue =
1625       lookupMember(S, "return_value", PromiseRecordDecl, Loc, HasRValue);
1626 
1627   StmtResult Fallthrough;
1628   if (HasRVoid && HasRValue) {
1629     // FIXME Improve this diagnostic
1630     S.Diag(FD.getLocation(),
1631            diag::err_coroutine_promise_incompatible_return_functions)
1632         << PromiseRecordDecl;
1633     S.Diag(LRVoid.getRepresentativeDecl()->getLocation(),
1634            diag::note_member_first_declared_here)
1635         << LRVoid.getLookupName();
1636     S.Diag(LRValue.getRepresentativeDecl()->getLocation(),
1637            diag::note_member_first_declared_here)
1638         << LRValue.getLookupName();
1639     return false;
1640   } else if (!HasRVoid && !HasRValue) {
1641     // We need to set 'Fallthrough'. Otherwise the other analysis part might
1642     // think the coroutine has defined a return_value method. So it might emit
1643     // **false** positive warning. e.g.,
1644     //
1645     //    promise_without_return_func foo() {
1646     //        co_await something();
1647     //    }
1648     //
1649     // Then AnalysisBasedWarning would emit a warning about `foo()` lacking a
1650     // co_return statements, which isn't correct.
1651     Fallthrough = S.ActOnNullStmt(PromiseRecordDecl->getLocation());
1652     if (Fallthrough.isInvalid())
1653       return false;
1654   } else if (HasRVoid) {
1655     Fallthrough = S.BuildCoreturnStmt(FD.getLocation(), nullptr,
1656                                       /*IsImplicit*/false);
1657     Fallthrough = S.ActOnFinishFullStmt(Fallthrough.get());
1658     if (Fallthrough.isInvalid())
1659       return false;
1660   }
1661 
1662   this->OnFallthrough = Fallthrough.get();
1663   return true;
1664 }
1665 
1666 bool CoroutineStmtBuilder::makeOnException() {
1667   // Try to form 'p.unhandled_exception();'
1668   assert(!IsPromiseDependentType &&
1669          "cannot make statement while the promise type is dependent");
1670 
1671   const bool RequireUnhandledException = S.getLangOpts().CXXExceptions;
1672 
1673   if (!lookupMember(S, "unhandled_exception", PromiseRecordDecl, Loc)) {
1674     auto DiagID =
1675         RequireUnhandledException
1676             ? diag::err_coroutine_promise_unhandled_exception_required
1677             : diag::
1678                   warn_coroutine_promise_unhandled_exception_required_with_exceptions;
1679     S.Diag(Loc, DiagID) << PromiseRecordDecl;
1680     S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here)
1681         << PromiseRecordDecl;
1682     return !RequireUnhandledException;
1683   }
1684 
1685   // If exceptions are disabled, don't try to build OnException.
1686   if (!S.getLangOpts().CXXExceptions)
1687     return true;
1688 
1689   ExprResult UnhandledException = buildPromiseCall(
1690       S, Fn.CoroutinePromise, Loc, "unhandled_exception", std::nullopt);
1691   UnhandledException = S.ActOnFinishFullExpr(UnhandledException.get(), Loc,
1692                                              /*DiscardedValue*/ false);
1693   if (UnhandledException.isInvalid())
1694     return false;
1695 
1696   // Since the body of the coroutine will be wrapped in try-catch, it will
1697   // be incompatible with SEH __try if present in a function.
1698   if (!S.getLangOpts().Borland && Fn.FirstSEHTryLoc.isValid()) {
1699     S.Diag(Fn.FirstSEHTryLoc, diag::err_seh_in_a_coroutine_with_cxx_exceptions);
1700     S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1701         << Fn.getFirstCoroutineStmtKeyword();
1702     return false;
1703   }
1704 
1705   this->OnException = UnhandledException.get();
1706   return true;
1707 }
1708 
1709 bool CoroutineStmtBuilder::makeReturnObject() {
1710   // [dcl.fct.def.coroutine]p7
1711   // The expression promise.get_return_object() is used to initialize the
1712   // returned reference or prvalue result object of a call to a coroutine.
1713   ExprResult ReturnObject = buildPromiseCall(S, Fn.CoroutinePromise, Loc,
1714                                              "get_return_object", std::nullopt);
1715   if (ReturnObject.isInvalid())
1716     return false;
1717 
1718   this->ReturnValue = ReturnObject.get();
1719   return true;
1720 }
1721 
1722 static void noteMemberDeclaredHere(Sema &S, Expr *E, FunctionScopeInfo &Fn) {
1723   if (auto *MbrRef = dyn_cast<CXXMemberCallExpr>(E)) {
1724     auto *MethodDecl = MbrRef->getMethodDecl();
1725     S.Diag(MethodDecl->getLocation(), diag::note_member_declared_here)
1726         << MethodDecl;
1727   }
1728   S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1729       << Fn.getFirstCoroutineStmtKeyword();
1730 }
1731 
1732 bool CoroutineStmtBuilder::makeGroDeclAndReturnStmt() {
1733   assert(!IsPromiseDependentType &&
1734          "cannot make statement while the promise type is dependent");
1735   assert(this->ReturnValue && "ReturnValue must be already formed");
1736 
1737   QualType const GroType = this->ReturnValue->getType();
1738   assert(!GroType->isDependentType() &&
1739          "get_return_object type must no longer be dependent");
1740 
1741   QualType const FnRetType = FD.getReturnType();
1742   assert(!FnRetType->isDependentType() &&
1743          "get_return_object type must no longer be dependent");
1744 
1745   // The call to get_­return_­object is sequenced before the call to
1746   // initial_­suspend and is invoked at most once, but there are caveats
1747   // regarding on whether the prvalue result object may be initialized
1748   // directly/eager or delayed, depending on the types involved.
1749   //
1750   // More info at https://github.com/cplusplus/papers/issues/1414
1751   bool GroMatchesRetType = S.getASTContext().hasSameType(GroType, FnRetType);
1752 
1753   if (FnRetType->isVoidType()) {
1754     ExprResult Res =
1755         S.ActOnFinishFullExpr(this->ReturnValue, Loc, /*DiscardedValue*/ false);
1756     if (Res.isInvalid())
1757       return false;
1758 
1759     if (!GroMatchesRetType)
1760       this->ResultDecl = Res.get();
1761     return true;
1762   }
1763 
1764   if (GroType->isVoidType()) {
1765     // Trigger a nice error message.
1766     InitializedEntity Entity =
1767         InitializedEntity::InitializeResult(Loc, FnRetType);
1768     S.PerformCopyInitialization(Entity, SourceLocation(), ReturnValue);
1769     noteMemberDeclaredHere(S, ReturnValue, Fn);
1770     return false;
1771   }
1772 
1773   StmtResult ReturnStmt;
1774   clang::VarDecl *GroDecl = nullptr;
1775   if (GroMatchesRetType) {
1776     ReturnStmt = S.BuildReturnStmt(Loc, ReturnValue);
1777   } else {
1778     GroDecl = VarDecl::Create(
1779         S.Context, &FD, FD.getLocation(), FD.getLocation(),
1780         &S.PP.getIdentifierTable().get("__coro_gro"), GroType,
1781         S.Context.getTrivialTypeSourceInfo(GroType, Loc), SC_None);
1782     GroDecl->setImplicit();
1783 
1784     S.CheckVariableDeclarationType(GroDecl);
1785     if (GroDecl->isInvalidDecl())
1786       return false;
1787 
1788     InitializedEntity Entity = InitializedEntity::InitializeVariable(GroDecl);
1789     ExprResult Res =
1790         S.PerformCopyInitialization(Entity, SourceLocation(), ReturnValue);
1791     if (Res.isInvalid())
1792       return false;
1793 
1794     Res = S.ActOnFinishFullExpr(Res.get(), /*DiscardedValue*/ false);
1795     if (Res.isInvalid())
1796       return false;
1797 
1798     S.AddInitializerToDecl(GroDecl, Res.get(),
1799                            /*DirectInit=*/false);
1800 
1801     S.FinalizeDeclaration(GroDecl);
1802 
1803     // Form a declaration statement for the return declaration, so that AST
1804     // visitors can more easily find it.
1805     StmtResult GroDeclStmt =
1806         S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(GroDecl), Loc, Loc);
1807     if (GroDeclStmt.isInvalid())
1808       return false;
1809 
1810     this->ResultDecl = GroDeclStmt.get();
1811 
1812     ExprResult declRef = S.BuildDeclRefExpr(GroDecl, GroType, VK_LValue, Loc);
1813     if (declRef.isInvalid())
1814       return false;
1815 
1816     ReturnStmt = S.BuildReturnStmt(Loc, declRef.get());
1817   }
1818 
1819   if (ReturnStmt.isInvalid()) {
1820     noteMemberDeclaredHere(S, ReturnValue, Fn);
1821     return false;
1822   }
1823 
1824   if (!GroMatchesRetType &&
1825       cast<clang::ReturnStmt>(ReturnStmt.get())->getNRVOCandidate() == GroDecl)
1826     GroDecl->setNRVOVariable(true);
1827 
1828   this->ReturnStmt = ReturnStmt.get();
1829   return true;
1830 }
1831 
1832 // Create a static_cast\<T&&>(expr).
1833 static Expr *castForMoving(Sema &S, Expr *E, QualType T = QualType()) {
1834   if (T.isNull())
1835     T = E->getType();
1836   QualType TargetType = S.BuildReferenceType(
1837       T, /*SpelledAsLValue*/ false, SourceLocation(), DeclarationName());
1838   SourceLocation ExprLoc = E->getBeginLoc();
1839   TypeSourceInfo *TargetLoc =
1840       S.Context.getTrivialTypeSourceInfo(TargetType, ExprLoc);
1841 
1842   return S
1843       .BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
1844                          SourceRange(ExprLoc, ExprLoc), E->getSourceRange())
1845       .get();
1846 }
1847 
1848 /// Build a variable declaration for move parameter.
1849 static VarDecl *buildVarDecl(Sema &S, SourceLocation Loc, QualType Type,
1850                              IdentifierInfo *II) {
1851   TypeSourceInfo *TInfo = S.Context.getTrivialTypeSourceInfo(Type, Loc);
1852   VarDecl *Decl = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, II, Type,
1853                                   TInfo, SC_None);
1854   Decl->setImplicit();
1855   return Decl;
1856 }
1857 
1858 // Build statements that move coroutine function parameters to the coroutine
1859 // frame, and store them on the function scope info.
1860 bool Sema::buildCoroutineParameterMoves(SourceLocation Loc) {
1861   assert(isa<FunctionDecl>(CurContext) && "not in a function scope");
1862   auto *FD = cast<FunctionDecl>(CurContext);
1863 
1864   auto *ScopeInfo = getCurFunction();
1865   if (!ScopeInfo->CoroutineParameterMoves.empty())
1866     return false;
1867 
1868   // [dcl.fct.def.coroutine]p13
1869   //   When a coroutine is invoked, after initializing its parameters
1870   //   ([expr.call]), a copy is created for each coroutine parameter. For a
1871   //   parameter of type cv T, the copy is a variable of type cv T with
1872   //   automatic storage duration that is direct-initialized from an xvalue of
1873   //   type T referring to the parameter.
1874   for (auto *PD : FD->parameters()) {
1875     if (PD->getType()->isDependentType())
1876       continue;
1877 
1878     ExprResult PDRefExpr =
1879         BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
1880                          ExprValueKind::VK_LValue, Loc); // FIXME: scope?
1881     if (PDRefExpr.isInvalid())
1882       return false;
1883 
1884     Expr *CExpr = nullptr;
1885     if (PD->getType()->getAsCXXRecordDecl() ||
1886         PD->getType()->isRValueReferenceType())
1887       CExpr = castForMoving(*this, PDRefExpr.get());
1888     else
1889       CExpr = PDRefExpr.get();
1890     // [dcl.fct.def.coroutine]p13
1891     //   The initialization and destruction of each parameter copy occurs in the
1892     //   context of the called coroutine.
1893     auto *D = buildVarDecl(*this, Loc, PD->getType(), PD->getIdentifier());
1894     AddInitializerToDecl(D, CExpr, /*DirectInit=*/true);
1895 
1896     // Convert decl to a statement.
1897     StmtResult Stmt = ActOnDeclStmt(ConvertDeclToDeclGroup(D), Loc, Loc);
1898     if (Stmt.isInvalid())
1899       return false;
1900 
1901     ScopeInfo->CoroutineParameterMoves.insert(std::make_pair(PD, Stmt.get()));
1902   }
1903   return true;
1904 }
1905 
1906 StmtResult Sema::BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
1907   CoroutineBodyStmt *Res = CoroutineBodyStmt::Create(Context, Args);
1908   if (!Res)
1909     return StmtError();
1910   return Res;
1911 }
1912 
1913 ClassTemplateDecl *Sema::lookupCoroutineTraits(SourceLocation KwLoc,
1914                                                SourceLocation FuncLoc) {
1915   if (StdCoroutineTraitsCache)
1916     return StdCoroutineTraitsCache;
1917 
1918   IdentifierInfo const &TraitIdent =
1919       PP.getIdentifierTable().get("coroutine_traits");
1920 
1921   NamespaceDecl *StdSpace = getStdNamespace();
1922   LookupResult Result(*this, &TraitIdent, FuncLoc, LookupOrdinaryName);
1923   bool Found = StdSpace && LookupQualifiedName(Result, StdSpace);
1924 
1925   if (!Found) {
1926     // The goggles, we found nothing!
1927     Diag(KwLoc, diag::err_implied_coroutine_type_not_found)
1928         << "std::coroutine_traits";
1929     return nullptr;
1930   }
1931 
1932   // coroutine_traits is required to be a class template.
1933   StdCoroutineTraitsCache = Result.getAsSingle<ClassTemplateDecl>();
1934   if (!StdCoroutineTraitsCache) {
1935     Result.suppressDiagnostics();
1936     NamedDecl *Found = *Result.begin();
1937     Diag(Found->getLocation(), diag::err_malformed_std_coroutine_traits);
1938     return nullptr;
1939   }
1940 
1941   return StdCoroutineTraitsCache;
1942 }
1943