blob: 7c125e999d0013a50d9c442e7b6dc9a3d06a3cd7 [file] [log] [blame]
Fangrui Song524b3c12019-03-01 06:49:51 +00001//===-- SemaCoroutine.cpp - Semantic Analysis for Coroutines --------------===//
Richard Smithcfd53b42015-10-22 06:13:50 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Richard Smithcfd53b42015-10-22 06:13:50 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for C++ Coroutines.
10//
Brian Gesiakc1b173a2018-06-23 18:01:02 +000011// This file contains references to sections of the Coroutines TS, which
12// can be found at http://wg21.link/coroutines.
13//
Richard Smithcfd53b42015-10-22 06:13:50 +000014//===----------------------------------------------------------------------===//
15
Eric Fiselierbee782b2017-04-03 19:21:00 +000016#include "CoroutineStmtBuilder.h"
Brian Gesiak98606222018-02-15 20:37:22 +000017#include "clang/AST/ASTLambda.h"
Richard Smith9f690bd2015-10-27 06:02:45 +000018#include "clang/AST/Decl.h"
19#include "clang/AST/ExprCXX.h"
20#include "clang/AST/StmtCXX.h"
Reid Kleckner979da9a2019-11-15 16:36:00 -080021#include "clang/Basic/Builtins.h"
Richard Smith9f690bd2015-10-27 06:02:45 +000022#include "clang/Lex/Preprocessor.h"
Richard Smith2af65c42015-11-24 02:34:39 +000023#include "clang/Sema/Initialization.h"
Richard Smith9f690bd2015-10-27 06:02:45 +000024#include "clang/Sema/Overload.h"
Reid Kleckner04f9bca2018-03-07 22:48:35 +000025#include "clang/Sema/ScopeInfo.h"
Eric Fiselierbee782b2017-04-03 19:21:00 +000026#include "clang/Sema/SemaInternal.h"
27
Richard Smithcfd53b42015-10-22 06:13:50 +000028using namespace clang;
29using namespace sema;
30
Eric Fiselierfc50f622017-05-25 14:59:39 +000031static LookupResult lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD,
32 SourceLocation Loc, bool &Res) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +000033 DeclarationName DN = S.PP.getIdentifierInfo(Name);
34 LookupResult LR(S, DN, Loc, Sema::LookupMemberName);
35 // Suppress diagnostics when a private member is selected. The same warnings
36 // will be produced again when building the call.
37 LR.suppressDiagnostics();
Eric Fiselierfc50f622017-05-25 14:59:39 +000038 Res = S.LookupQualifiedName(LR, RD);
39 return LR;
40}
41
42static bool lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD,
43 SourceLocation Loc) {
44 bool Res;
45 lookupMember(S, Name, RD, Loc, Res);
46 return Res;
Eric Fiselier20f25cb2017-03-06 23:38:15 +000047}
48
Richard Smith9f690bd2015-10-27 06:02:45 +000049/// Look up the std::coroutine_traits<...>::promise_type for the given
50/// function type.
Eric Fiselier166c6e62017-07-10 01:27:22 +000051static QualType lookupPromiseType(Sema &S, const FunctionDecl *FD,
52 SourceLocation KwLoc) {
53 const FunctionProtoType *FnType = FD->getType()->castAs<FunctionProtoType>();
54 const SourceLocation FuncLoc = FD->getLocation();
Richard Smith9f690bd2015-10-27 06:02:45 +000055 // FIXME: Cache std::coroutine_traits once we've found it.
Gor Nishanov3e048bb2016-10-04 00:31:16 +000056 NamespaceDecl *StdExp = S.lookupStdExperimentalNamespace();
57 if (!StdExp) {
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +000058 S.Diag(KwLoc, diag::err_implied_coroutine_type_not_found)
59 << "std::experimental::coroutine_traits";
Richard Smith9f690bd2015-10-27 06:02:45 +000060 return QualType();
61 }
62
Brian Gesiak3e65d9a2018-07-14 18:21:44 +000063 ClassTemplateDecl *CoroTraits = S.lookupCoroutineTraits(KwLoc, FuncLoc);
Richard Smith9f690bd2015-10-27 06:02:45 +000064 if (!CoroTraits) {
Richard Smith9f690bd2015-10-27 06:02:45 +000065 return QualType();
66 }
67
Eric Fiselier166c6e62017-07-10 01:27:22 +000068 // Form template argument list for coroutine_traits<R, P1, P2, ...> according
69 // to [dcl.fct.def.coroutine]3
Eric Fiselier89bf0e72017-03-06 22:52:28 +000070 TemplateArgumentListInfo Args(KwLoc, KwLoc);
Eric Fiselier166c6e62017-07-10 01:27:22 +000071 auto AddArg = [&](QualType T) {
Richard Smith9f690bd2015-10-27 06:02:45 +000072 Args.addArgument(TemplateArgumentLoc(
Eric Fiselier89bf0e72017-03-06 22:52:28 +000073 TemplateArgument(T), S.Context.getTrivialTypeSourceInfo(T, KwLoc)));
Eric Fiselier166c6e62017-07-10 01:27:22 +000074 };
75 AddArg(FnType->getReturnType());
76 // If the function is a non-static member function, add the type
77 // of the implicit object parameter before the formal parameters.
78 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
79 if (MD->isInstance()) {
80 // [over.match.funcs]4
81 // For non-static member functions, the type of the implicit object
82 // parameter is
Eric Fiselierbf166ce2017-07-10 02:52:34 +000083 // -- "lvalue reference to cv X" for functions declared without a
84 // ref-qualifier or with the & ref-qualifier
85 // -- "rvalue reference to cv X" for functions declared with the &&
86 // ref-qualifier
Simon Pilgrimdc4d9082019-10-07 14:25:46 +000087 QualType T = MD->getThisType()->castAs<PointerType>()->getPointeeType();
Eric Fiselier166c6e62017-07-10 01:27:22 +000088 T = FnType->getRefQualifier() == RQ_RValue
89 ? S.Context.getRValueReferenceType(T)
90 : S.Context.getLValueReferenceType(T, /*SpelledAsLValue*/ true);
91 AddArg(T);
92 }
93 }
94 for (QualType T : FnType->getParamTypes())
95 AddArg(T);
Richard Smith9f690bd2015-10-27 06:02:45 +000096
97 // Build the template-id.
98 QualType CoroTrait =
Eric Fiselier89bf0e72017-03-06 22:52:28 +000099 S.CheckTemplateIdType(TemplateName(CoroTraits), KwLoc, Args);
Richard Smith9f690bd2015-10-27 06:02:45 +0000100 if (CoroTrait.isNull())
101 return QualType();
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000102 if (S.RequireCompleteType(KwLoc, CoroTrait,
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000103 diag::err_coroutine_type_missing_specialization))
Richard Smith9f690bd2015-10-27 06:02:45 +0000104 return QualType();
105
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000106 auto *RD = CoroTrait->getAsCXXRecordDecl();
Richard Smith9f690bd2015-10-27 06:02:45 +0000107 assert(RD && "specialization of class template is not a class?");
108
109 // Look up the ::promise_type member.
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000110 LookupResult R(S, &S.PP.getIdentifierTable().get("promise_type"), KwLoc,
Richard Smith9f690bd2015-10-27 06:02:45 +0000111 Sema::LookupOrdinaryName);
112 S.LookupQualifiedName(R, RD);
113 auto *Promise = R.getAsSingle<TypeDecl>();
114 if (!Promise) {
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000115 S.Diag(FuncLoc,
116 diag::err_implied_std_coroutine_traits_promise_type_not_found)
Gor Nishanov8df64e92016-10-27 16:28:31 +0000117 << RD;
Richard Smith9f690bd2015-10-27 06:02:45 +0000118 return QualType();
119 }
Richard Smith9f690bd2015-10-27 06:02:45 +0000120 // The promise type is required to be a class type.
121 QualType PromiseType = S.Context.getTypeDeclType(Promise);
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000122
123 auto buildElaboratedType = [&]() {
Gor Nishanov3e048bb2016-10-04 00:31:16 +0000124 auto *NNS = NestedNameSpecifier::Create(S.Context, nullptr, StdExp);
Richard Smith9b2f53e2015-11-19 02:36:35 +0000125 NNS = NestedNameSpecifier::Create(S.Context, NNS, false,
126 CoroTrait.getTypePtr());
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000127 return S.Context.getElaboratedType(ETK_None, NNS, PromiseType);
128 };
Richard Smith9b2f53e2015-11-19 02:36:35 +0000129
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000130 if (!PromiseType->getAsCXXRecordDecl()) {
131 S.Diag(FuncLoc,
132 diag::err_implied_std_coroutine_traits_promise_type_not_class)
133 << buildElaboratedType();
Richard Smith9f690bd2015-10-27 06:02:45 +0000134 return QualType();
135 }
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000136 if (S.RequireCompleteType(FuncLoc, buildElaboratedType(),
137 diag::err_coroutine_promise_type_incomplete))
138 return QualType();
Richard Smith9f690bd2015-10-27 06:02:45 +0000139
140 return PromiseType;
141}
142
Gor Nishanov29ff6382017-05-24 14:34:19 +0000143/// Look up the std::experimental::coroutine_handle<PromiseType>.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000144static QualType lookupCoroutineHandleType(Sema &S, QualType PromiseType,
145 SourceLocation Loc) {
146 if (PromiseType.isNull())
147 return QualType();
148
149 NamespaceDecl *StdExp = S.lookupStdExperimentalNamespace();
150 assert(StdExp && "Should already be diagnosed");
151
152 LookupResult Result(S, &S.PP.getIdentifierTable().get("coroutine_handle"),
153 Loc, Sema::LookupOrdinaryName);
154 if (!S.LookupQualifiedName(Result, StdExp)) {
155 S.Diag(Loc, diag::err_implied_coroutine_type_not_found)
156 << "std::experimental::coroutine_handle";
157 return QualType();
158 }
159
160 ClassTemplateDecl *CoroHandle = Result.getAsSingle<ClassTemplateDecl>();
161 if (!CoroHandle) {
162 Result.suppressDiagnostics();
163 // We found something weird. Complain about the first thing we found.
164 NamedDecl *Found = *Result.begin();
165 S.Diag(Found->getLocation(), diag::err_malformed_std_coroutine_handle);
166 return QualType();
167 }
168
169 // Form template argument list for coroutine_handle<Promise>.
170 TemplateArgumentListInfo Args(Loc, Loc);
171 Args.addArgument(TemplateArgumentLoc(
172 TemplateArgument(PromiseType),
173 S.Context.getTrivialTypeSourceInfo(PromiseType, Loc)));
174
175 // Build the template-id.
176 QualType CoroHandleType =
177 S.CheckTemplateIdType(TemplateName(CoroHandle), Loc, Args);
178 if (CoroHandleType.isNull())
179 return QualType();
180 if (S.RequireCompleteType(Loc, CoroHandleType,
181 diag::err_coroutine_type_missing_specialization))
182 return QualType();
183
184 return CoroHandleType;
185}
186
Eric Fiselierc8efda72016-10-27 18:43:28 +0000187static bool isValidCoroutineContext(Sema &S, SourceLocation Loc,
188 StringRef Keyword) {
Brian Gesiakb15c35a2019-03-25 00:53:10 +0000189 // [expr.await]p2 dictates that 'co_await' and 'co_yield' must be used within
190 // a function body.
Brian Gesiakc1b173a2018-06-23 18:01:02 +0000191 // FIXME: This also covers [expr.await]p2: "An await-expression shall not
192 // appear in a default argument." But the diagnostic QoI here could be
193 // improved to inform the user that default arguments specifically are not
194 // allowed.
Richard Smithcfd53b42015-10-22 06:13:50 +0000195 auto *FD = dyn_cast<FunctionDecl>(S.CurContext);
196 if (!FD) {
197 S.Diag(Loc, isa<ObjCMethodDecl>(S.CurContext)
198 ? diag::err_coroutine_objc_method
199 : diag::err_coroutine_outside_function) << Keyword;
Eric Fiselierc8efda72016-10-27 18:43:28 +0000200 return false;
Richard Smithcfd53b42015-10-22 06:13:50 +0000201 }
202
Eric Fiselierc8efda72016-10-27 18:43:28 +0000203 // An enumeration for mapping the diagnostic type to the correct diagnostic
204 // selection index.
205 enum InvalidFuncDiag {
206 DiagCtor = 0,
207 DiagDtor,
Eric Fiselierc8efda72016-10-27 18:43:28 +0000208 DiagMain,
209 DiagConstexpr,
210 DiagAutoRet,
211 DiagVarargs,
Gauthier Harnisch796ed032019-06-14 08:56:20 +0000212 DiagConsteval,
Eric Fiselierc8efda72016-10-27 18:43:28 +0000213 };
214 bool Diagnosed = false;
215 auto DiagInvalid = [&](InvalidFuncDiag ID) {
216 S.Diag(Loc, diag::err_coroutine_invalid_func_context) << ID << Keyword;
217 Diagnosed = true;
218 return false;
219 };
220
Vivek Pandya3a0100a2019-06-19 14:12:19 +0000221 // Diagnose when a constructor, destructor
Eric Fiselierc8efda72016-10-27 18:43:28 +0000222 // or the function 'main' are declared as a coroutine.
223 auto *MD = dyn_cast<CXXMethodDecl>(FD);
Vivek Pandya3a0100a2019-06-19 14:12:19 +0000224 // [class.ctor]p11: "A constructor shall not be a coroutine."
Eric Fiselierc8efda72016-10-27 18:43:28 +0000225 if (MD && isa<CXXConstructorDecl>(MD))
226 return DiagInvalid(DiagCtor);
Brian Gesiakc1b173a2018-06-23 18:01:02 +0000227 // [class.dtor]p17: "A destructor shall not be a coroutine."
Eric Fiselierc8efda72016-10-27 18:43:28 +0000228 else if (MD && isa<CXXDestructorDecl>(MD))
229 return DiagInvalid(DiagDtor);
Brian Gesiakc1b173a2018-06-23 18:01:02 +0000230 // [basic.start.main]p3: "The function main shall not be a coroutine."
Eric Fiselierc8efda72016-10-27 18:43:28 +0000231 else if (FD->isMain())
232 return DiagInvalid(DiagMain);
233
234 // Emit a diagnostics for each of the following conditions which is not met.
Brian Gesiakc1b173a2018-06-23 18:01:02 +0000235 // [expr.const]p2: "An expression e is a core constant expression unless the
236 // evaluation of e [...] would evaluate one of the following expressions:
237 // [...] an await-expression [...] a yield-expression."
Eric Fiselierc8efda72016-10-27 18:43:28 +0000238 if (FD->isConstexpr())
Gauthier Harnisch796ed032019-06-14 08:56:20 +0000239 DiagInvalid(FD->isConsteval() ? DiagConsteval : DiagConstexpr);
Brian Gesiakc1b173a2018-06-23 18:01:02 +0000240 // [dcl.spec.auto]p15: "A function declared with a return type that uses a
241 // placeholder type shall not be a coroutine."
Eric Fiselierc8efda72016-10-27 18:43:28 +0000242 if (FD->getReturnType()->isUndeducedType())
243 DiagInvalid(DiagAutoRet);
Brian Gesiakc1b173a2018-06-23 18:01:02 +0000244 // [dcl.fct.def.coroutine]p1: "The parameter-declaration-clause of the
245 // coroutine shall not terminate with an ellipsis that is not part of a
246 // parameter-declaration."
Eric Fiselierc8efda72016-10-27 18:43:28 +0000247 if (FD->isVariadic())
248 DiagInvalid(DiagVarargs);
249
250 return !Diagnosed;
251}
252
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000253static ExprResult buildOperatorCoawaitLookupExpr(Sema &SemaRef, Scope *S,
254 SourceLocation Loc) {
255 DeclarationName OpName =
256 SemaRef.Context.DeclarationNames.getCXXOperatorName(OO_Coawait);
257 LookupResult Operators(SemaRef, OpName, SourceLocation(),
258 Sema::LookupOperatorName);
259 SemaRef.LookupName(Operators, S);
Eric Fiselierc8efda72016-10-27 18:43:28 +0000260
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000261 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
262 const auto &Functions = Operators.asUnresolvedSet();
263 bool IsOverloaded =
264 Functions.size() > 1 ||
265 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
266 Expr *CoawaitOp = UnresolvedLookupExpr::Create(
267 SemaRef.Context, /*NamingClass*/ nullptr, NestedNameSpecifierLoc(),
268 DeclarationNameInfo(OpName, Loc), /*RequiresADL*/ true, IsOverloaded,
269 Functions.begin(), Functions.end());
270 assert(CoawaitOp);
271 return CoawaitOp;
272}
Eric Fiselierc8efda72016-10-27 18:43:28 +0000273
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000274/// Build a call to 'operator co_await' if there is a suitable operator for
275/// the given expression.
276static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, SourceLocation Loc,
277 Expr *E,
278 UnresolvedLookupExpr *Lookup) {
279 UnresolvedSet<16> Functions;
280 Functions.append(Lookup->decls_begin(), Lookup->decls_end());
281 return SemaRef.CreateOverloadedUnaryOp(Loc, UO_Coawait, Functions, E);
282}
Eric Fiselierc8efda72016-10-27 18:43:28 +0000283
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000284static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, Scope *S,
285 SourceLocation Loc, Expr *E) {
286 ExprResult R = buildOperatorCoawaitLookupExpr(SemaRef, S, Loc);
287 if (R.isInvalid())
288 return ExprError();
289 return buildOperatorCoawaitCall(SemaRef, Loc, E,
290 cast<UnresolvedLookupExpr>(R.get()));
Richard Smithcfd53b42015-10-22 06:13:50 +0000291}
292
Gor Nishanov8df64e92016-10-27 16:28:31 +0000293static Expr *buildBuiltinCall(Sema &S, SourceLocation Loc, Builtin::ID Id,
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000294 MultiExprArg CallArgs) {
Gor Nishanov8df64e92016-10-27 16:28:31 +0000295 StringRef Name = S.Context.BuiltinInfo.getName(Id);
296 LookupResult R(S, &S.Context.Idents.get(Name), Loc, Sema::LookupOrdinaryName);
297 S.LookupName(R, S.TUScope, /*AllowBuiltinCreation=*/true);
298
299 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
300 assert(BuiltInDecl && "failed to find builtin declaration");
301
302 ExprResult DeclRef =
303 S.BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
304 assert(DeclRef.isUsable() && "Builtin reference cannot fail");
305
306 ExprResult Call =
Richard Smith255b85f2019-05-08 01:36:36 +0000307 S.BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
Gor Nishanov8df64e92016-10-27 16:28:31 +0000308
309 assert(!Call.isInvalid() && "Call to builtin cannot fail!");
310 return Call.get();
311}
312
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000313static ExprResult buildCoroutineHandle(Sema &S, QualType PromiseType,
314 SourceLocation Loc) {
315 QualType CoroHandleType = lookupCoroutineHandleType(S, PromiseType, Loc);
316 if (CoroHandleType.isNull())
317 return ExprError();
318
319 DeclContext *LookupCtx = S.computeDeclContext(CoroHandleType);
320 LookupResult Found(S, &S.PP.getIdentifierTable().get("from_address"), Loc,
321 Sema::LookupOrdinaryName);
322 if (!S.LookupQualifiedName(Found, LookupCtx)) {
323 S.Diag(Loc, diag::err_coroutine_handle_missing_member)
324 << "from_address";
325 return ExprError();
326 }
327
328 Expr *FramePtr =
329 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_frame, {});
330
331 CXXScopeSpec SS;
332 ExprResult FromAddr =
333 S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
334 if (FromAddr.isInvalid())
335 return ExprError();
336
Richard Smith255b85f2019-05-08 01:36:36 +0000337 return S.BuildCallExpr(nullptr, FromAddr.get(), Loc, FramePtr, Loc);
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000338}
Richard Smithcfd53b42015-10-22 06:13:50 +0000339
Richard Smith9f690bd2015-10-27 06:02:45 +0000340struct ReadySuspendResumeResult {
Eric Fiselierd978e532017-05-28 18:21:12 +0000341 enum AwaitCallType { ACT_Ready, ACT_Suspend, ACT_Resume };
Richard Smith9f690bd2015-10-27 06:02:45 +0000342 Expr *Results[3];
Gor Nishanovce43bd22017-03-11 01:30:17 +0000343 OpaqueValueExpr *OpaqueValue;
344 bool IsInvalid;
Richard Smith9f690bd2015-10-27 06:02:45 +0000345};
346
Richard Smith23da82c2015-11-20 22:40:06 +0000347static ExprResult buildMemberCall(Sema &S, Expr *Base, SourceLocation Loc,
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000348 StringRef Name, MultiExprArg Args) {
Richard Smith23da82c2015-11-20 22:40:06 +0000349 DeclarationNameInfo NameInfo(&S.PP.getIdentifierTable().get(Name), Loc);
350
351 // FIXME: Fix BuildMemberReferenceExpr to take a const CXXScopeSpec&.
352 CXXScopeSpec SS;
353 ExprResult Result = S.BuildMemberReferenceExpr(
354 Base, Base->getType(), Loc, /*IsPtr=*/false, SS,
355 SourceLocation(), nullptr, NameInfo, /*TemplateArgs=*/nullptr,
356 /*Scope=*/nullptr);
357 if (Result.isInvalid())
358 return ExprError();
359
Gor Nishanovd4507262018-03-27 20:38:19 +0000360 // We meant exactly what we asked for. No need for typo correction.
361 if (auto *TE = dyn_cast<TypoExpr>(Result.get())) {
362 S.clearDelayedTypo(TE);
363 S.Diag(Loc, diag::err_no_member)
364 << NameInfo.getName() << Base->getType()->getAsCXXRecordDecl()
365 << Base->getSourceRange();
366 return ExprError();
367 }
368
Richard Smith255b85f2019-05-08 01:36:36 +0000369 return S.BuildCallExpr(nullptr, Result.get(), Loc, Args, Loc, nullptr);
Richard Smith23da82c2015-11-20 22:40:06 +0000370}
371
Gor Nishanov0f333002017-08-25 04:46:54 +0000372// See if return type is coroutine-handle and if so, invoke builtin coro-resume
373// on its address. This is to enable experimental support for coroutine-handle
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000374// returning await_suspend that results in a guaranteed tail call to the target
Gor Nishanov0f333002017-08-25 04:46:54 +0000375// coroutine.
376static Expr *maybeTailCall(Sema &S, QualType RetType, Expr *E,
377 SourceLocation Loc) {
378 if (RetType->isReferenceType())
379 return nullptr;
380 Type const *T = RetType.getTypePtr();
381 if (!T->isClassType() && !T->isStructureType())
382 return nullptr;
383
384 // FIXME: Add convertability check to coroutine_handle<>. Possibly via
385 // EvaluateBinaryTypeTrait(BTT_IsConvertible, ...) which is at the moment
386 // a private function in SemaExprCXX.cpp
387
388 ExprResult AddressExpr = buildMemberCall(S, E, Loc, "address", None);
389 if (AddressExpr.isInvalid())
390 return nullptr;
391
392 Expr *JustAddress = AddressExpr.get();
393 // FIXME: Check that the type of AddressExpr is void*
394 return buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_resume,
395 JustAddress);
396}
397
Richard Smith9f690bd2015-10-27 06:02:45 +0000398/// Build calls to await_ready, await_suspend, and await_resume for a co_await
399/// expression.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000400static ReadySuspendResumeResult buildCoawaitCalls(Sema &S, VarDecl *CoroPromise,
401 SourceLocation Loc, Expr *E) {
Gor Nishanovce43bd22017-03-11 01:30:17 +0000402 OpaqueValueExpr *Operand = new (S.Context)
403 OpaqueValueExpr(Loc, E->getType(), VK_LValue, E->getObjectKind(), E);
404
Richard Smith9f690bd2015-10-27 06:02:45 +0000405 // Assume invalid until we see otherwise.
Gor Nishanovce43bd22017-03-11 01:30:17 +0000406 ReadySuspendResumeResult Calls = {{}, Operand, /*IsInvalid=*/true};
Richard Smith9f690bd2015-10-27 06:02:45 +0000407
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000408 ExprResult CoroHandleRes = buildCoroutineHandle(S, CoroPromise->getType(), Loc);
409 if (CoroHandleRes.isInvalid())
410 return Calls;
411 Expr *CoroHandle = CoroHandleRes.get();
412
Richard Smith9f690bd2015-10-27 06:02:45 +0000413 const StringRef Funcs[] = {"await_ready", "await_suspend", "await_resume"};
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000414 MultiExprArg Args[] = {None, CoroHandle, None};
Richard Smith9f690bd2015-10-27 06:02:45 +0000415 for (size_t I = 0, N = llvm::array_lengthof(Funcs); I != N; ++I) {
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000416 ExprResult Result = buildMemberCall(S, Operand, Loc, Funcs[I], Args[I]);
Richard Smith9f690bd2015-10-27 06:02:45 +0000417 if (Result.isInvalid())
418 return Calls;
419 Calls.Results[I] = Result.get();
420 }
421
Eric Fiselierd978e532017-05-28 18:21:12 +0000422 // Assume the calls are valid; all further checking should make them invalid.
Richard Smith9f690bd2015-10-27 06:02:45 +0000423 Calls.IsInvalid = false;
Eric Fiselierd978e532017-05-28 18:21:12 +0000424
425 using ACT = ReadySuspendResumeResult::AwaitCallType;
426 CallExpr *AwaitReady = cast<CallExpr>(Calls.Results[ACT::ACT_Ready]);
427 if (!AwaitReady->getType()->isDependentType()) {
428 // [expr.await]p3 [...]
429 // — await-ready is the expression e.await_ready(), contextually converted
430 // to bool.
431 ExprResult Conv = S.PerformContextuallyConvertToBool(AwaitReady);
432 if (Conv.isInvalid()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000433 S.Diag(AwaitReady->getDirectCallee()->getBeginLoc(),
Eric Fiselierd978e532017-05-28 18:21:12 +0000434 diag::note_await_ready_no_bool_conversion);
435 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
436 << AwaitReady->getDirectCallee() << E->getSourceRange();
437 Calls.IsInvalid = true;
438 }
439 Calls.Results[ACT::ACT_Ready] = Conv.get();
440 }
441 CallExpr *AwaitSuspend = cast<CallExpr>(Calls.Results[ACT::ACT_Suspend]);
442 if (!AwaitSuspend->getType()->isDependentType()) {
443 // [expr.await]p3 [...]
444 // - await-suspend is the expression e.await_suspend(h), which shall be
445 // a prvalue of type void or bool.
Eric Fiselier84ee7ff2017-05-31 23:41:11 +0000446 QualType RetType = AwaitSuspend->getCallReturnType(S.Context);
Gor Nishanovdb419a62017-09-05 19:31:52 +0000447
Gor Nishanov0f333002017-08-25 04:46:54 +0000448 // Experimental support for coroutine_handle returning await_suspend.
449 if (Expr *TailCallSuspend = maybeTailCall(S, RetType, AwaitSuspend, Loc))
450 Calls.Results[ACT::ACT_Suspend] = TailCallSuspend;
451 else {
452 // non-class prvalues always have cv-unqualified types
Gor Nishanov0f333002017-08-25 04:46:54 +0000453 if (RetType->isReferenceType() ||
Gor Nishanovdb419a62017-09-05 19:31:52 +0000454 (!RetType->isBooleanType() && !RetType->isVoidType())) {
Gor Nishanov0f333002017-08-25 04:46:54 +0000455 S.Diag(AwaitSuspend->getCalleeDecl()->getLocation(),
456 diag::err_await_suspend_invalid_return_type)
457 << RetType;
458 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
459 << AwaitSuspend->getDirectCallee();
460 Calls.IsInvalid = true;
461 }
Eric Fiselierd978e532017-05-28 18:21:12 +0000462 }
463 }
464
Richard Smith9f690bd2015-10-27 06:02:45 +0000465 return Calls;
466}
467
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000468static ExprResult buildPromiseCall(Sema &S, VarDecl *Promise,
469 SourceLocation Loc, StringRef Name,
470 MultiExprArg Args) {
471
472 // Form a reference to the promise.
473 ExprResult PromiseRef = S.BuildDeclRefExpr(
474 Promise, Promise->getType().getNonReferenceType(), VK_LValue, Loc);
475 if (PromiseRef.isInvalid())
476 return ExprError();
477
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000478 return buildMemberCall(S, PromiseRef.get(), Loc, Name, Args);
479}
480
481VarDecl *Sema::buildCoroutinePromise(SourceLocation Loc) {
482 assert(isa<FunctionDecl>(CurContext) && "not in a function scope");
483 auto *FD = cast<FunctionDecl>(CurContext);
Eric Fiselier166c6e62017-07-10 01:27:22 +0000484 bool IsThisDependentType = [&] {
485 if (auto *MD = dyn_cast_or_null<CXXMethodDecl>(FD))
Brian Gesiak5488ab42019-01-11 01:54:53 +0000486 return MD->isInstance() && MD->getThisType()->isDependentType();
Eric Fiselier166c6e62017-07-10 01:27:22 +0000487 else
488 return false;
489 }();
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000490
Eric Fiselier166c6e62017-07-10 01:27:22 +0000491 QualType T = FD->getType()->isDependentType() || IsThisDependentType
492 ? Context.DependentTy
493 : lookupPromiseType(*this, FD, Loc);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000494 if (T.isNull())
495 return nullptr;
496
497 auto *VD = VarDecl::Create(Context, FD, FD->getLocation(), FD->getLocation(),
498 &PP.getIdentifierTable().get("__promise"), T,
499 Context.getTrivialTypeSourceInfo(T, Loc), SC_None);
500 CheckVariableDeclarationType(VD);
501 if (VD->isInvalidDecl())
502 return nullptr;
Brian Gesiak61f4ac92018-01-24 22:15:42 +0000503
504 auto *ScopeInfo = getCurFunction();
505 // Build a list of arguments, based on the coroutine functions arguments,
506 // that will be passed to the promise type's constructor.
507 llvm::SmallVector<Expr *, 4> CtorArgExprs;
Gor Nishanov07ac63f2018-05-28 18:08:47 +0000508
509 // Add implicit object parameter.
510 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
511 if (MD->isInstance() && !isLambdaCallOperator(MD)) {
512 ExprResult ThisExpr = ActOnCXXThis(Loc);
513 if (ThisExpr.isInvalid())
514 return nullptr;
515 ThisExpr = CreateBuiltinUnaryOp(Loc, UO_Deref, ThisExpr.get());
516 if (ThisExpr.isInvalid())
517 return nullptr;
518 CtorArgExprs.push_back(ThisExpr.get());
519 }
520 }
521
Brian Gesiak61f4ac92018-01-24 22:15:42 +0000522 auto &Moves = ScopeInfo->CoroutineParameterMoves;
523 for (auto *PD : FD->parameters()) {
524 if (PD->getType()->isDependentType())
525 continue;
526
527 auto RefExpr = ExprEmpty();
528 auto Move = Moves.find(PD);
Brian Gesiak98606222018-02-15 20:37:22 +0000529 assert(Move != Moves.end() &&
530 "Coroutine function parameter not inserted into move map");
531 // If a reference to the function parameter exists in the coroutine
532 // frame, use that reference.
533 auto *MoveDecl =
534 cast<VarDecl>(cast<DeclStmt>(Move->second)->getSingleDecl());
535 RefExpr =
536 BuildDeclRefExpr(MoveDecl, MoveDecl->getType().getNonReferenceType(),
537 ExprValueKind::VK_LValue, FD->getLocation());
Brian Gesiak61f4ac92018-01-24 22:15:42 +0000538 if (RefExpr.isInvalid())
539 return nullptr;
540 CtorArgExprs.push_back(RefExpr.get());
541 }
542
543 // Create an initialization sequence for the promise type using the
544 // constructor arguments, wrapped in a parenthesized list expression.
Bruno Riccif49e1ca2018-11-20 16:20:40 +0000545 Expr *PLE = ParenListExpr::Create(Context, FD->getLocation(),
546 CtorArgExprs, FD->getLocation());
Brian Gesiak61f4ac92018-01-24 22:15:42 +0000547 InitializedEntity Entity = InitializedEntity::InitializeVariable(VD);
548 InitializationKind Kind = InitializationKind::CreateForInit(
549 VD->getLocation(), /*DirectInit=*/true, PLE);
550 InitializationSequence InitSeq(*this, Entity, Kind, CtorArgExprs,
551 /*TopLevelOfInitList=*/false,
552 /*TreatUnavailableAsInvalid=*/false);
553
554 // Attempt to initialize the promise type with the arguments.
555 // If that fails, fall back to the promise type's default constructor.
556 if (InitSeq) {
557 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, CtorArgExprs);
558 if (Result.isInvalid()) {
559 VD->setInvalidDecl();
560 } else if (Result.get()) {
561 VD->setInit(MaybeCreateExprWithCleanups(Result.get()));
562 VD->setInitStyle(VarDecl::CallInit);
563 CheckCompleteVariableDeclaration(VD);
564 }
565 } else
566 ActOnUninitializedDecl(VD);
567
Eric Fiselier37b8a372017-05-31 19:36:59 +0000568 FD->addDecl(VD);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000569 return VD;
570}
571
572/// Check that this is a context in which a coroutine suspension can appear.
573static FunctionScopeInfo *checkCoroutineContext(Sema &S, SourceLocation Loc,
Eric Fiseliercac0a592017-03-11 02:35:37 +0000574 StringRef Keyword,
575 bool IsImplicit = false) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000576 if (!isValidCoroutineContext(S, Loc, Keyword))
577 return nullptr;
578
579 assert(isa<FunctionDecl>(S.CurContext) && "not in a function scope");
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000580
581 auto *ScopeInfo = S.getCurFunction();
582 assert(ScopeInfo && "missing function scope for function");
583
Eric Fiseliercac0a592017-03-11 02:35:37 +0000584 if (ScopeInfo->FirstCoroutineStmtLoc.isInvalid() && !IsImplicit)
585 ScopeInfo->setFirstCoroutineStmt(Loc, Keyword);
586
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000587 if (ScopeInfo->CoroutinePromise)
588 return ScopeInfo;
589
Brian Gesiak61f4ac92018-01-24 22:15:42 +0000590 if (!S.buildCoroutineParameterMoves(Loc))
591 return nullptr;
592
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000593 ScopeInfo->CoroutinePromise = S.buildCoroutinePromise(Loc);
594 if (!ScopeInfo->CoroutinePromise)
595 return nullptr;
596
597 return ScopeInfo;
598}
599
Eric Fiselierb936a392017-06-14 03:24:55 +0000600bool Sema::ActOnCoroutineBodyStart(Scope *SC, SourceLocation KWLoc,
601 StringRef Keyword) {
602 if (!checkCoroutineContext(*this, KWLoc, Keyword))
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000603 return false;
Eric Fiselierb936a392017-06-14 03:24:55 +0000604 auto *ScopeInfo = getCurFunction();
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000605 assert(ScopeInfo->CoroutinePromise);
606
607 // If we have existing coroutine statements then we have already built
608 // the initial and final suspend points.
609 if (!ScopeInfo->NeedsCoroutineSuspends)
610 return true;
611
612 ScopeInfo->setNeedsCoroutineSuspends(false);
613
Eric Fiselierb936a392017-06-14 03:24:55 +0000614 auto *Fn = cast<FunctionDecl>(CurContext);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000615 SourceLocation Loc = Fn->getLocation();
616 // Build the initial suspend point
617 auto buildSuspends = [&](StringRef Name) mutable -> StmtResult {
618 ExprResult Suspend =
Eric Fiselierb936a392017-06-14 03:24:55 +0000619 buildPromiseCall(*this, ScopeInfo->CoroutinePromise, Loc, Name, None);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000620 if (Suspend.isInvalid())
621 return StmtError();
Eric Fiselierb936a392017-06-14 03:24:55 +0000622 Suspend = buildOperatorCoawaitCall(*this, SC, Loc, Suspend.get());
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000623 if (Suspend.isInvalid())
624 return StmtError();
Eric Fiselierb936a392017-06-14 03:24:55 +0000625 Suspend = BuildResolvedCoawaitExpr(Loc, Suspend.get(),
626 /*IsImplicit*/ true);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +0000627 Suspend = ActOnFinishFullExpr(Suspend.get(), /*DiscardedValue*/ false);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000628 if (Suspend.isInvalid()) {
Eric Fiselierb936a392017-06-14 03:24:55 +0000629 Diag(Loc, diag::note_coroutine_promise_suspend_implicitly_required)
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000630 << ((Name == "initial_suspend") ? 0 : 1);
Eric Fiselierb936a392017-06-14 03:24:55 +0000631 Diag(KWLoc, diag::note_declared_coroutine_here) << Keyword;
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000632 return StmtError();
633 }
634 return cast<Stmt>(Suspend.get());
635 };
636
637 StmtResult InitSuspend = buildSuspends("initial_suspend");
638 if (InitSuspend.isInvalid())
639 return true;
640
641 StmtResult FinalSuspend = buildSuspends("final_suspend");
642 if (FinalSuspend.isInvalid())
643 return true;
644
645 ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());
646
647 return true;
648}
649
Brian Gesiakb15c35a2019-03-25 00:53:10 +0000650// Recursively walks up the scope hierarchy until either a 'catch' or a function
651// scope is found, whichever comes first.
652static bool isWithinCatchScope(Scope *S) {
653 // 'co_await' and 'co_yield' keywords are disallowed within catch blocks, but
654 // lambdas that use 'co_await' are allowed. The loop below ends when a
655 // function scope is found in order to ensure the following behavior:
656 //
657 // void foo() { // <- function scope
658 // try { //
659 // co_await x; // <- 'co_await' is OK within a function scope
660 // } catch { // <- catch scope
661 // co_await x; // <- 'co_await' is not OK within a catch scope
662 // []() { // <- function scope
663 // co_await x; // <- 'co_await' is OK within a function scope
664 // }();
665 // }
666 // }
667 while (S && !(S->getFlags() & Scope::FnScope)) {
668 if (S->getFlags() & Scope::CatchScope)
669 return true;
670 S = S->getParent();
671 }
672 return false;
673}
674
675// [expr.await]p2, emphasis added: "An await-expression shall appear only in
676// a *potentially evaluated* expression within the compound-statement of a
677// function-body *outside of a handler* [...] A context within a function
678// where an await-expression can appear is called a suspension context of the
679// function."
680static void checkSuspensionContext(Sema &S, SourceLocation Loc,
681 StringRef Keyword) {
682 // First emphasis of [expr.await]p2: must be a potentially evaluated context.
683 // That is, 'co_await' and 'co_yield' cannot appear in subexpressions of
684 // \c sizeof.
685 if (S.isUnevaluatedContext())
686 S.Diag(Loc, diag::err_coroutine_unevaluated_context) << Keyword;
687
688 // Second emphasis of [expr.await]p2: must be outside of an exception handler.
689 if (isWithinCatchScope(S.getCurScope()))
690 S.Diag(Loc, diag::err_coroutine_within_handler) << Keyword;
691}
692
Richard Smith9f690bd2015-10-27 06:02:45 +0000693ExprResult Sema::ActOnCoawaitExpr(Scope *S, SourceLocation Loc, Expr *E) {
Eric Fiselierb936a392017-06-14 03:24:55 +0000694 if (!ActOnCoroutineBodyStart(S, Loc, "co_await")) {
Eric Fiseliera5465282016-09-29 21:47:39 +0000695 CorrectDelayedTyposInExpr(E);
696 return ExprError();
697 }
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000698
Brian Gesiakb15c35a2019-03-25 00:53:10 +0000699 checkSuspensionContext(*this, Loc, "co_await");
700
Richard Smith10610f72015-11-20 22:57:24 +0000701 if (E->getType()->isPlaceholderType()) {
702 ExprResult R = CheckPlaceholderExpr(E);
703 if (R.isInvalid()) return ExprError();
704 E = R.get();
705 }
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000706 ExprResult Lookup = buildOperatorCoawaitLookupExpr(*this, S, Loc);
707 if (Lookup.isInvalid())
708 return ExprError();
709 return BuildUnresolvedCoawaitExpr(Loc, E,
710 cast<UnresolvedLookupExpr>(Lookup.get()));
711}
Richard Smith10610f72015-11-20 22:57:24 +0000712
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000713ExprResult Sema::BuildUnresolvedCoawaitExpr(SourceLocation Loc, Expr *E,
Eric Fiseliercac0a592017-03-11 02:35:37 +0000714 UnresolvedLookupExpr *Lookup) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000715 auto *FSI = checkCoroutineContext(*this, Loc, "co_await");
716 if (!FSI)
717 return ExprError();
718
719 if (E->getType()->isPlaceholderType()) {
720 ExprResult R = CheckPlaceholderExpr(E);
721 if (R.isInvalid())
722 return ExprError();
723 E = R.get();
724 }
725
726 auto *Promise = FSI->CoroutinePromise;
727 if (Promise->getType()->isDependentType()) {
728 Expr *Res =
729 new (Context) DependentCoawaitExpr(Loc, Context.DependentTy, E, Lookup);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000730 return Res;
731 }
732
733 auto *RD = Promise->getType()->getAsCXXRecordDecl();
734 if (lookupMember(*this, "await_transform", RD, Loc)) {
735 ExprResult R = buildPromiseCall(*this, Promise, Loc, "await_transform", E);
736 if (R.isInvalid()) {
737 Diag(Loc,
738 diag::note_coroutine_promise_implicit_await_transform_required_here)
739 << E->getSourceRange();
740 return ExprError();
741 }
742 E = R.get();
743 }
744 ExprResult Awaitable = buildOperatorCoawaitCall(*this, Loc, E, Lookup);
Richard Smith9f690bd2015-10-27 06:02:45 +0000745 if (Awaitable.isInvalid())
746 return ExprError();
Eric Fiseliera5465282016-09-29 21:47:39 +0000747
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000748 return BuildResolvedCoawaitExpr(Loc, Awaitable.get());
Richard Smith9f690bd2015-10-27 06:02:45 +0000749}
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000750
751ExprResult Sema::BuildResolvedCoawaitExpr(SourceLocation Loc, Expr *E,
752 bool IsImplicit) {
Eric Fiseliercac0a592017-03-11 02:35:37 +0000753 auto *Coroutine = checkCoroutineContext(*this, Loc, "co_await", IsImplicit);
Richard Smith744b2242015-11-20 02:54:01 +0000754 if (!Coroutine)
755 return ExprError();
Richard Smith9f690bd2015-10-27 06:02:45 +0000756
Richard Smith9f690bd2015-10-27 06:02:45 +0000757 if (E->getType()->isPlaceholderType()) {
758 ExprResult R = CheckPlaceholderExpr(E);
759 if (R.isInvalid()) return ExprError();
760 E = R.get();
761 }
762
Richard Smith10610f72015-11-20 22:57:24 +0000763 if (E->getType()->isDependentType()) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000764 Expr *Res = new (Context)
765 CoawaitExpr(Loc, Context.DependentTy, E, IsImplicit);
Richard Smith10610f72015-11-20 22:57:24 +0000766 return Res;
767 }
768
Richard Smith1f38edd2015-11-22 03:13:02 +0000769 // If the expression is a temporary, materialize it as an lvalue so that we
770 // can use it multiple times.
771 if (E->getValueKind() == VK_RValue)
Tim Shen4a05bb82016-06-21 20:29:17 +0000772 E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
Richard Smith9f690bd2015-10-27 06:02:45 +0000773
Eric Fiselierd2e30d32018-03-27 03:15:46 +0000774 // The location of the `co_await` token cannot be used when constructing
775 // the member call expressions since it's before the location of `Expr`, which
776 // is used as the start of the member call expression.
777 SourceLocation CallLoc = E->getExprLoc();
778
Richard Smith9f690bd2015-10-27 06:02:45 +0000779 // Build the await_ready, await_suspend, await_resume calls.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000780 ReadySuspendResumeResult RSS =
Eric Fiselierd2e30d32018-03-27 03:15:46 +0000781 buildCoawaitCalls(*this, Coroutine->CoroutinePromise, CallLoc, E);
Richard Smith9f690bd2015-10-27 06:02:45 +0000782 if (RSS.IsInvalid)
783 return ExprError();
784
Gor Nishanovce43bd22017-03-11 01:30:17 +0000785 Expr *Res =
786 new (Context) CoawaitExpr(Loc, E, RSS.Results[0], RSS.Results[1],
787 RSS.Results[2], RSS.OpaqueValue, IsImplicit);
Eric Fiseliercac0a592017-03-11 02:35:37 +0000788
Richard Smithcfd53b42015-10-22 06:13:50 +0000789 return Res;
790}
791
Richard Smith9f690bd2015-10-27 06:02:45 +0000792ExprResult Sema::ActOnCoyieldExpr(Scope *S, SourceLocation Loc, Expr *E) {
Eric Fiselierb936a392017-06-14 03:24:55 +0000793 if (!ActOnCoroutineBodyStart(S, Loc, "co_yield")) {
Eric Fiseliera5465282016-09-29 21:47:39 +0000794 CorrectDelayedTyposInExpr(E);
Richard Smith23da82c2015-11-20 22:40:06 +0000795 return ExprError();
Eric Fiseliera5465282016-09-29 21:47:39 +0000796 }
Richard Smith23da82c2015-11-20 22:40:06 +0000797
Brian Gesiakb15c35a2019-03-25 00:53:10 +0000798 checkSuspensionContext(*this, Loc, "co_yield");
799
Richard Smith23da82c2015-11-20 22:40:06 +0000800 // Build yield_value call.
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000801 ExprResult Awaitable = buildPromiseCall(
802 *this, getCurFunction()->CoroutinePromise, Loc, "yield_value", E);
Richard Smith9f690bd2015-10-27 06:02:45 +0000803 if (Awaitable.isInvalid())
804 return ExprError();
Richard Smith23da82c2015-11-20 22:40:06 +0000805
806 // Build 'operator co_await' call.
807 Awaitable = buildOperatorCoawaitCall(*this, S, Loc, Awaitable.get());
808 if (Awaitable.isInvalid())
809 return ExprError();
810
Richard Smith9f690bd2015-10-27 06:02:45 +0000811 return BuildCoyieldExpr(Loc, Awaitable.get());
812}
813ExprResult Sema::BuildCoyieldExpr(SourceLocation Loc, Expr *E) {
814 auto *Coroutine = checkCoroutineContext(*this, Loc, "co_yield");
Richard Smith744b2242015-11-20 02:54:01 +0000815 if (!Coroutine)
816 return ExprError();
Richard Smithcfd53b42015-10-22 06:13:50 +0000817
Richard Smith10610f72015-11-20 22:57:24 +0000818 if (E->getType()->isPlaceholderType()) {
819 ExprResult R = CheckPlaceholderExpr(E);
820 if (R.isInvalid()) return ExprError();
821 E = R.get();
822 }
823
Richard Smithd7bed4d2015-11-22 02:57:17 +0000824 if (E->getType()->isDependentType()) {
825 Expr *Res = new (Context) CoyieldExpr(Loc, Context.DependentTy, E);
Richard Smithd7bed4d2015-11-22 02:57:17 +0000826 return Res;
827 }
828
Richard Smith1f38edd2015-11-22 03:13:02 +0000829 // If the expression is a temporary, materialize it as an lvalue so that we
830 // can use it multiple times.
831 if (E->getValueKind() == VK_RValue)
Tim Shen4a05bb82016-06-21 20:29:17 +0000832 E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
Richard Smithd7bed4d2015-11-22 02:57:17 +0000833
834 // Build the await_ready, await_suspend, await_resume calls.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000835 ReadySuspendResumeResult RSS =
836 buildCoawaitCalls(*this, Coroutine->CoroutinePromise, Loc, E);
Richard Smithd7bed4d2015-11-22 02:57:17 +0000837 if (RSS.IsInvalid)
838 return ExprError();
839
Eric Fiselierb936a392017-06-14 03:24:55 +0000840 Expr *Res =
841 new (Context) CoyieldExpr(Loc, E, RSS.Results[0], RSS.Results[1],
842 RSS.Results[2], RSS.OpaqueValue);
Eric Fiseliercac0a592017-03-11 02:35:37 +0000843
Richard Smithcfd53b42015-10-22 06:13:50 +0000844 return Res;
845}
846
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000847StmtResult Sema::ActOnCoreturnStmt(Scope *S, SourceLocation Loc, Expr *E) {
Eric Fiselierb936a392017-06-14 03:24:55 +0000848 if (!ActOnCoroutineBodyStart(S, Loc, "co_return")) {
Eric Fiseliera5465282016-09-29 21:47:39 +0000849 CorrectDelayedTyposInExpr(E);
850 return StmtError();
851 }
Richard Smith9f690bd2015-10-27 06:02:45 +0000852 return BuildCoreturnStmt(Loc, E);
853}
Gor Nishanov3e048bb2016-10-04 00:31:16 +0000854
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000855StmtResult Sema::BuildCoreturnStmt(SourceLocation Loc, Expr *E,
856 bool IsImplicit) {
Eric Fiseliercac0a592017-03-11 02:35:37 +0000857 auto *FSI = checkCoroutineContext(*this, Loc, "co_return", IsImplicit);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000858 if (!FSI)
Richard Smith71d403e2015-11-22 07:33:28 +0000859 return StmtError();
860
861 if (E && E->getType()->isPlaceholderType() &&
862 !E->getType()->isSpecificPlaceholderType(BuiltinType::Overload)) {
Richard Smith10610f72015-11-20 22:57:24 +0000863 ExprResult R = CheckPlaceholderExpr(E);
864 if (R.isInvalid()) return StmtError();
865 E = R.get();
866 }
867
Brian Gesiak0b568302018-10-08 03:08:39 +0000868 // Move the return value if we can
869 if (E) {
870 auto NRVOCandidate = this->getCopyElisionCandidate(E->getType(), E, CES_AsIfByStdMove);
871 if (NRVOCandidate) {
872 InitializedEntity Entity =
873 InitializedEntity::InitializeResult(Loc, E->getType(), NRVOCandidate);
874 ExprResult MoveResult = this->PerformMoveOrCopyInitialization(
875 Entity, NRVOCandidate, E->getType(), E);
876 if (MoveResult.get())
877 E = MoveResult.get();
878 }
879 }
880
Richard Smith4ba66602015-11-22 07:05:16 +0000881 // FIXME: If the operand is a reference to a variable that's about to go out
Richard Smith2af65c42015-11-24 02:34:39 +0000882 // of scope, we should treat the operand as an xvalue for this overload
Richard Smith4ba66602015-11-22 07:05:16 +0000883 // resolution.
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000884 VarDecl *Promise = FSI->CoroutinePromise;
Richard Smith4ba66602015-11-22 07:05:16 +0000885 ExprResult PC;
Eric Fiselier98131312016-10-06 21:23:38 +0000886 if (E && (isa<InitListExpr>(E) || !E->getType()->isVoidType())) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000887 PC = buildPromiseCall(*this, Promise, Loc, "return_value", E);
Richard Smith4ba66602015-11-22 07:05:16 +0000888 } else {
889 E = MakeFullDiscardedValueExpr(E).get();
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000890 PC = buildPromiseCall(*this, Promise, Loc, "return_void", None);
Richard Smith4ba66602015-11-22 07:05:16 +0000891 }
892 if (PC.isInvalid())
893 return StmtError();
894
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +0000895 Expr *PCE = ActOnFinishFullExpr(PC.get(), /*DiscardedValue*/ false).get();
Richard Smith4ba66602015-11-22 07:05:16 +0000896
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000897 Stmt *Res = new (Context) CoreturnStmt(Loc, E, PCE, IsImplicit);
Richard Smithcfd53b42015-10-22 06:13:50 +0000898 return Res;
899}
900
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000901/// Look up the std::nothrow object.
902static Expr *buildStdNoThrowDeclRef(Sema &S, SourceLocation Loc) {
903 NamespaceDecl *Std = S.getStdNamespace();
904 assert(Std && "Should already be diagnosed");
905
906 LookupResult Result(S, &S.PP.getIdentifierTable().get("nothrow"), Loc,
907 Sema::LookupOrdinaryName);
908 if (!S.LookupQualifiedName(Result, Std)) {
909 // FIXME: <experimental/coroutine> should have been included already.
910 // If we require it to include <new> then this diagnostic is no longer
911 // needed.
912 S.Diag(Loc, diag::err_implicit_coroutine_std_nothrow_type_not_found);
913 return nullptr;
914 }
915
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000916 auto *VD = Result.getAsSingle<VarDecl>();
917 if (!VD) {
918 Result.suppressDiagnostics();
919 // We found something weird. Complain about the first thing we found.
920 NamedDecl *Found = *Result.begin();
921 S.Diag(Found->getLocation(), diag::err_malformed_std_nothrow);
922 return nullptr;
923 }
924
925 ExprResult DR = S.BuildDeclRefExpr(VD, VD->getType(), VK_LValue, Loc);
926 if (DR.isInvalid())
927 return nullptr;
928
929 return DR.get();
930}
931
Gor Nishanov8df64e92016-10-27 16:28:31 +0000932// Find an appropriate delete for the promise.
933static FunctionDecl *findDeleteForPromise(Sema &S, SourceLocation Loc,
934 QualType PromiseType) {
935 FunctionDecl *OperatorDelete = nullptr;
936
937 DeclarationName DeleteName =
938 S.Context.DeclarationNames.getCXXOperatorName(OO_Delete);
939
940 auto *PointeeRD = PromiseType->getAsCXXRecordDecl();
941 assert(PointeeRD && "PromiseType must be a CxxRecordDecl type");
942
943 if (S.FindDeallocationFunction(Loc, PointeeRD, DeleteName, OperatorDelete))
944 return nullptr;
945
946 if (!OperatorDelete) {
947 // Look for a global declaration.
948 const bool CanProvideSize = S.isCompleteType(Loc, PromiseType);
949 const bool Overaligned = false;
950 OperatorDelete = S.FindUsualDeallocationFunction(Loc, CanProvideSize,
951 Overaligned, DeleteName);
952 }
953 S.MarkFunctionReferenced(Loc, OperatorDelete);
954 return OperatorDelete;
955}
956
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000957
958void Sema::CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body) {
959 FunctionScopeInfo *Fn = getCurFunction();
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000960 assert(Fn && Fn->isCoroutine() && "not a coroutine");
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000961 if (!Body) {
962 assert(FD->isInvalidDecl() &&
963 "a null body is only allowed for invalid declarations");
964 return;
965 }
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000966 // We have a function that uses coroutine keywords, but we failed to build
967 // the promise type.
968 if (!Fn->CoroutinePromise)
969 return FD->setInvalidDecl();
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000970
971 if (isa<CoroutineBodyStmt>(Body)) {
Gor Nishanov29ff6382017-05-24 14:34:19 +0000972 // Nothing todo. the body is already a transformed coroutine body statement.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000973 return;
974 }
975
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000976 // Coroutines [stmt.return]p1:
977 // A return statement shall not appear in a coroutine.
978 if (Fn->FirstReturnLoc.isValid()) {
Eric Fiseliercac0a592017-03-11 02:35:37 +0000979 assert(Fn->FirstCoroutineStmtLoc.isValid() &&
980 "first coroutine location not set");
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000981 Diag(Fn->FirstReturnLoc, diag::err_return_in_coroutine);
Eric Fiseliercac0a592017-03-11 02:35:37 +0000982 Diag(Fn->FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
983 << Fn->getFirstCoroutineStmtKeyword();
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000984 }
Eric Fiselierbee782b2017-04-03 19:21:00 +0000985 CoroutineStmtBuilder Builder(*this, *FD, *Fn, Body);
986 if (Builder.isInvalid() || !Builder.buildStatements())
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000987 return FD->setInvalidDecl();
988
989 // Build body for the coroutine wrapper statement.
990 Body = CoroutineBodyStmt::Create(Context, Builder);
991}
992
Eric Fiselierbee782b2017-04-03 19:21:00 +0000993CoroutineStmtBuilder::CoroutineStmtBuilder(Sema &S, FunctionDecl &FD,
994 sema::FunctionScopeInfo &Fn,
995 Stmt *Body)
996 : S(S), FD(FD), Fn(Fn), Loc(FD.getLocation()),
997 IsPromiseDependentType(
998 !Fn.CoroutinePromise ||
999 Fn.CoroutinePromise->getType()->isDependentType()) {
1000 this->Body = Body;
Brian Gesiak61f4ac92018-01-24 22:15:42 +00001001
1002 for (auto KV : Fn.CoroutineParameterMoves)
1003 this->ParamMovesVector.push_back(KV.second);
1004 this->ParamMoves = this->ParamMovesVector;
1005
Eric Fiselierbee782b2017-04-03 19:21:00 +00001006 if (!IsPromiseDependentType) {
1007 PromiseRecordDecl = Fn.CoroutinePromise->getType()->getAsCXXRecordDecl();
1008 assert(PromiseRecordDecl && "Type should have already been checked");
1009 }
1010 this->IsValid = makePromiseStmt() && makeInitialAndFinalSuspend();
1011}
1012
1013bool CoroutineStmtBuilder::buildStatements() {
1014 assert(this->IsValid && "coroutine already invalid");
Brian Gesiak61f4ac92018-01-24 22:15:42 +00001015 this->IsValid = makeReturnObject();
Eric Fiselierbee782b2017-04-03 19:21:00 +00001016 if (this->IsValid && !IsPromiseDependentType)
1017 buildDependentStatements();
1018 return this->IsValid;
1019}
1020
1021bool CoroutineStmtBuilder::buildDependentStatements() {
1022 assert(this->IsValid && "coroutine already invalid");
1023 assert(!this->IsPromiseDependentType &&
1024 "coroutine cannot have a dependent promise type");
1025 this->IsValid = makeOnException() && makeOnFallthrough() &&
Gor Nishanov6a470682017-05-22 20:22:23 +00001026 makeGroDeclAndReturnStmt() && makeReturnOnAllocFailure() &&
1027 makeNewAndDeleteExpr();
Eric Fiselierbee782b2017-04-03 19:21:00 +00001028 return this->IsValid;
1029}
1030
1031bool CoroutineStmtBuilder::makePromiseStmt() {
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001032 // Form a declaration statement for the promise declaration, so that AST
1033 // visitors can more easily find it.
1034 StmtResult PromiseStmt =
1035 S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(Fn.CoroutinePromise), Loc, Loc);
1036 if (PromiseStmt.isInvalid())
1037 return false;
1038
1039 this->Promise = PromiseStmt.get();
1040 return true;
1041}
1042
Eric Fiselierbee782b2017-04-03 19:21:00 +00001043bool CoroutineStmtBuilder::makeInitialAndFinalSuspend() {
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001044 if (Fn.hasInvalidCoroutineSuspends())
1045 return false;
1046 this->InitialSuspend = cast<Expr>(Fn.CoroutineSuspends.first);
1047 this->FinalSuspend = cast<Expr>(Fn.CoroutineSuspends.second);
1048 return true;
1049}
1050
Gor Nishanov3aa9eb32017-03-27 23:36:59 +00001051static bool diagReturnOnAllocFailure(Sema &S, Expr *E,
1052 CXXRecordDecl *PromiseRecordDecl,
1053 FunctionScopeInfo &Fn) {
1054 auto Loc = E->getExprLoc();
1055 if (auto *DeclRef = dyn_cast_or_null<DeclRefExpr>(E)) {
1056 auto *Decl = DeclRef->getDecl();
1057 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Decl)) {
1058 if (Method->isStatic())
1059 return true;
1060 else
1061 Loc = Decl->getLocation();
1062 }
1063 }
1064
1065 S.Diag(
1066 Loc,
1067 diag::err_coroutine_promise_get_return_object_on_allocation_failure)
1068 << PromiseRecordDecl;
1069 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1070 << Fn.getFirstCoroutineStmtKeyword();
1071 return false;
1072}
1073
Eric Fiselierbee782b2017-04-03 19:21:00 +00001074bool CoroutineStmtBuilder::makeReturnOnAllocFailure() {
1075 assert(!IsPromiseDependentType &&
1076 "cannot make statement while the promise type is dependent");
Gor Nishanov3aa9eb32017-03-27 23:36:59 +00001077
1078 // [dcl.fct.def.coroutine]/8
1079 // The unqualified-id get_return_object_on_allocation_failure is looked up in
1080 // the scope of class P by class member access lookup (3.4.5). ...
1081 // If an allocation function returns nullptr, ... the coroutine return value
1082 // is obtained by a call to ... get_return_object_on_allocation_failure().
1083
1084 DeclarationName DN =
1085 S.PP.getIdentifierInfo("get_return_object_on_allocation_failure");
1086 LookupResult Found(S, DN, Loc, Sema::LookupMemberName);
Eric Fiselierbee782b2017-04-03 19:21:00 +00001087 if (!S.LookupQualifiedName(Found, PromiseRecordDecl))
1088 return true;
Gor Nishanov3aa9eb32017-03-27 23:36:59 +00001089
1090 CXXScopeSpec SS;
1091 ExprResult DeclNameExpr =
1092 S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
Eric Fiselierbee782b2017-04-03 19:21:00 +00001093 if (DeclNameExpr.isInvalid())
1094 return false;
Gor Nishanov3aa9eb32017-03-27 23:36:59 +00001095
1096 if (!diagReturnOnAllocFailure(S, DeclNameExpr.get(), PromiseRecordDecl, Fn))
1097 return false;
1098
1099 ExprResult ReturnObjectOnAllocationFailure =
Richard Smith255b85f2019-05-08 01:36:36 +00001100 S.BuildCallExpr(nullptr, DeclNameExpr.get(), Loc, {}, Loc);
Eric Fiselierbee782b2017-04-03 19:21:00 +00001101 if (ReturnObjectOnAllocationFailure.isInvalid())
1102 return false;
Gor Nishanov3aa9eb32017-03-27 23:36:59 +00001103
Gor Nishanovc4a19082017-03-28 02:51:45 +00001104 StmtResult ReturnStmt =
1105 S.BuildReturnStmt(Loc, ReturnObjectOnAllocationFailure.get());
Gor Nishanov6a470682017-05-22 20:22:23 +00001106 if (ReturnStmt.isInvalid()) {
Eric Fiselierfc50f622017-05-25 14:59:39 +00001107 S.Diag(Found.getFoundDecl()->getLocation(), diag::note_member_declared_here)
1108 << DN;
Gor Nishanov6a470682017-05-22 20:22:23 +00001109 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1110 << Fn.getFirstCoroutineStmtKeyword();
Eric Fiselierbee782b2017-04-03 19:21:00 +00001111 return false;
Gor Nishanov6a470682017-05-22 20:22:23 +00001112 }
Gor Nishanov3aa9eb32017-03-27 23:36:59 +00001113
1114 this->ReturnStmtOnAllocFailure = ReturnStmt.get();
1115 return true;
1116}
1117
Eric Fiselierbee782b2017-04-03 19:21:00 +00001118bool CoroutineStmtBuilder::makeNewAndDeleteExpr() {
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001119 // Form and check allocation and deallocation calls.
Eric Fiselierbee782b2017-04-03 19:21:00 +00001120 assert(!IsPromiseDependentType &&
1121 "cannot make statement while the promise type is dependent");
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001122 QualType PromiseType = Fn.CoroutinePromise->getType();
Gor Nishanov8df64e92016-10-27 16:28:31 +00001123
1124 if (S.RequireCompleteType(Loc, PromiseType, diag::err_incomplete_type))
1125 return false;
1126
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001127 const bool RequiresNoThrowAlloc = ReturnStmtOnAllocFailure != nullptr;
1128
Brian Gesiak98606222018-02-15 20:37:22 +00001129 // [dcl.fct.def.coroutine]/7
1130 // Lookup allocation functions using a parameter list composed of the
1131 // requested size of the coroutine state being allocated, followed by
1132 // the coroutine function's arguments. If a matching allocation function
1133 // exists, use it. Otherwise, use an allocation function that just takes
1134 // the requested size.
Gor Nishanov8df64e92016-10-27 16:28:31 +00001135
1136 FunctionDecl *OperatorNew = nullptr;
1137 FunctionDecl *OperatorDelete = nullptr;
1138 FunctionDecl *UnusedResult = nullptr;
1139 bool PassAlignment = false;
Eric Fiselierf747f532017-04-18 05:08:08 +00001140 SmallVector<Expr *, 1> PlacementArgs;
Gor Nishanov8df64e92016-10-27 16:28:31 +00001141
Brian Gesiak98606222018-02-15 20:37:22 +00001142 // [dcl.fct.def.coroutine]/7
1143 // "The allocation function’s name is looked up in the scope of P.
1144 // [...] If the lookup finds an allocation function in the scope of P,
1145 // overload resolution is performed on a function call created by assembling
1146 // an argument list. The first argument is the amount of space requested,
1147 // and has type std::size_t. The lvalues p1 ... pn are the succeeding
1148 // arguments."
1149 //
1150 // ...where "p1 ... pn" are defined earlier as:
1151 //
1152 // [dcl.fct.def.coroutine]/3
1153 // "For a coroutine f that is a non-static member function, let P1 denote the
1154 // type of the implicit object parameter (13.3.1) and P2 ... Pn be the types
1155 // of the function parameters; otherwise let P1 ... Pn be the types of the
1156 // function parameters. Let p1 ... pn be lvalues denoting those objects."
1157 if (auto *MD = dyn_cast<CXXMethodDecl>(&FD)) {
1158 if (MD->isInstance() && !isLambdaCallOperator(MD)) {
1159 ExprResult ThisExpr = S.ActOnCXXThis(Loc);
1160 if (ThisExpr.isInvalid())
1161 return false;
1162 ThisExpr = S.CreateBuiltinUnaryOp(Loc, UO_Deref, ThisExpr.get());
1163 if (ThisExpr.isInvalid())
1164 return false;
1165 PlacementArgs.push_back(ThisExpr.get());
1166 }
1167 }
1168 for (auto *PD : FD.parameters()) {
1169 if (PD->getType()->isDependentType())
1170 continue;
1171
1172 // Build a reference to the parameter.
1173 auto PDLoc = PD->getLocation();
1174 ExprResult PDRefExpr =
1175 S.BuildDeclRefExpr(PD, PD->getOriginalType().getNonReferenceType(),
1176 ExprValueKind::VK_LValue, PDLoc);
1177 if (PDRefExpr.isInvalid())
1178 return false;
1179
1180 PlacementArgs.push_back(PDRefExpr.get());
1181 }
Brian Gesiakcb024022018-04-01 22:59:22 +00001182 S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Class,
1183 /*DeleteScope*/ Sema::AFS_Both, PromiseType,
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001184 /*isArray*/ false, PassAlignment, PlacementArgs,
Brian Gesiak98606222018-02-15 20:37:22 +00001185 OperatorNew, UnusedResult, /*Diagnose*/ false);
1186
1187 // [dcl.fct.def.coroutine]/7
1188 // "If no matching function is found, overload resolution is performed again
1189 // on a function call created by passing just the amount of space required as
1190 // an argument of type std::size_t."
1191 if (!OperatorNew && !PlacementArgs.empty()) {
1192 PlacementArgs.clear();
Brian Gesiakcb024022018-04-01 22:59:22 +00001193 S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Class,
1194 /*DeleteScope*/ Sema::AFS_Both, PromiseType,
1195 /*isArray*/ false, PassAlignment, PlacementArgs,
1196 OperatorNew, UnusedResult, /*Diagnose*/ false);
1197 }
1198
1199 // [dcl.fct.def.coroutine]/7
1200 // "The allocation function’s name is looked up in the scope of P. If this
1201 // lookup fails, the allocation function’s name is looked up in the global
1202 // scope."
1203 if (!OperatorNew) {
1204 S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Global,
1205 /*DeleteScope*/ Sema::AFS_Both, PromiseType,
1206 /*isArray*/ false, PassAlignment, PlacementArgs,
1207 OperatorNew, UnusedResult);
Brian Gesiak98606222018-02-15 20:37:22 +00001208 }
Gor Nishanov8df64e92016-10-27 16:28:31 +00001209
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001210 bool IsGlobalOverload =
1211 OperatorNew && !isa<CXXRecordDecl>(OperatorNew->getDeclContext());
1212 // If we didn't find a class-local new declaration and non-throwing new
1213 // was is required then we need to lookup the non-throwing global operator
1214 // instead.
1215 if (RequiresNoThrowAlloc && (!OperatorNew || IsGlobalOverload)) {
1216 auto *StdNoThrow = buildStdNoThrowDeclRef(S, Loc);
1217 if (!StdNoThrow)
1218 return false;
Eric Fiselierf747f532017-04-18 05:08:08 +00001219 PlacementArgs = {StdNoThrow};
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001220 OperatorNew = nullptr;
Brian Gesiakcb024022018-04-01 22:59:22 +00001221 S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Both,
1222 /*DeleteScope*/ Sema::AFS_Both, PromiseType,
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001223 /*isArray*/ false, PassAlignment, PlacementArgs,
1224 OperatorNew, UnusedResult);
1225 }
Gor Nishanov8df64e92016-10-27 16:28:31 +00001226
Brian Gesiak98606222018-02-15 20:37:22 +00001227 if (!OperatorNew)
1228 return false;
Eric Fiselierc5128752017-04-18 05:30:39 +00001229
1230 if (RequiresNoThrowAlloc) {
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001231 const auto *FT = OperatorNew->getType()->getAs<FunctionProtoType>();
Richard Smitheaf11ad2018-05-03 03:58:32 +00001232 if (!FT->isNothrow(/*ResultIfDependent*/ false)) {
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001233 S.Diag(OperatorNew->getLocation(),
1234 diag::err_coroutine_promise_new_requires_nothrow)
1235 << OperatorNew;
1236 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
1237 << OperatorNew;
1238 return false;
1239 }
1240 }
1241
1242 if ((OperatorDelete = findDeleteForPromise(S, Loc, PromiseType)) == nullptr)
Gor Nishanov8df64e92016-10-27 16:28:31 +00001243 return false;
1244
1245 Expr *FramePtr =
1246 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_frame, {});
1247
1248 Expr *FrameSize =
1249 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_size, {});
1250
1251 // Make new call.
1252
1253 ExprResult NewRef =
1254 S.BuildDeclRefExpr(OperatorNew, OperatorNew->getType(), VK_LValue, Loc);
1255 if (NewRef.isInvalid())
1256 return false;
1257
Eric Fiselierf747f532017-04-18 05:08:08 +00001258 SmallVector<Expr *, 2> NewArgs(1, FrameSize);
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001259 for (auto Arg : PlacementArgs)
1260 NewArgs.push_back(Arg);
1261
Gor Nishanov8df64e92016-10-27 16:28:31 +00001262 ExprResult NewExpr =
Richard Smith255b85f2019-05-08 01:36:36 +00001263 S.BuildCallExpr(S.getCurScope(), NewRef.get(), Loc, NewArgs, Loc);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00001264 NewExpr = S.ActOnFinishFullExpr(NewExpr.get(), /*DiscardedValue*/ false);
Gor Nishanov8df64e92016-10-27 16:28:31 +00001265 if (NewExpr.isInvalid())
1266 return false;
1267
Gor Nishanov8df64e92016-10-27 16:28:31 +00001268 // Make delete call.
1269
1270 QualType OpDeleteQualType = OperatorDelete->getType();
1271
1272 ExprResult DeleteRef =
1273 S.BuildDeclRefExpr(OperatorDelete, OpDeleteQualType, VK_LValue, Loc);
1274 if (DeleteRef.isInvalid())
1275 return false;
1276
1277 Expr *CoroFree =
1278 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_free, {FramePtr});
1279
1280 SmallVector<Expr *, 2> DeleteArgs{CoroFree};
1281
1282 // Check if we need to pass the size.
1283 const auto *OpDeleteType =
1284 OpDeleteQualType.getTypePtr()->getAs<FunctionProtoType>();
1285 if (OpDeleteType->getNumParams() > 1)
1286 DeleteArgs.push_back(FrameSize);
1287
1288 ExprResult DeleteExpr =
Richard Smith255b85f2019-05-08 01:36:36 +00001289 S.BuildCallExpr(S.getCurScope(), DeleteRef.get(), Loc, DeleteArgs, Loc);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00001290 DeleteExpr =
1291 S.ActOnFinishFullExpr(DeleteExpr.get(), /*DiscardedValue*/ false);
Gor Nishanov8df64e92016-10-27 16:28:31 +00001292 if (DeleteExpr.isInvalid())
1293 return false;
1294
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001295 this->Allocate = NewExpr.get();
1296 this->Deallocate = DeleteExpr.get();
Gor Nishanov8df64e92016-10-27 16:28:31 +00001297
1298 return true;
1299}
1300
Eric Fiselierbee782b2017-04-03 19:21:00 +00001301bool CoroutineStmtBuilder::makeOnFallthrough() {
1302 assert(!IsPromiseDependentType &&
1303 "cannot make statement while the promise type is dependent");
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001304
1305 // [dcl.fct.def.coroutine]/4
1306 // The unqualified-ids 'return_void' and 'return_value' are looked up in
1307 // the scope of class P. If both are found, the program is ill-formed.
Eric Fiselierfc50f622017-05-25 14:59:39 +00001308 bool HasRVoid, HasRValue;
1309 LookupResult LRVoid =
1310 lookupMember(S, "return_void", PromiseRecordDecl, Loc, HasRVoid);
1311 LookupResult LRValue =
1312 lookupMember(S, "return_value", PromiseRecordDecl, Loc, HasRValue);
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001313
Eric Fiselier709d1b32016-10-27 07:30:31 +00001314 StmtResult Fallthrough;
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001315 if (HasRVoid && HasRValue) {
1316 // FIXME Improve this diagnostic
Eric Fiselierfc50f622017-05-25 14:59:39 +00001317 S.Diag(FD.getLocation(),
1318 diag::err_coroutine_promise_incompatible_return_functions)
1319 << PromiseRecordDecl;
1320 S.Diag(LRVoid.getRepresentativeDecl()->getLocation(),
1321 diag::note_member_first_declared_here)
1322 << LRVoid.getLookupName();
1323 S.Diag(LRValue.getRepresentativeDecl()->getLocation(),
1324 diag::note_member_first_declared_here)
1325 << LRValue.getLookupName();
1326 return false;
1327 } else if (!HasRVoid && !HasRValue) {
1328 // FIXME: The PDTS currently specifies this case as UB, not ill-formed.
1329 // However we still diagnose this as an error since until the PDTS is fixed.
1330 S.Diag(FD.getLocation(),
1331 diag::err_coroutine_promise_requires_return_function)
1332 << PromiseRecordDecl;
1333 S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here)
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001334 << PromiseRecordDecl;
1335 return false;
1336 } else if (HasRVoid) {
1337 // If the unqualified-id return_void is found, flowing off the end of a
1338 // coroutine is equivalent to a co_return with no operand. Otherwise,
1339 // flowing off the end of a coroutine results in undefined behavior.
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001340 Fallthrough = S.BuildCoreturnStmt(FD.getLocation(), nullptr,
1341 /*IsImplicit*/false);
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001342 Fallthrough = S.ActOnFinishFullStmt(Fallthrough.get());
1343 if (Fallthrough.isInvalid())
1344 return false;
Eric Fiselier709d1b32016-10-27 07:30:31 +00001345 }
Richard Smith2af65c42015-11-24 02:34:39 +00001346
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001347 this->OnFallthrough = Fallthrough.get();
1348 return true;
1349}
1350
Eric Fiselierbee782b2017-04-03 19:21:00 +00001351bool CoroutineStmtBuilder::makeOnException() {
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001352 // Try to form 'p.unhandled_exception();'
Eric Fiselierbee782b2017-04-03 19:21:00 +00001353 assert(!IsPromiseDependentType &&
1354 "cannot make statement while the promise type is dependent");
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001355
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001356 const bool RequireUnhandledException = S.getLangOpts().CXXExceptions;
1357
1358 if (!lookupMember(S, "unhandled_exception", PromiseRecordDecl, Loc)) {
1359 auto DiagID =
1360 RequireUnhandledException
1361 ? diag::err_coroutine_promise_unhandled_exception_required
1362 : diag::
1363 warn_coroutine_promise_unhandled_exception_required_with_exceptions;
1364 S.Diag(Loc, DiagID) << PromiseRecordDecl;
Gor Nishanov29ff6382017-05-24 14:34:19 +00001365 S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here)
1366 << PromiseRecordDecl;
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001367 return !RequireUnhandledException;
1368 }
1369
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001370 // If exceptions are disabled, don't try to build OnException.
1371 if (!S.getLangOpts().CXXExceptions)
1372 return true;
1373
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001374 ExprResult UnhandledException = buildPromiseCall(S, Fn.CoroutinePromise, Loc,
1375 "unhandled_exception", None);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00001376 UnhandledException = S.ActOnFinishFullExpr(UnhandledException.get(), Loc,
1377 /*DiscardedValue*/ false);
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001378 if (UnhandledException.isInvalid())
1379 return false;
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001380
Gor Nishanov5b050e42017-05-22 22:33:17 +00001381 // Since the body of the coroutine will be wrapped in try-catch, it will
1382 // be incompatible with SEH __try if present in a function.
1383 if (!S.getLangOpts().Borland && Fn.FirstSEHTryLoc.isValid()) {
1384 S.Diag(Fn.FirstSEHTryLoc, diag::err_seh_in_a_coroutine_with_cxx_exceptions);
1385 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1386 << Fn.getFirstCoroutineStmtKeyword();
1387 return false;
1388 }
1389
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001390 this->OnException = UnhandledException.get();
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001391 return true;
1392}
1393
Eric Fiselierbee782b2017-04-03 19:21:00 +00001394bool CoroutineStmtBuilder::makeReturnObject() {
Richard Smith2af65c42015-11-24 02:34:39 +00001395 // Build implicit 'p.get_return_object()' expression and form initialization
1396 // of return type from it.
1397 ExprResult ReturnObject =
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001398 buildPromiseCall(S, Fn.CoroutinePromise, Loc, "get_return_object", None);
Richard Smith2af65c42015-11-24 02:34:39 +00001399 if (ReturnObject.isInvalid())
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001400 return false;
Richard Smith2af65c42015-11-24 02:34:39 +00001401
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001402 this->ReturnValue = ReturnObject.get();
1403 return true;
1404}
1405
Gor Nishanov6a470682017-05-22 20:22:23 +00001406static void noteMemberDeclaredHere(Sema &S, Expr *E, FunctionScopeInfo &Fn) {
1407 if (auto *MbrRef = dyn_cast<CXXMemberCallExpr>(E)) {
1408 auto *MethodDecl = MbrRef->getMethodDecl();
Eric Fiselierfc50f622017-05-25 14:59:39 +00001409 S.Diag(MethodDecl->getLocation(), diag::note_member_declared_here)
1410 << MethodDecl;
Gor Nishanov6a470682017-05-22 20:22:23 +00001411 }
1412 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1413 << Fn.getFirstCoroutineStmtKeyword();
1414}
1415
1416bool CoroutineStmtBuilder::makeGroDeclAndReturnStmt() {
1417 assert(!IsPromiseDependentType &&
1418 "cannot make statement while the promise type is dependent");
1419 assert(this->ReturnValue && "ReturnValue must be already formed");
1420
1421 QualType const GroType = this->ReturnValue->getType();
1422 assert(!GroType->isDependentType() &&
1423 "get_return_object type must no longer be dependent");
1424
1425 QualType const FnRetType = FD.getReturnType();
1426 assert(!FnRetType->isDependentType() &&
1427 "get_return_object type must no longer be dependent");
1428
1429 if (FnRetType->isVoidType()) {
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00001430 ExprResult Res =
1431 S.ActOnFinishFullExpr(this->ReturnValue, Loc, /*DiscardedValue*/ false);
Gor Nishanov6a470682017-05-22 20:22:23 +00001432 if (Res.isInvalid())
1433 return false;
1434
1435 this->ResultDecl = Res.get();
1436 return true;
1437 }
1438
1439 if (GroType->isVoidType()) {
1440 // Trigger a nice error message.
1441 InitializedEntity Entity =
1442 InitializedEntity::InitializeResult(Loc, FnRetType, false);
1443 S.PerformMoveOrCopyInitialization(Entity, nullptr, FnRetType, ReturnValue);
1444 noteMemberDeclaredHere(S, ReturnValue, Fn);
1445 return false;
1446 }
1447
1448 auto *GroDecl = VarDecl::Create(
1449 S.Context, &FD, FD.getLocation(), FD.getLocation(),
1450 &S.PP.getIdentifierTable().get("__coro_gro"), GroType,
1451 S.Context.getTrivialTypeSourceInfo(GroType, Loc), SC_None);
1452
1453 S.CheckVariableDeclarationType(GroDecl);
1454 if (GroDecl->isInvalidDecl())
1455 return false;
1456
1457 InitializedEntity Entity = InitializedEntity::InitializeVariable(GroDecl);
1458 ExprResult Res = S.PerformMoveOrCopyInitialization(Entity, nullptr, GroType,
1459 this->ReturnValue);
1460 if (Res.isInvalid())
1461 return false;
1462
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00001463 Res = S.ActOnFinishFullExpr(Res.get(), /*DiscardedValue*/ false);
Gor Nishanov6a470682017-05-22 20:22:23 +00001464 if (Res.isInvalid())
1465 return false;
1466
Gor Nishanov6a470682017-05-22 20:22:23 +00001467 S.AddInitializerToDecl(GroDecl, Res.get(),
1468 /*DirectInit=*/false);
1469
1470 S.FinalizeDeclaration(GroDecl);
1471
1472 // Form a declaration statement for the return declaration, so that AST
1473 // visitors can more easily find it.
1474 StmtResult GroDeclStmt =
1475 S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(GroDecl), Loc, Loc);
1476 if (GroDeclStmt.isInvalid())
1477 return false;
1478
1479 this->ResultDecl = GroDeclStmt.get();
1480
1481 ExprResult declRef = S.BuildDeclRefExpr(GroDecl, GroType, VK_LValue, Loc);
1482 if (declRef.isInvalid())
1483 return false;
1484
1485 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, declRef.get());
1486 if (ReturnStmt.isInvalid()) {
1487 noteMemberDeclaredHere(S, ReturnValue, Fn);
1488 return false;
1489 }
Eric Fiselier8ed97272018-02-01 23:47:54 +00001490 if (cast<clang::ReturnStmt>(ReturnStmt.get())->getNRVOCandidate() == GroDecl)
1491 GroDecl->setNRVOVariable(true);
Gor Nishanov6a470682017-05-22 20:22:23 +00001492
1493 this->ReturnStmt = ReturnStmt.get();
1494 return true;
1495}
1496
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001497// Create a static_cast\<T&&>(expr).
1498static Expr *castForMoving(Sema &S, Expr *E, QualType T = QualType()) {
1499 if (T.isNull())
1500 T = E->getType();
1501 QualType TargetType = S.BuildReferenceType(
1502 T, /*SpelledAsLValue*/ false, SourceLocation(), DeclarationName());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001503 SourceLocation ExprLoc = E->getBeginLoc();
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001504 TypeSourceInfo *TargetLoc =
1505 S.Context.getTrivialTypeSourceInfo(TargetType, ExprLoc);
1506
1507 return S
1508 .BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
1509 SourceRange(ExprLoc, ExprLoc), E->getSourceRange())
1510 .get();
1511}
1512
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001513/// Build a variable declaration for move parameter.
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001514static VarDecl *buildVarDecl(Sema &S, SourceLocation Loc, QualType Type,
Eric Fiselierde7943b2017-06-03 00:22:18 +00001515 IdentifierInfo *II) {
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001516 TypeSourceInfo *TInfo = S.Context.getTrivialTypeSourceInfo(Type, Loc);
Brian Gesiak61f4ac92018-01-24 22:15:42 +00001517 VarDecl *Decl = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, II, Type,
1518 TInfo, SC_None);
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001519 Decl->setImplicit();
1520 return Decl;
1521}
1522
Brian Gesiak61f4ac92018-01-24 22:15:42 +00001523// Build statements that move coroutine function parameters to the coroutine
1524// frame, and store them on the function scope info.
1525bool Sema::buildCoroutineParameterMoves(SourceLocation Loc) {
1526 assert(isa<FunctionDecl>(CurContext) && "not in a function scope");
1527 auto *FD = cast<FunctionDecl>(CurContext);
1528
1529 auto *ScopeInfo = getCurFunction();
1530 assert(ScopeInfo->CoroutineParameterMoves.empty() &&
1531 "Should not build parameter moves twice");
1532
1533 for (auto *PD : FD->parameters()) {
1534 if (PD->getType()->isDependentType())
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001535 continue;
1536
Brian Gesiak98606222018-02-15 20:37:22 +00001537 ExprResult PDRefExpr =
1538 BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
1539 ExprValueKind::VK_LValue, Loc); // FIXME: scope?
1540 if (PDRefExpr.isInvalid())
1541 return false;
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001542
Brian Gesiak98606222018-02-15 20:37:22 +00001543 Expr *CExpr = nullptr;
1544 if (PD->getType()->getAsCXXRecordDecl() ||
1545 PD->getType()->isRValueReferenceType())
1546 CExpr = castForMoving(*this, PDRefExpr.get());
1547 else
1548 CExpr = PDRefExpr.get();
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001549
Brian Gesiak98606222018-02-15 20:37:22 +00001550 auto D = buildVarDecl(*this, Loc, PD->getType(), PD->getIdentifier());
1551 AddInitializerToDecl(D, CExpr, /*DirectInit=*/true);
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001552
Brian Gesiak98606222018-02-15 20:37:22 +00001553 // Convert decl to a statement.
1554 StmtResult Stmt = ActOnDeclStmt(ConvertDeclToDeclGroup(D), Loc, Loc);
1555 if (Stmt.isInvalid())
1556 return false;
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001557
Brian Gesiak98606222018-02-15 20:37:22 +00001558 ScopeInfo->CoroutineParameterMoves.insert(std::make_pair(PD, Stmt.get()));
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001559 }
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001560 return true;
Richard Smithcfd53b42015-10-22 06:13:50 +00001561}
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001562
1563StmtResult Sema::BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
1564 CoroutineBodyStmt *Res = CoroutineBodyStmt::Create(Context, Args);
1565 if (!Res)
1566 return StmtError();
1567 return Res;
1568}
Brian Gesiak3e65d9a2018-07-14 18:21:44 +00001569
1570ClassTemplateDecl *Sema::lookupCoroutineTraits(SourceLocation KwLoc,
1571 SourceLocation FuncLoc) {
1572 if (!StdCoroutineTraitsCache) {
1573 if (auto StdExp = lookupStdExperimentalNamespace()) {
1574 LookupResult Result(*this,
1575 &PP.getIdentifierTable().get("coroutine_traits"),
1576 FuncLoc, LookupOrdinaryName);
1577 if (!LookupQualifiedName(Result, StdExp)) {
1578 Diag(KwLoc, diag::err_implied_coroutine_type_not_found)
1579 << "std::experimental::coroutine_traits";
1580 return nullptr;
1581 }
1582 if (!(StdCoroutineTraitsCache =
1583 Result.getAsSingle<ClassTemplateDecl>())) {
1584 Result.suppressDiagnostics();
1585 NamedDecl *Found = *Result.begin();
1586 Diag(Found->getLocation(), diag::err_malformed_std_coroutine_traits);
1587 return nullptr;
1588 }
1589 }
1590 }
1591 return StdCoroutineTraitsCache;
1592}