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