blob: dc259fe03f542284fb61523088156bf32c2d3714 [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"
21#include "clang/Lex/Preprocessor.h"
Richard Smith2af65c42015-11-24 02:34:39 +000022#include "clang/Sema/Initialization.h"
Richard Smith9f690bd2015-10-27 06:02:45 +000023#include "clang/Sema/Overload.h"
Reid Kleckner04f9bca2018-03-07 22:48:35 +000024#include "clang/Sema/ScopeInfo.h"
Eric Fiselierbee782b2017-04-03 19:21:00 +000025#include "clang/Sema/SemaInternal.h"
26
Richard Smithcfd53b42015-10-22 06:13:50 +000027using namespace clang;
28using namespace sema;
29
Eric Fiselierfc50f622017-05-25 14:59:39 +000030static LookupResult lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD,
31 SourceLocation Loc, bool &Res) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +000032 DeclarationName DN = S.PP.getIdentifierInfo(Name);
33 LookupResult LR(S, DN, Loc, Sema::LookupMemberName);
34 // Suppress diagnostics when a private member is selected. The same warnings
35 // will be produced again when building the call.
36 LR.suppressDiagnostics();
Eric Fiselierfc50f622017-05-25 14:59:39 +000037 Res = S.LookupQualifiedName(LR, RD);
38 return LR;
39}
40
41static bool lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD,
42 SourceLocation Loc) {
43 bool Res;
44 lookupMember(S, Name, RD, Loc, Res);
45 return Res;
Eric Fiselier20f25cb2017-03-06 23:38:15 +000046}
47
Richard Smith9f690bd2015-10-27 06:02:45 +000048/// Look up the std::coroutine_traits<...>::promise_type for the given
49/// function type.
Eric Fiselier166c6e62017-07-10 01:27:22 +000050static QualType lookupPromiseType(Sema &S, const FunctionDecl *FD,
51 SourceLocation KwLoc) {
52 const FunctionProtoType *FnType = FD->getType()->castAs<FunctionProtoType>();
53 const SourceLocation FuncLoc = FD->getLocation();
Richard Smith9f690bd2015-10-27 06:02:45 +000054 // FIXME: Cache std::coroutine_traits once we've found it.
Gor Nishanov3e048bb2016-10-04 00:31:16 +000055 NamespaceDecl *StdExp = S.lookupStdExperimentalNamespace();
56 if (!StdExp) {
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +000057 S.Diag(KwLoc, diag::err_implied_coroutine_type_not_found)
58 << "std::experimental::coroutine_traits";
Richard Smith9f690bd2015-10-27 06:02:45 +000059 return QualType();
60 }
61
Brian Gesiak3e65d9a2018-07-14 18:21:44 +000062 ClassTemplateDecl *CoroTraits = S.lookupCoroutineTraits(KwLoc, FuncLoc);
Richard Smith9f690bd2015-10-27 06:02:45 +000063 if (!CoroTraits) {
Richard Smith9f690bd2015-10-27 06:02:45 +000064 return QualType();
65 }
66
Eric Fiselier166c6e62017-07-10 01:27:22 +000067 // Form template argument list for coroutine_traits<R, P1, P2, ...> according
68 // to [dcl.fct.def.coroutine]3
Eric Fiselier89bf0e72017-03-06 22:52:28 +000069 TemplateArgumentListInfo Args(KwLoc, KwLoc);
Eric Fiselier166c6e62017-07-10 01:27:22 +000070 auto AddArg = [&](QualType T) {
Richard Smith9f690bd2015-10-27 06:02:45 +000071 Args.addArgument(TemplateArgumentLoc(
Eric Fiselier89bf0e72017-03-06 22:52:28 +000072 TemplateArgument(T), S.Context.getTrivialTypeSourceInfo(T, KwLoc)));
Eric Fiselier166c6e62017-07-10 01:27:22 +000073 };
74 AddArg(FnType->getReturnType());
75 // If the function is a non-static member function, add the type
76 // of the implicit object parameter before the formal parameters.
77 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
78 if (MD->isInstance()) {
79 // [over.match.funcs]4
80 // For non-static member functions, the type of the implicit object
81 // parameter is
Eric Fiselierbf166ce2017-07-10 02:52:34 +000082 // -- "lvalue reference to cv X" for functions declared without a
83 // ref-qualifier or with the & ref-qualifier
84 // -- "rvalue reference to cv X" for functions declared with the &&
85 // ref-qualifier
Brian Gesiak5488ab42019-01-11 01:54:53 +000086 QualType T = MD->getThisType()->getAs<PointerType>()->getPointeeType();
Eric Fiselier166c6e62017-07-10 01:27:22 +000087 T = FnType->getRefQualifier() == RQ_RValue
88 ? S.Context.getRValueReferenceType(T)
89 : S.Context.getLValueReferenceType(T, /*SpelledAsLValue*/ true);
90 AddArg(T);
91 }
92 }
93 for (QualType T : FnType->getParamTypes())
94 AddArg(T);
Richard Smith9f690bd2015-10-27 06:02:45 +000095
96 // Build the template-id.
97 QualType CoroTrait =
Eric Fiselier89bf0e72017-03-06 22:52:28 +000098 S.CheckTemplateIdType(TemplateName(CoroTraits), KwLoc, Args);
Richard Smith9f690bd2015-10-27 06:02:45 +000099 if (CoroTrait.isNull())
100 return QualType();
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000101 if (S.RequireCompleteType(KwLoc, CoroTrait,
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000102 diag::err_coroutine_type_missing_specialization))
Richard Smith9f690bd2015-10-27 06:02:45 +0000103 return QualType();
104
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000105 auto *RD = CoroTrait->getAsCXXRecordDecl();
Richard Smith9f690bd2015-10-27 06:02:45 +0000106 assert(RD && "specialization of class template is not a class?");
107
108 // Look up the ::promise_type member.
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000109 LookupResult R(S, &S.PP.getIdentifierTable().get("promise_type"), KwLoc,
Richard Smith9f690bd2015-10-27 06:02:45 +0000110 Sema::LookupOrdinaryName);
111 S.LookupQualifiedName(R, RD);
112 auto *Promise = R.getAsSingle<TypeDecl>();
113 if (!Promise) {
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000114 S.Diag(FuncLoc,
115 diag::err_implied_std_coroutine_traits_promise_type_not_found)
Gor Nishanov8df64e92016-10-27 16:28:31 +0000116 << RD;
Richard Smith9f690bd2015-10-27 06:02:45 +0000117 return QualType();
118 }
Richard Smith9f690bd2015-10-27 06:02:45 +0000119 // The promise type is required to be a class type.
120 QualType PromiseType = S.Context.getTypeDeclType(Promise);
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000121
122 auto buildElaboratedType = [&]() {
Gor Nishanov3e048bb2016-10-04 00:31:16 +0000123 auto *NNS = NestedNameSpecifier::Create(S.Context, nullptr, StdExp);
Richard Smith9b2f53e2015-11-19 02:36:35 +0000124 NNS = NestedNameSpecifier::Create(S.Context, NNS, false,
125 CoroTrait.getTypePtr());
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000126 return S.Context.getElaboratedType(ETK_None, NNS, PromiseType);
127 };
Richard Smith9b2f53e2015-11-19 02:36:35 +0000128
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000129 if (!PromiseType->getAsCXXRecordDecl()) {
130 S.Diag(FuncLoc,
131 diag::err_implied_std_coroutine_traits_promise_type_not_class)
132 << buildElaboratedType();
Richard Smith9f690bd2015-10-27 06:02:45 +0000133 return QualType();
134 }
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000135 if (S.RequireCompleteType(FuncLoc, buildElaboratedType(),
136 diag::err_coroutine_promise_type_incomplete))
137 return QualType();
Richard Smith9f690bd2015-10-27 06:02:45 +0000138
139 return PromiseType;
140}
141
Gor Nishanov29ff6382017-05-24 14:34:19 +0000142/// Look up the std::experimental::coroutine_handle<PromiseType>.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000143static QualType lookupCoroutineHandleType(Sema &S, QualType PromiseType,
144 SourceLocation Loc) {
145 if (PromiseType.isNull())
146 return QualType();
147
148 NamespaceDecl *StdExp = S.lookupStdExperimentalNamespace();
149 assert(StdExp && "Should already be diagnosed");
150
151 LookupResult Result(S, &S.PP.getIdentifierTable().get("coroutine_handle"),
152 Loc, Sema::LookupOrdinaryName);
153 if (!S.LookupQualifiedName(Result, StdExp)) {
154 S.Diag(Loc, diag::err_implied_coroutine_type_not_found)
155 << "std::experimental::coroutine_handle";
156 return QualType();
157 }
158
159 ClassTemplateDecl *CoroHandle = Result.getAsSingle<ClassTemplateDecl>();
160 if (!CoroHandle) {
161 Result.suppressDiagnostics();
162 // We found something weird. Complain about the first thing we found.
163 NamedDecl *Found = *Result.begin();
164 S.Diag(Found->getLocation(), diag::err_malformed_std_coroutine_handle);
165 return QualType();
166 }
167
168 // Form template argument list for coroutine_handle<Promise>.
169 TemplateArgumentListInfo Args(Loc, Loc);
170 Args.addArgument(TemplateArgumentLoc(
171 TemplateArgument(PromiseType),
172 S.Context.getTrivialTypeSourceInfo(PromiseType, Loc)));
173
174 // Build the template-id.
175 QualType CoroHandleType =
176 S.CheckTemplateIdType(TemplateName(CoroHandle), Loc, Args);
177 if (CoroHandleType.isNull())
178 return QualType();
179 if (S.RequireCompleteType(Loc, CoroHandleType,
180 diag::err_coroutine_type_missing_specialization))
181 return QualType();
182
183 return CoroHandleType;
184}
185
Eric Fiselierc8efda72016-10-27 18:43:28 +0000186static bool isValidCoroutineContext(Sema &S, SourceLocation Loc,
187 StringRef Keyword) {
Brian Gesiakb15c35a2019-03-25 00:53:10 +0000188 // [expr.await]p2 dictates that 'co_await' and 'co_yield' must be used within
189 // a function body.
Brian Gesiakc1b173a2018-06-23 18:01:02 +0000190 // FIXME: This also covers [expr.await]p2: "An await-expression shall not
191 // appear in a default argument." But the diagnostic QoI here could be
192 // improved to inform the user that default arguments specifically are not
193 // allowed.
Richard Smithcfd53b42015-10-22 06:13:50 +0000194 auto *FD = dyn_cast<FunctionDecl>(S.CurContext);
195 if (!FD) {
196 S.Diag(Loc, isa<ObjCMethodDecl>(S.CurContext)
197 ? diag::err_coroutine_objc_method
198 : diag::err_coroutine_outside_function) << Keyword;
Eric Fiselierc8efda72016-10-27 18:43:28 +0000199 return false;
Richard Smithcfd53b42015-10-22 06:13:50 +0000200 }
201
Eric Fiselierc8efda72016-10-27 18:43:28 +0000202 // An enumeration for mapping the diagnostic type to the correct diagnostic
203 // selection index.
204 enum InvalidFuncDiag {
205 DiagCtor = 0,
206 DiagDtor,
207 DiagCopyAssign,
208 DiagMoveAssign,
209 DiagMain,
210 DiagConstexpr,
211 DiagAutoRet,
212 DiagVarargs,
213 };
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
221 // Diagnose when a constructor, destructor, copy/move assignment operator,
222 // or the function 'main' are declared as a coroutine.
223 auto *MD = dyn_cast<CXXMethodDecl>(FD);
Brian Gesiakc1b173a2018-06-23 18:01:02 +0000224 // [class.ctor]p6: "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 // N4499 [special]p6: "A special member function shall not be a coroutine."
231 // Per C++ [special]p1, special member functions are the "default constructor,
232 // copy constructor and copy assignment operator, move constructor and move
233 // assignment operator, and destructor."
Eric Fiselierc8efda72016-10-27 18:43:28 +0000234 else if (MD && MD->isCopyAssignmentOperator())
235 return DiagInvalid(DiagCopyAssign);
236 else if (MD && MD->isMoveAssignmentOperator())
237 return DiagInvalid(DiagMoveAssign);
Brian Gesiakc1b173a2018-06-23 18:01:02 +0000238 // [basic.start.main]p3: "The function main shall not be a coroutine."
Eric Fiselierc8efda72016-10-27 18:43:28 +0000239 else if (FD->isMain())
240 return DiagInvalid(DiagMain);
241
242 // Emit a diagnostics for each of the following conditions which is not met.
Brian Gesiakc1b173a2018-06-23 18:01:02 +0000243 // [expr.const]p2: "An expression e is a core constant expression unless the
244 // evaluation of e [...] would evaluate one of the following expressions:
245 // [...] an await-expression [...] a yield-expression."
Eric Fiselierc8efda72016-10-27 18:43:28 +0000246 if (FD->isConstexpr())
247 DiagInvalid(DiagConstexpr);
Brian Gesiakc1b173a2018-06-23 18:01:02 +0000248 // [dcl.spec.auto]p15: "A function declared with a return type that uses a
249 // placeholder type shall not be a coroutine."
Eric Fiselierc8efda72016-10-27 18:43:28 +0000250 if (FD->getReturnType()->isUndeducedType())
251 DiagInvalid(DiagAutoRet);
Brian Gesiakc1b173a2018-06-23 18:01:02 +0000252 // [dcl.fct.def.coroutine]p1: "The parameter-declaration-clause of the
253 // coroutine shall not terminate with an ellipsis that is not part of a
254 // parameter-declaration."
Eric Fiselierc8efda72016-10-27 18:43:28 +0000255 if (FD->isVariadic())
256 DiagInvalid(DiagVarargs);
257
258 return !Diagnosed;
259}
260
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000261static ExprResult buildOperatorCoawaitLookupExpr(Sema &SemaRef, Scope *S,
262 SourceLocation Loc) {
263 DeclarationName OpName =
264 SemaRef.Context.DeclarationNames.getCXXOperatorName(OO_Coawait);
265 LookupResult Operators(SemaRef, OpName, SourceLocation(),
266 Sema::LookupOperatorName);
267 SemaRef.LookupName(Operators, S);
Eric Fiselierc8efda72016-10-27 18:43:28 +0000268
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000269 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
270 const auto &Functions = Operators.asUnresolvedSet();
271 bool IsOverloaded =
272 Functions.size() > 1 ||
273 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
274 Expr *CoawaitOp = UnresolvedLookupExpr::Create(
275 SemaRef.Context, /*NamingClass*/ nullptr, NestedNameSpecifierLoc(),
276 DeclarationNameInfo(OpName, Loc), /*RequiresADL*/ true, IsOverloaded,
277 Functions.begin(), Functions.end());
278 assert(CoawaitOp);
279 return CoawaitOp;
280}
Eric Fiselierc8efda72016-10-27 18:43:28 +0000281
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000282/// Build a call to 'operator co_await' if there is a suitable operator for
283/// the given expression.
284static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, SourceLocation Loc,
285 Expr *E,
286 UnresolvedLookupExpr *Lookup) {
287 UnresolvedSet<16> Functions;
288 Functions.append(Lookup->decls_begin(), Lookup->decls_end());
289 return SemaRef.CreateOverloadedUnaryOp(Loc, UO_Coawait, Functions, E);
290}
Eric Fiselierc8efda72016-10-27 18:43:28 +0000291
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000292static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, Scope *S,
293 SourceLocation Loc, Expr *E) {
294 ExprResult R = buildOperatorCoawaitLookupExpr(SemaRef, S, Loc);
295 if (R.isInvalid())
296 return ExprError();
297 return buildOperatorCoawaitCall(SemaRef, Loc, E,
298 cast<UnresolvedLookupExpr>(R.get()));
Richard Smithcfd53b42015-10-22 06:13:50 +0000299}
300
Gor Nishanov8df64e92016-10-27 16:28:31 +0000301static Expr *buildBuiltinCall(Sema &S, SourceLocation Loc, Builtin::ID Id,
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000302 MultiExprArg CallArgs) {
Gor Nishanov8df64e92016-10-27 16:28:31 +0000303 StringRef Name = S.Context.BuiltinInfo.getName(Id);
304 LookupResult R(S, &S.Context.Idents.get(Name), Loc, Sema::LookupOrdinaryName);
305 S.LookupName(R, S.TUScope, /*AllowBuiltinCreation=*/true);
306
307 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
308 assert(BuiltInDecl && "failed to find builtin declaration");
309
310 ExprResult DeclRef =
311 S.BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
312 assert(DeclRef.isUsable() && "Builtin reference cannot fail");
313
314 ExprResult Call =
Richard Smith255b85f2019-05-08 01:36:36 +0000315 S.BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
Gor Nishanov8df64e92016-10-27 16:28:31 +0000316
317 assert(!Call.isInvalid() && "Call to builtin cannot fail!");
318 return Call.get();
319}
320
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000321static ExprResult buildCoroutineHandle(Sema &S, QualType PromiseType,
322 SourceLocation Loc) {
323 QualType CoroHandleType = lookupCoroutineHandleType(S, PromiseType, Loc);
324 if (CoroHandleType.isNull())
325 return ExprError();
326
327 DeclContext *LookupCtx = S.computeDeclContext(CoroHandleType);
328 LookupResult Found(S, &S.PP.getIdentifierTable().get("from_address"), Loc,
329 Sema::LookupOrdinaryName);
330 if (!S.LookupQualifiedName(Found, LookupCtx)) {
331 S.Diag(Loc, diag::err_coroutine_handle_missing_member)
332 << "from_address";
333 return ExprError();
334 }
335
336 Expr *FramePtr =
337 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_frame, {});
338
339 CXXScopeSpec SS;
340 ExprResult FromAddr =
341 S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
342 if (FromAddr.isInvalid())
343 return ExprError();
344
Richard Smith255b85f2019-05-08 01:36:36 +0000345 return S.BuildCallExpr(nullptr, FromAddr.get(), Loc, FramePtr, Loc);
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000346}
Richard Smithcfd53b42015-10-22 06:13:50 +0000347
Richard Smith9f690bd2015-10-27 06:02:45 +0000348struct ReadySuspendResumeResult {
Eric Fiselierd978e532017-05-28 18:21:12 +0000349 enum AwaitCallType { ACT_Ready, ACT_Suspend, ACT_Resume };
Richard Smith9f690bd2015-10-27 06:02:45 +0000350 Expr *Results[3];
Gor Nishanovce43bd22017-03-11 01:30:17 +0000351 OpaqueValueExpr *OpaqueValue;
352 bool IsInvalid;
Richard Smith9f690bd2015-10-27 06:02:45 +0000353};
354
Richard Smith23da82c2015-11-20 22:40:06 +0000355static ExprResult buildMemberCall(Sema &S, Expr *Base, SourceLocation Loc,
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000356 StringRef Name, MultiExprArg Args) {
Richard Smith23da82c2015-11-20 22:40:06 +0000357 DeclarationNameInfo NameInfo(&S.PP.getIdentifierTable().get(Name), Loc);
358
359 // FIXME: Fix BuildMemberReferenceExpr to take a const CXXScopeSpec&.
360 CXXScopeSpec SS;
361 ExprResult Result = S.BuildMemberReferenceExpr(
362 Base, Base->getType(), Loc, /*IsPtr=*/false, SS,
363 SourceLocation(), nullptr, NameInfo, /*TemplateArgs=*/nullptr,
364 /*Scope=*/nullptr);
365 if (Result.isInvalid())
366 return ExprError();
367
Gor Nishanovd4507262018-03-27 20:38:19 +0000368 // We meant exactly what we asked for. No need for typo correction.
369 if (auto *TE = dyn_cast<TypoExpr>(Result.get())) {
370 S.clearDelayedTypo(TE);
371 S.Diag(Loc, diag::err_no_member)
372 << NameInfo.getName() << Base->getType()->getAsCXXRecordDecl()
373 << Base->getSourceRange();
374 return ExprError();
375 }
376
Richard Smith255b85f2019-05-08 01:36:36 +0000377 return S.BuildCallExpr(nullptr, Result.get(), Loc, Args, Loc, nullptr);
Richard Smith23da82c2015-11-20 22:40:06 +0000378}
379
Gor Nishanov0f333002017-08-25 04:46:54 +0000380// See if return type is coroutine-handle and if so, invoke builtin coro-resume
381// on its address. This is to enable experimental support for coroutine-handle
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000382// returning await_suspend that results in a guaranteed tail call to the target
Gor Nishanov0f333002017-08-25 04:46:54 +0000383// coroutine.
384static Expr *maybeTailCall(Sema &S, QualType RetType, Expr *E,
385 SourceLocation Loc) {
386 if (RetType->isReferenceType())
387 return nullptr;
388 Type const *T = RetType.getTypePtr();
389 if (!T->isClassType() && !T->isStructureType())
390 return nullptr;
391
392 // FIXME: Add convertability check to coroutine_handle<>. Possibly via
393 // EvaluateBinaryTypeTrait(BTT_IsConvertible, ...) which is at the moment
394 // a private function in SemaExprCXX.cpp
395
396 ExprResult AddressExpr = buildMemberCall(S, E, Loc, "address", None);
397 if (AddressExpr.isInvalid())
398 return nullptr;
399
400 Expr *JustAddress = AddressExpr.get();
401 // FIXME: Check that the type of AddressExpr is void*
402 return buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_resume,
403 JustAddress);
404}
405
Richard Smith9f690bd2015-10-27 06:02:45 +0000406/// Build calls to await_ready, await_suspend, and await_resume for a co_await
407/// expression.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000408static ReadySuspendResumeResult buildCoawaitCalls(Sema &S, VarDecl *CoroPromise,
409 SourceLocation Loc, Expr *E) {
Gor Nishanovce43bd22017-03-11 01:30:17 +0000410 OpaqueValueExpr *Operand = new (S.Context)
411 OpaqueValueExpr(Loc, E->getType(), VK_LValue, E->getObjectKind(), E);
412
Richard Smith9f690bd2015-10-27 06:02:45 +0000413 // Assume invalid until we see otherwise.
Gor Nishanovce43bd22017-03-11 01:30:17 +0000414 ReadySuspendResumeResult Calls = {{}, Operand, /*IsInvalid=*/true};
Richard Smith9f690bd2015-10-27 06:02:45 +0000415
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000416 ExprResult CoroHandleRes = buildCoroutineHandle(S, CoroPromise->getType(), Loc);
417 if (CoroHandleRes.isInvalid())
418 return Calls;
419 Expr *CoroHandle = CoroHandleRes.get();
420
Richard Smith9f690bd2015-10-27 06:02:45 +0000421 const StringRef Funcs[] = {"await_ready", "await_suspend", "await_resume"};
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000422 MultiExprArg Args[] = {None, CoroHandle, None};
Richard Smith9f690bd2015-10-27 06:02:45 +0000423 for (size_t I = 0, N = llvm::array_lengthof(Funcs); I != N; ++I) {
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000424 ExprResult Result = buildMemberCall(S, Operand, Loc, Funcs[I], Args[I]);
Richard Smith9f690bd2015-10-27 06:02:45 +0000425 if (Result.isInvalid())
426 return Calls;
427 Calls.Results[I] = Result.get();
428 }
429
Eric Fiselierd978e532017-05-28 18:21:12 +0000430 // Assume the calls are valid; all further checking should make them invalid.
Richard Smith9f690bd2015-10-27 06:02:45 +0000431 Calls.IsInvalid = false;
Eric Fiselierd978e532017-05-28 18:21:12 +0000432
433 using ACT = ReadySuspendResumeResult::AwaitCallType;
434 CallExpr *AwaitReady = cast<CallExpr>(Calls.Results[ACT::ACT_Ready]);
435 if (!AwaitReady->getType()->isDependentType()) {
436 // [expr.await]p3 [...]
437 // — await-ready is the expression e.await_ready(), contextually converted
438 // to bool.
439 ExprResult Conv = S.PerformContextuallyConvertToBool(AwaitReady);
440 if (Conv.isInvalid()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000441 S.Diag(AwaitReady->getDirectCallee()->getBeginLoc(),
Eric Fiselierd978e532017-05-28 18:21:12 +0000442 diag::note_await_ready_no_bool_conversion);
443 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
444 << AwaitReady->getDirectCallee() << E->getSourceRange();
445 Calls.IsInvalid = true;
446 }
447 Calls.Results[ACT::ACT_Ready] = Conv.get();
448 }
449 CallExpr *AwaitSuspend = cast<CallExpr>(Calls.Results[ACT::ACT_Suspend]);
450 if (!AwaitSuspend->getType()->isDependentType()) {
451 // [expr.await]p3 [...]
452 // - await-suspend is the expression e.await_suspend(h), which shall be
453 // a prvalue of type void or bool.
Eric Fiselier84ee7ff2017-05-31 23:41:11 +0000454 QualType RetType = AwaitSuspend->getCallReturnType(S.Context);
Gor Nishanovdb419a62017-09-05 19:31:52 +0000455
Gor Nishanov0f333002017-08-25 04:46:54 +0000456 // Experimental support for coroutine_handle returning await_suspend.
457 if (Expr *TailCallSuspend = maybeTailCall(S, RetType, AwaitSuspend, Loc))
458 Calls.Results[ACT::ACT_Suspend] = TailCallSuspend;
459 else {
460 // non-class prvalues always have cv-unqualified types
Gor Nishanov0f333002017-08-25 04:46:54 +0000461 if (RetType->isReferenceType() ||
Gor Nishanovdb419a62017-09-05 19:31:52 +0000462 (!RetType->isBooleanType() && !RetType->isVoidType())) {
Gor Nishanov0f333002017-08-25 04:46:54 +0000463 S.Diag(AwaitSuspend->getCalleeDecl()->getLocation(),
464 diag::err_await_suspend_invalid_return_type)
465 << RetType;
466 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
467 << AwaitSuspend->getDirectCallee();
468 Calls.IsInvalid = true;
469 }
Eric Fiselierd978e532017-05-28 18:21:12 +0000470 }
471 }
472
Richard Smith9f690bd2015-10-27 06:02:45 +0000473 return Calls;
474}
475
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000476static ExprResult buildPromiseCall(Sema &S, VarDecl *Promise,
477 SourceLocation Loc, StringRef Name,
478 MultiExprArg Args) {
479
480 // Form a reference to the promise.
481 ExprResult PromiseRef = S.BuildDeclRefExpr(
482 Promise, Promise->getType().getNonReferenceType(), VK_LValue, Loc);
483 if (PromiseRef.isInvalid())
484 return ExprError();
485
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000486 return buildMemberCall(S, PromiseRef.get(), Loc, Name, Args);
487}
488
489VarDecl *Sema::buildCoroutinePromise(SourceLocation Loc) {
490 assert(isa<FunctionDecl>(CurContext) && "not in a function scope");
491 auto *FD = cast<FunctionDecl>(CurContext);
Eric Fiselier166c6e62017-07-10 01:27:22 +0000492 bool IsThisDependentType = [&] {
493 if (auto *MD = dyn_cast_or_null<CXXMethodDecl>(FD))
Brian Gesiak5488ab42019-01-11 01:54:53 +0000494 return MD->isInstance() && MD->getThisType()->isDependentType();
Eric Fiselier166c6e62017-07-10 01:27:22 +0000495 else
496 return false;
497 }();
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000498
Eric Fiselier166c6e62017-07-10 01:27:22 +0000499 QualType T = FD->getType()->isDependentType() || IsThisDependentType
500 ? Context.DependentTy
501 : lookupPromiseType(*this, FD, Loc);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000502 if (T.isNull())
503 return nullptr;
504
505 auto *VD = VarDecl::Create(Context, FD, FD->getLocation(), FD->getLocation(),
506 &PP.getIdentifierTable().get("__promise"), T,
507 Context.getTrivialTypeSourceInfo(T, Loc), SC_None);
508 CheckVariableDeclarationType(VD);
509 if (VD->isInvalidDecl())
510 return nullptr;
Brian Gesiak61f4ac92018-01-24 22:15:42 +0000511
512 auto *ScopeInfo = getCurFunction();
513 // Build a list of arguments, based on the coroutine functions arguments,
514 // that will be passed to the promise type's constructor.
515 llvm::SmallVector<Expr *, 4> CtorArgExprs;
Gor Nishanov07ac63f2018-05-28 18:08:47 +0000516
517 // Add implicit object parameter.
518 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
519 if (MD->isInstance() && !isLambdaCallOperator(MD)) {
520 ExprResult ThisExpr = ActOnCXXThis(Loc);
521 if (ThisExpr.isInvalid())
522 return nullptr;
523 ThisExpr = CreateBuiltinUnaryOp(Loc, UO_Deref, ThisExpr.get());
524 if (ThisExpr.isInvalid())
525 return nullptr;
526 CtorArgExprs.push_back(ThisExpr.get());
527 }
528 }
529
Brian Gesiak61f4ac92018-01-24 22:15:42 +0000530 auto &Moves = ScopeInfo->CoroutineParameterMoves;
531 for (auto *PD : FD->parameters()) {
532 if (PD->getType()->isDependentType())
533 continue;
534
535 auto RefExpr = ExprEmpty();
536 auto Move = Moves.find(PD);
Brian Gesiak98606222018-02-15 20:37:22 +0000537 assert(Move != Moves.end() &&
538 "Coroutine function parameter not inserted into move map");
539 // If a reference to the function parameter exists in the coroutine
540 // frame, use that reference.
541 auto *MoveDecl =
542 cast<VarDecl>(cast<DeclStmt>(Move->second)->getSingleDecl());
543 RefExpr =
544 BuildDeclRefExpr(MoveDecl, MoveDecl->getType().getNonReferenceType(),
545 ExprValueKind::VK_LValue, FD->getLocation());
Brian Gesiak61f4ac92018-01-24 22:15:42 +0000546 if (RefExpr.isInvalid())
547 return nullptr;
548 CtorArgExprs.push_back(RefExpr.get());
549 }
550
551 // Create an initialization sequence for the promise type using the
552 // constructor arguments, wrapped in a parenthesized list expression.
Bruno Riccif49e1ca2018-11-20 16:20:40 +0000553 Expr *PLE = ParenListExpr::Create(Context, FD->getLocation(),
554 CtorArgExprs, FD->getLocation());
Brian Gesiak61f4ac92018-01-24 22:15:42 +0000555 InitializedEntity Entity = InitializedEntity::InitializeVariable(VD);
556 InitializationKind Kind = InitializationKind::CreateForInit(
557 VD->getLocation(), /*DirectInit=*/true, PLE);
558 InitializationSequence InitSeq(*this, Entity, Kind, CtorArgExprs,
559 /*TopLevelOfInitList=*/false,
560 /*TreatUnavailableAsInvalid=*/false);
561
562 // Attempt to initialize the promise type with the arguments.
563 // If that fails, fall back to the promise type's default constructor.
564 if (InitSeq) {
565 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, CtorArgExprs);
566 if (Result.isInvalid()) {
567 VD->setInvalidDecl();
568 } else if (Result.get()) {
569 VD->setInit(MaybeCreateExprWithCleanups(Result.get()));
570 VD->setInitStyle(VarDecl::CallInit);
571 CheckCompleteVariableDeclaration(VD);
572 }
573 } else
574 ActOnUninitializedDecl(VD);
575
Eric Fiselier37b8a372017-05-31 19:36:59 +0000576 FD->addDecl(VD);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000577 return VD;
578}
579
580/// Check that this is a context in which a coroutine suspension can appear.
581static FunctionScopeInfo *checkCoroutineContext(Sema &S, SourceLocation Loc,
Eric Fiseliercac0a592017-03-11 02:35:37 +0000582 StringRef Keyword,
583 bool IsImplicit = false) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000584 if (!isValidCoroutineContext(S, Loc, Keyword))
585 return nullptr;
586
587 assert(isa<FunctionDecl>(S.CurContext) && "not in a function scope");
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000588
589 auto *ScopeInfo = S.getCurFunction();
590 assert(ScopeInfo && "missing function scope for function");
591
Eric Fiseliercac0a592017-03-11 02:35:37 +0000592 if (ScopeInfo->FirstCoroutineStmtLoc.isInvalid() && !IsImplicit)
593 ScopeInfo->setFirstCoroutineStmt(Loc, Keyword);
594
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000595 if (ScopeInfo->CoroutinePromise)
596 return ScopeInfo;
597
Brian Gesiak61f4ac92018-01-24 22:15:42 +0000598 if (!S.buildCoroutineParameterMoves(Loc))
599 return nullptr;
600
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000601 ScopeInfo->CoroutinePromise = S.buildCoroutinePromise(Loc);
602 if (!ScopeInfo->CoroutinePromise)
603 return nullptr;
604
605 return ScopeInfo;
606}
607
Eric Fiselierb936a392017-06-14 03:24:55 +0000608bool Sema::ActOnCoroutineBodyStart(Scope *SC, SourceLocation KWLoc,
609 StringRef Keyword) {
610 if (!checkCoroutineContext(*this, KWLoc, Keyword))
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000611 return false;
Eric Fiselierb936a392017-06-14 03:24:55 +0000612 auto *ScopeInfo = getCurFunction();
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000613 assert(ScopeInfo->CoroutinePromise);
614
615 // If we have existing coroutine statements then we have already built
616 // the initial and final suspend points.
617 if (!ScopeInfo->NeedsCoroutineSuspends)
618 return true;
619
620 ScopeInfo->setNeedsCoroutineSuspends(false);
621
Eric Fiselierb936a392017-06-14 03:24:55 +0000622 auto *Fn = cast<FunctionDecl>(CurContext);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000623 SourceLocation Loc = Fn->getLocation();
624 // Build the initial suspend point
625 auto buildSuspends = [&](StringRef Name) mutable -> StmtResult {
626 ExprResult Suspend =
Eric Fiselierb936a392017-06-14 03:24:55 +0000627 buildPromiseCall(*this, ScopeInfo->CoroutinePromise, Loc, Name, None);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000628 if (Suspend.isInvalid())
629 return StmtError();
Eric Fiselierb936a392017-06-14 03:24:55 +0000630 Suspend = buildOperatorCoawaitCall(*this, SC, Loc, Suspend.get());
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000631 if (Suspend.isInvalid())
632 return StmtError();
Eric Fiselierb936a392017-06-14 03:24:55 +0000633 Suspend = BuildResolvedCoawaitExpr(Loc, Suspend.get(),
634 /*IsImplicit*/ true);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +0000635 Suspend = ActOnFinishFullExpr(Suspend.get(), /*DiscardedValue*/ false);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000636 if (Suspend.isInvalid()) {
Eric Fiselierb936a392017-06-14 03:24:55 +0000637 Diag(Loc, diag::note_coroutine_promise_suspend_implicitly_required)
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000638 << ((Name == "initial_suspend") ? 0 : 1);
Eric Fiselierb936a392017-06-14 03:24:55 +0000639 Diag(KWLoc, diag::note_declared_coroutine_here) << Keyword;
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000640 return StmtError();
641 }
642 return cast<Stmt>(Suspend.get());
643 };
644
645 StmtResult InitSuspend = buildSuspends("initial_suspend");
646 if (InitSuspend.isInvalid())
647 return true;
648
649 StmtResult FinalSuspend = buildSuspends("final_suspend");
650 if (FinalSuspend.isInvalid())
651 return true;
652
653 ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());
654
655 return true;
656}
657
Brian Gesiakb15c35a2019-03-25 00:53:10 +0000658// Recursively walks up the scope hierarchy until either a 'catch' or a function
659// scope is found, whichever comes first.
660static bool isWithinCatchScope(Scope *S) {
661 // 'co_await' and 'co_yield' keywords are disallowed within catch blocks, but
662 // lambdas that use 'co_await' are allowed. The loop below ends when a
663 // function scope is found in order to ensure the following behavior:
664 //
665 // void foo() { // <- function scope
666 // try { //
667 // co_await x; // <- 'co_await' is OK within a function scope
668 // } catch { // <- catch scope
669 // co_await x; // <- 'co_await' is not OK within a catch scope
670 // []() { // <- function scope
671 // co_await x; // <- 'co_await' is OK within a function scope
672 // }();
673 // }
674 // }
675 while (S && !(S->getFlags() & Scope::FnScope)) {
676 if (S->getFlags() & Scope::CatchScope)
677 return true;
678 S = S->getParent();
679 }
680 return false;
681}
682
683// [expr.await]p2, emphasis added: "An await-expression shall appear only in
684// a *potentially evaluated* expression within the compound-statement of a
685// function-body *outside of a handler* [...] A context within a function
686// where an await-expression can appear is called a suspension context of the
687// function."
688static void checkSuspensionContext(Sema &S, SourceLocation Loc,
689 StringRef Keyword) {
690 // First emphasis of [expr.await]p2: must be a potentially evaluated context.
691 // That is, 'co_await' and 'co_yield' cannot appear in subexpressions of
692 // \c sizeof.
693 if (S.isUnevaluatedContext())
694 S.Diag(Loc, diag::err_coroutine_unevaluated_context) << Keyword;
695
696 // Second emphasis of [expr.await]p2: must be outside of an exception handler.
697 if (isWithinCatchScope(S.getCurScope()))
698 S.Diag(Loc, diag::err_coroutine_within_handler) << Keyword;
699}
700
Richard Smith9f690bd2015-10-27 06:02:45 +0000701ExprResult Sema::ActOnCoawaitExpr(Scope *S, SourceLocation Loc, Expr *E) {
Eric Fiselierb936a392017-06-14 03:24:55 +0000702 if (!ActOnCoroutineBodyStart(S, Loc, "co_await")) {
Eric Fiseliera5465282016-09-29 21:47:39 +0000703 CorrectDelayedTyposInExpr(E);
704 return ExprError();
705 }
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000706
Brian Gesiakb15c35a2019-03-25 00:53:10 +0000707 checkSuspensionContext(*this, Loc, "co_await");
708
Richard Smith10610f72015-11-20 22:57:24 +0000709 if (E->getType()->isPlaceholderType()) {
710 ExprResult R = CheckPlaceholderExpr(E);
711 if (R.isInvalid()) return ExprError();
712 E = R.get();
713 }
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000714 ExprResult Lookup = buildOperatorCoawaitLookupExpr(*this, S, Loc);
715 if (Lookup.isInvalid())
716 return ExprError();
717 return BuildUnresolvedCoawaitExpr(Loc, E,
718 cast<UnresolvedLookupExpr>(Lookup.get()));
719}
Richard Smith10610f72015-11-20 22:57:24 +0000720
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000721ExprResult Sema::BuildUnresolvedCoawaitExpr(SourceLocation Loc, Expr *E,
Eric Fiseliercac0a592017-03-11 02:35:37 +0000722 UnresolvedLookupExpr *Lookup) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000723 auto *FSI = checkCoroutineContext(*this, Loc, "co_await");
724 if (!FSI)
725 return ExprError();
726
727 if (E->getType()->isPlaceholderType()) {
728 ExprResult R = CheckPlaceholderExpr(E);
729 if (R.isInvalid())
730 return ExprError();
731 E = R.get();
732 }
733
734 auto *Promise = FSI->CoroutinePromise;
735 if (Promise->getType()->isDependentType()) {
736 Expr *Res =
737 new (Context) DependentCoawaitExpr(Loc, Context.DependentTy, E, Lookup);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000738 return Res;
739 }
740
741 auto *RD = Promise->getType()->getAsCXXRecordDecl();
742 if (lookupMember(*this, "await_transform", RD, Loc)) {
743 ExprResult R = buildPromiseCall(*this, Promise, Loc, "await_transform", E);
744 if (R.isInvalid()) {
745 Diag(Loc,
746 diag::note_coroutine_promise_implicit_await_transform_required_here)
747 << E->getSourceRange();
748 return ExprError();
749 }
750 E = R.get();
751 }
752 ExprResult Awaitable = buildOperatorCoawaitCall(*this, Loc, E, Lookup);
Richard Smith9f690bd2015-10-27 06:02:45 +0000753 if (Awaitable.isInvalid())
754 return ExprError();
Eric Fiseliera5465282016-09-29 21:47:39 +0000755
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000756 return BuildResolvedCoawaitExpr(Loc, Awaitable.get());
Richard Smith9f690bd2015-10-27 06:02:45 +0000757}
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000758
759ExprResult Sema::BuildResolvedCoawaitExpr(SourceLocation Loc, Expr *E,
760 bool IsImplicit) {
Eric Fiseliercac0a592017-03-11 02:35:37 +0000761 auto *Coroutine = checkCoroutineContext(*this, Loc, "co_await", IsImplicit);
Richard Smith744b2242015-11-20 02:54:01 +0000762 if (!Coroutine)
763 return ExprError();
Richard Smith9f690bd2015-10-27 06:02:45 +0000764
Richard Smith9f690bd2015-10-27 06:02:45 +0000765 if (E->getType()->isPlaceholderType()) {
766 ExprResult R = CheckPlaceholderExpr(E);
767 if (R.isInvalid()) return ExprError();
768 E = R.get();
769 }
770
Richard Smith10610f72015-11-20 22:57:24 +0000771 if (E->getType()->isDependentType()) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000772 Expr *Res = new (Context)
773 CoawaitExpr(Loc, Context.DependentTy, E, IsImplicit);
Richard Smith10610f72015-11-20 22:57:24 +0000774 return Res;
775 }
776
Richard Smith1f38edd2015-11-22 03:13:02 +0000777 // If the expression is a temporary, materialize it as an lvalue so that we
778 // can use it multiple times.
779 if (E->getValueKind() == VK_RValue)
Tim Shen4a05bb82016-06-21 20:29:17 +0000780 E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
Richard Smith9f690bd2015-10-27 06:02:45 +0000781
Eric Fiselierd2e30d32018-03-27 03:15:46 +0000782 // The location of the `co_await` token cannot be used when constructing
783 // the member call expressions since it's before the location of `Expr`, which
784 // is used as the start of the member call expression.
785 SourceLocation CallLoc = E->getExprLoc();
786
Richard Smith9f690bd2015-10-27 06:02:45 +0000787 // Build the await_ready, await_suspend, await_resume calls.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000788 ReadySuspendResumeResult RSS =
Eric Fiselierd2e30d32018-03-27 03:15:46 +0000789 buildCoawaitCalls(*this, Coroutine->CoroutinePromise, CallLoc, E);
Richard Smith9f690bd2015-10-27 06:02:45 +0000790 if (RSS.IsInvalid)
791 return ExprError();
792
Gor Nishanovce43bd22017-03-11 01:30:17 +0000793 Expr *Res =
794 new (Context) CoawaitExpr(Loc, E, RSS.Results[0], RSS.Results[1],
795 RSS.Results[2], RSS.OpaqueValue, IsImplicit);
Eric Fiseliercac0a592017-03-11 02:35:37 +0000796
Richard Smithcfd53b42015-10-22 06:13:50 +0000797 return Res;
798}
799
Richard Smith9f690bd2015-10-27 06:02:45 +0000800ExprResult Sema::ActOnCoyieldExpr(Scope *S, SourceLocation Loc, Expr *E) {
Eric Fiselierb936a392017-06-14 03:24:55 +0000801 if (!ActOnCoroutineBodyStart(S, Loc, "co_yield")) {
Eric Fiseliera5465282016-09-29 21:47:39 +0000802 CorrectDelayedTyposInExpr(E);
Richard Smith23da82c2015-11-20 22:40:06 +0000803 return ExprError();
Eric Fiseliera5465282016-09-29 21:47:39 +0000804 }
Richard Smith23da82c2015-11-20 22:40:06 +0000805
Brian Gesiakb15c35a2019-03-25 00:53:10 +0000806 checkSuspensionContext(*this, Loc, "co_yield");
807
Richard Smith23da82c2015-11-20 22:40:06 +0000808 // Build yield_value call.
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000809 ExprResult Awaitable = buildPromiseCall(
810 *this, getCurFunction()->CoroutinePromise, Loc, "yield_value", E);
Richard Smith9f690bd2015-10-27 06:02:45 +0000811 if (Awaitable.isInvalid())
812 return ExprError();
Richard Smith23da82c2015-11-20 22:40:06 +0000813
814 // Build 'operator co_await' call.
815 Awaitable = buildOperatorCoawaitCall(*this, S, Loc, Awaitable.get());
816 if (Awaitable.isInvalid())
817 return ExprError();
818
Richard Smith9f690bd2015-10-27 06:02:45 +0000819 return BuildCoyieldExpr(Loc, Awaitable.get());
820}
821ExprResult Sema::BuildCoyieldExpr(SourceLocation Loc, Expr *E) {
822 auto *Coroutine = checkCoroutineContext(*this, Loc, "co_yield");
Richard Smith744b2242015-11-20 02:54:01 +0000823 if (!Coroutine)
824 return ExprError();
Richard Smithcfd53b42015-10-22 06:13:50 +0000825
Richard Smith10610f72015-11-20 22:57:24 +0000826 if (E->getType()->isPlaceholderType()) {
827 ExprResult R = CheckPlaceholderExpr(E);
828 if (R.isInvalid()) return ExprError();
829 E = R.get();
830 }
831
Richard Smithd7bed4d2015-11-22 02:57:17 +0000832 if (E->getType()->isDependentType()) {
833 Expr *Res = new (Context) CoyieldExpr(Loc, Context.DependentTy, E);
Richard Smithd7bed4d2015-11-22 02:57:17 +0000834 return Res;
835 }
836
Richard Smith1f38edd2015-11-22 03:13:02 +0000837 // If the expression is a temporary, materialize it as an lvalue so that we
838 // can use it multiple times.
839 if (E->getValueKind() == VK_RValue)
Tim Shen4a05bb82016-06-21 20:29:17 +0000840 E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
Richard Smithd7bed4d2015-11-22 02:57:17 +0000841
842 // Build the await_ready, await_suspend, await_resume calls.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000843 ReadySuspendResumeResult RSS =
844 buildCoawaitCalls(*this, Coroutine->CoroutinePromise, Loc, E);
Richard Smithd7bed4d2015-11-22 02:57:17 +0000845 if (RSS.IsInvalid)
846 return ExprError();
847
Eric Fiselierb936a392017-06-14 03:24:55 +0000848 Expr *Res =
849 new (Context) CoyieldExpr(Loc, E, RSS.Results[0], RSS.Results[1],
850 RSS.Results[2], RSS.OpaqueValue);
Eric Fiseliercac0a592017-03-11 02:35:37 +0000851
Richard Smithcfd53b42015-10-22 06:13:50 +0000852 return Res;
853}
854
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000855StmtResult Sema::ActOnCoreturnStmt(Scope *S, SourceLocation Loc, Expr *E) {
Eric Fiselierb936a392017-06-14 03:24:55 +0000856 if (!ActOnCoroutineBodyStart(S, Loc, "co_return")) {
Eric Fiseliera5465282016-09-29 21:47:39 +0000857 CorrectDelayedTyposInExpr(E);
858 return StmtError();
859 }
Richard Smith9f690bd2015-10-27 06:02:45 +0000860 return BuildCoreturnStmt(Loc, E);
861}
Gor Nishanov3e048bb2016-10-04 00:31:16 +0000862
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000863StmtResult Sema::BuildCoreturnStmt(SourceLocation Loc, Expr *E,
864 bool IsImplicit) {
Eric Fiseliercac0a592017-03-11 02:35:37 +0000865 auto *FSI = checkCoroutineContext(*this, Loc, "co_return", IsImplicit);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000866 if (!FSI)
Richard Smith71d403e2015-11-22 07:33:28 +0000867 return StmtError();
868
869 if (E && E->getType()->isPlaceholderType() &&
870 !E->getType()->isSpecificPlaceholderType(BuiltinType::Overload)) {
Richard Smith10610f72015-11-20 22:57:24 +0000871 ExprResult R = CheckPlaceholderExpr(E);
872 if (R.isInvalid()) return StmtError();
873 E = R.get();
874 }
875
Brian Gesiak0b568302018-10-08 03:08:39 +0000876 // Move the return value if we can
877 if (E) {
878 auto NRVOCandidate = this->getCopyElisionCandidate(E->getType(), E, CES_AsIfByStdMove);
879 if (NRVOCandidate) {
880 InitializedEntity Entity =
881 InitializedEntity::InitializeResult(Loc, E->getType(), NRVOCandidate);
882 ExprResult MoveResult = this->PerformMoveOrCopyInitialization(
883 Entity, NRVOCandidate, E->getType(), E);
884 if (MoveResult.get())
885 E = MoveResult.get();
886 }
887 }
888
Richard Smith4ba66602015-11-22 07:05:16 +0000889 // FIXME: If the operand is a reference to a variable that's about to go out
Richard Smith2af65c42015-11-24 02:34:39 +0000890 // of scope, we should treat the operand as an xvalue for this overload
Richard Smith4ba66602015-11-22 07:05:16 +0000891 // resolution.
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000892 VarDecl *Promise = FSI->CoroutinePromise;
Richard Smith4ba66602015-11-22 07:05:16 +0000893 ExprResult PC;
Eric Fiselier98131312016-10-06 21:23:38 +0000894 if (E && (isa<InitListExpr>(E) || !E->getType()->isVoidType())) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000895 PC = buildPromiseCall(*this, Promise, Loc, "return_value", E);
Richard Smith4ba66602015-11-22 07:05:16 +0000896 } else {
897 E = MakeFullDiscardedValueExpr(E).get();
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000898 PC = buildPromiseCall(*this, Promise, Loc, "return_void", None);
Richard Smith4ba66602015-11-22 07:05:16 +0000899 }
900 if (PC.isInvalid())
901 return StmtError();
902
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +0000903 Expr *PCE = ActOnFinishFullExpr(PC.get(), /*DiscardedValue*/ false).get();
Richard Smith4ba66602015-11-22 07:05:16 +0000904
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000905 Stmt *Res = new (Context) CoreturnStmt(Loc, E, PCE, IsImplicit);
Richard Smithcfd53b42015-10-22 06:13:50 +0000906 return Res;
907}
908
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000909/// Look up the std::nothrow object.
910static Expr *buildStdNoThrowDeclRef(Sema &S, SourceLocation Loc) {
911 NamespaceDecl *Std = S.getStdNamespace();
912 assert(Std && "Should already be diagnosed");
913
914 LookupResult Result(S, &S.PP.getIdentifierTable().get("nothrow"), Loc,
915 Sema::LookupOrdinaryName);
916 if (!S.LookupQualifiedName(Result, Std)) {
917 // FIXME: <experimental/coroutine> should have been included already.
918 // If we require it to include <new> then this diagnostic is no longer
919 // needed.
920 S.Diag(Loc, diag::err_implicit_coroutine_std_nothrow_type_not_found);
921 return nullptr;
922 }
923
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000924 auto *VD = Result.getAsSingle<VarDecl>();
925 if (!VD) {
926 Result.suppressDiagnostics();
927 // We found something weird. Complain about the first thing we found.
928 NamedDecl *Found = *Result.begin();
929 S.Diag(Found->getLocation(), diag::err_malformed_std_nothrow);
930 return nullptr;
931 }
932
933 ExprResult DR = S.BuildDeclRefExpr(VD, VD->getType(), VK_LValue, Loc);
934 if (DR.isInvalid())
935 return nullptr;
936
937 return DR.get();
938}
939
Gor Nishanov8df64e92016-10-27 16:28:31 +0000940// Find an appropriate delete for the promise.
941static FunctionDecl *findDeleteForPromise(Sema &S, SourceLocation Loc,
942 QualType PromiseType) {
943 FunctionDecl *OperatorDelete = nullptr;
944
945 DeclarationName DeleteName =
946 S.Context.DeclarationNames.getCXXOperatorName(OO_Delete);
947
948 auto *PointeeRD = PromiseType->getAsCXXRecordDecl();
949 assert(PointeeRD && "PromiseType must be a CxxRecordDecl type");
950
951 if (S.FindDeallocationFunction(Loc, PointeeRD, DeleteName, OperatorDelete))
952 return nullptr;
953
954 if (!OperatorDelete) {
955 // Look for a global declaration.
956 const bool CanProvideSize = S.isCompleteType(Loc, PromiseType);
957 const bool Overaligned = false;
958 OperatorDelete = S.FindUsualDeallocationFunction(Loc, CanProvideSize,
959 Overaligned, DeleteName);
960 }
961 S.MarkFunctionReferenced(Loc, OperatorDelete);
962 return OperatorDelete;
963}
964
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000965
966void Sema::CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body) {
967 FunctionScopeInfo *Fn = getCurFunction();
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000968 assert(Fn && Fn->isCoroutine() && "not a coroutine");
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000969 if (!Body) {
970 assert(FD->isInvalidDecl() &&
971 "a null body is only allowed for invalid declarations");
972 return;
973 }
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000974 // We have a function that uses coroutine keywords, but we failed to build
975 // the promise type.
976 if (!Fn->CoroutinePromise)
977 return FD->setInvalidDecl();
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000978
979 if (isa<CoroutineBodyStmt>(Body)) {
Gor Nishanov29ff6382017-05-24 14:34:19 +0000980 // Nothing todo. the body is already a transformed coroutine body statement.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000981 return;
982 }
983
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000984 // Coroutines [stmt.return]p1:
985 // A return statement shall not appear in a coroutine.
986 if (Fn->FirstReturnLoc.isValid()) {
Eric Fiseliercac0a592017-03-11 02:35:37 +0000987 assert(Fn->FirstCoroutineStmtLoc.isValid() &&
988 "first coroutine location not set");
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000989 Diag(Fn->FirstReturnLoc, diag::err_return_in_coroutine);
Eric Fiseliercac0a592017-03-11 02:35:37 +0000990 Diag(Fn->FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
991 << Fn->getFirstCoroutineStmtKeyword();
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000992 }
Eric Fiselierbee782b2017-04-03 19:21:00 +0000993 CoroutineStmtBuilder Builder(*this, *FD, *Fn, Body);
994 if (Builder.isInvalid() || !Builder.buildStatements())
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000995 return FD->setInvalidDecl();
996
997 // Build body for the coroutine wrapper statement.
998 Body = CoroutineBodyStmt::Create(Context, Builder);
999}
1000
Eric Fiselierbee782b2017-04-03 19:21:00 +00001001CoroutineStmtBuilder::CoroutineStmtBuilder(Sema &S, FunctionDecl &FD,
1002 sema::FunctionScopeInfo &Fn,
1003 Stmt *Body)
1004 : S(S), FD(FD), Fn(Fn), Loc(FD.getLocation()),
1005 IsPromiseDependentType(
1006 !Fn.CoroutinePromise ||
1007 Fn.CoroutinePromise->getType()->isDependentType()) {
1008 this->Body = Body;
Brian Gesiak61f4ac92018-01-24 22:15:42 +00001009
1010 for (auto KV : Fn.CoroutineParameterMoves)
1011 this->ParamMovesVector.push_back(KV.second);
1012 this->ParamMoves = this->ParamMovesVector;
1013
Eric Fiselierbee782b2017-04-03 19:21:00 +00001014 if (!IsPromiseDependentType) {
1015 PromiseRecordDecl = Fn.CoroutinePromise->getType()->getAsCXXRecordDecl();
1016 assert(PromiseRecordDecl && "Type should have already been checked");
1017 }
1018 this->IsValid = makePromiseStmt() && makeInitialAndFinalSuspend();
1019}
1020
1021bool CoroutineStmtBuilder::buildStatements() {
1022 assert(this->IsValid && "coroutine already invalid");
Brian Gesiak61f4ac92018-01-24 22:15:42 +00001023 this->IsValid = makeReturnObject();
Eric Fiselierbee782b2017-04-03 19:21:00 +00001024 if (this->IsValid && !IsPromiseDependentType)
1025 buildDependentStatements();
1026 return this->IsValid;
1027}
1028
1029bool CoroutineStmtBuilder::buildDependentStatements() {
1030 assert(this->IsValid && "coroutine already invalid");
1031 assert(!this->IsPromiseDependentType &&
1032 "coroutine cannot have a dependent promise type");
1033 this->IsValid = makeOnException() && makeOnFallthrough() &&
Gor Nishanov6a470682017-05-22 20:22:23 +00001034 makeGroDeclAndReturnStmt() && makeReturnOnAllocFailure() &&
1035 makeNewAndDeleteExpr();
Eric Fiselierbee782b2017-04-03 19:21:00 +00001036 return this->IsValid;
1037}
1038
1039bool CoroutineStmtBuilder::makePromiseStmt() {
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001040 // Form a declaration statement for the promise declaration, so that AST
1041 // visitors can more easily find it.
1042 StmtResult PromiseStmt =
1043 S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(Fn.CoroutinePromise), Loc, Loc);
1044 if (PromiseStmt.isInvalid())
1045 return false;
1046
1047 this->Promise = PromiseStmt.get();
1048 return true;
1049}
1050
Eric Fiselierbee782b2017-04-03 19:21:00 +00001051bool CoroutineStmtBuilder::makeInitialAndFinalSuspend() {
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001052 if (Fn.hasInvalidCoroutineSuspends())
1053 return false;
1054 this->InitialSuspend = cast<Expr>(Fn.CoroutineSuspends.first);
1055 this->FinalSuspend = cast<Expr>(Fn.CoroutineSuspends.second);
1056 return true;
1057}
1058
Gor Nishanov3aa9eb32017-03-27 23:36:59 +00001059static bool diagReturnOnAllocFailure(Sema &S, Expr *E,
1060 CXXRecordDecl *PromiseRecordDecl,
1061 FunctionScopeInfo &Fn) {
1062 auto Loc = E->getExprLoc();
1063 if (auto *DeclRef = dyn_cast_or_null<DeclRefExpr>(E)) {
1064 auto *Decl = DeclRef->getDecl();
1065 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Decl)) {
1066 if (Method->isStatic())
1067 return true;
1068 else
1069 Loc = Decl->getLocation();
1070 }
1071 }
1072
1073 S.Diag(
1074 Loc,
1075 diag::err_coroutine_promise_get_return_object_on_allocation_failure)
1076 << PromiseRecordDecl;
1077 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1078 << Fn.getFirstCoroutineStmtKeyword();
1079 return false;
1080}
1081
Eric Fiselierbee782b2017-04-03 19:21:00 +00001082bool CoroutineStmtBuilder::makeReturnOnAllocFailure() {
1083 assert(!IsPromiseDependentType &&
1084 "cannot make statement while the promise type is dependent");
Gor Nishanov3aa9eb32017-03-27 23:36:59 +00001085
1086 // [dcl.fct.def.coroutine]/8
1087 // The unqualified-id get_return_object_on_allocation_failure is looked up in
1088 // the scope of class P by class member access lookup (3.4.5). ...
1089 // If an allocation function returns nullptr, ... the coroutine return value
1090 // is obtained by a call to ... get_return_object_on_allocation_failure().
1091
1092 DeclarationName DN =
1093 S.PP.getIdentifierInfo("get_return_object_on_allocation_failure");
1094 LookupResult Found(S, DN, Loc, Sema::LookupMemberName);
Eric Fiselierbee782b2017-04-03 19:21:00 +00001095 if (!S.LookupQualifiedName(Found, PromiseRecordDecl))
1096 return true;
Gor Nishanov3aa9eb32017-03-27 23:36:59 +00001097
1098 CXXScopeSpec SS;
1099 ExprResult DeclNameExpr =
1100 S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
Eric Fiselierbee782b2017-04-03 19:21:00 +00001101 if (DeclNameExpr.isInvalid())
1102 return false;
Gor Nishanov3aa9eb32017-03-27 23:36:59 +00001103
1104 if (!diagReturnOnAllocFailure(S, DeclNameExpr.get(), PromiseRecordDecl, Fn))
1105 return false;
1106
1107 ExprResult ReturnObjectOnAllocationFailure =
Richard Smith255b85f2019-05-08 01:36:36 +00001108 S.BuildCallExpr(nullptr, DeclNameExpr.get(), Loc, {}, Loc);
Eric Fiselierbee782b2017-04-03 19:21:00 +00001109 if (ReturnObjectOnAllocationFailure.isInvalid())
1110 return false;
Gor Nishanov3aa9eb32017-03-27 23:36:59 +00001111
Gor Nishanovc4a19082017-03-28 02:51:45 +00001112 StmtResult ReturnStmt =
1113 S.BuildReturnStmt(Loc, ReturnObjectOnAllocationFailure.get());
Gor Nishanov6a470682017-05-22 20:22:23 +00001114 if (ReturnStmt.isInvalid()) {
Eric Fiselierfc50f622017-05-25 14:59:39 +00001115 S.Diag(Found.getFoundDecl()->getLocation(), diag::note_member_declared_here)
1116 << DN;
Gor Nishanov6a470682017-05-22 20:22:23 +00001117 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1118 << Fn.getFirstCoroutineStmtKeyword();
Eric Fiselierbee782b2017-04-03 19:21:00 +00001119 return false;
Gor Nishanov6a470682017-05-22 20:22:23 +00001120 }
Gor Nishanov3aa9eb32017-03-27 23:36:59 +00001121
1122 this->ReturnStmtOnAllocFailure = ReturnStmt.get();
1123 return true;
1124}
1125
Eric Fiselierbee782b2017-04-03 19:21:00 +00001126bool CoroutineStmtBuilder::makeNewAndDeleteExpr() {
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001127 // Form and check allocation and deallocation calls.
Eric Fiselierbee782b2017-04-03 19:21:00 +00001128 assert(!IsPromiseDependentType &&
1129 "cannot make statement while the promise type is dependent");
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001130 QualType PromiseType = Fn.CoroutinePromise->getType();
Gor Nishanov8df64e92016-10-27 16:28:31 +00001131
1132 if (S.RequireCompleteType(Loc, PromiseType, diag::err_incomplete_type))
1133 return false;
1134
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001135 const bool RequiresNoThrowAlloc = ReturnStmtOnAllocFailure != nullptr;
1136
Brian Gesiak98606222018-02-15 20:37:22 +00001137 // [dcl.fct.def.coroutine]/7
1138 // Lookup allocation functions using a parameter list composed of the
1139 // requested size of the coroutine state being allocated, followed by
1140 // the coroutine function's arguments. If a matching allocation function
1141 // exists, use it. Otherwise, use an allocation function that just takes
1142 // the requested size.
Gor Nishanov8df64e92016-10-27 16:28:31 +00001143
1144 FunctionDecl *OperatorNew = nullptr;
1145 FunctionDecl *OperatorDelete = nullptr;
1146 FunctionDecl *UnusedResult = nullptr;
1147 bool PassAlignment = false;
Eric Fiselierf747f532017-04-18 05:08:08 +00001148 SmallVector<Expr *, 1> PlacementArgs;
Gor Nishanov8df64e92016-10-27 16:28:31 +00001149
Brian Gesiak98606222018-02-15 20:37:22 +00001150 // [dcl.fct.def.coroutine]/7
1151 // "The allocation function’s name is looked up in the scope of P.
1152 // [...] If the lookup finds an allocation function in the scope of P,
1153 // overload resolution is performed on a function call created by assembling
1154 // an argument list. The first argument is the amount of space requested,
1155 // and has type std::size_t. The lvalues p1 ... pn are the succeeding
1156 // arguments."
1157 //
1158 // ...where "p1 ... pn" are defined earlier as:
1159 //
1160 // [dcl.fct.def.coroutine]/3
1161 // "For a coroutine f that is a non-static member function, let P1 denote the
1162 // type of the implicit object parameter (13.3.1) and P2 ... Pn be the types
1163 // of the function parameters; otherwise let P1 ... Pn be the types of the
1164 // function parameters. Let p1 ... pn be lvalues denoting those objects."
1165 if (auto *MD = dyn_cast<CXXMethodDecl>(&FD)) {
1166 if (MD->isInstance() && !isLambdaCallOperator(MD)) {
1167 ExprResult ThisExpr = S.ActOnCXXThis(Loc);
1168 if (ThisExpr.isInvalid())
1169 return false;
1170 ThisExpr = S.CreateBuiltinUnaryOp(Loc, UO_Deref, ThisExpr.get());
1171 if (ThisExpr.isInvalid())
1172 return false;
1173 PlacementArgs.push_back(ThisExpr.get());
1174 }
1175 }
1176 for (auto *PD : FD.parameters()) {
1177 if (PD->getType()->isDependentType())
1178 continue;
1179
1180 // Build a reference to the parameter.
1181 auto PDLoc = PD->getLocation();
1182 ExprResult PDRefExpr =
1183 S.BuildDeclRefExpr(PD, PD->getOriginalType().getNonReferenceType(),
1184 ExprValueKind::VK_LValue, PDLoc);
1185 if (PDRefExpr.isInvalid())
1186 return false;
1187
1188 PlacementArgs.push_back(PDRefExpr.get());
1189 }
Brian Gesiakcb024022018-04-01 22:59:22 +00001190 S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Class,
1191 /*DeleteScope*/ Sema::AFS_Both, PromiseType,
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001192 /*isArray*/ false, PassAlignment, PlacementArgs,
Brian Gesiak98606222018-02-15 20:37:22 +00001193 OperatorNew, UnusedResult, /*Diagnose*/ false);
1194
1195 // [dcl.fct.def.coroutine]/7
1196 // "If no matching function is found, overload resolution is performed again
1197 // on a function call created by passing just the amount of space required as
1198 // an argument of type std::size_t."
1199 if (!OperatorNew && !PlacementArgs.empty()) {
1200 PlacementArgs.clear();
Brian Gesiakcb024022018-04-01 22:59:22 +00001201 S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Class,
1202 /*DeleteScope*/ Sema::AFS_Both, PromiseType,
1203 /*isArray*/ false, PassAlignment, PlacementArgs,
1204 OperatorNew, UnusedResult, /*Diagnose*/ false);
1205 }
1206
1207 // [dcl.fct.def.coroutine]/7
1208 // "The allocation function’s name is looked up in the scope of P. If this
1209 // lookup fails, the allocation function’s name is looked up in the global
1210 // scope."
1211 if (!OperatorNew) {
1212 S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Global,
1213 /*DeleteScope*/ Sema::AFS_Both, PromiseType,
1214 /*isArray*/ false, PassAlignment, PlacementArgs,
1215 OperatorNew, UnusedResult);
Brian Gesiak98606222018-02-15 20:37:22 +00001216 }
Gor Nishanov8df64e92016-10-27 16:28:31 +00001217
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001218 bool IsGlobalOverload =
1219 OperatorNew && !isa<CXXRecordDecl>(OperatorNew->getDeclContext());
1220 // If we didn't find a class-local new declaration and non-throwing new
1221 // was is required then we need to lookup the non-throwing global operator
1222 // instead.
1223 if (RequiresNoThrowAlloc && (!OperatorNew || IsGlobalOverload)) {
1224 auto *StdNoThrow = buildStdNoThrowDeclRef(S, Loc);
1225 if (!StdNoThrow)
1226 return false;
Eric Fiselierf747f532017-04-18 05:08:08 +00001227 PlacementArgs = {StdNoThrow};
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001228 OperatorNew = nullptr;
Brian Gesiakcb024022018-04-01 22:59:22 +00001229 S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Both,
1230 /*DeleteScope*/ Sema::AFS_Both, PromiseType,
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001231 /*isArray*/ false, PassAlignment, PlacementArgs,
1232 OperatorNew, UnusedResult);
1233 }
Gor Nishanov8df64e92016-10-27 16:28:31 +00001234
Brian Gesiak98606222018-02-15 20:37:22 +00001235 if (!OperatorNew)
1236 return false;
Eric Fiselierc5128752017-04-18 05:30:39 +00001237
1238 if (RequiresNoThrowAlloc) {
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001239 const auto *FT = OperatorNew->getType()->getAs<FunctionProtoType>();
Richard Smitheaf11ad2018-05-03 03:58:32 +00001240 if (!FT->isNothrow(/*ResultIfDependent*/ false)) {
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001241 S.Diag(OperatorNew->getLocation(),
1242 diag::err_coroutine_promise_new_requires_nothrow)
1243 << OperatorNew;
1244 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
1245 << OperatorNew;
1246 return false;
1247 }
1248 }
1249
1250 if ((OperatorDelete = findDeleteForPromise(S, Loc, PromiseType)) == nullptr)
Gor Nishanov8df64e92016-10-27 16:28:31 +00001251 return false;
1252
1253 Expr *FramePtr =
1254 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_frame, {});
1255
1256 Expr *FrameSize =
1257 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_size, {});
1258
1259 // Make new call.
1260
1261 ExprResult NewRef =
1262 S.BuildDeclRefExpr(OperatorNew, OperatorNew->getType(), VK_LValue, Loc);
1263 if (NewRef.isInvalid())
1264 return false;
1265
Eric Fiselierf747f532017-04-18 05:08:08 +00001266 SmallVector<Expr *, 2> NewArgs(1, FrameSize);
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001267 for (auto Arg : PlacementArgs)
1268 NewArgs.push_back(Arg);
1269
Gor Nishanov8df64e92016-10-27 16:28:31 +00001270 ExprResult NewExpr =
Richard Smith255b85f2019-05-08 01:36:36 +00001271 S.BuildCallExpr(S.getCurScope(), NewRef.get(), Loc, NewArgs, Loc);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00001272 NewExpr = S.ActOnFinishFullExpr(NewExpr.get(), /*DiscardedValue*/ false);
Gor Nishanov8df64e92016-10-27 16:28:31 +00001273 if (NewExpr.isInvalid())
1274 return false;
1275
Gor Nishanov8df64e92016-10-27 16:28:31 +00001276 // Make delete call.
1277
1278 QualType OpDeleteQualType = OperatorDelete->getType();
1279
1280 ExprResult DeleteRef =
1281 S.BuildDeclRefExpr(OperatorDelete, OpDeleteQualType, VK_LValue, Loc);
1282 if (DeleteRef.isInvalid())
1283 return false;
1284
1285 Expr *CoroFree =
1286 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_free, {FramePtr});
1287
1288 SmallVector<Expr *, 2> DeleteArgs{CoroFree};
1289
1290 // Check if we need to pass the size.
1291 const auto *OpDeleteType =
1292 OpDeleteQualType.getTypePtr()->getAs<FunctionProtoType>();
1293 if (OpDeleteType->getNumParams() > 1)
1294 DeleteArgs.push_back(FrameSize);
1295
1296 ExprResult DeleteExpr =
Richard Smith255b85f2019-05-08 01:36:36 +00001297 S.BuildCallExpr(S.getCurScope(), DeleteRef.get(), Loc, DeleteArgs, Loc);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00001298 DeleteExpr =
1299 S.ActOnFinishFullExpr(DeleteExpr.get(), /*DiscardedValue*/ false);
Gor Nishanov8df64e92016-10-27 16:28:31 +00001300 if (DeleteExpr.isInvalid())
1301 return false;
1302
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001303 this->Allocate = NewExpr.get();
1304 this->Deallocate = DeleteExpr.get();
Gor Nishanov8df64e92016-10-27 16:28:31 +00001305
1306 return true;
1307}
1308
Eric Fiselierbee782b2017-04-03 19:21:00 +00001309bool CoroutineStmtBuilder::makeOnFallthrough() {
1310 assert(!IsPromiseDependentType &&
1311 "cannot make statement while the promise type is dependent");
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001312
1313 // [dcl.fct.def.coroutine]/4
1314 // The unqualified-ids 'return_void' and 'return_value' are looked up in
1315 // the scope of class P. If both are found, the program is ill-formed.
Eric Fiselierfc50f622017-05-25 14:59:39 +00001316 bool HasRVoid, HasRValue;
1317 LookupResult LRVoid =
1318 lookupMember(S, "return_void", PromiseRecordDecl, Loc, HasRVoid);
1319 LookupResult LRValue =
1320 lookupMember(S, "return_value", PromiseRecordDecl, Loc, HasRValue);
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001321
Eric Fiselier709d1b32016-10-27 07:30:31 +00001322 StmtResult Fallthrough;
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001323 if (HasRVoid && HasRValue) {
1324 // FIXME Improve this diagnostic
Eric Fiselierfc50f622017-05-25 14:59:39 +00001325 S.Diag(FD.getLocation(),
1326 diag::err_coroutine_promise_incompatible_return_functions)
1327 << PromiseRecordDecl;
1328 S.Diag(LRVoid.getRepresentativeDecl()->getLocation(),
1329 diag::note_member_first_declared_here)
1330 << LRVoid.getLookupName();
1331 S.Diag(LRValue.getRepresentativeDecl()->getLocation(),
1332 diag::note_member_first_declared_here)
1333 << LRValue.getLookupName();
1334 return false;
1335 } else if (!HasRVoid && !HasRValue) {
1336 // FIXME: The PDTS currently specifies this case as UB, not ill-formed.
1337 // However we still diagnose this as an error since until the PDTS is fixed.
1338 S.Diag(FD.getLocation(),
1339 diag::err_coroutine_promise_requires_return_function)
1340 << PromiseRecordDecl;
1341 S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here)
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001342 << PromiseRecordDecl;
1343 return false;
1344 } else if (HasRVoid) {
1345 // If the unqualified-id return_void is found, flowing off the end of a
1346 // coroutine is equivalent to a co_return with no operand. Otherwise,
1347 // flowing off the end of a coroutine results in undefined behavior.
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001348 Fallthrough = S.BuildCoreturnStmt(FD.getLocation(), nullptr,
1349 /*IsImplicit*/false);
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001350 Fallthrough = S.ActOnFinishFullStmt(Fallthrough.get());
1351 if (Fallthrough.isInvalid())
1352 return false;
Eric Fiselier709d1b32016-10-27 07:30:31 +00001353 }
Richard Smith2af65c42015-11-24 02:34:39 +00001354
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001355 this->OnFallthrough = Fallthrough.get();
1356 return true;
1357}
1358
Eric Fiselierbee782b2017-04-03 19:21:00 +00001359bool CoroutineStmtBuilder::makeOnException() {
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001360 // Try to form 'p.unhandled_exception();'
Eric Fiselierbee782b2017-04-03 19:21:00 +00001361 assert(!IsPromiseDependentType &&
1362 "cannot make statement while the promise type is dependent");
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001363
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001364 const bool RequireUnhandledException = S.getLangOpts().CXXExceptions;
1365
1366 if (!lookupMember(S, "unhandled_exception", PromiseRecordDecl, Loc)) {
1367 auto DiagID =
1368 RequireUnhandledException
1369 ? diag::err_coroutine_promise_unhandled_exception_required
1370 : diag::
1371 warn_coroutine_promise_unhandled_exception_required_with_exceptions;
1372 S.Diag(Loc, DiagID) << PromiseRecordDecl;
Gor Nishanov29ff6382017-05-24 14:34:19 +00001373 S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here)
1374 << PromiseRecordDecl;
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001375 return !RequireUnhandledException;
1376 }
1377
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001378 // If exceptions are disabled, don't try to build OnException.
1379 if (!S.getLangOpts().CXXExceptions)
1380 return true;
1381
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001382 ExprResult UnhandledException = buildPromiseCall(S, Fn.CoroutinePromise, Loc,
1383 "unhandled_exception", None);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00001384 UnhandledException = S.ActOnFinishFullExpr(UnhandledException.get(), Loc,
1385 /*DiscardedValue*/ false);
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001386 if (UnhandledException.isInvalid())
1387 return false;
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001388
Gor Nishanov5b050e42017-05-22 22:33:17 +00001389 // Since the body of the coroutine will be wrapped in try-catch, it will
1390 // be incompatible with SEH __try if present in a function.
1391 if (!S.getLangOpts().Borland && Fn.FirstSEHTryLoc.isValid()) {
1392 S.Diag(Fn.FirstSEHTryLoc, diag::err_seh_in_a_coroutine_with_cxx_exceptions);
1393 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1394 << Fn.getFirstCoroutineStmtKeyword();
1395 return false;
1396 }
1397
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001398 this->OnException = UnhandledException.get();
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001399 return true;
1400}
1401
Eric Fiselierbee782b2017-04-03 19:21:00 +00001402bool CoroutineStmtBuilder::makeReturnObject() {
Richard Smith2af65c42015-11-24 02:34:39 +00001403 // Build implicit 'p.get_return_object()' expression and form initialization
1404 // of return type from it.
1405 ExprResult ReturnObject =
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001406 buildPromiseCall(S, Fn.CoroutinePromise, Loc, "get_return_object", None);
Richard Smith2af65c42015-11-24 02:34:39 +00001407 if (ReturnObject.isInvalid())
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001408 return false;
Richard Smith2af65c42015-11-24 02:34:39 +00001409
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001410 this->ReturnValue = ReturnObject.get();
1411 return true;
1412}
1413
Gor Nishanov6a470682017-05-22 20:22:23 +00001414static void noteMemberDeclaredHere(Sema &S, Expr *E, FunctionScopeInfo &Fn) {
1415 if (auto *MbrRef = dyn_cast<CXXMemberCallExpr>(E)) {
1416 auto *MethodDecl = MbrRef->getMethodDecl();
Eric Fiselierfc50f622017-05-25 14:59:39 +00001417 S.Diag(MethodDecl->getLocation(), diag::note_member_declared_here)
1418 << MethodDecl;
Gor Nishanov6a470682017-05-22 20:22:23 +00001419 }
1420 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1421 << Fn.getFirstCoroutineStmtKeyword();
1422}
1423
1424bool CoroutineStmtBuilder::makeGroDeclAndReturnStmt() {
1425 assert(!IsPromiseDependentType &&
1426 "cannot make statement while the promise type is dependent");
1427 assert(this->ReturnValue && "ReturnValue must be already formed");
1428
1429 QualType const GroType = this->ReturnValue->getType();
1430 assert(!GroType->isDependentType() &&
1431 "get_return_object type must no longer be dependent");
1432
1433 QualType const FnRetType = FD.getReturnType();
1434 assert(!FnRetType->isDependentType() &&
1435 "get_return_object type must no longer be dependent");
1436
1437 if (FnRetType->isVoidType()) {
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00001438 ExprResult Res =
1439 S.ActOnFinishFullExpr(this->ReturnValue, Loc, /*DiscardedValue*/ false);
Gor Nishanov6a470682017-05-22 20:22:23 +00001440 if (Res.isInvalid())
1441 return false;
1442
1443 this->ResultDecl = Res.get();
1444 return true;
1445 }
1446
1447 if (GroType->isVoidType()) {
1448 // Trigger a nice error message.
1449 InitializedEntity Entity =
1450 InitializedEntity::InitializeResult(Loc, FnRetType, false);
1451 S.PerformMoveOrCopyInitialization(Entity, nullptr, FnRetType, ReturnValue);
1452 noteMemberDeclaredHere(S, ReturnValue, Fn);
1453 return false;
1454 }
1455
1456 auto *GroDecl = VarDecl::Create(
1457 S.Context, &FD, FD.getLocation(), FD.getLocation(),
1458 &S.PP.getIdentifierTable().get("__coro_gro"), GroType,
1459 S.Context.getTrivialTypeSourceInfo(GroType, Loc), SC_None);
1460
1461 S.CheckVariableDeclarationType(GroDecl);
1462 if (GroDecl->isInvalidDecl())
1463 return false;
1464
1465 InitializedEntity Entity = InitializedEntity::InitializeVariable(GroDecl);
1466 ExprResult Res = S.PerformMoveOrCopyInitialization(Entity, nullptr, GroType,
1467 this->ReturnValue);
1468 if (Res.isInvalid())
1469 return false;
1470
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00001471 Res = S.ActOnFinishFullExpr(Res.get(), /*DiscardedValue*/ false);
Gor Nishanov6a470682017-05-22 20:22:23 +00001472 if (Res.isInvalid())
1473 return false;
1474
Gor Nishanov6a470682017-05-22 20:22:23 +00001475 S.AddInitializerToDecl(GroDecl, Res.get(),
1476 /*DirectInit=*/false);
1477
1478 S.FinalizeDeclaration(GroDecl);
1479
1480 // Form a declaration statement for the return declaration, so that AST
1481 // visitors can more easily find it.
1482 StmtResult GroDeclStmt =
1483 S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(GroDecl), Loc, Loc);
1484 if (GroDeclStmt.isInvalid())
1485 return false;
1486
1487 this->ResultDecl = GroDeclStmt.get();
1488
1489 ExprResult declRef = S.BuildDeclRefExpr(GroDecl, GroType, VK_LValue, Loc);
1490 if (declRef.isInvalid())
1491 return false;
1492
1493 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, declRef.get());
1494 if (ReturnStmt.isInvalid()) {
1495 noteMemberDeclaredHere(S, ReturnValue, Fn);
1496 return false;
1497 }
Eric Fiselier8ed97272018-02-01 23:47:54 +00001498 if (cast<clang::ReturnStmt>(ReturnStmt.get())->getNRVOCandidate() == GroDecl)
1499 GroDecl->setNRVOVariable(true);
Gor Nishanov6a470682017-05-22 20:22:23 +00001500
1501 this->ReturnStmt = ReturnStmt.get();
1502 return true;
1503}
1504
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001505// Create a static_cast\<T&&>(expr).
1506static Expr *castForMoving(Sema &S, Expr *E, QualType T = QualType()) {
1507 if (T.isNull())
1508 T = E->getType();
1509 QualType TargetType = S.BuildReferenceType(
1510 T, /*SpelledAsLValue*/ false, SourceLocation(), DeclarationName());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001511 SourceLocation ExprLoc = E->getBeginLoc();
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001512 TypeSourceInfo *TargetLoc =
1513 S.Context.getTrivialTypeSourceInfo(TargetType, ExprLoc);
1514
1515 return S
1516 .BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
1517 SourceRange(ExprLoc, ExprLoc), E->getSourceRange())
1518 .get();
1519}
1520
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001521/// Build a variable declaration for move parameter.
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001522static VarDecl *buildVarDecl(Sema &S, SourceLocation Loc, QualType Type,
Eric Fiselierde7943b2017-06-03 00:22:18 +00001523 IdentifierInfo *II) {
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001524 TypeSourceInfo *TInfo = S.Context.getTrivialTypeSourceInfo(Type, Loc);
Brian Gesiak61f4ac92018-01-24 22:15:42 +00001525 VarDecl *Decl = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, II, Type,
1526 TInfo, SC_None);
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001527 Decl->setImplicit();
1528 return Decl;
1529}
1530
Brian Gesiak61f4ac92018-01-24 22:15:42 +00001531// Build statements that move coroutine function parameters to the coroutine
1532// frame, and store them on the function scope info.
1533bool Sema::buildCoroutineParameterMoves(SourceLocation Loc) {
1534 assert(isa<FunctionDecl>(CurContext) && "not in a function scope");
1535 auto *FD = cast<FunctionDecl>(CurContext);
1536
1537 auto *ScopeInfo = getCurFunction();
1538 assert(ScopeInfo->CoroutineParameterMoves.empty() &&
1539 "Should not build parameter moves twice");
1540
1541 for (auto *PD : FD->parameters()) {
1542 if (PD->getType()->isDependentType())
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001543 continue;
1544
Brian Gesiak98606222018-02-15 20:37:22 +00001545 ExprResult PDRefExpr =
1546 BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
1547 ExprValueKind::VK_LValue, Loc); // FIXME: scope?
1548 if (PDRefExpr.isInvalid())
1549 return false;
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001550
Brian Gesiak98606222018-02-15 20:37:22 +00001551 Expr *CExpr = nullptr;
1552 if (PD->getType()->getAsCXXRecordDecl() ||
1553 PD->getType()->isRValueReferenceType())
1554 CExpr = castForMoving(*this, PDRefExpr.get());
1555 else
1556 CExpr = PDRefExpr.get();
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001557
Brian Gesiak98606222018-02-15 20:37:22 +00001558 auto D = buildVarDecl(*this, Loc, PD->getType(), PD->getIdentifier());
1559 AddInitializerToDecl(D, CExpr, /*DirectInit=*/true);
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001560
Brian Gesiak98606222018-02-15 20:37:22 +00001561 // Convert decl to a statement.
1562 StmtResult Stmt = ActOnDeclStmt(ConvertDeclToDeclGroup(D), Loc, Loc);
1563 if (Stmt.isInvalid())
1564 return false;
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001565
Brian Gesiak98606222018-02-15 20:37:22 +00001566 ScopeInfo->CoroutineParameterMoves.insert(std::make_pair(PD, Stmt.get()));
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001567 }
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001568 return true;
Richard Smithcfd53b42015-10-22 06:13:50 +00001569}
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001570
1571StmtResult Sema::BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
1572 CoroutineBodyStmt *Res = CoroutineBodyStmt::Create(Context, Args);
1573 if (!Res)
1574 return StmtError();
1575 return Res;
1576}
Brian Gesiak3e65d9a2018-07-14 18:21:44 +00001577
1578ClassTemplateDecl *Sema::lookupCoroutineTraits(SourceLocation KwLoc,
1579 SourceLocation FuncLoc) {
1580 if (!StdCoroutineTraitsCache) {
1581 if (auto StdExp = lookupStdExperimentalNamespace()) {
1582 LookupResult Result(*this,
1583 &PP.getIdentifierTable().get("coroutine_traits"),
1584 FuncLoc, LookupOrdinaryName);
1585 if (!LookupQualifiedName(Result, StdExp)) {
1586 Diag(KwLoc, diag::err_implied_coroutine_type_not_found)
1587 << "std::experimental::coroutine_traits";
1588 return nullptr;
1589 }
1590 if (!(StdCoroutineTraitsCache =
1591 Result.getAsSingle<ClassTemplateDecl>())) {
1592 Result.suppressDiagnostics();
1593 NamedDecl *Found = *Result.begin();
1594 Diag(Found->getLocation(), diag::err_malformed_std_coroutine_traits);
1595 return nullptr;
1596 }
1597 }
1598 }
1599 return StdCoroutineTraitsCache;
1600}