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