1//===-- SemaCoroutine.cpp - Semantic Analysis for Coroutines --------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for C++ Coroutines.
10//
11// This file contains references to sections of the Coroutines TS, which
12// can be found at http://wg21.link/coroutines.
13//
14//===----------------------------------------------------------------------===//
15
16#include "CoroutineStmtBuilder.h"
17#include "clang/AST/ASTLambda.h"
18#include "clang/AST/Decl.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/ExprCXX.h"
21#include "clang/AST/StmtCXX.h"
22#include "clang/Basic/Builtins.h"
23#include "clang/Lex/Preprocessor.h"
24#include "clang/Sema/EnterExpressionEvaluationContext.h"
25#include "clang/Sema/Initialization.h"
26#include "clang/Sema/Overload.h"
27#include "clang/Sema/ScopeInfo.h"
28
29using namespace clang;
30using namespace sema;
31
32static LookupResult lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD,
33 SourceLocation Loc, bool &Res) {
34 DeclarationName DN = S.PP.getIdentifierInfo(Name);
35 LookupResult LR(S, DN, Loc, Sema::LookupMemberName);
36 // Suppress diagnostics when a private member is selected. The same warnings
37 // will be produced again when building the call.
38 LR.suppressDiagnostics();
39 Res = S.LookupQualifiedName(R&: LR, LookupCtx: RD);
40 return LR;
41}
42
43static bool lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD,
44 SourceLocation Loc) {
45 bool Res;
46 lookupMember(S, Name, RD, Loc, Res);
47 return Res;
48}
49
50/// Look up the std::coroutine_traits<...>::promise_type for the given
51/// function type.
52static QualType lookupPromiseType(Sema &S, const FunctionDecl *FD,
53 SourceLocation KwLoc) {
54 const FunctionProtoType *FnType = FD->getType()->castAs<FunctionProtoType>();
55 const SourceLocation FuncLoc = FD->getLocation();
56
57 ClassTemplateDecl *CoroTraits =
58 S.lookupCoroutineTraits(KwLoc, FuncLoc);
59 if (!CoroTraits)
60 return QualType();
61
62 // Form template argument list for coroutine_traits<R, P1, P2, ...> according
63 // to [dcl.fct.def.coroutine]3
64 TemplateArgumentListInfo Args(KwLoc, KwLoc);
65 auto AddArg = [&](QualType T) {
66 Args.addArgument(Loc: TemplateArgumentLoc(
67 TemplateArgument(T), S.Context.getTrivialTypeSourceInfo(T, Loc: KwLoc)));
68 };
69 AddArg(FnType->getReturnType());
70 // If the function is a non-static member function, add the type
71 // of the implicit object parameter before the formal parameters.
72 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
73 if (MD->isImplicitObjectMemberFunction()) {
74 // [over.match.funcs]4
75 // For non-static member functions, the type of the implicit object
76 // parameter is
77 // -- "lvalue reference to cv X" for functions declared without a
78 // ref-qualifier or with the & ref-qualifier
79 // -- "rvalue reference to cv X" for functions declared with the &&
80 // ref-qualifier
81 QualType T = MD->getFunctionObjectParameterType();
82 T = FnType->getRefQualifier() == RQ_RValue
83 ? S.Context.getRValueReferenceType(T)
84 : S.Context.getLValueReferenceType(T, /*SpelledAsLValue*/ true);
85 AddArg(T);
86 }
87 }
88 for (QualType T : FnType->getParamTypes())
89 AddArg(T);
90
91 // Build the template-id.
92 QualType CoroTrait =
93 S.CheckTemplateIdType(Template: TemplateName(CoroTraits), TemplateLoc: KwLoc, TemplateArgs&: Args);
94 if (CoroTrait.isNull())
95 return QualType();
96 if (S.RequireCompleteType(Loc: KwLoc, T: CoroTrait,
97 DiagID: diag::err_coroutine_type_missing_specialization))
98 return QualType();
99
100 auto *RD = CoroTrait->getAsCXXRecordDecl();
101 assert(RD && "specialization of class template is not a class?");
102
103 // Look up the ::promise_type member.
104 LookupResult R(S, &S.PP.getIdentifierTable().get(Name: "promise_type"), KwLoc,
105 Sema::LookupOrdinaryName);
106 S.LookupQualifiedName(R, LookupCtx: RD);
107 auto *Promise = R.getAsSingle<TypeDecl>();
108 if (!Promise) {
109 S.Diag(Loc: FuncLoc,
110 DiagID: diag::err_implied_std_coroutine_traits_promise_type_not_found)
111 << RD;
112 return QualType();
113 }
114 // The promise type is required to be a class type.
115 QualType PromiseType = S.Context.getTypeDeclType(Decl: Promise);
116
117 auto buildElaboratedType = [&]() {
118 auto *NNS = NestedNameSpecifier::Create(Context: S.Context, Prefix: nullptr, NS: S.getStdNamespace());
119 NNS = NestedNameSpecifier::Create(Context: S.Context, Prefix: NNS, T: CoroTrait.getTypePtr());
120 return S.Context.getElaboratedType(Keyword: ElaboratedTypeKeyword::None, NNS,
121 NamedType: PromiseType);
122 };
123
124 if (!PromiseType->getAsCXXRecordDecl()) {
125 S.Diag(Loc: FuncLoc,
126 DiagID: diag::err_implied_std_coroutine_traits_promise_type_not_class)
127 << buildElaboratedType();
128 return QualType();
129 }
130 if (S.RequireCompleteType(Loc: FuncLoc, T: buildElaboratedType(),
131 DiagID: diag::err_coroutine_promise_type_incomplete))
132 return QualType();
133
134 return PromiseType;
135}
136
137/// Look up the std::coroutine_handle<PromiseType>.
138static QualType lookupCoroutineHandleType(Sema &S, QualType PromiseType,
139 SourceLocation Loc) {
140 if (PromiseType.isNull())
141 return QualType();
142
143 NamespaceDecl *CoroNamespace = S.getStdNamespace();
144 assert(CoroNamespace && "Should already be diagnosed");
145
146 LookupResult Result(S, &S.PP.getIdentifierTable().get(Name: "coroutine_handle"),
147 Loc, Sema::LookupOrdinaryName);
148 if (!S.LookupQualifiedName(R&: Result, LookupCtx: CoroNamespace)) {
149 S.Diag(Loc, DiagID: diag::err_implied_coroutine_type_not_found)
150 << "std::coroutine_handle";
151 return QualType();
152 }
153
154 ClassTemplateDecl *CoroHandle = Result.getAsSingle<ClassTemplateDecl>();
155 if (!CoroHandle) {
156 Result.suppressDiagnostics();
157 // We found something weird. Complain about the first thing we found.
158 NamedDecl *Found = *Result.begin();
159 S.Diag(Loc: Found->getLocation(), DiagID: diag::err_malformed_std_coroutine_handle);
160 return QualType();
161 }
162
163 // Form template argument list for coroutine_handle<Promise>.
164 TemplateArgumentListInfo Args(Loc, Loc);
165 Args.addArgument(Loc: TemplateArgumentLoc(
166 TemplateArgument(PromiseType),
167 S.Context.getTrivialTypeSourceInfo(T: PromiseType, Loc)));
168
169 // Build the template-id.
170 QualType CoroHandleType =
171 S.CheckTemplateIdType(Template: TemplateName(CoroHandle), TemplateLoc: Loc, TemplateArgs&: Args);
172 if (CoroHandleType.isNull())
173 return QualType();
174 if (S.RequireCompleteType(Loc, T: CoroHandleType,
175 DiagID: diag::err_coroutine_type_missing_specialization))
176 return QualType();
177
178 return CoroHandleType;
179}
180
181static bool isValidCoroutineContext(Sema &S, SourceLocation Loc,
182 StringRef Keyword) {
183 // [expr.await]p2 dictates that 'co_await' and 'co_yield' must be used within
184 // a function body.
185 // FIXME: This also covers [expr.await]p2: "An await-expression shall not
186 // appear in a default argument." But the diagnostic QoI here could be
187 // improved to inform the user that default arguments specifically are not
188 // allowed.
189 auto *FD = dyn_cast<FunctionDecl>(Val: S.CurContext);
190 if (!FD) {
191 S.Diag(Loc, DiagID: isa<ObjCMethodDecl>(Val: S.CurContext)
192 ? diag::err_coroutine_objc_method
193 : diag::err_coroutine_outside_function) << Keyword;
194 return false;
195 }
196
197 // An enumeration for mapping the diagnostic type to the correct diagnostic
198 // selection index.
199 enum InvalidFuncDiag {
200 DiagCtor = 0,
201 DiagDtor,
202 DiagMain,
203 DiagConstexpr,
204 DiagAutoRet,
205 DiagVarargs,
206 DiagConsteval,
207 };
208 bool Diagnosed = false;
209 auto DiagInvalid = [&](InvalidFuncDiag ID) {
210 S.Diag(Loc, DiagID: diag::err_coroutine_invalid_func_context) << ID << Keyword;
211 Diagnosed = true;
212 return false;
213 };
214
215 // Diagnose when a constructor, destructor
216 // or the function 'main' are declared as a coroutine.
217 auto *MD = dyn_cast<CXXMethodDecl>(Val: FD);
218 // [class.ctor]p11: "A constructor shall not be a coroutine."
219 if (MD && isa<CXXConstructorDecl>(Val: MD))
220 return DiagInvalid(DiagCtor);
221 // [class.dtor]p17: "A destructor shall not be a coroutine."
222 else if (MD && isa<CXXDestructorDecl>(Val: MD))
223 return DiagInvalid(DiagDtor);
224 // [basic.start.main]p3: "The function main shall not be a coroutine."
225 else if (FD->isMain())
226 return DiagInvalid(DiagMain);
227
228 // Emit a diagnostics for each of the following conditions which is not met.
229 // [expr.const]p2: "An expression e is a core constant expression unless the
230 // evaluation of e [...] would evaluate one of the following expressions:
231 // [...] an await-expression [...] a yield-expression."
232 if (FD->isConstexpr())
233 DiagInvalid(FD->isConsteval() ? DiagConsteval : DiagConstexpr);
234 // [dcl.spec.auto]p15: "A function declared with a return type that uses a
235 // placeholder type shall not be a coroutine."
236 if (FD->getReturnType()->isUndeducedType())
237 DiagInvalid(DiagAutoRet);
238 // [dcl.fct.def.coroutine]p1
239 // The parameter-declaration-clause of the coroutine shall not terminate with
240 // an ellipsis that is not part of a parameter-declaration.
241 if (FD->isVariadic())
242 DiagInvalid(DiagVarargs);
243
244 return !Diagnosed;
245}
246
247/// Build a call to 'operator co_await' if there is a suitable operator for
248/// the given expression.
249ExprResult Sema::BuildOperatorCoawaitCall(SourceLocation Loc, Expr *E,
250 UnresolvedLookupExpr *Lookup) {
251 UnresolvedSet<16> Functions;
252 Functions.append(I: Lookup->decls_begin(), E: Lookup->decls_end());
253 return CreateOverloadedUnaryOp(OpLoc: Loc, Opc: UO_Coawait, Fns: Functions, input: E);
254}
255
256static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, Scope *S,
257 SourceLocation Loc, Expr *E) {
258 ExprResult R = SemaRef.BuildOperatorCoawaitLookupExpr(S, Loc);
259 if (R.isInvalid())
260 return ExprError();
261 return SemaRef.BuildOperatorCoawaitCall(Loc, E,
262 Lookup: cast<UnresolvedLookupExpr>(Val: R.get()));
263}
264
265static ExprResult buildCoroutineHandle(Sema &S, QualType PromiseType,
266 SourceLocation Loc) {
267 QualType CoroHandleType = lookupCoroutineHandleType(S, PromiseType, Loc);
268 if (CoroHandleType.isNull())
269 return ExprError();
270
271 DeclContext *LookupCtx = S.computeDeclContext(T: CoroHandleType);
272 LookupResult Found(S, &S.PP.getIdentifierTable().get(Name: "from_address"), Loc,
273 Sema::LookupOrdinaryName);
274 if (!S.LookupQualifiedName(R&: Found, LookupCtx)) {
275 S.Diag(Loc, DiagID: diag::err_coroutine_handle_missing_member)
276 << "from_address";
277 return ExprError();
278 }
279
280 Expr *FramePtr =
281 S.BuildBuiltinCallExpr(Loc, Id: Builtin::BI__builtin_coro_frame, CallArgs: {});
282
283 CXXScopeSpec SS;
284 ExprResult FromAddr =
285 S.BuildDeclarationNameExpr(SS, R&: Found, /*NeedsADL=*/false);
286 if (FromAddr.isInvalid())
287 return ExprError();
288
289 return S.BuildCallExpr(S: nullptr, Fn: FromAddr.get(), LParenLoc: Loc, ArgExprs: FramePtr, RParenLoc: Loc);
290}
291
292struct ReadySuspendResumeResult {
293 enum AwaitCallType { ACT_Ready, ACT_Suspend, ACT_Resume };
294 Expr *Results[3];
295 OpaqueValueExpr *OpaqueValue;
296 bool IsInvalid;
297};
298
299static ExprResult buildMemberCall(Sema &S, Expr *Base, SourceLocation Loc,
300 StringRef Name, MultiExprArg Args) {
301 DeclarationNameInfo NameInfo(&S.PP.getIdentifierTable().get(Name), Loc);
302
303 // FIXME: Fix BuildMemberReferenceExpr to take a const CXXScopeSpec&.
304 CXXScopeSpec SS;
305 ExprResult Result = S.BuildMemberReferenceExpr(
306 Base, BaseType: Base->getType(), OpLoc: Loc, /*IsPtr=*/IsArrow: false, SS,
307 TemplateKWLoc: SourceLocation(), FirstQualifierInScope: nullptr, NameInfo, /*TemplateArgs=*/nullptr,
308 /*Scope=*/S: nullptr);
309 if (Result.isInvalid())
310 return ExprError();
311
312 auto EndLoc = Args.empty() ? Loc : Args.back()->getEndLoc();
313 return S.BuildCallExpr(S: nullptr, Fn: Result.get(), LParenLoc: Loc, ArgExprs: Args, RParenLoc: EndLoc, ExecConfig: nullptr);
314}
315
316// See if return type is coroutine-handle and if so, invoke builtin coro-resume
317// on its address. This is to enable the support for coroutine-handle
318// returning await_suspend that results in a guaranteed tail call to the target
319// coroutine.
320static Expr *maybeTailCall(Sema &S, QualType RetType, Expr *E,
321 SourceLocation Loc) {
322 if (RetType->isReferenceType())
323 return nullptr;
324 Type const *T = RetType.getTypePtr();
325 if (!T->isClassType() && !T->isStructureType())
326 return nullptr;
327
328 // FIXME: Add convertability check to coroutine_handle<>. Possibly via
329 // EvaluateBinaryTypeTrait(BTT_IsConvertible, ...) which is at the moment
330 // a private function in SemaExprCXX.cpp
331
332 ExprResult AddressExpr = buildMemberCall(S, Base: E, Loc, Name: "address", Args: {});
333 if (AddressExpr.isInvalid())
334 return nullptr;
335
336 Expr *JustAddress = AddressExpr.get();
337
338 // Check that the type of AddressExpr is void*
339 if (!JustAddress->getType().getTypePtr()->isVoidPointerType())
340 S.Diag(Loc: cast<CallExpr>(Val: JustAddress)->getCalleeDecl()->getLocation(),
341 DiagID: diag::warn_coroutine_handle_address_invalid_return_type)
342 << JustAddress->getType();
343
344 // Clean up temporary objects, because the resulting expression
345 // will become the body of await_suspend wrapper.
346 return S.MaybeCreateExprWithCleanups(SubExpr: JustAddress);
347}
348
349/// Build calls to await_ready, await_suspend, and await_resume for a co_await
350/// expression.
351/// The generated AST tries to clean up temporary objects as early as
352/// possible so that they don't live across suspension points if possible.
353/// Having temporary objects living across suspension points unnecessarily can
354/// lead to large frame size, and also lead to memory corruptions if the
355/// coroutine frame is destroyed after coming back from suspension. This is done
356/// by wrapping both the await_ready call and the await_suspend call with
357/// ExprWithCleanups. In the end of this function, we also need to explicitly
358/// set cleanup state so that the CoawaitExpr is also wrapped with an
359/// ExprWithCleanups to clean up the awaiter associated with the co_await
360/// expression.
361static ReadySuspendResumeResult buildCoawaitCalls(Sema &S, VarDecl *CoroPromise,
362 SourceLocation Loc, Expr *E) {
363 OpaqueValueExpr *Operand = new (S.Context)
364 OpaqueValueExpr(Loc, E->getType(), VK_LValue, E->getObjectKind(), E);
365
366 // Assume valid until we see otherwise.
367 // Further operations are responsible for setting IsInalid to true.
368 ReadySuspendResumeResult Calls = {.Results: {}, .OpaqueValue: Operand, /*IsInvalid=*/false};
369
370 using ACT = ReadySuspendResumeResult::AwaitCallType;
371
372 auto BuildSubExpr = [&](ACT CallType, StringRef Func,
373 MultiExprArg Arg) -> Expr * {
374 ExprResult Result = buildMemberCall(S, Base: Operand, Loc, Name: Func, Args: Arg);
375 if (Result.isInvalid()) {
376 Calls.IsInvalid = true;
377 return nullptr;
378 }
379 Calls.Results[CallType] = Result.get();
380 return Result.get();
381 };
382
383 CallExpr *AwaitReady =
384 cast_or_null<CallExpr>(Val: BuildSubExpr(ACT::ACT_Ready, "await_ready", {}));
385 if (!AwaitReady)
386 return Calls;
387 if (!AwaitReady->getType()->isDependentType()) {
388 // [expr.await]p3 [...]
389 // — await-ready is the expression e.await_ready(), contextually converted
390 // to bool.
391 ExprResult Conv = S.PerformContextuallyConvertToBool(From: AwaitReady);
392 if (Conv.isInvalid()) {
393 S.Diag(Loc: AwaitReady->getDirectCallee()->getBeginLoc(),
394 DiagID: diag::note_await_ready_no_bool_conversion);
395 S.Diag(Loc, DiagID: diag::note_coroutine_promise_call_implicitly_required)
396 << AwaitReady->getDirectCallee() << E->getSourceRange();
397 Calls.IsInvalid = true;
398 } else
399 Calls.Results[ACT::ACT_Ready] = S.MaybeCreateExprWithCleanups(SubExpr: Conv.get());
400 }
401
402 ExprResult CoroHandleRes =
403 buildCoroutineHandle(S, PromiseType: CoroPromise->getType(), Loc);
404 if (CoroHandleRes.isInvalid()) {
405 Calls.IsInvalid = true;
406 return Calls;
407 }
408 Expr *CoroHandle = CoroHandleRes.get();
409 CallExpr *AwaitSuspend = cast_or_null<CallExpr>(
410 Val: BuildSubExpr(ACT::ACT_Suspend, "await_suspend", CoroHandle));
411 if (!AwaitSuspend)
412 return Calls;
413 if (!AwaitSuspend->getType()->isDependentType()) {
414 // [expr.await]p3 [...]
415 // - await-suspend is the expression e.await_suspend(h), which shall be
416 // a prvalue of type void, bool, or std::coroutine_handle<Z> for some
417 // type Z.
418 QualType RetType = AwaitSuspend->getCallReturnType(Ctx: S.Context);
419
420 // Support for coroutine_handle returning await_suspend.
421 if (Expr *TailCallSuspend =
422 maybeTailCall(S, RetType, E: AwaitSuspend, Loc))
423 // Note that we don't wrap the expression with ExprWithCleanups here
424 // because that might interfere with tailcall contract (e.g. inserting
425 // clean up instructions in-between tailcall and return). Instead
426 // ExprWithCleanups is wrapped within maybeTailCall() prior to the resume
427 // call.
428 Calls.Results[ACT::ACT_Suspend] = TailCallSuspend;
429 else {
430 // non-class prvalues always have cv-unqualified types
431 if (RetType->isReferenceType() ||
432 (!RetType->isBooleanType() && !RetType->isVoidType())) {
433 S.Diag(Loc: AwaitSuspend->getCalleeDecl()->getLocation(),
434 DiagID: diag::err_await_suspend_invalid_return_type)
435 << RetType;
436 S.Diag(Loc, DiagID: diag::note_coroutine_promise_call_implicitly_required)
437 << AwaitSuspend->getDirectCallee();
438 Calls.IsInvalid = true;
439 } else
440 Calls.Results[ACT::ACT_Suspend] =
441 S.MaybeCreateExprWithCleanups(SubExpr: AwaitSuspend);
442 }
443 }
444
445 BuildSubExpr(ACT::ACT_Resume, "await_resume", {});
446
447 // Make sure the awaiter object gets a chance to be cleaned up.
448 S.Cleanup.setExprNeedsCleanups(true);
449
450 return Calls;
451}
452
453static ExprResult buildPromiseCall(Sema &S, VarDecl *Promise,
454 SourceLocation Loc, StringRef Name,
455 MultiExprArg Args) {
456
457 // Form a reference to the promise.
458 ExprResult PromiseRef = S.BuildDeclRefExpr(
459 D: Promise, Ty: Promise->getType().getNonReferenceType(), VK: VK_LValue, Loc);
460 if (PromiseRef.isInvalid())
461 return ExprError();
462
463 return buildMemberCall(S, Base: PromiseRef.get(), Loc, Name, Args);
464}
465
466VarDecl *Sema::buildCoroutinePromise(SourceLocation Loc) {
467 assert(isa<FunctionDecl>(CurContext) && "not in a function scope");
468 auto *FD = cast<FunctionDecl>(Val: CurContext);
469 bool IsThisDependentType = [&] {
470 if (const auto *MD = dyn_cast_if_present<CXXMethodDecl>(Val: FD))
471 return MD->isImplicitObjectMemberFunction() &&
472 MD->getThisType()->isDependentType();
473 return false;
474 }();
475
476 QualType T = FD->getType()->isDependentType() || IsThisDependentType
477 ? Context.DependentTy
478 : lookupPromiseType(S&: *this, FD, KwLoc: Loc);
479 if (T.isNull())
480 return nullptr;
481
482 auto *VD = VarDecl::Create(C&: Context, DC: FD, StartLoc: FD->getLocation(), IdLoc: FD->getLocation(),
483 Id: &PP.getIdentifierTable().get(Name: "__promise"), T,
484 TInfo: Context.getTrivialTypeSourceInfo(T, Loc), S: SC_None);
485 VD->setImplicit();
486 CheckVariableDeclarationType(NewVD: VD);
487 if (VD->isInvalidDecl())
488 return nullptr;
489
490 auto *ScopeInfo = getCurFunction();
491
492 // Build a list of arguments, based on the coroutine function's arguments,
493 // that if present will be passed to the promise type's constructor.
494 llvm::SmallVector<Expr *, 4> CtorArgExprs;
495
496 // Add implicit object parameter.
497 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
498 if (MD->isImplicitObjectMemberFunction() && !isLambdaCallOperator(MD)) {
499 ExprResult ThisExpr = ActOnCXXThis(Loc);
500 if (ThisExpr.isInvalid())
501 return nullptr;
502 ThisExpr = CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_Deref, InputExpr: ThisExpr.get());
503 if (ThisExpr.isInvalid())
504 return nullptr;
505 CtorArgExprs.push_back(Elt: ThisExpr.get());
506 }
507 }
508
509 // Add the coroutine function's parameters.
510 auto &Moves = ScopeInfo->CoroutineParameterMoves;
511 for (auto *PD : FD->parameters()) {
512 if (PD->getType()->isDependentType())
513 continue;
514
515 auto RefExpr = ExprEmpty();
516 auto Move = Moves.find(Key: PD);
517 assert(Move != Moves.end() &&
518 "Coroutine function parameter not inserted into move map");
519 // If a reference to the function parameter exists in the coroutine
520 // frame, use that reference.
521 auto *MoveDecl =
522 cast<VarDecl>(Val: cast<DeclStmt>(Val: Move->second)->getSingleDecl());
523 RefExpr =
524 BuildDeclRefExpr(D: MoveDecl, Ty: MoveDecl->getType().getNonReferenceType(),
525 VK: ExprValueKind::VK_LValue, Loc: FD->getLocation());
526 if (RefExpr.isInvalid())
527 return nullptr;
528 CtorArgExprs.push_back(Elt: RefExpr.get());
529 }
530
531 // If we have a non-zero number of constructor arguments, try to use them.
532 // Otherwise, fall back to the promise type's default constructor.
533 if (!CtorArgExprs.empty()) {
534 // Create an initialization sequence for the promise type using the
535 // constructor arguments, wrapped in a parenthesized list expression.
536 Expr *PLE = ParenListExpr::Create(Ctx: Context, LParenLoc: FD->getLocation(),
537 Exprs: CtorArgExprs, RParenLoc: FD->getLocation());
538 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var: VD);
539 InitializationKind Kind = InitializationKind::CreateForInit(
540 Loc: VD->getLocation(), /*DirectInit=*/true, Init: PLE);
541 InitializationSequence InitSeq(*this, Entity, Kind, CtorArgExprs,
542 /*TopLevelOfInitList=*/false,
543 /*TreatUnavailableAsInvalid=*/false);
544
545 // [dcl.fct.def.coroutine]5.7
546 // promise-constructor-arguments is determined as follows: overload
547 // resolution is performed on a promise constructor call created by
548 // assembling an argument list q_1 ... q_n . If a viable constructor is
549 // found ([over.match.viable]), then promise-constructor-arguments is ( q_1
550 // , ..., q_n ), otherwise promise-constructor-arguments is empty.
551 if (InitSeq) {
552 ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args: CtorArgExprs);
553 if (Result.isInvalid()) {
554 VD->setInvalidDecl();
555 } else if (Result.get()) {
556 VD->setInit(MaybeCreateExprWithCleanups(SubExpr: Result.get()));
557 VD->setInitStyle(VarDecl::CallInit);
558 CheckCompleteVariableDeclaration(VD);
559 }
560 } else
561 ActOnUninitializedDecl(dcl: VD);
562 } else
563 ActOnUninitializedDecl(dcl: VD);
564
565 FD->addDecl(D: VD);
566 return VD;
567}
568
569/// Check that this is a context in which a coroutine suspension can appear.
570static FunctionScopeInfo *checkCoroutineContext(Sema &S, SourceLocation Loc,
571 StringRef Keyword,
572 bool IsImplicit = false) {
573 if (!isValidCoroutineContext(S, Loc, Keyword))
574 return nullptr;
575
576 assert(isa<FunctionDecl>(S.CurContext) && "not in a function scope");
577
578 auto *ScopeInfo = S.getCurFunction();
579 assert(ScopeInfo && "missing function scope for function");
580
581 if (ScopeInfo->FirstCoroutineStmtLoc.isInvalid() && !IsImplicit)
582 ScopeInfo->setFirstCoroutineStmt(Loc, Keyword);
583
584 if (ScopeInfo->CoroutinePromise)
585 return ScopeInfo;
586
587 if (!S.buildCoroutineParameterMoves(Loc))
588 return nullptr;
589
590 ScopeInfo->CoroutinePromise = S.buildCoroutinePromise(Loc);
591 if (!ScopeInfo->CoroutinePromise)
592 return nullptr;
593
594 return ScopeInfo;
595}
596
597/// Recursively check \p E and all its children to see if any call target
598/// (including constructor call) is declared noexcept. Also any value returned
599/// from the call has a noexcept destructor.
600static void checkNoThrow(Sema &S, const Stmt *E,
601 llvm::SmallPtrSetImpl<const Decl *> &ThrowingDecls) {
602 auto checkDeclNoexcept = [&](const Decl *D, bool IsDtor = false) {
603 // In the case of dtor, the call to dtor is implicit and hence we should
604 // pass nullptr to canCalleeThrow.
605 if (Sema::canCalleeThrow(S, E: IsDtor ? nullptr : cast<Expr>(Val: E), D)) {
606 if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
607 // co_await promise.final_suspend() could end up calling
608 // __builtin_coro_resume for symmetric transfer if await_suspend()
609 // returns a handle. In that case, even __builtin_coro_resume is not
610 // declared as noexcept and may throw, it does not throw _into_ the
611 // coroutine that just suspended, but rather throws back out from
612 // whoever called coroutine_handle::resume(), hence we claim that
613 // logically it does not throw.
614 if (FD->getBuiltinID() == Builtin::BI__builtin_coro_resume)
615 return;
616 }
617 if (ThrowingDecls.empty()) {
618 // [dcl.fct.def.coroutine]p15
619 // The expression co_await promise.final_suspend() shall not be
620 // potentially-throwing ([except.spec]).
621 //
622 // First time seeing an error, emit the error message.
623 S.Diag(Loc: cast<FunctionDecl>(Val: S.CurContext)->getLocation(),
624 DiagID: diag::err_coroutine_promise_final_suspend_requires_nothrow);
625 }
626 ThrowingDecls.insert(Ptr: D);
627 }
628 };
629
630 if (auto *CE = dyn_cast<CXXConstructExpr>(Val: E)) {
631 CXXConstructorDecl *Ctor = CE->getConstructor();
632 checkDeclNoexcept(Ctor);
633 // Check the corresponding destructor of the constructor.
634 checkDeclNoexcept(Ctor->getParent()->getDestructor(), /*IsDtor=*/true);
635 } else if (auto *CE = dyn_cast<CallExpr>(Val: E)) {
636 if (CE->isTypeDependent())
637 return;
638
639 checkDeclNoexcept(CE->getCalleeDecl());
640 QualType ReturnType = CE->getCallReturnType(Ctx: S.getASTContext());
641 // Check the destructor of the call return type, if any.
642 if (ReturnType.isDestructedType() ==
643 QualType::DestructionKind::DK_cxx_destructor) {
644 const auto *T =
645 cast<RecordType>(Val: ReturnType.getCanonicalType().getTypePtr());
646 checkDeclNoexcept(cast<CXXRecordDecl>(Val: T->getDecl())->getDestructor(),
647 /*IsDtor=*/true);
648 }
649 } else
650 for (const auto *Child : E->children()) {
651 if (!Child)
652 continue;
653 checkNoThrow(S, E: Child, ThrowingDecls);
654 }
655}
656
657bool Sema::checkFinalSuspendNoThrow(const Stmt *FinalSuspend) {
658 llvm::SmallPtrSet<const Decl *, 4> ThrowingDecls;
659 // We first collect all declarations that should not throw but not declared
660 // with noexcept. We then sort them based on the location before printing.
661 // This is to avoid emitting the same note multiple times on the same
662 // declaration, and also provide a deterministic order for the messages.
663 checkNoThrow(S&: *this, E: FinalSuspend, ThrowingDecls);
664 auto SortedDecls = llvm::SmallVector<const Decl *, 4>{ThrowingDecls.begin(),
665 ThrowingDecls.end()};
666 sort(C&: SortedDecls, Comp: [](const Decl *A, const Decl *B) {
667 return A->getEndLoc() < B->getEndLoc();
668 });
669 for (const auto *D : SortedDecls) {
670 Diag(Loc: D->getEndLoc(), DiagID: diag::note_coroutine_function_declare_noexcept);
671 }
672 return ThrowingDecls.empty();
673}
674
675// [stmt.return.coroutine]p1:
676// A coroutine shall not enclose a return statement ([stmt.return]).
677static void checkReturnStmtInCoroutine(Sema &S, FunctionScopeInfo *FSI) {
678 assert(FSI && "FunctionScopeInfo is null");
679 assert(FSI->FirstCoroutineStmtLoc.isValid() &&
680 "first coroutine location not set");
681 if (FSI->FirstReturnLoc.isInvalid())
682 return;
683 S.Diag(Loc: FSI->FirstReturnLoc, DiagID: diag::err_return_in_coroutine);
684 S.Diag(Loc: FSI->FirstCoroutineStmtLoc, DiagID: diag::note_declared_coroutine_here)
685 << FSI->getFirstCoroutineStmtKeyword();
686}
687
688bool Sema::ActOnCoroutineBodyStart(Scope *SC, SourceLocation KWLoc,
689 StringRef Keyword) {
690 // Ignore previous expr evaluation contexts.
691 EnterExpressionEvaluationContextForFunction PotentiallyEvaluated(
692 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated,
693 dyn_cast_or_null<FunctionDecl>(Val: CurContext));
694
695 if (!checkCoroutineContext(S&: *this, Loc: KWLoc, Keyword))
696 return false;
697 auto *ScopeInfo = getCurFunction();
698 assert(ScopeInfo->CoroutinePromise);
699
700 // Avoid duplicate errors, report only on first keyword.
701 if (ScopeInfo->FirstCoroutineStmtLoc == KWLoc)
702 checkReturnStmtInCoroutine(S&: *this, FSI: ScopeInfo);
703
704 // If we have existing coroutine statements then we have already built
705 // the initial and final suspend points.
706 if (!ScopeInfo->NeedsCoroutineSuspends)
707 return true;
708
709 ScopeInfo->setNeedsCoroutineSuspends(false);
710
711 auto *Fn = cast<FunctionDecl>(Val: CurContext);
712 SourceLocation Loc = Fn->getLocation();
713 // Build the initial suspend point
714 auto buildSuspends = [&](StringRef Name) mutable -> StmtResult {
715 ExprResult Operand =
716 buildPromiseCall(S&: *this, Promise: ScopeInfo->CoroutinePromise, Loc, Name, Args: {});
717 if (Operand.isInvalid())
718 return StmtError();
719 ExprResult Suspend =
720 buildOperatorCoawaitCall(SemaRef&: *this, S: SC, Loc, E: Operand.get());
721 if (Suspend.isInvalid())
722 return StmtError();
723 Suspend = BuildResolvedCoawaitExpr(KwLoc: Loc, Operand: Operand.get(), Awaiter: Suspend.get(),
724 /*IsImplicit*/ true);
725 Suspend = ActOnFinishFullExpr(Expr: Suspend.get(), /*DiscardedValue*/ false);
726 if (Suspend.isInvalid()) {
727 Diag(Loc, DiagID: diag::note_coroutine_promise_suspend_implicitly_required)
728 << ((Name == "initial_suspend") ? 0 : 1);
729 Diag(Loc: KWLoc, DiagID: diag::note_declared_coroutine_here) << Keyword;
730 return StmtError();
731 }
732 return cast<Stmt>(Val: Suspend.get());
733 };
734
735 StmtResult InitSuspend = buildSuspends("initial_suspend");
736 if (InitSuspend.isInvalid())
737 return true;
738
739 StmtResult FinalSuspend = buildSuspends("final_suspend");
740 if (FinalSuspend.isInvalid() || !checkFinalSuspendNoThrow(FinalSuspend: FinalSuspend.get()))
741 return true;
742
743 ScopeInfo->setCoroutineSuspends(Initial: InitSuspend.get(), Final: FinalSuspend.get());
744
745 return true;
746}
747
748// Recursively walks up the scope hierarchy until either a 'catch' or a function
749// scope is found, whichever comes first.
750static bool isWithinCatchScope(Scope *S) {
751 // 'co_await' and 'co_yield' keywords are disallowed within catch blocks, but
752 // lambdas that use 'co_await' are allowed. The loop below ends when a
753 // function scope is found in order to ensure the following behavior:
754 //
755 // void foo() { // <- function scope
756 // try { //
757 // co_await x; // <- 'co_await' is OK within a function scope
758 // } catch { // <- catch scope
759 // co_await x; // <- 'co_await' is not OK within a catch scope
760 // []() { // <- function scope
761 // co_await x; // <- 'co_await' is OK within a function scope
762 // }();
763 // }
764 // }
765 while (S && !S->isFunctionScope()) {
766 if (S->isCatchScope())
767 return true;
768 S = S->getParent();
769 }
770 return false;
771}
772
773// [expr.await]p2, emphasis added: "An await-expression shall appear only in
774// a *potentially evaluated* expression within the compound-statement of a
775// function-body *outside of a handler* [...] A context within a function
776// where an await-expression can appear is called a suspension context of the
777// function."
778static bool checkSuspensionContext(Sema &S, SourceLocation Loc,
779 StringRef Keyword) {
780 // First emphasis of [expr.await]p2: must be a potentially evaluated context.
781 // That is, 'co_await' and 'co_yield' cannot appear in subexpressions of
782 // \c sizeof.
783 const auto ExprContext = S.currentEvaluationContext().ExprContext;
784 const bool BadContext =
785 S.isUnevaluatedContext() ||
786 ExprContext != Sema::ExpressionEvaluationContextRecord::EK_Other;
787 if (BadContext) {
788 S.Diag(Loc, DiagID: diag::err_coroutine_unevaluated_context) << Keyword;
789 return false;
790 }
791
792 // Second emphasis of [expr.await]p2: must be outside of an exception handler.
793 if (isWithinCatchScope(S: S.getCurScope())) {
794 S.Diag(Loc, DiagID: diag::err_coroutine_within_handler) << Keyword;
795 return false;
796 }
797 return true;
798}
799
800ExprResult Sema::ActOnCoawaitExpr(Scope *S, SourceLocation Loc, Expr *E) {
801 if (!checkSuspensionContext(S&: *this, Loc, Keyword: "co_await"))
802 return ExprError();
803
804 if (!ActOnCoroutineBodyStart(SC: S, KWLoc: Loc, Keyword: "co_await")) {
805 return ExprError();
806 }
807
808 if (E->hasPlaceholderType()) {
809 ExprResult R = CheckPlaceholderExpr(E);
810 if (R.isInvalid()) return ExprError();
811 E = R.get();
812 }
813
814 ExprResult Lookup = BuildOperatorCoawaitLookupExpr(S, Loc);
815 if (Lookup.isInvalid())
816 return ExprError();
817 return BuildUnresolvedCoawaitExpr(KwLoc: Loc, Operand: E,
818 Lookup: cast<UnresolvedLookupExpr>(Val: Lookup.get()));
819}
820
821ExprResult Sema::BuildOperatorCoawaitLookupExpr(Scope *S, SourceLocation Loc) {
822 DeclarationName OpName =
823 Context.DeclarationNames.getCXXOperatorName(Op: OO_Coawait);
824 LookupResult Operators(*this, OpName, SourceLocation(),
825 Sema::LookupOperatorName);
826 LookupName(R&: Operators, S);
827
828 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
829 const auto &Functions = Operators.asUnresolvedSet();
830 Expr *CoawaitOp = UnresolvedLookupExpr::Create(
831 Context, /*NamingClass*/ nullptr, QualifierLoc: NestedNameSpecifierLoc(),
832 NameInfo: DeclarationNameInfo(OpName, Loc), /*RequiresADL*/ true, Begin: Functions.begin(),
833 End: Functions.end(), /*KnownDependent=*/false,
834 /*KnownInstantiationDependent=*/false);
835 assert(CoawaitOp);
836 return CoawaitOp;
837}
838
839static bool isAttributedCoroAwaitElidable(const QualType &QT) {
840 auto *Record = QT->getAsCXXRecordDecl();
841 return Record && Record->hasAttr<CoroAwaitElidableAttr>();
842}
843
844static void applySafeElideContext(Expr *Operand) {
845 auto *Call = dyn_cast<CallExpr>(Val: Operand->IgnoreImplicit());
846 if (!Call || !Call->isPRValue())
847 return;
848
849 if (!isAttributedCoroAwaitElidable(QT: Call->getType()))
850 return;
851
852 Call->setCoroElideSafe();
853
854 // Check parameter
855 auto *Fn = llvm::dyn_cast_if_present<FunctionDecl>(Val: Call->getCalleeDecl());
856 if (!Fn)
857 return;
858
859 size_t ParmIdx = 0;
860 for (ParmVarDecl *PD : Fn->parameters()) {
861 if (PD->hasAttr<CoroAwaitElidableArgumentAttr>())
862 applySafeElideContext(Operand: Call->getArg(Arg: ParmIdx));
863
864 ParmIdx++;
865 }
866}
867
868// Attempts to resolve and build a CoawaitExpr from "raw" inputs, bailing out to
869// DependentCoawaitExpr if needed.
870ExprResult Sema::BuildUnresolvedCoawaitExpr(SourceLocation Loc, Expr *Operand,
871 UnresolvedLookupExpr *Lookup) {
872 auto *FSI = checkCoroutineContext(S&: *this, Loc, Keyword: "co_await");
873 if (!FSI)
874 return ExprError();
875
876 if (Operand->hasPlaceholderType()) {
877 ExprResult R = CheckPlaceholderExpr(E: Operand);
878 if (R.isInvalid())
879 return ExprError();
880 Operand = R.get();
881 }
882
883 auto *Promise = FSI->CoroutinePromise;
884 if (Promise->getType()->isDependentType()) {
885 Expr *Res = new (Context)
886 DependentCoawaitExpr(Loc, Context.DependentTy, Operand, Lookup);
887 return Res;
888 }
889
890 auto *RD = Promise->getType()->getAsCXXRecordDecl();
891
892 bool CurFnAwaitElidable = isAttributedCoroAwaitElidable(
893 QT: getCurFunctionDecl(/*AllowLambda=*/true)->getReturnType());
894
895 if (CurFnAwaitElidable)
896 applySafeElideContext(Operand);
897
898 Expr *Transformed = Operand;
899 if (lookupMember(S&: *this, Name: "await_transform", RD, Loc)) {
900 ExprResult R =
901 buildPromiseCall(S&: *this, Promise, Loc, Name: "await_transform", Args: Operand);
902 if (R.isInvalid()) {
903 Diag(Loc,
904 DiagID: diag::note_coroutine_promise_implicit_await_transform_required_here)
905 << Operand->getSourceRange();
906 return ExprError();
907 }
908 Transformed = R.get();
909 }
910 ExprResult Awaiter = BuildOperatorCoawaitCall(Loc, E: Transformed, Lookup);
911 if (Awaiter.isInvalid())
912 return ExprError();
913
914 return BuildResolvedCoawaitExpr(KwLoc: Loc, Operand, Awaiter: Awaiter.get());
915}
916
917ExprResult Sema::BuildResolvedCoawaitExpr(SourceLocation Loc, Expr *Operand,
918 Expr *Awaiter, bool IsImplicit) {
919 auto *Coroutine = checkCoroutineContext(S&: *this, Loc, Keyword: "co_await", IsImplicit);
920 if (!Coroutine)
921 return ExprError();
922
923 if (Awaiter->hasPlaceholderType()) {
924 ExprResult R = CheckPlaceholderExpr(E: Awaiter);
925 if (R.isInvalid()) return ExprError();
926 Awaiter = R.get();
927 }
928
929 if (Awaiter->getType()->isDependentType()) {
930 Expr *Res = new (Context)
931 CoawaitExpr(Loc, Context.DependentTy, Operand, Awaiter, IsImplicit);
932 return Res;
933 }
934
935 // If the expression is a temporary, materialize it as an lvalue so that we
936 // can use it multiple times.
937 if (Awaiter->isPRValue())
938 Awaiter = CreateMaterializeTemporaryExpr(T: Awaiter->getType(), Temporary: Awaiter, BoundToLvalueReference: true);
939
940 // The location of the `co_await` token cannot be used when constructing
941 // the member call expressions since it's before the location of `Expr`, which
942 // is used as the start of the member call expression.
943 SourceLocation CallLoc = Awaiter->getExprLoc();
944
945 // Build the await_ready, await_suspend, await_resume calls.
946 ReadySuspendResumeResult RSS =
947 buildCoawaitCalls(S&: *this, CoroPromise: Coroutine->CoroutinePromise, Loc: CallLoc, E: Awaiter);
948 if (RSS.IsInvalid)
949 return ExprError();
950
951 Expr *Res = new (Context)
952 CoawaitExpr(Loc, Operand, Awaiter, RSS.Results[0], RSS.Results[1],
953 RSS.Results[2], RSS.OpaqueValue, IsImplicit);
954
955 return Res;
956}
957
958ExprResult Sema::ActOnCoyieldExpr(Scope *S, SourceLocation Loc, Expr *E) {
959 if (!checkSuspensionContext(S&: *this, Loc, Keyword: "co_yield"))
960 return ExprError();
961
962 if (!ActOnCoroutineBodyStart(SC: S, KWLoc: Loc, Keyword: "co_yield")) {
963 return ExprError();
964 }
965
966 // Build yield_value call.
967 ExprResult Awaitable = buildPromiseCall(
968 S&: *this, Promise: getCurFunction()->CoroutinePromise, Loc, Name: "yield_value", Args: E);
969 if (Awaitable.isInvalid())
970 return ExprError();
971
972 // Build 'operator co_await' call.
973 Awaitable = buildOperatorCoawaitCall(SemaRef&: *this, S, Loc, E: Awaitable.get());
974 if (Awaitable.isInvalid())
975 return ExprError();
976
977 return BuildCoyieldExpr(KwLoc: Loc, E: Awaitable.get());
978}
979ExprResult Sema::BuildCoyieldExpr(SourceLocation Loc, Expr *E) {
980 auto *Coroutine = checkCoroutineContext(S&: *this, Loc, Keyword: "co_yield");
981 if (!Coroutine)
982 return ExprError();
983
984 if (E->hasPlaceholderType()) {
985 ExprResult R = CheckPlaceholderExpr(E);
986 if (R.isInvalid()) return ExprError();
987 E = R.get();
988 }
989
990 Expr *Operand = E;
991
992 if (E->getType()->isDependentType()) {
993 Expr *Res = new (Context) CoyieldExpr(Loc, Context.DependentTy, Operand, E);
994 return Res;
995 }
996
997 // If the expression is a temporary, materialize it as an lvalue so that we
998 // can use it multiple times.
999 if (E->isPRValue())
1000 E = CreateMaterializeTemporaryExpr(T: E->getType(), Temporary: E, BoundToLvalueReference: true);
1001
1002 // Build the await_ready, await_suspend, await_resume calls.
1003 ReadySuspendResumeResult RSS = buildCoawaitCalls(
1004 S&: *this, CoroPromise: Coroutine->CoroutinePromise, Loc, E);
1005 if (RSS.IsInvalid)
1006 return ExprError();
1007
1008 Expr *Res =
1009 new (Context) CoyieldExpr(Loc, Operand, E, RSS.Results[0], RSS.Results[1],
1010 RSS.Results[2], RSS.OpaqueValue);
1011
1012 return Res;
1013}
1014
1015StmtResult Sema::ActOnCoreturnStmt(Scope *S, SourceLocation Loc, Expr *E) {
1016 if (!ActOnCoroutineBodyStart(SC: S, KWLoc: Loc, Keyword: "co_return")) {
1017 return StmtError();
1018 }
1019 return BuildCoreturnStmt(KwLoc: Loc, E);
1020}
1021
1022StmtResult Sema::BuildCoreturnStmt(SourceLocation Loc, Expr *E,
1023 bool IsImplicit) {
1024 auto *FSI = checkCoroutineContext(S&: *this, Loc, Keyword: "co_return", IsImplicit);
1025 if (!FSI)
1026 return StmtError();
1027
1028 if (E && E->hasPlaceholderType() &&
1029 !E->hasPlaceholderType(K: BuiltinType::Overload)) {
1030 ExprResult R = CheckPlaceholderExpr(E);
1031 if (R.isInvalid()) return StmtError();
1032 E = R.get();
1033 }
1034
1035 VarDecl *Promise = FSI->CoroutinePromise;
1036 ExprResult PC;
1037 if (E && (isa<InitListExpr>(Val: E) || !E->getType()->isVoidType())) {
1038 getNamedReturnInfo(E, Mode: SimplerImplicitMoveMode::ForceOn);
1039 PC = buildPromiseCall(S&: *this, Promise, Loc, Name: "return_value", Args: E);
1040 } else {
1041 E = MakeFullDiscardedValueExpr(Arg: E).get();
1042 PC = buildPromiseCall(S&: *this, Promise, Loc, Name: "return_void", Args: {});
1043 }
1044 if (PC.isInvalid())
1045 return StmtError();
1046
1047 Expr *PCE = ActOnFinishFullExpr(Expr: PC.get(), /*DiscardedValue*/ false).get();
1048
1049 Stmt *Res = new (Context) CoreturnStmt(Loc, E, PCE, IsImplicit);
1050 return Res;
1051}
1052
1053/// Look up the std::nothrow object.
1054static Expr *buildStdNoThrowDeclRef(Sema &S, SourceLocation Loc) {
1055 NamespaceDecl *Std = S.getStdNamespace();
1056 assert(Std && "Should already be diagnosed");
1057
1058 LookupResult Result(S, &S.PP.getIdentifierTable().get(Name: "nothrow"), Loc,
1059 Sema::LookupOrdinaryName);
1060 if (!S.LookupQualifiedName(R&: Result, LookupCtx: Std)) {
1061 // <coroutine> is not requred to include <new>, so we couldn't omit
1062 // the check here.
1063 S.Diag(Loc, DiagID: diag::err_implicit_coroutine_std_nothrow_type_not_found);
1064 return nullptr;
1065 }
1066
1067 auto *VD = Result.getAsSingle<VarDecl>();
1068 if (!VD) {
1069 Result.suppressDiagnostics();
1070 // We found something weird. Complain about the first thing we found.
1071 NamedDecl *Found = *Result.begin();
1072 S.Diag(Loc: Found->getLocation(), DiagID: diag::err_malformed_std_nothrow);
1073 return nullptr;
1074 }
1075
1076 ExprResult DR = S.BuildDeclRefExpr(D: VD, Ty: VD->getType(), VK: VK_LValue, Loc);
1077 if (DR.isInvalid())
1078 return nullptr;
1079
1080 return DR.get();
1081}
1082
1083static TypeSourceInfo *getTypeSourceInfoForStdAlignValT(Sema &S,
1084 SourceLocation Loc) {
1085 EnumDecl *StdAlignValT = S.getStdAlignValT();
1086 QualType StdAlignValDecl = S.Context.getTypeDeclType(Decl: StdAlignValT);
1087 return S.Context.getTrivialTypeSourceInfo(T: StdAlignValDecl);
1088}
1089
1090// When searching for custom allocators on the PromiseType we want to
1091// warn that we will ignore type aware allocators.
1092static bool DiagnoseTypeAwareAllocators(Sema &S, SourceLocation Loc,
1093 unsigned DiagnosticID,
1094 DeclarationName Name,
1095 QualType PromiseType) {
1096 assert(PromiseType->isRecordType());
1097
1098 LookupResult R(S, Name, Loc, Sema::LookupOrdinaryName);
1099 S.LookupQualifiedName(R, LookupCtx: PromiseType->getAsCXXRecordDecl());
1100 bool HaveIssuedWarning = false;
1101 for (auto Decl : R) {
1102 if (!Decl->getAsFunction()->isTypeAwareOperatorNewOrDelete())
1103 continue;
1104 if (!HaveIssuedWarning) {
1105 S.Diag(Loc, DiagID: DiagnosticID) << Name;
1106 HaveIssuedWarning = true;
1107 }
1108 S.Diag(Loc: Decl->getLocation(), DiagID: diag::note_type_aware_operator_declared)
1109 << /* isTypeAware=*/1 << Decl << Decl->getDeclContext();
1110 }
1111 R.suppressDiagnostics();
1112 return HaveIssuedWarning;
1113}
1114
1115// Find an appropriate delete for the promise.
1116static bool findDeleteForPromise(Sema &S, SourceLocation Loc, QualType PromiseType,
1117 FunctionDecl *&OperatorDelete) {
1118 DeclarationName DeleteName =
1119 S.Context.DeclarationNames.getCXXOperatorName(Op: OO_Delete);
1120 DiagnoseTypeAwareAllocators(S, Loc,
1121 DiagnosticID: diag::warn_coroutine_type_aware_allocator_ignored,
1122 Name: DeleteName, PromiseType);
1123 auto *PointeeRD = PromiseType->getAsCXXRecordDecl();
1124 assert(PointeeRD && "PromiseType must be a CxxRecordDecl type");
1125
1126 const bool Overaligned = S.getLangOpts().CoroAlignedAllocation;
1127
1128 // [dcl.fct.def.coroutine]p12
1129 // The deallocation function's name is looked up by searching for it in the
1130 // scope of the promise type. If nothing is found, a search is performed in
1131 // the global scope.
1132 ImplicitDeallocationParameters IDP = {
1133 alignedAllocationModeFromBool(IsAligned: Overaligned), SizedDeallocationMode::Yes};
1134 if (S.FindDeallocationFunction(StartLoc: Loc, RD: PointeeRD, Name: DeleteName, Operator&: OperatorDelete,
1135 IDP, /*Diagnose=*/true))
1136 return false;
1137
1138 // [dcl.fct.def.coroutine]p12
1139 // If both a usual deallocation function with only a pointer parameter and a
1140 // usual deallocation function with both a pointer parameter and a size
1141 // parameter are found, then the selected deallocation function shall be the
1142 // one with two parameters. Otherwise, the selected deallocation function
1143 // shall be the function with one parameter.
1144 if (!OperatorDelete) {
1145 // Look for a global declaration.
1146 // Sema::FindUsualDeallocationFunction will try to find the one with two
1147 // parameters first. It will return the deallocation function with one
1148 // parameter if failed.
1149 // Coroutines can always provide their required size.
1150 IDP.PassSize = SizedDeallocationMode::Yes;
1151 OperatorDelete = S.FindUsualDeallocationFunction(StartLoc: Loc, IDP, Name: DeleteName);
1152
1153 if (!OperatorDelete)
1154 return false;
1155 }
1156
1157 assert(!OperatorDelete->isTypeAwareOperatorNewOrDelete());
1158 S.MarkFunctionReferenced(Loc, Func: OperatorDelete);
1159 return true;
1160}
1161
1162
1163void Sema::CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body) {
1164 FunctionScopeInfo *Fn = getCurFunction();
1165 assert(Fn && Fn->isCoroutine() && "not a coroutine");
1166 if (!Body) {
1167 assert(FD->isInvalidDecl() &&
1168 "a null body is only allowed for invalid declarations");
1169 return;
1170 }
1171 // We have a function that uses coroutine keywords, but we failed to build
1172 // the promise type.
1173 if (!Fn->CoroutinePromise)
1174 return FD->setInvalidDecl();
1175
1176 if (isa<CoroutineBodyStmt>(Val: Body)) {
1177 // Nothing todo. the body is already a transformed coroutine body statement.
1178 return;
1179 }
1180
1181 // The always_inline attribute doesn't reliably apply to a coroutine,
1182 // because the coroutine will be split into pieces and some pieces
1183 // might be called indirectly, as in a virtual call. Even the ramp
1184 // function cannot be inlined at -O0, due to pipeline ordering
1185 // problems (see https://llvm.org/PR53413). Tell the user about it.
1186 if (FD->hasAttr<AlwaysInlineAttr>())
1187 Diag(Loc: FD->getLocation(), DiagID: diag::warn_always_inline_coroutine);
1188
1189 // The design of coroutines means we cannot allow use of VLAs within one, so
1190 // diagnose if we've seen a VLA in the body of this function.
1191 if (Fn->FirstVLALoc.isValid())
1192 Diag(Loc: Fn->FirstVLALoc, DiagID: diag::err_vla_in_coroutine_unsupported);
1193
1194 // Coroutines will get splitted into pieces. The GNU address of label
1195 // extension wouldn't be meaningful in coroutines.
1196 for (AddrLabelExpr *ALE : Fn->AddrLabels)
1197 Diag(Loc: ALE->getBeginLoc(), DiagID: diag::err_coro_invalid_addr_of_label);
1198
1199 // Coroutines always return a handle, so they can't be [[noreturn]].
1200 if (FD->isNoReturn())
1201 Diag(Loc: FD->getLocation(), DiagID: diag::warn_noreturn_coroutine) << FD;
1202
1203 CoroutineStmtBuilder Builder(*this, *FD, *Fn, Body);
1204 if (Builder.isInvalid() || !Builder.buildStatements())
1205 return FD->setInvalidDecl();
1206
1207 // Build body for the coroutine wrapper statement.
1208 Body = CoroutineBodyStmt::Create(C: Context, Args: Builder);
1209}
1210
1211static CompoundStmt *buildCoroutineBody(Stmt *Body, ASTContext &Context) {
1212 if (auto *CS = dyn_cast<CompoundStmt>(Val: Body))
1213 return CS;
1214
1215 // The body of the coroutine may be a try statement if it is in
1216 // 'function-try-block' syntax. Here we wrap it into a compound
1217 // statement for consistency.
1218 assert(isa<CXXTryStmt>(Body) && "Unimaged coroutine body type");
1219 return CompoundStmt::Create(C: Context, Stmts: {Body}, FPFeatures: FPOptionsOverride(),
1220 LB: SourceLocation(), RB: SourceLocation());
1221}
1222
1223CoroutineStmtBuilder::CoroutineStmtBuilder(Sema &S, FunctionDecl &FD,
1224 sema::FunctionScopeInfo &Fn,
1225 Stmt *Body)
1226 : S(S), FD(FD), Fn(Fn), Loc(FD.getLocation()),
1227 IsPromiseDependentType(
1228 !Fn.CoroutinePromise ||
1229 Fn.CoroutinePromise->getType()->isDependentType()) {
1230 this->Body = buildCoroutineBody(Body, Context&: S.getASTContext());
1231
1232 for (auto KV : Fn.CoroutineParameterMoves)
1233 this->ParamMovesVector.push_back(Elt: KV.second);
1234 this->ParamMoves = this->ParamMovesVector;
1235
1236 if (!IsPromiseDependentType) {
1237 PromiseRecordDecl = Fn.CoroutinePromise->getType()->getAsCXXRecordDecl();
1238 assert(PromiseRecordDecl && "Type should have already been checked");
1239 }
1240 this->IsValid = makePromiseStmt() && makeInitialAndFinalSuspend();
1241}
1242
1243bool CoroutineStmtBuilder::buildStatements() {
1244 assert(this->IsValid && "coroutine already invalid");
1245 this->IsValid = makeReturnObject();
1246 if (this->IsValid && !IsPromiseDependentType)
1247 buildDependentStatements();
1248 return this->IsValid;
1249}
1250
1251bool CoroutineStmtBuilder::buildDependentStatements() {
1252 assert(this->IsValid && "coroutine already invalid");
1253 assert(!this->IsPromiseDependentType &&
1254 "coroutine cannot have a dependent promise type");
1255 this->IsValid = makeOnException() && makeOnFallthrough() &&
1256 makeGroDeclAndReturnStmt() && makeReturnOnAllocFailure() &&
1257 makeNewAndDeleteExpr();
1258 return this->IsValid;
1259}
1260
1261bool CoroutineStmtBuilder::makePromiseStmt() {
1262 // Form a declaration statement for the promise declaration, so that AST
1263 // visitors can more easily find it.
1264 StmtResult PromiseStmt =
1265 S.ActOnDeclStmt(Decl: S.ConvertDeclToDeclGroup(Ptr: Fn.CoroutinePromise), StartLoc: Loc, EndLoc: Loc);
1266 if (PromiseStmt.isInvalid())
1267 return false;
1268
1269 this->Promise = PromiseStmt.get();
1270 return true;
1271}
1272
1273bool CoroutineStmtBuilder::makeInitialAndFinalSuspend() {
1274 if (Fn.hasInvalidCoroutineSuspends())
1275 return false;
1276 this->InitialSuspend = cast<Expr>(Val: Fn.CoroutineSuspends.first);
1277 this->FinalSuspend = cast<Expr>(Val: Fn.CoroutineSuspends.second);
1278 return true;
1279}
1280
1281static bool diagReturnOnAllocFailure(Sema &S, Expr *E,
1282 CXXRecordDecl *PromiseRecordDecl,
1283 FunctionScopeInfo &Fn) {
1284 auto Loc = E->getExprLoc();
1285 if (auto *DeclRef = dyn_cast_or_null<DeclRefExpr>(Val: E)) {
1286 auto *Decl = DeclRef->getDecl();
1287 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Val: Decl)) {
1288 if (Method->isStatic())
1289 return true;
1290 else
1291 Loc = Decl->getLocation();
1292 }
1293 }
1294
1295 S.Diag(
1296 Loc,
1297 DiagID: diag::err_coroutine_promise_get_return_object_on_allocation_failure)
1298 << PromiseRecordDecl;
1299 S.Diag(Loc: Fn.FirstCoroutineStmtLoc, DiagID: diag::note_declared_coroutine_here)
1300 << Fn.getFirstCoroutineStmtKeyword();
1301 return false;
1302}
1303
1304bool CoroutineStmtBuilder::makeReturnOnAllocFailure() {
1305 assert(!IsPromiseDependentType &&
1306 "cannot make statement while the promise type is dependent");
1307
1308 // [dcl.fct.def.coroutine]p10
1309 // If a search for the name get_return_object_on_allocation_failure in
1310 // the scope of the promise type ([class.member.lookup]) finds any
1311 // declarations, then the result of a call to an allocation function used to
1312 // obtain storage for the coroutine state is assumed to return nullptr if it
1313 // fails to obtain storage, ... If the allocation function returns nullptr,
1314 // ... and the return value is obtained by a call to
1315 // T::get_return_object_on_allocation_failure(), where T is the
1316 // promise type.
1317 DeclarationName DN =
1318 S.PP.getIdentifierInfo(Name: "get_return_object_on_allocation_failure");
1319 LookupResult Found(S, DN, Loc, Sema::LookupMemberName);
1320 if (!S.LookupQualifiedName(R&: Found, LookupCtx: PromiseRecordDecl))
1321 return true;
1322
1323 CXXScopeSpec SS;
1324 ExprResult DeclNameExpr =
1325 S.BuildDeclarationNameExpr(SS, R&: Found, /*NeedsADL=*/false);
1326 if (DeclNameExpr.isInvalid())
1327 return false;
1328
1329 if (!diagReturnOnAllocFailure(S, E: DeclNameExpr.get(), PromiseRecordDecl, Fn))
1330 return false;
1331
1332 ExprResult ReturnObjectOnAllocationFailure =
1333 S.BuildCallExpr(S: nullptr, Fn: DeclNameExpr.get(), LParenLoc: Loc, ArgExprs: {}, RParenLoc: Loc);
1334 if (ReturnObjectOnAllocationFailure.isInvalid())
1335 return false;
1336
1337 StmtResult ReturnStmt =
1338 S.BuildReturnStmt(ReturnLoc: Loc, RetValExp: ReturnObjectOnAllocationFailure.get());
1339 if (ReturnStmt.isInvalid()) {
1340 S.Diag(Loc: Found.getFoundDecl()->getLocation(), DiagID: diag::note_member_declared_here)
1341 << DN;
1342 S.Diag(Loc: Fn.FirstCoroutineStmtLoc, DiagID: diag::note_declared_coroutine_here)
1343 << Fn.getFirstCoroutineStmtKeyword();
1344 return false;
1345 }
1346
1347 this->ReturnStmtOnAllocFailure = ReturnStmt.get();
1348 return true;
1349}
1350
1351// Collect placement arguments for allocation function of coroutine FD.
1352// Return true if we collect placement arguments succesfully. Return false,
1353// otherwise.
1354static bool collectPlacementArgs(Sema &S, FunctionDecl &FD, SourceLocation Loc,
1355 SmallVectorImpl<Expr *> &PlacementArgs) {
1356 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: &FD)) {
1357 if (MD->isImplicitObjectMemberFunction() && !isLambdaCallOperator(MD)) {
1358 ExprResult ThisExpr = S.ActOnCXXThis(Loc);
1359 if (ThisExpr.isInvalid())
1360 return false;
1361 ThisExpr = S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_Deref, InputExpr: ThisExpr.get());
1362 if (ThisExpr.isInvalid())
1363 return false;
1364 PlacementArgs.push_back(Elt: ThisExpr.get());
1365 }
1366 }
1367
1368 for (auto *PD : FD.parameters()) {
1369 if (PD->getType()->isDependentType())
1370 continue;
1371
1372 // Build a reference to the parameter.
1373 auto PDLoc = PD->getLocation();
1374 ExprResult PDRefExpr =
1375 S.BuildDeclRefExpr(D: PD, Ty: PD->getOriginalType().getNonReferenceType(),
1376 VK: ExprValueKind::VK_LValue, Loc: PDLoc);
1377 if (PDRefExpr.isInvalid())
1378 return false;
1379
1380 PlacementArgs.push_back(Elt: PDRefExpr.get());
1381 }
1382
1383 return true;
1384}
1385
1386bool CoroutineStmtBuilder::makeNewAndDeleteExpr() {
1387 // Form and check allocation and deallocation calls.
1388 assert(!IsPromiseDependentType &&
1389 "cannot make statement while the promise type is dependent");
1390 QualType PromiseType = Fn.CoroutinePromise->getType();
1391
1392 if (S.RequireCompleteType(Loc, T: PromiseType, DiagID: diag::err_incomplete_type))
1393 return false;
1394
1395 const bool RequiresNoThrowAlloc = ReturnStmtOnAllocFailure != nullptr;
1396
1397 // According to [dcl.fct.def.coroutine]p9, Lookup allocation functions using a
1398 // parameter list composed of the requested size of the coroutine state being
1399 // allocated, followed by the coroutine function's arguments. If a matching
1400 // allocation function exists, use it. Otherwise, use an allocation function
1401 // that just takes the requested size.
1402 //
1403 // [dcl.fct.def.coroutine]p9
1404 // An implementation may need to allocate additional storage for a
1405 // coroutine.
1406 // This storage is known as the coroutine state and is obtained by calling a
1407 // non-array allocation function ([basic.stc.dynamic.allocation]). The
1408 // allocation function's name is looked up by searching for it in the scope of
1409 // the promise type.
1410 // - If any declarations are found, overload resolution is performed on a
1411 // function call created by assembling an argument list. The first argument is
1412 // the amount of space requested, and has type std::size_t. The
1413 // lvalues p1 ... pn are the succeeding arguments.
1414 //
1415 // ...where "p1 ... pn" are defined earlier as:
1416 //
1417 // [dcl.fct.def.coroutine]p3
1418 // The promise type of a coroutine is `std::coroutine_traits<R, P1, ...,
1419 // Pn>`
1420 // , where R is the return type of the function, and `P1, ..., Pn` are the
1421 // sequence of types of the non-object function parameters, preceded by the
1422 // type of the object parameter ([dcl.fct]) if the coroutine is a non-static
1423 // member function. [dcl.fct.def.coroutine]p4 In the following, p_i is an
1424 // lvalue of type P_i, where p1 denotes the object parameter and p_i+1 denotes
1425 // the i-th non-object function parameter for a non-static member function,
1426 // and p_i denotes the i-th function parameter otherwise. For a non-static
1427 // member function, q_1 is an lvalue that denotes *this; any other q_i is an
1428 // lvalue that denotes the parameter copy corresponding to p_i.
1429
1430 FunctionDecl *OperatorNew = nullptr;
1431 SmallVector<Expr *, 1> PlacementArgs;
1432 DeclarationName NewName =
1433 S.getASTContext().DeclarationNames.getCXXOperatorName(Op: OO_New);
1434
1435 const bool PromiseContainsNew = [this, &PromiseType, NewName]() -> bool {
1436 LookupResult R(S, NewName, Loc, Sema::LookupOrdinaryName);
1437
1438 if (PromiseType->isRecordType())
1439 S.LookupQualifiedName(R, LookupCtx: PromiseType->getAsCXXRecordDecl());
1440
1441 return !R.empty() && !R.isAmbiguous();
1442 }();
1443
1444 // Helper function to indicate whether the last lookup found the aligned
1445 // allocation function.
1446 ImplicitAllocationParameters IAP(
1447 alignedAllocationModeFromBool(IsAligned: S.getLangOpts().CoroAlignedAllocation));
1448 auto LookupAllocationFunction = [&](AllocationFunctionScope NewScope =
1449 AllocationFunctionScope::Both,
1450 bool WithoutPlacementArgs = false,
1451 bool ForceNonAligned = false) {
1452 // [dcl.fct.def.coroutine]p9
1453 // The allocation function's name is looked up by searching for it in the
1454 // scope of the promise type.
1455 // - If any declarations are found, ...
1456 // - If no declarations are found in the scope of the promise type, a search
1457 // is performed in the global scope.
1458 if (NewScope == AllocationFunctionScope::Both)
1459 NewScope = PromiseContainsNew ? AllocationFunctionScope::Class
1460 : AllocationFunctionScope::Global;
1461
1462 bool ShouldUseAlignedAlloc =
1463 !ForceNonAligned && S.getLangOpts().CoroAlignedAllocation;
1464 IAP = ImplicitAllocationParameters(
1465 alignedAllocationModeFromBool(IsAligned: ShouldUseAlignedAlloc));
1466
1467 FunctionDecl *UnusedResult = nullptr;
1468 S.FindAllocationFunctions(
1469 StartLoc: Loc, Range: SourceRange(), NewScope,
1470 /*DeleteScope=*/AllocationFunctionScope::Both, AllocType: PromiseType,
1471 /*isArray=*/IsArray: false, IAP,
1472 PlaceArgs: WithoutPlacementArgs ? MultiExprArg{} : PlacementArgs, OperatorNew,
1473 OperatorDelete&: UnusedResult, /*Diagnose=*/false);
1474 assert(!OperatorNew || !OperatorNew->isTypeAwareOperatorNewOrDelete());
1475 };
1476
1477 // We don't expect to call to global operator new with (size, p0, …, pn).
1478 // So if we choose to lookup the allocation function in global scope, we
1479 // shouldn't lookup placement arguments.
1480 if (PromiseContainsNew && !collectPlacementArgs(S, FD, Loc, PlacementArgs))
1481 return false;
1482
1483 LookupAllocationFunction();
1484
1485 if (PromiseContainsNew && !PlacementArgs.empty()) {
1486 // [dcl.fct.def.coroutine]p9
1487 // If no viable function is found ([over.match.viable]), overload
1488 // resolution
1489 // is performed again on a function call created by passing just the amount
1490 // of space required as an argument of type std::size_t.
1491 //
1492 // Proposed Change of [dcl.fct.def.coroutine]p9 in P2014R0:
1493 // Otherwise, overload resolution is performed again on a function call
1494 // created
1495 // by passing the amount of space requested as an argument of type
1496 // std::size_t as the first argument, and the requested alignment as
1497 // an argument of type std:align_val_t as the second argument.
1498 if (!OperatorNew || (S.getLangOpts().CoroAlignedAllocation &&
1499 !isAlignedAllocation(Mode: IAP.PassAlignment)))
1500 LookupAllocationFunction(/*NewScope*/ AllocationFunctionScope::Class,
1501 /*WithoutPlacementArgs*/ true);
1502 }
1503
1504 // Proposed Change of [dcl.fct.def.coroutine]p12 in P2014R0:
1505 // Otherwise, overload resolution is performed again on a function call
1506 // created
1507 // by passing the amount of space requested as an argument of type
1508 // std::size_t as the first argument, and the lvalues p1 ... pn as the
1509 // succeeding arguments. Otherwise, overload resolution is performed again
1510 // on a function call created by passing just the amount of space required as
1511 // an argument of type std::size_t.
1512 //
1513 // So within the proposed change in P2014RO, the priority order of aligned
1514 // allocation functions wiht promise_type is:
1515 //
1516 // void* operator new( std::size_t, std::align_val_t, placement_args... );
1517 // void* operator new( std::size_t, std::align_val_t);
1518 // void* operator new( std::size_t, placement_args... );
1519 // void* operator new( std::size_t);
1520
1521 // Helper variable to emit warnings.
1522 bool FoundNonAlignedInPromise = false;
1523 if (PromiseContainsNew && S.getLangOpts().CoroAlignedAllocation)
1524 if (!OperatorNew || !isAlignedAllocation(Mode: IAP.PassAlignment)) {
1525 FoundNonAlignedInPromise = OperatorNew;
1526
1527 LookupAllocationFunction(/*NewScope*/ AllocationFunctionScope::Class,
1528 /*WithoutPlacementArgs*/ false,
1529 /*ForceNonAligned*/ true);
1530
1531 if (!OperatorNew && !PlacementArgs.empty())
1532 LookupAllocationFunction(/*NewScope*/ AllocationFunctionScope::Class,
1533 /*WithoutPlacementArgs*/ true,
1534 /*ForceNonAligned*/ true);
1535 }
1536
1537 bool IsGlobalOverload =
1538 OperatorNew && !isa<CXXRecordDecl>(Val: OperatorNew->getDeclContext());
1539 // If we didn't find a class-local new declaration and non-throwing new
1540 // was is required then we need to lookup the non-throwing global operator
1541 // instead.
1542 if (RequiresNoThrowAlloc && (!OperatorNew || IsGlobalOverload)) {
1543 auto *StdNoThrow = buildStdNoThrowDeclRef(S, Loc);
1544 if (!StdNoThrow)
1545 return false;
1546 PlacementArgs = {StdNoThrow};
1547 OperatorNew = nullptr;
1548 LookupAllocationFunction(AllocationFunctionScope::Global);
1549 }
1550
1551 // If we found a non-aligned allocation function in the promise_type,
1552 // it indicates the user forgot to update the allocation function. Let's emit
1553 // a warning here.
1554 if (FoundNonAlignedInPromise) {
1555 S.Diag(Loc: OperatorNew->getLocation(),
1556 DiagID: diag::warn_non_aligned_allocation_function)
1557 << &FD;
1558 }
1559
1560 if (!OperatorNew) {
1561 if (PromiseContainsNew) {
1562 S.Diag(Loc, DiagID: diag::err_coroutine_unusable_new) << PromiseType << &FD;
1563 DiagnoseTypeAwareAllocators(
1564 S, Loc, DiagnosticID: diag::note_coroutine_unusable_type_aware_allocators, Name: NewName,
1565 PromiseType);
1566 } else if (RequiresNoThrowAlloc)
1567 S.Diag(Loc, DiagID: diag::err_coroutine_unfound_nothrow_new)
1568 << &FD << S.getLangOpts().CoroAlignedAllocation;
1569
1570 return false;
1571 }
1572 assert(!OperatorNew->isTypeAwareOperatorNewOrDelete());
1573
1574 DiagnoseTypeAwareAllocators(S, Loc,
1575 DiagnosticID: diag::warn_coroutine_type_aware_allocator_ignored,
1576 Name: NewName, PromiseType);
1577
1578 if (RequiresNoThrowAlloc) {
1579 const auto *FT = OperatorNew->getType()->castAs<FunctionProtoType>();
1580 if (!FT->isNothrow(/*ResultIfDependent*/ false)) {
1581 S.Diag(Loc: OperatorNew->getLocation(),
1582 DiagID: diag::err_coroutine_promise_new_requires_nothrow)
1583 << OperatorNew;
1584 S.Diag(Loc, DiagID: diag::note_coroutine_promise_call_implicitly_required)
1585 << OperatorNew;
1586 return false;
1587 }
1588 }
1589
1590 FunctionDecl *OperatorDelete = nullptr;
1591 if (!findDeleteForPromise(S, Loc, PromiseType, OperatorDelete)) {
1592 // FIXME: We should add an error here. According to:
1593 // [dcl.fct.def.coroutine]p12
1594 // If no usual deallocation function is found, the program is ill-formed.
1595 return false;
1596 }
1597
1598 assert(!OperatorDelete->isTypeAwareOperatorNewOrDelete());
1599
1600 Expr *FramePtr =
1601 S.BuildBuiltinCallExpr(Loc, Id: Builtin::BI__builtin_coro_frame, CallArgs: {});
1602
1603 Expr *FrameSize =
1604 S.BuildBuiltinCallExpr(Loc, Id: Builtin::BI__builtin_coro_size, CallArgs: {});
1605
1606 Expr *FrameAlignment = nullptr;
1607
1608 if (S.getLangOpts().CoroAlignedAllocation) {
1609 FrameAlignment =
1610 S.BuildBuiltinCallExpr(Loc, Id: Builtin::BI__builtin_coro_align, CallArgs: {});
1611
1612 TypeSourceInfo *AlignValTy = getTypeSourceInfoForStdAlignValT(S, Loc);
1613 if (!AlignValTy)
1614 return false;
1615
1616 FrameAlignment = S.BuildCXXNamedCast(OpLoc: Loc, Kind: tok::kw_static_cast, Ty: AlignValTy,
1617 E: FrameAlignment, AngleBrackets: SourceRange(Loc, Loc),
1618 Parens: SourceRange(Loc, Loc))
1619 .get();
1620 }
1621
1622 // Make new call.
1623 ExprResult NewRef =
1624 S.BuildDeclRefExpr(D: OperatorNew, Ty: OperatorNew->getType(), VK: VK_LValue, Loc);
1625 if (NewRef.isInvalid())
1626 return false;
1627
1628 SmallVector<Expr *, 2> NewArgs(1, FrameSize);
1629 if (S.getLangOpts().CoroAlignedAllocation &&
1630 isAlignedAllocation(Mode: IAP.PassAlignment))
1631 NewArgs.push_back(Elt: FrameAlignment);
1632
1633 if (OperatorNew->getNumParams() > NewArgs.size())
1634 llvm::append_range(C&: NewArgs, R&: PlacementArgs);
1635
1636 ExprResult NewExpr =
1637 S.BuildCallExpr(S: S.getCurScope(), Fn: NewRef.get(), LParenLoc: Loc, ArgExprs: NewArgs, RParenLoc: Loc);
1638 NewExpr = S.ActOnFinishFullExpr(Expr: NewExpr.get(), /*DiscardedValue*/ false);
1639 if (NewExpr.isInvalid())
1640 return false;
1641
1642 // Make delete call.
1643
1644 QualType OpDeleteQualType = OperatorDelete->getType();
1645
1646 ExprResult DeleteRef =
1647 S.BuildDeclRefExpr(D: OperatorDelete, Ty: OpDeleteQualType, VK: VK_LValue, Loc);
1648 if (DeleteRef.isInvalid())
1649 return false;
1650
1651 Expr *CoroFree =
1652 S.BuildBuiltinCallExpr(Loc, Id: Builtin::BI__builtin_coro_free, CallArgs: {FramePtr});
1653
1654 SmallVector<Expr *, 2> DeleteArgs{CoroFree};
1655
1656 // [dcl.fct.def.coroutine]p12
1657 // The selected deallocation function shall be called with the address of
1658 // the block of storage to be reclaimed as its first argument. If a
1659 // deallocation function with a parameter of type std::size_t is
1660 // used, the size of the block is passed as the corresponding argument.
1661 const auto *OpDeleteType =
1662 OpDeleteQualType.getTypePtr()->castAs<FunctionProtoType>();
1663 if (OpDeleteType->getNumParams() > DeleteArgs.size() &&
1664 S.getASTContext().hasSameUnqualifiedType(
1665 T1: OpDeleteType->getParamType(i: DeleteArgs.size()), T2: FrameSize->getType()))
1666 DeleteArgs.push_back(Elt: FrameSize);
1667
1668 // Proposed Change of [dcl.fct.def.coroutine]p12 in P2014R0:
1669 // If deallocation function lookup finds a usual deallocation function with
1670 // a pointer parameter, size parameter and alignment parameter then this
1671 // will be the selected deallocation function, otherwise if lookup finds a
1672 // usual deallocation function with both a pointer parameter and a size
1673 // parameter, then this will be the selected deallocation function.
1674 // Otherwise, if lookup finds a usual deallocation function with only a
1675 // pointer parameter, then this will be the selected deallocation
1676 // function.
1677 //
1678 // So we are not forced to pass alignment to the deallocation function.
1679 if (S.getLangOpts().CoroAlignedAllocation &&
1680 OpDeleteType->getNumParams() > DeleteArgs.size() &&
1681 S.getASTContext().hasSameUnqualifiedType(
1682 T1: OpDeleteType->getParamType(i: DeleteArgs.size()),
1683 T2: FrameAlignment->getType()))
1684 DeleteArgs.push_back(Elt: FrameAlignment);
1685
1686 ExprResult DeleteExpr =
1687 S.BuildCallExpr(S: S.getCurScope(), Fn: DeleteRef.get(), LParenLoc: Loc, ArgExprs: DeleteArgs, RParenLoc: Loc);
1688 DeleteExpr =
1689 S.ActOnFinishFullExpr(Expr: DeleteExpr.get(), /*DiscardedValue*/ false);
1690 if (DeleteExpr.isInvalid())
1691 return false;
1692
1693 this->Allocate = NewExpr.get();
1694 this->Deallocate = DeleteExpr.get();
1695
1696 return true;
1697}
1698
1699bool CoroutineStmtBuilder::makeOnFallthrough() {
1700 assert(!IsPromiseDependentType &&
1701 "cannot make statement while the promise type is dependent");
1702
1703 // [dcl.fct.def.coroutine]/p6
1704 // If searches for the names return_void and return_value in the scope of
1705 // the promise type each find any declarations, the program is ill-formed.
1706 // [Note 1: If return_void is found, flowing off the end of a coroutine is
1707 // equivalent to a co_return with no operand. Otherwise, flowing off the end
1708 // of a coroutine results in undefined behavior ([stmt.return.coroutine]). —
1709 // end note]
1710 bool HasRVoid, HasRValue;
1711 LookupResult LRVoid =
1712 lookupMember(S, Name: "return_void", RD: PromiseRecordDecl, Loc, Res&: HasRVoid);
1713 LookupResult LRValue =
1714 lookupMember(S, Name: "return_value", RD: PromiseRecordDecl, Loc, Res&: HasRValue);
1715
1716 StmtResult Fallthrough;
1717 if (HasRVoid && HasRValue) {
1718 // FIXME Improve this diagnostic
1719 S.Diag(Loc: FD.getLocation(),
1720 DiagID: diag::err_coroutine_promise_incompatible_return_functions)
1721 << PromiseRecordDecl;
1722 S.Diag(Loc: LRVoid.getRepresentativeDecl()->getLocation(),
1723 DiagID: diag::note_member_first_declared_here)
1724 << LRVoid.getLookupName();
1725 S.Diag(Loc: LRValue.getRepresentativeDecl()->getLocation(),
1726 DiagID: diag::note_member_first_declared_here)
1727 << LRValue.getLookupName();
1728 return false;
1729 } else if (!HasRVoid && !HasRValue) {
1730 // We need to set 'Fallthrough'. Otherwise the other analysis part might
1731 // think the coroutine has defined a return_value method. So it might emit
1732 // **false** positive warning. e.g.,
1733 //
1734 // promise_without_return_func foo() {
1735 // co_await something();
1736 // }
1737 //
1738 // Then AnalysisBasedWarning would emit a warning about `foo()` lacking a
1739 // co_return statements, which isn't correct.
1740 Fallthrough = S.ActOnNullStmt(SemiLoc: PromiseRecordDecl->getLocation());
1741 if (Fallthrough.isInvalid())
1742 return false;
1743 } else if (HasRVoid) {
1744 Fallthrough = S.BuildCoreturnStmt(Loc: FD.getLocation(), E: nullptr,
1745 /*IsImplicit=*/true);
1746 Fallthrough = S.ActOnFinishFullStmt(Stmt: Fallthrough.get());
1747 if (Fallthrough.isInvalid())
1748 return false;
1749 }
1750
1751 this->OnFallthrough = Fallthrough.get();
1752 return true;
1753}
1754
1755bool CoroutineStmtBuilder::makeOnException() {
1756 // Try to form 'p.unhandled_exception();'
1757 assert(!IsPromiseDependentType &&
1758 "cannot make statement while the promise type is dependent");
1759
1760 const bool RequireUnhandledException = S.getLangOpts().CXXExceptions;
1761
1762 if (!lookupMember(S, Name: "unhandled_exception", RD: PromiseRecordDecl, Loc)) {
1763 auto DiagID =
1764 RequireUnhandledException
1765 ? diag::err_coroutine_promise_unhandled_exception_required
1766 : diag::
1767 warn_coroutine_promise_unhandled_exception_required_with_exceptions;
1768 S.Diag(Loc, DiagID) << PromiseRecordDecl;
1769 S.Diag(Loc: PromiseRecordDecl->getLocation(), DiagID: diag::note_defined_here)
1770 << PromiseRecordDecl;
1771 return !RequireUnhandledException;
1772 }
1773
1774 // If exceptions are disabled, don't try to build OnException.
1775 if (!S.getLangOpts().CXXExceptions)
1776 return true;
1777
1778 ExprResult UnhandledException =
1779 buildPromiseCall(S, Promise: Fn.CoroutinePromise, Loc, Name: "unhandled_exception", Args: {});
1780 UnhandledException = S.ActOnFinishFullExpr(Expr: UnhandledException.get(), CC: Loc,
1781 /*DiscardedValue*/ false);
1782 if (UnhandledException.isInvalid())
1783 return false;
1784
1785 // Since the body of the coroutine will be wrapped in try-catch, it will
1786 // be incompatible with SEH __try if present in a function.
1787 if (!S.getLangOpts().Borland && Fn.FirstSEHTryLoc.isValid()) {
1788 S.Diag(Loc: Fn.FirstSEHTryLoc, DiagID: diag::err_seh_in_a_coroutine_with_cxx_exceptions);
1789 S.Diag(Loc: Fn.FirstCoroutineStmtLoc, DiagID: diag::note_declared_coroutine_here)
1790 << Fn.getFirstCoroutineStmtKeyword();
1791 return false;
1792 }
1793
1794 this->OnException = UnhandledException.get();
1795 return true;
1796}
1797
1798bool CoroutineStmtBuilder::makeReturnObject() {
1799 // [dcl.fct.def.coroutine]p7
1800 // The expression promise.get_return_object() is used to initialize the
1801 // returned reference or prvalue result object of a call to a coroutine.
1802 ExprResult ReturnObject =
1803 buildPromiseCall(S, Promise: Fn.CoroutinePromise, Loc, Name: "get_return_object", Args: {});
1804 if (ReturnObject.isInvalid())
1805 return false;
1806
1807 this->ReturnValue = ReturnObject.get();
1808 return true;
1809}
1810
1811static void noteMemberDeclaredHere(Sema &S, Expr *E, FunctionScopeInfo &Fn) {
1812 if (auto *MbrRef = dyn_cast<CXXMemberCallExpr>(Val: E)) {
1813 auto *MethodDecl = MbrRef->getMethodDecl();
1814 S.Diag(Loc: MethodDecl->getLocation(), DiagID: diag::note_member_declared_here)
1815 << MethodDecl;
1816 }
1817 S.Diag(Loc: Fn.FirstCoroutineStmtLoc, DiagID: diag::note_declared_coroutine_here)
1818 << Fn.getFirstCoroutineStmtKeyword();
1819}
1820
1821bool CoroutineStmtBuilder::makeGroDeclAndReturnStmt() {
1822 assert(!IsPromiseDependentType &&
1823 "cannot make statement while the promise type is dependent");
1824 assert(this->ReturnValue && "ReturnValue must be already formed");
1825
1826 QualType const GroType = this->ReturnValue->getType();
1827 assert(!GroType->isDependentType() &&
1828 "get_return_object type must no longer be dependent");
1829
1830 QualType const FnRetType = FD.getReturnType();
1831 assert(!FnRetType->isDependentType() &&
1832 "get_return_object type must no longer be dependent");
1833
1834 // The call to get_­return_­object is sequenced before the call to
1835 // initial_­suspend and is invoked at most once, but there are caveats
1836 // regarding on whether the prvalue result object may be initialized
1837 // directly/eager or delayed, depending on the types involved.
1838 //
1839 // More info at https://github.com/cplusplus/papers/issues/1414
1840 bool GroMatchesRetType = S.getASTContext().hasSameType(T1: GroType, T2: FnRetType);
1841
1842 if (FnRetType->isVoidType()) {
1843 ExprResult Res =
1844 S.ActOnFinishFullExpr(Expr: this->ReturnValue, CC: Loc, /*DiscardedValue*/ false);
1845 if (Res.isInvalid())
1846 return false;
1847
1848 if (!GroMatchesRetType)
1849 this->ResultDecl = Res.get();
1850 return true;
1851 }
1852
1853 if (GroType->isVoidType()) {
1854 // Trigger a nice error message.
1855 InitializedEntity Entity =
1856 InitializedEntity::InitializeResult(ReturnLoc: Loc, Type: FnRetType);
1857 S.PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: ReturnValue);
1858 noteMemberDeclaredHere(S, E: ReturnValue, Fn);
1859 return false;
1860 }
1861
1862 StmtResult ReturnStmt;
1863 clang::VarDecl *GroDecl = nullptr;
1864 if (GroMatchesRetType) {
1865 ReturnStmt = S.BuildReturnStmt(ReturnLoc: Loc, RetValExp: ReturnValue);
1866 } else {
1867 GroDecl = VarDecl::Create(
1868 C&: S.Context, DC: &FD, StartLoc: FD.getLocation(), IdLoc: FD.getLocation(),
1869 Id: &S.PP.getIdentifierTable().get(Name: "__coro_gro"), T: GroType,
1870 TInfo: S.Context.getTrivialTypeSourceInfo(T: GroType, Loc), S: SC_None);
1871 GroDecl->setImplicit();
1872
1873 S.CheckVariableDeclarationType(NewVD: GroDecl);
1874 if (GroDecl->isInvalidDecl())
1875 return false;
1876
1877 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var: GroDecl);
1878 ExprResult Res =
1879 S.PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: ReturnValue);
1880 if (Res.isInvalid())
1881 return false;
1882
1883 Res = S.ActOnFinishFullExpr(Expr: Res.get(), /*DiscardedValue*/ false);
1884 if (Res.isInvalid())
1885 return false;
1886
1887 S.AddInitializerToDecl(dcl: GroDecl, init: Res.get(),
1888 /*DirectInit=*/false);
1889
1890 S.FinalizeDeclaration(D: GroDecl);
1891
1892 // Form a declaration statement for the return declaration, so that AST
1893 // visitors can more easily find it.
1894 StmtResult GroDeclStmt =
1895 S.ActOnDeclStmt(Decl: S.ConvertDeclToDeclGroup(Ptr: GroDecl), StartLoc: Loc, EndLoc: Loc);
1896 if (GroDeclStmt.isInvalid())
1897 return false;
1898
1899 this->ResultDecl = GroDeclStmt.get();
1900
1901 ExprResult declRef = S.BuildDeclRefExpr(D: GroDecl, Ty: GroType, VK: VK_LValue, Loc);
1902 if (declRef.isInvalid())
1903 return false;
1904
1905 ReturnStmt = S.BuildReturnStmt(ReturnLoc: Loc, RetValExp: declRef.get());
1906 }
1907
1908 if (ReturnStmt.isInvalid()) {
1909 noteMemberDeclaredHere(S, E: ReturnValue, Fn);
1910 return false;
1911 }
1912
1913 if (!GroMatchesRetType &&
1914 cast<clang::ReturnStmt>(Val: ReturnStmt.get())->getNRVOCandidate() == GroDecl)
1915 GroDecl->setNRVOVariable(true);
1916
1917 this->ReturnStmt = ReturnStmt.get();
1918 return true;
1919}
1920
1921// Create a static_cast\<T&&>(expr).
1922static Expr *castForMoving(Sema &S, Expr *E, QualType T = QualType()) {
1923 if (T.isNull())
1924 T = E->getType();
1925 QualType TargetType = S.BuildReferenceType(
1926 T, /*SpelledAsLValue*/ LValueRef: false, Loc: SourceLocation(), Entity: DeclarationName());
1927 SourceLocation ExprLoc = E->getBeginLoc();
1928 TypeSourceInfo *TargetLoc =
1929 S.Context.getTrivialTypeSourceInfo(T: TargetType, Loc: ExprLoc);
1930
1931 return S
1932 .BuildCXXNamedCast(OpLoc: ExprLoc, Kind: tok::kw_static_cast, Ty: TargetLoc, E,
1933 AngleBrackets: SourceRange(ExprLoc, ExprLoc), Parens: E->getSourceRange())
1934 .get();
1935}
1936
1937/// Build a variable declaration for move parameter.
1938static VarDecl *buildVarDecl(Sema &S, SourceLocation Loc, QualType Type,
1939 IdentifierInfo *II) {
1940 TypeSourceInfo *TInfo = S.Context.getTrivialTypeSourceInfo(T: Type, Loc);
1941 VarDecl *Decl = VarDecl::Create(C&: S.Context, DC: S.CurContext, StartLoc: Loc, IdLoc: Loc, Id: II, T: Type,
1942 TInfo, S: SC_None);
1943 Decl->setImplicit();
1944 return Decl;
1945}
1946
1947// Build statements that move coroutine function parameters to the coroutine
1948// frame, and store them on the function scope info.
1949bool Sema::buildCoroutineParameterMoves(SourceLocation Loc) {
1950 assert(isa<FunctionDecl>(CurContext) && "not in a function scope");
1951 auto *FD = cast<FunctionDecl>(Val: CurContext);
1952
1953 auto *ScopeInfo = getCurFunction();
1954 if (!ScopeInfo->CoroutineParameterMoves.empty())
1955 return false;
1956
1957 // [dcl.fct.def.coroutine]p13
1958 // When a coroutine is invoked, after initializing its parameters
1959 // ([expr.call]), a copy is created for each coroutine parameter. For a
1960 // parameter of type cv T, the copy is a variable of type cv T with
1961 // automatic storage duration that is direct-initialized from an xvalue of
1962 // type T referring to the parameter.
1963 for (auto *PD : FD->parameters()) {
1964 if (PD->getType()->isDependentType())
1965 continue;
1966
1967 // Preserve the referenced state for unused parameter diagnostics.
1968 bool DeclReferenced = PD->isReferenced();
1969
1970 ExprResult PDRefExpr =
1971 BuildDeclRefExpr(D: PD, Ty: PD->getType().getNonReferenceType(),
1972 VK: ExprValueKind::VK_LValue, Loc); // FIXME: scope?
1973
1974 PD->setReferenced(DeclReferenced);
1975
1976 if (PDRefExpr.isInvalid())
1977 return false;
1978
1979 Expr *CExpr = nullptr;
1980 if (PD->getType()->getAsCXXRecordDecl() ||
1981 PD->getType()->isRValueReferenceType())
1982 CExpr = castForMoving(S&: *this, E: PDRefExpr.get());
1983 else
1984 CExpr = PDRefExpr.get();
1985 // [dcl.fct.def.coroutine]p13
1986 // The initialization and destruction of each parameter copy occurs in the
1987 // context of the called coroutine.
1988 auto *D = buildVarDecl(S&: *this, Loc, Type: PD->getType(), II: PD->getIdentifier());
1989 AddInitializerToDecl(dcl: D, init: CExpr, /*DirectInit=*/true);
1990
1991 // Convert decl to a statement.
1992 StmtResult Stmt = ActOnDeclStmt(Decl: ConvertDeclToDeclGroup(Ptr: D), StartLoc: Loc, EndLoc: Loc);
1993 if (Stmt.isInvalid())
1994 return false;
1995
1996 ScopeInfo->CoroutineParameterMoves.insert(KV: std::make_pair(x&: PD, y: Stmt.get()));
1997 }
1998 return true;
1999}
2000
2001StmtResult Sema::BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
2002 CoroutineBodyStmt *Res = CoroutineBodyStmt::Create(C: Context, Args);
2003 if (!Res)
2004 return StmtError();
2005 return Res;
2006}
2007
2008ClassTemplateDecl *Sema::lookupCoroutineTraits(SourceLocation KwLoc,
2009 SourceLocation FuncLoc) {
2010 if (StdCoroutineTraitsCache)
2011 return StdCoroutineTraitsCache;
2012
2013 IdentifierInfo const &TraitIdent =
2014 PP.getIdentifierTable().get(Name: "coroutine_traits");
2015
2016 NamespaceDecl *StdSpace = getStdNamespace();
2017 LookupResult Result(*this, &TraitIdent, FuncLoc, LookupOrdinaryName);
2018 bool Found = StdSpace && LookupQualifiedName(R&: Result, LookupCtx: StdSpace);
2019
2020 if (!Found) {
2021 // The goggles, we found nothing!
2022 Diag(Loc: KwLoc, DiagID: diag::err_implied_coroutine_type_not_found)
2023 << "std::coroutine_traits";
2024 return nullptr;
2025 }
2026
2027 // coroutine_traits is required to be a class template.
2028 StdCoroutineTraitsCache = Result.getAsSingle<ClassTemplateDecl>();
2029 if (!StdCoroutineTraitsCache) {
2030 Result.suppressDiagnostics();
2031 NamedDecl *Found = *Result.begin();
2032 Diag(Loc: Found->getLocation(), DiagID: diag::err_malformed_std_coroutine_traits);
2033 return nullptr;
2034 }
2035
2036 return StdCoroutineTraitsCache;
2037}
2038