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 395 // Check that the type of AddressExpr is void* 396 if (!JustAddress->getType().getTypePtr()->isVoidPointerType()) 397 S.Diag(cast<CallExpr>(JustAddress)->getCalleeDecl()->getLocation(), 398 diag::warn_coroutine_handle_address_invalid_return_type) 399 << JustAddress->getType(); 400 401 return buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_resume, 402 JustAddress); 403 } 404 405 /// Build calls to await_ready, await_suspend, and await_resume for a co_await 406 /// expression. 407 static ReadySuspendResumeResult buildCoawaitCalls(Sema &S, VarDecl *CoroPromise, 408 SourceLocation Loc, Expr *E) { 409 OpaqueValueExpr *Operand = new (S.Context) 410 OpaqueValueExpr(Loc, E->getType(), VK_LValue, E->getObjectKind(), E); 411 412 // Assume invalid until we see otherwise. 413 ReadySuspendResumeResult Calls = {{}, Operand, /*IsInvalid=*/true}; 414 415 ExprResult CoroHandleRes = buildCoroutineHandle(S, CoroPromise->getType(), Loc); 416 if (CoroHandleRes.isInvalid()) 417 return Calls; 418 Expr *CoroHandle = CoroHandleRes.get(); 419 420 const StringRef Funcs[] = {"await_ready", "await_suspend", "await_resume"}; 421 MultiExprArg Args[] = {None, CoroHandle, None}; 422 for (size_t I = 0, N = llvm::array_lengthof(Funcs); I != N; ++I) { 423 ExprResult Result = buildMemberCall(S, Operand, Loc, Funcs[I], Args[I]); 424 if (Result.isInvalid()) 425 return Calls; 426 Calls.Results[I] = Result.get(); 427 } 428 429 // Assume the calls are valid; all further checking should make them invalid. 430 Calls.IsInvalid = false; 431 432 using ACT = ReadySuspendResumeResult::AwaitCallType; 433 CallExpr *AwaitReady = cast<CallExpr>(Calls.Results[ACT::ACT_Ready]); 434 if (!AwaitReady->getType()->isDependentType()) { 435 // [expr.await]p3 [...] 436 // — await-ready is the expression e.await_ready(), contextually converted 437 // to bool. 438 ExprResult Conv = S.PerformContextuallyConvertToBool(AwaitReady); 439 if (Conv.isInvalid()) { 440 S.Diag(AwaitReady->getDirectCallee()->getBeginLoc(), 441 diag::note_await_ready_no_bool_conversion); 442 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required) 443 << AwaitReady->getDirectCallee() << E->getSourceRange(); 444 Calls.IsInvalid = true; 445 } 446 Calls.Results[ACT::ACT_Ready] = Conv.get(); 447 } 448 CallExpr *AwaitSuspend = cast<CallExpr>(Calls.Results[ACT::ACT_Suspend]); 449 if (!AwaitSuspend->getType()->isDependentType()) { 450 // [expr.await]p3 [...] 451 // - await-suspend is the expression e.await_suspend(h), which shall be 452 // a prvalue of type void, bool, or std::coroutine_handle<Z> for some 453 // type Z. 454 QualType RetType = AwaitSuspend->getCallReturnType(S.Context); 455 456 // Experimental support for coroutine_handle returning await_suspend. 457 if (Expr *TailCallSuspend = maybeTailCall(S, RetType, AwaitSuspend, Loc)) 458 Calls.Results[ACT::ACT_Suspend] = TailCallSuspend; 459 else { 460 // non-class prvalues always have cv-unqualified types 461 if (RetType->isReferenceType() || 462 (!RetType->isBooleanType() && !RetType->isVoidType())) { 463 S.Diag(AwaitSuspend->getCalleeDecl()->getLocation(), 464 diag::err_await_suspend_invalid_return_type) 465 << RetType; 466 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required) 467 << AwaitSuspend->getDirectCallee(); 468 Calls.IsInvalid = true; 469 } 470 } 471 } 472 473 return Calls; 474 } 475 476 static ExprResult buildPromiseCall(Sema &S, VarDecl *Promise, 477 SourceLocation Loc, StringRef Name, 478 MultiExprArg Args) { 479 480 // Form a reference to the promise. 481 ExprResult PromiseRef = S.BuildDeclRefExpr( 482 Promise, Promise->getType().getNonReferenceType(), VK_LValue, Loc); 483 if (PromiseRef.isInvalid()) 484 return ExprError(); 485 486 return buildMemberCall(S, PromiseRef.get(), Loc, Name, Args); 487 } 488 489 VarDecl *Sema::buildCoroutinePromise(SourceLocation Loc) { 490 assert(isa<FunctionDecl>(CurContext) && "not in a function scope"); 491 auto *FD = cast<FunctionDecl>(CurContext); 492 bool IsThisDependentType = [&] { 493 if (auto *MD = dyn_cast_or_null<CXXMethodDecl>(FD)) 494 return MD->isInstance() && MD->getThisType()->isDependentType(); 495 else 496 return false; 497 }(); 498 499 QualType T = FD->getType()->isDependentType() || IsThisDependentType 500 ? Context.DependentTy 501 : lookupPromiseType(*this, FD, Loc); 502 if (T.isNull()) 503 return nullptr; 504 505 auto *VD = VarDecl::Create(Context, FD, FD->getLocation(), FD->getLocation(), 506 &PP.getIdentifierTable().get("__promise"), T, 507 Context.getTrivialTypeSourceInfo(T, Loc), SC_None); 508 CheckVariableDeclarationType(VD); 509 if (VD->isInvalidDecl()) 510 return nullptr; 511 512 auto *ScopeInfo = getCurFunction(); 513 514 // Build a list of arguments, based on the coroutine function's arguments, 515 // that if present will be passed to the promise type's constructor. 516 llvm::SmallVector<Expr *, 4> CtorArgExprs; 517 518 // Add implicit object parameter. 519 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 520 if (MD->isInstance() && !isLambdaCallOperator(MD)) { 521 ExprResult ThisExpr = ActOnCXXThis(Loc); 522 if (ThisExpr.isInvalid()) 523 return nullptr; 524 ThisExpr = CreateBuiltinUnaryOp(Loc, UO_Deref, ThisExpr.get()); 525 if (ThisExpr.isInvalid()) 526 return nullptr; 527 CtorArgExprs.push_back(ThisExpr.get()); 528 } 529 } 530 531 // Add the coroutine function's parameters. 532 auto &Moves = ScopeInfo->CoroutineParameterMoves; 533 for (auto *PD : FD->parameters()) { 534 if (PD->getType()->isDependentType()) 535 continue; 536 537 auto RefExpr = ExprEmpty(); 538 auto Move = Moves.find(PD); 539 assert(Move != Moves.end() && 540 "Coroutine function parameter not inserted into move map"); 541 // If a reference to the function parameter exists in the coroutine 542 // frame, use that reference. 543 auto *MoveDecl = 544 cast<VarDecl>(cast<DeclStmt>(Move->second)->getSingleDecl()); 545 RefExpr = 546 BuildDeclRefExpr(MoveDecl, MoveDecl->getType().getNonReferenceType(), 547 ExprValueKind::VK_LValue, FD->getLocation()); 548 if (RefExpr.isInvalid()) 549 return nullptr; 550 CtorArgExprs.push_back(RefExpr.get()); 551 } 552 553 // If we have a non-zero number of constructor arguments, try to use them. 554 // Otherwise, fall back to the promise type's default constructor. 555 if (!CtorArgExprs.empty()) { 556 // Create an initialization sequence for the promise type using the 557 // constructor arguments, wrapped in a parenthesized list expression. 558 Expr *PLE = ParenListExpr::Create(Context, FD->getLocation(), 559 CtorArgExprs, FD->getLocation()); 560 InitializedEntity Entity = InitializedEntity::InitializeVariable(VD); 561 InitializationKind Kind = InitializationKind::CreateForInit( 562 VD->getLocation(), /*DirectInit=*/true, PLE); 563 InitializationSequence InitSeq(*this, Entity, Kind, CtorArgExprs, 564 /*TopLevelOfInitList=*/false, 565 /*TreatUnavailableAsInvalid=*/false); 566 567 // Attempt to initialize the promise type with the arguments. 568 // If that fails, fall back to the promise type's default constructor. 569 if (InitSeq) { 570 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, CtorArgExprs); 571 if (Result.isInvalid()) { 572 VD->setInvalidDecl(); 573 } else if (Result.get()) { 574 VD->setInit(MaybeCreateExprWithCleanups(Result.get())); 575 VD->setInitStyle(VarDecl::CallInit); 576 CheckCompleteVariableDeclaration(VD); 577 } 578 } else 579 ActOnUninitializedDecl(VD); 580 } else 581 ActOnUninitializedDecl(VD); 582 583 FD->addDecl(VD); 584 return VD; 585 } 586 587 /// Check that this is a context in which a coroutine suspension can appear. 588 static FunctionScopeInfo *checkCoroutineContext(Sema &S, SourceLocation Loc, 589 StringRef Keyword, 590 bool IsImplicit = false) { 591 if (!isValidCoroutineContext(S, Loc, Keyword)) 592 return nullptr; 593 594 assert(isa<FunctionDecl>(S.CurContext) && "not in a function scope"); 595 596 auto *ScopeInfo = S.getCurFunction(); 597 assert(ScopeInfo && "missing function scope for function"); 598 599 if (ScopeInfo->FirstCoroutineStmtLoc.isInvalid() && !IsImplicit) 600 ScopeInfo->setFirstCoroutineStmt(Loc, Keyword); 601 602 if (ScopeInfo->CoroutinePromise) 603 return ScopeInfo; 604 605 if (!S.buildCoroutineParameterMoves(Loc)) 606 return nullptr; 607 608 ScopeInfo->CoroutinePromise = S.buildCoroutinePromise(Loc); 609 if (!ScopeInfo->CoroutinePromise) 610 return nullptr; 611 612 return ScopeInfo; 613 } 614 615 /// Recursively check \p E and all its children to see if any call target 616 /// (including constructor call) is declared noexcept. Also any value returned 617 /// from the call has a noexcept destructor. 618 static void checkNoThrow(Sema &S, const Stmt *E, 619 llvm::SmallPtrSetImpl<const Decl *> &ThrowingDecls) { 620 auto checkDeclNoexcept = [&](const Decl *D, bool IsDtor = false) { 621 // In the case of dtor, the call to dtor is implicit and hence we should 622 // pass nullptr to canCalleeThrow. 623 if (Sema::canCalleeThrow(S, IsDtor ? nullptr : cast<Expr>(E), D)) { 624 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 625 // co_await promise.final_suspend() could end up calling 626 // __builtin_coro_resume for symmetric transfer if await_suspend() 627 // returns a handle. In that case, even __builtin_coro_resume is not 628 // declared as noexcept and may throw, it does not throw _into_ the 629 // coroutine that just suspended, but rather throws back out from 630 // whoever called coroutine_handle::resume(), hence we claim that 631 // logically it does not throw. 632 if (FD->getBuiltinID() == Builtin::BI__builtin_coro_resume) 633 return; 634 } 635 if (ThrowingDecls.empty()) { 636 // First time seeing an error, emit the error message. 637 S.Diag(cast<FunctionDecl>(S.CurContext)->getLocation(), 638 diag::err_coroutine_promise_final_suspend_requires_nothrow); 639 } 640 ThrowingDecls.insert(D); 641 } 642 }; 643 auto SC = E->getStmtClass(); 644 if (SC == Expr::CXXConstructExprClass) { 645 auto const *Ctor = cast<CXXConstructExpr>(E)->getConstructor(); 646 checkDeclNoexcept(Ctor); 647 // Check the corresponding destructor of the constructor. 648 checkDeclNoexcept(Ctor->getParent()->getDestructor(), true); 649 } else if (SC == Expr::CallExprClass || SC == Expr::CXXMemberCallExprClass || 650 SC == Expr::CXXOperatorCallExprClass) { 651 if (!cast<CallExpr>(E)->isTypeDependent()) { 652 checkDeclNoexcept(cast<CallExpr>(E)->getCalleeDecl()); 653 auto ReturnType = cast<CallExpr>(E)->getCallReturnType(S.getASTContext()); 654 // Check the destructor of the call return type, if any. 655 if (ReturnType.isDestructedType() == 656 QualType::DestructionKind::DK_cxx_destructor) { 657 const auto *T = 658 cast<RecordType>(ReturnType.getCanonicalType().getTypePtr()); 659 checkDeclNoexcept( 660 dyn_cast<CXXRecordDecl>(T->getDecl())->getDestructor(), true); 661 } 662 } 663 } 664 for (const auto *Child : E->children()) { 665 if (!Child) 666 continue; 667 checkNoThrow(S, Child, ThrowingDecls); 668 } 669 } 670 671 bool Sema::checkFinalSuspendNoThrow(const Stmt *FinalSuspend) { 672 llvm::SmallPtrSet<const Decl *, 4> ThrowingDecls; 673 // We first collect all declarations that should not throw but not declared 674 // with noexcept. We then sort them based on the location before printing. 675 // This is to avoid emitting the same note multiple times on the same 676 // declaration, and also provide a deterministic order for the messages. 677 checkNoThrow(*this, FinalSuspend, ThrowingDecls); 678 auto SortedDecls = llvm::SmallVector<const Decl *, 4>{ThrowingDecls.begin(), 679 ThrowingDecls.end()}; 680 sort(SortedDecls, [](const Decl *A, const Decl *B) { 681 return A->getEndLoc() < B->getEndLoc(); 682 }); 683 for (const auto *D : SortedDecls) { 684 Diag(D->getEndLoc(), diag::note_coroutine_function_declare_noexcept); 685 } 686 return ThrowingDecls.empty(); 687 } 688 689 bool Sema::ActOnCoroutineBodyStart(Scope *SC, SourceLocation KWLoc, 690 StringRef Keyword) { 691 if (!checkCoroutineContext(*this, KWLoc, Keyword)) 692 return false; 693 auto *ScopeInfo = getCurFunction(); 694 assert(ScopeInfo->CoroutinePromise); 695 696 // If we have existing coroutine statements then we have already built 697 // the initial and final suspend points. 698 if (!ScopeInfo->NeedsCoroutineSuspends) 699 return true; 700 701 ScopeInfo->setNeedsCoroutineSuspends(false); 702 703 auto *Fn = cast<FunctionDecl>(CurContext); 704 SourceLocation Loc = Fn->getLocation(); 705 // Build the initial suspend point 706 auto buildSuspends = [&](StringRef Name) mutable -> StmtResult { 707 ExprResult Suspend = 708 buildPromiseCall(*this, ScopeInfo->CoroutinePromise, Loc, Name, None); 709 if (Suspend.isInvalid()) 710 return StmtError(); 711 Suspend = buildOperatorCoawaitCall(*this, SC, Loc, Suspend.get()); 712 if (Suspend.isInvalid()) 713 return StmtError(); 714 Suspend = BuildResolvedCoawaitExpr(Loc, Suspend.get(), 715 /*IsImplicit*/ true); 716 Suspend = ActOnFinishFullExpr(Suspend.get(), /*DiscardedValue*/ false); 717 if (Suspend.isInvalid()) { 718 Diag(Loc, diag::note_coroutine_promise_suspend_implicitly_required) 719 << ((Name == "initial_suspend") ? 0 : 1); 720 Diag(KWLoc, diag::note_declared_coroutine_here) << Keyword; 721 return StmtError(); 722 } 723 return cast<Stmt>(Suspend.get()); 724 }; 725 726 StmtResult InitSuspend = buildSuspends("initial_suspend"); 727 if (InitSuspend.isInvalid()) 728 return true; 729 730 StmtResult FinalSuspend = buildSuspends("final_suspend"); 731 if (FinalSuspend.isInvalid() || !checkFinalSuspendNoThrow(FinalSuspend.get())) 732 return true; 733 734 ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get()); 735 736 return true; 737 } 738 739 // Recursively walks up the scope hierarchy until either a 'catch' or a function 740 // scope is found, whichever comes first. 741 static bool isWithinCatchScope(Scope *S) { 742 // 'co_await' and 'co_yield' keywords are disallowed within catch blocks, but 743 // lambdas that use 'co_await' are allowed. The loop below ends when a 744 // function scope is found in order to ensure the following behavior: 745 // 746 // void foo() { // <- function scope 747 // try { // 748 // co_await x; // <- 'co_await' is OK within a function scope 749 // } catch { // <- catch scope 750 // co_await x; // <- 'co_await' is not OK within a catch scope 751 // []() { // <- function scope 752 // co_await x; // <- 'co_await' is OK within a function scope 753 // }(); 754 // } 755 // } 756 while (S && !(S->getFlags() & Scope::FnScope)) { 757 if (S->getFlags() & Scope::CatchScope) 758 return true; 759 S = S->getParent(); 760 } 761 return false; 762 } 763 764 // [expr.await]p2, emphasis added: "An await-expression shall appear only in 765 // a *potentially evaluated* expression within the compound-statement of a 766 // function-body *outside of a handler* [...] A context within a function 767 // where an await-expression can appear is called a suspension context of the 768 // function." 769 static void checkSuspensionContext(Sema &S, SourceLocation Loc, 770 StringRef Keyword) { 771 // First emphasis of [expr.await]p2: must be a potentially evaluated context. 772 // That is, 'co_await' and 'co_yield' cannot appear in subexpressions of 773 // \c sizeof. 774 if (S.isUnevaluatedContext()) 775 S.Diag(Loc, diag::err_coroutine_unevaluated_context) << Keyword; 776 777 // Second emphasis of [expr.await]p2: must be outside of an exception handler. 778 if (isWithinCatchScope(S.getCurScope())) 779 S.Diag(Loc, diag::err_coroutine_within_handler) << Keyword; 780 } 781 782 ExprResult Sema::ActOnCoawaitExpr(Scope *S, SourceLocation Loc, Expr *E) { 783 if (!ActOnCoroutineBodyStart(S, Loc, "co_await")) { 784 CorrectDelayedTyposInExpr(E); 785 return ExprError(); 786 } 787 788 checkSuspensionContext(*this, Loc, "co_await"); 789 790 if (E->getType()->isPlaceholderType()) { 791 ExprResult R = CheckPlaceholderExpr(E); 792 if (R.isInvalid()) return ExprError(); 793 E = R.get(); 794 } 795 ExprResult Lookup = buildOperatorCoawaitLookupExpr(*this, S, Loc); 796 if (Lookup.isInvalid()) 797 return ExprError(); 798 return BuildUnresolvedCoawaitExpr(Loc, E, 799 cast<UnresolvedLookupExpr>(Lookup.get())); 800 } 801 802 ExprResult Sema::BuildUnresolvedCoawaitExpr(SourceLocation Loc, Expr *E, 803 UnresolvedLookupExpr *Lookup) { 804 auto *FSI = checkCoroutineContext(*this, Loc, "co_await"); 805 if (!FSI) 806 return ExprError(); 807 808 if (E->getType()->isPlaceholderType()) { 809 ExprResult R = CheckPlaceholderExpr(E); 810 if (R.isInvalid()) 811 return ExprError(); 812 E = R.get(); 813 } 814 815 auto *Promise = FSI->CoroutinePromise; 816 if (Promise->getType()->isDependentType()) { 817 Expr *Res = 818 new (Context) DependentCoawaitExpr(Loc, Context.DependentTy, E, Lookup); 819 return Res; 820 } 821 822 auto *RD = Promise->getType()->getAsCXXRecordDecl(); 823 if (lookupMember(*this, "await_transform", RD, Loc)) { 824 ExprResult R = buildPromiseCall(*this, Promise, Loc, "await_transform", E); 825 if (R.isInvalid()) { 826 Diag(Loc, 827 diag::note_coroutine_promise_implicit_await_transform_required_here) 828 << E->getSourceRange(); 829 return ExprError(); 830 } 831 E = R.get(); 832 } 833 ExprResult Awaitable = buildOperatorCoawaitCall(*this, Loc, E, Lookup); 834 if (Awaitable.isInvalid()) 835 return ExprError(); 836 837 return BuildResolvedCoawaitExpr(Loc, Awaitable.get()); 838 } 839 840 ExprResult Sema::BuildResolvedCoawaitExpr(SourceLocation Loc, Expr *E, 841 bool IsImplicit) { 842 auto *Coroutine = checkCoroutineContext(*this, Loc, "co_await", IsImplicit); 843 if (!Coroutine) 844 return ExprError(); 845 846 if (E->getType()->isPlaceholderType()) { 847 ExprResult R = CheckPlaceholderExpr(E); 848 if (R.isInvalid()) return ExprError(); 849 E = R.get(); 850 } 851 852 if (E->getType()->isDependentType()) { 853 Expr *Res = new (Context) 854 CoawaitExpr(Loc, Context.DependentTy, E, IsImplicit); 855 return Res; 856 } 857 858 // If the expression is a temporary, materialize it as an lvalue so that we 859 // can use it multiple times. 860 if (E->getValueKind() == VK_RValue) 861 E = CreateMaterializeTemporaryExpr(E->getType(), E, true); 862 863 // The location of the `co_await` token cannot be used when constructing 864 // the member call expressions since it's before the location of `Expr`, which 865 // is used as the start of the member call expression. 866 SourceLocation CallLoc = E->getExprLoc(); 867 868 // Build the await_ready, await_suspend, await_resume calls. 869 ReadySuspendResumeResult RSS = 870 buildCoawaitCalls(*this, Coroutine->CoroutinePromise, CallLoc, E); 871 if (RSS.IsInvalid) 872 return ExprError(); 873 874 Expr *Res = 875 new (Context) CoawaitExpr(Loc, E, RSS.Results[0], RSS.Results[1], 876 RSS.Results[2], RSS.OpaqueValue, IsImplicit); 877 878 return Res; 879 } 880 881 ExprResult Sema::ActOnCoyieldExpr(Scope *S, SourceLocation Loc, Expr *E) { 882 if (!ActOnCoroutineBodyStart(S, Loc, "co_yield")) { 883 CorrectDelayedTyposInExpr(E); 884 return ExprError(); 885 } 886 887 checkSuspensionContext(*this, Loc, "co_yield"); 888 889 // Build yield_value call. 890 ExprResult Awaitable = buildPromiseCall( 891 *this, getCurFunction()->CoroutinePromise, Loc, "yield_value", E); 892 if (Awaitable.isInvalid()) 893 return ExprError(); 894 895 // Build 'operator co_await' call. 896 Awaitable = buildOperatorCoawaitCall(*this, S, Loc, Awaitable.get()); 897 if (Awaitable.isInvalid()) 898 return ExprError(); 899 900 return BuildCoyieldExpr(Loc, Awaitable.get()); 901 } 902 ExprResult Sema::BuildCoyieldExpr(SourceLocation Loc, Expr *E) { 903 auto *Coroutine = checkCoroutineContext(*this, Loc, "co_yield"); 904 if (!Coroutine) 905 return ExprError(); 906 907 if (E->getType()->isPlaceholderType()) { 908 ExprResult R = CheckPlaceholderExpr(E); 909 if (R.isInvalid()) return ExprError(); 910 E = R.get(); 911 } 912 913 if (E->getType()->isDependentType()) { 914 Expr *Res = new (Context) CoyieldExpr(Loc, Context.DependentTy, E); 915 return Res; 916 } 917 918 // If the expression is a temporary, materialize it as an lvalue so that we 919 // can use it multiple times. 920 if (E->getValueKind() == VK_RValue) 921 E = CreateMaterializeTemporaryExpr(E->getType(), E, true); 922 923 // Build the await_ready, await_suspend, await_resume calls. 924 ReadySuspendResumeResult RSS = 925 buildCoawaitCalls(*this, Coroutine->CoroutinePromise, Loc, E); 926 if (RSS.IsInvalid) 927 return ExprError(); 928 929 Expr *Res = 930 new (Context) CoyieldExpr(Loc, E, RSS.Results[0], RSS.Results[1], 931 RSS.Results[2], RSS.OpaqueValue); 932 933 return Res; 934 } 935 936 StmtResult Sema::ActOnCoreturnStmt(Scope *S, SourceLocation Loc, Expr *E) { 937 if (!ActOnCoroutineBodyStart(S, Loc, "co_return")) { 938 CorrectDelayedTyposInExpr(E); 939 return StmtError(); 940 } 941 return BuildCoreturnStmt(Loc, E); 942 } 943 944 StmtResult Sema::BuildCoreturnStmt(SourceLocation Loc, Expr *E, 945 bool IsImplicit) { 946 auto *FSI = checkCoroutineContext(*this, Loc, "co_return", IsImplicit); 947 if (!FSI) 948 return StmtError(); 949 950 if (E && E->getType()->isPlaceholderType() && 951 !E->getType()->isSpecificPlaceholderType(BuiltinType::Overload)) { 952 ExprResult R = CheckPlaceholderExpr(E); 953 if (R.isInvalid()) return StmtError(); 954 E = R.get(); 955 } 956 957 // Move the return value if we can 958 if (E) { 959 auto NRVOCandidate = this->getCopyElisionCandidate(E->getType(), E, CES_AsIfByStdMove); 960 if (NRVOCandidate) { 961 InitializedEntity Entity = 962 InitializedEntity::InitializeResult(Loc, E->getType(), NRVOCandidate); 963 ExprResult MoveResult = this->PerformMoveOrCopyInitialization( 964 Entity, NRVOCandidate, E->getType(), E); 965 if (MoveResult.get()) 966 E = MoveResult.get(); 967 } 968 } 969 970 // FIXME: If the operand is a reference to a variable that's about to go out 971 // of scope, we should treat the operand as an xvalue for this overload 972 // resolution. 973 VarDecl *Promise = FSI->CoroutinePromise; 974 ExprResult PC; 975 if (E && (isa<InitListExpr>(E) || !E->getType()->isVoidType())) { 976 PC = buildPromiseCall(*this, Promise, Loc, "return_value", E); 977 } else { 978 E = MakeFullDiscardedValueExpr(E).get(); 979 PC = buildPromiseCall(*this, Promise, Loc, "return_void", None); 980 } 981 if (PC.isInvalid()) 982 return StmtError(); 983 984 Expr *PCE = ActOnFinishFullExpr(PC.get(), /*DiscardedValue*/ false).get(); 985 986 Stmt *Res = new (Context) CoreturnStmt(Loc, E, PCE, IsImplicit); 987 return Res; 988 } 989 990 /// Look up the std::nothrow object. 991 static Expr *buildStdNoThrowDeclRef(Sema &S, SourceLocation Loc) { 992 NamespaceDecl *Std = S.getStdNamespace(); 993 assert(Std && "Should already be diagnosed"); 994 995 LookupResult Result(S, &S.PP.getIdentifierTable().get("nothrow"), Loc, 996 Sema::LookupOrdinaryName); 997 if (!S.LookupQualifiedName(Result, Std)) { 998 // FIXME: <experimental/coroutine> should have been included already. 999 // If we require it to include <new> then this diagnostic is no longer 1000 // needed. 1001 S.Diag(Loc, diag::err_implicit_coroutine_std_nothrow_type_not_found); 1002 return nullptr; 1003 } 1004 1005 auto *VD = Result.getAsSingle<VarDecl>(); 1006 if (!VD) { 1007 Result.suppressDiagnostics(); 1008 // We found something weird. Complain about the first thing we found. 1009 NamedDecl *Found = *Result.begin(); 1010 S.Diag(Found->getLocation(), diag::err_malformed_std_nothrow); 1011 return nullptr; 1012 } 1013 1014 ExprResult DR = S.BuildDeclRefExpr(VD, VD->getType(), VK_LValue, Loc); 1015 if (DR.isInvalid()) 1016 return nullptr; 1017 1018 return DR.get(); 1019 } 1020 1021 // Find an appropriate delete for the promise. 1022 static FunctionDecl *findDeleteForPromise(Sema &S, SourceLocation Loc, 1023 QualType PromiseType) { 1024 FunctionDecl *OperatorDelete = nullptr; 1025 1026 DeclarationName DeleteName = 1027 S.Context.DeclarationNames.getCXXOperatorName(OO_Delete); 1028 1029 auto *PointeeRD = PromiseType->getAsCXXRecordDecl(); 1030 assert(PointeeRD && "PromiseType must be a CxxRecordDecl type"); 1031 1032 if (S.FindDeallocationFunction(Loc, PointeeRD, DeleteName, OperatorDelete)) 1033 return nullptr; 1034 1035 if (!OperatorDelete) { 1036 // Look for a global declaration. 1037 const bool CanProvideSize = S.isCompleteType(Loc, PromiseType); 1038 const bool Overaligned = false; 1039 OperatorDelete = S.FindUsualDeallocationFunction(Loc, CanProvideSize, 1040 Overaligned, DeleteName); 1041 } 1042 S.MarkFunctionReferenced(Loc, OperatorDelete); 1043 return OperatorDelete; 1044 } 1045 1046 1047 void Sema::CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body) { 1048 FunctionScopeInfo *Fn = getCurFunction(); 1049 assert(Fn && Fn->isCoroutine() && "not a coroutine"); 1050 if (!Body) { 1051 assert(FD->isInvalidDecl() && 1052 "a null body is only allowed for invalid declarations"); 1053 return; 1054 } 1055 // We have a function that uses coroutine keywords, but we failed to build 1056 // the promise type. 1057 if (!Fn->CoroutinePromise) 1058 return FD->setInvalidDecl(); 1059 1060 if (isa<CoroutineBodyStmt>(Body)) { 1061 // Nothing todo. the body is already a transformed coroutine body statement. 1062 return; 1063 } 1064 1065 // Coroutines [stmt.return]p1: 1066 // A return statement shall not appear in a coroutine. 1067 if (Fn->FirstReturnLoc.isValid()) { 1068 assert(Fn->FirstCoroutineStmtLoc.isValid() && 1069 "first coroutine location not set"); 1070 Diag(Fn->FirstReturnLoc, diag::err_return_in_coroutine); 1071 Diag(Fn->FirstCoroutineStmtLoc, diag::note_declared_coroutine_here) 1072 << Fn->getFirstCoroutineStmtKeyword(); 1073 } 1074 CoroutineStmtBuilder Builder(*this, *FD, *Fn, Body); 1075 if (Builder.isInvalid() || !Builder.buildStatements()) 1076 return FD->setInvalidDecl(); 1077 1078 // Build body for the coroutine wrapper statement. 1079 Body = CoroutineBodyStmt::Create(Context, Builder); 1080 } 1081 1082 CoroutineStmtBuilder::CoroutineStmtBuilder(Sema &S, FunctionDecl &FD, 1083 sema::FunctionScopeInfo &Fn, 1084 Stmt *Body) 1085 : S(S), FD(FD), Fn(Fn), Loc(FD.getLocation()), 1086 IsPromiseDependentType( 1087 !Fn.CoroutinePromise || 1088 Fn.CoroutinePromise->getType()->isDependentType()) { 1089 this->Body = Body; 1090 1091 for (auto KV : Fn.CoroutineParameterMoves) 1092 this->ParamMovesVector.push_back(KV.second); 1093 this->ParamMoves = this->ParamMovesVector; 1094 1095 if (!IsPromiseDependentType) { 1096 PromiseRecordDecl = Fn.CoroutinePromise->getType()->getAsCXXRecordDecl(); 1097 assert(PromiseRecordDecl && "Type should have already been checked"); 1098 } 1099 this->IsValid = makePromiseStmt() && makeInitialAndFinalSuspend(); 1100 } 1101 1102 bool CoroutineStmtBuilder::buildStatements() { 1103 assert(this->IsValid && "coroutine already invalid"); 1104 this->IsValid = makeReturnObject(); 1105 if (this->IsValid && !IsPromiseDependentType) 1106 buildDependentStatements(); 1107 return this->IsValid; 1108 } 1109 1110 bool CoroutineStmtBuilder::buildDependentStatements() { 1111 assert(this->IsValid && "coroutine already invalid"); 1112 assert(!this->IsPromiseDependentType && 1113 "coroutine cannot have a dependent promise type"); 1114 this->IsValid = makeOnException() && makeOnFallthrough() && 1115 makeGroDeclAndReturnStmt() && makeReturnOnAllocFailure() && 1116 makeNewAndDeleteExpr(); 1117 return this->IsValid; 1118 } 1119 1120 bool CoroutineStmtBuilder::makePromiseStmt() { 1121 // Form a declaration statement for the promise declaration, so that AST 1122 // visitors can more easily find it. 1123 StmtResult PromiseStmt = 1124 S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(Fn.CoroutinePromise), Loc, Loc); 1125 if (PromiseStmt.isInvalid()) 1126 return false; 1127 1128 this->Promise = PromiseStmt.get(); 1129 return true; 1130 } 1131 1132 bool CoroutineStmtBuilder::makeInitialAndFinalSuspend() { 1133 if (Fn.hasInvalidCoroutineSuspends()) 1134 return false; 1135 this->InitialSuspend = cast<Expr>(Fn.CoroutineSuspends.first); 1136 this->FinalSuspend = cast<Expr>(Fn.CoroutineSuspends.second); 1137 return true; 1138 } 1139 1140 static bool diagReturnOnAllocFailure(Sema &S, Expr *E, 1141 CXXRecordDecl *PromiseRecordDecl, 1142 FunctionScopeInfo &Fn) { 1143 auto Loc = E->getExprLoc(); 1144 if (auto *DeclRef = dyn_cast_or_null<DeclRefExpr>(E)) { 1145 auto *Decl = DeclRef->getDecl(); 1146 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Decl)) { 1147 if (Method->isStatic()) 1148 return true; 1149 else 1150 Loc = Decl->getLocation(); 1151 } 1152 } 1153 1154 S.Diag( 1155 Loc, 1156 diag::err_coroutine_promise_get_return_object_on_allocation_failure) 1157 << PromiseRecordDecl; 1158 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here) 1159 << Fn.getFirstCoroutineStmtKeyword(); 1160 return false; 1161 } 1162 1163 bool CoroutineStmtBuilder::makeReturnOnAllocFailure() { 1164 assert(!IsPromiseDependentType && 1165 "cannot make statement while the promise type is dependent"); 1166 1167 // [dcl.fct.def.coroutine]/8 1168 // The unqualified-id get_return_object_on_allocation_failure is looked up in 1169 // the scope of class P by class member access lookup (3.4.5). ... 1170 // If an allocation function returns nullptr, ... the coroutine return value 1171 // is obtained by a call to ... get_return_object_on_allocation_failure(). 1172 1173 DeclarationName DN = 1174 S.PP.getIdentifierInfo("get_return_object_on_allocation_failure"); 1175 LookupResult Found(S, DN, Loc, Sema::LookupMemberName); 1176 if (!S.LookupQualifiedName(Found, PromiseRecordDecl)) 1177 return true; 1178 1179 CXXScopeSpec SS; 1180 ExprResult DeclNameExpr = 1181 S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false); 1182 if (DeclNameExpr.isInvalid()) 1183 return false; 1184 1185 if (!diagReturnOnAllocFailure(S, DeclNameExpr.get(), PromiseRecordDecl, Fn)) 1186 return false; 1187 1188 ExprResult ReturnObjectOnAllocationFailure = 1189 S.BuildCallExpr(nullptr, DeclNameExpr.get(), Loc, {}, Loc); 1190 if (ReturnObjectOnAllocationFailure.isInvalid()) 1191 return false; 1192 1193 StmtResult ReturnStmt = 1194 S.BuildReturnStmt(Loc, ReturnObjectOnAllocationFailure.get()); 1195 if (ReturnStmt.isInvalid()) { 1196 S.Diag(Found.getFoundDecl()->getLocation(), diag::note_member_declared_here) 1197 << DN; 1198 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here) 1199 << Fn.getFirstCoroutineStmtKeyword(); 1200 return false; 1201 } 1202 1203 this->ReturnStmtOnAllocFailure = ReturnStmt.get(); 1204 return true; 1205 } 1206 1207 bool CoroutineStmtBuilder::makeNewAndDeleteExpr() { 1208 // Form and check allocation and deallocation calls. 1209 assert(!IsPromiseDependentType && 1210 "cannot make statement while the promise type is dependent"); 1211 QualType PromiseType = Fn.CoroutinePromise->getType(); 1212 1213 if (S.RequireCompleteType(Loc, PromiseType, diag::err_incomplete_type)) 1214 return false; 1215 1216 const bool RequiresNoThrowAlloc = ReturnStmtOnAllocFailure != nullptr; 1217 1218 // [dcl.fct.def.coroutine]/7 1219 // Lookup allocation functions using a parameter list composed of the 1220 // requested size of the coroutine state being allocated, followed by 1221 // the coroutine function's arguments. If a matching allocation function 1222 // exists, use it. Otherwise, use an allocation function that just takes 1223 // the requested size. 1224 1225 FunctionDecl *OperatorNew = nullptr; 1226 FunctionDecl *OperatorDelete = nullptr; 1227 FunctionDecl *UnusedResult = nullptr; 1228 bool PassAlignment = false; 1229 SmallVector<Expr *, 1> PlacementArgs; 1230 1231 // [dcl.fct.def.coroutine]/7 1232 // "The allocation function’s name is looked up in the scope of P. 1233 // [...] If the lookup finds an allocation function in the scope of P, 1234 // overload resolution is performed on a function call created by assembling 1235 // an argument list. The first argument is the amount of space requested, 1236 // and has type std::size_t. The lvalues p1 ... pn are the succeeding 1237 // arguments." 1238 // 1239 // ...where "p1 ... pn" are defined earlier as: 1240 // 1241 // [dcl.fct.def.coroutine]/3 1242 // "For a coroutine f that is a non-static member function, let P1 denote the 1243 // type of the implicit object parameter (13.3.1) and P2 ... Pn be the types 1244 // of the function parameters; otherwise let P1 ... Pn be the types of the 1245 // function parameters. Let p1 ... pn be lvalues denoting those objects." 1246 if (auto *MD = dyn_cast<CXXMethodDecl>(&FD)) { 1247 if (MD->isInstance() && !isLambdaCallOperator(MD)) { 1248 ExprResult ThisExpr = S.ActOnCXXThis(Loc); 1249 if (ThisExpr.isInvalid()) 1250 return false; 1251 ThisExpr = S.CreateBuiltinUnaryOp(Loc, UO_Deref, ThisExpr.get()); 1252 if (ThisExpr.isInvalid()) 1253 return false; 1254 PlacementArgs.push_back(ThisExpr.get()); 1255 } 1256 } 1257 for (auto *PD : FD.parameters()) { 1258 if (PD->getType()->isDependentType()) 1259 continue; 1260 1261 // Build a reference to the parameter. 1262 auto PDLoc = PD->getLocation(); 1263 ExprResult PDRefExpr = 1264 S.BuildDeclRefExpr(PD, PD->getOriginalType().getNonReferenceType(), 1265 ExprValueKind::VK_LValue, PDLoc); 1266 if (PDRefExpr.isInvalid()) 1267 return false; 1268 1269 PlacementArgs.push_back(PDRefExpr.get()); 1270 } 1271 S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Class, 1272 /*DeleteScope*/ Sema::AFS_Both, PromiseType, 1273 /*isArray*/ false, PassAlignment, PlacementArgs, 1274 OperatorNew, UnusedResult, /*Diagnose*/ false); 1275 1276 // [dcl.fct.def.coroutine]/7 1277 // "If no matching function is found, overload resolution is performed again 1278 // on a function call created by passing just the amount of space required as 1279 // an argument of type std::size_t." 1280 if (!OperatorNew && !PlacementArgs.empty()) { 1281 PlacementArgs.clear(); 1282 S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Class, 1283 /*DeleteScope*/ Sema::AFS_Both, PromiseType, 1284 /*isArray*/ false, PassAlignment, PlacementArgs, 1285 OperatorNew, UnusedResult, /*Diagnose*/ false); 1286 } 1287 1288 // [dcl.fct.def.coroutine]/7 1289 // "The allocation function’s name is looked up in the scope of P. If this 1290 // lookup fails, the allocation function’s name is looked up in the global 1291 // scope." 1292 if (!OperatorNew) { 1293 S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Global, 1294 /*DeleteScope*/ Sema::AFS_Both, PromiseType, 1295 /*isArray*/ false, PassAlignment, PlacementArgs, 1296 OperatorNew, UnusedResult); 1297 } 1298 1299 bool IsGlobalOverload = 1300 OperatorNew && !isa<CXXRecordDecl>(OperatorNew->getDeclContext()); 1301 // If we didn't find a class-local new declaration and non-throwing new 1302 // was is required then we need to lookup the non-throwing global operator 1303 // instead. 1304 if (RequiresNoThrowAlloc && (!OperatorNew || IsGlobalOverload)) { 1305 auto *StdNoThrow = buildStdNoThrowDeclRef(S, Loc); 1306 if (!StdNoThrow) 1307 return false; 1308 PlacementArgs = {StdNoThrow}; 1309 OperatorNew = nullptr; 1310 S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Both, 1311 /*DeleteScope*/ Sema::AFS_Both, PromiseType, 1312 /*isArray*/ false, PassAlignment, PlacementArgs, 1313 OperatorNew, UnusedResult); 1314 } 1315 1316 if (!OperatorNew) 1317 return false; 1318 1319 if (RequiresNoThrowAlloc) { 1320 const auto *FT = OperatorNew->getType()->castAs<FunctionProtoType>(); 1321 if (!FT->isNothrow(/*ResultIfDependent*/ false)) { 1322 S.Diag(OperatorNew->getLocation(), 1323 diag::err_coroutine_promise_new_requires_nothrow) 1324 << OperatorNew; 1325 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required) 1326 << OperatorNew; 1327 return false; 1328 } 1329 } 1330 1331 if ((OperatorDelete = findDeleteForPromise(S, Loc, PromiseType)) == nullptr) 1332 return false; 1333 1334 Expr *FramePtr = 1335 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_frame, {}); 1336 1337 Expr *FrameSize = 1338 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_size, {}); 1339 1340 // Make new call. 1341 1342 ExprResult NewRef = 1343 S.BuildDeclRefExpr(OperatorNew, OperatorNew->getType(), VK_LValue, Loc); 1344 if (NewRef.isInvalid()) 1345 return false; 1346 1347 SmallVector<Expr *, 2> NewArgs(1, FrameSize); 1348 for (auto Arg : PlacementArgs) 1349 NewArgs.push_back(Arg); 1350 1351 ExprResult NewExpr = 1352 S.BuildCallExpr(S.getCurScope(), NewRef.get(), Loc, NewArgs, Loc); 1353 NewExpr = S.ActOnFinishFullExpr(NewExpr.get(), /*DiscardedValue*/ false); 1354 if (NewExpr.isInvalid()) 1355 return false; 1356 1357 // Make delete call. 1358 1359 QualType OpDeleteQualType = OperatorDelete->getType(); 1360 1361 ExprResult DeleteRef = 1362 S.BuildDeclRefExpr(OperatorDelete, OpDeleteQualType, VK_LValue, Loc); 1363 if (DeleteRef.isInvalid()) 1364 return false; 1365 1366 Expr *CoroFree = 1367 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_free, {FramePtr}); 1368 1369 SmallVector<Expr *, 2> DeleteArgs{CoroFree}; 1370 1371 // Check if we need to pass the size. 1372 const auto *OpDeleteType = 1373 OpDeleteQualType.getTypePtr()->castAs<FunctionProtoType>(); 1374 if (OpDeleteType->getNumParams() > 1) 1375 DeleteArgs.push_back(FrameSize); 1376 1377 ExprResult DeleteExpr = 1378 S.BuildCallExpr(S.getCurScope(), DeleteRef.get(), Loc, DeleteArgs, Loc); 1379 DeleteExpr = 1380 S.ActOnFinishFullExpr(DeleteExpr.get(), /*DiscardedValue*/ false); 1381 if (DeleteExpr.isInvalid()) 1382 return false; 1383 1384 this->Allocate = NewExpr.get(); 1385 this->Deallocate = DeleteExpr.get(); 1386 1387 return true; 1388 } 1389 1390 bool CoroutineStmtBuilder::makeOnFallthrough() { 1391 assert(!IsPromiseDependentType && 1392 "cannot make statement while the promise type is dependent"); 1393 1394 // [dcl.fct.def.coroutine]/4 1395 // The unqualified-ids 'return_void' and 'return_value' are looked up in 1396 // the scope of class P. If both are found, the program is ill-formed. 1397 bool HasRVoid, HasRValue; 1398 LookupResult LRVoid = 1399 lookupMember(S, "return_void", PromiseRecordDecl, Loc, HasRVoid); 1400 LookupResult LRValue = 1401 lookupMember(S, "return_value", PromiseRecordDecl, Loc, HasRValue); 1402 1403 StmtResult Fallthrough; 1404 if (HasRVoid && HasRValue) { 1405 // FIXME Improve this diagnostic 1406 S.Diag(FD.getLocation(), 1407 diag::err_coroutine_promise_incompatible_return_functions) 1408 << PromiseRecordDecl; 1409 S.Diag(LRVoid.getRepresentativeDecl()->getLocation(), 1410 diag::note_member_first_declared_here) 1411 << LRVoid.getLookupName(); 1412 S.Diag(LRValue.getRepresentativeDecl()->getLocation(), 1413 diag::note_member_first_declared_here) 1414 << LRValue.getLookupName(); 1415 return false; 1416 } else if (!HasRVoid && !HasRValue) { 1417 // FIXME: The PDTS currently specifies this case as UB, not ill-formed. 1418 // However we still diagnose this as an error since until the PDTS is fixed. 1419 S.Diag(FD.getLocation(), 1420 diag::err_coroutine_promise_requires_return_function) 1421 << PromiseRecordDecl; 1422 S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here) 1423 << PromiseRecordDecl; 1424 return false; 1425 } else if (HasRVoid) { 1426 // If the unqualified-id return_void is found, flowing off the end of a 1427 // coroutine is equivalent to a co_return with no operand. Otherwise, 1428 // flowing off the end of a coroutine results in undefined behavior. 1429 Fallthrough = S.BuildCoreturnStmt(FD.getLocation(), nullptr, 1430 /*IsImplicit*/false); 1431 Fallthrough = S.ActOnFinishFullStmt(Fallthrough.get()); 1432 if (Fallthrough.isInvalid()) 1433 return false; 1434 } 1435 1436 this->OnFallthrough = Fallthrough.get(); 1437 return true; 1438 } 1439 1440 bool CoroutineStmtBuilder::makeOnException() { 1441 // Try to form 'p.unhandled_exception();' 1442 assert(!IsPromiseDependentType && 1443 "cannot make statement while the promise type is dependent"); 1444 1445 const bool RequireUnhandledException = S.getLangOpts().CXXExceptions; 1446 1447 if (!lookupMember(S, "unhandled_exception", PromiseRecordDecl, Loc)) { 1448 auto DiagID = 1449 RequireUnhandledException 1450 ? diag::err_coroutine_promise_unhandled_exception_required 1451 : diag:: 1452 warn_coroutine_promise_unhandled_exception_required_with_exceptions; 1453 S.Diag(Loc, DiagID) << PromiseRecordDecl; 1454 S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here) 1455 << PromiseRecordDecl; 1456 return !RequireUnhandledException; 1457 } 1458 1459 // If exceptions are disabled, don't try to build OnException. 1460 if (!S.getLangOpts().CXXExceptions) 1461 return true; 1462 1463 ExprResult UnhandledException = buildPromiseCall(S, Fn.CoroutinePromise, Loc, 1464 "unhandled_exception", None); 1465 UnhandledException = S.ActOnFinishFullExpr(UnhandledException.get(), Loc, 1466 /*DiscardedValue*/ false); 1467 if (UnhandledException.isInvalid()) 1468 return false; 1469 1470 // Since the body of the coroutine will be wrapped in try-catch, it will 1471 // be incompatible with SEH __try if present in a function. 1472 if (!S.getLangOpts().Borland && Fn.FirstSEHTryLoc.isValid()) { 1473 S.Diag(Fn.FirstSEHTryLoc, diag::err_seh_in_a_coroutine_with_cxx_exceptions); 1474 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here) 1475 << Fn.getFirstCoroutineStmtKeyword(); 1476 return false; 1477 } 1478 1479 this->OnException = UnhandledException.get(); 1480 return true; 1481 } 1482 1483 bool CoroutineStmtBuilder::makeReturnObject() { 1484 // Build implicit 'p.get_return_object()' expression and form initialization 1485 // of return type from it. 1486 ExprResult ReturnObject = 1487 buildPromiseCall(S, Fn.CoroutinePromise, Loc, "get_return_object", None); 1488 if (ReturnObject.isInvalid()) 1489 return false; 1490 1491 this->ReturnValue = ReturnObject.get(); 1492 return true; 1493 } 1494 1495 static void noteMemberDeclaredHere(Sema &S, Expr *E, FunctionScopeInfo &Fn) { 1496 if (auto *MbrRef = dyn_cast<CXXMemberCallExpr>(E)) { 1497 auto *MethodDecl = MbrRef->getMethodDecl(); 1498 S.Diag(MethodDecl->getLocation(), diag::note_member_declared_here) 1499 << MethodDecl; 1500 } 1501 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here) 1502 << Fn.getFirstCoroutineStmtKeyword(); 1503 } 1504 1505 bool CoroutineStmtBuilder::makeGroDeclAndReturnStmt() { 1506 assert(!IsPromiseDependentType && 1507 "cannot make statement while the promise type is dependent"); 1508 assert(this->ReturnValue && "ReturnValue must be already formed"); 1509 1510 QualType const GroType = this->ReturnValue->getType(); 1511 assert(!GroType->isDependentType() && 1512 "get_return_object type must no longer be dependent"); 1513 1514 QualType const FnRetType = FD.getReturnType(); 1515 assert(!FnRetType->isDependentType() && 1516 "get_return_object type must no longer be dependent"); 1517 1518 if (FnRetType->isVoidType()) { 1519 ExprResult Res = 1520 S.ActOnFinishFullExpr(this->ReturnValue, Loc, /*DiscardedValue*/ false); 1521 if (Res.isInvalid()) 1522 return false; 1523 1524 this->ResultDecl = Res.get(); 1525 return true; 1526 } 1527 1528 if (GroType->isVoidType()) { 1529 // Trigger a nice error message. 1530 InitializedEntity Entity = 1531 InitializedEntity::InitializeResult(Loc, FnRetType, false); 1532 S.PerformMoveOrCopyInitialization(Entity, nullptr, FnRetType, ReturnValue); 1533 noteMemberDeclaredHere(S, ReturnValue, Fn); 1534 return false; 1535 } 1536 1537 auto *GroDecl = VarDecl::Create( 1538 S.Context, &FD, FD.getLocation(), FD.getLocation(), 1539 &S.PP.getIdentifierTable().get("__coro_gro"), GroType, 1540 S.Context.getTrivialTypeSourceInfo(GroType, Loc), SC_None); 1541 1542 S.CheckVariableDeclarationType(GroDecl); 1543 if (GroDecl->isInvalidDecl()) 1544 return false; 1545 1546 InitializedEntity Entity = InitializedEntity::InitializeVariable(GroDecl); 1547 ExprResult Res = S.PerformMoveOrCopyInitialization(Entity, nullptr, GroType, 1548 this->ReturnValue); 1549 if (Res.isInvalid()) 1550 return false; 1551 1552 Res = S.ActOnFinishFullExpr(Res.get(), /*DiscardedValue*/ false); 1553 if (Res.isInvalid()) 1554 return false; 1555 1556 S.AddInitializerToDecl(GroDecl, Res.get(), 1557 /*DirectInit=*/false); 1558 1559 S.FinalizeDeclaration(GroDecl); 1560 1561 // Form a declaration statement for the return declaration, so that AST 1562 // visitors can more easily find it. 1563 StmtResult GroDeclStmt = 1564 S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(GroDecl), Loc, Loc); 1565 if (GroDeclStmt.isInvalid()) 1566 return false; 1567 1568 this->ResultDecl = GroDeclStmt.get(); 1569 1570 ExprResult declRef = S.BuildDeclRefExpr(GroDecl, GroType, VK_LValue, Loc); 1571 if (declRef.isInvalid()) 1572 return false; 1573 1574 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, declRef.get()); 1575 if (ReturnStmt.isInvalid()) { 1576 noteMemberDeclaredHere(S, ReturnValue, Fn); 1577 return false; 1578 } 1579 if (cast<clang::ReturnStmt>(ReturnStmt.get())->getNRVOCandidate() == GroDecl) 1580 GroDecl->setNRVOVariable(true); 1581 1582 this->ReturnStmt = ReturnStmt.get(); 1583 return true; 1584 } 1585 1586 // Create a static_cast\<T&&>(expr). 1587 static Expr *castForMoving(Sema &S, Expr *E, QualType T = QualType()) { 1588 if (T.isNull()) 1589 T = E->getType(); 1590 QualType TargetType = S.BuildReferenceType( 1591 T, /*SpelledAsLValue*/ false, SourceLocation(), DeclarationName()); 1592 SourceLocation ExprLoc = E->getBeginLoc(); 1593 TypeSourceInfo *TargetLoc = 1594 S.Context.getTrivialTypeSourceInfo(TargetType, ExprLoc); 1595 1596 return S 1597 .BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 1598 SourceRange(ExprLoc, ExprLoc), E->getSourceRange()) 1599 .get(); 1600 } 1601 1602 /// Build a variable declaration for move parameter. 1603 static VarDecl *buildVarDecl(Sema &S, SourceLocation Loc, QualType Type, 1604 IdentifierInfo *II) { 1605 TypeSourceInfo *TInfo = S.Context.getTrivialTypeSourceInfo(Type, Loc); 1606 VarDecl *Decl = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, II, Type, 1607 TInfo, SC_None); 1608 Decl->setImplicit(); 1609 return Decl; 1610 } 1611 1612 // Build statements that move coroutine function parameters to the coroutine 1613 // frame, and store them on the function scope info. 1614 bool Sema::buildCoroutineParameterMoves(SourceLocation Loc) { 1615 assert(isa<FunctionDecl>(CurContext) && "not in a function scope"); 1616 auto *FD = cast<FunctionDecl>(CurContext); 1617 1618 auto *ScopeInfo = getCurFunction(); 1619 if (!ScopeInfo->CoroutineParameterMoves.empty()) 1620 return false; 1621 1622 for (auto *PD : FD->parameters()) { 1623 if (PD->getType()->isDependentType()) 1624 continue; 1625 1626 ExprResult PDRefExpr = 1627 BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(), 1628 ExprValueKind::VK_LValue, Loc); // FIXME: scope? 1629 if (PDRefExpr.isInvalid()) 1630 return false; 1631 1632 Expr *CExpr = nullptr; 1633 if (PD->getType()->getAsCXXRecordDecl() || 1634 PD->getType()->isRValueReferenceType()) 1635 CExpr = castForMoving(*this, PDRefExpr.get()); 1636 else 1637 CExpr = PDRefExpr.get(); 1638 1639 auto D = buildVarDecl(*this, Loc, PD->getType(), PD->getIdentifier()); 1640 AddInitializerToDecl(D, CExpr, /*DirectInit=*/true); 1641 1642 // Convert decl to a statement. 1643 StmtResult Stmt = ActOnDeclStmt(ConvertDeclToDeclGroup(D), Loc, Loc); 1644 if (Stmt.isInvalid()) 1645 return false; 1646 1647 ScopeInfo->CoroutineParameterMoves.insert(std::make_pair(PD, Stmt.get())); 1648 } 1649 return true; 1650 } 1651 1652 StmtResult Sema::BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) { 1653 CoroutineBodyStmt *Res = CoroutineBodyStmt::Create(Context, Args); 1654 if (!Res) 1655 return StmtError(); 1656 return Res; 1657 } 1658 1659 ClassTemplateDecl *Sema::lookupCoroutineTraits(SourceLocation KwLoc, 1660 SourceLocation FuncLoc) { 1661 if (!StdCoroutineTraitsCache) { 1662 if (auto StdExp = lookupStdExperimentalNamespace()) { 1663 LookupResult Result(*this, 1664 &PP.getIdentifierTable().get("coroutine_traits"), 1665 FuncLoc, LookupOrdinaryName); 1666 if (!LookupQualifiedName(Result, StdExp)) { 1667 Diag(KwLoc, diag::err_implied_coroutine_type_not_found) 1668 << "std::experimental::coroutine_traits"; 1669 return nullptr; 1670 } 1671 if (!(StdCoroutineTraitsCache = 1672 Result.getAsSingle<ClassTemplateDecl>())) { 1673 Result.suppressDiagnostics(); 1674 NamedDecl *Found = *Result.begin(); 1675 Diag(Found->getLocation(), diag::err_malformed_std_coroutine_traits); 1676 return nullptr; 1677 } 1678 } 1679 } 1680 return StdCoroutineTraitsCache; 1681 } 1682