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