1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===// 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++ declarations. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/AST/ASTConsumer.h" 14 #include "clang/AST/ASTContext.h" 15 #include "clang/AST/ASTLambda.h" 16 #include "clang/AST/ASTMutationListener.h" 17 #include "clang/AST/CXXInheritance.h" 18 #include "clang/AST/CharUnits.h" 19 #include "clang/AST/ComparisonCategories.h" 20 #include "clang/AST/EvaluatedExprVisitor.h" 21 #include "clang/AST/ExprCXX.h" 22 #include "clang/AST/RecordLayout.h" 23 #include "clang/AST/RecursiveASTVisitor.h" 24 #include "clang/AST/StmtVisitor.h" 25 #include "clang/AST/TypeLoc.h" 26 #include "clang/AST/TypeOrdering.h" 27 #include "clang/Basic/AttributeCommonInfo.h" 28 #include "clang/Basic/PartialDiagnostic.h" 29 #include "clang/Basic/Specifiers.h" 30 #include "clang/Basic/TargetInfo.h" 31 #include "clang/Lex/LiteralSupport.h" 32 #include "clang/Lex/Preprocessor.h" 33 #include "clang/Sema/CXXFieldCollector.h" 34 #include "clang/Sema/DeclSpec.h" 35 #include "clang/Sema/Initialization.h" 36 #include "clang/Sema/Lookup.h" 37 #include "clang/Sema/ParsedTemplate.h" 38 #include "clang/Sema/Scope.h" 39 #include "clang/Sema/ScopeInfo.h" 40 #include "clang/Sema/SemaInternal.h" 41 #include "clang/Sema/Template.h" 42 #include "llvm/ADT/ScopeExit.h" 43 #include "llvm/ADT/SmallString.h" 44 #include "llvm/ADT/STLExtras.h" 45 #include "llvm/ADT/StringExtras.h" 46 #include <map> 47 #include <set> 48 49 using namespace clang; 50 51 //===----------------------------------------------------------------------===// 52 // CheckDefaultArgumentVisitor 53 //===----------------------------------------------------------------------===// 54 55 namespace { 56 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 57 /// the default argument of a parameter to determine whether it 58 /// contains any ill-formed subexpressions. For example, this will 59 /// diagnose the use of local variables or parameters within the 60 /// default argument expression. 61 class CheckDefaultArgumentVisitor 62 : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> { 63 Sema &S; 64 const Expr *DefaultArg; 65 66 public: 67 CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg) 68 : S(S), DefaultArg(DefaultArg) {} 69 70 bool VisitExpr(const Expr *Node); 71 bool VisitDeclRefExpr(const DeclRefExpr *DRE); 72 bool VisitCXXThisExpr(const CXXThisExpr *ThisE); 73 bool VisitLambdaExpr(const LambdaExpr *Lambda); 74 bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE); 75 }; 76 77 /// VisitExpr - Visit all of the children of this expression. 78 bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) { 79 bool IsInvalid = false; 80 for (const Stmt *SubStmt : Node->children()) 81 IsInvalid |= Visit(SubStmt); 82 return IsInvalid; 83 } 84 85 /// VisitDeclRefExpr - Visit a reference to a declaration, to 86 /// determine whether this declaration can be used in the default 87 /// argument expression. 88 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) { 89 const NamedDecl *Decl = DRE->getDecl(); 90 if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) { 91 // C++ [dcl.fct.default]p9: 92 // [...] parameters of a function shall not be used in default 93 // argument expressions, even if they are not evaluated. [...] 94 // 95 // C++17 [dcl.fct.default]p9 (by CWG 2082): 96 // [...] A parameter shall not appear as a potentially-evaluated 97 // expression in a default argument. [...] 98 // 99 if (DRE->isNonOdrUse() != NOUR_Unevaluated) 100 return S.Diag(DRE->getBeginLoc(), 101 diag::err_param_default_argument_references_param) 102 << Param->getDeclName() << DefaultArg->getSourceRange(); 103 } else if (const auto *VDecl = dyn_cast<VarDecl>(Decl)) { 104 // C++ [dcl.fct.default]p7: 105 // Local variables shall not be used in default argument 106 // expressions. 107 // 108 // C++17 [dcl.fct.default]p7 (by CWG 2082): 109 // A local variable shall not appear as a potentially-evaluated 110 // expression in a default argument. 111 // 112 // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346): 113 // Note: A local variable cannot be odr-used (6.3) in a default argument. 114 // 115 if (VDecl->isLocalVarDecl() && !DRE->isNonOdrUse()) 116 return S.Diag(DRE->getBeginLoc(), 117 diag::err_param_default_argument_references_local) 118 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 119 } 120 121 return false; 122 } 123 124 /// VisitCXXThisExpr - Visit a C++ "this" expression. 125 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) { 126 // C++ [dcl.fct.default]p8: 127 // The keyword this shall not be used in a default argument of a 128 // member function. 129 return S.Diag(ThisE->getBeginLoc(), 130 diag::err_param_default_argument_references_this) 131 << ThisE->getSourceRange(); 132 } 133 134 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr( 135 const PseudoObjectExpr *POE) { 136 bool Invalid = false; 137 for (const Expr *E : POE->semantics()) { 138 // Look through bindings. 139 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) { 140 E = OVE->getSourceExpr(); 141 assert(E && "pseudo-object binding without source expression?"); 142 } 143 144 Invalid |= Visit(E); 145 } 146 return Invalid; 147 } 148 149 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) { 150 // C++11 [expr.lambda.prim]p13: 151 // A lambda-expression appearing in a default argument shall not 152 // implicitly or explicitly capture any entity. 153 if (Lambda->capture_begin() == Lambda->capture_end()) 154 return false; 155 156 return S.Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg); 157 } 158 } // namespace 159 160 void 161 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc, 162 const CXXMethodDecl *Method) { 163 // If we have an MSAny spec already, don't bother. 164 if (!Method || ComputedEST == EST_MSAny) 165 return; 166 167 const FunctionProtoType *Proto 168 = Method->getType()->getAs<FunctionProtoType>(); 169 Proto = Self->ResolveExceptionSpec(CallLoc, Proto); 170 if (!Proto) 171 return; 172 173 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 174 175 // If we have a throw-all spec at this point, ignore the function. 176 if (ComputedEST == EST_None) 177 return; 178 179 if (EST == EST_None && Method->hasAttr<NoThrowAttr>()) 180 EST = EST_BasicNoexcept; 181 182 switch (EST) { 183 case EST_Unparsed: 184 case EST_Uninstantiated: 185 case EST_Unevaluated: 186 llvm_unreachable("should not see unresolved exception specs here"); 187 188 // If this function can throw any exceptions, make a note of that. 189 case EST_MSAny: 190 case EST_None: 191 // FIXME: Whichever we see last of MSAny and None determines our result. 192 // We should make a consistent, order-independent choice here. 193 ClearExceptions(); 194 ComputedEST = EST; 195 return; 196 case EST_NoexceptFalse: 197 ClearExceptions(); 198 ComputedEST = EST_None; 199 return; 200 // FIXME: If the call to this decl is using any of its default arguments, we 201 // need to search them for potentially-throwing calls. 202 // If this function has a basic noexcept, it doesn't affect the outcome. 203 case EST_BasicNoexcept: 204 case EST_NoexceptTrue: 205 case EST_NoThrow: 206 return; 207 // If we're still at noexcept(true) and there's a throw() callee, 208 // change to that specification. 209 case EST_DynamicNone: 210 if (ComputedEST == EST_BasicNoexcept) 211 ComputedEST = EST_DynamicNone; 212 return; 213 case EST_DependentNoexcept: 214 llvm_unreachable( 215 "should not generate implicit declarations for dependent cases"); 216 case EST_Dynamic: 217 break; 218 } 219 assert(EST == EST_Dynamic && "EST case not considered earlier."); 220 assert(ComputedEST != EST_None && 221 "Shouldn't collect exceptions when throw-all is guaranteed."); 222 ComputedEST = EST_Dynamic; 223 // Record the exceptions in this function's exception specification. 224 for (const auto &E : Proto->exceptions()) 225 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second) 226 Exceptions.push_back(E); 227 } 228 229 void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) { 230 if (!S || ComputedEST == EST_MSAny) 231 return; 232 233 // FIXME: 234 // 235 // C++0x [except.spec]p14: 236 // [An] implicit exception-specification specifies the type-id T if and 237 // only if T is allowed by the exception-specification of a function directly 238 // invoked by f's implicit definition; f shall allow all exceptions if any 239 // function it directly invokes allows all exceptions, and f shall allow no 240 // exceptions if every function it directly invokes allows no exceptions. 241 // 242 // Note in particular that if an implicit exception-specification is generated 243 // for a function containing a throw-expression, that specification can still 244 // be noexcept(true). 245 // 246 // Note also that 'directly invoked' is not defined in the standard, and there 247 // is no indication that we should only consider potentially-evaluated calls. 248 // 249 // Ultimately we should implement the intent of the standard: the exception 250 // specification should be the set of exceptions which can be thrown by the 251 // implicit definition. For now, we assume that any non-nothrow expression can 252 // throw any exception. 253 254 if (Self->canThrow(S)) 255 ComputedEST = EST_None; 256 } 257 258 ExprResult Sema::ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 259 SourceLocation EqualLoc) { 260 if (RequireCompleteType(Param->getLocation(), Param->getType(), 261 diag::err_typecheck_decl_incomplete_type)) 262 return true; 263 264 // C++ [dcl.fct.default]p5 265 // A default argument expression is implicitly converted (clause 266 // 4) to the parameter type. The default argument expression has 267 // the same semantic constraints as the initializer expression in 268 // a declaration of a variable of the parameter type, using the 269 // copy-initialization semantics (8.5). 270 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 271 Param); 272 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 273 EqualLoc); 274 InitializationSequence InitSeq(*this, Entity, Kind, Arg); 275 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); 276 if (Result.isInvalid()) 277 return true; 278 Arg = Result.getAs<Expr>(); 279 280 CheckCompletedExpr(Arg, EqualLoc); 281 Arg = MaybeCreateExprWithCleanups(Arg); 282 283 return Arg; 284 } 285 286 void Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 287 SourceLocation EqualLoc) { 288 // Add the default argument to the parameter 289 Param->setDefaultArg(Arg); 290 291 // We have already instantiated this parameter; provide each of the 292 // instantiations with the uninstantiated default argument. 293 UnparsedDefaultArgInstantiationsMap::iterator InstPos 294 = UnparsedDefaultArgInstantiations.find(Param); 295 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 296 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 297 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 298 299 // We're done tracking this parameter's instantiations. 300 UnparsedDefaultArgInstantiations.erase(InstPos); 301 } 302 } 303 304 /// ActOnParamDefaultArgument - Check whether the default argument 305 /// provided for a function parameter is well-formed. If so, attach it 306 /// to the parameter declaration. 307 void 308 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 309 Expr *DefaultArg) { 310 if (!param || !DefaultArg) 311 return; 312 313 ParmVarDecl *Param = cast<ParmVarDecl>(param); 314 UnparsedDefaultArgLocs.erase(Param); 315 316 auto Fail = [&] { 317 Param->setInvalidDecl(); 318 Param->setDefaultArg(new (Context) OpaqueValueExpr( 319 EqualLoc, Param->getType().getNonReferenceType(), VK_PRValue)); 320 }; 321 322 // Default arguments are only permitted in C++ 323 if (!getLangOpts().CPlusPlus) { 324 Diag(EqualLoc, diag::err_param_default_argument) 325 << DefaultArg->getSourceRange(); 326 return Fail(); 327 } 328 329 // Check for unexpanded parameter packs. 330 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 331 return Fail(); 332 } 333 334 // C++11 [dcl.fct.default]p3 335 // A default argument expression [...] shall not be specified for a 336 // parameter pack. 337 if (Param->isParameterPack()) { 338 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack) 339 << DefaultArg->getSourceRange(); 340 // Recover by discarding the default argument. 341 Param->setDefaultArg(nullptr); 342 return; 343 } 344 345 ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc); 346 if (Result.isInvalid()) 347 return Fail(); 348 349 DefaultArg = Result.getAs<Expr>(); 350 351 // Check that the default argument is well-formed 352 CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg); 353 if (DefaultArgChecker.Visit(DefaultArg)) 354 return Fail(); 355 356 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 357 } 358 359 /// ActOnParamUnparsedDefaultArgument - We've seen a default 360 /// argument for a function parameter, but we can't parse it yet 361 /// because we're inside a class definition. Note that this default 362 /// argument will be parsed later. 363 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 364 SourceLocation EqualLoc, 365 SourceLocation ArgLoc) { 366 if (!param) 367 return; 368 369 ParmVarDecl *Param = cast<ParmVarDecl>(param); 370 Param->setUnparsedDefaultArg(); 371 UnparsedDefaultArgLocs[Param] = ArgLoc; 372 } 373 374 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 375 /// the default argument for the parameter param failed. 376 void Sema::ActOnParamDefaultArgumentError(Decl *param, 377 SourceLocation EqualLoc) { 378 if (!param) 379 return; 380 381 ParmVarDecl *Param = cast<ParmVarDecl>(param); 382 Param->setInvalidDecl(); 383 UnparsedDefaultArgLocs.erase(Param); 384 Param->setDefaultArg(new (Context) OpaqueValueExpr( 385 EqualLoc, Param->getType().getNonReferenceType(), VK_PRValue)); 386 } 387 388 /// CheckExtraCXXDefaultArguments - Check for any extra default 389 /// arguments in the declarator, which is not a function declaration 390 /// or definition and therefore is not permitted to have default 391 /// arguments. This routine should be invoked for every declarator 392 /// that is not a function declaration or definition. 393 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 394 // C++ [dcl.fct.default]p3 395 // A default argument expression shall be specified only in the 396 // parameter-declaration-clause of a function declaration or in a 397 // template-parameter (14.1). It shall not be specified for a 398 // parameter pack. If it is specified in a 399 // parameter-declaration-clause, it shall not occur within a 400 // declarator or abstract-declarator of a parameter-declaration. 401 bool MightBeFunction = D.isFunctionDeclarationContext(); 402 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 403 DeclaratorChunk &chunk = D.getTypeObject(i); 404 if (chunk.Kind == DeclaratorChunk::Function) { 405 if (MightBeFunction) { 406 // This is a function declaration. It can have default arguments, but 407 // keep looking in case its return type is a function type with default 408 // arguments. 409 MightBeFunction = false; 410 continue; 411 } 412 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e; 413 ++argIdx) { 414 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param); 415 if (Param->hasUnparsedDefaultArg()) { 416 std::unique_ptr<CachedTokens> Toks = 417 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens); 418 SourceRange SR; 419 if (Toks->size() > 1) 420 SR = SourceRange((*Toks)[1].getLocation(), 421 Toks->back().getLocation()); 422 else 423 SR = UnparsedDefaultArgLocs[Param]; 424 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 425 << SR; 426 } else if (Param->getDefaultArg()) { 427 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 428 << Param->getDefaultArg()->getSourceRange(); 429 Param->setDefaultArg(nullptr); 430 } 431 } 432 } else if (chunk.Kind != DeclaratorChunk::Paren) { 433 MightBeFunction = false; 434 } 435 } 436 } 437 438 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { 439 return llvm::any_of(FD->parameters(), [](ParmVarDecl *P) { 440 return P->hasDefaultArg() && !P->hasInheritedDefaultArg(); 441 }); 442 } 443 444 /// MergeCXXFunctionDecl - Merge two declarations of the same C++ 445 /// function, once we already know that they have the same 446 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an 447 /// error, false otherwise. 448 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 449 Scope *S) { 450 bool Invalid = false; 451 452 // The declaration context corresponding to the scope is the semantic 453 // parent, unless this is a local function declaration, in which case 454 // it is that surrounding function. 455 DeclContext *ScopeDC = New->isLocalExternDecl() 456 ? New->getLexicalDeclContext() 457 : New->getDeclContext(); 458 459 // Find the previous declaration for the purpose of default arguments. 460 FunctionDecl *PrevForDefaultArgs = Old; 461 for (/**/; PrevForDefaultArgs; 462 // Don't bother looking back past the latest decl if this is a local 463 // extern declaration; nothing else could work. 464 PrevForDefaultArgs = New->isLocalExternDecl() 465 ? nullptr 466 : PrevForDefaultArgs->getPreviousDecl()) { 467 // Ignore hidden declarations. 468 if (!LookupResult::isVisible(*this, PrevForDefaultArgs)) 469 continue; 470 471 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) && 472 !New->isCXXClassMember()) { 473 // Ignore default arguments of old decl if they are not in 474 // the same scope and this is not an out-of-line definition of 475 // a member function. 476 continue; 477 } 478 479 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) { 480 // If only one of these is a local function declaration, then they are 481 // declared in different scopes, even though isDeclInScope may think 482 // they're in the same scope. (If both are local, the scope check is 483 // sufficient, and if neither is local, then they are in the same scope.) 484 continue; 485 } 486 487 // We found the right previous declaration. 488 break; 489 } 490 491 // C++ [dcl.fct.default]p4: 492 // For non-template functions, default arguments can be added in 493 // later declarations of a function in the same 494 // scope. Declarations in different scopes have completely 495 // distinct sets of default arguments. That is, declarations in 496 // inner scopes do not acquire default arguments from 497 // declarations in outer scopes, and vice versa. In a given 498 // function declaration, all parameters subsequent to a 499 // parameter with a default argument shall have default 500 // arguments supplied in this or previous declarations. A 501 // default argument shall not be redefined by a later 502 // declaration (not even to the same value). 503 // 504 // C++ [dcl.fct.default]p6: 505 // Except for member functions of class templates, the default arguments 506 // in a member function definition that appears outside of the class 507 // definition are added to the set of default arguments provided by the 508 // member function declaration in the class definition. 509 for (unsigned p = 0, NumParams = PrevForDefaultArgs 510 ? PrevForDefaultArgs->getNumParams() 511 : 0; 512 p < NumParams; ++p) { 513 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p); 514 ParmVarDecl *NewParam = New->getParamDecl(p); 515 516 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false; 517 bool NewParamHasDfl = NewParam->hasDefaultArg(); 518 519 if (OldParamHasDfl && NewParamHasDfl) { 520 unsigned DiagDefaultParamID = 521 diag::err_param_default_argument_redefinition; 522 523 // MSVC accepts that default parameters be redefined for member functions 524 // of template class. The new default parameter's value is ignored. 525 Invalid = true; 526 if (getLangOpts().MicrosoftExt) { 527 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New); 528 if (MD && MD->getParent()->getDescribedClassTemplate()) { 529 // Merge the old default argument into the new parameter. 530 NewParam->setHasInheritedDefaultArg(); 531 if (OldParam->hasUninstantiatedDefaultArg()) 532 NewParam->setUninstantiatedDefaultArg( 533 OldParam->getUninstantiatedDefaultArg()); 534 else 535 NewParam->setDefaultArg(OldParam->getInit()); 536 DiagDefaultParamID = diag::ext_param_default_argument_redefinition; 537 Invalid = false; 538 } 539 } 540 541 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 542 // hint here. Alternatively, we could walk the type-source information 543 // for NewParam to find the last source location in the type... but it 544 // isn't worth the effort right now. This is the kind of test case that 545 // is hard to get right: 546 // int f(int); 547 // void g(int (*fp)(int) = f); 548 // void g(int (*fp)(int) = &f); 549 Diag(NewParam->getLocation(), DiagDefaultParamID) 550 << NewParam->getDefaultArgRange(); 551 552 // Look for the function declaration where the default argument was 553 // actually written, which may be a declaration prior to Old. 554 for (auto Older = PrevForDefaultArgs; 555 OldParam->hasInheritedDefaultArg(); /**/) { 556 Older = Older->getPreviousDecl(); 557 OldParam = Older->getParamDecl(p); 558 } 559 560 Diag(OldParam->getLocation(), diag::note_previous_definition) 561 << OldParam->getDefaultArgRange(); 562 } else if (OldParamHasDfl) { 563 // Merge the old default argument into the new parameter unless the new 564 // function is a friend declaration in a template class. In the latter 565 // case the default arguments will be inherited when the friend 566 // declaration will be instantiated. 567 if (New->getFriendObjectKind() == Decl::FOK_None || 568 !New->getLexicalDeclContext()->isDependentContext()) { 569 // It's important to use getInit() here; getDefaultArg() 570 // strips off any top-level ExprWithCleanups. 571 NewParam->setHasInheritedDefaultArg(); 572 if (OldParam->hasUnparsedDefaultArg()) 573 NewParam->setUnparsedDefaultArg(); 574 else if (OldParam->hasUninstantiatedDefaultArg()) 575 NewParam->setUninstantiatedDefaultArg( 576 OldParam->getUninstantiatedDefaultArg()); 577 else 578 NewParam->setDefaultArg(OldParam->getInit()); 579 } 580 } else if (NewParamHasDfl) { 581 if (New->getDescribedFunctionTemplate()) { 582 // Paragraph 4, quoted above, only applies to non-template functions. 583 Diag(NewParam->getLocation(), 584 diag::err_param_default_argument_template_redecl) 585 << NewParam->getDefaultArgRange(); 586 Diag(PrevForDefaultArgs->getLocation(), 587 diag::note_template_prev_declaration) 588 << false; 589 } else if (New->getTemplateSpecializationKind() 590 != TSK_ImplicitInstantiation && 591 New->getTemplateSpecializationKind() != TSK_Undeclared) { 592 // C++ [temp.expr.spec]p21: 593 // Default function arguments shall not be specified in a declaration 594 // or a definition for one of the following explicit specializations: 595 // - the explicit specialization of a function template; 596 // - the explicit specialization of a member function template; 597 // - the explicit specialization of a member function of a class 598 // template where the class template specialization to which the 599 // member function specialization belongs is implicitly 600 // instantiated. 601 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 602 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 603 << New->getDeclName() 604 << NewParam->getDefaultArgRange(); 605 } else if (New->getDeclContext()->isDependentContext()) { 606 // C++ [dcl.fct.default]p6 (DR217): 607 // Default arguments for a member function of a class template shall 608 // be specified on the initial declaration of the member function 609 // within the class template. 610 // 611 // Reading the tea leaves a bit in DR217 and its reference to DR205 612 // leads me to the conclusion that one cannot add default function 613 // arguments for an out-of-line definition of a member function of a 614 // dependent type. 615 int WhichKind = 2; 616 if (CXXRecordDecl *Record 617 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 618 if (Record->getDescribedClassTemplate()) 619 WhichKind = 0; 620 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 621 WhichKind = 1; 622 else 623 WhichKind = 2; 624 } 625 626 Diag(NewParam->getLocation(), 627 diag::err_param_default_argument_member_template_redecl) 628 << WhichKind 629 << NewParam->getDefaultArgRange(); 630 } 631 } 632 } 633 634 // DR1344: If a default argument is added outside a class definition and that 635 // default argument makes the function a special member function, the program 636 // is ill-formed. This can only happen for constructors. 637 if (isa<CXXConstructorDecl>(New) && 638 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 639 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 640 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 641 if (NewSM != OldSM) { 642 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 643 assert(NewParam->hasDefaultArg()); 644 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 645 << NewParam->getDefaultArgRange() << NewSM; 646 Diag(Old->getLocation(), diag::note_previous_declaration); 647 } 648 } 649 650 const FunctionDecl *Def; 651 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 652 // template has a constexpr specifier then all its declarations shall 653 // contain the constexpr specifier. 654 if (New->getConstexprKind() != Old->getConstexprKind()) { 655 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 656 << New << static_cast<int>(New->getConstexprKind()) 657 << static_cast<int>(Old->getConstexprKind()); 658 Diag(Old->getLocation(), diag::note_previous_declaration); 659 Invalid = true; 660 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() && 661 Old->isDefined(Def) && 662 // If a friend function is inlined but does not have 'inline' 663 // specifier, it is a definition. Do not report attribute conflict 664 // in this case, redefinition will be diagnosed later. 665 (New->isInlineSpecified() || 666 New->getFriendObjectKind() == Decl::FOK_None)) { 667 // C++11 [dcl.fcn.spec]p4: 668 // If the definition of a function appears in a translation unit before its 669 // first declaration as inline, the program is ill-formed. 670 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 671 Diag(Def->getLocation(), diag::note_previous_definition); 672 Invalid = true; 673 } 674 675 // C++17 [temp.deduct.guide]p3: 676 // Two deduction guide declarations in the same translation unit 677 // for the same class template shall not have equivalent 678 // parameter-declaration-clauses. 679 if (isa<CXXDeductionGuideDecl>(New) && 680 !New->isFunctionTemplateSpecialization() && isVisible(Old)) { 681 Diag(New->getLocation(), diag::err_deduction_guide_redeclared); 682 Diag(Old->getLocation(), diag::note_previous_declaration); 683 } 684 685 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 686 // argument expression, that declaration shall be a definition and shall be 687 // the only declaration of the function or function template in the 688 // translation unit. 689 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 690 functionDeclHasDefaultArgument(Old)) { 691 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 692 Diag(Old->getLocation(), diag::note_previous_declaration); 693 Invalid = true; 694 } 695 696 // C++11 [temp.friend]p4 (DR329): 697 // When a function is defined in a friend function declaration in a class 698 // template, the function is instantiated when the function is odr-used. 699 // The same restrictions on multiple declarations and definitions that 700 // apply to non-template function declarations and definitions also apply 701 // to these implicit definitions. 702 const FunctionDecl *OldDefinition = nullptr; 703 if (New->isThisDeclarationInstantiatedFromAFriendDefinition() && 704 Old->isDefined(OldDefinition, true)) 705 CheckForFunctionRedefinition(New, OldDefinition); 706 707 return Invalid; 708 } 709 710 NamedDecl * 711 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D, 712 MultiTemplateParamsArg TemplateParamLists) { 713 assert(D.isDecompositionDeclarator()); 714 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 715 716 // The syntax only allows a decomposition declarator as a simple-declaration, 717 // a for-range-declaration, or a condition in Clang, but we parse it in more 718 // cases than that. 719 if (!D.mayHaveDecompositionDeclarator()) { 720 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 721 << Decomp.getSourceRange(); 722 return nullptr; 723 } 724 725 if (!TemplateParamLists.empty()) { 726 // FIXME: There's no rule against this, but there are also no rules that 727 // would actually make it usable, so we reject it for now. 728 Diag(TemplateParamLists.front()->getTemplateLoc(), 729 diag::err_decomp_decl_template); 730 return nullptr; 731 } 732 733 Diag(Decomp.getLSquareLoc(), 734 !getLangOpts().CPlusPlus17 735 ? diag::ext_decomp_decl 736 : D.getContext() == DeclaratorContext::Condition 737 ? diag::ext_decomp_decl_cond 738 : diag::warn_cxx14_compat_decomp_decl) 739 << Decomp.getSourceRange(); 740 741 // The semantic context is always just the current context. 742 DeclContext *const DC = CurContext; 743 744 // C++17 [dcl.dcl]/8: 745 // The decl-specifier-seq shall contain only the type-specifier auto 746 // and cv-qualifiers. 747 // C++2a [dcl.dcl]/8: 748 // If decl-specifier-seq contains any decl-specifier other than static, 749 // thread_local, auto, or cv-qualifiers, the program is ill-formed. 750 auto &DS = D.getDeclSpec(); 751 { 752 SmallVector<StringRef, 8> BadSpecifiers; 753 SmallVector<SourceLocation, 8> BadSpecifierLocs; 754 SmallVector<StringRef, 8> CPlusPlus20Specifiers; 755 SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs; 756 if (auto SCS = DS.getStorageClassSpec()) { 757 if (SCS == DeclSpec::SCS_static) { 758 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS)); 759 CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 760 } else { 761 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS)); 762 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 763 } 764 } 765 if (auto TSCS = DS.getThreadStorageClassSpec()) { 766 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS)); 767 CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc()); 768 } 769 if (DS.hasConstexprSpecifier()) { 770 BadSpecifiers.push_back( 771 DeclSpec::getSpecifierName(DS.getConstexprSpecifier())); 772 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc()); 773 } 774 if (DS.isInlineSpecified()) { 775 BadSpecifiers.push_back("inline"); 776 BadSpecifierLocs.push_back(DS.getInlineSpecLoc()); 777 } 778 if (!BadSpecifiers.empty()) { 779 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec); 780 Err << (int)BadSpecifiers.size() 781 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " "); 782 // Don't add FixItHints to remove the specifiers; we do still respect 783 // them when building the underlying variable. 784 for (auto Loc : BadSpecifierLocs) 785 Err << SourceRange(Loc, Loc); 786 } else if (!CPlusPlus20Specifiers.empty()) { 787 auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(), 788 getLangOpts().CPlusPlus20 789 ? diag::warn_cxx17_compat_decomp_decl_spec 790 : diag::ext_decomp_decl_spec); 791 Warn << (int)CPlusPlus20Specifiers.size() 792 << llvm::join(CPlusPlus20Specifiers.begin(), 793 CPlusPlus20Specifiers.end(), " "); 794 for (auto Loc : CPlusPlus20SpecifierLocs) 795 Warn << SourceRange(Loc, Loc); 796 } 797 // We can't recover from it being declared as a typedef. 798 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 799 return nullptr; 800 } 801 802 // C++2a [dcl.struct.bind]p1: 803 // A cv that includes volatile is deprecated 804 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) && 805 getLangOpts().CPlusPlus20) 806 Diag(DS.getVolatileSpecLoc(), 807 diag::warn_deprecated_volatile_structured_binding); 808 809 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 810 QualType R = TInfo->getType(); 811 812 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 813 UPPC_DeclarationType)) 814 D.setInvalidType(); 815 816 // The syntax only allows a single ref-qualifier prior to the decomposition 817 // declarator. No other declarator chunks are permitted. Also check the type 818 // specifier here. 819 if (DS.getTypeSpecType() != DeclSpec::TST_auto || 820 D.hasGroupingParens() || D.getNumTypeObjects() > 1 || 821 (D.getNumTypeObjects() == 1 && 822 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) { 823 Diag(Decomp.getLSquareLoc(), 824 (D.hasGroupingParens() || 825 (D.getNumTypeObjects() && 826 D.getTypeObject(0).Kind == DeclaratorChunk::Paren)) 827 ? diag::err_decomp_decl_parens 828 : diag::err_decomp_decl_type) 829 << R; 830 831 // In most cases, there's no actual problem with an explicitly-specified 832 // type, but a function type won't work here, and ActOnVariableDeclarator 833 // shouldn't be called for such a type. 834 if (R->isFunctionType()) 835 D.setInvalidType(); 836 } 837 838 // Build the BindingDecls. 839 SmallVector<BindingDecl*, 8> Bindings; 840 841 // Build the BindingDecls. 842 for (auto &B : D.getDecompositionDeclarator().bindings()) { 843 // Check for name conflicts. 844 DeclarationNameInfo NameInfo(B.Name, B.NameLoc); 845 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 846 ForVisibleRedeclaration); 847 LookupName(Previous, S, 848 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit()); 849 850 // It's not permitted to shadow a template parameter name. 851 if (Previous.isSingleResult() && 852 Previous.getFoundDecl()->isTemplateParameter()) { 853 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 854 Previous.getFoundDecl()); 855 Previous.clear(); 856 } 857 858 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name); 859 860 // Find the shadowed declaration before filtering for scope. 861 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 862 ? getShadowedDeclaration(BD, Previous) 863 : nullptr; 864 865 bool ConsiderLinkage = DC->isFunctionOrMethod() && 866 DS.getStorageClassSpec() == DeclSpec::SCS_extern; 867 FilterLookupForScope(Previous, DC, S, ConsiderLinkage, 868 /*AllowInlineNamespace*/false); 869 870 if (!Previous.empty()) { 871 auto *Old = Previous.getRepresentativeDecl(); 872 Diag(B.NameLoc, diag::err_redefinition) << B.Name; 873 Diag(Old->getLocation(), diag::note_previous_definition); 874 } else if (ShadowedDecl && !D.isRedeclaration()) { 875 CheckShadow(BD, ShadowedDecl, Previous); 876 } 877 PushOnScopeChains(BD, S, true); 878 Bindings.push_back(BD); 879 ParsingInitForAutoVars.insert(BD); 880 } 881 882 // There are no prior lookup results for the variable itself, because it 883 // is unnamed. 884 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr, 885 Decomp.getLSquareLoc()); 886 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 887 ForVisibleRedeclaration); 888 889 // Build the variable that holds the non-decomposed object. 890 bool AddToScope = true; 891 NamedDecl *New = 892 ActOnVariableDeclarator(S, D, DC, TInfo, Previous, 893 MultiTemplateParamsArg(), AddToScope, Bindings); 894 if (AddToScope) { 895 S->AddDecl(New); 896 CurContext->addHiddenDecl(New); 897 } 898 899 if (isInOpenMPDeclareTargetContext()) 900 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 901 902 return New; 903 } 904 905 static bool checkSimpleDecomposition( 906 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src, 907 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType, 908 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) { 909 if ((int64_t)Bindings.size() != NumElems) { 910 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 911 << DecompType << (unsigned)Bindings.size() 912 << (unsigned)NumElems.getLimitedValue(UINT_MAX) 913 << toString(NumElems, 10) << (NumElems < Bindings.size()); 914 return true; 915 } 916 917 unsigned I = 0; 918 for (auto *B : Bindings) { 919 SourceLocation Loc = B->getLocation(); 920 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 921 if (E.isInvalid()) 922 return true; 923 E = GetInit(Loc, E.get(), I++); 924 if (E.isInvalid()) 925 return true; 926 B->setBinding(ElemType, E.get()); 927 } 928 929 return false; 930 } 931 932 static bool checkArrayLikeDecomposition(Sema &S, 933 ArrayRef<BindingDecl *> Bindings, 934 ValueDecl *Src, QualType DecompType, 935 const llvm::APSInt &NumElems, 936 QualType ElemType) { 937 return checkSimpleDecomposition( 938 S, Bindings, Src, DecompType, NumElems, ElemType, 939 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 940 ExprResult E = S.ActOnIntegerConstant(Loc, I); 941 if (E.isInvalid()) 942 return ExprError(); 943 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc); 944 }); 945 } 946 947 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 948 ValueDecl *Src, QualType DecompType, 949 const ConstantArrayType *CAT) { 950 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType, 951 llvm::APSInt(CAT->getSize()), 952 CAT->getElementType()); 953 } 954 955 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 956 ValueDecl *Src, QualType DecompType, 957 const VectorType *VT) { 958 return checkArrayLikeDecomposition( 959 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()), 960 S.Context.getQualifiedType(VT->getElementType(), 961 DecompType.getQualifiers())); 962 } 963 964 static bool checkComplexDecomposition(Sema &S, 965 ArrayRef<BindingDecl *> Bindings, 966 ValueDecl *Src, QualType DecompType, 967 const ComplexType *CT) { 968 return checkSimpleDecomposition( 969 S, Bindings, Src, DecompType, llvm::APSInt::get(2), 970 S.Context.getQualifiedType(CT->getElementType(), 971 DecompType.getQualifiers()), 972 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 973 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base); 974 }); 975 } 976 977 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy, 978 TemplateArgumentListInfo &Args, 979 const TemplateParameterList *Params) { 980 SmallString<128> SS; 981 llvm::raw_svector_ostream OS(SS); 982 bool First = true; 983 unsigned I = 0; 984 for (auto &Arg : Args.arguments()) { 985 if (!First) 986 OS << ", "; 987 Arg.getArgument().print(PrintingPolicy, OS, 988 TemplateParameterList::shouldIncludeTypeForArgument( 989 PrintingPolicy, Params, I)); 990 First = false; 991 I++; 992 } 993 return std::string(OS.str()); 994 } 995 996 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup, 997 SourceLocation Loc, StringRef Trait, 998 TemplateArgumentListInfo &Args, 999 unsigned DiagID) { 1000 auto DiagnoseMissing = [&] { 1001 if (DiagID) 1002 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(), 1003 Args, /*Params*/ nullptr); 1004 return true; 1005 }; 1006 1007 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine. 1008 NamespaceDecl *Std = S.getStdNamespace(); 1009 if (!Std) 1010 return DiagnoseMissing(); 1011 1012 // Look up the trait itself, within namespace std. We can diagnose various 1013 // problems with this lookup even if we've been asked to not diagnose a 1014 // missing specialization, because this can only fail if the user has been 1015 // declaring their own names in namespace std or we don't support the 1016 // standard library implementation in use. 1017 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait), 1018 Loc, Sema::LookupOrdinaryName); 1019 if (!S.LookupQualifiedName(Result, Std)) 1020 return DiagnoseMissing(); 1021 if (Result.isAmbiguous()) 1022 return true; 1023 1024 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>(); 1025 if (!TraitTD) { 1026 Result.suppressDiagnostics(); 1027 NamedDecl *Found = *Result.begin(); 1028 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait; 1029 S.Diag(Found->getLocation(), diag::note_declared_at); 1030 return true; 1031 } 1032 1033 // Build the template-id. 1034 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args); 1035 if (TraitTy.isNull()) 1036 return true; 1037 if (!S.isCompleteType(Loc, TraitTy)) { 1038 if (DiagID) 1039 S.RequireCompleteType( 1040 Loc, TraitTy, DiagID, 1041 printTemplateArgs(S.Context.getPrintingPolicy(), Args, 1042 TraitTD->getTemplateParameters())); 1043 return true; 1044 } 1045 1046 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl(); 1047 assert(RD && "specialization of class template is not a class?"); 1048 1049 // Look up the member of the trait type. 1050 S.LookupQualifiedName(TraitMemberLookup, RD); 1051 return TraitMemberLookup.isAmbiguous(); 1052 } 1053 1054 static TemplateArgumentLoc 1055 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, 1056 uint64_t I) { 1057 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T); 1058 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc); 1059 } 1060 1061 static TemplateArgumentLoc 1062 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) { 1063 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc); 1064 } 1065 1066 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; } 1067 1068 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, 1069 llvm::APSInt &Size) { 1070 EnterExpressionEvaluationContext ContextRAII( 1071 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 1072 1073 DeclarationName Value = S.PP.getIdentifierInfo("value"); 1074 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName); 1075 1076 // Form template argument list for tuple_size<T>. 1077 TemplateArgumentListInfo Args(Loc, Loc); 1078 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1079 1080 // If there's no tuple_size specialization or the lookup of 'value' is empty, 1081 // it's not tuple-like. 1082 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) || 1083 R.empty()) 1084 return IsTupleLike::NotTupleLike; 1085 1086 // If we get this far, we've committed to the tuple interpretation, but 1087 // we can still fail if there actually isn't a usable ::value. 1088 1089 struct ICEDiagnoser : Sema::VerifyICEDiagnoser { 1090 LookupResult &R; 1091 TemplateArgumentListInfo &Args; 1092 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args) 1093 : R(R), Args(Args) {} 1094 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S, 1095 SourceLocation Loc) override { 1096 return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant) 1097 << printTemplateArgs(S.Context.getPrintingPolicy(), Args, 1098 /*Params*/ nullptr); 1099 } 1100 } Diagnoser(R, Args); 1101 1102 ExprResult E = 1103 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false); 1104 if (E.isInvalid()) 1105 return IsTupleLike::Error; 1106 1107 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser); 1108 if (E.isInvalid()) 1109 return IsTupleLike::Error; 1110 1111 return IsTupleLike::TupleLike; 1112 } 1113 1114 /// \return std::tuple_element<I, T>::type. 1115 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, 1116 unsigned I, QualType T) { 1117 // Form template argument list for tuple_element<I, T>. 1118 TemplateArgumentListInfo Args(Loc, Loc); 1119 Args.addArgument( 1120 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1121 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1122 1123 DeclarationName TypeDN = S.PP.getIdentifierInfo("type"); 1124 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName); 1125 if (lookupStdTypeTraitMember( 1126 S, R, Loc, "tuple_element", Args, 1127 diag::err_decomp_decl_std_tuple_element_not_specialized)) 1128 return QualType(); 1129 1130 auto *TD = R.getAsSingle<TypeDecl>(); 1131 if (!TD) { 1132 R.suppressDiagnostics(); 1133 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized) 1134 << printTemplateArgs(S.Context.getPrintingPolicy(), Args, 1135 /*Params*/ nullptr); 1136 if (!R.empty()) 1137 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at); 1138 return QualType(); 1139 } 1140 1141 return S.Context.getTypeDeclType(TD); 1142 } 1143 1144 namespace { 1145 struct InitializingBinding { 1146 Sema &S; 1147 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) { 1148 Sema::CodeSynthesisContext Ctx; 1149 Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding; 1150 Ctx.PointOfInstantiation = BD->getLocation(); 1151 Ctx.Entity = BD; 1152 S.pushCodeSynthesisContext(Ctx); 1153 } 1154 ~InitializingBinding() { 1155 S.popCodeSynthesisContext(); 1156 } 1157 }; 1158 } 1159 1160 static bool checkTupleLikeDecomposition(Sema &S, 1161 ArrayRef<BindingDecl *> Bindings, 1162 VarDecl *Src, QualType DecompType, 1163 const llvm::APSInt &TupleSize) { 1164 if ((int64_t)Bindings.size() != TupleSize) { 1165 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1166 << DecompType << (unsigned)Bindings.size() 1167 << (unsigned)TupleSize.getLimitedValue(UINT_MAX) 1168 << toString(TupleSize, 10) << (TupleSize < Bindings.size()); 1169 return true; 1170 } 1171 1172 if (Bindings.empty()) 1173 return false; 1174 1175 DeclarationName GetDN = S.PP.getIdentifierInfo("get"); 1176 1177 // [dcl.decomp]p3: 1178 // The unqualified-id get is looked up in the scope of E by class member 1179 // access lookup ... 1180 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName); 1181 bool UseMemberGet = false; 1182 if (S.isCompleteType(Src->getLocation(), DecompType)) { 1183 if (auto *RD = DecompType->getAsCXXRecordDecl()) 1184 S.LookupQualifiedName(MemberGet, RD); 1185 if (MemberGet.isAmbiguous()) 1186 return true; 1187 // ... and if that finds at least one declaration that is a function 1188 // template whose first template parameter is a non-type parameter ... 1189 for (NamedDecl *D : MemberGet) { 1190 if (FunctionTemplateDecl *FTD = 1191 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) { 1192 TemplateParameterList *TPL = FTD->getTemplateParameters(); 1193 if (TPL->size() != 0 && 1194 isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) { 1195 // ... the initializer is e.get<i>(). 1196 UseMemberGet = true; 1197 break; 1198 } 1199 } 1200 } 1201 } 1202 1203 unsigned I = 0; 1204 for (auto *B : Bindings) { 1205 InitializingBinding InitContext(S, B); 1206 SourceLocation Loc = B->getLocation(); 1207 1208 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1209 if (E.isInvalid()) 1210 return true; 1211 1212 // e is an lvalue if the type of the entity is an lvalue reference and 1213 // an xvalue otherwise 1214 if (!Src->getType()->isLValueReferenceType()) 1215 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp, 1216 E.get(), nullptr, VK_XValue, 1217 FPOptionsOverride()); 1218 1219 TemplateArgumentListInfo Args(Loc, Loc); 1220 Args.addArgument( 1221 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1222 1223 if (UseMemberGet) { 1224 // if [lookup of member get] finds at least one declaration, the 1225 // initializer is e.get<i-1>(). 1226 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false, 1227 CXXScopeSpec(), SourceLocation(), nullptr, 1228 MemberGet, &Args, nullptr); 1229 if (E.isInvalid()) 1230 return true; 1231 1232 E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc); 1233 } else { 1234 // Otherwise, the initializer is get<i-1>(e), where get is looked up 1235 // in the associated namespaces. 1236 Expr *Get = UnresolvedLookupExpr::Create( 1237 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(), 1238 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args, 1239 UnresolvedSetIterator(), UnresolvedSetIterator()); 1240 1241 Expr *Arg = E.get(); 1242 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc); 1243 } 1244 if (E.isInvalid()) 1245 return true; 1246 Expr *Init = E.get(); 1247 1248 // Given the type T designated by std::tuple_element<i - 1, E>::type, 1249 QualType T = getTupleLikeElementType(S, Loc, I, DecompType); 1250 if (T.isNull()) 1251 return true; 1252 1253 // each vi is a variable of type "reference to T" initialized with the 1254 // initializer, where the reference is an lvalue reference if the 1255 // initializer is an lvalue and an rvalue reference otherwise 1256 QualType RefType = 1257 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName()); 1258 if (RefType.isNull()) 1259 return true; 1260 auto *RefVD = VarDecl::Create( 1261 S.Context, Src->getDeclContext(), Loc, Loc, 1262 B->getDeclName().getAsIdentifierInfo(), RefType, 1263 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass()); 1264 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext()); 1265 RefVD->setTSCSpec(Src->getTSCSpec()); 1266 RefVD->setImplicit(); 1267 if (Src->isInlineSpecified()) 1268 RefVD->setInlineSpecified(); 1269 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD); 1270 1271 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD); 1272 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc); 1273 InitializationSequence Seq(S, Entity, Kind, Init); 1274 E = Seq.Perform(S, Entity, Kind, Init); 1275 if (E.isInvalid()) 1276 return true; 1277 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false); 1278 if (E.isInvalid()) 1279 return true; 1280 RefVD->setInit(E.get()); 1281 S.CheckCompleteVariableDeclaration(RefVD); 1282 1283 E = S.BuildDeclarationNameExpr(CXXScopeSpec(), 1284 DeclarationNameInfo(B->getDeclName(), Loc), 1285 RefVD); 1286 if (E.isInvalid()) 1287 return true; 1288 1289 B->setBinding(T, E.get()); 1290 I++; 1291 } 1292 1293 return false; 1294 } 1295 1296 /// Find the base class to decompose in a built-in decomposition of a class type. 1297 /// This base class search is, unfortunately, not quite like any other that we 1298 /// perform anywhere else in C++. 1299 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc, 1300 const CXXRecordDecl *RD, 1301 CXXCastPath &BasePath) { 1302 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier, 1303 CXXBasePath &Path) { 1304 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields(); 1305 }; 1306 1307 const CXXRecordDecl *ClassWithFields = nullptr; 1308 AccessSpecifier AS = AS_public; 1309 if (RD->hasDirectFields()) 1310 // [dcl.decomp]p4: 1311 // Otherwise, all of E's non-static data members shall be public direct 1312 // members of E ... 1313 ClassWithFields = RD; 1314 else { 1315 // ... or of ... 1316 CXXBasePaths Paths; 1317 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD)); 1318 if (!RD->lookupInBases(BaseHasFields, Paths)) { 1319 // If no classes have fields, just decompose RD itself. (This will work 1320 // if and only if zero bindings were provided.) 1321 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public); 1322 } 1323 1324 CXXBasePath *BestPath = nullptr; 1325 for (auto &P : Paths) { 1326 if (!BestPath) 1327 BestPath = &P; 1328 else if (!S.Context.hasSameType(P.back().Base->getType(), 1329 BestPath->back().Base->getType())) { 1330 // ... the same ... 1331 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1332 << false << RD << BestPath->back().Base->getType() 1333 << P.back().Base->getType(); 1334 return DeclAccessPair(); 1335 } else if (P.Access < BestPath->Access) { 1336 BestPath = &P; 1337 } 1338 } 1339 1340 // ... unambiguous ... 1341 QualType BaseType = BestPath->back().Base->getType(); 1342 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) { 1343 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base) 1344 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths); 1345 return DeclAccessPair(); 1346 } 1347 1348 // ... [accessible, implied by other rules] base class of E. 1349 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD), 1350 *BestPath, diag::err_decomp_decl_inaccessible_base); 1351 AS = BestPath->Access; 1352 1353 ClassWithFields = BaseType->getAsCXXRecordDecl(); 1354 S.BuildBasePathArray(Paths, BasePath); 1355 } 1356 1357 // The above search did not check whether the selected class itself has base 1358 // classes with fields, so check that now. 1359 CXXBasePaths Paths; 1360 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) { 1361 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1362 << (ClassWithFields == RD) << RD << ClassWithFields 1363 << Paths.front().back().Base->getType(); 1364 return DeclAccessPair(); 1365 } 1366 1367 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS); 1368 } 1369 1370 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 1371 ValueDecl *Src, QualType DecompType, 1372 const CXXRecordDecl *OrigRD) { 1373 if (S.RequireCompleteType(Src->getLocation(), DecompType, 1374 diag::err_incomplete_type)) 1375 return true; 1376 1377 CXXCastPath BasePath; 1378 DeclAccessPair BasePair = 1379 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath); 1380 const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl()); 1381 if (!RD) 1382 return true; 1383 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD), 1384 DecompType.getQualifiers()); 1385 1386 auto DiagnoseBadNumberOfBindings = [&]() -> bool { 1387 unsigned NumFields = llvm::count_if( 1388 RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); }); 1389 assert(Bindings.size() != NumFields); 1390 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1391 << DecompType << (unsigned)Bindings.size() << NumFields << NumFields 1392 << (NumFields < Bindings.size()); 1393 return true; 1394 }; 1395 1396 // all of E's non-static data members shall be [...] well-formed 1397 // when named as e.name in the context of the structured binding, 1398 // E shall not have an anonymous union member, ... 1399 unsigned I = 0; 1400 for (auto *FD : RD->fields()) { 1401 if (FD->isUnnamedBitfield()) 1402 continue; 1403 1404 // All the non-static data members are required to be nameable, so they 1405 // must all have names. 1406 if (!FD->getDeclName()) { 1407 if (RD->isLambda()) { 1408 S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda); 1409 S.Diag(RD->getLocation(), diag::note_lambda_decl); 1410 return true; 1411 } 1412 1413 if (FD->isAnonymousStructOrUnion()) { 1414 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member) 1415 << DecompType << FD->getType()->isUnionType(); 1416 S.Diag(FD->getLocation(), diag::note_declared_at); 1417 return true; 1418 } 1419 1420 // FIXME: Are there any other ways we could have an anonymous member? 1421 } 1422 1423 // We have a real field to bind. 1424 if (I >= Bindings.size()) 1425 return DiagnoseBadNumberOfBindings(); 1426 auto *B = Bindings[I++]; 1427 SourceLocation Loc = B->getLocation(); 1428 1429 // The field must be accessible in the context of the structured binding. 1430 // We already checked that the base class is accessible. 1431 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the 1432 // const_cast here. 1433 S.CheckStructuredBindingMemberAccess( 1434 Loc, const_cast<CXXRecordDecl *>(OrigRD), 1435 DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess( 1436 BasePair.getAccess(), FD->getAccess()))); 1437 1438 // Initialize the binding to Src.FD. 1439 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1440 if (E.isInvalid()) 1441 return true; 1442 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase, 1443 VK_LValue, &BasePath); 1444 if (E.isInvalid()) 1445 return true; 1446 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc, 1447 CXXScopeSpec(), FD, 1448 DeclAccessPair::make(FD, FD->getAccess()), 1449 DeclarationNameInfo(FD->getDeclName(), Loc)); 1450 if (E.isInvalid()) 1451 return true; 1452 1453 // If the type of the member is T, the referenced type is cv T, where cv is 1454 // the cv-qualification of the decomposition expression. 1455 // 1456 // FIXME: We resolve a defect here: if the field is mutable, we do not add 1457 // 'const' to the type of the field. 1458 Qualifiers Q = DecompType.getQualifiers(); 1459 if (FD->isMutable()) 1460 Q.removeConst(); 1461 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get()); 1462 } 1463 1464 if (I != Bindings.size()) 1465 return DiagnoseBadNumberOfBindings(); 1466 1467 return false; 1468 } 1469 1470 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) { 1471 QualType DecompType = DD->getType(); 1472 1473 // If the type of the decomposition is dependent, then so is the type of 1474 // each binding. 1475 if (DecompType->isDependentType()) { 1476 for (auto *B : DD->bindings()) 1477 B->setType(Context.DependentTy); 1478 return; 1479 } 1480 1481 DecompType = DecompType.getNonReferenceType(); 1482 ArrayRef<BindingDecl*> Bindings = DD->bindings(); 1483 1484 // C++1z [dcl.decomp]/2: 1485 // If E is an array type [...] 1486 // As an extension, we also support decomposition of built-in complex and 1487 // vector types. 1488 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) { 1489 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT)) 1490 DD->setInvalidDecl(); 1491 return; 1492 } 1493 if (auto *VT = DecompType->getAs<VectorType>()) { 1494 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT)) 1495 DD->setInvalidDecl(); 1496 return; 1497 } 1498 if (auto *CT = DecompType->getAs<ComplexType>()) { 1499 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT)) 1500 DD->setInvalidDecl(); 1501 return; 1502 } 1503 1504 // C++1z [dcl.decomp]/3: 1505 // if the expression std::tuple_size<E>::value is a well-formed integral 1506 // constant expression, [...] 1507 llvm::APSInt TupleSize(32); 1508 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) { 1509 case IsTupleLike::Error: 1510 DD->setInvalidDecl(); 1511 return; 1512 1513 case IsTupleLike::TupleLike: 1514 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize)) 1515 DD->setInvalidDecl(); 1516 return; 1517 1518 case IsTupleLike::NotTupleLike: 1519 break; 1520 } 1521 1522 // C++1z [dcl.dcl]/8: 1523 // [E shall be of array or non-union class type] 1524 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl(); 1525 if (!RD || RD->isUnion()) { 1526 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type) 1527 << DD << !RD << DecompType; 1528 DD->setInvalidDecl(); 1529 return; 1530 } 1531 1532 // C++1z [dcl.decomp]/4: 1533 // all of E's non-static data members shall be [...] direct members of 1534 // E or of the same unambiguous public base class of E, ... 1535 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD)) 1536 DD->setInvalidDecl(); 1537 } 1538 1539 /// Merge the exception specifications of two variable declarations. 1540 /// 1541 /// This is called when there's a redeclaration of a VarDecl. The function 1542 /// checks if the redeclaration might have an exception specification and 1543 /// validates compatibility and merges the specs if necessary. 1544 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 1545 // Shortcut if exceptions are disabled. 1546 if (!getLangOpts().CXXExceptions) 1547 return; 1548 1549 assert(Context.hasSameType(New->getType(), Old->getType()) && 1550 "Should only be called if types are otherwise the same."); 1551 1552 QualType NewType = New->getType(); 1553 QualType OldType = Old->getType(); 1554 1555 // We're only interested in pointers and references to functions, as well 1556 // as pointers to member functions. 1557 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 1558 NewType = R->getPointeeType(); 1559 OldType = OldType->castAs<ReferenceType>()->getPointeeType(); 1560 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 1561 NewType = P->getPointeeType(); 1562 OldType = OldType->castAs<PointerType>()->getPointeeType(); 1563 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 1564 NewType = M->getPointeeType(); 1565 OldType = OldType->castAs<MemberPointerType>()->getPointeeType(); 1566 } 1567 1568 if (!NewType->isFunctionProtoType()) 1569 return; 1570 1571 // There's lots of special cases for functions. For function pointers, system 1572 // libraries are hopefully not as broken so that we don't need these 1573 // workarounds. 1574 if (CheckEquivalentExceptionSpec( 1575 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 1576 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 1577 New->setInvalidDecl(); 1578 } 1579 } 1580 1581 /// CheckCXXDefaultArguments - Verify that the default arguments for a 1582 /// function declaration are well-formed according to C++ 1583 /// [dcl.fct.default]. 1584 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 1585 unsigned NumParams = FD->getNumParams(); 1586 unsigned ParamIdx = 0; 1587 1588 // This checking doesn't make sense for explicit specializations; their 1589 // default arguments are determined by the declaration we're specializing, 1590 // not by FD. 1591 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 1592 return; 1593 if (auto *FTD = FD->getDescribedFunctionTemplate()) 1594 if (FTD->isMemberSpecialization()) 1595 return; 1596 1597 // Find first parameter with a default argument 1598 for (; ParamIdx < NumParams; ++ParamIdx) { 1599 ParmVarDecl *Param = FD->getParamDecl(ParamIdx); 1600 if (Param->hasDefaultArg()) 1601 break; 1602 } 1603 1604 // C++20 [dcl.fct.default]p4: 1605 // In a given function declaration, each parameter subsequent to a parameter 1606 // with a default argument shall have a default argument supplied in this or 1607 // a previous declaration, unless the parameter was expanded from a 1608 // parameter pack, or shall be a function parameter pack. 1609 for (; ParamIdx < NumParams; ++ParamIdx) { 1610 ParmVarDecl *Param = FD->getParamDecl(ParamIdx); 1611 if (!Param->hasDefaultArg() && !Param->isParameterPack() && 1612 !(CurrentInstantiationScope && 1613 CurrentInstantiationScope->isLocalPackExpansion(Param))) { 1614 if (Param->isInvalidDecl()) 1615 /* We already complained about this parameter. */; 1616 else if (Param->getIdentifier()) 1617 Diag(Param->getLocation(), 1618 diag::err_param_default_argument_missing_name) 1619 << Param->getIdentifier(); 1620 else 1621 Diag(Param->getLocation(), 1622 diag::err_param_default_argument_missing); 1623 } 1624 } 1625 } 1626 1627 /// Check that the given type is a literal type. Issue a diagnostic if not, 1628 /// if Kind is Diagnose. 1629 /// \return \c true if a problem has been found (and optionally diagnosed). 1630 template <typename... Ts> 1631 static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind, 1632 SourceLocation Loc, QualType T, unsigned DiagID, 1633 Ts &&...DiagArgs) { 1634 if (T->isDependentType()) 1635 return false; 1636 1637 switch (Kind) { 1638 case Sema::CheckConstexprKind::Diagnose: 1639 return SemaRef.RequireLiteralType(Loc, T, DiagID, 1640 std::forward<Ts>(DiagArgs)...); 1641 1642 case Sema::CheckConstexprKind::CheckValid: 1643 return !T->isLiteralType(SemaRef.Context); 1644 } 1645 1646 llvm_unreachable("unknown CheckConstexprKind"); 1647 } 1648 1649 /// Determine whether a destructor cannot be constexpr due to 1650 static bool CheckConstexprDestructorSubobjects(Sema &SemaRef, 1651 const CXXDestructorDecl *DD, 1652 Sema::CheckConstexprKind Kind) { 1653 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) { 1654 const CXXRecordDecl *RD = 1655 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 1656 if (!RD || RD->hasConstexprDestructor()) 1657 return true; 1658 1659 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1660 SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject) 1661 << static_cast<int>(DD->getConstexprKind()) << !FD 1662 << (FD ? FD->getDeclName() : DeclarationName()) << T; 1663 SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject) 1664 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T; 1665 } 1666 return false; 1667 }; 1668 1669 const CXXRecordDecl *RD = DD->getParent(); 1670 for (const CXXBaseSpecifier &B : RD->bases()) 1671 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr)) 1672 return false; 1673 for (const FieldDecl *FD : RD->fields()) 1674 if (!Check(FD->getLocation(), FD->getType(), FD)) 1675 return false; 1676 return true; 1677 } 1678 1679 /// Check whether a function's parameter types are all literal types. If so, 1680 /// return true. If not, produce a suitable diagnostic and return false. 1681 static bool CheckConstexprParameterTypes(Sema &SemaRef, 1682 const FunctionDecl *FD, 1683 Sema::CheckConstexprKind Kind) { 1684 unsigned ArgIndex = 0; 1685 const auto *FT = FD->getType()->castAs<FunctionProtoType>(); 1686 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 1687 e = FT->param_type_end(); 1688 i != e; ++i, ++ArgIndex) { 1689 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 1690 SourceLocation ParamLoc = PD->getLocation(); 1691 if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i, 1692 diag::err_constexpr_non_literal_param, ArgIndex + 1, 1693 PD->getSourceRange(), isa<CXXConstructorDecl>(FD), 1694 FD->isConsteval())) 1695 return false; 1696 } 1697 return true; 1698 } 1699 1700 /// Check whether a function's return type is a literal type. If so, return 1701 /// true. If not, produce a suitable diagnostic and return false. 1702 static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD, 1703 Sema::CheckConstexprKind Kind) { 1704 if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(), 1705 diag::err_constexpr_non_literal_return, 1706 FD->isConsteval())) 1707 return false; 1708 return true; 1709 } 1710 1711 /// Get diagnostic %select index for tag kind for 1712 /// record diagnostic message. 1713 /// WARNING: Indexes apply to particular diagnostics only! 1714 /// 1715 /// \returns diagnostic %select index. 1716 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 1717 switch (Tag) { 1718 case TTK_Struct: return 0; 1719 case TTK_Interface: return 1; 1720 case TTK_Class: return 2; 1721 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 1722 } 1723 } 1724 1725 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, 1726 Stmt *Body, 1727 Sema::CheckConstexprKind Kind); 1728 1729 // Check whether a function declaration satisfies the requirements of a 1730 // constexpr function definition or a constexpr constructor definition. If so, 1731 // return true. If not, produce appropriate diagnostics (unless asked not to by 1732 // Kind) and return false. 1733 // 1734 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 1735 bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD, 1736 CheckConstexprKind Kind) { 1737 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 1738 if (MD && MD->isInstance()) { 1739 // C++11 [dcl.constexpr]p4: 1740 // The definition of a constexpr constructor shall satisfy the following 1741 // constraints: 1742 // - the class shall not have any virtual base classes; 1743 // 1744 // FIXME: This only applies to constructors and destructors, not arbitrary 1745 // member functions. 1746 const CXXRecordDecl *RD = MD->getParent(); 1747 if (RD->getNumVBases()) { 1748 if (Kind == CheckConstexprKind::CheckValid) 1749 return false; 1750 1751 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 1752 << isa<CXXConstructorDecl>(NewFD) 1753 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 1754 for (const auto &I : RD->vbases()) 1755 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here) 1756 << I.getSourceRange(); 1757 return false; 1758 } 1759 } 1760 1761 if (!isa<CXXConstructorDecl>(NewFD)) { 1762 // C++11 [dcl.constexpr]p3: 1763 // The definition of a constexpr function shall satisfy the following 1764 // constraints: 1765 // - it shall not be virtual; (removed in C++20) 1766 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 1767 if (Method && Method->isVirtual()) { 1768 if (getLangOpts().CPlusPlus20) { 1769 if (Kind == CheckConstexprKind::Diagnose) 1770 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual); 1771 } else { 1772 if (Kind == CheckConstexprKind::CheckValid) 1773 return false; 1774 1775 Method = Method->getCanonicalDecl(); 1776 Diag(Method->getLocation(), diag::err_constexpr_virtual); 1777 1778 // If it's not obvious why this function is virtual, find an overridden 1779 // function which uses the 'virtual' keyword. 1780 const CXXMethodDecl *WrittenVirtual = Method; 1781 while (!WrittenVirtual->isVirtualAsWritten()) 1782 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 1783 if (WrittenVirtual != Method) 1784 Diag(WrittenVirtual->getLocation(), 1785 diag::note_overridden_virtual_function); 1786 return false; 1787 } 1788 } 1789 1790 // - its return type shall be a literal type; 1791 if (!CheckConstexprReturnType(*this, NewFD, Kind)) 1792 return false; 1793 } 1794 1795 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) { 1796 // A destructor can be constexpr only if the defaulted destructor could be; 1797 // we don't need to check the members and bases if we already know they all 1798 // have constexpr destructors. 1799 if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) { 1800 if (Kind == CheckConstexprKind::CheckValid) 1801 return false; 1802 if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind)) 1803 return false; 1804 } 1805 } 1806 1807 // - each of its parameter types shall be a literal type; 1808 if (!CheckConstexprParameterTypes(*this, NewFD, Kind)) 1809 return false; 1810 1811 Stmt *Body = NewFD->getBody(); 1812 assert(Body && 1813 "CheckConstexprFunctionDefinition called on function with no body"); 1814 return CheckConstexprFunctionBody(*this, NewFD, Body, Kind); 1815 } 1816 1817 /// Check the given declaration statement is legal within a constexpr function 1818 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 1819 /// 1820 /// \return true if the body is OK (maybe only as an extension), false if we 1821 /// have diagnosed a problem. 1822 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 1823 DeclStmt *DS, SourceLocation &Cxx1yLoc, 1824 Sema::CheckConstexprKind Kind) { 1825 // C++11 [dcl.constexpr]p3 and p4: 1826 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 1827 // contain only 1828 for (const auto *DclIt : DS->decls()) { 1829 switch (DclIt->getKind()) { 1830 case Decl::StaticAssert: 1831 case Decl::Using: 1832 case Decl::UsingShadow: 1833 case Decl::UsingDirective: 1834 case Decl::UnresolvedUsingTypename: 1835 case Decl::UnresolvedUsingValue: 1836 case Decl::UsingEnum: 1837 // - static_assert-declarations 1838 // - using-declarations, 1839 // - using-directives, 1840 // - using-enum-declaration 1841 continue; 1842 1843 case Decl::Typedef: 1844 case Decl::TypeAlias: { 1845 // - typedef declarations and alias-declarations that do not define 1846 // classes or enumerations, 1847 const auto *TN = cast<TypedefNameDecl>(DclIt); 1848 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 1849 // Don't allow variably-modified types in constexpr functions. 1850 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1851 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 1852 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 1853 << TL.getSourceRange() << TL.getType() 1854 << isa<CXXConstructorDecl>(Dcl); 1855 } 1856 return false; 1857 } 1858 continue; 1859 } 1860 1861 case Decl::Enum: 1862 case Decl::CXXRecord: 1863 // C++1y allows types to be defined, not just declared. 1864 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) { 1865 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1866 SemaRef.Diag(DS->getBeginLoc(), 1867 SemaRef.getLangOpts().CPlusPlus14 1868 ? diag::warn_cxx11_compat_constexpr_type_definition 1869 : diag::ext_constexpr_type_definition) 1870 << isa<CXXConstructorDecl>(Dcl); 1871 } else if (!SemaRef.getLangOpts().CPlusPlus14) { 1872 return false; 1873 } 1874 } 1875 continue; 1876 1877 case Decl::EnumConstant: 1878 case Decl::IndirectField: 1879 case Decl::ParmVar: 1880 // These can only appear with other declarations which are banned in 1881 // C++11 and permitted in C++1y, so ignore them. 1882 continue; 1883 1884 case Decl::Var: 1885 case Decl::Decomposition: { 1886 // C++1y [dcl.constexpr]p3 allows anything except: 1887 // a definition of a variable of non-literal type or of static or 1888 // thread storage duration or [before C++2a] for which no 1889 // initialization is performed. 1890 const auto *VD = cast<VarDecl>(DclIt); 1891 if (VD->isThisDeclarationADefinition()) { 1892 if (VD->isStaticLocal()) { 1893 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1894 SemaRef.Diag(VD->getLocation(), 1895 diag::err_constexpr_local_var_static) 1896 << isa<CXXConstructorDecl>(Dcl) 1897 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 1898 } 1899 return false; 1900 } 1901 if (CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(), 1902 diag::err_constexpr_local_var_non_literal_type, 1903 isa<CXXConstructorDecl>(Dcl))) 1904 return false; 1905 if (!VD->getType()->isDependentType() && 1906 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 1907 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1908 SemaRef.Diag( 1909 VD->getLocation(), 1910 SemaRef.getLangOpts().CPlusPlus20 1911 ? diag::warn_cxx17_compat_constexpr_local_var_no_init 1912 : diag::ext_constexpr_local_var_no_init) 1913 << isa<CXXConstructorDecl>(Dcl); 1914 } else if (!SemaRef.getLangOpts().CPlusPlus20) { 1915 return false; 1916 } 1917 continue; 1918 } 1919 } 1920 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1921 SemaRef.Diag(VD->getLocation(), 1922 SemaRef.getLangOpts().CPlusPlus14 1923 ? diag::warn_cxx11_compat_constexpr_local_var 1924 : diag::ext_constexpr_local_var) 1925 << isa<CXXConstructorDecl>(Dcl); 1926 } else if (!SemaRef.getLangOpts().CPlusPlus14) { 1927 return false; 1928 } 1929 continue; 1930 } 1931 1932 case Decl::NamespaceAlias: 1933 case Decl::Function: 1934 // These are disallowed in C++11 and permitted in C++1y. Allow them 1935 // everywhere as an extension. 1936 if (!Cxx1yLoc.isValid()) 1937 Cxx1yLoc = DS->getBeginLoc(); 1938 continue; 1939 1940 default: 1941 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1942 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 1943 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 1944 } 1945 return false; 1946 } 1947 } 1948 1949 return true; 1950 } 1951 1952 /// Check that the given field is initialized within a constexpr constructor. 1953 /// 1954 /// \param Dcl The constexpr constructor being checked. 1955 /// \param Field The field being checked. This may be a member of an anonymous 1956 /// struct or union nested within the class being checked. 1957 /// \param Inits All declarations, including anonymous struct/union members and 1958 /// indirect members, for which any initialization was provided. 1959 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach 1960 /// multiple notes for different members to the same error. 1961 /// \param Kind Whether we're diagnosing a constructor as written or determining 1962 /// whether the formal requirements are satisfied. 1963 /// \return \c false if we're checking for validity and the constructor does 1964 /// not satisfy the requirements on a constexpr constructor. 1965 static bool CheckConstexprCtorInitializer(Sema &SemaRef, 1966 const FunctionDecl *Dcl, 1967 FieldDecl *Field, 1968 llvm::SmallSet<Decl*, 16> &Inits, 1969 bool &Diagnosed, 1970 Sema::CheckConstexprKind Kind) { 1971 // In C++20 onwards, there's nothing to check for validity. 1972 if (Kind == Sema::CheckConstexprKind::CheckValid && 1973 SemaRef.getLangOpts().CPlusPlus20) 1974 return true; 1975 1976 if (Field->isInvalidDecl()) 1977 return true; 1978 1979 if (Field->isUnnamedBitfield()) 1980 return true; 1981 1982 // Anonymous unions with no variant members and empty anonymous structs do not 1983 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 1984 // indirect fields don't need initializing. 1985 if (Field->isAnonymousStructOrUnion() && 1986 (Field->getType()->isUnionType() 1987 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 1988 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 1989 return true; 1990 1991 if (!Inits.count(Field)) { 1992 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1993 if (!Diagnosed) { 1994 SemaRef.Diag(Dcl->getLocation(), 1995 SemaRef.getLangOpts().CPlusPlus20 1996 ? diag::warn_cxx17_compat_constexpr_ctor_missing_init 1997 : diag::ext_constexpr_ctor_missing_init); 1998 Diagnosed = true; 1999 } 2000 SemaRef.Diag(Field->getLocation(), 2001 diag::note_constexpr_ctor_missing_init); 2002 } else if (!SemaRef.getLangOpts().CPlusPlus20) { 2003 return false; 2004 } 2005 } else if (Field->isAnonymousStructOrUnion()) { 2006 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 2007 for (auto *I : RD->fields()) 2008 // If an anonymous union contains an anonymous struct of which any member 2009 // is initialized, all members must be initialized. 2010 if (!RD->isUnion() || Inits.count(I)) 2011 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, 2012 Kind)) 2013 return false; 2014 } 2015 return true; 2016 } 2017 2018 /// Check the provided statement is allowed in a constexpr function 2019 /// definition. 2020 static bool 2021 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 2022 SmallVectorImpl<SourceLocation> &ReturnStmts, 2023 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc, 2024 Sema::CheckConstexprKind Kind) { 2025 // - its function-body shall be [...] a compound-statement that contains only 2026 switch (S->getStmtClass()) { 2027 case Stmt::NullStmtClass: 2028 // - null statements, 2029 return true; 2030 2031 case Stmt::DeclStmtClass: 2032 // - static_assert-declarations 2033 // - using-declarations, 2034 // - using-directives, 2035 // - typedef declarations and alias-declarations that do not define 2036 // classes or enumerations, 2037 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind)) 2038 return false; 2039 return true; 2040 2041 case Stmt::ReturnStmtClass: 2042 // - and exactly one return statement; 2043 if (isa<CXXConstructorDecl>(Dcl)) { 2044 // C++1y allows return statements in constexpr constructors. 2045 if (!Cxx1yLoc.isValid()) 2046 Cxx1yLoc = S->getBeginLoc(); 2047 return true; 2048 } 2049 2050 ReturnStmts.push_back(S->getBeginLoc()); 2051 return true; 2052 2053 case Stmt::AttributedStmtClass: 2054 // Attributes on a statement don't affect its formal kind and hence don't 2055 // affect its validity in a constexpr function. 2056 return CheckConstexprFunctionStmt(SemaRef, Dcl, 2057 cast<AttributedStmt>(S)->getSubStmt(), 2058 ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind); 2059 2060 case Stmt::CompoundStmtClass: { 2061 // C++1y allows compound-statements. 2062 if (!Cxx1yLoc.isValid()) 2063 Cxx1yLoc = S->getBeginLoc(); 2064 2065 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 2066 for (auto *BodyIt : CompStmt->body()) { 2067 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 2068 Cxx1yLoc, Cxx2aLoc, Kind)) 2069 return false; 2070 } 2071 return true; 2072 } 2073 2074 case Stmt::IfStmtClass: { 2075 // C++1y allows if-statements. 2076 if (!Cxx1yLoc.isValid()) 2077 Cxx1yLoc = S->getBeginLoc(); 2078 2079 IfStmt *If = cast<IfStmt>(S); 2080 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 2081 Cxx1yLoc, Cxx2aLoc, Kind)) 2082 return false; 2083 if (If->getElse() && 2084 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 2085 Cxx1yLoc, Cxx2aLoc, Kind)) 2086 return false; 2087 return true; 2088 } 2089 2090 case Stmt::WhileStmtClass: 2091 case Stmt::DoStmtClass: 2092 case Stmt::ForStmtClass: 2093 case Stmt::CXXForRangeStmtClass: 2094 case Stmt::ContinueStmtClass: 2095 // C++1y allows all of these. We don't allow them as extensions in C++11, 2096 // because they don't make sense without variable mutation. 2097 if (!SemaRef.getLangOpts().CPlusPlus14) 2098 break; 2099 if (!Cxx1yLoc.isValid()) 2100 Cxx1yLoc = S->getBeginLoc(); 2101 for (Stmt *SubStmt : S->children()) 2102 if (SubStmt && 2103 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2104 Cxx1yLoc, Cxx2aLoc, Kind)) 2105 return false; 2106 return true; 2107 2108 case Stmt::SwitchStmtClass: 2109 case Stmt::CaseStmtClass: 2110 case Stmt::DefaultStmtClass: 2111 case Stmt::BreakStmtClass: 2112 // C++1y allows switch-statements, and since they don't need variable 2113 // mutation, we can reasonably allow them in C++11 as an extension. 2114 if (!Cxx1yLoc.isValid()) 2115 Cxx1yLoc = S->getBeginLoc(); 2116 for (Stmt *SubStmt : S->children()) 2117 if (SubStmt && 2118 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2119 Cxx1yLoc, Cxx2aLoc, Kind)) 2120 return false; 2121 return true; 2122 2123 case Stmt::GCCAsmStmtClass: 2124 case Stmt::MSAsmStmtClass: 2125 // C++2a allows inline assembly statements. 2126 case Stmt::CXXTryStmtClass: 2127 if (Cxx2aLoc.isInvalid()) 2128 Cxx2aLoc = S->getBeginLoc(); 2129 for (Stmt *SubStmt : S->children()) { 2130 if (SubStmt && 2131 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2132 Cxx1yLoc, Cxx2aLoc, Kind)) 2133 return false; 2134 } 2135 return true; 2136 2137 case Stmt::CXXCatchStmtClass: 2138 // Do not bother checking the language mode (already covered by the 2139 // try block check). 2140 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, 2141 cast<CXXCatchStmt>(S)->getHandlerBlock(), 2142 ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind)) 2143 return false; 2144 return true; 2145 2146 default: 2147 if (!isa<Expr>(S)) 2148 break; 2149 2150 // C++1y allows expression-statements. 2151 if (!Cxx1yLoc.isValid()) 2152 Cxx1yLoc = S->getBeginLoc(); 2153 return true; 2154 } 2155 2156 if (Kind == Sema::CheckConstexprKind::Diagnose) { 2157 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 2158 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 2159 } 2160 return false; 2161 } 2162 2163 /// Check the body for the given constexpr function declaration only contains 2164 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 2165 /// 2166 /// \return true if the body is OK, false if we have found or diagnosed a 2167 /// problem. 2168 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, 2169 Stmt *Body, 2170 Sema::CheckConstexprKind Kind) { 2171 SmallVector<SourceLocation, 4> ReturnStmts; 2172 2173 if (isa<CXXTryStmt>(Body)) { 2174 // C++11 [dcl.constexpr]p3: 2175 // The definition of a constexpr function shall satisfy the following 2176 // constraints: [...] 2177 // - its function-body shall be = delete, = default, or a 2178 // compound-statement 2179 // 2180 // C++11 [dcl.constexpr]p4: 2181 // In the definition of a constexpr constructor, [...] 2182 // - its function-body shall not be a function-try-block; 2183 // 2184 // This restriction is lifted in C++2a, as long as inner statements also 2185 // apply the general constexpr rules. 2186 switch (Kind) { 2187 case Sema::CheckConstexprKind::CheckValid: 2188 if (!SemaRef.getLangOpts().CPlusPlus20) 2189 return false; 2190 break; 2191 2192 case Sema::CheckConstexprKind::Diagnose: 2193 SemaRef.Diag(Body->getBeginLoc(), 2194 !SemaRef.getLangOpts().CPlusPlus20 2195 ? diag::ext_constexpr_function_try_block_cxx20 2196 : diag::warn_cxx17_compat_constexpr_function_try_block) 2197 << isa<CXXConstructorDecl>(Dcl); 2198 break; 2199 } 2200 } 2201 2202 // - its function-body shall be [...] a compound-statement that contains only 2203 // [... list of cases ...] 2204 // 2205 // Note that walking the children here is enough to properly check for 2206 // CompoundStmt and CXXTryStmt body. 2207 SourceLocation Cxx1yLoc, Cxx2aLoc; 2208 for (Stmt *SubStmt : Body->children()) { 2209 if (SubStmt && 2210 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2211 Cxx1yLoc, Cxx2aLoc, Kind)) 2212 return false; 2213 } 2214 2215 if (Kind == Sema::CheckConstexprKind::CheckValid) { 2216 // If this is only valid as an extension, report that we don't satisfy the 2217 // constraints of the current language. 2218 if ((Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) || 2219 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17)) 2220 return false; 2221 } else if (Cxx2aLoc.isValid()) { 2222 SemaRef.Diag(Cxx2aLoc, 2223 SemaRef.getLangOpts().CPlusPlus20 2224 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt 2225 : diag::ext_constexpr_body_invalid_stmt_cxx20) 2226 << isa<CXXConstructorDecl>(Dcl); 2227 } else if (Cxx1yLoc.isValid()) { 2228 SemaRef.Diag(Cxx1yLoc, 2229 SemaRef.getLangOpts().CPlusPlus14 2230 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 2231 : diag::ext_constexpr_body_invalid_stmt) 2232 << isa<CXXConstructorDecl>(Dcl); 2233 } 2234 2235 if (const CXXConstructorDecl *Constructor 2236 = dyn_cast<CXXConstructorDecl>(Dcl)) { 2237 const CXXRecordDecl *RD = Constructor->getParent(); 2238 // DR1359: 2239 // - every non-variant non-static data member and base class sub-object 2240 // shall be initialized; 2241 // DR1460: 2242 // - if the class is a union having variant members, exactly one of them 2243 // shall be initialized; 2244 if (RD->isUnion()) { 2245 if (Constructor->getNumCtorInitializers() == 0 && 2246 RD->hasVariantMembers()) { 2247 if (Kind == Sema::CheckConstexprKind::Diagnose) { 2248 SemaRef.Diag( 2249 Dcl->getLocation(), 2250 SemaRef.getLangOpts().CPlusPlus20 2251 ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init 2252 : diag::ext_constexpr_union_ctor_no_init); 2253 } else if (!SemaRef.getLangOpts().CPlusPlus20) { 2254 return false; 2255 } 2256 } 2257 } else if (!Constructor->isDependentContext() && 2258 !Constructor->isDelegatingConstructor()) { 2259 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 2260 2261 // Skip detailed checking if we have enough initializers, and we would 2262 // allow at most one initializer per member. 2263 bool AnyAnonStructUnionMembers = false; 2264 unsigned Fields = 0; 2265 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 2266 E = RD->field_end(); I != E; ++I, ++Fields) { 2267 if (I->isAnonymousStructOrUnion()) { 2268 AnyAnonStructUnionMembers = true; 2269 break; 2270 } 2271 } 2272 // DR1460: 2273 // - if the class is a union-like class, but is not a union, for each of 2274 // its anonymous union members having variant members, exactly one of 2275 // them shall be initialized; 2276 if (AnyAnonStructUnionMembers || 2277 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 2278 // Check initialization of non-static data members. Base classes are 2279 // always initialized so do not need to be checked. Dependent bases 2280 // might not have initializers in the member initializer list. 2281 llvm::SmallSet<Decl*, 16> Inits; 2282 for (const auto *I: Constructor->inits()) { 2283 if (FieldDecl *FD = I->getMember()) 2284 Inits.insert(FD); 2285 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 2286 Inits.insert(ID->chain_begin(), ID->chain_end()); 2287 } 2288 2289 bool Diagnosed = false; 2290 for (auto *I : RD->fields()) 2291 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, 2292 Kind)) 2293 return false; 2294 } 2295 } 2296 } else { 2297 if (ReturnStmts.empty()) { 2298 // C++1y doesn't require constexpr functions to contain a 'return' 2299 // statement. We still do, unless the return type might be void, because 2300 // otherwise if there's no return statement, the function cannot 2301 // be used in a core constant expression. 2302 bool OK = SemaRef.getLangOpts().CPlusPlus14 && 2303 (Dcl->getReturnType()->isVoidType() || 2304 Dcl->getReturnType()->isDependentType()); 2305 switch (Kind) { 2306 case Sema::CheckConstexprKind::Diagnose: 2307 SemaRef.Diag(Dcl->getLocation(), 2308 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 2309 : diag::err_constexpr_body_no_return) 2310 << Dcl->isConsteval(); 2311 if (!OK) 2312 return false; 2313 break; 2314 2315 case Sema::CheckConstexprKind::CheckValid: 2316 // The formal requirements don't include this rule in C++14, even 2317 // though the "must be able to produce a constant expression" rules 2318 // still imply it in some cases. 2319 if (!SemaRef.getLangOpts().CPlusPlus14) 2320 return false; 2321 break; 2322 } 2323 } else if (ReturnStmts.size() > 1) { 2324 switch (Kind) { 2325 case Sema::CheckConstexprKind::Diagnose: 2326 SemaRef.Diag( 2327 ReturnStmts.back(), 2328 SemaRef.getLangOpts().CPlusPlus14 2329 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 2330 : diag::ext_constexpr_body_multiple_return); 2331 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 2332 SemaRef.Diag(ReturnStmts[I], 2333 diag::note_constexpr_body_previous_return); 2334 break; 2335 2336 case Sema::CheckConstexprKind::CheckValid: 2337 if (!SemaRef.getLangOpts().CPlusPlus14) 2338 return false; 2339 break; 2340 } 2341 } 2342 } 2343 2344 // C++11 [dcl.constexpr]p5: 2345 // if no function argument values exist such that the function invocation 2346 // substitution would produce a constant expression, the program is 2347 // ill-formed; no diagnostic required. 2348 // C++11 [dcl.constexpr]p3: 2349 // - every constructor call and implicit conversion used in initializing the 2350 // return value shall be one of those allowed in a constant expression. 2351 // C++11 [dcl.constexpr]p4: 2352 // - every constructor involved in initializing non-static data members and 2353 // base class sub-objects shall be a constexpr constructor. 2354 // 2355 // Note that this rule is distinct from the "requirements for a constexpr 2356 // function", so is not checked in CheckValid mode. 2357 SmallVector<PartialDiagnosticAt, 8> Diags; 2358 if (Kind == Sema::CheckConstexprKind::Diagnose && 2359 !Expr::isPotentialConstantExpr(Dcl, Diags)) { 2360 SemaRef.Diag(Dcl->getLocation(), 2361 diag::ext_constexpr_function_never_constant_expr) 2362 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 2363 for (size_t I = 0, N = Diags.size(); I != N; ++I) 2364 SemaRef.Diag(Diags[I].first, Diags[I].second); 2365 // Don't return false here: we allow this for compatibility in 2366 // system headers. 2367 } 2368 2369 return true; 2370 } 2371 2372 /// Get the class that is directly named by the current context. This is the 2373 /// class for which an unqualified-id in this scope could name a constructor 2374 /// or destructor. 2375 /// 2376 /// If the scope specifier denotes a class, this will be that class. 2377 /// If the scope specifier is empty, this will be the class whose 2378 /// member-specification we are currently within. Otherwise, there 2379 /// is no such class. 2380 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) { 2381 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2382 2383 if (SS && SS->isInvalid()) 2384 return nullptr; 2385 2386 if (SS && SS->isNotEmpty()) { 2387 DeclContext *DC = computeDeclContext(*SS, true); 2388 return dyn_cast_or_null<CXXRecordDecl>(DC); 2389 } 2390 2391 return dyn_cast_or_null<CXXRecordDecl>(CurContext); 2392 } 2393 2394 /// isCurrentClassName - Determine whether the identifier II is the 2395 /// name of the class type currently being defined. In the case of 2396 /// nested classes, this will only return true if II is the name of 2397 /// the innermost class. 2398 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S, 2399 const CXXScopeSpec *SS) { 2400 CXXRecordDecl *CurDecl = getCurrentClass(S, SS); 2401 return CurDecl && &II == CurDecl->getIdentifier(); 2402 } 2403 2404 /// Determine whether the identifier II is a typo for the name of 2405 /// the class type currently being defined. If so, update it to the identifier 2406 /// that should have been used. 2407 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 2408 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2409 2410 if (!getLangOpts().SpellChecking) 2411 return false; 2412 2413 CXXRecordDecl *CurDecl; 2414 if (SS && SS->isSet() && !SS->isInvalid()) { 2415 DeclContext *DC = computeDeclContext(*SS, true); 2416 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 2417 } else 2418 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 2419 2420 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 2421 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 2422 < II->getLength()) { 2423 II = CurDecl->getIdentifier(); 2424 return true; 2425 } 2426 2427 return false; 2428 } 2429 2430 /// Determine whether the given class is a base class of the given 2431 /// class, including looking at dependent bases. 2432 static bool findCircularInheritance(const CXXRecordDecl *Class, 2433 const CXXRecordDecl *Current) { 2434 SmallVector<const CXXRecordDecl*, 8> Queue; 2435 2436 Class = Class->getCanonicalDecl(); 2437 while (true) { 2438 for (const auto &I : Current->bases()) { 2439 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 2440 if (!Base) 2441 continue; 2442 2443 Base = Base->getDefinition(); 2444 if (!Base) 2445 continue; 2446 2447 if (Base->getCanonicalDecl() == Class) 2448 return true; 2449 2450 Queue.push_back(Base); 2451 } 2452 2453 if (Queue.empty()) 2454 return false; 2455 2456 Current = Queue.pop_back_val(); 2457 } 2458 2459 return false; 2460 } 2461 2462 /// Check the validity of a C++ base class specifier. 2463 /// 2464 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 2465 /// and returns NULL otherwise. 2466 CXXBaseSpecifier * 2467 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 2468 SourceRange SpecifierRange, 2469 bool Virtual, AccessSpecifier Access, 2470 TypeSourceInfo *TInfo, 2471 SourceLocation EllipsisLoc) { 2472 QualType BaseType = TInfo->getType(); 2473 if (BaseType->containsErrors()) { 2474 // Already emitted a diagnostic when parsing the error type. 2475 return nullptr; 2476 } 2477 // C++ [class.union]p1: 2478 // A union shall not have base classes. 2479 if (Class->isUnion()) { 2480 Diag(Class->getLocation(), diag::err_base_clause_on_union) 2481 << SpecifierRange; 2482 return nullptr; 2483 } 2484 2485 if (EllipsisLoc.isValid() && 2486 !TInfo->getType()->containsUnexpandedParameterPack()) { 2487 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2488 << TInfo->getTypeLoc().getSourceRange(); 2489 EllipsisLoc = SourceLocation(); 2490 } 2491 2492 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 2493 2494 if (BaseType->isDependentType()) { 2495 // Make sure that we don't have circular inheritance among our dependent 2496 // bases. For non-dependent bases, the check for completeness below handles 2497 // this. 2498 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 2499 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 2500 ((BaseDecl = BaseDecl->getDefinition()) && 2501 findCircularInheritance(Class, BaseDecl))) { 2502 Diag(BaseLoc, diag::err_circular_inheritance) 2503 << BaseType << Context.getTypeDeclType(Class); 2504 2505 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 2506 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 2507 << BaseType; 2508 2509 return nullptr; 2510 } 2511 } 2512 2513 // Make sure that we don't make an ill-formed AST where the type of the 2514 // Class is non-dependent and its attached base class specifier is an 2515 // dependent type, which violates invariants in many clang code paths (e.g. 2516 // constexpr evaluator). If this case happens (in errory-recovery mode), we 2517 // explicitly mark the Class decl invalid. The diagnostic was already 2518 // emitted. 2519 if (!Class->getTypeForDecl()->isDependentType()) 2520 Class->setInvalidDecl(); 2521 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2522 Class->getTagKind() == TTK_Class, 2523 Access, TInfo, EllipsisLoc); 2524 } 2525 2526 // Base specifiers must be record types. 2527 if (!BaseType->isRecordType()) { 2528 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 2529 return nullptr; 2530 } 2531 2532 // C++ [class.union]p1: 2533 // A union shall not be used as a base class. 2534 if (BaseType->isUnionType()) { 2535 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 2536 return nullptr; 2537 } 2538 2539 // For the MS ABI, propagate DLL attributes to base class templates. 2540 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 2541 if (Attr *ClassAttr = getDLLAttr(Class)) { 2542 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 2543 BaseType->getAsCXXRecordDecl())) { 2544 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate, 2545 BaseLoc); 2546 } 2547 } 2548 } 2549 2550 // C++ [class.derived]p2: 2551 // The class-name in a base-specifier shall not be an incompletely 2552 // defined class. 2553 if (RequireCompleteType(BaseLoc, BaseType, 2554 diag::err_incomplete_base_class, SpecifierRange)) { 2555 Class->setInvalidDecl(); 2556 return nullptr; 2557 } 2558 2559 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 2560 RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl(); 2561 assert(BaseDecl && "Record type has no declaration"); 2562 BaseDecl = BaseDecl->getDefinition(); 2563 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 2564 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 2565 assert(CXXBaseDecl && "Base type is not a C++ type"); 2566 2567 // Microsoft docs say: 2568 // "If a base-class has a code_seg attribute, derived classes must have the 2569 // same attribute." 2570 const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>(); 2571 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>(); 2572 if ((DerivedCSA || BaseCSA) && 2573 (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) { 2574 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base); 2575 Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here) 2576 << CXXBaseDecl; 2577 return nullptr; 2578 } 2579 2580 // A class which contains a flexible array member is not suitable for use as a 2581 // base class: 2582 // - If the layout determines that a base comes before another base, 2583 // the flexible array member would index into the subsequent base. 2584 // - If the layout determines that base comes before the derived class, 2585 // the flexible array member would index into the derived class. 2586 if (CXXBaseDecl->hasFlexibleArrayMember()) { 2587 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 2588 << CXXBaseDecl->getDeclName(); 2589 return nullptr; 2590 } 2591 2592 // C++ [class]p3: 2593 // If a class is marked final and it appears as a base-type-specifier in 2594 // base-clause, the program is ill-formed. 2595 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 2596 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 2597 << CXXBaseDecl->getDeclName() 2598 << FA->isSpelledAsSealed(); 2599 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 2600 << CXXBaseDecl->getDeclName() << FA->getRange(); 2601 return nullptr; 2602 } 2603 2604 if (BaseDecl->isInvalidDecl()) 2605 Class->setInvalidDecl(); 2606 2607 // Create the base specifier. 2608 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2609 Class->getTagKind() == TTK_Class, 2610 Access, TInfo, EllipsisLoc); 2611 } 2612 2613 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 2614 /// one entry in the base class list of a class specifier, for 2615 /// example: 2616 /// class foo : public bar, virtual private baz { 2617 /// 'public bar' and 'virtual private baz' are each base-specifiers. 2618 BaseResult 2619 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 2620 ParsedAttributes &Attributes, 2621 bool Virtual, AccessSpecifier Access, 2622 ParsedType basetype, SourceLocation BaseLoc, 2623 SourceLocation EllipsisLoc) { 2624 if (!classdecl) 2625 return true; 2626 2627 AdjustDeclIfTemplate(classdecl); 2628 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 2629 if (!Class) 2630 return true; 2631 2632 // We haven't yet attached the base specifiers. 2633 Class->setIsParsingBaseSpecifiers(); 2634 2635 // We do not support any C++11 attributes on base-specifiers yet. 2636 // Diagnose any attributes we see. 2637 for (const ParsedAttr &AL : Attributes) { 2638 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute) 2639 continue; 2640 Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute 2641 ? (unsigned)diag::warn_unknown_attribute_ignored 2642 : (unsigned)diag::err_base_specifier_attribute) 2643 << AL << AL.getRange(); 2644 } 2645 2646 TypeSourceInfo *TInfo = nullptr; 2647 GetTypeFromParser(basetype, &TInfo); 2648 2649 if (EllipsisLoc.isInvalid() && 2650 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 2651 UPPC_BaseType)) 2652 return true; 2653 2654 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 2655 Virtual, Access, TInfo, 2656 EllipsisLoc)) 2657 return BaseSpec; 2658 else 2659 Class->setInvalidDecl(); 2660 2661 return true; 2662 } 2663 2664 /// Use small set to collect indirect bases. As this is only used 2665 /// locally, there's no need to abstract the small size parameter. 2666 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet; 2667 2668 /// Recursively add the bases of Type. Don't add Type itself. 2669 static void 2670 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, 2671 const QualType &Type) 2672 { 2673 // Even though the incoming type is a base, it might not be 2674 // a class -- it could be a template parm, for instance. 2675 if (auto Rec = Type->getAs<RecordType>()) { 2676 auto Decl = Rec->getAsCXXRecordDecl(); 2677 2678 // Iterate over its bases. 2679 for (const auto &BaseSpec : Decl->bases()) { 2680 QualType Base = Context.getCanonicalType(BaseSpec.getType()) 2681 .getUnqualifiedType(); 2682 if (Set.insert(Base).second) 2683 // If we've not already seen it, recurse. 2684 NoteIndirectBases(Context, Set, Base); 2685 } 2686 } 2687 } 2688 2689 /// Performs the actual work of attaching the given base class 2690 /// specifiers to a C++ class. 2691 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, 2692 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2693 if (Bases.empty()) 2694 return false; 2695 2696 // Used to keep track of which base types we have already seen, so 2697 // that we can properly diagnose redundant direct base types. Note 2698 // that the key is always the unqualified canonical type of the base 2699 // class. 2700 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 2701 2702 // Used to track indirect bases so we can see if a direct base is 2703 // ambiguous. 2704 IndirectBaseSet IndirectBaseTypes; 2705 2706 // Copy non-redundant base specifiers into permanent storage. 2707 unsigned NumGoodBases = 0; 2708 bool Invalid = false; 2709 for (unsigned idx = 0; idx < Bases.size(); ++idx) { 2710 QualType NewBaseType 2711 = Context.getCanonicalType(Bases[idx]->getType()); 2712 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 2713 2714 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 2715 if (KnownBase) { 2716 // C++ [class.mi]p3: 2717 // A class shall not be specified as a direct base class of a 2718 // derived class more than once. 2719 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class) 2720 << KnownBase->getType() << Bases[idx]->getSourceRange(); 2721 2722 // Delete the duplicate base class specifier; we're going to 2723 // overwrite its pointer later. 2724 Context.Deallocate(Bases[idx]); 2725 2726 Invalid = true; 2727 } else { 2728 // Okay, add this new base class. 2729 KnownBase = Bases[idx]; 2730 Bases[NumGoodBases++] = Bases[idx]; 2731 2732 if (NewBaseType->isDependentType()) 2733 continue; 2734 // Note this base's direct & indirect bases, if there could be ambiguity. 2735 if (Bases.size() > 1) 2736 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType); 2737 2738 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 2739 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 2740 if (Class->isInterface() && 2741 (!RD->isInterfaceLike() || 2742 KnownBase->getAccessSpecifier() != AS_public)) { 2743 // The Microsoft extension __interface does not permit bases that 2744 // are not themselves public interfaces. 2745 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface) 2746 << getRecordDiagFromTagKind(RD->getTagKind()) << RD 2747 << RD->getSourceRange(); 2748 Invalid = true; 2749 } 2750 if (RD->hasAttr<WeakAttr>()) 2751 Class->addAttr(WeakAttr::CreateImplicit(Context)); 2752 } 2753 } 2754 } 2755 2756 // Attach the remaining base class specifiers to the derived class. 2757 Class->setBases(Bases.data(), NumGoodBases); 2758 2759 // Check that the only base classes that are duplicate are virtual. 2760 for (unsigned idx = 0; idx < NumGoodBases; ++idx) { 2761 // Check whether this direct base is inaccessible due to ambiguity. 2762 QualType BaseType = Bases[idx]->getType(); 2763 2764 // Skip all dependent types in templates being used as base specifiers. 2765 // Checks below assume that the base specifier is a CXXRecord. 2766 if (BaseType->isDependentType()) 2767 continue; 2768 2769 CanQualType CanonicalBase = Context.getCanonicalType(BaseType) 2770 .getUnqualifiedType(); 2771 2772 if (IndirectBaseTypes.count(CanonicalBase)) { 2773 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2774 /*DetectVirtual=*/true); 2775 bool found 2776 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); 2777 assert(found); 2778 (void)found; 2779 2780 if (Paths.isAmbiguous(CanonicalBase)) 2781 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class) 2782 << BaseType << getAmbiguousPathsDisplayString(Paths) 2783 << Bases[idx]->getSourceRange(); 2784 else 2785 assert(Bases[idx]->isVirtual()); 2786 } 2787 2788 // Delete the base class specifier, since its data has been copied 2789 // into the CXXRecordDecl. 2790 Context.Deallocate(Bases[idx]); 2791 } 2792 2793 return Invalid; 2794 } 2795 2796 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 2797 /// class, after checking whether there are any duplicate base 2798 /// classes. 2799 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, 2800 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2801 if (!ClassDecl || Bases.empty()) 2802 return; 2803 2804 AdjustDeclIfTemplate(ClassDecl); 2805 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases); 2806 } 2807 2808 /// Determine whether the type \p Derived is a C++ class that is 2809 /// derived from the type \p Base. 2810 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) { 2811 if (!getLangOpts().CPlusPlus) 2812 return false; 2813 2814 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2815 if (!DerivedRD) 2816 return false; 2817 2818 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2819 if (!BaseRD) 2820 return false; 2821 2822 // If either the base or the derived type is invalid, don't try to 2823 // check whether one is derived from the other. 2824 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 2825 return false; 2826 2827 // FIXME: In a modules build, do we need the entire path to be visible for us 2828 // to be able to use the inheritance relationship? 2829 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2830 return false; 2831 2832 return DerivedRD->isDerivedFrom(BaseRD); 2833 } 2834 2835 /// Determine whether the type \p Derived is a C++ class that is 2836 /// derived from the type \p Base. 2837 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, 2838 CXXBasePaths &Paths) { 2839 if (!getLangOpts().CPlusPlus) 2840 return false; 2841 2842 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2843 if (!DerivedRD) 2844 return false; 2845 2846 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2847 if (!BaseRD) 2848 return false; 2849 2850 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2851 return false; 2852 2853 return DerivedRD->isDerivedFrom(BaseRD, Paths); 2854 } 2855 2856 static void BuildBasePathArray(const CXXBasePath &Path, 2857 CXXCastPath &BasePathArray) { 2858 // We first go backward and check if we have a virtual base. 2859 // FIXME: It would be better if CXXBasePath had the base specifier for 2860 // the nearest virtual base. 2861 unsigned Start = 0; 2862 for (unsigned I = Path.size(); I != 0; --I) { 2863 if (Path[I - 1].Base->isVirtual()) { 2864 Start = I - 1; 2865 break; 2866 } 2867 } 2868 2869 // Now add all bases. 2870 for (unsigned I = Start, E = Path.size(); I != E; ++I) 2871 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 2872 } 2873 2874 2875 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 2876 CXXCastPath &BasePathArray) { 2877 assert(BasePathArray.empty() && "Base path array must be empty!"); 2878 assert(Paths.isRecordingPaths() && "Must record paths!"); 2879 return ::BuildBasePathArray(Paths.front(), BasePathArray); 2880 } 2881 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 2882 /// conversion (where Derived and Base are class types) is 2883 /// well-formed, meaning that the conversion is unambiguous (and 2884 /// that all of the base classes are accessible). Returns true 2885 /// and emits a diagnostic if the code is ill-formed, returns false 2886 /// otherwise. Loc is the location where this routine should point to 2887 /// if there is an error, and Range is the source range to highlight 2888 /// if there is an error. 2889 /// 2890 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the 2891 /// diagnostic for the respective type of error will be suppressed, but the 2892 /// check for ill-formed code will still be performed. 2893 bool 2894 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2895 unsigned InaccessibleBaseID, 2896 unsigned AmbiguousBaseConvID, 2897 SourceLocation Loc, SourceRange Range, 2898 DeclarationName Name, 2899 CXXCastPath *BasePath, 2900 bool IgnoreAccess) { 2901 // First, determine whether the path from Derived to Base is 2902 // ambiguous. This is slightly more expensive than checking whether 2903 // the Derived to Base conversion exists, because here we need to 2904 // explore multiple paths to determine if there is an ambiguity. 2905 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2906 /*DetectVirtual=*/false); 2907 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2908 if (!DerivationOkay) 2909 return true; 2910 2911 const CXXBasePath *Path = nullptr; 2912 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) 2913 Path = &Paths.front(); 2914 2915 // For MSVC compatibility, check if Derived directly inherits from Base. Clang 2916 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the 2917 // user to access such bases. 2918 if (!Path && getLangOpts().MSVCCompat) { 2919 for (const CXXBasePath &PossiblePath : Paths) { 2920 if (PossiblePath.size() == 1) { 2921 Path = &PossiblePath; 2922 if (AmbiguousBaseConvID) 2923 Diag(Loc, diag::ext_ms_ambiguous_direct_base) 2924 << Base << Derived << Range; 2925 break; 2926 } 2927 } 2928 } 2929 2930 if (Path) { 2931 if (!IgnoreAccess) { 2932 // Check that the base class can be accessed. 2933 switch ( 2934 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) { 2935 case AR_inaccessible: 2936 return true; 2937 case AR_accessible: 2938 case AR_dependent: 2939 case AR_delayed: 2940 break; 2941 } 2942 } 2943 2944 // Build a base path if necessary. 2945 if (BasePath) 2946 ::BuildBasePathArray(*Path, *BasePath); 2947 return false; 2948 } 2949 2950 if (AmbiguousBaseConvID) { 2951 // We know that the derived-to-base conversion is ambiguous, and 2952 // we're going to produce a diagnostic. Perform the derived-to-base 2953 // search just one more time to compute all of the possible paths so 2954 // that we can print them out. This is more expensive than any of 2955 // the previous derived-to-base checks we've done, but at this point 2956 // performance isn't as much of an issue. 2957 Paths.clear(); 2958 Paths.setRecordingPaths(true); 2959 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2960 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 2961 (void)StillOkay; 2962 2963 // Build up a textual representation of the ambiguous paths, e.g., 2964 // D -> B -> A, that will be used to illustrate the ambiguous 2965 // conversions in the diagnostic. We only print one of the paths 2966 // to each base class subobject. 2967 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2968 2969 Diag(Loc, AmbiguousBaseConvID) 2970 << Derived << Base << PathDisplayStr << Range << Name; 2971 } 2972 return true; 2973 } 2974 2975 bool 2976 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2977 SourceLocation Loc, SourceRange Range, 2978 CXXCastPath *BasePath, 2979 bool IgnoreAccess) { 2980 return CheckDerivedToBaseConversion( 2981 Derived, Base, diag::err_upcast_to_inaccessible_base, 2982 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(), 2983 BasePath, IgnoreAccess); 2984 } 2985 2986 2987 /// Builds a string representing ambiguous paths from a 2988 /// specific derived class to different subobjects of the same base 2989 /// class. 2990 /// 2991 /// This function builds a string that can be used in error messages 2992 /// to show the different paths that one can take through the 2993 /// inheritance hierarchy to go from the derived class to different 2994 /// subobjects of a base class. The result looks something like this: 2995 /// @code 2996 /// struct D -> struct B -> struct A 2997 /// struct D -> struct C -> struct A 2998 /// @endcode 2999 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 3000 std::string PathDisplayStr; 3001 std::set<unsigned> DisplayedPaths; 3002 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 3003 Path != Paths.end(); ++Path) { 3004 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 3005 // We haven't displayed a path to this particular base 3006 // class subobject yet. 3007 PathDisplayStr += "\n "; 3008 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 3009 for (CXXBasePath::const_iterator Element = Path->begin(); 3010 Element != Path->end(); ++Element) 3011 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 3012 } 3013 } 3014 3015 return PathDisplayStr; 3016 } 3017 3018 //===----------------------------------------------------------------------===// 3019 // C++ class member Handling 3020 //===----------------------------------------------------------------------===// 3021 3022 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 3023 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, 3024 SourceLocation ColonLoc, 3025 const ParsedAttributesView &Attrs) { 3026 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 3027 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 3028 ASLoc, ColonLoc); 3029 CurContext->addHiddenDecl(ASDecl); 3030 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 3031 } 3032 3033 /// CheckOverrideControl - Check C++11 override control semantics. 3034 void Sema::CheckOverrideControl(NamedDecl *D) { 3035 if (D->isInvalidDecl()) 3036 return; 3037 3038 // We only care about "override" and "final" declarations. 3039 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 3040 return; 3041 3042 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 3043 3044 // We can't check dependent instance methods. 3045 if (MD && MD->isInstance() && 3046 (MD->getParent()->hasAnyDependentBases() || 3047 MD->getType()->isDependentType())) 3048 return; 3049 3050 if (MD && !MD->isVirtual()) { 3051 // If we have a non-virtual method, check if if hides a virtual method. 3052 // (In that case, it's most likely the method has the wrong type.) 3053 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 3054 FindHiddenVirtualMethods(MD, OverloadedMethods); 3055 3056 if (!OverloadedMethods.empty()) { 3057 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 3058 Diag(OA->getLocation(), 3059 diag::override_keyword_hides_virtual_member_function) 3060 << "override" << (OverloadedMethods.size() > 1); 3061 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 3062 Diag(FA->getLocation(), 3063 diag::override_keyword_hides_virtual_member_function) 3064 << (FA->isSpelledAsSealed() ? "sealed" : "final") 3065 << (OverloadedMethods.size() > 1); 3066 } 3067 NoteHiddenVirtualMethods(MD, OverloadedMethods); 3068 MD->setInvalidDecl(); 3069 return; 3070 } 3071 // Fall through into the general case diagnostic. 3072 // FIXME: We might want to attempt typo correction here. 3073 } 3074 3075 if (!MD || !MD->isVirtual()) { 3076 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 3077 Diag(OA->getLocation(), 3078 diag::override_keyword_only_allowed_on_virtual_member_functions) 3079 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 3080 D->dropAttr<OverrideAttr>(); 3081 } 3082 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 3083 Diag(FA->getLocation(), 3084 diag::override_keyword_only_allowed_on_virtual_member_functions) 3085 << (FA->isSpelledAsSealed() ? "sealed" : "final") 3086 << FixItHint::CreateRemoval(FA->getLocation()); 3087 D->dropAttr<FinalAttr>(); 3088 } 3089 return; 3090 } 3091 3092 // C++11 [class.virtual]p5: 3093 // If a function is marked with the virt-specifier override and 3094 // does not override a member function of a base class, the program is 3095 // ill-formed. 3096 bool HasOverriddenMethods = MD->size_overridden_methods() != 0; 3097 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 3098 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 3099 << MD->getDeclName(); 3100 } 3101 3102 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) { 3103 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) 3104 return; 3105 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 3106 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>()) 3107 return; 3108 3109 SourceLocation Loc = MD->getLocation(); 3110 SourceLocation SpellingLoc = Loc; 3111 if (getSourceManager().isMacroArgExpansion(Loc)) 3112 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin(); 3113 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); 3114 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) 3115 return; 3116 3117 if (MD->size_overridden_methods() > 0) { 3118 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) { 3119 unsigned DiagID = 3120 Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation()) 3121 ? DiagInconsistent 3122 : DiagSuggest; 3123 Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 3124 const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); 3125 Diag(OMD->getLocation(), diag::note_overridden_virtual_function); 3126 }; 3127 if (isa<CXXDestructorDecl>(MD)) 3128 EmitDiag( 3129 diag::warn_inconsistent_destructor_marked_not_override_overriding, 3130 diag::warn_suggest_destructor_marked_not_override_overriding); 3131 else 3132 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding, 3133 diag::warn_suggest_function_marked_not_override_overriding); 3134 } 3135 } 3136 3137 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 3138 /// function overrides a virtual member function marked 'final', according to 3139 /// C++11 [class.virtual]p4. 3140 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 3141 const CXXMethodDecl *Old) { 3142 FinalAttr *FA = Old->getAttr<FinalAttr>(); 3143 if (!FA) 3144 return false; 3145 3146 Diag(New->getLocation(), diag::err_final_function_overridden) 3147 << New->getDeclName() 3148 << FA->isSpelledAsSealed(); 3149 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 3150 return true; 3151 } 3152 3153 static bool InitializationHasSideEffects(const FieldDecl &FD) { 3154 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 3155 // FIXME: Destruction of ObjC lifetime types has side-effects. 3156 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 3157 return !RD->isCompleteDefinition() || 3158 !RD->hasTrivialDefaultConstructor() || 3159 !RD->hasTrivialDestructor(); 3160 return false; 3161 } 3162 3163 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) { 3164 ParsedAttributesView::const_iterator Itr = 3165 llvm::find_if(list, [](const ParsedAttr &AL) { 3166 return AL.isDeclspecPropertyAttribute(); 3167 }); 3168 if (Itr != list.end()) 3169 return &*Itr; 3170 return nullptr; 3171 } 3172 3173 // Check if there is a field shadowing. 3174 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc, 3175 DeclarationName FieldName, 3176 const CXXRecordDecl *RD, 3177 bool DeclIsField) { 3178 if (Diags.isIgnored(diag::warn_shadow_field, Loc)) 3179 return; 3180 3181 // To record a shadowed field in a base 3182 std::map<CXXRecordDecl*, NamedDecl*> Bases; 3183 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier, 3184 CXXBasePath &Path) { 3185 const auto Base = Specifier->getType()->getAsCXXRecordDecl(); 3186 // Record an ambiguous path directly 3187 if (Bases.find(Base) != Bases.end()) 3188 return true; 3189 for (const auto Field : Base->lookup(FieldName)) { 3190 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) && 3191 Field->getAccess() != AS_private) { 3192 assert(Field->getAccess() != AS_none); 3193 assert(Bases.find(Base) == Bases.end()); 3194 Bases[Base] = Field; 3195 return true; 3196 } 3197 } 3198 return false; 3199 }; 3200 3201 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3202 /*DetectVirtual=*/true); 3203 if (!RD->lookupInBases(FieldShadowed, Paths)) 3204 return; 3205 3206 for (const auto &P : Paths) { 3207 auto Base = P.back().Base->getType()->getAsCXXRecordDecl(); 3208 auto It = Bases.find(Base); 3209 // Skip duplicated bases 3210 if (It == Bases.end()) 3211 continue; 3212 auto BaseField = It->second; 3213 assert(BaseField->getAccess() != AS_private); 3214 if (AS_none != 3215 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) { 3216 Diag(Loc, diag::warn_shadow_field) 3217 << FieldName << RD << Base << DeclIsField; 3218 Diag(BaseField->getLocation(), diag::note_shadow_field); 3219 Bases.erase(It); 3220 } 3221 } 3222 } 3223 3224 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 3225 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 3226 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 3227 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 3228 /// present (but parsing it has been deferred). 3229 NamedDecl * 3230 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 3231 MultiTemplateParamsArg TemplateParameterLists, 3232 Expr *BW, const VirtSpecifiers &VS, 3233 InClassInitStyle InitStyle) { 3234 const DeclSpec &DS = D.getDeclSpec(); 3235 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 3236 DeclarationName Name = NameInfo.getName(); 3237 SourceLocation Loc = NameInfo.getLoc(); 3238 3239 // For anonymous bitfields, the location should point to the type. 3240 if (Loc.isInvalid()) 3241 Loc = D.getBeginLoc(); 3242 3243 Expr *BitWidth = static_cast<Expr*>(BW); 3244 3245 assert(isa<CXXRecordDecl>(CurContext)); 3246 assert(!DS.isFriendSpecified()); 3247 3248 bool isFunc = D.isDeclarationOfFunction(); 3249 const ParsedAttr *MSPropertyAttr = 3250 getMSPropertyAttr(D.getDeclSpec().getAttributes()); 3251 3252 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 3253 // The Microsoft extension __interface only permits public member functions 3254 // and prohibits constructors, destructors, operators, non-public member 3255 // functions, static methods and data members. 3256 unsigned InvalidDecl; 3257 bool ShowDeclName = true; 3258 if (!isFunc && 3259 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr)) 3260 InvalidDecl = 0; 3261 else if (!isFunc) 3262 InvalidDecl = 1; 3263 else if (AS != AS_public) 3264 InvalidDecl = 2; 3265 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 3266 InvalidDecl = 3; 3267 else switch (Name.getNameKind()) { 3268 case DeclarationName::CXXConstructorName: 3269 InvalidDecl = 4; 3270 ShowDeclName = false; 3271 break; 3272 3273 case DeclarationName::CXXDestructorName: 3274 InvalidDecl = 5; 3275 ShowDeclName = false; 3276 break; 3277 3278 case DeclarationName::CXXOperatorName: 3279 case DeclarationName::CXXConversionFunctionName: 3280 InvalidDecl = 6; 3281 break; 3282 3283 default: 3284 InvalidDecl = 0; 3285 break; 3286 } 3287 3288 if (InvalidDecl) { 3289 if (ShowDeclName) 3290 Diag(Loc, diag::err_invalid_member_in_interface) 3291 << (InvalidDecl-1) << Name; 3292 else 3293 Diag(Loc, diag::err_invalid_member_in_interface) 3294 << (InvalidDecl-1) << ""; 3295 return nullptr; 3296 } 3297 } 3298 3299 // C++ 9.2p6: A member shall not be declared to have automatic storage 3300 // duration (auto, register) or with the extern storage-class-specifier. 3301 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 3302 // data members and cannot be applied to names declared const or static, 3303 // and cannot be applied to reference members. 3304 switch (DS.getStorageClassSpec()) { 3305 case DeclSpec::SCS_unspecified: 3306 case DeclSpec::SCS_typedef: 3307 case DeclSpec::SCS_static: 3308 break; 3309 case DeclSpec::SCS_mutable: 3310 if (isFunc) { 3311 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 3312 3313 // FIXME: It would be nicer if the keyword was ignored only for this 3314 // declarator. Otherwise we could get follow-up errors. 3315 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3316 } 3317 break; 3318 default: 3319 Diag(DS.getStorageClassSpecLoc(), 3320 diag::err_storageclass_invalid_for_member); 3321 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3322 break; 3323 } 3324 3325 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 3326 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 3327 !isFunc); 3328 3329 if (DS.hasConstexprSpecifier() && isInstField) { 3330 SemaDiagnosticBuilder B = 3331 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 3332 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 3333 if (InitStyle == ICIS_NoInit) { 3334 B << 0 << 0; 3335 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 3336 B << FixItHint::CreateRemoval(ConstexprLoc); 3337 else { 3338 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 3339 D.getMutableDeclSpec().ClearConstexprSpec(); 3340 const char *PrevSpec; 3341 unsigned DiagID; 3342 bool Failed = D.getMutableDeclSpec().SetTypeQual( 3343 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 3344 (void)Failed; 3345 assert(!Failed && "Making a constexpr member const shouldn't fail"); 3346 } 3347 } else { 3348 B << 1; 3349 const char *PrevSpec; 3350 unsigned DiagID; 3351 if (D.getMutableDeclSpec().SetStorageClassSpec( 3352 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 3353 Context.getPrintingPolicy())) { 3354 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 3355 "This is the only DeclSpec that should fail to be applied"); 3356 B << 1; 3357 } else { 3358 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 3359 isInstField = false; 3360 } 3361 } 3362 } 3363 3364 NamedDecl *Member; 3365 if (isInstField) { 3366 CXXScopeSpec &SS = D.getCXXScopeSpec(); 3367 3368 // Data members must have identifiers for names. 3369 if (!Name.isIdentifier()) { 3370 Diag(Loc, diag::err_bad_variable_name) 3371 << Name; 3372 return nullptr; 3373 } 3374 3375 IdentifierInfo *II = Name.getAsIdentifierInfo(); 3376 3377 // Member field could not be with "template" keyword. 3378 // So TemplateParameterLists should be empty in this case. 3379 if (TemplateParameterLists.size()) { 3380 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 3381 if (TemplateParams->size()) { 3382 // There is no such thing as a member field template. 3383 Diag(D.getIdentifierLoc(), diag::err_template_member) 3384 << II 3385 << SourceRange(TemplateParams->getTemplateLoc(), 3386 TemplateParams->getRAngleLoc()); 3387 } else { 3388 // There is an extraneous 'template<>' for this member. 3389 Diag(TemplateParams->getTemplateLoc(), 3390 diag::err_template_member_noparams) 3391 << II 3392 << SourceRange(TemplateParams->getTemplateLoc(), 3393 TemplateParams->getRAngleLoc()); 3394 } 3395 return nullptr; 3396 } 3397 3398 if (SS.isSet() && !SS.isInvalid()) { 3399 // The user provided a superfluous scope specifier inside a class 3400 // definition: 3401 // 3402 // class X { 3403 // int X::member; 3404 // }; 3405 if (DeclContext *DC = computeDeclContext(SS, false)) 3406 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(), 3407 D.getName().getKind() == 3408 UnqualifiedIdKind::IK_TemplateId); 3409 else 3410 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 3411 << Name << SS.getRange(); 3412 3413 SS.clear(); 3414 } 3415 3416 if (MSPropertyAttr) { 3417 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3418 BitWidth, InitStyle, AS, *MSPropertyAttr); 3419 if (!Member) 3420 return nullptr; 3421 isInstField = false; 3422 } else { 3423 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3424 BitWidth, InitStyle, AS); 3425 if (!Member) 3426 return nullptr; 3427 } 3428 3429 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext)); 3430 } else { 3431 Member = HandleDeclarator(S, D, TemplateParameterLists); 3432 if (!Member) 3433 return nullptr; 3434 3435 // Non-instance-fields can't have a bitfield. 3436 if (BitWidth) { 3437 if (Member->isInvalidDecl()) { 3438 // don't emit another diagnostic. 3439 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) { 3440 // C++ 9.6p3: A bit-field shall not be a static member. 3441 // "static member 'A' cannot be a bit-field" 3442 Diag(Loc, diag::err_static_not_bitfield) 3443 << Name << BitWidth->getSourceRange(); 3444 } else if (isa<TypedefDecl>(Member)) { 3445 // "typedef member 'x' cannot be a bit-field" 3446 Diag(Loc, diag::err_typedef_not_bitfield) 3447 << Name << BitWidth->getSourceRange(); 3448 } else { 3449 // A function typedef ("typedef int f(); f a;"). 3450 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 3451 Diag(Loc, diag::err_not_integral_type_bitfield) 3452 << Name << cast<ValueDecl>(Member)->getType() 3453 << BitWidth->getSourceRange(); 3454 } 3455 3456 BitWidth = nullptr; 3457 Member->setInvalidDecl(); 3458 } 3459 3460 NamedDecl *NonTemplateMember = Member; 3461 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 3462 NonTemplateMember = FunTmpl->getTemplatedDecl(); 3463 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 3464 NonTemplateMember = VarTmpl->getTemplatedDecl(); 3465 3466 Member->setAccess(AS); 3467 3468 // If we have declared a member function template or static data member 3469 // template, set the access of the templated declaration as well. 3470 if (NonTemplateMember != Member) 3471 NonTemplateMember->setAccess(AS); 3472 3473 // C++ [temp.deduct.guide]p3: 3474 // A deduction guide [...] for a member class template [shall be 3475 // declared] with the same access [as the template]. 3476 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) { 3477 auto *TD = DG->getDeducedTemplate(); 3478 // Access specifiers are only meaningful if both the template and the 3479 // deduction guide are from the same scope. 3480 if (AS != TD->getAccess() && 3481 TD->getDeclContext()->getRedeclContext()->Equals( 3482 DG->getDeclContext()->getRedeclContext())) { 3483 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access); 3484 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access) 3485 << TD->getAccess(); 3486 const AccessSpecDecl *LastAccessSpec = nullptr; 3487 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) { 3488 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D)) 3489 LastAccessSpec = AccessSpec; 3490 } 3491 assert(LastAccessSpec && "differing access with no access specifier"); 3492 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access) 3493 << AS; 3494 } 3495 } 3496 } 3497 3498 if (VS.isOverrideSpecified()) 3499 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(), 3500 AttributeCommonInfo::AS_Keyword)); 3501 if (VS.isFinalSpecified()) 3502 Member->addAttr(FinalAttr::Create( 3503 Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword, 3504 static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed()))); 3505 3506 if (VS.getLastLocation().isValid()) { 3507 // Update the end location of a method that has a virt-specifiers. 3508 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 3509 MD->setRangeEnd(VS.getLastLocation()); 3510 } 3511 3512 CheckOverrideControl(Member); 3513 3514 assert((Name || isInstField) && "No identifier for non-field ?"); 3515 3516 if (isInstField) { 3517 FieldDecl *FD = cast<FieldDecl>(Member); 3518 FieldCollector->Add(FD); 3519 3520 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 3521 // Remember all explicit private FieldDecls that have a name, no side 3522 // effects and are not part of a dependent type declaration. 3523 if (!FD->isImplicit() && FD->getDeclName() && 3524 FD->getAccess() == AS_private && 3525 !FD->hasAttr<UnusedAttr>() && 3526 !FD->getParent()->isDependentContext() && 3527 !InitializationHasSideEffects(*FD)) 3528 UnusedPrivateFields.insert(FD); 3529 } 3530 } 3531 3532 return Member; 3533 } 3534 3535 namespace { 3536 class UninitializedFieldVisitor 3537 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 3538 Sema &S; 3539 // List of Decls to generate a warning on. Also remove Decls that become 3540 // initialized. 3541 llvm::SmallPtrSetImpl<ValueDecl*> &Decls; 3542 // List of base classes of the record. Classes are removed after their 3543 // initializers. 3544 llvm::SmallPtrSetImpl<QualType> &BaseClasses; 3545 // Vector of decls to be removed from the Decl set prior to visiting the 3546 // nodes. These Decls may have been initialized in the prior initializer. 3547 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; 3548 // If non-null, add a note to the warning pointing back to the constructor. 3549 const CXXConstructorDecl *Constructor; 3550 // Variables to hold state when processing an initializer list. When 3551 // InitList is true, special case initialization of FieldDecls matching 3552 // InitListFieldDecl. 3553 bool InitList; 3554 FieldDecl *InitListFieldDecl; 3555 llvm::SmallVector<unsigned, 4> InitFieldIndex; 3556 3557 public: 3558 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 3559 UninitializedFieldVisitor(Sema &S, 3560 llvm::SmallPtrSetImpl<ValueDecl*> &Decls, 3561 llvm::SmallPtrSetImpl<QualType> &BaseClasses) 3562 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), 3563 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} 3564 3565 // Returns true if the use of ME is not an uninitialized use. 3566 bool IsInitListMemberExprInitialized(MemberExpr *ME, 3567 bool CheckReferenceOnly) { 3568 llvm::SmallVector<FieldDecl*, 4> Fields; 3569 bool ReferenceField = false; 3570 while (ME) { 3571 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 3572 if (!FD) 3573 return false; 3574 Fields.push_back(FD); 3575 if (FD->getType()->isReferenceType()) 3576 ReferenceField = true; 3577 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); 3578 } 3579 3580 // Binding a reference to an uninitialized field is not an 3581 // uninitialized use. 3582 if (CheckReferenceOnly && !ReferenceField) 3583 return true; 3584 3585 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 3586 // Discard the first field since it is the field decl that is being 3587 // initialized. 3588 for (const FieldDecl *FD : llvm::drop_begin(llvm::reverse(Fields))) 3589 UsedFieldIndex.push_back(FD->getFieldIndex()); 3590 3591 for (auto UsedIter = UsedFieldIndex.begin(), 3592 UsedEnd = UsedFieldIndex.end(), 3593 OrigIter = InitFieldIndex.begin(), 3594 OrigEnd = InitFieldIndex.end(); 3595 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 3596 if (*UsedIter < *OrigIter) 3597 return true; 3598 if (*UsedIter > *OrigIter) 3599 break; 3600 } 3601 3602 return false; 3603 } 3604 3605 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, 3606 bool AddressOf) { 3607 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 3608 return; 3609 3610 // FieldME is the inner-most MemberExpr that is not an anonymous struct 3611 // or union. 3612 MemberExpr *FieldME = ME; 3613 3614 bool AllPODFields = FieldME->getType().isPODType(S.Context); 3615 3616 Expr *Base = ME; 3617 while (MemberExpr *SubME = 3618 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { 3619 3620 if (isa<VarDecl>(SubME->getMemberDecl())) 3621 return; 3622 3623 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) 3624 if (!FD->isAnonymousStructOrUnion()) 3625 FieldME = SubME; 3626 3627 if (!FieldME->getType().isPODType(S.Context)) 3628 AllPODFields = false; 3629 3630 Base = SubME->getBase(); 3631 } 3632 3633 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) { 3634 Visit(Base); 3635 return; 3636 } 3637 3638 if (AddressOf && AllPODFields) 3639 return; 3640 3641 ValueDecl* FoundVD = FieldME->getMemberDecl(); 3642 3643 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { 3644 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { 3645 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); 3646 } 3647 3648 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { 3649 QualType T = BaseCast->getType(); 3650 if (T->isPointerType() && 3651 BaseClasses.count(T->getPointeeType())) { 3652 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) 3653 << T->getPointeeType() << FoundVD; 3654 } 3655 } 3656 } 3657 3658 if (!Decls.count(FoundVD)) 3659 return; 3660 3661 const bool IsReference = FoundVD->getType()->isReferenceType(); 3662 3663 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { 3664 // Special checking for initializer lists. 3665 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { 3666 return; 3667 } 3668 } else { 3669 // Prevent double warnings on use of unbounded references. 3670 if (CheckReferenceOnly && !IsReference) 3671 return; 3672 } 3673 3674 unsigned diag = IsReference 3675 ? diag::warn_reference_field_is_uninit 3676 : diag::warn_field_is_uninit; 3677 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 3678 if (Constructor) 3679 S.Diag(Constructor->getLocation(), 3680 diag::note_uninit_in_this_constructor) 3681 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 3682 3683 } 3684 3685 void HandleValue(Expr *E, bool AddressOf) { 3686 E = E->IgnoreParens(); 3687 3688 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3689 HandleMemberExpr(ME, false /*CheckReferenceOnly*/, 3690 AddressOf /*AddressOf*/); 3691 return; 3692 } 3693 3694 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 3695 Visit(CO->getCond()); 3696 HandleValue(CO->getTrueExpr(), AddressOf); 3697 HandleValue(CO->getFalseExpr(), AddressOf); 3698 return; 3699 } 3700 3701 if (BinaryConditionalOperator *BCO = 3702 dyn_cast<BinaryConditionalOperator>(E)) { 3703 Visit(BCO->getCond()); 3704 HandleValue(BCO->getFalseExpr(), AddressOf); 3705 return; 3706 } 3707 3708 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 3709 HandleValue(OVE->getSourceExpr(), AddressOf); 3710 return; 3711 } 3712 3713 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 3714 switch (BO->getOpcode()) { 3715 default: 3716 break; 3717 case(BO_PtrMemD): 3718 case(BO_PtrMemI): 3719 HandleValue(BO->getLHS(), AddressOf); 3720 Visit(BO->getRHS()); 3721 return; 3722 case(BO_Comma): 3723 Visit(BO->getLHS()); 3724 HandleValue(BO->getRHS(), AddressOf); 3725 return; 3726 } 3727 } 3728 3729 Visit(E); 3730 } 3731 3732 void CheckInitListExpr(InitListExpr *ILE) { 3733 InitFieldIndex.push_back(0); 3734 for (auto Child : ILE->children()) { 3735 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { 3736 CheckInitListExpr(SubList); 3737 } else { 3738 Visit(Child); 3739 } 3740 ++InitFieldIndex.back(); 3741 } 3742 InitFieldIndex.pop_back(); 3743 } 3744 3745 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, 3746 FieldDecl *Field, const Type *BaseClass) { 3747 // Remove Decls that may have been initialized in the previous 3748 // initializer. 3749 for (ValueDecl* VD : DeclsToRemove) 3750 Decls.erase(VD); 3751 DeclsToRemove.clear(); 3752 3753 Constructor = FieldConstructor; 3754 InitListExpr *ILE = dyn_cast<InitListExpr>(E); 3755 3756 if (ILE && Field) { 3757 InitList = true; 3758 InitListFieldDecl = Field; 3759 InitFieldIndex.clear(); 3760 CheckInitListExpr(ILE); 3761 } else { 3762 InitList = false; 3763 Visit(E); 3764 } 3765 3766 if (Field) 3767 Decls.erase(Field); 3768 if (BaseClass) 3769 BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); 3770 } 3771 3772 void VisitMemberExpr(MemberExpr *ME) { 3773 // All uses of unbounded reference fields will warn. 3774 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); 3775 } 3776 3777 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 3778 if (E->getCastKind() == CK_LValueToRValue) { 3779 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3780 return; 3781 } 3782 3783 Inherited::VisitImplicitCastExpr(E); 3784 } 3785 3786 void VisitCXXConstructExpr(CXXConstructExpr *E) { 3787 if (E->getConstructor()->isCopyConstructor()) { 3788 Expr *ArgExpr = E->getArg(0); 3789 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 3790 if (ILE->getNumInits() == 1) 3791 ArgExpr = ILE->getInit(0); 3792 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 3793 if (ICE->getCastKind() == CK_NoOp) 3794 ArgExpr = ICE->getSubExpr(); 3795 HandleValue(ArgExpr, false /*AddressOf*/); 3796 return; 3797 } 3798 Inherited::VisitCXXConstructExpr(E); 3799 } 3800 3801 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 3802 Expr *Callee = E->getCallee(); 3803 if (isa<MemberExpr>(Callee)) { 3804 HandleValue(Callee, false /*AddressOf*/); 3805 for (auto Arg : E->arguments()) 3806 Visit(Arg); 3807 return; 3808 } 3809 3810 Inherited::VisitCXXMemberCallExpr(E); 3811 } 3812 3813 void VisitCallExpr(CallExpr *E) { 3814 // Treat std::move as a use. 3815 if (E->isCallToStdMove()) { 3816 HandleValue(E->getArg(0), /*AddressOf=*/false); 3817 return; 3818 } 3819 3820 Inherited::VisitCallExpr(E); 3821 } 3822 3823 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 3824 Expr *Callee = E->getCallee(); 3825 3826 if (isa<UnresolvedLookupExpr>(Callee)) 3827 return Inherited::VisitCXXOperatorCallExpr(E); 3828 3829 Visit(Callee); 3830 for (auto Arg : E->arguments()) 3831 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); 3832 } 3833 3834 void VisitBinaryOperator(BinaryOperator *E) { 3835 // If a field assignment is detected, remove the field from the 3836 // uninitiailized field set. 3837 if (E->getOpcode() == BO_Assign) 3838 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 3839 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 3840 if (!FD->getType()->isReferenceType()) 3841 DeclsToRemove.push_back(FD); 3842 3843 if (E->isCompoundAssignmentOp()) { 3844 HandleValue(E->getLHS(), false /*AddressOf*/); 3845 Visit(E->getRHS()); 3846 return; 3847 } 3848 3849 Inherited::VisitBinaryOperator(E); 3850 } 3851 3852 void VisitUnaryOperator(UnaryOperator *E) { 3853 if (E->isIncrementDecrementOp()) { 3854 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3855 return; 3856 } 3857 if (E->getOpcode() == UO_AddrOf) { 3858 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { 3859 HandleValue(ME->getBase(), true /*AddressOf*/); 3860 return; 3861 } 3862 } 3863 3864 Inherited::VisitUnaryOperator(E); 3865 } 3866 }; 3867 3868 // Diagnose value-uses of fields to initialize themselves, e.g. 3869 // foo(foo) 3870 // where foo is not also a parameter to the constructor. 3871 // Also diagnose across field uninitialized use such as 3872 // x(y), y(x) 3873 // TODO: implement -Wuninitialized and fold this into that framework. 3874 static void DiagnoseUninitializedFields( 3875 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 3876 3877 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 3878 Constructor->getLocation())) { 3879 return; 3880 } 3881 3882 if (Constructor->isInvalidDecl()) 3883 return; 3884 3885 const CXXRecordDecl *RD = Constructor->getParent(); 3886 3887 if (RD->isDependentContext()) 3888 return; 3889 3890 // Holds fields that are uninitialized. 3891 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 3892 3893 // At the beginning, all fields are uninitialized. 3894 for (auto *I : RD->decls()) { 3895 if (auto *FD = dyn_cast<FieldDecl>(I)) { 3896 UninitializedFields.insert(FD); 3897 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 3898 UninitializedFields.insert(IFD->getAnonField()); 3899 } 3900 } 3901 3902 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; 3903 for (auto I : RD->bases()) 3904 UninitializedBaseClasses.insert(I.getType().getCanonicalType()); 3905 3906 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3907 return; 3908 3909 UninitializedFieldVisitor UninitializedChecker(SemaRef, 3910 UninitializedFields, 3911 UninitializedBaseClasses); 3912 3913 for (const auto *FieldInit : Constructor->inits()) { 3914 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3915 break; 3916 3917 Expr *InitExpr = FieldInit->getInit(); 3918 if (!InitExpr) 3919 continue; 3920 3921 if (CXXDefaultInitExpr *Default = 3922 dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 3923 InitExpr = Default->getExpr(); 3924 if (!InitExpr) 3925 continue; 3926 // In class initializers will point to the constructor. 3927 UninitializedChecker.CheckInitializer(InitExpr, Constructor, 3928 FieldInit->getAnyMember(), 3929 FieldInit->getBaseClass()); 3930 } else { 3931 UninitializedChecker.CheckInitializer(InitExpr, nullptr, 3932 FieldInit->getAnyMember(), 3933 FieldInit->getBaseClass()); 3934 } 3935 } 3936 } 3937 } // namespace 3938 3939 /// Enter a new C++ default initializer scope. After calling this, the 3940 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 3941 /// parsing or instantiating the initializer failed. 3942 void Sema::ActOnStartCXXInClassMemberInitializer() { 3943 // Create a synthetic function scope to represent the call to the constructor 3944 // that notionally surrounds a use of this initializer. 3945 PushFunctionScope(); 3946 } 3947 3948 void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) { 3949 if (!D.isFunctionDeclarator()) 3950 return; 3951 auto &FTI = D.getFunctionTypeInfo(); 3952 if (!FTI.Params) 3953 return; 3954 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params, 3955 FTI.NumParams)) { 3956 auto *ParamDecl = cast<NamedDecl>(Param.Param); 3957 if (ParamDecl->getDeclName()) 3958 PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false); 3959 } 3960 } 3961 3962 ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) { 3963 return ActOnRequiresClause(ConstraintExpr); 3964 } 3965 3966 ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) { 3967 if (ConstraintExpr.isInvalid()) 3968 return ExprError(); 3969 3970 ConstraintExpr = CorrectDelayedTyposInExpr(ConstraintExpr); 3971 if (ConstraintExpr.isInvalid()) 3972 return ExprError(); 3973 3974 if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(), 3975 UPPC_RequiresClause)) 3976 return ExprError(); 3977 3978 return ConstraintExpr; 3979 } 3980 3981 /// This is invoked after parsing an in-class initializer for a 3982 /// non-static C++ class member, and after instantiating an in-class initializer 3983 /// in a class template. Such actions are deferred until the class is complete. 3984 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 3985 SourceLocation InitLoc, 3986 Expr *InitExpr) { 3987 // Pop the notional constructor scope we created earlier. 3988 PopFunctionScopeInfo(nullptr, D); 3989 3990 FieldDecl *FD = dyn_cast<FieldDecl>(D); 3991 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && 3992 "must set init style when field is created"); 3993 3994 if (!InitExpr) { 3995 D->setInvalidDecl(); 3996 if (FD) 3997 FD->removeInClassInitializer(); 3998 return; 3999 } 4000 4001 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 4002 FD->setInvalidDecl(); 4003 FD->removeInClassInitializer(); 4004 return; 4005 } 4006 4007 ExprResult Init = InitExpr; 4008 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 4009 InitializedEntity Entity = 4010 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD); 4011 InitializationKind Kind = 4012 FD->getInClassInitStyle() == ICIS_ListInit 4013 ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(), 4014 InitExpr->getBeginLoc(), 4015 InitExpr->getEndLoc()) 4016 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc); 4017 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 4018 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 4019 if (Init.isInvalid()) { 4020 FD->setInvalidDecl(); 4021 return; 4022 } 4023 } 4024 4025 // C++11 [class.base.init]p7: 4026 // The initialization of each base and member constitutes a 4027 // full-expression. 4028 Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false); 4029 if (Init.isInvalid()) { 4030 FD->setInvalidDecl(); 4031 return; 4032 } 4033 4034 InitExpr = Init.get(); 4035 4036 FD->setInClassInitializer(InitExpr); 4037 } 4038 4039 /// Find the direct and/or virtual base specifiers that 4040 /// correspond to the given base type, for use in base initialization 4041 /// within a constructor. 4042 static bool FindBaseInitializer(Sema &SemaRef, 4043 CXXRecordDecl *ClassDecl, 4044 QualType BaseType, 4045 const CXXBaseSpecifier *&DirectBaseSpec, 4046 const CXXBaseSpecifier *&VirtualBaseSpec) { 4047 // First, check for a direct base class. 4048 DirectBaseSpec = nullptr; 4049 for (const auto &Base : ClassDecl->bases()) { 4050 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 4051 // We found a direct base of this type. That's what we're 4052 // initializing. 4053 DirectBaseSpec = &Base; 4054 break; 4055 } 4056 } 4057 4058 // Check for a virtual base class. 4059 // FIXME: We might be able to short-circuit this if we know in advance that 4060 // there are no virtual bases. 4061 VirtualBaseSpec = nullptr; 4062 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 4063 // We haven't found a base yet; search the class hierarchy for a 4064 // virtual base class. 4065 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 4066 /*DetectVirtual=*/false); 4067 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(), 4068 SemaRef.Context.getTypeDeclType(ClassDecl), 4069 BaseType, Paths)) { 4070 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 4071 Path != Paths.end(); ++Path) { 4072 if (Path->back().Base->isVirtual()) { 4073 VirtualBaseSpec = Path->back().Base; 4074 break; 4075 } 4076 } 4077 } 4078 } 4079 4080 return DirectBaseSpec || VirtualBaseSpec; 4081 } 4082 4083 /// Handle a C++ member initializer using braced-init-list syntax. 4084 MemInitResult 4085 Sema::ActOnMemInitializer(Decl *ConstructorD, 4086 Scope *S, 4087 CXXScopeSpec &SS, 4088 IdentifierInfo *MemberOrBase, 4089 ParsedType TemplateTypeTy, 4090 const DeclSpec &DS, 4091 SourceLocation IdLoc, 4092 Expr *InitList, 4093 SourceLocation EllipsisLoc) { 4094 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 4095 DS, IdLoc, InitList, 4096 EllipsisLoc); 4097 } 4098 4099 /// Handle a C++ member initializer using parentheses syntax. 4100 MemInitResult 4101 Sema::ActOnMemInitializer(Decl *ConstructorD, 4102 Scope *S, 4103 CXXScopeSpec &SS, 4104 IdentifierInfo *MemberOrBase, 4105 ParsedType TemplateTypeTy, 4106 const DeclSpec &DS, 4107 SourceLocation IdLoc, 4108 SourceLocation LParenLoc, 4109 ArrayRef<Expr *> Args, 4110 SourceLocation RParenLoc, 4111 SourceLocation EllipsisLoc) { 4112 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc); 4113 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 4114 DS, IdLoc, List, EllipsisLoc); 4115 } 4116 4117 namespace { 4118 4119 // Callback to only accept typo corrections that can be a valid C++ member 4120 // initializer: either a non-static field member or a base class. 4121 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback { 4122 public: 4123 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 4124 : ClassDecl(ClassDecl) {} 4125 4126 bool ValidateCandidate(const TypoCorrection &candidate) override { 4127 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 4128 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 4129 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 4130 return isa<TypeDecl>(ND); 4131 } 4132 return false; 4133 } 4134 4135 std::unique_ptr<CorrectionCandidateCallback> clone() override { 4136 return std::make_unique<MemInitializerValidatorCCC>(*this); 4137 } 4138 4139 private: 4140 CXXRecordDecl *ClassDecl; 4141 }; 4142 4143 } 4144 4145 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, 4146 CXXScopeSpec &SS, 4147 ParsedType TemplateTypeTy, 4148 IdentifierInfo *MemberOrBase) { 4149 if (SS.getScopeRep() || TemplateTypeTy) 4150 return nullptr; 4151 for (auto *D : ClassDecl->lookup(MemberOrBase)) 4152 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) 4153 return cast<ValueDecl>(D); 4154 return nullptr; 4155 } 4156 4157 /// Handle a C++ member initializer. 4158 MemInitResult 4159 Sema::BuildMemInitializer(Decl *ConstructorD, 4160 Scope *S, 4161 CXXScopeSpec &SS, 4162 IdentifierInfo *MemberOrBase, 4163 ParsedType TemplateTypeTy, 4164 const DeclSpec &DS, 4165 SourceLocation IdLoc, 4166 Expr *Init, 4167 SourceLocation EllipsisLoc) { 4168 ExprResult Res = CorrectDelayedTyposInExpr(Init, /*InitDecl=*/nullptr, 4169 /*RecoverUncorrectedTypos=*/true); 4170 if (!Res.isUsable()) 4171 return true; 4172 Init = Res.get(); 4173 4174 if (!ConstructorD) 4175 return true; 4176 4177 AdjustDeclIfTemplate(ConstructorD); 4178 4179 CXXConstructorDecl *Constructor 4180 = dyn_cast<CXXConstructorDecl>(ConstructorD); 4181 if (!Constructor) { 4182 // The user wrote a constructor initializer on a function that is 4183 // not a C++ constructor. Ignore the error for now, because we may 4184 // have more member initializers coming; we'll diagnose it just 4185 // once in ActOnMemInitializers. 4186 return true; 4187 } 4188 4189 CXXRecordDecl *ClassDecl = Constructor->getParent(); 4190 4191 // C++ [class.base.init]p2: 4192 // Names in a mem-initializer-id are looked up in the scope of the 4193 // constructor's class and, if not found in that scope, are looked 4194 // up in the scope containing the constructor's definition. 4195 // [Note: if the constructor's class contains a member with the 4196 // same name as a direct or virtual base class of the class, a 4197 // mem-initializer-id naming the member or base class and composed 4198 // of a single identifier refers to the class member. A 4199 // mem-initializer-id for the hidden base class may be specified 4200 // using a qualified name. ] 4201 4202 // Look for a member, first. 4203 if (ValueDecl *Member = tryLookupCtorInitMemberDecl( 4204 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) { 4205 if (EllipsisLoc.isValid()) 4206 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 4207 << MemberOrBase 4208 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 4209 4210 return BuildMemberInitializer(Member, Init, IdLoc); 4211 } 4212 // It didn't name a member, so see if it names a class. 4213 QualType BaseType; 4214 TypeSourceInfo *TInfo = nullptr; 4215 4216 if (TemplateTypeTy) { 4217 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 4218 if (BaseType.isNull()) 4219 return true; 4220 } else if (DS.getTypeSpecType() == TST_decltype) { 4221 BaseType = BuildDecltypeType(DS.getRepAsExpr()); 4222 } else if (DS.getTypeSpecType() == TST_decltype_auto) { 4223 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); 4224 return true; 4225 } else { 4226 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 4227 LookupParsedName(R, S, &SS); 4228 4229 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 4230 if (!TyD) { 4231 if (R.isAmbiguous()) return true; 4232 4233 // We don't want access-control diagnostics here. 4234 R.suppressDiagnostics(); 4235 4236 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 4237 bool NotUnknownSpecialization = false; 4238 DeclContext *DC = computeDeclContext(SS, false); 4239 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 4240 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 4241 4242 if (!NotUnknownSpecialization) { 4243 // When the scope specifier can refer to a member of an unknown 4244 // specialization, we take it as a type name. 4245 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 4246 SS.getWithLocInContext(Context), 4247 *MemberOrBase, IdLoc); 4248 if (BaseType.isNull()) 4249 return true; 4250 4251 TInfo = Context.CreateTypeSourceInfo(BaseType); 4252 DependentNameTypeLoc TL = 4253 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>(); 4254 if (!TL.isNull()) { 4255 TL.setNameLoc(IdLoc); 4256 TL.setElaboratedKeywordLoc(SourceLocation()); 4257 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4258 } 4259 4260 R.clear(); 4261 R.setLookupName(MemberOrBase); 4262 } 4263 } 4264 4265 // If no results were found, try to correct typos. 4266 TypoCorrection Corr; 4267 MemInitializerValidatorCCC CCC(ClassDecl); 4268 if (R.empty() && BaseType.isNull() && 4269 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 4270 CCC, CTK_ErrorRecovery, ClassDecl))) { 4271 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 4272 // We have found a non-static data member with a similar 4273 // name to what was typed; complain and initialize that 4274 // member. 4275 diagnoseTypo(Corr, 4276 PDiag(diag::err_mem_init_not_member_or_class_suggest) 4277 << MemberOrBase << true); 4278 return BuildMemberInitializer(Member, Init, IdLoc); 4279 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 4280 const CXXBaseSpecifier *DirectBaseSpec; 4281 const CXXBaseSpecifier *VirtualBaseSpec; 4282 if (FindBaseInitializer(*this, ClassDecl, 4283 Context.getTypeDeclType(Type), 4284 DirectBaseSpec, VirtualBaseSpec)) { 4285 // We have found a direct or virtual base class with a 4286 // similar name to what was typed; complain and initialize 4287 // that base class. 4288 diagnoseTypo(Corr, 4289 PDiag(diag::err_mem_init_not_member_or_class_suggest) 4290 << MemberOrBase << false, 4291 PDiag() /*Suppress note, we provide our own.*/); 4292 4293 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 4294 : VirtualBaseSpec; 4295 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here) 4296 << BaseSpec->getType() << BaseSpec->getSourceRange(); 4297 4298 TyD = Type; 4299 } 4300 } 4301 } 4302 4303 if (!TyD && BaseType.isNull()) { 4304 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 4305 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 4306 return true; 4307 } 4308 } 4309 4310 if (BaseType.isNull()) { 4311 BaseType = Context.getTypeDeclType(TyD); 4312 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); 4313 if (SS.isSet()) { 4314 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 4315 BaseType); 4316 TInfo = Context.CreateTypeSourceInfo(BaseType); 4317 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>(); 4318 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc); 4319 TL.setElaboratedKeywordLoc(SourceLocation()); 4320 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4321 } 4322 } 4323 } 4324 4325 if (!TInfo) 4326 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 4327 4328 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 4329 } 4330 4331 MemInitResult 4332 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 4333 SourceLocation IdLoc) { 4334 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 4335 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 4336 assert((DirectMember || IndirectMember) && 4337 "Member must be a FieldDecl or IndirectFieldDecl"); 4338 4339 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4340 return true; 4341 4342 if (Member->isInvalidDecl()) 4343 return true; 4344 4345 MultiExprArg Args; 4346 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4347 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4348 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 4349 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 4350 } else { 4351 // Template instantiation doesn't reconstruct ParenListExprs for us. 4352 Args = Init; 4353 } 4354 4355 SourceRange InitRange = Init->getSourceRange(); 4356 4357 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 4358 // Can't check initialization for a member of dependent type or when 4359 // any of the arguments are type-dependent expressions. 4360 DiscardCleanupsInEvaluationContext(); 4361 } else { 4362 bool InitList = false; 4363 if (isa<InitListExpr>(Init)) { 4364 InitList = true; 4365 Args = Init; 4366 } 4367 4368 // Initialize the member. 4369 InitializedEntity MemberEntity = 4370 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 4371 : InitializedEntity::InitializeMember(IndirectMember, 4372 nullptr); 4373 InitializationKind Kind = 4374 InitList ? InitializationKind::CreateDirectList( 4375 IdLoc, Init->getBeginLoc(), Init->getEndLoc()) 4376 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 4377 InitRange.getEnd()); 4378 4379 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 4380 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 4381 nullptr); 4382 if (!MemberInit.isInvalid()) { 4383 // C++11 [class.base.init]p7: 4384 // The initialization of each base and member constitutes a 4385 // full-expression. 4386 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(), 4387 /*DiscardedValue*/ false); 4388 } 4389 4390 if (MemberInit.isInvalid()) { 4391 // Args were sensible expressions but we couldn't initialize the member 4392 // from them. Preserve them in a RecoveryExpr instead. 4393 Init = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args, 4394 Member->getType()) 4395 .get(); 4396 if (!Init) 4397 return true; 4398 } else { 4399 Init = MemberInit.get(); 4400 } 4401 } 4402 4403 if (DirectMember) { 4404 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 4405 InitRange.getBegin(), Init, 4406 InitRange.getEnd()); 4407 } else { 4408 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 4409 InitRange.getBegin(), Init, 4410 InitRange.getEnd()); 4411 } 4412 } 4413 4414 MemInitResult 4415 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 4416 CXXRecordDecl *ClassDecl) { 4417 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4418 if (!LangOpts.CPlusPlus11) 4419 return Diag(NameLoc, diag::err_delegating_ctor) 4420 << TInfo->getTypeLoc().getLocalSourceRange(); 4421 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 4422 4423 bool InitList = true; 4424 MultiExprArg Args = Init; 4425 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4426 InitList = false; 4427 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4428 } 4429 4430 SourceRange InitRange = Init->getSourceRange(); 4431 // Initialize the object. 4432 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 4433 QualType(ClassDecl->getTypeForDecl(), 0)); 4434 InitializationKind Kind = 4435 InitList ? InitializationKind::CreateDirectList( 4436 NameLoc, Init->getBeginLoc(), Init->getEndLoc()) 4437 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 4438 InitRange.getEnd()); 4439 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 4440 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 4441 Args, nullptr); 4442 if (!DelegationInit.isInvalid()) { 4443 assert((DelegationInit.get()->containsErrors() || 4444 cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) && 4445 "Delegating constructor with no target?"); 4446 4447 // C++11 [class.base.init]p7: 4448 // The initialization of each base and member constitutes a 4449 // full-expression. 4450 DelegationInit = ActOnFinishFullExpr( 4451 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false); 4452 } 4453 4454 if (DelegationInit.isInvalid()) { 4455 DelegationInit = 4456 CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args, 4457 QualType(ClassDecl->getTypeForDecl(), 0)); 4458 if (DelegationInit.isInvalid()) 4459 return true; 4460 } else { 4461 // If we are in a dependent context, template instantiation will 4462 // perform this type-checking again. Just save the arguments that we 4463 // received in a ParenListExpr. 4464 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4465 // of the information that we have about the base 4466 // initializer. However, deconstructing the ASTs is a dicey process, 4467 // and this approach is far more likely to get the corner cases right. 4468 if (CurContext->isDependentContext()) 4469 DelegationInit = Init; 4470 } 4471 4472 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 4473 DelegationInit.getAs<Expr>(), 4474 InitRange.getEnd()); 4475 } 4476 4477 MemInitResult 4478 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 4479 Expr *Init, CXXRecordDecl *ClassDecl, 4480 SourceLocation EllipsisLoc) { 4481 SourceLocation BaseLoc 4482 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4483 4484 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 4485 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 4486 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4487 4488 // C++ [class.base.init]p2: 4489 // [...] Unless the mem-initializer-id names a nonstatic data 4490 // member of the constructor's class or a direct or virtual base 4491 // of that class, the mem-initializer is ill-formed. A 4492 // mem-initializer-list can initialize a base class using any 4493 // name that denotes that base class type. 4494 4495 // We can store the initializers in "as-written" form and delay analysis until 4496 // instantiation if the constructor is dependent. But not for dependent 4497 // (broken) code in a non-template! SetCtorInitializers does not expect this. 4498 bool Dependent = CurContext->isDependentContext() && 4499 (BaseType->isDependentType() || Init->isTypeDependent()); 4500 4501 SourceRange InitRange = Init->getSourceRange(); 4502 if (EllipsisLoc.isValid()) { 4503 // This is a pack expansion. 4504 if (!BaseType->containsUnexpandedParameterPack()) { 4505 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 4506 << SourceRange(BaseLoc, InitRange.getEnd()); 4507 4508 EllipsisLoc = SourceLocation(); 4509 } 4510 } else { 4511 // Check for any unexpanded parameter packs. 4512 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 4513 return true; 4514 4515 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4516 return true; 4517 } 4518 4519 // Check for direct and virtual base classes. 4520 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 4521 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 4522 if (!Dependent) { 4523 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 4524 BaseType)) 4525 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 4526 4527 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 4528 VirtualBaseSpec); 4529 4530 // C++ [base.class.init]p2: 4531 // Unless the mem-initializer-id names a nonstatic data member of the 4532 // constructor's class or a direct or virtual base of that class, the 4533 // mem-initializer is ill-formed. 4534 if (!DirectBaseSpec && !VirtualBaseSpec) { 4535 // If the class has any dependent bases, then it's possible that 4536 // one of those types will resolve to the same type as 4537 // BaseType. Therefore, just treat this as a dependent base 4538 // class initialization. FIXME: Should we try to check the 4539 // initialization anyway? It seems odd. 4540 if (ClassDecl->hasAnyDependentBases()) 4541 Dependent = true; 4542 else 4543 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 4544 << BaseType << Context.getTypeDeclType(ClassDecl) 4545 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4546 } 4547 } 4548 4549 if (Dependent) { 4550 DiscardCleanupsInEvaluationContext(); 4551 4552 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4553 /*IsVirtual=*/false, 4554 InitRange.getBegin(), Init, 4555 InitRange.getEnd(), EllipsisLoc); 4556 } 4557 4558 // C++ [base.class.init]p2: 4559 // If a mem-initializer-id is ambiguous because it designates both 4560 // a direct non-virtual base class and an inherited virtual base 4561 // class, the mem-initializer is ill-formed. 4562 if (DirectBaseSpec && VirtualBaseSpec) 4563 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 4564 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4565 4566 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 4567 if (!BaseSpec) 4568 BaseSpec = VirtualBaseSpec; 4569 4570 // Initialize the base. 4571 bool InitList = true; 4572 MultiExprArg Args = Init; 4573 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4574 InitList = false; 4575 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4576 } 4577 4578 InitializedEntity BaseEntity = 4579 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 4580 InitializationKind Kind = 4581 InitList ? InitializationKind::CreateDirectList(BaseLoc) 4582 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 4583 InitRange.getEnd()); 4584 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 4585 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 4586 if (!BaseInit.isInvalid()) { 4587 // C++11 [class.base.init]p7: 4588 // The initialization of each base and member constitutes a 4589 // full-expression. 4590 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(), 4591 /*DiscardedValue*/ false); 4592 } 4593 4594 if (BaseInit.isInvalid()) { 4595 BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), 4596 Args, BaseType); 4597 if (BaseInit.isInvalid()) 4598 return true; 4599 } else { 4600 // If we are in a dependent context, template instantiation will 4601 // perform this type-checking again. Just save the arguments that we 4602 // received in a ParenListExpr. 4603 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4604 // of the information that we have about the base 4605 // initializer. However, deconstructing the ASTs is a dicey process, 4606 // and this approach is far more likely to get the corner cases right. 4607 if (CurContext->isDependentContext()) 4608 BaseInit = Init; 4609 } 4610 4611 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4612 BaseSpec->isVirtual(), 4613 InitRange.getBegin(), 4614 BaseInit.getAs<Expr>(), 4615 InitRange.getEnd(), EllipsisLoc); 4616 } 4617 4618 // Create a static_cast\<T&&>(expr). 4619 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 4620 if (T.isNull()) T = E->getType(); 4621 QualType TargetType = SemaRef.BuildReferenceType( 4622 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 4623 SourceLocation ExprLoc = E->getBeginLoc(); 4624 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 4625 TargetType, ExprLoc); 4626 4627 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 4628 SourceRange(ExprLoc, ExprLoc), 4629 E->getSourceRange()).get(); 4630 } 4631 4632 /// ImplicitInitializerKind - How an implicit base or member initializer should 4633 /// initialize its base or member. 4634 enum ImplicitInitializerKind { 4635 IIK_Default, 4636 IIK_Copy, 4637 IIK_Move, 4638 IIK_Inherit 4639 }; 4640 4641 static bool 4642 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4643 ImplicitInitializerKind ImplicitInitKind, 4644 CXXBaseSpecifier *BaseSpec, 4645 bool IsInheritedVirtualBase, 4646 CXXCtorInitializer *&CXXBaseInit) { 4647 InitializedEntity InitEntity 4648 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 4649 IsInheritedVirtualBase); 4650 4651 ExprResult BaseInit; 4652 4653 switch (ImplicitInitKind) { 4654 case IIK_Inherit: 4655 case IIK_Default: { 4656 InitializationKind InitKind 4657 = InitializationKind::CreateDefault(Constructor->getLocation()); 4658 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4659 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4660 break; 4661 } 4662 4663 case IIK_Move: 4664 case IIK_Copy: { 4665 bool Moving = ImplicitInitKind == IIK_Move; 4666 ParmVarDecl *Param = Constructor->getParamDecl(0); 4667 QualType ParamType = Param->getType().getNonReferenceType(); 4668 4669 Expr *CopyCtorArg = 4670 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4671 SourceLocation(), Param, false, 4672 Constructor->getLocation(), ParamType, 4673 VK_LValue, nullptr); 4674 4675 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 4676 4677 // Cast to the base class to avoid ambiguities. 4678 QualType ArgTy = 4679 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 4680 ParamType.getQualifiers()); 4681 4682 if (Moving) { 4683 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 4684 } 4685 4686 CXXCastPath BasePath; 4687 BasePath.push_back(BaseSpec); 4688 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 4689 CK_UncheckedDerivedToBase, 4690 Moving ? VK_XValue : VK_LValue, 4691 &BasePath).get(); 4692 4693 InitializationKind InitKind 4694 = InitializationKind::CreateDirect(Constructor->getLocation(), 4695 SourceLocation(), SourceLocation()); 4696 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 4697 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 4698 break; 4699 } 4700 } 4701 4702 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 4703 if (BaseInit.isInvalid()) 4704 return true; 4705 4706 CXXBaseInit = 4707 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4708 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 4709 SourceLocation()), 4710 BaseSpec->isVirtual(), 4711 SourceLocation(), 4712 BaseInit.getAs<Expr>(), 4713 SourceLocation(), 4714 SourceLocation()); 4715 4716 return false; 4717 } 4718 4719 static bool RefersToRValueRef(Expr *MemRef) { 4720 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 4721 return Referenced->getType()->isRValueReferenceType(); 4722 } 4723 4724 static bool 4725 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4726 ImplicitInitializerKind ImplicitInitKind, 4727 FieldDecl *Field, IndirectFieldDecl *Indirect, 4728 CXXCtorInitializer *&CXXMemberInit) { 4729 if (Field->isInvalidDecl()) 4730 return true; 4731 4732 SourceLocation Loc = Constructor->getLocation(); 4733 4734 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 4735 bool Moving = ImplicitInitKind == IIK_Move; 4736 ParmVarDecl *Param = Constructor->getParamDecl(0); 4737 QualType ParamType = Param->getType().getNonReferenceType(); 4738 4739 // Suppress copying zero-width bitfields. 4740 if (Field->isZeroLengthBitField(SemaRef.Context)) 4741 return false; 4742 4743 Expr *MemberExprBase = 4744 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4745 SourceLocation(), Param, false, 4746 Loc, ParamType, VK_LValue, nullptr); 4747 4748 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 4749 4750 if (Moving) { 4751 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 4752 } 4753 4754 // Build a reference to this field within the parameter. 4755 CXXScopeSpec SS; 4756 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 4757 Sema::LookupMemberName); 4758 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 4759 : cast<ValueDecl>(Field), AS_public); 4760 MemberLookup.resolveKind(); 4761 ExprResult CtorArg 4762 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 4763 ParamType, Loc, 4764 /*IsArrow=*/false, 4765 SS, 4766 /*TemplateKWLoc=*/SourceLocation(), 4767 /*FirstQualifierInScope=*/nullptr, 4768 MemberLookup, 4769 /*TemplateArgs=*/nullptr, 4770 /*S*/nullptr); 4771 if (CtorArg.isInvalid()) 4772 return true; 4773 4774 // C++11 [class.copy]p15: 4775 // - if a member m has rvalue reference type T&&, it is direct-initialized 4776 // with static_cast<T&&>(x.m); 4777 if (RefersToRValueRef(CtorArg.get())) { 4778 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 4779 } 4780 4781 InitializedEntity Entity = 4782 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4783 /*Implicit*/ true) 4784 : InitializedEntity::InitializeMember(Field, nullptr, 4785 /*Implicit*/ true); 4786 4787 // Direct-initialize to use the copy constructor. 4788 InitializationKind InitKind = 4789 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 4790 4791 Expr *CtorArgE = CtorArg.getAs<Expr>(); 4792 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE); 4793 ExprResult MemberInit = 4794 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1)); 4795 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4796 if (MemberInit.isInvalid()) 4797 return true; 4798 4799 if (Indirect) 4800 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4801 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4802 else 4803 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4804 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4805 return false; 4806 } 4807 4808 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 4809 "Unhandled implicit init kind!"); 4810 4811 QualType FieldBaseElementType = 4812 SemaRef.Context.getBaseElementType(Field->getType()); 4813 4814 if (FieldBaseElementType->isRecordType()) { 4815 InitializedEntity InitEntity = 4816 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4817 /*Implicit*/ true) 4818 : InitializedEntity::InitializeMember(Field, nullptr, 4819 /*Implicit*/ true); 4820 InitializationKind InitKind = 4821 InitializationKind::CreateDefault(Loc); 4822 4823 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4824 ExprResult MemberInit = 4825 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4826 4827 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4828 if (MemberInit.isInvalid()) 4829 return true; 4830 4831 if (Indirect) 4832 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4833 Indirect, Loc, 4834 Loc, 4835 MemberInit.get(), 4836 Loc); 4837 else 4838 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4839 Field, Loc, Loc, 4840 MemberInit.get(), 4841 Loc); 4842 return false; 4843 } 4844 4845 if (!Field->getParent()->isUnion()) { 4846 if (FieldBaseElementType->isReferenceType()) { 4847 SemaRef.Diag(Constructor->getLocation(), 4848 diag::err_uninitialized_member_in_ctor) 4849 << (int)Constructor->isImplicit() 4850 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4851 << 0 << Field->getDeclName(); 4852 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4853 return true; 4854 } 4855 4856 if (FieldBaseElementType.isConstQualified()) { 4857 SemaRef.Diag(Constructor->getLocation(), 4858 diag::err_uninitialized_member_in_ctor) 4859 << (int)Constructor->isImplicit() 4860 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4861 << 1 << Field->getDeclName(); 4862 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4863 return true; 4864 } 4865 } 4866 4867 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) { 4868 // ARC and Weak: 4869 // Default-initialize Objective-C pointers to NULL. 4870 CXXMemberInit 4871 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 4872 Loc, Loc, 4873 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 4874 Loc); 4875 return false; 4876 } 4877 4878 // Nothing to initialize. 4879 CXXMemberInit = nullptr; 4880 return false; 4881 } 4882 4883 namespace { 4884 struct BaseAndFieldInfo { 4885 Sema &S; 4886 CXXConstructorDecl *Ctor; 4887 bool AnyErrorsInInits; 4888 ImplicitInitializerKind IIK; 4889 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 4890 SmallVector<CXXCtorInitializer*, 8> AllToInit; 4891 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 4892 4893 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 4894 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 4895 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 4896 if (Ctor->getInheritedConstructor()) 4897 IIK = IIK_Inherit; 4898 else if (Generated && Ctor->isCopyConstructor()) 4899 IIK = IIK_Copy; 4900 else if (Generated && Ctor->isMoveConstructor()) 4901 IIK = IIK_Move; 4902 else 4903 IIK = IIK_Default; 4904 } 4905 4906 bool isImplicitCopyOrMove() const { 4907 switch (IIK) { 4908 case IIK_Copy: 4909 case IIK_Move: 4910 return true; 4911 4912 case IIK_Default: 4913 case IIK_Inherit: 4914 return false; 4915 } 4916 4917 llvm_unreachable("Invalid ImplicitInitializerKind!"); 4918 } 4919 4920 bool addFieldInitializer(CXXCtorInitializer *Init) { 4921 AllToInit.push_back(Init); 4922 4923 // Check whether this initializer makes the field "used". 4924 if (Init->getInit()->HasSideEffects(S.Context)) 4925 S.UnusedPrivateFields.remove(Init->getAnyMember()); 4926 4927 return false; 4928 } 4929 4930 bool isInactiveUnionMember(FieldDecl *Field) { 4931 RecordDecl *Record = Field->getParent(); 4932 if (!Record->isUnion()) 4933 return false; 4934 4935 if (FieldDecl *Active = 4936 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 4937 return Active != Field->getCanonicalDecl(); 4938 4939 // In an implicit copy or move constructor, ignore any in-class initializer. 4940 if (isImplicitCopyOrMove()) 4941 return true; 4942 4943 // If there's no explicit initialization, the field is active only if it 4944 // has an in-class initializer... 4945 if (Field->hasInClassInitializer()) 4946 return false; 4947 // ... or it's an anonymous struct or union whose class has an in-class 4948 // initializer. 4949 if (!Field->isAnonymousStructOrUnion()) 4950 return true; 4951 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 4952 return !FieldRD->hasInClassInitializer(); 4953 } 4954 4955 /// Determine whether the given field is, or is within, a union member 4956 /// that is inactive (because there was an initializer given for a different 4957 /// member of the union, or because the union was not initialized at all). 4958 bool isWithinInactiveUnionMember(FieldDecl *Field, 4959 IndirectFieldDecl *Indirect) { 4960 if (!Indirect) 4961 return isInactiveUnionMember(Field); 4962 4963 for (auto *C : Indirect->chain()) { 4964 FieldDecl *Field = dyn_cast<FieldDecl>(C); 4965 if (Field && isInactiveUnionMember(Field)) 4966 return true; 4967 } 4968 return false; 4969 } 4970 }; 4971 } 4972 4973 /// Determine whether the given type is an incomplete or zero-lenfgth 4974 /// array type. 4975 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 4976 if (T->isIncompleteArrayType()) 4977 return true; 4978 4979 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 4980 if (!ArrayT->getSize()) 4981 return true; 4982 4983 T = ArrayT->getElementType(); 4984 } 4985 4986 return false; 4987 } 4988 4989 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 4990 FieldDecl *Field, 4991 IndirectFieldDecl *Indirect = nullptr) { 4992 if (Field->isInvalidDecl()) 4993 return false; 4994 4995 // Overwhelmingly common case: we have a direct initializer for this field. 4996 if (CXXCtorInitializer *Init = 4997 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 4998 return Info.addFieldInitializer(Init); 4999 5000 // C++11 [class.base.init]p8: 5001 // if the entity is a non-static data member that has a 5002 // brace-or-equal-initializer and either 5003 // -- the constructor's class is a union and no other variant member of that 5004 // union is designated by a mem-initializer-id or 5005 // -- the constructor's class is not a union, and, if the entity is a member 5006 // of an anonymous union, no other member of that union is designated by 5007 // a mem-initializer-id, 5008 // the entity is initialized as specified in [dcl.init]. 5009 // 5010 // We also apply the same rules to handle anonymous structs within anonymous 5011 // unions. 5012 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 5013 return false; 5014 5015 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 5016 ExprResult DIE = 5017 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); 5018 if (DIE.isInvalid()) 5019 return true; 5020 5021 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true); 5022 SemaRef.checkInitializerLifetime(Entity, DIE.get()); 5023 5024 CXXCtorInitializer *Init; 5025 if (Indirect) 5026 Init = new (SemaRef.Context) 5027 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), 5028 SourceLocation(), DIE.get(), SourceLocation()); 5029 else 5030 Init = new (SemaRef.Context) 5031 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), 5032 SourceLocation(), DIE.get(), SourceLocation()); 5033 return Info.addFieldInitializer(Init); 5034 } 5035 5036 // Don't initialize incomplete or zero-length arrays. 5037 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 5038 return false; 5039 5040 // Don't try to build an implicit initializer if there were semantic 5041 // errors in any of the initializers (and therefore we might be 5042 // missing some that the user actually wrote). 5043 if (Info.AnyErrorsInInits) 5044 return false; 5045 5046 CXXCtorInitializer *Init = nullptr; 5047 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 5048 Indirect, Init)) 5049 return true; 5050 5051 if (!Init) 5052 return false; 5053 5054 return Info.addFieldInitializer(Init); 5055 } 5056 5057 bool 5058 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 5059 CXXCtorInitializer *Initializer) { 5060 assert(Initializer->isDelegatingInitializer()); 5061 Constructor->setNumCtorInitializers(1); 5062 CXXCtorInitializer **initializer = 5063 new (Context) CXXCtorInitializer*[1]; 5064 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 5065 Constructor->setCtorInitializers(initializer); 5066 5067 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 5068 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 5069 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 5070 } 5071 5072 DelegatingCtorDecls.push_back(Constructor); 5073 5074 DiagnoseUninitializedFields(*this, Constructor); 5075 5076 return false; 5077 } 5078 5079 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 5080 ArrayRef<CXXCtorInitializer *> Initializers) { 5081 if (Constructor->isDependentContext()) { 5082 // Just store the initializers as written, they will be checked during 5083 // instantiation. 5084 if (!Initializers.empty()) { 5085 Constructor->setNumCtorInitializers(Initializers.size()); 5086 CXXCtorInitializer **baseOrMemberInitializers = 5087 new (Context) CXXCtorInitializer*[Initializers.size()]; 5088 memcpy(baseOrMemberInitializers, Initializers.data(), 5089 Initializers.size() * sizeof(CXXCtorInitializer*)); 5090 Constructor->setCtorInitializers(baseOrMemberInitializers); 5091 } 5092 5093 // Let template instantiation know whether we had errors. 5094 if (AnyErrors) 5095 Constructor->setInvalidDecl(); 5096 5097 return false; 5098 } 5099 5100 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 5101 5102 // We need to build the initializer AST according to order of construction 5103 // and not what user specified in the Initializers list. 5104 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 5105 if (!ClassDecl) 5106 return true; 5107 5108 bool HadError = false; 5109 5110 for (unsigned i = 0; i < Initializers.size(); i++) { 5111 CXXCtorInitializer *Member = Initializers[i]; 5112 5113 if (Member->isBaseInitializer()) 5114 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 5115 else { 5116 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 5117 5118 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 5119 for (auto *C : F->chain()) { 5120 FieldDecl *FD = dyn_cast<FieldDecl>(C); 5121 if (FD && FD->getParent()->isUnion()) 5122 Info.ActiveUnionMember.insert(std::make_pair( 5123 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 5124 } 5125 } else if (FieldDecl *FD = Member->getMember()) { 5126 if (FD->getParent()->isUnion()) 5127 Info.ActiveUnionMember.insert(std::make_pair( 5128 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 5129 } 5130 } 5131 } 5132 5133 // Keep track of the direct virtual bases. 5134 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 5135 for (auto &I : ClassDecl->bases()) { 5136 if (I.isVirtual()) 5137 DirectVBases.insert(&I); 5138 } 5139 5140 // Push virtual bases before others. 5141 for (auto &VBase : ClassDecl->vbases()) { 5142 if (CXXCtorInitializer *Value 5143 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 5144 // [class.base.init]p7, per DR257: 5145 // A mem-initializer where the mem-initializer-id names a virtual base 5146 // class is ignored during execution of a constructor of any class that 5147 // is not the most derived class. 5148 if (ClassDecl->isAbstract()) { 5149 // FIXME: Provide a fixit to remove the base specifier. This requires 5150 // tracking the location of the associated comma for a base specifier. 5151 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 5152 << VBase.getType() << ClassDecl; 5153 DiagnoseAbstractType(ClassDecl); 5154 } 5155 5156 Info.AllToInit.push_back(Value); 5157 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 5158 // [class.base.init]p8, per DR257: 5159 // If a given [...] base class is not named by a mem-initializer-id 5160 // [...] and the entity is not a virtual base class of an abstract 5161 // class, then [...] the entity is default-initialized. 5162 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 5163 CXXCtorInitializer *CXXBaseInit; 5164 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 5165 &VBase, IsInheritedVirtualBase, 5166 CXXBaseInit)) { 5167 HadError = true; 5168 continue; 5169 } 5170 5171 Info.AllToInit.push_back(CXXBaseInit); 5172 } 5173 } 5174 5175 // Non-virtual bases. 5176 for (auto &Base : ClassDecl->bases()) { 5177 // Virtuals are in the virtual base list and already constructed. 5178 if (Base.isVirtual()) 5179 continue; 5180 5181 if (CXXCtorInitializer *Value 5182 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 5183 Info.AllToInit.push_back(Value); 5184 } else if (!AnyErrors) { 5185 CXXCtorInitializer *CXXBaseInit; 5186 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 5187 &Base, /*IsInheritedVirtualBase=*/false, 5188 CXXBaseInit)) { 5189 HadError = true; 5190 continue; 5191 } 5192 5193 Info.AllToInit.push_back(CXXBaseInit); 5194 } 5195 } 5196 5197 // Fields. 5198 for (auto *Mem : ClassDecl->decls()) { 5199 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 5200 // C++ [class.bit]p2: 5201 // A declaration for a bit-field that omits the identifier declares an 5202 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 5203 // initialized. 5204 if (F->isUnnamedBitfield()) 5205 continue; 5206 5207 // If we're not generating the implicit copy/move constructor, then we'll 5208 // handle anonymous struct/union fields based on their individual 5209 // indirect fields. 5210 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 5211 continue; 5212 5213 if (CollectFieldInitializer(*this, Info, F)) 5214 HadError = true; 5215 continue; 5216 } 5217 5218 // Beyond this point, we only consider default initialization. 5219 if (Info.isImplicitCopyOrMove()) 5220 continue; 5221 5222 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 5223 if (F->getType()->isIncompleteArrayType()) { 5224 assert(ClassDecl->hasFlexibleArrayMember() && 5225 "Incomplete array type is not valid"); 5226 continue; 5227 } 5228 5229 // Initialize each field of an anonymous struct individually. 5230 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 5231 HadError = true; 5232 5233 continue; 5234 } 5235 } 5236 5237 unsigned NumInitializers = Info.AllToInit.size(); 5238 if (NumInitializers > 0) { 5239 Constructor->setNumCtorInitializers(NumInitializers); 5240 CXXCtorInitializer **baseOrMemberInitializers = 5241 new (Context) CXXCtorInitializer*[NumInitializers]; 5242 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 5243 NumInitializers * sizeof(CXXCtorInitializer*)); 5244 Constructor->setCtorInitializers(baseOrMemberInitializers); 5245 5246 // Constructors implicitly reference the base and member 5247 // destructors. 5248 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 5249 Constructor->getParent()); 5250 } 5251 5252 return HadError; 5253 } 5254 5255 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 5256 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 5257 const RecordDecl *RD = RT->getDecl(); 5258 if (RD->isAnonymousStructOrUnion()) { 5259 for (auto *Field : RD->fields()) 5260 PopulateKeysForFields(Field, IdealInits); 5261 return; 5262 } 5263 } 5264 IdealInits.push_back(Field->getCanonicalDecl()); 5265 } 5266 5267 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 5268 return Context.getCanonicalType(BaseType).getTypePtr(); 5269 } 5270 5271 static const void *GetKeyForMember(ASTContext &Context, 5272 CXXCtorInitializer *Member) { 5273 if (!Member->isAnyMemberInitializer()) 5274 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 5275 5276 return Member->getAnyMember()->getCanonicalDecl(); 5277 } 5278 5279 static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag, 5280 const CXXCtorInitializer *Previous, 5281 const CXXCtorInitializer *Current) { 5282 if (Previous->isAnyMemberInitializer()) 5283 Diag << 0 << Previous->getAnyMember(); 5284 else 5285 Diag << 1 << Previous->getTypeSourceInfo()->getType(); 5286 5287 if (Current->isAnyMemberInitializer()) 5288 Diag << 0 << Current->getAnyMember(); 5289 else 5290 Diag << 1 << Current->getTypeSourceInfo()->getType(); 5291 } 5292 5293 static void DiagnoseBaseOrMemInitializerOrder( 5294 Sema &SemaRef, const CXXConstructorDecl *Constructor, 5295 ArrayRef<CXXCtorInitializer *> Inits) { 5296 if (Constructor->getDeclContext()->isDependentContext()) 5297 return; 5298 5299 // Don't check initializers order unless the warning is enabled at the 5300 // location of at least one initializer. 5301 bool ShouldCheckOrder = false; 5302 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 5303 CXXCtorInitializer *Init = Inits[InitIndex]; 5304 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 5305 Init->getSourceLocation())) { 5306 ShouldCheckOrder = true; 5307 break; 5308 } 5309 } 5310 if (!ShouldCheckOrder) 5311 return; 5312 5313 // Build the list of bases and members in the order that they'll 5314 // actually be initialized. The explicit initializers should be in 5315 // this same order but may be missing things. 5316 SmallVector<const void*, 32> IdealInitKeys; 5317 5318 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 5319 5320 // 1. Virtual bases. 5321 for (const auto &VBase : ClassDecl->vbases()) 5322 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 5323 5324 // 2. Non-virtual bases. 5325 for (const auto &Base : ClassDecl->bases()) { 5326 if (Base.isVirtual()) 5327 continue; 5328 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 5329 } 5330 5331 // 3. Direct fields. 5332 for (auto *Field : ClassDecl->fields()) { 5333 if (Field->isUnnamedBitfield()) 5334 continue; 5335 5336 PopulateKeysForFields(Field, IdealInitKeys); 5337 } 5338 5339 unsigned NumIdealInits = IdealInitKeys.size(); 5340 unsigned IdealIndex = 0; 5341 5342 // Track initializers that are in an incorrect order for either a warning or 5343 // note if multiple ones occur. 5344 SmallVector<unsigned> WarnIndexes; 5345 // Correlates the index of an initializer in the init-list to the index of 5346 // the field/base in the class. 5347 SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder; 5348 5349 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 5350 const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]); 5351 5352 // Scan forward to try to find this initializer in the idealized 5353 // initializers list. 5354 for (; IdealIndex != NumIdealInits; ++IdealIndex) 5355 if (InitKey == IdealInitKeys[IdealIndex]) 5356 break; 5357 5358 // If we didn't find this initializer, it must be because we 5359 // scanned past it on a previous iteration. That can only 5360 // happen if we're out of order; emit a warning. 5361 if (IdealIndex == NumIdealInits && InitIndex) { 5362 WarnIndexes.push_back(InitIndex); 5363 5364 // Move back to the initializer's location in the ideal list. 5365 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 5366 if (InitKey == IdealInitKeys[IdealIndex]) 5367 break; 5368 5369 assert(IdealIndex < NumIdealInits && 5370 "initializer not found in initializer list"); 5371 } 5372 CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex); 5373 } 5374 5375 if (WarnIndexes.empty()) 5376 return; 5377 5378 // Sort based on the ideal order, first in the pair. 5379 llvm::sort(CorrelatedInitOrder, 5380 [](auto &LHS, auto &RHS) { return LHS.first < RHS.first; }); 5381 5382 // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to 5383 // emit the diagnostic before we can try adding notes. 5384 { 5385 Sema::SemaDiagnosticBuilder D = SemaRef.Diag( 5386 Inits[WarnIndexes.front() - 1]->getSourceLocation(), 5387 WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order 5388 : diag::warn_some_initializers_out_of_order); 5389 5390 for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) { 5391 if (CorrelatedInitOrder[I].second == I) 5392 continue; 5393 // Ideally we would be using InsertFromRange here, but clang doesn't 5394 // appear to handle InsertFromRange correctly when the source range is 5395 // modified by another fix-it. 5396 D << FixItHint::CreateReplacement( 5397 Inits[I]->getSourceRange(), 5398 Lexer::getSourceText( 5399 CharSourceRange::getTokenRange( 5400 Inits[CorrelatedInitOrder[I].second]->getSourceRange()), 5401 SemaRef.getSourceManager(), SemaRef.getLangOpts())); 5402 } 5403 5404 // If there is only 1 item out of order, the warning expects the name and 5405 // type of each being added to it. 5406 if (WarnIndexes.size() == 1) { 5407 AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1], 5408 Inits[WarnIndexes.front()]); 5409 return; 5410 } 5411 } 5412 // More than 1 item to warn, create notes letting the user know which ones 5413 // are bad. 5414 for (unsigned WarnIndex : WarnIndexes) { 5415 const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1]; 5416 auto D = SemaRef.Diag(PrevInit->getSourceLocation(), 5417 diag::note_initializer_out_of_order); 5418 AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]); 5419 D << PrevInit->getSourceRange(); 5420 } 5421 } 5422 5423 namespace { 5424 bool CheckRedundantInit(Sema &S, 5425 CXXCtorInitializer *Init, 5426 CXXCtorInitializer *&PrevInit) { 5427 if (!PrevInit) { 5428 PrevInit = Init; 5429 return false; 5430 } 5431 5432 if (FieldDecl *Field = Init->getAnyMember()) 5433 S.Diag(Init->getSourceLocation(), 5434 diag::err_multiple_mem_initialization) 5435 << Field->getDeclName() 5436 << Init->getSourceRange(); 5437 else { 5438 const Type *BaseClass = Init->getBaseClass(); 5439 assert(BaseClass && "neither field nor base"); 5440 S.Diag(Init->getSourceLocation(), 5441 diag::err_multiple_base_initialization) 5442 << QualType(BaseClass, 0) 5443 << Init->getSourceRange(); 5444 } 5445 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 5446 << 0 << PrevInit->getSourceRange(); 5447 5448 return true; 5449 } 5450 5451 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 5452 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 5453 5454 bool CheckRedundantUnionInit(Sema &S, 5455 CXXCtorInitializer *Init, 5456 RedundantUnionMap &Unions) { 5457 FieldDecl *Field = Init->getAnyMember(); 5458 RecordDecl *Parent = Field->getParent(); 5459 NamedDecl *Child = Field; 5460 5461 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 5462 if (Parent->isUnion()) { 5463 UnionEntry &En = Unions[Parent]; 5464 if (En.first && En.first != Child) { 5465 S.Diag(Init->getSourceLocation(), 5466 diag::err_multiple_mem_union_initialization) 5467 << Field->getDeclName() 5468 << Init->getSourceRange(); 5469 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 5470 << 0 << En.second->getSourceRange(); 5471 return true; 5472 } 5473 if (!En.first) { 5474 En.first = Child; 5475 En.second = Init; 5476 } 5477 if (!Parent->isAnonymousStructOrUnion()) 5478 return false; 5479 } 5480 5481 Child = Parent; 5482 Parent = cast<RecordDecl>(Parent->getDeclContext()); 5483 } 5484 5485 return false; 5486 } 5487 } // namespace 5488 5489 /// ActOnMemInitializers - Handle the member initializers for a constructor. 5490 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 5491 SourceLocation ColonLoc, 5492 ArrayRef<CXXCtorInitializer*> MemInits, 5493 bool AnyErrors) { 5494 if (!ConstructorDecl) 5495 return; 5496 5497 AdjustDeclIfTemplate(ConstructorDecl); 5498 5499 CXXConstructorDecl *Constructor 5500 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 5501 5502 if (!Constructor) { 5503 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 5504 return; 5505 } 5506 5507 // Mapping for the duplicate initializers check. 5508 // For member initializers, this is keyed with a FieldDecl*. 5509 // For base initializers, this is keyed with a Type*. 5510 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 5511 5512 // Mapping for the inconsistent anonymous-union initializers check. 5513 RedundantUnionMap MemberUnions; 5514 5515 bool HadError = false; 5516 for (unsigned i = 0; i < MemInits.size(); i++) { 5517 CXXCtorInitializer *Init = MemInits[i]; 5518 5519 // Set the source order index. 5520 Init->setSourceOrder(i); 5521 5522 if (Init->isAnyMemberInitializer()) { 5523 const void *Key = GetKeyForMember(Context, Init); 5524 if (CheckRedundantInit(*this, Init, Members[Key]) || 5525 CheckRedundantUnionInit(*this, Init, MemberUnions)) 5526 HadError = true; 5527 } else if (Init->isBaseInitializer()) { 5528 const void *Key = GetKeyForMember(Context, Init); 5529 if (CheckRedundantInit(*this, Init, Members[Key])) 5530 HadError = true; 5531 } else { 5532 assert(Init->isDelegatingInitializer()); 5533 // This must be the only initializer 5534 if (MemInits.size() != 1) { 5535 Diag(Init->getSourceLocation(), 5536 diag::err_delegating_initializer_alone) 5537 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 5538 // We will treat this as being the only initializer. 5539 } 5540 SetDelegatingInitializer(Constructor, MemInits[i]); 5541 // Return immediately as the initializer is set. 5542 return; 5543 } 5544 } 5545 5546 if (HadError) 5547 return; 5548 5549 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 5550 5551 SetCtorInitializers(Constructor, AnyErrors, MemInits); 5552 5553 DiagnoseUninitializedFields(*this, Constructor); 5554 } 5555 5556 void 5557 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 5558 CXXRecordDecl *ClassDecl) { 5559 // Ignore dependent contexts. Also ignore unions, since their members never 5560 // have destructors implicitly called. 5561 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 5562 return; 5563 5564 // FIXME: all the access-control diagnostics are positioned on the 5565 // field/base declaration. That's probably good; that said, the 5566 // user might reasonably want to know why the destructor is being 5567 // emitted, and we currently don't say. 5568 5569 // Non-static data members. 5570 for (auto *Field : ClassDecl->fields()) { 5571 if (Field->isInvalidDecl()) 5572 continue; 5573 5574 // Don't destroy incomplete or zero-length arrays. 5575 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 5576 continue; 5577 5578 QualType FieldType = Context.getBaseElementType(Field->getType()); 5579 5580 const RecordType* RT = FieldType->getAs<RecordType>(); 5581 if (!RT) 5582 continue; 5583 5584 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5585 if (FieldClassDecl->isInvalidDecl()) 5586 continue; 5587 if (FieldClassDecl->hasIrrelevantDestructor()) 5588 continue; 5589 // The destructor for an implicit anonymous union member is never invoked. 5590 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 5591 continue; 5592 5593 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 5594 assert(Dtor && "No dtor found for FieldClassDecl!"); 5595 CheckDestructorAccess(Field->getLocation(), Dtor, 5596 PDiag(diag::err_access_dtor_field) 5597 << Field->getDeclName() 5598 << FieldType); 5599 5600 MarkFunctionReferenced(Location, Dtor); 5601 DiagnoseUseOfDecl(Dtor, Location); 5602 } 5603 5604 // We only potentially invoke the destructors of potentially constructed 5605 // subobjects. 5606 bool VisitVirtualBases = !ClassDecl->isAbstract(); 5607 5608 // If the destructor exists and has already been marked used in the MS ABI, 5609 // then virtual base destructors have already been checked and marked used. 5610 // Skip checking them again to avoid duplicate diagnostics. 5611 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 5612 CXXDestructorDecl *Dtor = ClassDecl->getDestructor(); 5613 if (Dtor && Dtor->isUsed()) 5614 VisitVirtualBases = false; 5615 } 5616 5617 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 5618 5619 // Bases. 5620 for (const auto &Base : ClassDecl->bases()) { 5621 const RecordType *RT = Base.getType()->getAs<RecordType>(); 5622 if (!RT) 5623 continue; 5624 5625 // Remember direct virtual bases. 5626 if (Base.isVirtual()) { 5627 if (!VisitVirtualBases) 5628 continue; 5629 DirectVirtualBases.insert(RT); 5630 } 5631 5632 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5633 // If our base class is invalid, we probably can't get its dtor anyway. 5634 if (BaseClassDecl->isInvalidDecl()) 5635 continue; 5636 if (BaseClassDecl->hasIrrelevantDestructor()) 5637 continue; 5638 5639 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5640 assert(Dtor && "No dtor found for BaseClassDecl!"); 5641 5642 // FIXME: caret should be on the start of the class name 5643 CheckDestructorAccess(Base.getBeginLoc(), Dtor, 5644 PDiag(diag::err_access_dtor_base) 5645 << Base.getType() << Base.getSourceRange(), 5646 Context.getTypeDeclType(ClassDecl)); 5647 5648 MarkFunctionReferenced(Location, Dtor); 5649 DiagnoseUseOfDecl(Dtor, Location); 5650 } 5651 5652 if (VisitVirtualBases) 5653 MarkVirtualBaseDestructorsReferenced(Location, ClassDecl, 5654 &DirectVirtualBases); 5655 } 5656 5657 void Sema::MarkVirtualBaseDestructorsReferenced( 5658 SourceLocation Location, CXXRecordDecl *ClassDecl, 5659 llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) { 5660 // Virtual bases. 5661 for (const auto &VBase : ClassDecl->vbases()) { 5662 // Bases are always records in a well-formed non-dependent class. 5663 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 5664 5665 // Ignore already visited direct virtual bases. 5666 if (DirectVirtualBases && DirectVirtualBases->count(RT)) 5667 continue; 5668 5669 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5670 // If our base class is invalid, we probably can't get its dtor anyway. 5671 if (BaseClassDecl->isInvalidDecl()) 5672 continue; 5673 if (BaseClassDecl->hasIrrelevantDestructor()) 5674 continue; 5675 5676 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5677 assert(Dtor && "No dtor found for BaseClassDecl!"); 5678 if (CheckDestructorAccess( 5679 ClassDecl->getLocation(), Dtor, 5680 PDiag(diag::err_access_dtor_vbase) 5681 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 5682 Context.getTypeDeclType(ClassDecl)) == 5683 AR_accessible) { 5684 CheckDerivedToBaseConversion( 5685 Context.getTypeDeclType(ClassDecl), VBase.getType(), 5686 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 5687 SourceRange(), DeclarationName(), nullptr); 5688 } 5689 5690 MarkFunctionReferenced(Location, Dtor); 5691 DiagnoseUseOfDecl(Dtor, Location); 5692 } 5693 } 5694 5695 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 5696 if (!CDtorDecl) 5697 return; 5698 5699 if (CXXConstructorDecl *Constructor 5700 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 5701 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 5702 DiagnoseUninitializedFields(*this, Constructor); 5703 } 5704 } 5705 5706 bool Sema::isAbstractType(SourceLocation Loc, QualType T) { 5707 if (!getLangOpts().CPlusPlus) 5708 return false; 5709 5710 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl(); 5711 if (!RD) 5712 return false; 5713 5714 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a 5715 // class template specialization here, but doing so breaks a lot of code. 5716 5717 // We can't answer whether something is abstract until it has a 5718 // definition. If it's currently being defined, we'll walk back 5719 // over all the declarations when we have a full definition. 5720 const CXXRecordDecl *Def = RD->getDefinition(); 5721 if (!Def || Def->isBeingDefined()) 5722 return false; 5723 5724 return RD->isAbstract(); 5725 } 5726 5727 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 5728 TypeDiagnoser &Diagnoser) { 5729 if (!isAbstractType(Loc, T)) 5730 return false; 5731 5732 T = Context.getBaseElementType(T); 5733 Diagnoser.diagnose(*this, Loc, T); 5734 DiagnoseAbstractType(T->getAsCXXRecordDecl()); 5735 return true; 5736 } 5737 5738 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 5739 // Check if we've already emitted the list of pure virtual functions 5740 // for this class. 5741 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 5742 return; 5743 5744 // If the diagnostic is suppressed, don't emit the notes. We're only 5745 // going to emit them once, so try to attach them to a diagnostic we're 5746 // actually going to show. 5747 if (Diags.isLastDiagnosticIgnored()) 5748 return; 5749 5750 CXXFinalOverriderMap FinalOverriders; 5751 RD->getFinalOverriders(FinalOverriders); 5752 5753 // Keep a set of seen pure methods so we won't diagnose the same method 5754 // more than once. 5755 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 5756 5757 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 5758 MEnd = FinalOverriders.end(); 5759 M != MEnd; 5760 ++M) { 5761 for (OverridingMethods::iterator SO = M->second.begin(), 5762 SOEnd = M->second.end(); 5763 SO != SOEnd; ++SO) { 5764 // C++ [class.abstract]p4: 5765 // A class is abstract if it contains or inherits at least one 5766 // pure virtual function for which the final overrider is pure 5767 // virtual. 5768 5769 // 5770 if (SO->second.size() != 1) 5771 continue; 5772 5773 if (!SO->second.front().Method->isPure()) 5774 continue; 5775 5776 if (!SeenPureMethods.insert(SO->second.front().Method).second) 5777 continue; 5778 5779 Diag(SO->second.front().Method->getLocation(), 5780 diag::note_pure_virtual_function) 5781 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 5782 } 5783 } 5784 5785 if (!PureVirtualClassDiagSet) 5786 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 5787 PureVirtualClassDiagSet->insert(RD); 5788 } 5789 5790 namespace { 5791 struct AbstractUsageInfo { 5792 Sema &S; 5793 CXXRecordDecl *Record; 5794 CanQualType AbstractType; 5795 bool Invalid; 5796 5797 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 5798 : S(S), Record(Record), 5799 AbstractType(S.Context.getCanonicalType( 5800 S.Context.getTypeDeclType(Record))), 5801 Invalid(false) {} 5802 5803 void DiagnoseAbstractType() { 5804 if (Invalid) return; 5805 S.DiagnoseAbstractType(Record); 5806 Invalid = true; 5807 } 5808 5809 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 5810 }; 5811 5812 struct CheckAbstractUsage { 5813 AbstractUsageInfo &Info; 5814 const NamedDecl *Ctx; 5815 5816 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 5817 : Info(Info), Ctx(Ctx) {} 5818 5819 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5820 switch (TL.getTypeLocClass()) { 5821 #define ABSTRACT_TYPELOC(CLASS, PARENT) 5822 #define TYPELOC(CLASS, PARENT) \ 5823 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 5824 #include "clang/AST/TypeLocNodes.def" 5825 } 5826 } 5827 5828 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5829 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 5830 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 5831 if (!TL.getParam(I)) 5832 continue; 5833 5834 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 5835 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 5836 } 5837 } 5838 5839 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5840 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 5841 } 5842 5843 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5844 // Visit the type parameters from a permissive context. 5845 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 5846 TemplateArgumentLoc TAL = TL.getArgLoc(I); 5847 if (TAL.getArgument().getKind() == TemplateArgument::Type) 5848 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 5849 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 5850 // TODO: other template argument types? 5851 } 5852 } 5853 5854 // Visit pointee types from a permissive context. 5855 #define CheckPolymorphic(Type) \ 5856 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 5857 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 5858 } 5859 CheckPolymorphic(PointerTypeLoc) 5860 CheckPolymorphic(ReferenceTypeLoc) 5861 CheckPolymorphic(MemberPointerTypeLoc) 5862 CheckPolymorphic(BlockPointerTypeLoc) 5863 CheckPolymorphic(AtomicTypeLoc) 5864 5865 /// Handle all the types we haven't given a more specific 5866 /// implementation for above. 5867 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5868 // Every other kind of type that we haven't called out already 5869 // that has an inner type is either (1) sugar or (2) contains that 5870 // inner type in some way as a subobject. 5871 if (TypeLoc Next = TL.getNextTypeLoc()) 5872 return Visit(Next, Sel); 5873 5874 // If there's no inner type and we're in a permissive context, 5875 // don't diagnose. 5876 if (Sel == Sema::AbstractNone) return; 5877 5878 // Check whether the type matches the abstract type. 5879 QualType T = TL.getType(); 5880 if (T->isArrayType()) { 5881 Sel = Sema::AbstractArrayType; 5882 T = Info.S.Context.getBaseElementType(T); 5883 } 5884 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 5885 if (CT != Info.AbstractType) return; 5886 5887 // It matched; do some magic. 5888 // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646. 5889 if (Sel == Sema::AbstractArrayType) { 5890 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 5891 << T << TL.getSourceRange(); 5892 } else { 5893 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 5894 << Sel << T << TL.getSourceRange(); 5895 } 5896 Info.DiagnoseAbstractType(); 5897 } 5898 }; 5899 5900 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 5901 Sema::AbstractDiagSelID Sel) { 5902 CheckAbstractUsage(*this, D).Visit(TL, Sel); 5903 } 5904 5905 } 5906 5907 /// Check for invalid uses of an abstract type in a function declaration. 5908 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5909 FunctionDecl *FD) { 5910 // No need to do the check on definitions, which require that 5911 // the return/param types be complete. 5912 if (FD->doesThisDeclarationHaveABody()) 5913 return; 5914 5915 // For safety's sake, just ignore it if we don't have type source 5916 // information. This should never happen for non-implicit methods, 5917 // but... 5918 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 5919 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractNone); 5920 } 5921 5922 /// Check for invalid uses of an abstract type in a variable0 declaration. 5923 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5924 VarDecl *VD) { 5925 // No need to do the check on definitions, which require that 5926 // the type is complete. 5927 if (VD->isThisDeclarationADefinition()) 5928 return; 5929 5930 Info.CheckType(VD, VD->getTypeSourceInfo()->getTypeLoc(), 5931 Sema::AbstractVariableType); 5932 } 5933 5934 /// Check for invalid uses of an abstract type within a class definition. 5935 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5936 CXXRecordDecl *RD) { 5937 for (auto *D : RD->decls()) { 5938 if (D->isImplicit()) continue; 5939 5940 // Step through friends to the befriended declaration. 5941 if (auto *FD = dyn_cast<FriendDecl>(D)) { 5942 D = FD->getFriendDecl(); 5943 if (!D) continue; 5944 } 5945 5946 // Functions and function templates. 5947 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 5948 CheckAbstractClassUsage(Info, FD); 5949 } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) { 5950 CheckAbstractClassUsage(Info, FTD->getTemplatedDecl()); 5951 5952 // Fields and static variables. 5953 } else if (auto *FD = dyn_cast<FieldDecl>(D)) { 5954 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 5955 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 5956 } else if (auto *VD = dyn_cast<VarDecl>(D)) { 5957 CheckAbstractClassUsage(Info, VD); 5958 } else if (auto *VTD = dyn_cast<VarTemplateDecl>(D)) { 5959 CheckAbstractClassUsage(Info, VTD->getTemplatedDecl()); 5960 5961 // Nested classes and class templates. 5962 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 5963 CheckAbstractClassUsage(Info, RD); 5964 } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(D)) { 5965 CheckAbstractClassUsage(Info, CTD->getTemplatedDecl()); 5966 } 5967 } 5968 } 5969 5970 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) { 5971 Attr *ClassAttr = getDLLAttr(Class); 5972 if (!ClassAttr) 5973 return; 5974 5975 assert(ClassAttr->getKind() == attr::DLLExport); 5976 5977 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5978 5979 if (TSK == TSK_ExplicitInstantiationDeclaration) 5980 // Don't go any further if this is just an explicit instantiation 5981 // declaration. 5982 return; 5983 5984 // Add a context note to explain how we got to any diagnostics produced below. 5985 struct MarkingClassDllexported { 5986 Sema &S; 5987 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class, 5988 SourceLocation AttrLoc) 5989 : S(S) { 5990 Sema::CodeSynthesisContext Ctx; 5991 Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported; 5992 Ctx.PointOfInstantiation = AttrLoc; 5993 Ctx.Entity = Class; 5994 S.pushCodeSynthesisContext(Ctx); 5995 } 5996 ~MarkingClassDllexported() { 5997 S.popCodeSynthesisContext(); 5998 } 5999 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation()); 6000 6001 if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) 6002 S.MarkVTableUsed(Class->getLocation(), Class, true); 6003 6004 for (Decl *Member : Class->decls()) { 6005 // Skip members that were not marked exported. 6006 if (!Member->hasAttr<DLLExportAttr>()) 6007 continue; 6008 6009 // Defined static variables that are members of an exported base 6010 // class must be marked export too. 6011 auto *VD = dyn_cast<VarDecl>(Member); 6012 if (VD && VD->getStorageClass() == SC_Static && 6013 TSK == TSK_ImplicitInstantiation) 6014 S.MarkVariableReferenced(VD->getLocation(), VD); 6015 6016 auto *MD = dyn_cast<CXXMethodDecl>(Member); 6017 if (!MD) 6018 continue; 6019 6020 if (MD->isUserProvided()) { 6021 // Instantiate non-default class member functions ... 6022 6023 // .. except for certain kinds of template specializations. 6024 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 6025 continue; 6026 6027 // If this is an MS ABI dllexport default constructor, instantiate any 6028 // default arguments. 6029 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) { 6030 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 6031 if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) { 6032 S.InstantiateDefaultCtorDefaultArgs(CD); 6033 } 6034 } 6035 6036 S.MarkFunctionReferenced(Class->getLocation(), MD); 6037 6038 // The function will be passed to the consumer when its definition is 6039 // encountered. 6040 } else if (MD->isExplicitlyDefaulted()) { 6041 // Synthesize and instantiate explicitly defaulted methods. 6042 S.MarkFunctionReferenced(Class->getLocation(), MD); 6043 6044 if (TSK != TSK_ExplicitInstantiationDefinition) { 6045 // Except for explicit instantiation defs, we will not see the 6046 // definition again later, so pass it to the consumer now. 6047 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 6048 } 6049 } else if (!MD->isTrivial() || 6050 MD->isCopyAssignmentOperator() || 6051 MD->isMoveAssignmentOperator()) { 6052 // Synthesize and instantiate non-trivial implicit methods, and the copy 6053 // and move assignment operators. The latter are exported even if they 6054 // are trivial, because the address of an operator can be taken and 6055 // should compare equal across libraries. 6056 S.MarkFunctionReferenced(Class->getLocation(), MD); 6057 6058 // There is no later point when we will see the definition of this 6059 // function, so pass it to the consumer now. 6060 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 6061 } 6062 } 6063 } 6064 6065 static void checkForMultipleExportedDefaultConstructors(Sema &S, 6066 CXXRecordDecl *Class) { 6067 // Only the MS ABI has default constructor closures, so we don't need to do 6068 // this semantic checking anywhere else. 6069 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft()) 6070 return; 6071 6072 CXXConstructorDecl *LastExportedDefaultCtor = nullptr; 6073 for (Decl *Member : Class->decls()) { 6074 // Look for exported default constructors. 6075 auto *CD = dyn_cast<CXXConstructorDecl>(Member); 6076 if (!CD || !CD->isDefaultConstructor()) 6077 continue; 6078 auto *Attr = CD->getAttr<DLLExportAttr>(); 6079 if (!Attr) 6080 continue; 6081 6082 // If the class is non-dependent, mark the default arguments as ODR-used so 6083 // that we can properly codegen the constructor closure. 6084 if (!Class->isDependentContext()) { 6085 for (ParmVarDecl *PD : CD->parameters()) { 6086 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD); 6087 S.DiscardCleanupsInEvaluationContext(); 6088 } 6089 } 6090 6091 if (LastExportedDefaultCtor) { 6092 S.Diag(LastExportedDefaultCtor->getLocation(), 6093 diag::err_attribute_dll_ambiguous_default_ctor) 6094 << Class; 6095 S.Diag(CD->getLocation(), diag::note_entity_declared_at) 6096 << CD->getDeclName(); 6097 return; 6098 } 6099 LastExportedDefaultCtor = CD; 6100 } 6101 } 6102 6103 static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S, 6104 CXXRecordDecl *Class) { 6105 bool ErrorReported = false; 6106 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S, 6107 ClassTemplateDecl *TD) { 6108 if (ErrorReported) 6109 return; 6110 S.Diag(TD->getLocation(), 6111 diag::err_cuda_device_builtin_surftex_cls_template) 6112 << /*surface*/ 0 << TD; 6113 ErrorReported = true; 6114 }; 6115 6116 ClassTemplateDecl *TD = Class->getDescribedClassTemplate(); 6117 if (!TD) { 6118 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class); 6119 if (!SD) { 6120 S.Diag(Class->getLocation(), 6121 diag::err_cuda_device_builtin_surftex_ref_decl) 6122 << /*surface*/ 0 << Class; 6123 S.Diag(Class->getLocation(), 6124 diag::note_cuda_device_builtin_surftex_should_be_template_class) 6125 << Class; 6126 return; 6127 } 6128 TD = SD->getSpecializedTemplate(); 6129 } 6130 6131 TemplateParameterList *Params = TD->getTemplateParameters(); 6132 unsigned N = Params->size(); 6133 6134 if (N != 2) { 6135 reportIllegalClassTemplate(S, TD); 6136 S.Diag(TD->getLocation(), 6137 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args) 6138 << TD << 2; 6139 } 6140 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 6141 reportIllegalClassTemplate(S, TD); 6142 S.Diag(TD->getLocation(), 6143 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6144 << TD << /*1st*/ 0 << /*type*/ 0; 6145 } 6146 if (N > 1) { 6147 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 6148 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 6149 reportIllegalClassTemplate(S, TD); 6150 S.Diag(TD->getLocation(), 6151 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6152 << TD << /*2nd*/ 1 << /*integer*/ 1; 6153 } 6154 } 6155 } 6156 6157 static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S, 6158 CXXRecordDecl *Class) { 6159 bool ErrorReported = false; 6160 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S, 6161 ClassTemplateDecl *TD) { 6162 if (ErrorReported) 6163 return; 6164 S.Diag(TD->getLocation(), 6165 diag::err_cuda_device_builtin_surftex_cls_template) 6166 << /*texture*/ 1 << TD; 6167 ErrorReported = true; 6168 }; 6169 6170 ClassTemplateDecl *TD = Class->getDescribedClassTemplate(); 6171 if (!TD) { 6172 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class); 6173 if (!SD) { 6174 S.Diag(Class->getLocation(), 6175 diag::err_cuda_device_builtin_surftex_ref_decl) 6176 << /*texture*/ 1 << Class; 6177 S.Diag(Class->getLocation(), 6178 diag::note_cuda_device_builtin_surftex_should_be_template_class) 6179 << Class; 6180 return; 6181 } 6182 TD = SD->getSpecializedTemplate(); 6183 } 6184 6185 TemplateParameterList *Params = TD->getTemplateParameters(); 6186 unsigned N = Params->size(); 6187 6188 if (N != 3) { 6189 reportIllegalClassTemplate(S, TD); 6190 S.Diag(TD->getLocation(), 6191 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args) 6192 << TD << 3; 6193 } 6194 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 6195 reportIllegalClassTemplate(S, TD); 6196 S.Diag(TD->getLocation(), 6197 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6198 << TD << /*1st*/ 0 << /*type*/ 0; 6199 } 6200 if (N > 1) { 6201 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 6202 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 6203 reportIllegalClassTemplate(S, TD); 6204 S.Diag(TD->getLocation(), 6205 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6206 << TD << /*2nd*/ 1 << /*integer*/ 1; 6207 } 6208 } 6209 if (N > 2) { 6210 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2)); 6211 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 6212 reportIllegalClassTemplate(S, TD); 6213 S.Diag(TD->getLocation(), 6214 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6215 << TD << /*3rd*/ 2 << /*integer*/ 1; 6216 } 6217 } 6218 } 6219 6220 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) { 6221 // Mark any compiler-generated routines with the implicit code_seg attribute. 6222 for (auto *Method : Class->methods()) { 6223 if (Method->isUserProvided()) 6224 continue; 6225 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true)) 6226 Method->addAttr(A); 6227 } 6228 } 6229 6230 /// Check class-level dllimport/dllexport attribute. 6231 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) { 6232 Attr *ClassAttr = getDLLAttr(Class); 6233 6234 // MSVC inherits DLL attributes to partial class template specializations. 6235 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) { 6236 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 6237 if (Attr *TemplateAttr = 6238 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 6239 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext())); 6240 A->setInherited(true); 6241 ClassAttr = A; 6242 } 6243 } 6244 } 6245 6246 if (!ClassAttr) 6247 return; 6248 6249 if (!Class->isExternallyVisible()) { 6250 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) 6251 << Class << ClassAttr; 6252 return; 6253 } 6254 6255 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && 6256 !ClassAttr->isInherited()) { 6257 // Diagnose dll attributes on members of class with dll attribute. 6258 for (Decl *Member : Class->decls()) { 6259 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 6260 continue; 6261 InheritableAttr *MemberAttr = getDLLAttr(Member); 6262 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 6263 continue; 6264 6265 Diag(MemberAttr->getLocation(), 6266 diag::err_attribute_dll_member_of_dll_class) 6267 << MemberAttr << ClassAttr; 6268 Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 6269 Member->setInvalidDecl(); 6270 } 6271 } 6272 6273 if (Class->getDescribedClassTemplate()) 6274 // Don't inherit dll attribute until the template is instantiated. 6275 return; 6276 6277 // The class is either imported or exported. 6278 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 6279 6280 // Check if this was a dllimport attribute propagated from a derived class to 6281 // a base class template specialization. We don't apply these attributes to 6282 // static data members. 6283 const bool PropagatedImport = 6284 !ClassExported && 6285 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate(); 6286 6287 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 6288 6289 // Ignore explicit dllexport on explicit class template instantiation 6290 // declarations, except in MinGW mode. 6291 if (ClassExported && !ClassAttr->isInherited() && 6292 TSK == TSK_ExplicitInstantiationDeclaration && 6293 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) { 6294 Class->dropAttr<DLLExportAttr>(); 6295 return; 6296 } 6297 6298 // Force declaration of implicit members so they can inherit the attribute. 6299 ForceDeclarationOfImplicitMembers(Class); 6300 6301 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 6302 // seem to be true in practice? 6303 6304 for (Decl *Member : Class->decls()) { 6305 VarDecl *VD = dyn_cast<VarDecl>(Member); 6306 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 6307 6308 // Only methods and static fields inherit the attributes. 6309 if (!VD && !MD) 6310 continue; 6311 6312 if (MD) { 6313 // Don't process deleted methods. 6314 if (MD->isDeleted()) 6315 continue; 6316 6317 if (MD->isInlined()) { 6318 // MinGW does not import or export inline methods. But do it for 6319 // template instantiations. 6320 if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() && 6321 TSK != TSK_ExplicitInstantiationDeclaration && 6322 TSK != TSK_ExplicitInstantiationDefinition) 6323 continue; 6324 6325 // MSVC versions before 2015 don't export the move assignment operators 6326 // and move constructor, so don't attempt to import/export them if 6327 // we have a definition. 6328 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD); 6329 if ((MD->isMoveAssignmentOperator() || 6330 (Ctor && Ctor->isMoveConstructor())) && 6331 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015)) 6332 continue; 6333 6334 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign 6335 // operator is exported anyway. 6336 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 6337 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial()) 6338 continue; 6339 } 6340 } 6341 6342 // Don't apply dllimport attributes to static data members of class template 6343 // instantiations when the attribute is propagated from a derived class. 6344 if (VD && PropagatedImport) 6345 continue; 6346 6347 if (!cast<NamedDecl>(Member)->isExternallyVisible()) 6348 continue; 6349 6350 if (!getDLLAttr(Member)) { 6351 InheritableAttr *NewAttr = nullptr; 6352 6353 // Do not export/import inline function when -fno-dllexport-inlines is 6354 // passed. But add attribute for later local static var check. 6355 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() && 6356 TSK != TSK_ExplicitInstantiationDeclaration && 6357 TSK != TSK_ExplicitInstantiationDefinition) { 6358 if (ClassExported) { 6359 NewAttr = ::new (getASTContext()) 6360 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr); 6361 } else { 6362 NewAttr = ::new (getASTContext()) 6363 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr); 6364 } 6365 } else { 6366 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6367 } 6368 6369 NewAttr->setInherited(true); 6370 Member->addAttr(NewAttr); 6371 6372 if (MD) { 6373 // Propagate DLLAttr to friend re-declarations of MD that have already 6374 // been constructed. 6375 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD; 6376 FD = FD->getPreviousDecl()) { 6377 if (FD->getFriendObjectKind() == Decl::FOK_None) 6378 continue; 6379 assert(!getDLLAttr(FD) && 6380 "friend re-decl should not already have a DLLAttr"); 6381 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6382 NewAttr->setInherited(true); 6383 FD->addAttr(NewAttr); 6384 } 6385 } 6386 } 6387 } 6388 6389 if (ClassExported) 6390 DelayedDllExportClasses.push_back(Class); 6391 } 6392 6393 /// Perform propagation of DLL attributes from a derived class to a 6394 /// templated base class for MS compatibility. 6395 void Sema::propagateDLLAttrToBaseClassTemplate( 6396 CXXRecordDecl *Class, Attr *ClassAttr, 6397 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 6398 if (getDLLAttr( 6399 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 6400 // If the base class template has a DLL attribute, don't try to change it. 6401 return; 6402 } 6403 6404 auto TSK = BaseTemplateSpec->getSpecializationKind(); 6405 if (!getDLLAttr(BaseTemplateSpec) && 6406 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration || 6407 TSK == TSK_ImplicitInstantiation)) { 6408 // The template hasn't been instantiated yet (or it has, but only as an 6409 // explicit instantiation declaration or implicit instantiation, which means 6410 // we haven't codegenned any members yet), so propagate the attribute. 6411 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6412 NewAttr->setInherited(true); 6413 BaseTemplateSpec->addAttr(NewAttr); 6414 6415 // If this was an import, mark that we propagated it from a derived class to 6416 // a base class template specialization. 6417 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr)) 6418 ImportAttr->setPropagatedToBaseTemplate(); 6419 6420 // If the template is already instantiated, checkDLLAttributeRedeclaration() 6421 // needs to be run again to work see the new attribute. Otherwise this will 6422 // get run whenever the template is instantiated. 6423 if (TSK != TSK_Undeclared) 6424 checkClassLevelDLLAttribute(BaseTemplateSpec); 6425 6426 return; 6427 } 6428 6429 if (getDLLAttr(BaseTemplateSpec)) { 6430 // The template has already been specialized or instantiated with an 6431 // attribute, explicitly or through propagation. We should not try to change 6432 // it. 6433 return; 6434 } 6435 6436 // The template was previously instantiated or explicitly specialized without 6437 // a dll attribute, It's too late for us to add an attribute, so warn that 6438 // this is unsupported. 6439 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 6440 << BaseTemplateSpec->isExplicitSpecialization(); 6441 Diag(ClassAttr->getLocation(), diag::note_attribute); 6442 if (BaseTemplateSpec->isExplicitSpecialization()) { 6443 Diag(BaseTemplateSpec->getLocation(), 6444 diag::note_template_class_explicit_specialization_was_here) 6445 << BaseTemplateSpec; 6446 } else { 6447 Diag(BaseTemplateSpec->getPointOfInstantiation(), 6448 diag::note_template_class_instantiation_was_here) 6449 << BaseTemplateSpec; 6450 } 6451 } 6452 6453 /// Determine the kind of defaulting that would be done for a given function. 6454 /// 6455 /// If the function is both a default constructor and a copy / move constructor 6456 /// (due to having a default argument for the first parameter), this picks 6457 /// CXXDefaultConstructor. 6458 /// 6459 /// FIXME: Check that case is properly handled by all callers. 6460 Sema::DefaultedFunctionKind 6461 Sema::getDefaultedFunctionKind(const FunctionDecl *FD) { 6462 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 6463 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 6464 if (Ctor->isDefaultConstructor()) 6465 return Sema::CXXDefaultConstructor; 6466 6467 if (Ctor->isCopyConstructor()) 6468 return Sema::CXXCopyConstructor; 6469 6470 if (Ctor->isMoveConstructor()) 6471 return Sema::CXXMoveConstructor; 6472 } 6473 6474 if (MD->isCopyAssignmentOperator()) 6475 return Sema::CXXCopyAssignment; 6476 6477 if (MD->isMoveAssignmentOperator()) 6478 return Sema::CXXMoveAssignment; 6479 6480 if (isa<CXXDestructorDecl>(FD)) 6481 return Sema::CXXDestructor; 6482 } 6483 6484 switch (FD->getDeclName().getCXXOverloadedOperator()) { 6485 case OO_EqualEqual: 6486 return DefaultedComparisonKind::Equal; 6487 6488 case OO_ExclaimEqual: 6489 return DefaultedComparisonKind::NotEqual; 6490 6491 case OO_Spaceship: 6492 // No point allowing this if <=> doesn't exist in the current language mode. 6493 if (!getLangOpts().CPlusPlus20) 6494 break; 6495 return DefaultedComparisonKind::ThreeWay; 6496 6497 case OO_Less: 6498 case OO_LessEqual: 6499 case OO_Greater: 6500 case OO_GreaterEqual: 6501 // No point allowing this if <=> doesn't exist in the current language mode. 6502 if (!getLangOpts().CPlusPlus20) 6503 break; 6504 return DefaultedComparisonKind::Relational; 6505 6506 default: 6507 break; 6508 } 6509 6510 // Not defaultable. 6511 return DefaultedFunctionKind(); 6512 } 6513 6514 static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD, 6515 SourceLocation DefaultLoc) { 6516 Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD); 6517 if (DFK.isComparison()) 6518 return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison()); 6519 6520 switch (DFK.asSpecialMember()) { 6521 case Sema::CXXDefaultConstructor: 6522 S.DefineImplicitDefaultConstructor(DefaultLoc, 6523 cast<CXXConstructorDecl>(FD)); 6524 break; 6525 case Sema::CXXCopyConstructor: 6526 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD)); 6527 break; 6528 case Sema::CXXCopyAssignment: 6529 S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD)); 6530 break; 6531 case Sema::CXXDestructor: 6532 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD)); 6533 break; 6534 case Sema::CXXMoveConstructor: 6535 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD)); 6536 break; 6537 case Sema::CXXMoveAssignment: 6538 S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD)); 6539 break; 6540 case Sema::CXXInvalid: 6541 llvm_unreachable("Invalid special member."); 6542 } 6543 } 6544 6545 /// Determine whether a type is permitted to be passed or returned in 6546 /// registers, per C++ [class.temporary]p3. 6547 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D, 6548 TargetInfo::CallingConvKind CCK) { 6549 if (D->isDependentType() || D->isInvalidDecl()) 6550 return false; 6551 6552 // Clang <= 4 used the pre-C++11 rule, which ignores move operations. 6553 // The PS4 platform ABI follows the behavior of Clang 3.2. 6554 if (CCK == TargetInfo::CCK_ClangABI4OrPS4) 6555 return !D->hasNonTrivialDestructorForCall() && 6556 !D->hasNonTrivialCopyConstructorForCall(); 6557 6558 if (CCK == TargetInfo::CCK_MicrosoftWin64) { 6559 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false; 6560 bool DtorIsTrivialForCall = false; 6561 6562 // If a class has at least one non-deleted, trivial copy constructor, it 6563 // is passed according to the C ABI. Otherwise, it is passed indirectly. 6564 // 6565 // Note: This permits classes with non-trivial copy or move ctors to be 6566 // passed in registers, so long as they *also* have a trivial copy ctor, 6567 // which is non-conforming. 6568 if (D->needsImplicitCopyConstructor()) { 6569 if (!D->defaultedCopyConstructorIsDeleted()) { 6570 if (D->hasTrivialCopyConstructor()) 6571 CopyCtorIsTrivial = true; 6572 if (D->hasTrivialCopyConstructorForCall()) 6573 CopyCtorIsTrivialForCall = true; 6574 } 6575 } else { 6576 for (const CXXConstructorDecl *CD : D->ctors()) { 6577 if (CD->isCopyConstructor() && !CD->isDeleted()) { 6578 if (CD->isTrivial()) 6579 CopyCtorIsTrivial = true; 6580 if (CD->isTrivialForCall()) 6581 CopyCtorIsTrivialForCall = true; 6582 } 6583 } 6584 } 6585 6586 if (D->needsImplicitDestructor()) { 6587 if (!D->defaultedDestructorIsDeleted() && 6588 D->hasTrivialDestructorForCall()) 6589 DtorIsTrivialForCall = true; 6590 } else if (const auto *DD = D->getDestructor()) { 6591 if (!DD->isDeleted() && DD->isTrivialForCall()) 6592 DtorIsTrivialForCall = true; 6593 } 6594 6595 // If the copy ctor and dtor are both trivial-for-calls, pass direct. 6596 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall) 6597 return true; 6598 6599 // If a class has a destructor, we'd really like to pass it indirectly 6600 // because it allows us to elide copies. Unfortunately, MSVC makes that 6601 // impossible for small types, which it will pass in a single register or 6602 // stack slot. Most objects with dtors are large-ish, so handle that early. 6603 // We can't call out all large objects as being indirect because there are 6604 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate 6605 // how we pass large POD types. 6606 6607 // Note: This permits small classes with nontrivial destructors to be 6608 // passed in registers, which is non-conforming. 6609 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64(); 6610 uint64_t TypeSize = isAArch64 ? 128 : 64; 6611 6612 if (CopyCtorIsTrivial && 6613 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize) 6614 return true; 6615 return false; 6616 } 6617 6618 // Per C++ [class.temporary]p3, the relevant condition is: 6619 // each copy constructor, move constructor, and destructor of X is 6620 // either trivial or deleted, and X has at least one non-deleted copy 6621 // or move constructor 6622 bool HasNonDeletedCopyOrMove = false; 6623 6624 if (D->needsImplicitCopyConstructor() && 6625 !D->defaultedCopyConstructorIsDeleted()) { 6626 if (!D->hasTrivialCopyConstructorForCall()) 6627 return false; 6628 HasNonDeletedCopyOrMove = true; 6629 } 6630 6631 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() && 6632 !D->defaultedMoveConstructorIsDeleted()) { 6633 if (!D->hasTrivialMoveConstructorForCall()) 6634 return false; 6635 HasNonDeletedCopyOrMove = true; 6636 } 6637 6638 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() && 6639 !D->hasTrivialDestructorForCall()) 6640 return false; 6641 6642 for (const CXXMethodDecl *MD : D->methods()) { 6643 if (MD->isDeleted()) 6644 continue; 6645 6646 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 6647 if (CD && CD->isCopyOrMoveConstructor()) 6648 HasNonDeletedCopyOrMove = true; 6649 else if (!isa<CXXDestructorDecl>(MD)) 6650 continue; 6651 6652 if (!MD->isTrivialForCall()) 6653 return false; 6654 } 6655 6656 return HasNonDeletedCopyOrMove; 6657 } 6658 6659 /// Report an error regarding overriding, along with any relevant 6660 /// overridden methods. 6661 /// 6662 /// \param DiagID the primary error to report. 6663 /// \param MD the overriding method. 6664 static bool 6665 ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD, 6666 llvm::function_ref<bool(const CXXMethodDecl *)> Report) { 6667 bool IssuedDiagnostic = false; 6668 for (const CXXMethodDecl *O : MD->overridden_methods()) { 6669 if (Report(O)) { 6670 if (!IssuedDiagnostic) { 6671 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 6672 IssuedDiagnostic = true; 6673 } 6674 S.Diag(O->getLocation(), diag::note_overridden_virtual_function); 6675 } 6676 } 6677 return IssuedDiagnostic; 6678 } 6679 6680 /// Perform semantic checks on a class definition that has been 6681 /// completing, introducing implicitly-declared members, checking for 6682 /// abstract types, etc. 6683 /// 6684 /// \param S The scope in which the class was parsed. Null if we didn't just 6685 /// parse a class definition. 6686 /// \param Record The completed class. 6687 void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) { 6688 if (!Record) 6689 return; 6690 6691 if (Record->isAbstract() && !Record->isInvalidDecl()) { 6692 AbstractUsageInfo Info(*this, Record); 6693 CheckAbstractClassUsage(Info, Record); 6694 } 6695 6696 // If this is not an aggregate type and has no user-declared constructor, 6697 // complain about any non-static data members of reference or const scalar 6698 // type, since they will never get initializers. 6699 if (!Record->isInvalidDecl() && !Record->isDependentType() && 6700 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 6701 !Record->isLambda()) { 6702 bool Complained = false; 6703 for (const auto *F : Record->fields()) { 6704 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 6705 continue; 6706 6707 if (F->getType()->isReferenceType() || 6708 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 6709 if (!Complained) { 6710 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 6711 << Record->getTagKind() << Record; 6712 Complained = true; 6713 } 6714 6715 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 6716 << F->getType()->isReferenceType() 6717 << F->getDeclName(); 6718 } 6719 } 6720 } 6721 6722 if (Record->getIdentifier()) { 6723 // C++ [class.mem]p13: 6724 // If T is the name of a class, then each of the following shall have a 6725 // name different from T: 6726 // - every member of every anonymous union that is a member of class T. 6727 // 6728 // C++ [class.mem]p14: 6729 // In addition, if class T has a user-declared constructor (12.1), every 6730 // non-static data member of class T shall have a name different from T. 6731 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 6732 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 6733 ++I) { 6734 NamedDecl *D = (*I)->getUnderlyingDecl(); 6735 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) && 6736 Record->hasUserDeclaredConstructor()) || 6737 isa<IndirectFieldDecl>(D)) { 6738 Diag((*I)->getLocation(), diag::err_member_name_of_class) 6739 << D->getDeclName(); 6740 break; 6741 } 6742 } 6743 } 6744 6745 // Warn if the class has virtual methods but non-virtual public destructor. 6746 if (Record->isPolymorphic() && !Record->isDependentType()) { 6747 CXXDestructorDecl *dtor = Record->getDestructor(); 6748 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 6749 !Record->hasAttr<FinalAttr>()) 6750 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 6751 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 6752 } 6753 6754 if (Record->isAbstract()) { 6755 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 6756 Diag(Record->getLocation(), diag::warn_abstract_final_class) 6757 << FA->isSpelledAsSealed(); 6758 DiagnoseAbstractType(Record); 6759 } 6760 } 6761 6762 // Warn if the class has a final destructor but is not itself marked final. 6763 if (!Record->hasAttr<FinalAttr>()) { 6764 if (const CXXDestructorDecl *dtor = Record->getDestructor()) { 6765 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) { 6766 Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class) 6767 << FA->isSpelledAsSealed() 6768 << FixItHint::CreateInsertion( 6769 getLocForEndOfToken(Record->getLocation()), 6770 (FA->isSpelledAsSealed() ? " sealed" : " final")); 6771 Diag(Record->getLocation(), 6772 diag::note_final_dtor_non_final_class_silence) 6773 << Context.getRecordType(Record) << FA->isSpelledAsSealed(); 6774 } 6775 } 6776 } 6777 6778 // See if trivial_abi has to be dropped. 6779 if (Record->hasAttr<TrivialABIAttr>()) 6780 checkIllFormedTrivialABIStruct(*Record); 6781 6782 // Set HasTrivialSpecialMemberForCall if the record has attribute 6783 // "trivial_abi". 6784 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>(); 6785 6786 if (HasTrivialABI) 6787 Record->setHasTrivialSpecialMemberForCall(); 6788 6789 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=). 6790 // We check these last because they can depend on the properties of the 6791 // primary comparison functions (==, <=>). 6792 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons; 6793 6794 // Perform checks that can't be done until we know all the properties of a 6795 // member function (whether it's defaulted, deleted, virtual, overriding, 6796 // ...). 6797 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) { 6798 // A static function cannot override anything. 6799 if (MD->getStorageClass() == SC_Static) { 6800 if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD, 6801 [](const CXXMethodDecl *) { return true; })) 6802 return; 6803 } 6804 6805 // A deleted function cannot override a non-deleted function and vice 6806 // versa. 6807 if (ReportOverrides(*this, 6808 MD->isDeleted() ? diag::err_deleted_override 6809 : diag::err_non_deleted_override, 6810 MD, [&](const CXXMethodDecl *V) { 6811 return MD->isDeleted() != V->isDeleted(); 6812 })) { 6813 if (MD->isDefaulted() && MD->isDeleted()) 6814 // Explain why this defaulted function was deleted. 6815 DiagnoseDeletedDefaultedFunction(MD); 6816 return; 6817 } 6818 6819 // A consteval function cannot override a non-consteval function and vice 6820 // versa. 6821 if (ReportOverrides(*this, 6822 MD->isConsteval() ? diag::err_consteval_override 6823 : diag::err_non_consteval_override, 6824 MD, [&](const CXXMethodDecl *V) { 6825 return MD->isConsteval() != V->isConsteval(); 6826 })) { 6827 if (MD->isDefaulted() && MD->isDeleted()) 6828 // Explain why this defaulted function was deleted. 6829 DiagnoseDeletedDefaultedFunction(MD); 6830 return; 6831 } 6832 }; 6833 6834 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool { 6835 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted()) 6836 return false; 6837 6838 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD); 6839 if (DFK.asComparison() == DefaultedComparisonKind::NotEqual || 6840 DFK.asComparison() == DefaultedComparisonKind::Relational) { 6841 DefaultedSecondaryComparisons.push_back(FD); 6842 return true; 6843 } 6844 6845 CheckExplicitlyDefaultedFunction(S, FD); 6846 return false; 6847 }; 6848 6849 auto CompleteMemberFunction = [&](CXXMethodDecl *M) { 6850 // Check whether the explicitly-defaulted members are valid. 6851 bool Incomplete = CheckForDefaultedFunction(M); 6852 6853 // Skip the rest of the checks for a member of a dependent class. 6854 if (Record->isDependentType()) 6855 return; 6856 6857 // For an explicitly defaulted or deleted special member, we defer 6858 // determining triviality until the class is complete. That time is now! 6859 CXXSpecialMember CSM = getSpecialMember(M); 6860 if (!M->isImplicit() && !M->isUserProvided()) { 6861 if (CSM != CXXInvalid) { 6862 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 6863 // Inform the class that we've finished declaring this member. 6864 Record->finishedDefaultedOrDeletedMember(M); 6865 M->setTrivialForCall( 6866 HasTrivialABI || 6867 SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI)); 6868 Record->setTrivialForCallFlags(M); 6869 } 6870 } 6871 6872 // Set triviality for the purpose of calls if this is a user-provided 6873 // copy/move constructor or destructor. 6874 if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor || 6875 CSM == CXXDestructor) && M->isUserProvided()) { 6876 M->setTrivialForCall(HasTrivialABI); 6877 Record->setTrivialForCallFlags(M); 6878 } 6879 6880 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() && 6881 M->hasAttr<DLLExportAttr>()) { 6882 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 6883 M->isTrivial() && 6884 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor || 6885 CSM == CXXDestructor)) 6886 M->dropAttr<DLLExportAttr>(); 6887 6888 if (M->hasAttr<DLLExportAttr>()) { 6889 // Define after any fields with in-class initializers have been parsed. 6890 DelayedDllExportMemberFunctions.push_back(M); 6891 } 6892 } 6893 6894 // Define defaulted constexpr virtual functions that override a base class 6895 // function right away. 6896 // FIXME: We can defer doing this until the vtable is marked as used. 6897 if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods()) 6898 DefineDefaultedFunction(*this, M, M->getLocation()); 6899 6900 if (!Incomplete) 6901 CheckCompletedMemberFunction(M); 6902 }; 6903 6904 // Check the destructor before any other member function. We need to 6905 // determine whether it's trivial in order to determine whether the claas 6906 // type is a literal type, which is a prerequisite for determining whether 6907 // other special member functions are valid and whether they're implicitly 6908 // 'constexpr'. 6909 if (CXXDestructorDecl *Dtor = Record->getDestructor()) 6910 CompleteMemberFunction(Dtor); 6911 6912 bool HasMethodWithOverrideControl = false, 6913 HasOverridingMethodWithoutOverrideControl = false; 6914 for (auto *D : Record->decls()) { 6915 if (auto *M = dyn_cast<CXXMethodDecl>(D)) { 6916 // FIXME: We could do this check for dependent types with non-dependent 6917 // bases. 6918 if (!Record->isDependentType()) { 6919 // See if a method overloads virtual methods in a base 6920 // class without overriding any. 6921 if (!M->isStatic()) 6922 DiagnoseHiddenVirtualMethods(M); 6923 if (M->hasAttr<OverrideAttr>()) 6924 HasMethodWithOverrideControl = true; 6925 else if (M->size_overridden_methods() > 0) 6926 HasOverridingMethodWithoutOverrideControl = true; 6927 } 6928 6929 if (!isa<CXXDestructorDecl>(M)) 6930 CompleteMemberFunction(M); 6931 } else if (auto *F = dyn_cast<FriendDecl>(D)) { 6932 CheckForDefaultedFunction( 6933 dyn_cast_or_null<FunctionDecl>(F->getFriendDecl())); 6934 } 6935 } 6936 6937 if (HasOverridingMethodWithoutOverrideControl) { 6938 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl; 6939 for (auto *M : Record->methods()) 6940 DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl); 6941 } 6942 6943 // Check the defaulted secondary comparisons after any other member functions. 6944 for (FunctionDecl *FD : DefaultedSecondaryComparisons) { 6945 CheckExplicitlyDefaultedFunction(S, FD); 6946 6947 // If this is a member function, we deferred checking it until now. 6948 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) 6949 CheckCompletedMemberFunction(MD); 6950 } 6951 6952 // ms_struct is a request to use the same ABI rules as MSVC. Check 6953 // whether this class uses any C++ features that are implemented 6954 // completely differently in MSVC, and if so, emit a diagnostic. 6955 // That diagnostic defaults to an error, but we allow projects to 6956 // map it down to a warning (or ignore it). It's a fairly common 6957 // practice among users of the ms_struct pragma to mass-annotate 6958 // headers, sweeping up a bunch of types that the project doesn't 6959 // really rely on MSVC-compatible layout for. We must therefore 6960 // support "ms_struct except for C++ stuff" as a secondary ABI. 6961 // Don't emit this diagnostic if the feature was enabled as a 6962 // language option (as opposed to via a pragma or attribute), as 6963 // the option -mms-bitfields otherwise essentially makes it impossible 6964 // to build C++ code, unless this diagnostic is turned off. 6965 if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields && 6966 (Record->isPolymorphic() || Record->getNumBases())) { 6967 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 6968 } 6969 6970 checkClassLevelDLLAttribute(Record); 6971 checkClassLevelCodeSegAttribute(Record); 6972 6973 bool ClangABICompat4 = 6974 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4; 6975 TargetInfo::CallingConvKind CCK = 6976 Context.getTargetInfo().getCallingConvKind(ClangABICompat4); 6977 bool CanPass = canPassInRegisters(*this, Record, CCK); 6978 6979 // Do not change ArgPassingRestrictions if it has already been set to 6980 // APK_CanNeverPassInRegs. 6981 if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs) 6982 Record->setArgPassingRestrictions(CanPass 6983 ? RecordDecl::APK_CanPassInRegs 6984 : RecordDecl::APK_CannotPassInRegs); 6985 6986 // If canPassInRegisters returns true despite the record having a non-trivial 6987 // destructor, the record is destructed in the callee. This happens only when 6988 // the record or one of its subobjects has a field annotated with trivial_abi 6989 // or a field qualified with ObjC __strong/__weak. 6990 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee()) 6991 Record->setParamDestroyedInCallee(true); 6992 else if (Record->hasNonTrivialDestructor()) 6993 Record->setParamDestroyedInCallee(CanPass); 6994 6995 if (getLangOpts().ForceEmitVTables) { 6996 // If we want to emit all the vtables, we need to mark it as used. This 6997 // is especially required for cases like vtable assumption loads. 6998 MarkVTableUsed(Record->getInnerLocStart(), Record); 6999 } 7000 7001 if (getLangOpts().CUDA) { 7002 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>()) 7003 checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record); 7004 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>()) 7005 checkCUDADeviceBuiltinTextureClassTemplate(*this, Record); 7006 } 7007 } 7008 7009 /// Look up the special member function that would be called by a special 7010 /// member function for a subobject of class type. 7011 /// 7012 /// \param Class The class type of the subobject. 7013 /// \param CSM The kind of special member function. 7014 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 7015 /// \param ConstRHS True if this is a copy operation with a const object 7016 /// on its RHS, that is, if the argument to the outer special member 7017 /// function is 'const' and this is not a field marked 'mutable'. 7018 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember( 7019 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 7020 unsigned FieldQuals, bool ConstRHS) { 7021 unsigned LHSQuals = 0; 7022 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 7023 LHSQuals = FieldQuals; 7024 7025 unsigned RHSQuals = FieldQuals; 7026 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 7027 RHSQuals = 0; 7028 else if (ConstRHS) 7029 RHSQuals |= Qualifiers::Const; 7030 7031 return S.LookupSpecialMember(Class, CSM, 7032 RHSQuals & Qualifiers::Const, 7033 RHSQuals & Qualifiers::Volatile, 7034 false, 7035 LHSQuals & Qualifiers::Const, 7036 LHSQuals & Qualifiers::Volatile); 7037 } 7038 7039 class Sema::InheritedConstructorInfo { 7040 Sema &S; 7041 SourceLocation UseLoc; 7042 7043 /// A mapping from the base classes through which the constructor was 7044 /// inherited to the using shadow declaration in that base class (or a null 7045 /// pointer if the constructor was declared in that base class). 7046 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *> 7047 InheritedFromBases; 7048 7049 public: 7050 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, 7051 ConstructorUsingShadowDecl *Shadow) 7052 : S(S), UseLoc(UseLoc) { 7053 bool DiagnosedMultipleConstructedBases = false; 7054 CXXRecordDecl *ConstructedBase = nullptr; 7055 BaseUsingDecl *ConstructedBaseIntroducer = nullptr; 7056 7057 // Find the set of such base class subobjects and check that there's a 7058 // unique constructed subobject. 7059 for (auto *D : Shadow->redecls()) { 7060 auto *DShadow = cast<ConstructorUsingShadowDecl>(D); 7061 auto *DNominatedBase = DShadow->getNominatedBaseClass(); 7062 auto *DConstructedBase = DShadow->getConstructedBaseClass(); 7063 7064 InheritedFromBases.insert( 7065 std::make_pair(DNominatedBase->getCanonicalDecl(), 7066 DShadow->getNominatedBaseClassShadowDecl())); 7067 if (DShadow->constructsVirtualBase()) 7068 InheritedFromBases.insert( 7069 std::make_pair(DConstructedBase->getCanonicalDecl(), 7070 DShadow->getConstructedBaseClassShadowDecl())); 7071 else 7072 assert(DNominatedBase == DConstructedBase); 7073 7074 // [class.inhctor.init]p2: 7075 // If the constructor was inherited from multiple base class subobjects 7076 // of type B, the program is ill-formed. 7077 if (!ConstructedBase) { 7078 ConstructedBase = DConstructedBase; 7079 ConstructedBaseIntroducer = D->getIntroducer(); 7080 } else if (ConstructedBase != DConstructedBase && 7081 !Shadow->isInvalidDecl()) { 7082 if (!DiagnosedMultipleConstructedBases) { 7083 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor) 7084 << Shadow->getTargetDecl(); 7085 S.Diag(ConstructedBaseIntroducer->getLocation(), 7086 diag::note_ambiguous_inherited_constructor_using) 7087 << ConstructedBase; 7088 DiagnosedMultipleConstructedBases = true; 7089 } 7090 S.Diag(D->getIntroducer()->getLocation(), 7091 diag::note_ambiguous_inherited_constructor_using) 7092 << DConstructedBase; 7093 } 7094 } 7095 7096 if (DiagnosedMultipleConstructedBases) 7097 Shadow->setInvalidDecl(); 7098 } 7099 7100 /// Find the constructor to use for inherited construction of a base class, 7101 /// and whether that base class constructor inherits the constructor from a 7102 /// virtual base class (in which case it won't actually invoke it). 7103 std::pair<CXXConstructorDecl *, bool> 7104 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const { 7105 auto It = InheritedFromBases.find(Base->getCanonicalDecl()); 7106 if (It == InheritedFromBases.end()) 7107 return std::make_pair(nullptr, false); 7108 7109 // This is an intermediary class. 7110 if (It->second) 7111 return std::make_pair( 7112 S.findInheritingConstructor(UseLoc, Ctor, It->second), 7113 It->second->constructsVirtualBase()); 7114 7115 // This is the base class from which the constructor was inherited. 7116 return std::make_pair(Ctor, false); 7117 } 7118 }; 7119 7120 /// Is the special member function which would be selected to perform the 7121 /// specified operation on the specified class type a constexpr constructor? 7122 static bool 7123 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 7124 Sema::CXXSpecialMember CSM, unsigned Quals, 7125 bool ConstRHS, 7126 CXXConstructorDecl *InheritedCtor = nullptr, 7127 Sema::InheritedConstructorInfo *Inherited = nullptr) { 7128 // If we're inheriting a constructor, see if we need to call it for this base 7129 // class. 7130 if (InheritedCtor) { 7131 assert(CSM == Sema::CXXDefaultConstructor); 7132 auto BaseCtor = 7133 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first; 7134 if (BaseCtor) 7135 return BaseCtor->isConstexpr(); 7136 } 7137 7138 if (CSM == Sema::CXXDefaultConstructor) 7139 return ClassDecl->hasConstexprDefaultConstructor(); 7140 if (CSM == Sema::CXXDestructor) 7141 return ClassDecl->hasConstexprDestructor(); 7142 7143 Sema::SpecialMemberOverloadResult SMOR = 7144 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 7145 if (!SMOR.getMethod()) 7146 // A constructor we wouldn't select can't be "involved in initializing" 7147 // anything. 7148 return true; 7149 return SMOR.getMethod()->isConstexpr(); 7150 } 7151 7152 /// Determine whether the specified special member function would be constexpr 7153 /// if it were implicitly defined. 7154 static bool defaultedSpecialMemberIsConstexpr( 7155 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, 7156 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr, 7157 Sema::InheritedConstructorInfo *Inherited = nullptr) { 7158 if (!S.getLangOpts().CPlusPlus11) 7159 return false; 7160 7161 // C++11 [dcl.constexpr]p4: 7162 // In the definition of a constexpr constructor [...] 7163 bool Ctor = true; 7164 switch (CSM) { 7165 case Sema::CXXDefaultConstructor: 7166 if (Inherited) 7167 break; 7168 // Since default constructor lookup is essentially trivial (and cannot 7169 // involve, for instance, template instantiation), we compute whether a 7170 // defaulted default constructor is constexpr directly within CXXRecordDecl. 7171 // 7172 // This is important for performance; we need to know whether the default 7173 // constructor is constexpr to determine whether the type is a literal type. 7174 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 7175 7176 case Sema::CXXCopyConstructor: 7177 case Sema::CXXMoveConstructor: 7178 // For copy or move constructors, we need to perform overload resolution. 7179 break; 7180 7181 case Sema::CXXCopyAssignment: 7182 case Sema::CXXMoveAssignment: 7183 if (!S.getLangOpts().CPlusPlus14) 7184 return false; 7185 // In C++1y, we need to perform overload resolution. 7186 Ctor = false; 7187 break; 7188 7189 case Sema::CXXDestructor: 7190 return ClassDecl->defaultedDestructorIsConstexpr(); 7191 7192 case Sema::CXXInvalid: 7193 return false; 7194 } 7195 7196 // -- if the class is a non-empty union, or for each non-empty anonymous 7197 // union member of a non-union class, exactly one non-static data member 7198 // shall be initialized; [DR1359] 7199 // 7200 // If we squint, this is guaranteed, since exactly one non-static data member 7201 // will be initialized (if the constructor isn't deleted), we just don't know 7202 // which one. 7203 if (Ctor && ClassDecl->isUnion()) 7204 return CSM == Sema::CXXDefaultConstructor 7205 ? ClassDecl->hasInClassInitializer() || 7206 !ClassDecl->hasVariantMembers() 7207 : true; 7208 7209 // -- the class shall not have any virtual base classes; 7210 if (Ctor && ClassDecl->getNumVBases()) 7211 return false; 7212 7213 // C++1y [class.copy]p26: 7214 // -- [the class] is a literal type, and 7215 if (!Ctor && !ClassDecl->isLiteral()) 7216 return false; 7217 7218 // -- every constructor involved in initializing [...] base class 7219 // sub-objects shall be a constexpr constructor; 7220 // -- the assignment operator selected to copy/move each direct base 7221 // class is a constexpr function, and 7222 for (const auto &B : ClassDecl->bases()) { 7223 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 7224 if (!BaseType) continue; 7225 7226 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7227 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg, 7228 InheritedCtor, Inherited)) 7229 return false; 7230 } 7231 7232 // -- every constructor involved in initializing non-static data members 7233 // [...] shall be a constexpr constructor; 7234 // -- every non-static data member and base class sub-object shall be 7235 // initialized 7236 // -- for each non-static data member of X that is of class type (or array 7237 // thereof), the assignment operator selected to copy/move that member is 7238 // a constexpr function 7239 for (const auto *F : ClassDecl->fields()) { 7240 if (F->isInvalidDecl()) 7241 continue; 7242 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer()) 7243 continue; 7244 QualType BaseType = S.Context.getBaseElementType(F->getType()); 7245 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 7246 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 7247 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 7248 BaseType.getCVRQualifiers(), 7249 ConstArg && !F->isMutable())) 7250 return false; 7251 } else if (CSM == Sema::CXXDefaultConstructor) { 7252 return false; 7253 } 7254 } 7255 7256 // All OK, it's constexpr! 7257 return true; 7258 } 7259 7260 namespace { 7261 /// RAII object to register a defaulted function as having its exception 7262 /// specification computed. 7263 struct ComputingExceptionSpec { 7264 Sema &S; 7265 7266 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc) 7267 : S(S) { 7268 Sema::CodeSynthesisContext Ctx; 7269 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation; 7270 Ctx.PointOfInstantiation = Loc; 7271 Ctx.Entity = FD; 7272 S.pushCodeSynthesisContext(Ctx); 7273 } 7274 ~ComputingExceptionSpec() { 7275 S.popCodeSynthesisContext(); 7276 } 7277 }; 7278 } 7279 7280 static Sema::ImplicitExceptionSpecification 7281 ComputeDefaultedSpecialMemberExceptionSpec( 7282 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 7283 Sema::InheritedConstructorInfo *ICI); 7284 7285 static Sema::ImplicitExceptionSpecification 7286 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, 7287 FunctionDecl *FD, 7288 Sema::DefaultedComparisonKind DCK); 7289 7290 static Sema::ImplicitExceptionSpecification 7291 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) { 7292 auto DFK = S.getDefaultedFunctionKind(FD); 7293 if (DFK.isSpecialMember()) 7294 return ComputeDefaultedSpecialMemberExceptionSpec( 7295 S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr); 7296 if (DFK.isComparison()) 7297 return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD, 7298 DFK.asComparison()); 7299 7300 auto *CD = cast<CXXConstructorDecl>(FD); 7301 assert(CD->getInheritedConstructor() && 7302 "only defaulted functions and inherited constructors have implicit " 7303 "exception specs"); 7304 Sema::InheritedConstructorInfo ICI( 7305 S, Loc, CD->getInheritedConstructor().getShadowDecl()); 7306 return ComputeDefaultedSpecialMemberExceptionSpec( 7307 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI); 7308 } 7309 7310 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 7311 CXXMethodDecl *MD) { 7312 FunctionProtoType::ExtProtoInfo EPI; 7313 7314 // Build an exception specification pointing back at this member. 7315 EPI.ExceptionSpec.Type = EST_Unevaluated; 7316 EPI.ExceptionSpec.SourceDecl = MD; 7317 7318 // Set the calling convention to the default for C++ instance methods. 7319 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 7320 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 7321 /*IsCXXMethod=*/true)); 7322 return EPI; 7323 } 7324 7325 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) { 7326 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>(); 7327 if (FPT->getExceptionSpecType() != EST_Unevaluated) 7328 return; 7329 7330 // Evaluate the exception specification. 7331 auto IES = computeImplicitExceptionSpec(*this, Loc, FD); 7332 auto ESI = IES.getExceptionSpec(); 7333 7334 // Update the type of the special member to use it. 7335 UpdateExceptionSpec(FD, ESI); 7336 } 7337 7338 void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) { 7339 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted"); 7340 7341 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD); 7342 if (!DefKind) { 7343 assert(FD->getDeclContext()->isDependentContext()); 7344 return; 7345 } 7346 7347 if (DefKind.isComparison()) 7348 UnusedPrivateFields.clear(); 7349 7350 if (DefKind.isSpecialMember() 7351 ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD), 7352 DefKind.asSpecialMember()) 7353 : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison())) 7354 FD->setInvalidDecl(); 7355 } 7356 7357 bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD, 7358 CXXSpecialMember CSM) { 7359 CXXRecordDecl *RD = MD->getParent(); 7360 7361 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 7362 "not an explicitly-defaulted special member"); 7363 7364 // Defer all checking for special members of a dependent type. 7365 if (RD->isDependentType()) 7366 return false; 7367 7368 // Whether this was the first-declared instance of the constructor. 7369 // This affects whether we implicitly add an exception spec and constexpr. 7370 bool First = MD == MD->getCanonicalDecl(); 7371 7372 bool HadError = false; 7373 7374 // C++11 [dcl.fct.def.default]p1: 7375 // A function that is explicitly defaulted shall 7376 // -- be a special member function [...] (checked elsewhere), 7377 // -- have the same type (except for ref-qualifiers, and except that a 7378 // copy operation can take a non-const reference) as an implicit 7379 // declaration, and 7380 // -- not have default arguments. 7381 // C++2a changes the second bullet to instead delete the function if it's 7382 // defaulted on its first declaration, unless it's "an assignment operator, 7383 // and its return type differs or its parameter type is not a reference". 7384 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First; 7385 bool ShouldDeleteForTypeMismatch = false; 7386 unsigned ExpectedParams = 1; 7387 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 7388 ExpectedParams = 0; 7389 if (MD->getNumParams() != ExpectedParams) { 7390 // This checks for default arguments: a copy or move constructor with a 7391 // default argument is classified as a default constructor, and assignment 7392 // operations and destructors can't have default arguments. 7393 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 7394 << CSM << MD->getSourceRange(); 7395 HadError = true; 7396 } else if (MD->isVariadic()) { 7397 if (DeleteOnTypeMismatch) 7398 ShouldDeleteForTypeMismatch = true; 7399 else { 7400 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 7401 << CSM << MD->getSourceRange(); 7402 HadError = true; 7403 } 7404 } 7405 7406 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 7407 7408 bool CanHaveConstParam = false; 7409 if (CSM == CXXCopyConstructor) 7410 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 7411 else if (CSM == CXXCopyAssignment) 7412 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 7413 7414 QualType ReturnType = Context.VoidTy; 7415 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 7416 // Check for return type matching. 7417 ReturnType = Type->getReturnType(); 7418 7419 QualType DeclType = Context.getTypeDeclType(RD); 7420 DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace()); 7421 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType); 7422 7423 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 7424 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 7425 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 7426 HadError = true; 7427 } 7428 7429 // A defaulted special member cannot have cv-qualifiers. 7430 if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) { 7431 if (DeleteOnTypeMismatch) 7432 ShouldDeleteForTypeMismatch = true; 7433 else { 7434 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 7435 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 7436 HadError = true; 7437 } 7438 } 7439 } 7440 7441 // Check for parameter type matching. 7442 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 7443 bool HasConstParam = false; 7444 if (ExpectedParams && ArgType->isReferenceType()) { 7445 // Argument must be reference to possibly-const T. 7446 QualType ReferentType = ArgType->getPointeeType(); 7447 HasConstParam = ReferentType.isConstQualified(); 7448 7449 if (ReferentType.isVolatileQualified()) { 7450 if (DeleteOnTypeMismatch) 7451 ShouldDeleteForTypeMismatch = true; 7452 else { 7453 Diag(MD->getLocation(), 7454 diag::err_defaulted_special_member_volatile_param) << CSM; 7455 HadError = true; 7456 } 7457 } 7458 7459 if (HasConstParam && !CanHaveConstParam) { 7460 if (DeleteOnTypeMismatch) 7461 ShouldDeleteForTypeMismatch = true; 7462 else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 7463 Diag(MD->getLocation(), 7464 diag::err_defaulted_special_member_copy_const_param) 7465 << (CSM == CXXCopyAssignment); 7466 // FIXME: Explain why this special member can't be const. 7467 HadError = true; 7468 } else { 7469 Diag(MD->getLocation(), 7470 diag::err_defaulted_special_member_move_const_param) 7471 << (CSM == CXXMoveAssignment); 7472 HadError = true; 7473 } 7474 } 7475 } else if (ExpectedParams) { 7476 // A copy assignment operator can take its argument by value, but a 7477 // defaulted one cannot. 7478 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 7479 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 7480 HadError = true; 7481 } 7482 7483 // C++11 [dcl.fct.def.default]p2: 7484 // An explicitly-defaulted function may be declared constexpr only if it 7485 // would have been implicitly declared as constexpr, 7486 // Do not apply this rule to members of class templates, since core issue 1358 7487 // makes such functions always instantiate to constexpr functions. For 7488 // functions which cannot be constexpr (for non-constructors in C++11 and for 7489 // destructors in C++14 and C++17), this is checked elsewhere. 7490 // 7491 // FIXME: This should not apply if the member is deleted. 7492 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 7493 HasConstParam); 7494 if ((getLangOpts().CPlusPlus20 || 7495 (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 7496 : isa<CXXConstructorDecl>(MD))) && 7497 MD->isConstexpr() && !Constexpr && 7498 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 7499 Diag(MD->getBeginLoc(), MD->isConsteval() 7500 ? diag::err_incorrect_defaulted_consteval 7501 : diag::err_incorrect_defaulted_constexpr) 7502 << CSM; 7503 // FIXME: Explain why the special member can't be constexpr. 7504 HadError = true; 7505 } 7506 7507 if (First) { 7508 // C++2a [dcl.fct.def.default]p3: 7509 // If a function is explicitly defaulted on its first declaration, it is 7510 // implicitly considered to be constexpr if the implicit declaration 7511 // would be. 7512 MD->setConstexprKind(Constexpr ? (MD->isConsteval() 7513 ? ConstexprSpecKind::Consteval 7514 : ConstexprSpecKind::Constexpr) 7515 : ConstexprSpecKind::Unspecified); 7516 7517 if (!Type->hasExceptionSpec()) { 7518 // C++2a [except.spec]p3: 7519 // If a declaration of a function does not have a noexcept-specifier 7520 // [and] is defaulted on its first declaration, [...] the exception 7521 // specification is as specified below 7522 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 7523 EPI.ExceptionSpec.Type = EST_Unevaluated; 7524 EPI.ExceptionSpec.SourceDecl = MD; 7525 MD->setType(Context.getFunctionType(ReturnType, 7526 llvm::makeArrayRef(&ArgType, 7527 ExpectedParams), 7528 EPI)); 7529 } 7530 } 7531 7532 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) { 7533 if (First) { 7534 SetDeclDeleted(MD, MD->getLocation()); 7535 if (!inTemplateInstantiation() && !HadError) { 7536 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM; 7537 if (ShouldDeleteForTypeMismatch) { 7538 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM; 7539 } else { 7540 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 7541 } 7542 } 7543 if (ShouldDeleteForTypeMismatch && !HadError) { 7544 Diag(MD->getLocation(), 7545 diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM; 7546 } 7547 } else { 7548 // C++11 [dcl.fct.def.default]p4: 7549 // [For a] user-provided explicitly-defaulted function [...] if such a 7550 // function is implicitly defined as deleted, the program is ill-formed. 7551 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 7552 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl"); 7553 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 7554 HadError = true; 7555 } 7556 } 7557 7558 return HadError; 7559 } 7560 7561 namespace { 7562 /// Helper class for building and checking a defaulted comparison. 7563 /// 7564 /// Defaulted functions are built in two phases: 7565 /// 7566 /// * First, the set of operations that the function will perform are 7567 /// identified, and some of them are checked. If any of the checked 7568 /// operations is invalid in certain ways, the comparison function is 7569 /// defined as deleted and no body is built. 7570 /// * Then, if the function is not defined as deleted, the body is built. 7571 /// 7572 /// This is accomplished by performing two visitation steps over the eventual 7573 /// body of the function. 7574 template<typename Derived, typename ResultList, typename Result, 7575 typename Subobject> 7576 class DefaultedComparisonVisitor { 7577 public: 7578 using DefaultedComparisonKind = Sema::DefaultedComparisonKind; 7579 7580 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7581 DefaultedComparisonKind DCK) 7582 : S(S), RD(RD), FD(FD), DCK(DCK) { 7583 if (auto *Info = FD->getDefaultedFunctionInfo()) { 7584 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an 7585 // UnresolvedSet to avoid this copy. 7586 Fns.assign(Info->getUnqualifiedLookups().begin(), 7587 Info->getUnqualifiedLookups().end()); 7588 } 7589 } 7590 7591 ResultList visit() { 7592 // The type of an lvalue naming a parameter of this function. 7593 QualType ParamLvalType = 7594 FD->getParamDecl(0)->getType().getNonReferenceType(); 7595 7596 ResultList Results; 7597 7598 switch (DCK) { 7599 case DefaultedComparisonKind::None: 7600 llvm_unreachable("not a defaulted comparison"); 7601 7602 case DefaultedComparisonKind::Equal: 7603 case DefaultedComparisonKind::ThreeWay: 7604 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers()); 7605 return Results; 7606 7607 case DefaultedComparisonKind::NotEqual: 7608 case DefaultedComparisonKind::Relational: 7609 Results.add(getDerived().visitExpandedSubobject( 7610 ParamLvalType, getDerived().getCompleteObject())); 7611 return Results; 7612 } 7613 llvm_unreachable(""); 7614 } 7615 7616 protected: 7617 Derived &getDerived() { return static_cast<Derived&>(*this); } 7618 7619 /// Visit the expanded list of subobjects of the given type, as specified in 7620 /// C++2a [class.compare.default]. 7621 /// 7622 /// \return \c true if the ResultList object said we're done, \c false if not. 7623 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record, 7624 Qualifiers Quals) { 7625 // C++2a [class.compare.default]p4: 7626 // The direct base class subobjects of C 7627 for (CXXBaseSpecifier &Base : Record->bases()) 7628 if (Results.add(getDerived().visitSubobject( 7629 S.Context.getQualifiedType(Base.getType(), Quals), 7630 getDerived().getBase(&Base)))) 7631 return true; 7632 7633 // followed by the non-static data members of C 7634 for (FieldDecl *Field : Record->fields()) { 7635 // Recursively expand anonymous structs. 7636 if (Field->isAnonymousStructOrUnion()) { 7637 if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(), 7638 Quals)) 7639 return true; 7640 continue; 7641 } 7642 7643 // Figure out the type of an lvalue denoting this field. 7644 Qualifiers FieldQuals = Quals; 7645 if (Field->isMutable()) 7646 FieldQuals.removeConst(); 7647 QualType FieldType = 7648 S.Context.getQualifiedType(Field->getType(), FieldQuals); 7649 7650 if (Results.add(getDerived().visitSubobject( 7651 FieldType, getDerived().getField(Field)))) 7652 return true; 7653 } 7654 7655 // form a list of subobjects. 7656 return false; 7657 } 7658 7659 Result visitSubobject(QualType Type, Subobject Subobj) { 7660 // In that list, any subobject of array type is recursively expanded 7661 const ArrayType *AT = S.Context.getAsArrayType(Type); 7662 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT)) 7663 return getDerived().visitSubobjectArray(CAT->getElementType(), 7664 CAT->getSize(), Subobj); 7665 return getDerived().visitExpandedSubobject(Type, Subobj); 7666 } 7667 7668 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size, 7669 Subobject Subobj) { 7670 return getDerived().visitSubobject(Type, Subobj); 7671 } 7672 7673 protected: 7674 Sema &S; 7675 CXXRecordDecl *RD; 7676 FunctionDecl *FD; 7677 DefaultedComparisonKind DCK; 7678 UnresolvedSet<16> Fns; 7679 }; 7680 7681 /// Information about a defaulted comparison, as determined by 7682 /// DefaultedComparisonAnalyzer. 7683 struct DefaultedComparisonInfo { 7684 bool Deleted = false; 7685 bool Constexpr = true; 7686 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering; 7687 7688 static DefaultedComparisonInfo deleted() { 7689 DefaultedComparisonInfo Deleted; 7690 Deleted.Deleted = true; 7691 return Deleted; 7692 } 7693 7694 bool add(const DefaultedComparisonInfo &R) { 7695 Deleted |= R.Deleted; 7696 Constexpr &= R.Constexpr; 7697 Category = commonComparisonType(Category, R.Category); 7698 return Deleted; 7699 } 7700 }; 7701 7702 /// An element in the expanded list of subobjects of a defaulted comparison, as 7703 /// specified in C++2a [class.compare.default]p4. 7704 struct DefaultedComparisonSubobject { 7705 enum { CompleteObject, Member, Base } Kind; 7706 NamedDecl *Decl; 7707 SourceLocation Loc; 7708 }; 7709 7710 /// A visitor over the notional body of a defaulted comparison that determines 7711 /// whether that body would be deleted or constexpr. 7712 class DefaultedComparisonAnalyzer 7713 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer, 7714 DefaultedComparisonInfo, 7715 DefaultedComparisonInfo, 7716 DefaultedComparisonSubobject> { 7717 public: 7718 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr }; 7719 7720 private: 7721 DiagnosticKind Diagnose; 7722 7723 public: 7724 using Base = DefaultedComparisonVisitor; 7725 using Result = DefaultedComparisonInfo; 7726 using Subobject = DefaultedComparisonSubobject; 7727 7728 friend Base; 7729 7730 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7731 DefaultedComparisonKind DCK, 7732 DiagnosticKind Diagnose = NoDiagnostics) 7733 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {} 7734 7735 Result visit() { 7736 if ((DCK == DefaultedComparisonKind::Equal || 7737 DCK == DefaultedComparisonKind::ThreeWay) && 7738 RD->hasVariantMembers()) { 7739 // C++2a [class.compare.default]p2 [P2002R0]: 7740 // A defaulted comparison operator function for class C is defined as 7741 // deleted if [...] C has variant members. 7742 if (Diagnose == ExplainDeleted) { 7743 S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union) 7744 << FD << RD->isUnion() << RD; 7745 } 7746 return Result::deleted(); 7747 } 7748 7749 return Base::visit(); 7750 } 7751 7752 private: 7753 Subobject getCompleteObject() { 7754 return Subobject{Subobject::CompleteObject, RD, FD->getLocation()}; 7755 } 7756 7757 Subobject getBase(CXXBaseSpecifier *Base) { 7758 return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(), 7759 Base->getBaseTypeLoc()}; 7760 } 7761 7762 Subobject getField(FieldDecl *Field) { 7763 return Subobject{Subobject::Member, Field, Field->getLocation()}; 7764 } 7765 7766 Result visitExpandedSubobject(QualType Type, Subobject Subobj) { 7767 // C++2a [class.compare.default]p2 [P2002R0]: 7768 // A defaulted <=> or == operator function for class C is defined as 7769 // deleted if any non-static data member of C is of reference type 7770 if (Type->isReferenceType()) { 7771 if (Diagnose == ExplainDeleted) { 7772 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member) 7773 << FD << RD; 7774 } 7775 return Result::deleted(); 7776 } 7777 7778 // [...] Let xi be an lvalue denoting the ith element [...] 7779 OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue); 7780 Expr *Args[] = {&Xi, &Xi}; 7781 7782 // All operators start by trying to apply that same operator recursively. 7783 OverloadedOperatorKind OO = FD->getOverloadedOperator(); 7784 assert(OO != OO_None && "not an overloaded operator!"); 7785 return visitBinaryOperator(OO, Args, Subobj); 7786 } 7787 7788 Result 7789 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args, 7790 Subobject Subobj, 7791 OverloadCandidateSet *SpaceshipCandidates = nullptr) { 7792 // Note that there is no need to consider rewritten candidates here if 7793 // we've already found there is no viable 'operator<=>' candidate (and are 7794 // considering synthesizing a '<=>' from '==' and '<'). 7795 OverloadCandidateSet CandidateSet( 7796 FD->getLocation(), OverloadCandidateSet::CSK_Operator, 7797 OverloadCandidateSet::OperatorRewriteInfo( 7798 OO, /*AllowRewrittenCandidates=*/!SpaceshipCandidates)); 7799 7800 /// C++2a [class.compare.default]p1 [P2002R0]: 7801 /// [...] the defaulted function itself is never a candidate for overload 7802 /// resolution [...] 7803 CandidateSet.exclude(FD); 7804 7805 if (Args[0]->getType()->isOverloadableType()) 7806 S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args); 7807 else 7808 // FIXME: We determine whether this is a valid expression by checking to 7809 // see if there's a viable builtin operator candidate for it. That isn't 7810 // really what the rules ask us to do, but should give the right results. 7811 S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet); 7812 7813 Result R; 7814 7815 OverloadCandidateSet::iterator Best; 7816 switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) { 7817 case OR_Success: { 7818 // C++2a [class.compare.secondary]p2 [P2002R0]: 7819 // The operator function [...] is defined as deleted if [...] the 7820 // candidate selected by overload resolution is not a rewritten 7821 // candidate. 7822 if ((DCK == DefaultedComparisonKind::NotEqual || 7823 DCK == DefaultedComparisonKind::Relational) && 7824 !Best->RewriteKind) { 7825 if (Diagnose == ExplainDeleted) { 7826 if (Best->Function) { 7827 S.Diag(Best->Function->getLocation(), 7828 diag::note_defaulted_comparison_not_rewritten_callee) 7829 << FD; 7830 } else { 7831 assert(Best->Conversions.size() == 2 && 7832 Best->Conversions[0].isUserDefined() && 7833 "non-user-defined conversion from class to built-in " 7834 "comparison"); 7835 S.Diag(Best->Conversions[0] 7836 .UserDefined.FoundConversionFunction.getDecl() 7837 ->getLocation(), 7838 diag::note_defaulted_comparison_not_rewritten_conversion) 7839 << FD; 7840 } 7841 } 7842 return Result::deleted(); 7843 } 7844 7845 // Throughout C++2a [class.compare]: if overload resolution does not 7846 // result in a usable function, the candidate function is defined as 7847 // deleted. This requires that we selected an accessible function. 7848 // 7849 // Note that this only considers the access of the function when named 7850 // within the type of the subobject, and not the access path for any 7851 // derived-to-base conversion. 7852 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl(); 7853 if (ArgClass && Best->FoundDecl.getDecl() && 7854 Best->FoundDecl.getDecl()->isCXXClassMember()) { 7855 QualType ObjectType = Subobj.Kind == Subobject::Member 7856 ? Args[0]->getType() 7857 : S.Context.getRecordType(RD); 7858 if (!S.isMemberAccessibleForDeletion( 7859 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc, 7860 Diagnose == ExplainDeleted 7861 ? S.PDiag(diag::note_defaulted_comparison_inaccessible) 7862 << FD << Subobj.Kind << Subobj.Decl 7863 : S.PDiag())) 7864 return Result::deleted(); 7865 } 7866 7867 bool NeedsDeducing = 7868 OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType(); 7869 7870 if (FunctionDecl *BestFD = Best->Function) { 7871 // C++2a [class.compare.default]p3 [P2002R0]: 7872 // A defaulted comparison function is constexpr-compatible if 7873 // [...] no overlod resolution performed [...] results in a 7874 // non-constexpr function. 7875 assert(!BestFD->isDeleted() && "wrong overload resolution result"); 7876 // If it's not constexpr, explain why not. 7877 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) { 7878 if (Subobj.Kind != Subobject::CompleteObject) 7879 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr) 7880 << Subobj.Kind << Subobj.Decl; 7881 S.Diag(BestFD->getLocation(), 7882 diag::note_defaulted_comparison_not_constexpr_here); 7883 // Bail out after explaining; we don't want any more notes. 7884 return Result::deleted(); 7885 } 7886 R.Constexpr &= BestFD->isConstexpr(); 7887 7888 if (NeedsDeducing) { 7889 // If any callee has an undeduced return type, deduce it now. 7890 // FIXME: It's not clear how a failure here should be handled. For 7891 // now, we produce an eager diagnostic, because that is forward 7892 // compatible with most (all?) other reasonable options. 7893 if (BestFD->getReturnType()->isUndeducedType() && 7894 S.DeduceReturnType(BestFD, FD->getLocation(), 7895 /*Diagnose=*/false)) { 7896 // Don't produce a duplicate error when asked to explain why the 7897 // comparison is deleted: we diagnosed that when initially checking 7898 // the defaulted operator. 7899 if (Diagnose == NoDiagnostics) { 7900 S.Diag( 7901 FD->getLocation(), 7902 diag::err_defaulted_comparison_cannot_deduce_undeduced_auto) 7903 << Subobj.Kind << Subobj.Decl; 7904 S.Diag( 7905 Subobj.Loc, 7906 diag::note_defaulted_comparison_cannot_deduce_undeduced_auto) 7907 << Subobj.Kind << Subobj.Decl; 7908 S.Diag(BestFD->getLocation(), 7909 diag::note_defaulted_comparison_cannot_deduce_callee) 7910 << Subobj.Kind << Subobj.Decl; 7911 } 7912 return Result::deleted(); 7913 } 7914 auto *Info = S.Context.CompCategories.lookupInfoForType( 7915 BestFD->getCallResultType()); 7916 if (!Info) { 7917 if (Diagnose == ExplainDeleted) { 7918 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce) 7919 << Subobj.Kind << Subobj.Decl 7920 << BestFD->getCallResultType().withoutLocalFastQualifiers(); 7921 S.Diag(BestFD->getLocation(), 7922 diag::note_defaulted_comparison_cannot_deduce_callee) 7923 << Subobj.Kind << Subobj.Decl; 7924 } 7925 return Result::deleted(); 7926 } 7927 R.Category = Info->Kind; 7928 } 7929 } else { 7930 QualType T = Best->BuiltinParamTypes[0]; 7931 assert(T == Best->BuiltinParamTypes[1] && 7932 "builtin comparison for different types?"); 7933 assert(Best->BuiltinParamTypes[2].isNull() && 7934 "invalid builtin comparison"); 7935 7936 if (NeedsDeducing) { 7937 Optional<ComparisonCategoryType> Cat = 7938 getComparisonCategoryForBuiltinCmp(T); 7939 assert(Cat && "no category for builtin comparison?"); 7940 R.Category = *Cat; 7941 } 7942 } 7943 7944 // Note that we might be rewriting to a different operator. That call is 7945 // not considered until we come to actually build the comparison function. 7946 break; 7947 } 7948 7949 case OR_Ambiguous: 7950 if (Diagnose == ExplainDeleted) { 7951 unsigned Kind = 0; 7952 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship) 7953 Kind = OO == OO_EqualEqual ? 1 : 2; 7954 CandidateSet.NoteCandidates( 7955 PartialDiagnosticAt( 7956 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous) 7957 << FD << Kind << Subobj.Kind << Subobj.Decl), 7958 S, OCD_AmbiguousCandidates, Args); 7959 } 7960 R = Result::deleted(); 7961 break; 7962 7963 case OR_Deleted: 7964 if (Diagnose == ExplainDeleted) { 7965 if ((DCK == DefaultedComparisonKind::NotEqual || 7966 DCK == DefaultedComparisonKind::Relational) && 7967 !Best->RewriteKind) { 7968 S.Diag(Best->Function->getLocation(), 7969 diag::note_defaulted_comparison_not_rewritten_callee) 7970 << FD; 7971 } else { 7972 S.Diag(Subobj.Loc, 7973 diag::note_defaulted_comparison_calls_deleted) 7974 << FD << Subobj.Kind << Subobj.Decl; 7975 S.NoteDeletedFunction(Best->Function); 7976 } 7977 } 7978 R = Result::deleted(); 7979 break; 7980 7981 case OR_No_Viable_Function: 7982 // If there's no usable candidate, we're done unless we can rewrite a 7983 // '<=>' in terms of '==' and '<'. 7984 if (OO == OO_Spaceship && 7985 S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) { 7986 // For any kind of comparison category return type, we need a usable 7987 // '==' and a usable '<'. 7988 if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj, 7989 &CandidateSet))) 7990 R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet)); 7991 break; 7992 } 7993 7994 if (Diagnose == ExplainDeleted) { 7995 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function) 7996 << FD << (OO == OO_ExclaimEqual) << Subobj.Kind << Subobj.Decl; 7997 7998 // For a three-way comparison, list both the candidates for the 7999 // original operator and the candidates for the synthesized operator. 8000 if (SpaceshipCandidates) { 8001 SpaceshipCandidates->NoteCandidates( 8002 S, Args, 8003 SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates, 8004 Args, FD->getLocation())); 8005 S.Diag(Subobj.Loc, 8006 diag::note_defaulted_comparison_no_viable_function_synthesized) 8007 << (OO == OO_EqualEqual ? 0 : 1); 8008 } 8009 8010 CandidateSet.NoteCandidates( 8011 S, Args, 8012 CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args, 8013 FD->getLocation())); 8014 } 8015 R = Result::deleted(); 8016 break; 8017 } 8018 8019 return R; 8020 } 8021 }; 8022 8023 /// A list of statements. 8024 struct StmtListResult { 8025 bool IsInvalid = false; 8026 llvm::SmallVector<Stmt*, 16> Stmts; 8027 8028 bool add(const StmtResult &S) { 8029 IsInvalid |= S.isInvalid(); 8030 if (IsInvalid) 8031 return true; 8032 Stmts.push_back(S.get()); 8033 return false; 8034 } 8035 }; 8036 8037 /// A visitor over the notional body of a defaulted comparison that synthesizes 8038 /// the actual body. 8039 class DefaultedComparisonSynthesizer 8040 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer, 8041 StmtListResult, StmtResult, 8042 std::pair<ExprResult, ExprResult>> { 8043 SourceLocation Loc; 8044 unsigned ArrayDepth = 0; 8045 8046 public: 8047 using Base = DefaultedComparisonVisitor; 8048 using ExprPair = std::pair<ExprResult, ExprResult>; 8049 8050 friend Base; 8051 8052 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 8053 DefaultedComparisonKind DCK, 8054 SourceLocation BodyLoc) 8055 : Base(S, RD, FD, DCK), Loc(BodyLoc) {} 8056 8057 /// Build a suitable function body for this defaulted comparison operator. 8058 StmtResult build() { 8059 Sema::CompoundScopeRAII CompoundScope(S); 8060 8061 StmtListResult Stmts = visit(); 8062 if (Stmts.IsInvalid) 8063 return StmtError(); 8064 8065 ExprResult RetVal; 8066 switch (DCK) { 8067 case DefaultedComparisonKind::None: 8068 llvm_unreachable("not a defaulted comparison"); 8069 8070 case DefaultedComparisonKind::Equal: { 8071 // C++2a [class.eq]p3: 8072 // [...] compar[e] the corresponding elements [...] until the first 8073 // index i where xi == yi yields [...] false. If no such index exists, 8074 // V is true. Otherwise, V is false. 8075 // 8076 // Join the comparisons with '&&'s and return the result. Use a right 8077 // fold (traversing the conditions right-to-left), because that 8078 // short-circuits more naturally. 8079 auto OldStmts = std::move(Stmts.Stmts); 8080 Stmts.Stmts.clear(); 8081 ExprResult CmpSoFar; 8082 // Finish a particular comparison chain. 8083 auto FinishCmp = [&] { 8084 if (Expr *Prior = CmpSoFar.get()) { 8085 // Convert the last expression to 'return ...;' 8086 if (RetVal.isUnset() && Stmts.Stmts.empty()) 8087 RetVal = CmpSoFar; 8088 // Convert any prior comparison to 'if (!(...)) return false;' 8089 else if (Stmts.add(buildIfNotCondReturnFalse(Prior))) 8090 return true; 8091 CmpSoFar = ExprResult(); 8092 } 8093 return false; 8094 }; 8095 for (Stmt *EAsStmt : llvm::reverse(OldStmts)) { 8096 Expr *E = dyn_cast<Expr>(EAsStmt); 8097 if (!E) { 8098 // Found an array comparison. 8099 if (FinishCmp() || Stmts.add(EAsStmt)) 8100 return StmtError(); 8101 continue; 8102 } 8103 8104 if (CmpSoFar.isUnset()) { 8105 CmpSoFar = E; 8106 continue; 8107 } 8108 CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get()); 8109 if (CmpSoFar.isInvalid()) 8110 return StmtError(); 8111 } 8112 if (FinishCmp()) 8113 return StmtError(); 8114 std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end()); 8115 // If no such index exists, V is true. 8116 if (RetVal.isUnset()) 8117 RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true); 8118 break; 8119 } 8120 8121 case DefaultedComparisonKind::ThreeWay: { 8122 // Per C++2a [class.spaceship]p3, as a fallback add: 8123 // return static_cast<R>(std::strong_ordering::equal); 8124 QualType StrongOrdering = S.CheckComparisonCategoryType( 8125 ComparisonCategoryType::StrongOrdering, Loc, 8126 Sema::ComparisonCategoryUsage::DefaultedOperator); 8127 if (StrongOrdering.isNull()) 8128 return StmtError(); 8129 VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering) 8130 .getValueInfo(ComparisonCategoryResult::Equal) 8131 ->VD; 8132 RetVal = getDecl(EqualVD); 8133 if (RetVal.isInvalid()) 8134 return StmtError(); 8135 RetVal = buildStaticCastToR(RetVal.get()); 8136 break; 8137 } 8138 8139 case DefaultedComparisonKind::NotEqual: 8140 case DefaultedComparisonKind::Relational: 8141 RetVal = cast<Expr>(Stmts.Stmts.pop_back_val()); 8142 break; 8143 } 8144 8145 // Build the final return statement. 8146 if (RetVal.isInvalid()) 8147 return StmtError(); 8148 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get()); 8149 if (ReturnStmt.isInvalid()) 8150 return StmtError(); 8151 Stmts.Stmts.push_back(ReturnStmt.get()); 8152 8153 return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false); 8154 } 8155 8156 private: 8157 ExprResult getDecl(ValueDecl *VD) { 8158 return S.BuildDeclarationNameExpr( 8159 CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD); 8160 } 8161 8162 ExprResult getParam(unsigned I) { 8163 ParmVarDecl *PD = FD->getParamDecl(I); 8164 return getDecl(PD); 8165 } 8166 8167 ExprPair getCompleteObject() { 8168 unsigned Param = 0; 8169 ExprResult LHS; 8170 if (isa<CXXMethodDecl>(FD)) { 8171 // LHS is '*this'. 8172 LHS = S.ActOnCXXThis(Loc); 8173 if (!LHS.isInvalid()) 8174 LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get()); 8175 } else { 8176 LHS = getParam(Param++); 8177 } 8178 ExprResult RHS = getParam(Param++); 8179 assert(Param == FD->getNumParams()); 8180 return {LHS, RHS}; 8181 } 8182 8183 ExprPair getBase(CXXBaseSpecifier *Base) { 8184 ExprPair Obj = getCompleteObject(); 8185 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 8186 return {ExprError(), ExprError()}; 8187 CXXCastPath Path = {Base}; 8188 return {S.ImpCastExprToType(Obj.first.get(), Base->getType(), 8189 CK_DerivedToBase, VK_LValue, &Path), 8190 S.ImpCastExprToType(Obj.second.get(), Base->getType(), 8191 CK_DerivedToBase, VK_LValue, &Path)}; 8192 } 8193 8194 ExprPair getField(FieldDecl *Field) { 8195 ExprPair Obj = getCompleteObject(); 8196 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 8197 return {ExprError(), ExprError()}; 8198 8199 DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess()); 8200 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc); 8201 return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc, 8202 CXXScopeSpec(), Field, Found, NameInfo), 8203 S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc, 8204 CXXScopeSpec(), Field, Found, NameInfo)}; 8205 } 8206 8207 // FIXME: When expanding a subobject, register a note in the code synthesis 8208 // stack to say which subobject we're comparing. 8209 8210 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) { 8211 if (Cond.isInvalid()) 8212 return StmtError(); 8213 8214 ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get()); 8215 if (NotCond.isInvalid()) 8216 return StmtError(); 8217 8218 ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false); 8219 assert(!False.isInvalid() && "should never fail"); 8220 StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get()); 8221 if (ReturnFalse.isInvalid()) 8222 return StmtError(); 8223 8224 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, nullptr, 8225 S.ActOnCondition(nullptr, Loc, NotCond.get(), 8226 Sema::ConditionKind::Boolean), 8227 Loc, ReturnFalse.get(), SourceLocation(), nullptr); 8228 } 8229 8230 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size, 8231 ExprPair Subobj) { 8232 QualType SizeType = S.Context.getSizeType(); 8233 Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType)); 8234 8235 // Build 'size_t i$n = 0'. 8236 IdentifierInfo *IterationVarName = nullptr; 8237 { 8238 SmallString<8> Str; 8239 llvm::raw_svector_ostream OS(Str); 8240 OS << "i" << ArrayDepth; 8241 IterationVarName = &S.Context.Idents.get(OS.str()); 8242 } 8243 VarDecl *IterationVar = VarDecl::Create( 8244 S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType, 8245 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None); 8246 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 8247 IterationVar->setInit( 8248 IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 8249 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc); 8250 8251 auto IterRef = [&] { 8252 ExprResult Ref = S.BuildDeclarationNameExpr( 8253 CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc), 8254 IterationVar); 8255 assert(!Ref.isInvalid() && "can't reference our own variable?"); 8256 return Ref.get(); 8257 }; 8258 8259 // Build 'i$n != Size'. 8260 ExprResult Cond = S.CreateBuiltinBinOp( 8261 Loc, BO_NE, IterRef(), 8262 IntegerLiteral::Create(S.Context, Size, SizeType, Loc)); 8263 assert(!Cond.isInvalid() && "should never fail"); 8264 8265 // Build '++i$n'. 8266 ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef()); 8267 assert(!Inc.isInvalid() && "should never fail"); 8268 8269 // Build 'a[i$n]' and 'b[i$n]'. 8270 auto Index = [&](ExprResult E) { 8271 if (E.isInvalid()) 8272 return ExprError(); 8273 return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc); 8274 }; 8275 Subobj.first = Index(Subobj.first); 8276 Subobj.second = Index(Subobj.second); 8277 8278 // Compare the array elements. 8279 ++ArrayDepth; 8280 StmtResult Substmt = visitSubobject(Type, Subobj); 8281 --ArrayDepth; 8282 8283 if (Substmt.isInvalid()) 8284 return StmtError(); 8285 8286 // For the inner level of an 'operator==', build 'if (!cmp) return false;'. 8287 // For outer levels or for an 'operator<=>' we already have a suitable 8288 // statement that returns as necessary. 8289 if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) { 8290 assert(DCK == DefaultedComparisonKind::Equal && 8291 "should have non-expression statement"); 8292 Substmt = buildIfNotCondReturnFalse(ElemCmp); 8293 if (Substmt.isInvalid()) 8294 return StmtError(); 8295 } 8296 8297 // Build 'for (...) ...' 8298 return S.ActOnForStmt(Loc, Loc, Init, 8299 S.ActOnCondition(nullptr, Loc, Cond.get(), 8300 Sema::ConditionKind::Boolean), 8301 S.MakeFullDiscardedValueExpr(Inc.get()), Loc, 8302 Substmt.get()); 8303 } 8304 8305 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) { 8306 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 8307 return StmtError(); 8308 8309 OverloadedOperatorKind OO = FD->getOverloadedOperator(); 8310 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO); 8311 ExprResult Op; 8312 if (Type->isOverloadableType()) 8313 Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(), 8314 Obj.second.get(), /*PerformADL=*/true, 8315 /*AllowRewrittenCandidates=*/true, FD); 8316 else 8317 Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get()); 8318 if (Op.isInvalid()) 8319 return StmtError(); 8320 8321 switch (DCK) { 8322 case DefaultedComparisonKind::None: 8323 llvm_unreachable("not a defaulted comparison"); 8324 8325 case DefaultedComparisonKind::Equal: 8326 // Per C++2a [class.eq]p2, each comparison is individually contextually 8327 // converted to bool. 8328 Op = S.PerformContextuallyConvertToBool(Op.get()); 8329 if (Op.isInvalid()) 8330 return StmtError(); 8331 return Op.get(); 8332 8333 case DefaultedComparisonKind::ThreeWay: { 8334 // Per C++2a [class.spaceship]p3, form: 8335 // if (R cmp = static_cast<R>(op); cmp != 0) 8336 // return cmp; 8337 QualType R = FD->getReturnType(); 8338 Op = buildStaticCastToR(Op.get()); 8339 if (Op.isInvalid()) 8340 return StmtError(); 8341 8342 // R cmp = ...; 8343 IdentifierInfo *Name = &S.Context.Idents.get("cmp"); 8344 VarDecl *VD = 8345 VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R, 8346 S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None); 8347 S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false); 8348 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc); 8349 8350 // cmp != 0 8351 ExprResult VDRef = getDecl(VD); 8352 if (VDRef.isInvalid()) 8353 return StmtError(); 8354 llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0); 8355 Expr *Zero = 8356 IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc); 8357 ExprResult Comp; 8358 if (VDRef.get()->getType()->isOverloadableType()) 8359 Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true, 8360 true, FD); 8361 else 8362 Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero); 8363 if (Comp.isInvalid()) 8364 return StmtError(); 8365 Sema::ConditionResult Cond = S.ActOnCondition( 8366 nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean); 8367 if (Cond.isInvalid()) 8368 return StmtError(); 8369 8370 // return cmp; 8371 VDRef = getDecl(VD); 8372 if (VDRef.isInvalid()) 8373 return StmtError(); 8374 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get()); 8375 if (ReturnStmt.isInvalid()) 8376 return StmtError(); 8377 8378 // if (...) 8379 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, InitStmt, Cond, 8380 Loc, ReturnStmt.get(), 8381 /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr); 8382 } 8383 8384 case DefaultedComparisonKind::NotEqual: 8385 case DefaultedComparisonKind::Relational: 8386 // C++2a [class.compare.secondary]p2: 8387 // Otherwise, the operator function yields x @ y. 8388 return Op.get(); 8389 } 8390 llvm_unreachable(""); 8391 } 8392 8393 /// Build "static_cast<R>(E)". 8394 ExprResult buildStaticCastToR(Expr *E) { 8395 QualType R = FD->getReturnType(); 8396 assert(!R->isUndeducedType() && "type should have been deduced already"); 8397 8398 // Don't bother forming a no-op cast in the common case. 8399 if (E->isPRValue() && S.Context.hasSameType(E->getType(), R)) 8400 return E; 8401 return S.BuildCXXNamedCast(Loc, tok::kw_static_cast, 8402 S.Context.getTrivialTypeSourceInfo(R, Loc), E, 8403 SourceRange(Loc, Loc), SourceRange(Loc, Loc)); 8404 } 8405 }; 8406 } 8407 8408 /// Perform the unqualified lookups that might be needed to form a defaulted 8409 /// comparison function for the given operator. 8410 static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S, 8411 UnresolvedSetImpl &Operators, 8412 OverloadedOperatorKind Op) { 8413 auto Lookup = [&](OverloadedOperatorKind OO) { 8414 Self.LookupOverloadedOperatorName(OO, S, Operators); 8415 }; 8416 8417 // Every defaulted operator looks up itself. 8418 Lookup(Op); 8419 // ... and the rewritten form of itself, if any. 8420 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op)) 8421 Lookup(ExtraOp); 8422 8423 // For 'operator<=>', we also form a 'cmp != 0' expression, and might 8424 // synthesize a three-way comparison from '<' and '=='. In a dependent 8425 // context, we also need to look up '==' in case we implicitly declare a 8426 // defaulted 'operator=='. 8427 if (Op == OO_Spaceship) { 8428 Lookup(OO_ExclaimEqual); 8429 Lookup(OO_Less); 8430 Lookup(OO_EqualEqual); 8431 } 8432 } 8433 8434 bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD, 8435 DefaultedComparisonKind DCK) { 8436 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison"); 8437 8438 // Perform any unqualified lookups we're going to need to default this 8439 // function. 8440 if (S) { 8441 UnresolvedSet<32> Operators; 8442 lookupOperatorsForDefaultedComparison(*this, S, Operators, 8443 FD->getOverloadedOperator()); 8444 FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create( 8445 Context, Operators.pairs())); 8446 } 8447 8448 // C++2a [class.compare.default]p1: 8449 // A defaulted comparison operator function for some class C shall be a 8450 // non-template function declared in the member-specification of C that is 8451 // -- a non-static const member of C having one parameter of type 8452 // const C&, or 8453 // -- a friend of C having two parameters of type const C& or two 8454 // parameters of type C. 8455 8456 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()); 8457 bool IsMethod = isa<CXXMethodDecl>(FD); 8458 if (IsMethod) { 8459 auto *MD = cast<CXXMethodDecl>(FD); 8460 assert(!MD->isStatic() && "comparison function cannot be a static member"); 8461 8462 // If we're out-of-class, this is the class we're comparing. 8463 if (!RD) 8464 RD = MD->getParent(); 8465 8466 if (!MD->isConst()) { 8467 SourceLocation InsertLoc; 8468 if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc()) 8469 InsertLoc = getLocForEndOfToken(Loc.getRParenLoc()); 8470 // Don't diagnose an implicit 'operator=='; we will have diagnosed the 8471 // corresponding defaulted 'operator<=>' already. 8472 if (!MD->isImplicit()) { 8473 Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const) 8474 << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const"); 8475 } 8476 8477 // Add the 'const' to the type to recover. 8478 const auto *FPT = MD->getType()->castAs<FunctionProtoType>(); 8479 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8480 EPI.TypeQuals.addConst(); 8481 MD->setType(Context.getFunctionType(FPT->getReturnType(), 8482 FPT->getParamTypes(), EPI)); 8483 } 8484 } 8485 8486 if (FD->getNumParams() != (IsMethod ? 1 : 2)) { 8487 // Let's not worry about using a variadic template pack here -- who would do 8488 // such a thing? 8489 Diag(FD->getLocation(), diag::err_defaulted_comparison_num_args) 8490 << int(IsMethod) << int(DCK); 8491 return true; 8492 } 8493 8494 const ParmVarDecl *KnownParm = nullptr; 8495 for (const ParmVarDecl *Param : FD->parameters()) { 8496 QualType ParmTy = Param->getType(); 8497 if (ParmTy->isDependentType()) 8498 continue; 8499 if (!KnownParm) { 8500 auto CTy = ParmTy; 8501 // Is it `T const &`? 8502 bool Ok = !IsMethod; 8503 QualType ExpectedTy; 8504 if (RD) 8505 ExpectedTy = Context.getRecordType(RD); 8506 if (auto *Ref = CTy->getAs<ReferenceType>()) { 8507 CTy = Ref->getPointeeType(); 8508 if (RD) 8509 ExpectedTy.addConst(); 8510 Ok = true; 8511 } 8512 8513 // Is T a class? 8514 if (!Ok) { 8515 } else if (RD) { 8516 if (!RD->isDependentType() && !Context.hasSameType(CTy, ExpectedTy)) 8517 Ok = false; 8518 } else if (auto *CRD = CTy->getAsRecordDecl()) { 8519 RD = cast<CXXRecordDecl>(CRD); 8520 } else { 8521 Ok = false; 8522 } 8523 8524 if (Ok) { 8525 KnownParm = Param; 8526 } else { 8527 // Don't diagnose an implicit 'operator=='; we will have diagnosed the 8528 // corresponding defaulted 'operator<=>' already. 8529 if (!FD->isImplicit()) { 8530 if (RD) { 8531 QualType PlainTy = Context.getRecordType(RD); 8532 QualType RefTy = 8533 Context.getLValueReferenceType(PlainTy.withConst()); 8534 if (IsMethod) 8535 PlainTy = QualType(); 8536 Diag(FD->getLocation(), diag::err_defaulted_comparison_param) 8537 << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy 8538 << Param->getSourceRange(); 8539 } else { 8540 assert(!IsMethod && "should know expected type for method"); 8541 Diag(FD->getLocation(), 8542 diag::err_defaulted_comparison_param_unknown) 8543 << int(DCK) << ParmTy << Param->getSourceRange(); 8544 } 8545 } 8546 return true; 8547 } 8548 } else if (!Context.hasSameType(KnownParm->getType(), ParmTy)) { 8549 Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch) 8550 << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange() 8551 << ParmTy << Param->getSourceRange(); 8552 return true; 8553 } 8554 } 8555 8556 assert(RD && "must have determined class"); 8557 if (IsMethod) { 8558 } else if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 8559 // In-class, must be a friend decl. 8560 assert(FD->getFriendObjectKind() && "expected a friend declaration"); 8561 } else { 8562 // Out of class, require the defaulted comparison to be a friend (of a 8563 // complete type). 8564 if (RequireCompleteType(FD->getLocation(), Context.getRecordType(RD), 8565 diag::err_defaulted_comparison_not_friend, int(DCK), 8566 int(1))) 8567 return true; 8568 8569 if (llvm::find_if(RD->friends(), [&](const FriendDecl *F) { 8570 return FD->getCanonicalDecl() == 8571 F->getFriendDecl()->getCanonicalDecl(); 8572 }) == RD->friends().end()) { 8573 Diag(FD->getLocation(), diag::err_defaulted_comparison_not_friend) 8574 << int(DCK) << int(0) << RD; 8575 Diag(RD->getCanonicalDecl()->getLocation(), diag::note_declared_at); 8576 return true; 8577 } 8578 } 8579 8580 // C++2a [class.eq]p1, [class.rel]p1: 8581 // A [defaulted comparison other than <=>] shall have a declared return 8582 // type bool. 8583 if (DCK != DefaultedComparisonKind::ThreeWay && 8584 !FD->getDeclaredReturnType()->isDependentType() && 8585 !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) { 8586 Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool) 8587 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy 8588 << FD->getReturnTypeSourceRange(); 8589 return true; 8590 } 8591 // C++2a [class.spaceship]p2 [P2002R0]: 8592 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise, 8593 // R shall not contain a placeholder type. 8594 if (DCK == DefaultedComparisonKind::ThreeWay && 8595 FD->getDeclaredReturnType()->getContainedDeducedType() && 8596 !Context.hasSameType(FD->getDeclaredReturnType(), 8597 Context.getAutoDeductType())) { 8598 Diag(FD->getLocation(), 8599 diag::err_defaulted_comparison_deduced_return_type_not_auto) 8600 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy 8601 << FD->getReturnTypeSourceRange(); 8602 return true; 8603 } 8604 8605 // For a defaulted function in a dependent class, defer all remaining checks 8606 // until instantiation. 8607 if (RD->isDependentType()) 8608 return false; 8609 8610 // Determine whether the function should be defined as deleted. 8611 DefaultedComparisonInfo Info = 8612 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit(); 8613 8614 bool First = FD == FD->getCanonicalDecl(); 8615 8616 // If we want to delete the function, then do so; there's nothing else to 8617 // check in that case. 8618 if (Info.Deleted) { 8619 if (!First) { 8620 // C++11 [dcl.fct.def.default]p4: 8621 // [For a] user-provided explicitly-defaulted function [...] if such a 8622 // function is implicitly defined as deleted, the program is ill-formed. 8623 // 8624 // This is really just a consequence of the general rule that you can 8625 // only delete a function on its first declaration. 8626 Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes) 8627 << FD->isImplicit() << (int)DCK; 8628 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8629 DefaultedComparisonAnalyzer::ExplainDeleted) 8630 .visit(); 8631 return true; 8632 } 8633 8634 SetDeclDeleted(FD, FD->getLocation()); 8635 if (!inTemplateInstantiation() && !FD->isImplicit()) { 8636 Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted) 8637 << (int)DCK; 8638 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8639 DefaultedComparisonAnalyzer::ExplainDeleted) 8640 .visit(); 8641 } 8642 return false; 8643 } 8644 8645 // C++2a [class.spaceship]p2: 8646 // The return type is deduced as the common comparison type of R0, R1, ... 8647 if (DCK == DefaultedComparisonKind::ThreeWay && 8648 FD->getDeclaredReturnType()->isUndeducedAutoType()) { 8649 SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin(); 8650 if (RetLoc.isInvalid()) 8651 RetLoc = FD->getBeginLoc(); 8652 // FIXME: Should we really care whether we have the complete type and the 8653 // 'enumerator' constants here? A forward declaration seems sufficient. 8654 QualType Cat = CheckComparisonCategoryType( 8655 Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator); 8656 if (Cat.isNull()) 8657 return true; 8658 Context.adjustDeducedFunctionResultType( 8659 FD, SubstAutoType(FD->getDeclaredReturnType(), Cat)); 8660 } 8661 8662 // C++2a [dcl.fct.def.default]p3 [P2002R0]: 8663 // An explicitly-defaulted function that is not defined as deleted may be 8664 // declared constexpr or consteval only if it is constexpr-compatible. 8665 // C++2a [class.compare.default]p3 [P2002R0]: 8666 // A defaulted comparison function is constexpr-compatible if it satisfies 8667 // the requirements for a constexpr function [...] 8668 // The only relevant requirements are that the parameter and return types are 8669 // literal types. The remaining conditions are checked by the analyzer. 8670 if (FD->isConstexpr()) { 8671 if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) && 8672 CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) && 8673 !Info.Constexpr) { 8674 Diag(FD->getBeginLoc(), 8675 diag::err_incorrect_defaulted_comparison_constexpr) 8676 << FD->isImplicit() << (int)DCK << FD->isConsteval(); 8677 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8678 DefaultedComparisonAnalyzer::ExplainConstexpr) 8679 .visit(); 8680 } 8681 } 8682 8683 // C++2a [dcl.fct.def.default]p3 [P2002R0]: 8684 // If a constexpr-compatible function is explicitly defaulted on its first 8685 // declaration, it is implicitly considered to be constexpr. 8686 // FIXME: Only applying this to the first declaration seems problematic, as 8687 // simple reorderings can affect the meaning of the program. 8688 if (First && !FD->isConstexpr() && Info.Constexpr) 8689 FD->setConstexprKind(ConstexprSpecKind::Constexpr); 8690 8691 // C++2a [except.spec]p3: 8692 // If a declaration of a function does not have a noexcept-specifier 8693 // [and] is defaulted on its first declaration, [...] the exception 8694 // specification is as specified below 8695 if (FD->getExceptionSpecType() == EST_None) { 8696 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 8697 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8698 EPI.ExceptionSpec.Type = EST_Unevaluated; 8699 EPI.ExceptionSpec.SourceDecl = FD; 8700 FD->setType(Context.getFunctionType(FPT->getReturnType(), 8701 FPT->getParamTypes(), EPI)); 8702 } 8703 8704 return false; 8705 } 8706 8707 void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD, 8708 FunctionDecl *Spaceship) { 8709 Sema::CodeSynthesisContext Ctx; 8710 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison; 8711 Ctx.PointOfInstantiation = Spaceship->getEndLoc(); 8712 Ctx.Entity = Spaceship; 8713 pushCodeSynthesisContext(Ctx); 8714 8715 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship)) 8716 EqualEqual->setImplicit(); 8717 8718 popCodeSynthesisContext(); 8719 } 8720 8721 void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD, 8722 DefaultedComparisonKind DCK) { 8723 assert(FD->isDefaulted() && !FD->isDeleted() && 8724 !FD->doesThisDeclarationHaveABody()); 8725 if (FD->willHaveBody() || FD->isInvalidDecl()) 8726 return; 8727 8728 SynthesizedFunctionScope Scope(*this, FD); 8729 8730 // Add a context note for diagnostics produced after this point. 8731 Scope.addContextNote(UseLoc); 8732 8733 { 8734 // Build and set up the function body. 8735 // The first parameter has type maybe-ref-to maybe-const T, use that to get 8736 // the type of the class being compared. 8737 auto PT = FD->getParamDecl(0)->getType(); 8738 CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl(); 8739 SourceLocation BodyLoc = 8740 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation(); 8741 StmtResult Body = 8742 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build(); 8743 if (Body.isInvalid()) { 8744 FD->setInvalidDecl(); 8745 return; 8746 } 8747 FD->setBody(Body.get()); 8748 FD->markUsed(Context); 8749 } 8750 8751 // The exception specification is needed because we are defining the 8752 // function. Note that this will reuse the body we just built. 8753 ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>()); 8754 8755 if (ASTMutationListener *L = getASTMutationListener()) 8756 L->CompletedImplicitDefinition(FD); 8757 } 8758 8759 static Sema::ImplicitExceptionSpecification 8760 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, 8761 FunctionDecl *FD, 8762 Sema::DefaultedComparisonKind DCK) { 8763 ComputingExceptionSpec CES(S, FD, Loc); 8764 Sema::ImplicitExceptionSpecification ExceptSpec(S); 8765 8766 if (FD->isInvalidDecl()) 8767 return ExceptSpec; 8768 8769 // The common case is that we just defined the comparison function. In that 8770 // case, just look at whether the body can throw. 8771 if (FD->hasBody()) { 8772 ExceptSpec.CalledStmt(FD->getBody()); 8773 } else { 8774 // Otherwise, build a body so we can check it. This should ideally only 8775 // happen when we're not actually marking the function referenced. (This is 8776 // only really important for efficiency: we don't want to build and throw 8777 // away bodies for comparison functions more than we strictly need to.) 8778 8779 // Pretend to synthesize the function body in an unevaluated context. 8780 // Note that we can't actually just go ahead and define the function here: 8781 // we are not permitted to mark its callees as referenced. 8782 Sema::SynthesizedFunctionScope Scope(S, FD); 8783 EnterExpressionEvaluationContext Context( 8784 S, Sema::ExpressionEvaluationContext::Unevaluated); 8785 8786 CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent()); 8787 SourceLocation BodyLoc = 8788 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation(); 8789 StmtResult Body = 8790 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build(); 8791 if (!Body.isInvalid()) 8792 ExceptSpec.CalledStmt(Body.get()); 8793 8794 // FIXME: Can we hold onto this body and just transform it to potentially 8795 // evaluated when we're asked to define the function rather than rebuilding 8796 // it? Either that, or we should only build the bits of the body that we 8797 // need (the expressions, not the statements). 8798 } 8799 8800 return ExceptSpec; 8801 } 8802 8803 void Sema::CheckDelayedMemberExceptionSpecs() { 8804 decltype(DelayedOverridingExceptionSpecChecks) Overriding; 8805 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent; 8806 8807 std::swap(Overriding, DelayedOverridingExceptionSpecChecks); 8808 std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks); 8809 8810 // Perform any deferred checking of exception specifications for virtual 8811 // destructors. 8812 for (auto &Check : Overriding) 8813 CheckOverridingFunctionExceptionSpec(Check.first, Check.second); 8814 8815 // Perform any deferred checking of exception specifications for befriended 8816 // special members. 8817 for (auto &Check : Equivalent) 8818 CheckEquivalentExceptionSpec(Check.second, Check.first); 8819 } 8820 8821 namespace { 8822 /// CRTP base class for visiting operations performed by a special member 8823 /// function (or inherited constructor). 8824 template<typename Derived> 8825 struct SpecialMemberVisitor { 8826 Sema &S; 8827 CXXMethodDecl *MD; 8828 Sema::CXXSpecialMember CSM; 8829 Sema::InheritedConstructorInfo *ICI; 8830 8831 // Properties of the special member, computed for convenience. 8832 bool IsConstructor = false, IsAssignment = false, ConstArg = false; 8833 8834 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 8835 Sema::InheritedConstructorInfo *ICI) 8836 : S(S), MD(MD), CSM(CSM), ICI(ICI) { 8837 switch (CSM) { 8838 case Sema::CXXDefaultConstructor: 8839 case Sema::CXXCopyConstructor: 8840 case Sema::CXXMoveConstructor: 8841 IsConstructor = true; 8842 break; 8843 case Sema::CXXCopyAssignment: 8844 case Sema::CXXMoveAssignment: 8845 IsAssignment = true; 8846 break; 8847 case Sema::CXXDestructor: 8848 break; 8849 case Sema::CXXInvalid: 8850 llvm_unreachable("invalid special member kind"); 8851 } 8852 8853 if (MD->getNumParams()) { 8854 if (const ReferenceType *RT = 8855 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 8856 ConstArg = RT->getPointeeType().isConstQualified(); 8857 } 8858 } 8859 8860 Derived &getDerived() { return static_cast<Derived&>(*this); } 8861 8862 /// Is this a "move" special member? 8863 bool isMove() const { 8864 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment; 8865 } 8866 8867 /// Look up the corresponding special member in the given class. 8868 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class, 8869 unsigned Quals, bool IsMutable) { 8870 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 8871 ConstArg && !IsMutable); 8872 } 8873 8874 /// Look up the constructor for the specified base class to see if it's 8875 /// overridden due to this being an inherited constructor. 8876 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) { 8877 if (!ICI) 8878 return {}; 8879 assert(CSM == Sema::CXXDefaultConstructor); 8880 auto *BaseCtor = 8881 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor(); 8882 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first) 8883 return MD; 8884 return {}; 8885 } 8886 8887 /// A base or member subobject. 8888 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 8889 8890 /// Get the location to use for a subobject in diagnostics. 8891 static SourceLocation getSubobjectLoc(Subobject Subobj) { 8892 // FIXME: For an indirect virtual base, the direct base leading to 8893 // the indirect virtual base would be a more useful choice. 8894 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>()) 8895 return B->getBaseTypeLoc(); 8896 else 8897 return Subobj.get<FieldDecl*>()->getLocation(); 8898 } 8899 8900 enum BasesToVisit { 8901 /// Visit all non-virtual (direct) bases. 8902 VisitNonVirtualBases, 8903 /// Visit all direct bases, virtual or not. 8904 VisitDirectBases, 8905 /// Visit all non-virtual bases, and all virtual bases if the class 8906 /// is not abstract. 8907 VisitPotentiallyConstructedBases, 8908 /// Visit all direct or virtual bases. 8909 VisitAllBases 8910 }; 8911 8912 // Visit the bases and members of the class. 8913 bool visit(BasesToVisit Bases) { 8914 CXXRecordDecl *RD = MD->getParent(); 8915 8916 if (Bases == VisitPotentiallyConstructedBases) 8917 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases; 8918 8919 for (auto &B : RD->bases()) 8920 if ((Bases == VisitDirectBases || !B.isVirtual()) && 8921 getDerived().visitBase(&B)) 8922 return true; 8923 8924 if (Bases == VisitAllBases) 8925 for (auto &B : RD->vbases()) 8926 if (getDerived().visitBase(&B)) 8927 return true; 8928 8929 for (auto *F : RD->fields()) 8930 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() && 8931 getDerived().visitField(F)) 8932 return true; 8933 8934 return false; 8935 } 8936 }; 8937 } 8938 8939 namespace { 8940 struct SpecialMemberDeletionInfo 8941 : SpecialMemberVisitor<SpecialMemberDeletionInfo> { 8942 bool Diagnose; 8943 8944 SourceLocation Loc; 8945 8946 bool AllFieldsAreConst; 8947 8948 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 8949 Sema::CXXSpecialMember CSM, 8950 Sema::InheritedConstructorInfo *ICI, bool Diagnose) 8951 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose), 8952 Loc(MD->getLocation()), AllFieldsAreConst(true) {} 8953 8954 bool inUnion() const { return MD->getParent()->isUnion(); } 8955 8956 Sema::CXXSpecialMember getEffectiveCSM() { 8957 return ICI ? Sema::CXXInvalid : CSM; 8958 } 8959 8960 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType); 8961 8962 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); } 8963 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); } 8964 8965 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 8966 bool shouldDeleteForField(FieldDecl *FD); 8967 bool shouldDeleteForAllConstMembers(); 8968 8969 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 8970 unsigned Quals); 8971 bool shouldDeleteForSubobjectCall(Subobject Subobj, 8972 Sema::SpecialMemberOverloadResult SMOR, 8973 bool IsDtorCallInCtor); 8974 8975 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 8976 }; 8977 } 8978 8979 /// Is the given special member inaccessible when used on the given 8980 /// sub-object. 8981 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 8982 CXXMethodDecl *target) { 8983 /// If we're operating on a base class, the object type is the 8984 /// type of this special member. 8985 QualType objectTy; 8986 AccessSpecifier access = target->getAccess(); 8987 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 8988 objectTy = S.Context.getTypeDeclType(MD->getParent()); 8989 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 8990 8991 // If we're operating on a field, the object type is the type of the field. 8992 } else { 8993 objectTy = S.Context.getTypeDeclType(target->getParent()); 8994 } 8995 8996 return S.isMemberAccessibleForDeletion( 8997 target->getParent(), DeclAccessPair::make(target, access), objectTy); 8998 } 8999 9000 /// Check whether we should delete a special member due to the implicit 9001 /// definition containing a call to a special member of a subobject. 9002 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 9003 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR, 9004 bool IsDtorCallInCtor) { 9005 CXXMethodDecl *Decl = SMOR.getMethod(); 9006 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 9007 9008 int DiagKind = -1; 9009 9010 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 9011 DiagKind = !Decl ? 0 : 1; 9012 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 9013 DiagKind = 2; 9014 else if (!isAccessible(Subobj, Decl)) 9015 DiagKind = 3; 9016 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 9017 !Decl->isTrivial()) { 9018 // A member of a union must have a trivial corresponding special member. 9019 // As a weird special case, a destructor call from a union's constructor 9020 // must be accessible and non-deleted, but need not be trivial. Such a 9021 // destructor is never actually called, but is semantically checked as 9022 // if it were. 9023 DiagKind = 4; 9024 } 9025 9026 if (DiagKind == -1) 9027 return false; 9028 9029 if (Diagnose) { 9030 if (Field) { 9031 S.Diag(Field->getLocation(), 9032 diag::note_deleted_special_member_class_subobject) 9033 << getEffectiveCSM() << MD->getParent() << /*IsField*/true 9034 << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false; 9035 } else { 9036 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 9037 S.Diag(Base->getBeginLoc(), 9038 diag::note_deleted_special_member_class_subobject) 9039 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 9040 << Base->getType() << DiagKind << IsDtorCallInCtor 9041 << /*IsObjCPtr*/false; 9042 } 9043 9044 if (DiagKind == 1) 9045 S.NoteDeletedFunction(Decl); 9046 // FIXME: Explain inaccessibility if DiagKind == 3. 9047 } 9048 9049 return true; 9050 } 9051 9052 /// Check whether we should delete a special member function due to having a 9053 /// direct or virtual base class or non-static data member of class type M. 9054 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 9055 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 9056 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 9057 bool IsMutable = Field && Field->isMutable(); 9058 9059 // C++11 [class.ctor]p5: 9060 // -- any direct or virtual base class, or non-static data member with no 9061 // brace-or-equal-initializer, has class type M (or array thereof) and 9062 // either M has no default constructor or overload resolution as applied 9063 // to M's default constructor results in an ambiguity or in a function 9064 // that is deleted or inaccessible 9065 // C++11 [class.copy]p11, C++11 [class.copy]p23: 9066 // -- a direct or virtual base class B that cannot be copied/moved because 9067 // overload resolution, as applied to B's corresponding special member, 9068 // results in an ambiguity or a function that is deleted or inaccessible 9069 // from the defaulted special member 9070 // C++11 [class.dtor]p5: 9071 // -- any direct or virtual base class [...] has a type with a destructor 9072 // that is deleted or inaccessible 9073 if (!(CSM == Sema::CXXDefaultConstructor && 9074 Field && Field->hasInClassInitializer()) && 9075 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 9076 false)) 9077 return true; 9078 9079 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 9080 // -- any direct or virtual base class or non-static data member has a 9081 // type with a destructor that is deleted or inaccessible 9082 if (IsConstructor) { 9083 Sema::SpecialMemberOverloadResult SMOR = 9084 S.LookupSpecialMember(Class, Sema::CXXDestructor, 9085 false, false, false, false, false); 9086 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 9087 return true; 9088 } 9089 9090 return false; 9091 } 9092 9093 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember( 9094 FieldDecl *FD, QualType FieldType) { 9095 // The defaulted special functions are defined as deleted if this is a variant 9096 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak 9097 // type under ARC. 9098 if (!FieldType.hasNonTrivialObjCLifetime()) 9099 return false; 9100 9101 // Don't make the defaulted default constructor defined as deleted if the 9102 // member has an in-class initializer. 9103 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) 9104 return false; 9105 9106 if (Diagnose) { 9107 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent()); 9108 S.Diag(FD->getLocation(), 9109 diag::note_deleted_special_member_class_subobject) 9110 << getEffectiveCSM() << ParentClass << /*IsField*/true 9111 << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true; 9112 } 9113 9114 return true; 9115 } 9116 9117 /// Check whether we should delete a special member function due to the class 9118 /// having a particular direct or virtual base class. 9119 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 9120 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 9121 // If program is correct, BaseClass cannot be null, but if it is, the error 9122 // must be reported elsewhere. 9123 if (!BaseClass) 9124 return false; 9125 // If we have an inheriting constructor, check whether we're calling an 9126 // inherited constructor instead of a default constructor. 9127 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 9128 if (auto *BaseCtor = SMOR.getMethod()) { 9129 // Note that we do not check access along this path; other than that, 9130 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false); 9131 // FIXME: Check that the base has a usable destructor! Sink this into 9132 // shouldDeleteForClassSubobject. 9133 if (BaseCtor->isDeleted() && Diagnose) { 9134 S.Diag(Base->getBeginLoc(), 9135 diag::note_deleted_special_member_class_subobject) 9136 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 9137 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false 9138 << /*IsObjCPtr*/false; 9139 S.NoteDeletedFunction(BaseCtor); 9140 } 9141 return BaseCtor->isDeleted(); 9142 } 9143 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 9144 } 9145 9146 /// Check whether we should delete a special member function due to the class 9147 /// having a particular non-static data member. 9148 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 9149 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 9150 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 9151 9152 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType)) 9153 return true; 9154 9155 if (CSM == Sema::CXXDefaultConstructor) { 9156 // For a default constructor, all references must be initialized in-class 9157 // and, if a union, it must have a non-const member. 9158 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 9159 if (Diagnose) 9160 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 9161 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0; 9162 return true; 9163 } 9164 // C++11 [class.ctor]p5: any non-variant non-static data member of 9165 // const-qualified type (or array thereof) with no 9166 // brace-or-equal-initializer does not have a user-provided default 9167 // constructor. 9168 if (!inUnion() && FieldType.isConstQualified() && 9169 !FD->hasInClassInitializer() && 9170 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 9171 if (Diagnose) 9172 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 9173 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1; 9174 return true; 9175 } 9176 9177 if (inUnion() && !FieldType.isConstQualified()) 9178 AllFieldsAreConst = false; 9179 } else if (CSM == Sema::CXXCopyConstructor) { 9180 // For a copy constructor, data members must not be of rvalue reference 9181 // type. 9182 if (FieldType->isRValueReferenceType()) { 9183 if (Diagnose) 9184 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 9185 << MD->getParent() << FD << FieldType; 9186 return true; 9187 } 9188 } else if (IsAssignment) { 9189 // For an assignment operator, data members must not be of reference type. 9190 if (FieldType->isReferenceType()) { 9191 if (Diagnose) 9192 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 9193 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0; 9194 return true; 9195 } 9196 if (!FieldRecord && FieldType.isConstQualified()) { 9197 // C++11 [class.copy]p23: 9198 // -- a non-static data member of const non-class type (or array thereof) 9199 if (Diagnose) 9200 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 9201 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1; 9202 return true; 9203 } 9204 } 9205 9206 if (FieldRecord) { 9207 // Some additional restrictions exist on the variant members. 9208 if (!inUnion() && FieldRecord->isUnion() && 9209 FieldRecord->isAnonymousStructOrUnion()) { 9210 bool AllVariantFieldsAreConst = true; 9211 9212 // FIXME: Handle anonymous unions declared within anonymous unions. 9213 for (auto *UI : FieldRecord->fields()) { 9214 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 9215 9216 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType)) 9217 return true; 9218 9219 if (!UnionFieldType.isConstQualified()) 9220 AllVariantFieldsAreConst = false; 9221 9222 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 9223 if (UnionFieldRecord && 9224 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 9225 UnionFieldType.getCVRQualifiers())) 9226 return true; 9227 } 9228 9229 // At least one member in each anonymous union must be non-const 9230 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 9231 !FieldRecord->field_empty()) { 9232 if (Diagnose) 9233 S.Diag(FieldRecord->getLocation(), 9234 diag::note_deleted_default_ctor_all_const) 9235 << !!ICI << MD->getParent() << /*anonymous union*/1; 9236 return true; 9237 } 9238 9239 // Don't check the implicit member of the anonymous union type. 9240 // This is technically non-conformant but supported, and we have a 9241 // diagnostic for this elsewhere. 9242 return false; 9243 } 9244 9245 if (shouldDeleteForClassSubobject(FieldRecord, FD, 9246 FieldType.getCVRQualifiers())) 9247 return true; 9248 } 9249 9250 return false; 9251 } 9252 9253 /// C++11 [class.ctor] p5: 9254 /// A defaulted default constructor for a class X is defined as deleted if 9255 /// X is a union and all of its variant members are of const-qualified type. 9256 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 9257 // This is a silly definition, because it gives an empty union a deleted 9258 // default constructor. Don't do that. 9259 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) { 9260 bool AnyFields = false; 9261 for (auto *F : MD->getParent()->fields()) 9262 if ((AnyFields = !F->isUnnamedBitfield())) 9263 break; 9264 if (!AnyFields) 9265 return false; 9266 if (Diagnose) 9267 S.Diag(MD->getParent()->getLocation(), 9268 diag::note_deleted_default_ctor_all_const) 9269 << !!ICI << MD->getParent() << /*not anonymous union*/0; 9270 return true; 9271 } 9272 return false; 9273 } 9274 9275 /// Determine whether a defaulted special member function should be defined as 9276 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 9277 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 9278 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 9279 InheritedConstructorInfo *ICI, 9280 bool Diagnose) { 9281 if (MD->isInvalidDecl()) 9282 return false; 9283 CXXRecordDecl *RD = MD->getParent(); 9284 assert(!RD->isDependentType() && "do deletion after instantiation"); 9285 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 9286 return false; 9287 9288 // C++11 [expr.lambda.prim]p19: 9289 // The closure type associated with a lambda-expression has a 9290 // deleted (8.4.3) default constructor and a deleted copy 9291 // assignment operator. 9292 // C++2a adds back these operators if the lambda has no lambda-capture. 9293 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() && 9294 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 9295 if (Diagnose) 9296 Diag(RD->getLocation(), diag::note_lambda_decl); 9297 return true; 9298 } 9299 9300 // For an anonymous struct or union, the copy and assignment special members 9301 // will never be used, so skip the check. For an anonymous union declared at 9302 // namespace scope, the constructor and destructor are used. 9303 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 9304 RD->isAnonymousStructOrUnion()) 9305 return false; 9306 9307 // C++11 [class.copy]p7, p18: 9308 // If the class definition declares a move constructor or move assignment 9309 // operator, an implicitly declared copy constructor or copy assignment 9310 // operator is defined as deleted. 9311 if (MD->isImplicit() && 9312 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 9313 CXXMethodDecl *UserDeclaredMove = nullptr; 9314 9315 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the 9316 // deletion of the corresponding copy operation, not both copy operations. 9317 // MSVC 2015 has adopted the standards conforming behavior. 9318 bool DeletesOnlyMatchingCopy = 9319 getLangOpts().MSVCCompat && 9320 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015); 9321 9322 if (RD->hasUserDeclaredMoveConstructor() && 9323 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) { 9324 if (!Diagnose) return true; 9325 9326 // Find any user-declared move constructor. 9327 for (auto *I : RD->ctors()) { 9328 if (I->isMoveConstructor()) { 9329 UserDeclaredMove = I; 9330 break; 9331 } 9332 } 9333 assert(UserDeclaredMove); 9334 } else if (RD->hasUserDeclaredMoveAssignment() && 9335 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) { 9336 if (!Diagnose) return true; 9337 9338 // Find any user-declared move assignment operator. 9339 for (auto *I : RD->methods()) { 9340 if (I->isMoveAssignmentOperator()) { 9341 UserDeclaredMove = I; 9342 break; 9343 } 9344 } 9345 assert(UserDeclaredMove); 9346 } 9347 9348 if (UserDeclaredMove) { 9349 Diag(UserDeclaredMove->getLocation(), 9350 diag::note_deleted_copy_user_declared_move) 9351 << (CSM == CXXCopyAssignment) << RD 9352 << UserDeclaredMove->isMoveAssignmentOperator(); 9353 return true; 9354 } 9355 } 9356 9357 // Do access control from the special member function 9358 ContextRAII MethodContext(*this, MD); 9359 9360 // C++11 [class.dtor]p5: 9361 // -- for a virtual destructor, lookup of the non-array deallocation function 9362 // results in an ambiguity or in a function that is deleted or inaccessible 9363 if (CSM == CXXDestructor && MD->isVirtual()) { 9364 FunctionDecl *OperatorDelete = nullptr; 9365 DeclarationName Name = 9366 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 9367 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 9368 OperatorDelete, /*Diagnose*/false)) { 9369 if (Diagnose) 9370 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 9371 return true; 9372 } 9373 } 9374 9375 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose); 9376 9377 // Per DR1611, do not consider virtual bases of constructors of abstract 9378 // classes, since we are not going to construct them. 9379 // Per DR1658, do not consider virtual bases of destructors of abstract 9380 // classes either. 9381 // Per DR2180, for assignment operators we only assign (and thus only 9382 // consider) direct bases. 9383 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases 9384 : SMI.VisitPotentiallyConstructedBases)) 9385 return true; 9386 9387 if (SMI.shouldDeleteForAllConstMembers()) 9388 return true; 9389 9390 if (getLangOpts().CUDA) { 9391 // We should delete the special member in CUDA mode if target inference 9392 // failed. 9393 // For inherited constructors (non-null ICI), CSM may be passed so that MD 9394 // is treated as certain special member, which may not reflect what special 9395 // member MD really is. However inferCUDATargetForImplicitSpecialMember 9396 // expects CSM to match MD, therefore recalculate CSM. 9397 assert(ICI || CSM == getSpecialMember(MD)); 9398 auto RealCSM = CSM; 9399 if (ICI) 9400 RealCSM = getSpecialMember(MD); 9401 9402 return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD, 9403 SMI.ConstArg, Diagnose); 9404 } 9405 9406 return false; 9407 } 9408 9409 void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) { 9410 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD); 9411 assert(DFK && "not a defaultable function"); 9412 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted"); 9413 9414 if (DFK.isSpecialMember()) { 9415 ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), 9416 nullptr, /*Diagnose=*/true); 9417 } else { 9418 DefaultedComparisonAnalyzer( 9419 *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD, 9420 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted) 9421 .visit(); 9422 } 9423 } 9424 9425 /// Perform lookup for a special member of the specified kind, and determine 9426 /// whether it is trivial. If the triviality can be determined without the 9427 /// lookup, skip it. This is intended for use when determining whether a 9428 /// special member of a containing object is trivial, and thus does not ever 9429 /// perform overload resolution for default constructors. 9430 /// 9431 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 9432 /// member that was most likely to be intended to be trivial, if any. 9433 /// 9434 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to 9435 /// determine whether the special member is trivial. 9436 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 9437 Sema::CXXSpecialMember CSM, unsigned Quals, 9438 bool ConstRHS, 9439 Sema::TrivialABIHandling TAH, 9440 CXXMethodDecl **Selected) { 9441 if (Selected) 9442 *Selected = nullptr; 9443 9444 switch (CSM) { 9445 case Sema::CXXInvalid: 9446 llvm_unreachable("not a special member"); 9447 9448 case Sema::CXXDefaultConstructor: 9449 // C++11 [class.ctor]p5: 9450 // A default constructor is trivial if: 9451 // - all the [direct subobjects] have trivial default constructors 9452 // 9453 // Note, no overload resolution is performed in this case. 9454 if (RD->hasTrivialDefaultConstructor()) 9455 return true; 9456 9457 if (Selected) { 9458 // If there's a default constructor which could have been trivial, dig it 9459 // out. Otherwise, if there's any user-provided default constructor, point 9460 // to that as an example of why there's not a trivial one. 9461 CXXConstructorDecl *DefCtor = nullptr; 9462 if (RD->needsImplicitDefaultConstructor()) 9463 S.DeclareImplicitDefaultConstructor(RD); 9464 for (auto *CI : RD->ctors()) { 9465 if (!CI->isDefaultConstructor()) 9466 continue; 9467 DefCtor = CI; 9468 if (!DefCtor->isUserProvided()) 9469 break; 9470 } 9471 9472 *Selected = DefCtor; 9473 } 9474 9475 return false; 9476 9477 case Sema::CXXDestructor: 9478 // C++11 [class.dtor]p5: 9479 // A destructor is trivial if: 9480 // - all the direct [subobjects] have trivial destructors 9481 if (RD->hasTrivialDestructor() || 9482 (TAH == Sema::TAH_ConsiderTrivialABI && 9483 RD->hasTrivialDestructorForCall())) 9484 return true; 9485 9486 if (Selected) { 9487 if (RD->needsImplicitDestructor()) 9488 S.DeclareImplicitDestructor(RD); 9489 *Selected = RD->getDestructor(); 9490 } 9491 9492 return false; 9493 9494 case Sema::CXXCopyConstructor: 9495 // C++11 [class.copy]p12: 9496 // A copy constructor is trivial if: 9497 // - the constructor selected to copy each direct [subobject] is trivial 9498 if (RD->hasTrivialCopyConstructor() || 9499 (TAH == Sema::TAH_ConsiderTrivialABI && 9500 RD->hasTrivialCopyConstructorForCall())) { 9501 if (Quals == Qualifiers::Const) 9502 // We must either select the trivial copy constructor or reach an 9503 // ambiguity; no need to actually perform overload resolution. 9504 return true; 9505 } else if (!Selected) { 9506 return false; 9507 } 9508 // In C++98, we are not supposed to perform overload resolution here, but we 9509 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 9510 // cases like B as having a non-trivial copy constructor: 9511 // struct A { template<typename T> A(T&); }; 9512 // struct B { mutable A a; }; 9513 goto NeedOverloadResolution; 9514 9515 case Sema::CXXCopyAssignment: 9516 // C++11 [class.copy]p25: 9517 // A copy assignment operator is trivial if: 9518 // - the assignment operator selected to copy each direct [subobject] is 9519 // trivial 9520 if (RD->hasTrivialCopyAssignment()) { 9521 if (Quals == Qualifiers::Const) 9522 return true; 9523 } else if (!Selected) { 9524 return false; 9525 } 9526 // In C++98, we are not supposed to perform overload resolution here, but we 9527 // treat that as a language defect. 9528 goto NeedOverloadResolution; 9529 9530 case Sema::CXXMoveConstructor: 9531 case Sema::CXXMoveAssignment: 9532 NeedOverloadResolution: 9533 Sema::SpecialMemberOverloadResult SMOR = 9534 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 9535 9536 // The standard doesn't describe how to behave if the lookup is ambiguous. 9537 // We treat it as not making the member non-trivial, just like the standard 9538 // mandates for the default constructor. This should rarely matter, because 9539 // the member will also be deleted. 9540 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 9541 return true; 9542 9543 if (!SMOR.getMethod()) { 9544 assert(SMOR.getKind() == 9545 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 9546 return false; 9547 } 9548 9549 // We deliberately don't check if we found a deleted special member. We're 9550 // not supposed to! 9551 if (Selected) 9552 *Selected = SMOR.getMethod(); 9553 9554 if (TAH == Sema::TAH_ConsiderTrivialABI && 9555 (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor)) 9556 return SMOR.getMethod()->isTrivialForCall(); 9557 return SMOR.getMethod()->isTrivial(); 9558 } 9559 9560 llvm_unreachable("unknown special method kind"); 9561 } 9562 9563 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 9564 for (auto *CI : RD->ctors()) 9565 if (!CI->isImplicit()) 9566 return CI; 9567 9568 // Look for constructor templates. 9569 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 9570 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 9571 if (CXXConstructorDecl *CD = 9572 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 9573 return CD; 9574 } 9575 9576 return nullptr; 9577 } 9578 9579 /// The kind of subobject we are checking for triviality. The values of this 9580 /// enumeration are used in diagnostics. 9581 enum TrivialSubobjectKind { 9582 /// The subobject is a base class. 9583 TSK_BaseClass, 9584 /// The subobject is a non-static data member. 9585 TSK_Field, 9586 /// The object is actually the complete object. 9587 TSK_CompleteObject 9588 }; 9589 9590 /// Check whether the special member selected for a given type would be trivial. 9591 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 9592 QualType SubType, bool ConstRHS, 9593 Sema::CXXSpecialMember CSM, 9594 TrivialSubobjectKind Kind, 9595 Sema::TrivialABIHandling TAH, bool Diagnose) { 9596 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 9597 if (!SubRD) 9598 return true; 9599 9600 CXXMethodDecl *Selected; 9601 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 9602 ConstRHS, TAH, Diagnose ? &Selected : nullptr)) 9603 return true; 9604 9605 if (Diagnose) { 9606 if (ConstRHS) 9607 SubType.addConst(); 9608 9609 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 9610 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 9611 << Kind << SubType.getUnqualifiedType(); 9612 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 9613 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 9614 } else if (!Selected) 9615 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 9616 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 9617 else if (Selected->isUserProvided()) { 9618 if (Kind == TSK_CompleteObject) 9619 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 9620 << Kind << SubType.getUnqualifiedType() << CSM; 9621 else { 9622 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 9623 << Kind << SubType.getUnqualifiedType() << CSM; 9624 S.Diag(Selected->getLocation(), diag::note_declared_at); 9625 } 9626 } else { 9627 if (Kind != TSK_CompleteObject) 9628 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 9629 << Kind << SubType.getUnqualifiedType() << CSM; 9630 9631 // Explain why the defaulted or deleted special member isn't trivial. 9632 S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI, 9633 Diagnose); 9634 } 9635 } 9636 9637 return false; 9638 } 9639 9640 /// Check whether the members of a class type allow a special member to be 9641 /// trivial. 9642 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 9643 Sema::CXXSpecialMember CSM, 9644 bool ConstArg, 9645 Sema::TrivialABIHandling TAH, 9646 bool Diagnose) { 9647 for (const auto *FI : RD->fields()) { 9648 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 9649 continue; 9650 9651 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 9652 9653 // Pretend anonymous struct or union members are members of this class. 9654 if (FI->isAnonymousStructOrUnion()) { 9655 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 9656 CSM, ConstArg, TAH, Diagnose)) 9657 return false; 9658 continue; 9659 } 9660 9661 // C++11 [class.ctor]p5: 9662 // A default constructor is trivial if [...] 9663 // -- no non-static data member of its class has a 9664 // brace-or-equal-initializer 9665 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 9666 if (Diagnose) 9667 S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init) 9668 << FI; 9669 return false; 9670 } 9671 9672 // Objective C ARC 4.3.5: 9673 // [...] nontrivally ownership-qualified types are [...] not trivially 9674 // default constructible, copy constructible, move constructible, copy 9675 // assignable, move assignable, or destructible [...] 9676 if (FieldType.hasNonTrivialObjCLifetime()) { 9677 if (Diagnose) 9678 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 9679 << RD << FieldType.getObjCLifetime(); 9680 return false; 9681 } 9682 9683 bool ConstRHS = ConstArg && !FI->isMutable(); 9684 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 9685 CSM, TSK_Field, TAH, Diagnose)) 9686 return false; 9687 } 9688 9689 return true; 9690 } 9691 9692 /// Diagnose why the specified class does not have a trivial special member of 9693 /// the given kind. 9694 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 9695 QualType Ty = Context.getRecordType(RD); 9696 9697 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 9698 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 9699 TSK_CompleteObject, TAH_IgnoreTrivialABI, 9700 /*Diagnose*/true); 9701 } 9702 9703 /// Determine whether a defaulted or deleted special member function is trivial, 9704 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 9705 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 9706 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 9707 TrivialABIHandling TAH, bool Diagnose) { 9708 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 9709 9710 CXXRecordDecl *RD = MD->getParent(); 9711 9712 bool ConstArg = false; 9713 9714 // C++11 [class.copy]p12, p25: [DR1593] 9715 // A [special member] is trivial if [...] its parameter-type-list is 9716 // equivalent to the parameter-type-list of an implicit declaration [...] 9717 switch (CSM) { 9718 case CXXDefaultConstructor: 9719 case CXXDestructor: 9720 // Trivial default constructors and destructors cannot have parameters. 9721 break; 9722 9723 case CXXCopyConstructor: 9724 case CXXCopyAssignment: { 9725 // Trivial copy operations always have const, non-volatile parameter types. 9726 ConstArg = true; 9727 const ParmVarDecl *Param0 = MD->getParamDecl(0); 9728 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 9729 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 9730 if (Diagnose) 9731 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 9732 << Param0->getSourceRange() << Param0->getType() 9733 << Context.getLValueReferenceType( 9734 Context.getRecordType(RD).withConst()); 9735 return false; 9736 } 9737 break; 9738 } 9739 9740 case CXXMoveConstructor: 9741 case CXXMoveAssignment: { 9742 // Trivial move operations always have non-cv-qualified parameters. 9743 const ParmVarDecl *Param0 = MD->getParamDecl(0); 9744 const RValueReferenceType *RT = 9745 Param0->getType()->getAs<RValueReferenceType>(); 9746 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 9747 if (Diagnose) 9748 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 9749 << Param0->getSourceRange() << Param0->getType() 9750 << Context.getRValueReferenceType(Context.getRecordType(RD)); 9751 return false; 9752 } 9753 break; 9754 } 9755 9756 case CXXInvalid: 9757 llvm_unreachable("not a special member"); 9758 } 9759 9760 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 9761 if (Diagnose) 9762 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 9763 diag::note_nontrivial_default_arg) 9764 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 9765 return false; 9766 } 9767 if (MD->isVariadic()) { 9768 if (Diagnose) 9769 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 9770 return false; 9771 } 9772 9773 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 9774 // A copy/move [constructor or assignment operator] is trivial if 9775 // -- the [member] selected to copy/move each direct base class subobject 9776 // is trivial 9777 // 9778 // C++11 [class.copy]p12, C++11 [class.copy]p25: 9779 // A [default constructor or destructor] is trivial if 9780 // -- all the direct base classes have trivial [default constructors or 9781 // destructors] 9782 for (const auto &BI : RD->bases()) 9783 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(), 9784 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose)) 9785 return false; 9786 9787 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 9788 // A copy/move [constructor or assignment operator] for a class X is 9789 // trivial if 9790 // -- for each non-static data member of X that is of class type (or array 9791 // thereof), the constructor selected to copy/move that member is 9792 // trivial 9793 // 9794 // C++11 [class.copy]p12, C++11 [class.copy]p25: 9795 // A [default constructor or destructor] is trivial if 9796 // -- for all of the non-static data members of its class that are of class 9797 // type (or array thereof), each such class has a trivial [default 9798 // constructor or destructor] 9799 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose)) 9800 return false; 9801 9802 // C++11 [class.dtor]p5: 9803 // A destructor is trivial if [...] 9804 // -- the destructor is not virtual 9805 if (CSM == CXXDestructor && MD->isVirtual()) { 9806 if (Diagnose) 9807 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 9808 return false; 9809 } 9810 9811 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 9812 // A [special member] for class X is trivial if [...] 9813 // -- class X has no virtual functions and no virtual base classes 9814 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 9815 if (!Diagnose) 9816 return false; 9817 9818 if (RD->getNumVBases()) { 9819 // Check for virtual bases. We already know that the corresponding 9820 // member in all bases is trivial, so vbases must all be direct. 9821 CXXBaseSpecifier &BS = *RD->vbases_begin(); 9822 assert(BS.isVirtual()); 9823 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1; 9824 return false; 9825 } 9826 9827 // Must have a virtual method. 9828 for (const auto *MI : RD->methods()) { 9829 if (MI->isVirtual()) { 9830 SourceLocation MLoc = MI->getBeginLoc(); 9831 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 9832 return false; 9833 } 9834 } 9835 9836 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 9837 } 9838 9839 // Looks like it's trivial! 9840 return true; 9841 } 9842 9843 namespace { 9844 struct FindHiddenVirtualMethod { 9845 Sema *S; 9846 CXXMethodDecl *Method; 9847 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 9848 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 9849 9850 private: 9851 /// Check whether any most overridden method from MD in Methods 9852 static bool CheckMostOverridenMethods( 9853 const CXXMethodDecl *MD, 9854 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) { 9855 if (MD->size_overridden_methods() == 0) 9856 return Methods.count(MD->getCanonicalDecl()); 9857 for (const CXXMethodDecl *O : MD->overridden_methods()) 9858 if (CheckMostOverridenMethods(O, Methods)) 9859 return true; 9860 return false; 9861 } 9862 9863 public: 9864 /// Member lookup function that determines whether a given C++ 9865 /// method overloads virtual methods in a base class without overriding any, 9866 /// to be used with CXXRecordDecl::lookupInBases(). 9867 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 9868 RecordDecl *BaseRecord = 9869 Specifier->getType()->castAs<RecordType>()->getDecl(); 9870 9871 DeclarationName Name = Method->getDeclName(); 9872 assert(Name.getNameKind() == DeclarationName::Identifier); 9873 9874 bool foundSameNameMethod = false; 9875 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 9876 for (Path.Decls = BaseRecord->lookup(Name).begin(); 9877 Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) { 9878 NamedDecl *D = *Path.Decls; 9879 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 9880 MD = MD->getCanonicalDecl(); 9881 foundSameNameMethod = true; 9882 // Interested only in hidden virtual methods. 9883 if (!MD->isVirtual()) 9884 continue; 9885 // If the method we are checking overrides a method from its base 9886 // don't warn about the other overloaded methods. Clang deviates from 9887 // GCC by only diagnosing overloads of inherited virtual functions that 9888 // do not override any other virtual functions in the base. GCC's 9889 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 9890 // function from a base class. These cases may be better served by a 9891 // warning (not specific to virtual functions) on call sites when the 9892 // call would select a different function from the base class, were it 9893 // visible. 9894 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 9895 if (!S->IsOverload(Method, MD, false)) 9896 return true; 9897 // Collect the overload only if its hidden. 9898 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods)) 9899 overloadedMethods.push_back(MD); 9900 } 9901 } 9902 9903 if (foundSameNameMethod) 9904 OverloadedMethods.append(overloadedMethods.begin(), 9905 overloadedMethods.end()); 9906 return foundSameNameMethod; 9907 } 9908 }; 9909 } // end anonymous namespace 9910 9911 /// Add the most overridden methods from MD to Methods 9912 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 9913 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 9914 if (MD->size_overridden_methods() == 0) 9915 Methods.insert(MD->getCanonicalDecl()); 9916 else 9917 for (const CXXMethodDecl *O : MD->overridden_methods()) 9918 AddMostOverridenMethods(O, Methods); 9919 } 9920 9921 /// Check if a method overloads virtual methods in a base class without 9922 /// overriding any. 9923 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 9924 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 9925 if (!MD->getDeclName().isIdentifier()) 9926 return; 9927 9928 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 9929 /*bool RecordPaths=*/false, 9930 /*bool DetectVirtual=*/false); 9931 FindHiddenVirtualMethod FHVM; 9932 FHVM.Method = MD; 9933 FHVM.S = this; 9934 9935 // Keep the base methods that were overridden or introduced in the subclass 9936 // by 'using' in a set. A base method not in this set is hidden. 9937 CXXRecordDecl *DC = MD->getParent(); 9938 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 9939 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 9940 NamedDecl *ND = *I; 9941 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 9942 ND = shad->getTargetDecl(); 9943 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 9944 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods); 9945 } 9946 9947 if (DC->lookupInBases(FHVM, Paths)) 9948 OverloadedMethods = FHVM.OverloadedMethods; 9949 } 9950 9951 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 9952 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 9953 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 9954 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 9955 PartialDiagnostic PD = PDiag( 9956 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 9957 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 9958 Diag(overloadedMD->getLocation(), PD); 9959 } 9960 } 9961 9962 /// Diagnose methods which overload virtual methods in a base class 9963 /// without overriding any. 9964 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 9965 if (MD->isInvalidDecl()) 9966 return; 9967 9968 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 9969 return; 9970 9971 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 9972 FindHiddenVirtualMethods(MD, OverloadedMethods); 9973 if (!OverloadedMethods.empty()) { 9974 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 9975 << MD << (OverloadedMethods.size() > 1); 9976 9977 NoteHiddenVirtualMethods(MD, OverloadedMethods); 9978 } 9979 } 9980 9981 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) { 9982 auto PrintDiagAndRemoveAttr = [&](unsigned N) { 9983 // No diagnostics if this is a template instantiation. 9984 if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) { 9985 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), 9986 diag::ext_cannot_use_trivial_abi) << &RD; 9987 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), 9988 diag::note_cannot_use_trivial_abi_reason) << &RD << N; 9989 } 9990 RD.dropAttr<TrivialABIAttr>(); 9991 }; 9992 9993 // Ill-formed if the copy and move constructors are deleted. 9994 auto HasNonDeletedCopyOrMoveConstructor = [&]() { 9995 // If the type is dependent, then assume it might have 9996 // implicit copy or move ctor because we won't know yet at this point. 9997 if (RD.isDependentType()) 9998 return true; 9999 if (RD.needsImplicitCopyConstructor() && 10000 !RD.defaultedCopyConstructorIsDeleted()) 10001 return true; 10002 if (RD.needsImplicitMoveConstructor() && 10003 !RD.defaultedMoveConstructorIsDeleted()) 10004 return true; 10005 for (const CXXConstructorDecl *CD : RD.ctors()) 10006 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted()) 10007 return true; 10008 return false; 10009 }; 10010 10011 if (!HasNonDeletedCopyOrMoveConstructor()) { 10012 PrintDiagAndRemoveAttr(0); 10013 return; 10014 } 10015 10016 // Ill-formed if the struct has virtual functions. 10017 if (RD.isPolymorphic()) { 10018 PrintDiagAndRemoveAttr(1); 10019 return; 10020 } 10021 10022 for (const auto &B : RD.bases()) { 10023 // Ill-formed if the base class is non-trivial for the purpose of calls or a 10024 // virtual base. 10025 if (!B.getType()->isDependentType() && 10026 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) { 10027 PrintDiagAndRemoveAttr(2); 10028 return; 10029 } 10030 10031 if (B.isVirtual()) { 10032 PrintDiagAndRemoveAttr(3); 10033 return; 10034 } 10035 } 10036 10037 for (const auto *FD : RD.fields()) { 10038 // Ill-formed if the field is an ObjectiveC pointer or of a type that is 10039 // non-trivial for the purpose of calls. 10040 QualType FT = FD->getType(); 10041 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) { 10042 PrintDiagAndRemoveAttr(4); 10043 return; 10044 } 10045 10046 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>()) 10047 if (!RT->isDependentType() && 10048 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) { 10049 PrintDiagAndRemoveAttr(5); 10050 return; 10051 } 10052 } 10053 } 10054 10055 void Sema::ActOnFinishCXXMemberSpecification( 10056 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, 10057 SourceLocation RBrac, const ParsedAttributesView &AttrList) { 10058 if (!TagDecl) 10059 return; 10060 10061 AdjustDeclIfTemplate(TagDecl); 10062 10063 for (const ParsedAttr &AL : AttrList) { 10064 if (AL.getKind() != ParsedAttr::AT_Visibility) 10065 continue; 10066 AL.setInvalid(); 10067 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL; 10068 } 10069 10070 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 10071 // strict aliasing violation! 10072 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 10073 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 10074 10075 CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl)); 10076 } 10077 10078 /// Find the equality comparison functions that should be implicitly declared 10079 /// in a given class definition, per C++2a [class.compare.default]p3. 10080 static void findImplicitlyDeclaredEqualityComparisons( 10081 ASTContext &Ctx, CXXRecordDecl *RD, 10082 llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) { 10083 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual); 10084 if (!RD->lookup(EqEq).empty()) 10085 // Member operator== explicitly declared: no implicit operator==s. 10086 return; 10087 10088 // Traverse friends looking for an '==' or a '<=>'. 10089 for (FriendDecl *Friend : RD->friends()) { 10090 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl()); 10091 if (!FD) continue; 10092 10093 if (FD->getOverloadedOperator() == OO_EqualEqual) { 10094 // Friend operator== explicitly declared: no implicit operator==s. 10095 Spaceships.clear(); 10096 return; 10097 } 10098 10099 if (FD->getOverloadedOperator() == OO_Spaceship && 10100 FD->isExplicitlyDefaulted()) 10101 Spaceships.push_back(FD); 10102 } 10103 10104 // Look for members named 'operator<=>'. 10105 DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship); 10106 for (NamedDecl *ND : RD->lookup(Cmp)) { 10107 // Note that we could find a non-function here (either a function template 10108 // or a using-declaration). Neither case results in an implicit 10109 // 'operator=='. 10110 if (auto *FD = dyn_cast<FunctionDecl>(ND)) 10111 if (FD->isExplicitlyDefaulted()) 10112 Spaceships.push_back(FD); 10113 } 10114 } 10115 10116 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 10117 /// special functions, such as the default constructor, copy 10118 /// constructor, or destructor, to the given C++ class (C++ 10119 /// [special]p1). This routine can only be executed just before the 10120 /// definition of the class is complete. 10121 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 10122 // Don't add implicit special members to templated classes. 10123 // FIXME: This means unqualified lookups for 'operator=' within a class 10124 // template don't work properly. 10125 if (!ClassDecl->isDependentType()) { 10126 if (ClassDecl->needsImplicitDefaultConstructor()) { 10127 ++getASTContext().NumImplicitDefaultConstructors; 10128 10129 if (ClassDecl->hasInheritedConstructor()) 10130 DeclareImplicitDefaultConstructor(ClassDecl); 10131 } 10132 10133 if (ClassDecl->needsImplicitCopyConstructor()) { 10134 ++getASTContext().NumImplicitCopyConstructors; 10135 10136 // If the properties or semantics of the copy constructor couldn't be 10137 // determined while the class was being declared, force a declaration 10138 // of it now. 10139 if (ClassDecl->needsOverloadResolutionForCopyConstructor() || 10140 ClassDecl->hasInheritedConstructor()) 10141 DeclareImplicitCopyConstructor(ClassDecl); 10142 // For the MS ABI we need to know whether the copy ctor is deleted. A 10143 // prerequisite for deleting the implicit copy ctor is that the class has 10144 // a move ctor or move assignment that is either user-declared or whose 10145 // semantics are inherited from a subobject. FIXME: We should provide a 10146 // more direct way for CodeGen to ask whether the constructor was deleted. 10147 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 10148 (ClassDecl->hasUserDeclaredMoveConstructor() || 10149 ClassDecl->needsOverloadResolutionForMoveConstructor() || 10150 ClassDecl->hasUserDeclaredMoveAssignment() || 10151 ClassDecl->needsOverloadResolutionForMoveAssignment())) 10152 DeclareImplicitCopyConstructor(ClassDecl); 10153 } 10154 10155 if (getLangOpts().CPlusPlus11 && 10156 ClassDecl->needsImplicitMoveConstructor()) { 10157 ++getASTContext().NumImplicitMoveConstructors; 10158 10159 if (ClassDecl->needsOverloadResolutionForMoveConstructor() || 10160 ClassDecl->hasInheritedConstructor()) 10161 DeclareImplicitMoveConstructor(ClassDecl); 10162 } 10163 10164 if (ClassDecl->needsImplicitCopyAssignment()) { 10165 ++getASTContext().NumImplicitCopyAssignmentOperators; 10166 10167 // If we have a dynamic class, then the copy assignment operator may be 10168 // virtual, so we have to declare it immediately. This ensures that, e.g., 10169 // it shows up in the right place in the vtable and that we diagnose 10170 // problems with the implicit exception specification. 10171 if (ClassDecl->isDynamicClass() || 10172 ClassDecl->needsOverloadResolutionForCopyAssignment() || 10173 ClassDecl->hasInheritedAssignment()) 10174 DeclareImplicitCopyAssignment(ClassDecl); 10175 } 10176 10177 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 10178 ++getASTContext().NumImplicitMoveAssignmentOperators; 10179 10180 // Likewise for the move assignment operator. 10181 if (ClassDecl->isDynamicClass() || 10182 ClassDecl->needsOverloadResolutionForMoveAssignment() || 10183 ClassDecl->hasInheritedAssignment()) 10184 DeclareImplicitMoveAssignment(ClassDecl); 10185 } 10186 10187 if (ClassDecl->needsImplicitDestructor()) { 10188 ++getASTContext().NumImplicitDestructors; 10189 10190 // If we have a dynamic class, then the destructor may be virtual, so we 10191 // have to declare the destructor immediately. This ensures that, e.g., it 10192 // shows up in the right place in the vtable and that we diagnose problems 10193 // with the implicit exception specification. 10194 if (ClassDecl->isDynamicClass() || 10195 ClassDecl->needsOverloadResolutionForDestructor()) 10196 DeclareImplicitDestructor(ClassDecl); 10197 } 10198 } 10199 10200 // C++2a [class.compare.default]p3: 10201 // If the member-specification does not explicitly declare any member or 10202 // friend named operator==, an == operator function is declared implicitly 10203 // for each defaulted three-way comparison operator function defined in 10204 // the member-specification 10205 // FIXME: Consider doing this lazily. 10206 // We do this during the initial parse for a class template, not during 10207 // instantiation, so that we can handle unqualified lookups for 'operator==' 10208 // when parsing the template. 10209 if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) { 10210 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships; 10211 findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl, 10212 DefaultedSpaceships); 10213 for (auto *FD : DefaultedSpaceships) 10214 DeclareImplicitEqualityComparison(ClassDecl, FD); 10215 } 10216 } 10217 10218 unsigned 10219 Sema::ActOnReenterTemplateScope(Decl *D, 10220 llvm::function_ref<Scope *()> EnterScope) { 10221 if (!D) 10222 return 0; 10223 AdjustDeclIfTemplate(D); 10224 10225 // In order to get name lookup right, reenter template scopes in order from 10226 // outermost to innermost. 10227 SmallVector<TemplateParameterList *, 4> ParameterLists; 10228 DeclContext *LookupDC = dyn_cast<DeclContext>(D); 10229 10230 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 10231 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 10232 ParameterLists.push_back(DD->getTemplateParameterList(i)); 10233 10234 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 10235 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 10236 ParameterLists.push_back(FTD->getTemplateParameters()); 10237 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 10238 LookupDC = VD->getDeclContext(); 10239 10240 if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate()) 10241 ParameterLists.push_back(VTD->getTemplateParameters()); 10242 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D)) 10243 ParameterLists.push_back(PSD->getTemplateParameters()); 10244 } 10245 } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 10246 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 10247 ParameterLists.push_back(TD->getTemplateParameterList(i)); 10248 10249 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 10250 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 10251 ParameterLists.push_back(CTD->getTemplateParameters()); 10252 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 10253 ParameterLists.push_back(PSD->getTemplateParameters()); 10254 } 10255 } 10256 // FIXME: Alias declarations and concepts. 10257 10258 unsigned Count = 0; 10259 Scope *InnermostTemplateScope = nullptr; 10260 for (TemplateParameterList *Params : ParameterLists) { 10261 // Ignore explicit specializations; they don't contribute to the template 10262 // depth. 10263 if (Params->size() == 0) 10264 continue; 10265 10266 InnermostTemplateScope = EnterScope(); 10267 for (NamedDecl *Param : *Params) { 10268 if (Param->getDeclName()) { 10269 InnermostTemplateScope->AddDecl(Param); 10270 IdResolver.AddDecl(Param); 10271 } 10272 } 10273 ++Count; 10274 } 10275 10276 // Associate the new template scopes with the corresponding entities. 10277 if (InnermostTemplateScope) { 10278 assert(LookupDC && "no enclosing DeclContext for template lookup"); 10279 EnterTemplatedContext(InnermostTemplateScope, LookupDC); 10280 } 10281 10282 return Count; 10283 } 10284 10285 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 10286 if (!RecordD) return; 10287 AdjustDeclIfTemplate(RecordD); 10288 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 10289 PushDeclContext(S, Record); 10290 } 10291 10292 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 10293 if (!RecordD) return; 10294 PopDeclContext(); 10295 } 10296 10297 /// This is used to implement the constant expression evaluation part of the 10298 /// attribute enable_if extension. There is nothing in standard C++ which would 10299 /// require reentering parameters. 10300 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 10301 if (!Param) 10302 return; 10303 10304 S->AddDecl(Param); 10305 if (Param->getDeclName()) 10306 IdResolver.AddDecl(Param); 10307 } 10308 10309 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 10310 /// parsing a top-level (non-nested) C++ class, and we are now 10311 /// parsing those parts of the given Method declaration that could 10312 /// not be parsed earlier (C++ [class.mem]p2), such as default 10313 /// arguments. This action should enter the scope of the given 10314 /// Method declaration as if we had just parsed the qualified method 10315 /// name. However, it should not bring the parameters into scope; 10316 /// that will be performed by ActOnDelayedCXXMethodParameter. 10317 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 10318 } 10319 10320 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 10321 /// C++ method declaration. We're (re-)introducing the given 10322 /// function parameter into scope for use in parsing later parts of 10323 /// the method declaration. For example, we could see an 10324 /// ActOnParamDefaultArgument event for this parameter. 10325 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 10326 if (!ParamD) 10327 return; 10328 10329 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 10330 10331 S->AddDecl(Param); 10332 if (Param->getDeclName()) 10333 IdResolver.AddDecl(Param); 10334 } 10335 10336 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 10337 /// processing the delayed method declaration for Method. The method 10338 /// declaration is now considered finished. There may be a separate 10339 /// ActOnStartOfFunctionDef action later (not necessarily 10340 /// immediately!) for this method, if it was also defined inside the 10341 /// class body. 10342 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 10343 if (!MethodD) 10344 return; 10345 10346 AdjustDeclIfTemplate(MethodD); 10347 10348 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 10349 10350 // Now that we have our default arguments, check the constructor 10351 // again. It could produce additional diagnostics or affect whether 10352 // the class has implicitly-declared destructors, among other 10353 // things. 10354 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 10355 CheckConstructor(Constructor); 10356 10357 // Check the default arguments, which we may have added. 10358 if (!Method->isInvalidDecl()) 10359 CheckCXXDefaultArguments(Method); 10360 } 10361 10362 // Emit the given diagnostic for each non-address-space qualifier. 10363 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator. 10364 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) { 10365 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10366 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) { 10367 bool DiagOccured = false; 10368 FTI.MethodQualifiers->forEachQualifier( 10369 [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName, 10370 SourceLocation SL) { 10371 // This diagnostic should be emitted on any qualifier except an addr 10372 // space qualifier. However, forEachQualifier currently doesn't visit 10373 // addr space qualifiers, so there's no way to write this condition 10374 // right now; we just diagnose on everything. 10375 S.Diag(SL, DiagID) << QualName << SourceRange(SL); 10376 DiagOccured = true; 10377 }); 10378 if (DiagOccured) 10379 D.setInvalidType(); 10380 } 10381 } 10382 10383 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 10384 /// the well-formedness of the constructor declarator @p D with type @p 10385 /// R. If there are any errors in the declarator, this routine will 10386 /// emit diagnostics and set the invalid bit to true. In any case, the type 10387 /// will be updated to reflect a well-formed type for the constructor and 10388 /// returned. 10389 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 10390 StorageClass &SC) { 10391 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 10392 10393 // C++ [class.ctor]p3: 10394 // A constructor shall not be virtual (10.3) or static (9.4). A 10395 // constructor can be invoked for a const, volatile or const 10396 // volatile object. A constructor shall not be declared const, 10397 // volatile, or const volatile (9.3.2). 10398 if (isVirtual) { 10399 if (!D.isInvalidType()) 10400 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 10401 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 10402 << SourceRange(D.getIdentifierLoc()); 10403 D.setInvalidType(); 10404 } 10405 if (SC == SC_Static) { 10406 if (!D.isInvalidType()) 10407 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 10408 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10409 << SourceRange(D.getIdentifierLoc()); 10410 D.setInvalidType(); 10411 SC = SC_None; 10412 } 10413 10414 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 10415 diagnoseIgnoredQualifiers( 10416 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 10417 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 10418 D.getDeclSpec().getRestrictSpecLoc(), 10419 D.getDeclSpec().getAtomicSpecLoc()); 10420 D.setInvalidType(); 10421 } 10422 10423 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor); 10424 10425 // C++0x [class.ctor]p4: 10426 // A constructor shall not be declared with a ref-qualifier. 10427 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10428 if (FTI.hasRefQualifier()) { 10429 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 10430 << FTI.RefQualifierIsLValueRef 10431 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 10432 D.setInvalidType(); 10433 } 10434 10435 // Rebuild the function type "R" without any type qualifiers (in 10436 // case any of the errors above fired) and with "void" as the 10437 // return type, since constructors don't have return types. 10438 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>(); 10439 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 10440 return R; 10441 10442 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 10443 EPI.TypeQuals = Qualifiers(); 10444 EPI.RefQualifier = RQ_None; 10445 10446 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 10447 } 10448 10449 /// CheckConstructor - Checks a fully-formed constructor for 10450 /// well-formedness, issuing any diagnostics required. Returns true if 10451 /// the constructor declarator is invalid. 10452 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 10453 CXXRecordDecl *ClassDecl 10454 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 10455 if (!ClassDecl) 10456 return Constructor->setInvalidDecl(); 10457 10458 // C++ [class.copy]p3: 10459 // A declaration of a constructor for a class X is ill-formed if 10460 // its first parameter is of type (optionally cv-qualified) X and 10461 // either there are no other parameters or else all other 10462 // parameters have default arguments. 10463 if (!Constructor->isInvalidDecl() && 10464 Constructor->hasOneParamOrDefaultArgs() && 10465 Constructor->getTemplateSpecializationKind() != 10466 TSK_ImplicitInstantiation) { 10467 QualType ParamType = Constructor->getParamDecl(0)->getType(); 10468 QualType ClassTy = Context.getTagDeclType(ClassDecl); 10469 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 10470 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 10471 const char *ConstRef 10472 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 10473 : " const &"; 10474 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 10475 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 10476 10477 // FIXME: Rather that making the constructor invalid, we should endeavor 10478 // to fix the type. 10479 Constructor->setInvalidDecl(); 10480 } 10481 } 10482 } 10483 10484 /// CheckDestructor - Checks a fully-formed destructor definition for 10485 /// well-formedness, issuing any diagnostics required. Returns true 10486 /// on error. 10487 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 10488 CXXRecordDecl *RD = Destructor->getParent(); 10489 10490 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 10491 SourceLocation Loc; 10492 10493 if (!Destructor->isImplicit()) 10494 Loc = Destructor->getLocation(); 10495 else 10496 Loc = RD->getLocation(); 10497 10498 // If we have a virtual destructor, look up the deallocation function 10499 if (FunctionDecl *OperatorDelete = 10500 FindDeallocationFunctionForDestructor(Loc, RD)) { 10501 Expr *ThisArg = nullptr; 10502 10503 // If the notional 'delete this' expression requires a non-trivial 10504 // conversion from 'this' to the type of a destroying operator delete's 10505 // first parameter, perform that conversion now. 10506 if (OperatorDelete->isDestroyingOperatorDelete()) { 10507 QualType ParamType = OperatorDelete->getParamDecl(0)->getType(); 10508 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) { 10509 // C++ [class.dtor]p13: 10510 // ... as if for the expression 'delete this' appearing in a 10511 // non-virtual destructor of the destructor's class. 10512 ContextRAII SwitchContext(*this, Destructor); 10513 ExprResult This = 10514 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation()); 10515 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?"); 10516 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing); 10517 if (This.isInvalid()) { 10518 // FIXME: Register this as a context note so that it comes out 10519 // in the right order. 10520 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here); 10521 return true; 10522 } 10523 ThisArg = This.get(); 10524 } 10525 } 10526 10527 DiagnoseUseOfDecl(OperatorDelete, Loc); 10528 MarkFunctionReferenced(Loc, OperatorDelete); 10529 Destructor->setOperatorDelete(OperatorDelete, ThisArg); 10530 } 10531 } 10532 10533 return false; 10534 } 10535 10536 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 10537 /// the well-formednes of the destructor declarator @p D with type @p 10538 /// R. If there are any errors in the declarator, this routine will 10539 /// emit diagnostics and set the declarator to invalid. Even if this happens, 10540 /// will be updated to reflect a well-formed type for the destructor and 10541 /// returned. 10542 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 10543 StorageClass& SC) { 10544 // C++ [class.dtor]p1: 10545 // [...] A typedef-name that names a class is a class-name 10546 // (7.1.3); however, a typedef-name that names a class shall not 10547 // be used as the identifier in the declarator for a destructor 10548 // declaration. 10549 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 10550 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 10551 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name) 10552 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 10553 else if (const TemplateSpecializationType *TST = 10554 DeclaratorType->getAs<TemplateSpecializationType>()) 10555 if (TST->isTypeAlias()) 10556 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name) 10557 << DeclaratorType << 1; 10558 10559 // C++ [class.dtor]p2: 10560 // A destructor is used to destroy objects of its class type. A 10561 // destructor takes no parameters, and no return type can be 10562 // specified for it (not even void). The address of a destructor 10563 // shall not be taken. A destructor shall not be static. A 10564 // destructor can be invoked for a const, volatile or const 10565 // volatile object. A destructor shall not be declared const, 10566 // volatile or const volatile (9.3.2). 10567 if (SC == SC_Static) { 10568 if (!D.isInvalidType()) 10569 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 10570 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10571 << SourceRange(D.getIdentifierLoc()) 10572 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 10573 10574 SC = SC_None; 10575 } 10576 if (!D.isInvalidType()) { 10577 // Destructors don't have return types, but the parser will 10578 // happily parse something like: 10579 // 10580 // class X { 10581 // float ~X(); 10582 // }; 10583 // 10584 // The return type will be eliminated later. 10585 if (D.getDeclSpec().hasTypeSpecifier()) 10586 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 10587 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 10588 << SourceRange(D.getIdentifierLoc()); 10589 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 10590 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 10591 SourceLocation(), 10592 D.getDeclSpec().getConstSpecLoc(), 10593 D.getDeclSpec().getVolatileSpecLoc(), 10594 D.getDeclSpec().getRestrictSpecLoc(), 10595 D.getDeclSpec().getAtomicSpecLoc()); 10596 D.setInvalidType(); 10597 } 10598 } 10599 10600 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor); 10601 10602 // C++0x [class.dtor]p2: 10603 // A destructor shall not be declared with a ref-qualifier. 10604 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10605 if (FTI.hasRefQualifier()) { 10606 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 10607 << FTI.RefQualifierIsLValueRef 10608 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 10609 D.setInvalidType(); 10610 } 10611 10612 // Make sure we don't have any parameters. 10613 if (FTIHasNonVoidParameters(FTI)) { 10614 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 10615 10616 // Delete the parameters. 10617 FTI.freeParams(); 10618 D.setInvalidType(); 10619 } 10620 10621 // Make sure the destructor isn't variadic. 10622 if (FTI.isVariadic) { 10623 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 10624 D.setInvalidType(); 10625 } 10626 10627 // Rebuild the function type "R" without any type qualifiers or 10628 // parameters (in case any of the errors above fired) and with 10629 // "void" as the return type, since destructors don't have return 10630 // types. 10631 if (!D.isInvalidType()) 10632 return R; 10633 10634 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>(); 10635 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 10636 EPI.Variadic = false; 10637 EPI.TypeQuals = Qualifiers(); 10638 EPI.RefQualifier = RQ_None; 10639 return Context.getFunctionType(Context.VoidTy, None, EPI); 10640 } 10641 10642 static void extendLeft(SourceRange &R, SourceRange Before) { 10643 if (Before.isInvalid()) 10644 return; 10645 R.setBegin(Before.getBegin()); 10646 if (R.getEnd().isInvalid()) 10647 R.setEnd(Before.getEnd()); 10648 } 10649 10650 static void extendRight(SourceRange &R, SourceRange After) { 10651 if (After.isInvalid()) 10652 return; 10653 if (R.getBegin().isInvalid()) 10654 R.setBegin(After.getBegin()); 10655 R.setEnd(After.getEnd()); 10656 } 10657 10658 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 10659 /// well-formednes of the conversion function declarator @p D with 10660 /// type @p R. If there are any errors in the declarator, this routine 10661 /// will emit diagnostics and return true. Otherwise, it will return 10662 /// false. Either way, the type @p R will be updated to reflect a 10663 /// well-formed type for the conversion operator. 10664 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 10665 StorageClass& SC) { 10666 // C++ [class.conv.fct]p1: 10667 // Neither parameter types nor return type can be specified. The 10668 // type of a conversion function (8.3.5) is "function taking no 10669 // parameter returning conversion-type-id." 10670 if (SC == SC_Static) { 10671 if (!D.isInvalidType()) 10672 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 10673 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10674 << D.getName().getSourceRange(); 10675 D.setInvalidType(); 10676 SC = SC_None; 10677 } 10678 10679 TypeSourceInfo *ConvTSI = nullptr; 10680 QualType ConvType = 10681 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); 10682 10683 const DeclSpec &DS = D.getDeclSpec(); 10684 if (DS.hasTypeSpecifier() && !D.isInvalidType()) { 10685 // Conversion functions don't have return types, but the parser will 10686 // happily parse something like: 10687 // 10688 // class X { 10689 // float operator bool(); 10690 // }; 10691 // 10692 // The return type will be changed later anyway. 10693 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 10694 << SourceRange(DS.getTypeSpecTypeLoc()) 10695 << SourceRange(D.getIdentifierLoc()); 10696 D.setInvalidType(); 10697 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) { 10698 // It's also plausible that the user writes type qualifiers in the wrong 10699 // place, such as: 10700 // struct S { const operator int(); }; 10701 // FIXME: we could provide a fixit to move the qualifiers onto the 10702 // conversion type. 10703 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 10704 << SourceRange(D.getIdentifierLoc()) << 0; 10705 D.setInvalidType(); 10706 } 10707 10708 const auto *Proto = R->castAs<FunctionProtoType>(); 10709 10710 // Make sure we don't have any parameters. 10711 if (Proto->getNumParams() > 0) { 10712 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 10713 10714 // Delete the parameters. 10715 D.getFunctionTypeInfo().freeParams(); 10716 D.setInvalidType(); 10717 } else if (Proto->isVariadic()) { 10718 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 10719 D.setInvalidType(); 10720 } 10721 10722 // Diagnose "&operator bool()" and other such nonsense. This 10723 // is actually a gcc extension which we don't support. 10724 if (Proto->getReturnType() != ConvType) { 10725 bool NeedsTypedef = false; 10726 SourceRange Before, After; 10727 10728 // Walk the chunks and extract information on them for our diagnostic. 10729 bool PastFunctionChunk = false; 10730 for (auto &Chunk : D.type_objects()) { 10731 switch (Chunk.Kind) { 10732 case DeclaratorChunk::Function: 10733 if (!PastFunctionChunk) { 10734 if (Chunk.Fun.HasTrailingReturnType) { 10735 TypeSourceInfo *TRT = nullptr; 10736 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); 10737 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); 10738 } 10739 PastFunctionChunk = true; 10740 break; 10741 } 10742 LLVM_FALLTHROUGH; 10743 case DeclaratorChunk::Array: 10744 NeedsTypedef = true; 10745 extendRight(After, Chunk.getSourceRange()); 10746 break; 10747 10748 case DeclaratorChunk::Pointer: 10749 case DeclaratorChunk::BlockPointer: 10750 case DeclaratorChunk::Reference: 10751 case DeclaratorChunk::MemberPointer: 10752 case DeclaratorChunk::Pipe: 10753 extendLeft(Before, Chunk.getSourceRange()); 10754 break; 10755 10756 case DeclaratorChunk::Paren: 10757 extendLeft(Before, Chunk.Loc); 10758 extendRight(After, Chunk.EndLoc); 10759 break; 10760 } 10761 } 10762 10763 SourceLocation Loc = Before.isValid() ? Before.getBegin() : 10764 After.isValid() ? After.getBegin() : 10765 D.getIdentifierLoc(); 10766 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); 10767 DB << Before << After; 10768 10769 if (!NeedsTypedef) { 10770 DB << /*don't need a typedef*/0; 10771 10772 // If we can provide a correct fix-it hint, do so. 10773 if (After.isInvalid() && ConvTSI) { 10774 SourceLocation InsertLoc = 10775 getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc()); 10776 DB << FixItHint::CreateInsertion(InsertLoc, " ") 10777 << FixItHint::CreateInsertionFromRange( 10778 InsertLoc, CharSourceRange::getTokenRange(Before)) 10779 << FixItHint::CreateRemoval(Before); 10780 } 10781 } else if (!Proto->getReturnType()->isDependentType()) { 10782 DB << /*typedef*/1 << Proto->getReturnType(); 10783 } else if (getLangOpts().CPlusPlus11) { 10784 DB << /*alias template*/2 << Proto->getReturnType(); 10785 } else { 10786 DB << /*might not be fixable*/3; 10787 } 10788 10789 // Recover by incorporating the other type chunks into the result type. 10790 // Note, this does *not* change the name of the function. This is compatible 10791 // with the GCC extension: 10792 // struct S { &operator int(); } s; 10793 // int &r = s.operator int(); // ok in GCC 10794 // S::operator int&() {} // error in GCC, function name is 'operator int'. 10795 ConvType = Proto->getReturnType(); 10796 } 10797 10798 // C++ [class.conv.fct]p4: 10799 // The conversion-type-id shall not represent a function type nor 10800 // an array type. 10801 if (ConvType->isArrayType()) { 10802 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 10803 ConvType = Context.getPointerType(ConvType); 10804 D.setInvalidType(); 10805 } else if (ConvType->isFunctionType()) { 10806 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 10807 ConvType = Context.getPointerType(ConvType); 10808 D.setInvalidType(); 10809 } 10810 10811 // Rebuild the function type "R" without any parameters (in case any 10812 // of the errors above fired) and with the conversion type as the 10813 // return type. 10814 if (D.isInvalidType()) 10815 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 10816 10817 // C++0x explicit conversion operators. 10818 if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20) 10819 Diag(DS.getExplicitSpecLoc(), 10820 getLangOpts().CPlusPlus11 10821 ? diag::warn_cxx98_compat_explicit_conversion_functions 10822 : diag::ext_explicit_conversion_functions) 10823 << SourceRange(DS.getExplicitSpecRange()); 10824 } 10825 10826 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 10827 /// the declaration of the given C++ conversion function. This routine 10828 /// is responsible for recording the conversion function in the C++ 10829 /// class, if possible. 10830 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 10831 assert(Conversion && "Expected to receive a conversion function declaration"); 10832 10833 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 10834 10835 // Make sure we aren't redeclaring the conversion function. 10836 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 10837 // C++ [class.conv.fct]p1: 10838 // [...] A conversion function is never used to convert a 10839 // (possibly cv-qualified) object to the (possibly cv-qualified) 10840 // same object type (or a reference to it), to a (possibly 10841 // cv-qualified) base class of that type (or a reference to it), 10842 // or to (possibly cv-qualified) void. 10843 QualType ClassType 10844 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 10845 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 10846 ConvType = ConvTypeRef->getPointeeType(); 10847 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 10848 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 10849 /* Suppress diagnostics for instantiations. */; 10850 else if (Conversion->size_overridden_methods() != 0) 10851 /* Suppress diagnostics for overriding virtual function in a base class. */; 10852 else if (ConvType->isRecordType()) { 10853 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 10854 if (ConvType == ClassType) 10855 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 10856 << ClassType; 10857 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType)) 10858 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 10859 << ClassType << ConvType; 10860 } else if (ConvType->isVoidType()) { 10861 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 10862 << ClassType << ConvType; 10863 } 10864 10865 if (FunctionTemplateDecl *ConversionTemplate 10866 = Conversion->getDescribedFunctionTemplate()) 10867 return ConversionTemplate; 10868 10869 return Conversion; 10870 } 10871 10872 namespace { 10873 /// Utility class to accumulate and print a diagnostic listing the invalid 10874 /// specifier(s) on a declaration. 10875 struct BadSpecifierDiagnoser { 10876 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID) 10877 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {} 10878 ~BadSpecifierDiagnoser() { 10879 Diagnostic << Specifiers; 10880 } 10881 10882 template<typename T> void check(SourceLocation SpecLoc, T Spec) { 10883 return check(SpecLoc, DeclSpec::getSpecifierName(Spec)); 10884 } 10885 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) { 10886 return check(SpecLoc, 10887 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy())); 10888 } 10889 void check(SourceLocation SpecLoc, const char *Spec) { 10890 if (SpecLoc.isInvalid()) return; 10891 Diagnostic << SourceRange(SpecLoc, SpecLoc); 10892 if (!Specifiers.empty()) Specifiers += " "; 10893 Specifiers += Spec; 10894 } 10895 10896 Sema &S; 10897 Sema::SemaDiagnosticBuilder Diagnostic; 10898 std::string Specifiers; 10899 }; 10900 } 10901 10902 /// Check the validity of a declarator that we parsed for a deduction-guide. 10903 /// These aren't actually declarators in the grammar, so we need to check that 10904 /// the user didn't specify any pieces that are not part of the deduction-guide 10905 /// grammar. 10906 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R, 10907 StorageClass &SC) { 10908 TemplateName GuidedTemplate = D.getName().TemplateName.get().get(); 10909 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl(); 10910 assert(GuidedTemplateDecl && "missing template decl for deduction guide"); 10911 10912 // C++ [temp.deduct.guide]p3: 10913 // A deduction-gide shall be declared in the same scope as the 10914 // corresponding class template. 10915 if (!CurContext->getRedeclContext()->Equals( 10916 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) { 10917 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope) 10918 << GuidedTemplateDecl; 10919 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here); 10920 } 10921 10922 auto &DS = D.getMutableDeclSpec(); 10923 // We leave 'friend' and 'virtual' to be rejected in the normal way. 10924 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() || 10925 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() || 10926 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) { 10927 BadSpecifierDiagnoser Diagnoser( 10928 *this, D.getIdentifierLoc(), 10929 diag::err_deduction_guide_invalid_specifier); 10930 10931 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec()); 10932 DS.ClearStorageClassSpecs(); 10933 SC = SC_None; 10934 10935 // 'explicit' is permitted. 10936 Diagnoser.check(DS.getInlineSpecLoc(), "inline"); 10937 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn"); 10938 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr"); 10939 DS.ClearConstexprSpec(); 10940 10941 Diagnoser.check(DS.getConstSpecLoc(), "const"); 10942 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict"); 10943 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile"); 10944 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic"); 10945 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned"); 10946 DS.ClearTypeQualifiers(); 10947 10948 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex()); 10949 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign()); 10950 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth()); 10951 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType()); 10952 DS.ClearTypeSpecType(); 10953 } 10954 10955 if (D.isInvalidType()) 10956 return; 10957 10958 // Check the declarator is simple enough. 10959 bool FoundFunction = false; 10960 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) { 10961 if (Chunk.Kind == DeclaratorChunk::Paren) 10962 continue; 10963 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) { 10964 Diag(D.getDeclSpec().getBeginLoc(), 10965 diag::err_deduction_guide_with_complex_decl) 10966 << D.getSourceRange(); 10967 break; 10968 } 10969 if (!Chunk.Fun.hasTrailingReturnType()) { 10970 Diag(D.getName().getBeginLoc(), 10971 diag::err_deduction_guide_no_trailing_return_type); 10972 break; 10973 } 10974 10975 // Check that the return type is written as a specialization of 10976 // the template specified as the deduction-guide's name. 10977 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType(); 10978 TypeSourceInfo *TSI = nullptr; 10979 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI); 10980 assert(TSI && "deduction guide has valid type but invalid return type?"); 10981 bool AcceptableReturnType = false; 10982 bool MightInstantiateToSpecialization = false; 10983 if (auto RetTST = 10984 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) { 10985 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName(); 10986 bool TemplateMatches = 10987 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate); 10988 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches) 10989 AcceptableReturnType = true; 10990 else { 10991 // This could still instantiate to the right type, unless we know it 10992 // names the wrong class template. 10993 auto *TD = SpecifiedName.getAsTemplateDecl(); 10994 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) && 10995 !TemplateMatches); 10996 } 10997 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) { 10998 MightInstantiateToSpecialization = true; 10999 } 11000 11001 if (!AcceptableReturnType) { 11002 Diag(TSI->getTypeLoc().getBeginLoc(), 11003 diag::err_deduction_guide_bad_trailing_return_type) 11004 << GuidedTemplate << TSI->getType() 11005 << MightInstantiateToSpecialization 11006 << TSI->getTypeLoc().getSourceRange(); 11007 } 11008 11009 // Keep going to check that we don't have any inner declarator pieces (we 11010 // could still have a function returning a pointer to a function). 11011 FoundFunction = true; 11012 } 11013 11014 if (D.isFunctionDefinition()) 11015 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function); 11016 } 11017 11018 //===----------------------------------------------------------------------===// 11019 // Namespace Handling 11020 //===----------------------------------------------------------------------===// 11021 11022 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is 11023 /// reopened. 11024 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 11025 SourceLocation Loc, 11026 IdentifierInfo *II, bool *IsInline, 11027 NamespaceDecl *PrevNS) { 11028 assert(*IsInline != PrevNS->isInline()); 11029 11030 if (PrevNS->isInline()) 11031 // The user probably just forgot the 'inline', so suggest that it 11032 // be added back. 11033 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 11034 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 11035 else 11036 S.Diag(Loc, diag::err_inline_namespace_mismatch); 11037 11038 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 11039 *IsInline = PrevNS->isInline(); 11040 } 11041 11042 /// ActOnStartNamespaceDef - This is called at the start of a namespace 11043 /// definition. 11044 Decl *Sema::ActOnStartNamespaceDef( 11045 Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc, 11046 SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace, 11047 const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) { 11048 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 11049 // For anonymous namespace, take the location of the left brace. 11050 SourceLocation Loc = II ? IdentLoc : LBrace; 11051 bool IsInline = InlineLoc.isValid(); 11052 bool IsInvalid = false; 11053 bool IsStd = false; 11054 bool AddToKnown = false; 11055 Scope *DeclRegionScope = NamespcScope->getParent(); 11056 11057 NamespaceDecl *PrevNS = nullptr; 11058 if (II) { 11059 // C++ [namespace.def]p2: 11060 // The identifier in an original-namespace-definition shall not 11061 // have been previously defined in the declarative region in 11062 // which the original-namespace-definition appears. The 11063 // identifier in an original-namespace-definition is the name of 11064 // the namespace. Subsequently in that declarative region, it is 11065 // treated as an original-namespace-name. 11066 // 11067 // Since namespace names are unique in their scope, and we don't 11068 // look through using directives, just look for any ordinary names 11069 // as if by qualified name lookup. 11070 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, 11071 ForExternalRedeclaration); 11072 LookupQualifiedName(R, CurContext->getRedeclContext()); 11073 NamedDecl *PrevDecl = 11074 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr; 11075 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 11076 11077 if (PrevNS) { 11078 // This is an extended namespace definition. 11079 if (IsInline != PrevNS->isInline()) 11080 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 11081 &IsInline, PrevNS); 11082 } else if (PrevDecl) { 11083 // This is an invalid name redefinition. 11084 Diag(Loc, diag::err_redefinition_different_kind) 11085 << II; 11086 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 11087 IsInvalid = true; 11088 // Continue on to push Namespc as current DeclContext and return it. 11089 } else if (II->isStr("std") && 11090 CurContext->getRedeclContext()->isTranslationUnit()) { 11091 // This is the first "real" definition of the namespace "std", so update 11092 // our cache of the "std" namespace to point at this definition. 11093 PrevNS = getStdNamespace(); 11094 IsStd = true; 11095 AddToKnown = !IsInline; 11096 } else { 11097 // We've seen this namespace for the first time. 11098 AddToKnown = !IsInline; 11099 } 11100 } else { 11101 // Anonymous namespaces. 11102 11103 // Determine whether the parent already has an anonymous namespace. 11104 DeclContext *Parent = CurContext->getRedeclContext(); 11105 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 11106 PrevNS = TU->getAnonymousNamespace(); 11107 } else { 11108 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 11109 PrevNS = ND->getAnonymousNamespace(); 11110 } 11111 11112 if (PrevNS && IsInline != PrevNS->isInline()) 11113 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 11114 &IsInline, PrevNS); 11115 } 11116 11117 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 11118 StartLoc, Loc, II, PrevNS); 11119 if (IsInvalid) 11120 Namespc->setInvalidDecl(); 11121 11122 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 11123 AddPragmaAttributes(DeclRegionScope, Namespc); 11124 11125 // FIXME: Should we be merging attributes? 11126 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 11127 PushNamespaceVisibilityAttr(Attr, Loc); 11128 11129 if (IsStd) 11130 StdNamespace = Namespc; 11131 if (AddToKnown) 11132 KnownNamespaces[Namespc] = false; 11133 11134 if (II) { 11135 PushOnScopeChains(Namespc, DeclRegionScope); 11136 } else { 11137 // Link the anonymous namespace into its parent. 11138 DeclContext *Parent = CurContext->getRedeclContext(); 11139 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 11140 TU->setAnonymousNamespace(Namespc); 11141 } else { 11142 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 11143 } 11144 11145 CurContext->addDecl(Namespc); 11146 11147 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 11148 // behaves as if it were replaced by 11149 // namespace unique { /* empty body */ } 11150 // using namespace unique; 11151 // namespace unique { namespace-body } 11152 // where all occurrences of 'unique' in a translation unit are 11153 // replaced by the same identifier and this identifier differs 11154 // from all other identifiers in the entire program. 11155 11156 // We just create the namespace with an empty name and then add an 11157 // implicit using declaration, just like the standard suggests. 11158 // 11159 // CodeGen enforces the "universally unique" aspect by giving all 11160 // declarations semantically contained within an anonymous 11161 // namespace internal linkage. 11162 11163 if (!PrevNS) { 11164 UD = UsingDirectiveDecl::Create(Context, Parent, 11165 /* 'using' */ LBrace, 11166 /* 'namespace' */ SourceLocation(), 11167 /* qualifier */ NestedNameSpecifierLoc(), 11168 /* identifier */ SourceLocation(), 11169 Namespc, 11170 /* Ancestor */ Parent); 11171 UD->setImplicit(); 11172 Parent->addDecl(UD); 11173 } 11174 } 11175 11176 ActOnDocumentableDecl(Namespc); 11177 11178 // Although we could have an invalid decl (i.e. the namespace name is a 11179 // redefinition), push it as current DeclContext and try to continue parsing. 11180 // FIXME: We should be able to push Namespc here, so that the each DeclContext 11181 // for the namespace has the declarations that showed up in that particular 11182 // namespace definition. 11183 PushDeclContext(NamespcScope, Namespc); 11184 return Namespc; 11185 } 11186 11187 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 11188 /// is a namespace alias, returns the namespace it points to. 11189 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 11190 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 11191 return AD->getNamespace(); 11192 return dyn_cast_or_null<NamespaceDecl>(D); 11193 } 11194 11195 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 11196 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 11197 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 11198 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 11199 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 11200 Namespc->setRBraceLoc(RBrace); 11201 PopDeclContext(); 11202 if (Namespc->hasAttr<VisibilityAttr>()) 11203 PopPragmaVisibility(true, RBrace); 11204 // If this namespace contains an export-declaration, export it now. 11205 if (DeferredExportedNamespaces.erase(Namespc)) 11206 Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported); 11207 } 11208 11209 CXXRecordDecl *Sema::getStdBadAlloc() const { 11210 return cast_or_null<CXXRecordDecl>( 11211 StdBadAlloc.get(Context.getExternalSource())); 11212 } 11213 11214 EnumDecl *Sema::getStdAlignValT() const { 11215 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource())); 11216 } 11217 11218 NamespaceDecl *Sema::getStdNamespace() const { 11219 return cast_or_null<NamespaceDecl>( 11220 StdNamespace.get(Context.getExternalSource())); 11221 } 11222 11223 NamespaceDecl *Sema::lookupStdExperimentalNamespace() { 11224 if (!StdExperimentalNamespaceCache) { 11225 if (auto Std = getStdNamespace()) { 11226 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"), 11227 SourceLocation(), LookupNamespaceName); 11228 if (!LookupQualifiedName(Result, Std) || 11229 !(StdExperimentalNamespaceCache = 11230 Result.getAsSingle<NamespaceDecl>())) 11231 Result.suppressDiagnostics(); 11232 } 11233 } 11234 return StdExperimentalNamespaceCache; 11235 } 11236 11237 namespace { 11238 11239 enum UnsupportedSTLSelect { 11240 USS_InvalidMember, 11241 USS_MissingMember, 11242 USS_NonTrivial, 11243 USS_Other 11244 }; 11245 11246 struct InvalidSTLDiagnoser { 11247 Sema &S; 11248 SourceLocation Loc; 11249 QualType TyForDiags; 11250 11251 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "", 11252 const VarDecl *VD = nullptr) { 11253 { 11254 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported) 11255 << TyForDiags << ((int)Sel); 11256 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) { 11257 assert(!Name.empty()); 11258 D << Name; 11259 } 11260 } 11261 if (Sel == USS_InvalidMember) { 11262 S.Diag(VD->getLocation(), diag::note_var_declared_here) 11263 << VD << VD->getSourceRange(); 11264 } 11265 return QualType(); 11266 } 11267 }; 11268 } // namespace 11269 11270 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind, 11271 SourceLocation Loc, 11272 ComparisonCategoryUsage Usage) { 11273 assert(getLangOpts().CPlusPlus && 11274 "Looking for comparison category type outside of C++."); 11275 11276 // Use an elaborated type for diagnostics which has a name containing the 11277 // prepended 'std' namespace but not any inline namespace names. 11278 auto TyForDiags = [&](ComparisonCategoryInfo *Info) { 11279 auto *NNS = 11280 NestedNameSpecifier::Create(Context, nullptr, getStdNamespace()); 11281 return Context.getElaboratedType(ETK_None, NNS, Info->getType()); 11282 }; 11283 11284 // Check if we've already successfully checked the comparison category type 11285 // before. If so, skip checking it again. 11286 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind); 11287 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) { 11288 // The only thing we need to check is that the type has a reachable 11289 // definition in the current context. 11290 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type)) 11291 return QualType(); 11292 11293 return Info->getType(); 11294 } 11295 11296 // If lookup failed 11297 if (!Info) { 11298 std::string NameForDiags = "std::"; 11299 NameForDiags += ComparisonCategories::getCategoryString(Kind); 11300 Diag(Loc, diag::err_implied_comparison_category_type_not_found) 11301 << NameForDiags << (int)Usage; 11302 return QualType(); 11303 } 11304 11305 assert(Info->Kind == Kind); 11306 assert(Info->Record); 11307 11308 // Update the Record decl in case we encountered a forward declaration on our 11309 // first pass. FIXME: This is a bit of a hack. 11310 if (Info->Record->hasDefinition()) 11311 Info->Record = Info->Record->getDefinition(); 11312 11313 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type)) 11314 return QualType(); 11315 11316 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)}; 11317 11318 if (!Info->Record->isTriviallyCopyable()) 11319 return UnsupportedSTLError(USS_NonTrivial); 11320 11321 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) { 11322 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl(); 11323 // Tolerate empty base classes. 11324 if (Base->isEmpty()) 11325 continue; 11326 // Reject STL implementations which have at least one non-empty base. 11327 return UnsupportedSTLError(); 11328 } 11329 11330 // Check that the STL has implemented the types using a single integer field. 11331 // This expectation allows better codegen for builtin operators. We require: 11332 // (1) The class has exactly one field. 11333 // (2) The field is an integral or enumeration type. 11334 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end(); 11335 if (std::distance(FIt, FEnd) != 1 || 11336 !FIt->getType()->isIntegralOrEnumerationType()) { 11337 return UnsupportedSTLError(); 11338 } 11339 11340 // Build each of the require values and store them in Info. 11341 for (ComparisonCategoryResult CCR : 11342 ComparisonCategories::getPossibleResultsForType(Kind)) { 11343 StringRef MemName = ComparisonCategories::getResultString(CCR); 11344 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR); 11345 11346 if (!ValInfo) 11347 return UnsupportedSTLError(USS_MissingMember, MemName); 11348 11349 VarDecl *VD = ValInfo->VD; 11350 assert(VD && "should not be null!"); 11351 11352 // Attempt to diagnose reasons why the STL definition of this type 11353 // might be foobar, including it failing to be a constant expression. 11354 // TODO Handle more ways the lookup or result can be invalid. 11355 if (!VD->isStaticDataMember() || 11356 !VD->isUsableInConstantExpressions(Context)) 11357 return UnsupportedSTLError(USS_InvalidMember, MemName, VD); 11358 11359 // Attempt to evaluate the var decl as a constant expression and extract 11360 // the value of its first field as a ICE. If this fails, the STL 11361 // implementation is not supported. 11362 if (!ValInfo->hasValidIntValue()) 11363 return UnsupportedSTLError(); 11364 11365 MarkVariableReferenced(Loc, VD); 11366 } 11367 11368 // We've successfully built the required types and expressions. Update 11369 // the cache and return the newly cached value. 11370 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true; 11371 return Info->getType(); 11372 } 11373 11374 /// Retrieve the special "std" namespace, which may require us to 11375 /// implicitly define the namespace. 11376 NamespaceDecl *Sema::getOrCreateStdNamespace() { 11377 if (!StdNamespace) { 11378 // The "std" namespace has not yet been defined, so build one implicitly. 11379 StdNamespace = NamespaceDecl::Create(Context, 11380 Context.getTranslationUnitDecl(), 11381 /*Inline=*/false, 11382 SourceLocation(), SourceLocation(), 11383 &PP.getIdentifierTable().get("std"), 11384 /*PrevDecl=*/nullptr); 11385 getStdNamespace()->setImplicit(true); 11386 } 11387 11388 return getStdNamespace(); 11389 } 11390 11391 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 11392 assert(getLangOpts().CPlusPlus && 11393 "Looking for std::initializer_list outside of C++."); 11394 11395 // We're looking for implicit instantiations of 11396 // template <typename E> class std::initializer_list. 11397 11398 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 11399 return false; 11400 11401 ClassTemplateDecl *Template = nullptr; 11402 const TemplateArgument *Arguments = nullptr; 11403 11404 if (const RecordType *RT = Ty->getAs<RecordType>()) { 11405 11406 ClassTemplateSpecializationDecl *Specialization = 11407 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 11408 if (!Specialization) 11409 return false; 11410 11411 Template = Specialization->getSpecializedTemplate(); 11412 Arguments = Specialization->getTemplateArgs().data(); 11413 } else if (const TemplateSpecializationType *TST = 11414 Ty->getAs<TemplateSpecializationType>()) { 11415 Template = dyn_cast_or_null<ClassTemplateDecl>( 11416 TST->getTemplateName().getAsTemplateDecl()); 11417 Arguments = TST->getArgs(); 11418 } 11419 if (!Template) 11420 return false; 11421 11422 if (!StdInitializerList) { 11423 // Haven't recognized std::initializer_list yet, maybe this is it. 11424 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 11425 if (TemplateClass->getIdentifier() != 11426 &PP.getIdentifierTable().get("initializer_list") || 11427 !getStdNamespace()->InEnclosingNamespaceSetOf( 11428 TemplateClass->getDeclContext())) 11429 return false; 11430 // This is a template called std::initializer_list, but is it the right 11431 // template? 11432 TemplateParameterList *Params = Template->getTemplateParameters(); 11433 if (Params->getMinRequiredArguments() != 1) 11434 return false; 11435 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 11436 return false; 11437 11438 // It's the right template. 11439 StdInitializerList = Template; 11440 } 11441 11442 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) 11443 return false; 11444 11445 // This is an instance of std::initializer_list. Find the argument type. 11446 if (Element) 11447 *Element = Arguments[0].getAsType(); 11448 return true; 11449 } 11450 11451 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 11452 NamespaceDecl *Std = S.getStdNamespace(); 11453 if (!Std) { 11454 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 11455 return nullptr; 11456 } 11457 11458 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 11459 Loc, Sema::LookupOrdinaryName); 11460 if (!S.LookupQualifiedName(Result, Std)) { 11461 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 11462 return nullptr; 11463 } 11464 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 11465 if (!Template) { 11466 Result.suppressDiagnostics(); 11467 // We found something weird. Complain about the first thing we found. 11468 NamedDecl *Found = *Result.begin(); 11469 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 11470 return nullptr; 11471 } 11472 11473 // We found some template called std::initializer_list. Now verify that it's 11474 // correct. 11475 TemplateParameterList *Params = Template->getTemplateParameters(); 11476 if (Params->getMinRequiredArguments() != 1 || 11477 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 11478 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 11479 return nullptr; 11480 } 11481 11482 return Template; 11483 } 11484 11485 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 11486 if (!StdInitializerList) { 11487 StdInitializerList = LookupStdInitializerList(*this, Loc); 11488 if (!StdInitializerList) 11489 return QualType(); 11490 } 11491 11492 TemplateArgumentListInfo Args(Loc, Loc); 11493 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 11494 Context.getTrivialTypeSourceInfo(Element, 11495 Loc))); 11496 return Context.getCanonicalType( 11497 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 11498 } 11499 11500 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) { 11501 // C++ [dcl.init.list]p2: 11502 // A constructor is an initializer-list constructor if its first parameter 11503 // is of type std::initializer_list<E> or reference to possibly cv-qualified 11504 // std::initializer_list<E> for some type E, and either there are no other 11505 // parameters or else all other parameters have default arguments. 11506 if (!Ctor->hasOneParamOrDefaultArgs()) 11507 return false; 11508 11509 QualType ArgType = Ctor->getParamDecl(0)->getType(); 11510 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 11511 ArgType = RT->getPointeeType().getUnqualifiedType(); 11512 11513 return isStdInitializerList(ArgType, nullptr); 11514 } 11515 11516 /// Determine whether a using statement is in a context where it will be 11517 /// apply in all contexts. 11518 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 11519 switch (CurContext->getDeclKind()) { 11520 case Decl::TranslationUnit: 11521 return true; 11522 case Decl::LinkageSpec: 11523 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 11524 default: 11525 return false; 11526 } 11527 } 11528 11529 namespace { 11530 11531 // Callback to only accept typo corrections that are namespaces. 11532 class NamespaceValidatorCCC final : public CorrectionCandidateCallback { 11533 public: 11534 bool ValidateCandidate(const TypoCorrection &candidate) override { 11535 if (NamedDecl *ND = candidate.getCorrectionDecl()) 11536 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 11537 return false; 11538 } 11539 11540 std::unique_ptr<CorrectionCandidateCallback> clone() override { 11541 return std::make_unique<NamespaceValidatorCCC>(*this); 11542 } 11543 }; 11544 11545 } 11546 11547 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 11548 CXXScopeSpec &SS, 11549 SourceLocation IdentLoc, 11550 IdentifierInfo *Ident) { 11551 R.clear(); 11552 NamespaceValidatorCCC CCC{}; 11553 if (TypoCorrection Corrected = 11554 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC, 11555 Sema::CTK_ErrorRecovery)) { 11556 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 11557 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 11558 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 11559 Ident->getName().equals(CorrectedStr); 11560 S.diagnoseTypo(Corrected, 11561 S.PDiag(diag::err_using_directive_member_suggest) 11562 << Ident << DC << DroppedSpecifier << SS.getRange(), 11563 S.PDiag(diag::note_namespace_defined_here)); 11564 } else { 11565 S.diagnoseTypo(Corrected, 11566 S.PDiag(diag::err_using_directive_suggest) << Ident, 11567 S.PDiag(diag::note_namespace_defined_here)); 11568 } 11569 R.addDecl(Corrected.getFoundDecl()); 11570 return true; 11571 } 11572 return false; 11573 } 11574 11575 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc, 11576 SourceLocation NamespcLoc, CXXScopeSpec &SS, 11577 SourceLocation IdentLoc, 11578 IdentifierInfo *NamespcName, 11579 const ParsedAttributesView &AttrList) { 11580 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 11581 assert(NamespcName && "Invalid NamespcName."); 11582 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 11583 11584 // This can only happen along a recovery path. 11585 while (S->isTemplateParamScope()) 11586 S = S->getParent(); 11587 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 11588 11589 UsingDirectiveDecl *UDir = nullptr; 11590 NestedNameSpecifier *Qualifier = nullptr; 11591 if (SS.isSet()) 11592 Qualifier = SS.getScopeRep(); 11593 11594 // Lookup namespace name. 11595 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 11596 LookupParsedName(R, S, &SS); 11597 if (R.isAmbiguous()) 11598 return nullptr; 11599 11600 if (R.empty()) { 11601 R.clear(); 11602 // Allow "using namespace std;" or "using namespace ::std;" even if 11603 // "std" hasn't been defined yet, for GCC compatibility. 11604 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 11605 NamespcName->isStr("std")) { 11606 Diag(IdentLoc, diag::ext_using_undefined_std); 11607 R.addDecl(getOrCreateStdNamespace()); 11608 R.resolveKind(); 11609 } 11610 // Otherwise, attempt typo correction. 11611 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 11612 } 11613 11614 if (!R.empty()) { 11615 NamedDecl *Named = R.getRepresentativeDecl(); 11616 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>(); 11617 assert(NS && "expected namespace decl"); 11618 11619 // The use of a nested name specifier may trigger deprecation warnings. 11620 DiagnoseUseOfDecl(Named, IdentLoc); 11621 11622 // C++ [namespace.udir]p1: 11623 // A using-directive specifies that the names in the nominated 11624 // namespace can be used in the scope in which the 11625 // using-directive appears after the using-directive. During 11626 // unqualified name lookup (3.4.1), the names appear as if they 11627 // were declared in the nearest enclosing namespace which 11628 // contains both the using-directive and the nominated 11629 // namespace. [Note: in this context, "contains" means "contains 11630 // directly or indirectly". ] 11631 11632 // Find enclosing context containing both using-directive and 11633 // nominated namespace. 11634 DeclContext *CommonAncestor = NS; 11635 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 11636 CommonAncestor = CommonAncestor->getParent(); 11637 11638 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 11639 SS.getWithLocInContext(Context), 11640 IdentLoc, Named, CommonAncestor); 11641 11642 if (IsUsingDirectiveInToplevelContext(CurContext) && 11643 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 11644 Diag(IdentLoc, diag::warn_using_directive_in_header); 11645 } 11646 11647 PushUsingDirective(S, UDir); 11648 } else { 11649 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 11650 } 11651 11652 if (UDir) 11653 ProcessDeclAttributeList(S, UDir, AttrList); 11654 11655 return UDir; 11656 } 11657 11658 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 11659 // If the scope has an associated entity and the using directive is at 11660 // namespace or translation unit scope, add the UsingDirectiveDecl into 11661 // its lookup structure so qualified name lookup can find it. 11662 DeclContext *Ctx = S->getEntity(); 11663 if (Ctx && !Ctx->isFunctionOrMethod()) 11664 Ctx->addDecl(UDir); 11665 else 11666 // Otherwise, it is at block scope. The using-directives will affect lookup 11667 // only to the end of the scope. 11668 S->PushUsingDirective(UDir); 11669 } 11670 11671 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS, 11672 SourceLocation UsingLoc, 11673 SourceLocation TypenameLoc, CXXScopeSpec &SS, 11674 UnqualifiedId &Name, 11675 SourceLocation EllipsisLoc, 11676 const ParsedAttributesView &AttrList) { 11677 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 11678 11679 if (SS.isEmpty()) { 11680 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname); 11681 return nullptr; 11682 } 11683 11684 switch (Name.getKind()) { 11685 case UnqualifiedIdKind::IK_ImplicitSelfParam: 11686 case UnqualifiedIdKind::IK_Identifier: 11687 case UnqualifiedIdKind::IK_OperatorFunctionId: 11688 case UnqualifiedIdKind::IK_LiteralOperatorId: 11689 case UnqualifiedIdKind::IK_ConversionFunctionId: 11690 break; 11691 11692 case UnqualifiedIdKind::IK_ConstructorName: 11693 case UnqualifiedIdKind::IK_ConstructorTemplateId: 11694 // C++11 inheriting constructors. 11695 Diag(Name.getBeginLoc(), 11696 getLangOpts().CPlusPlus11 11697 ? diag::warn_cxx98_compat_using_decl_constructor 11698 : diag::err_using_decl_constructor) 11699 << SS.getRange(); 11700 11701 if (getLangOpts().CPlusPlus11) break; 11702 11703 return nullptr; 11704 11705 case UnqualifiedIdKind::IK_DestructorName: 11706 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange(); 11707 return nullptr; 11708 11709 case UnqualifiedIdKind::IK_TemplateId: 11710 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id) 11711 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 11712 return nullptr; 11713 11714 case UnqualifiedIdKind::IK_DeductionGuideName: 11715 llvm_unreachable("cannot parse qualified deduction guide name"); 11716 } 11717 11718 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 11719 DeclarationName TargetName = TargetNameInfo.getName(); 11720 if (!TargetName) 11721 return nullptr; 11722 11723 // Warn about access declarations. 11724 if (UsingLoc.isInvalid()) { 11725 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11 11726 ? diag::err_access_decl 11727 : diag::warn_access_decl_deprecated) 11728 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 11729 } 11730 11731 if (EllipsisLoc.isInvalid()) { 11732 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 11733 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 11734 return nullptr; 11735 } else { 11736 if (!SS.getScopeRep()->containsUnexpandedParameterPack() && 11737 !TargetNameInfo.containsUnexpandedParameterPack()) { 11738 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 11739 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc()); 11740 EllipsisLoc = SourceLocation(); 11741 } 11742 } 11743 11744 NamedDecl *UD = 11745 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc, 11746 SS, TargetNameInfo, EllipsisLoc, AttrList, 11747 /*IsInstantiation*/ false, 11748 AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists)); 11749 if (UD) 11750 PushOnScopeChains(UD, S, /*AddToContext*/ false); 11751 11752 return UD; 11753 } 11754 11755 Decl *Sema::ActOnUsingEnumDeclaration(Scope *S, AccessSpecifier AS, 11756 SourceLocation UsingLoc, 11757 SourceLocation EnumLoc, 11758 const DeclSpec &DS) { 11759 switch (DS.getTypeSpecType()) { 11760 case DeclSpec::TST_error: 11761 // This will already have been diagnosed 11762 return nullptr; 11763 11764 case DeclSpec::TST_enum: 11765 break; 11766 11767 case DeclSpec::TST_typename: 11768 Diag(DS.getTypeSpecTypeLoc(), diag::err_using_enum_is_dependent); 11769 return nullptr; 11770 11771 default: 11772 llvm_unreachable("unexpected DeclSpec type"); 11773 } 11774 11775 // As with enum-decls, we ignore attributes for now. 11776 auto *Enum = cast<EnumDecl>(DS.getRepAsDecl()); 11777 if (auto *Def = Enum->getDefinition()) 11778 Enum = Def; 11779 11780 auto *UD = BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc, 11781 DS.getTypeSpecTypeNameLoc(), Enum); 11782 if (UD) 11783 PushOnScopeChains(UD, S, /*AddToContext*/ false); 11784 11785 return UD; 11786 } 11787 11788 /// Determine whether a using declaration considers the given 11789 /// declarations as "equivalent", e.g., if they are redeclarations of 11790 /// the same entity or are both typedefs of the same type. 11791 static bool 11792 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 11793 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 11794 return true; 11795 11796 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 11797 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 11798 return Context.hasSameType(TD1->getUnderlyingType(), 11799 TD2->getUnderlyingType()); 11800 11801 // Two using_if_exists using-declarations are equivalent if both are 11802 // unresolved. 11803 if (isa<UnresolvedUsingIfExistsDecl>(D1) && 11804 isa<UnresolvedUsingIfExistsDecl>(D2)) 11805 return true; 11806 11807 return false; 11808 } 11809 11810 11811 /// Determines whether to create a using shadow decl for a particular 11812 /// decl, given the set of decls existing prior to this using lookup. 11813 bool Sema::CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Orig, 11814 const LookupResult &Previous, 11815 UsingShadowDecl *&PrevShadow) { 11816 // Diagnose finding a decl which is not from a base class of the 11817 // current class. We do this now because there are cases where this 11818 // function will silently decide not to build a shadow decl, which 11819 // will pre-empt further diagnostics. 11820 // 11821 // We don't need to do this in C++11 because we do the check once on 11822 // the qualifier. 11823 // 11824 // FIXME: diagnose the following if we care enough: 11825 // struct A { int foo; }; 11826 // struct B : A { using A::foo; }; 11827 // template <class T> struct C : A {}; 11828 // template <class T> struct D : C<T> { using B::foo; } // <--- 11829 // This is invalid (during instantiation) in C++03 because B::foo 11830 // resolves to the using decl in B, which is not a base class of D<T>. 11831 // We can't diagnose it immediately because C<T> is an unknown 11832 // specialization. The UsingShadowDecl in D<T> then points directly 11833 // to A::foo, which will look well-formed when we instantiate. 11834 // The right solution is to not collapse the shadow-decl chain. 11835 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) 11836 if (auto *Using = dyn_cast<UsingDecl>(BUD)) { 11837 DeclContext *OrigDC = Orig->getDeclContext(); 11838 11839 // Handle enums and anonymous structs. 11840 if (isa<EnumDecl>(OrigDC)) 11841 OrigDC = OrigDC->getParent(); 11842 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 11843 while (OrigRec->isAnonymousStructOrUnion()) 11844 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 11845 11846 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 11847 if (OrigDC == CurContext) { 11848 Diag(Using->getLocation(), 11849 diag::err_using_decl_nested_name_specifier_is_current_class) 11850 << Using->getQualifierLoc().getSourceRange(); 11851 Diag(Orig->getLocation(), diag::note_using_decl_target); 11852 Using->setInvalidDecl(); 11853 return true; 11854 } 11855 11856 Diag(Using->getQualifierLoc().getBeginLoc(), 11857 diag::err_using_decl_nested_name_specifier_is_not_base_class) 11858 << Using->getQualifier() << cast<CXXRecordDecl>(CurContext) 11859 << Using->getQualifierLoc().getSourceRange(); 11860 Diag(Orig->getLocation(), diag::note_using_decl_target); 11861 Using->setInvalidDecl(); 11862 return true; 11863 } 11864 } 11865 11866 if (Previous.empty()) return false; 11867 11868 NamedDecl *Target = Orig; 11869 if (isa<UsingShadowDecl>(Target)) 11870 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 11871 11872 // If the target happens to be one of the previous declarations, we 11873 // don't have a conflict. 11874 // 11875 // FIXME: but we might be increasing its access, in which case we 11876 // should redeclare it. 11877 NamedDecl *NonTag = nullptr, *Tag = nullptr; 11878 bool FoundEquivalentDecl = false; 11879 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 11880 I != E; ++I) { 11881 NamedDecl *D = (*I)->getUnderlyingDecl(); 11882 // We can have UsingDecls in our Previous results because we use the same 11883 // LookupResult for checking whether the UsingDecl itself is a valid 11884 // redeclaration. 11885 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D) || isa<UsingEnumDecl>(D)) 11886 continue; 11887 11888 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 11889 // C++ [class.mem]p19: 11890 // If T is the name of a class, then [every named member other than 11891 // a non-static data member] shall have a name different from T 11892 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) && 11893 !isa<IndirectFieldDecl>(Target) && 11894 !isa<UnresolvedUsingValueDecl>(Target) && 11895 DiagnoseClassNameShadow( 11896 CurContext, 11897 DeclarationNameInfo(BUD->getDeclName(), BUD->getLocation()))) 11898 return true; 11899 } 11900 11901 if (IsEquivalentForUsingDecl(Context, D, Target)) { 11902 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 11903 PrevShadow = Shadow; 11904 FoundEquivalentDecl = true; 11905 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) { 11906 // We don't conflict with an existing using shadow decl of an equivalent 11907 // declaration, but we're not a redeclaration of it. 11908 FoundEquivalentDecl = true; 11909 } 11910 11911 if (isVisible(D)) 11912 (isa<TagDecl>(D) ? Tag : NonTag) = D; 11913 } 11914 11915 if (FoundEquivalentDecl) 11916 return false; 11917 11918 // Always emit a diagnostic for a mismatch between an unresolved 11919 // using_if_exists and a resolved using declaration in either direction. 11920 if (isa<UnresolvedUsingIfExistsDecl>(Target) != 11921 (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) { 11922 if (!NonTag && !Tag) 11923 return false; 11924 Diag(BUD->getLocation(), diag::err_using_decl_conflict); 11925 Diag(Target->getLocation(), diag::note_using_decl_target); 11926 Diag((NonTag ? NonTag : Tag)->getLocation(), 11927 diag::note_using_decl_conflict); 11928 BUD->setInvalidDecl(); 11929 return true; 11930 } 11931 11932 if (FunctionDecl *FD = Target->getAsFunction()) { 11933 NamedDecl *OldDecl = nullptr; 11934 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 11935 /*IsForUsingDecl*/ true)) { 11936 case Ovl_Overload: 11937 return false; 11938 11939 case Ovl_NonFunction: 11940 Diag(BUD->getLocation(), diag::err_using_decl_conflict); 11941 break; 11942 11943 // We found a decl with the exact signature. 11944 case Ovl_Match: 11945 // If we're in a record, we want to hide the target, so we 11946 // return true (without a diagnostic) to tell the caller not to 11947 // build a shadow decl. 11948 if (CurContext->isRecord()) 11949 return true; 11950 11951 // If we're not in a record, this is an error. 11952 Diag(BUD->getLocation(), diag::err_using_decl_conflict); 11953 break; 11954 } 11955 11956 Diag(Target->getLocation(), diag::note_using_decl_target); 11957 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 11958 BUD->setInvalidDecl(); 11959 return true; 11960 } 11961 11962 // Target is not a function. 11963 11964 if (isa<TagDecl>(Target)) { 11965 // No conflict between a tag and a non-tag. 11966 if (!Tag) return false; 11967 11968 Diag(BUD->getLocation(), diag::err_using_decl_conflict); 11969 Diag(Target->getLocation(), diag::note_using_decl_target); 11970 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 11971 BUD->setInvalidDecl(); 11972 return true; 11973 } 11974 11975 // No conflict between a tag and a non-tag. 11976 if (!NonTag) return false; 11977 11978 Diag(BUD->getLocation(), diag::err_using_decl_conflict); 11979 Diag(Target->getLocation(), diag::note_using_decl_target); 11980 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 11981 BUD->setInvalidDecl(); 11982 return true; 11983 } 11984 11985 /// Determine whether a direct base class is a virtual base class. 11986 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) { 11987 if (!Derived->getNumVBases()) 11988 return false; 11989 for (auto &B : Derived->bases()) 11990 if (B.getType()->getAsCXXRecordDecl() == Base) 11991 return B.isVirtual(); 11992 llvm_unreachable("not a direct base class"); 11993 } 11994 11995 /// Builds a shadow declaration corresponding to a 'using' declaration. 11996 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD, 11997 NamedDecl *Orig, 11998 UsingShadowDecl *PrevDecl) { 11999 // If we resolved to another shadow declaration, just coalesce them. 12000 NamedDecl *Target = Orig; 12001 if (isa<UsingShadowDecl>(Target)) { 12002 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 12003 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 12004 } 12005 12006 NamedDecl *NonTemplateTarget = Target; 12007 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target)) 12008 NonTemplateTarget = TargetTD->getTemplatedDecl(); 12009 12010 UsingShadowDecl *Shadow; 12011 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) { 12012 UsingDecl *Using = cast<UsingDecl>(BUD); 12013 bool IsVirtualBase = 12014 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext), 12015 Using->getQualifier()->getAsRecordDecl()); 12016 Shadow = ConstructorUsingShadowDecl::Create( 12017 Context, CurContext, Using->getLocation(), Using, Orig, IsVirtualBase); 12018 } else { 12019 Shadow = UsingShadowDecl::Create(Context, CurContext, BUD->getLocation(), 12020 Target->getDeclName(), BUD, Target); 12021 } 12022 BUD->addShadowDecl(Shadow); 12023 12024 Shadow->setAccess(BUD->getAccess()); 12025 if (Orig->isInvalidDecl() || BUD->isInvalidDecl()) 12026 Shadow->setInvalidDecl(); 12027 12028 Shadow->setPreviousDecl(PrevDecl); 12029 12030 if (S) 12031 PushOnScopeChains(Shadow, S); 12032 else 12033 CurContext->addDecl(Shadow); 12034 12035 12036 return Shadow; 12037 } 12038 12039 /// Hides a using shadow declaration. This is required by the current 12040 /// using-decl implementation when a resolvable using declaration in a 12041 /// class is followed by a declaration which would hide or override 12042 /// one or more of the using decl's targets; for example: 12043 /// 12044 /// struct Base { void foo(int); }; 12045 /// struct Derived : Base { 12046 /// using Base::foo; 12047 /// void foo(int); 12048 /// }; 12049 /// 12050 /// The governing language is C++03 [namespace.udecl]p12: 12051 /// 12052 /// When a using-declaration brings names from a base class into a 12053 /// derived class scope, member functions in the derived class 12054 /// override and/or hide member functions with the same name and 12055 /// parameter types in a base class (rather than conflicting). 12056 /// 12057 /// There are two ways to implement this: 12058 /// (1) optimistically create shadow decls when they're not hidden 12059 /// by existing declarations, or 12060 /// (2) don't create any shadow decls (or at least don't make them 12061 /// visible) until we've fully parsed/instantiated the class. 12062 /// The problem with (1) is that we might have to retroactively remove 12063 /// a shadow decl, which requires several O(n) operations because the 12064 /// decl structures are (very reasonably) not designed for removal. 12065 /// (2) avoids this but is very fiddly and phase-dependent. 12066 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 12067 if (Shadow->getDeclName().getNameKind() == 12068 DeclarationName::CXXConversionFunctionName) 12069 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 12070 12071 // Remove it from the DeclContext... 12072 Shadow->getDeclContext()->removeDecl(Shadow); 12073 12074 // ...and the scope, if applicable... 12075 if (S) { 12076 S->RemoveDecl(Shadow); 12077 IdResolver.RemoveDecl(Shadow); 12078 } 12079 12080 // ...and the using decl. 12081 Shadow->getIntroducer()->removeShadowDecl(Shadow); 12082 12083 // TODO: complain somehow if Shadow was used. It shouldn't 12084 // be possible for this to happen, because...? 12085 } 12086 12087 /// Find the base specifier for a base class with the given type. 12088 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 12089 QualType DesiredBase, 12090 bool &AnyDependentBases) { 12091 // Check whether the named type is a direct base class. 12092 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified() 12093 .getUnqualifiedType(); 12094 for (auto &Base : Derived->bases()) { 12095 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 12096 if (CanonicalDesiredBase == BaseType) 12097 return &Base; 12098 if (BaseType->isDependentType()) 12099 AnyDependentBases = true; 12100 } 12101 return nullptr; 12102 } 12103 12104 namespace { 12105 class UsingValidatorCCC final : public CorrectionCandidateCallback { 12106 public: 12107 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 12108 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 12109 : HasTypenameKeyword(HasTypenameKeyword), 12110 IsInstantiation(IsInstantiation), OldNNS(NNS), 12111 RequireMemberOf(RequireMemberOf) {} 12112 12113 bool ValidateCandidate(const TypoCorrection &Candidate) override { 12114 NamedDecl *ND = Candidate.getCorrectionDecl(); 12115 12116 // Keywords are not valid here. 12117 if (!ND || isa<NamespaceDecl>(ND)) 12118 return false; 12119 12120 // Completely unqualified names are invalid for a 'using' declaration. 12121 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 12122 return false; 12123 12124 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would 12125 // reject. 12126 12127 if (RequireMemberOf) { 12128 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 12129 if (FoundRecord && FoundRecord->isInjectedClassName()) { 12130 // No-one ever wants a using-declaration to name an injected-class-name 12131 // of a base class, unless they're declaring an inheriting constructor. 12132 ASTContext &Ctx = ND->getASTContext(); 12133 if (!Ctx.getLangOpts().CPlusPlus11) 12134 return false; 12135 QualType FoundType = Ctx.getRecordType(FoundRecord); 12136 12137 // Check that the injected-class-name is named as a member of its own 12138 // type; we don't want to suggest 'using Derived::Base;', since that 12139 // means something else. 12140 NestedNameSpecifier *Specifier = 12141 Candidate.WillReplaceSpecifier() 12142 ? Candidate.getCorrectionSpecifier() 12143 : OldNNS; 12144 if (!Specifier->getAsType() || 12145 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 12146 return false; 12147 12148 // Check that this inheriting constructor declaration actually names a 12149 // direct base class of the current class. 12150 bool AnyDependentBases = false; 12151 if (!findDirectBaseWithType(RequireMemberOf, 12152 Ctx.getRecordType(FoundRecord), 12153 AnyDependentBases) && 12154 !AnyDependentBases) 12155 return false; 12156 } else { 12157 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 12158 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 12159 return false; 12160 12161 // FIXME: Check that the base class member is accessible? 12162 } 12163 } else { 12164 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 12165 if (FoundRecord && FoundRecord->isInjectedClassName()) 12166 return false; 12167 } 12168 12169 if (isa<TypeDecl>(ND)) 12170 return HasTypenameKeyword || !IsInstantiation; 12171 12172 return !HasTypenameKeyword; 12173 } 12174 12175 std::unique_ptr<CorrectionCandidateCallback> clone() override { 12176 return std::make_unique<UsingValidatorCCC>(*this); 12177 } 12178 12179 private: 12180 bool HasTypenameKeyword; 12181 bool IsInstantiation; 12182 NestedNameSpecifier *OldNNS; 12183 CXXRecordDecl *RequireMemberOf; 12184 }; 12185 } // end anonymous namespace 12186 12187 /// Remove decls we can't actually see from a lookup being used to declare 12188 /// shadow using decls. 12189 /// 12190 /// \param S - The scope of the potential shadow decl 12191 /// \param Previous - The lookup of a potential shadow decl's name. 12192 void Sema::FilterUsingLookup(Scope *S, LookupResult &Previous) { 12193 // It is really dumb that we have to do this. 12194 LookupResult::Filter F = Previous.makeFilter(); 12195 while (F.hasNext()) { 12196 NamedDecl *D = F.next(); 12197 if (!isDeclInScope(D, CurContext, S)) 12198 F.erase(); 12199 // If we found a local extern declaration that's not ordinarily visible, 12200 // and this declaration is being added to a non-block scope, ignore it. 12201 // We're only checking for scope conflicts here, not also for violations 12202 // of the linkage rules. 12203 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 12204 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 12205 F.erase(); 12206 } 12207 F.done(); 12208 } 12209 12210 /// Builds a using declaration. 12211 /// 12212 /// \param IsInstantiation - Whether this call arises from an 12213 /// instantiation of an unresolved using declaration. We treat 12214 /// the lookup differently for these declarations. 12215 NamedDecl *Sema::BuildUsingDeclaration( 12216 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, 12217 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, 12218 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, 12219 const ParsedAttributesView &AttrList, bool IsInstantiation, 12220 bool IsUsingIfExists) { 12221 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 12222 SourceLocation IdentLoc = NameInfo.getLoc(); 12223 assert(IdentLoc.isValid() && "Invalid TargetName location."); 12224 12225 // FIXME: We ignore attributes for now. 12226 12227 // For an inheriting constructor declaration, the name of the using 12228 // declaration is the name of a constructor in this class, not in the 12229 // base class. 12230 DeclarationNameInfo UsingName = NameInfo; 12231 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName) 12232 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext)) 12233 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 12234 Context.getCanonicalType(Context.getRecordType(RD)))); 12235 12236 // Do the redeclaration lookup in the current scope. 12237 LookupResult Previous(*this, UsingName, LookupUsingDeclName, 12238 ForVisibleRedeclaration); 12239 Previous.setHideTags(false); 12240 if (S) { 12241 LookupName(Previous, S); 12242 12243 FilterUsingLookup(S, Previous); 12244 } else { 12245 assert(IsInstantiation && "no scope in non-instantiation"); 12246 if (CurContext->isRecord()) 12247 LookupQualifiedName(Previous, CurContext); 12248 else { 12249 // No redeclaration check is needed here; in non-member contexts we 12250 // diagnosed all possible conflicts with other using-declarations when 12251 // building the template: 12252 // 12253 // For a dependent non-type using declaration, the only valid case is 12254 // if we instantiate to a single enumerator. We check for conflicts 12255 // between shadow declarations we introduce, and we check in the template 12256 // definition for conflicts between a non-type using declaration and any 12257 // other declaration, which together covers all cases. 12258 // 12259 // A dependent typename using declaration will never successfully 12260 // instantiate, since it will always name a class member, so we reject 12261 // that in the template definition. 12262 } 12263 } 12264 12265 // Check for invalid redeclarations. 12266 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 12267 SS, IdentLoc, Previous)) 12268 return nullptr; 12269 12270 // 'using_if_exists' doesn't make sense on an inherited constructor. 12271 if (IsUsingIfExists && UsingName.getName().getNameKind() == 12272 DeclarationName::CXXConstructorName) { 12273 Diag(UsingLoc, diag::err_using_if_exists_on_ctor); 12274 return nullptr; 12275 } 12276 12277 DeclContext *LookupContext = computeDeclContext(SS); 12278 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 12279 if (!LookupContext || EllipsisLoc.isValid()) { 12280 NamedDecl *D; 12281 // Dependent scope, or an unexpanded pack 12282 if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, 12283 SS, NameInfo, IdentLoc)) 12284 return nullptr; 12285 12286 if (HasTypenameKeyword) { 12287 // FIXME: not all declaration name kinds are legal here 12288 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 12289 UsingLoc, TypenameLoc, 12290 QualifierLoc, 12291 IdentLoc, NameInfo.getName(), 12292 EllipsisLoc); 12293 } else { 12294 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 12295 QualifierLoc, NameInfo, EllipsisLoc); 12296 } 12297 D->setAccess(AS); 12298 CurContext->addDecl(D); 12299 ProcessDeclAttributeList(S, D, AttrList); 12300 return D; 12301 } 12302 12303 auto Build = [&](bool Invalid) { 12304 UsingDecl *UD = 12305 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 12306 UsingName, HasTypenameKeyword); 12307 UD->setAccess(AS); 12308 CurContext->addDecl(UD); 12309 ProcessDeclAttributeList(S, UD, AttrList); 12310 UD->setInvalidDecl(Invalid); 12311 return UD; 12312 }; 12313 auto BuildInvalid = [&]{ return Build(true); }; 12314 auto BuildValid = [&]{ return Build(false); }; 12315 12316 if (RequireCompleteDeclContext(SS, LookupContext)) 12317 return BuildInvalid(); 12318 12319 // Look up the target name. 12320 LookupResult R(*this, NameInfo, LookupOrdinaryName); 12321 12322 // Unlike most lookups, we don't always want to hide tag 12323 // declarations: tag names are visible through the using declaration 12324 // even if hidden by ordinary names, *except* in a dependent context 12325 // where they may be used by two-phase lookup. 12326 if (!IsInstantiation) 12327 R.setHideTags(false); 12328 12329 // For the purposes of this lookup, we have a base object type 12330 // equal to that of the current context. 12331 if (CurContext->isRecord()) { 12332 R.setBaseObjectType( 12333 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 12334 } 12335 12336 LookupQualifiedName(R, LookupContext); 12337 12338 // Validate the context, now we have a lookup 12339 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo, 12340 IdentLoc, &R)) 12341 return nullptr; 12342 12343 if (R.empty() && IsUsingIfExists) 12344 R.addDecl(UnresolvedUsingIfExistsDecl::Create(Context, CurContext, UsingLoc, 12345 UsingName.getName()), 12346 AS_public); 12347 12348 // Try to correct typos if possible. If constructor name lookup finds no 12349 // results, that means the named class has no explicit constructors, and we 12350 // suppressed declaring implicit ones (probably because it's dependent or 12351 // invalid). 12352 if (R.empty() && 12353 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { 12354 // HACK 2017-01-08: Work around an issue with libstdc++'s detection of 12355 // ::gets. Sometimes it believes that glibc provides a ::gets in cases where 12356 // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later. 12357 auto *II = NameInfo.getName().getAsIdentifierInfo(); 12358 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") && 12359 CurContext->isStdNamespace() && 12360 isa<TranslationUnitDecl>(LookupContext) && 12361 getSourceManager().isInSystemHeader(UsingLoc)) 12362 return nullptr; 12363 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 12364 dyn_cast<CXXRecordDecl>(CurContext)); 12365 if (TypoCorrection Corrected = 12366 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 12367 CTK_ErrorRecovery)) { 12368 // We reject candidates where DroppedSpecifier == true, hence the 12369 // literal '0' below. 12370 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 12371 << NameInfo.getName() << LookupContext << 0 12372 << SS.getRange()); 12373 12374 // If we picked a correction with no attached Decl we can't do anything 12375 // useful with it, bail out. 12376 NamedDecl *ND = Corrected.getCorrectionDecl(); 12377 if (!ND) 12378 return BuildInvalid(); 12379 12380 // If we corrected to an inheriting constructor, handle it as one. 12381 auto *RD = dyn_cast<CXXRecordDecl>(ND); 12382 if (RD && RD->isInjectedClassName()) { 12383 // The parent of the injected class name is the class itself. 12384 RD = cast<CXXRecordDecl>(RD->getParent()); 12385 12386 // Fix up the information we'll use to build the using declaration. 12387 if (Corrected.WillReplaceSpecifier()) { 12388 NestedNameSpecifierLocBuilder Builder; 12389 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 12390 QualifierLoc.getSourceRange()); 12391 QualifierLoc = Builder.getWithLocInContext(Context); 12392 } 12393 12394 // In this case, the name we introduce is the name of a derived class 12395 // constructor. 12396 auto *CurClass = cast<CXXRecordDecl>(CurContext); 12397 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 12398 Context.getCanonicalType(Context.getRecordType(CurClass)))); 12399 UsingName.setNamedTypeInfo(nullptr); 12400 for (auto *Ctor : LookupConstructors(RD)) 12401 R.addDecl(Ctor); 12402 R.resolveKind(); 12403 } else { 12404 // FIXME: Pick up all the declarations if we found an overloaded 12405 // function. 12406 UsingName.setName(ND->getDeclName()); 12407 R.addDecl(ND); 12408 } 12409 } else { 12410 Diag(IdentLoc, diag::err_no_member) 12411 << NameInfo.getName() << LookupContext << SS.getRange(); 12412 return BuildInvalid(); 12413 } 12414 } 12415 12416 if (R.isAmbiguous()) 12417 return BuildInvalid(); 12418 12419 if (HasTypenameKeyword) { 12420 // If we asked for a typename and got a non-type decl, error out. 12421 if (!R.getAsSingle<TypeDecl>() && 12422 !R.getAsSingle<UnresolvedUsingIfExistsDecl>()) { 12423 Diag(IdentLoc, diag::err_using_typename_non_type); 12424 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 12425 Diag((*I)->getUnderlyingDecl()->getLocation(), 12426 diag::note_using_decl_target); 12427 return BuildInvalid(); 12428 } 12429 } else { 12430 // If we asked for a non-typename and we got a type, error out, 12431 // but only if this is an instantiation of an unresolved using 12432 // decl. Otherwise just silently find the type name. 12433 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 12434 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 12435 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 12436 return BuildInvalid(); 12437 } 12438 } 12439 12440 // C++14 [namespace.udecl]p6: 12441 // A using-declaration shall not name a namespace. 12442 if (R.getAsSingle<NamespaceDecl>()) { 12443 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 12444 << SS.getRange(); 12445 return BuildInvalid(); 12446 } 12447 12448 UsingDecl *UD = BuildValid(); 12449 12450 // Some additional rules apply to inheriting constructors. 12451 if (UsingName.getName().getNameKind() == 12452 DeclarationName::CXXConstructorName) { 12453 // Suppress access diagnostics; the access check is instead performed at the 12454 // point of use for an inheriting constructor. 12455 R.suppressDiagnostics(); 12456 if (CheckInheritingConstructorUsingDecl(UD)) 12457 return UD; 12458 } 12459 12460 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 12461 UsingShadowDecl *PrevDecl = nullptr; 12462 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 12463 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 12464 } 12465 12466 return UD; 12467 } 12468 12469 NamedDecl *Sema::BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS, 12470 SourceLocation UsingLoc, 12471 SourceLocation EnumLoc, 12472 SourceLocation NameLoc, 12473 EnumDecl *ED) { 12474 bool Invalid = false; 12475 12476 if (CurContext->getRedeclContext()->isRecord()) { 12477 /// In class scope, check if this is a duplicate, for better a diagnostic. 12478 DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc); 12479 LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName, 12480 ForVisibleRedeclaration); 12481 12482 LookupName(Previous, S); 12483 12484 for (NamedDecl *D : Previous) 12485 if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D)) 12486 if (UED->getEnumDecl() == ED) { 12487 Diag(UsingLoc, diag::err_using_enum_decl_redeclaration) 12488 << SourceRange(EnumLoc, NameLoc); 12489 Diag(D->getLocation(), diag::note_using_enum_decl) << 1; 12490 Invalid = true; 12491 break; 12492 } 12493 } 12494 12495 if (RequireCompleteEnumDecl(ED, NameLoc)) 12496 Invalid = true; 12497 12498 UsingEnumDecl *UD = UsingEnumDecl::Create(Context, CurContext, UsingLoc, 12499 EnumLoc, NameLoc, ED); 12500 UD->setAccess(AS); 12501 CurContext->addDecl(UD); 12502 12503 if (Invalid) { 12504 UD->setInvalidDecl(); 12505 return UD; 12506 } 12507 12508 // Create the shadow decls for each enumerator 12509 for (EnumConstantDecl *EC : ED->enumerators()) { 12510 UsingShadowDecl *PrevDecl = nullptr; 12511 DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation()); 12512 LookupResult Previous(*this, DNI, LookupOrdinaryName, 12513 ForVisibleRedeclaration); 12514 LookupName(Previous, S); 12515 FilterUsingLookup(S, Previous); 12516 12517 if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl)) 12518 BuildUsingShadowDecl(S, UD, EC, PrevDecl); 12519 } 12520 12521 return UD; 12522 } 12523 12524 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom, 12525 ArrayRef<NamedDecl *> Expansions) { 12526 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || 12527 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || 12528 isa<UsingPackDecl>(InstantiatedFrom)); 12529 12530 auto *UPD = 12531 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions); 12532 UPD->setAccess(InstantiatedFrom->getAccess()); 12533 CurContext->addDecl(UPD); 12534 return UPD; 12535 } 12536 12537 /// Additional checks for a using declaration referring to a constructor name. 12538 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 12539 assert(!UD->hasTypename() && "expecting a constructor name"); 12540 12541 const Type *SourceType = UD->getQualifier()->getAsType(); 12542 assert(SourceType && 12543 "Using decl naming constructor doesn't have type in scope spec."); 12544 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 12545 12546 // Check whether the named type is a direct base class. 12547 bool AnyDependentBases = false; 12548 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 12549 AnyDependentBases); 12550 if (!Base && !AnyDependentBases) { 12551 Diag(UD->getUsingLoc(), 12552 diag::err_using_decl_constructor_not_in_direct_base) 12553 << UD->getNameInfo().getSourceRange() 12554 << QualType(SourceType, 0) << TargetClass; 12555 UD->setInvalidDecl(); 12556 return true; 12557 } 12558 12559 if (Base) 12560 Base->setInheritConstructors(); 12561 12562 return false; 12563 } 12564 12565 /// Checks that the given using declaration is not an invalid 12566 /// redeclaration. Note that this is checking only for the using decl 12567 /// itself, not for any ill-formedness among the UsingShadowDecls. 12568 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 12569 bool HasTypenameKeyword, 12570 const CXXScopeSpec &SS, 12571 SourceLocation NameLoc, 12572 const LookupResult &Prev) { 12573 NestedNameSpecifier *Qual = SS.getScopeRep(); 12574 12575 // C++03 [namespace.udecl]p8: 12576 // C++0x [namespace.udecl]p10: 12577 // A using-declaration is a declaration and can therefore be used 12578 // repeatedly where (and only where) multiple declarations are 12579 // allowed. 12580 // 12581 // That's in non-member contexts. 12582 if (!CurContext->getRedeclContext()->isRecord()) { 12583 // A dependent qualifier outside a class can only ever resolve to an 12584 // enumeration type. Therefore it conflicts with any other non-type 12585 // declaration in the same scope. 12586 // FIXME: How should we check for dependent type-type conflicts at block 12587 // scope? 12588 if (Qual->isDependent() && !HasTypenameKeyword) { 12589 for (auto *D : Prev) { 12590 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) { 12591 bool OldCouldBeEnumerator = 12592 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D); 12593 Diag(NameLoc, 12594 OldCouldBeEnumerator ? diag::err_redefinition 12595 : diag::err_redefinition_different_kind) 12596 << Prev.getLookupName(); 12597 Diag(D->getLocation(), diag::note_previous_definition); 12598 return true; 12599 } 12600 } 12601 } 12602 return false; 12603 } 12604 12605 const NestedNameSpecifier *CNNS = 12606 Context.getCanonicalNestedNameSpecifier(Qual); 12607 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 12608 NamedDecl *D = *I; 12609 12610 bool DTypename; 12611 NestedNameSpecifier *DQual; 12612 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 12613 DTypename = UD->hasTypename(); 12614 DQual = UD->getQualifier(); 12615 } else if (UnresolvedUsingValueDecl *UD 12616 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 12617 DTypename = false; 12618 DQual = UD->getQualifier(); 12619 } else if (UnresolvedUsingTypenameDecl *UD 12620 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 12621 DTypename = true; 12622 DQual = UD->getQualifier(); 12623 } else continue; 12624 12625 // using decls differ if one says 'typename' and the other doesn't. 12626 // FIXME: non-dependent using decls? 12627 if (HasTypenameKeyword != DTypename) continue; 12628 12629 // using decls differ if they name different scopes (but note that 12630 // template instantiation can cause this check to trigger when it 12631 // didn't before instantiation). 12632 if (CNNS != Context.getCanonicalNestedNameSpecifier(DQual)) 12633 continue; 12634 12635 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 12636 Diag(D->getLocation(), diag::note_using_decl) << 1; 12637 return true; 12638 } 12639 12640 return false; 12641 } 12642 12643 /// Checks that the given nested-name qualifier used in a using decl 12644 /// in the current context is appropriately related to the current 12645 /// scope. If an error is found, diagnoses it and returns true. 12646 /// R is nullptr, if the caller has not (yet) done a lookup, otherwise it's the 12647 /// result of that lookup. UD is likewise nullptr, except when we have an 12648 /// already-populated UsingDecl whose shadow decls contain the same information 12649 /// (i.e. we're instantiating a UsingDecl with non-dependent scope). 12650 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename, 12651 const CXXScopeSpec &SS, 12652 const DeclarationNameInfo &NameInfo, 12653 SourceLocation NameLoc, 12654 const LookupResult *R, const UsingDecl *UD) { 12655 DeclContext *NamedContext = computeDeclContext(SS); 12656 assert(bool(NamedContext) == (R || UD) && !(R && UD) && 12657 "resolvable context must have exactly one set of decls"); 12658 12659 // C++ 20 permits using an enumerator that does not have a class-hierarchy 12660 // relationship. 12661 bool Cxx20Enumerator = false; 12662 if (NamedContext) { 12663 EnumConstantDecl *EC = nullptr; 12664 if (R) 12665 EC = R->getAsSingle<EnumConstantDecl>(); 12666 else if (UD && UD->shadow_size() == 1) 12667 EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl()); 12668 if (EC) 12669 Cxx20Enumerator = getLangOpts().CPlusPlus20; 12670 12671 if (auto *ED = dyn_cast<EnumDecl>(NamedContext)) { 12672 // C++14 [namespace.udecl]p7: 12673 // A using-declaration shall not name a scoped enumerator. 12674 // C++20 p1099 permits enumerators. 12675 if (EC && R && ED->isScoped()) 12676 Diag(SS.getBeginLoc(), 12677 getLangOpts().CPlusPlus20 12678 ? diag::warn_cxx17_compat_using_decl_scoped_enumerator 12679 : diag::ext_using_decl_scoped_enumerator) 12680 << SS.getRange(); 12681 12682 // We want to consider the scope of the enumerator 12683 NamedContext = ED->getDeclContext(); 12684 } 12685 } 12686 12687 if (!CurContext->isRecord()) { 12688 // C++03 [namespace.udecl]p3: 12689 // C++0x [namespace.udecl]p8: 12690 // A using-declaration for a class member shall be a member-declaration. 12691 // C++20 [namespace.udecl]p7 12692 // ... other than an enumerator ... 12693 12694 // If we weren't able to compute a valid scope, it might validly be a 12695 // dependent class or enumeration scope. If we have a 'typename' keyword, 12696 // the scope must resolve to a class type. 12697 if (NamedContext ? !NamedContext->getRedeclContext()->isRecord() 12698 : !HasTypename) 12699 return false; // OK 12700 12701 Diag(NameLoc, 12702 Cxx20Enumerator 12703 ? diag::warn_cxx17_compat_using_decl_class_member_enumerator 12704 : diag::err_using_decl_can_not_refer_to_class_member) 12705 << SS.getRange(); 12706 12707 if (Cxx20Enumerator) 12708 return false; // OK 12709 12710 auto *RD = NamedContext 12711 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext()) 12712 : nullptr; 12713 if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) { 12714 // See if there's a helpful fixit 12715 12716 if (!R) { 12717 // We will have already diagnosed the problem on the template 12718 // definition, Maybe we should do so again? 12719 } else if (R->getAsSingle<TypeDecl>()) { 12720 if (getLangOpts().CPlusPlus11) { 12721 // Convert 'using X::Y;' to 'using Y = X::Y;'. 12722 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 12723 << 0 // alias declaration 12724 << FixItHint::CreateInsertion(SS.getBeginLoc(), 12725 NameInfo.getName().getAsString() + 12726 " = "); 12727 } else { 12728 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 12729 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc()); 12730 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 12731 << 1 // typedef declaration 12732 << FixItHint::CreateReplacement(UsingLoc, "typedef") 12733 << FixItHint::CreateInsertion( 12734 InsertLoc, " " + NameInfo.getName().getAsString()); 12735 } 12736 } else if (R->getAsSingle<VarDecl>()) { 12737 // Don't provide a fixit outside C++11 mode; we don't want to suggest 12738 // repeating the type of the static data member here. 12739 FixItHint FixIt; 12740 if (getLangOpts().CPlusPlus11) { 12741 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 12742 FixIt = FixItHint::CreateReplacement( 12743 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 12744 } 12745 12746 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 12747 << 2 // reference declaration 12748 << FixIt; 12749 } else if (R->getAsSingle<EnumConstantDecl>()) { 12750 // Don't provide a fixit outside C++11 mode; we don't want to suggest 12751 // repeating the type of the enumeration here, and we can't do so if 12752 // the type is anonymous. 12753 FixItHint FixIt; 12754 if (getLangOpts().CPlusPlus11) { 12755 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 12756 FixIt = FixItHint::CreateReplacement( 12757 UsingLoc, 12758 "constexpr auto " + NameInfo.getName().getAsString() + " = "); 12759 } 12760 12761 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 12762 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable 12763 << FixIt; 12764 } 12765 } 12766 12767 return true; // Fail 12768 } 12769 12770 // If the named context is dependent, we can't decide much. 12771 if (!NamedContext) { 12772 // FIXME: in C++0x, we can diagnose if we can prove that the 12773 // nested-name-specifier does not refer to a base class, which is 12774 // still possible in some cases. 12775 12776 // Otherwise we have to conservatively report that things might be 12777 // okay. 12778 return false; 12779 } 12780 12781 // The current scope is a record. 12782 if (!NamedContext->isRecord()) { 12783 // Ideally this would point at the last name in the specifier, 12784 // but we don't have that level of source info. 12785 Diag(SS.getBeginLoc(), 12786 Cxx20Enumerator 12787 ? diag::warn_cxx17_compat_using_decl_non_member_enumerator 12788 : diag::err_using_decl_nested_name_specifier_is_not_class) 12789 << SS.getScopeRep() << SS.getRange(); 12790 12791 if (Cxx20Enumerator) 12792 return false; // OK 12793 12794 return true; 12795 } 12796 12797 if (!NamedContext->isDependentContext() && 12798 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 12799 return true; 12800 12801 if (getLangOpts().CPlusPlus11) { 12802 // C++11 [namespace.udecl]p3: 12803 // In a using-declaration used as a member-declaration, the 12804 // nested-name-specifier shall name a base class of the class 12805 // being defined. 12806 12807 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 12808 cast<CXXRecordDecl>(NamedContext))) { 12809 12810 if (Cxx20Enumerator) { 12811 Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator) 12812 << SS.getRange(); 12813 return false; 12814 } 12815 12816 if (CurContext == NamedContext) { 12817 Diag(SS.getBeginLoc(), 12818 diag::err_using_decl_nested_name_specifier_is_current_class) 12819 << SS.getRange(); 12820 return !getLangOpts().CPlusPlus20; 12821 } 12822 12823 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) { 12824 Diag(SS.getBeginLoc(), 12825 diag::err_using_decl_nested_name_specifier_is_not_base_class) 12826 << SS.getScopeRep() << cast<CXXRecordDecl>(CurContext) 12827 << SS.getRange(); 12828 } 12829 return true; 12830 } 12831 12832 return false; 12833 } 12834 12835 // C++03 [namespace.udecl]p4: 12836 // A using-declaration used as a member-declaration shall refer 12837 // to a member of a base class of the class being defined [etc.]. 12838 12839 // Salient point: SS doesn't have to name a base class as long as 12840 // lookup only finds members from base classes. Therefore we can 12841 // diagnose here only if we can prove that that can't happen, 12842 // i.e. if the class hierarchies provably don't intersect. 12843 12844 // TODO: it would be nice if "definitely valid" results were cached 12845 // in the UsingDecl and UsingShadowDecl so that these checks didn't 12846 // need to be repeated. 12847 12848 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases; 12849 auto Collect = [&Bases](const CXXRecordDecl *Base) { 12850 Bases.insert(Base); 12851 return true; 12852 }; 12853 12854 // Collect all bases. Return false if we find a dependent base. 12855 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect)) 12856 return false; 12857 12858 // Returns true if the base is dependent or is one of the accumulated base 12859 // classes. 12860 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) { 12861 return !Bases.count(Base); 12862 }; 12863 12864 // Return false if the class has a dependent base or if it or one 12865 // of its bases is present in the base set of the current context. 12866 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) || 12867 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase)) 12868 return false; 12869 12870 Diag(SS.getRange().getBegin(), 12871 diag::err_using_decl_nested_name_specifier_is_not_base_class) 12872 << SS.getScopeRep() 12873 << cast<CXXRecordDecl>(CurContext) 12874 << SS.getRange(); 12875 12876 return true; 12877 } 12878 12879 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS, 12880 MultiTemplateParamsArg TemplateParamLists, 12881 SourceLocation UsingLoc, UnqualifiedId &Name, 12882 const ParsedAttributesView &AttrList, 12883 TypeResult Type, Decl *DeclFromDeclSpec) { 12884 // Skip up to the relevant declaration scope. 12885 while (S->isTemplateParamScope()) 12886 S = S->getParent(); 12887 assert((S->getFlags() & Scope::DeclScope) && 12888 "got alias-declaration outside of declaration scope"); 12889 12890 if (Type.isInvalid()) 12891 return nullptr; 12892 12893 bool Invalid = false; 12894 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 12895 TypeSourceInfo *TInfo = nullptr; 12896 GetTypeFromParser(Type.get(), &TInfo); 12897 12898 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 12899 return nullptr; 12900 12901 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 12902 UPPC_DeclarationType)) { 12903 Invalid = true; 12904 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 12905 TInfo->getTypeLoc().getBeginLoc()); 12906 } 12907 12908 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 12909 TemplateParamLists.size() 12910 ? forRedeclarationInCurContext() 12911 : ForVisibleRedeclaration); 12912 LookupName(Previous, S); 12913 12914 // Warn about shadowing the name of a template parameter. 12915 if (Previous.isSingleResult() && 12916 Previous.getFoundDecl()->isTemplateParameter()) { 12917 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 12918 Previous.clear(); 12919 } 12920 12921 assert(Name.Kind == UnqualifiedIdKind::IK_Identifier && 12922 "name in alias declaration must be an identifier"); 12923 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 12924 Name.StartLocation, 12925 Name.Identifier, TInfo); 12926 12927 NewTD->setAccess(AS); 12928 12929 if (Invalid) 12930 NewTD->setInvalidDecl(); 12931 12932 ProcessDeclAttributeList(S, NewTD, AttrList); 12933 AddPragmaAttributes(S, NewTD); 12934 12935 CheckTypedefForVariablyModifiedType(S, NewTD); 12936 Invalid |= NewTD->isInvalidDecl(); 12937 12938 bool Redeclaration = false; 12939 12940 NamedDecl *NewND; 12941 if (TemplateParamLists.size()) { 12942 TypeAliasTemplateDecl *OldDecl = nullptr; 12943 TemplateParameterList *OldTemplateParams = nullptr; 12944 12945 if (TemplateParamLists.size() != 1) { 12946 Diag(UsingLoc, diag::err_alias_template_extra_headers) 12947 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 12948 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 12949 } 12950 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 12951 12952 // Check that we can declare a template here. 12953 if (CheckTemplateDeclScope(S, TemplateParams)) 12954 return nullptr; 12955 12956 // Only consider previous declarations in the same scope. 12957 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 12958 /*ExplicitInstantiationOrSpecialization*/false); 12959 if (!Previous.empty()) { 12960 Redeclaration = true; 12961 12962 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 12963 if (!OldDecl && !Invalid) { 12964 Diag(UsingLoc, diag::err_redefinition_different_kind) 12965 << Name.Identifier; 12966 12967 NamedDecl *OldD = Previous.getRepresentativeDecl(); 12968 if (OldD->getLocation().isValid()) 12969 Diag(OldD->getLocation(), diag::note_previous_definition); 12970 12971 Invalid = true; 12972 } 12973 12974 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 12975 if (TemplateParameterListsAreEqual(TemplateParams, 12976 OldDecl->getTemplateParameters(), 12977 /*Complain=*/true, 12978 TPL_TemplateMatch)) 12979 OldTemplateParams = 12980 OldDecl->getMostRecentDecl()->getTemplateParameters(); 12981 else 12982 Invalid = true; 12983 12984 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 12985 if (!Invalid && 12986 !Context.hasSameType(OldTD->getUnderlyingType(), 12987 NewTD->getUnderlyingType())) { 12988 // FIXME: The C++0x standard does not clearly say this is ill-formed, 12989 // but we can't reasonably accept it. 12990 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 12991 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 12992 if (OldTD->getLocation().isValid()) 12993 Diag(OldTD->getLocation(), diag::note_previous_definition); 12994 Invalid = true; 12995 } 12996 } 12997 } 12998 12999 // Merge any previous default template arguments into our parameters, 13000 // and check the parameter list. 13001 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 13002 TPC_TypeAliasTemplate)) 13003 return nullptr; 13004 13005 TypeAliasTemplateDecl *NewDecl = 13006 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 13007 Name.Identifier, TemplateParams, 13008 NewTD); 13009 NewTD->setDescribedAliasTemplate(NewDecl); 13010 13011 NewDecl->setAccess(AS); 13012 13013 if (Invalid) 13014 NewDecl->setInvalidDecl(); 13015 else if (OldDecl) { 13016 NewDecl->setPreviousDecl(OldDecl); 13017 CheckRedeclarationModuleOwnership(NewDecl, OldDecl); 13018 } 13019 13020 NewND = NewDecl; 13021 } else { 13022 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { 13023 setTagNameForLinkagePurposes(TD, NewTD); 13024 handleTagNumbering(TD, S); 13025 } 13026 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 13027 NewND = NewTD; 13028 } 13029 13030 PushOnScopeChains(NewND, S); 13031 ActOnDocumentableDecl(NewND); 13032 return NewND; 13033 } 13034 13035 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 13036 SourceLocation AliasLoc, 13037 IdentifierInfo *Alias, CXXScopeSpec &SS, 13038 SourceLocation IdentLoc, 13039 IdentifierInfo *Ident) { 13040 13041 // Lookup the namespace name. 13042 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 13043 LookupParsedName(R, S, &SS); 13044 13045 if (R.isAmbiguous()) 13046 return nullptr; 13047 13048 if (R.empty()) { 13049 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 13050 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 13051 return nullptr; 13052 } 13053 } 13054 assert(!R.isAmbiguous() && !R.empty()); 13055 NamedDecl *ND = R.getRepresentativeDecl(); 13056 13057 // Check if we have a previous declaration with the same name. 13058 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName, 13059 ForVisibleRedeclaration); 13060 LookupName(PrevR, S); 13061 13062 // Check we're not shadowing a template parameter. 13063 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) { 13064 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl()); 13065 PrevR.clear(); 13066 } 13067 13068 // Filter out any other lookup result from an enclosing scope. 13069 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false, 13070 /*AllowInlineNamespace*/false); 13071 13072 // Find the previous declaration and check that we can redeclare it. 13073 NamespaceAliasDecl *Prev = nullptr; 13074 if (PrevR.isSingleResult()) { 13075 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl(); 13076 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 13077 // We already have an alias with the same name that points to the same 13078 // namespace; check that it matches. 13079 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) { 13080 Prev = AD; 13081 } else if (isVisible(PrevDecl)) { 13082 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 13083 << Alias; 13084 Diag(AD->getLocation(), diag::note_previous_namespace_alias) 13085 << AD->getNamespace(); 13086 return nullptr; 13087 } 13088 } else if (isVisible(PrevDecl)) { 13089 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl()) 13090 ? diag::err_redefinition 13091 : diag::err_redefinition_different_kind; 13092 Diag(AliasLoc, DiagID) << Alias; 13093 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 13094 return nullptr; 13095 } 13096 } 13097 13098 // The use of a nested name specifier may trigger deprecation warnings. 13099 DiagnoseUseOfDecl(ND, IdentLoc); 13100 13101 NamespaceAliasDecl *AliasDecl = 13102 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 13103 Alias, SS.getWithLocInContext(Context), 13104 IdentLoc, ND); 13105 if (Prev) 13106 AliasDecl->setPreviousDecl(Prev); 13107 13108 PushOnScopeChains(AliasDecl, S); 13109 return AliasDecl; 13110 } 13111 13112 namespace { 13113 struct SpecialMemberExceptionSpecInfo 13114 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> { 13115 SourceLocation Loc; 13116 Sema::ImplicitExceptionSpecification ExceptSpec; 13117 13118 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD, 13119 Sema::CXXSpecialMember CSM, 13120 Sema::InheritedConstructorInfo *ICI, 13121 SourceLocation Loc) 13122 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {} 13123 13124 bool visitBase(CXXBaseSpecifier *Base); 13125 bool visitField(FieldDecl *FD); 13126 13127 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 13128 unsigned Quals); 13129 13130 void visitSubobjectCall(Subobject Subobj, 13131 Sema::SpecialMemberOverloadResult SMOR); 13132 }; 13133 } 13134 13135 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) { 13136 auto *RT = Base->getType()->getAs<RecordType>(); 13137 if (!RT) 13138 return false; 13139 13140 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl()); 13141 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 13142 if (auto *BaseCtor = SMOR.getMethod()) { 13143 visitSubobjectCall(Base, BaseCtor); 13144 return false; 13145 } 13146 13147 visitClassSubobject(BaseClass, Base, 0); 13148 return false; 13149 } 13150 13151 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) { 13152 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) { 13153 Expr *E = FD->getInClassInitializer(); 13154 if (!E) 13155 // FIXME: It's a little wasteful to build and throw away a 13156 // CXXDefaultInitExpr here. 13157 // FIXME: We should have a single context note pointing at Loc, and 13158 // this location should be MD->getLocation() instead, since that's 13159 // the location where we actually use the default init expression. 13160 E = S.BuildCXXDefaultInitExpr(Loc, FD).get(); 13161 if (E) 13162 ExceptSpec.CalledExpr(E); 13163 } else if (auto *RT = S.Context.getBaseElementType(FD->getType()) 13164 ->getAs<RecordType>()) { 13165 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD, 13166 FD->getType().getCVRQualifiers()); 13167 } 13168 return false; 13169 } 13170 13171 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class, 13172 Subobject Subobj, 13173 unsigned Quals) { 13174 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 13175 bool IsMutable = Field && Field->isMutable(); 13176 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable)); 13177 } 13178 13179 void SpecialMemberExceptionSpecInfo::visitSubobjectCall( 13180 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) { 13181 // Note, if lookup fails, it doesn't matter what exception specification we 13182 // choose because the special member will be deleted. 13183 if (CXXMethodDecl *MD = SMOR.getMethod()) 13184 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD); 13185 } 13186 13187 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) { 13188 llvm::APSInt Result; 13189 ExprResult Converted = CheckConvertedConstantExpression( 13190 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool); 13191 ExplicitSpec.setExpr(Converted.get()); 13192 if (Converted.isUsable() && !Converted.get()->isValueDependent()) { 13193 ExplicitSpec.setKind(Result.getBoolValue() 13194 ? ExplicitSpecKind::ResolvedTrue 13195 : ExplicitSpecKind::ResolvedFalse); 13196 return true; 13197 } 13198 ExplicitSpec.setKind(ExplicitSpecKind::Unresolved); 13199 return false; 13200 } 13201 13202 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) { 13203 ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved); 13204 if (!ExplicitExpr->isTypeDependent()) 13205 tryResolveExplicitSpecifier(ES); 13206 return ES; 13207 } 13208 13209 static Sema::ImplicitExceptionSpecification 13210 ComputeDefaultedSpecialMemberExceptionSpec( 13211 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 13212 Sema::InheritedConstructorInfo *ICI) { 13213 ComputingExceptionSpec CES(S, MD, Loc); 13214 13215 CXXRecordDecl *ClassDecl = MD->getParent(); 13216 13217 // C++ [except.spec]p14: 13218 // An implicitly declared special member function (Clause 12) shall have an 13219 // exception-specification. [...] 13220 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation()); 13221 if (ClassDecl->isInvalidDecl()) 13222 return Info.ExceptSpec; 13223 13224 // FIXME: If this diagnostic fires, we're probably missing a check for 13225 // attempting to resolve an exception specification before it's known 13226 // at a higher level. 13227 if (S.RequireCompleteType(MD->getLocation(), 13228 S.Context.getRecordType(ClassDecl), 13229 diag::err_exception_spec_incomplete_type)) 13230 return Info.ExceptSpec; 13231 13232 // C++1z [except.spec]p7: 13233 // [Look for exceptions thrown by] a constructor selected [...] to 13234 // initialize a potentially constructed subobject, 13235 // C++1z [except.spec]p8: 13236 // The exception specification for an implicitly-declared destructor, or a 13237 // destructor without a noexcept-specifier, is potentially-throwing if and 13238 // only if any of the destructors for any of its potentially constructed 13239 // subojects is potentially throwing. 13240 // FIXME: We respect the first rule but ignore the "potentially constructed" 13241 // in the second rule to resolve a core issue (no number yet) that would have 13242 // us reject: 13243 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; }; 13244 // struct B : A {}; 13245 // struct C : B { void f(); }; 13246 // ... due to giving B::~B() a non-throwing exception specification. 13247 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases 13248 : Info.VisitAllBases); 13249 13250 return Info.ExceptSpec; 13251 } 13252 13253 namespace { 13254 /// RAII object to register a special member as being currently declared. 13255 struct DeclaringSpecialMember { 13256 Sema &S; 13257 Sema::SpecialMemberDecl D; 13258 Sema::ContextRAII SavedContext; 13259 bool WasAlreadyBeingDeclared; 13260 13261 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 13262 : S(S), D(RD, CSM), SavedContext(S, RD) { 13263 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 13264 if (WasAlreadyBeingDeclared) 13265 // This almost never happens, but if it does, ensure that our cache 13266 // doesn't contain a stale result. 13267 S.SpecialMemberCache.clear(); 13268 else { 13269 // Register a note to be produced if we encounter an error while 13270 // declaring the special member. 13271 Sema::CodeSynthesisContext Ctx; 13272 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember; 13273 // FIXME: We don't have a location to use here. Using the class's 13274 // location maintains the fiction that we declare all special members 13275 // with the class, but (1) it's not clear that lying about that helps our 13276 // users understand what's going on, and (2) there may be outer contexts 13277 // on the stack (some of which are relevant) and printing them exposes 13278 // our lies. 13279 Ctx.PointOfInstantiation = RD->getLocation(); 13280 Ctx.Entity = RD; 13281 Ctx.SpecialMember = CSM; 13282 S.pushCodeSynthesisContext(Ctx); 13283 } 13284 } 13285 ~DeclaringSpecialMember() { 13286 if (!WasAlreadyBeingDeclared) { 13287 S.SpecialMembersBeingDeclared.erase(D); 13288 S.popCodeSynthesisContext(); 13289 } 13290 } 13291 13292 /// Are we already trying to declare this special member? 13293 bool isAlreadyBeingDeclared() const { 13294 return WasAlreadyBeingDeclared; 13295 } 13296 }; 13297 } 13298 13299 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) { 13300 // Look up any existing declarations, but don't trigger declaration of all 13301 // implicit special members with this name. 13302 DeclarationName Name = FD->getDeclName(); 13303 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName, 13304 ForExternalRedeclaration); 13305 for (auto *D : FD->getParent()->lookup(Name)) 13306 if (auto *Acceptable = R.getAcceptableDecl(D)) 13307 R.addDecl(Acceptable); 13308 R.resolveKind(); 13309 R.suppressDiagnostics(); 13310 13311 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false); 13312 } 13313 13314 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem, 13315 QualType ResultTy, 13316 ArrayRef<QualType> Args) { 13317 // Build an exception specification pointing back at this constructor. 13318 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem); 13319 13320 LangAS AS = getDefaultCXXMethodAddrSpace(); 13321 if (AS != LangAS::Default) { 13322 EPI.TypeQuals.addAddressSpace(AS); 13323 } 13324 13325 auto QT = Context.getFunctionType(ResultTy, Args, EPI); 13326 SpecialMem->setType(QT); 13327 13328 // During template instantiation of implicit special member functions we need 13329 // a reliable TypeSourceInfo for the function prototype in order to allow 13330 // functions to be substituted. 13331 if (inTemplateInstantiation() && 13332 cast<CXXRecordDecl>(SpecialMem->getParent())->isLambda()) { 13333 TypeSourceInfo *TSI = 13334 Context.getTrivialTypeSourceInfo(SpecialMem->getType()); 13335 SpecialMem->setTypeSourceInfo(TSI); 13336 } 13337 } 13338 13339 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 13340 CXXRecordDecl *ClassDecl) { 13341 // C++ [class.ctor]p5: 13342 // A default constructor for a class X is a constructor of class X 13343 // that can be called without an argument. If there is no 13344 // user-declared constructor for class X, a default constructor is 13345 // implicitly declared. An implicitly-declared default constructor 13346 // is an inline public member of its class. 13347 assert(ClassDecl->needsImplicitDefaultConstructor() && 13348 "Should not build implicit default constructor!"); 13349 13350 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 13351 if (DSM.isAlreadyBeingDeclared()) 13352 return nullptr; 13353 13354 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 13355 CXXDefaultConstructor, 13356 false); 13357 13358 // Create the actual constructor declaration. 13359 CanQualType ClassType 13360 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 13361 SourceLocation ClassLoc = ClassDecl->getLocation(); 13362 DeclarationName Name 13363 = Context.DeclarationNames.getCXXConstructorName(ClassType); 13364 DeclarationNameInfo NameInfo(Name, ClassLoc); 13365 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 13366 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(), 13367 /*TInfo=*/nullptr, ExplicitSpecifier(), 13368 getCurFPFeatures().isFPConstrained(), 13369 /*isInline=*/true, /*isImplicitlyDeclared=*/true, 13370 Constexpr ? ConstexprSpecKind::Constexpr 13371 : ConstexprSpecKind::Unspecified); 13372 DefaultCon->setAccess(AS_public); 13373 DefaultCon->setDefaulted(); 13374 13375 if (getLangOpts().CUDA) { 13376 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 13377 DefaultCon, 13378 /* ConstRHS */ false, 13379 /* Diagnose */ false); 13380 } 13381 13382 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None); 13383 13384 // We don't need to use SpecialMemberIsTrivial here; triviality for default 13385 // constructors is easy to compute. 13386 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 13387 13388 // Note that we have declared this constructor. 13389 ++getASTContext().NumImplicitDefaultConstructorsDeclared; 13390 13391 Scope *S = getScopeForContext(ClassDecl); 13392 CheckImplicitSpecialMemberDeclaration(S, DefaultCon); 13393 13394 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 13395 SetDeclDeleted(DefaultCon, ClassLoc); 13396 13397 if (S) 13398 PushOnScopeChains(DefaultCon, S, false); 13399 ClassDecl->addDecl(DefaultCon); 13400 13401 return DefaultCon; 13402 } 13403 13404 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 13405 CXXConstructorDecl *Constructor) { 13406 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 13407 !Constructor->doesThisDeclarationHaveABody() && 13408 !Constructor->isDeleted()) && 13409 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 13410 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 13411 return; 13412 13413 CXXRecordDecl *ClassDecl = Constructor->getParent(); 13414 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 13415 13416 SynthesizedFunctionScope Scope(*this, Constructor); 13417 13418 // The exception specification is needed because we are defining the 13419 // function. 13420 ResolveExceptionSpec(CurrentLocation, 13421 Constructor->getType()->castAs<FunctionProtoType>()); 13422 MarkVTableUsed(CurrentLocation, ClassDecl); 13423 13424 // Add a context note for diagnostics produced after this point. 13425 Scope.addContextNote(CurrentLocation); 13426 13427 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) { 13428 Constructor->setInvalidDecl(); 13429 return; 13430 } 13431 13432 SourceLocation Loc = Constructor->getEndLoc().isValid() 13433 ? Constructor->getEndLoc() 13434 : Constructor->getLocation(); 13435 Constructor->setBody(new (Context) CompoundStmt(Loc)); 13436 Constructor->markUsed(Context); 13437 13438 if (ASTMutationListener *L = getASTMutationListener()) { 13439 L->CompletedImplicitDefinition(Constructor); 13440 } 13441 13442 DiagnoseUninitializedFields(*this, Constructor); 13443 } 13444 13445 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 13446 // Perform any delayed checks on exception specifications. 13447 CheckDelayedMemberExceptionSpecs(); 13448 } 13449 13450 /// Find or create the fake constructor we synthesize to model constructing an 13451 /// object of a derived class via a constructor of a base class. 13452 CXXConstructorDecl * 13453 Sema::findInheritingConstructor(SourceLocation Loc, 13454 CXXConstructorDecl *BaseCtor, 13455 ConstructorUsingShadowDecl *Shadow) { 13456 CXXRecordDecl *Derived = Shadow->getParent(); 13457 SourceLocation UsingLoc = Shadow->getLocation(); 13458 13459 // FIXME: Add a new kind of DeclarationName for an inherited constructor. 13460 // For now we use the name of the base class constructor as a member of the 13461 // derived class to indicate a (fake) inherited constructor name. 13462 DeclarationName Name = BaseCtor->getDeclName(); 13463 13464 // Check to see if we already have a fake constructor for this inherited 13465 // constructor call. 13466 for (NamedDecl *Ctor : Derived->lookup(Name)) 13467 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor) 13468 ->getInheritedConstructor() 13469 .getConstructor(), 13470 BaseCtor)) 13471 return cast<CXXConstructorDecl>(Ctor); 13472 13473 DeclarationNameInfo NameInfo(Name, UsingLoc); 13474 TypeSourceInfo *TInfo = 13475 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc); 13476 FunctionProtoTypeLoc ProtoLoc = 13477 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 13478 13479 // Check the inherited constructor is valid and find the list of base classes 13480 // from which it was inherited. 13481 InheritedConstructorInfo ICI(*this, Loc, Shadow); 13482 13483 bool Constexpr = 13484 BaseCtor->isConstexpr() && 13485 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor, 13486 false, BaseCtor, &ICI); 13487 13488 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 13489 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo, 13490 BaseCtor->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(), 13491 /*isInline=*/true, 13492 /*isImplicitlyDeclared=*/true, 13493 Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified, 13494 InheritedConstructor(Shadow, BaseCtor), 13495 BaseCtor->getTrailingRequiresClause()); 13496 if (Shadow->isInvalidDecl()) 13497 DerivedCtor->setInvalidDecl(); 13498 13499 // Build an unevaluated exception specification for this fake constructor. 13500 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>(); 13501 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 13502 EPI.ExceptionSpec.Type = EST_Unevaluated; 13503 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 13504 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 13505 FPT->getParamTypes(), EPI)); 13506 13507 // Build the parameter declarations. 13508 SmallVector<ParmVarDecl *, 16> ParamDecls; 13509 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 13510 TypeSourceInfo *TInfo = 13511 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 13512 ParmVarDecl *PD = ParmVarDecl::Create( 13513 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 13514 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr); 13515 PD->setScopeInfo(0, I); 13516 PD->setImplicit(); 13517 // Ensure attributes are propagated onto parameters (this matters for 13518 // format, pass_object_size, ...). 13519 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I)); 13520 ParamDecls.push_back(PD); 13521 ProtoLoc.setParam(I, PD); 13522 } 13523 13524 // Set up the new constructor. 13525 assert(!BaseCtor->isDeleted() && "should not use deleted constructor"); 13526 DerivedCtor->setAccess(BaseCtor->getAccess()); 13527 DerivedCtor->setParams(ParamDecls); 13528 Derived->addDecl(DerivedCtor); 13529 13530 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI)) 13531 SetDeclDeleted(DerivedCtor, UsingLoc); 13532 13533 return DerivedCtor; 13534 } 13535 13536 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) { 13537 InheritedConstructorInfo ICI(*this, Ctor->getLocation(), 13538 Ctor->getInheritedConstructor().getShadowDecl()); 13539 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI, 13540 /*Diagnose*/true); 13541 } 13542 13543 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 13544 CXXConstructorDecl *Constructor) { 13545 CXXRecordDecl *ClassDecl = Constructor->getParent(); 13546 assert(Constructor->getInheritedConstructor() && 13547 !Constructor->doesThisDeclarationHaveABody() && 13548 !Constructor->isDeleted()); 13549 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 13550 return; 13551 13552 // Initializations are performed "as if by a defaulted default constructor", 13553 // so enter the appropriate scope. 13554 SynthesizedFunctionScope Scope(*this, Constructor); 13555 13556 // The exception specification is needed because we are defining the 13557 // function. 13558 ResolveExceptionSpec(CurrentLocation, 13559 Constructor->getType()->castAs<FunctionProtoType>()); 13560 MarkVTableUsed(CurrentLocation, ClassDecl); 13561 13562 // Add a context note for diagnostics produced after this point. 13563 Scope.addContextNote(CurrentLocation); 13564 13565 ConstructorUsingShadowDecl *Shadow = 13566 Constructor->getInheritedConstructor().getShadowDecl(); 13567 CXXConstructorDecl *InheritedCtor = 13568 Constructor->getInheritedConstructor().getConstructor(); 13569 13570 // [class.inhctor.init]p1: 13571 // initialization proceeds as if a defaulted default constructor is used to 13572 // initialize the D object and each base class subobject from which the 13573 // constructor was inherited 13574 13575 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow); 13576 CXXRecordDecl *RD = Shadow->getParent(); 13577 SourceLocation InitLoc = Shadow->getLocation(); 13578 13579 // Build explicit initializers for all base classes from which the 13580 // constructor was inherited. 13581 SmallVector<CXXCtorInitializer*, 8> Inits; 13582 for (bool VBase : {false, true}) { 13583 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) { 13584 if (B.isVirtual() != VBase) 13585 continue; 13586 13587 auto *BaseRD = B.getType()->getAsCXXRecordDecl(); 13588 if (!BaseRD) 13589 continue; 13590 13591 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor); 13592 if (!BaseCtor.first) 13593 continue; 13594 13595 MarkFunctionReferenced(CurrentLocation, BaseCtor.first); 13596 ExprResult Init = new (Context) CXXInheritedCtorInitExpr( 13597 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second); 13598 13599 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc); 13600 Inits.push_back(new (Context) CXXCtorInitializer( 13601 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc, 13602 SourceLocation())); 13603 } 13604 } 13605 13606 // We now proceed as if for a defaulted default constructor, with the relevant 13607 // initializers replaced. 13608 13609 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) { 13610 Constructor->setInvalidDecl(); 13611 return; 13612 } 13613 13614 Constructor->setBody(new (Context) CompoundStmt(InitLoc)); 13615 Constructor->markUsed(Context); 13616 13617 if (ASTMutationListener *L = getASTMutationListener()) { 13618 L->CompletedImplicitDefinition(Constructor); 13619 } 13620 13621 DiagnoseUninitializedFields(*this, Constructor); 13622 } 13623 13624 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 13625 // C++ [class.dtor]p2: 13626 // If a class has no user-declared destructor, a destructor is 13627 // declared implicitly. An implicitly-declared destructor is an 13628 // inline public member of its class. 13629 assert(ClassDecl->needsImplicitDestructor()); 13630 13631 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 13632 if (DSM.isAlreadyBeingDeclared()) 13633 return nullptr; 13634 13635 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 13636 CXXDestructor, 13637 false); 13638 13639 // Create the actual destructor declaration. 13640 CanQualType ClassType 13641 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 13642 SourceLocation ClassLoc = ClassDecl->getLocation(); 13643 DeclarationName Name 13644 = Context.DeclarationNames.getCXXDestructorName(ClassType); 13645 DeclarationNameInfo NameInfo(Name, ClassLoc); 13646 CXXDestructorDecl *Destructor = CXXDestructorDecl::Create( 13647 Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr, 13648 getCurFPFeatures().isFPConstrained(), 13649 /*isInline=*/true, 13650 /*isImplicitlyDeclared=*/true, 13651 Constexpr ? ConstexprSpecKind::Constexpr 13652 : ConstexprSpecKind::Unspecified); 13653 Destructor->setAccess(AS_public); 13654 Destructor->setDefaulted(); 13655 13656 if (getLangOpts().CUDA) { 13657 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 13658 Destructor, 13659 /* ConstRHS */ false, 13660 /* Diagnose */ false); 13661 } 13662 13663 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None); 13664 13665 // We don't need to use SpecialMemberIsTrivial here; triviality for 13666 // destructors is easy to compute. 13667 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 13668 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() || 13669 ClassDecl->hasTrivialDestructorForCall()); 13670 13671 // Note that we have declared this destructor. 13672 ++getASTContext().NumImplicitDestructorsDeclared; 13673 13674 Scope *S = getScopeForContext(ClassDecl); 13675 CheckImplicitSpecialMemberDeclaration(S, Destructor); 13676 13677 // We can't check whether an implicit destructor is deleted before we complete 13678 // the definition of the class, because its validity depends on the alignment 13679 // of the class. We'll check this from ActOnFields once the class is complete. 13680 if (ClassDecl->isCompleteDefinition() && 13681 ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 13682 SetDeclDeleted(Destructor, ClassLoc); 13683 13684 // Introduce this destructor into its scope. 13685 if (S) 13686 PushOnScopeChains(Destructor, S, false); 13687 ClassDecl->addDecl(Destructor); 13688 13689 return Destructor; 13690 } 13691 13692 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 13693 CXXDestructorDecl *Destructor) { 13694 assert((Destructor->isDefaulted() && 13695 !Destructor->doesThisDeclarationHaveABody() && 13696 !Destructor->isDeleted()) && 13697 "DefineImplicitDestructor - call it for implicit default dtor"); 13698 if (Destructor->willHaveBody() || Destructor->isInvalidDecl()) 13699 return; 13700 13701 CXXRecordDecl *ClassDecl = Destructor->getParent(); 13702 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 13703 13704 SynthesizedFunctionScope Scope(*this, Destructor); 13705 13706 // The exception specification is needed because we are defining the 13707 // function. 13708 ResolveExceptionSpec(CurrentLocation, 13709 Destructor->getType()->castAs<FunctionProtoType>()); 13710 MarkVTableUsed(CurrentLocation, ClassDecl); 13711 13712 // Add a context note for diagnostics produced after this point. 13713 Scope.addContextNote(CurrentLocation); 13714 13715 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 13716 Destructor->getParent()); 13717 13718 if (CheckDestructor(Destructor)) { 13719 Destructor->setInvalidDecl(); 13720 return; 13721 } 13722 13723 SourceLocation Loc = Destructor->getEndLoc().isValid() 13724 ? Destructor->getEndLoc() 13725 : Destructor->getLocation(); 13726 Destructor->setBody(new (Context) CompoundStmt(Loc)); 13727 Destructor->markUsed(Context); 13728 13729 if (ASTMutationListener *L = getASTMutationListener()) { 13730 L->CompletedImplicitDefinition(Destructor); 13731 } 13732 } 13733 13734 void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation, 13735 CXXDestructorDecl *Destructor) { 13736 if (Destructor->isInvalidDecl()) 13737 return; 13738 13739 CXXRecordDecl *ClassDecl = Destructor->getParent(); 13740 assert(Context.getTargetInfo().getCXXABI().isMicrosoft() && 13741 "implicit complete dtors unneeded outside MS ABI"); 13742 assert(ClassDecl->getNumVBases() > 0 && 13743 "complete dtor only exists for classes with vbases"); 13744 13745 SynthesizedFunctionScope Scope(*this, Destructor); 13746 13747 // Add a context note for diagnostics produced after this point. 13748 Scope.addContextNote(CurrentLocation); 13749 13750 MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl); 13751 } 13752 13753 /// Perform any semantic analysis which needs to be delayed until all 13754 /// pending class member declarations have been parsed. 13755 void Sema::ActOnFinishCXXMemberDecls() { 13756 // If the context is an invalid C++ class, just suppress these checks. 13757 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 13758 if (Record->isInvalidDecl()) { 13759 DelayedOverridingExceptionSpecChecks.clear(); 13760 DelayedEquivalentExceptionSpecChecks.clear(); 13761 return; 13762 } 13763 checkForMultipleExportedDefaultConstructors(*this, Record); 13764 } 13765 } 13766 13767 void Sema::ActOnFinishCXXNonNestedClass() { 13768 referenceDLLExportedClassMethods(); 13769 13770 if (!DelayedDllExportMemberFunctions.empty()) { 13771 SmallVector<CXXMethodDecl*, 4> WorkList; 13772 std::swap(DelayedDllExportMemberFunctions, WorkList); 13773 for (CXXMethodDecl *M : WorkList) { 13774 DefineDefaultedFunction(*this, M, M->getLocation()); 13775 13776 // Pass the method to the consumer to get emitted. This is not necessary 13777 // for explicit instantiation definitions, as they will get emitted 13778 // anyway. 13779 if (M->getParent()->getTemplateSpecializationKind() != 13780 TSK_ExplicitInstantiationDefinition) 13781 ActOnFinishInlineFunctionDef(M); 13782 } 13783 } 13784 } 13785 13786 void Sema::referenceDLLExportedClassMethods() { 13787 if (!DelayedDllExportClasses.empty()) { 13788 // Calling ReferenceDllExportedMembers might cause the current function to 13789 // be called again, so use a local copy of DelayedDllExportClasses. 13790 SmallVector<CXXRecordDecl *, 4> WorkList; 13791 std::swap(DelayedDllExportClasses, WorkList); 13792 for (CXXRecordDecl *Class : WorkList) 13793 ReferenceDllExportedMembers(*this, Class); 13794 } 13795 } 13796 13797 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) { 13798 assert(getLangOpts().CPlusPlus11 && 13799 "adjusting dtor exception specs was introduced in c++11"); 13800 13801 if (Destructor->isDependentContext()) 13802 return; 13803 13804 // C++11 [class.dtor]p3: 13805 // A declaration of a destructor that does not have an exception- 13806 // specification is implicitly considered to have the same exception- 13807 // specification as an implicit declaration. 13808 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>(); 13809 if (DtorType->hasExceptionSpec()) 13810 return; 13811 13812 // Replace the destructor's type, building off the existing one. Fortunately, 13813 // the only thing of interest in the destructor type is its extended info. 13814 // The return and arguments are fixed. 13815 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 13816 EPI.ExceptionSpec.Type = EST_Unevaluated; 13817 EPI.ExceptionSpec.SourceDecl = Destructor; 13818 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 13819 13820 // FIXME: If the destructor has a body that could throw, and the newly created 13821 // spec doesn't allow exceptions, we should emit a warning, because this 13822 // change in behavior can break conforming C++03 programs at runtime. 13823 // However, we don't have a body or an exception specification yet, so it 13824 // needs to be done somewhere else. 13825 } 13826 13827 namespace { 13828 /// An abstract base class for all helper classes used in building the 13829 // copy/move operators. These classes serve as factory functions and help us 13830 // avoid using the same Expr* in the AST twice. 13831 class ExprBuilder { 13832 ExprBuilder(const ExprBuilder&) = delete; 13833 ExprBuilder &operator=(const ExprBuilder&) = delete; 13834 13835 protected: 13836 static Expr *assertNotNull(Expr *E) { 13837 assert(E && "Expression construction must not fail."); 13838 return E; 13839 } 13840 13841 public: 13842 ExprBuilder() {} 13843 virtual ~ExprBuilder() {} 13844 13845 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 13846 }; 13847 13848 class RefBuilder: public ExprBuilder { 13849 VarDecl *Var; 13850 QualType VarType; 13851 13852 public: 13853 Expr *build(Sema &S, SourceLocation Loc) const override { 13854 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc)); 13855 } 13856 13857 RefBuilder(VarDecl *Var, QualType VarType) 13858 : Var(Var), VarType(VarType) {} 13859 }; 13860 13861 class ThisBuilder: public ExprBuilder { 13862 public: 13863 Expr *build(Sema &S, SourceLocation Loc) const override { 13864 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 13865 } 13866 }; 13867 13868 class CastBuilder: public ExprBuilder { 13869 const ExprBuilder &Builder; 13870 QualType Type; 13871 ExprValueKind Kind; 13872 const CXXCastPath &Path; 13873 13874 public: 13875 Expr *build(Sema &S, SourceLocation Loc) const override { 13876 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 13877 CK_UncheckedDerivedToBase, Kind, 13878 &Path).get()); 13879 } 13880 13881 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 13882 const CXXCastPath &Path) 13883 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 13884 }; 13885 13886 class DerefBuilder: public ExprBuilder { 13887 const ExprBuilder &Builder; 13888 13889 public: 13890 Expr *build(Sema &S, SourceLocation Loc) const override { 13891 return assertNotNull( 13892 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 13893 } 13894 13895 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13896 }; 13897 13898 class MemberBuilder: public ExprBuilder { 13899 const ExprBuilder &Builder; 13900 QualType Type; 13901 CXXScopeSpec SS; 13902 bool IsArrow; 13903 LookupResult &MemberLookup; 13904 13905 public: 13906 Expr *build(Sema &S, SourceLocation Loc) const override { 13907 return assertNotNull(S.BuildMemberReferenceExpr( 13908 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 13909 nullptr, MemberLookup, nullptr, nullptr).get()); 13910 } 13911 13912 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 13913 LookupResult &MemberLookup) 13914 : Builder(Builder), Type(Type), IsArrow(IsArrow), 13915 MemberLookup(MemberLookup) {} 13916 }; 13917 13918 class MoveCastBuilder: public ExprBuilder { 13919 const ExprBuilder &Builder; 13920 13921 public: 13922 Expr *build(Sema &S, SourceLocation Loc) const override { 13923 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 13924 } 13925 13926 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13927 }; 13928 13929 class LvalueConvBuilder: public ExprBuilder { 13930 const ExprBuilder &Builder; 13931 13932 public: 13933 Expr *build(Sema &S, SourceLocation Loc) const override { 13934 return assertNotNull( 13935 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 13936 } 13937 13938 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13939 }; 13940 13941 class SubscriptBuilder: public ExprBuilder { 13942 const ExprBuilder &Base; 13943 const ExprBuilder &Index; 13944 13945 public: 13946 Expr *build(Sema &S, SourceLocation Loc) const override { 13947 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 13948 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 13949 } 13950 13951 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 13952 : Base(Base), Index(Index) {} 13953 }; 13954 13955 } // end anonymous namespace 13956 13957 /// When generating a defaulted copy or move assignment operator, if a field 13958 /// should be copied with __builtin_memcpy rather than via explicit assignments, 13959 /// do so. This optimization only applies for arrays of scalars, and for arrays 13960 /// of class type where the selected copy/move-assignment operator is trivial. 13961 static StmtResult 13962 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 13963 const ExprBuilder &ToB, const ExprBuilder &FromB) { 13964 // Compute the size of the memory buffer to be copied. 13965 QualType SizeType = S.Context.getSizeType(); 13966 llvm::APInt Size(S.Context.getTypeSize(SizeType), 13967 S.Context.getTypeSizeInChars(T).getQuantity()); 13968 13969 // Take the address of the field references for "from" and "to". We 13970 // directly construct UnaryOperators here because semantic analysis 13971 // does not permit us to take the address of an xvalue. 13972 Expr *From = FromB.build(S, Loc); 13973 From = UnaryOperator::Create( 13974 S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()), 13975 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides()); 13976 Expr *To = ToB.build(S, Loc); 13977 To = UnaryOperator::Create( 13978 S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()), 13979 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides()); 13980 13981 const Type *E = T->getBaseElementTypeUnsafe(); 13982 bool NeedsCollectableMemCpy = 13983 E->isRecordType() && 13984 E->castAs<RecordType>()->getDecl()->hasObjectMember(); 13985 13986 // Create a reference to the __builtin_objc_memmove_collectable function 13987 StringRef MemCpyName = NeedsCollectableMemCpy ? 13988 "__builtin_objc_memmove_collectable" : 13989 "__builtin_memcpy"; 13990 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 13991 Sema::LookupOrdinaryName); 13992 S.LookupName(R, S.TUScope, true); 13993 13994 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 13995 if (!MemCpy) 13996 // Something went horribly wrong earlier, and we will have complained 13997 // about it. 13998 return StmtError(); 13999 14000 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 14001 VK_PRValue, Loc, nullptr); 14002 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 14003 14004 Expr *CallArgs[] = { 14005 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 14006 }; 14007 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 14008 Loc, CallArgs, Loc); 14009 14010 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 14011 return Call.getAs<Stmt>(); 14012 } 14013 14014 /// Builds a statement that copies/moves the given entity from \p From to 14015 /// \c To. 14016 /// 14017 /// This routine is used to copy/move the members of a class with an 14018 /// implicitly-declared copy/move assignment operator. When the entities being 14019 /// copied are arrays, this routine builds for loops to copy them. 14020 /// 14021 /// \param S The Sema object used for type-checking. 14022 /// 14023 /// \param Loc The location where the implicit copy/move is being generated. 14024 /// 14025 /// \param T The type of the expressions being copied/moved. Both expressions 14026 /// must have this type. 14027 /// 14028 /// \param To The expression we are copying/moving to. 14029 /// 14030 /// \param From The expression we are copying/moving from. 14031 /// 14032 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 14033 /// Otherwise, it's a non-static member subobject. 14034 /// 14035 /// \param Copying Whether we're copying or moving. 14036 /// 14037 /// \param Depth Internal parameter recording the depth of the recursion. 14038 /// 14039 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 14040 /// if a memcpy should be used instead. 14041 static StmtResult 14042 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 14043 const ExprBuilder &To, const ExprBuilder &From, 14044 bool CopyingBaseSubobject, bool Copying, 14045 unsigned Depth = 0) { 14046 // C++11 [class.copy]p28: 14047 // Each subobject is assigned in the manner appropriate to its type: 14048 // 14049 // - if the subobject is of class type, as if by a call to operator= with 14050 // the subobject as the object expression and the corresponding 14051 // subobject of x as a single function argument (as if by explicit 14052 // qualification; that is, ignoring any possible virtual overriding 14053 // functions in more derived classes); 14054 // 14055 // C++03 [class.copy]p13: 14056 // - if the subobject is of class type, the copy assignment operator for 14057 // the class is used (as if by explicit qualification; that is, 14058 // ignoring any possible virtual overriding functions in more derived 14059 // classes); 14060 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 14061 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 14062 14063 // Look for operator=. 14064 DeclarationName Name 14065 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 14066 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 14067 S.LookupQualifiedName(OpLookup, ClassDecl, false); 14068 14069 // Prior to C++11, filter out any result that isn't a copy/move-assignment 14070 // operator. 14071 if (!S.getLangOpts().CPlusPlus11) { 14072 LookupResult::Filter F = OpLookup.makeFilter(); 14073 while (F.hasNext()) { 14074 NamedDecl *D = F.next(); 14075 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 14076 if (Method->isCopyAssignmentOperator() || 14077 (!Copying && Method->isMoveAssignmentOperator())) 14078 continue; 14079 14080 F.erase(); 14081 } 14082 F.done(); 14083 } 14084 14085 // Suppress the protected check (C++ [class.protected]) for each of the 14086 // assignment operators we found. This strange dance is required when 14087 // we're assigning via a base classes's copy-assignment operator. To 14088 // ensure that we're getting the right base class subobject (without 14089 // ambiguities), we need to cast "this" to that subobject type; to 14090 // ensure that we don't go through the virtual call mechanism, we need 14091 // to qualify the operator= name with the base class (see below). However, 14092 // this means that if the base class has a protected copy assignment 14093 // operator, the protected member access check will fail. So, we 14094 // rewrite "protected" access to "public" access in this case, since we 14095 // know by construction that we're calling from a derived class. 14096 if (CopyingBaseSubobject) { 14097 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 14098 L != LEnd; ++L) { 14099 if (L.getAccess() == AS_protected) 14100 L.setAccess(AS_public); 14101 } 14102 } 14103 14104 // Create the nested-name-specifier that will be used to qualify the 14105 // reference to operator=; this is required to suppress the virtual 14106 // call mechanism. 14107 CXXScopeSpec SS; 14108 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 14109 SS.MakeTrivial(S.Context, 14110 NestedNameSpecifier::Create(S.Context, nullptr, false, 14111 CanonicalT), 14112 Loc); 14113 14114 // Create the reference to operator=. 14115 ExprResult OpEqualRef 14116 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false, 14117 SS, /*TemplateKWLoc=*/SourceLocation(), 14118 /*FirstQualifierInScope=*/nullptr, 14119 OpLookup, 14120 /*TemplateArgs=*/nullptr, /*S*/nullptr, 14121 /*SuppressQualifierCheck=*/true); 14122 if (OpEqualRef.isInvalid()) 14123 return StmtError(); 14124 14125 // Build the call to the assignment operator. 14126 14127 Expr *FromInst = From.build(S, Loc); 14128 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 14129 OpEqualRef.getAs<Expr>(), 14130 Loc, FromInst, Loc); 14131 if (Call.isInvalid()) 14132 return StmtError(); 14133 14134 // If we built a call to a trivial 'operator=' while copying an array, 14135 // bail out. We'll replace the whole shebang with a memcpy. 14136 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 14137 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 14138 return StmtResult((Stmt*)nullptr); 14139 14140 // Convert to an expression-statement, and clean up any produced 14141 // temporaries. 14142 return S.ActOnExprStmt(Call); 14143 } 14144 14145 // - if the subobject is of scalar type, the built-in assignment 14146 // operator is used. 14147 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 14148 if (!ArrayTy) { 14149 ExprResult Assignment = S.CreateBuiltinBinOp( 14150 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 14151 if (Assignment.isInvalid()) 14152 return StmtError(); 14153 return S.ActOnExprStmt(Assignment); 14154 } 14155 14156 // - if the subobject is an array, each element is assigned, in the 14157 // manner appropriate to the element type; 14158 14159 // Construct a loop over the array bounds, e.g., 14160 // 14161 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 14162 // 14163 // that will copy each of the array elements. 14164 QualType SizeType = S.Context.getSizeType(); 14165 14166 // Create the iteration variable. 14167 IdentifierInfo *IterationVarName = nullptr; 14168 { 14169 SmallString<8> Str; 14170 llvm::raw_svector_ostream OS(Str); 14171 OS << "__i" << Depth; 14172 IterationVarName = &S.Context.Idents.get(OS.str()); 14173 } 14174 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 14175 IterationVarName, SizeType, 14176 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 14177 SC_None); 14178 14179 // Initialize the iteration variable to zero. 14180 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 14181 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 14182 14183 // Creates a reference to the iteration variable. 14184 RefBuilder IterationVarRef(IterationVar, SizeType); 14185 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 14186 14187 // Create the DeclStmt that holds the iteration variable. 14188 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 14189 14190 // Subscript the "from" and "to" expressions with the iteration variable. 14191 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 14192 MoveCastBuilder FromIndexMove(FromIndexCopy); 14193 const ExprBuilder *FromIndex; 14194 if (Copying) 14195 FromIndex = &FromIndexCopy; 14196 else 14197 FromIndex = &FromIndexMove; 14198 14199 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 14200 14201 // Build the copy/move for an individual element of the array. 14202 StmtResult Copy = 14203 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 14204 ToIndex, *FromIndex, CopyingBaseSubobject, 14205 Copying, Depth + 1); 14206 // Bail out if copying fails or if we determined that we should use memcpy. 14207 if (Copy.isInvalid() || !Copy.get()) 14208 return Copy; 14209 14210 // Create the comparison against the array bound. 14211 llvm::APInt Upper 14212 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 14213 Expr *Comparison = BinaryOperator::Create( 14214 S.Context, IterationVarRefRVal.build(S, Loc), 14215 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE, 14216 S.Context.BoolTy, VK_PRValue, OK_Ordinary, Loc, 14217 S.CurFPFeatureOverrides()); 14218 14219 // Create the pre-increment of the iteration variable. We can determine 14220 // whether the increment will overflow based on the value of the array 14221 // bound. 14222 Expr *Increment = UnaryOperator::Create( 14223 S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue, 14224 OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides()); 14225 14226 // Construct the loop that copies all elements of this array. 14227 return S.ActOnForStmt( 14228 Loc, Loc, InitStmt, 14229 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean), 14230 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get()); 14231 } 14232 14233 static StmtResult 14234 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 14235 const ExprBuilder &To, const ExprBuilder &From, 14236 bool CopyingBaseSubobject, bool Copying) { 14237 // Maybe we should use a memcpy? 14238 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 14239 T.isTriviallyCopyableType(S.Context)) 14240 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 14241 14242 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 14243 CopyingBaseSubobject, 14244 Copying, 0)); 14245 14246 // If we ended up picking a trivial assignment operator for an array of a 14247 // non-trivially-copyable class type, just emit a memcpy. 14248 if (!Result.isInvalid() && !Result.get()) 14249 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 14250 14251 return Result; 14252 } 14253 14254 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 14255 // Note: The following rules are largely analoguous to the copy 14256 // constructor rules. Note that virtual bases are not taken into account 14257 // for determining the argument type of the operator. Note also that 14258 // operators taking an object instead of a reference are allowed. 14259 assert(ClassDecl->needsImplicitCopyAssignment()); 14260 14261 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 14262 if (DSM.isAlreadyBeingDeclared()) 14263 return nullptr; 14264 14265 QualType ArgType = Context.getTypeDeclType(ClassDecl); 14266 LangAS AS = getDefaultCXXMethodAddrSpace(); 14267 if (AS != LangAS::Default) 14268 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 14269 QualType RetType = Context.getLValueReferenceType(ArgType); 14270 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 14271 if (Const) 14272 ArgType = ArgType.withConst(); 14273 14274 ArgType = Context.getLValueReferenceType(ArgType); 14275 14276 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14277 CXXCopyAssignment, 14278 Const); 14279 14280 // An implicitly-declared copy assignment operator is an inline public 14281 // member of its class. 14282 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 14283 SourceLocation ClassLoc = ClassDecl->getLocation(); 14284 DeclarationNameInfo NameInfo(Name, ClassLoc); 14285 CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create( 14286 Context, ClassDecl, ClassLoc, NameInfo, QualType(), 14287 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 14288 getCurFPFeatures().isFPConstrained(), 14289 /*isInline=*/true, 14290 Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified, 14291 SourceLocation()); 14292 CopyAssignment->setAccess(AS_public); 14293 CopyAssignment->setDefaulted(); 14294 CopyAssignment->setImplicit(); 14295 14296 if (getLangOpts().CUDA) { 14297 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 14298 CopyAssignment, 14299 /* ConstRHS */ Const, 14300 /* Diagnose */ false); 14301 } 14302 14303 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType); 14304 14305 // Add the parameter to the operator. 14306 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 14307 ClassLoc, ClassLoc, 14308 /*Id=*/nullptr, ArgType, 14309 /*TInfo=*/nullptr, SC_None, 14310 nullptr); 14311 CopyAssignment->setParams(FromParam); 14312 14313 CopyAssignment->setTrivial( 14314 ClassDecl->needsOverloadResolutionForCopyAssignment() 14315 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 14316 : ClassDecl->hasTrivialCopyAssignment()); 14317 14318 // Note that we have added this copy-assignment operator. 14319 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared; 14320 14321 Scope *S = getScopeForContext(ClassDecl); 14322 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment); 14323 14324 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) { 14325 ClassDecl->setImplicitCopyAssignmentIsDeleted(); 14326 SetDeclDeleted(CopyAssignment, ClassLoc); 14327 } 14328 14329 if (S) 14330 PushOnScopeChains(CopyAssignment, S, false); 14331 ClassDecl->addDecl(CopyAssignment); 14332 14333 return CopyAssignment; 14334 } 14335 14336 /// Diagnose an implicit copy operation for a class which is odr-used, but 14337 /// which is deprecated because the class has a user-declared copy constructor, 14338 /// copy assignment operator, or destructor. 14339 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) { 14340 assert(CopyOp->isImplicit()); 14341 14342 CXXRecordDecl *RD = CopyOp->getParent(); 14343 CXXMethodDecl *UserDeclaredOperation = nullptr; 14344 14345 // In Microsoft mode, assignment operations don't affect constructors and 14346 // vice versa. 14347 if (RD->hasUserDeclaredDestructor()) { 14348 UserDeclaredOperation = RD->getDestructor(); 14349 } else if (!isa<CXXConstructorDecl>(CopyOp) && 14350 RD->hasUserDeclaredCopyConstructor() && 14351 !S.getLangOpts().MSVCCompat) { 14352 // Find any user-declared copy constructor. 14353 for (auto *I : RD->ctors()) { 14354 if (I->isCopyConstructor()) { 14355 UserDeclaredOperation = I; 14356 break; 14357 } 14358 } 14359 assert(UserDeclaredOperation); 14360 } else if (isa<CXXConstructorDecl>(CopyOp) && 14361 RD->hasUserDeclaredCopyAssignment() && 14362 !S.getLangOpts().MSVCCompat) { 14363 // Find any user-declared move assignment operator. 14364 for (auto *I : RD->methods()) { 14365 if (I->isCopyAssignmentOperator()) { 14366 UserDeclaredOperation = I; 14367 break; 14368 } 14369 } 14370 assert(UserDeclaredOperation); 14371 } 14372 14373 if (UserDeclaredOperation) { 14374 bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided(); 14375 bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation); 14376 bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp); 14377 unsigned DiagID = 14378 (UDOIsUserProvided && UDOIsDestructor) 14379 ? diag::warn_deprecated_copy_with_user_provided_dtor 14380 : (UDOIsUserProvided && !UDOIsDestructor) 14381 ? diag::warn_deprecated_copy_with_user_provided_copy 14382 : (!UDOIsUserProvided && UDOIsDestructor) 14383 ? diag::warn_deprecated_copy_with_dtor 14384 : diag::warn_deprecated_copy; 14385 S.Diag(UserDeclaredOperation->getLocation(), DiagID) 14386 << RD << IsCopyAssignment; 14387 } 14388 } 14389 14390 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 14391 CXXMethodDecl *CopyAssignOperator) { 14392 assert((CopyAssignOperator->isDefaulted() && 14393 CopyAssignOperator->isOverloadedOperator() && 14394 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 14395 !CopyAssignOperator->doesThisDeclarationHaveABody() && 14396 !CopyAssignOperator->isDeleted()) && 14397 "DefineImplicitCopyAssignment called for wrong function"); 14398 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl()) 14399 return; 14400 14401 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 14402 if (ClassDecl->isInvalidDecl()) { 14403 CopyAssignOperator->setInvalidDecl(); 14404 return; 14405 } 14406 14407 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 14408 14409 // The exception specification is needed because we are defining the 14410 // function. 14411 ResolveExceptionSpec(CurrentLocation, 14412 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 14413 14414 // Add a context note for diagnostics produced after this point. 14415 Scope.addContextNote(CurrentLocation); 14416 14417 // C++11 [class.copy]p18: 14418 // The [definition of an implicitly declared copy assignment operator] is 14419 // deprecated if the class has a user-declared copy constructor or a 14420 // user-declared destructor. 14421 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 14422 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator); 14423 14424 // C++0x [class.copy]p30: 14425 // The implicitly-defined or explicitly-defaulted copy assignment operator 14426 // for a non-union class X performs memberwise copy assignment of its 14427 // subobjects. The direct base classes of X are assigned first, in the 14428 // order of their declaration in the base-specifier-list, and then the 14429 // immediate non-static data members of X are assigned, in the order in 14430 // which they were declared in the class definition. 14431 14432 // The statements that form the synthesized function body. 14433 SmallVector<Stmt*, 8> Statements; 14434 14435 // The parameter for the "other" object, which we are copying from. 14436 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 14437 Qualifiers OtherQuals = Other->getType().getQualifiers(); 14438 QualType OtherRefType = Other->getType(); 14439 if (const LValueReferenceType *OtherRef 14440 = OtherRefType->getAs<LValueReferenceType>()) { 14441 OtherRefType = OtherRef->getPointeeType(); 14442 OtherQuals = OtherRefType.getQualifiers(); 14443 } 14444 14445 // Our location for everything implicitly-generated. 14446 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid() 14447 ? CopyAssignOperator->getEndLoc() 14448 : CopyAssignOperator->getLocation(); 14449 14450 // Builds a DeclRefExpr for the "other" object. 14451 RefBuilder OtherRef(Other, OtherRefType); 14452 14453 // Builds the "this" pointer. 14454 ThisBuilder This; 14455 14456 // Assign base classes. 14457 bool Invalid = false; 14458 for (auto &Base : ClassDecl->bases()) { 14459 // Form the assignment: 14460 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 14461 QualType BaseType = Base.getType().getUnqualifiedType(); 14462 if (!BaseType->isRecordType()) { 14463 Invalid = true; 14464 continue; 14465 } 14466 14467 CXXCastPath BasePath; 14468 BasePath.push_back(&Base); 14469 14470 // Construct the "from" expression, which is an implicit cast to the 14471 // appropriately-qualified base type. 14472 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 14473 VK_LValue, BasePath); 14474 14475 // Dereference "this". 14476 DerefBuilder DerefThis(This); 14477 CastBuilder To(DerefThis, 14478 Context.getQualifiedType( 14479 BaseType, CopyAssignOperator->getMethodQualifiers()), 14480 VK_LValue, BasePath); 14481 14482 // Build the copy. 14483 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 14484 To, From, 14485 /*CopyingBaseSubobject=*/true, 14486 /*Copying=*/true); 14487 if (Copy.isInvalid()) { 14488 CopyAssignOperator->setInvalidDecl(); 14489 return; 14490 } 14491 14492 // Success! Record the copy. 14493 Statements.push_back(Copy.getAs<Expr>()); 14494 } 14495 14496 // Assign non-static members. 14497 for (auto *Field : ClassDecl->fields()) { 14498 // FIXME: We should form some kind of AST representation for the implied 14499 // memcpy in a union copy operation. 14500 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 14501 continue; 14502 14503 if (Field->isInvalidDecl()) { 14504 Invalid = true; 14505 continue; 14506 } 14507 14508 // Check for members of reference type; we can't copy those. 14509 if (Field->getType()->isReferenceType()) { 14510 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14511 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 14512 Diag(Field->getLocation(), diag::note_declared_at); 14513 Invalid = true; 14514 continue; 14515 } 14516 14517 // Check for members of const-qualified, non-class type. 14518 QualType BaseType = Context.getBaseElementType(Field->getType()); 14519 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 14520 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14521 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 14522 Diag(Field->getLocation(), diag::note_declared_at); 14523 Invalid = true; 14524 continue; 14525 } 14526 14527 // Suppress assigning zero-width bitfields. 14528 if (Field->isZeroLengthBitField(Context)) 14529 continue; 14530 14531 QualType FieldType = Field->getType().getNonReferenceType(); 14532 if (FieldType->isIncompleteArrayType()) { 14533 assert(ClassDecl->hasFlexibleArrayMember() && 14534 "Incomplete array type is not valid"); 14535 continue; 14536 } 14537 14538 // Build references to the field in the object we're copying from and to. 14539 CXXScopeSpec SS; // Intentionally empty 14540 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 14541 LookupMemberName); 14542 MemberLookup.addDecl(Field); 14543 MemberLookup.resolveKind(); 14544 14545 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 14546 14547 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 14548 14549 // Build the copy of this field. 14550 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 14551 To, From, 14552 /*CopyingBaseSubobject=*/false, 14553 /*Copying=*/true); 14554 if (Copy.isInvalid()) { 14555 CopyAssignOperator->setInvalidDecl(); 14556 return; 14557 } 14558 14559 // Success! Record the copy. 14560 Statements.push_back(Copy.getAs<Stmt>()); 14561 } 14562 14563 if (!Invalid) { 14564 // Add a "return *this;" 14565 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 14566 14567 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 14568 if (Return.isInvalid()) 14569 Invalid = true; 14570 else 14571 Statements.push_back(Return.getAs<Stmt>()); 14572 } 14573 14574 if (Invalid) { 14575 CopyAssignOperator->setInvalidDecl(); 14576 return; 14577 } 14578 14579 StmtResult Body; 14580 { 14581 CompoundScopeRAII CompoundScope(*this); 14582 Body = ActOnCompoundStmt(Loc, Loc, Statements, 14583 /*isStmtExpr=*/false); 14584 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 14585 } 14586 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 14587 CopyAssignOperator->markUsed(Context); 14588 14589 if (ASTMutationListener *L = getASTMutationListener()) { 14590 L->CompletedImplicitDefinition(CopyAssignOperator); 14591 } 14592 } 14593 14594 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 14595 assert(ClassDecl->needsImplicitMoveAssignment()); 14596 14597 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 14598 if (DSM.isAlreadyBeingDeclared()) 14599 return nullptr; 14600 14601 // Note: The following rules are largely analoguous to the move 14602 // constructor rules. 14603 14604 QualType ArgType = Context.getTypeDeclType(ClassDecl); 14605 LangAS AS = getDefaultCXXMethodAddrSpace(); 14606 if (AS != LangAS::Default) 14607 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 14608 QualType RetType = Context.getLValueReferenceType(ArgType); 14609 ArgType = Context.getRValueReferenceType(ArgType); 14610 14611 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14612 CXXMoveAssignment, 14613 false); 14614 14615 // An implicitly-declared move assignment operator is an inline public 14616 // member of its class. 14617 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 14618 SourceLocation ClassLoc = ClassDecl->getLocation(); 14619 DeclarationNameInfo NameInfo(Name, ClassLoc); 14620 CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create( 14621 Context, ClassDecl, ClassLoc, NameInfo, QualType(), 14622 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 14623 getCurFPFeatures().isFPConstrained(), 14624 /*isInline=*/true, 14625 Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified, 14626 SourceLocation()); 14627 MoveAssignment->setAccess(AS_public); 14628 MoveAssignment->setDefaulted(); 14629 MoveAssignment->setImplicit(); 14630 14631 if (getLangOpts().CUDA) { 14632 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 14633 MoveAssignment, 14634 /* ConstRHS */ false, 14635 /* Diagnose */ false); 14636 } 14637 14638 setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType); 14639 14640 // Add the parameter to the operator. 14641 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 14642 ClassLoc, ClassLoc, 14643 /*Id=*/nullptr, ArgType, 14644 /*TInfo=*/nullptr, SC_None, 14645 nullptr); 14646 MoveAssignment->setParams(FromParam); 14647 14648 MoveAssignment->setTrivial( 14649 ClassDecl->needsOverloadResolutionForMoveAssignment() 14650 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 14651 : ClassDecl->hasTrivialMoveAssignment()); 14652 14653 // Note that we have added this copy-assignment operator. 14654 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared; 14655 14656 Scope *S = getScopeForContext(ClassDecl); 14657 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment); 14658 14659 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 14660 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 14661 SetDeclDeleted(MoveAssignment, ClassLoc); 14662 } 14663 14664 if (S) 14665 PushOnScopeChains(MoveAssignment, S, false); 14666 ClassDecl->addDecl(MoveAssignment); 14667 14668 return MoveAssignment; 14669 } 14670 14671 /// Check if we're implicitly defining a move assignment operator for a class 14672 /// with virtual bases. Such a move assignment might move-assign the virtual 14673 /// base multiple times. 14674 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 14675 SourceLocation CurrentLocation) { 14676 assert(!Class->isDependentContext() && "should not define dependent move"); 14677 14678 // Only a virtual base could get implicitly move-assigned multiple times. 14679 // Only a non-trivial move assignment can observe this. We only want to 14680 // diagnose if we implicitly define an assignment operator that assigns 14681 // two base classes, both of which move-assign the same virtual base. 14682 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 14683 Class->getNumBases() < 2) 14684 return; 14685 14686 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 14687 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 14688 VBaseMap VBases; 14689 14690 for (auto &BI : Class->bases()) { 14691 Worklist.push_back(&BI); 14692 while (!Worklist.empty()) { 14693 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 14694 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 14695 14696 // If the base has no non-trivial move assignment operators, 14697 // we don't care about moves from it. 14698 if (!Base->hasNonTrivialMoveAssignment()) 14699 continue; 14700 14701 // If there's nothing virtual here, skip it. 14702 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 14703 continue; 14704 14705 // If we're not actually going to call a move assignment for this base, 14706 // or the selected move assignment is trivial, skip it. 14707 Sema::SpecialMemberOverloadResult SMOR = 14708 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 14709 /*ConstArg*/false, /*VolatileArg*/false, 14710 /*RValueThis*/true, /*ConstThis*/false, 14711 /*VolatileThis*/false); 14712 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() || 14713 !SMOR.getMethod()->isMoveAssignmentOperator()) 14714 continue; 14715 14716 if (BaseSpec->isVirtual()) { 14717 // We're going to move-assign this virtual base, and its move 14718 // assignment operator is not trivial. If this can happen for 14719 // multiple distinct direct bases of Class, diagnose it. (If it 14720 // only happens in one base, we'll diagnose it when synthesizing 14721 // that base class's move assignment operator.) 14722 CXXBaseSpecifier *&Existing = 14723 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 14724 .first->second; 14725 if (Existing && Existing != &BI) { 14726 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 14727 << Class << Base; 14728 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here) 14729 << (Base->getCanonicalDecl() == 14730 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 14731 << Base << Existing->getType() << Existing->getSourceRange(); 14732 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here) 14733 << (Base->getCanonicalDecl() == 14734 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 14735 << Base << BI.getType() << BaseSpec->getSourceRange(); 14736 14737 // Only diagnose each vbase once. 14738 Existing = nullptr; 14739 } 14740 } else { 14741 // Only walk over bases that have defaulted move assignment operators. 14742 // We assume that any user-provided move assignment operator handles 14743 // the multiple-moves-of-vbase case itself somehow. 14744 if (!SMOR.getMethod()->isDefaulted()) 14745 continue; 14746 14747 // We're going to move the base classes of Base. Add them to the list. 14748 for (auto &BI : Base->bases()) 14749 Worklist.push_back(&BI); 14750 } 14751 } 14752 } 14753 } 14754 14755 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 14756 CXXMethodDecl *MoveAssignOperator) { 14757 assert((MoveAssignOperator->isDefaulted() && 14758 MoveAssignOperator->isOverloadedOperator() && 14759 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 14760 !MoveAssignOperator->doesThisDeclarationHaveABody() && 14761 !MoveAssignOperator->isDeleted()) && 14762 "DefineImplicitMoveAssignment called for wrong function"); 14763 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl()) 14764 return; 14765 14766 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 14767 if (ClassDecl->isInvalidDecl()) { 14768 MoveAssignOperator->setInvalidDecl(); 14769 return; 14770 } 14771 14772 // C++0x [class.copy]p28: 14773 // The implicitly-defined or move assignment operator for a non-union class 14774 // X performs memberwise move assignment of its subobjects. The direct base 14775 // classes of X are assigned first, in the order of their declaration in the 14776 // base-specifier-list, and then the immediate non-static data members of X 14777 // are assigned, in the order in which they were declared in the class 14778 // definition. 14779 14780 // Issue a warning if our implicit move assignment operator will move 14781 // from a virtual base more than once. 14782 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 14783 14784 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 14785 14786 // The exception specification is needed because we are defining the 14787 // function. 14788 ResolveExceptionSpec(CurrentLocation, 14789 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 14790 14791 // Add a context note for diagnostics produced after this point. 14792 Scope.addContextNote(CurrentLocation); 14793 14794 // The statements that form the synthesized function body. 14795 SmallVector<Stmt*, 8> Statements; 14796 14797 // The parameter for the "other" object, which we are move from. 14798 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 14799 QualType OtherRefType = 14800 Other->getType()->castAs<RValueReferenceType>()->getPointeeType(); 14801 14802 // Our location for everything implicitly-generated. 14803 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid() 14804 ? MoveAssignOperator->getEndLoc() 14805 : MoveAssignOperator->getLocation(); 14806 14807 // Builds a reference to the "other" object. 14808 RefBuilder OtherRef(Other, OtherRefType); 14809 // Cast to rvalue. 14810 MoveCastBuilder MoveOther(OtherRef); 14811 14812 // Builds the "this" pointer. 14813 ThisBuilder This; 14814 14815 // Assign base classes. 14816 bool Invalid = false; 14817 for (auto &Base : ClassDecl->bases()) { 14818 // C++11 [class.copy]p28: 14819 // It is unspecified whether subobjects representing virtual base classes 14820 // are assigned more than once by the implicitly-defined copy assignment 14821 // operator. 14822 // FIXME: Do not assign to a vbase that will be assigned by some other base 14823 // class. For a move-assignment, this can result in the vbase being moved 14824 // multiple times. 14825 14826 // Form the assignment: 14827 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 14828 QualType BaseType = Base.getType().getUnqualifiedType(); 14829 if (!BaseType->isRecordType()) { 14830 Invalid = true; 14831 continue; 14832 } 14833 14834 CXXCastPath BasePath; 14835 BasePath.push_back(&Base); 14836 14837 // Construct the "from" expression, which is an implicit cast to the 14838 // appropriately-qualified base type. 14839 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 14840 14841 // Dereference "this". 14842 DerefBuilder DerefThis(This); 14843 14844 // Implicitly cast "this" to the appropriately-qualified base type. 14845 CastBuilder To(DerefThis, 14846 Context.getQualifiedType( 14847 BaseType, MoveAssignOperator->getMethodQualifiers()), 14848 VK_LValue, BasePath); 14849 14850 // Build the move. 14851 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 14852 To, From, 14853 /*CopyingBaseSubobject=*/true, 14854 /*Copying=*/false); 14855 if (Move.isInvalid()) { 14856 MoveAssignOperator->setInvalidDecl(); 14857 return; 14858 } 14859 14860 // Success! Record the move. 14861 Statements.push_back(Move.getAs<Expr>()); 14862 } 14863 14864 // Assign non-static members. 14865 for (auto *Field : ClassDecl->fields()) { 14866 // FIXME: We should form some kind of AST representation for the implied 14867 // memcpy in a union copy operation. 14868 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 14869 continue; 14870 14871 if (Field->isInvalidDecl()) { 14872 Invalid = true; 14873 continue; 14874 } 14875 14876 // Check for members of reference type; we can't move those. 14877 if (Field->getType()->isReferenceType()) { 14878 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14879 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 14880 Diag(Field->getLocation(), diag::note_declared_at); 14881 Invalid = true; 14882 continue; 14883 } 14884 14885 // Check for members of const-qualified, non-class type. 14886 QualType BaseType = Context.getBaseElementType(Field->getType()); 14887 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 14888 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14889 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 14890 Diag(Field->getLocation(), diag::note_declared_at); 14891 Invalid = true; 14892 continue; 14893 } 14894 14895 // Suppress assigning zero-width bitfields. 14896 if (Field->isZeroLengthBitField(Context)) 14897 continue; 14898 14899 QualType FieldType = Field->getType().getNonReferenceType(); 14900 if (FieldType->isIncompleteArrayType()) { 14901 assert(ClassDecl->hasFlexibleArrayMember() && 14902 "Incomplete array type is not valid"); 14903 continue; 14904 } 14905 14906 // Build references to the field in the object we're copying from and to. 14907 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 14908 LookupMemberName); 14909 MemberLookup.addDecl(Field); 14910 MemberLookup.resolveKind(); 14911 MemberBuilder From(MoveOther, OtherRefType, 14912 /*IsArrow=*/false, MemberLookup); 14913 MemberBuilder To(This, getCurrentThisType(), 14914 /*IsArrow=*/true, MemberLookup); 14915 14916 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 14917 "Member reference with rvalue base must be rvalue except for reference " 14918 "members, which aren't allowed for move assignment."); 14919 14920 // Build the move of this field. 14921 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 14922 To, From, 14923 /*CopyingBaseSubobject=*/false, 14924 /*Copying=*/false); 14925 if (Move.isInvalid()) { 14926 MoveAssignOperator->setInvalidDecl(); 14927 return; 14928 } 14929 14930 // Success! Record the copy. 14931 Statements.push_back(Move.getAs<Stmt>()); 14932 } 14933 14934 if (!Invalid) { 14935 // Add a "return *this;" 14936 ExprResult ThisObj = 14937 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 14938 14939 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 14940 if (Return.isInvalid()) 14941 Invalid = true; 14942 else 14943 Statements.push_back(Return.getAs<Stmt>()); 14944 } 14945 14946 if (Invalid) { 14947 MoveAssignOperator->setInvalidDecl(); 14948 return; 14949 } 14950 14951 StmtResult Body; 14952 { 14953 CompoundScopeRAII CompoundScope(*this); 14954 Body = ActOnCompoundStmt(Loc, Loc, Statements, 14955 /*isStmtExpr=*/false); 14956 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 14957 } 14958 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 14959 MoveAssignOperator->markUsed(Context); 14960 14961 if (ASTMutationListener *L = getASTMutationListener()) { 14962 L->CompletedImplicitDefinition(MoveAssignOperator); 14963 } 14964 } 14965 14966 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 14967 CXXRecordDecl *ClassDecl) { 14968 // C++ [class.copy]p4: 14969 // If the class definition does not explicitly declare a copy 14970 // constructor, one is declared implicitly. 14971 assert(ClassDecl->needsImplicitCopyConstructor()); 14972 14973 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 14974 if (DSM.isAlreadyBeingDeclared()) 14975 return nullptr; 14976 14977 QualType ClassType = Context.getTypeDeclType(ClassDecl); 14978 QualType ArgType = ClassType; 14979 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 14980 if (Const) 14981 ArgType = ArgType.withConst(); 14982 14983 LangAS AS = getDefaultCXXMethodAddrSpace(); 14984 if (AS != LangAS::Default) 14985 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 14986 14987 ArgType = Context.getLValueReferenceType(ArgType); 14988 14989 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14990 CXXCopyConstructor, 14991 Const); 14992 14993 DeclarationName Name 14994 = Context.DeclarationNames.getCXXConstructorName( 14995 Context.getCanonicalType(ClassType)); 14996 SourceLocation ClassLoc = ClassDecl->getLocation(); 14997 DeclarationNameInfo NameInfo(Name, ClassLoc); 14998 14999 // An implicitly-declared copy constructor is an inline public 15000 // member of its class. 15001 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 15002 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 15003 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(), 15004 /*isInline=*/true, 15005 /*isImplicitlyDeclared=*/true, 15006 Constexpr ? ConstexprSpecKind::Constexpr 15007 : ConstexprSpecKind::Unspecified); 15008 CopyConstructor->setAccess(AS_public); 15009 CopyConstructor->setDefaulted(); 15010 15011 if (getLangOpts().CUDA) { 15012 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 15013 CopyConstructor, 15014 /* ConstRHS */ Const, 15015 /* Diagnose */ false); 15016 } 15017 15018 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType); 15019 15020 // During template instantiation of special member functions we need a 15021 // reliable TypeSourceInfo for the parameter types in order to allow functions 15022 // to be substituted. 15023 TypeSourceInfo *TSI = nullptr; 15024 if (inTemplateInstantiation() && ClassDecl->isLambda()) 15025 TSI = Context.getTrivialTypeSourceInfo(ArgType); 15026 15027 // Add the parameter to the constructor. 15028 ParmVarDecl *FromParam = 15029 ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc, 15030 /*IdentifierInfo=*/nullptr, ArgType, 15031 /*TInfo=*/TSI, SC_None, nullptr); 15032 CopyConstructor->setParams(FromParam); 15033 15034 CopyConstructor->setTrivial( 15035 ClassDecl->needsOverloadResolutionForCopyConstructor() 15036 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 15037 : ClassDecl->hasTrivialCopyConstructor()); 15038 15039 CopyConstructor->setTrivialForCall( 15040 ClassDecl->hasAttr<TrivialABIAttr>() || 15041 (ClassDecl->needsOverloadResolutionForCopyConstructor() 15042 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor, 15043 TAH_ConsiderTrivialABI) 15044 : ClassDecl->hasTrivialCopyConstructorForCall())); 15045 15046 // Note that we have declared this constructor. 15047 ++getASTContext().NumImplicitCopyConstructorsDeclared; 15048 15049 Scope *S = getScopeForContext(ClassDecl); 15050 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor); 15051 15052 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) { 15053 ClassDecl->setImplicitCopyConstructorIsDeleted(); 15054 SetDeclDeleted(CopyConstructor, ClassLoc); 15055 } 15056 15057 if (S) 15058 PushOnScopeChains(CopyConstructor, S, false); 15059 ClassDecl->addDecl(CopyConstructor); 15060 15061 return CopyConstructor; 15062 } 15063 15064 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 15065 CXXConstructorDecl *CopyConstructor) { 15066 assert((CopyConstructor->isDefaulted() && 15067 CopyConstructor->isCopyConstructor() && 15068 !CopyConstructor->doesThisDeclarationHaveABody() && 15069 !CopyConstructor->isDeleted()) && 15070 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 15071 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl()) 15072 return; 15073 15074 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 15075 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 15076 15077 SynthesizedFunctionScope Scope(*this, CopyConstructor); 15078 15079 // The exception specification is needed because we are defining the 15080 // function. 15081 ResolveExceptionSpec(CurrentLocation, 15082 CopyConstructor->getType()->castAs<FunctionProtoType>()); 15083 MarkVTableUsed(CurrentLocation, ClassDecl); 15084 15085 // Add a context note for diagnostics produced after this point. 15086 Scope.addContextNote(CurrentLocation); 15087 15088 // C++11 [class.copy]p7: 15089 // The [definition of an implicitly declared copy constructor] is 15090 // deprecated if the class has a user-declared copy assignment operator 15091 // or a user-declared destructor. 15092 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 15093 diagnoseDeprecatedCopyOperation(*this, CopyConstructor); 15094 15095 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) { 15096 CopyConstructor->setInvalidDecl(); 15097 } else { 15098 SourceLocation Loc = CopyConstructor->getEndLoc().isValid() 15099 ? CopyConstructor->getEndLoc() 15100 : CopyConstructor->getLocation(); 15101 Sema::CompoundScopeRAII CompoundScope(*this); 15102 CopyConstructor->setBody( 15103 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 15104 CopyConstructor->markUsed(Context); 15105 } 15106 15107 if (ASTMutationListener *L = getASTMutationListener()) { 15108 L->CompletedImplicitDefinition(CopyConstructor); 15109 } 15110 } 15111 15112 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 15113 CXXRecordDecl *ClassDecl) { 15114 assert(ClassDecl->needsImplicitMoveConstructor()); 15115 15116 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 15117 if (DSM.isAlreadyBeingDeclared()) 15118 return nullptr; 15119 15120 QualType ClassType = Context.getTypeDeclType(ClassDecl); 15121 15122 QualType ArgType = ClassType; 15123 LangAS AS = getDefaultCXXMethodAddrSpace(); 15124 if (AS != LangAS::Default) 15125 ArgType = Context.getAddrSpaceQualType(ClassType, AS); 15126 ArgType = Context.getRValueReferenceType(ArgType); 15127 15128 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 15129 CXXMoveConstructor, 15130 false); 15131 15132 DeclarationName Name 15133 = Context.DeclarationNames.getCXXConstructorName( 15134 Context.getCanonicalType(ClassType)); 15135 SourceLocation ClassLoc = ClassDecl->getLocation(); 15136 DeclarationNameInfo NameInfo(Name, ClassLoc); 15137 15138 // C++11 [class.copy]p11: 15139 // An implicitly-declared copy/move constructor is an inline public 15140 // member of its class. 15141 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 15142 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 15143 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(), 15144 /*isInline=*/true, 15145 /*isImplicitlyDeclared=*/true, 15146 Constexpr ? ConstexprSpecKind::Constexpr 15147 : ConstexprSpecKind::Unspecified); 15148 MoveConstructor->setAccess(AS_public); 15149 MoveConstructor->setDefaulted(); 15150 15151 if (getLangOpts().CUDA) { 15152 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 15153 MoveConstructor, 15154 /* ConstRHS */ false, 15155 /* Diagnose */ false); 15156 } 15157 15158 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType); 15159 15160 // Add the parameter to the constructor. 15161 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 15162 ClassLoc, ClassLoc, 15163 /*IdentifierInfo=*/nullptr, 15164 ArgType, /*TInfo=*/nullptr, 15165 SC_None, nullptr); 15166 MoveConstructor->setParams(FromParam); 15167 15168 MoveConstructor->setTrivial( 15169 ClassDecl->needsOverloadResolutionForMoveConstructor() 15170 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 15171 : ClassDecl->hasTrivialMoveConstructor()); 15172 15173 MoveConstructor->setTrivialForCall( 15174 ClassDecl->hasAttr<TrivialABIAttr>() || 15175 (ClassDecl->needsOverloadResolutionForMoveConstructor() 15176 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor, 15177 TAH_ConsiderTrivialABI) 15178 : ClassDecl->hasTrivialMoveConstructorForCall())); 15179 15180 // Note that we have declared this constructor. 15181 ++getASTContext().NumImplicitMoveConstructorsDeclared; 15182 15183 Scope *S = getScopeForContext(ClassDecl); 15184 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor); 15185 15186 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 15187 ClassDecl->setImplicitMoveConstructorIsDeleted(); 15188 SetDeclDeleted(MoveConstructor, ClassLoc); 15189 } 15190 15191 if (S) 15192 PushOnScopeChains(MoveConstructor, S, false); 15193 ClassDecl->addDecl(MoveConstructor); 15194 15195 return MoveConstructor; 15196 } 15197 15198 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 15199 CXXConstructorDecl *MoveConstructor) { 15200 assert((MoveConstructor->isDefaulted() && 15201 MoveConstructor->isMoveConstructor() && 15202 !MoveConstructor->doesThisDeclarationHaveABody() && 15203 !MoveConstructor->isDeleted()) && 15204 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 15205 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl()) 15206 return; 15207 15208 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 15209 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 15210 15211 SynthesizedFunctionScope Scope(*this, MoveConstructor); 15212 15213 // The exception specification is needed because we are defining the 15214 // function. 15215 ResolveExceptionSpec(CurrentLocation, 15216 MoveConstructor->getType()->castAs<FunctionProtoType>()); 15217 MarkVTableUsed(CurrentLocation, ClassDecl); 15218 15219 // Add a context note for diagnostics produced after this point. 15220 Scope.addContextNote(CurrentLocation); 15221 15222 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) { 15223 MoveConstructor->setInvalidDecl(); 15224 } else { 15225 SourceLocation Loc = MoveConstructor->getEndLoc().isValid() 15226 ? MoveConstructor->getEndLoc() 15227 : MoveConstructor->getLocation(); 15228 Sema::CompoundScopeRAII CompoundScope(*this); 15229 MoveConstructor->setBody(ActOnCompoundStmt( 15230 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 15231 MoveConstructor->markUsed(Context); 15232 } 15233 15234 if (ASTMutationListener *L = getASTMutationListener()) { 15235 L->CompletedImplicitDefinition(MoveConstructor); 15236 } 15237 } 15238 15239 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 15240 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 15241 } 15242 15243 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 15244 SourceLocation CurrentLocation, 15245 CXXConversionDecl *Conv) { 15246 SynthesizedFunctionScope Scope(*this, Conv); 15247 assert(!Conv->getReturnType()->isUndeducedType()); 15248 15249 QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType(); 15250 CallingConv CC = 15251 ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv(); 15252 15253 CXXRecordDecl *Lambda = Conv->getParent(); 15254 FunctionDecl *CallOp = Lambda->getLambdaCallOperator(); 15255 FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(CC); 15256 15257 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) { 15258 CallOp = InstantiateFunctionDeclaration( 15259 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 15260 if (!CallOp) 15261 return; 15262 15263 Invoker = InstantiateFunctionDeclaration( 15264 Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 15265 if (!Invoker) 15266 return; 15267 } 15268 15269 if (CallOp->isInvalidDecl()) 15270 return; 15271 15272 // Mark the call operator referenced (and add to pending instantiations 15273 // if necessary). 15274 // For both the conversion and static-invoker template specializations 15275 // we construct their body's in this function, so no need to add them 15276 // to the PendingInstantiations. 15277 MarkFunctionReferenced(CurrentLocation, CallOp); 15278 15279 // Fill in the __invoke function with a dummy implementation. IR generation 15280 // will fill in the actual details. Update its type in case it contained 15281 // an 'auto'. 15282 Invoker->markUsed(Context); 15283 Invoker->setReferenced(); 15284 Invoker->setType(Conv->getReturnType()->getPointeeType()); 15285 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 15286 15287 // Construct the body of the conversion function { return __invoke; }. 15288 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 15289 VK_LValue, Conv->getLocation()); 15290 assert(FunctionRef && "Can't refer to __invoke function?"); 15291 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 15292 Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(), 15293 Conv->getLocation())); 15294 Conv->markUsed(Context); 15295 Conv->setReferenced(); 15296 15297 if (ASTMutationListener *L = getASTMutationListener()) { 15298 L->CompletedImplicitDefinition(Conv); 15299 L->CompletedImplicitDefinition(Invoker); 15300 } 15301 } 15302 15303 15304 15305 void Sema::DefineImplicitLambdaToBlockPointerConversion( 15306 SourceLocation CurrentLocation, 15307 CXXConversionDecl *Conv) 15308 { 15309 assert(!Conv->getParent()->isGenericLambda()); 15310 15311 SynthesizedFunctionScope Scope(*this, Conv); 15312 15313 // Copy-initialize the lambda object as needed to capture it. 15314 Expr *This = ActOnCXXThis(CurrentLocation).get(); 15315 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 15316 15317 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 15318 Conv->getLocation(), 15319 Conv, DerefThis); 15320 15321 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 15322 // behavior. Note that only the general conversion function does this 15323 // (since it's unusable otherwise); in the case where we inline the 15324 // block literal, it has block literal lifetime semantics. 15325 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 15326 BuildBlock = ImplicitCastExpr::Create( 15327 Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject, 15328 BuildBlock.get(), nullptr, VK_PRValue, FPOptionsOverride()); 15329 15330 if (BuildBlock.isInvalid()) { 15331 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 15332 Conv->setInvalidDecl(); 15333 return; 15334 } 15335 15336 // Create the return statement that returns the block from the conversion 15337 // function. 15338 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 15339 if (Return.isInvalid()) { 15340 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 15341 Conv->setInvalidDecl(); 15342 return; 15343 } 15344 15345 // Set the body of the conversion function. 15346 Stmt *ReturnS = Return.get(); 15347 Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(), 15348 Conv->getLocation())); 15349 Conv->markUsed(Context); 15350 15351 // We're done; notify the mutation listener, if any. 15352 if (ASTMutationListener *L = getASTMutationListener()) { 15353 L->CompletedImplicitDefinition(Conv); 15354 } 15355 } 15356 15357 /// Determine whether the given list arguments contains exactly one 15358 /// "real" (non-default) argument. 15359 static bool hasOneRealArgument(MultiExprArg Args) { 15360 switch (Args.size()) { 15361 case 0: 15362 return false; 15363 15364 default: 15365 if (!Args[1]->isDefaultArgument()) 15366 return false; 15367 15368 LLVM_FALLTHROUGH; 15369 case 1: 15370 return !Args[0]->isDefaultArgument(); 15371 } 15372 15373 return false; 15374 } 15375 15376 ExprResult 15377 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 15378 NamedDecl *FoundDecl, 15379 CXXConstructorDecl *Constructor, 15380 MultiExprArg ExprArgs, 15381 bool HadMultipleCandidates, 15382 bool IsListInitialization, 15383 bool IsStdInitListInitialization, 15384 bool RequiresZeroInit, 15385 unsigned ConstructKind, 15386 SourceRange ParenRange) { 15387 bool Elidable = false; 15388 15389 // C++0x [class.copy]p34: 15390 // When certain criteria are met, an implementation is allowed to 15391 // omit the copy/move construction of a class object, even if the 15392 // copy/move constructor and/or destructor for the object have 15393 // side effects. [...] 15394 // - when a temporary class object that has not been bound to a 15395 // reference (12.2) would be copied/moved to a class object 15396 // with the same cv-unqualified type, the copy/move operation 15397 // can be omitted by constructing the temporary object 15398 // directly into the target of the omitted copy/move 15399 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor && 15400 // FIXME: Converting constructors should also be accepted. 15401 // But to fix this, the logic that digs down into a CXXConstructExpr 15402 // to find the source object needs to handle it. 15403 // Right now it assumes the source object is passed directly as the 15404 // first argument. 15405 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 15406 Expr *SubExpr = ExprArgs[0]; 15407 // FIXME: Per above, this is also incorrect if we want to accept 15408 // converting constructors, as isTemporaryObject will 15409 // reject temporaries with different type from the 15410 // CXXRecord itself. 15411 Elidable = SubExpr->isTemporaryObject( 15412 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 15413 } 15414 15415 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, 15416 FoundDecl, Constructor, 15417 Elidable, ExprArgs, HadMultipleCandidates, 15418 IsListInitialization, 15419 IsStdInitListInitialization, RequiresZeroInit, 15420 ConstructKind, ParenRange); 15421 } 15422 15423 ExprResult 15424 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 15425 NamedDecl *FoundDecl, 15426 CXXConstructorDecl *Constructor, 15427 bool Elidable, 15428 MultiExprArg ExprArgs, 15429 bool HadMultipleCandidates, 15430 bool IsListInitialization, 15431 bool IsStdInitListInitialization, 15432 bool RequiresZeroInit, 15433 unsigned ConstructKind, 15434 SourceRange ParenRange) { 15435 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) { 15436 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow); 15437 if (DiagnoseUseOfDecl(Constructor, ConstructLoc)) 15438 return ExprError(); 15439 } 15440 15441 return BuildCXXConstructExpr( 15442 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs, 15443 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 15444 RequiresZeroInit, ConstructKind, ParenRange); 15445 } 15446 15447 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 15448 /// including handling of its default argument expressions. 15449 ExprResult 15450 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 15451 CXXConstructorDecl *Constructor, 15452 bool Elidable, 15453 MultiExprArg ExprArgs, 15454 bool HadMultipleCandidates, 15455 bool IsListInitialization, 15456 bool IsStdInitListInitialization, 15457 bool RequiresZeroInit, 15458 unsigned ConstructKind, 15459 SourceRange ParenRange) { 15460 assert(declaresSameEntity( 15461 Constructor->getParent(), 15462 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && 15463 "given constructor for wrong type"); 15464 MarkFunctionReferenced(ConstructLoc, Constructor); 15465 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor)) 15466 return ExprError(); 15467 if (getLangOpts().SYCLIsDevice && 15468 !checkSYCLDeviceFunction(ConstructLoc, Constructor)) 15469 return ExprError(); 15470 15471 return CheckForImmediateInvocation( 15472 CXXConstructExpr::Create( 15473 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs, 15474 HadMultipleCandidates, IsListInitialization, 15475 IsStdInitListInitialization, RequiresZeroInit, 15476 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 15477 ParenRange), 15478 Constructor); 15479 } 15480 15481 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 15482 assert(Field->hasInClassInitializer()); 15483 15484 // If we already have the in-class initializer nothing needs to be done. 15485 if (Field->getInClassInitializer()) 15486 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext); 15487 15488 // If we might have already tried and failed to instantiate, don't try again. 15489 if (Field->isInvalidDecl()) 15490 return ExprError(); 15491 15492 // Maybe we haven't instantiated the in-class initializer. Go check the 15493 // pattern FieldDecl to see if it has one. 15494 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 15495 15496 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 15497 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 15498 DeclContext::lookup_result Lookup = 15499 ClassPattern->lookup(Field->getDeclName()); 15500 15501 FieldDecl *Pattern = nullptr; 15502 for (auto L : Lookup) { 15503 if (isa<FieldDecl>(L)) { 15504 Pattern = cast<FieldDecl>(L); 15505 break; 15506 } 15507 } 15508 assert(Pattern && "We must have set the Pattern!"); 15509 15510 if (!Pattern->hasInClassInitializer() || 15511 InstantiateInClassInitializer(Loc, Field, Pattern, 15512 getTemplateInstantiationArgs(Field))) { 15513 // Don't diagnose this again. 15514 Field->setInvalidDecl(); 15515 return ExprError(); 15516 } 15517 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext); 15518 } 15519 15520 // DR1351: 15521 // If the brace-or-equal-initializer of a non-static data member 15522 // invokes a defaulted default constructor of its class or of an 15523 // enclosing class in a potentially evaluated subexpression, the 15524 // program is ill-formed. 15525 // 15526 // This resolution is unworkable: the exception specification of the 15527 // default constructor can be needed in an unevaluated context, in 15528 // particular, in the operand of a noexcept-expression, and we can be 15529 // unable to compute an exception specification for an enclosed class. 15530 // 15531 // Any attempt to resolve the exception specification of a defaulted default 15532 // constructor before the initializer is lexically complete will ultimately 15533 // come here at which point we can diagnose it. 15534 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 15535 Diag(Loc, diag::err_default_member_initializer_not_yet_parsed) 15536 << OutermostClass << Field; 15537 Diag(Field->getEndLoc(), 15538 diag::note_default_member_initializer_not_yet_parsed); 15539 // Recover by marking the field invalid, unless we're in a SFINAE context. 15540 if (!isSFINAEContext()) 15541 Field->setInvalidDecl(); 15542 return ExprError(); 15543 } 15544 15545 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 15546 if (VD->isInvalidDecl()) return; 15547 // If initializing the variable failed, don't also diagnose problems with 15548 // the destructor, they're likely related. 15549 if (VD->getInit() && VD->getInit()->containsErrors()) 15550 return; 15551 15552 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 15553 if (ClassDecl->isInvalidDecl()) return; 15554 if (ClassDecl->hasIrrelevantDestructor()) return; 15555 if (ClassDecl->isDependentContext()) return; 15556 15557 if (VD->isNoDestroy(getASTContext())) 15558 return; 15559 15560 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 15561 15562 // If this is an array, we'll require the destructor during initialization, so 15563 // we can skip over this. We still want to emit exit-time destructor warnings 15564 // though. 15565 if (!VD->getType()->isArrayType()) { 15566 MarkFunctionReferenced(VD->getLocation(), Destructor); 15567 CheckDestructorAccess(VD->getLocation(), Destructor, 15568 PDiag(diag::err_access_dtor_var) 15569 << VD->getDeclName() << VD->getType()); 15570 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 15571 } 15572 15573 if (Destructor->isTrivial()) return; 15574 15575 // If the destructor is constexpr, check whether the variable has constant 15576 // destruction now. 15577 if (Destructor->isConstexpr()) { 15578 bool HasConstantInit = false; 15579 if (VD->getInit() && !VD->getInit()->isValueDependent()) 15580 HasConstantInit = VD->evaluateValue(); 15581 SmallVector<PartialDiagnosticAt, 8> Notes; 15582 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() && 15583 HasConstantInit) { 15584 Diag(VD->getLocation(), 15585 diag::err_constexpr_var_requires_const_destruction) << VD; 15586 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 15587 Diag(Notes[I].first, Notes[I].second); 15588 } 15589 } 15590 15591 if (!VD->hasGlobalStorage()) return; 15592 15593 // Emit warning for non-trivial dtor in global scope (a real global, 15594 // class-static, function-static). 15595 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 15596 15597 // TODO: this should be re-enabled for static locals by !CXAAtExit 15598 if (!VD->isStaticLocal()) 15599 Diag(VD->getLocation(), diag::warn_global_destructor); 15600 } 15601 15602 /// Given a constructor and the set of arguments provided for the 15603 /// constructor, convert the arguments and add any required default arguments 15604 /// to form a proper call to this constructor. 15605 /// 15606 /// \returns true if an error occurred, false otherwise. 15607 bool Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 15608 QualType DeclInitType, MultiExprArg ArgsPtr, 15609 SourceLocation Loc, 15610 SmallVectorImpl<Expr *> &ConvertedArgs, 15611 bool AllowExplicit, 15612 bool IsListInitialization) { 15613 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 15614 unsigned NumArgs = ArgsPtr.size(); 15615 Expr **Args = ArgsPtr.data(); 15616 15617 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>(); 15618 unsigned NumParams = Proto->getNumParams(); 15619 15620 // If too few arguments are available, we'll fill in the rest with defaults. 15621 if (NumArgs < NumParams) 15622 ConvertedArgs.reserve(NumParams); 15623 else 15624 ConvertedArgs.reserve(NumArgs); 15625 15626 VariadicCallType CallType = 15627 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 15628 SmallVector<Expr *, 8> AllArgs; 15629 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 15630 Proto, 0, 15631 llvm::makeArrayRef(Args, NumArgs), 15632 AllArgs, 15633 CallType, AllowExplicit, 15634 IsListInitialization); 15635 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 15636 15637 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 15638 15639 CheckConstructorCall(Constructor, DeclInitType, 15640 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 15641 Proto, Loc); 15642 15643 return Invalid; 15644 } 15645 15646 static inline bool 15647 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 15648 const FunctionDecl *FnDecl) { 15649 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 15650 if (isa<NamespaceDecl>(DC)) { 15651 return SemaRef.Diag(FnDecl->getLocation(), 15652 diag::err_operator_new_delete_declared_in_namespace) 15653 << FnDecl->getDeclName(); 15654 } 15655 15656 if (isa<TranslationUnitDecl>(DC) && 15657 FnDecl->getStorageClass() == SC_Static) { 15658 return SemaRef.Diag(FnDecl->getLocation(), 15659 diag::err_operator_new_delete_declared_static) 15660 << FnDecl->getDeclName(); 15661 } 15662 15663 return false; 15664 } 15665 15666 static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef, 15667 const PointerType *PtrTy) { 15668 auto &Ctx = SemaRef.Context; 15669 Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers(); 15670 PtrQuals.removeAddressSpace(); 15671 return Ctx.getPointerType(Ctx.getCanonicalType(Ctx.getQualifiedType( 15672 PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals))); 15673 } 15674 15675 static inline bool 15676 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 15677 CanQualType ExpectedResultType, 15678 CanQualType ExpectedFirstParamType, 15679 unsigned DependentParamTypeDiag, 15680 unsigned InvalidParamTypeDiag) { 15681 QualType ResultType = 15682 FnDecl->getType()->castAs<FunctionType>()->getReturnType(); 15683 15684 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 15685 // The operator is valid on any address space for OpenCL. 15686 // Drop address space from actual and expected result types. 15687 if (const auto *PtrTy = ResultType->getAs<PointerType>()) 15688 ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 15689 15690 if (auto ExpectedPtrTy = ExpectedResultType->getAs<PointerType>()) 15691 ExpectedResultType = RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy); 15692 } 15693 15694 // Check that the result type is what we expect. 15695 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) { 15696 // Reject even if the type is dependent; an operator delete function is 15697 // required to have a non-dependent result type. 15698 return SemaRef.Diag( 15699 FnDecl->getLocation(), 15700 ResultType->isDependentType() 15701 ? diag::err_operator_new_delete_dependent_result_type 15702 : diag::err_operator_new_delete_invalid_result_type) 15703 << FnDecl->getDeclName() << ExpectedResultType; 15704 } 15705 15706 // A function template must have at least 2 parameters. 15707 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 15708 return SemaRef.Diag(FnDecl->getLocation(), 15709 diag::err_operator_new_delete_template_too_few_parameters) 15710 << FnDecl->getDeclName(); 15711 15712 // The function decl must have at least 1 parameter. 15713 if (FnDecl->getNumParams() == 0) 15714 return SemaRef.Diag(FnDecl->getLocation(), 15715 diag::err_operator_new_delete_too_few_parameters) 15716 << FnDecl->getDeclName(); 15717 15718 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 15719 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 15720 // The operator is valid on any address space for OpenCL. 15721 // Drop address space from actual and expected first parameter types. 15722 if (const auto *PtrTy = 15723 FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) 15724 FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 15725 15726 if (auto ExpectedPtrTy = ExpectedFirstParamType->getAs<PointerType>()) 15727 ExpectedFirstParamType = 15728 RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy); 15729 } 15730 15731 // Check that the first parameter type is what we expect. 15732 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 15733 ExpectedFirstParamType) { 15734 // The first parameter type is not allowed to be dependent. As a tentative 15735 // DR resolution, we allow a dependent parameter type if it is the right 15736 // type anyway, to allow destroying operator delete in class templates. 15737 return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType() 15738 ? DependentParamTypeDiag 15739 : InvalidParamTypeDiag) 15740 << FnDecl->getDeclName() << ExpectedFirstParamType; 15741 } 15742 15743 return false; 15744 } 15745 15746 static bool 15747 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 15748 // C++ [basic.stc.dynamic.allocation]p1: 15749 // A program is ill-formed if an allocation function is declared in a 15750 // namespace scope other than global scope or declared static in global 15751 // scope. 15752 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 15753 return true; 15754 15755 CanQualType SizeTy = 15756 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 15757 15758 // C++ [basic.stc.dynamic.allocation]p1: 15759 // The return type shall be void*. The first parameter shall have type 15760 // std::size_t. 15761 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 15762 SizeTy, 15763 diag::err_operator_new_dependent_param_type, 15764 diag::err_operator_new_param_type)) 15765 return true; 15766 15767 // C++ [basic.stc.dynamic.allocation]p1: 15768 // The first parameter shall not have an associated default argument. 15769 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 15770 return SemaRef.Diag(FnDecl->getLocation(), 15771 diag::err_operator_new_default_arg) 15772 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 15773 15774 return false; 15775 } 15776 15777 static bool 15778 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 15779 // C++ [basic.stc.dynamic.deallocation]p1: 15780 // A program is ill-formed if deallocation functions are declared in a 15781 // namespace scope other than global scope or declared static in global 15782 // scope. 15783 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 15784 return true; 15785 15786 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl); 15787 15788 // C++ P0722: 15789 // Within a class C, the first parameter of a destroying operator delete 15790 // shall be of type C *. The first parameter of any other deallocation 15791 // function shall be of type void *. 15792 CanQualType ExpectedFirstParamType = 15793 MD && MD->isDestroyingOperatorDelete() 15794 ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType( 15795 SemaRef.Context.getRecordType(MD->getParent()))) 15796 : SemaRef.Context.VoidPtrTy; 15797 15798 // C++ [basic.stc.dynamic.deallocation]p2: 15799 // Each deallocation function shall return void 15800 if (CheckOperatorNewDeleteTypes( 15801 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType, 15802 diag::err_operator_delete_dependent_param_type, 15803 diag::err_operator_delete_param_type)) 15804 return true; 15805 15806 // C++ P0722: 15807 // A destroying operator delete shall be a usual deallocation function. 15808 if (MD && !MD->getParent()->isDependentContext() && 15809 MD->isDestroyingOperatorDelete() && 15810 !SemaRef.isUsualDeallocationFunction(MD)) { 15811 SemaRef.Diag(MD->getLocation(), 15812 diag::err_destroying_operator_delete_not_usual); 15813 return true; 15814 } 15815 15816 return false; 15817 } 15818 15819 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 15820 /// of this overloaded operator is well-formed. If so, returns false; 15821 /// otherwise, emits appropriate diagnostics and returns true. 15822 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 15823 assert(FnDecl && FnDecl->isOverloadedOperator() && 15824 "Expected an overloaded operator declaration"); 15825 15826 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 15827 15828 // C++ [over.oper]p5: 15829 // The allocation and deallocation functions, operator new, 15830 // operator new[], operator delete and operator delete[], are 15831 // described completely in 3.7.3. The attributes and restrictions 15832 // found in the rest of this subclause do not apply to them unless 15833 // explicitly stated in 3.7.3. 15834 if (Op == OO_Delete || Op == OO_Array_Delete) 15835 return CheckOperatorDeleteDeclaration(*this, FnDecl); 15836 15837 if (Op == OO_New || Op == OO_Array_New) 15838 return CheckOperatorNewDeclaration(*this, FnDecl); 15839 15840 // C++ [over.oper]p6: 15841 // An operator function shall either be a non-static member 15842 // function or be a non-member function and have at least one 15843 // parameter whose type is a class, a reference to a class, an 15844 // enumeration, or a reference to an enumeration. 15845 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 15846 if (MethodDecl->isStatic()) 15847 return Diag(FnDecl->getLocation(), 15848 diag::err_operator_overload_static) << FnDecl->getDeclName(); 15849 } else { 15850 bool ClassOrEnumParam = false; 15851 for (auto Param : FnDecl->parameters()) { 15852 QualType ParamType = Param->getType().getNonReferenceType(); 15853 if (ParamType->isDependentType() || ParamType->isRecordType() || 15854 ParamType->isEnumeralType()) { 15855 ClassOrEnumParam = true; 15856 break; 15857 } 15858 } 15859 15860 if (!ClassOrEnumParam) 15861 return Diag(FnDecl->getLocation(), 15862 diag::err_operator_overload_needs_class_or_enum) 15863 << FnDecl->getDeclName(); 15864 } 15865 15866 // C++ [over.oper]p8: 15867 // An operator function cannot have default arguments (8.3.6), 15868 // except where explicitly stated below. 15869 // 15870 // Only the function-call operator allows default arguments 15871 // (C++ [over.call]p1). 15872 if (Op != OO_Call) { 15873 for (auto Param : FnDecl->parameters()) { 15874 if (Param->hasDefaultArg()) 15875 return Diag(Param->getLocation(), 15876 diag::err_operator_overload_default_arg) 15877 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 15878 } 15879 } 15880 15881 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 15882 { false, false, false } 15883 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 15884 , { Unary, Binary, MemberOnly } 15885 #include "clang/Basic/OperatorKinds.def" 15886 }; 15887 15888 bool CanBeUnaryOperator = OperatorUses[Op][0]; 15889 bool CanBeBinaryOperator = OperatorUses[Op][1]; 15890 bool MustBeMemberOperator = OperatorUses[Op][2]; 15891 15892 // C++ [over.oper]p8: 15893 // [...] Operator functions cannot have more or fewer parameters 15894 // than the number required for the corresponding operator, as 15895 // described in the rest of this subclause. 15896 unsigned NumParams = FnDecl->getNumParams() 15897 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 15898 if (Op != OO_Call && 15899 ((NumParams == 1 && !CanBeUnaryOperator) || 15900 (NumParams == 2 && !CanBeBinaryOperator) || 15901 (NumParams < 1) || (NumParams > 2))) { 15902 // We have the wrong number of parameters. 15903 unsigned ErrorKind; 15904 if (CanBeUnaryOperator && CanBeBinaryOperator) { 15905 ErrorKind = 2; // 2 -> unary or binary. 15906 } else if (CanBeUnaryOperator) { 15907 ErrorKind = 0; // 0 -> unary 15908 } else { 15909 assert(CanBeBinaryOperator && 15910 "All non-call overloaded operators are unary or binary!"); 15911 ErrorKind = 1; // 1 -> binary 15912 } 15913 15914 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 15915 << FnDecl->getDeclName() << NumParams << ErrorKind; 15916 } 15917 15918 // Overloaded operators other than operator() cannot be variadic. 15919 if (Op != OO_Call && 15920 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) { 15921 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 15922 << FnDecl->getDeclName(); 15923 } 15924 15925 // Some operators must be non-static member functions. 15926 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 15927 return Diag(FnDecl->getLocation(), 15928 diag::err_operator_overload_must_be_member) 15929 << FnDecl->getDeclName(); 15930 } 15931 15932 // C++ [over.inc]p1: 15933 // The user-defined function called operator++ implements the 15934 // prefix and postfix ++ operator. If this function is a member 15935 // function with no parameters, or a non-member function with one 15936 // parameter of class or enumeration type, it defines the prefix 15937 // increment operator ++ for objects of that type. If the function 15938 // is a member function with one parameter (which shall be of type 15939 // int) or a non-member function with two parameters (the second 15940 // of which shall be of type int), it defines the postfix 15941 // increment operator ++ for objects of that type. 15942 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 15943 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 15944 QualType ParamType = LastParam->getType(); 15945 15946 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 15947 !ParamType->isDependentType()) 15948 return Diag(LastParam->getLocation(), 15949 diag::err_operator_overload_post_incdec_must_be_int) 15950 << LastParam->getType() << (Op == OO_MinusMinus); 15951 } 15952 15953 return false; 15954 } 15955 15956 static bool 15957 checkLiteralOperatorTemplateParameterList(Sema &SemaRef, 15958 FunctionTemplateDecl *TpDecl) { 15959 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters(); 15960 15961 // Must have one or two template parameters. 15962 if (TemplateParams->size() == 1) { 15963 NonTypeTemplateParmDecl *PmDecl = 15964 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0)); 15965 15966 // The template parameter must be a char parameter pack. 15967 if (PmDecl && PmDecl->isTemplateParameterPack() && 15968 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy)) 15969 return false; 15970 15971 // C++20 [over.literal]p5: 15972 // A string literal operator template is a literal operator template 15973 // whose template-parameter-list comprises a single non-type 15974 // template-parameter of class type. 15975 // 15976 // As a DR resolution, we also allow placeholders for deduced class 15977 // template specializations. 15978 if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl && 15979 !PmDecl->isTemplateParameterPack() && 15980 (PmDecl->getType()->isRecordType() || 15981 PmDecl->getType()->getAs<DeducedTemplateSpecializationType>())) 15982 return false; 15983 } else if (TemplateParams->size() == 2) { 15984 TemplateTypeParmDecl *PmType = 15985 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0)); 15986 NonTypeTemplateParmDecl *PmArgs = 15987 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1)); 15988 15989 // The second template parameter must be a parameter pack with the 15990 // first template parameter as its type. 15991 if (PmType && PmArgs && !PmType->isTemplateParameterPack() && 15992 PmArgs->isTemplateParameterPack()) { 15993 const TemplateTypeParmType *TArgs = 15994 PmArgs->getType()->getAs<TemplateTypeParmType>(); 15995 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 15996 TArgs->getIndex() == PmType->getIndex()) { 15997 if (!SemaRef.inTemplateInstantiation()) 15998 SemaRef.Diag(TpDecl->getLocation(), 15999 diag::ext_string_literal_operator_template); 16000 return false; 16001 } 16002 } 16003 } 16004 16005 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(), 16006 diag::err_literal_operator_template) 16007 << TpDecl->getTemplateParameters()->getSourceRange(); 16008 return true; 16009 } 16010 16011 /// CheckLiteralOperatorDeclaration - Check whether the declaration 16012 /// of this literal operator function is well-formed. If so, returns 16013 /// false; otherwise, emits appropriate diagnostics and returns true. 16014 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 16015 if (isa<CXXMethodDecl>(FnDecl)) { 16016 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 16017 << FnDecl->getDeclName(); 16018 return true; 16019 } 16020 16021 if (FnDecl->isExternC()) { 16022 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 16023 if (const LinkageSpecDecl *LSD = 16024 FnDecl->getDeclContext()->getExternCContext()) 16025 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here); 16026 return true; 16027 } 16028 16029 // This might be the definition of a literal operator template. 16030 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 16031 16032 // This might be a specialization of a literal operator template. 16033 if (!TpDecl) 16034 TpDecl = FnDecl->getPrimaryTemplate(); 16035 16036 // template <char...> type operator "" name() and 16037 // template <class T, T...> type operator "" name() are the only valid 16038 // template signatures, and the only valid signatures with no parameters. 16039 // 16040 // C++20 also allows template <SomeClass T> type operator "" name(). 16041 if (TpDecl) { 16042 if (FnDecl->param_size() != 0) { 16043 Diag(FnDecl->getLocation(), 16044 diag::err_literal_operator_template_with_params); 16045 return true; 16046 } 16047 16048 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl)) 16049 return true; 16050 16051 } else if (FnDecl->param_size() == 1) { 16052 const ParmVarDecl *Param = FnDecl->getParamDecl(0); 16053 16054 QualType ParamType = Param->getType().getUnqualifiedType(); 16055 16056 // Only unsigned long long int, long double, any character type, and const 16057 // char * are allowed as the only parameters. 16058 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) || 16059 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) || 16060 Context.hasSameType(ParamType, Context.CharTy) || 16061 Context.hasSameType(ParamType, Context.WideCharTy) || 16062 Context.hasSameType(ParamType, Context.Char8Ty) || 16063 Context.hasSameType(ParamType, Context.Char16Ty) || 16064 Context.hasSameType(ParamType, Context.Char32Ty)) { 16065 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) { 16066 QualType InnerType = Ptr->getPointeeType(); 16067 16068 // Pointer parameter must be a const char *. 16069 if (!(Context.hasSameType(InnerType.getUnqualifiedType(), 16070 Context.CharTy) && 16071 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) { 16072 Diag(Param->getSourceRange().getBegin(), 16073 diag::err_literal_operator_param) 16074 << ParamType << "'const char *'" << Param->getSourceRange(); 16075 return true; 16076 } 16077 16078 } else if (ParamType->isRealFloatingType()) { 16079 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 16080 << ParamType << Context.LongDoubleTy << Param->getSourceRange(); 16081 return true; 16082 16083 } else if (ParamType->isIntegerType()) { 16084 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 16085 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange(); 16086 return true; 16087 16088 } else { 16089 Diag(Param->getSourceRange().getBegin(), 16090 diag::err_literal_operator_invalid_param) 16091 << ParamType << Param->getSourceRange(); 16092 return true; 16093 } 16094 16095 } else if (FnDecl->param_size() == 2) { 16096 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 16097 16098 // First, verify that the first parameter is correct. 16099 16100 QualType FirstParamType = (*Param)->getType().getUnqualifiedType(); 16101 16102 // Two parameter function must have a pointer to const as a 16103 // first parameter; let's strip those qualifiers. 16104 const PointerType *PT = FirstParamType->getAs<PointerType>(); 16105 16106 if (!PT) { 16107 Diag((*Param)->getSourceRange().getBegin(), 16108 diag::err_literal_operator_param) 16109 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 16110 return true; 16111 } 16112 16113 QualType PointeeType = PT->getPointeeType(); 16114 // First parameter must be const 16115 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) { 16116 Diag((*Param)->getSourceRange().getBegin(), 16117 diag::err_literal_operator_param) 16118 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 16119 return true; 16120 } 16121 16122 QualType InnerType = PointeeType.getUnqualifiedType(); 16123 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and 16124 // const char32_t* are allowed as the first parameter to a two-parameter 16125 // function 16126 if (!(Context.hasSameType(InnerType, Context.CharTy) || 16127 Context.hasSameType(InnerType, Context.WideCharTy) || 16128 Context.hasSameType(InnerType, Context.Char8Ty) || 16129 Context.hasSameType(InnerType, Context.Char16Ty) || 16130 Context.hasSameType(InnerType, Context.Char32Ty))) { 16131 Diag((*Param)->getSourceRange().getBegin(), 16132 diag::err_literal_operator_param) 16133 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 16134 return true; 16135 } 16136 16137 // Move on to the second and final parameter. 16138 ++Param; 16139 16140 // The second parameter must be a std::size_t. 16141 QualType SecondParamType = (*Param)->getType().getUnqualifiedType(); 16142 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) { 16143 Diag((*Param)->getSourceRange().getBegin(), 16144 diag::err_literal_operator_param) 16145 << SecondParamType << Context.getSizeType() 16146 << (*Param)->getSourceRange(); 16147 return true; 16148 } 16149 } else { 16150 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count); 16151 return true; 16152 } 16153 16154 // Parameters are good. 16155 16156 // A parameter-declaration-clause containing a default argument is not 16157 // equivalent to any of the permitted forms. 16158 for (auto Param : FnDecl->parameters()) { 16159 if (Param->hasDefaultArg()) { 16160 Diag(Param->getDefaultArgRange().getBegin(), 16161 diag::err_literal_operator_default_argument) 16162 << Param->getDefaultArgRange(); 16163 break; 16164 } 16165 } 16166 16167 StringRef LiteralName 16168 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 16169 if (LiteralName[0] != '_' && 16170 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) { 16171 // C++11 [usrlit.suffix]p1: 16172 // Literal suffix identifiers that do not start with an underscore 16173 // are reserved for future standardization. 16174 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 16175 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 16176 } 16177 16178 return false; 16179 } 16180 16181 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 16182 /// linkage specification, including the language and (if present) 16183 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 16184 /// language string literal. LBraceLoc, if valid, provides the location of 16185 /// the '{' brace. Otherwise, this linkage specification does not 16186 /// have any braces. 16187 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 16188 Expr *LangStr, 16189 SourceLocation LBraceLoc) { 16190 StringLiteral *Lit = cast<StringLiteral>(LangStr); 16191 if (!Lit->isAscii()) { 16192 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 16193 << LangStr->getSourceRange(); 16194 return nullptr; 16195 } 16196 16197 StringRef Lang = Lit->getString(); 16198 LinkageSpecDecl::LanguageIDs Language; 16199 if (Lang == "C") 16200 Language = LinkageSpecDecl::lang_c; 16201 else if (Lang == "C++") 16202 Language = LinkageSpecDecl::lang_cxx; 16203 else { 16204 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 16205 << LangStr->getSourceRange(); 16206 return nullptr; 16207 } 16208 16209 // FIXME: Add all the various semantics of linkage specifications 16210 16211 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 16212 LangStr->getExprLoc(), Language, 16213 LBraceLoc.isValid()); 16214 16215 /// C++ [module.unit]p7.2.3 16216 /// - Otherwise, if the declaration 16217 /// - ... 16218 /// - ... 16219 /// - appears within a linkage-specification, 16220 /// it is attached to the global module. 16221 /// 16222 /// If the declaration is already in global module fragment, we don't 16223 /// need to attach it again. 16224 if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) { 16225 Module *GlobalModule = 16226 PushGlobalModuleFragment(ExternLoc, /*IsImplicit=*/true); 16227 D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate); 16228 D->setLocalOwningModule(GlobalModule); 16229 } 16230 16231 CurContext->addDecl(D); 16232 PushDeclContext(S, D); 16233 return D; 16234 } 16235 16236 /// ActOnFinishLinkageSpecification - Complete the definition of 16237 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 16238 /// valid, it's the position of the closing '}' brace in a linkage 16239 /// specification that uses braces. 16240 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 16241 Decl *LinkageSpec, 16242 SourceLocation RBraceLoc) { 16243 if (RBraceLoc.isValid()) { 16244 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 16245 LSDecl->setRBraceLoc(RBraceLoc); 16246 } 16247 16248 // If the current module doesn't has Parent, it implies that the 16249 // LinkageSpec isn't in the module created by itself. So we don't 16250 // need to pop it. 16251 if (getLangOpts().CPlusPlusModules && getCurrentModule() && 16252 getCurrentModule()->isGlobalModule() && getCurrentModule()->Parent) 16253 PopGlobalModuleFragment(); 16254 16255 PopDeclContext(); 16256 return LinkageSpec; 16257 } 16258 16259 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 16260 const ParsedAttributesView &AttrList, 16261 SourceLocation SemiLoc) { 16262 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 16263 // Attribute declarations appertain to empty declaration so we handle 16264 // them here. 16265 ProcessDeclAttributeList(S, ED, AttrList); 16266 16267 CurContext->addDecl(ED); 16268 return ED; 16269 } 16270 16271 /// Perform semantic analysis for the variable declaration that 16272 /// occurs within a C++ catch clause, returning the newly-created 16273 /// variable. 16274 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 16275 TypeSourceInfo *TInfo, 16276 SourceLocation StartLoc, 16277 SourceLocation Loc, 16278 IdentifierInfo *Name) { 16279 bool Invalid = false; 16280 QualType ExDeclType = TInfo->getType(); 16281 16282 // Arrays and functions decay. 16283 if (ExDeclType->isArrayType()) 16284 ExDeclType = Context.getArrayDecayedType(ExDeclType); 16285 else if (ExDeclType->isFunctionType()) 16286 ExDeclType = Context.getPointerType(ExDeclType); 16287 16288 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 16289 // The exception-declaration shall not denote a pointer or reference to an 16290 // incomplete type, other than [cv] void*. 16291 // N2844 forbids rvalue references. 16292 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 16293 Diag(Loc, diag::err_catch_rvalue_ref); 16294 Invalid = true; 16295 } 16296 16297 if (ExDeclType->isVariablyModifiedType()) { 16298 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType; 16299 Invalid = true; 16300 } 16301 16302 QualType BaseType = ExDeclType; 16303 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 16304 unsigned DK = diag::err_catch_incomplete; 16305 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 16306 BaseType = Ptr->getPointeeType(); 16307 Mode = 1; 16308 DK = diag::err_catch_incomplete_ptr; 16309 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 16310 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 16311 BaseType = Ref->getPointeeType(); 16312 Mode = 2; 16313 DK = diag::err_catch_incomplete_ref; 16314 } 16315 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 16316 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 16317 Invalid = true; 16318 16319 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) { 16320 Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType; 16321 Invalid = true; 16322 } 16323 16324 if (!Invalid && !ExDeclType->isDependentType() && 16325 RequireNonAbstractType(Loc, ExDeclType, 16326 diag::err_abstract_type_in_decl, 16327 AbstractVariableType)) 16328 Invalid = true; 16329 16330 // Only the non-fragile NeXT runtime currently supports C++ catches 16331 // of ObjC types, and no runtime supports catching ObjC types by value. 16332 if (!Invalid && getLangOpts().ObjC) { 16333 QualType T = ExDeclType; 16334 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 16335 T = RT->getPointeeType(); 16336 16337 if (T->isObjCObjectType()) { 16338 Diag(Loc, diag::err_objc_object_catch); 16339 Invalid = true; 16340 } else if (T->isObjCObjectPointerType()) { 16341 // FIXME: should this be a test for macosx-fragile specifically? 16342 if (getLangOpts().ObjCRuntime.isFragile()) 16343 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 16344 } 16345 } 16346 16347 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 16348 ExDeclType, TInfo, SC_None); 16349 ExDecl->setExceptionVariable(true); 16350 16351 // In ARC, infer 'retaining' for variables of retainable type. 16352 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 16353 Invalid = true; 16354 16355 if (!Invalid && !ExDeclType->isDependentType()) { 16356 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 16357 // Insulate this from anything else we might currently be parsing. 16358 EnterExpressionEvaluationContext scope( 16359 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 16360 16361 // C++ [except.handle]p16: 16362 // The object declared in an exception-declaration or, if the 16363 // exception-declaration does not specify a name, a temporary (12.2) is 16364 // copy-initialized (8.5) from the exception object. [...] 16365 // The object is destroyed when the handler exits, after the destruction 16366 // of any automatic objects initialized within the handler. 16367 // 16368 // We just pretend to initialize the object with itself, then make sure 16369 // it can be destroyed later. 16370 QualType initType = Context.getExceptionObjectType(ExDeclType); 16371 16372 InitializedEntity entity = 16373 InitializedEntity::InitializeVariable(ExDecl); 16374 InitializationKind initKind = 16375 InitializationKind::CreateCopy(Loc, SourceLocation()); 16376 16377 Expr *opaqueValue = 16378 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 16379 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 16380 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 16381 if (result.isInvalid()) 16382 Invalid = true; 16383 else { 16384 // If the constructor used was non-trivial, set this as the 16385 // "initializer". 16386 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 16387 if (!construct->getConstructor()->isTrivial()) { 16388 Expr *init = MaybeCreateExprWithCleanups(construct); 16389 ExDecl->setInit(init); 16390 } 16391 16392 // And make sure it's destructable. 16393 FinalizeVarWithDestructor(ExDecl, recordType); 16394 } 16395 } 16396 } 16397 16398 if (Invalid) 16399 ExDecl->setInvalidDecl(); 16400 16401 return ExDecl; 16402 } 16403 16404 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 16405 /// handler. 16406 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 16407 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16408 bool Invalid = D.isInvalidType(); 16409 16410 // Check for unexpanded parameter packs. 16411 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 16412 UPPC_ExceptionType)) { 16413 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 16414 D.getIdentifierLoc()); 16415 Invalid = true; 16416 } 16417 16418 IdentifierInfo *II = D.getIdentifier(); 16419 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 16420 LookupOrdinaryName, 16421 ForVisibleRedeclaration)) { 16422 // The scope should be freshly made just for us. There is just no way 16423 // it contains any previous declaration, except for function parameters in 16424 // a function-try-block's catch statement. 16425 assert(!S->isDeclScope(PrevDecl)); 16426 if (isDeclInScope(PrevDecl, CurContext, S)) { 16427 Diag(D.getIdentifierLoc(), diag::err_redefinition) 16428 << D.getIdentifier(); 16429 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 16430 Invalid = true; 16431 } else if (PrevDecl->isTemplateParameter()) 16432 // Maybe we will complain about the shadowed template parameter. 16433 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 16434 } 16435 16436 if (D.getCXXScopeSpec().isSet() && !Invalid) { 16437 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 16438 << D.getCXXScopeSpec().getRange(); 16439 Invalid = true; 16440 } 16441 16442 VarDecl *ExDecl = BuildExceptionDeclaration( 16443 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier()); 16444 if (Invalid) 16445 ExDecl->setInvalidDecl(); 16446 16447 // Add the exception declaration into this scope. 16448 if (II) 16449 PushOnScopeChains(ExDecl, S); 16450 else 16451 CurContext->addDecl(ExDecl); 16452 16453 ProcessDeclAttributes(S, ExDecl, D); 16454 return ExDecl; 16455 } 16456 16457 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 16458 Expr *AssertExpr, 16459 Expr *AssertMessageExpr, 16460 SourceLocation RParenLoc) { 16461 StringLiteral *AssertMessage = 16462 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 16463 16464 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 16465 return nullptr; 16466 16467 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 16468 AssertMessage, RParenLoc, false); 16469 } 16470 16471 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 16472 Expr *AssertExpr, 16473 StringLiteral *AssertMessage, 16474 SourceLocation RParenLoc, 16475 bool Failed) { 16476 assert(AssertExpr != nullptr && "Expected non-null condition"); 16477 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 16478 !Failed) { 16479 // In a static_assert-declaration, the constant-expression shall be a 16480 // constant expression that can be contextually converted to bool. 16481 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 16482 if (Converted.isInvalid()) 16483 Failed = true; 16484 16485 ExprResult FullAssertExpr = 16486 ActOnFinishFullExpr(Converted.get(), StaticAssertLoc, 16487 /*DiscardedValue*/ false, 16488 /*IsConstexpr*/ true); 16489 if (FullAssertExpr.isInvalid()) 16490 Failed = true; 16491 else 16492 AssertExpr = FullAssertExpr.get(); 16493 16494 llvm::APSInt Cond; 16495 if (!Failed && VerifyIntegerConstantExpression( 16496 AssertExpr, &Cond, 16497 diag::err_static_assert_expression_is_not_constant) 16498 .isInvalid()) 16499 Failed = true; 16500 16501 if (!Failed && !Cond) { 16502 SmallString<256> MsgBuffer; 16503 llvm::raw_svector_ostream Msg(MsgBuffer); 16504 if (AssertMessage) 16505 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 16506 16507 Expr *InnerCond = nullptr; 16508 std::string InnerCondDescription; 16509 std::tie(InnerCond, InnerCondDescription) = 16510 findFailedBooleanCondition(Converted.get()); 16511 if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) { 16512 // Drill down into concept specialization expressions to see why they 16513 // weren't satisfied. 16514 Diag(StaticAssertLoc, diag::err_static_assert_failed) 16515 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 16516 ConstraintSatisfaction Satisfaction; 16517 if (!CheckConstraintSatisfaction(InnerCond, Satisfaction)) 16518 DiagnoseUnsatisfiedConstraint(Satisfaction); 16519 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond) 16520 && !isa<IntegerLiteral>(InnerCond)) { 16521 Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed) 16522 << InnerCondDescription << !AssertMessage 16523 << Msg.str() << InnerCond->getSourceRange(); 16524 } else { 16525 Diag(StaticAssertLoc, diag::err_static_assert_failed) 16526 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 16527 } 16528 Failed = true; 16529 } 16530 } else { 16531 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc, 16532 /*DiscardedValue*/false, 16533 /*IsConstexpr*/true); 16534 if (FullAssertExpr.isInvalid()) 16535 Failed = true; 16536 else 16537 AssertExpr = FullAssertExpr.get(); 16538 } 16539 16540 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 16541 AssertExpr, AssertMessage, RParenLoc, 16542 Failed); 16543 16544 CurContext->addDecl(Decl); 16545 return Decl; 16546 } 16547 16548 /// Perform semantic analysis of the given friend type declaration. 16549 /// 16550 /// \returns A friend declaration that. 16551 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 16552 SourceLocation FriendLoc, 16553 TypeSourceInfo *TSInfo) { 16554 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 16555 16556 QualType T = TSInfo->getType(); 16557 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 16558 16559 // C++03 [class.friend]p2: 16560 // An elaborated-type-specifier shall be used in a friend declaration 16561 // for a class.* 16562 // 16563 // * The class-key of the elaborated-type-specifier is required. 16564 if (!CodeSynthesisContexts.empty()) { 16565 // Do not complain about the form of friend template types during any kind 16566 // of code synthesis. For template instantiation, we will have complained 16567 // when the template was defined. 16568 } else { 16569 if (!T->isElaboratedTypeSpecifier()) { 16570 // If we evaluated the type to a record type, suggest putting 16571 // a tag in front. 16572 if (const RecordType *RT = T->getAs<RecordType>()) { 16573 RecordDecl *RD = RT->getDecl(); 16574 16575 SmallString<16> InsertionText(" "); 16576 InsertionText += RD->getKindName(); 16577 16578 Diag(TypeRange.getBegin(), 16579 getLangOpts().CPlusPlus11 ? 16580 diag::warn_cxx98_compat_unelaborated_friend_type : 16581 diag::ext_unelaborated_friend_type) 16582 << (unsigned) RD->getTagKind() 16583 << T 16584 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc), 16585 InsertionText); 16586 } else { 16587 Diag(FriendLoc, 16588 getLangOpts().CPlusPlus11 ? 16589 diag::warn_cxx98_compat_nonclass_type_friend : 16590 diag::ext_nonclass_type_friend) 16591 << T 16592 << TypeRange; 16593 } 16594 } else if (T->getAs<EnumType>()) { 16595 Diag(FriendLoc, 16596 getLangOpts().CPlusPlus11 ? 16597 diag::warn_cxx98_compat_enum_friend : 16598 diag::ext_enum_friend) 16599 << T 16600 << TypeRange; 16601 } 16602 16603 // C++11 [class.friend]p3: 16604 // A friend declaration that does not declare a function shall have one 16605 // of the following forms: 16606 // friend elaborated-type-specifier ; 16607 // friend simple-type-specifier ; 16608 // friend typename-specifier ; 16609 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 16610 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 16611 } 16612 16613 // If the type specifier in a friend declaration designates a (possibly 16614 // cv-qualified) class type, that class is declared as a friend; otherwise, 16615 // the friend declaration is ignored. 16616 return FriendDecl::Create(Context, CurContext, 16617 TSInfo->getTypeLoc().getBeginLoc(), TSInfo, 16618 FriendLoc); 16619 } 16620 16621 /// Handle a friend tag declaration where the scope specifier was 16622 /// templated. 16623 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 16624 unsigned TagSpec, SourceLocation TagLoc, 16625 CXXScopeSpec &SS, IdentifierInfo *Name, 16626 SourceLocation NameLoc, 16627 const ParsedAttributesView &Attr, 16628 MultiTemplateParamsArg TempParamLists) { 16629 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 16630 16631 bool IsMemberSpecialization = false; 16632 bool Invalid = false; 16633 16634 if (TemplateParameterList *TemplateParams = 16635 MatchTemplateParametersToScopeSpecifier( 16636 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 16637 IsMemberSpecialization, Invalid)) { 16638 if (TemplateParams->size() > 0) { 16639 // This is a declaration of a class template. 16640 if (Invalid) 16641 return nullptr; 16642 16643 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 16644 NameLoc, Attr, TemplateParams, AS_public, 16645 /*ModulePrivateLoc=*/SourceLocation(), 16646 FriendLoc, TempParamLists.size() - 1, 16647 TempParamLists.data()).get(); 16648 } else { 16649 // The "template<>" header is extraneous. 16650 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 16651 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 16652 IsMemberSpecialization = true; 16653 } 16654 } 16655 16656 if (Invalid) return nullptr; 16657 16658 bool isAllExplicitSpecializations = true; 16659 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 16660 if (TempParamLists[I]->size()) { 16661 isAllExplicitSpecializations = false; 16662 break; 16663 } 16664 } 16665 16666 // FIXME: don't ignore attributes. 16667 16668 // If it's explicit specializations all the way down, just forget 16669 // about the template header and build an appropriate non-templated 16670 // friend. TODO: for source fidelity, remember the headers. 16671 if (isAllExplicitSpecializations) { 16672 if (SS.isEmpty()) { 16673 bool Owned = false; 16674 bool IsDependent = false; 16675 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 16676 Attr, AS_public, 16677 /*ModulePrivateLoc=*/SourceLocation(), 16678 MultiTemplateParamsArg(), Owned, IsDependent, 16679 /*ScopedEnumKWLoc=*/SourceLocation(), 16680 /*ScopedEnumUsesClassTag=*/false, 16681 /*UnderlyingType=*/TypeResult(), 16682 /*IsTypeSpecifier=*/false, 16683 /*IsTemplateParamOrArg=*/false); 16684 } 16685 16686 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 16687 ElaboratedTypeKeyword Keyword 16688 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 16689 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 16690 *Name, NameLoc); 16691 if (T.isNull()) 16692 return nullptr; 16693 16694 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 16695 if (isa<DependentNameType>(T)) { 16696 DependentNameTypeLoc TL = 16697 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 16698 TL.setElaboratedKeywordLoc(TagLoc); 16699 TL.setQualifierLoc(QualifierLoc); 16700 TL.setNameLoc(NameLoc); 16701 } else { 16702 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 16703 TL.setElaboratedKeywordLoc(TagLoc); 16704 TL.setQualifierLoc(QualifierLoc); 16705 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 16706 } 16707 16708 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 16709 TSI, FriendLoc, TempParamLists); 16710 Friend->setAccess(AS_public); 16711 CurContext->addDecl(Friend); 16712 return Friend; 16713 } 16714 16715 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 16716 16717 16718 16719 // Handle the case of a templated-scope friend class. e.g. 16720 // template <class T> class A<T>::B; 16721 // FIXME: we don't support these right now. 16722 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 16723 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 16724 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 16725 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 16726 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 16727 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 16728 TL.setElaboratedKeywordLoc(TagLoc); 16729 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 16730 TL.setNameLoc(NameLoc); 16731 16732 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 16733 TSI, FriendLoc, TempParamLists); 16734 Friend->setAccess(AS_public); 16735 Friend->setUnsupportedFriend(true); 16736 CurContext->addDecl(Friend); 16737 return Friend; 16738 } 16739 16740 /// Handle a friend type declaration. This works in tandem with 16741 /// ActOnTag. 16742 /// 16743 /// Notes on friend class templates: 16744 /// 16745 /// We generally treat friend class declarations as if they were 16746 /// declaring a class. So, for example, the elaborated type specifier 16747 /// in a friend declaration is required to obey the restrictions of a 16748 /// class-head (i.e. no typedefs in the scope chain), template 16749 /// parameters are required to match up with simple template-ids, &c. 16750 /// However, unlike when declaring a template specialization, it's 16751 /// okay to refer to a template specialization without an empty 16752 /// template parameter declaration, e.g. 16753 /// friend class A<T>::B<unsigned>; 16754 /// We permit this as a special case; if there are any template 16755 /// parameters present at all, require proper matching, i.e. 16756 /// template <> template \<class T> friend class A<int>::B; 16757 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 16758 MultiTemplateParamsArg TempParams) { 16759 SourceLocation Loc = DS.getBeginLoc(); 16760 16761 assert(DS.isFriendSpecified()); 16762 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 16763 16764 // C++ [class.friend]p3: 16765 // A friend declaration that does not declare a function shall have one of 16766 // the following forms: 16767 // friend elaborated-type-specifier ; 16768 // friend simple-type-specifier ; 16769 // friend typename-specifier ; 16770 // 16771 // Any declaration with a type qualifier does not have that form. (It's 16772 // legal to specify a qualified type as a friend, you just can't write the 16773 // keywords.) 16774 if (DS.getTypeQualifiers()) { 16775 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 16776 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const"; 16777 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 16778 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile"; 16779 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 16780 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict"; 16781 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 16782 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic"; 16783 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 16784 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned"; 16785 } 16786 16787 // Try to convert the decl specifier to a type. This works for 16788 // friend templates because ActOnTag never produces a ClassTemplateDecl 16789 // for a TUK_Friend. 16790 Declarator TheDeclarator(DS, DeclaratorContext::Member); 16791 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 16792 QualType T = TSI->getType(); 16793 if (TheDeclarator.isInvalidType()) 16794 return nullptr; 16795 16796 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 16797 return nullptr; 16798 16799 // This is definitely an error in C++98. It's probably meant to 16800 // be forbidden in C++0x, too, but the specification is just 16801 // poorly written. 16802 // 16803 // The problem is with declarations like the following: 16804 // template <T> friend A<T>::foo; 16805 // where deciding whether a class C is a friend or not now hinges 16806 // on whether there exists an instantiation of A that causes 16807 // 'foo' to equal C. There are restrictions on class-heads 16808 // (which we declare (by fiat) elaborated friend declarations to 16809 // be) that makes this tractable. 16810 // 16811 // FIXME: handle "template <> friend class A<T>;", which 16812 // is possibly well-formed? Who even knows? 16813 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 16814 Diag(Loc, diag::err_tagless_friend_type_template) 16815 << DS.getSourceRange(); 16816 return nullptr; 16817 } 16818 16819 // C++98 [class.friend]p1: A friend of a class is a function 16820 // or class that is not a member of the class . . . 16821 // This is fixed in DR77, which just barely didn't make the C++03 16822 // deadline. It's also a very silly restriction that seriously 16823 // affects inner classes and which nobody else seems to implement; 16824 // thus we never diagnose it, not even in -pedantic. 16825 // 16826 // But note that we could warn about it: it's always useless to 16827 // friend one of your own members (it's not, however, worthless to 16828 // friend a member of an arbitrary specialization of your template). 16829 16830 Decl *D; 16831 if (!TempParams.empty()) 16832 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 16833 TempParams, 16834 TSI, 16835 DS.getFriendSpecLoc()); 16836 else 16837 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 16838 16839 if (!D) 16840 return nullptr; 16841 16842 D->setAccess(AS_public); 16843 CurContext->addDecl(D); 16844 16845 return D; 16846 } 16847 16848 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 16849 MultiTemplateParamsArg TemplateParams) { 16850 const DeclSpec &DS = D.getDeclSpec(); 16851 16852 assert(DS.isFriendSpecified()); 16853 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 16854 16855 SourceLocation Loc = D.getIdentifierLoc(); 16856 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16857 16858 // C++ [class.friend]p1 16859 // A friend of a class is a function or class.... 16860 // Note that this sees through typedefs, which is intended. 16861 // It *doesn't* see through dependent types, which is correct 16862 // according to [temp.arg.type]p3: 16863 // If a declaration acquires a function type through a 16864 // type dependent on a template-parameter and this causes 16865 // a declaration that does not use the syntactic form of a 16866 // function declarator to have a function type, the program 16867 // is ill-formed. 16868 if (!TInfo->getType()->isFunctionType()) { 16869 Diag(Loc, diag::err_unexpected_friend); 16870 16871 // It might be worthwhile to try to recover by creating an 16872 // appropriate declaration. 16873 return nullptr; 16874 } 16875 16876 // C++ [namespace.memdef]p3 16877 // - If a friend declaration in a non-local class first declares a 16878 // class or function, the friend class or function is a member 16879 // of the innermost enclosing namespace. 16880 // - The name of the friend is not found by simple name lookup 16881 // until a matching declaration is provided in that namespace 16882 // scope (either before or after the class declaration granting 16883 // friendship). 16884 // - If a friend function is called, its name may be found by the 16885 // name lookup that considers functions from namespaces and 16886 // classes associated with the types of the function arguments. 16887 // - When looking for a prior declaration of a class or a function 16888 // declared as a friend, scopes outside the innermost enclosing 16889 // namespace scope are not considered. 16890 16891 CXXScopeSpec &SS = D.getCXXScopeSpec(); 16892 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 16893 assert(NameInfo.getName()); 16894 16895 // Check for unexpanded parameter packs. 16896 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 16897 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 16898 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 16899 return nullptr; 16900 16901 // The context we found the declaration in, or in which we should 16902 // create the declaration. 16903 DeclContext *DC; 16904 Scope *DCScope = S; 16905 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 16906 ForExternalRedeclaration); 16907 16908 // There are five cases here. 16909 // - There's no scope specifier and we're in a local class. Only look 16910 // for functions declared in the immediately-enclosing block scope. 16911 // We recover from invalid scope qualifiers as if they just weren't there. 16912 FunctionDecl *FunctionContainingLocalClass = nullptr; 16913 if ((SS.isInvalid() || !SS.isSet()) && 16914 (FunctionContainingLocalClass = 16915 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 16916 // C++11 [class.friend]p11: 16917 // If a friend declaration appears in a local class and the name 16918 // specified is an unqualified name, a prior declaration is 16919 // looked up without considering scopes that are outside the 16920 // innermost enclosing non-class scope. For a friend function 16921 // declaration, if there is no prior declaration, the program is 16922 // ill-formed. 16923 16924 // Find the innermost enclosing non-class scope. This is the block 16925 // scope containing the local class definition (or for a nested class, 16926 // the outer local class). 16927 DCScope = S->getFnParent(); 16928 16929 // Look up the function name in the scope. 16930 Previous.clear(LookupLocalFriendName); 16931 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 16932 16933 if (!Previous.empty()) { 16934 // All possible previous declarations must have the same context: 16935 // either they were declared at block scope or they are members of 16936 // one of the enclosing local classes. 16937 DC = Previous.getRepresentativeDecl()->getDeclContext(); 16938 } else { 16939 // This is ill-formed, but provide the context that we would have 16940 // declared the function in, if we were permitted to, for error recovery. 16941 DC = FunctionContainingLocalClass; 16942 } 16943 adjustContextForLocalExternDecl(DC); 16944 16945 // C++ [class.friend]p6: 16946 // A function can be defined in a friend declaration of a class if and 16947 // only if the class is a non-local class (9.8), the function name is 16948 // unqualified, and the function has namespace scope. 16949 if (D.isFunctionDefinition()) { 16950 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 16951 } 16952 16953 // - There's no scope specifier, in which case we just go to the 16954 // appropriate scope and look for a function or function template 16955 // there as appropriate. 16956 } else if (SS.isInvalid() || !SS.isSet()) { 16957 // C++11 [namespace.memdef]p3: 16958 // If the name in a friend declaration is neither qualified nor 16959 // a template-id and the declaration is a function or an 16960 // elaborated-type-specifier, the lookup to determine whether 16961 // the entity has been previously declared shall not consider 16962 // any scopes outside the innermost enclosing namespace. 16963 bool isTemplateId = 16964 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId; 16965 16966 // Find the appropriate context according to the above. 16967 DC = CurContext; 16968 16969 // Skip class contexts. If someone can cite chapter and verse 16970 // for this behavior, that would be nice --- it's what GCC and 16971 // EDG do, and it seems like a reasonable intent, but the spec 16972 // really only says that checks for unqualified existing 16973 // declarations should stop at the nearest enclosing namespace, 16974 // not that they should only consider the nearest enclosing 16975 // namespace. 16976 while (DC->isRecord()) 16977 DC = DC->getParent(); 16978 16979 DeclContext *LookupDC = DC->getNonTransparentContext(); 16980 while (true) { 16981 LookupQualifiedName(Previous, LookupDC); 16982 16983 if (!Previous.empty()) { 16984 DC = LookupDC; 16985 break; 16986 } 16987 16988 if (isTemplateId) { 16989 if (isa<TranslationUnitDecl>(LookupDC)) break; 16990 } else { 16991 if (LookupDC->isFileContext()) break; 16992 } 16993 LookupDC = LookupDC->getParent(); 16994 } 16995 16996 DCScope = getScopeForDeclContext(S, DC); 16997 16998 // - There's a non-dependent scope specifier, in which case we 16999 // compute it and do a previous lookup there for a function 17000 // or function template. 17001 } else if (!SS.getScopeRep()->isDependent()) { 17002 DC = computeDeclContext(SS); 17003 if (!DC) return nullptr; 17004 17005 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 17006 17007 LookupQualifiedName(Previous, DC); 17008 17009 // C++ [class.friend]p1: A friend of a class is a function or 17010 // class that is not a member of the class . . . 17011 if (DC->Equals(CurContext)) 17012 Diag(DS.getFriendSpecLoc(), 17013 getLangOpts().CPlusPlus11 ? 17014 diag::warn_cxx98_compat_friend_is_member : 17015 diag::err_friend_is_member); 17016 17017 if (D.isFunctionDefinition()) { 17018 // C++ [class.friend]p6: 17019 // A function can be defined in a friend declaration of a class if and 17020 // only if the class is a non-local class (9.8), the function name is 17021 // unqualified, and the function has namespace scope. 17022 // 17023 // FIXME: We should only do this if the scope specifier names the 17024 // innermost enclosing namespace; otherwise the fixit changes the 17025 // meaning of the code. 17026 SemaDiagnosticBuilder DB 17027 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 17028 17029 DB << SS.getScopeRep(); 17030 if (DC->isFileContext()) 17031 DB << FixItHint::CreateRemoval(SS.getRange()); 17032 SS.clear(); 17033 } 17034 17035 // - There's a scope specifier that does not match any template 17036 // parameter lists, in which case we use some arbitrary context, 17037 // create a method or method template, and wait for instantiation. 17038 // - There's a scope specifier that does match some template 17039 // parameter lists, which we don't handle right now. 17040 } else { 17041 if (D.isFunctionDefinition()) { 17042 // C++ [class.friend]p6: 17043 // A function can be defined in a friend declaration of a class if and 17044 // only if the class is a non-local class (9.8), the function name is 17045 // unqualified, and the function has namespace scope. 17046 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 17047 << SS.getScopeRep(); 17048 } 17049 17050 DC = CurContext; 17051 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 17052 } 17053 17054 if (!DC->isRecord()) { 17055 int DiagArg = -1; 17056 switch (D.getName().getKind()) { 17057 case UnqualifiedIdKind::IK_ConstructorTemplateId: 17058 case UnqualifiedIdKind::IK_ConstructorName: 17059 DiagArg = 0; 17060 break; 17061 case UnqualifiedIdKind::IK_DestructorName: 17062 DiagArg = 1; 17063 break; 17064 case UnqualifiedIdKind::IK_ConversionFunctionId: 17065 DiagArg = 2; 17066 break; 17067 case UnqualifiedIdKind::IK_DeductionGuideName: 17068 DiagArg = 3; 17069 break; 17070 case UnqualifiedIdKind::IK_Identifier: 17071 case UnqualifiedIdKind::IK_ImplicitSelfParam: 17072 case UnqualifiedIdKind::IK_LiteralOperatorId: 17073 case UnqualifiedIdKind::IK_OperatorFunctionId: 17074 case UnqualifiedIdKind::IK_TemplateId: 17075 break; 17076 } 17077 // This implies that it has to be an operator or function. 17078 if (DiagArg >= 0) { 17079 Diag(Loc, diag::err_introducing_special_friend) << DiagArg; 17080 return nullptr; 17081 } 17082 } 17083 17084 // FIXME: This is an egregious hack to cope with cases where the scope stack 17085 // does not contain the declaration context, i.e., in an out-of-line 17086 // definition of a class. 17087 Scope FakeDCScope(S, Scope::DeclScope, Diags); 17088 if (!DCScope) { 17089 FakeDCScope.setEntity(DC); 17090 DCScope = &FakeDCScope; 17091 } 17092 17093 bool AddToScope = true; 17094 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 17095 TemplateParams, AddToScope); 17096 if (!ND) return nullptr; 17097 17098 assert(ND->getLexicalDeclContext() == CurContext); 17099 17100 // If we performed typo correction, we might have added a scope specifier 17101 // and changed the decl context. 17102 DC = ND->getDeclContext(); 17103 17104 // Add the function declaration to the appropriate lookup tables, 17105 // adjusting the redeclarations list as necessary. We don't 17106 // want to do this yet if the friending class is dependent. 17107 // 17108 // Also update the scope-based lookup if the target context's 17109 // lookup context is in lexical scope. 17110 if (!CurContext->isDependentContext()) { 17111 DC = DC->getRedeclContext(); 17112 DC->makeDeclVisibleInContext(ND); 17113 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 17114 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 17115 } 17116 17117 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 17118 D.getIdentifierLoc(), ND, 17119 DS.getFriendSpecLoc()); 17120 FrD->setAccess(AS_public); 17121 CurContext->addDecl(FrD); 17122 17123 if (ND->isInvalidDecl()) { 17124 FrD->setInvalidDecl(); 17125 } else { 17126 if (DC->isRecord()) CheckFriendAccess(ND); 17127 17128 FunctionDecl *FD; 17129 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 17130 FD = FTD->getTemplatedDecl(); 17131 else 17132 FD = cast<FunctionDecl>(ND); 17133 17134 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 17135 // default argument expression, that declaration shall be a definition 17136 // and shall be the only declaration of the function or function 17137 // template in the translation unit. 17138 if (functionDeclHasDefaultArgument(FD)) { 17139 // We can't look at FD->getPreviousDecl() because it may not have been set 17140 // if we're in a dependent context. If the function is known to be a 17141 // redeclaration, we will have narrowed Previous down to the right decl. 17142 if (D.isRedeclaration()) { 17143 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 17144 Diag(Previous.getRepresentativeDecl()->getLocation(), 17145 diag::note_previous_declaration); 17146 } else if (!D.isFunctionDefinition()) 17147 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 17148 } 17149 17150 // Mark templated-scope function declarations as unsupported. 17151 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 17152 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 17153 << SS.getScopeRep() << SS.getRange() 17154 << cast<CXXRecordDecl>(CurContext); 17155 FrD->setUnsupportedFriend(true); 17156 } 17157 } 17158 17159 warnOnReservedIdentifier(ND); 17160 17161 return ND; 17162 } 17163 17164 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 17165 AdjustDeclIfTemplate(Dcl); 17166 17167 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 17168 if (!Fn) { 17169 Diag(DelLoc, diag::err_deleted_non_function); 17170 return; 17171 } 17172 17173 // Deleted function does not have a body. 17174 Fn->setWillHaveBody(false); 17175 17176 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 17177 // Don't consider the implicit declaration we generate for explicit 17178 // specializations. FIXME: Do not generate these implicit declarations. 17179 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 17180 Prev->getPreviousDecl()) && 17181 !Prev->isDefined()) { 17182 Diag(DelLoc, diag::err_deleted_decl_not_first); 17183 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 17184 Prev->isImplicit() ? diag::note_previous_implicit_declaration 17185 : diag::note_previous_declaration); 17186 // We can't recover from this; the declaration might have already 17187 // been used. 17188 Fn->setInvalidDecl(); 17189 return; 17190 } 17191 17192 // To maintain the invariant that functions are only deleted on their first 17193 // declaration, mark the implicitly-instantiated declaration of the 17194 // explicitly-specialized function as deleted instead of marking the 17195 // instantiated redeclaration. 17196 Fn = Fn->getCanonicalDecl(); 17197 } 17198 17199 // dllimport/dllexport cannot be deleted. 17200 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 17201 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 17202 Fn->setInvalidDecl(); 17203 } 17204 17205 // C++11 [basic.start.main]p3: 17206 // A program that defines main as deleted [...] is ill-formed. 17207 if (Fn->isMain()) 17208 Diag(DelLoc, diag::err_deleted_main); 17209 17210 // C++11 [dcl.fct.def.delete]p4: 17211 // A deleted function is implicitly inline. 17212 Fn->setImplicitlyInline(); 17213 Fn->setDeletedAsWritten(); 17214 } 17215 17216 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 17217 if (!Dcl || Dcl->isInvalidDecl()) 17218 return; 17219 17220 auto *FD = dyn_cast<FunctionDecl>(Dcl); 17221 if (!FD) { 17222 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) { 17223 if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) { 17224 Diag(DefaultLoc, diag::err_defaulted_comparison_template); 17225 return; 17226 } 17227 } 17228 17229 Diag(DefaultLoc, diag::err_default_special_members) 17230 << getLangOpts().CPlusPlus20; 17231 return; 17232 } 17233 17234 // Reject if this can't possibly be a defaultable function. 17235 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD); 17236 if (!DefKind && 17237 // A dependent function that doesn't locally look defaultable can 17238 // still instantiate to a defaultable function if it's a constructor 17239 // or assignment operator. 17240 (!FD->isDependentContext() || 17241 (!isa<CXXConstructorDecl>(FD) && 17242 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) { 17243 Diag(DefaultLoc, diag::err_default_special_members) 17244 << getLangOpts().CPlusPlus20; 17245 return; 17246 } 17247 17248 // Issue compatibility warning. We already warned if the operator is 17249 // 'operator<=>' when parsing the '<=>' token. 17250 if (DefKind.isComparison() && 17251 DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) { 17252 Diag(DefaultLoc, getLangOpts().CPlusPlus20 17253 ? diag::warn_cxx17_compat_defaulted_comparison 17254 : diag::ext_defaulted_comparison); 17255 } 17256 17257 FD->setDefaulted(); 17258 FD->setExplicitlyDefaulted(); 17259 17260 // Defer checking functions that are defaulted in a dependent context. 17261 if (FD->isDependentContext()) 17262 return; 17263 17264 // Unset that we will have a body for this function. We might not, 17265 // if it turns out to be trivial, and we don't need this marking now 17266 // that we've marked it as defaulted. 17267 FD->setWillHaveBody(false); 17268 17269 // If this is a comparison's defaulted definition within the record, do 17270 // the checking when the record is complete. 17271 if (DefKind.isComparison() && isa<CXXRecordDecl>(FD->getLexicalDeclContext())) 17272 return; 17273 17274 // If this member fn was defaulted on its first declaration, we will have 17275 // already performed the checking in CheckCompletedCXXClass. Such a 17276 // declaration doesn't trigger an implicit definition. 17277 if (isa<CXXMethodDecl>(FD)) { 17278 const FunctionDecl *Primary = FD; 17279 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern()) 17280 // Ask the template instantiation pattern that actually had the 17281 // '= default' on it. 17282 Primary = Pattern; 17283 if (Primary->getCanonicalDecl()->isDefaulted()) 17284 return; 17285 } 17286 17287 if (DefKind.isComparison()) { 17288 if (CheckExplicitlyDefaultedComparison(nullptr, FD, DefKind.asComparison())) 17289 FD->setInvalidDecl(); 17290 else 17291 DefineDefaultedComparison(DefaultLoc, FD, DefKind.asComparison()); 17292 } else { 17293 auto *MD = cast<CXXMethodDecl>(FD); 17294 17295 if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember())) 17296 MD->setInvalidDecl(); 17297 else 17298 DefineDefaultedFunction(*this, MD, DefaultLoc); 17299 } 17300 } 17301 17302 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 17303 for (Stmt *SubStmt : S->children()) { 17304 if (!SubStmt) 17305 continue; 17306 if (isa<ReturnStmt>(SubStmt)) 17307 Self.Diag(SubStmt->getBeginLoc(), 17308 diag::err_return_in_constructor_handler); 17309 if (!isa<Expr>(SubStmt)) 17310 SearchForReturnInStmt(Self, SubStmt); 17311 } 17312 } 17313 17314 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 17315 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 17316 CXXCatchStmt *Handler = TryBlock->getHandler(I); 17317 SearchForReturnInStmt(*this, Handler); 17318 } 17319 } 17320 17321 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 17322 const CXXMethodDecl *Old) { 17323 const auto *NewFT = New->getType()->castAs<FunctionProtoType>(); 17324 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>(); 17325 17326 if (OldFT->hasExtParameterInfos()) { 17327 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I) 17328 // A parameter of the overriding method should be annotated with noescape 17329 // if the corresponding parameter of the overridden method is annotated. 17330 if (OldFT->getExtParameterInfo(I).isNoEscape() && 17331 !NewFT->getExtParameterInfo(I).isNoEscape()) { 17332 Diag(New->getParamDecl(I)->getLocation(), 17333 diag::warn_overriding_method_missing_noescape); 17334 Diag(Old->getParamDecl(I)->getLocation(), 17335 diag::note_overridden_marked_noescape); 17336 } 17337 } 17338 17339 // Virtual overrides must have the same code_seg. 17340 const auto *OldCSA = Old->getAttr<CodeSegAttr>(); 17341 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 17342 if ((NewCSA || OldCSA) && 17343 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) { 17344 Diag(New->getLocation(), diag::err_mismatched_code_seg_override); 17345 Diag(Old->getLocation(), diag::note_previous_declaration); 17346 return true; 17347 } 17348 17349 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 17350 17351 // If the calling conventions match, everything is fine 17352 if (NewCC == OldCC) 17353 return false; 17354 17355 // If the calling conventions mismatch because the new function is static, 17356 // suppress the calling convention mismatch error; the error about static 17357 // function override (err_static_overrides_virtual from 17358 // Sema::CheckFunctionDeclaration) is more clear. 17359 if (New->getStorageClass() == SC_Static) 17360 return false; 17361 17362 Diag(New->getLocation(), 17363 diag::err_conflicting_overriding_cc_attributes) 17364 << New->getDeclName() << New->getType() << Old->getType(); 17365 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 17366 return true; 17367 } 17368 17369 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 17370 const CXXMethodDecl *Old) { 17371 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType(); 17372 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType(); 17373 17374 if (Context.hasSameType(NewTy, OldTy) || 17375 NewTy->isDependentType() || OldTy->isDependentType()) 17376 return false; 17377 17378 // Check if the return types are covariant 17379 QualType NewClassTy, OldClassTy; 17380 17381 /// Both types must be pointers or references to classes. 17382 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 17383 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 17384 NewClassTy = NewPT->getPointeeType(); 17385 OldClassTy = OldPT->getPointeeType(); 17386 } 17387 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 17388 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 17389 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 17390 NewClassTy = NewRT->getPointeeType(); 17391 OldClassTy = OldRT->getPointeeType(); 17392 } 17393 } 17394 } 17395 17396 // The return types aren't either both pointers or references to a class type. 17397 if (NewClassTy.isNull()) { 17398 Diag(New->getLocation(), 17399 diag::err_different_return_type_for_overriding_virtual_function) 17400 << New->getDeclName() << NewTy << OldTy 17401 << New->getReturnTypeSourceRange(); 17402 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17403 << Old->getReturnTypeSourceRange(); 17404 17405 return true; 17406 } 17407 17408 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 17409 // C++14 [class.virtual]p8: 17410 // If the class type in the covariant return type of D::f differs from 17411 // that of B::f, the class type in the return type of D::f shall be 17412 // complete at the point of declaration of D::f or shall be the class 17413 // type D. 17414 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 17415 if (!RT->isBeingDefined() && 17416 RequireCompleteType(New->getLocation(), NewClassTy, 17417 diag::err_covariant_return_incomplete, 17418 New->getDeclName())) 17419 return true; 17420 } 17421 17422 // Check if the new class derives from the old class. 17423 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) { 17424 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 17425 << New->getDeclName() << NewTy << OldTy 17426 << New->getReturnTypeSourceRange(); 17427 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17428 << Old->getReturnTypeSourceRange(); 17429 return true; 17430 } 17431 17432 // Check if we the conversion from derived to base is valid. 17433 if (CheckDerivedToBaseConversion( 17434 NewClassTy, OldClassTy, 17435 diag::err_covariant_return_inaccessible_base, 17436 diag::err_covariant_return_ambiguous_derived_to_base_conv, 17437 New->getLocation(), New->getReturnTypeSourceRange(), 17438 New->getDeclName(), nullptr)) { 17439 // FIXME: this note won't trigger for delayed access control 17440 // diagnostics, and it's impossible to get an undelayed error 17441 // here from access control during the original parse because 17442 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 17443 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17444 << Old->getReturnTypeSourceRange(); 17445 return true; 17446 } 17447 } 17448 17449 // The qualifiers of the return types must be the same. 17450 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 17451 Diag(New->getLocation(), 17452 diag::err_covariant_return_type_different_qualifications) 17453 << New->getDeclName() << NewTy << OldTy 17454 << New->getReturnTypeSourceRange(); 17455 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17456 << Old->getReturnTypeSourceRange(); 17457 return true; 17458 } 17459 17460 17461 // The new class type must have the same or less qualifiers as the old type. 17462 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 17463 Diag(New->getLocation(), 17464 diag::err_covariant_return_type_class_type_more_qualified) 17465 << New->getDeclName() << NewTy << OldTy 17466 << New->getReturnTypeSourceRange(); 17467 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17468 << Old->getReturnTypeSourceRange(); 17469 return true; 17470 } 17471 17472 return false; 17473 } 17474 17475 /// Mark the given method pure. 17476 /// 17477 /// \param Method the method to be marked pure. 17478 /// 17479 /// \param InitRange the source range that covers the "0" initializer. 17480 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 17481 SourceLocation EndLoc = InitRange.getEnd(); 17482 if (EndLoc.isValid()) 17483 Method->setRangeEnd(EndLoc); 17484 17485 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 17486 Method->setPure(); 17487 return false; 17488 } 17489 17490 if (!Method->isInvalidDecl()) 17491 Diag(Method->getLocation(), diag::err_non_virtual_pure) 17492 << Method->getDeclName() << InitRange; 17493 return true; 17494 } 17495 17496 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) { 17497 if (D->getFriendObjectKind()) 17498 Diag(D->getLocation(), diag::err_pure_friend); 17499 else if (auto *M = dyn_cast<CXXMethodDecl>(D)) 17500 CheckPureMethod(M, ZeroLoc); 17501 else 17502 Diag(D->getLocation(), diag::err_illegal_initializer); 17503 } 17504 17505 /// Determine whether the given declaration is a global variable or 17506 /// static data member. 17507 static bool isNonlocalVariable(const Decl *D) { 17508 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 17509 return Var->hasGlobalStorage(); 17510 17511 return false; 17512 } 17513 17514 /// Invoked when we are about to parse an initializer for the declaration 17515 /// 'Dcl'. 17516 /// 17517 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 17518 /// static data member of class X, names should be looked up in the scope of 17519 /// class X. If the declaration had a scope specifier, a scope will have 17520 /// been created and passed in for this purpose. Otherwise, S will be null. 17521 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 17522 // If there is no declaration, there was an error parsing it. 17523 if (!D || D->isInvalidDecl()) 17524 return; 17525 17526 // We will always have a nested name specifier here, but this declaration 17527 // might not be out of line if the specifier names the current namespace: 17528 // extern int n; 17529 // int ::n = 0; 17530 if (S && D->isOutOfLine()) 17531 EnterDeclaratorContext(S, D->getDeclContext()); 17532 17533 // If we are parsing the initializer for a static data member, push a 17534 // new expression evaluation context that is associated with this static 17535 // data member. 17536 if (isNonlocalVariable(D)) 17537 PushExpressionEvaluationContext( 17538 ExpressionEvaluationContext::PotentiallyEvaluated, D); 17539 } 17540 17541 /// Invoked after we are finished parsing an initializer for the declaration D. 17542 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 17543 // If there is no declaration, there was an error parsing it. 17544 if (!D || D->isInvalidDecl()) 17545 return; 17546 17547 if (isNonlocalVariable(D)) 17548 PopExpressionEvaluationContext(); 17549 17550 if (S && D->isOutOfLine()) 17551 ExitDeclaratorContext(S); 17552 } 17553 17554 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 17555 /// C++ if/switch/while/for statement. 17556 /// e.g: "if (int x = f()) {...}" 17557 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 17558 // C++ 6.4p2: 17559 // The declarator shall not specify a function or an array. 17560 // The type-specifier-seq shall not contain typedef and shall not declare a 17561 // new class or enumeration. 17562 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 17563 "Parser allowed 'typedef' as storage class of condition decl."); 17564 17565 Decl *Dcl = ActOnDeclarator(S, D); 17566 if (!Dcl) 17567 return true; 17568 17569 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 17570 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 17571 << D.getSourceRange(); 17572 return true; 17573 } 17574 17575 return Dcl; 17576 } 17577 17578 void Sema::LoadExternalVTableUses() { 17579 if (!ExternalSource) 17580 return; 17581 17582 SmallVector<ExternalVTableUse, 4> VTables; 17583 ExternalSource->ReadUsedVTables(VTables); 17584 SmallVector<VTableUse, 4> NewUses; 17585 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 17586 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 17587 = VTablesUsed.find(VTables[I].Record); 17588 // Even if a definition wasn't required before, it may be required now. 17589 if (Pos != VTablesUsed.end()) { 17590 if (!Pos->second && VTables[I].DefinitionRequired) 17591 Pos->second = true; 17592 continue; 17593 } 17594 17595 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 17596 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 17597 } 17598 17599 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 17600 } 17601 17602 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 17603 bool DefinitionRequired) { 17604 // Ignore any vtable uses in unevaluated operands or for classes that do 17605 // not have a vtable. 17606 if (!Class->isDynamicClass() || Class->isDependentContext() || 17607 CurContext->isDependentContext() || isUnevaluatedContext()) 17608 return; 17609 // Do not mark as used if compiling for the device outside of the target 17610 // region. 17611 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice && 17612 !isInOpenMPDeclareTargetContext() && 17613 !isInOpenMPTargetExecutionDirective()) { 17614 if (!DefinitionRequired) 17615 MarkVirtualMembersReferenced(Loc, Class); 17616 return; 17617 } 17618 17619 // Try to insert this class into the map. 17620 LoadExternalVTableUses(); 17621 Class = Class->getCanonicalDecl(); 17622 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 17623 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 17624 if (!Pos.second) { 17625 // If we already had an entry, check to see if we are promoting this vtable 17626 // to require a definition. If so, we need to reappend to the VTableUses 17627 // list, since we may have already processed the first entry. 17628 if (DefinitionRequired && !Pos.first->second) { 17629 Pos.first->second = true; 17630 } else { 17631 // Otherwise, we can early exit. 17632 return; 17633 } 17634 } else { 17635 // The Microsoft ABI requires that we perform the destructor body 17636 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 17637 // the deleting destructor is emitted with the vtable, not with the 17638 // destructor definition as in the Itanium ABI. 17639 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 17640 CXXDestructorDecl *DD = Class->getDestructor(); 17641 if (DD && DD->isVirtual() && !DD->isDeleted()) { 17642 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) { 17643 // If this is an out-of-line declaration, marking it referenced will 17644 // not do anything. Manually call CheckDestructor to look up operator 17645 // delete(). 17646 ContextRAII SavedContext(*this, DD); 17647 CheckDestructor(DD); 17648 } else { 17649 MarkFunctionReferenced(Loc, Class->getDestructor()); 17650 } 17651 } 17652 } 17653 } 17654 17655 // Local classes need to have their virtual members marked 17656 // immediately. For all other classes, we mark their virtual members 17657 // at the end of the translation unit. 17658 if (Class->isLocalClass()) 17659 MarkVirtualMembersReferenced(Loc, Class); 17660 else 17661 VTableUses.push_back(std::make_pair(Class, Loc)); 17662 } 17663 17664 bool Sema::DefineUsedVTables() { 17665 LoadExternalVTableUses(); 17666 if (VTableUses.empty()) 17667 return false; 17668 17669 // Note: The VTableUses vector could grow as a result of marking 17670 // the members of a class as "used", so we check the size each 17671 // time through the loop and prefer indices (which are stable) to 17672 // iterators (which are not). 17673 bool DefinedAnything = false; 17674 for (unsigned I = 0; I != VTableUses.size(); ++I) { 17675 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 17676 if (!Class) 17677 continue; 17678 TemplateSpecializationKind ClassTSK = 17679 Class->getTemplateSpecializationKind(); 17680 17681 SourceLocation Loc = VTableUses[I].second; 17682 17683 bool DefineVTable = true; 17684 17685 // If this class has a key function, but that key function is 17686 // defined in another translation unit, we don't need to emit the 17687 // vtable even though we're using it. 17688 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 17689 if (KeyFunction && !KeyFunction->hasBody()) { 17690 // The key function is in another translation unit. 17691 DefineVTable = false; 17692 TemplateSpecializationKind TSK = 17693 KeyFunction->getTemplateSpecializationKind(); 17694 assert(TSK != TSK_ExplicitInstantiationDefinition && 17695 TSK != TSK_ImplicitInstantiation && 17696 "Instantiations don't have key functions"); 17697 (void)TSK; 17698 } else if (!KeyFunction) { 17699 // If we have a class with no key function that is the subject 17700 // of an explicit instantiation declaration, suppress the 17701 // vtable; it will live with the explicit instantiation 17702 // definition. 17703 bool IsExplicitInstantiationDeclaration = 17704 ClassTSK == TSK_ExplicitInstantiationDeclaration; 17705 for (auto R : Class->redecls()) { 17706 TemplateSpecializationKind TSK 17707 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 17708 if (TSK == TSK_ExplicitInstantiationDeclaration) 17709 IsExplicitInstantiationDeclaration = true; 17710 else if (TSK == TSK_ExplicitInstantiationDefinition) { 17711 IsExplicitInstantiationDeclaration = false; 17712 break; 17713 } 17714 } 17715 17716 if (IsExplicitInstantiationDeclaration) 17717 DefineVTable = false; 17718 } 17719 17720 // The exception specifications for all virtual members may be needed even 17721 // if we are not providing an authoritative form of the vtable in this TU. 17722 // We may choose to emit it available_externally anyway. 17723 if (!DefineVTable) { 17724 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 17725 continue; 17726 } 17727 17728 // Mark all of the virtual members of this class as referenced, so 17729 // that we can build a vtable. Then, tell the AST consumer that a 17730 // vtable for this class is required. 17731 DefinedAnything = true; 17732 MarkVirtualMembersReferenced(Loc, Class); 17733 CXXRecordDecl *Canonical = Class->getCanonicalDecl(); 17734 if (VTablesUsed[Canonical]) 17735 Consumer.HandleVTable(Class); 17736 17737 // Warn if we're emitting a weak vtable. The vtable will be weak if there is 17738 // no key function or the key function is inlined. Don't warn in C++ ABIs 17739 // that lack key functions, since the user won't be able to make one. 17740 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() && 17741 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation && 17742 ClassTSK != TSK_ExplicitInstantiationDefinition) { 17743 const FunctionDecl *KeyFunctionDef = nullptr; 17744 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) && 17745 KeyFunctionDef->isInlined())) 17746 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class; 17747 } 17748 } 17749 VTableUses.clear(); 17750 17751 return DefinedAnything; 17752 } 17753 17754 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 17755 const CXXRecordDecl *RD) { 17756 for (const auto *I : RD->methods()) 17757 if (I->isVirtual() && !I->isPure()) 17758 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 17759 } 17760 17761 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 17762 const CXXRecordDecl *RD, 17763 bool ConstexprOnly) { 17764 // Mark all functions which will appear in RD's vtable as used. 17765 CXXFinalOverriderMap FinalOverriders; 17766 RD->getFinalOverriders(FinalOverriders); 17767 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 17768 E = FinalOverriders.end(); 17769 I != E; ++I) { 17770 for (OverridingMethods::const_iterator OI = I->second.begin(), 17771 OE = I->second.end(); 17772 OI != OE; ++OI) { 17773 assert(OI->second.size() > 0 && "no final overrider"); 17774 CXXMethodDecl *Overrider = OI->second.front().Method; 17775 17776 // C++ [basic.def.odr]p2: 17777 // [...] A virtual member function is used if it is not pure. [...] 17778 if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr())) 17779 MarkFunctionReferenced(Loc, Overrider); 17780 } 17781 } 17782 17783 // Only classes that have virtual bases need a VTT. 17784 if (RD->getNumVBases() == 0) 17785 return; 17786 17787 for (const auto &I : RD->bases()) { 17788 const auto *Base = 17789 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 17790 if (Base->getNumVBases() == 0) 17791 continue; 17792 MarkVirtualMembersReferenced(Loc, Base); 17793 } 17794 } 17795 17796 /// SetIvarInitializers - This routine builds initialization ASTs for the 17797 /// Objective-C implementation whose ivars need be initialized. 17798 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 17799 if (!getLangOpts().CPlusPlus) 17800 return; 17801 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 17802 SmallVector<ObjCIvarDecl*, 8> ivars; 17803 CollectIvarsToConstructOrDestruct(OID, ivars); 17804 if (ivars.empty()) 17805 return; 17806 SmallVector<CXXCtorInitializer*, 32> AllToInit; 17807 for (unsigned i = 0; i < ivars.size(); i++) { 17808 FieldDecl *Field = ivars[i]; 17809 if (Field->isInvalidDecl()) 17810 continue; 17811 17812 CXXCtorInitializer *Member; 17813 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 17814 InitializationKind InitKind = 17815 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 17816 17817 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 17818 ExprResult MemberInit = 17819 InitSeq.Perform(*this, InitEntity, InitKind, None); 17820 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 17821 // Note, MemberInit could actually come back empty if no initialization 17822 // is required (e.g., because it would call a trivial default constructor) 17823 if (!MemberInit.get() || MemberInit.isInvalid()) 17824 continue; 17825 17826 Member = 17827 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 17828 SourceLocation(), 17829 MemberInit.getAs<Expr>(), 17830 SourceLocation()); 17831 AllToInit.push_back(Member); 17832 17833 // Be sure that the destructor is accessible and is marked as referenced. 17834 if (const RecordType *RecordTy = 17835 Context.getBaseElementType(Field->getType()) 17836 ->getAs<RecordType>()) { 17837 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 17838 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 17839 MarkFunctionReferenced(Field->getLocation(), Destructor); 17840 CheckDestructorAccess(Field->getLocation(), Destructor, 17841 PDiag(diag::err_access_dtor_ivar) 17842 << Context.getBaseElementType(Field->getType())); 17843 } 17844 } 17845 } 17846 ObjCImplementation->setIvarInitializers(Context, 17847 AllToInit.data(), AllToInit.size()); 17848 } 17849 } 17850 17851 static 17852 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 17853 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid, 17854 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid, 17855 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current, 17856 Sema &S) { 17857 if (Ctor->isInvalidDecl()) 17858 return; 17859 17860 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 17861 17862 // Target may not be determinable yet, for instance if this is a dependent 17863 // call in an uninstantiated template. 17864 if (Target) { 17865 const FunctionDecl *FNTarget = nullptr; 17866 (void)Target->hasBody(FNTarget); 17867 Target = const_cast<CXXConstructorDecl*>( 17868 cast_or_null<CXXConstructorDecl>(FNTarget)); 17869 } 17870 17871 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 17872 // Avoid dereferencing a null pointer here. 17873 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 17874 17875 if (!Current.insert(Canonical).second) 17876 return; 17877 17878 // We know that beyond here, we aren't chaining into a cycle. 17879 if (!Target || !Target->isDelegatingConstructor() || 17880 Target->isInvalidDecl() || Valid.count(TCanonical)) { 17881 Valid.insert(Current.begin(), Current.end()); 17882 Current.clear(); 17883 // We've hit a cycle. 17884 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 17885 Current.count(TCanonical)) { 17886 // If we haven't diagnosed this cycle yet, do so now. 17887 if (!Invalid.count(TCanonical)) { 17888 S.Diag((*Ctor->init_begin())->getSourceLocation(), 17889 diag::warn_delegating_ctor_cycle) 17890 << Ctor; 17891 17892 // Don't add a note for a function delegating directly to itself. 17893 if (TCanonical != Canonical) 17894 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 17895 17896 CXXConstructorDecl *C = Target; 17897 while (C->getCanonicalDecl() != Canonical) { 17898 const FunctionDecl *FNTarget = nullptr; 17899 (void)C->getTargetConstructor()->hasBody(FNTarget); 17900 assert(FNTarget && "Ctor cycle through bodiless function"); 17901 17902 C = const_cast<CXXConstructorDecl*>( 17903 cast<CXXConstructorDecl>(FNTarget)); 17904 S.Diag(C->getLocation(), diag::note_which_delegates_to); 17905 } 17906 } 17907 17908 Invalid.insert(Current.begin(), Current.end()); 17909 Current.clear(); 17910 } else { 17911 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 17912 } 17913 } 17914 17915 17916 void Sema::CheckDelegatingCtorCycles() { 17917 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 17918 17919 for (DelegatingCtorDeclsType::iterator 17920 I = DelegatingCtorDecls.begin(ExternalSource), 17921 E = DelegatingCtorDecls.end(); 17922 I != E; ++I) 17923 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 17924 17925 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI) 17926 (*CI)->setInvalidDecl(); 17927 } 17928 17929 namespace { 17930 /// AST visitor that finds references to the 'this' expression. 17931 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 17932 Sema &S; 17933 17934 public: 17935 explicit FindCXXThisExpr(Sema &S) : S(S) { } 17936 17937 bool VisitCXXThisExpr(CXXThisExpr *E) { 17938 S.Diag(E->getLocation(), diag::err_this_static_member_func) 17939 << E->isImplicit(); 17940 return false; 17941 } 17942 }; 17943 } 17944 17945 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 17946 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 17947 if (!TSInfo) 17948 return false; 17949 17950 TypeLoc TL = TSInfo->getTypeLoc(); 17951 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 17952 if (!ProtoTL) 17953 return false; 17954 17955 // C++11 [expr.prim.general]p3: 17956 // [The expression this] shall not appear before the optional 17957 // cv-qualifier-seq and it shall not appear within the declaration of a 17958 // static member function (although its type and value category are defined 17959 // within a static member function as they are within a non-static member 17960 // function). [ Note: this is because declaration matching does not occur 17961 // until the complete declarator is known. - end note ] 17962 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 17963 FindCXXThisExpr Finder(*this); 17964 17965 // If the return type came after the cv-qualifier-seq, check it now. 17966 if (Proto->hasTrailingReturn() && 17967 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 17968 return true; 17969 17970 // Check the exception specification. 17971 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 17972 return true; 17973 17974 // Check the trailing requires clause 17975 if (Expr *E = Method->getTrailingRequiresClause()) 17976 if (!Finder.TraverseStmt(E)) 17977 return true; 17978 17979 return checkThisInStaticMemberFunctionAttributes(Method); 17980 } 17981 17982 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 17983 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 17984 if (!TSInfo) 17985 return false; 17986 17987 TypeLoc TL = TSInfo->getTypeLoc(); 17988 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 17989 if (!ProtoTL) 17990 return false; 17991 17992 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 17993 FindCXXThisExpr Finder(*this); 17994 17995 switch (Proto->getExceptionSpecType()) { 17996 case EST_Unparsed: 17997 case EST_Uninstantiated: 17998 case EST_Unevaluated: 17999 case EST_BasicNoexcept: 18000 case EST_NoThrow: 18001 case EST_DynamicNone: 18002 case EST_MSAny: 18003 case EST_None: 18004 break; 18005 18006 case EST_DependentNoexcept: 18007 case EST_NoexceptFalse: 18008 case EST_NoexceptTrue: 18009 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 18010 return true; 18011 LLVM_FALLTHROUGH; 18012 18013 case EST_Dynamic: 18014 for (const auto &E : Proto->exceptions()) { 18015 if (!Finder.TraverseType(E)) 18016 return true; 18017 } 18018 break; 18019 } 18020 18021 return false; 18022 } 18023 18024 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 18025 FindCXXThisExpr Finder(*this); 18026 18027 // Check attributes. 18028 for (const auto *A : Method->attrs()) { 18029 // FIXME: This should be emitted by tblgen. 18030 Expr *Arg = nullptr; 18031 ArrayRef<Expr *> Args; 18032 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 18033 Arg = G->getArg(); 18034 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 18035 Arg = G->getArg(); 18036 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 18037 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 18038 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 18039 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 18040 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 18041 Arg = ETLF->getSuccessValue(); 18042 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 18043 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 18044 Arg = STLF->getSuccessValue(); 18045 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 18046 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 18047 Arg = LR->getArg(); 18048 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 18049 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 18050 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 18051 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 18052 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 18053 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 18054 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 18055 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 18056 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 18057 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 18058 18059 if (Arg && !Finder.TraverseStmt(Arg)) 18060 return true; 18061 18062 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 18063 if (!Finder.TraverseStmt(Args[I])) 18064 return true; 18065 } 18066 } 18067 18068 return false; 18069 } 18070 18071 void Sema::checkExceptionSpecification( 18072 bool IsTopLevel, ExceptionSpecificationType EST, 18073 ArrayRef<ParsedType> DynamicExceptions, 18074 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 18075 SmallVectorImpl<QualType> &Exceptions, 18076 FunctionProtoType::ExceptionSpecInfo &ESI) { 18077 Exceptions.clear(); 18078 ESI.Type = EST; 18079 if (EST == EST_Dynamic) { 18080 Exceptions.reserve(DynamicExceptions.size()); 18081 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 18082 // FIXME: Preserve type source info. 18083 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 18084 18085 if (IsTopLevel) { 18086 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 18087 collectUnexpandedParameterPacks(ET, Unexpanded); 18088 if (!Unexpanded.empty()) { 18089 DiagnoseUnexpandedParameterPacks( 18090 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 18091 Unexpanded); 18092 continue; 18093 } 18094 } 18095 18096 // Check that the type is valid for an exception spec, and 18097 // drop it if not. 18098 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 18099 Exceptions.push_back(ET); 18100 } 18101 ESI.Exceptions = Exceptions; 18102 return; 18103 } 18104 18105 if (isComputedNoexcept(EST)) { 18106 assert((NoexceptExpr->isTypeDependent() || 18107 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 18108 Context.BoolTy) && 18109 "Parser should have made sure that the expression is boolean"); 18110 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 18111 ESI.Type = EST_BasicNoexcept; 18112 return; 18113 } 18114 18115 ESI.NoexceptExpr = NoexceptExpr; 18116 return; 18117 } 18118 } 18119 18120 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 18121 ExceptionSpecificationType EST, 18122 SourceRange SpecificationRange, 18123 ArrayRef<ParsedType> DynamicExceptions, 18124 ArrayRef<SourceRange> DynamicExceptionRanges, 18125 Expr *NoexceptExpr) { 18126 if (!MethodD) 18127 return; 18128 18129 // Dig out the method we're referring to. 18130 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 18131 MethodD = FunTmpl->getTemplatedDecl(); 18132 18133 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 18134 if (!Method) 18135 return; 18136 18137 // Check the exception specification. 18138 llvm::SmallVector<QualType, 4> Exceptions; 18139 FunctionProtoType::ExceptionSpecInfo ESI; 18140 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 18141 DynamicExceptionRanges, NoexceptExpr, Exceptions, 18142 ESI); 18143 18144 // Update the exception specification on the function type. 18145 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 18146 18147 if (Method->isStatic()) 18148 checkThisInStaticMemberFunctionExceptionSpec(Method); 18149 18150 if (Method->isVirtual()) { 18151 // Check overrides, which we previously had to delay. 18152 for (const CXXMethodDecl *O : Method->overridden_methods()) 18153 CheckOverridingFunctionExceptionSpec(Method, O); 18154 } 18155 } 18156 18157 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 18158 /// 18159 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 18160 SourceLocation DeclStart, Declarator &D, 18161 Expr *BitWidth, 18162 InClassInitStyle InitStyle, 18163 AccessSpecifier AS, 18164 const ParsedAttr &MSPropertyAttr) { 18165 IdentifierInfo *II = D.getIdentifier(); 18166 if (!II) { 18167 Diag(DeclStart, diag::err_anonymous_property); 18168 return nullptr; 18169 } 18170 SourceLocation Loc = D.getIdentifierLoc(); 18171 18172 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 18173 QualType T = TInfo->getType(); 18174 if (getLangOpts().CPlusPlus) { 18175 CheckExtraCXXDefaultArguments(D); 18176 18177 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 18178 UPPC_DataMemberType)) { 18179 D.setInvalidType(); 18180 T = Context.IntTy; 18181 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 18182 } 18183 } 18184 18185 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 18186 18187 if (D.getDeclSpec().isInlineSpecified()) 18188 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 18189 << getLangOpts().CPlusPlus17; 18190 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 18191 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 18192 diag::err_invalid_thread) 18193 << DeclSpec::getSpecifierName(TSCS); 18194 18195 // Check to see if this name was declared as a member previously 18196 NamedDecl *PrevDecl = nullptr; 18197 LookupResult Previous(*this, II, Loc, LookupMemberName, 18198 ForVisibleRedeclaration); 18199 LookupName(Previous, S); 18200 switch (Previous.getResultKind()) { 18201 case LookupResult::Found: 18202 case LookupResult::FoundUnresolvedValue: 18203 PrevDecl = Previous.getAsSingle<NamedDecl>(); 18204 break; 18205 18206 case LookupResult::FoundOverloaded: 18207 PrevDecl = Previous.getRepresentativeDecl(); 18208 break; 18209 18210 case LookupResult::NotFound: 18211 case LookupResult::NotFoundInCurrentInstantiation: 18212 case LookupResult::Ambiguous: 18213 break; 18214 } 18215 18216 if (PrevDecl && PrevDecl->isTemplateParameter()) { 18217 // Maybe we will complain about the shadowed template parameter. 18218 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 18219 // Just pretend that we didn't see the previous declaration. 18220 PrevDecl = nullptr; 18221 } 18222 18223 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 18224 PrevDecl = nullptr; 18225 18226 SourceLocation TSSL = D.getBeginLoc(); 18227 MSPropertyDecl *NewPD = 18228 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL, 18229 MSPropertyAttr.getPropertyDataGetter(), 18230 MSPropertyAttr.getPropertyDataSetter()); 18231 ProcessDeclAttributes(TUScope, NewPD, D); 18232 NewPD->setAccess(AS); 18233 18234 if (NewPD->isInvalidDecl()) 18235 Record->setInvalidDecl(); 18236 18237 if (D.getDeclSpec().isModulePrivateSpecified()) 18238 NewPD->setModulePrivate(); 18239 18240 if (NewPD->isInvalidDecl() && PrevDecl) { 18241 // Don't introduce NewFD into scope; there's already something 18242 // with the same name in the same scope. 18243 } else if (II) { 18244 PushOnScopeChains(NewPD, S); 18245 } else 18246 Record->addDecl(NewPD); 18247 18248 return NewPD; 18249 } 18250 18251 void Sema::ActOnStartFunctionDeclarationDeclarator( 18252 Declarator &Declarator, unsigned TemplateParameterDepth) { 18253 auto &Info = InventedParameterInfos.emplace_back(); 18254 TemplateParameterList *ExplicitParams = nullptr; 18255 ArrayRef<TemplateParameterList *> ExplicitLists = 18256 Declarator.getTemplateParameterLists(); 18257 if (!ExplicitLists.empty()) { 18258 bool IsMemberSpecialization, IsInvalid; 18259 ExplicitParams = MatchTemplateParametersToScopeSpecifier( 18260 Declarator.getBeginLoc(), Declarator.getIdentifierLoc(), 18261 Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr, 18262 ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid, 18263 /*SuppressDiagnostic=*/true); 18264 } 18265 if (ExplicitParams) { 18266 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth(); 18267 for (NamedDecl *Param : *ExplicitParams) 18268 Info.TemplateParams.push_back(Param); 18269 Info.NumExplicitTemplateParams = ExplicitParams->size(); 18270 } else { 18271 Info.AutoTemplateParameterDepth = TemplateParameterDepth; 18272 Info.NumExplicitTemplateParams = 0; 18273 } 18274 } 18275 18276 void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) { 18277 auto &FSI = InventedParameterInfos.back(); 18278 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) { 18279 if (FSI.NumExplicitTemplateParams != 0) { 18280 TemplateParameterList *ExplicitParams = 18281 Declarator.getTemplateParameterLists().back(); 18282 Declarator.setInventedTemplateParameterList( 18283 TemplateParameterList::Create( 18284 Context, ExplicitParams->getTemplateLoc(), 18285 ExplicitParams->getLAngleLoc(), FSI.TemplateParams, 18286 ExplicitParams->getRAngleLoc(), 18287 ExplicitParams->getRequiresClause())); 18288 } else { 18289 Declarator.setInventedTemplateParameterList( 18290 TemplateParameterList::Create( 18291 Context, SourceLocation(), SourceLocation(), FSI.TemplateParams, 18292 SourceLocation(), /*RequiresClause=*/nullptr)); 18293 } 18294 } 18295 InventedParameterInfos.pop_back(); 18296 } 18297