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