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/ExprCXX.h" 20 #include "clang/AST/StmtCXX.h" 21 #include "clang/Basic/Builtins.h" 22 #include "clang/Lex/Preprocessor.h" 23 #include "clang/Sema/Initialization.h" 24 #include "clang/Sema/Overload.h" 25 #include "clang/Sema/ScopeInfo.h" 26 #include "clang/Sema/SemaInternal.h" 27 #include "llvm/ADT/SmallSet.h" 28 29 using namespace clang; 30 using namespace sema; 31 32 static 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(LR, RD); 40 return LR; 41 } 42 43 static 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. 52 static 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 // FIXME: Cache std::coroutine_traits once we've found it. 57 NamespaceDecl *StdExp = S.lookupStdExperimentalNamespace(); 58 if (!StdExp) { 59 S.Diag(KwLoc, diag::err_implied_coroutine_type_not_found) 60 << "std::experimental::coroutine_traits"; 61 return QualType(); 62 } 63 64 ClassTemplateDecl *CoroTraits = S.lookupCoroutineTraits(KwLoc, FuncLoc); 65 if (!CoroTraits) { 66 return QualType(); 67 } 68 69 // Form template argument list for coroutine_traits<R, P1, P2, ...> according 70 // to [dcl.fct.def.coroutine]3 71 TemplateArgumentListInfo Args(KwLoc, KwLoc); 72 auto AddArg = [&](QualType T) { 73 Args.addArgument(TemplateArgumentLoc( 74 TemplateArgument(T), S.Context.getTrivialTypeSourceInfo(T, KwLoc))); 75 }; 76 AddArg(FnType->getReturnType()); 77 // If the function is a non-static member function, add the type 78 // of the implicit object parameter before the formal parameters. 79 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 80 if (MD->isInstance()) { 81 // [over.match.funcs]4 82 // For non-static member functions, the type of the implicit object 83 // parameter is 84 // -- "lvalue reference to cv X" for functions declared without a 85 // ref-qualifier or with the & ref-qualifier 86 // -- "rvalue reference to cv X" for functions declared with the && 87 // ref-qualifier 88 QualType T = MD->getThisType()->castAs<PointerType>()->getPointeeType(); 89 T = FnType->getRefQualifier() == RQ_RValue 90 ? S.Context.getRValueReferenceType(T) 91 : S.Context.getLValueReferenceType(T, /*SpelledAsLValue*/ true); 92 AddArg(T); 93 } 94 } 95 for (QualType T : FnType->getParamTypes()) 96 AddArg(T); 97 98 // Build the template-id. 99 QualType CoroTrait = 100 S.CheckTemplateIdType(TemplateName(CoroTraits), KwLoc, Args); 101 if (CoroTrait.isNull()) 102 return QualType(); 103 if (S.RequireCompleteType(KwLoc, CoroTrait, 104 diag::err_coroutine_type_missing_specialization)) 105 return QualType(); 106 107 auto *RD = CoroTrait->getAsCXXRecordDecl(); 108 assert(RD && "specialization of class template is not a class?"); 109 110 // Look up the ::promise_type member. 111 LookupResult R(S, &S.PP.getIdentifierTable().get("promise_type"), KwLoc, 112 Sema::LookupOrdinaryName); 113 S.LookupQualifiedName(R, RD); 114 auto *Promise = R.getAsSingle<TypeDecl>(); 115 if (!Promise) { 116 S.Diag(FuncLoc, 117 diag::err_implied_std_coroutine_traits_promise_type_not_found) 118 << RD; 119 return QualType(); 120 } 121 // The promise type is required to be a class type. 122 QualType PromiseType = S.Context.getTypeDeclType(Promise); 123 124 auto buildElaboratedType = [&]() { 125 auto *NNS = NestedNameSpecifier::Create(S.Context, nullptr, StdExp); 126 NNS = NestedNameSpecifier::Create(S.Context, NNS, false, 127 CoroTrait.getTypePtr()); 128 return S.Context.getElaboratedType(ETK_None, NNS, PromiseType); 129 }; 130 131 if (!PromiseType->getAsCXXRecordDecl()) { 132 S.Diag(FuncLoc, 133 diag::err_implied_std_coroutine_traits_promise_type_not_class) 134 << buildElaboratedType(); 135 return QualType(); 136 } 137 if (S.RequireCompleteType(FuncLoc, buildElaboratedType(), 138 diag::err_coroutine_promise_type_incomplete)) 139 return QualType(); 140 141 return PromiseType; 142 } 143 144 /// Look up the std::experimental::coroutine_handle<PromiseType>. 145 static QualType lookupCoroutineHandleType(Sema &S, QualType PromiseType, 146 SourceLocation Loc) { 147 if (PromiseType.isNull()) 148 return QualType(); 149 150 NamespaceDecl *StdExp = S.lookupStdExperimentalNamespace(); 151 assert(StdExp && "Should already be diagnosed"); 152 153 LookupResult Result(S, &S.PP.getIdentifierTable().get("coroutine_handle"), 154 Loc, Sema::LookupOrdinaryName); 155 if (!S.LookupQualifiedName(Result, StdExp)) { 156 S.Diag(Loc, diag::err_implied_coroutine_type_not_found) 157 << "std::experimental::coroutine_handle"; 158 return QualType(); 159 } 160 161 ClassTemplateDecl *CoroHandle = Result.getAsSingle<ClassTemplateDecl>(); 162 if (!CoroHandle) { 163 Result.suppressDiagnostics(); 164 // We found something weird. Complain about the first thing we found. 165 NamedDecl *Found = *Result.begin(); 166 S.Diag(Found->getLocation(), diag::err_malformed_std_coroutine_handle); 167 return QualType(); 168 } 169 170 // Form template argument list for coroutine_handle<Promise>. 171 TemplateArgumentListInfo Args(Loc, Loc); 172 Args.addArgument(TemplateArgumentLoc( 173 TemplateArgument(PromiseType), 174 S.Context.getTrivialTypeSourceInfo(PromiseType, Loc))); 175 176 // Build the template-id. 177 QualType CoroHandleType = 178 S.CheckTemplateIdType(TemplateName(CoroHandle), Loc, Args); 179 if (CoroHandleType.isNull()) 180 return QualType(); 181 if (S.RequireCompleteType(Loc, CoroHandleType, 182 diag::err_coroutine_type_missing_specialization)) 183 return QualType(); 184 185 return CoroHandleType; 186 } 187 188 static bool isValidCoroutineContext(Sema &S, SourceLocation Loc, 189 StringRef Keyword) { 190 // [expr.await]p2 dictates that 'co_await' and 'co_yield' must be used within 191 // a function body. 192 // FIXME: This also covers [expr.await]p2: "An await-expression shall not 193 // appear in a default argument." But the diagnostic QoI here could be 194 // improved to inform the user that default arguments specifically are not 195 // allowed. 196 auto *FD = dyn_cast<FunctionDecl>(S.CurContext); 197 if (!FD) { 198 S.Diag(Loc, isa<ObjCMethodDecl>(S.CurContext) 199 ? diag::err_coroutine_objc_method 200 : diag::err_coroutine_outside_function) << Keyword; 201 return false; 202 } 203 204 // An enumeration for mapping the diagnostic type to the correct diagnostic 205 // selection index. 206 enum InvalidFuncDiag { 207 DiagCtor = 0, 208 DiagDtor, 209 DiagMain, 210 DiagConstexpr, 211 DiagAutoRet, 212 DiagVarargs, 213 DiagConsteval, 214 }; 215 bool Diagnosed = false; 216 auto DiagInvalid = [&](InvalidFuncDiag ID) { 217 S.Diag(Loc, diag::err_coroutine_invalid_func_context) << ID << Keyword; 218 Diagnosed = true; 219 return false; 220 }; 221 222 // Diagnose when a constructor, destructor 223 // or the function 'main' are declared as a coroutine. 224 auto *MD = dyn_cast<CXXMethodDecl>(FD); 225 // [class.ctor]p11: "A constructor shall not be a coroutine." 226 if (MD && isa<CXXConstructorDecl>(MD)) 227 return DiagInvalid(DiagCtor); 228 // [class.dtor]p17: "A destructor shall not be a coroutine." 229 else if (MD && isa<CXXDestructorDecl>(MD)) 230 return DiagInvalid(DiagDtor); 231 // [basic.start.main]p3: "The function main shall not be a coroutine." 232 else if (FD->isMain()) 233 return DiagInvalid(DiagMain); 234 235 // Emit a diagnostics for each of the following conditions which is not met. 236 // [expr.const]p2: "An expression e is a core constant expression unless the 237 // evaluation of e [...] would evaluate one of the following expressions: 238 // [...] an await-expression [...] a yield-expression." 239 if (FD->isConstexpr()) 240 DiagInvalid(FD->isConsteval() ? DiagConsteval : DiagConstexpr); 241 // [dcl.spec.auto]p15: "A function declared with a return type that uses a 242 // placeholder type shall not be a coroutine." 243 if (FD->getReturnType()->isUndeducedType()) 244 DiagInvalid(DiagAutoRet); 245 // [dcl.fct.def.coroutine]p1: "The parameter-declaration-clause of the 246 // coroutine shall not terminate with an ellipsis that is not part of a 247 // parameter-declaration." 248 if (FD->isVariadic()) 249 DiagInvalid(DiagVarargs); 250 251 return !Diagnosed; 252 } 253 254 static ExprResult buildOperatorCoawaitLookupExpr(Sema &SemaRef, Scope *S, 255 SourceLocation Loc) { 256 DeclarationName OpName = 257 SemaRef.Context.DeclarationNames.getCXXOperatorName(OO_Coawait); 258 LookupResult Operators(SemaRef, OpName, SourceLocation(), 259 Sema::LookupOperatorName); 260 SemaRef.LookupName(Operators, S); 261 262 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous"); 263 const auto &Functions = Operators.asUnresolvedSet(); 264 bool IsOverloaded = 265 Functions.size() > 1 || 266 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 267 Expr *CoawaitOp = UnresolvedLookupExpr::Create( 268 SemaRef.Context, /*NamingClass*/ nullptr, NestedNameSpecifierLoc(), 269 DeclarationNameInfo(OpName, Loc), /*RequiresADL*/ true, IsOverloaded, 270 Functions.begin(), Functions.end()); 271 assert(CoawaitOp); 272 return CoawaitOp; 273 } 274 275 /// Build a call to 'operator co_await' if there is a suitable operator for 276 /// the given expression. 277 static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, SourceLocation Loc, 278 Expr *E, 279 UnresolvedLookupExpr *Lookup) { 280 UnresolvedSet<16> Functions; 281 Functions.append(Lookup->decls_begin(), Lookup->decls_end()); 282 return SemaRef.CreateOverloadedUnaryOp(Loc, UO_Coawait, Functions, E); 283 } 284 285 static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, Scope *S, 286 SourceLocation Loc, Expr *E) { 287 ExprResult R = buildOperatorCoawaitLookupExpr(SemaRef, S, Loc); 288 if (R.isInvalid()) 289 return ExprError(); 290 return buildOperatorCoawaitCall(SemaRef, Loc, E, 291 cast<UnresolvedLookupExpr>(R.get())); 292 } 293 294 static Expr *buildBuiltinCall(Sema &S, SourceLocation Loc, Builtin::ID Id, 295 MultiExprArg CallArgs) { 296 StringRef Name = S.Context.BuiltinInfo.getName(Id); 297 LookupResult R(S, &S.Context.Idents.get(Name), Loc, Sema::LookupOrdinaryName); 298 S.LookupName(R, S.TUScope, /*AllowBuiltinCreation=*/true); 299 300 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>(); 301 assert(BuiltInDecl && "failed to find builtin declaration"); 302 303 ExprResult DeclRef = 304 S.BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc); 305 assert(DeclRef.isUsable() && "Builtin reference cannot fail"); 306 307 ExprResult Call = 308 S.BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc); 309 310 assert(!Call.isInvalid() && "Call to builtin cannot fail!"); 311 return Call.get(); 312 } 313 314 static ExprResult buildCoroutineHandle(Sema &S, QualType PromiseType, 315 SourceLocation Loc) { 316 QualType CoroHandleType = lookupCoroutineHandleType(S, PromiseType, Loc); 317 if (CoroHandleType.isNull()) 318 return ExprError(); 319 320 DeclContext *LookupCtx = S.computeDeclContext(CoroHandleType); 321 LookupResult Found(S, &S.PP.getIdentifierTable().get("from_address"), Loc, 322 Sema::LookupOrdinaryName); 323 if (!S.LookupQualifiedName(Found, LookupCtx)) { 324 S.Diag(Loc, diag::err_coroutine_handle_missing_member) 325 << "from_address"; 326 return ExprError(); 327 } 328 329 Expr *FramePtr = 330 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_frame, {}); 331 332 CXXScopeSpec SS; 333 ExprResult FromAddr = 334 S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false); 335 if (FromAddr.isInvalid()) 336 return ExprError(); 337 338 return S.BuildCallExpr(nullptr, FromAddr.get(), Loc, FramePtr, Loc); 339 } 340 341 struct ReadySuspendResumeResult { 342 enum AwaitCallType { ACT_Ready, ACT_Suspend, ACT_Resume }; 343 Expr *Results[3]; 344 OpaqueValueExpr *OpaqueValue; 345 bool IsInvalid; 346 }; 347 348 static ExprResult buildMemberCall(Sema &S, Expr *Base, SourceLocation Loc, 349 StringRef Name, MultiExprArg Args) { 350 DeclarationNameInfo NameInfo(&S.PP.getIdentifierTable().get(Name), Loc); 351 352 // FIXME: Fix BuildMemberReferenceExpr to take a const CXXScopeSpec&. 353 CXXScopeSpec SS; 354 ExprResult Result = S.BuildMemberReferenceExpr( 355 Base, Base->getType(), Loc, /*IsPtr=*/false, SS, 356 SourceLocation(), nullptr, NameInfo, /*TemplateArgs=*/nullptr, 357 /*Scope=*/nullptr); 358 if (Result.isInvalid()) 359 return ExprError(); 360 361 // We meant exactly what we asked for. No need for typo correction. 362 if (auto *TE = dyn_cast<TypoExpr>(Result.get())) { 363 S.clearDelayedTypo(TE); 364 S.Diag(Loc, diag::err_no_member) 365 << NameInfo.getName() << Base->getType()->getAsCXXRecordDecl() 366 << Base->getSourceRange(); 367 return ExprError(); 368 } 369 370 return S.BuildCallExpr(nullptr, Result.get(), Loc, Args, Loc, nullptr); 371 } 372 373 // See if return type is coroutine-handle and if so, invoke builtin coro-resume 374 // on its address. This is to enable experimental support for coroutine-handle 375 // returning await_suspend that results in a guaranteed tail call to the target 376 // coroutine. 377 static Expr *maybeTailCall(Sema &S, QualType RetType, Expr *E, 378 SourceLocation Loc) { 379 if (RetType->isReferenceType()) 380 return nullptr; 381 Type const *T = RetType.getTypePtr(); 382 if (!T->isClassType() && !T->isStructureType()) 383 return nullptr; 384 385 // FIXME: Add convertability check to coroutine_handle<>. Possibly via 386 // EvaluateBinaryTypeTrait(BTT_IsConvertible, ...) which is at the moment 387 // a private function in SemaExprCXX.cpp 388 389 ExprResult AddressExpr = buildMemberCall(S, E, Loc, "address", None); 390 if (AddressExpr.isInvalid()) 391 return nullptr; 392 393 Expr *JustAddress = AddressExpr.get(); 394 // FIXME: Check that the type of AddressExpr is void* 395 return buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_resume, 396 JustAddress); 397 } 398 399 /// Build calls to await_ready, await_suspend, and await_resume for a co_await 400 /// expression. 401 static ReadySuspendResumeResult buildCoawaitCalls(Sema &S, VarDecl *CoroPromise, 402 SourceLocation Loc, Expr *E) { 403 OpaqueValueExpr *Operand = new (S.Context) 404 OpaqueValueExpr(Loc, E->getType(), VK_LValue, E->getObjectKind(), E); 405 406 // Assume invalid until we see otherwise. 407 ReadySuspendResumeResult Calls = {{}, Operand, /*IsInvalid=*/true}; 408 409 ExprResult CoroHandleRes = buildCoroutineHandle(S, CoroPromise->getType(), Loc); 410 if (CoroHandleRes.isInvalid()) 411 return Calls; 412 Expr *CoroHandle = CoroHandleRes.get(); 413 414 const StringRef Funcs[] = {"await_ready", "await_suspend", "await_resume"}; 415 MultiExprArg Args[] = {None, CoroHandle, None}; 416 for (size_t I = 0, N = llvm::array_lengthof(Funcs); I != N; ++I) { 417 ExprResult Result = buildMemberCall(S, Operand, Loc, Funcs[I], Args[I]); 418 if (Result.isInvalid()) 419 return Calls; 420 Calls.Results[I] = Result.get(); 421 } 422 423 // Assume the calls are valid; all further checking should make them invalid. 424 Calls.IsInvalid = false; 425 426 using ACT = ReadySuspendResumeResult::AwaitCallType; 427 CallExpr *AwaitReady = cast<CallExpr>(Calls.Results[ACT::ACT_Ready]); 428 if (!AwaitReady->getType()->isDependentType()) { 429 // [expr.await]p3 [...] 430 // — await-ready is the expression e.await_ready(), contextually converted 431 // to bool. 432 ExprResult Conv = S.PerformContextuallyConvertToBool(AwaitReady); 433 if (Conv.isInvalid()) { 434 S.Diag(AwaitReady->getDirectCallee()->getBeginLoc(), 435 diag::note_await_ready_no_bool_conversion); 436 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required) 437 << AwaitReady->getDirectCallee() << E->getSourceRange(); 438 Calls.IsInvalid = true; 439 } 440 Calls.Results[ACT::ACT_Ready] = Conv.get(); 441 } 442 CallExpr *AwaitSuspend = cast<CallExpr>(Calls.Results[ACT::ACT_Suspend]); 443 if (!AwaitSuspend->getType()->isDependentType()) { 444 // [expr.await]p3 [...] 445 // - await-suspend is the expression e.await_suspend(h), which shall be 446 // a prvalue of type void or bool. 447 QualType RetType = AwaitSuspend->getCallReturnType(S.Context); 448 449 // Experimental support for coroutine_handle returning await_suspend. 450 if (Expr *TailCallSuspend = maybeTailCall(S, RetType, AwaitSuspend, Loc)) 451 Calls.Results[ACT::ACT_Suspend] = TailCallSuspend; 452 else { 453 // non-class prvalues always have cv-unqualified types 454 if (RetType->isReferenceType() || 455 (!RetType->isBooleanType() && !RetType->isVoidType())) { 456 S.Diag(AwaitSuspend->getCalleeDecl()->getLocation(), 457 diag::err_await_suspend_invalid_return_type) 458 << RetType; 459 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required) 460 << AwaitSuspend->getDirectCallee(); 461 Calls.IsInvalid = true; 462 } 463 } 464 } 465 466 return Calls; 467 } 468 469 static ExprResult buildPromiseCall(Sema &S, VarDecl *Promise, 470 SourceLocation Loc, StringRef Name, 471 MultiExprArg Args) { 472 473 // Form a reference to the promise. 474 ExprResult PromiseRef = S.BuildDeclRefExpr( 475 Promise, Promise->getType().getNonReferenceType(), VK_LValue, Loc); 476 if (PromiseRef.isInvalid()) 477 return ExprError(); 478 479 return buildMemberCall(S, PromiseRef.get(), Loc, Name, Args); 480 } 481 482 VarDecl *Sema::buildCoroutinePromise(SourceLocation Loc) { 483 assert(isa<FunctionDecl>(CurContext) && "not in a function scope"); 484 auto *FD = cast<FunctionDecl>(CurContext); 485 bool IsThisDependentType = [&] { 486 if (auto *MD = dyn_cast_or_null<CXXMethodDecl>(FD)) 487 return MD->isInstance() && MD->getThisType()->isDependentType(); 488 else 489 return false; 490 }(); 491 492 QualType T = FD->getType()->isDependentType() || IsThisDependentType 493 ? Context.DependentTy 494 : lookupPromiseType(*this, FD, Loc); 495 if (T.isNull()) 496 return nullptr; 497 498 auto *VD = VarDecl::Create(Context, FD, FD->getLocation(), FD->getLocation(), 499 &PP.getIdentifierTable().get("__promise"), T, 500 Context.getTrivialTypeSourceInfo(T, Loc), SC_None); 501 CheckVariableDeclarationType(VD); 502 if (VD->isInvalidDecl()) 503 return nullptr; 504 505 auto *ScopeInfo = getCurFunction(); 506 507 // Build a list of arguments, based on the coroutine function's arguments, 508 // that if present will be passed to the promise type's constructor. 509 llvm::SmallVector<Expr *, 4> CtorArgExprs; 510 511 // Add implicit object parameter. 512 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 513 if (MD->isInstance() && !isLambdaCallOperator(MD)) { 514 ExprResult ThisExpr = ActOnCXXThis(Loc); 515 if (ThisExpr.isInvalid()) 516 return nullptr; 517 ThisExpr = CreateBuiltinUnaryOp(Loc, UO_Deref, ThisExpr.get()); 518 if (ThisExpr.isInvalid()) 519 return nullptr; 520 CtorArgExprs.push_back(ThisExpr.get()); 521 } 522 } 523 524 // Add the coroutine function's parameters. 525 auto &Moves = ScopeInfo->CoroutineParameterMoves; 526 for (auto *PD : FD->parameters()) { 527 if (PD->getType()->isDependentType()) 528 continue; 529 530 auto RefExpr = ExprEmpty(); 531 auto Move = Moves.find(PD); 532 assert(Move != Moves.end() && 533 "Coroutine function parameter not inserted into move map"); 534 // If a reference to the function parameter exists in the coroutine 535 // frame, use that reference. 536 auto *MoveDecl = 537 cast<VarDecl>(cast<DeclStmt>(Move->second)->getSingleDecl()); 538 RefExpr = 539 BuildDeclRefExpr(MoveDecl, MoveDecl->getType().getNonReferenceType(), 540 ExprValueKind::VK_LValue, FD->getLocation()); 541 if (RefExpr.isInvalid()) 542 return nullptr; 543 CtorArgExprs.push_back(RefExpr.get()); 544 } 545 546 // If we have a non-zero number of constructor arguments, try to use them. 547 // Otherwise, fall back to the promise type's default constructor. 548 if (!CtorArgExprs.empty()) { 549 // Create an initialization sequence for the promise type using the 550 // constructor arguments, wrapped in a parenthesized list expression. 551 Expr *PLE = ParenListExpr::Create(Context, FD->getLocation(), 552 CtorArgExprs, FD->getLocation()); 553 InitializedEntity Entity = InitializedEntity::InitializeVariable(VD); 554 InitializationKind Kind = InitializationKind::CreateForInit( 555 VD->getLocation(), /*DirectInit=*/true, PLE); 556 InitializationSequence InitSeq(*this, Entity, Kind, CtorArgExprs, 557 /*TopLevelOfInitList=*/false, 558 /*TreatUnavailableAsInvalid=*/false); 559 560 // Attempt to initialize the promise type with the arguments. 561 // If that fails, fall back to the promise type's default constructor. 562 if (InitSeq) { 563 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, CtorArgExprs); 564 if (Result.isInvalid()) { 565 VD->setInvalidDecl(); 566 } else if (Result.get()) { 567 VD->setInit(MaybeCreateExprWithCleanups(Result.get())); 568 VD->setInitStyle(VarDecl::CallInit); 569 CheckCompleteVariableDeclaration(VD); 570 } 571 } else 572 ActOnUninitializedDecl(VD); 573 } else 574 ActOnUninitializedDecl(VD); 575 576 FD->addDecl(VD); 577 return VD; 578 } 579 580 /// Check that this is a context in which a coroutine suspension can appear. 581 static FunctionScopeInfo *checkCoroutineContext(Sema &S, SourceLocation Loc, 582 StringRef Keyword, 583 bool IsImplicit = false) { 584 if (!isValidCoroutineContext(S, Loc, Keyword)) 585 return nullptr; 586 587 assert(isa<FunctionDecl>(S.CurContext) && "not in a function scope"); 588 589 auto *ScopeInfo = S.getCurFunction(); 590 assert(ScopeInfo && "missing function scope for function"); 591 592 if (ScopeInfo->FirstCoroutineStmtLoc.isInvalid() && !IsImplicit) 593 ScopeInfo->setFirstCoroutineStmt(Loc, Keyword); 594 595 if (ScopeInfo->CoroutinePromise) 596 return ScopeInfo; 597 598 if (!S.buildCoroutineParameterMoves(Loc)) 599 return nullptr; 600 601 ScopeInfo->CoroutinePromise = S.buildCoroutinePromise(Loc); 602 if (!ScopeInfo->CoroutinePromise) 603 return nullptr; 604 605 return ScopeInfo; 606 } 607 608 /// Recursively check \p E and all its children to see if any call target 609 /// (including constructor call) is declared noexcept. Also any value returned 610 /// from the call has a noexcept destructor. 611 static void checkNoThrow(Sema &S, const Stmt *E, 612 llvm::SmallPtrSetImpl<const Decl *> &ThrowingDecls) { 613 auto checkDeclNoexcept = [&](const Decl *D, bool IsDtor = false) { 614 // In the case of dtor, the call to dtor is implicit and hence we should 615 // pass nullptr to canCalleeThrow. 616 if (Sema::canCalleeThrow(S, IsDtor ? nullptr : cast<Expr>(E), D)) { 617 if (ThrowingDecls.empty()) { 618 // First time seeing an error, emit the error message. 619 S.Diag(cast<FunctionDecl>(S.CurContext)->getLocation(), 620 diag::err_coroutine_promise_final_suspend_requires_nothrow); 621 } 622 ThrowingDecls.insert(D); 623 } 624 }; 625 auto SC = E->getStmtClass(); 626 if (SC == Expr::CXXConstructExprClass) { 627 auto const *Ctor = cast<CXXConstructExpr>(E)->getConstructor(); 628 checkDeclNoexcept(Ctor); 629 // Check the corresponding destructor of the constructor. 630 checkDeclNoexcept(Ctor->getParent()->getDestructor(), true); 631 } else if (SC == Expr::CallExprClass || SC == Expr::CXXMemberCallExprClass || 632 SC == Expr::CXXOperatorCallExprClass) { 633 if (!cast<CallExpr>(E)->isTypeDependent()) { 634 // FIXME: Handle dependent types. 635 checkDeclNoexcept(cast<CallExpr>(E)->getCalleeDecl()); 636 auto ReturnType = cast<CallExpr>(E)->getCallReturnType(S.getASTContext()); 637 // Check the destructor of the call return type, if any. 638 if (ReturnType.isDestructedType() == 639 QualType::DestructionKind::DK_cxx_destructor) { 640 const auto *T = 641 cast<RecordType>(ReturnType.getCanonicalType().getTypePtr()); 642 checkDeclNoexcept( 643 dyn_cast<CXXRecordDecl>(T->getDecl())->getDestructor(), true); 644 } 645 } 646 } 647 for (const auto *Child : E->children()) { 648 if (!Child) 649 continue; 650 checkNoThrow(S, Child, ThrowingDecls); 651 } 652 } 653 654 /// Check that the expression co_await promise.final_suspend() shall not be 655 /// potentially-throwing. 656 static bool checkNoThrow(Sema &S, const Stmt *FinalSuspend) { 657 llvm::SmallPtrSet<const Decl *, 4> ThrowingDecls; 658 // We first collect all declarations that should not throw but not declared 659 // with noexcept. We then sort them based on the location before printing. 660 // This is to avoid emitting the same note multiple times on the same 661 // declaration, and also provide a deterministic order for the messages. 662 checkNoThrow(S, FinalSuspend, ThrowingDecls); 663 auto SortedDecls = llvm::SmallVector<const Decl *, 4>{ThrowingDecls.begin(), 664 ThrowingDecls.end()}; 665 sort(SortedDecls, [](const Decl *A, const Decl *B) { 666 return A->getEndLoc() < B->getEndLoc(); 667 }); 668 for (const auto *D : SortedDecls) { 669 S.Diag(D->getEndLoc(), diag::note_coroutine_function_declare_noexcept); 670 } 671 return ThrowingDecls.empty(); 672 } 673 674 bool Sema::ActOnCoroutineBodyStart(Scope *SC, SourceLocation KWLoc, 675 StringRef Keyword) { 676 if (!checkCoroutineContext(*this, KWLoc, Keyword)) 677 return false; 678 auto *ScopeInfo = getCurFunction(); 679 assert(ScopeInfo->CoroutinePromise); 680 681 // If we have existing coroutine statements then we have already built 682 // the initial and final suspend points. 683 if (!ScopeInfo->NeedsCoroutineSuspends) 684 return true; 685 686 ScopeInfo->setNeedsCoroutineSuspends(false); 687 688 auto *Fn = cast<FunctionDecl>(CurContext); 689 SourceLocation Loc = Fn->getLocation(); 690 // Build the initial suspend point 691 auto buildSuspends = [&](StringRef Name) mutable -> StmtResult { 692 ExprResult Suspend = 693 buildPromiseCall(*this, ScopeInfo->CoroutinePromise, Loc, Name, None); 694 if (Suspend.isInvalid()) 695 return StmtError(); 696 Suspend = buildOperatorCoawaitCall(*this, SC, Loc, Suspend.get()); 697 if (Suspend.isInvalid()) 698 return StmtError(); 699 Suspend = BuildResolvedCoawaitExpr(Loc, Suspend.get(), 700 /*IsImplicit*/ true); 701 Suspend = ActOnFinishFullExpr(Suspend.get(), /*DiscardedValue*/ false); 702 if (Suspend.isInvalid()) { 703 Diag(Loc, diag::note_coroutine_promise_suspend_implicitly_required) 704 << ((Name == "initial_suspend") ? 0 : 1); 705 Diag(KWLoc, diag::note_declared_coroutine_here) << Keyword; 706 return StmtError(); 707 } 708 return cast<Stmt>(Suspend.get()); 709 }; 710 711 StmtResult InitSuspend = buildSuspends("initial_suspend"); 712 if (InitSuspend.isInvalid()) 713 return true; 714 715 StmtResult FinalSuspend = buildSuspends("final_suspend"); 716 if (FinalSuspend.isInvalid() || !checkNoThrow(*this, FinalSuspend.get())) 717 return true; 718 719 ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get()); 720 721 return true; 722 } 723 724 // Recursively walks up the scope hierarchy until either a 'catch' or a function 725 // scope is found, whichever comes first. 726 static bool isWithinCatchScope(Scope *S) { 727 // 'co_await' and 'co_yield' keywords are disallowed within catch blocks, but 728 // lambdas that use 'co_await' are allowed. The loop below ends when a 729 // function scope is found in order to ensure the following behavior: 730 // 731 // void foo() { // <- function scope 732 // try { // 733 // co_await x; // <- 'co_await' is OK within a function scope 734 // } catch { // <- catch scope 735 // co_await x; // <- 'co_await' is not OK within a catch scope 736 // []() { // <- function scope 737 // co_await x; // <- 'co_await' is OK within a function scope 738 // }(); 739 // } 740 // } 741 while (S && !(S->getFlags() & Scope::FnScope)) { 742 if (S->getFlags() & Scope::CatchScope) 743 return true; 744 S = S->getParent(); 745 } 746 return false; 747 } 748 749 // [expr.await]p2, emphasis added: "An await-expression shall appear only in 750 // a *potentially evaluated* expression within the compound-statement of a 751 // function-body *outside of a handler* [...] A context within a function 752 // where an await-expression can appear is called a suspension context of the 753 // function." 754 static void checkSuspensionContext(Sema &S, SourceLocation Loc, 755 StringRef Keyword) { 756 // First emphasis of [expr.await]p2: must be a potentially evaluated context. 757 // That is, 'co_await' and 'co_yield' cannot appear in subexpressions of 758 // \c sizeof. 759 if (S.isUnevaluatedContext()) 760 S.Diag(Loc, diag::err_coroutine_unevaluated_context) << Keyword; 761 762 // Second emphasis of [expr.await]p2: must be outside of an exception handler. 763 if (isWithinCatchScope(S.getCurScope())) 764 S.Diag(Loc, diag::err_coroutine_within_handler) << Keyword; 765 } 766 767 ExprResult Sema::ActOnCoawaitExpr(Scope *S, SourceLocation Loc, Expr *E) { 768 if (!ActOnCoroutineBodyStart(S, Loc, "co_await")) { 769 CorrectDelayedTyposInExpr(E); 770 return ExprError(); 771 } 772 773 checkSuspensionContext(*this, Loc, "co_await"); 774 775 if (E->getType()->isPlaceholderType()) { 776 ExprResult R = CheckPlaceholderExpr(E); 777 if (R.isInvalid()) return ExprError(); 778 E = R.get(); 779 } 780 ExprResult Lookup = buildOperatorCoawaitLookupExpr(*this, S, Loc); 781 if (Lookup.isInvalid()) 782 return ExprError(); 783 return BuildUnresolvedCoawaitExpr(Loc, E, 784 cast<UnresolvedLookupExpr>(Lookup.get())); 785 } 786 787 ExprResult Sema::BuildUnresolvedCoawaitExpr(SourceLocation Loc, Expr *E, 788 UnresolvedLookupExpr *Lookup) { 789 auto *FSI = checkCoroutineContext(*this, Loc, "co_await"); 790 if (!FSI) 791 return ExprError(); 792 793 if (E->getType()->isPlaceholderType()) { 794 ExprResult R = CheckPlaceholderExpr(E); 795 if (R.isInvalid()) 796 return ExprError(); 797 E = R.get(); 798 } 799 800 auto *Promise = FSI->CoroutinePromise; 801 if (Promise->getType()->isDependentType()) { 802 Expr *Res = 803 new (Context) DependentCoawaitExpr(Loc, Context.DependentTy, E, Lookup); 804 return Res; 805 } 806 807 auto *RD = Promise->getType()->getAsCXXRecordDecl(); 808 if (lookupMember(*this, "await_transform", RD, Loc)) { 809 ExprResult R = buildPromiseCall(*this, Promise, Loc, "await_transform", E); 810 if (R.isInvalid()) { 811 Diag(Loc, 812 diag::note_coroutine_promise_implicit_await_transform_required_here) 813 << E->getSourceRange(); 814 return ExprError(); 815 } 816 E = R.get(); 817 } 818 ExprResult Awaitable = buildOperatorCoawaitCall(*this, Loc, E, Lookup); 819 if (Awaitable.isInvalid()) 820 return ExprError(); 821 822 return BuildResolvedCoawaitExpr(Loc, Awaitable.get()); 823 } 824 825 ExprResult Sema::BuildResolvedCoawaitExpr(SourceLocation Loc, Expr *E, 826 bool IsImplicit) { 827 auto *Coroutine = checkCoroutineContext(*this, Loc, "co_await", IsImplicit); 828 if (!Coroutine) 829 return ExprError(); 830 831 if (E->getType()->isPlaceholderType()) { 832 ExprResult R = CheckPlaceholderExpr(E); 833 if (R.isInvalid()) return ExprError(); 834 E = R.get(); 835 } 836 837 if (E->getType()->isDependentType()) { 838 Expr *Res = new (Context) 839 CoawaitExpr(Loc, Context.DependentTy, E, IsImplicit); 840 return Res; 841 } 842 843 // If the expression is a temporary, materialize it as an lvalue so that we 844 // can use it multiple times. 845 if (E->getValueKind() == VK_RValue) 846 E = CreateMaterializeTemporaryExpr(E->getType(), E, true); 847 848 // The location of the `co_await` token cannot be used when constructing 849 // the member call expressions since it's before the location of `Expr`, which 850 // is used as the start of the member call expression. 851 SourceLocation CallLoc = E->getExprLoc(); 852 853 // Build the await_ready, await_suspend, await_resume calls. 854 ReadySuspendResumeResult RSS = 855 buildCoawaitCalls(*this, Coroutine->CoroutinePromise, CallLoc, E); 856 if (RSS.IsInvalid) 857 return ExprError(); 858 859 Expr *Res = 860 new (Context) CoawaitExpr(Loc, E, RSS.Results[0], RSS.Results[1], 861 RSS.Results[2], RSS.OpaqueValue, IsImplicit); 862 863 return Res; 864 } 865 866 ExprResult Sema::ActOnCoyieldExpr(Scope *S, SourceLocation Loc, Expr *E) { 867 if (!ActOnCoroutineBodyStart(S, Loc, "co_yield")) { 868 CorrectDelayedTyposInExpr(E); 869 return ExprError(); 870 } 871 872 checkSuspensionContext(*this, Loc, "co_yield"); 873 874 // Build yield_value call. 875 ExprResult Awaitable = buildPromiseCall( 876 *this, getCurFunction()->CoroutinePromise, Loc, "yield_value", E); 877 if (Awaitable.isInvalid()) 878 return ExprError(); 879 880 // Build 'operator co_await' call. 881 Awaitable = buildOperatorCoawaitCall(*this, S, Loc, Awaitable.get()); 882 if (Awaitable.isInvalid()) 883 return ExprError(); 884 885 return BuildCoyieldExpr(Loc, Awaitable.get()); 886 } 887 ExprResult Sema::BuildCoyieldExpr(SourceLocation Loc, Expr *E) { 888 auto *Coroutine = checkCoroutineContext(*this, Loc, "co_yield"); 889 if (!Coroutine) 890 return ExprError(); 891 892 if (E->getType()->isPlaceholderType()) { 893 ExprResult R = CheckPlaceholderExpr(E); 894 if (R.isInvalid()) return ExprError(); 895 E = R.get(); 896 } 897 898 if (E->getType()->isDependentType()) { 899 Expr *Res = new (Context) CoyieldExpr(Loc, Context.DependentTy, E); 900 return Res; 901 } 902 903 // If the expression is a temporary, materialize it as an lvalue so that we 904 // can use it multiple times. 905 if (E->getValueKind() == VK_RValue) 906 E = CreateMaterializeTemporaryExpr(E->getType(), E, true); 907 908 // Build the await_ready, await_suspend, await_resume calls. 909 ReadySuspendResumeResult RSS = 910 buildCoawaitCalls(*this, Coroutine->CoroutinePromise, Loc, E); 911 if (RSS.IsInvalid) 912 return ExprError(); 913 914 Expr *Res = 915 new (Context) CoyieldExpr(Loc, E, RSS.Results[0], RSS.Results[1], 916 RSS.Results[2], RSS.OpaqueValue); 917 918 return Res; 919 } 920 921 StmtResult Sema::ActOnCoreturnStmt(Scope *S, SourceLocation Loc, Expr *E) { 922 if (!ActOnCoroutineBodyStart(S, Loc, "co_return")) { 923 CorrectDelayedTyposInExpr(E); 924 return StmtError(); 925 } 926 return BuildCoreturnStmt(Loc, E); 927 } 928 929 StmtResult Sema::BuildCoreturnStmt(SourceLocation Loc, Expr *E, 930 bool IsImplicit) { 931 auto *FSI = checkCoroutineContext(*this, Loc, "co_return", IsImplicit); 932 if (!FSI) 933 return StmtError(); 934 935 if (E && E->getType()->isPlaceholderType() && 936 !E->getType()->isSpecificPlaceholderType(BuiltinType::Overload)) { 937 ExprResult R = CheckPlaceholderExpr(E); 938 if (R.isInvalid()) return StmtError(); 939 E = R.get(); 940 } 941 942 // Move the return value if we can 943 if (E) { 944 auto NRVOCandidate = this->getCopyElisionCandidate(E->getType(), E, CES_AsIfByStdMove); 945 if (NRVOCandidate) { 946 InitializedEntity Entity = 947 InitializedEntity::InitializeResult(Loc, E->getType(), NRVOCandidate); 948 ExprResult MoveResult = this->PerformMoveOrCopyInitialization( 949 Entity, NRVOCandidate, E->getType(), E); 950 if (MoveResult.get()) 951 E = MoveResult.get(); 952 } 953 } 954 955 // FIXME: If the operand is a reference to a variable that's about to go out 956 // of scope, we should treat the operand as an xvalue for this overload 957 // resolution. 958 VarDecl *Promise = FSI->CoroutinePromise; 959 ExprResult PC; 960 if (E && (isa<InitListExpr>(E) || !E->getType()->isVoidType())) { 961 PC = buildPromiseCall(*this, Promise, Loc, "return_value", E); 962 } else { 963 E = MakeFullDiscardedValueExpr(E).get(); 964 PC = buildPromiseCall(*this, Promise, Loc, "return_void", None); 965 } 966 if (PC.isInvalid()) 967 return StmtError(); 968 969 Expr *PCE = ActOnFinishFullExpr(PC.get(), /*DiscardedValue*/ false).get(); 970 971 Stmt *Res = new (Context) CoreturnStmt(Loc, E, PCE, IsImplicit); 972 return Res; 973 } 974 975 /// Look up the std::nothrow object. 976 static Expr *buildStdNoThrowDeclRef(Sema &S, SourceLocation Loc) { 977 NamespaceDecl *Std = S.getStdNamespace(); 978 assert(Std && "Should already be diagnosed"); 979 980 LookupResult Result(S, &S.PP.getIdentifierTable().get("nothrow"), Loc, 981 Sema::LookupOrdinaryName); 982 if (!S.LookupQualifiedName(Result, Std)) { 983 // FIXME: <experimental/coroutine> should have been included already. 984 // If we require it to include <new> then this diagnostic is no longer 985 // needed. 986 S.Diag(Loc, diag::err_implicit_coroutine_std_nothrow_type_not_found); 987 return nullptr; 988 } 989 990 auto *VD = Result.getAsSingle<VarDecl>(); 991 if (!VD) { 992 Result.suppressDiagnostics(); 993 // We found something weird. Complain about the first thing we found. 994 NamedDecl *Found = *Result.begin(); 995 S.Diag(Found->getLocation(), diag::err_malformed_std_nothrow); 996 return nullptr; 997 } 998 999 ExprResult DR = S.BuildDeclRefExpr(VD, VD->getType(), VK_LValue, Loc); 1000 if (DR.isInvalid()) 1001 return nullptr; 1002 1003 return DR.get(); 1004 } 1005 1006 // Find an appropriate delete for the promise. 1007 static FunctionDecl *findDeleteForPromise(Sema &S, SourceLocation Loc, 1008 QualType PromiseType) { 1009 FunctionDecl *OperatorDelete = nullptr; 1010 1011 DeclarationName DeleteName = 1012 S.Context.DeclarationNames.getCXXOperatorName(OO_Delete); 1013 1014 auto *PointeeRD = PromiseType->getAsCXXRecordDecl(); 1015 assert(PointeeRD && "PromiseType must be a CxxRecordDecl type"); 1016 1017 if (S.FindDeallocationFunction(Loc, PointeeRD, DeleteName, OperatorDelete)) 1018 return nullptr; 1019 1020 if (!OperatorDelete) { 1021 // Look for a global declaration. 1022 const bool CanProvideSize = S.isCompleteType(Loc, PromiseType); 1023 const bool Overaligned = false; 1024 OperatorDelete = S.FindUsualDeallocationFunction(Loc, CanProvideSize, 1025 Overaligned, DeleteName); 1026 } 1027 S.MarkFunctionReferenced(Loc, OperatorDelete); 1028 return OperatorDelete; 1029 } 1030 1031 1032 void Sema::CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body) { 1033 FunctionScopeInfo *Fn = getCurFunction(); 1034 assert(Fn && Fn->isCoroutine() && "not a coroutine"); 1035 if (!Body) { 1036 assert(FD->isInvalidDecl() && 1037 "a null body is only allowed for invalid declarations"); 1038 return; 1039 } 1040 // We have a function that uses coroutine keywords, but we failed to build 1041 // the promise type. 1042 if (!Fn->CoroutinePromise) 1043 return FD->setInvalidDecl(); 1044 1045 if (isa<CoroutineBodyStmt>(Body)) { 1046 // Nothing todo. the body is already a transformed coroutine body statement. 1047 return; 1048 } 1049 1050 // Coroutines [stmt.return]p1: 1051 // A return statement shall not appear in a coroutine. 1052 if (Fn->FirstReturnLoc.isValid()) { 1053 assert(Fn->FirstCoroutineStmtLoc.isValid() && 1054 "first coroutine location not set"); 1055 Diag(Fn->FirstReturnLoc, diag::err_return_in_coroutine); 1056 Diag(Fn->FirstCoroutineStmtLoc, diag::note_declared_coroutine_here) 1057 << Fn->getFirstCoroutineStmtKeyword(); 1058 } 1059 CoroutineStmtBuilder Builder(*this, *FD, *Fn, Body); 1060 if (Builder.isInvalid() || !Builder.buildStatements()) 1061 return FD->setInvalidDecl(); 1062 1063 // Build body for the coroutine wrapper statement. 1064 Body = CoroutineBodyStmt::Create(Context, Builder); 1065 } 1066 1067 CoroutineStmtBuilder::CoroutineStmtBuilder(Sema &S, FunctionDecl &FD, 1068 sema::FunctionScopeInfo &Fn, 1069 Stmt *Body) 1070 : S(S), FD(FD), Fn(Fn), Loc(FD.getLocation()), 1071 IsPromiseDependentType( 1072 !Fn.CoroutinePromise || 1073 Fn.CoroutinePromise->getType()->isDependentType()) { 1074 this->Body = Body; 1075 1076 for (auto KV : Fn.CoroutineParameterMoves) 1077 this->ParamMovesVector.push_back(KV.second); 1078 this->ParamMoves = this->ParamMovesVector; 1079 1080 if (!IsPromiseDependentType) { 1081 PromiseRecordDecl = Fn.CoroutinePromise->getType()->getAsCXXRecordDecl(); 1082 assert(PromiseRecordDecl && "Type should have already been checked"); 1083 } 1084 this->IsValid = makePromiseStmt() && makeInitialAndFinalSuspend(); 1085 } 1086 1087 bool CoroutineStmtBuilder::buildStatements() { 1088 assert(this->IsValid && "coroutine already invalid"); 1089 this->IsValid = makeReturnObject(); 1090 if (this->IsValid && !IsPromiseDependentType) 1091 buildDependentStatements(); 1092 return this->IsValid; 1093 } 1094 1095 bool CoroutineStmtBuilder::buildDependentStatements() { 1096 assert(this->IsValid && "coroutine already invalid"); 1097 assert(!this->IsPromiseDependentType && 1098 "coroutine cannot have a dependent promise type"); 1099 this->IsValid = makeOnException() && makeOnFallthrough() && 1100 makeGroDeclAndReturnStmt() && makeReturnOnAllocFailure() && 1101 makeNewAndDeleteExpr(); 1102 return this->IsValid; 1103 } 1104 1105 bool CoroutineStmtBuilder::makePromiseStmt() { 1106 // Form a declaration statement for the promise declaration, so that AST 1107 // visitors can more easily find it. 1108 StmtResult PromiseStmt = 1109 S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(Fn.CoroutinePromise), Loc, Loc); 1110 if (PromiseStmt.isInvalid()) 1111 return false; 1112 1113 this->Promise = PromiseStmt.get(); 1114 return true; 1115 } 1116 1117 bool CoroutineStmtBuilder::makeInitialAndFinalSuspend() { 1118 if (Fn.hasInvalidCoroutineSuspends()) 1119 return false; 1120 this->InitialSuspend = cast<Expr>(Fn.CoroutineSuspends.first); 1121 this->FinalSuspend = cast<Expr>(Fn.CoroutineSuspends.second); 1122 return true; 1123 } 1124 1125 static bool diagReturnOnAllocFailure(Sema &S, Expr *E, 1126 CXXRecordDecl *PromiseRecordDecl, 1127 FunctionScopeInfo &Fn) { 1128 auto Loc = E->getExprLoc(); 1129 if (auto *DeclRef = dyn_cast_or_null<DeclRefExpr>(E)) { 1130 auto *Decl = DeclRef->getDecl(); 1131 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Decl)) { 1132 if (Method->isStatic()) 1133 return true; 1134 else 1135 Loc = Decl->getLocation(); 1136 } 1137 } 1138 1139 S.Diag( 1140 Loc, 1141 diag::err_coroutine_promise_get_return_object_on_allocation_failure) 1142 << PromiseRecordDecl; 1143 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here) 1144 << Fn.getFirstCoroutineStmtKeyword(); 1145 return false; 1146 } 1147 1148 bool CoroutineStmtBuilder::makeReturnOnAllocFailure() { 1149 assert(!IsPromiseDependentType && 1150 "cannot make statement while the promise type is dependent"); 1151 1152 // [dcl.fct.def.coroutine]/8 1153 // The unqualified-id get_return_object_on_allocation_failure is looked up in 1154 // the scope of class P by class member access lookup (3.4.5). ... 1155 // If an allocation function returns nullptr, ... the coroutine return value 1156 // is obtained by a call to ... get_return_object_on_allocation_failure(). 1157 1158 DeclarationName DN = 1159 S.PP.getIdentifierInfo("get_return_object_on_allocation_failure"); 1160 LookupResult Found(S, DN, Loc, Sema::LookupMemberName); 1161 if (!S.LookupQualifiedName(Found, PromiseRecordDecl)) 1162 return true; 1163 1164 CXXScopeSpec SS; 1165 ExprResult DeclNameExpr = 1166 S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false); 1167 if (DeclNameExpr.isInvalid()) 1168 return false; 1169 1170 if (!diagReturnOnAllocFailure(S, DeclNameExpr.get(), PromiseRecordDecl, Fn)) 1171 return false; 1172 1173 ExprResult ReturnObjectOnAllocationFailure = 1174 S.BuildCallExpr(nullptr, DeclNameExpr.get(), Loc, {}, Loc); 1175 if (ReturnObjectOnAllocationFailure.isInvalid()) 1176 return false; 1177 1178 StmtResult ReturnStmt = 1179 S.BuildReturnStmt(Loc, ReturnObjectOnAllocationFailure.get()); 1180 if (ReturnStmt.isInvalid()) { 1181 S.Diag(Found.getFoundDecl()->getLocation(), diag::note_member_declared_here) 1182 << DN; 1183 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here) 1184 << Fn.getFirstCoroutineStmtKeyword(); 1185 return false; 1186 } 1187 1188 this->ReturnStmtOnAllocFailure = ReturnStmt.get(); 1189 return true; 1190 } 1191 1192 bool CoroutineStmtBuilder::makeNewAndDeleteExpr() { 1193 // Form and check allocation and deallocation calls. 1194 assert(!IsPromiseDependentType && 1195 "cannot make statement while the promise type is dependent"); 1196 QualType PromiseType = Fn.CoroutinePromise->getType(); 1197 1198 if (S.RequireCompleteType(Loc, PromiseType, diag::err_incomplete_type)) 1199 return false; 1200 1201 const bool RequiresNoThrowAlloc = ReturnStmtOnAllocFailure != nullptr; 1202 1203 // [dcl.fct.def.coroutine]/7 1204 // Lookup allocation functions using a parameter list composed of the 1205 // requested size of the coroutine state being allocated, followed by 1206 // the coroutine function's arguments. If a matching allocation function 1207 // exists, use it. Otherwise, use an allocation function that just takes 1208 // the requested size. 1209 1210 FunctionDecl *OperatorNew = nullptr; 1211 FunctionDecl *OperatorDelete = nullptr; 1212 FunctionDecl *UnusedResult = nullptr; 1213 bool PassAlignment = false; 1214 SmallVector<Expr *, 1> PlacementArgs; 1215 1216 // [dcl.fct.def.coroutine]/7 1217 // "The allocation function’s name is looked up in the scope of P. 1218 // [...] If the lookup finds an allocation function in the scope of P, 1219 // overload resolution is performed on a function call created by assembling 1220 // an argument list. The first argument is the amount of space requested, 1221 // and has type std::size_t. The lvalues p1 ... pn are the succeeding 1222 // arguments." 1223 // 1224 // ...where "p1 ... pn" are defined earlier as: 1225 // 1226 // [dcl.fct.def.coroutine]/3 1227 // "For a coroutine f that is a non-static member function, let P1 denote the 1228 // type of the implicit object parameter (13.3.1) and P2 ... Pn be the types 1229 // of the function parameters; otherwise let P1 ... Pn be the types of the 1230 // function parameters. Let p1 ... pn be lvalues denoting those objects." 1231 if (auto *MD = dyn_cast<CXXMethodDecl>(&FD)) { 1232 if (MD->isInstance() && !isLambdaCallOperator(MD)) { 1233 ExprResult ThisExpr = S.ActOnCXXThis(Loc); 1234 if (ThisExpr.isInvalid()) 1235 return false; 1236 ThisExpr = S.CreateBuiltinUnaryOp(Loc, UO_Deref, ThisExpr.get()); 1237 if (ThisExpr.isInvalid()) 1238 return false; 1239 PlacementArgs.push_back(ThisExpr.get()); 1240 } 1241 } 1242 for (auto *PD : FD.parameters()) { 1243 if (PD->getType()->isDependentType()) 1244 continue; 1245 1246 // Build a reference to the parameter. 1247 auto PDLoc = PD->getLocation(); 1248 ExprResult PDRefExpr = 1249 S.BuildDeclRefExpr(PD, PD->getOriginalType().getNonReferenceType(), 1250 ExprValueKind::VK_LValue, PDLoc); 1251 if (PDRefExpr.isInvalid()) 1252 return false; 1253 1254 PlacementArgs.push_back(PDRefExpr.get()); 1255 } 1256 S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Class, 1257 /*DeleteScope*/ Sema::AFS_Both, PromiseType, 1258 /*isArray*/ false, PassAlignment, PlacementArgs, 1259 OperatorNew, UnusedResult, /*Diagnose*/ false); 1260 1261 // [dcl.fct.def.coroutine]/7 1262 // "If no matching function is found, overload resolution is performed again 1263 // on a function call created by passing just the amount of space required as 1264 // an argument of type std::size_t." 1265 if (!OperatorNew && !PlacementArgs.empty()) { 1266 PlacementArgs.clear(); 1267 S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Class, 1268 /*DeleteScope*/ Sema::AFS_Both, PromiseType, 1269 /*isArray*/ false, PassAlignment, PlacementArgs, 1270 OperatorNew, UnusedResult, /*Diagnose*/ false); 1271 } 1272 1273 // [dcl.fct.def.coroutine]/7 1274 // "The allocation function’s name is looked up in the scope of P. If this 1275 // lookup fails, the allocation function’s name is looked up in the global 1276 // scope." 1277 if (!OperatorNew) { 1278 S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Global, 1279 /*DeleteScope*/ Sema::AFS_Both, PromiseType, 1280 /*isArray*/ false, PassAlignment, PlacementArgs, 1281 OperatorNew, UnusedResult); 1282 } 1283 1284 bool IsGlobalOverload = 1285 OperatorNew && !isa<CXXRecordDecl>(OperatorNew->getDeclContext()); 1286 // If we didn't find a class-local new declaration and non-throwing new 1287 // was is required then we need to lookup the non-throwing global operator 1288 // instead. 1289 if (RequiresNoThrowAlloc && (!OperatorNew || IsGlobalOverload)) { 1290 auto *StdNoThrow = buildStdNoThrowDeclRef(S, Loc); 1291 if (!StdNoThrow) 1292 return false; 1293 PlacementArgs = {StdNoThrow}; 1294 OperatorNew = nullptr; 1295 S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Both, 1296 /*DeleteScope*/ Sema::AFS_Both, PromiseType, 1297 /*isArray*/ false, PassAlignment, PlacementArgs, 1298 OperatorNew, UnusedResult); 1299 } 1300 1301 if (!OperatorNew) 1302 return false; 1303 1304 if (RequiresNoThrowAlloc) { 1305 const auto *FT = OperatorNew->getType()->castAs<FunctionProtoType>(); 1306 if (!FT->isNothrow(/*ResultIfDependent*/ false)) { 1307 S.Diag(OperatorNew->getLocation(), 1308 diag::err_coroutine_promise_new_requires_nothrow) 1309 << OperatorNew; 1310 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required) 1311 << OperatorNew; 1312 return false; 1313 } 1314 } 1315 1316 if ((OperatorDelete = findDeleteForPromise(S, Loc, PromiseType)) == nullptr) 1317 return false; 1318 1319 Expr *FramePtr = 1320 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_frame, {}); 1321 1322 Expr *FrameSize = 1323 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_size, {}); 1324 1325 // Make new call. 1326 1327 ExprResult NewRef = 1328 S.BuildDeclRefExpr(OperatorNew, OperatorNew->getType(), VK_LValue, Loc); 1329 if (NewRef.isInvalid()) 1330 return false; 1331 1332 SmallVector<Expr *, 2> NewArgs(1, FrameSize); 1333 for (auto Arg : PlacementArgs) 1334 NewArgs.push_back(Arg); 1335 1336 ExprResult NewExpr = 1337 S.BuildCallExpr(S.getCurScope(), NewRef.get(), Loc, NewArgs, Loc); 1338 NewExpr = S.ActOnFinishFullExpr(NewExpr.get(), /*DiscardedValue*/ false); 1339 if (NewExpr.isInvalid()) 1340 return false; 1341 1342 // Make delete call. 1343 1344 QualType OpDeleteQualType = OperatorDelete->getType(); 1345 1346 ExprResult DeleteRef = 1347 S.BuildDeclRefExpr(OperatorDelete, OpDeleteQualType, VK_LValue, Loc); 1348 if (DeleteRef.isInvalid()) 1349 return false; 1350 1351 Expr *CoroFree = 1352 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_free, {FramePtr}); 1353 1354 SmallVector<Expr *, 2> DeleteArgs{CoroFree}; 1355 1356 // Check if we need to pass the size. 1357 const auto *OpDeleteType = 1358 OpDeleteQualType.getTypePtr()->castAs<FunctionProtoType>(); 1359 if (OpDeleteType->getNumParams() > 1) 1360 DeleteArgs.push_back(FrameSize); 1361 1362 ExprResult DeleteExpr = 1363 S.BuildCallExpr(S.getCurScope(), DeleteRef.get(), Loc, DeleteArgs, Loc); 1364 DeleteExpr = 1365 S.ActOnFinishFullExpr(DeleteExpr.get(), /*DiscardedValue*/ false); 1366 if (DeleteExpr.isInvalid()) 1367 return false; 1368 1369 this->Allocate = NewExpr.get(); 1370 this->Deallocate = DeleteExpr.get(); 1371 1372 return true; 1373 } 1374 1375 bool CoroutineStmtBuilder::makeOnFallthrough() { 1376 assert(!IsPromiseDependentType && 1377 "cannot make statement while the promise type is dependent"); 1378 1379 // [dcl.fct.def.coroutine]/4 1380 // The unqualified-ids 'return_void' and 'return_value' are looked up in 1381 // the scope of class P. If both are found, the program is ill-formed. 1382 bool HasRVoid, HasRValue; 1383 LookupResult LRVoid = 1384 lookupMember(S, "return_void", PromiseRecordDecl, Loc, HasRVoid); 1385 LookupResult LRValue = 1386 lookupMember(S, "return_value", PromiseRecordDecl, Loc, HasRValue); 1387 1388 StmtResult Fallthrough; 1389 if (HasRVoid && HasRValue) { 1390 // FIXME Improve this diagnostic 1391 S.Diag(FD.getLocation(), 1392 diag::err_coroutine_promise_incompatible_return_functions) 1393 << PromiseRecordDecl; 1394 S.Diag(LRVoid.getRepresentativeDecl()->getLocation(), 1395 diag::note_member_first_declared_here) 1396 << LRVoid.getLookupName(); 1397 S.Diag(LRValue.getRepresentativeDecl()->getLocation(), 1398 diag::note_member_first_declared_here) 1399 << LRValue.getLookupName(); 1400 return false; 1401 } else if (!HasRVoid && !HasRValue) { 1402 // FIXME: The PDTS currently specifies this case as UB, not ill-formed. 1403 // However we still diagnose this as an error since until the PDTS is fixed. 1404 S.Diag(FD.getLocation(), 1405 diag::err_coroutine_promise_requires_return_function) 1406 << PromiseRecordDecl; 1407 S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here) 1408 << PromiseRecordDecl; 1409 return false; 1410 } else if (HasRVoid) { 1411 // If the unqualified-id return_void is found, flowing off the end of a 1412 // coroutine is equivalent to a co_return with no operand. Otherwise, 1413 // flowing off the end of a coroutine results in undefined behavior. 1414 Fallthrough = S.BuildCoreturnStmt(FD.getLocation(), nullptr, 1415 /*IsImplicit*/false); 1416 Fallthrough = S.ActOnFinishFullStmt(Fallthrough.get()); 1417 if (Fallthrough.isInvalid()) 1418 return false; 1419 } 1420 1421 this->OnFallthrough = Fallthrough.get(); 1422 return true; 1423 } 1424 1425 bool CoroutineStmtBuilder::makeOnException() { 1426 // Try to form 'p.unhandled_exception();' 1427 assert(!IsPromiseDependentType && 1428 "cannot make statement while the promise type is dependent"); 1429 1430 const bool RequireUnhandledException = S.getLangOpts().CXXExceptions; 1431 1432 if (!lookupMember(S, "unhandled_exception", PromiseRecordDecl, Loc)) { 1433 auto DiagID = 1434 RequireUnhandledException 1435 ? diag::err_coroutine_promise_unhandled_exception_required 1436 : diag:: 1437 warn_coroutine_promise_unhandled_exception_required_with_exceptions; 1438 S.Diag(Loc, DiagID) << PromiseRecordDecl; 1439 S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here) 1440 << PromiseRecordDecl; 1441 return !RequireUnhandledException; 1442 } 1443 1444 // If exceptions are disabled, don't try to build OnException. 1445 if (!S.getLangOpts().CXXExceptions) 1446 return true; 1447 1448 ExprResult UnhandledException = buildPromiseCall(S, Fn.CoroutinePromise, Loc, 1449 "unhandled_exception", None); 1450 UnhandledException = S.ActOnFinishFullExpr(UnhandledException.get(), Loc, 1451 /*DiscardedValue*/ false); 1452 if (UnhandledException.isInvalid()) 1453 return false; 1454 1455 // Since the body of the coroutine will be wrapped in try-catch, it will 1456 // be incompatible with SEH __try if present in a function. 1457 if (!S.getLangOpts().Borland && Fn.FirstSEHTryLoc.isValid()) { 1458 S.Diag(Fn.FirstSEHTryLoc, diag::err_seh_in_a_coroutine_with_cxx_exceptions); 1459 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here) 1460 << Fn.getFirstCoroutineStmtKeyword(); 1461 return false; 1462 } 1463 1464 this->OnException = UnhandledException.get(); 1465 return true; 1466 } 1467 1468 bool CoroutineStmtBuilder::makeReturnObject() { 1469 // Build implicit 'p.get_return_object()' expression and form initialization 1470 // of return type from it. 1471 ExprResult ReturnObject = 1472 buildPromiseCall(S, Fn.CoroutinePromise, Loc, "get_return_object", None); 1473 if (ReturnObject.isInvalid()) 1474 return false; 1475 1476 this->ReturnValue = ReturnObject.get(); 1477 return true; 1478 } 1479 1480 static void noteMemberDeclaredHere(Sema &S, Expr *E, FunctionScopeInfo &Fn) { 1481 if (auto *MbrRef = dyn_cast<CXXMemberCallExpr>(E)) { 1482 auto *MethodDecl = MbrRef->getMethodDecl(); 1483 S.Diag(MethodDecl->getLocation(), diag::note_member_declared_here) 1484 << MethodDecl; 1485 } 1486 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here) 1487 << Fn.getFirstCoroutineStmtKeyword(); 1488 } 1489 1490 bool CoroutineStmtBuilder::makeGroDeclAndReturnStmt() { 1491 assert(!IsPromiseDependentType && 1492 "cannot make statement while the promise type is dependent"); 1493 assert(this->ReturnValue && "ReturnValue must be already formed"); 1494 1495 QualType const GroType = this->ReturnValue->getType(); 1496 assert(!GroType->isDependentType() && 1497 "get_return_object type must no longer be dependent"); 1498 1499 QualType const FnRetType = FD.getReturnType(); 1500 assert(!FnRetType->isDependentType() && 1501 "get_return_object type must no longer be dependent"); 1502 1503 if (FnRetType->isVoidType()) { 1504 ExprResult Res = 1505 S.ActOnFinishFullExpr(this->ReturnValue, Loc, /*DiscardedValue*/ false); 1506 if (Res.isInvalid()) 1507 return false; 1508 1509 this->ResultDecl = Res.get(); 1510 return true; 1511 } 1512 1513 if (GroType->isVoidType()) { 1514 // Trigger a nice error message. 1515 InitializedEntity Entity = 1516 InitializedEntity::InitializeResult(Loc, FnRetType, false); 1517 S.PerformMoveOrCopyInitialization(Entity, nullptr, FnRetType, ReturnValue); 1518 noteMemberDeclaredHere(S, ReturnValue, Fn); 1519 return false; 1520 } 1521 1522 auto *GroDecl = VarDecl::Create( 1523 S.Context, &FD, FD.getLocation(), FD.getLocation(), 1524 &S.PP.getIdentifierTable().get("__coro_gro"), GroType, 1525 S.Context.getTrivialTypeSourceInfo(GroType, Loc), SC_None); 1526 1527 S.CheckVariableDeclarationType(GroDecl); 1528 if (GroDecl->isInvalidDecl()) 1529 return false; 1530 1531 InitializedEntity Entity = InitializedEntity::InitializeVariable(GroDecl); 1532 ExprResult Res = S.PerformMoveOrCopyInitialization(Entity, nullptr, GroType, 1533 this->ReturnValue); 1534 if (Res.isInvalid()) 1535 return false; 1536 1537 Res = S.ActOnFinishFullExpr(Res.get(), /*DiscardedValue*/ false); 1538 if (Res.isInvalid()) 1539 return false; 1540 1541 S.AddInitializerToDecl(GroDecl, Res.get(), 1542 /*DirectInit=*/false); 1543 1544 S.FinalizeDeclaration(GroDecl); 1545 1546 // Form a declaration statement for the return declaration, so that AST 1547 // visitors can more easily find it. 1548 StmtResult GroDeclStmt = 1549 S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(GroDecl), Loc, Loc); 1550 if (GroDeclStmt.isInvalid()) 1551 return false; 1552 1553 this->ResultDecl = GroDeclStmt.get(); 1554 1555 ExprResult declRef = S.BuildDeclRefExpr(GroDecl, GroType, VK_LValue, Loc); 1556 if (declRef.isInvalid()) 1557 return false; 1558 1559 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, declRef.get()); 1560 if (ReturnStmt.isInvalid()) { 1561 noteMemberDeclaredHere(S, ReturnValue, Fn); 1562 return false; 1563 } 1564 if (cast<clang::ReturnStmt>(ReturnStmt.get())->getNRVOCandidate() == GroDecl) 1565 GroDecl->setNRVOVariable(true); 1566 1567 this->ReturnStmt = ReturnStmt.get(); 1568 return true; 1569 } 1570 1571 // Create a static_cast\<T&&>(expr). 1572 static Expr *castForMoving(Sema &S, Expr *E, QualType T = QualType()) { 1573 if (T.isNull()) 1574 T = E->getType(); 1575 QualType TargetType = S.BuildReferenceType( 1576 T, /*SpelledAsLValue*/ false, SourceLocation(), DeclarationName()); 1577 SourceLocation ExprLoc = E->getBeginLoc(); 1578 TypeSourceInfo *TargetLoc = 1579 S.Context.getTrivialTypeSourceInfo(TargetType, ExprLoc); 1580 1581 return S 1582 .BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 1583 SourceRange(ExprLoc, ExprLoc), E->getSourceRange()) 1584 .get(); 1585 } 1586 1587 /// Build a variable declaration for move parameter. 1588 static VarDecl *buildVarDecl(Sema &S, SourceLocation Loc, QualType Type, 1589 IdentifierInfo *II) { 1590 TypeSourceInfo *TInfo = S.Context.getTrivialTypeSourceInfo(Type, Loc); 1591 VarDecl *Decl = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, II, Type, 1592 TInfo, SC_None); 1593 Decl->setImplicit(); 1594 return Decl; 1595 } 1596 1597 // Build statements that move coroutine function parameters to the coroutine 1598 // frame, and store them on the function scope info. 1599 bool Sema::buildCoroutineParameterMoves(SourceLocation Loc) { 1600 assert(isa<FunctionDecl>(CurContext) && "not in a function scope"); 1601 auto *FD = cast<FunctionDecl>(CurContext); 1602 1603 auto *ScopeInfo = getCurFunction(); 1604 if (!ScopeInfo->CoroutineParameterMoves.empty()) 1605 return false; 1606 1607 for (auto *PD : FD->parameters()) { 1608 if (PD->getType()->isDependentType()) 1609 continue; 1610 1611 ExprResult PDRefExpr = 1612 BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(), 1613 ExprValueKind::VK_LValue, Loc); // FIXME: scope? 1614 if (PDRefExpr.isInvalid()) 1615 return false; 1616 1617 Expr *CExpr = nullptr; 1618 if (PD->getType()->getAsCXXRecordDecl() || 1619 PD->getType()->isRValueReferenceType()) 1620 CExpr = castForMoving(*this, PDRefExpr.get()); 1621 else 1622 CExpr = PDRefExpr.get(); 1623 1624 auto D = buildVarDecl(*this, Loc, PD->getType(), PD->getIdentifier()); 1625 AddInitializerToDecl(D, CExpr, /*DirectInit=*/true); 1626 1627 // Convert decl to a statement. 1628 StmtResult Stmt = ActOnDeclStmt(ConvertDeclToDeclGroup(D), Loc, Loc); 1629 if (Stmt.isInvalid()) 1630 return false; 1631 1632 ScopeInfo->CoroutineParameterMoves.insert(std::make_pair(PD, Stmt.get())); 1633 } 1634 return true; 1635 } 1636 1637 StmtResult Sema::BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) { 1638 CoroutineBodyStmt *Res = CoroutineBodyStmt::Create(Context, Args); 1639 if (!Res) 1640 return StmtError(); 1641 return Res; 1642 } 1643 1644 ClassTemplateDecl *Sema::lookupCoroutineTraits(SourceLocation KwLoc, 1645 SourceLocation FuncLoc) { 1646 if (!StdCoroutineTraitsCache) { 1647 if (auto StdExp = lookupStdExperimentalNamespace()) { 1648 LookupResult Result(*this, 1649 &PP.getIdentifierTable().get("coroutine_traits"), 1650 FuncLoc, LookupOrdinaryName); 1651 if (!LookupQualifiedName(Result, StdExp)) { 1652 Diag(KwLoc, diag::err_implied_coroutine_type_not_found) 1653 << "std::experimental::coroutine_traits"; 1654 return nullptr; 1655 } 1656 if (!(StdCoroutineTraitsCache = 1657 Result.getAsSingle<ClassTemplateDecl>())) { 1658 Result.suppressDiagnostics(); 1659 NamedDecl *Found = *Result.begin(); 1660 Diag(Found->getLocation(), diag::err_malformed_std_coroutine_traits); 1661 return nullptr; 1662 } 1663 } 1664 } 1665 return StdCoroutineTraitsCache; 1666 } 1667