blob: 009380df0e1a61efb217eb07eea3f4eaddb52fa4 [file] [log] [blame]
Richard Smithcfd53b42015-10-22 06:13:50 +00001//===--- SemaCoroutines.cpp - Semantic Analysis for Coroutines ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ Coroutines.
11//
12//===----------------------------------------------------------------------===//
13
Eric Fiselierbee782b2017-04-03 19:21:00 +000014#include "CoroutineStmtBuilder.h"
Richard Smith9f690bd2015-10-27 06:02:45 +000015#include "clang/AST/Decl.h"
16#include "clang/AST/ExprCXX.h"
17#include "clang/AST/StmtCXX.h"
18#include "clang/Lex/Preprocessor.h"
Richard Smith2af65c42015-11-24 02:34:39 +000019#include "clang/Sema/Initialization.h"
Richard Smith9f690bd2015-10-27 06:02:45 +000020#include "clang/Sema/Overload.h"
Eric Fiselierbee782b2017-04-03 19:21:00 +000021#include "clang/Sema/SemaInternal.h"
22
Richard Smithcfd53b42015-10-22 06:13:50 +000023using namespace clang;
24using namespace sema;
25
Eric Fiselierfc50f622017-05-25 14:59:39 +000026static LookupResult lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD,
27 SourceLocation Loc, bool &Res) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +000028 DeclarationName DN = S.PP.getIdentifierInfo(Name);
29 LookupResult LR(S, DN, Loc, Sema::LookupMemberName);
30 // Suppress diagnostics when a private member is selected. The same warnings
31 // will be produced again when building the call.
32 LR.suppressDiagnostics();
Eric Fiselierfc50f622017-05-25 14:59:39 +000033 Res = S.LookupQualifiedName(LR, RD);
34 return LR;
35}
36
37static bool lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD,
38 SourceLocation Loc) {
39 bool Res;
40 lookupMember(S, Name, RD, Loc, Res);
41 return Res;
Eric Fiselier20f25cb2017-03-06 23:38:15 +000042}
43
Richard Smith9f690bd2015-10-27 06:02:45 +000044/// Look up the std::coroutine_traits<...>::promise_type for the given
45/// function type.
46static QualType lookupPromiseType(Sema &S, const FunctionProtoType *FnType,
Eric Fiselier89bf0e72017-03-06 22:52:28 +000047 SourceLocation KwLoc,
48 SourceLocation FuncLoc) {
Richard Smith9f690bd2015-10-27 06:02:45 +000049 // FIXME: Cache std::coroutine_traits once we've found it.
Gor Nishanov3e048bb2016-10-04 00:31:16 +000050 NamespaceDecl *StdExp = S.lookupStdExperimentalNamespace();
51 if (!StdExp) {
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +000052 S.Diag(KwLoc, diag::err_implied_coroutine_type_not_found)
53 << "std::experimental::coroutine_traits";
Richard Smith9f690bd2015-10-27 06:02:45 +000054 return QualType();
55 }
56
57 LookupResult Result(S, &S.PP.getIdentifierTable().get("coroutine_traits"),
Eric Fiselier89bf0e72017-03-06 22:52:28 +000058 FuncLoc, Sema::LookupOrdinaryName);
Gor Nishanov3e048bb2016-10-04 00:31:16 +000059 if (!S.LookupQualifiedName(Result, StdExp)) {
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +000060 S.Diag(KwLoc, diag::err_implied_coroutine_type_not_found)
61 << "std::experimental::coroutine_traits";
Richard Smith9f690bd2015-10-27 06:02:45 +000062 return QualType();
63 }
64
65 ClassTemplateDecl *CoroTraits = Result.getAsSingle<ClassTemplateDecl>();
66 if (!CoroTraits) {
67 Result.suppressDiagnostics();
68 // We found something weird. Complain about the first thing we found.
69 NamedDecl *Found = *Result.begin();
70 S.Diag(Found->getLocation(), diag::err_malformed_std_coroutine_traits);
71 return QualType();
72 }
73
74 // Form template argument list for coroutine_traits<R, P1, P2, ...>.
Eric Fiselier89bf0e72017-03-06 22:52:28 +000075 TemplateArgumentListInfo Args(KwLoc, KwLoc);
Richard Smith9f690bd2015-10-27 06:02:45 +000076 Args.addArgument(TemplateArgumentLoc(
77 TemplateArgument(FnType->getReturnType()),
Eric Fiselier89bf0e72017-03-06 22:52:28 +000078 S.Context.getTrivialTypeSourceInfo(FnType->getReturnType(), KwLoc)));
Richard Smith71d403e2015-11-22 07:33:28 +000079 // FIXME: If the function is a non-static member function, add the type
80 // of the implicit object parameter before the formal parameters.
Richard Smith9f690bd2015-10-27 06:02:45 +000081 for (QualType T : FnType->getParamTypes())
82 Args.addArgument(TemplateArgumentLoc(
Eric Fiselier89bf0e72017-03-06 22:52:28 +000083 TemplateArgument(T), S.Context.getTrivialTypeSourceInfo(T, KwLoc)));
Richard Smith9f690bd2015-10-27 06:02:45 +000084
85 // Build the template-id.
86 QualType CoroTrait =
Eric Fiselier89bf0e72017-03-06 22:52:28 +000087 S.CheckTemplateIdType(TemplateName(CoroTraits), KwLoc, Args);
Richard Smith9f690bd2015-10-27 06:02:45 +000088 if (CoroTrait.isNull())
89 return QualType();
Eric Fiselier89bf0e72017-03-06 22:52:28 +000090 if (S.RequireCompleteType(KwLoc, CoroTrait,
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +000091 diag::err_coroutine_type_missing_specialization))
Richard Smith9f690bd2015-10-27 06:02:45 +000092 return QualType();
93
Eric Fiselier89bf0e72017-03-06 22:52:28 +000094 auto *RD = CoroTrait->getAsCXXRecordDecl();
Richard Smith9f690bd2015-10-27 06:02:45 +000095 assert(RD && "specialization of class template is not a class?");
96
97 // Look up the ::promise_type member.
Eric Fiselier89bf0e72017-03-06 22:52:28 +000098 LookupResult R(S, &S.PP.getIdentifierTable().get("promise_type"), KwLoc,
Richard Smith9f690bd2015-10-27 06:02:45 +000099 Sema::LookupOrdinaryName);
100 S.LookupQualifiedName(R, RD);
101 auto *Promise = R.getAsSingle<TypeDecl>();
102 if (!Promise) {
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000103 S.Diag(FuncLoc,
104 diag::err_implied_std_coroutine_traits_promise_type_not_found)
Gor Nishanov8df64e92016-10-27 16:28:31 +0000105 << RD;
Richard Smith9f690bd2015-10-27 06:02:45 +0000106 return QualType();
107 }
Richard Smith9f690bd2015-10-27 06:02:45 +0000108 // The promise type is required to be a class type.
109 QualType PromiseType = S.Context.getTypeDeclType(Promise);
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000110
111 auto buildElaboratedType = [&]() {
Gor Nishanov3e048bb2016-10-04 00:31:16 +0000112 auto *NNS = NestedNameSpecifier::Create(S.Context, nullptr, StdExp);
Richard Smith9b2f53e2015-11-19 02:36:35 +0000113 NNS = NestedNameSpecifier::Create(S.Context, NNS, false,
114 CoroTrait.getTypePtr());
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000115 return S.Context.getElaboratedType(ETK_None, NNS, PromiseType);
116 };
Richard Smith9b2f53e2015-11-19 02:36:35 +0000117
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000118 if (!PromiseType->getAsCXXRecordDecl()) {
119 S.Diag(FuncLoc,
120 diag::err_implied_std_coroutine_traits_promise_type_not_class)
121 << buildElaboratedType();
Richard Smith9f690bd2015-10-27 06:02:45 +0000122 return QualType();
123 }
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000124 if (S.RequireCompleteType(FuncLoc, buildElaboratedType(),
125 diag::err_coroutine_promise_type_incomplete))
126 return QualType();
Richard Smith9f690bd2015-10-27 06:02:45 +0000127
128 return PromiseType;
129}
130
Gor Nishanov29ff6382017-05-24 14:34:19 +0000131/// Look up the std::experimental::coroutine_handle<PromiseType>.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000132static QualType lookupCoroutineHandleType(Sema &S, QualType PromiseType,
133 SourceLocation Loc) {
134 if (PromiseType.isNull())
135 return QualType();
136
137 NamespaceDecl *StdExp = S.lookupStdExperimentalNamespace();
138 assert(StdExp && "Should already be diagnosed");
139
140 LookupResult Result(S, &S.PP.getIdentifierTable().get("coroutine_handle"),
141 Loc, Sema::LookupOrdinaryName);
142 if (!S.LookupQualifiedName(Result, StdExp)) {
143 S.Diag(Loc, diag::err_implied_coroutine_type_not_found)
144 << "std::experimental::coroutine_handle";
145 return QualType();
146 }
147
148 ClassTemplateDecl *CoroHandle = Result.getAsSingle<ClassTemplateDecl>();
149 if (!CoroHandle) {
150 Result.suppressDiagnostics();
151 // We found something weird. Complain about the first thing we found.
152 NamedDecl *Found = *Result.begin();
153 S.Diag(Found->getLocation(), diag::err_malformed_std_coroutine_handle);
154 return QualType();
155 }
156
157 // Form template argument list for coroutine_handle<Promise>.
158 TemplateArgumentListInfo Args(Loc, Loc);
159 Args.addArgument(TemplateArgumentLoc(
160 TemplateArgument(PromiseType),
161 S.Context.getTrivialTypeSourceInfo(PromiseType, Loc)));
162
163 // Build the template-id.
164 QualType CoroHandleType =
165 S.CheckTemplateIdType(TemplateName(CoroHandle), Loc, Args);
166 if (CoroHandleType.isNull())
167 return QualType();
168 if (S.RequireCompleteType(Loc, CoroHandleType,
169 diag::err_coroutine_type_missing_specialization))
170 return QualType();
171
172 return CoroHandleType;
173}
174
Eric Fiselierc8efda72016-10-27 18:43:28 +0000175static bool isValidCoroutineContext(Sema &S, SourceLocation Loc,
176 StringRef Keyword) {
Richard Smith744b2242015-11-20 02:54:01 +0000177 // 'co_await' and 'co_yield' are not permitted in unevaluated operands.
178 if (S.isUnevaluatedContext()) {
179 S.Diag(Loc, diag::err_coroutine_unevaluated_context) << Keyword;
Eric Fiselierc8efda72016-10-27 18:43:28 +0000180 return false;
Richard Smith744b2242015-11-20 02:54:01 +0000181 }
Richard Smithcfd53b42015-10-22 06:13:50 +0000182
183 // Any other usage must be within a function.
184 auto *FD = dyn_cast<FunctionDecl>(S.CurContext);
185 if (!FD) {
186 S.Diag(Loc, isa<ObjCMethodDecl>(S.CurContext)
187 ? diag::err_coroutine_objc_method
188 : diag::err_coroutine_outside_function) << Keyword;
Eric Fiselierc8efda72016-10-27 18:43:28 +0000189 return false;
Richard Smithcfd53b42015-10-22 06:13:50 +0000190 }
191
Eric Fiselierc8efda72016-10-27 18:43:28 +0000192 // An enumeration for mapping the diagnostic type to the correct diagnostic
193 // selection index.
194 enum InvalidFuncDiag {
195 DiagCtor = 0,
196 DiagDtor,
197 DiagCopyAssign,
198 DiagMoveAssign,
199 DiagMain,
200 DiagConstexpr,
201 DiagAutoRet,
202 DiagVarargs,
203 };
204 bool Diagnosed = false;
205 auto DiagInvalid = [&](InvalidFuncDiag ID) {
206 S.Diag(Loc, diag::err_coroutine_invalid_func_context) << ID << Keyword;
207 Diagnosed = true;
208 return false;
209 };
210
211 // Diagnose when a constructor, destructor, copy/move assignment operator,
212 // or the function 'main' are declared as a coroutine.
213 auto *MD = dyn_cast<CXXMethodDecl>(FD);
214 if (MD && isa<CXXConstructorDecl>(MD))
215 return DiagInvalid(DiagCtor);
216 else if (MD && isa<CXXDestructorDecl>(MD))
217 return DiagInvalid(DiagDtor);
218 else if (MD && MD->isCopyAssignmentOperator())
219 return DiagInvalid(DiagCopyAssign);
220 else if (MD && MD->isMoveAssignmentOperator())
221 return DiagInvalid(DiagMoveAssign);
222 else if (FD->isMain())
223 return DiagInvalid(DiagMain);
224
225 // Emit a diagnostics for each of the following conditions which is not met.
226 if (FD->isConstexpr())
227 DiagInvalid(DiagConstexpr);
228 if (FD->getReturnType()->isUndeducedType())
229 DiagInvalid(DiagAutoRet);
230 if (FD->isVariadic())
231 DiagInvalid(DiagVarargs);
232
233 return !Diagnosed;
234}
235
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000236static ExprResult buildOperatorCoawaitLookupExpr(Sema &SemaRef, Scope *S,
237 SourceLocation Loc) {
238 DeclarationName OpName =
239 SemaRef.Context.DeclarationNames.getCXXOperatorName(OO_Coawait);
240 LookupResult Operators(SemaRef, OpName, SourceLocation(),
241 Sema::LookupOperatorName);
242 SemaRef.LookupName(Operators, S);
Eric Fiselierc8efda72016-10-27 18:43:28 +0000243
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000244 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
245 const auto &Functions = Operators.asUnresolvedSet();
246 bool IsOverloaded =
247 Functions.size() > 1 ||
248 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
249 Expr *CoawaitOp = UnresolvedLookupExpr::Create(
250 SemaRef.Context, /*NamingClass*/ nullptr, NestedNameSpecifierLoc(),
251 DeclarationNameInfo(OpName, Loc), /*RequiresADL*/ true, IsOverloaded,
252 Functions.begin(), Functions.end());
253 assert(CoawaitOp);
254 return CoawaitOp;
255}
Eric Fiselierc8efda72016-10-27 18:43:28 +0000256
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000257/// Build a call to 'operator co_await' if there is a suitable operator for
258/// the given expression.
259static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, SourceLocation Loc,
260 Expr *E,
261 UnresolvedLookupExpr *Lookup) {
262 UnresolvedSet<16> Functions;
263 Functions.append(Lookup->decls_begin(), Lookup->decls_end());
264 return SemaRef.CreateOverloadedUnaryOp(Loc, UO_Coawait, Functions, E);
265}
Eric Fiselierc8efda72016-10-27 18:43:28 +0000266
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000267static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, Scope *S,
268 SourceLocation Loc, Expr *E) {
269 ExprResult R = buildOperatorCoawaitLookupExpr(SemaRef, S, Loc);
270 if (R.isInvalid())
271 return ExprError();
272 return buildOperatorCoawaitCall(SemaRef, Loc, E,
273 cast<UnresolvedLookupExpr>(R.get()));
Richard Smithcfd53b42015-10-22 06:13:50 +0000274}
275
Gor Nishanov8df64e92016-10-27 16:28:31 +0000276static Expr *buildBuiltinCall(Sema &S, SourceLocation Loc, Builtin::ID Id,
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000277 MultiExprArg CallArgs) {
Gor Nishanov8df64e92016-10-27 16:28:31 +0000278 StringRef Name = S.Context.BuiltinInfo.getName(Id);
279 LookupResult R(S, &S.Context.Idents.get(Name), Loc, Sema::LookupOrdinaryName);
280 S.LookupName(R, S.TUScope, /*AllowBuiltinCreation=*/true);
281
282 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
283 assert(BuiltInDecl && "failed to find builtin declaration");
284
285 ExprResult DeclRef =
286 S.BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
287 assert(DeclRef.isUsable() && "Builtin reference cannot fail");
288
289 ExprResult Call =
290 S.ActOnCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
291
292 assert(!Call.isInvalid() && "Call to builtin cannot fail!");
293 return Call.get();
294}
295
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000296static ExprResult buildCoroutineHandle(Sema &S, QualType PromiseType,
297 SourceLocation Loc) {
298 QualType CoroHandleType = lookupCoroutineHandleType(S, PromiseType, Loc);
299 if (CoroHandleType.isNull())
300 return ExprError();
301
302 DeclContext *LookupCtx = S.computeDeclContext(CoroHandleType);
303 LookupResult Found(S, &S.PP.getIdentifierTable().get("from_address"), Loc,
304 Sema::LookupOrdinaryName);
305 if (!S.LookupQualifiedName(Found, LookupCtx)) {
306 S.Diag(Loc, diag::err_coroutine_handle_missing_member)
307 << "from_address";
308 return ExprError();
309 }
310
311 Expr *FramePtr =
312 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_frame, {});
313
314 CXXScopeSpec SS;
315 ExprResult FromAddr =
316 S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
317 if (FromAddr.isInvalid())
318 return ExprError();
319
320 return S.ActOnCallExpr(nullptr, FromAddr.get(), Loc, FramePtr, Loc);
321}
Richard Smithcfd53b42015-10-22 06:13:50 +0000322
Richard Smith9f690bd2015-10-27 06:02:45 +0000323struct ReadySuspendResumeResult {
Richard Smith9f690bd2015-10-27 06:02:45 +0000324 Expr *Results[3];
Gor Nishanovce43bd22017-03-11 01:30:17 +0000325 OpaqueValueExpr *OpaqueValue;
326 bool IsInvalid;
Richard Smith9f690bd2015-10-27 06:02:45 +0000327};
328
Richard Smith23da82c2015-11-20 22:40:06 +0000329static ExprResult buildMemberCall(Sema &S, Expr *Base, SourceLocation Loc,
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000330 StringRef Name, MultiExprArg Args) {
Richard Smith23da82c2015-11-20 22:40:06 +0000331 DeclarationNameInfo NameInfo(&S.PP.getIdentifierTable().get(Name), Loc);
332
333 // FIXME: Fix BuildMemberReferenceExpr to take a const CXXScopeSpec&.
334 CXXScopeSpec SS;
335 ExprResult Result = S.BuildMemberReferenceExpr(
336 Base, Base->getType(), Loc, /*IsPtr=*/false, SS,
337 SourceLocation(), nullptr, NameInfo, /*TemplateArgs=*/nullptr,
338 /*Scope=*/nullptr);
339 if (Result.isInvalid())
340 return ExprError();
341
342 return S.ActOnCallExpr(nullptr, Result.get(), Loc, Args, Loc, nullptr);
343}
344
Richard Smith9f690bd2015-10-27 06:02:45 +0000345/// Build calls to await_ready, await_suspend, and await_resume for a co_await
346/// expression.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000347static ReadySuspendResumeResult buildCoawaitCalls(Sema &S, VarDecl *CoroPromise,
348 SourceLocation Loc, Expr *E) {
Gor Nishanovce43bd22017-03-11 01:30:17 +0000349 OpaqueValueExpr *Operand = new (S.Context)
350 OpaqueValueExpr(Loc, E->getType(), VK_LValue, E->getObjectKind(), E);
351
Richard Smith9f690bd2015-10-27 06:02:45 +0000352 // Assume invalid until we see otherwise.
Gor Nishanovce43bd22017-03-11 01:30:17 +0000353 ReadySuspendResumeResult Calls = {{}, Operand, /*IsInvalid=*/true};
Richard Smith9f690bd2015-10-27 06:02:45 +0000354
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000355 ExprResult CoroHandleRes = buildCoroutineHandle(S, CoroPromise->getType(), Loc);
356 if (CoroHandleRes.isInvalid())
357 return Calls;
358 Expr *CoroHandle = CoroHandleRes.get();
359
Richard Smith9f690bd2015-10-27 06:02:45 +0000360 const StringRef Funcs[] = {"await_ready", "await_suspend", "await_resume"};
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000361 MultiExprArg Args[] = {None, CoroHandle, None};
Richard Smith9f690bd2015-10-27 06:02:45 +0000362 for (size_t I = 0, N = llvm::array_lengthof(Funcs); I != N; ++I) {
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000363 ExprResult Result = buildMemberCall(S, Operand, Loc, Funcs[I], Args[I]);
Richard Smith9f690bd2015-10-27 06:02:45 +0000364 if (Result.isInvalid())
365 return Calls;
366 Calls.Results[I] = Result.get();
367 }
368
369 Calls.IsInvalid = false;
370 return Calls;
371}
372
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000373static ExprResult buildPromiseCall(Sema &S, VarDecl *Promise,
374 SourceLocation Loc, StringRef Name,
375 MultiExprArg Args) {
376
377 // Form a reference to the promise.
378 ExprResult PromiseRef = S.BuildDeclRefExpr(
379 Promise, Promise->getType().getNonReferenceType(), VK_LValue, Loc);
380 if (PromiseRef.isInvalid())
381 return ExprError();
382
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000383 return buildMemberCall(S, PromiseRef.get(), Loc, Name, Args);
384}
385
386VarDecl *Sema::buildCoroutinePromise(SourceLocation Loc) {
387 assert(isa<FunctionDecl>(CurContext) && "not in a function scope");
388 auto *FD = cast<FunctionDecl>(CurContext);
389
390 QualType T =
391 FD->getType()->isDependentType()
392 ? Context.DependentTy
393 : lookupPromiseType(*this, FD->getType()->castAs<FunctionProtoType>(),
394 Loc, FD->getLocation());
395 if (T.isNull())
396 return nullptr;
397
398 auto *VD = VarDecl::Create(Context, FD, FD->getLocation(), FD->getLocation(),
399 &PP.getIdentifierTable().get("__promise"), T,
400 Context.getTrivialTypeSourceInfo(T, Loc), SC_None);
401 CheckVariableDeclarationType(VD);
402 if (VD->isInvalidDecl())
403 return nullptr;
404 ActOnUninitializedDecl(VD);
405 assert(!VD->isInvalidDecl());
406 return VD;
407}
408
409/// Check that this is a context in which a coroutine suspension can appear.
410static FunctionScopeInfo *checkCoroutineContext(Sema &S, SourceLocation Loc,
Eric Fiseliercac0a592017-03-11 02:35:37 +0000411 StringRef Keyword,
412 bool IsImplicit = false) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000413 if (!isValidCoroutineContext(S, Loc, Keyword))
414 return nullptr;
415
416 assert(isa<FunctionDecl>(S.CurContext) && "not in a function scope");
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000417
418 auto *ScopeInfo = S.getCurFunction();
419 assert(ScopeInfo && "missing function scope for function");
420
Eric Fiseliercac0a592017-03-11 02:35:37 +0000421 if (ScopeInfo->FirstCoroutineStmtLoc.isInvalid() && !IsImplicit)
422 ScopeInfo->setFirstCoroutineStmt(Loc, Keyword);
423
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000424 if (ScopeInfo->CoroutinePromise)
425 return ScopeInfo;
426
427 ScopeInfo->CoroutinePromise = S.buildCoroutinePromise(Loc);
428 if (!ScopeInfo->CoroutinePromise)
429 return nullptr;
430
431 return ScopeInfo;
432}
433
434static bool actOnCoroutineBodyStart(Sema &S, Scope *SC, SourceLocation KWLoc,
435 StringRef Keyword) {
436 if (!checkCoroutineContext(S, KWLoc, Keyword))
437 return false;
438 auto *ScopeInfo = S.getCurFunction();
439 assert(ScopeInfo->CoroutinePromise);
440
441 // If we have existing coroutine statements then we have already built
442 // the initial and final suspend points.
443 if (!ScopeInfo->NeedsCoroutineSuspends)
444 return true;
445
446 ScopeInfo->setNeedsCoroutineSuspends(false);
447
448 auto *Fn = cast<FunctionDecl>(S.CurContext);
449 SourceLocation Loc = Fn->getLocation();
450 // Build the initial suspend point
451 auto buildSuspends = [&](StringRef Name) mutable -> StmtResult {
452 ExprResult Suspend =
453 buildPromiseCall(S, ScopeInfo->CoroutinePromise, Loc, Name, None);
454 if (Suspend.isInvalid())
455 return StmtError();
456 Suspend = buildOperatorCoawaitCall(S, SC, Loc, Suspend.get());
457 if (Suspend.isInvalid())
458 return StmtError();
459 Suspend = S.BuildResolvedCoawaitExpr(Loc, Suspend.get(),
460 /*IsImplicit*/ true);
461 Suspend = S.ActOnFinishFullExpr(Suspend.get());
462 if (Suspend.isInvalid()) {
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000463 S.Diag(Loc, diag::note_coroutine_promise_suspend_implicitly_required)
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000464 << ((Name == "initial_suspend") ? 0 : 1);
465 S.Diag(KWLoc, diag::note_declared_coroutine_here) << Keyword;
466 return StmtError();
467 }
468 return cast<Stmt>(Suspend.get());
469 };
470
471 StmtResult InitSuspend = buildSuspends("initial_suspend");
472 if (InitSuspend.isInvalid())
473 return true;
474
475 StmtResult FinalSuspend = buildSuspends("final_suspend");
476 if (FinalSuspend.isInvalid())
477 return true;
478
479 ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());
480
481 return true;
482}
483
Richard Smith9f690bd2015-10-27 06:02:45 +0000484ExprResult Sema::ActOnCoawaitExpr(Scope *S, SourceLocation Loc, Expr *E) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000485 if (!actOnCoroutineBodyStart(*this, S, Loc, "co_await")) {
Eric Fiseliera5465282016-09-29 21:47:39 +0000486 CorrectDelayedTyposInExpr(E);
487 return ExprError();
488 }
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000489
Richard Smith10610f72015-11-20 22:57:24 +0000490 if (E->getType()->isPlaceholderType()) {
491 ExprResult R = CheckPlaceholderExpr(E);
492 if (R.isInvalid()) return ExprError();
493 E = R.get();
494 }
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000495 ExprResult Lookup = buildOperatorCoawaitLookupExpr(*this, S, Loc);
496 if (Lookup.isInvalid())
497 return ExprError();
498 return BuildUnresolvedCoawaitExpr(Loc, E,
499 cast<UnresolvedLookupExpr>(Lookup.get()));
500}
Richard Smith10610f72015-11-20 22:57:24 +0000501
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000502ExprResult Sema::BuildUnresolvedCoawaitExpr(SourceLocation Loc, Expr *E,
Eric Fiseliercac0a592017-03-11 02:35:37 +0000503 UnresolvedLookupExpr *Lookup) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000504 auto *FSI = checkCoroutineContext(*this, Loc, "co_await");
505 if (!FSI)
506 return ExprError();
507
508 if (E->getType()->isPlaceholderType()) {
509 ExprResult R = CheckPlaceholderExpr(E);
510 if (R.isInvalid())
511 return ExprError();
512 E = R.get();
513 }
514
515 auto *Promise = FSI->CoroutinePromise;
516 if (Promise->getType()->isDependentType()) {
517 Expr *Res =
518 new (Context) DependentCoawaitExpr(Loc, Context.DependentTy, E, Lookup);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000519 return Res;
520 }
521
522 auto *RD = Promise->getType()->getAsCXXRecordDecl();
523 if (lookupMember(*this, "await_transform", RD, Loc)) {
524 ExprResult R = buildPromiseCall(*this, Promise, Loc, "await_transform", E);
525 if (R.isInvalid()) {
526 Diag(Loc,
527 diag::note_coroutine_promise_implicit_await_transform_required_here)
528 << E->getSourceRange();
529 return ExprError();
530 }
531 E = R.get();
532 }
533 ExprResult Awaitable = buildOperatorCoawaitCall(*this, Loc, E, Lookup);
Richard Smith9f690bd2015-10-27 06:02:45 +0000534 if (Awaitable.isInvalid())
535 return ExprError();
Eric Fiseliera5465282016-09-29 21:47:39 +0000536
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000537 return BuildResolvedCoawaitExpr(Loc, Awaitable.get());
Richard Smith9f690bd2015-10-27 06:02:45 +0000538}
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000539
540ExprResult Sema::BuildResolvedCoawaitExpr(SourceLocation Loc, Expr *E,
541 bool IsImplicit) {
Eric Fiseliercac0a592017-03-11 02:35:37 +0000542 auto *Coroutine = checkCoroutineContext(*this, Loc, "co_await", IsImplicit);
Richard Smith744b2242015-11-20 02:54:01 +0000543 if (!Coroutine)
544 return ExprError();
Richard Smith9f690bd2015-10-27 06:02:45 +0000545
Richard Smith9f690bd2015-10-27 06:02:45 +0000546 if (E->getType()->isPlaceholderType()) {
547 ExprResult R = CheckPlaceholderExpr(E);
548 if (R.isInvalid()) return ExprError();
549 E = R.get();
550 }
551
Richard Smith10610f72015-11-20 22:57:24 +0000552 if (E->getType()->isDependentType()) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000553 Expr *Res = new (Context)
554 CoawaitExpr(Loc, Context.DependentTy, E, IsImplicit);
Richard Smith10610f72015-11-20 22:57:24 +0000555 return Res;
556 }
557
Richard Smith1f38edd2015-11-22 03:13:02 +0000558 // If the expression is a temporary, materialize it as an lvalue so that we
559 // can use it multiple times.
560 if (E->getValueKind() == VK_RValue)
Tim Shen4a05bb82016-06-21 20:29:17 +0000561 E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
Richard Smith9f690bd2015-10-27 06:02:45 +0000562
563 // Build the await_ready, await_suspend, await_resume calls.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000564 ReadySuspendResumeResult RSS =
565 buildCoawaitCalls(*this, Coroutine->CoroutinePromise, Loc, E);
Richard Smith9f690bd2015-10-27 06:02:45 +0000566 if (RSS.IsInvalid)
567 return ExprError();
568
Gor Nishanovce43bd22017-03-11 01:30:17 +0000569 Expr *Res =
570 new (Context) CoawaitExpr(Loc, E, RSS.Results[0], RSS.Results[1],
571 RSS.Results[2], RSS.OpaqueValue, IsImplicit);
Eric Fiseliercac0a592017-03-11 02:35:37 +0000572
Richard Smithcfd53b42015-10-22 06:13:50 +0000573 return Res;
574}
575
Richard Smith9f690bd2015-10-27 06:02:45 +0000576ExprResult Sema::ActOnCoyieldExpr(Scope *S, SourceLocation Loc, Expr *E) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000577 if (!actOnCoroutineBodyStart(*this, S, Loc, "co_yield")) {
Eric Fiseliera5465282016-09-29 21:47:39 +0000578 CorrectDelayedTyposInExpr(E);
Richard Smith23da82c2015-11-20 22:40:06 +0000579 return ExprError();
Eric Fiseliera5465282016-09-29 21:47:39 +0000580 }
Richard Smith23da82c2015-11-20 22:40:06 +0000581
582 // Build yield_value call.
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000583 ExprResult Awaitable = buildPromiseCall(
584 *this, getCurFunction()->CoroutinePromise, Loc, "yield_value", E);
Richard Smith9f690bd2015-10-27 06:02:45 +0000585 if (Awaitable.isInvalid())
586 return ExprError();
Richard Smith23da82c2015-11-20 22:40:06 +0000587
588 // Build 'operator co_await' call.
589 Awaitable = buildOperatorCoawaitCall(*this, S, Loc, Awaitable.get());
590 if (Awaitable.isInvalid())
591 return ExprError();
592
Richard Smith9f690bd2015-10-27 06:02:45 +0000593 return BuildCoyieldExpr(Loc, Awaitable.get());
594}
595ExprResult Sema::BuildCoyieldExpr(SourceLocation Loc, Expr *E) {
596 auto *Coroutine = checkCoroutineContext(*this, Loc, "co_yield");
Richard Smith744b2242015-11-20 02:54:01 +0000597 if (!Coroutine)
598 return ExprError();
Richard Smithcfd53b42015-10-22 06:13:50 +0000599
Richard Smith10610f72015-11-20 22:57:24 +0000600 if (E->getType()->isPlaceholderType()) {
601 ExprResult R = CheckPlaceholderExpr(E);
602 if (R.isInvalid()) return ExprError();
603 E = R.get();
604 }
605
Richard Smithd7bed4d2015-11-22 02:57:17 +0000606 if (E->getType()->isDependentType()) {
607 Expr *Res = new (Context) CoyieldExpr(Loc, Context.DependentTy, E);
Richard Smithd7bed4d2015-11-22 02:57:17 +0000608 return Res;
609 }
610
Richard Smith1f38edd2015-11-22 03:13:02 +0000611 // If the expression is a temporary, materialize it as an lvalue so that we
612 // can use it multiple times.
613 if (E->getValueKind() == VK_RValue)
Tim Shen4a05bb82016-06-21 20:29:17 +0000614 E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
Richard Smithd7bed4d2015-11-22 02:57:17 +0000615
616 // Build the await_ready, await_suspend, await_resume calls.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000617 ReadySuspendResumeResult RSS =
618 buildCoawaitCalls(*this, Coroutine->CoroutinePromise, Loc, E);
Richard Smithd7bed4d2015-11-22 02:57:17 +0000619 if (RSS.IsInvalid)
620 return ExprError();
621
622 Expr *Res = new (Context) CoyieldExpr(Loc, E, RSS.Results[0], RSS.Results[1],
Gor Nishanovce43bd22017-03-11 01:30:17 +0000623 RSS.Results[2], RSS.OpaqueValue);
Eric Fiseliercac0a592017-03-11 02:35:37 +0000624
Richard Smithcfd53b42015-10-22 06:13:50 +0000625 return Res;
626}
627
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000628StmtResult Sema::ActOnCoreturnStmt(Scope *S, SourceLocation Loc, Expr *E) {
629 if (!actOnCoroutineBodyStart(*this, S, Loc, "co_return")) {
Eric Fiseliera5465282016-09-29 21:47:39 +0000630 CorrectDelayedTyposInExpr(E);
631 return StmtError();
632 }
Richard Smith9f690bd2015-10-27 06:02:45 +0000633 return BuildCoreturnStmt(Loc, E);
634}
Gor Nishanov3e048bb2016-10-04 00:31:16 +0000635
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000636StmtResult Sema::BuildCoreturnStmt(SourceLocation Loc, Expr *E,
637 bool IsImplicit) {
Eric Fiseliercac0a592017-03-11 02:35:37 +0000638 auto *FSI = checkCoroutineContext(*this, Loc, "co_return", IsImplicit);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000639 if (!FSI)
Richard Smith71d403e2015-11-22 07:33:28 +0000640 return StmtError();
641
642 if (E && E->getType()->isPlaceholderType() &&
643 !E->getType()->isSpecificPlaceholderType(BuiltinType::Overload)) {
Richard Smith10610f72015-11-20 22:57:24 +0000644 ExprResult R = CheckPlaceholderExpr(E);
645 if (R.isInvalid()) return StmtError();
646 E = R.get();
647 }
648
Richard Smith4ba66602015-11-22 07:05:16 +0000649 // FIXME: If the operand is a reference to a variable that's about to go out
Richard Smith2af65c42015-11-24 02:34:39 +0000650 // of scope, we should treat the operand as an xvalue for this overload
Richard Smith4ba66602015-11-22 07:05:16 +0000651 // resolution.
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000652 VarDecl *Promise = FSI->CoroutinePromise;
Richard Smith4ba66602015-11-22 07:05:16 +0000653 ExprResult PC;
Eric Fiselier98131312016-10-06 21:23:38 +0000654 if (E && (isa<InitListExpr>(E) || !E->getType()->isVoidType())) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000655 PC = buildPromiseCall(*this, Promise, Loc, "return_value", E);
Richard Smith4ba66602015-11-22 07:05:16 +0000656 } else {
657 E = MakeFullDiscardedValueExpr(E).get();
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000658 PC = buildPromiseCall(*this, Promise, Loc, "return_void", None);
Richard Smith4ba66602015-11-22 07:05:16 +0000659 }
660 if (PC.isInvalid())
661 return StmtError();
662
663 Expr *PCE = ActOnFinishFullExpr(PC.get()).get();
664
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000665 Stmt *Res = new (Context) CoreturnStmt(Loc, E, PCE, IsImplicit);
Richard Smithcfd53b42015-10-22 06:13:50 +0000666 return Res;
667}
668
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000669/// Look up the std::nothrow object.
670static Expr *buildStdNoThrowDeclRef(Sema &S, SourceLocation Loc) {
671 NamespaceDecl *Std = S.getStdNamespace();
672 assert(Std && "Should already be diagnosed");
673
674 LookupResult Result(S, &S.PP.getIdentifierTable().get("nothrow"), Loc,
675 Sema::LookupOrdinaryName);
676 if (!S.LookupQualifiedName(Result, Std)) {
677 // FIXME: <experimental/coroutine> should have been included already.
678 // If we require it to include <new> then this diagnostic is no longer
679 // needed.
680 S.Diag(Loc, diag::err_implicit_coroutine_std_nothrow_type_not_found);
681 return nullptr;
682 }
683
684 // FIXME: Mark the variable as ODR used. This currently does not work
685 // likely due to the scope at in which this function is called.
686 auto *VD = Result.getAsSingle<VarDecl>();
687 if (!VD) {
688 Result.suppressDiagnostics();
689 // We found something weird. Complain about the first thing we found.
690 NamedDecl *Found = *Result.begin();
691 S.Diag(Found->getLocation(), diag::err_malformed_std_nothrow);
692 return nullptr;
693 }
694
695 ExprResult DR = S.BuildDeclRefExpr(VD, VD->getType(), VK_LValue, Loc);
696 if (DR.isInvalid())
697 return nullptr;
698
699 return DR.get();
700}
701
Gor Nishanov8df64e92016-10-27 16:28:31 +0000702// Find an appropriate delete for the promise.
703static FunctionDecl *findDeleteForPromise(Sema &S, SourceLocation Loc,
704 QualType PromiseType) {
705 FunctionDecl *OperatorDelete = nullptr;
706
707 DeclarationName DeleteName =
708 S.Context.DeclarationNames.getCXXOperatorName(OO_Delete);
709
710 auto *PointeeRD = PromiseType->getAsCXXRecordDecl();
711 assert(PointeeRD && "PromiseType must be a CxxRecordDecl type");
712
713 if (S.FindDeallocationFunction(Loc, PointeeRD, DeleteName, OperatorDelete))
714 return nullptr;
715
716 if (!OperatorDelete) {
717 // Look for a global declaration.
718 const bool CanProvideSize = S.isCompleteType(Loc, PromiseType);
719 const bool Overaligned = false;
720 OperatorDelete = S.FindUsualDeallocationFunction(Loc, CanProvideSize,
721 Overaligned, DeleteName);
722 }
723 S.MarkFunctionReferenced(Loc, OperatorDelete);
724 return OperatorDelete;
725}
726
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000727
728void Sema::CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body) {
729 FunctionScopeInfo *Fn = getCurFunction();
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000730 assert(Fn && Fn->isCoroutine() && "not a coroutine");
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000731 if (!Body) {
732 assert(FD->isInvalidDecl() &&
733 "a null body is only allowed for invalid declarations");
734 return;
735 }
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000736 // We have a function that uses coroutine keywords, but we failed to build
737 // the promise type.
738 if (!Fn->CoroutinePromise)
739 return FD->setInvalidDecl();
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000740
741 if (isa<CoroutineBodyStmt>(Body)) {
Gor Nishanov29ff6382017-05-24 14:34:19 +0000742 // Nothing todo. the body is already a transformed coroutine body statement.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000743 return;
744 }
745
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000746 // Coroutines [stmt.return]p1:
747 // A return statement shall not appear in a coroutine.
748 if (Fn->FirstReturnLoc.isValid()) {
Eric Fiseliercac0a592017-03-11 02:35:37 +0000749 assert(Fn->FirstCoroutineStmtLoc.isValid() &&
750 "first coroutine location not set");
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000751 Diag(Fn->FirstReturnLoc, diag::err_return_in_coroutine);
Eric Fiseliercac0a592017-03-11 02:35:37 +0000752 Diag(Fn->FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
753 << Fn->getFirstCoroutineStmtKeyword();
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000754 }
Eric Fiselierbee782b2017-04-03 19:21:00 +0000755 CoroutineStmtBuilder Builder(*this, *FD, *Fn, Body);
756 if (Builder.isInvalid() || !Builder.buildStatements())
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000757 return FD->setInvalidDecl();
758
759 // Build body for the coroutine wrapper statement.
760 Body = CoroutineBodyStmt::Create(Context, Builder);
761}
762
Eric Fiselierbee782b2017-04-03 19:21:00 +0000763CoroutineStmtBuilder::CoroutineStmtBuilder(Sema &S, FunctionDecl &FD,
764 sema::FunctionScopeInfo &Fn,
765 Stmt *Body)
766 : S(S), FD(FD), Fn(Fn), Loc(FD.getLocation()),
767 IsPromiseDependentType(
768 !Fn.CoroutinePromise ||
769 Fn.CoroutinePromise->getType()->isDependentType()) {
770 this->Body = Body;
771 if (!IsPromiseDependentType) {
772 PromiseRecordDecl = Fn.CoroutinePromise->getType()->getAsCXXRecordDecl();
773 assert(PromiseRecordDecl && "Type should have already been checked");
774 }
775 this->IsValid = makePromiseStmt() && makeInitialAndFinalSuspend();
776}
777
778bool CoroutineStmtBuilder::buildStatements() {
779 assert(this->IsValid && "coroutine already invalid");
780 this->IsValid = makeReturnObject() && makeParamMoves();
781 if (this->IsValid && !IsPromiseDependentType)
782 buildDependentStatements();
783 return this->IsValid;
784}
785
786bool CoroutineStmtBuilder::buildDependentStatements() {
787 assert(this->IsValid && "coroutine already invalid");
788 assert(!this->IsPromiseDependentType &&
789 "coroutine cannot have a dependent promise type");
790 this->IsValid = makeOnException() && makeOnFallthrough() &&
Gor Nishanov6a470682017-05-22 20:22:23 +0000791 makeGroDeclAndReturnStmt() && makeReturnOnAllocFailure() &&
792 makeNewAndDeleteExpr();
Eric Fiselierbee782b2017-04-03 19:21:00 +0000793 return this->IsValid;
794}
795
796bool CoroutineStmtBuilder::makePromiseStmt() {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000797 // Form a declaration statement for the promise declaration, so that AST
798 // visitors can more easily find it.
799 StmtResult PromiseStmt =
800 S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(Fn.CoroutinePromise), Loc, Loc);
801 if (PromiseStmt.isInvalid())
802 return false;
803
804 this->Promise = PromiseStmt.get();
805 return true;
806}
807
Eric Fiselierbee782b2017-04-03 19:21:00 +0000808bool CoroutineStmtBuilder::makeInitialAndFinalSuspend() {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000809 if (Fn.hasInvalidCoroutineSuspends())
810 return false;
811 this->InitialSuspend = cast<Expr>(Fn.CoroutineSuspends.first);
812 this->FinalSuspend = cast<Expr>(Fn.CoroutineSuspends.second);
813 return true;
814}
815
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000816static bool diagReturnOnAllocFailure(Sema &S, Expr *E,
817 CXXRecordDecl *PromiseRecordDecl,
818 FunctionScopeInfo &Fn) {
819 auto Loc = E->getExprLoc();
820 if (auto *DeclRef = dyn_cast_or_null<DeclRefExpr>(E)) {
821 auto *Decl = DeclRef->getDecl();
822 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Decl)) {
823 if (Method->isStatic())
824 return true;
825 else
826 Loc = Decl->getLocation();
827 }
828 }
829
830 S.Diag(
831 Loc,
832 diag::err_coroutine_promise_get_return_object_on_allocation_failure)
833 << PromiseRecordDecl;
834 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
835 << Fn.getFirstCoroutineStmtKeyword();
836 return false;
837}
838
Eric Fiselierbee782b2017-04-03 19:21:00 +0000839bool CoroutineStmtBuilder::makeReturnOnAllocFailure() {
840 assert(!IsPromiseDependentType &&
841 "cannot make statement while the promise type is dependent");
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000842
843 // [dcl.fct.def.coroutine]/8
844 // The unqualified-id get_return_object_on_allocation_failure is looked up in
845 // the scope of class P by class member access lookup (3.4.5). ...
846 // If an allocation function returns nullptr, ... the coroutine return value
847 // is obtained by a call to ... get_return_object_on_allocation_failure().
848
849 DeclarationName DN =
850 S.PP.getIdentifierInfo("get_return_object_on_allocation_failure");
851 LookupResult Found(S, DN, Loc, Sema::LookupMemberName);
Eric Fiselierbee782b2017-04-03 19:21:00 +0000852 if (!S.LookupQualifiedName(Found, PromiseRecordDecl))
853 return true;
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000854
855 CXXScopeSpec SS;
856 ExprResult DeclNameExpr =
857 S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
Eric Fiselierbee782b2017-04-03 19:21:00 +0000858 if (DeclNameExpr.isInvalid())
859 return false;
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000860
861 if (!diagReturnOnAllocFailure(S, DeclNameExpr.get(), PromiseRecordDecl, Fn))
862 return false;
863
864 ExprResult ReturnObjectOnAllocationFailure =
865 S.ActOnCallExpr(nullptr, DeclNameExpr.get(), Loc, {}, Loc);
Eric Fiselierbee782b2017-04-03 19:21:00 +0000866 if (ReturnObjectOnAllocationFailure.isInvalid())
867 return false;
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000868
Gor Nishanovc4a19082017-03-28 02:51:45 +0000869 StmtResult ReturnStmt =
870 S.BuildReturnStmt(Loc, ReturnObjectOnAllocationFailure.get());
Gor Nishanov6a470682017-05-22 20:22:23 +0000871 if (ReturnStmt.isInvalid()) {
Eric Fiselierfc50f622017-05-25 14:59:39 +0000872 S.Diag(Found.getFoundDecl()->getLocation(), diag::note_member_declared_here)
873 << DN;
Gor Nishanov6a470682017-05-22 20:22:23 +0000874 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
875 << Fn.getFirstCoroutineStmtKeyword();
Eric Fiselierbee782b2017-04-03 19:21:00 +0000876 return false;
Gor Nishanov6a470682017-05-22 20:22:23 +0000877 }
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000878
879 this->ReturnStmtOnAllocFailure = ReturnStmt.get();
880 return true;
881}
882
Eric Fiselierbee782b2017-04-03 19:21:00 +0000883bool CoroutineStmtBuilder::makeNewAndDeleteExpr() {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000884 // Form and check allocation and deallocation calls.
Eric Fiselierbee782b2017-04-03 19:21:00 +0000885 assert(!IsPromiseDependentType &&
886 "cannot make statement while the promise type is dependent");
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000887 QualType PromiseType = Fn.CoroutinePromise->getType();
Gor Nishanov8df64e92016-10-27 16:28:31 +0000888
889 if (S.RequireCompleteType(Loc, PromiseType, diag::err_incomplete_type))
890 return false;
891
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000892 const bool RequiresNoThrowAlloc = ReturnStmtOnAllocFailure != nullptr;
893
Gor Nishanov8df64e92016-10-27 16:28:31 +0000894 // FIXME: Add support for stateful allocators.
895
896 FunctionDecl *OperatorNew = nullptr;
897 FunctionDecl *OperatorDelete = nullptr;
898 FunctionDecl *UnusedResult = nullptr;
899 bool PassAlignment = false;
Eric Fiselierf747f532017-04-18 05:08:08 +0000900 SmallVector<Expr *, 1> PlacementArgs;
Gor Nishanov8df64e92016-10-27 16:28:31 +0000901
902 S.FindAllocationFunctions(Loc, SourceRange(),
903 /*UseGlobal*/ false, PromiseType,
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000904 /*isArray*/ false, PassAlignment, PlacementArgs,
905 OperatorNew, UnusedResult);
Gor Nishanov8df64e92016-10-27 16:28:31 +0000906
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000907 bool IsGlobalOverload =
908 OperatorNew && !isa<CXXRecordDecl>(OperatorNew->getDeclContext());
909 // If we didn't find a class-local new declaration and non-throwing new
910 // was is required then we need to lookup the non-throwing global operator
911 // instead.
912 if (RequiresNoThrowAlloc && (!OperatorNew || IsGlobalOverload)) {
913 auto *StdNoThrow = buildStdNoThrowDeclRef(S, Loc);
914 if (!StdNoThrow)
915 return false;
Eric Fiselierf747f532017-04-18 05:08:08 +0000916 PlacementArgs = {StdNoThrow};
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000917 OperatorNew = nullptr;
918 S.FindAllocationFunctions(Loc, SourceRange(),
919 /*UseGlobal*/ true, PromiseType,
920 /*isArray*/ false, PassAlignment, PlacementArgs,
921 OperatorNew, UnusedResult);
922 }
Gor Nishanov8df64e92016-10-27 16:28:31 +0000923
Eric Fiselierc5128752017-04-18 05:30:39 +0000924 assert(OperatorNew && "expected definition of operator new to be found");
925
926 if (RequiresNoThrowAlloc) {
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000927 const auto *FT = OperatorNew->getType()->getAs<FunctionProtoType>();
928 if (!FT->isNothrow(S.Context, /*ResultIfDependent*/ false)) {
929 S.Diag(OperatorNew->getLocation(),
930 diag::err_coroutine_promise_new_requires_nothrow)
931 << OperatorNew;
932 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
933 << OperatorNew;
934 return false;
935 }
936 }
937
938 if ((OperatorDelete = findDeleteForPromise(S, Loc, PromiseType)) == nullptr)
Gor Nishanov8df64e92016-10-27 16:28:31 +0000939 return false;
940
941 Expr *FramePtr =
942 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_frame, {});
943
944 Expr *FrameSize =
945 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_size, {});
946
947 // Make new call.
948
949 ExprResult NewRef =
950 S.BuildDeclRefExpr(OperatorNew, OperatorNew->getType(), VK_LValue, Loc);
951 if (NewRef.isInvalid())
952 return false;
953
Eric Fiselierf747f532017-04-18 05:08:08 +0000954 SmallVector<Expr *, 2> NewArgs(1, FrameSize);
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000955 for (auto Arg : PlacementArgs)
956 NewArgs.push_back(Arg);
957
Gor Nishanov8df64e92016-10-27 16:28:31 +0000958 ExprResult NewExpr =
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000959 S.ActOnCallExpr(S.getCurScope(), NewRef.get(), Loc, NewArgs, Loc);
960 NewExpr = S.ActOnFinishFullExpr(NewExpr.get());
Gor Nishanov8df64e92016-10-27 16:28:31 +0000961 if (NewExpr.isInvalid())
962 return false;
963
Gor Nishanov8df64e92016-10-27 16:28:31 +0000964 // Make delete call.
965
966 QualType OpDeleteQualType = OperatorDelete->getType();
967
968 ExprResult DeleteRef =
969 S.BuildDeclRefExpr(OperatorDelete, OpDeleteQualType, VK_LValue, Loc);
970 if (DeleteRef.isInvalid())
971 return false;
972
973 Expr *CoroFree =
974 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_free, {FramePtr});
975
976 SmallVector<Expr *, 2> DeleteArgs{CoroFree};
977
978 // Check if we need to pass the size.
979 const auto *OpDeleteType =
980 OpDeleteQualType.getTypePtr()->getAs<FunctionProtoType>();
981 if (OpDeleteType->getNumParams() > 1)
982 DeleteArgs.push_back(FrameSize);
983
984 ExprResult DeleteExpr =
985 S.ActOnCallExpr(S.getCurScope(), DeleteRef.get(), Loc, DeleteArgs, Loc);
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000986 DeleteExpr = S.ActOnFinishFullExpr(DeleteExpr.get());
Gor Nishanov8df64e92016-10-27 16:28:31 +0000987 if (DeleteExpr.isInvalid())
988 return false;
989
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000990 this->Allocate = NewExpr.get();
991 this->Deallocate = DeleteExpr.get();
Gor Nishanov8df64e92016-10-27 16:28:31 +0000992
993 return true;
994}
995
Eric Fiselierbee782b2017-04-03 19:21:00 +0000996bool CoroutineStmtBuilder::makeOnFallthrough() {
997 assert(!IsPromiseDependentType &&
998 "cannot make statement while the promise type is dependent");
Gor Nishanovbbe1c072017-02-13 05:05:02 +0000999
1000 // [dcl.fct.def.coroutine]/4
1001 // The unqualified-ids 'return_void' and 'return_value' are looked up in
1002 // the scope of class P. If both are found, the program is ill-formed.
Eric Fiselierfc50f622017-05-25 14:59:39 +00001003 bool HasRVoid, HasRValue;
1004 LookupResult LRVoid =
1005 lookupMember(S, "return_void", PromiseRecordDecl, Loc, HasRVoid);
1006 LookupResult LRValue =
1007 lookupMember(S, "return_value", PromiseRecordDecl, Loc, HasRValue);
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001008
Eric Fiselier709d1b32016-10-27 07:30:31 +00001009 StmtResult Fallthrough;
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001010 if (HasRVoid && HasRValue) {
1011 // FIXME Improve this diagnostic
Eric Fiselierfc50f622017-05-25 14:59:39 +00001012 S.Diag(FD.getLocation(),
1013 diag::err_coroutine_promise_incompatible_return_functions)
1014 << PromiseRecordDecl;
1015 S.Diag(LRVoid.getRepresentativeDecl()->getLocation(),
1016 diag::note_member_first_declared_here)
1017 << LRVoid.getLookupName();
1018 S.Diag(LRValue.getRepresentativeDecl()->getLocation(),
1019 diag::note_member_first_declared_here)
1020 << LRValue.getLookupName();
1021 return false;
1022 } else if (!HasRVoid && !HasRValue) {
1023 // FIXME: The PDTS currently specifies this case as UB, not ill-formed.
1024 // However we still diagnose this as an error since until the PDTS is fixed.
1025 S.Diag(FD.getLocation(),
1026 diag::err_coroutine_promise_requires_return_function)
1027 << PromiseRecordDecl;
1028 S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here)
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001029 << PromiseRecordDecl;
1030 return false;
1031 } else if (HasRVoid) {
1032 // If the unqualified-id return_void is found, flowing off the end of a
1033 // coroutine is equivalent to a co_return with no operand. Otherwise,
1034 // flowing off the end of a coroutine results in undefined behavior.
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001035 Fallthrough = S.BuildCoreturnStmt(FD.getLocation(), nullptr,
1036 /*IsImplicit*/false);
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001037 Fallthrough = S.ActOnFinishFullStmt(Fallthrough.get());
1038 if (Fallthrough.isInvalid())
1039 return false;
Eric Fiselier709d1b32016-10-27 07:30:31 +00001040 }
Richard Smith2af65c42015-11-24 02:34:39 +00001041
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001042 this->OnFallthrough = Fallthrough.get();
1043 return true;
1044}
1045
Eric Fiselierbee782b2017-04-03 19:21:00 +00001046bool CoroutineStmtBuilder::makeOnException() {
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001047 // Try to form 'p.unhandled_exception();'
Eric Fiselierbee782b2017-04-03 19:21:00 +00001048 assert(!IsPromiseDependentType &&
1049 "cannot make statement while the promise type is dependent");
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001050
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001051 const bool RequireUnhandledException = S.getLangOpts().CXXExceptions;
1052
1053 if (!lookupMember(S, "unhandled_exception", PromiseRecordDecl, Loc)) {
1054 auto DiagID =
1055 RequireUnhandledException
1056 ? diag::err_coroutine_promise_unhandled_exception_required
1057 : diag::
1058 warn_coroutine_promise_unhandled_exception_required_with_exceptions;
1059 S.Diag(Loc, DiagID) << PromiseRecordDecl;
Gor Nishanov29ff6382017-05-24 14:34:19 +00001060 S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here)
1061 << PromiseRecordDecl;
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001062 return !RequireUnhandledException;
1063 }
1064
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001065 // If exceptions are disabled, don't try to build OnException.
1066 if (!S.getLangOpts().CXXExceptions)
1067 return true;
1068
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001069 ExprResult UnhandledException = buildPromiseCall(S, Fn.CoroutinePromise, Loc,
1070 "unhandled_exception", None);
1071 UnhandledException = S.ActOnFinishFullExpr(UnhandledException.get(), Loc);
1072 if (UnhandledException.isInvalid())
1073 return false;
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001074
Gor Nishanov5b050e42017-05-22 22:33:17 +00001075 // Since the body of the coroutine will be wrapped in try-catch, it will
1076 // be incompatible with SEH __try if present in a function.
1077 if (!S.getLangOpts().Borland && Fn.FirstSEHTryLoc.isValid()) {
1078 S.Diag(Fn.FirstSEHTryLoc, diag::err_seh_in_a_coroutine_with_cxx_exceptions);
1079 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1080 << Fn.getFirstCoroutineStmtKeyword();
1081 return false;
1082 }
1083
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001084 this->OnException = UnhandledException.get();
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001085 return true;
1086}
1087
Eric Fiselierbee782b2017-04-03 19:21:00 +00001088bool CoroutineStmtBuilder::makeReturnObject() {
Richard Smith2af65c42015-11-24 02:34:39 +00001089 // Build implicit 'p.get_return_object()' expression and form initialization
1090 // of return type from it.
1091 ExprResult ReturnObject =
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001092 buildPromiseCall(S, Fn.CoroutinePromise, Loc, "get_return_object", None);
Richard Smith2af65c42015-11-24 02:34:39 +00001093 if (ReturnObject.isInvalid())
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001094 return false;
Richard Smith2af65c42015-11-24 02:34:39 +00001095
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001096 this->ReturnValue = ReturnObject.get();
1097 return true;
1098}
1099
Gor Nishanov6a470682017-05-22 20:22:23 +00001100static void noteMemberDeclaredHere(Sema &S, Expr *E, FunctionScopeInfo &Fn) {
1101 if (auto *MbrRef = dyn_cast<CXXMemberCallExpr>(E)) {
1102 auto *MethodDecl = MbrRef->getMethodDecl();
Eric Fiselierfc50f622017-05-25 14:59:39 +00001103 S.Diag(MethodDecl->getLocation(), diag::note_member_declared_here)
1104 << MethodDecl;
Gor Nishanov6a470682017-05-22 20:22:23 +00001105 }
1106 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1107 << Fn.getFirstCoroutineStmtKeyword();
1108}
1109
1110bool CoroutineStmtBuilder::makeGroDeclAndReturnStmt() {
1111 assert(!IsPromiseDependentType &&
1112 "cannot make statement while the promise type is dependent");
1113 assert(this->ReturnValue && "ReturnValue must be already formed");
1114
1115 QualType const GroType = this->ReturnValue->getType();
1116 assert(!GroType->isDependentType() &&
1117 "get_return_object type must no longer be dependent");
1118
1119 QualType const FnRetType = FD.getReturnType();
1120 assert(!FnRetType->isDependentType() &&
1121 "get_return_object type must no longer be dependent");
1122
1123 if (FnRetType->isVoidType()) {
1124 ExprResult Res = S.ActOnFinishFullExpr(this->ReturnValue, Loc);
1125 if (Res.isInvalid())
1126 return false;
1127
1128 this->ResultDecl = Res.get();
1129 return true;
1130 }
1131
1132 if (GroType->isVoidType()) {
1133 // Trigger a nice error message.
1134 InitializedEntity Entity =
1135 InitializedEntity::InitializeResult(Loc, FnRetType, false);
1136 S.PerformMoveOrCopyInitialization(Entity, nullptr, FnRetType, ReturnValue);
1137 noteMemberDeclaredHere(S, ReturnValue, Fn);
1138 return false;
1139 }
1140
1141 auto *GroDecl = VarDecl::Create(
1142 S.Context, &FD, FD.getLocation(), FD.getLocation(),
1143 &S.PP.getIdentifierTable().get("__coro_gro"), GroType,
1144 S.Context.getTrivialTypeSourceInfo(GroType, Loc), SC_None);
1145
1146 S.CheckVariableDeclarationType(GroDecl);
1147 if (GroDecl->isInvalidDecl())
1148 return false;
1149
1150 InitializedEntity Entity = InitializedEntity::InitializeVariable(GroDecl);
1151 ExprResult Res = S.PerformMoveOrCopyInitialization(Entity, nullptr, GroType,
1152 this->ReturnValue);
1153 if (Res.isInvalid())
1154 return false;
1155
1156 Res = S.ActOnFinishFullExpr(Res.get());
1157 if (Res.isInvalid())
1158 return false;
1159
1160 if (GroType == FnRetType) {
1161 GroDecl->setNRVOVariable(true);
1162 }
1163
1164 S.AddInitializerToDecl(GroDecl, Res.get(),
1165 /*DirectInit=*/false);
1166
1167 S.FinalizeDeclaration(GroDecl);
1168
1169 // Form a declaration statement for the return declaration, so that AST
1170 // visitors can more easily find it.
1171 StmtResult GroDeclStmt =
1172 S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(GroDecl), Loc, Loc);
1173 if (GroDeclStmt.isInvalid())
1174 return false;
1175
1176 this->ResultDecl = GroDeclStmt.get();
1177
1178 ExprResult declRef = S.BuildDeclRefExpr(GroDecl, GroType, VK_LValue, Loc);
1179 if (declRef.isInvalid())
1180 return false;
1181
1182 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, declRef.get());
1183 if (ReturnStmt.isInvalid()) {
1184 noteMemberDeclaredHere(S, ReturnValue, Fn);
1185 return false;
1186 }
1187
1188 this->ReturnStmt = ReturnStmt.get();
1189 return true;
1190}
1191
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001192// Create a static_cast\<T&&>(expr).
1193static Expr *castForMoving(Sema &S, Expr *E, QualType T = QualType()) {
1194 if (T.isNull())
1195 T = E->getType();
1196 QualType TargetType = S.BuildReferenceType(
1197 T, /*SpelledAsLValue*/ false, SourceLocation(), DeclarationName());
1198 SourceLocation ExprLoc = E->getLocStart();
1199 TypeSourceInfo *TargetLoc =
1200 S.Context.getTrivialTypeSourceInfo(TargetType, ExprLoc);
1201
1202 return S
1203 .BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
1204 SourceRange(ExprLoc, ExprLoc), E->getSourceRange())
1205 .get();
1206}
1207
1208/// \brief Build a variable declaration for move parameter.
1209static VarDecl *buildVarDecl(Sema &S, SourceLocation Loc, QualType Type,
1210 StringRef Name) {
1211 DeclContext *DC = S.CurContext;
1212 IdentifierInfo *II = &S.PP.getIdentifierTable().get(Name);
1213 TypeSourceInfo *TInfo = S.Context.getTrivialTypeSourceInfo(Type, Loc);
1214 VarDecl *Decl =
1215 VarDecl::Create(S.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
1216 Decl->setImplicit();
1217 return Decl;
1218}
1219
Eric Fiselierbee782b2017-04-03 19:21:00 +00001220bool CoroutineStmtBuilder::makeParamMoves() {
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001221 for (auto *paramDecl : FD.parameters()) {
1222 auto Ty = paramDecl->getType();
1223 if (Ty->isDependentType())
1224 continue;
1225
1226 // No need to copy scalars, llvm will take care of them.
1227 if (Ty->getAsCXXRecordDecl()) {
1228 if (!paramDecl->getIdentifier())
1229 continue;
1230
1231 ExprResult ParamRef =
1232 S.BuildDeclRefExpr(paramDecl, paramDecl->getType(),
1233 ExprValueKind::VK_LValue, Loc); // FIXME: scope?
1234 if (ParamRef.isInvalid())
1235 return false;
1236
1237 Expr *RCast = castForMoving(S, ParamRef.get());
1238
1239 auto D = buildVarDecl(S, Loc, Ty, paramDecl->getIdentifier()->getName());
1240
1241 S.AddInitializerToDecl(D, RCast, /*DirectInit=*/true);
1242
1243 // Convert decl to a statement.
1244 StmtResult Stmt = S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(D), Loc, Loc);
1245 if (Stmt.isInvalid())
1246 return false;
1247
1248 ParamMovesVector.push_back(Stmt.get());
1249 }
1250 }
1251
1252 // Convert to ArrayRef in CtorArgs structure that builder inherits from.
1253 ParamMoves = ParamMovesVector;
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001254 return true;
Richard Smithcfd53b42015-10-22 06:13:50 +00001255}
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001256
1257StmtResult Sema::BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
1258 CoroutineBodyStmt *Res = CoroutineBodyStmt::Create(Context, Args);
1259 if (!Res)
1260 return StmtError();
1261 return Res;
1262}