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