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/TargetInfo.h" 30 #include "clang/Lex/LiteralSupport.h" 31 #include "clang/Lex/Preprocessor.h" 32 #include "clang/Sema/CXXFieldCollector.h" 33 #include "clang/Sema/DeclSpec.h" 34 #include "clang/Sema/Initialization.h" 35 #include "clang/Sema/Lookup.h" 36 #include "clang/Sema/ParsedTemplate.h" 37 #include "clang/Sema/Scope.h" 38 #include "clang/Sema/ScopeInfo.h" 39 #include "clang/Sema/SemaInternal.h" 40 #include "clang/Sema/Template.h" 41 #include "llvm/ADT/ScopeExit.h" 42 #include "llvm/ADT/SmallString.h" 43 #include "llvm/ADT/STLExtras.h" 44 #include "llvm/ADT/StringExtras.h" 45 #include <map> 46 #include <set> 47 48 using namespace clang; 49 50 //===----------------------------------------------------------------------===// 51 // CheckDefaultArgumentVisitor 52 //===----------------------------------------------------------------------===// 53 54 namespace { 55 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 56 /// the default argument of a parameter to determine whether it 57 /// contains any ill-formed subexpressions. For example, this will 58 /// diagnose the use of local variables or parameters within the 59 /// default argument expression. 60 class CheckDefaultArgumentVisitor 61 : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> { 62 Sema &S; 63 const Expr *DefaultArg; 64 65 public: 66 CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg) 67 : S(S), DefaultArg(DefaultArg) {} 68 69 bool VisitExpr(const Expr *Node); 70 bool VisitDeclRefExpr(const DeclRefExpr *DRE); 71 bool VisitCXXThisExpr(const CXXThisExpr *ThisE); 72 bool VisitLambdaExpr(const LambdaExpr *Lambda); 73 bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE); 74 }; 75 76 /// VisitExpr - Visit all of the children of this expression. 77 bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) { 78 bool IsInvalid = false; 79 for (const Stmt *SubStmt : Node->children()) 80 IsInvalid |= Visit(SubStmt); 81 return IsInvalid; 82 } 83 84 /// VisitDeclRefExpr - Visit a reference to a declaration, to 85 /// determine whether this declaration can be used in the default 86 /// argument expression. 87 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) { 88 const NamedDecl *Decl = DRE->getDecl(); 89 if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) { 90 // C++ [dcl.fct.default]p9: 91 // [...] parameters of a function shall not be used in default 92 // argument expressions, even if they are not evaluated. [...] 93 // 94 // C++17 [dcl.fct.default]p9 (by CWG 2082): 95 // [...] A parameter shall not appear as a potentially-evaluated 96 // expression in a default argument. [...] 97 // 98 if (DRE->isNonOdrUse() != NOUR_Unevaluated) 99 return S.Diag(DRE->getBeginLoc(), 100 diag::err_param_default_argument_references_param) 101 << Param->getDeclName() << DefaultArg->getSourceRange(); 102 } else if (const auto *VDecl = dyn_cast<VarDecl>(Decl)) { 103 // C++ [dcl.fct.default]p7: 104 // Local variables shall not be used in default argument 105 // expressions. 106 // 107 // C++17 [dcl.fct.default]p7 (by CWG 2082): 108 // A local variable shall not appear as a potentially-evaluated 109 // expression in a default argument. 110 // 111 // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346): 112 // Note: A local variable cannot be odr-used (6.3) in a default argument. 113 // 114 if (VDecl->isLocalVarDecl() && !DRE->isNonOdrUse()) 115 return S.Diag(DRE->getBeginLoc(), 116 diag::err_param_default_argument_references_local) 117 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 118 } 119 120 return false; 121 } 122 123 /// VisitCXXThisExpr - Visit a C++ "this" expression. 124 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) { 125 // C++ [dcl.fct.default]p8: 126 // The keyword this shall not be used in a default argument of a 127 // member function. 128 return S.Diag(ThisE->getBeginLoc(), 129 diag::err_param_default_argument_references_this) 130 << ThisE->getSourceRange(); 131 } 132 133 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr( 134 const PseudoObjectExpr *POE) { 135 bool Invalid = false; 136 for (const Expr *E : POE->semantics()) { 137 // Look through bindings. 138 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) { 139 E = OVE->getSourceExpr(); 140 assert(E && "pseudo-object binding without source expression?"); 141 } 142 143 Invalid |= Visit(E); 144 } 145 return Invalid; 146 } 147 148 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) { 149 // C++11 [expr.lambda.prim]p13: 150 // A lambda-expression appearing in a default argument shall not 151 // implicitly or explicitly capture any entity. 152 if (Lambda->capture_begin() == Lambda->capture_end()) 153 return false; 154 155 return S.Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg); 156 } 157 } // namespace 158 159 void 160 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc, 161 const CXXMethodDecl *Method) { 162 // If we have an MSAny spec already, don't bother. 163 if (!Method || ComputedEST == EST_MSAny) 164 return; 165 166 const FunctionProtoType *Proto 167 = Method->getType()->getAs<FunctionProtoType>(); 168 Proto = Self->ResolveExceptionSpec(CallLoc, Proto); 169 if (!Proto) 170 return; 171 172 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 173 174 // If we have a throw-all spec at this point, ignore the function. 175 if (ComputedEST == EST_None) 176 return; 177 178 if (EST == EST_None && Method->hasAttr<NoThrowAttr>()) 179 EST = EST_BasicNoexcept; 180 181 switch (EST) { 182 case EST_Unparsed: 183 case EST_Uninstantiated: 184 case EST_Unevaluated: 185 llvm_unreachable("should not see unresolved exception specs here"); 186 187 // If this function can throw any exceptions, make a note of that. 188 case EST_MSAny: 189 case EST_None: 190 // FIXME: Whichever we see last of MSAny and None determines our result. 191 // We should make a consistent, order-independent choice here. 192 ClearExceptions(); 193 ComputedEST = EST; 194 return; 195 case EST_NoexceptFalse: 196 ClearExceptions(); 197 ComputedEST = EST_None; 198 return; 199 // FIXME: If the call to this decl is using any of its default arguments, we 200 // need to search them for potentially-throwing calls. 201 // If this function has a basic noexcept, it doesn't affect the outcome. 202 case EST_BasicNoexcept: 203 case EST_NoexceptTrue: 204 case EST_NoThrow: 205 return; 206 // If we're still at noexcept(true) and there's a throw() callee, 207 // change to that specification. 208 case EST_DynamicNone: 209 if (ComputedEST == EST_BasicNoexcept) 210 ComputedEST = EST_DynamicNone; 211 return; 212 case EST_DependentNoexcept: 213 llvm_unreachable( 214 "should not generate implicit declarations for dependent cases"); 215 case EST_Dynamic: 216 break; 217 } 218 assert(EST == EST_Dynamic && "EST case not considered earlier."); 219 assert(ComputedEST != EST_None && 220 "Shouldn't collect exceptions when throw-all is guaranteed."); 221 ComputedEST = EST_Dynamic; 222 // Record the exceptions in this function's exception specification. 223 for (const auto &E : Proto->exceptions()) 224 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second) 225 Exceptions.push_back(E); 226 } 227 228 void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) { 229 if (!S || ComputedEST == EST_MSAny) 230 return; 231 232 // FIXME: 233 // 234 // C++0x [except.spec]p14: 235 // [An] implicit exception-specification specifies the type-id T if and 236 // only if T is allowed by the exception-specification of a function directly 237 // invoked by f's implicit definition; f shall allow all exceptions if any 238 // function it directly invokes allows all exceptions, and f shall allow no 239 // exceptions if every function it directly invokes allows no exceptions. 240 // 241 // Note in particular that if an implicit exception-specification is generated 242 // for a function containing a throw-expression, that specification can still 243 // be noexcept(true). 244 // 245 // Note also that 'directly invoked' is not defined in the standard, and there 246 // is no indication that we should only consider potentially-evaluated calls. 247 // 248 // Ultimately we should implement the intent of the standard: the exception 249 // specification should be the set of exceptions which can be thrown by the 250 // implicit definition. For now, we assume that any non-nothrow expression can 251 // throw any exception. 252 253 if (Self->canThrow(S)) 254 ComputedEST = EST_None; 255 } 256 257 ExprResult Sema::ConvertParamDefaultArgument(const ParmVarDecl *Param, 258 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_RValue)); 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) 385 OpaqueValueExpr(EqualLoc, 386 Param->getType().getNonReferenceType(), 387 VK_RValue)); 388 } 389 390 /// CheckExtraCXXDefaultArguments - Check for any extra default 391 /// arguments in the declarator, which is not a function declaration 392 /// or definition and therefore is not permitted to have default 393 /// arguments. This routine should be invoked for every declarator 394 /// that is not a function declaration or definition. 395 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 396 // C++ [dcl.fct.default]p3 397 // A default argument expression shall be specified only in the 398 // parameter-declaration-clause of a function declaration or in a 399 // template-parameter (14.1). It shall not be specified for a 400 // parameter pack. If it is specified in a 401 // parameter-declaration-clause, it shall not occur within a 402 // declarator or abstract-declarator of a parameter-declaration. 403 bool MightBeFunction = D.isFunctionDeclarationContext(); 404 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 405 DeclaratorChunk &chunk = D.getTypeObject(i); 406 if (chunk.Kind == DeclaratorChunk::Function) { 407 if (MightBeFunction) { 408 // This is a function declaration. It can have default arguments, but 409 // keep looking in case its return type is a function type with default 410 // arguments. 411 MightBeFunction = false; 412 continue; 413 } 414 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e; 415 ++argIdx) { 416 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param); 417 if (Param->hasUnparsedDefaultArg()) { 418 std::unique_ptr<CachedTokens> Toks = 419 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens); 420 SourceRange SR; 421 if (Toks->size() > 1) 422 SR = SourceRange((*Toks)[1].getLocation(), 423 Toks->back().getLocation()); 424 else 425 SR = UnparsedDefaultArgLocs[Param]; 426 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 427 << SR; 428 } else if (Param->getDefaultArg()) { 429 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 430 << Param->getDefaultArg()->getSourceRange(); 431 Param->setDefaultArg(nullptr); 432 } 433 } 434 } else if (chunk.Kind != DeclaratorChunk::Paren) { 435 MightBeFunction = false; 436 } 437 } 438 } 439 440 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { 441 return std::any_of(FD->param_begin(), FD->param_end(), [](ParmVarDecl *P) { 442 return P->hasDefaultArg() && !P->hasInheritedDefaultArg(); 443 }); 444 } 445 446 /// MergeCXXFunctionDecl - Merge two declarations of the same C++ 447 /// function, once we already know that they have the same 448 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an 449 /// error, false otherwise. 450 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 451 Scope *S) { 452 bool Invalid = false; 453 454 // The declaration context corresponding to the scope is the semantic 455 // parent, unless this is a local function declaration, in which case 456 // it is that surrounding function. 457 DeclContext *ScopeDC = New->isLocalExternDecl() 458 ? New->getLexicalDeclContext() 459 : New->getDeclContext(); 460 461 // Find the previous declaration for the purpose of default arguments. 462 FunctionDecl *PrevForDefaultArgs = Old; 463 for (/**/; PrevForDefaultArgs; 464 // Don't bother looking back past the latest decl if this is a local 465 // extern declaration; nothing else could work. 466 PrevForDefaultArgs = New->isLocalExternDecl() 467 ? nullptr 468 : PrevForDefaultArgs->getPreviousDecl()) { 469 // Ignore hidden declarations. 470 if (!LookupResult::isVisible(*this, PrevForDefaultArgs)) 471 continue; 472 473 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) && 474 !New->isCXXClassMember()) { 475 // Ignore default arguments of old decl if they are not in 476 // the same scope and this is not an out-of-line definition of 477 // a member function. 478 continue; 479 } 480 481 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) { 482 // If only one of these is a local function declaration, then they are 483 // declared in different scopes, even though isDeclInScope may think 484 // they're in the same scope. (If both are local, the scope check is 485 // sufficient, and if neither is local, then they are in the same scope.) 486 continue; 487 } 488 489 // We found the right previous declaration. 490 break; 491 } 492 493 // C++ [dcl.fct.default]p4: 494 // For non-template functions, default arguments can be added in 495 // later declarations of a function in the same 496 // scope. Declarations in different scopes have completely 497 // distinct sets of default arguments. That is, declarations in 498 // inner scopes do not acquire default arguments from 499 // declarations in outer scopes, and vice versa. In a given 500 // function declaration, all parameters subsequent to a 501 // parameter with a default argument shall have default 502 // arguments supplied in this or previous declarations. A 503 // default argument shall not be redefined by a later 504 // declaration (not even to the same value). 505 // 506 // C++ [dcl.fct.default]p6: 507 // Except for member functions of class templates, the default arguments 508 // in a member function definition that appears outside of the class 509 // definition are added to the set of default arguments provided by the 510 // member function declaration in the class definition. 511 for (unsigned p = 0, NumParams = PrevForDefaultArgs 512 ? PrevForDefaultArgs->getNumParams() 513 : 0; 514 p < NumParams; ++p) { 515 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p); 516 ParmVarDecl *NewParam = New->getParamDecl(p); 517 518 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false; 519 bool NewParamHasDfl = NewParam->hasDefaultArg(); 520 521 if (OldParamHasDfl && NewParamHasDfl) { 522 unsigned DiagDefaultParamID = 523 diag::err_param_default_argument_redefinition; 524 525 // MSVC accepts that default parameters be redefined for member functions 526 // of template class. The new default parameter's value is ignored. 527 Invalid = true; 528 if (getLangOpts().MicrosoftExt) { 529 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New); 530 if (MD && MD->getParent()->getDescribedClassTemplate()) { 531 // Merge the old default argument into the new parameter. 532 NewParam->setHasInheritedDefaultArg(); 533 if (OldParam->hasUninstantiatedDefaultArg()) 534 NewParam->setUninstantiatedDefaultArg( 535 OldParam->getUninstantiatedDefaultArg()); 536 else 537 NewParam->setDefaultArg(OldParam->getInit()); 538 DiagDefaultParamID = diag::ext_param_default_argument_redefinition; 539 Invalid = false; 540 } 541 } 542 543 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 544 // hint here. Alternatively, we could walk the type-source information 545 // for NewParam to find the last source location in the type... but it 546 // isn't worth the effort right now. This is the kind of test case that 547 // is hard to get right: 548 // int f(int); 549 // void g(int (*fp)(int) = f); 550 // void g(int (*fp)(int) = &f); 551 Diag(NewParam->getLocation(), DiagDefaultParamID) 552 << NewParam->getDefaultArgRange(); 553 554 // Look for the function declaration where the default argument was 555 // actually written, which may be a declaration prior to Old. 556 for (auto Older = PrevForDefaultArgs; 557 OldParam->hasInheritedDefaultArg(); /**/) { 558 Older = Older->getPreviousDecl(); 559 OldParam = Older->getParamDecl(p); 560 } 561 562 Diag(OldParam->getLocation(), diag::note_previous_definition) 563 << OldParam->getDefaultArgRange(); 564 } else if (OldParamHasDfl) { 565 // Merge the old default argument into the new parameter unless the new 566 // function is a friend declaration in a template class. In the latter 567 // case the default arguments will be inherited when the friend 568 // declaration will be instantiated. 569 if (New->getFriendObjectKind() == Decl::FOK_None || 570 !New->getLexicalDeclContext()->isDependentContext()) { 571 // It's important to use getInit() here; getDefaultArg() 572 // strips off any top-level ExprWithCleanups. 573 NewParam->setHasInheritedDefaultArg(); 574 if (OldParam->hasUnparsedDefaultArg()) 575 NewParam->setUnparsedDefaultArg(); 576 else if (OldParam->hasUninstantiatedDefaultArg()) 577 NewParam->setUninstantiatedDefaultArg( 578 OldParam->getUninstantiatedDefaultArg()); 579 else 580 NewParam->setDefaultArg(OldParam->getInit()); 581 } 582 } else if (NewParamHasDfl) { 583 if (New->getDescribedFunctionTemplate()) { 584 // Paragraph 4, quoted above, only applies to non-template functions. 585 Diag(NewParam->getLocation(), 586 diag::err_param_default_argument_template_redecl) 587 << NewParam->getDefaultArgRange(); 588 Diag(PrevForDefaultArgs->getLocation(), 589 diag::note_template_prev_declaration) 590 << false; 591 } else if (New->getTemplateSpecializationKind() 592 != TSK_ImplicitInstantiation && 593 New->getTemplateSpecializationKind() != TSK_Undeclared) { 594 // C++ [temp.expr.spec]p21: 595 // Default function arguments shall not be specified in a declaration 596 // or a definition for one of the following explicit specializations: 597 // - the explicit specialization of a function template; 598 // - the explicit specialization of a member function template; 599 // - the explicit specialization of a member function of a class 600 // template where the class template specialization to which the 601 // member function specialization belongs is implicitly 602 // instantiated. 603 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 604 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 605 << New->getDeclName() 606 << NewParam->getDefaultArgRange(); 607 } else if (New->getDeclContext()->isDependentContext()) { 608 // C++ [dcl.fct.default]p6 (DR217): 609 // Default arguments for a member function of a class template shall 610 // be specified on the initial declaration of the member function 611 // within the class template. 612 // 613 // Reading the tea leaves a bit in DR217 and its reference to DR205 614 // leads me to the conclusion that one cannot add default function 615 // arguments for an out-of-line definition of a member function of a 616 // dependent type. 617 int WhichKind = 2; 618 if (CXXRecordDecl *Record 619 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 620 if (Record->getDescribedClassTemplate()) 621 WhichKind = 0; 622 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 623 WhichKind = 1; 624 else 625 WhichKind = 2; 626 } 627 628 Diag(NewParam->getLocation(), 629 diag::err_param_default_argument_member_template_redecl) 630 << WhichKind 631 << NewParam->getDefaultArgRange(); 632 } 633 } 634 } 635 636 // DR1344: If a default argument is added outside a class definition and that 637 // default argument makes the function a special member function, the program 638 // is ill-formed. This can only happen for constructors. 639 if (isa<CXXConstructorDecl>(New) && 640 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 641 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 642 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 643 if (NewSM != OldSM) { 644 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 645 assert(NewParam->hasDefaultArg()); 646 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 647 << NewParam->getDefaultArgRange() << NewSM; 648 Diag(Old->getLocation(), diag::note_previous_declaration); 649 } 650 } 651 652 const FunctionDecl *Def; 653 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 654 // template has a constexpr specifier then all its declarations shall 655 // contain the constexpr specifier. 656 if (New->getConstexprKind() != Old->getConstexprKind()) { 657 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 658 << New << static_cast<int>(New->getConstexprKind()) 659 << static_cast<int>(Old->getConstexprKind()); 660 Diag(Old->getLocation(), diag::note_previous_declaration); 661 Invalid = true; 662 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() && 663 Old->isDefined(Def) && 664 // If a friend function is inlined but does not have 'inline' 665 // specifier, it is a definition. Do not report attribute conflict 666 // in this case, redefinition will be diagnosed later. 667 (New->isInlineSpecified() || 668 New->getFriendObjectKind() == Decl::FOK_None)) { 669 // C++11 [dcl.fcn.spec]p4: 670 // If the definition of a function appears in a translation unit before its 671 // first declaration as inline, the program is ill-formed. 672 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 673 Diag(Def->getLocation(), diag::note_previous_definition); 674 Invalid = true; 675 } 676 677 // C++17 [temp.deduct.guide]p3: 678 // Two deduction guide declarations in the same translation unit 679 // for the same class template shall not have equivalent 680 // parameter-declaration-clauses. 681 if (isa<CXXDeductionGuideDecl>(New) && 682 !New->isFunctionTemplateSpecialization() && isVisible(Old)) { 683 Diag(New->getLocation(), diag::err_deduction_guide_redeclared); 684 Diag(Old->getLocation(), diag::note_previous_declaration); 685 } 686 687 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 688 // argument expression, that declaration shall be a definition and shall be 689 // the only declaration of the function or function template in the 690 // translation unit. 691 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 692 functionDeclHasDefaultArgument(Old)) { 693 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 694 Diag(Old->getLocation(), diag::note_previous_declaration); 695 Invalid = true; 696 } 697 698 // C++11 [temp.friend]p4 (DR329): 699 // When a function is defined in a friend function declaration in a class 700 // template, the function is instantiated when the function is odr-used. 701 // The same restrictions on multiple declarations and definitions that 702 // apply to non-template function declarations and definitions also apply 703 // to these implicit definitions. 704 const FunctionDecl *OldDefinition = nullptr; 705 if (New->isThisDeclarationInstantiatedFromAFriendDefinition() && 706 Old->isDefined(OldDefinition, true)) 707 CheckForFunctionRedefinition(New, OldDefinition); 708 709 return Invalid; 710 } 711 712 NamedDecl * 713 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D, 714 MultiTemplateParamsArg TemplateParamLists) { 715 assert(D.isDecompositionDeclarator()); 716 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 717 718 // The syntax only allows a decomposition declarator as a simple-declaration, 719 // a for-range-declaration, or a condition in Clang, but we parse it in more 720 // cases than that. 721 if (!D.mayHaveDecompositionDeclarator()) { 722 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 723 << Decomp.getSourceRange(); 724 return nullptr; 725 } 726 727 if (!TemplateParamLists.empty()) { 728 // FIXME: There's no rule against this, but there are also no rules that 729 // would actually make it usable, so we reject it for now. 730 Diag(TemplateParamLists.front()->getTemplateLoc(), 731 diag::err_decomp_decl_template); 732 return nullptr; 733 } 734 735 Diag(Decomp.getLSquareLoc(), 736 !getLangOpts().CPlusPlus17 737 ? diag::ext_decomp_decl 738 : D.getContext() == DeclaratorContext::Condition 739 ? diag::ext_decomp_decl_cond 740 : diag::warn_cxx14_compat_decomp_decl) 741 << Decomp.getSourceRange(); 742 743 // The semantic context is always just the current context. 744 DeclContext *const DC = CurContext; 745 746 // C++17 [dcl.dcl]/8: 747 // The decl-specifier-seq shall contain only the type-specifier auto 748 // and cv-qualifiers. 749 // C++2a [dcl.dcl]/8: 750 // If decl-specifier-seq contains any decl-specifier other than static, 751 // thread_local, auto, or cv-qualifiers, the program is ill-formed. 752 auto &DS = D.getDeclSpec(); 753 { 754 SmallVector<StringRef, 8> BadSpecifiers; 755 SmallVector<SourceLocation, 8> BadSpecifierLocs; 756 SmallVector<StringRef, 8> CPlusPlus20Specifiers; 757 SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs; 758 if (auto SCS = DS.getStorageClassSpec()) { 759 if (SCS == DeclSpec::SCS_static) { 760 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS)); 761 CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 762 } else { 763 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS)); 764 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 765 } 766 } 767 if (auto TSCS = DS.getThreadStorageClassSpec()) { 768 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS)); 769 CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc()); 770 } 771 if (DS.hasConstexprSpecifier()) { 772 BadSpecifiers.push_back( 773 DeclSpec::getSpecifierName(DS.getConstexprSpecifier())); 774 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc()); 775 } 776 if (DS.isInlineSpecified()) { 777 BadSpecifiers.push_back("inline"); 778 BadSpecifierLocs.push_back(DS.getInlineSpecLoc()); 779 } 780 if (!BadSpecifiers.empty()) { 781 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec); 782 Err << (int)BadSpecifiers.size() 783 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " "); 784 // Don't add FixItHints to remove the specifiers; we do still respect 785 // them when building the underlying variable. 786 for (auto Loc : BadSpecifierLocs) 787 Err << SourceRange(Loc, Loc); 788 } else if (!CPlusPlus20Specifiers.empty()) { 789 auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(), 790 getLangOpts().CPlusPlus20 791 ? diag::warn_cxx17_compat_decomp_decl_spec 792 : diag::ext_decomp_decl_spec); 793 Warn << (int)CPlusPlus20Specifiers.size() 794 << llvm::join(CPlusPlus20Specifiers.begin(), 795 CPlusPlus20Specifiers.end(), " "); 796 for (auto Loc : CPlusPlus20SpecifierLocs) 797 Warn << SourceRange(Loc, Loc); 798 } 799 // We can't recover from it being declared as a typedef. 800 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 801 return nullptr; 802 } 803 804 // C++2a [dcl.struct.bind]p1: 805 // A cv that includes volatile is deprecated 806 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) && 807 getLangOpts().CPlusPlus20) 808 Diag(DS.getVolatileSpecLoc(), 809 diag::warn_deprecated_volatile_structured_binding); 810 811 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 812 QualType R = TInfo->getType(); 813 814 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 815 UPPC_DeclarationType)) 816 D.setInvalidType(); 817 818 // The syntax only allows a single ref-qualifier prior to the decomposition 819 // declarator. No other declarator chunks are permitted. Also check the type 820 // specifier here. 821 if (DS.getTypeSpecType() != DeclSpec::TST_auto || 822 D.hasGroupingParens() || D.getNumTypeObjects() > 1 || 823 (D.getNumTypeObjects() == 1 && 824 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) { 825 Diag(Decomp.getLSquareLoc(), 826 (D.hasGroupingParens() || 827 (D.getNumTypeObjects() && 828 D.getTypeObject(0).Kind == DeclaratorChunk::Paren)) 829 ? diag::err_decomp_decl_parens 830 : diag::err_decomp_decl_type) 831 << R; 832 833 // In most cases, there's no actual problem with an explicitly-specified 834 // type, but a function type won't work here, and ActOnVariableDeclarator 835 // shouldn't be called for such a type. 836 if (R->isFunctionType()) 837 D.setInvalidType(); 838 } 839 840 // Build the BindingDecls. 841 SmallVector<BindingDecl*, 8> Bindings; 842 843 // Build the BindingDecls. 844 for (auto &B : D.getDecompositionDeclarator().bindings()) { 845 // Check for name conflicts. 846 DeclarationNameInfo NameInfo(B.Name, B.NameLoc); 847 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 848 ForVisibleRedeclaration); 849 LookupName(Previous, S, 850 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit()); 851 852 // It's not permitted to shadow a template parameter name. 853 if (Previous.isSingleResult() && 854 Previous.getFoundDecl()->isTemplateParameter()) { 855 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 856 Previous.getFoundDecl()); 857 Previous.clear(); 858 } 859 860 bool ConsiderLinkage = DC->isFunctionOrMethod() && 861 DS.getStorageClassSpec() == DeclSpec::SCS_extern; 862 FilterLookupForScope(Previous, DC, S, ConsiderLinkage, 863 /*AllowInlineNamespace*/false); 864 if (!Previous.empty()) { 865 auto *Old = Previous.getRepresentativeDecl(); 866 Diag(B.NameLoc, diag::err_redefinition) << B.Name; 867 Diag(Old->getLocation(), diag::note_previous_definition); 868 } 869 870 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name); 871 PushOnScopeChains(BD, S, true); 872 Bindings.push_back(BD); 873 ParsingInitForAutoVars.insert(BD); 874 } 875 876 // There are no prior lookup results for the variable itself, because it 877 // is unnamed. 878 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr, 879 Decomp.getLSquareLoc()); 880 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 881 ForVisibleRedeclaration); 882 883 // Build the variable that holds the non-decomposed object. 884 bool AddToScope = true; 885 NamedDecl *New = 886 ActOnVariableDeclarator(S, D, DC, TInfo, Previous, 887 MultiTemplateParamsArg(), AddToScope, Bindings); 888 if (AddToScope) { 889 S->AddDecl(New); 890 CurContext->addHiddenDecl(New); 891 } 892 893 if (isInOpenMPDeclareTargetContext()) 894 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 895 896 return New; 897 } 898 899 static bool checkSimpleDecomposition( 900 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src, 901 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType, 902 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) { 903 if ((int64_t)Bindings.size() != NumElems) { 904 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 905 << DecompType << (unsigned)Bindings.size() 906 << (unsigned)NumElems.getLimitedValue(UINT_MAX) << NumElems.toString(10) 907 << (NumElems < Bindings.size()); 908 return true; 909 } 910 911 unsigned I = 0; 912 for (auto *B : Bindings) { 913 SourceLocation Loc = B->getLocation(); 914 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 915 if (E.isInvalid()) 916 return true; 917 E = GetInit(Loc, E.get(), I++); 918 if (E.isInvalid()) 919 return true; 920 B->setBinding(ElemType, E.get()); 921 } 922 923 return false; 924 } 925 926 static bool checkArrayLikeDecomposition(Sema &S, 927 ArrayRef<BindingDecl *> Bindings, 928 ValueDecl *Src, QualType DecompType, 929 const llvm::APSInt &NumElems, 930 QualType ElemType) { 931 return checkSimpleDecomposition( 932 S, Bindings, Src, DecompType, NumElems, ElemType, 933 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 934 ExprResult E = S.ActOnIntegerConstant(Loc, I); 935 if (E.isInvalid()) 936 return ExprError(); 937 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc); 938 }); 939 } 940 941 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 942 ValueDecl *Src, QualType DecompType, 943 const ConstantArrayType *CAT) { 944 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType, 945 llvm::APSInt(CAT->getSize()), 946 CAT->getElementType()); 947 } 948 949 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 950 ValueDecl *Src, QualType DecompType, 951 const VectorType *VT) { 952 return checkArrayLikeDecomposition( 953 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()), 954 S.Context.getQualifiedType(VT->getElementType(), 955 DecompType.getQualifiers())); 956 } 957 958 static bool checkComplexDecomposition(Sema &S, 959 ArrayRef<BindingDecl *> Bindings, 960 ValueDecl *Src, QualType DecompType, 961 const ComplexType *CT) { 962 return checkSimpleDecomposition( 963 S, Bindings, Src, DecompType, llvm::APSInt::get(2), 964 S.Context.getQualifiedType(CT->getElementType(), 965 DecompType.getQualifiers()), 966 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 967 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base); 968 }); 969 } 970 971 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy, 972 TemplateArgumentListInfo &Args) { 973 SmallString<128> SS; 974 llvm::raw_svector_ostream OS(SS); 975 bool First = true; 976 for (auto &Arg : Args.arguments()) { 977 if (!First) 978 OS << ", "; 979 Arg.getArgument().print(PrintingPolicy, OS); 980 First = false; 981 } 982 return std::string(OS.str()); 983 } 984 985 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup, 986 SourceLocation Loc, StringRef Trait, 987 TemplateArgumentListInfo &Args, 988 unsigned DiagID) { 989 auto DiagnoseMissing = [&] { 990 if (DiagID) 991 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(), 992 Args); 993 return true; 994 }; 995 996 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine. 997 NamespaceDecl *Std = S.getStdNamespace(); 998 if (!Std) 999 return DiagnoseMissing(); 1000 1001 // Look up the trait itself, within namespace std. We can diagnose various 1002 // problems with this lookup even if we've been asked to not diagnose a 1003 // missing specialization, because this can only fail if the user has been 1004 // declaring their own names in namespace std or we don't support the 1005 // standard library implementation in use. 1006 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait), 1007 Loc, Sema::LookupOrdinaryName); 1008 if (!S.LookupQualifiedName(Result, Std)) 1009 return DiagnoseMissing(); 1010 if (Result.isAmbiguous()) 1011 return true; 1012 1013 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>(); 1014 if (!TraitTD) { 1015 Result.suppressDiagnostics(); 1016 NamedDecl *Found = *Result.begin(); 1017 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait; 1018 S.Diag(Found->getLocation(), diag::note_declared_at); 1019 return true; 1020 } 1021 1022 // Build the template-id. 1023 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args); 1024 if (TraitTy.isNull()) 1025 return true; 1026 if (!S.isCompleteType(Loc, TraitTy)) { 1027 if (DiagID) 1028 S.RequireCompleteType( 1029 Loc, TraitTy, DiagID, 1030 printTemplateArgs(S.Context.getPrintingPolicy(), Args)); 1031 return true; 1032 } 1033 1034 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl(); 1035 assert(RD && "specialization of class template is not a class?"); 1036 1037 // Look up the member of the trait type. 1038 S.LookupQualifiedName(TraitMemberLookup, RD); 1039 return TraitMemberLookup.isAmbiguous(); 1040 } 1041 1042 static TemplateArgumentLoc 1043 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, 1044 uint64_t I) { 1045 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T); 1046 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc); 1047 } 1048 1049 static TemplateArgumentLoc 1050 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) { 1051 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc); 1052 } 1053 1054 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; } 1055 1056 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, 1057 llvm::APSInt &Size) { 1058 EnterExpressionEvaluationContext ContextRAII( 1059 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 1060 1061 DeclarationName Value = S.PP.getIdentifierInfo("value"); 1062 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName); 1063 1064 // Form template argument list for tuple_size<T>. 1065 TemplateArgumentListInfo Args(Loc, Loc); 1066 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1067 1068 // If there's no tuple_size specialization or the lookup of 'value' is empty, 1069 // it's not tuple-like. 1070 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) || 1071 R.empty()) 1072 return IsTupleLike::NotTupleLike; 1073 1074 // If we get this far, we've committed to the tuple interpretation, but 1075 // we can still fail if there actually isn't a usable ::value. 1076 1077 struct ICEDiagnoser : Sema::VerifyICEDiagnoser { 1078 LookupResult &R; 1079 TemplateArgumentListInfo &Args; 1080 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args) 1081 : R(R), Args(Args) {} 1082 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S, 1083 SourceLocation Loc) override { 1084 return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant) 1085 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1086 } 1087 } Diagnoser(R, Args); 1088 1089 ExprResult E = 1090 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false); 1091 if (E.isInvalid()) 1092 return IsTupleLike::Error; 1093 1094 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser); 1095 if (E.isInvalid()) 1096 return IsTupleLike::Error; 1097 1098 return IsTupleLike::TupleLike; 1099 } 1100 1101 /// \return std::tuple_element<I, T>::type. 1102 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, 1103 unsigned I, QualType T) { 1104 // Form template argument list for tuple_element<I, T>. 1105 TemplateArgumentListInfo Args(Loc, Loc); 1106 Args.addArgument( 1107 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1108 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1109 1110 DeclarationName TypeDN = S.PP.getIdentifierInfo("type"); 1111 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName); 1112 if (lookupStdTypeTraitMember( 1113 S, R, Loc, "tuple_element", Args, 1114 diag::err_decomp_decl_std_tuple_element_not_specialized)) 1115 return QualType(); 1116 1117 auto *TD = R.getAsSingle<TypeDecl>(); 1118 if (!TD) { 1119 R.suppressDiagnostics(); 1120 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized) 1121 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1122 if (!R.empty()) 1123 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at); 1124 return QualType(); 1125 } 1126 1127 return S.Context.getTypeDeclType(TD); 1128 } 1129 1130 namespace { 1131 struct InitializingBinding { 1132 Sema &S; 1133 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) { 1134 Sema::CodeSynthesisContext Ctx; 1135 Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding; 1136 Ctx.PointOfInstantiation = BD->getLocation(); 1137 Ctx.Entity = BD; 1138 S.pushCodeSynthesisContext(Ctx); 1139 } 1140 ~InitializingBinding() { 1141 S.popCodeSynthesisContext(); 1142 } 1143 }; 1144 } 1145 1146 static bool checkTupleLikeDecomposition(Sema &S, 1147 ArrayRef<BindingDecl *> Bindings, 1148 VarDecl *Src, QualType DecompType, 1149 const llvm::APSInt &TupleSize) { 1150 if ((int64_t)Bindings.size() != TupleSize) { 1151 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1152 << DecompType << (unsigned)Bindings.size() 1153 << (unsigned)TupleSize.getLimitedValue(UINT_MAX) 1154 << TupleSize.toString(10) << (TupleSize < Bindings.size()); 1155 return true; 1156 } 1157 1158 if (Bindings.empty()) 1159 return false; 1160 1161 DeclarationName GetDN = S.PP.getIdentifierInfo("get"); 1162 1163 // [dcl.decomp]p3: 1164 // The unqualified-id get is looked up in the scope of E by class member 1165 // access lookup ... 1166 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName); 1167 bool UseMemberGet = false; 1168 if (S.isCompleteType(Src->getLocation(), DecompType)) { 1169 if (auto *RD = DecompType->getAsCXXRecordDecl()) 1170 S.LookupQualifiedName(MemberGet, RD); 1171 if (MemberGet.isAmbiguous()) 1172 return true; 1173 // ... and if that finds at least one declaration that is a function 1174 // template whose first template parameter is a non-type parameter ... 1175 for (NamedDecl *D : MemberGet) { 1176 if (FunctionTemplateDecl *FTD = 1177 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) { 1178 TemplateParameterList *TPL = FTD->getTemplateParameters(); 1179 if (TPL->size() != 0 && 1180 isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) { 1181 // ... the initializer is e.get<i>(). 1182 UseMemberGet = true; 1183 break; 1184 } 1185 } 1186 } 1187 } 1188 1189 unsigned I = 0; 1190 for (auto *B : Bindings) { 1191 InitializingBinding InitContext(S, B); 1192 SourceLocation Loc = B->getLocation(); 1193 1194 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1195 if (E.isInvalid()) 1196 return true; 1197 1198 // e is an lvalue if the type of the entity is an lvalue reference and 1199 // an xvalue otherwise 1200 if (!Src->getType()->isLValueReferenceType()) 1201 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp, 1202 E.get(), nullptr, VK_XValue, 1203 FPOptionsOverride()); 1204 1205 TemplateArgumentListInfo Args(Loc, Loc); 1206 Args.addArgument( 1207 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1208 1209 if (UseMemberGet) { 1210 // if [lookup of member get] finds at least one declaration, the 1211 // initializer is e.get<i-1>(). 1212 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false, 1213 CXXScopeSpec(), SourceLocation(), nullptr, 1214 MemberGet, &Args, nullptr); 1215 if (E.isInvalid()) 1216 return true; 1217 1218 E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc); 1219 } else { 1220 // Otherwise, the initializer is get<i-1>(e), where get is looked up 1221 // in the associated namespaces. 1222 Expr *Get = UnresolvedLookupExpr::Create( 1223 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(), 1224 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args, 1225 UnresolvedSetIterator(), UnresolvedSetIterator()); 1226 1227 Expr *Arg = E.get(); 1228 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc); 1229 } 1230 if (E.isInvalid()) 1231 return true; 1232 Expr *Init = E.get(); 1233 1234 // Given the type T designated by std::tuple_element<i - 1, E>::type, 1235 QualType T = getTupleLikeElementType(S, Loc, I, DecompType); 1236 if (T.isNull()) 1237 return true; 1238 1239 // each vi is a variable of type "reference to T" initialized with the 1240 // initializer, where the reference is an lvalue reference if the 1241 // initializer is an lvalue and an rvalue reference otherwise 1242 QualType RefType = 1243 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName()); 1244 if (RefType.isNull()) 1245 return true; 1246 auto *RefVD = VarDecl::Create( 1247 S.Context, Src->getDeclContext(), Loc, Loc, 1248 B->getDeclName().getAsIdentifierInfo(), RefType, 1249 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass()); 1250 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext()); 1251 RefVD->setTSCSpec(Src->getTSCSpec()); 1252 RefVD->setImplicit(); 1253 if (Src->isInlineSpecified()) 1254 RefVD->setInlineSpecified(); 1255 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD); 1256 1257 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD); 1258 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc); 1259 InitializationSequence Seq(S, Entity, Kind, Init); 1260 E = Seq.Perform(S, Entity, Kind, Init); 1261 if (E.isInvalid()) 1262 return true; 1263 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false); 1264 if (E.isInvalid()) 1265 return true; 1266 RefVD->setInit(E.get()); 1267 S.CheckCompleteVariableDeclaration(RefVD); 1268 1269 E = S.BuildDeclarationNameExpr(CXXScopeSpec(), 1270 DeclarationNameInfo(B->getDeclName(), Loc), 1271 RefVD); 1272 if (E.isInvalid()) 1273 return true; 1274 1275 B->setBinding(T, E.get()); 1276 I++; 1277 } 1278 1279 return false; 1280 } 1281 1282 /// Find the base class to decompose in a built-in decomposition of a class type. 1283 /// This base class search is, unfortunately, not quite like any other that we 1284 /// perform anywhere else in C++. 1285 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc, 1286 const CXXRecordDecl *RD, 1287 CXXCastPath &BasePath) { 1288 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier, 1289 CXXBasePath &Path) { 1290 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields(); 1291 }; 1292 1293 const CXXRecordDecl *ClassWithFields = nullptr; 1294 AccessSpecifier AS = AS_public; 1295 if (RD->hasDirectFields()) 1296 // [dcl.decomp]p4: 1297 // Otherwise, all of E's non-static data members shall be public direct 1298 // members of E ... 1299 ClassWithFields = RD; 1300 else { 1301 // ... or of ... 1302 CXXBasePaths Paths; 1303 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD)); 1304 if (!RD->lookupInBases(BaseHasFields, Paths)) { 1305 // If no classes have fields, just decompose RD itself. (This will work 1306 // if and only if zero bindings were provided.) 1307 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public); 1308 } 1309 1310 CXXBasePath *BestPath = nullptr; 1311 for (auto &P : Paths) { 1312 if (!BestPath) 1313 BestPath = &P; 1314 else if (!S.Context.hasSameType(P.back().Base->getType(), 1315 BestPath->back().Base->getType())) { 1316 // ... the same ... 1317 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1318 << false << RD << BestPath->back().Base->getType() 1319 << P.back().Base->getType(); 1320 return DeclAccessPair(); 1321 } else if (P.Access < BestPath->Access) { 1322 BestPath = &P; 1323 } 1324 } 1325 1326 // ... unambiguous ... 1327 QualType BaseType = BestPath->back().Base->getType(); 1328 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) { 1329 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base) 1330 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths); 1331 return DeclAccessPair(); 1332 } 1333 1334 // ... [accessible, implied by other rules] base class of E. 1335 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD), 1336 *BestPath, diag::err_decomp_decl_inaccessible_base); 1337 AS = BestPath->Access; 1338 1339 ClassWithFields = BaseType->getAsCXXRecordDecl(); 1340 S.BuildBasePathArray(Paths, BasePath); 1341 } 1342 1343 // The above search did not check whether the selected class itself has base 1344 // classes with fields, so check that now. 1345 CXXBasePaths Paths; 1346 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) { 1347 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1348 << (ClassWithFields == RD) << RD << ClassWithFields 1349 << Paths.front().back().Base->getType(); 1350 return DeclAccessPair(); 1351 } 1352 1353 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS); 1354 } 1355 1356 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 1357 ValueDecl *Src, QualType DecompType, 1358 const CXXRecordDecl *OrigRD) { 1359 if (S.RequireCompleteType(Src->getLocation(), DecompType, 1360 diag::err_incomplete_type)) 1361 return true; 1362 1363 CXXCastPath BasePath; 1364 DeclAccessPair BasePair = 1365 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath); 1366 const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl()); 1367 if (!RD) 1368 return true; 1369 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD), 1370 DecompType.getQualifiers()); 1371 1372 auto DiagnoseBadNumberOfBindings = [&]() -> bool { 1373 unsigned NumFields = 1374 std::count_if(RD->field_begin(), RD->field_end(), 1375 [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); }); 1376 assert(Bindings.size() != NumFields); 1377 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1378 << DecompType << (unsigned)Bindings.size() << NumFields << NumFields 1379 << (NumFields < Bindings.size()); 1380 return true; 1381 }; 1382 1383 // all of E's non-static data members shall be [...] well-formed 1384 // when named as e.name in the context of the structured binding, 1385 // E shall not have an anonymous union member, ... 1386 unsigned I = 0; 1387 for (auto *FD : RD->fields()) { 1388 if (FD->isUnnamedBitfield()) 1389 continue; 1390 1391 // All the non-static data members are required to be nameable, so they 1392 // must all have names. 1393 if (!FD->getDeclName()) { 1394 if (RD->isLambda()) { 1395 S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda); 1396 S.Diag(RD->getLocation(), diag::note_lambda_decl); 1397 return true; 1398 } 1399 1400 if (FD->isAnonymousStructOrUnion()) { 1401 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member) 1402 << DecompType << FD->getType()->isUnionType(); 1403 S.Diag(FD->getLocation(), diag::note_declared_at); 1404 return true; 1405 } 1406 1407 // FIXME: Are there any other ways we could have an anonymous member? 1408 } 1409 1410 // We have a real field to bind. 1411 if (I >= Bindings.size()) 1412 return DiagnoseBadNumberOfBindings(); 1413 auto *B = Bindings[I++]; 1414 SourceLocation Loc = B->getLocation(); 1415 1416 // The field must be accessible in the context of the structured binding. 1417 // We already checked that the base class is accessible. 1418 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the 1419 // const_cast here. 1420 S.CheckStructuredBindingMemberAccess( 1421 Loc, const_cast<CXXRecordDecl *>(OrigRD), 1422 DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess( 1423 BasePair.getAccess(), FD->getAccess()))); 1424 1425 // Initialize the binding to Src.FD. 1426 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1427 if (E.isInvalid()) 1428 return true; 1429 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase, 1430 VK_LValue, &BasePath); 1431 if (E.isInvalid()) 1432 return true; 1433 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc, 1434 CXXScopeSpec(), FD, 1435 DeclAccessPair::make(FD, FD->getAccess()), 1436 DeclarationNameInfo(FD->getDeclName(), Loc)); 1437 if (E.isInvalid()) 1438 return true; 1439 1440 // If the type of the member is T, the referenced type is cv T, where cv is 1441 // the cv-qualification of the decomposition expression. 1442 // 1443 // FIXME: We resolve a defect here: if the field is mutable, we do not add 1444 // 'const' to the type of the field. 1445 Qualifiers Q = DecompType.getQualifiers(); 1446 if (FD->isMutable()) 1447 Q.removeConst(); 1448 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get()); 1449 } 1450 1451 if (I != Bindings.size()) 1452 return DiagnoseBadNumberOfBindings(); 1453 1454 return false; 1455 } 1456 1457 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) { 1458 QualType DecompType = DD->getType(); 1459 1460 // If the type of the decomposition is dependent, then so is the type of 1461 // each binding. 1462 if (DecompType->isDependentType()) { 1463 for (auto *B : DD->bindings()) 1464 B->setType(Context.DependentTy); 1465 return; 1466 } 1467 1468 DecompType = DecompType.getNonReferenceType(); 1469 ArrayRef<BindingDecl*> Bindings = DD->bindings(); 1470 1471 // C++1z [dcl.decomp]/2: 1472 // If E is an array type [...] 1473 // As an extension, we also support decomposition of built-in complex and 1474 // vector types. 1475 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) { 1476 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT)) 1477 DD->setInvalidDecl(); 1478 return; 1479 } 1480 if (auto *VT = DecompType->getAs<VectorType>()) { 1481 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT)) 1482 DD->setInvalidDecl(); 1483 return; 1484 } 1485 if (auto *CT = DecompType->getAs<ComplexType>()) { 1486 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT)) 1487 DD->setInvalidDecl(); 1488 return; 1489 } 1490 1491 // C++1z [dcl.decomp]/3: 1492 // if the expression std::tuple_size<E>::value is a well-formed integral 1493 // constant expression, [...] 1494 llvm::APSInt TupleSize(32); 1495 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) { 1496 case IsTupleLike::Error: 1497 DD->setInvalidDecl(); 1498 return; 1499 1500 case IsTupleLike::TupleLike: 1501 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize)) 1502 DD->setInvalidDecl(); 1503 return; 1504 1505 case IsTupleLike::NotTupleLike: 1506 break; 1507 } 1508 1509 // C++1z [dcl.dcl]/8: 1510 // [E shall be of array or non-union class type] 1511 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl(); 1512 if (!RD || RD->isUnion()) { 1513 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type) 1514 << DD << !RD << DecompType; 1515 DD->setInvalidDecl(); 1516 return; 1517 } 1518 1519 // C++1z [dcl.decomp]/4: 1520 // all of E's non-static data members shall be [...] direct members of 1521 // E or of the same unambiguous public base class of E, ... 1522 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD)) 1523 DD->setInvalidDecl(); 1524 } 1525 1526 /// Merge the exception specifications of two variable declarations. 1527 /// 1528 /// This is called when there's a redeclaration of a VarDecl. The function 1529 /// checks if the redeclaration might have an exception specification and 1530 /// validates compatibility and merges the specs if necessary. 1531 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 1532 // Shortcut if exceptions are disabled. 1533 if (!getLangOpts().CXXExceptions) 1534 return; 1535 1536 assert(Context.hasSameType(New->getType(), Old->getType()) && 1537 "Should only be called if types are otherwise the same."); 1538 1539 QualType NewType = New->getType(); 1540 QualType OldType = Old->getType(); 1541 1542 // We're only interested in pointers and references to functions, as well 1543 // as pointers to member functions. 1544 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 1545 NewType = R->getPointeeType(); 1546 OldType = OldType->castAs<ReferenceType>()->getPointeeType(); 1547 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 1548 NewType = P->getPointeeType(); 1549 OldType = OldType->castAs<PointerType>()->getPointeeType(); 1550 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 1551 NewType = M->getPointeeType(); 1552 OldType = OldType->castAs<MemberPointerType>()->getPointeeType(); 1553 } 1554 1555 if (!NewType->isFunctionProtoType()) 1556 return; 1557 1558 // There's lots of special cases for functions. For function pointers, system 1559 // libraries are hopefully not as broken so that we don't need these 1560 // workarounds. 1561 if (CheckEquivalentExceptionSpec( 1562 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 1563 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 1564 New->setInvalidDecl(); 1565 } 1566 } 1567 1568 /// CheckCXXDefaultArguments - Verify that the default arguments for a 1569 /// function declaration are well-formed according to C++ 1570 /// [dcl.fct.default]. 1571 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 1572 unsigned NumParams = FD->getNumParams(); 1573 unsigned ParamIdx = 0; 1574 1575 // This checking doesn't make sense for explicit specializations; their 1576 // default arguments are determined by the declaration we're specializing, 1577 // not by FD. 1578 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 1579 return; 1580 if (auto *FTD = FD->getDescribedFunctionTemplate()) 1581 if (FTD->isMemberSpecialization()) 1582 return; 1583 1584 // Find first parameter with a default argument 1585 for (; ParamIdx < NumParams; ++ParamIdx) { 1586 ParmVarDecl *Param = FD->getParamDecl(ParamIdx); 1587 if (Param->hasDefaultArg()) 1588 break; 1589 } 1590 1591 // C++20 [dcl.fct.default]p4: 1592 // In a given function declaration, each parameter subsequent to a parameter 1593 // with a default argument shall have a default argument supplied in this or 1594 // a previous declaration, unless the parameter was expanded from a 1595 // parameter pack, or shall be a function parameter pack. 1596 for (; ParamIdx < NumParams; ++ParamIdx) { 1597 ParmVarDecl *Param = FD->getParamDecl(ParamIdx); 1598 if (!Param->hasDefaultArg() && !Param->isParameterPack() && 1599 !(CurrentInstantiationScope && 1600 CurrentInstantiationScope->isLocalPackExpansion(Param))) { 1601 if (Param->isInvalidDecl()) 1602 /* We already complained about this parameter. */; 1603 else if (Param->getIdentifier()) 1604 Diag(Param->getLocation(), 1605 diag::err_param_default_argument_missing_name) 1606 << Param->getIdentifier(); 1607 else 1608 Diag(Param->getLocation(), 1609 diag::err_param_default_argument_missing); 1610 } 1611 } 1612 } 1613 1614 /// Check that the given type is a literal type. Issue a diagnostic if not, 1615 /// if Kind is Diagnose. 1616 /// \return \c true if a problem has been found (and optionally diagnosed). 1617 template <typename... Ts> 1618 static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind, 1619 SourceLocation Loc, QualType T, unsigned DiagID, 1620 Ts &&...DiagArgs) { 1621 if (T->isDependentType()) 1622 return false; 1623 1624 switch (Kind) { 1625 case Sema::CheckConstexprKind::Diagnose: 1626 return SemaRef.RequireLiteralType(Loc, T, DiagID, 1627 std::forward<Ts>(DiagArgs)...); 1628 1629 case Sema::CheckConstexprKind::CheckValid: 1630 return !T->isLiteralType(SemaRef.Context); 1631 } 1632 1633 llvm_unreachable("unknown CheckConstexprKind"); 1634 } 1635 1636 /// Determine whether a destructor cannot be constexpr due to 1637 static bool CheckConstexprDestructorSubobjects(Sema &SemaRef, 1638 const CXXDestructorDecl *DD, 1639 Sema::CheckConstexprKind Kind) { 1640 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) { 1641 const CXXRecordDecl *RD = 1642 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 1643 if (!RD || RD->hasConstexprDestructor()) 1644 return true; 1645 1646 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1647 SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject) 1648 << static_cast<int>(DD->getConstexprKind()) << !FD 1649 << (FD ? FD->getDeclName() : DeclarationName()) << T; 1650 SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject) 1651 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T; 1652 } 1653 return false; 1654 }; 1655 1656 const CXXRecordDecl *RD = DD->getParent(); 1657 for (const CXXBaseSpecifier &B : RD->bases()) 1658 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr)) 1659 return false; 1660 for (const FieldDecl *FD : RD->fields()) 1661 if (!Check(FD->getLocation(), FD->getType(), FD)) 1662 return false; 1663 return true; 1664 } 1665 1666 /// Check whether a function's parameter types are all literal types. If so, 1667 /// return true. If not, produce a suitable diagnostic and return false. 1668 static bool CheckConstexprParameterTypes(Sema &SemaRef, 1669 const FunctionDecl *FD, 1670 Sema::CheckConstexprKind Kind) { 1671 unsigned ArgIndex = 0; 1672 const auto *FT = FD->getType()->castAs<FunctionProtoType>(); 1673 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 1674 e = FT->param_type_end(); 1675 i != e; ++i, ++ArgIndex) { 1676 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 1677 SourceLocation ParamLoc = PD->getLocation(); 1678 if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i, 1679 diag::err_constexpr_non_literal_param, ArgIndex + 1, 1680 PD->getSourceRange(), isa<CXXConstructorDecl>(FD), 1681 FD->isConsteval())) 1682 return false; 1683 } 1684 return true; 1685 } 1686 1687 /// Check whether a function's return type is a literal type. If so, return 1688 /// true. If not, produce a suitable diagnostic and return false. 1689 static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD, 1690 Sema::CheckConstexprKind Kind) { 1691 if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(), 1692 diag::err_constexpr_non_literal_return, 1693 FD->isConsteval())) 1694 return false; 1695 return true; 1696 } 1697 1698 /// Get diagnostic %select index for tag kind for 1699 /// record diagnostic message. 1700 /// WARNING: Indexes apply to particular diagnostics only! 1701 /// 1702 /// \returns diagnostic %select index. 1703 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 1704 switch (Tag) { 1705 case TTK_Struct: return 0; 1706 case TTK_Interface: return 1; 1707 case TTK_Class: return 2; 1708 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 1709 } 1710 } 1711 1712 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, 1713 Stmt *Body, 1714 Sema::CheckConstexprKind Kind); 1715 1716 // Check whether a function declaration satisfies the requirements of a 1717 // constexpr function definition or a constexpr constructor definition. If so, 1718 // return true. If not, produce appropriate diagnostics (unless asked not to by 1719 // Kind) and return false. 1720 // 1721 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 1722 bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD, 1723 CheckConstexprKind Kind) { 1724 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 1725 if (MD && MD->isInstance()) { 1726 // C++11 [dcl.constexpr]p4: 1727 // The definition of a constexpr constructor shall satisfy the following 1728 // constraints: 1729 // - the class shall not have any virtual base classes; 1730 // 1731 // FIXME: This only applies to constructors and destructors, not arbitrary 1732 // member functions. 1733 const CXXRecordDecl *RD = MD->getParent(); 1734 if (RD->getNumVBases()) { 1735 if (Kind == CheckConstexprKind::CheckValid) 1736 return false; 1737 1738 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 1739 << isa<CXXConstructorDecl>(NewFD) 1740 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 1741 for (const auto &I : RD->vbases()) 1742 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here) 1743 << I.getSourceRange(); 1744 return false; 1745 } 1746 } 1747 1748 if (!isa<CXXConstructorDecl>(NewFD)) { 1749 // C++11 [dcl.constexpr]p3: 1750 // The definition of a constexpr function shall satisfy the following 1751 // constraints: 1752 // - it shall not be virtual; (removed in C++20) 1753 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 1754 if (Method && Method->isVirtual()) { 1755 if (getLangOpts().CPlusPlus20) { 1756 if (Kind == CheckConstexprKind::Diagnose) 1757 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual); 1758 } else { 1759 if (Kind == CheckConstexprKind::CheckValid) 1760 return false; 1761 1762 Method = Method->getCanonicalDecl(); 1763 Diag(Method->getLocation(), diag::err_constexpr_virtual); 1764 1765 // If it's not obvious why this function is virtual, find an overridden 1766 // function which uses the 'virtual' keyword. 1767 const CXXMethodDecl *WrittenVirtual = Method; 1768 while (!WrittenVirtual->isVirtualAsWritten()) 1769 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 1770 if (WrittenVirtual != Method) 1771 Diag(WrittenVirtual->getLocation(), 1772 diag::note_overridden_virtual_function); 1773 return false; 1774 } 1775 } 1776 1777 // - its return type shall be a literal type; 1778 if (!CheckConstexprReturnType(*this, NewFD, Kind)) 1779 return false; 1780 } 1781 1782 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) { 1783 // A destructor can be constexpr only if the defaulted destructor could be; 1784 // we don't need to check the members and bases if we already know they all 1785 // have constexpr destructors. 1786 if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) { 1787 if (Kind == CheckConstexprKind::CheckValid) 1788 return false; 1789 if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind)) 1790 return false; 1791 } 1792 } 1793 1794 // - each of its parameter types shall be a literal type; 1795 if (!CheckConstexprParameterTypes(*this, NewFD, Kind)) 1796 return false; 1797 1798 Stmt *Body = NewFD->getBody(); 1799 assert(Body && 1800 "CheckConstexprFunctionDefinition called on function with no body"); 1801 return CheckConstexprFunctionBody(*this, NewFD, Body, Kind); 1802 } 1803 1804 /// Check the given declaration statement is legal within a constexpr function 1805 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 1806 /// 1807 /// \return true if the body is OK (maybe only as an extension), false if we 1808 /// have diagnosed a problem. 1809 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 1810 DeclStmt *DS, SourceLocation &Cxx1yLoc, 1811 Sema::CheckConstexprKind Kind) { 1812 // C++11 [dcl.constexpr]p3 and p4: 1813 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 1814 // contain only 1815 for (const auto *DclIt : DS->decls()) { 1816 switch (DclIt->getKind()) { 1817 case Decl::StaticAssert: 1818 case Decl::Using: 1819 case Decl::UsingShadow: 1820 case Decl::UsingDirective: 1821 case Decl::UnresolvedUsingTypename: 1822 case Decl::UnresolvedUsingValue: 1823 // - static_assert-declarations 1824 // - using-declarations, 1825 // - using-directives, 1826 continue; 1827 1828 case Decl::Typedef: 1829 case Decl::TypeAlias: { 1830 // - typedef declarations and alias-declarations that do not define 1831 // classes or enumerations, 1832 const auto *TN = cast<TypedefNameDecl>(DclIt); 1833 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 1834 // Don't allow variably-modified types in constexpr functions. 1835 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1836 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 1837 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 1838 << TL.getSourceRange() << TL.getType() 1839 << isa<CXXConstructorDecl>(Dcl); 1840 } 1841 return false; 1842 } 1843 continue; 1844 } 1845 1846 case Decl::Enum: 1847 case Decl::CXXRecord: 1848 // C++1y allows types to be defined, not just declared. 1849 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) { 1850 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1851 SemaRef.Diag(DS->getBeginLoc(), 1852 SemaRef.getLangOpts().CPlusPlus14 1853 ? diag::warn_cxx11_compat_constexpr_type_definition 1854 : diag::ext_constexpr_type_definition) 1855 << isa<CXXConstructorDecl>(Dcl); 1856 } else if (!SemaRef.getLangOpts().CPlusPlus14) { 1857 return false; 1858 } 1859 } 1860 continue; 1861 1862 case Decl::EnumConstant: 1863 case Decl::IndirectField: 1864 case Decl::ParmVar: 1865 // These can only appear with other declarations which are banned in 1866 // C++11 and permitted in C++1y, so ignore them. 1867 continue; 1868 1869 case Decl::Var: 1870 case Decl::Decomposition: { 1871 // C++1y [dcl.constexpr]p3 allows anything except: 1872 // a definition of a variable of non-literal type or of static or 1873 // thread storage duration or [before C++2a] for which no 1874 // initialization is performed. 1875 const auto *VD = cast<VarDecl>(DclIt); 1876 if (VD->isThisDeclarationADefinition()) { 1877 if (VD->isStaticLocal()) { 1878 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1879 SemaRef.Diag(VD->getLocation(), 1880 diag::err_constexpr_local_var_static) 1881 << isa<CXXConstructorDecl>(Dcl) 1882 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 1883 } 1884 return false; 1885 } 1886 if (CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(), 1887 diag::err_constexpr_local_var_non_literal_type, 1888 isa<CXXConstructorDecl>(Dcl))) 1889 return false; 1890 if (!VD->getType()->isDependentType() && 1891 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 1892 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1893 SemaRef.Diag( 1894 VD->getLocation(), 1895 SemaRef.getLangOpts().CPlusPlus20 1896 ? diag::warn_cxx17_compat_constexpr_local_var_no_init 1897 : diag::ext_constexpr_local_var_no_init) 1898 << isa<CXXConstructorDecl>(Dcl); 1899 } else if (!SemaRef.getLangOpts().CPlusPlus20) { 1900 return false; 1901 } 1902 continue; 1903 } 1904 } 1905 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1906 SemaRef.Diag(VD->getLocation(), 1907 SemaRef.getLangOpts().CPlusPlus14 1908 ? diag::warn_cxx11_compat_constexpr_local_var 1909 : diag::ext_constexpr_local_var) 1910 << isa<CXXConstructorDecl>(Dcl); 1911 } else if (!SemaRef.getLangOpts().CPlusPlus14) { 1912 return false; 1913 } 1914 continue; 1915 } 1916 1917 case Decl::NamespaceAlias: 1918 case Decl::Function: 1919 // These are disallowed in C++11 and permitted in C++1y. Allow them 1920 // everywhere as an extension. 1921 if (!Cxx1yLoc.isValid()) 1922 Cxx1yLoc = DS->getBeginLoc(); 1923 continue; 1924 1925 default: 1926 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1927 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 1928 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 1929 } 1930 return false; 1931 } 1932 } 1933 1934 return true; 1935 } 1936 1937 /// Check that the given field is initialized within a constexpr constructor. 1938 /// 1939 /// \param Dcl The constexpr constructor being checked. 1940 /// \param Field The field being checked. This may be a member of an anonymous 1941 /// struct or union nested within the class being checked. 1942 /// \param Inits All declarations, including anonymous struct/union members and 1943 /// indirect members, for which any initialization was provided. 1944 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach 1945 /// multiple notes for different members to the same error. 1946 /// \param Kind Whether we're diagnosing a constructor as written or determining 1947 /// whether the formal requirements are satisfied. 1948 /// \return \c false if we're checking for validity and the constructor does 1949 /// not satisfy the requirements on a constexpr constructor. 1950 static bool CheckConstexprCtorInitializer(Sema &SemaRef, 1951 const FunctionDecl *Dcl, 1952 FieldDecl *Field, 1953 llvm::SmallSet<Decl*, 16> &Inits, 1954 bool &Diagnosed, 1955 Sema::CheckConstexprKind Kind) { 1956 // In C++20 onwards, there's nothing to check for validity. 1957 if (Kind == Sema::CheckConstexprKind::CheckValid && 1958 SemaRef.getLangOpts().CPlusPlus20) 1959 return true; 1960 1961 if (Field->isInvalidDecl()) 1962 return true; 1963 1964 if (Field->isUnnamedBitfield()) 1965 return true; 1966 1967 // Anonymous unions with no variant members and empty anonymous structs do not 1968 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 1969 // indirect fields don't need initializing. 1970 if (Field->isAnonymousStructOrUnion() && 1971 (Field->getType()->isUnionType() 1972 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 1973 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 1974 return true; 1975 1976 if (!Inits.count(Field)) { 1977 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1978 if (!Diagnosed) { 1979 SemaRef.Diag(Dcl->getLocation(), 1980 SemaRef.getLangOpts().CPlusPlus20 1981 ? diag::warn_cxx17_compat_constexpr_ctor_missing_init 1982 : diag::ext_constexpr_ctor_missing_init); 1983 Diagnosed = true; 1984 } 1985 SemaRef.Diag(Field->getLocation(), 1986 diag::note_constexpr_ctor_missing_init); 1987 } else if (!SemaRef.getLangOpts().CPlusPlus20) { 1988 return false; 1989 } 1990 } else if (Field->isAnonymousStructOrUnion()) { 1991 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 1992 for (auto *I : RD->fields()) 1993 // If an anonymous union contains an anonymous struct of which any member 1994 // is initialized, all members must be initialized. 1995 if (!RD->isUnion() || Inits.count(I)) 1996 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, 1997 Kind)) 1998 return false; 1999 } 2000 return true; 2001 } 2002 2003 /// Check the provided statement is allowed in a constexpr function 2004 /// definition. 2005 static bool 2006 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 2007 SmallVectorImpl<SourceLocation> &ReturnStmts, 2008 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc, 2009 Sema::CheckConstexprKind Kind) { 2010 // - its function-body shall be [...] a compound-statement that contains only 2011 switch (S->getStmtClass()) { 2012 case Stmt::NullStmtClass: 2013 // - null statements, 2014 return true; 2015 2016 case Stmt::DeclStmtClass: 2017 // - static_assert-declarations 2018 // - using-declarations, 2019 // - using-directives, 2020 // - typedef declarations and alias-declarations that do not define 2021 // classes or enumerations, 2022 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind)) 2023 return false; 2024 return true; 2025 2026 case Stmt::ReturnStmtClass: 2027 // - and exactly one return statement; 2028 if (isa<CXXConstructorDecl>(Dcl)) { 2029 // C++1y allows return statements in constexpr constructors. 2030 if (!Cxx1yLoc.isValid()) 2031 Cxx1yLoc = S->getBeginLoc(); 2032 return true; 2033 } 2034 2035 ReturnStmts.push_back(S->getBeginLoc()); 2036 return true; 2037 2038 case Stmt::CompoundStmtClass: { 2039 // C++1y allows compound-statements. 2040 if (!Cxx1yLoc.isValid()) 2041 Cxx1yLoc = S->getBeginLoc(); 2042 2043 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 2044 for (auto *BodyIt : CompStmt->body()) { 2045 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 2046 Cxx1yLoc, Cxx2aLoc, Kind)) 2047 return false; 2048 } 2049 return true; 2050 } 2051 2052 case Stmt::AttributedStmtClass: 2053 if (!Cxx1yLoc.isValid()) 2054 Cxx1yLoc = S->getBeginLoc(); 2055 return true; 2056 2057 case Stmt::IfStmtClass: { 2058 // C++1y allows if-statements. 2059 if (!Cxx1yLoc.isValid()) 2060 Cxx1yLoc = S->getBeginLoc(); 2061 2062 IfStmt *If = cast<IfStmt>(S); 2063 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 2064 Cxx1yLoc, Cxx2aLoc, Kind)) 2065 return false; 2066 if (If->getElse() && 2067 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 2068 Cxx1yLoc, Cxx2aLoc, Kind)) 2069 return false; 2070 return true; 2071 } 2072 2073 case Stmt::WhileStmtClass: 2074 case Stmt::DoStmtClass: 2075 case Stmt::ForStmtClass: 2076 case Stmt::CXXForRangeStmtClass: 2077 case Stmt::ContinueStmtClass: 2078 // C++1y allows all of these. We don't allow them as extensions in C++11, 2079 // because they don't make sense without variable mutation. 2080 if (!SemaRef.getLangOpts().CPlusPlus14) 2081 break; 2082 if (!Cxx1yLoc.isValid()) 2083 Cxx1yLoc = S->getBeginLoc(); 2084 for (Stmt *SubStmt : S->children()) 2085 if (SubStmt && 2086 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2087 Cxx1yLoc, Cxx2aLoc, Kind)) 2088 return false; 2089 return true; 2090 2091 case Stmt::SwitchStmtClass: 2092 case Stmt::CaseStmtClass: 2093 case Stmt::DefaultStmtClass: 2094 case Stmt::BreakStmtClass: 2095 // C++1y allows switch-statements, and since they don't need variable 2096 // mutation, we can reasonably allow them in C++11 as an extension. 2097 if (!Cxx1yLoc.isValid()) 2098 Cxx1yLoc = S->getBeginLoc(); 2099 for (Stmt *SubStmt : S->children()) 2100 if (SubStmt && 2101 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2102 Cxx1yLoc, Cxx2aLoc, Kind)) 2103 return false; 2104 return true; 2105 2106 case Stmt::GCCAsmStmtClass: 2107 case Stmt::MSAsmStmtClass: 2108 // C++2a allows inline assembly statements. 2109 case Stmt::CXXTryStmtClass: 2110 if (Cxx2aLoc.isInvalid()) 2111 Cxx2aLoc = S->getBeginLoc(); 2112 for (Stmt *SubStmt : S->children()) { 2113 if (SubStmt && 2114 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2115 Cxx1yLoc, Cxx2aLoc, Kind)) 2116 return false; 2117 } 2118 return true; 2119 2120 case Stmt::CXXCatchStmtClass: 2121 // Do not bother checking the language mode (already covered by the 2122 // try block check). 2123 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, 2124 cast<CXXCatchStmt>(S)->getHandlerBlock(), 2125 ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind)) 2126 return false; 2127 return true; 2128 2129 default: 2130 if (!isa<Expr>(S)) 2131 break; 2132 2133 // C++1y allows expression-statements. 2134 if (!Cxx1yLoc.isValid()) 2135 Cxx1yLoc = S->getBeginLoc(); 2136 return true; 2137 } 2138 2139 if (Kind == Sema::CheckConstexprKind::Diagnose) { 2140 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 2141 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 2142 } 2143 return false; 2144 } 2145 2146 /// Check the body for the given constexpr function declaration only contains 2147 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 2148 /// 2149 /// \return true if the body is OK, false if we have found or diagnosed a 2150 /// problem. 2151 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, 2152 Stmt *Body, 2153 Sema::CheckConstexprKind Kind) { 2154 SmallVector<SourceLocation, 4> ReturnStmts; 2155 2156 if (isa<CXXTryStmt>(Body)) { 2157 // C++11 [dcl.constexpr]p3: 2158 // The definition of a constexpr function shall satisfy the following 2159 // constraints: [...] 2160 // - its function-body shall be = delete, = default, or a 2161 // compound-statement 2162 // 2163 // C++11 [dcl.constexpr]p4: 2164 // In the definition of a constexpr constructor, [...] 2165 // - its function-body shall not be a function-try-block; 2166 // 2167 // This restriction is lifted in C++2a, as long as inner statements also 2168 // apply the general constexpr rules. 2169 switch (Kind) { 2170 case Sema::CheckConstexprKind::CheckValid: 2171 if (!SemaRef.getLangOpts().CPlusPlus20) 2172 return false; 2173 break; 2174 2175 case Sema::CheckConstexprKind::Diagnose: 2176 SemaRef.Diag(Body->getBeginLoc(), 2177 !SemaRef.getLangOpts().CPlusPlus20 2178 ? diag::ext_constexpr_function_try_block_cxx20 2179 : diag::warn_cxx17_compat_constexpr_function_try_block) 2180 << isa<CXXConstructorDecl>(Dcl); 2181 break; 2182 } 2183 } 2184 2185 // - its function-body shall be [...] a compound-statement that contains only 2186 // [... list of cases ...] 2187 // 2188 // Note that walking the children here is enough to properly check for 2189 // CompoundStmt and CXXTryStmt body. 2190 SourceLocation Cxx1yLoc, Cxx2aLoc; 2191 for (Stmt *SubStmt : Body->children()) { 2192 if (SubStmt && 2193 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2194 Cxx1yLoc, Cxx2aLoc, Kind)) 2195 return false; 2196 } 2197 2198 if (Kind == Sema::CheckConstexprKind::CheckValid) { 2199 // If this is only valid as an extension, report that we don't satisfy the 2200 // constraints of the current language. 2201 if ((Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) || 2202 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17)) 2203 return false; 2204 } else if (Cxx2aLoc.isValid()) { 2205 SemaRef.Diag(Cxx2aLoc, 2206 SemaRef.getLangOpts().CPlusPlus20 2207 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt 2208 : diag::ext_constexpr_body_invalid_stmt_cxx20) 2209 << isa<CXXConstructorDecl>(Dcl); 2210 } else if (Cxx1yLoc.isValid()) { 2211 SemaRef.Diag(Cxx1yLoc, 2212 SemaRef.getLangOpts().CPlusPlus14 2213 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 2214 : diag::ext_constexpr_body_invalid_stmt) 2215 << isa<CXXConstructorDecl>(Dcl); 2216 } 2217 2218 if (const CXXConstructorDecl *Constructor 2219 = dyn_cast<CXXConstructorDecl>(Dcl)) { 2220 const CXXRecordDecl *RD = Constructor->getParent(); 2221 // DR1359: 2222 // - every non-variant non-static data member and base class sub-object 2223 // shall be initialized; 2224 // DR1460: 2225 // - if the class is a union having variant members, exactly one of them 2226 // shall be initialized; 2227 if (RD->isUnion()) { 2228 if (Constructor->getNumCtorInitializers() == 0 && 2229 RD->hasVariantMembers()) { 2230 if (Kind == Sema::CheckConstexprKind::Diagnose) { 2231 SemaRef.Diag( 2232 Dcl->getLocation(), 2233 SemaRef.getLangOpts().CPlusPlus20 2234 ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init 2235 : diag::ext_constexpr_union_ctor_no_init); 2236 } else if (!SemaRef.getLangOpts().CPlusPlus20) { 2237 return false; 2238 } 2239 } 2240 } else if (!Constructor->isDependentContext() && 2241 !Constructor->isDelegatingConstructor()) { 2242 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 2243 2244 // Skip detailed checking if we have enough initializers, and we would 2245 // allow at most one initializer per member. 2246 bool AnyAnonStructUnionMembers = false; 2247 unsigned Fields = 0; 2248 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 2249 E = RD->field_end(); I != E; ++I, ++Fields) { 2250 if (I->isAnonymousStructOrUnion()) { 2251 AnyAnonStructUnionMembers = true; 2252 break; 2253 } 2254 } 2255 // DR1460: 2256 // - if the class is a union-like class, but is not a union, for each of 2257 // its anonymous union members having variant members, exactly one of 2258 // them shall be initialized; 2259 if (AnyAnonStructUnionMembers || 2260 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 2261 // Check initialization of non-static data members. Base classes are 2262 // always initialized so do not need to be checked. Dependent bases 2263 // might not have initializers in the member initializer list. 2264 llvm::SmallSet<Decl*, 16> Inits; 2265 for (const auto *I: Constructor->inits()) { 2266 if (FieldDecl *FD = I->getMember()) 2267 Inits.insert(FD); 2268 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 2269 Inits.insert(ID->chain_begin(), ID->chain_end()); 2270 } 2271 2272 bool Diagnosed = false; 2273 for (auto *I : RD->fields()) 2274 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, 2275 Kind)) 2276 return false; 2277 } 2278 } 2279 } else { 2280 if (ReturnStmts.empty()) { 2281 // C++1y doesn't require constexpr functions to contain a 'return' 2282 // statement. We still do, unless the return type might be void, because 2283 // otherwise if there's no return statement, the function cannot 2284 // be used in a core constant expression. 2285 bool OK = SemaRef.getLangOpts().CPlusPlus14 && 2286 (Dcl->getReturnType()->isVoidType() || 2287 Dcl->getReturnType()->isDependentType()); 2288 switch (Kind) { 2289 case Sema::CheckConstexprKind::Diagnose: 2290 SemaRef.Diag(Dcl->getLocation(), 2291 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 2292 : diag::err_constexpr_body_no_return) 2293 << Dcl->isConsteval(); 2294 if (!OK) 2295 return false; 2296 break; 2297 2298 case Sema::CheckConstexprKind::CheckValid: 2299 // The formal requirements don't include this rule in C++14, even 2300 // though the "must be able to produce a constant expression" rules 2301 // still imply it in some cases. 2302 if (!SemaRef.getLangOpts().CPlusPlus14) 2303 return false; 2304 break; 2305 } 2306 } else if (ReturnStmts.size() > 1) { 2307 switch (Kind) { 2308 case Sema::CheckConstexprKind::Diagnose: 2309 SemaRef.Diag( 2310 ReturnStmts.back(), 2311 SemaRef.getLangOpts().CPlusPlus14 2312 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 2313 : diag::ext_constexpr_body_multiple_return); 2314 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 2315 SemaRef.Diag(ReturnStmts[I], 2316 diag::note_constexpr_body_previous_return); 2317 break; 2318 2319 case Sema::CheckConstexprKind::CheckValid: 2320 if (!SemaRef.getLangOpts().CPlusPlus14) 2321 return false; 2322 break; 2323 } 2324 } 2325 } 2326 2327 // C++11 [dcl.constexpr]p5: 2328 // if no function argument values exist such that the function invocation 2329 // substitution would produce a constant expression, the program is 2330 // ill-formed; no diagnostic required. 2331 // C++11 [dcl.constexpr]p3: 2332 // - every constructor call and implicit conversion used in initializing the 2333 // return value shall be one of those allowed in a constant expression. 2334 // C++11 [dcl.constexpr]p4: 2335 // - every constructor involved in initializing non-static data members and 2336 // base class sub-objects shall be a constexpr constructor. 2337 // 2338 // Note that this rule is distinct from the "requirements for a constexpr 2339 // function", so is not checked in CheckValid mode. 2340 SmallVector<PartialDiagnosticAt, 8> Diags; 2341 if (Kind == Sema::CheckConstexprKind::Diagnose && 2342 !Expr::isPotentialConstantExpr(Dcl, Diags)) { 2343 SemaRef.Diag(Dcl->getLocation(), 2344 diag::ext_constexpr_function_never_constant_expr) 2345 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 2346 for (size_t I = 0, N = Diags.size(); I != N; ++I) 2347 SemaRef.Diag(Diags[I].first, Diags[I].second); 2348 // Don't return false here: we allow this for compatibility in 2349 // system headers. 2350 } 2351 2352 return true; 2353 } 2354 2355 /// Get the class that is directly named by the current context. This is the 2356 /// class for which an unqualified-id in this scope could name a constructor 2357 /// or destructor. 2358 /// 2359 /// If the scope specifier denotes a class, this will be that class. 2360 /// If the scope specifier is empty, this will be the class whose 2361 /// member-specification we are currently within. Otherwise, there 2362 /// is no such class. 2363 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) { 2364 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2365 2366 if (SS && SS->isInvalid()) 2367 return nullptr; 2368 2369 if (SS && SS->isNotEmpty()) { 2370 DeclContext *DC = computeDeclContext(*SS, true); 2371 return dyn_cast_or_null<CXXRecordDecl>(DC); 2372 } 2373 2374 return dyn_cast_or_null<CXXRecordDecl>(CurContext); 2375 } 2376 2377 /// isCurrentClassName - Determine whether the identifier II is the 2378 /// name of the class type currently being defined. In the case of 2379 /// nested classes, this will only return true if II is the name of 2380 /// the innermost class. 2381 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S, 2382 const CXXScopeSpec *SS) { 2383 CXXRecordDecl *CurDecl = getCurrentClass(S, SS); 2384 return CurDecl && &II == CurDecl->getIdentifier(); 2385 } 2386 2387 /// Determine whether the identifier II is a typo for the name of 2388 /// the class type currently being defined. If so, update it to the identifier 2389 /// that should have been used. 2390 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 2391 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2392 2393 if (!getLangOpts().SpellChecking) 2394 return false; 2395 2396 CXXRecordDecl *CurDecl; 2397 if (SS && SS->isSet() && !SS->isInvalid()) { 2398 DeclContext *DC = computeDeclContext(*SS, true); 2399 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 2400 } else 2401 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 2402 2403 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 2404 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 2405 < II->getLength()) { 2406 II = CurDecl->getIdentifier(); 2407 return true; 2408 } 2409 2410 return false; 2411 } 2412 2413 /// Determine whether the given class is a base class of the given 2414 /// class, including looking at dependent bases. 2415 static bool findCircularInheritance(const CXXRecordDecl *Class, 2416 const CXXRecordDecl *Current) { 2417 SmallVector<const CXXRecordDecl*, 8> Queue; 2418 2419 Class = Class->getCanonicalDecl(); 2420 while (true) { 2421 for (const auto &I : Current->bases()) { 2422 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 2423 if (!Base) 2424 continue; 2425 2426 Base = Base->getDefinition(); 2427 if (!Base) 2428 continue; 2429 2430 if (Base->getCanonicalDecl() == Class) 2431 return true; 2432 2433 Queue.push_back(Base); 2434 } 2435 2436 if (Queue.empty()) 2437 return false; 2438 2439 Current = Queue.pop_back_val(); 2440 } 2441 2442 return false; 2443 } 2444 2445 /// Check the validity of a C++ base class specifier. 2446 /// 2447 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 2448 /// and returns NULL otherwise. 2449 CXXBaseSpecifier * 2450 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 2451 SourceRange SpecifierRange, 2452 bool Virtual, AccessSpecifier Access, 2453 TypeSourceInfo *TInfo, 2454 SourceLocation EllipsisLoc) { 2455 QualType BaseType = TInfo->getType(); 2456 if (BaseType->containsErrors()) { 2457 // Already emitted a diagnostic when parsing the error type. 2458 return nullptr; 2459 } 2460 // C++ [class.union]p1: 2461 // A union shall not have base classes. 2462 if (Class->isUnion()) { 2463 Diag(Class->getLocation(), diag::err_base_clause_on_union) 2464 << SpecifierRange; 2465 return nullptr; 2466 } 2467 2468 if (EllipsisLoc.isValid() && 2469 !TInfo->getType()->containsUnexpandedParameterPack()) { 2470 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2471 << TInfo->getTypeLoc().getSourceRange(); 2472 EllipsisLoc = SourceLocation(); 2473 } 2474 2475 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 2476 2477 if (BaseType->isDependentType()) { 2478 // Make sure that we don't have circular inheritance among our dependent 2479 // bases. For non-dependent bases, the check for completeness below handles 2480 // this. 2481 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 2482 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 2483 ((BaseDecl = BaseDecl->getDefinition()) && 2484 findCircularInheritance(Class, BaseDecl))) { 2485 Diag(BaseLoc, diag::err_circular_inheritance) 2486 << BaseType << Context.getTypeDeclType(Class); 2487 2488 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 2489 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 2490 << BaseType; 2491 2492 return nullptr; 2493 } 2494 } 2495 2496 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2497 Class->getTagKind() == TTK_Class, 2498 Access, TInfo, EllipsisLoc); 2499 } 2500 2501 // Base specifiers must be record types. 2502 if (!BaseType->isRecordType()) { 2503 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 2504 return nullptr; 2505 } 2506 2507 // C++ [class.union]p1: 2508 // A union shall not be used as a base class. 2509 if (BaseType->isUnionType()) { 2510 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 2511 return nullptr; 2512 } 2513 2514 // For the MS ABI, propagate DLL attributes to base class templates. 2515 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 2516 if (Attr *ClassAttr = getDLLAttr(Class)) { 2517 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 2518 BaseType->getAsCXXRecordDecl())) { 2519 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate, 2520 BaseLoc); 2521 } 2522 } 2523 } 2524 2525 // C++ [class.derived]p2: 2526 // The class-name in a base-specifier shall not be an incompletely 2527 // defined class. 2528 if (RequireCompleteType(BaseLoc, BaseType, 2529 diag::err_incomplete_base_class, SpecifierRange)) { 2530 Class->setInvalidDecl(); 2531 return nullptr; 2532 } 2533 2534 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 2535 RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl(); 2536 assert(BaseDecl && "Record type has no declaration"); 2537 BaseDecl = BaseDecl->getDefinition(); 2538 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 2539 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 2540 assert(CXXBaseDecl && "Base type is not a C++ type"); 2541 2542 // Microsoft docs say: 2543 // "If a base-class has a code_seg attribute, derived classes must have the 2544 // same attribute." 2545 const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>(); 2546 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>(); 2547 if ((DerivedCSA || BaseCSA) && 2548 (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) { 2549 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base); 2550 Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here) 2551 << CXXBaseDecl; 2552 return nullptr; 2553 } 2554 2555 // A class which contains a flexible array member is not suitable for use as a 2556 // base class: 2557 // - If the layout determines that a base comes before another base, 2558 // the flexible array member would index into the subsequent base. 2559 // - If the layout determines that base comes before the derived class, 2560 // the flexible array member would index into the derived class. 2561 if (CXXBaseDecl->hasFlexibleArrayMember()) { 2562 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 2563 << CXXBaseDecl->getDeclName(); 2564 return nullptr; 2565 } 2566 2567 // C++ [class]p3: 2568 // If a class is marked final and it appears as a base-type-specifier in 2569 // base-clause, the program is ill-formed. 2570 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 2571 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 2572 << CXXBaseDecl->getDeclName() 2573 << FA->isSpelledAsSealed(); 2574 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 2575 << CXXBaseDecl->getDeclName() << FA->getRange(); 2576 return nullptr; 2577 } 2578 2579 if (BaseDecl->isInvalidDecl()) 2580 Class->setInvalidDecl(); 2581 2582 // Create the base specifier. 2583 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2584 Class->getTagKind() == TTK_Class, 2585 Access, TInfo, EllipsisLoc); 2586 } 2587 2588 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 2589 /// one entry in the base class list of a class specifier, for 2590 /// example: 2591 /// class foo : public bar, virtual private baz { 2592 /// 'public bar' and 'virtual private baz' are each base-specifiers. 2593 BaseResult 2594 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 2595 ParsedAttributes &Attributes, 2596 bool Virtual, AccessSpecifier Access, 2597 ParsedType basetype, SourceLocation BaseLoc, 2598 SourceLocation EllipsisLoc) { 2599 if (!classdecl) 2600 return true; 2601 2602 AdjustDeclIfTemplate(classdecl); 2603 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 2604 if (!Class) 2605 return true; 2606 2607 // We haven't yet attached the base specifiers. 2608 Class->setIsParsingBaseSpecifiers(); 2609 2610 // We do not support any C++11 attributes on base-specifiers yet. 2611 // Diagnose any attributes we see. 2612 for (const ParsedAttr &AL : Attributes) { 2613 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute) 2614 continue; 2615 Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute 2616 ? (unsigned)diag::warn_unknown_attribute_ignored 2617 : (unsigned)diag::err_base_specifier_attribute) 2618 << AL << AL.getRange(); 2619 } 2620 2621 TypeSourceInfo *TInfo = nullptr; 2622 GetTypeFromParser(basetype, &TInfo); 2623 2624 if (EllipsisLoc.isInvalid() && 2625 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 2626 UPPC_BaseType)) 2627 return true; 2628 2629 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 2630 Virtual, Access, TInfo, 2631 EllipsisLoc)) 2632 return BaseSpec; 2633 else 2634 Class->setInvalidDecl(); 2635 2636 return true; 2637 } 2638 2639 /// Use small set to collect indirect bases. As this is only used 2640 /// locally, there's no need to abstract the small size parameter. 2641 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet; 2642 2643 /// Recursively add the bases of Type. Don't add Type itself. 2644 static void 2645 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, 2646 const QualType &Type) 2647 { 2648 // Even though the incoming type is a base, it might not be 2649 // a class -- it could be a template parm, for instance. 2650 if (auto Rec = Type->getAs<RecordType>()) { 2651 auto Decl = Rec->getAsCXXRecordDecl(); 2652 2653 // Iterate over its bases. 2654 for (const auto &BaseSpec : Decl->bases()) { 2655 QualType Base = Context.getCanonicalType(BaseSpec.getType()) 2656 .getUnqualifiedType(); 2657 if (Set.insert(Base).second) 2658 // If we've not already seen it, recurse. 2659 NoteIndirectBases(Context, Set, Base); 2660 } 2661 } 2662 } 2663 2664 /// Performs the actual work of attaching the given base class 2665 /// specifiers to a C++ class. 2666 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, 2667 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2668 if (Bases.empty()) 2669 return false; 2670 2671 // Used to keep track of which base types we have already seen, so 2672 // that we can properly diagnose redundant direct base types. Note 2673 // that the key is always the unqualified canonical type of the base 2674 // class. 2675 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 2676 2677 // Used to track indirect bases so we can see if a direct base is 2678 // ambiguous. 2679 IndirectBaseSet IndirectBaseTypes; 2680 2681 // Copy non-redundant base specifiers into permanent storage. 2682 unsigned NumGoodBases = 0; 2683 bool Invalid = false; 2684 for (unsigned idx = 0; idx < Bases.size(); ++idx) { 2685 QualType NewBaseType 2686 = Context.getCanonicalType(Bases[idx]->getType()); 2687 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 2688 2689 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 2690 if (KnownBase) { 2691 // C++ [class.mi]p3: 2692 // A class shall not be specified as a direct base class of a 2693 // derived class more than once. 2694 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class) 2695 << KnownBase->getType() << Bases[idx]->getSourceRange(); 2696 2697 // Delete the duplicate base class specifier; we're going to 2698 // overwrite its pointer later. 2699 Context.Deallocate(Bases[idx]); 2700 2701 Invalid = true; 2702 } else { 2703 // Okay, add this new base class. 2704 KnownBase = Bases[idx]; 2705 Bases[NumGoodBases++] = Bases[idx]; 2706 2707 // Note this base's direct & indirect bases, if there could be ambiguity. 2708 if (Bases.size() > 1) 2709 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType); 2710 2711 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 2712 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 2713 if (Class->isInterface() && 2714 (!RD->isInterfaceLike() || 2715 KnownBase->getAccessSpecifier() != AS_public)) { 2716 // The Microsoft extension __interface does not permit bases that 2717 // are not themselves public interfaces. 2718 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface) 2719 << getRecordDiagFromTagKind(RD->getTagKind()) << RD 2720 << RD->getSourceRange(); 2721 Invalid = true; 2722 } 2723 if (RD->hasAttr<WeakAttr>()) 2724 Class->addAttr(WeakAttr::CreateImplicit(Context)); 2725 } 2726 } 2727 } 2728 2729 // Attach the remaining base class specifiers to the derived class. 2730 Class->setBases(Bases.data(), NumGoodBases); 2731 2732 // Check that the only base classes that are duplicate are virtual. 2733 for (unsigned idx = 0; idx < NumGoodBases; ++idx) { 2734 // Check whether this direct base is inaccessible due to ambiguity. 2735 QualType BaseType = Bases[idx]->getType(); 2736 2737 // Skip all dependent types in templates being used as base specifiers. 2738 // Checks below assume that the base specifier is a CXXRecord. 2739 if (BaseType->isDependentType()) 2740 continue; 2741 2742 CanQualType CanonicalBase = Context.getCanonicalType(BaseType) 2743 .getUnqualifiedType(); 2744 2745 if (IndirectBaseTypes.count(CanonicalBase)) { 2746 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2747 /*DetectVirtual=*/true); 2748 bool found 2749 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); 2750 assert(found); 2751 (void)found; 2752 2753 if (Paths.isAmbiguous(CanonicalBase)) 2754 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class) 2755 << BaseType << getAmbiguousPathsDisplayString(Paths) 2756 << Bases[idx]->getSourceRange(); 2757 else 2758 assert(Bases[idx]->isVirtual()); 2759 } 2760 2761 // Delete the base class specifier, since its data has been copied 2762 // into the CXXRecordDecl. 2763 Context.Deallocate(Bases[idx]); 2764 } 2765 2766 return Invalid; 2767 } 2768 2769 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 2770 /// class, after checking whether there are any duplicate base 2771 /// classes. 2772 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, 2773 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2774 if (!ClassDecl || Bases.empty()) 2775 return; 2776 2777 AdjustDeclIfTemplate(ClassDecl); 2778 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases); 2779 } 2780 2781 /// Determine whether the type \p Derived is a C++ class that is 2782 /// derived from the type \p Base. 2783 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) { 2784 if (!getLangOpts().CPlusPlus) 2785 return false; 2786 2787 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2788 if (!DerivedRD) 2789 return false; 2790 2791 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2792 if (!BaseRD) 2793 return false; 2794 2795 // If either the base or the derived type is invalid, don't try to 2796 // check whether one is derived from the other. 2797 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 2798 return false; 2799 2800 // FIXME: In a modules build, do we need the entire path to be visible for us 2801 // to be able to use the inheritance relationship? 2802 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2803 return false; 2804 2805 return DerivedRD->isDerivedFrom(BaseRD); 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 CXXBasePaths &Paths) { 2812 if (!getLangOpts().CPlusPlus) 2813 return false; 2814 2815 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2816 if (!DerivedRD) 2817 return false; 2818 2819 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2820 if (!BaseRD) 2821 return false; 2822 2823 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2824 return false; 2825 2826 return DerivedRD->isDerivedFrom(BaseRD, Paths); 2827 } 2828 2829 static void BuildBasePathArray(const CXXBasePath &Path, 2830 CXXCastPath &BasePathArray) { 2831 // We first go backward and check if we have a virtual base. 2832 // FIXME: It would be better if CXXBasePath had the base specifier for 2833 // the nearest virtual base. 2834 unsigned Start = 0; 2835 for (unsigned I = Path.size(); I != 0; --I) { 2836 if (Path[I - 1].Base->isVirtual()) { 2837 Start = I - 1; 2838 break; 2839 } 2840 } 2841 2842 // Now add all bases. 2843 for (unsigned I = Start, E = Path.size(); I != E; ++I) 2844 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 2845 } 2846 2847 2848 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 2849 CXXCastPath &BasePathArray) { 2850 assert(BasePathArray.empty() && "Base path array must be empty!"); 2851 assert(Paths.isRecordingPaths() && "Must record paths!"); 2852 return ::BuildBasePathArray(Paths.front(), BasePathArray); 2853 } 2854 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 2855 /// conversion (where Derived and Base are class types) is 2856 /// well-formed, meaning that the conversion is unambiguous (and 2857 /// that all of the base classes are accessible). Returns true 2858 /// and emits a diagnostic if the code is ill-formed, returns false 2859 /// otherwise. Loc is the location where this routine should point to 2860 /// if there is an error, and Range is the source range to highlight 2861 /// if there is an error. 2862 /// 2863 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the 2864 /// diagnostic for the respective type of error will be suppressed, but the 2865 /// check for ill-formed code will still be performed. 2866 bool 2867 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2868 unsigned InaccessibleBaseID, 2869 unsigned AmbiguousBaseConvID, 2870 SourceLocation Loc, SourceRange Range, 2871 DeclarationName Name, 2872 CXXCastPath *BasePath, 2873 bool IgnoreAccess) { 2874 // First, determine whether the path from Derived to Base is 2875 // ambiguous. This is slightly more expensive than checking whether 2876 // the Derived to Base conversion exists, because here we need to 2877 // explore multiple paths to determine if there is an ambiguity. 2878 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2879 /*DetectVirtual=*/false); 2880 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2881 if (!DerivationOkay) 2882 return true; 2883 2884 const CXXBasePath *Path = nullptr; 2885 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) 2886 Path = &Paths.front(); 2887 2888 // For MSVC compatibility, check if Derived directly inherits from Base. Clang 2889 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the 2890 // user to access such bases. 2891 if (!Path && getLangOpts().MSVCCompat) { 2892 for (const CXXBasePath &PossiblePath : Paths) { 2893 if (PossiblePath.size() == 1) { 2894 Path = &PossiblePath; 2895 if (AmbiguousBaseConvID) 2896 Diag(Loc, diag::ext_ms_ambiguous_direct_base) 2897 << Base << Derived << Range; 2898 break; 2899 } 2900 } 2901 } 2902 2903 if (Path) { 2904 if (!IgnoreAccess) { 2905 // Check that the base class can be accessed. 2906 switch ( 2907 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) { 2908 case AR_inaccessible: 2909 return true; 2910 case AR_accessible: 2911 case AR_dependent: 2912 case AR_delayed: 2913 break; 2914 } 2915 } 2916 2917 // Build a base path if necessary. 2918 if (BasePath) 2919 ::BuildBasePathArray(*Path, *BasePath); 2920 return false; 2921 } 2922 2923 if (AmbiguousBaseConvID) { 2924 // We know that the derived-to-base conversion is ambiguous, and 2925 // we're going to produce a diagnostic. Perform the derived-to-base 2926 // search just one more time to compute all of the possible paths so 2927 // that we can print them out. This is more expensive than any of 2928 // the previous derived-to-base checks we've done, but at this point 2929 // performance isn't as much of an issue. 2930 Paths.clear(); 2931 Paths.setRecordingPaths(true); 2932 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2933 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 2934 (void)StillOkay; 2935 2936 // Build up a textual representation of the ambiguous paths, e.g., 2937 // D -> B -> A, that will be used to illustrate the ambiguous 2938 // conversions in the diagnostic. We only print one of the paths 2939 // to each base class subobject. 2940 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2941 2942 Diag(Loc, AmbiguousBaseConvID) 2943 << Derived << Base << PathDisplayStr << Range << Name; 2944 } 2945 return true; 2946 } 2947 2948 bool 2949 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2950 SourceLocation Loc, SourceRange Range, 2951 CXXCastPath *BasePath, 2952 bool IgnoreAccess) { 2953 return CheckDerivedToBaseConversion( 2954 Derived, Base, diag::err_upcast_to_inaccessible_base, 2955 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(), 2956 BasePath, IgnoreAccess); 2957 } 2958 2959 2960 /// Builds a string representing ambiguous paths from a 2961 /// specific derived class to different subobjects of the same base 2962 /// class. 2963 /// 2964 /// This function builds a string that can be used in error messages 2965 /// to show the different paths that one can take through the 2966 /// inheritance hierarchy to go from the derived class to different 2967 /// subobjects of a base class. The result looks something like this: 2968 /// @code 2969 /// struct D -> struct B -> struct A 2970 /// struct D -> struct C -> struct A 2971 /// @endcode 2972 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 2973 std::string PathDisplayStr; 2974 std::set<unsigned> DisplayedPaths; 2975 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2976 Path != Paths.end(); ++Path) { 2977 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 2978 // We haven't displayed a path to this particular base 2979 // class subobject yet. 2980 PathDisplayStr += "\n "; 2981 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 2982 for (CXXBasePath::const_iterator Element = Path->begin(); 2983 Element != Path->end(); ++Element) 2984 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 2985 } 2986 } 2987 2988 return PathDisplayStr; 2989 } 2990 2991 //===----------------------------------------------------------------------===// 2992 // C++ class member Handling 2993 //===----------------------------------------------------------------------===// 2994 2995 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 2996 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, 2997 SourceLocation ColonLoc, 2998 const ParsedAttributesView &Attrs) { 2999 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 3000 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 3001 ASLoc, ColonLoc); 3002 CurContext->addHiddenDecl(ASDecl); 3003 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 3004 } 3005 3006 /// CheckOverrideControl - Check C++11 override control semantics. 3007 void Sema::CheckOverrideControl(NamedDecl *D) { 3008 if (D->isInvalidDecl()) 3009 return; 3010 3011 // We only care about "override" and "final" declarations. 3012 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 3013 return; 3014 3015 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 3016 3017 // We can't check dependent instance methods. 3018 if (MD && MD->isInstance() && 3019 (MD->getParent()->hasAnyDependentBases() || 3020 MD->getType()->isDependentType())) 3021 return; 3022 3023 if (MD && !MD->isVirtual()) { 3024 // If we have a non-virtual method, check if if hides a virtual method. 3025 // (In that case, it's most likely the method has the wrong type.) 3026 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 3027 FindHiddenVirtualMethods(MD, OverloadedMethods); 3028 3029 if (!OverloadedMethods.empty()) { 3030 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 3031 Diag(OA->getLocation(), 3032 diag::override_keyword_hides_virtual_member_function) 3033 << "override" << (OverloadedMethods.size() > 1); 3034 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 3035 Diag(FA->getLocation(), 3036 diag::override_keyword_hides_virtual_member_function) 3037 << (FA->isSpelledAsSealed() ? "sealed" : "final") 3038 << (OverloadedMethods.size() > 1); 3039 } 3040 NoteHiddenVirtualMethods(MD, OverloadedMethods); 3041 MD->setInvalidDecl(); 3042 return; 3043 } 3044 // Fall through into the general case diagnostic. 3045 // FIXME: We might want to attempt typo correction here. 3046 } 3047 3048 if (!MD || !MD->isVirtual()) { 3049 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 3050 Diag(OA->getLocation(), 3051 diag::override_keyword_only_allowed_on_virtual_member_functions) 3052 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 3053 D->dropAttr<OverrideAttr>(); 3054 } 3055 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 3056 Diag(FA->getLocation(), 3057 diag::override_keyword_only_allowed_on_virtual_member_functions) 3058 << (FA->isSpelledAsSealed() ? "sealed" : "final") 3059 << FixItHint::CreateRemoval(FA->getLocation()); 3060 D->dropAttr<FinalAttr>(); 3061 } 3062 return; 3063 } 3064 3065 // C++11 [class.virtual]p5: 3066 // If a function is marked with the virt-specifier override and 3067 // does not override a member function of a base class, the program is 3068 // ill-formed. 3069 bool HasOverriddenMethods = MD->size_overridden_methods() != 0; 3070 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 3071 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 3072 << MD->getDeclName(); 3073 } 3074 3075 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) { 3076 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) 3077 return; 3078 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 3079 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>()) 3080 return; 3081 3082 SourceLocation Loc = MD->getLocation(); 3083 SourceLocation SpellingLoc = Loc; 3084 if (getSourceManager().isMacroArgExpansion(Loc)) 3085 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin(); 3086 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); 3087 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) 3088 return; 3089 3090 if (MD->size_overridden_methods() > 0) { 3091 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) { 3092 unsigned DiagID = 3093 Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation()) 3094 ? DiagInconsistent 3095 : DiagSuggest; 3096 Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 3097 const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); 3098 Diag(OMD->getLocation(), diag::note_overridden_virtual_function); 3099 }; 3100 if (isa<CXXDestructorDecl>(MD)) 3101 EmitDiag( 3102 diag::warn_inconsistent_destructor_marked_not_override_overriding, 3103 diag::warn_suggest_destructor_marked_not_override_overriding); 3104 else 3105 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding, 3106 diag::warn_suggest_function_marked_not_override_overriding); 3107 } 3108 } 3109 3110 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 3111 /// function overrides a virtual member function marked 'final', according to 3112 /// C++11 [class.virtual]p4. 3113 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 3114 const CXXMethodDecl *Old) { 3115 FinalAttr *FA = Old->getAttr<FinalAttr>(); 3116 if (!FA) 3117 return false; 3118 3119 Diag(New->getLocation(), diag::err_final_function_overridden) 3120 << New->getDeclName() 3121 << FA->isSpelledAsSealed(); 3122 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 3123 return true; 3124 } 3125 3126 static bool InitializationHasSideEffects(const FieldDecl &FD) { 3127 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 3128 // FIXME: Destruction of ObjC lifetime types has side-effects. 3129 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 3130 return !RD->isCompleteDefinition() || 3131 !RD->hasTrivialDefaultConstructor() || 3132 !RD->hasTrivialDestructor(); 3133 return false; 3134 } 3135 3136 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) { 3137 ParsedAttributesView::const_iterator Itr = 3138 llvm::find_if(list, [](const ParsedAttr &AL) { 3139 return AL.isDeclspecPropertyAttribute(); 3140 }); 3141 if (Itr != list.end()) 3142 return &*Itr; 3143 return nullptr; 3144 } 3145 3146 // Check if there is a field shadowing. 3147 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc, 3148 DeclarationName FieldName, 3149 const CXXRecordDecl *RD, 3150 bool DeclIsField) { 3151 if (Diags.isIgnored(diag::warn_shadow_field, Loc)) 3152 return; 3153 3154 // To record a shadowed field in a base 3155 std::map<CXXRecordDecl*, NamedDecl*> Bases; 3156 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier, 3157 CXXBasePath &Path) { 3158 const auto Base = Specifier->getType()->getAsCXXRecordDecl(); 3159 // Record an ambiguous path directly 3160 if (Bases.find(Base) != Bases.end()) 3161 return true; 3162 for (const auto Field : Base->lookup(FieldName)) { 3163 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) && 3164 Field->getAccess() != AS_private) { 3165 assert(Field->getAccess() != AS_none); 3166 assert(Bases.find(Base) == Bases.end()); 3167 Bases[Base] = Field; 3168 return true; 3169 } 3170 } 3171 return false; 3172 }; 3173 3174 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3175 /*DetectVirtual=*/true); 3176 if (!RD->lookupInBases(FieldShadowed, Paths)) 3177 return; 3178 3179 for (const auto &P : Paths) { 3180 auto Base = P.back().Base->getType()->getAsCXXRecordDecl(); 3181 auto It = Bases.find(Base); 3182 // Skip duplicated bases 3183 if (It == Bases.end()) 3184 continue; 3185 auto BaseField = It->second; 3186 assert(BaseField->getAccess() != AS_private); 3187 if (AS_none != 3188 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) { 3189 Diag(Loc, diag::warn_shadow_field) 3190 << FieldName << RD << Base << DeclIsField; 3191 Diag(BaseField->getLocation(), diag::note_shadow_field); 3192 Bases.erase(It); 3193 } 3194 } 3195 } 3196 3197 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 3198 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 3199 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 3200 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 3201 /// present (but parsing it has been deferred). 3202 NamedDecl * 3203 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 3204 MultiTemplateParamsArg TemplateParameterLists, 3205 Expr *BW, const VirtSpecifiers &VS, 3206 InClassInitStyle InitStyle) { 3207 const DeclSpec &DS = D.getDeclSpec(); 3208 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 3209 DeclarationName Name = NameInfo.getName(); 3210 SourceLocation Loc = NameInfo.getLoc(); 3211 3212 // For anonymous bitfields, the location should point to the type. 3213 if (Loc.isInvalid()) 3214 Loc = D.getBeginLoc(); 3215 3216 Expr *BitWidth = static_cast<Expr*>(BW); 3217 3218 assert(isa<CXXRecordDecl>(CurContext)); 3219 assert(!DS.isFriendSpecified()); 3220 3221 bool isFunc = D.isDeclarationOfFunction(); 3222 const ParsedAttr *MSPropertyAttr = 3223 getMSPropertyAttr(D.getDeclSpec().getAttributes()); 3224 3225 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 3226 // The Microsoft extension __interface only permits public member functions 3227 // and prohibits constructors, destructors, operators, non-public member 3228 // functions, static methods and data members. 3229 unsigned InvalidDecl; 3230 bool ShowDeclName = true; 3231 if (!isFunc && 3232 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr)) 3233 InvalidDecl = 0; 3234 else if (!isFunc) 3235 InvalidDecl = 1; 3236 else if (AS != AS_public) 3237 InvalidDecl = 2; 3238 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 3239 InvalidDecl = 3; 3240 else switch (Name.getNameKind()) { 3241 case DeclarationName::CXXConstructorName: 3242 InvalidDecl = 4; 3243 ShowDeclName = false; 3244 break; 3245 3246 case DeclarationName::CXXDestructorName: 3247 InvalidDecl = 5; 3248 ShowDeclName = false; 3249 break; 3250 3251 case DeclarationName::CXXOperatorName: 3252 case DeclarationName::CXXConversionFunctionName: 3253 InvalidDecl = 6; 3254 break; 3255 3256 default: 3257 InvalidDecl = 0; 3258 break; 3259 } 3260 3261 if (InvalidDecl) { 3262 if (ShowDeclName) 3263 Diag(Loc, diag::err_invalid_member_in_interface) 3264 << (InvalidDecl-1) << Name; 3265 else 3266 Diag(Loc, diag::err_invalid_member_in_interface) 3267 << (InvalidDecl-1) << ""; 3268 return nullptr; 3269 } 3270 } 3271 3272 // C++ 9.2p6: A member shall not be declared to have automatic storage 3273 // duration (auto, register) or with the extern storage-class-specifier. 3274 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 3275 // data members and cannot be applied to names declared const or static, 3276 // and cannot be applied to reference members. 3277 switch (DS.getStorageClassSpec()) { 3278 case DeclSpec::SCS_unspecified: 3279 case DeclSpec::SCS_typedef: 3280 case DeclSpec::SCS_static: 3281 break; 3282 case DeclSpec::SCS_mutable: 3283 if (isFunc) { 3284 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 3285 3286 // FIXME: It would be nicer if the keyword was ignored only for this 3287 // declarator. Otherwise we could get follow-up errors. 3288 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3289 } 3290 break; 3291 default: 3292 Diag(DS.getStorageClassSpecLoc(), 3293 diag::err_storageclass_invalid_for_member); 3294 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3295 break; 3296 } 3297 3298 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 3299 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 3300 !isFunc); 3301 3302 if (DS.hasConstexprSpecifier() && isInstField) { 3303 SemaDiagnosticBuilder B = 3304 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 3305 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 3306 if (InitStyle == ICIS_NoInit) { 3307 B << 0 << 0; 3308 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 3309 B << FixItHint::CreateRemoval(ConstexprLoc); 3310 else { 3311 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 3312 D.getMutableDeclSpec().ClearConstexprSpec(); 3313 const char *PrevSpec; 3314 unsigned DiagID; 3315 bool Failed = D.getMutableDeclSpec().SetTypeQual( 3316 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 3317 (void)Failed; 3318 assert(!Failed && "Making a constexpr member const shouldn't fail"); 3319 } 3320 } else { 3321 B << 1; 3322 const char *PrevSpec; 3323 unsigned DiagID; 3324 if (D.getMutableDeclSpec().SetStorageClassSpec( 3325 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 3326 Context.getPrintingPolicy())) { 3327 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 3328 "This is the only DeclSpec that should fail to be applied"); 3329 B << 1; 3330 } else { 3331 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 3332 isInstField = false; 3333 } 3334 } 3335 } 3336 3337 NamedDecl *Member; 3338 if (isInstField) { 3339 CXXScopeSpec &SS = D.getCXXScopeSpec(); 3340 3341 // Data members must have identifiers for names. 3342 if (!Name.isIdentifier()) { 3343 Diag(Loc, diag::err_bad_variable_name) 3344 << Name; 3345 return nullptr; 3346 } 3347 3348 IdentifierInfo *II = Name.getAsIdentifierInfo(); 3349 3350 // Member field could not be with "template" keyword. 3351 // So TemplateParameterLists should be empty in this case. 3352 if (TemplateParameterLists.size()) { 3353 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 3354 if (TemplateParams->size()) { 3355 // There is no such thing as a member field template. 3356 Diag(D.getIdentifierLoc(), diag::err_template_member) 3357 << II 3358 << SourceRange(TemplateParams->getTemplateLoc(), 3359 TemplateParams->getRAngleLoc()); 3360 } else { 3361 // There is an extraneous 'template<>' for this member. 3362 Diag(TemplateParams->getTemplateLoc(), 3363 diag::err_template_member_noparams) 3364 << II 3365 << SourceRange(TemplateParams->getTemplateLoc(), 3366 TemplateParams->getRAngleLoc()); 3367 } 3368 return nullptr; 3369 } 3370 3371 if (SS.isSet() && !SS.isInvalid()) { 3372 // The user provided a superfluous scope specifier inside a class 3373 // definition: 3374 // 3375 // class X { 3376 // int X::member; 3377 // }; 3378 if (DeclContext *DC = computeDeclContext(SS, false)) 3379 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(), 3380 D.getName().getKind() == 3381 UnqualifiedIdKind::IK_TemplateId); 3382 else 3383 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 3384 << Name << SS.getRange(); 3385 3386 SS.clear(); 3387 } 3388 3389 if (MSPropertyAttr) { 3390 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3391 BitWidth, InitStyle, AS, *MSPropertyAttr); 3392 if (!Member) 3393 return nullptr; 3394 isInstField = false; 3395 } else { 3396 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3397 BitWidth, InitStyle, AS); 3398 if (!Member) 3399 return nullptr; 3400 } 3401 3402 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext)); 3403 } else { 3404 Member = HandleDeclarator(S, D, TemplateParameterLists); 3405 if (!Member) 3406 return nullptr; 3407 3408 // Non-instance-fields can't have a bitfield. 3409 if (BitWidth) { 3410 if (Member->isInvalidDecl()) { 3411 // don't emit another diagnostic. 3412 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) { 3413 // C++ 9.6p3: A bit-field shall not be a static member. 3414 // "static member 'A' cannot be a bit-field" 3415 Diag(Loc, diag::err_static_not_bitfield) 3416 << Name << BitWidth->getSourceRange(); 3417 } else if (isa<TypedefDecl>(Member)) { 3418 // "typedef member 'x' cannot be a bit-field" 3419 Diag(Loc, diag::err_typedef_not_bitfield) 3420 << Name << BitWidth->getSourceRange(); 3421 } else { 3422 // A function typedef ("typedef int f(); f a;"). 3423 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 3424 Diag(Loc, diag::err_not_integral_type_bitfield) 3425 << Name << cast<ValueDecl>(Member)->getType() 3426 << BitWidth->getSourceRange(); 3427 } 3428 3429 BitWidth = nullptr; 3430 Member->setInvalidDecl(); 3431 } 3432 3433 NamedDecl *NonTemplateMember = Member; 3434 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 3435 NonTemplateMember = FunTmpl->getTemplatedDecl(); 3436 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 3437 NonTemplateMember = VarTmpl->getTemplatedDecl(); 3438 3439 Member->setAccess(AS); 3440 3441 // If we have declared a member function template or static data member 3442 // template, set the access of the templated declaration as well. 3443 if (NonTemplateMember != Member) 3444 NonTemplateMember->setAccess(AS); 3445 3446 // C++ [temp.deduct.guide]p3: 3447 // A deduction guide [...] for a member class template [shall be 3448 // declared] with the same access [as the template]. 3449 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) { 3450 auto *TD = DG->getDeducedTemplate(); 3451 // Access specifiers are only meaningful if both the template and the 3452 // deduction guide are from the same scope. 3453 if (AS != TD->getAccess() && 3454 TD->getDeclContext()->getRedeclContext()->Equals( 3455 DG->getDeclContext()->getRedeclContext())) { 3456 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access); 3457 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access) 3458 << TD->getAccess(); 3459 const AccessSpecDecl *LastAccessSpec = nullptr; 3460 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) { 3461 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D)) 3462 LastAccessSpec = AccessSpec; 3463 } 3464 assert(LastAccessSpec && "differing access with no access specifier"); 3465 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access) 3466 << AS; 3467 } 3468 } 3469 } 3470 3471 if (VS.isOverrideSpecified()) 3472 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(), 3473 AttributeCommonInfo::AS_Keyword)); 3474 if (VS.isFinalSpecified()) 3475 Member->addAttr(FinalAttr::Create( 3476 Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword, 3477 static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed()))); 3478 3479 if (VS.getLastLocation().isValid()) { 3480 // Update the end location of a method that has a virt-specifiers. 3481 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 3482 MD->setRangeEnd(VS.getLastLocation()); 3483 } 3484 3485 CheckOverrideControl(Member); 3486 3487 assert((Name || isInstField) && "No identifier for non-field ?"); 3488 3489 if (isInstField) { 3490 FieldDecl *FD = cast<FieldDecl>(Member); 3491 FieldCollector->Add(FD); 3492 3493 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 3494 // Remember all explicit private FieldDecls that have a name, no side 3495 // effects and are not part of a dependent type declaration. 3496 if (!FD->isImplicit() && FD->getDeclName() && 3497 FD->getAccess() == AS_private && 3498 !FD->hasAttr<UnusedAttr>() && 3499 !FD->getParent()->isDependentContext() && 3500 !InitializationHasSideEffects(*FD)) 3501 UnusedPrivateFields.insert(FD); 3502 } 3503 } 3504 3505 return Member; 3506 } 3507 3508 namespace { 3509 class UninitializedFieldVisitor 3510 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 3511 Sema &S; 3512 // List of Decls to generate a warning on. Also remove Decls that become 3513 // initialized. 3514 llvm::SmallPtrSetImpl<ValueDecl*> &Decls; 3515 // List of base classes of the record. Classes are removed after their 3516 // initializers. 3517 llvm::SmallPtrSetImpl<QualType> &BaseClasses; 3518 // Vector of decls to be removed from the Decl set prior to visiting the 3519 // nodes. These Decls may have been initialized in the prior initializer. 3520 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; 3521 // If non-null, add a note to the warning pointing back to the constructor. 3522 const CXXConstructorDecl *Constructor; 3523 // Variables to hold state when processing an initializer list. When 3524 // InitList is true, special case initialization of FieldDecls matching 3525 // InitListFieldDecl. 3526 bool InitList; 3527 FieldDecl *InitListFieldDecl; 3528 llvm::SmallVector<unsigned, 4> InitFieldIndex; 3529 3530 public: 3531 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 3532 UninitializedFieldVisitor(Sema &S, 3533 llvm::SmallPtrSetImpl<ValueDecl*> &Decls, 3534 llvm::SmallPtrSetImpl<QualType> &BaseClasses) 3535 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), 3536 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} 3537 3538 // Returns true if the use of ME is not an uninitialized use. 3539 bool IsInitListMemberExprInitialized(MemberExpr *ME, 3540 bool CheckReferenceOnly) { 3541 llvm::SmallVector<FieldDecl*, 4> Fields; 3542 bool ReferenceField = false; 3543 while (ME) { 3544 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 3545 if (!FD) 3546 return false; 3547 Fields.push_back(FD); 3548 if (FD->getType()->isReferenceType()) 3549 ReferenceField = true; 3550 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); 3551 } 3552 3553 // Binding a reference to an uninitialized field is not an 3554 // uninitialized use. 3555 if (CheckReferenceOnly && !ReferenceField) 3556 return true; 3557 3558 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 3559 // Discard the first field since it is the field decl that is being 3560 // initialized. 3561 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) { 3562 UsedFieldIndex.push_back((*I)->getFieldIndex()); 3563 } 3564 3565 for (auto UsedIter = UsedFieldIndex.begin(), 3566 UsedEnd = UsedFieldIndex.end(), 3567 OrigIter = InitFieldIndex.begin(), 3568 OrigEnd = InitFieldIndex.end(); 3569 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 3570 if (*UsedIter < *OrigIter) 3571 return true; 3572 if (*UsedIter > *OrigIter) 3573 break; 3574 } 3575 3576 return false; 3577 } 3578 3579 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, 3580 bool AddressOf) { 3581 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 3582 return; 3583 3584 // FieldME is the inner-most MemberExpr that is not an anonymous struct 3585 // or union. 3586 MemberExpr *FieldME = ME; 3587 3588 bool AllPODFields = FieldME->getType().isPODType(S.Context); 3589 3590 Expr *Base = ME; 3591 while (MemberExpr *SubME = 3592 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { 3593 3594 if (isa<VarDecl>(SubME->getMemberDecl())) 3595 return; 3596 3597 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) 3598 if (!FD->isAnonymousStructOrUnion()) 3599 FieldME = SubME; 3600 3601 if (!FieldME->getType().isPODType(S.Context)) 3602 AllPODFields = false; 3603 3604 Base = SubME->getBase(); 3605 } 3606 3607 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) { 3608 Visit(Base); 3609 return; 3610 } 3611 3612 if (AddressOf && AllPODFields) 3613 return; 3614 3615 ValueDecl* FoundVD = FieldME->getMemberDecl(); 3616 3617 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { 3618 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { 3619 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); 3620 } 3621 3622 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { 3623 QualType T = BaseCast->getType(); 3624 if (T->isPointerType() && 3625 BaseClasses.count(T->getPointeeType())) { 3626 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) 3627 << T->getPointeeType() << FoundVD; 3628 } 3629 } 3630 } 3631 3632 if (!Decls.count(FoundVD)) 3633 return; 3634 3635 const bool IsReference = FoundVD->getType()->isReferenceType(); 3636 3637 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { 3638 // Special checking for initializer lists. 3639 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { 3640 return; 3641 } 3642 } else { 3643 // Prevent double warnings on use of unbounded references. 3644 if (CheckReferenceOnly && !IsReference) 3645 return; 3646 } 3647 3648 unsigned diag = IsReference 3649 ? diag::warn_reference_field_is_uninit 3650 : diag::warn_field_is_uninit; 3651 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 3652 if (Constructor) 3653 S.Diag(Constructor->getLocation(), 3654 diag::note_uninit_in_this_constructor) 3655 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 3656 3657 } 3658 3659 void HandleValue(Expr *E, bool AddressOf) { 3660 E = E->IgnoreParens(); 3661 3662 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3663 HandleMemberExpr(ME, false /*CheckReferenceOnly*/, 3664 AddressOf /*AddressOf*/); 3665 return; 3666 } 3667 3668 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 3669 Visit(CO->getCond()); 3670 HandleValue(CO->getTrueExpr(), AddressOf); 3671 HandleValue(CO->getFalseExpr(), AddressOf); 3672 return; 3673 } 3674 3675 if (BinaryConditionalOperator *BCO = 3676 dyn_cast<BinaryConditionalOperator>(E)) { 3677 Visit(BCO->getCond()); 3678 HandleValue(BCO->getFalseExpr(), AddressOf); 3679 return; 3680 } 3681 3682 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 3683 HandleValue(OVE->getSourceExpr(), AddressOf); 3684 return; 3685 } 3686 3687 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 3688 switch (BO->getOpcode()) { 3689 default: 3690 break; 3691 case(BO_PtrMemD): 3692 case(BO_PtrMemI): 3693 HandleValue(BO->getLHS(), AddressOf); 3694 Visit(BO->getRHS()); 3695 return; 3696 case(BO_Comma): 3697 Visit(BO->getLHS()); 3698 HandleValue(BO->getRHS(), AddressOf); 3699 return; 3700 } 3701 } 3702 3703 Visit(E); 3704 } 3705 3706 void CheckInitListExpr(InitListExpr *ILE) { 3707 InitFieldIndex.push_back(0); 3708 for (auto Child : ILE->children()) { 3709 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { 3710 CheckInitListExpr(SubList); 3711 } else { 3712 Visit(Child); 3713 } 3714 ++InitFieldIndex.back(); 3715 } 3716 InitFieldIndex.pop_back(); 3717 } 3718 3719 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, 3720 FieldDecl *Field, const Type *BaseClass) { 3721 // Remove Decls that may have been initialized in the previous 3722 // initializer. 3723 for (ValueDecl* VD : DeclsToRemove) 3724 Decls.erase(VD); 3725 DeclsToRemove.clear(); 3726 3727 Constructor = FieldConstructor; 3728 InitListExpr *ILE = dyn_cast<InitListExpr>(E); 3729 3730 if (ILE && Field) { 3731 InitList = true; 3732 InitListFieldDecl = Field; 3733 InitFieldIndex.clear(); 3734 CheckInitListExpr(ILE); 3735 } else { 3736 InitList = false; 3737 Visit(E); 3738 } 3739 3740 if (Field) 3741 Decls.erase(Field); 3742 if (BaseClass) 3743 BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); 3744 } 3745 3746 void VisitMemberExpr(MemberExpr *ME) { 3747 // All uses of unbounded reference fields will warn. 3748 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); 3749 } 3750 3751 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 3752 if (E->getCastKind() == CK_LValueToRValue) { 3753 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3754 return; 3755 } 3756 3757 Inherited::VisitImplicitCastExpr(E); 3758 } 3759 3760 void VisitCXXConstructExpr(CXXConstructExpr *E) { 3761 if (E->getConstructor()->isCopyConstructor()) { 3762 Expr *ArgExpr = E->getArg(0); 3763 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 3764 if (ILE->getNumInits() == 1) 3765 ArgExpr = ILE->getInit(0); 3766 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 3767 if (ICE->getCastKind() == CK_NoOp) 3768 ArgExpr = ICE->getSubExpr(); 3769 HandleValue(ArgExpr, false /*AddressOf*/); 3770 return; 3771 } 3772 Inherited::VisitCXXConstructExpr(E); 3773 } 3774 3775 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 3776 Expr *Callee = E->getCallee(); 3777 if (isa<MemberExpr>(Callee)) { 3778 HandleValue(Callee, false /*AddressOf*/); 3779 for (auto Arg : E->arguments()) 3780 Visit(Arg); 3781 return; 3782 } 3783 3784 Inherited::VisitCXXMemberCallExpr(E); 3785 } 3786 3787 void VisitCallExpr(CallExpr *E) { 3788 // Treat std::move as a use. 3789 if (E->isCallToStdMove()) { 3790 HandleValue(E->getArg(0), /*AddressOf=*/false); 3791 return; 3792 } 3793 3794 Inherited::VisitCallExpr(E); 3795 } 3796 3797 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 3798 Expr *Callee = E->getCallee(); 3799 3800 if (isa<UnresolvedLookupExpr>(Callee)) 3801 return Inherited::VisitCXXOperatorCallExpr(E); 3802 3803 Visit(Callee); 3804 for (auto Arg : E->arguments()) 3805 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); 3806 } 3807 3808 void VisitBinaryOperator(BinaryOperator *E) { 3809 // If a field assignment is detected, remove the field from the 3810 // uninitiailized field set. 3811 if (E->getOpcode() == BO_Assign) 3812 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 3813 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 3814 if (!FD->getType()->isReferenceType()) 3815 DeclsToRemove.push_back(FD); 3816 3817 if (E->isCompoundAssignmentOp()) { 3818 HandleValue(E->getLHS(), false /*AddressOf*/); 3819 Visit(E->getRHS()); 3820 return; 3821 } 3822 3823 Inherited::VisitBinaryOperator(E); 3824 } 3825 3826 void VisitUnaryOperator(UnaryOperator *E) { 3827 if (E->isIncrementDecrementOp()) { 3828 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3829 return; 3830 } 3831 if (E->getOpcode() == UO_AddrOf) { 3832 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { 3833 HandleValue(ME->getBase(), true /*AddressOf*/); 3834 return; 3835 } 3836 } 3837 3838 Inherited::VisitUnaryOperator(E); 3839 } 3840 }; 3841 3842 // Diagnose value-uses of fields to initialize themselves, e.g. 3843 // foo(foo) 3844 // where foo is not also a parameter to the constructor. 3845 // Also diagnose across field uninitialized use such as 3846 // x(y), y(x) 3847 // TODO: implement -Wuninitialized and fold this into that framework. 3848 static void DiagnoseUninitializedFields( 3849 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 3850 3851 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 3852 Constructor->getLocation())) { 3853 return; 3854 } 3855 3856 if (Constructor->isInvalidDecl()) 3857 return; 3858 3859 const CXXRecordDecl *RD = Constructor->getParent(); 3860 3861 if (RD->isDependentContext()) 3862 return; 3863 3864 // Holds fields that are uninitialized. 3865 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 3866 3867 // At the beginning, all fields are uninitialized. 3868 for (auto *I : RD->decls()) { 3869 if (auto *FD = dyn_cast<FieldDecl>(I)) { 3870 UninitializedFields.insert(FD); 3871 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 3872 UninitializedFields.insert(IFD->getAnonField()); 3873 } 3874 } 3875 3876 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; 3877 for (auto I : RD->bases()) 3878 UninitializedBaseClasses.insert(I.getType().getCanonicalType()); 3879 3880 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3881 return; 3882 3883 UninitializedFieldVisitor UninitializedChecker(SemaRef, 3884 UninitializedFields, 3885 UninitializedBaseClasses); 3886 3887 for (const auto *FieldInit : Constructor->inits()) { 3888 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3889 break; 3890 3891 Expr *InitExpr = FieldInit->getInit(); 3892 if (!InitExpr) 3893 continue; 3894 3895 if (CXXDefaultInitExpr *Default = 3896 dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 3897 InitExpr = Default->getExpr(); 3898 if (!InitExpr) 3899 continue; 3900 // In class initializers will point to the constructor. 3901 UninitializedChecker.CheckInitializer(InitExpr, Constructor, 3902 FieldInit->getAnyMember(), 3903 FieldInit->getBaseClass()); 3904 } else { 3905 UninitializedChecker.CheckInitializer(InitExpr, nullptr, 3906 FieldInit->getAnyMember(), 3907 FieldInit->getBaseClass()); 3908 } 3909 } 3910 } 3911 } // namespace 3912 3913 /// Enter a new C++ default initializer scope. After calling this, the 3914 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 3915 /// parsing or instantiating the initializer failed. 3916 void Sema::ActOnStartCXXInClassMemberInitializer() { 3917 // Create a synthetic function scope to represent the call to the constructor 3918 // that notionally surrounds a use of this initializer. 3919 PushFunctionScope(); 3920 } 3921 3922 void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) { 3923 if (!D.isFunctionDeclarator()) 3924 return; 3925 auto &FTI = D.getFunctionTypeInfo(); 3926 if (!FTI.Params) 3927 return; 3928 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params, 3929 FTI.NumParams)) { 3930 auto *ParamDecl = cast<NamedDecl>(Param.Param); 3931 if (ParamDecl->getDeclName()) 3932 PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false); 3933 } 3934 } 3935 3936 ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) { 3937 return ActOnRequiresClause(ConstraintExpr); 3938 } 3939 3940 ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) { 3941 if (ConstraintExpr.isInvalid()) 3942 return ExprError(); 3943 3944 ConstraintExpr = CorrectDelayedTyposInExpr(ConstraintExpr); 3945 if (ConstraintExpr.isInvalid()) 3946 return ExprError(); 3947 3948 if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(), 3949 UPPC_RequiresClause)) 3950 return ExprError(); 3951 3952 return ConstraintExpr; 3953 } 3954 3955 /// This is invoked after parsing an in-class initializer for a 3956 /// non-static C++ class member, and after instantiating an in-class initializer 3957 /// in a class template. Such actions are deferred until the class is complete. 3958 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 3959 SourceLocation InitLoc, 3960 Expr *InitExpr) { 3961 // Pop the notional constructor scope we created earlier. 3962 PopFunctionScopeInfo(nullptr, D); 3963 3964 FieldDecl *FD = dyn_cast<FieldDecl>(D); 3965 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && 3966 "must set init style when field is created"); 3967 3968 if (!InitExpr) { 3969 D->setInvalidDecl(); 3970 if (FD) 3971 FD->removeInClassInitializer(); 3972 return; 3973 } 3974 3975 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 3976 FD->setInvalidDecl(); 3977 FD->removeInClassInitializer(); 3978 return; 3979 } 3980 3981 ExprResult Init = InitExpr; 3982 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 3983 InitializedEntity Entity = 3984 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD); 3985 InitializationKind Kind = 3986 FD->getInClassInitStyle() == ICIS_ListInit 3987 ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(), 3988 InitExpr->getBeginLoc(), 3989 InitExpr->getEndLoc()) 3990 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc); 3991 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 3992 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 3993 if (Init.isInvalid()) { 3994 FD->setInvalidDecl(); 3995 return; 3996 } 3997 } 3998 3999 // C++11 [class.base.init]p7: 4000 // The initialization of each base and member constitutes a 4001 // full-expression. 4002 Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false); 4003 if (Init.isInvalid()) { 4004 FD->setInvalidDecl(); 4005 return; 4006 } 4007 4008 InitExpr = Init.get(); 4009 4010 FD->setInClassInitializer(InitExpr); 4011 } 4012 4013 /// Find the direct and/or virtual base specifiers that 4014 /// correspond to the given base type, for use in base initialization 4015 /// within a constructor. 4016 static bool FindBaseInitializer(Sema &SemaRef, 4017 CXXRecordDecl *ClassDecl, 4018 QualType BaseType, 4019 const CXXBaseSpecifier *&DirectBaseSpec, 4020 const CXXBaseSpecifier *&VirtualBaseSpec) { 4021 // First, check for a direct base class. 4022 DirectBaseSpec = nullptr; 4023 for (const auto &Base : ClassDecl->bases()) { 4024 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 4025 // We found a direct base of this type. That's what we're 4026 // initializing. 4027 DirectBaseSpec = &Base; 4028 break; 4029 } 4030 } 4031 4032 // Check for a virtual base class. 4033 // FIXME: We might be able to short-circuit this if we know in advance that 4034 // there are no virtual bases. 4035 VirtualBaseSpec = nullptr; 4036 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 4037 // We haven't found a base yet; search the class hierarchy for a 4038 // virtual base class. 4039 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 4040 /*DetectVirtual=*/false); 4041 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(), 4042 SemaRef.Context.getTypeDeclType(ClassDecl), 4043 BaseType, Paths)) { 4044 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 4045 Path != Paths.end(); ++Path) { 4046 if (Path->back().Base->isVirtual()) { 4047 VirtualBaseSpec = Path->back().Base; 4048 break; 4049 } 4050 } 4051 } 4052 } 4053 4054 return DirectBaseSpec || VirtualBaseSpec; 4055 } 4056 4057 /// Handle a C++ member initializer using braced-init-list syntax. 4058 MemInitResult 4059 Sema::ActOnMemInitializer(Decl *ConstructorD, 4060 Scope *S, 4061 CXXScopeSpec &SS, 4062 IdentifierInfo *MemberOrBase, 4063 ParsedType TemplateTypeTy, 4064 const DeclSpec &DS, 4065 SourceLocation IdLoc, 4066 Expr *InitList, 4067 SourceLocation EllipsisLoc) { 4068 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 4069 DS, IdLoc, InitList, 4070 EllipsisLoc); 4071 } 4072 4073 /// Handle a C++ member initializer using parentheses syntax. 4074 MemInitResult 4075 Sema::ActOnMemInitializer(Decl *ConstructorD, 4076 Scope *S, 4077 CXXScopeSpec &SS, 4078 IdentifierInfo *MemberOrBase, 4079 ParsedType TemplateTypeTy, 4080 const DeclSpec &DS, 4081 SourceLocation IdLoc, 4082 SourceLocation LParenLoc, 4083 ArrayRef<Expr *> Args, 4084 SourceLocation RParenLoc, 4085 SourceLocation EllipsisLoc) { 4086 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc); 4087 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 4088 DS, IdLoc, List, EllipsisLoc); 4089 } 4090 4091 namespace { 4092 4093 // Callback to only accept typo corrections that can be a valid C++ member 4094 // intializer: either a non-static field member or a base class. 4095 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback { 4096 public: 4097 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 4098 : ClassDecl(ClassDecl) {} 4099 4100 bool ValidateCandidate(const TypoCorrection &candidate) override { 4101 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 4102 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 4103 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 4104 return isa<TypeDecl>(ND); 4105 } 4106 return false; 4107 } 4108 4109 std::unique_ptr<CorrectionCandidateCallback> clone() override { 4110 return std::make_unique<MemInitializerValidatorCCC>(*this); 4111 } 4112 4113 private: 4114 CXXRecordDecl *ClassDecl; 4115 }; 4116 4117 } 4118 4119 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, 4120 CXXScopeSpec &SS, 4121 ParsedType TemplateTypeTy, 4122 IdentifierInfo *MemberOrBase) { 4123 if (SS.getScopeRep() || TemplateTypeTy) 4124 return nullptr; 4125 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase); 4126 if (Result.empty()) 4127 return nullptr; 4128 ValueDecl *Member; 4129 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 4130 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) 4131 return Member; 4132 return nullptr; 4133 } 4134 4135 /// Handle a C++ member initializer. 4136 MemInitResult 4137 Sema::BuildMemInitializer(Decl *ConstructorD, 4138 Scope *S, 4139 CXXScopeSpec &SS, 4140 IdentifierInfo *MemberOrBase, 4141 ParsedType TemplateTypeTy, 4142 const DeclSpec &DS, 4143 SourceLocation IdLoc, 4144 Expr *Init, 4145 SourceLocation EllipsisLoc) { 4146 ExprResult Res = CorrectDelayedTyposInExpr(Init); 4147 if (!Res.isUsable()) 4148 return true; 4149 Init = Res.get(); 4150 4151 if (!ConstructorD) 4152 return true; 4153 4154 AdjustDeclIfTemplate(ConstructorD); 4155 4156 CXXConstructorDecl *Constructor 4157 = dyn_cast<CXXConstructorDecl>(ConstructorD); 4158 if (!Constructor) { 4159 // The user wrote a constructor initializer on a function that is 4160 // not a C++ constructor. Ignore the error for now, because we may 4161 // have more member initializers coming; we'll diagnose it just 4162 // once in ActOnMemInitializers. 4163 return true; 4164 } 4165 4166 CXXRecordDecl *ClassDecl = Constructor->getParent(); 4167 4168 // C++ [class.base.init]p2: 4169 // Names in a mem-initializer-id are looked up in the scope of the 4170 // constructor's class and, if not found in that scope, are looked 4171 // up in the scope containing the constructor's definition. 4172 // [Note: if the constructor's class contains a member with the 4173 // same name as a direct or virtual base class of the class, a 4174 // mem-initializer-id naming the member or base class and composed 4175 // of a single identifier refers to the class member. A 4176 // mem-initializer-id for the hidden base class may be specified 4177 // using a qualified name. ] 4178 4179 // Look for a member, first. 4180 if (ValueDecl *Member = tryLookupCtorInitMemberDecl( 4181 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) { 4182 if (EllipsisLoc.isValid()) 4183 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 4184 << MemberOrBase 4185 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 4186 4187 return BuildMemberInitializer(Member, Init, IdLoc); 4188 } 4189 // It didn't name a member, so see if it names a class. 4190 QualType BaseType; 4191 TypeSourceInfo *TInfo = nullptr; 4192 4193 if (TemplateTypeTy) { 4194 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 4195 if (BaseType.isNull()) 4196 return true; 4197 } else if (DS.getTypeSpecType() == TST_decltype) { 4198 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 4199 } else if (DS.getTypeSpecType() == TST_decltype_auto) { 4200 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); 4201 return true; 4202 } else { 4203 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 4204 LookupParsedName(R, S, &SS); 4205 4206 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 4207 if (!TyD) { 4208 if (R.isAmbiguous()) return true; 4209 4210 // We don't want access-control diagnostics here. 4211 R.suppressDiagnostics(); 4212 4213 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 4214 bool NotUnknownSpecialization = false; 4215 DeclContext *DC = computeDeclContext(SS, false); 4216 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 4217 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 4218 4219 if (!NotUnknownSpecialization) { 4220 // When the scope specifier can refer to a member of an unknown 4221 // specialization, we take it as a type name. 4222 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 4223 SS.getWithLocInContext(Context), 4224 *MemberOrBase, IdLoc); 4225 if (BaseType.isNull()) 4226 return true; 4227 4228 TInfo = Context.CreateTypeSourceInfo(BaseType); 4229 DependentNameTypeLoc TL = 4230 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>(); 4231 if (!TL.isNull()) { 4232 TL.setNameLoc(IdLoc); 4233 TL.setElaboratedKeywordLoc(SourceLocation()); 4234 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4235 } 4236 4237 R.clear(); 4238 R.setLookupName(MemberOrBase); 4239 } 4240 } 4241 4242 // If no results were found, try to correct typos. 4243 TypoCorrection Corr; 4244 MemInitializerValidatorCCC CCC(ClassDecl); 4245 if (R.empty() && BaseType.isNull() && 4246 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 4247 CCC, CTK_ErrorRecovery, ClassDecl))) { 4248 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 4249 // We have found a non-static data member with a similar 4250 // name to what was typed; complain and initialize that 4251 // member. 4252 diagnoseTypo(Corr, 4253 PDiag(diag::err_mem_init_not_member_or_class_suggest) 4254 << MemberOrBase << true); 4255 return BuildMemberInitializer(Member, Init, IdLoc); 4256 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 4257 const CXXBaseSpecifier *DirectBaseSpec; 4258 const CXXBaseSpecifier *VirtualBaseSpec; 4259 if (FindBaseInitializer(*this, ClassDecl, 4260 Context.getTypeDeclType(Type), 4261 DirectBaseSpec, VirtualBaseSpec)) { 4262 // We have found a direct or virtual base class with a 4263 // similar name to what was typed; complain and initialize 4264 // that base class. 4265 diagnoseTypo(Corr, 4266 PDiag(diag::err_mem_init_not_member_or_class_suggest) 4267 << MemberOrBase << false, 4268 PDiag() /*Suppress note, we provide our own.*/); 4269 4270 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 4271 : VirtualBaseSpec; 4272 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here) 4273 << BaseSpec->getType() << BaseSpec->getSourceRange(); 4274 4275 TyD = Type; 4276 } 4277 } 4278 } 4279 4280 if (!TyD && BaseType.isNull()) { 4281 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 4282 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 4283 return true; 4284 } 4285 } 4286 4287 if (BaseType.isNull()) { 4288 BaseType = Context.getTypeDeclType(TyD); 4289 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); 4290 if (SS.isSet()) { 4291 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 4292 BaseType); 4293 TInfo = Context.CreateTypeSourceInfo(BaseType); 4294 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>(); 4295 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc); 4296 TL.setElaboratedKeywordLoc(SourceLocation()); 4297 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4298 } 4299 } 4300 } 4301 4302 if (!TInfo) 4303 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 4304 4305 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 4306 } 4307 4308 MemInitResult 4309 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 4310 SourceLocation IdLoc) { 4311 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 4312 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 4313 assert((DirectMember || IndirectMember) && 4314 "Member must be a FieldDecl or IndirectFieldDecl"); 4315 4316 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4317 return true; 4318 4319 if (Member->isInvalidDecl()) 4320 return true; 4321 4322 MultiExprArg Args; 4323 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4324 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4325 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 4326 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 4327 } else { 4328 // Template instantiation doesn't reconstruct ParenListExprs for us. 4329 Args = Init; 4330 } 4331 4332 SourceRange InitRange = Init->getSourceRange(); 4333 4334 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 4335 // Can't check initialization for a member of dependent type or when 4336 // any of the arguments are type-dependent expressions. 4337 DiscardCleanupsInEvaluationContext(); 4338 } else { 4339 bool InitList = false; 4340 if (isa<InitListExpr>(Init)) { 4341 InitList = true; 4342 Args = Init; 4343 } 4344 4345 // Initialize the member. 4346 InitializedEntity MemberEntity = 4347 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 4348 : InitializedEntity::InitializeMember(IndirectMember, 4349 nullptr); 4350 InitializationKind Kind = 4351 InitList ? InitializationKind::CreateDirectList( 4352 IdLoc, Init->getBeginLoc(), Init->getEndLoc()) 4353 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 4354 InitRange.getEnd()); 4355 4356 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 4357 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 4358 nullptr); 4359 if (MemberInit.isInvalid()) 4360 return true; 4361 4362 // C++11 [class.base.init]p7: 4363 // The initialization of each base and member constitutes a 4364 // full-expression. 4365 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(), 4366 /*DiscardedValue*/ false); 4367 if (MemberInit.isInvalid()) 4368 return true; 4369 4370 Init = MemberInit.get(); 4371 } 4372 4373 if (DirectMember) { 4374 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 4375 InitRange.getBegin(), Init, 4376 InitRange.getEnd()); 4377 } else { 4378 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 4379 InitRange.getBegin(), Init, 4380 InitRange.getEnd()); 4381 } 4382 } 4383 4384 MemInitResult 4385 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 4386 CXXRecordDecl *ClassDecl) { 4387 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4388 if (!LangOpts.CPlusPlus11) 4389 return Diag(NameLoc, diag::err_delegating_ctor) 4390 << TInfo->getTypeLoc().getLocalSourceRange(); 4391 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 4392 4393 bool InitList = true; 4394 MultiExprArg Args = Init; 4395 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4396 InitList = false; 4397 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4398 } 4399 4400 SourceRange InitRange = Init->getSourceRange(); 4401 // Initialize the object. 4402 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 4403 QualType(ClassDecl->getTypeForDecl(), 0)); 4404 InitializationKind Kind = 4405 InitList ? InitializationKind::CreateDirectList( 4406 NameLoc, Init->getBeginLoc(), Init->getEndLoc()) 4407 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 4408 InitRange.getEnd()); 4409 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 4410 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 4411 Args, nullptr); 4412 if (DelegationInit.isInvalid()) 4413 return true; 4414 4415 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 4416 "Delegating constructor with no target?"); 4417 4418 // C++11 [class.base.init]p7: 4419 // The initialization of each base and member constitutes a 4420 // full-expression. 4421 DelegationInit = ActOnFinishFullExpr( 4422 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false); 4423 if (DelegationInit.isInvalid()) 4424 return true; 4425 4426 // If we are in a dependent context, template instantiation will 4427 // perform this type-checking again. Just save the arguments that we 4428 // received in a ParenListExpr. 4429 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4430 // of the information that we have about the base 4431 // initializer. However, deconstructing the ASTs is a dicey process, 4432 // and this approach is far more likely to get the corner cases right. 4433 if (CurContext->isDependentContext()) 4434 DelegationInit = Init; 4435 4436 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 4437 DelegationInit.getAs<Expr>(), 4438 InitRange.getEnd()); 4439 } 4440 4441 MemInitResult 4442 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 4443 Expr *Init, CXXRecordDecl *ClassDecl, 4444 SourceLocation EllipsisLoc) { 4445 SourceLocation BaseLoc 4446 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4447 4448 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 4449 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 4450 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4451 4452 // C++ [class.base.init]p2: 4453 // [...] Unless the mem-initializer-id names a nonstatic data 4454 // member of the constructor's class or a direct or virtual base 4455 // of that class, the mem-initializer is ill-formed. A 4456 // mem-initializer-list can initialize a base class using any 4457 // name that denotes that base class type. 4458 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 4459 4460 SourceRange InitRange = Init->getSourceRange(); 4461 if (EllipsisLoc.isValid()) { 4462 // This is a pack expansion. 4463 if (!BaseType->containsUnexpandedParameterPack()) { 4464 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 4465 << SourceRange(BaseLoc, InitRange.getEnd()); 4466 4467 EllipsisLoc = SourceLocation(); 4468 } 4469 } else { 4470 // Check for any unexpanded parameter packs. 4471 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 4472 return true; 4473 4474 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4475 return true; 4476 } 4477 4478 // Check for direct and virtual base classes. 4479 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 4480 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 4481 if (!Dependent) { 4482 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 4483 BaseType)) 4484 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 4485 4486 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 4487 VirtualBaseSpec); 4488 4489 // C++ [base.class.init]p2: 4490 // Unless the mem-initializer-id names a nonstatic data member of the 4491 // constructor's class or a direct or virtual base of that class, the 4492 // mem-initializer is ill-formed. 4493 if (!DirectBaseSpec && !VirtualBaseSpec) { 4494 // If the class has any dependent bases, then it's possible that 4495 // one of those types will resolve to the same type as 4496 // BaseType. Therefore, just treat this as a dependent base 4497 // class initialization. FIXME: Should we try to check the 4498 // initialization anyway? It seems odd. 4499 if (ClassDecl->hasAnyDependentBases()) 4500 Dependent = true; 4501 else 4502 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 4503 << BaseType << Context.getTypeDeclType(ClassDecl) 4504 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4505 } 4506 } 4507 4508 if (Dependent) { 4509 DiscardCleanupsInEvaluationContext(); 4510 4511 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4512 /*IsVirtual=*/false, 4513 InitRange.getBegin(), Init, 4514 InitRange.getEnd(), EllipsisLoc); 4515 } 4516 4517 // C++ [base.class.init]p2: 4518 // If a mem-initializer-id is ambiguous because it designates both 4519 // a direct non-virtual base class and an inherited virtual base 4520 // class, the mem-initializer is ill-formed. 4521 if (DirectBaseSpec && VirtualBaseSpec) 4522 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 4523 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4524 4525 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 4526 if (!BaseSpec) 4527 BaseSpec = VirtualBaseSpec; 4528 4529 // Initialize the base. 4530 bool InitList = true; 4531 MultiExprArg Args = Init; 4532 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4533 InitList = false; 4534 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4535 } 4536 4537 InitializedEntity BaseEntity = 4538 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 4539 InitializationKind Kind = 4540 InitList ? InitializationKind::CreateDirectList(BaseLoc) 4541 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 4542 InitRange.getEnd()); 4543 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 4544 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 4545 if (BaseInit.isInvalid()) 4546 return true; 4547 4548 // C++11 [class.base.init]p7: 4549 // The initialization of each base and member constitutes a 4550 // full-expression. 4551 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(), 4552 /*DiscardedValue*/ false); 4553 if (BaseInit.isInvalid()) 4554 return true; 4555 4556 // If we are in a dependent context, template instantiation will 4557 // perform this type-checking again. Just save the arguments that we 4558 // received in a ParenListExpr. 4559 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4560 // of the information that we have about the base 4561 // initializer. However, deconstructing the ASTs is a dicey process, 4562 // and this approach is far more likely to get the corner cases right. 4563 if (CurContext->isDependentContext()) 4564 BaseInit = Init; 4565 4566 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4567 BaseSpec->isVirtual(), 4568 InitRange.getBegin(), 4569 BaseInit.getAs<Expr>(), 4570 InitRange.getEnd(), EllipsisLoc); 4571 } 4572 4573 // Create a static_cast\<T&&>(expr). 4574 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 4575 if (T.isNull()) T = E->getType(); 4576 QualType TargetType = SemaRef.BuildReferenceType( 4577 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 4578 SourceLocation ExprLoc = E->getBeginLoc(); 4579 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 4580 TargetType, ExprLoc); 4581 4582 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 4583 SourceRange(ExprLoc, ExprLoc), 4584 E->getSourceRange()).get(); 4585 } 4586 4587 /// ImplicitInitializerKind - How an implicit base or member initializer should 4588 /// initialize its base or member. 4589 enum ImplicitInitializerKind { 4590 IIK_Default, 4591 IIK_Copy, 4592 IIK_Move, 4593 IIK_Inherit 4594 }; 4595 4596 static bool 4597 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4598 ImplicitInitializerKind ImplicitInitKind, 4599 CXXBaseSpecifier *BaseSpec, 4600 bool IsInheritedVirtualBase, 4601 CXXCtorInitializer *&CXXBaseInit) { 4602 InitializedEntity InitEntity 4603 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 4604 IsInheritedVirtualBase); 4605 4606 ExprResult BaseInit; 4607 4608 switch (ImplicitInitKind) { 4609 case IIK_Inherit: 4610 case IIK_Default: { 4611 InitializationKind InitKind 4612 = InitializationKind::CreateDefault(Constructor->getLocation()); 4613 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4614 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4615 break; 4616 } 4617 4618 case IIK_Move: 4619 case IIK_Copy: { 4620 bool Moving = ImplicitInitKind == IIK_Move; 4621 ParmVarDecl *Param = Constructor->getParamDecl(0); 4622 QualType ParamType = Param->getType().getNonReferenceType(); 4623 4624 Expr *CopyCtorArg = 4625 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4626 SourceLocation(), Param, false, 4627 Constructor->getLocation(), ParamType, 4628 VK_LValue, nullptr); 4629 4630 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 4631 4632 // Cast to the base class to avoid ambiguities. 4633 QualType ArgTy = 4634 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 4635 ParamType.getQualifiers()); 4636 4637 if (Moving) { 4638 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 4639 } 4640 4641 CXXCastPath BasePath; 4642 BasePath.push_back(BaseSpec); 4643 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 4644 CK_UncheckedDerivedToBase, 4645 Moving ? VK_XValue : VK_LValue, 4646 &BasePath).get(); 4647 4648 InitializationKind InitKind 4649 = InitializationKind::CreateDirect(Constructor->getLocation(), 4650 SourceLocation(), SourceLocation()); 4651 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 4652 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 4653 break; 4654 } 4655 } 4656 4657 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 4658 if (BaseInit.isInvalid()) 4659 return true; 4660 4661 CXXBaseInit = 4662 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4663 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 4664 SourceLocation()), 4665 BaseSpec->isVirtual(), 4666 SourceLocation(), 4667 BaseInit.getAs<Expr>(), 4668 SourceLocation(), 4669 SourceLocation()); 4670 4671 return false; 4672 } 4673 4674 static bool RefersToRValueRef(Expr *MemRef) { 4675 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 4676 return Referenced->getType()->isRValueReferenceType(); 4677 } 4678 4679 static bool 4680 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4681 ImplicitInitializerKind ImplicitInitKind, 4682 FieldDecl *Field, IndirectFieldDecl *Indirect, 4683 CXXCtorInitializer *&CXXMemberInit) { 4684 if (Field->isInvalidDecl()) 4685 return true; 4686 4687 SourceLocation Loc = Constructor->getLocation(); 4688 4689 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 4690 bool Moving = ImplicitInitKind == IIK_Move; 4691 ParmVarDecl *Param = Constructor->getParamDecl(0); 4692 QualType ParamType = Param->getType().getNonReferenceType(); 4693 4694 // Suppress copying zero-width bitfields. 4695 if (Field->isZeroLengthBitField(SemaRef.Context)) 4696 return false; 4697 4698 Expr *MemberExprBase = 4699 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4700 SourceLocation(), Param, false, 4701 Loc, ParamType, VK_LValue, nullptr); 4702 4703 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 4704 4705 if (Moving) { 4706 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 4707 } 4708 4709 // Build a reference to this field within the parameter. 4710 CXXScopeSpec SS; 4711 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 4712 Sema::LookupMemberName); 4713 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 4714 : cast<ValueDecl>(Field), AS_public); 4715 MemberLookup.resolveKind(); 4716 ExprResult CtorArg 4717 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 4718 ParamType, Loc, 4719 /*IsArrow=*/false, 4720 SS, 4721 /*TemplateKWLoc=*/SourceLocation(), 4722 /*FirstQualifierInScope=*/nullptr, 4723 MemberLookup, 4724 /*TemplateArgs=*/nullptr, 4725 /*S*/nullptr); 4726 if (CtorArg.isInvalid()) 4727 return true; 4728 4729 // C++11 [class.copy]p15: 4730 // - if a member m has rvalue reference type T&&, it is direct-initialized 4731 // with static_cast<T&&>(x.m); 4732 if (RefersToRValueRef(CtorArg.get())) { 4733 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 4734 } 4735 4736 InitializedEntity Entity = 4737 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4738 /*Implicit*/ true) 4739 : InitializedEntity::InitializeMember(Field, nullptr, 4740 /*Implicit*/ true); 4741 4742 // Direct-initialize to use the copy constructor. 4743 InitializationKind InitKind = 4744 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 4745 4746 Expr *CtorArgE = CtorArg.getAs<Expr>(); 4747 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE); 4748 ExprResult MemberInit = 4749 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1)); 4750 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4751 if (MemberInit.isInvalid()) 4752 return true; 4753 4754 if (Indirect) 4755 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4756 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4757 else 4758 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4759 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4760 return false; 4761 } 4762 4763 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 4764 "Unhandled implicit init kind!"); 4765 4766 QualType FieldBaseElementType = 4767 SemaRef.Context.getBaseElementType(Field->getType()); 4768 4769 if (FieldBaseElementType->isRecordType()) { 4770 InitializedEntity InitEntity = 4771 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4772 /*Implicit*/ true) 4773 : InitializedEntity::InitializeMember(Field, nullptr, 4774 /*Implicit*/ true); 4775 InitializationKind InitKind = 4776 InitializationKind::CreateDefault(Loc); 4777 4778 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4779 ExprResult MemberInit = 4780 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4781 4782 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4783 if (MemberInit.isInvalid()) 4784 return true; 4785 4786 if (Indirect) 4787 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4788 Indirect, Loc, 4789 Loc, 4790 MemberInit.get(), 4791 Loc); 4792 else 4793 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4794 Field, Loc, Loc, 4795 MemberInit.get(), 4796 Loc); 4797 return false; 4798 } 4799 4800 if (!Field->getParent()->isUnion()) { 4801 if (FieldBaseElementType->isReferenceType()) { 4802 SemaRef.Diag(Constructor->getLocation(), 4803 diag::err_uninitialized_member_in_ctor) 4804 << (int)Constructor->isImplicit() 4805 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4806 << 0 << Field->getDeclName(); 4807 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4808 return true; 4809 } 4810 4811 if (FieldBaseElementType.isConstQualified()) { 4812 SemaRef.Diag(Constructor->getLocation(), 4813 diag::err_uninitialized_member_in_ctor) 4814 << (int)Constructor->isImplicit() 4815 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4816 << 1 << Field->getDeclName(); 4817 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4818 return true; 4819 } 4820 } 4821 4822 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) { 4823 // ARC and Weak: 4824 // Default-initialize Objective-C pointers to NULL. 4825 CXXMemberInit 4826 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 4827 Loc, Loc, 4828 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 4829 Loc); 4830 return false; 4831 } 4832 4833 // Nothing to initialize. 4834 CXXMemberInit = nullptr; 4835 return false; 4836 } 4837 4838 namespace { 4839 struct BaseAndFieldInfo { 4840 Sema &S; 4841 CXXConstructorDecl *Ctor; 4842 bool AnyErrorsInInits; 4843 ImplicitInitializerKind IIK; 4844 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 4845 SmallVector<CXXCtorInitializer*, 8> AllToInit; 4846 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 4847 4848 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 4849 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 4850 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 4851 if (Ctor->getInheritedConstructor()) 4852 IIK = IIK_Inherit; 4853 else if (Generated && Ctor->isCopyConstructor()) 4854 IIK = IIK_Copy; 4855 else if (Generated && Ctor->isMoveConstructor()) 4856 IIK = IIK_Move; 4857 else 4858 IIK = IIK_Default; 4859 } 4860 4861 bool isImplicitCopyOrMove() const { 4862 switch (IIK) { 4863 case IIK_Copy: 4864 case IIK_Move: 4865 return true; 4866 4867 case IIK_Default: 4868 case IIK_Inherit: 4869 return false; 4870 } 4871 4872 llvm_unreachable("Invalid ImplicitInitializerKind!"); 4873 } 4874 4875 bool addFieldInitializer(CXXCtorInitializer *Init) { 4876 AllToInit.push_back(Init); 4877 4878 // Check whether this initializer makes the field "used". 4879 if (Init->getInit()->HasSideEffects(S.Context)) 4880 S.UnusedPrivateFields.remove(Init->getAnyMember()); 4881 4882 return false; 4883 } 4884 4885 bool isInactiveUnionMember(FieldDecl *Field) { 4886 RecordDecl *Record = Field->getParent(); 4887 if (!Record->isUnion()) 4888 return false; 4889 4890 if (FieldDecl *Active = 4891 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 4892 return Active != Field->getCanonicalDecl(); 4893 4894 // In an implicit copy or move constructor, ignore any in-class initializer. 4895 if (isImplicitCopyOrMove()) 4896 return true; 4897 4898 // If there's no explicit initialization, the field is active only if it 4899 // has an in-class initializer... 4900 if (Field->hasInClassInitializer()) 4901 return false; 4902 // ... or it's an anonymous struct or union whose class has an in-class 4903 // initializer. 4904 if (!Field->isAnonymousStructOrUnion()) 4905 return true; 4906 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 4907 return !FieldRD->hasInClassInitializer(); 4908 } 4909 4910 /// Determine whether the given field is, or is within, a union member 4911 /// that is inactive (because there was an initializer given for a different 4912 /// member of the union, or because the union was not initialized at all). 4913 bool isWithinInactiveUnionMember(FieldDecl *Field, 4914 IndirectFieldDecl *Indirect) { 4915 if (!Indirect) 4916 return isInactiveUnionMember(Field); 4917 4918 for (auto *C : Indirect->chain()) { 4919 FieldDecl *Field = dyn_cast<FieldDecl>(C); 4920 if (Field && isInactiveUnionMember(Field)) 4921 return true; 4922 } 4923 return false; 4924 } 4925 }; 4926 } 4927 4928 /// Determine whether the given type is an incomplete or zero-lenfgth 4929 /// array type. 4930 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 4931 if (T->isIncompleteArrayType()) 4932 return true; 4933 4934 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 4935 if (!ArrayT->getSize()) 4936 return true; 4937 4938 T = ArrayT->getElementType(); 4939 } 4940 4941 return false; 4942 } 4943 4944 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 4945 FieldDecl *Field, 4946 IndirectFieldDecl *Indirect = nullptr) { 4947 if (Field->isInvalidDecl()) 4948 return false; 4949 4950 // Overwhelmingly common case: we have a direct initializer for this field. 4951 if (CXXCtorInitializer *Init = 4952 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 4953 return Info.addFieldInitializer(Init); 4954 4955 // C++11 [class.base.init]p8: 4956 // if the entity is a non-static data member that has a 4957 // brace-or-equal-initializer and either 4958 // -- the constructor's class is a union and no other variant member of that 4959 // union is designated by a mem-initializer-id or 4960 // -- the constructor's class is not a union, and, if the entity is a member 4961 // of an anonymous union, no other member of that union is designated by 4962 // a mem-initializer-id, 4963 // the entity is initialized as specified in [dcl.init]. 4964 // 4965 // We also apply the same rules to handle anonymous structs within anonymous 4966 // unions. 4967 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 4968 return false; 4969 4970 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 4971 ExprResult DIE = 4972 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); 4973 if (DIE.isInvalid()) 4974 return true; 4975 4976 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true); 4977 SemaRef.checkInitializerLifetime(Entity, DIE.get()); 4978 4979 CXXCtorInitializer *Init; 4980 if (Indirect) 4981 Init = new (SemaRef.Context) 4982 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), 4983 SourceLocation(), DIE.get(), SourceLocation()); 4984 else 4985 Init = new (SemaRef.Context) 4986 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), 4987 SourceLocation(), DIE.get(), SourceLocation()); 4988 return Info.addFieldInitializer(Init); 4989 } 4990 4991 // Don't initialize incomplete or zero-length arrays. 4992 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 4993 return false; 4994 4995 // Don't try to build an implicit initializer if there were semantic 4996 // errors in any of the initializers (and therefore we might be 4997 // missing some that the user actually wrote). 4998 if (Info.AnyErrorsInInits) 4999 return false; 5000 5001 CXXCtorInitializer *Init = nullptr; 5002 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 5003 Indirect, Init)) 5004 return true; 5005 5006 if (!Init) 5007 return false; 5008 5009 return Info.addFieldInitializer(Init); 5010 } 5011 5012 bool 5013 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 5014 CXXCtorInitializer *Initializer) { 5015 assert(Initializer->isDelegatingInitializer()); 5016 Constructor->setNumCtorInitializers(1); 5017 CXXCtorInitializer **initializer = 5018 new (Context) CXXCtorInitializer*[1]; 5019 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 5020 Constructor->setCtorInitializers(initializer); 5021 5022 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 5023 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 5024 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 5025 } 5026 5027 DelegatingCtorDecls.push_back(Constructor); 5028 5029 DiagnoseUninitializedFields(*this, Constructor); 5030 5031 return false; 5032 } 5033 5034 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 5035 ArrayRef<CXXCtorInitializer *> Initializers) { 5036 if (Constructor->isDependentContext()) { 5037 // Just store the initializers as written, they will be checked during 5038 // instantiation. 5039 if (!Initializers.empty()) { 5040 Constructor->setNumCtorInitializers(Initializers.size()); 5041 CXXCtorInitializer **baseOrMemberInitializers = 5042 new (Context) CXXCtorInitializer*[Initializers.size()]; 5043 memcpy(baseOrMemberInitializers, Initializers.data(), 5044 Initializers.size() * sizeof(CXXCtorInitializer*)); 5045 Constructor->setCtorInitializers(baseOrMemberInitializers); 5046 } 5047 5048 // Let template instantiation know whether we had errors. 5049 if (AnyErrors) 5050 Constructor->setInvalidDecl(); 5051 5052 return false; 5053 } 5054 5055 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 5056 5057 // We need to build the initializer AST according to order of construction 5058 // and not what user specified in the Initializers list. 5059 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 5060 if (!ClassDecl) 5061 return true; 5062 5063 bool HadError = false; 5064 5065 for (unsigned i = 0; i < Initializers.size(); i++) { 5066 CXXCtorInitializer *Member = Initializers[i]; 5067 5068 if (Member->isBaseInitializer()) 5069 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 5070 else { 5071 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 5072 5073 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 5074 for (auto *C : F->chain()) { 5075 FieldDecl *FD = dyn_cast<FieldDecl>(C); 5076 if (FD && FD->getParent()->isUnion()) 5077 Info.ActiveUnionMember.insert(std::make_pair( 5078 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 5079 } 5080 } else if (FieldDecl *FD = Member->getMember()) { 5081 if (FD->getParent()->isUnion()) 5082 Info.ActiveUnionMember.insert(std::make_pair( 5083 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 5084 } 5085 } 5086 } 5087 5088 // Keep track of the direct virtual bases. 5089 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 5090 for (auto &I : ClassDecl->bases()) { 5091 if (I.isVirtual()) 5092 DirectVBases.insert(&I); 5093 } 5094 5095 // Push virtual bases before others. 5096 for (auto &VBase : ClassDecl->vbases()) { 5097 if (CXXCtorInitializer *Value 5098 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 5099 // [class.base.init]p7, per DR257: 5100 // A mem-initializer where the mem-initializer-id names a virtual base 5101 // class is ignored during execution of a constructor of any class that 5102 // is not the most derived class. 5103 if (ClassDecl->isAbstract()) { 5104 // FIXME: Provide a fixit to remove the base specifier. This requires 5105 // tracking the location of the associated comma for a base specifier. 5106 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 5107 << VBase.getType() << ClassDecl; 5108 DiagnoseAbstractType(ClassDecl); 5109 } 5110 5111 Info.AllToInit.push_back(Value); 5112 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 5113 // [class.base.init]p8, per DR257: 5114 // If a given [...] base class is not named by a mem-initializer-id 5115 // [...] and the entity is not a virtual base class of an abstract 5116 // class, then [...] the entity is default-initialized. 5117 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 5118 CXXCtorInitializer *CXXBaseInit; 5119 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 5120 &VBase, IsInheritedVirtualBase, 5121 CXXBaseInit)) { 5122 HadError = true; 5123 continue; 5124 } 5125 5126 Info.AllToInit.push_back(CXXBaseInit); 5127 } 5128 } 5129 5130 // Non-virtual bases. 5131 for (auto &Base : ClassDecl->bases()) { 5132 // Virtuals are in the virtual base list and already constructed. 5133 if (Base.isVirtual()) 5134 continue; 5135 5136 if (CXXCtorInitializer *Value 5137 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 5138 Info.AllToInit.push_back(Value); 5139 } else if (!AnyErrors) { 5140 CXXCtorInitializer *CXXBaseInit; 5141 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 5142 &Base, /*IsInheritedVirtualBase=*/false, 5143 CXXBaseInit)) { 5144 HadError = true; 5145 continue; 5146 } 5147 5148 Info.AllToInit.push_back(CXXBaseInit); 5149 } 5150 } 5151 5152 // Fields. 5153 for (auto *Mem : ClassDecl->decls()) { 5154 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 5155 // C++ [class.bit]p2: 5156 // A declaration for a bit-field that omits the identifier declares an 5157 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 5158 // initialized. 5159 if (F->isUnnamedBitfield()) 5160 continue; 5161 5162 // If we're not generating the implicit copy/move constructor, then we'll 5163 // handle anonymous struct/union fields based on their individual 5164 // indirect fields. 5165 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 5166 continue; 5167 5168 if (CollectFieldInitializer(*this, Info, F)) 5169 HadError = true; 5170 continue; 5171 } 5172 5173 // Beyond this point, we only consider default initialization. 5174 if (Info.isImplicitCopyOrMove()) 5175 continue; 5176 5177 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 5178 if (F->getType()->isIncompleteArrayType()) { 5179 assert(ClassDecl->hasFlexibleArrayMember() && 5180 "Incomplete array type is not valid"); 5181 continue; 5182 } 5183 5184 // Initialize each field of an anonymous struct individually. 5185 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 5186 HadError = true; 5187 5188 continue; 5189 } 5190 } 5191 5192 unsigned NumInitializers = Info.AllToInit.size(); 5193 if (NumInitializers > 0) { 5194 Constructor->setNumCtorInitializers(NumInitializers); 5195 CXXCtorInitializer **baseOrMemberInitializers = 5196 new (Context) CXXCtorInitializer*[NumInitializers]; 5197 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 5198 NumInitializers * sizeof(CXXCtorInitializer*)); 5199 Constructor->setCtorInitializers(baseOrMemberInitializers); 5200 5201 // Constructors implicitly reference the base and member 5202 // destructors. 5203 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 5204 Constructor->getParent()); 5205 } 5206 5207 return HadError; 5208 } 5209 5210 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 5211 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 5212 const RecordDecl *RD = RT->getDecl(); 5213 if (RD->isAnonymousStructOrUnion()) { 5214 for (auto *Field : RD->fields()) 5215 PopulateKeysForFields(Field, IdealInits); 5216 return; 5217 } 5218 } 5219 IdealInits.push_back(Field->getCanonicalDecl()); 5220 } 5221 5222 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 5223 return Context.getCanonicalType(BaseType).getTypePtr(); 5224 } 5225 5226 static const void *GetKeyForMember(ASTContext &Context, 5227 CXXCtorInitializer *Member) { 5228 if (!Member->isAnyMemberInitializer()) 5229 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 5230 5231 return Member->getAnyMember()->getCanonicalDecl(); 5232 } 5233 5234 static void DiagnoseBaseOrMemInitializerOrder( 5235 Sema &SemaRef, const CXXConstructorDecl *Constructor, 5236 ArrayRef<CXXCtorInitializer *> Inits) { 5237 if (Constructor->getDeclContext()->isDependentContext()) 5238 return; 5239 5240 // Don't check initializers order unless the warning is enabled at the 5241 // location of at least one initializer. 5242 bool ShouldCheckOrder = false; 5243 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 5244 CXXCtorInitializer *Init = Inits[InitIndex]; 5245 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 5246 Init->getSourceLocation())) { 5247 ShouldCheckOrder = true; 5248 break; 5249 } 5250 } 5251 if (!ShouldCheckOrder) 5252 return; 5253 5254 // Build the list of bases and members in the order that they'll 5255 // actually be initialized. The explicit initializers should be in 5256 // this same order but may be missing things. 5257 SmallVector<const void*, 32> IdealInitKeys; 5258 5259 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 5260 5261 // 1. Virtual bases. 5262 for (const auto &VBase : ClassDecl->vbases()) 5263 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 5264 5265 // 2. Non-virtual bases. 5266 for (const auto &Base : ClassDecl->bases()) { 5267 if (Base.isVirtual()) 5268 continue; 5269 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 5270 } 5271 5272 // 3. Direct fields. 5273 for (auto *Field : ClassDecl->fields()) { 5274 if (Field->isUnnamedBitfield()) 5275 continue; 5276 5277 PopulateKeysForFields(Field, IdealInitKeys); 5278 } 5279 5280 unsigned NumIdealInits = IdealInitKeys.size(); 5281 unsigned IdealIndex = 0; 5282 5283 CXXCtorInitializer *PrevInit = nullptr; 5284 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 5285 CXXCtorInitializer *Init = Inits[InitIndex]; 5286 const void *InitKey = GetKeyForMember(SemaRef.Context, Init); 5287 5288 // Scan forward to try to find this initializer in the idealized 5289 // initializers list. 5290 for (; IdealIndex != NumIdealInits; ++IdealIndex) 5291 if (InitKey == IdealInitKeys[IdealIndex]) 5292 break; 5293 5294 // If we didn't find this initializer, it must be because we 5295 // scanned past it on a previous iteration. That can only 5296 // happen if we're out of order; emit a warning. 5297 if (IdealIndex == NumIdealInits && PrevInit) { 5298 Sema::SemaDiagnosticBuilder D = 5299 SemaRef.Diag(PrevInit->getSourceLocation(), 5300 diag::warn_initializer_out_of_order); 5301 5302 if (PrevInit->isAnyMemberInitializer()) 5303 D << 0 << PrevInit->getAnyMember()->getDeclName(); 5304 else 5305 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 5306 5307 if (Init->isAnyMemberInitializer()) 5308 D << 0 << Init->getAnyMember()->getDeclName(); 5309 else 5310 D << 1 << Init->getTypeSourceInfo()->getType(); 5311 5312 // Move back to the initializer's location in the ideal list. 5313 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 5314 if (InitKey == IdealInitKeys[IdealIndex]) 5315 break; 5316 5317 assert(IdealIndex < NumIdealInits && 5318 "initializer not found in initializer list"); 5319 } 5320 5321 PrevInit = Init; 5322 } 5323 } 5324 5325 namespace { 5326 bool CheckRedundantInit(Sema &S, 5327 CXXCtorInitializer *Init, 5328 CXXCtorInitializer *&PrevInit) { 5329 if (!PrevInit) { 5330 PrevInit = Init; 5331 return false; 5332 } 5333 5334 if (FieldDecl *Field = Init->getAnyMember()) 5335 S.Diag(Init->getSourceLocation(), 5336 diag::err_multiple_mem_initialization) 5337 << Field->getDeclName() 5338 << Init->getSourceRange(); 5339 else { 5340 const Type *BaseClass = Init->getBaseClass(); 5341 assert(BaseClass && "neither field nor base"); 5342 S.Diag(Init->getSourceLocation(), 5343 diag::err_multiple_base_initialization) 5344 << QualType(BaseClass, 0) 5345 << Init->getSourceRange(); 5346 } 5347 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 5348 << 0 << PrevInit->getSourceRange(); 5349 5350 return true; 5351 } 5352 5353 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 5354 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 5355 5356 bool CheckRedundantUnionInit(Sema &S, 5357 CXXCtorInitializer *Init, 5358 RedundantUnionMap &Unions) { 5359 FieldDecl *Field = Init->getAnyMember(); 5360 RecordDecl *Parent = Field->getParent(); 5361 NamedDecl *Child = Field; 5362 5363 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 5364 if (Parent->isUnion()) { 5365 UnionEntry &En = Unions[Parent]; 5366 if (En.first && En.first != Child) { 5367 S.Diag(Init->getSourceLocation(), 5368 diag::err_multiple_mem_union_initialization) 5369 << Field->getDeclName() 5370 << Init->getSourceRange(); 5371 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 5372 << 0 << En.second->getSourceRange(); 5373 return true; 5374 } 5375 if (!En.first) { 5376 En.first = Child; 5377 En.second = Init; 5378 } 5379 if (!Parent->isAnonymousStructOrUnion()) 5380 return false; 5381 } 5382 5383 Child = Parent; 5384 Parent = cast<RecordDecl>(Parent->getDeclContext()); 5385 } 5386 5387 return false; 5388 } 5389 } 5390 5391 /// ActOnMemInitializers - Handle the member initializers for a constructor. 5392 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 5393 SourceLocation ColonLoc, 5394 ArrayRef<CXXCtorInitializer*> MemInits, 5395 bool AnyErrors) { 5396 if (!ConstructorDecl) 5397 return; 5398 5399 AdjustDeclIfTemplate(ConstructorDecl); 5400 5401 CXXConstructorDecl *Constructor 5402 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 5403 5404 if (!Constructor) { 5405 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 5406 return; 5407 } 5408 5409 // Mapping for the duplicate initializers check. 5410 // For member initializers, this is keyed with a FieldDecl*. 5411 // For base initializers, this is keyed with a Type*. 5412 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 5413 5414 // Mapping for the inconsistent anonymous-union initializers check. 5415 RedundantUnionMap MemberUnions; 5416 5417 bool HadError = false; 5418 for (unsigned i = 0; i < MemInits.size(); i++) { 5419 CXXCtorInitializer *Init = MemInits[i]; 5420 5421 // Set the source order index. 5422 Init->setSourceOrder(i); 5423 5424 if (Init->isAnyMemberInitializer()) { 5425 const void *Key = GetKeyForMember(Context, Init); 5426 if (CheckRedundantInit(*this, Init, Members[Key]) || 5427 CheckRedundantUnionInit(*this, Init, MemberUnions)) 5428 HadError = true; 5429 } else if (Init->isBaseInitializer()) { 5430 const void *Key = GetKeyForMember(Context, Init); 5431 if (CheckRedundantInit(*this, Init, Members[Key])) 5432 HadError = true; 5433 } else { 5434 assert(Init->isDelegatingInitializer()); 5435 // This must be the only initializer 5436 if (MemInits.size() != 1) { 5437 Diag(Init->getSourceLocation(), 5438 diag::err_delegating_initializer_alone) 5439 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 5440 // We will treat this as being the only initializer. 5441 } 5442 SetDelegatingInitializer(Constructor, MemInits[i]); 5443 // Return immediately as the initializer is set. 5444 return; 5445 } 5446 } 5447 5448 if (HadError) 5449 return; 5450 5451 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 5452 5453 SetCtorInitializers(Constructor, AnyErrors, MemInits); 5454 5455 DiagnoseUninitializedFields(*this, Constructor); 5456 } 5457 5458 void 5459 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 5460 CXXRecordDecl *ClassDecl) { 5461 // Ignore dependent contexts. Also ignore unions, since their members never 5462 // have destructors implicitly called. 5463 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 5464 return; 5465 5466 // FIXME: all the access-control diagnostics are positioned on the 5467 // field/base declaration. That's probably good; that said, the 5468 // user might reasonably want to know why the destructor is being 5469 // emitted, and we currently don't say. 5470 5471 // Non-static data members. 5472 for (auto *Field : ClassDecl->fields()) { 5473 if (Field->isInvalidDecl()) 5474 continue; 5475 5476 // Don't destroy incomplete or zero-length arrays. 5477 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 5478 continue; 5479 5480 QualType FieldType = Context.getBaseElementType(Field->getType()); 5481 5482 const RecordType* RT = FieldType->getAs<RecordType>(); 5483 if (!RT) 5484 continue; 5485 5486 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5487 if (FieldClassDecl->isInvalidDecl()) 5488 continue; 5489 if (FieldClassDecl->hasIrrelevantDestructor()) 5490 continue; 5491 // The destructor for an implicit anonymous union member is never invoked. 5492 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 5493 continue; 5494 5495 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 5496 assert(Dtor && "No dtor found for FieldClassDecl!"); 5497 CheckDestructorAccess(Field->getLocation(), Dtor, 5498 PDiag(diag::err_access_dtor_field) 5499 << Field->getDeclName() 5500 << FieldType); 5501 5502 MarkFunctionReferenced(Location, Dtor); 5503 DiagnoseUseOfDecl(Dtor, Location); 5504 } 5505 5506 // We only potentially invoke the destructors of potentially constructed 5507 // subobjects. 5508 bool VisitVirtualBases = !ClassDecl->isAbstract(); 5509 5510 // If the destructor exists and has already been marked used in the MS ABI, 5511 // then virtual base destructors have already been checked and marked used. 5512 // Skip checking them again to avoid duplicate diagnostics. 5513 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 5514 CXXDestructorDecl *Dtor = ClassDecl->getDestructor(); 5515 if (Dtor && Dtor->isUsed()) 5516 VisitVirtualBases = false; 5517 } 5518 5519 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 5520 5521 // Bases. 5522 for (const auto &Base : ClassDecl->bases()) { 5523 const RecordType *RT = Base.getType()->getAs<RecordType>(); 5524 if (!RT) 5525 continue; 5526 5527 // Remember direct virtual bases. 5528 if (Base.isVirtual()) { 5529 if (!VisitVirtualBases) 5530 continue; 5531 DirectVirtualBases.insert(RT); 5532 } 5533 5534 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5535 // If our base class is invalid, we probably can't get its dtor anyway. 5536 if (BaseClassDecl->isInvalidDecl()) 5537 continue; 5538 if (BaseClassDecl->hasIrrelevantDestructor()) 5539 continue; 5540 5541 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5542 assert(Dtor && "No dtor found for BaseClassDecl!"); 5543 5544 // FIXME: caret should be on the start of the class name 5545 CheckDestructorAccess(Base.getBeginLoc(), Dtor, 5546 PDiag(diag::err_access_dtor_base) 5547 << Base.getType() << Base.getSourceRange(), 5548 Context.getTypeDeclType(ClassDecl)); 5549 5550 MarkFunctionReferenced(Location, Dtor); 5551 DiagnoseUseOfDecl(Dtor, Location); 5552 } 5553 5554 if (VisitVirtualBases) 5555 MarkVirtualBaseDestructorsReferenced(Location, ClassDecl, 5556 &DirectVirtualBases); 5557 } 5558 5559 void Sema::MarkVirtualBaseDestructorsReferenced( 5560 SourceLocation Location, CXXRecordDecl *ClassDecl, 5561 llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) { 5562 // Virtual bases. 5563 for (const auto &VBase : ClassDecl->vbases()) { 5564 // Bases are always records in a well-formed non-dependent class. 5565 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 5566 5567 // Ignore already visited direct virtual bases. 5568 if (DirectVirtualBases && DirectVirtualBases->count(RT)) 5569 continue; 5570 5571 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5572 // If our base class is invalid, we probably can't get its dtor anyway. 5573 if (BaseClassDecl->isInvalidDecl()) 5574 continue; 5575 if (BaseClassDecl->hasIrrelevantDestructor()) 5576 continue; 5577 5578 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5579 assert(Dtor && "No dtor found for BaseClassDecl!"); 5580 if (CheckDestructorAccess( 5581 ClassDecl->getLocation(), Dtor, 5582 PDiag(diag::err_access_dtor_vbase) 5583 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 5584 Context.getTypeDeclType(ClassDecl)) == 5585 AR_accessible) { 5586 CheckDerivedToBaseConversion( 5587 Context.getTypeDeclType(ClassDecl), VBase.getType(), 5588 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 5589 SourceRange(), DeclarationName(), nullptr); 5590 } 5591 5592 MarkFunctionReferenced(Location, Dtor); 5593 DiagnoseUseOfDecl(Dtor, Location); 5594 } 5595 } 5596 5597 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 5598 if (!CDtorDecl) 5599 return; 5600 5601 if (CXXConstructorDecl *Constructor 5602 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 5603 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 5604 DiagnoseUninitializedFields(*this, Constructor); 5605 } 5606 } 5607 5608 bool Sema::isAbstractType(SourceLocation Loc, QualType T) { 5609 if (!getLangOpts().CPlusPlus) 5610 return false; 5611 5612 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl(); 5613 if (!RD) 5614 return false; 5615 5616 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a 5617 // class template specialization here, but doing so breaks a lot of code. 5618 5619 // We can't answer whether something is abstract until it has a 5620 // definition. If it's currently being defined, we'll walk back 5621 // over all the declarations when we have a full definition. 5622 const CXXRecordDecl *Def = RD->getDefinition(); 5623 if (!Def || Def->isBeingDefined()) 5624 return false; 5625 5626 return RD->isAbstract(); 5627 } 5628 5629 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 5630 TypeDiagnoser &Diagnoser) { 5631 if (!isAbstractType(Loc, T)) 5632 return false; 5633 5634 T = Context.getBaseElementType(T); 5635 Diagnoser.diagnose(*this, Loc, T); 5636 DiagnoseAbstractType(T->getAsCXXRecordDecl()); 5637 return true; 5638 } 5639 5640 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 5641 // Check if we've already emitted the list of pure virtual functions 5642 // for this class. 5643 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 5644 return; 5645 5646 // If the diagnostic is suppressed, don't emit the notes. We're only 5647 // going to emit them once, so try to attach them to a diagnostic we're 5648 // actually going to show. 5649 if (Diags.isLastDiagnosticIgnored()) 5650 return; 5651 5652 CXXFinalOverriderMap FinalOverriders; 5653 RD->getFinalOverriders(FinalOverriders); 5654 5655 // Keep a set of seen pure methods so we won't diagnose the same method 5656 // more than once. 5657 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 5658 5659 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 5660 MEnd = FinalOverriders.end(); 5661 M != MEnd; 5662 ++M) { 5663 for (OverridingMethods::iterator SO = M->second.begin(), 5664 SOEnd = M->second.end(); 5665 SO != SOEnd; ++SO) { 5666 // C++ [class.abstract]p4: 5667 // A class is abstract if it contains or inherits at least one 5668 // pure virtual function for which the final overrider is pure 5669 // virtual. 5670 5671 // 5672 if (SO->second.size() != 1) 5673 continue; 5674 5675 if (!SO->second.front().Method->isPure()) 5676 continue; 5677 5678 if (!SeenPureMethods.insert(SO->second.front().Method).second) 5679 continue; 5680 5681 Diag(SO->second.front().Method->getLocation(), 5682 diag::note_pure_virtual_function) 5683 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 5684 } 5685 } 5686 5687 if (!PureVirtualClassDiagSet) 5688 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 5689 PureVirtualClassDiagSet->insert(RD); 5690 } 5691 5692 namespace { 5693 struct AbstractUsageInfo { 5694 Sema &S; 5695 CXXRecordDecl *Record; 5696 CanQualType AbstractType; 5697 bool Invalid; 5698 5699 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 5700 : S(S), Record(Record), 5701 AbstractType(S.Context.getCanonicalType( 5702 S.Context.getTypeDeclType(Record))), 5703 Invalid(false) {} 5704 5705 void DiagnoseAbstractType() { 5706 if (Invalid) return; 5707 S.DiagnoseAbstractType(Record); 5708 Invalid = true; 5709 } 5710 5711 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 5712 }; 5713 5714 struct CheckAbstractUsage { 5715 AbstractUsageInfo &Info; 5716 const NamedDecl *Ctx; 5717 5718 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 5719 : Info(Info), Ctx(Ctx) {} 5720 5721 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5722 switch (TL.getTypeLocClass()) { 5723 #define ABSTRACT_TYPELOC(CLASS, PARENT) 5724 #define TYPELOC(CLASS, PARENT) \ 5725 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 5726 #include "clang/AST/TypeLocNodes.def" 5727 } 5728 } 5729 5730 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5731 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 5732 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 5733 if (!TL.getParam(I)) 5734 continue; 5735 5736 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 5737 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 5738 } 5739 } 5740 5741 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5742 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 5743 } 5744 5745 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5746 // Visit the type parameters from a permissive context. 5747 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 5748 TemplateArgumentLoc TAL = TL.getArgLoc(I); 5749 if (TAL.getArgument().getKind() == TemplateArgument::Type) 5750 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 5751 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 5752 // TODO: other template argument types? 5753 } 5754 } 5755 5756 // Visit pointee types from a permissive context. 5757 #define CheckPolymorphic(Type) \ 5758 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 5759 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 5760 } 5761 CheckPolymorphic(PointerTypeLoc) 5762 CheckPolymorphic(ReferenceTypeLoc) 5763 CheckPolymorphic(MemberPointerTypeLoc) 5764 CheckPolymorphic(BlockPointerTypeLoc) 5765 CheckPolymorphic(AtomicTypeLoc) 5766 5767 /// Handle all the types we haven't given a more specific 5768 /// implementation for above. 5769 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5770 // Every other kind of type that we haven't called out already 5771 // that has an inner type is either (1) sugar or (2) contains that 5772 // inner type in some way as a subobject. 5773 if (TypeLoc Next = TL.getNextTypeLoc()) 5774 return Visit(Next, Sel); 5775 5776 // If there's no inner type and we're in a permissive context, 5777 // don't diagnose. 5778 if (Sel == Sema::AbstractNone) return; 5779 5780 // Check whether the type matches the abstract type. 5781 QualType T = TL.getType(); 5782 if (T->isArrayType()) { 5783 Sel = Sema::AbstractArrayType; 5784 T = Info.S.Context.getBaseElementType(T); 5785 } 5786 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 5787 if (CT != Info.AbstractType) return; 5788 5789 // It matched; do some magic. 5790 if (Sel == Sema::AbstractArrayType) { 5791 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 5792 << T << TL.getSourceRange(); 5793 } else { 5794 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 5795 << Sel << T << TL.getSourceRange(); 5796 } 5797 Info.DiagnoseAbstractType(); 5798 } 5799 }; 5800 5801 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 5802 Sema::AbstractDiagSelID Sel) { 5803 CheckAbstractUsage(*this, D).Visit(TL, Sel); 5804 } 5805 5806 } 5807 5808 /// Check for invalid uses of an abstract type in a method declaration. 5809 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5810 CXXMethodDecl *MD) { 5811 // No need to do the check on definitions, which require that 5812 // the return/param types be complete. 5813 if (MD->doesThisDeclarationHaveABody()) 5814 return; 5815 5816 // For safety's sake, just ignore it if we don't have type source 5817 // information. This should never happen for non-implicit methods, 5818 // but... 5819 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 5820 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 5821 } 5822 5823 /// Check for invalid uses of an abstract type within a class definition. 5824 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5825 CXXRecordDecl *RD) { 5826 for (auto *D : RD->decls()) { 5827 if (D->isImplicit()) continue; 5828 5829 // Methods and method templates. 5830 if (isa<CXXMethodDecl>(D)) { 5831 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 5832 } else if (isa<FunctionTemplateDecl>(D)) { 5833 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 5834 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 5835 5836 // Fields and static variables. 5837 } else if (isa<FieldDecl>(D)) { 5838 FieldDecl *FD = cast<FieldDecl>(D); 5839 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 5840 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 5841 } else if (isa<VarDecl>(D)) { 5842 VarDecl *VD = cast<VarDecl>(D); 5843 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 5844 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 5845 5846 // Nested classes and class templates. 5847 } else if (isa<CXXRecordDecl>(D)) { 5848 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 5849 } else if (isa<ClassTemplateDecl>(D)) { 5850 CheckAbstractClassUsage(Info, 5851 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 5852 } 5853 } 5854 } 5855 5856 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) { 5857 Attr *ClassAttr = getDLLAttr(Class); 5858 if (!ClassAttr) 5859 return; 5860 5861 assert(ClassAttr->getKind() == attr::DLLExport); 5862 5863 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5864 5865 if (TSK == TSK_ExplicitInstantiationDeclaration) 5866 // Don't go any further if this is just an explicit instantiation 5867 // declaration. 5868 return; 5869 5870 // Add a context note to explain how we got to any diagnostics produced below. 5871 struct MarkingClassDllexported { 5872 Sema &S; 5873 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class, 5874 SourceLocation AttrLoc) 5875 : S(S) { 5876 Sema::CodeSynthesisContext Ctx; 5877 Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported; 5878 Ctx.PointOfInstantiation = AttrLoc; 5879 Ctx.Entity = Class; 5880 S.pushCodeSynthesisContext(Ctx); 5881 } 5882 ~MarkingClassDllexported() { 5883 S.popCodeSynthesisContext(); 5884 } 5885 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation()); 5886 5887 if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) 5888 S.MarkVTableUsed(Class->getLocation(), Class, true); 5889 5890 for (Decl *Member : Class->decls()) { 5891 // Defined static variables that are members of an exported base 5892 // class must be marked export too. 5893 auto *VD = dyn_cast<VarDecl>(Member); 5894 if (VD && Member->getAttr<DLLExportAttr>() && 5895 VD->getStorageClass() == SC_Static && 5896 TSK == TSK_ImplicitInstantiation) 5897 S.MarkVariableReferenced(VD->getLocation(), VD); 5898 5899 auto *MD = dyn_cast<CXXMethodDecl>(Member); 5900 if (!MD) 5901 continue; 5902 5903 if (Member->getAttr<DLLExportAttr>()) { 5904 if (MD->isUserProvided()) { 5905 // Instantiate non-default class member functions ... 5906 5907 // .. except for certain kinds of template specializations. 5908 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 5909 continue; 5910 5911 S.MarkFunctionReferenced(Class->getLocation(), MD); 5912 5913 // The function will be passed to the consumer when its definition is 5914 // encountered. 5915 } else if (MD->isExplicitlyDefaulted()) { 5916 // Synthesize and instantiate explicitly defaulted methods. 5917 S.MarkFunctionReferenced(Class->getLocation(), MD); 5918 5919 if (TSK != TSK_ExplicitInstantiationDefinition) { 5920 // Except for explicit instantiation defs, we will not see the 5921 // definition again later, so pass it to the consumer now. 5922 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 5923 } 5924 } else if (!MD->isTrivial() || 5925 MD->isCopyAssignmentOperator() || 5926 MD->isMoveAssignmentOperator()) { 5927 // Synthesize and instantiate non-trivial implicit methods, and the copy 5928 // and move assignment operators. The latter are exported even if they 5929 // are trivial, because the address of an operator can be taken and 5930 // should compare equal across libraries. 5931 S.MarkFunctionReferenced(Class->getLocation(), MD); 5932 5933 // There is no later point when we will see the definition of this 5934 // function, so pass it to the consumer now. 5935 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 5936 } 5937 } 5938 } 5939 } 5940 5941 static void checkForMultipleExportedDefaultConstructors(Sema &S, 5942 CXXRecordDecl *Class) { 5943 // Only the MS ABI has default constructor closures, so we don't need to do 5944 // this semantic checking anywhere else. 5945 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft()) 5946 return; 5947 5948 CXXConstructorDecl *LastExportedDefaultCtor = nullptr; 5949 for (Decl *Member : Class->decls()) { 5950 // Look for exported default constructors. 5951 auto *CD = dyn_cast<CXXConstructorDecl>(Member); 5952 if (!CD || !CD->isDefaultConstructor()) 5953 continue; 5954 auto *Attr = CD->getAttr<DLLExportAttr>(); 5955 if (!Attr) 5956 continue; 5957 5958 // If the class is non-dependent, mark the default arguments as ODR-used so 5959 // that we can properly codegen the constructor closure. 5960 if (!Class->isDependentContext()) { 5961 for (ParmVarDecl *PD : CD->parameters()) { 5962 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD); 5963 S.DiscardCleanupsInEvaluationContext(); 5964 } 5965 } 5966 5967 if (LastExportedDefaultCtor) { 5968 S.Diag(LastExportedDefaultCtor->getLocation(), 5969 diag::err_attribute_dll_ambiguous_default_ctor) 5970 << Class; 5971 S.Diag(CD->getLocation(), diag::note_entity_declared_at) 5972 << CD->getDeclName(); 5973 return; 5974 } 5975 LastExportedDefaultCtor = CD; 5976 } 5977 } 5978 5979 static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S, 5980 CXXRecordDecl *Class) { 5981 bool ErrorReported = false; 5982 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S, 5983 ClassTemplateDecl *TD) { 5984 if (ErrorReported) 5985 return; 5986 S.Diag(TD->getLocation(), 5987 diag::err_cuda_device_builtin_surftex_cls_template) 5988 << /*surface*/ 0 << TD; 5989 ErrorReported = true; 5990 }; 5991 5992 ClassTemplateDecl *TD = Class->getDescribedClassTemplate(); 5993 if (!TD) { 5994 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class); 5995 if (!SD) { 5996 S.Diag(Class->getLocation(), 5997 diag::err_cuda_device_builtin_surftex_ref_decl) 5998 << /*surface*/ 0 << Class; 5999 S.Diag(Class->getLocation(), 6000 diag::note_cuda_device_builtin_surftex_should_be_template_class) 6001 << Class; 6002 return; 6003 } 6004 TD = SD->getSpecializedTemplate(); 6005 } 6006 6007 TemplateParameterList *Params = TD->getTemplateParameters(); 6008 unsigned N = Params->size(); 6009 6010 if (N != 2) { 6011 reportIllegalClassTemplate(S, TD); 6012 S.Diag(TD->getLocation(), 6013 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args) 6014 << TD << 2; 6015 } 6016 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 6017 reportIllegalClassTemplate(S, TD); 6018 S.Diag(TD->getLocation(), 6019 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6020 << TD << /*1st*/ 0 << /*type*/ 0; 6021 } 6022 if (N > 1) { 6023 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 6024 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 6025 reportIllegalClassTemplate(S, TD); 6026 S.Diag(TD->getLocation(), 6027 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6028 << TD << /*2nd*/ 1 << /*integer*/ 1; 6029 } 6030 } 6031 } 6032 6033 static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S, 6034 CXXRecordDecl *Class) { 6035 bool ErrorReported = false; 6036 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S, 6037 ClassTemplateDecl *TD) { 6038 if (ErrorReported) 6039 return; 6040 S.Diag(TD->getLocation(), 6041 diag::err_cuda_device_builtin_surftex_cls_template) 6042 << /*texture*/ 1 << TD; 6043 ErrorReported = true; 6044 }; 6045 6046 ClassTemplateDecl *TD = Class->getDescribedClassTemplate(); 6047 if (!TD) { 6048 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class); 6049 if (!SD) { 6050 S.Diag(Class->getLocation(), 6051 diag::err_cuda_device_builtin_surftex_ref_decl) 6052 << /*texture*/ 1 << Class; 6053 S.Diag(Class->getLocation(), 6054 diag::note_cuda_device_builtin_surftex_should_be_template_class) 6055 << Class; 6056 return; 6057 } 6058 TD = SD->getSpecializedTemplate(); 6059 } 6060 6061 TemplateParameterList *Params = TD->getTemplateParameters(); 6062 unsigned N = Params->size(); 6063 6064 if (N != 3) { 6065 reportIllegalClassTemplate(S, TD); 6066 S.Diag(TD->getLocation(), 6067 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args) 6068 << TD << 3; 6069 } 6070 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 6071 reportIllegalClassTemplate(S, TD); 6072 S.Diag(TD->getLocation(), 6073 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6074 << TD << /*1st*/ 0 << /*type*/ 0; 6075 } 6076 if (N > 1) { 6077 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 6078 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 6079 reportIllegalClassTemplate(S, TD); 6080 S.Diag(TD->getLocation(), 6081 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6082 << TD << /*2nd*/ 1 << /*integer*/ 1; 6083 } 6084 } 6085 if (N > 2) { 6086 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2)); 6087 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 6088 reportIllegalClassTemplate(S, TD); 6089 S.Diag(TD->getLocation(), 6090 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6091 << TD << /*3rd*/ 2 << /*integer*/ 1; 6092 } 6093 } 6094 } 6095 6096 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) { 6097 // Mark any compiler-generated routines with the implicit code_seg attribute. 6098 for (auto *Method : Class->methods()) { 6099 if (Method->isUserProvided()) 6100 continue; 6101 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true)) 6102 Method->addAttr(A); 6103 } 6104 } 6105 6106 /// Check class-level dllimport/dllexport attribute. 6107 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) { 6108 Attr *ClassAttr = getDLLAttr(Class); 6109 6110 // MSVC inherits DLL attributes to partial class template specializations. 6111 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) { 6112 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 6113 if (Attr *TemplateAttr = 6114 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 6115 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext())); 6116 A->setInherited(true); 6117 ClassAttr = A; 6118 } 6119 } 6120 } 6121 6122 if (!ClassAttr) 6123 return; 6124 6125 if (!Class->isExternallyVisible()) { 6126 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) 6127 << Class << ClassAttr; 6128 return; 6129 } 6130 6131 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && 6132 !ClassAttr->isInherited()) { 6133 // Diagnose dll attributes on members of class with dll attribute. 6134 for (Decl *Member : Class->decls()) { 6135 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 6136 continue; 6137 InheritableAttr *MemberAttr = getDLLAttr(Member); 6138 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 6139 continue; 6140 6141 Diag(MemberAttr->getLocation(), 6142 diag::err_attribute_dll_member_of_dll_class) 6143 << MemberAttr << ClassAttr; 6144 Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 6145 Member->setInvalidDecl(); 6146 } 6147 } 6148 6149 if (Class->getDescribedClassTemplate()) 6150 // Don't inherit dll attribute until the template is instantiated. 6151 return; 6152 6153 // The class is either imported or exported. 6154 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 6155 6156 // Check if this was a dllimport attribute propagated from a derived class to 6157 // a base class template specialization. We don't apply these attributes to 6158 // static data members. 6159 const bool PropagatedImport = 6160 !ClassExported && 6161 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate(); 6162 6163 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 6164 6165 // Ignore explicit dllexport on explicit class template instantiation 6166 // declarations, except in MinGW mode. 6167 if (ClassExported && !ClassAttr->isInherited() && 6168 TSK == TSK_ExplicitInstantiationDeclaration && 6169 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) { 6170 Class->dropAttr<DLLExportAttr>(); 6171 return; 6172 } 6173 6174 // Force declaration of implicit members so they can inherit the attribute. 6175 ForceDeclarationOfImplicitMembers(Class); 6176 6177 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 6178 // seem to be true in practice? 6179 6180 for (Decl *Member : Class->decls()) { 6181 VarDecl *VD = dyn_cast<VarDecl>(Member); 6182 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 6183 6184 // Only methods and static fields inherit the attributes. 6185 if (!VD && !MD) 6186 continue; 6187 6188 if (MD) { 6189 // Don't process deleted methods. 6190 if (MD->isDeleted()) 6191 continue; 6192 6193 if (MD->isInlined()) { 6194 // MinGW does not import or export inline methods. But do it for 6195 // template instantiations. 6196 if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() && 6197 TSK != TSK_ExplicitInstantiationDeclaration && 6198 TSK != TSK_ExplicitInstantiationDefinition) 6199 continue; 6200 6201 // MSVC versions before 2015 don't export the move assignment operators 6202 // and move constructor, so don't attempt to import/export them if 6203 // we have a definition. 6204 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD); 6205 if ((MD->isMoveAssignmentOperator() || 6206 (Ctor && Ctor->isMoveConstructor())) && 6207 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015)) 6208 continue; 6209 6210 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign 6211 // operator is exported anyway. 6212 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 6213 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial()) 6214 continue; 6215 } 6216 } 6217 6218 // Don't apply dllimport attributes to static data members of class template 6219 // instantiations when the attribute is propagated from a derived class. 6220 if (VD && PropagatedImport) 6221 continue; 6222 6223 if (!cast<NamedDecl>(Member)->isExternallyVisible()) 6224 continue; 6225 6226 if (!getDLLAttr(Member)) { 6227 InheritableAttr *NewAttr = nullptr; 6228 6229 // Do not export/import inline function when -fno-dllexport-inlines is 6230 // passed. But add attribute for later local static var check. 6231 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() && 6232 TSK != TSK_ExplicitInstantiationDeclaration && 6233 TSK != TSK_ExplicitInstantiationDefinition) { 6234 if (ClassExported) { 6235 NewAttr = ::new (getASTContext()) 6236 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr); 6237 } else { 6238 NewAttr = ::new (getASTContext()) 6239 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr); 6240 } 6241 } else { 6242 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6243 } 6244 6245 NewAttr->setInherited(true); 6246 Member->addAttr(NewAttr); 6247 6248 if (MD) { 6249 // Propagate DLLAttr to friend re-declarations of MD that have already 6250 // been constructed. 6251 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD; 6252 FD = FD->getPreviousDecl()) { 6253 if (FD->getFriendObjectKind() == Decl::FOK_None) 6254 continue; 6255 assert(!getDLLAttr(FD) && 6256 "friend re-decl should not already have a DLLAttr"); 6257 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6258 NewAttr->setInherited(true); 6259 FD->addAttr(NewAttr); 6260 } 6261 } 6262 } 6263 } 6264 6265 if (ClassExported) 6266 DelayedDllExportClasses.push_back(Class); 6267 } 6268 6269 /// Perform propagation of DLL attributes from a derived class to a 6270 /// templated base class for MS compatibility. 6271 void Sema::propagateDLLAttrToBaseClassTemplate( 6272 CXXRecordDecl *Class, Attr *ClassAttr, 6273 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 6274 if (getDLLAttr( 6275 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 6276 // If the base class template has a DLL attribute, don't try to change it. 6277 return; 6278 } 6279 6280 auto TSK = BaseTemplateSpec->getSpecializationKind(); 6281 if (!getDLLAttr(BaseTemplateSpec) && 6282 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration || 6283 TSK == TSK_ImplicitInstantiation)) { 6284 // The template hasn't been instantiated yet (or it has, but only as an 6285 // explicit instantiation declaration or implicit instantiation, which means 6286 // we haven't codegenned any members yet), so propagate the attribute. 6287 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6288 NewAttr->setInherited(true); 6289 BaseTemplateSpec->addAttr(NewAttr); 6290 6291 // If this was an import, mark that we propagated it from a derived class to 6292 // a base class template specialization. 6293 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr)) 6294 ImportAttr->setPropagatedToBaseTemplate(); 6295 6296 // If the template is already instantiated, checkDLLAttributeRedeclaration() 6297 // needs to be run again to work see the new attribute. Otherwise this will 6298 // get run whenever the template is instantiated. 6299 if (TSK != TSK_Undeclared) 6300 checkClassLevelDLLAttribute(BaseTemplateSpec); 6301 6302 return; 6303 } 6304 6305 if (getDLLAttr(BaseTemplateSpec)) { 6306 // The template has already been specialized or instantiated with an 6307 // attribute, explicitly or through propagation. We should not try to change 6308 // it. 6309 return; 6310 } 6311 6312 // The template was previously instantiated or explicitly specialized without 6313 // a dll attribute, It's too late for us to add an attribute, so warn that 6314 // this is unsupported. 6315 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 6316 << BaseTemplateSpec->isExplicitSpecialization(); 6317 Diag(ClassAttr->getLocation(), diag::note_attribute); 6318 if (BaseTemplateSpec->isExplicitSpecialization()) { 6319 Diag(BaseTemplateSpec->getLocation(), 6320 diag::note_template_class_explicit_specialization_was_here) 6321 << BaseTemplateSpec; 6322 } else { 6323 Diag(BaseTemplateSpec->getPointOfInstantiation(), 6324 diag::note_template_class_instantiation_was_here) 6325 << BaseTemplateSpec; 6326 } 6327 } 6328 6329 /// Determine the kind of defaulting that would be done for a given function. 6330 /// 6331 /// If the function is both a default constructor and a copy / move constructor 6332 /// (due to having a default argument for the first parameter), this picks 6333 /// CXXDefaultConstructor. 6334 /// 6335 /// FIXME: Check that case is properly handled by all callers. 6336 Sema::DefaultedFunctionKind 6337 Sema::getDefaultedFunctionKind(const FunctionDecl *FD) { 6338 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 6339 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 6340 if (Ctor->isDefaultConstructor()) 6341 return Sema::CXXDefaultConstructor; 6342 6343 if (Ctor->isCopyConstructor()) 6344 return Sema::CXXCopyConstructor; 6345 6346 if (Ctor->isMoveConstructor()) 6347 return Sema::CXXMoveConstructor; 6348 } 6349 6350 if (MD->isCopyAssignmentOperator()) 6351 return Sema::CXXCopyAssignment; 6352 6353 if (MD->isMoveAssignmentOperator()) 6354 return Sema::CXXMoveAssignment; 6355 6356 if (isa<CXXDestructorDecl>(FD)) 6357 return Sema::CXXDestructor; 6358 } 6359 6360 switch (FD->getDeclName().getCXXOverloadedOperator()) { 6361 case OO_EqualEqual: 6362 return DefaultedComparisonKind::Equal; 6363 6364 case OO_ExclaimEqual: 6365 return DefaultedComparisonKind::NotEqual; 6366 6367 case OO_Spaceship: 6368 // No point allowing this if <=> doesn't exist in the current language mode. 6369 if (!getLangOpts().CPlusPlus20) 6370 break; 6371 return DefaultedComparisonKind::ThreeWay; 6372 6373 case OO_Less: 6374 case OO_LessEqual: 6375 case OO_Greater: 6376 case OO_GreaterEqual: 6377 // No point allowing this if <=> doesn't exist in the current language mode. 6378 if (!getLangOpts().CPlusPlus20) 6379 break; 6380 return DefaultedComparisonKind::Relational; 6381 6382 default: 6383 break; 6384 } 6385 6386 // Not defaultable. 6387 return DefaultedFunctionKind(); 6388 } 6389 6390 static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD, 6391 SourceLocation DefaultLoc) { 6392 Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD); 6393 if (DFK.isComparison()) 6394 return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison()); 6395 6396 switch (DFK.asSpecialMember()) { 6397 case Sema::CXXDefaultConstructor: 6398 S.DefineImplicitDefaultConstructor(DefaultLoc, 6399 cast<CXXConstructorDecl>(FD)); 6400 break; 6401 case Sema::CXXCopyConstructor: 6402 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD)); 6403 break; 6404 case Sema::CXXCopyAssignment: 6405 S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD)); 6406 break; 6407 case Sema::CXXDestructor: 6408 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD)); 6409 break; 6410 case Sema::CXXMoveConstructor: 6411 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD)); 6412 break; 6413 case Sema::CXXMoveAssignment: 6414 S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD)); 6415 break; 6416 case Sema::CXXInvalid: 6417 llvm_unreachable("Invalid special member."); 6418 } 6419 } 6420 6421 /// Determine whether a type is permitted to be passed or returned in 6422 /// registers, per C++ [class.temporary]p3. 6423 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D, 6424 TargetInfo::CallingConvKind CCK) { 6425 if (D->isDependentType() || D->isInvalidDecl()) 6426 return false; 6427 6428 // Clang <= 4 used the pre-C++11 rule, which ignores move operations. 6429 // The PS4 platform ABI follows the behavior of Clang 3.2. 6430 if (CCK == TargetInfo::CCK_ClangABI4OrPS4) 6431 return !D->hasNonTrivialDestructorForCall() && 6432 !D->hasNonTrivialCopyConstructorForCall(); 6433 6434 if (CCK == TargetInfo::CCK_MicrosoftWin64) { 6435 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false; 6436 bool DtorIsTrivialForCall = false; 6437 6438 // If a class has at least one non-deleted, trivial copy constructor, it 6439 // is passed according to the C ABI. Otherwise, it is passed indirectly. 6440 // 6441 // Note: This permits classes with non-trivial copy or move ctors to be 6442 // passed in registers, so long as they *also* have a trivial copy ctor, 6443 // which is non-conforming. 6444 if (D->needsImplicitCopyConstructor()) { 6445 if (!D->defaultedCopyConstructorIsDeleted()) { 6446 if (D->hasTrivialCopyConstructor()) 6447 CopyCtorIsTrivial = true; 6448 if (D->hasTrivialCopyConstructorForCall()) 6449 CopyCtorIsTrivialForCall = true; 6450 } 6451 } else { 6452 for (const CXXConstructorDecl *CD : D->ctors()) { 6453 if (CD->isCopyConstructor() && !CD->isDeleted()) { 6454 if (CD->isTrivial()) 6455 CopyCtorIsTrivial = true; 6456 if (CD->isTrivialForCall()) 6457 CopyCtorIsTrivialForCall = true; 6458 } 6459 } 6460 } 6461 6462 if (D->needsImplicitDestructor()) { 6463 if (!D->defaultedDestructorIsDeleted() && 6464 D->hasTrivialDestructorForCall()) 6465 DtorIsTrivialForCall = true; 6466 } else if (const auto *DD = D->getDestructor()) { 6467 if (!DD->isDeleted() && DD->isTrivialForCall()) 6468 DtorIsTrivialForCall = true; 6469 } 6470 6471 // If the copy ctor and dtor are both trivial-for-calls, pass direct. 6472 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall) 6473 return true; 6474 6475 // If a class has a destructor, we'd really like to pass it indirectly 6476 // because it allows us to elide copies. Unfortunately, MSVC makes that 6477 // impossible for small types, which it will pass in a single register or 6478 // stack slot. Most objects with dtors are large-ish, so handle that early. 6479 // We can't call out all large objects as being indirect because there are 6480 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate 6481 // how we pass large POD types. 6482 6483 // Note: This permits small classes with nontrivial destructors to be 6484 // passed in registers, which is non-conforming. 6485 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64(); 6486 uint64_t TypeSize = isAArch64 ? 128 : 64; 6487 6488 if (CopyCtorIsTrivial && 6489 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize) 6490 return true; 6491 return false; 6492 } 6493 6494 // Per C++ [class.temporary]p3, the relevant condition is: 6495 // each copy constructor, move constructor, and destructor of X is 6496 // either trivial or deleted, and X has at least one non-deleted copy 6497 // or move constructor 6498 bool HasNonDeletedCopyOrMove = false; 6499 6500 if (D->needsImplicitCopyConstructor() && 6501 !D->defaultedCopyConstructorIsDeleted()) { 6502 if (!D->hasTrivialCopyConstructorForCall()) 6503 return false; 6504 HasNonDeletedCopyOrMove = true; 6505 } 6506 6507 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() && 6508 !D->defaultedMoveConstructorIsDeleted()) { 6509 if (!D->hasTrivialMoveConstructorForCall()) 6510 return false; 6511 HasNonDeletedCopyOrMove = true; 6512 } 6513 6514 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() && 6515 !D->hasTrivialDestructorForCall()) 6516 return false; 6517 6518 for (const CXXMethodDecl *MD : D->methods()) { 6519 if (MD->isDeleted()) 6520 continue; 6521 6522 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 6523 if (CD && CD->isCopyOrMoveConstructor()) 6524 HasNonDeletedCopyOrMove = true; 6525 else if (!isa<CXXDestructorDecl>(MD)) 6526 continue; 6527 6528 if (!MD->isTrivialForCall()) 6529 return false; 6530 } 6531 6532 return HasNonDeletedCopyOrMove; 6533 } 6534 6535 /// Report an error regarding overriding, along with any relevant 6536 /// overridden methods. 6537 /// 6538 /// \param DiagID the primary error to report. 6539 /// \param MD the overriding method. 6540 static bool 6541 ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD, 6542 llvm::function_ref<bool(const CXXMethodDecl *)> Report) { 6543 bool IssuedDiagnostic = false; 6544 for (const CXXMethodDecl *O : MD->overridden_methods()) { 6545 if (Report(O)) { 6546 if (!IssuedDiagnostic) { 6547 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 6548 IssuedDiagnostic = true; 6549 } 6550 S.Diag(O->getLocation(), diag::note_overridden_virtual_function); 6551 } 6552 } 6553 return IssuedDiagnostic; 6554 } 6555 6556 /// Perform semantic checks on a class definition that has been 6557 /// completing, introducing implicitly-declared members, checking for 6558 /// abstract types, etc. 6559 /// 6560 /// \param S The scope in which the class was parsed. Null if we didn't just 6561 /// parse a class definition. 6562 /// \param Record The completed class. 6563 void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) { 6564 if (!Record) 6565 return; 6566 6567 if (Record->isAbstract() && !Record->isInvalidDecl()) { 6568 AbstractUsageInfo Info(*this, Record); 6569 CheckAbstractClassUsage(Info, Record); 6570 } 6571 6572 // If this is not an aggregate type and has no user-declared constructor, 6573 // complain about any non-static data members of reference or const scalar 6574 // type, since they will never get initializers. 6575 if (!Record->isInvalidDecl() && !Record->isDependentType() && 6576 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 6577 !Record->isLambda()) { 6578 bool Complained = false; 6579 for (const auto *F : Record->fields()) { 6580 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 6581 continue; 6582 6583 if (F->getType()->isReferenceType() || 6584 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 6585 if (!Complained) { 6586 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 6587 << Record->getTagKind() << Record; 6588 Complained = true; 6589 } 6590 6591 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 6592 << F->getType()->isReferenceType() 6593 << F->getDeclName(); 6594 } 6595 } 6596 } 6597 6598 if (Record->getIdentifier()) { 6599 // C++ [class.mem]p13: 6600 // If T is the name of a class, then each of the following shall have a 6601 // name different from T: 6602 // - every member of every anonymous union that is a member of class T. 6603 // 6604 // C++ [class.mem]p14: 6605 // In addition, if class T has a user-declared constructor (12.1), every 6606 // non-static data member of class T shall have a name different from T. 6607 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 6608 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 6609 ++I) { 6610 NamedDecl *D = (*I)->getUnderlyingDecl(); 6611 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) && 6612 Record->hasUserDeclaredConstructor()) || 6613 isa<IndirectFieldDecl>(D)) { 6614 Diag((*I)->getLocation(), diag::err_member_name_of_class) 6615 << D->getDeclName(); 6616 break; 6617 } 6618 } 6619 } 6620 6621 // Warn if the class has virtual methods but non-virtual public destructor. 6622 if (Record->isPolymorphic() && !Record->isDependentType()) { 6623 CXXDestructorDecl *dtor = Record->getDestructor(); 6624 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 6625 !Record->hasAttr<FinalAttr>()) 6626 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 6627 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 6628 } 6629 6630 if (Record->isAbstract()) { 6631 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 6632 Diag(Record->getLocation(), diag::warn_abstract_final_class) 6633 << FA->isSpelledAsSealed(); 6634 DiagnoseAbstractType(Record); 6635 } 6636 } 6637 6638 // Warn if the class has a final destructor but is not itself marked final. 6639 if (!Record->hasAttr<FinalAttr>()) { 6640 if (const CXXDestructorDecl *dtor = Record->getDestructor()) { 6641 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) { 6642 Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class) 6643 << FA->isSpelledAsSealed() 6644 << FixItHint::CreateInsertion( 6645 getLocForEndOfToken(Record->getLocation()), 6646 (FA->isSpelledAsSealed() ? " sealed" : " final")); 6647 Diag(Record->getLocation(), 6648 diag::note_final_dtor_non_final_class_silence) 6649 << Context.getRecordType(Record) << FA->isSpelledAsSealed(); 6650 } 6651 } 6652 } 6653 6654 // See if trivial_abi has to be dropped. 6655 if (Record->hasAttr<TrivialABIAttr>()) 6656 checkIllFormedTrivialABIStruct(*Record); 6657 6658 // Set HasTrivialSpecialMemberForCall if the record has attribute 6659 // "trivial_abi". 6660 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>(); 6661 6662 if (HasTrivialABI) 6663 Record->setHasTrivialSpecialMemberForCall(); 6664 6665 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=). 6666 // We check these last because they can depend on the properties of the 6667 // primary comparison functions (==, <=>). 6668 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons; 6669 6670 // Perform checks that can't be done until we know all the properties of a 6671 // member function (whether it's defaulted, deleted, virtual, overriding, 6672 // ...). 6673 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) { 6674 // A static function cannot override anything. 6675 if (MD->getStorageClass() == SC_Static) { 6676 if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD, 6677 [](const CXXMethodDecl *) { return true; })) 6678 return; 6679 } 6680 6681 // A deleted function cannot override a non-deleted function and vice 6682 // versa. 6683 if (ReportOverrides(*this, 6684 MD->isDeleted() ? diag::err_deleted_override 6685 : diag::err_non_deleted_override, 6686 MD, [&](const CXXMethodDecl *V) { 6687 return MD->isDeleted() != V->isDeleted(); 6688 })) { 6689 if (MD->isDefaulted() && MD->isDeleted()) 6690 // Explain why this defaulted function was deleted. 6691 DiagnoseDeletedDefaultedFunction(MD); 6692 return; 6693 } 6694 6695 // A consteval function cannot override a non-consteval function and vice 6696 // versa. 6697 if (ReportOverrides(*this, 6698 MD->isConsteval() ? diag::err_consteval_override 6699 : diag::err_non_consteval_override, 6700 MD, [&](const CXXMethodDecl *V) { 6701 return MD->isConsteval() != V->isConsteval(); 6702 })) { 6703 if (MD->isDefaulted() && MD->isDeleted()) 6704 // Explain why this defaulted function was deleted. 6705 DiagnoseDeletedDefaultedFunction(MD); 6706 return; 6707 } 6708 }; 6709 6710 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool { 6711 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted()) 6712 return false; 6713 6714 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD); 6715 if (DFK.asComparison() == DefaultedComparisonKind::NotEqual || 6716 DFK.asComparison() == DefaultedComparisonKind::Relational) { 6717 DefaultedSecondaryComparisons.push_back(FD); 6718 return true; 6719 } 6720 6721 CheckExplicitlyDefaultedFunction(S, FD); 6722 return false; 6723 }; 6724 6725 auto CompleteMemberFunction = [&](CXXMethodDecl *M) { 6726 // Check whether the explicitly-defaulted members are valid. 6727 bool Incomplete = CheckForDefaultedFunction(M); 6728 6729 // Skip the rest of the checks for a member of a dependent class. 6730 if (Record->isDependentType()) 6731 return; 6732 6733 // For an explicitly defaulted or deleted special member, we defer 6734 // determining triviality until the class is complete. That time is now! 6735 CXXSpecialMember CSM = getSpecialMember(M); 6736 if (!M->isImplicit() && !M->isUserProvided()) { 6737 if (CSM != CXXInvalid) { 6738 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 6739 // Inform the class that we've finished declaring this member. 6740 Record->finishedDefaultedOrDeletedMember(M); 6741 M->setTrivialForCall( 6742 HasTrivialABI || 6743 SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI)); 6744 Record->setTrivialForCallFlags(M); 6745 } 6746 } 6747 6748 // Set triviality for the purpose of calls if this is a user-provided 6749 // copy/move constructor or destructor. 6750 if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor || 6751 CSM == CXXDestructor) && M->isUserProvided()) { 6752 M->setTrivialForCall(HasTrivialABI); 6753 Record->setTrivialForCallFlags(M); 6754 } 6755 6756 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() && 6757 M->hasAttr<DLLExportAttr>()) { 6758 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 6759 M->isTrivial() && 6760 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor || 6761 CSM == CXXDestructor)) 6762 M->dropAttr<DLLExportAttr>(); 6763 6764 if (M->hasAttr<DLLExportAttr>()) { 6765 // Define after any fields with in-class initializers have been parsed. 6766 DelayedDllExportMemberFunctions.push_back(M); 6767 } 6768 } 6769 6770 // Define defaulted constexpr virtual functions that override a base class 6771 // function right away. 6772 // FIXME: We can defer doing this until the vtable is marked as used. 6773 if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods()) 6774 DefineDefaultedFunction(*this, M, M->getLocation()); 6775 6776 if (!Incomplete) 6777 CheckCompletedMemberFunction(M); 6778 }; 6779 6780 // Check the destructor before any other member function. We need to 6781 // determine whether it's trivial in order to determine whether the claas 6782 // type is a literal type, which is a prerequisite for determining whether 6783 // other special member functions are valid and whether they're implicitly 6784 // 'constexpr'. 6785 if (CXXDestructorDecl *Dtor = Record->getDestructor()) 6786 CompleteMemberFunction(Dtor); 6787 6788 bool HasMethodWithOverrideControl = false, 6789 HasOverridingMethodWithoutOverrideControl = false; 6790 for (auto *D : Record->decls()) { 6791 if (auto *M = dyn_cast<CXXMethodDecl>(D)) { 6792 // FIXME: We could do this check for dependent types with non-dependent 6793 // bases. 6794 if (!Record->isDependentType()) { 6795 // See if a method overloads virtual methods in a base 6796 // class without overriding any. 6797 if (!M->isStatic()) 6798 DiagnoseHiddenVirtualMethods(M); 6799 if (M->hasAttr<OverrideAttr>()) 6800 HasMethodWithOverrideControl = true; 6801 else if (M->size_overridden_methods() > 0) 6802 HasOverridingMethodWithoutOverrideControl = true; 6803 } 6804 6805 if (!isa<CXXDestructorDecl>(M)) 6806 CompleteMemberFunction(M); 6807 } else if (auto *F = dyn_cast<FriendDecl>(D)) { 6808 CheckForDefaultedFunction( 6809 dyn_cast_or_null<FunctionDecl>(F->getFriendDecl())); 6810 } 6811 } 6812 6813 if (HasOverridingMethodWithoutOverrideControl) { 6814 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl; 6815 for (auto *M : Record->methods()) 6816 DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl); 6817 } 6818 6819 // Check the defaulted secondary comparisons after any other member functions. 6820 for (FunctionDecl *FD : DefaultedSecondaryComparisons) { 6821 CheckExplicitlyDefaultedFunction(S, FD); 6822 6823 // If this is a member function, we deferred checking it until now. 6824 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) 6825 CheckCompletedMemberFunction(MD); 6826 } 6827 6828 // ms_struct is a request to use the same ABI rules as MSVC. Check 6829 // whether this class uses any C++ features that are implemented 6830 // completely differently in MSVC, and if so, emit a diagnostic. 6831 // That diagnostic defaults to an error, but we allow projects to 6832 // map it down to a warning (or ignore it). It's a fairly common 6833 // practice among users of the ms_struct pragma to mass-annotate 6834 // headers, sweeping up a bunch of types that the project doesn't 6835 // really rely on MSVC-compatible layout for. We must therefore 6836 // support "ms_struct except for C++ stuff" as a secondary ABI. 6837 // Don't emit this diagnostic if the feature was enabled as a 6838 // language option (as opposed to via a pragma or attribute), as 6839 // the option -mms-bitfields otherwise essentially makes it impossible 6840 // to build C++ code, unless this diagnostic is turned off. 6841 if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields && 6842 (Record->isPolymorphic() || Record->getNumBases())) { 6843 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 6844 } 6845 6846 checkClassLevelDLLAttribute(Record); 6847 checkClassLevelCodeSegAttribute(Record); 6848 6849 bool ClangABICompat4 = 6850 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4; 6851 TargetInfo::CallingConvKind CCK = 6852 Context.getTargetInfo().getCallingConvKind(ClangABICompat4); 6853 bool CanPass = canPassInRegisters(*this, Record, CCK); 6854 6855 // Do not change ArgPassingRestrictions if it has already been set to 6856 // APK_CanNeverPassInRegs. 6857 if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs) 6858 Record->setArgPassingRestrictions(CanPass 6859 ? RecordDecl::APK_CanPassInRegs 6860 : RecordDecl::APK_CannotPassInRegs); 6861 6862 // If canPassInRegisters returns true despite the record having a non-trivial 6863 // destructor, the record is destructed in the callee. This happens only when 6864 // the record or one of its subobjects has a field annotated with trivial_abi 6865 // or a field qualified with ObjC __strong/__weak. 6866 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee()) 6867 Record->setParamDestroyedInCallee(true); 6868 else if (Record->hasNonTrivialDestructor()) 6869 Record->setParamDestroyedInCallee(CanPass); 6870 6871 if (getLangOpts().ForceEmitVTables) { 6872 // If we want to emit all the vtables, we need to mark it as used. This 6873 // is especially required for cases like vtable assumption loads. 6874 MarkVTableUsed(Record->getInnerLocStart(), Record); 6875 } 6876 6877 if (getLangOpts().CUDA) { 6878 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>()) 6879 checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record); 6880 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>()) 6881 checkCUDADeviceBuiltinTextureClassTemplate(*this, Record); 6882 } 6883 } 6884 6885 /// Look up the special member function that would be called by a special 6886 /// member function for a subobject of class type. 6887 /// 6888 /// \param Class The class type of the subobject. 6889 /// \param CSM The kind of special member function. 6890 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 6891 /// \param ConstRHS True if this is a copy operation with a const object 6892 /// on its RHS, that is, if the argument to the outer special member 6893 /// function is 'const' and this is not a field marked 'mutable'. 6894 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember( 6895 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 6896 unsigned FieldQuals, bool ConstRHS) { 6897 unsigned LHSQuals = 0; 6898 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 6899 LHSQuals = FieldQuals; 6900 6901 unsigned RHSQuals = FieldQuals; 6902 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 6903 RHSQuals = 0; 6904 else if (ConstRHS) 6905 RHSQuals |= Qualifiers::Const; 6906 6907 return S.LookupSpecialMember(Class, CSM, 6908 RHSQuals & Qualifiers::Const, 6909 RHSQuals & Qualifiers::Volatile, 6910 false, 6911 LHSQuals & Qualifiers::Const, 6912 LHSQuals & Qualifiers::Volatile); 6913 } 6914 6915 class Sema::InheritedConstructorInfo { 6916 Sema &S; 6917 SourceLocation UseLoc; 6918 6919 /// A mapping from the base classes through which the constructor was 6920 /// inherited to the using shadow declaration in that base class (or a null 6921 /// pointer if the constructor was declared in that base class). 6922 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *> 6923 InheritedFromBases; 6924 6925 public: 6926 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, 6927 ConstructorUsingShadowDecl *Shadow) 6928 : S(S), UseLoc(UseLoc) { 6929 bool DiagnosedMultipleConstructedBases = false; 6930 CXXRecordDecl *ConstructedBase = nullptr; 6931 UsingDecl *ConstructedBaseUsing = nullptr; 6932 6933 // Find the set of such base class subobjects and check that there's a 6934 // unique constructed subobject. 6935 for (auto *D : Shadow->redecls()) { 6936 auto *DShadow = cast<ConstructorUsingShadowDecl>(D); 6937 auto *DNominatedBase = DShadow->getNominatedBaseClass(); 6938 auto *DConstructedBase = DShadow->getConstructedBaseClass(); 6939 6940 InheritedFromBases.insert( 6941 std::make_pair(DNominatedBase->getCanonicalDecl(), 6942 DShadow->getNominatedBaseClassShadowDecl())); 6943 if (DShadow->constructsVirtualBase()) 6944 InheritedFromBases.insert( 6945 std::make_pair(DConstructedBase->getCanonicalDecl(), 6946 DShadow->getConstructedBaseClassShadowDecl())); 6947 else 6948 assert(DNominatedBase == DConstructedBase); 6949 6950 // [class.inhctor.init]p2: 6951 // If the constructor was inherited from multiple base class subobjects 6952 // of type B, the program is ill-formed. 6953 if (!ConstructedBase) { 6954 ConstructedBase = DConstructedBase; 6955 ConstructedBaseUsing = D->getUsingDecl(); 6956 } else if (ConstructedBase != DConstructedBase && 6957 !Shadow->isInvalidDecl()) { 6958 if (!DiagnosedMultipleConstructedBases) { 6959 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor) 6960 << Shadow->getTargetDecl(); 6961 S.Diag(ConstructedBaseUsing->getLocation(), 6962 diag::note_ambiguous_inherited_constructor_using) 6963 << ConstructedBase; 6964 DiagnosedMultipleConstructedBases = true; 6965 } 6966 S.Diag(D->getUsingDecl()->getLocation(), 6967 diag::note_ambiguous_inherited_constructor_using) 6968 << DConstructedBase; 6969 } 6970 } 6971 6972 if (DiagnosedMultipleConstructedBases) 6973 Shadow->setInvalidDecl(); 6974 } 6975 6976 /// Find the constructor to use for inherited construction of a base class, 6977 /// and whether that base class constructor inherits the constructor from a 6978 /// virtual base class (in which case it won't actually invoke it). 6979 std::pair<CXXConstructorDecl *, bool> 6980 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const { 6981 auto It = InheritedFromBases.find(Base->getCanonicalDecl()); 6982 if (It == InheritedFromBases.end()) 6983 return std::make_pair(nullptr, false); 6984 6985 // This is an intermediary class. 6986 if (It->second) 6987 return std::make_pair( 6988 S.findInheritingConstructor(UseLoc, Ctor, It->second), 6989 It->second->constructsVirtualBase()); 6990 6991 // This is the base class from which the constructor was inherited. 6992 return std::make_pair(Ctor, false); 6993 } 6994 }; 6995 6996 /// Is the special member function which would be selected to perform the 6997 /// specified operation on the specified class type a constexpr constructor? 6998 static bool 6999 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 7000 Sema::CXXSpecialMember CSM, unsigned Quals, 7001 bool ConstRHS, 7002 CXXConstructorDecl *InheritedCtor = nullptr, 7003 Sema::InheritedConstructorInfo *Inherited = nullptr) { 7004 // If we're inheriting a constructor, see if we need to call it for this base 7005 // class. 7006 if (InheritedCtor) { 7007 assert(CSM == Sema::CXXDefaultConstructor); 7008 auto BaseCtor = 7009 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first; 7010 if (BaseCtor) 7011 return BaseCtor->isConstexpr(); 7012 } 7013 7014 if (CSM == Sema::CXXDefaultConstructor) 7015 return ClassDecl->hasConstexprDefaultConstructor(); 7016 if (CSM == Sema::CXXDestructor) 7017 return ClassDecl->hasConstexprDestructor(); 7018 7019 Sema::SpecialMemberOverloadResult SMOR = 7020 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 7021 if (!SMOR.getMethod()) 7022 // A constructor we wouldn't select can't be "involved in initializing" 7023 // anything. 7024 return true; 7025 return SMOR.getMethod()->isConstexpr(); 7026 } 7027 7028 /// Determine whether the specified special member function would be constexpr 7029 /// if it were implicitly defined. 7030 static bool defaultedSpecialMemberIsConstexpr( 7031 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, 7032 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr, 7033 Sema::InheritedConstructorInfo *Inherited = nullptr) { 7034 if (!S.getLangOpts().CPlusPlus11) 7035 return false; 7036 7037 // C++11 [dcl.constexpr]p4: 7038 // In the definition of a constexpr constructor [...] 7039 bool Ctor = true; 7040 switch (CSM) { 7041 case Sema::CXXDefaultConstructor: 7042 if (Inherited) 7043 break; 7044 // Since default constructor lookup is essentially trivial (and cannot 7045 // involve, for instance, template instantiation), we compute whether a 7046 // defaulted default constructor is constexpr directly within CXXRecordDecl. 7047 // 7048 // This is important for performance; we need to know whether the default 7049 // constructor is constexpr to determine whether the type is a literal type. 7050 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 7051 7052 case Sema::CXXCopyConstructor: 7053 case Sema::CXXMoveConstructor: 7054 // For copy or move constructors, we need to perform overload resolution. 7055 break; 7056 7057 case Sema::CXXCopyAssignment: 7058 case Sema::CXXMoveAssignment: 7059 if (!S.getLangOpts().CPlusPlus14) 7060 return false; 7061 // In C++1y, we need to perform overload resolution. 7062 Ctor = false; 7063 break; 7064 7065 case Sema::CXXDestructor: 7066 return ClassDecl->defaultedDestructorIsConstexpr(); 7067 7068 case Sema::CXXInvalid: 7069 return false; 7070 } 7071 7072 // -- if the class is a non-empty union, or for each non-empty anonymous 7073 // union member of a non-union class, exactly one non-static data member 7074 // shall be initialized; [DR1359] 7075 // 7076 // If we squint, this is guaranteed, since exactly one non-static data member 7077 // will be initialized (if the constructor isn't deleted), we just don't know 7078 // which one. 7079 if (Ctor && ClassDecl->isUnion()) 7080 return CSM == Sema::CXXDefaultConstructor 7081 ? ClassDecl->hasInClassInitializer() || 7082 !ClassDecl->hasVariantMembers() 7083 : true; 7084 7085 // -- the class shall not have any virtual base classes; 7086 if (Ctor && ClassDecl->getNumVBases()) 7087 return false; 7088 7089 // C++1y [class.copy]p26: 7090 // -- [the class] is a literal type, and 7091 if (!Ctor && !ClassDecl->isLiteral()) 7092 return false; 7093 7094 // -- every constructor involved in initializing [...] base class 7095 // sub-objects shall be a constexpr constructor; 7096 // -- the assignment operator selected to copy/move each direct base 7097 // class is a constexpr function, and 7098 for (const auto &B : ClassDecl->bases()) { 7099 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 7100 if (!BaseType) continue; 7101 7102 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7103 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg, 7104 InheritedCtor, Inherited)) 7105 return false; 7106 } 7107 7108 // -- every constructor involved in initializing non-static data members 7109 // [...] shall be a constexpr constructor; 7110 // -- every non-static data member and base class sub-object shall be 7111 // initialized 7112 // -- for each non-static data member of X that is of class type (or array 7113 // thereof), the assignment operator selected to copy/move that member is 7114 // a constexpr function 7115 for (const auto *F : ClassDecl->fields()) { 7116 if (F->isInvalidDecl()) 7117 continue; 7118 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer()) 7119 continue; 7120 QualType BaseType = S.Context.getBaseElementType(F->getType()); 7121 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 7122 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 7123 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 7124 BaseType.getCVRQualifiers(), 7125 ConstArg && !F->isMutable())) 7126 return false; 7127 } else if (CSM == Sema::CXXDefaultConstructor) { 7128 return false; 7129 } 7130 } 7131 7132 // All OK, it's constexpr! 7133 return true; 7134 } 7135 7136 namespace { 7137 /// RAII object to register a defaulted function as having its exception 7138 /// specification computed. 7139 struct ComputingExceptionSpec { 7140 Sema &S; 7141 7142 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc) 7143 : S(S) { 7144 Sema::CodeSynthesisContext Ctx; 7145 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation; 7146 Ctx.PointOfInstantiation = Loc; 7147 Ctx.Entity = FD; 7148 S.pushCodeSynthesisContext(Ctx); 7149 } 7150 ~ComputingExceptionSpec() { 7151 S.popCodeSynthesisContext(); 7152 } 7153 }; 7154 } 7155 7156 static Sema::ImplicitExceptionSpecification 7157 ComputeDefaultedSpecialMemberExceptionSpec( 7158 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 7159 Sema::InheritedConstructorInfo *ICI); 7160 7161 static Sema::ImplicitExceptionSpecification 7162 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, 7163 FunctionDecl *FD, 7164 Sema::DefaultedComparisonKind DCK); 7165 7166 static Sema::ImplicitExceptionSpecification 7167 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) { 7168 auto DFK = S.getDefaultedFunctionKind(FD); 7169 if (DFK.isSpecialMember()) 7170 return ComputeDefaultedSpecialMemberExceptionSpec( 7171 S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr); 7172 if (DFK.isComparison()) 7173 return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD, 7174 DFK.asComparison()); 7175 7176 auto *CD = cast<CXXConstructorDecl>(FD); 7177 assert(CD->getInheritedConstructor() && 7178 "only defaulted functions and inherited constructors have implicit " 7179 "exception specs"); 7180 Sema::InheritedConstructorInfo ICI( 7181 S, Loc, CD->getInheritedConstructor().getShadowDecl()); 7182 return ComputeDefaultedSpecialMemberExceptionSpec( 7183 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI); 7184 } 7185 7186 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 7187 CXXMethodDecl *MD) { 7188 FunctionProtoType::ExtProtoInfo EPI; 7189 7190 // Build an exception specification pointing back at this member. 7191 EPI.ExceptionSpec.Type = EST_Unevaluated; 7192 EPI.ExceptionSpec.SourceDecl = MD; 7193 7194 // Set the calling convention to the default for C++ instance methods. 7195 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 7196 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 7197 /*IsCXXMethod=*/true)); 7198 return EPI; 7199 } 7200 7201 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) { 7202 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>(); 7203 if (FPT->getExceptionSpecType() != EST_Unevaluated) 7204 return; 7205 7206 // Evaluate the exception specification. 7207 auto IES = computeImplicitExceptionSpec(*this, Loc, FD); 7208 auto ESI = IES.getExceptionSpec(); 7209 7210 // Update the type of the special member to use it. 7211 UpdateExceptionSpec(FD, ESI); 7212 } 7213 7214 void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) { 7215 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted"); 7216 7217 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD); 7218 if (!DefKind) { 7219 assert(FD->getDeclContext()->isDependentContext()); 7220 return; 7221 } 7222 7223 if (DefKind.isSpecialMember() 7224 ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD), 7225 DefKind.asSpecialMember()) 7226 : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison())) 7227 FD->setInvalidDecl(); 7228 } 7229 7230 bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD, 7231 CXXSpecialMember CSM) { 7232 CXXRecordDecl *RD = MD->getParent(); 7233 7234 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 7235 "not an explicitly-defaulted special member"); 7236 7237 // Defer all checking for special members of a dependent type. 7238 if (RD->isDependentType()) 7239 return false; 7240 7241 // Whether this was the first-declared instance of the constructor. 7242 // This affects whether we implicitly add an exception spec and constexpr. 7243 bool First = MD == MD->getCanonicalDecl(); 7244 7245 bool HadError = false; 7246 7247 // C++11 [dcl.fct.def.default]p1: 7248 // A function that is explicitly defaulted shall 7249 // -- be a special member function [...] (checked elsewhere), 7250 // -- have the same type (except for ref-qualifiers, and except that a 7251 // copy operation can take a non-const reference) as an implicit 7252 // declaration, and 7253 // -- not have default arguments. 7254 // C++2a changes the second bullet to instead delete the function if it's 7255 // defaulted on its first declaration, unless it's "an assignment operator, 7256 // and its return type differs or its parameter type is not a reference". 7257 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First; 7258 bool ShouldDeleteForTypeMismatch = false; 7259 unsigned ExpectedParams = 1; 7260 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 7261 ExpectedParams = 0; 7262 if (MD->getNumParams() != ExpectedParams) { 7263 // This checks for default arguments: a copy or move constructor with a 7264 // default argument is classified as a default constructor, and assignment 7265 // operations and destructors can't have default arguments. 7266 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 7267 << CSM << MD->getSourceRange(); 7268 HadError = true; 7269 } else if (MD->isVariadic()) { 7270 if (DeleteOnTypeMismatch) 7271 ShouldDeleteForTypeMismatch = true; 7272 else { 7273 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 7274 << CSM << MD->getSourceRange(); 7275 HadError = true; 7276 } 7277 } 7278 7279 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 7280 7281 bool CanHaveConstParam = false; 7282 if (CSM == CXXCopyConstructor) 7283 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 7284 else if (CSM == CXXCopyAssignment) 7285 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 7286 7287 QualType ReturnType = Context.VoidTy; 7288 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 7289 // Check for return type matching. 7290 ReturnType = Type->getReturnType(); 7291 7292 QualType DeclType = Context.getTypeDeclType(RD); 7293 DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace()); 7294 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType); 7295 7296 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 7297 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 7298 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 7299 HadError = true; 7300 } 7301 7302 // A defaulted special member cannot have cv-qualifiers. 7303 if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) { 7304 if (DeleteOnTypeMismatch) 7305 ShouldDeleteForTypeMismatch = true; 7306 else { 7307 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 7308 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 7309 HadError = true; 7310 } 7311 } 7312 } 7313 7314 // Check for parameter type matching. 7315 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 7316 bool HasConstParam = false; 7317 if (ExpectedParams && ArgType->isReferenceType()) { 7318 // Argument must be reference to possibly-const T. 7319 QualType ReferentType = ArgType->getPointeeType(); 7320 HasConstParam = ReferentType.isConstQualified(); 7321 7322 if (ReferentType.isVolatileQualified()) { 7323 if (DeleteOnTypeMismatch) 7324 ShouldDeleteForTypeMismatch = true; 7325 else { 7326 Diag(MD->getLocation(), 7327 diag::err_defaulted_special_member_volatile_param) << CSM; 7328 HadError = true; 7329 } 7330 } 7331 7332 if (HasConstParam && !CanHaveConstParam) { 7333 if (DeleteOnTypeMismatch) 7334 ShouldDeleteForTypeMismatch = true; 7335 else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 7336 Diag(MD->getLocation(), 7337 diag::err_defaulted_special_member_copy_const_param) 7338 << (CSM == CXXCopyAssignment); 7339 // FIXME: Explain why this special member can't be const. 7340 HadError = true; 7341 } else { 7342 Diag(MD->getLocation(), 7343 diag::err_defaulted_special_member_move_const_param) 7344 << (CSM == CXXMoveAssignment); 7345 HadError = true; 7346 } 7347 } 7348 } else if (ExpectedParams) { 7349 // A copy assignment operator can take its argument by value, but a 7350 // defaulted one cannot. 7351 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 7352 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 7353 HadError = true; 7354 } 7355 7356 // C++11 [dcl.fct.def.default]p2: 7357 // An explicitly-defaulted function may be declared constexpr only if it 7358 // would have been implicitly declared as constexpr, 7359 // Do not apply this rule to members of class templates, since core issue 1358 7360 // makes such functions always instantiate to constexpr functions. For 7361 // functions which cannot be constexpr (for non-constructors in C++11 and for 7362 // destructors in C++14 and C++17), this is checked elsewhere. 7363 // 7364 // FIXME: This should not apply if the member is deleted. 7365 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 7366 HasConstParam); 7367 if ((getLangOpts().CPlusPlus20 || 7368 (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 7369 : isa<CXXConstructorDecl>(MD))) && 7370 MD->isConstexpr() && !Constexpr && 7371 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 7372 Diag(MD->getBeginLoc(), MD->isConsteval() 7373 ? diag::err_incorrect_defaulted_consteval 7374 : diag::err_incorrect_defaulted_constexpr) 7375 << CSM; 7376 // FIXME: Explain why the special member can't be constexpr. 7377 HadError = true; 7378 } 7379 7380 if (First) { 7381 // C++2a [dcl.fct.def.default]p3: 7382 // If a function is explicitly defaulted on its first declaration, it is 7383 // implicitly considered to be constexpr if the implicit declaration 7384 // would be. 7385 MD->setConstexprKind(Constexpr ? (MD->isConsteval() 7386 ? ConstexprSpecKind::Consteval 7387 : ConstexprSpecKind::Constexpr) 7388 : ConstexprSpecKind::Unspecified); 7389 7390 if (!Type->hasExceptionSpec()) { 7391 // C++2a [except.spec]p3: 7392 // If a declaration of a function does not have a noexcept-specifier 7393 // [and] is defaulted on its first declaration, [...] the exception 7394 // specification is as specified below 7395 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 7396 EPI.ExceptionSpec.Type = EST_Unevaluated; 7397 EPI.ExceptionSpec.SourceDecl = MD; 7398 MD->setType(Context.getFunctionType(ReturnType, 7399 llvm::makeArrayRef(&ArgType, 7400 ExpectedParams), 7401 EPI)); 7402 } 7403 } 7404 7405 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) { 7406 if (First) { 7407 SetDeclDeleted(MD, MD->getLocation()); 7408 if (!inTemplateInstantiation() && !HadError) { 7409 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM; 7410 if (ShouldDeleteForTypeMismatch) { 7411 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM; 7412 } else { 7413 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 7414 } 7415 } 7416 if (ShouldDeleteForTypeMismatch && !HadError) { 7417 Diag(MD->getLocation(), 7418 diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM; 7419 } 7420 } else { 7421 // C++11 [dcl.fct.def.default]p4: 7422 // [For a] user-provided explicitly-defaulted function [...] if such a 7423 // function is implicitly defined as deleted, the program is ill-formed. 7424 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 7425 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl"); 7426 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 7427 HadError = true; 7428 } 7429 } 7430 7431 return HadError; 7432 } 7433 7434 namespace { 7435 /// Helper class for building and checking a defaulted comparison. 7436 /// 7437 /// Defaulted functions are built in two phases: 7438 /// 7439 /// * First, the set of operations that the function will perform are 7440 /// identified, and some of them are checked. If any of the checked 7441 /// operations is invalid in certain ways, the comparison function is 7442 /// defined as deleted and no body is built. 7443 /// * Then, if the function is not defined as deleted, the body is built. 7444 /// 7445 /// This is accomplished by performing two visitation steps over the eventual 7446 /// body of the function. 7447 template<typename Derived, typename ResultList, typename Result, 7448 typename Subobject> 7449 class DefaultedComparisonVisitor { 7450 public: 7451 using DefaultedComparisonKind = Sema::DefaultedComparisonKind; 7452 7453 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7454 DefaultedComparisonKind DCK) 7455 : S(S), RD(RD), FD(FD), DCK(DCK) { 7456 if (auto *Info = FD->getDefaultedFunctionInfo()) { 7457 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an 7458 // UnresolvedSet to avoid this copy. 7459 Fns.assign(Info->getUnqualifiedLookups().begin(), 7460 Info->getUnqualifiedLookups().end()); 7461 } 7462 } 7463 7464 ResultList visit() { 7465 // The type of an lvalue naming a parameter of this function. 7466 QualType ParamLvalType = 7467 FD->getParamDecl(0)->getType().getNonReferenceType(); 7468 7469 ResultList Results; 7470 7471 switch (DCK) { 7472 case DefaultedComparisonKind::None: 7473 llvm_unreachable("not a defaulted comparison"); 7474 7475 case DefaultedComparisonKind::Equal: 7476 case DefaultedComparisonKind::ThreeWay: 7477 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers()); 7478 return Results; 7479 7480 case DefaultedComparisonKind::NotEqual: 7481 case DefaultedComparisonKind::Relational: 7482 Results.add(getDerived().visitExpandedSubobject( 7483 ParamLvalType, getDerived().getCompleteObject())); 7484 return Results; 7485 } 7486 llvm_unreachable(""); 7487 } 7488 7489 protected: 7490 Derived &getDerived() { return static_cast<Derived&>(*this); } 7491 7492 /// Visit the expanded list of subobjects of the given type, as specified in 7493 /// C++2a [class.compare.default]. 7494 /// 7495 /// \return \c true if the ResultList object said we're done, \c false if not. 7496 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record, 7497 Qualifiers Quals) { 7498 // C++2a [class.compare.default]p4: 7499 // The direct base class subobjects of C 7500 for (CXXBaseSpecifier &Base : Record->bases()) 7501 if (Results.add(getDerived().visitSubobject( 7502 S.Context.getQualifiedType(Base.getType(), Quals), 7503 getDerived().getBase(&Base)))) 7504 return true; 7505 7506 // followed by the non-static data members of C 7507 for (FieldDecl *Field : Record->fields()) { 7508 // Recursively expand anonymous structs. 7509 if (Field->isAnonymousStructOrUnion()) { 7510 if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(), 7511 Quals)) 7512 return true; 7513 continue; 7514 } 7515 7516 // Figure out the type of an lvalue denoting this field. 7517 Qualifiers FieldQuals = Quals; 7518 if (Field->isMutable()) 7519 FieldQuals.removeConst(); 7520 QualType FieldType = 7521 S.Context.getQualifiedType(Field->getType(), FieldQuals); 7522 7523 if (Results.add(getDerived().visitSubobject( 7524 FieldType, getDerived().getField(Field)))) 7525 return true; 7526 } 7527 7528 // form a list of subobjects. 7529 return false; 7530 } 7531 7532 Result visitSubobject(QualType Type, Subobject Subobj) { 7533 // In that list, any subobject of array type is recursively expanded 7534 const ArrayType *AT = S.Context.getAsArrayType(Type); 7535 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT)) 7536 return getDerived().visitSubobjectArray(CAT->getElementType(), 7537 CAT->getSize(), Subobj); 7538 return getDerived().visitExpandedSubobject(Type, Subobj); 7539 } 7540 7541 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size, 7542 Subobject Subobj) { 7543 return getDerived().visitSubobject(Type, Subobj); 7544 } 7545 7546 protected: 7547 Sema &S; 7548 CXXRecordDecl *RD; 7549 FunctionDecl *FD; 7550 DefaultedComparisonKind DCK; 7551 UnresolvedSet<16> Fns; 7552 }; 7553 7554 /// Information about a defaulted comparison, as determined by 7555 /// DefaultedComparisonAnalyzer. 7556 struct DefaultedComparisonInfo { 7557 bool Deleted = false; 7558 bool Constexpr = true; 7559 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering; 7560 7561 static DefaultedComparisonInfo deleted() { 7562 DefaultedComparisonInfo Deleted; 7563 Deleted.Deleted = true; 7564 return Deleted; 7565 } 7566 7567 bool add(const DefaultedComparisonInfo &R) { 7568 Deleted |= R.Deleted; 7569 Constexpr &= R.Constexpr; 7570 Category = commonComparisonType(Category, R.Category); 7571 return Deleted; 7572 } 7573 }; 7574 7575 /// An element in the expanded list of subobjects of a defaulted comparison, as 7576 /// specified in C++2a [class.compare.default]p4. 7577 struct DefaultedComparisonSubobject { 7578 enum { CompleteObject, Member, Base } Kind; 7579 NamedDecl *Decl; 7580 SourceLocation Loc; 7581 }; 7582 7583 /// A visitor over the notional body of a defaulted comparison that determines 7584 /// whether that body would be deleted or constexpr. 7585 class DefaultedComparisonAnalyzer 7586 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer, 7587 DefaultedComparisonInfo, 7588 DefaultedComparisonInfo, 7589 DefaultedComparisonSubobject> { 7590 public: 7591 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr }; 7592 7593 private: 7594 DiagnosticKind Diagnose; 7595 7596 public: 7597 using Base = DefaultedComparisonVisitor; 7598 using Result = DefaultedComparisonInfo; 7599 using Subobject = DefaultedComparisonSubobject; 7600 7601 friend Base; 7602 7603 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7604 DefaultedComparisonKind DCK, 7605 DiagnosticKind Diagnose = NoDiagnostics) 7606 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {} 7607 7608 Result visit() { 7609 if ((DCK == DefaultedComparisonKind::Equal || 7610 DCK == DefaultedComparisonKind::ThreeWay) && 7611 RD->hasVariantMembers()) { 7612 // C++2a [class.compare.default]p2 [P2002R0]: 7613 // A defaulted comparison operator function for class C is defined as 7614 // deleted if [...] C has variant members. 7615 if (Diagnose == ExplainDeleted) { 7616 S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union) 7617 << FD << RD->isUnion() << RD; 7618 } 7619 return Result::deleted(); 7620 } 7621 7622 return Base::visit(); 7623 } 7624 7625 private: 7626 Subobject getCompleteObject() { 7627 return Subobject{Subobject::CompleteObject, nullptr, FD->getLocation()}; 7628 } 7629 7630 Subobject getBase(CXXBaseSpecifier *Base) { 7631 return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(), 7632 Base->getBaseTypeLoc()}; 7633 } 7634 7635 Subobject getField(FieldDecl *Field) { 7636 return Subobject{Subobject::Member, Field, Field->getLocation()}; 7637 } 7638 7639 Result visitExpandedSubobject(QualType Type, Subobject Subobj) { 7640 // C++2a [class.compare.default]p2 [P2002R0]: 7641 // A defaulted <=> or == operator function for class C is defined as 7642 // deleted if any non-static data member of C is of reference type 7643 if (Type->isReferenceType()) { 7644 if (Diagnose == ExplainDeleted) { 7645 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member) 7646 << FD << RD; 7647 } 7648 return Result::deleted(); 7649 } 7650 7651 // [...] Let xi be an lvalue denoting the ith element [...] 7652 OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue); 7653 Expr *Args[] = {&Xi, &Xi}; 7654 7655 // All operators start by trying to apply that same operator recursively. 7656 OverloadedOperatorKind OO = FD->getOverloadedOperator(); 7657 assert(OO != OO_None && "not an overloaded operator!"); 7658 return visitBinaryOperator(OO, Args, Subobj); 7659 } 7660 7661 Result 7662 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args, 7663 Subobject Subobj, 7664 OverloadCandidateSet *SpaceshipCandidates = nullptr) { 7665 // Note that there is no need to consider rewritten candidates here if 7666 // we've already found there is no viable 'operator<=>' candidate (and are 7667 // considering synthesizing a '<=>' from '==' and '<'). 7668 OverloadCandidateSet CandidateSet( 7669 FD->getLocation(), OverloadCandidateSet::CSK_Operator, 7670 OverloadCandidateSet::OperatorRewriteInfo( 7671 OO, /*AllowRewrittenCandidates=*/!SpaceshipCandidates)); 7672 7673 /// C++2a [class.compare.default]p1 [P2002R0]: 7674 /// [...] the defaulted function itself is never a candidate for overload 7675 /// resolution [...] 7676 CandidateSet.exclude(FD); 7677 7678 if (Args[0]->getType()->isOverloadableType()) 7679 S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args); 7680 else { 7681 // FIXME: We determine whether this is a valid expression by checking to 7682 // see if there's a viable builtin operator candidate for it. That isn't 7683 // really what the rules ask us to do, but should give the right results. 7684 S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet); 7685 } 7686 7687 Result R; 7688 7689 OverloadCandidateSet::iterator Best; 7690 switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) { 7691 case OR_Success: { 7692 // C++2a [class.compare.secondary]p2 [P2002R0]: 7693 // The operator function [...] is defined as deleted if [...] the 7694 // candidate selected by overload resolution is not a rewritten 7695 // candidate. 7696 if ((DCK == DefaultedComparisonKind::NotEqual || 7697 DCK == DefaultedComparisonKind::Relational) && 7698 !Best->RewriteKind) { 7699 if (Diagnose == ExplainDeleted) { 7700 S.Diag(Best->Function->getLocation(), 7701 diag::note_defaulted_comparison_not_rewritten_callee) 7702 << FD; 7703 } 7704 return Result::deleted(); 7705 } 7706 7707 // Throughout C++2a [class.compare]: if overload resolution does not 7708 // result in a usable function, the candidate function is defined as 7709 // deleted. This requires that we selected an accessible function. 7710 // 7711 // Note that this only considers the access of the function when named 7712 // within the type of the subobject, and not the access path for any 7713 // derived-to-base conversion. 7714 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl(); 7715 if (ArgClass && Best->FoundDecl.getDecl() && 7716 Best->FoundDecl.getDecl()->isCXXClassMember()) { 7717 QualType ObjectType = Subobj.Kind == Subobject::Member 7718 ? Args[0]->getType() 7719 : S.Context.getRecordType(RD); 7720 if (!S.isMemberAccessibleForDeletion( 7721 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc, 7722 Diagnose == ExplainDeleted 7723 ? S.PDiag(diag::note_defaulted_comparison_inaccessible) 7724 << FD << Subobj.Kind << Subobj.Decl 7725 : S.PDiag())) 7726 return Result::deleted(); 7727 } 7728 7729 // C++2a [class.compare.default]p3 [P2002R0]: 7730 // A defaulted comparison function is constexpr-compatible if [...] 7731 // no overlod resolution performed [...] results in a non-constexpr 7732 // function. 7733 if (FunctionDecl *BestFD = Best->Function) { 7734 assert(!BestFD->isDeleted() && "wrong overload resolution result"); 7735 // If it's not constexpr, explain why not. 7736 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) { 7737 if (Subobj.Kind != Subobject::CompleteObject) 7738 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr) 7739 << Subobj.Kind << Subobj.Decl; 7740 S.Diag(BestFD->getLocation(), 7741 diag::note_defaulted_comparison_not_constexpr_here); 7742 // Bail out after explaining; we don't want any more notes. 7743 return Result::deleted(); 7744 } 7745 R.Constexpr &= BestFD->isConstexpr(); 7746 } 7747 7748 if (OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType()) { 7749 if (auto *BestFD = Best->Function) { 7750 // If any callee has an undeduced return type, deduce it now. 7751 // FIXME: It's not clear how a failure here should be handled. For 7752 // now, we produce an eager diagnostic, because that is forward 7753 // compatible with most (all?) other reasonable options. 7754 if (BestFD->getReturnType()->isUndeducedType() && 7755 S.DeduceReturnType(BestFD, FD->getLocation(), 7756 /*Diagnose=*/false)) { 7757 // Don't produce a duplicate error when asked to explain why the 7758 // comparison is deleted: we diagnosed that when initially checking 7759 // the defaulted operator. 7760 if (Diagnose == NoDiagnostics) { 7761 S.Diag( 7762 FD->getLocation(), 7763 diag::err_defaulted_comparison_cannot_deduce_undeduced_auto) 7764 << Subobj.Kind << Subobj.Decl; 7765 S.Diag( 7766 Subobj.Loc, 7767 diag::note_defaulted_comparison_cannot_deduce_undeduced_auto) 7768 << Subobj.Kind << Subobj.Decl; 7769 S.Diag(BestFD->getLocation(), 7770 diag::note_defaulted_comparison_cannot_deduce_callee) 7771 << Subobj.Kind << Subobj.Decl; 7772 } 7773 return Result::deleted(); 7774 } 7775 if (auto *Info = S.Context.CompCategories.lookupInfoForType( 7776 BestFD->getCallResultType())) { 7777 R.Category = Info->Kind; 7778 } else { 7779 if (Diagnose == ExplainDeleted) { 7780 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce) 7781 << Subobj.Kind << Subobj.Decl 7782 << BestFD->getCallResultType().withoutLocalFastQualifiers(); 7783 S.Diag(BestFD->getLocation(), 7784 diag::note_defaulted_comparison_cannot_deduce_callee) 7785 << Subobj.Kind << Subobj.Decl; 7786 } 7787 return Result::deleted(); 7788 } 7789 } else { 7790 Optional<ComparisonCategoryType> Cat = 7791 getComparisonCategoryForBuiltinCmp(Args[0]->getType()); 7792 assert(Cat && "no category for builtin comparison?"); 7793 R.Category = *Cat; 7794 } 7795 } 7796 7797 // Note that we might be rewriting to a different operator. That call is 7798 // not considered until we come to actually build the comparison function. 7799 break; 7800 } 7801 7802 case OR_Ambiguous: 7803 if (Diagnose == ExplainDeleted) { 7804 unsigned Kind = 0; 7805 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship) 7806 Kind = OO == OO_EqualEqual ? 1 : 2; 7807 CandidateSet.NoteCandidates( 7808 PartialDiagnosticAt( 7809 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous) 7810 << FD << Kind << Subobj.Kind << Subobj.Decl), 7811 S, OCD_AmbiguousCandidates, Args); 7812 } 7813 R = Result::deleted(); 7814 break; 7815 7816 case OR_Deleted: 7817 if (Diagnose == ExplainDeleted) { 7818 if ((DCK == DefaultedComparisonKind::NotEqual || 7819 DCK == DefaultedComparisonKind::Relational) && 7820 !Best->RewriteKind) { 7821 S.Diag(Best->Function->getLocation(), 7822 diag::note_defaulted_comparison_not_rewritten_callee) 7823 << FD; 7824 } else { 7825 S.Diag(Subobj.Loc, 7826 diag::note_defaulted_comparison_calls_deleted) 7827 << FD << Subobj.Kind << Subobj.Decl; 7828 S.NoteDeletedFunction(Best->Function); 7829 } 7830 } 7831 R = Result::deleted(); 7832 break; 7833 7834 case OR_No_Viable_Function: 7835 // If there's no usable candidate, we're done unless we can rewrite a 7836 // '<=>' in terms of '==' and '<'. 7837 if (OO == OO_Spaceship && 7838 S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) { 7839 // For any kind of comparison category return type, we need a usable 7840 // '==' and a usable '<'. 7841 if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj, 7842 &CandidateSet))) 7843 R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet)); 7844 break; 7845 } 7846 7847 if (Diagnose == ExplainDeleted) { 7848 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function) 7849 << FD << Subobj.Kind << Subobj.Decl; 7850 7851 // For a three-way comparison, list both the candidates for the 7852 // original operator and the candidates for the synthesized operator. 7853 if (SpaceshipCandidates) { 7854 SpaceshipCandidates->NoteCandidates( 7855 S, Args, 7856 SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates, 7857 Args, FD->getLocation())); 7858 S.Diag(Subobj.Loc, 7859 diag::note_defaulted_comparison_no_viable_function_synthesized) 7860 << (OO == OO_EqualEqual ? 0 : 1); 7861 } 7862 7863 CandidateSet.NoteCandidates( 7864 S, Args, 7865 CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args, 7866 FD->getLocation())); 7867 } 7868 R = Result::deleted(); 7869 break; 7870 } 7871 7872 return R; 7873 } 7874 }; 7875 7876 /// A list of statements. 7877 struct StmtListResult { 7878 bool IsInvalid = false; 7879 llvm::SmallVector<Stmt*, 16> Stmts; 7880 7881 bool add(const StmtResult &S) { 7882 IsInvalid |= S.isInvalid(); 7883 if (IsInvalid) 7884 return true; 7885 Stmts.push_back(S.get()); 7886 return false; 7887 } 7888 }; 7889 7890 /// A visitor over the notional body of a defaulted comparison that synthesizes 7891 /// the actual body. 7892 class DefaultedComparisonSynthesizer 7893 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer, 7894 StmtListResult, StmtResult, 7895 std::pair<ExprResult, ExprResult>> { 7896 SourceLocation Loc; 7897 unsigned ArrayDepth = 0; 7898 7899 public: 7900 using Base = DefaultedComparisonVisitor; 7901 using ExprPair = std::pair<ExprResult, ExprResult>; 7902 7903 friend Base; 7904 7905 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7906 DefaultedComparisonKind DCK, 7907 SourceLocation BodyLoc) 7908 : Base(S, RD, FD, DCK), Loc(BodyLoc) {} 7909 7910 /// Build a suitable function body for this defaulted comparison operator. 7911 StmtResult build() { 7912 Sema::CompoundScopeRAII CompoundScope(S); 7913 7914 StmtListResult Stmts = visit(); 7915 if (Stmts.IsInvalid) 7916 return StmtError(); 7917 7918 ExprResult RetVal; 7919 switch (DCK) { 7920 case DefaultedComparisonKind::None: 7921 llvm_unreachable("not a defaulted comparison"); 7922 7923 case DefaultedComparisonKind::Equal: { 7924 // C++2a [class.eq]p3: 7925 // [...] compar[e] the corresponding elements [...] until the first 7926 // index i where xi == yi yields [...] false. If no such index exists, 7927 // V is true. Otherwise, V is false. 7928 // 7929 // Join the comparisons with '&&'s and return the result. Use a right 7930 // fold (traversing the conditions right-to-left), because that 7931 // short-circuits more naturally. 7932 auto OldStmts = std::move(Stmts.Stmts); 7933 Stmts.Stmts.clear(); 7934 ExprResult CmpSoFar; 7935 // Finish a particular comparison chain. 7936 auto FinishCmp = [&] { 7937 if (Expr *Prior = CmpSoFar.get()) { 7938 // Convert the last expression to 'return ...;' 7939 if (RetVal.isUnset() && Stmts.Stmts.empty()) 7940 RetVal = CmpSoFar; 7941 // Convert any prior comparison to 'if (!(...)) return false;' 7942 else if (Stmts.add(buildIfNotCondReturnFalse(Prior))) 7943 return true; 7944 CmpSoFar = ExprResult(); 7945 } 7946 return false; 7947 }; 7948 for (Stmt *EAsStmt : llvm::reverse(OldStmts)) { 7949 Expr *E = dyn_cast<Expr>(EAsStmt); 7950 if (!E) { 7951 // Found an array comparison. 7952 if (FinishCmp() || Stmts.add(EAsStmt)) 7953 return StmtError(); 7954 continue; 7955 } 7956 7957 if (CmpSoFar.isUnset()) { 7958 CmpSoFar = E; 7959 continue; 7960 } 7961 CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get()); 7962 if (CmpSoFar.isInvalid()) 7963 return StmtError(); 7964 } 7965 if (FinishCmp()) 7966 return StmtError(); 7967 std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end()); 7968 // If no such index exists, V is true. 7969 if (RetVal.isUnset()) 7970 RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true); 7971 break; 7972 } 7973 7974 case DefaultedComparisonKind::ThreeWay: { 7975 // Per C++2a [class.spaceship]p3, as a fallback add: 7976 // return static_cast<R>(std::strong_ordering::equal); 7977 QualType StrongOrdering = S.CheckComparisonCategoryType( 7978 ComparisonCategoryType::StrongOrdering, Loc, 7979 Sema::ComparisonCategoryUsage::DefaultedOperator); 7980 if (StrongOrdering.isNull()) 7981 return StmtError(); 7982 VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering) 7983 .getValueInfo(ComparisonCategoryResult::Equal) 7984 ->VD; 7985 RetVal = getDecl(EqualVD); 7986 if (RetVal.isInvalid()) 7987 return StmtError(); 7988 RetVal = buildStaticCastToR(RetVal.get()); 7989 break; 7990 } 7991 7992 case DefaultedComparisonKind::NotEqual: 7993 case DefaultedComparisonKind::Relational: 7994 RetVal = cast<Expr>(Stmts.Stmts.pop_back_val()); 7995 break; 7996 } 7997 7998 // Build the final return statement. 7999 if (RetVal.isInvalid()) 8000 return StmtError(); 8001 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get()); 8002 if (ReturnStmt.isInvalid()) 8003 return StmtError(); 8004 Stmts.Stmts.push_back(ReturnStmt.get()); 8005 8006 return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false); 8007 } 8008 8009 private: 8010 ExprResult getDecl(ValueDecl *VD) { 8011 return S.BuildDeclarationNameExpr( 8012 CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD); 8013 } 8014 8015 ExprResult getParam(unsigned I) { 8016 ParmVarDecl *PD = FD->getParamDecl(I); 8017 return getDecl(PD); 8018 } 8019 8020 ExprPair getCompleteObject() { 8021 unsigned Param = 0; 8022 ExprResult LHS; 8023 if (isa<CXXMethodDecl>(FD)) { 8024 // LHS is '*this'. 8025 LHS = S.ActOnCXXThis(Loc); 8026 if (!LHS.isInvalid()) 8027 LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get()); 8028 } else { 8029 LHS = getParam(Param++); 8030 } 8031 ExprResult RHS = getParam(Param++); 8032 assert(Param == FD->getNumParams()); 8033 return {LHS, RHS}; 8034 } 8035 8036 ExprPair getBase(CXXBaseSpecifier *Base) { 8037 ExprPair Obj = getCompleteObject(); 8038 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 8039 return {ExprError(), ExprError()}; 8040 CXXCastPath Path = {Base}; 8041 return {S.ImpCastExprToType(Obj.first.get(), Base->getType(), 8042 CK_DerivedToBase, VK_LValue, &Path), 8043 S.ImpCastExprToType(Obj.second.get(), Base->getType(), 8044 CK_DerivedToBase, VK_LValue, &Path)}; 8045 } 8046 8047 ExprPair getField(FieldDecl *Field) { 8048 ExprPair Obj = getCompleteObject(); 8049 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 8050 return {ExprError(), ExprError()}; 8051 8052 DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess()); 8053 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc); 8054 return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc, 8055 CXXScopeSpec(), Field, Found, NameInfo), 8056 S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc, 8057 CXXScopeSpec(), Field, Found, NameInfo)}; 8058 } 8059 8060 // FIXME: When expanding a subobject, register a note in the code synthesis 8061 // stack to say which subobject we're comparing. 8062 8063 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) { 8064 if (Cond.isInvalid()) 8065 return StmtError(); 8066 8067 ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get()); 8068 if (NotCond.isInvalid()) 8069 return StmtError(); 8070 8071 ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false); 8072 assert(!False.isInvalid() && "should never fail"); 8073 StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get()); 8074 if (ReturnFalse.isInvalid()) 8075 return StmtError(); 8076 8077 return S.ActOnIfStmt(Loc, false, Loc, nullptr, 8078 S.ActOnCondition(nullptr, Loc, NotCond.get(), 8079 Sema::ConditionKind::Boolean), 8080 Loc, ReturnFalse.get(), SourceLocation(), nullptr); 8081 } 8082 8083 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size, 8084 ExprPair Subobj) { 8085 QualType SizeType = S.Context.getSizeType(); 8086 Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType)); 8087 8088 // Build 'size_t i$n = 0'. 8089 IdentifierInfo *IterationVarName = nullptr; 8090 { 8091 SmallString<8> Str; 8092 llvm::raw_svector_ostream OS(Str); 8093 OS << "i" << ArrayDepth; 8094 IterationVarName = &S.Context.Idents.get(OS.str()); 8095 } 8096 VarDecl *IterationVar = VarDecl::Create( 8097 S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType, 8098 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None); 8099 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 8100 IterationVar->setInit( 8101 IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 8102 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc); 8103 8104 auto IterRef = [&] { 8105 ExprResult Ref = S.BuildDeclarationNameExpr( 8106 CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc), 8107 IterationVar); 8108 assert(!Ref.isInvalid() && "can't reference our own variable?"); 8109 return Ref.get(); 8110 }; 8111 8112 // Build 'i$n != Size'. 8113 ExprResult Cond = S.CreateBuiltinBinOp( 8114 Loc, BO_NE, IterRef(), 8115 IntegerLiteral::Create(S.Context, Size, SizeType, Loc)); 8116 assert(!Cond.isInvalid() && "should never fail"); 8117 8118 // Build '++i$n'. 8119 ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef()); 8120 assert(!Inc.isInvalid() && "should never fail"); 8121 8122 // Build 'a[i$n]' and 'b[i$n]'. 8123 auto Index = [&](ExprResult E) { 8124 if (E.isInvalid()) 8125 return ExprError(); 8126 return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc); 8127 }; 8128 Subobj.first = Index(Subobj.first); 8129 Subobj.second = Index(Subobj.second); 8130 8131 // Compare the array elements. 8132 ++ArrayDepth; 8133 StmtResult Substmt = visitSubobject(Type, Subobj); 8134 --ArrayDepth; 8135 8136 if (Substmt.isInvalid()) 8137 return StmtError(); 8138 8139 // For the inner level of an 'operator==', build 'if (!cmp) return false;'. 8140 // For outer levels or for an 'operator<=>' we already have a suitable 8141 // statement that returns as necessary. 8142 if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) { 8143 assert(DCK == DefaultedComparisonKind::Equal && 8144 "should have non-expression statement"); 8145 Substmt = buildIfNotCondReturnFalse(ElemCmp); 8146 if (Substmt.isInvalid()) 8147 return StmtError(); 8148 } 8149 8150 // Build 'for (...) ...' 8151 return S.ActOnForStmt(Loc, Loc, Init, 8152 S.ActOnCondition(nullptr, Loc, Cond.get(), 8153 Sema::ConditionKind::Boolean), 8154 S.MakeFullDiscardedValueExpr(Inc.get()), Loc, 8155 Substmt.get()); 8156 } 8157 8158 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) { 8159 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 8160 return StmtError(); 8161 8162 OverloadedOperatorKind OO = FD->getOverloadedOperator(); 8163 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO); 8164 ExprResult Op; 8165 if (Type->isOverloadableType()) 8166 Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(), 8167 Obj.second.get(), /*PerformADL=*/true, 8168 /*AllowRewrittenCandidates=*/true, FD); 8169 else 8170 Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get()); 8171 if (Op.isInvalid()) 8172 return StmtError(); 8173 8174 switch (DCK) { 8175 case DefaultedComparisonKind::None: 8176 llvm_unreachable("not a defaulted comparison"); 8177 8178 case DefaultedComparisonKind::Equal: 8179 // Per C++2a [class.eq]p2, each comparison is individually contextually 8180 // converted to bool. 8181 Op = S.PerformContextuallyConvertToBool(Op.get()); 8182 if (Op.isInvalid()) 8183 return StmtError(); 8184 return Op.get(); 8185 8186 case DefaultedComparisonKind::ThreeWay: { 8187 // Per C++2a [class.spaceship]p3, form: 8188 // if (R cmp = static_cast<R>(op); cmp != 0) 8189 // return cmp; 8190 QualType R = FD->getReturnType(); 8191 Op = buildStaticCastToR(Op.get()); 8192 if (Op.isInvalid()) 8193 return StmtError(); 8194 8195 // R cmp = ...; 8196 IdentifierInfo *Name = &S.Context.Idents.get("cmp"); 8197 VarDecl *VD = 8198 VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R, 8199 S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None); 8200 S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false); 8201 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc); 8202 8203 // cmp != 0 8204 ExprResult VDRef = getDecl(VD); 8205 if (VDRef.isInvalid()) 8206 return StmtError(); 8207 llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0); 8208 Expr *Zero = 8209 IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc); 8210 ExprResult Comp; 8211 if (VDRef.get()->getType()->isOverloadableType()) 8212 Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true, 8213 true, FD); 8214 else 8215 Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero); 8216 if (Comp.isInvalid()) 8217 return StmtError(); 8218 Sema::ConditionResult Cond = S.ActOnCondition( 8219 nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean); 8220 if (Cond.isInvalid()) 8221 return StmtError(); 8222 8223 // return cmp; 8224 VDRef = getDecl(VD); 8225 if (VDRef.isInvalid()) 8226 return StmtError(); 8227 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get()); 8228 if (ReturnStmt.isInvalid()) 8229 return StmtError(); 8230 8231 // if (...) 8232 return S.ActOnIfStmt(Loc, /*IsConstexpr=*/false, Loc, InitStmt, Cond, Loc, 8233 ReturnStmt.get(), 8234 /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr); 8235 } 8236 8237 case DefaultedComparisonKind::NotEqual: 8238 case DefaultedComparisonKind::Relational: 8239 // C++2a [class.compare.secondary]p2: 8240 // Otherwise, the operator function yields x @ y. 8241 return Op.get(); 8242 } 8243 llvm_unreachable(""); 8244 } 8245 8246 /// Build "static_cast<R>(E)". 8247 ExprResult buildStaticCastToR(Expr *E) { 8248 QualType R = FD->getReturnType(); 8249 assert(!R->isUndeducedType() && "type should have been deduced already"); 8250 8251 // Don't bother forming a no-op cast in the common case. 8252 if (E->isRValue() && S.Context.hasSameType(E->getType(), R)) 8253 return E; 8254 return S.BuildCXXNamedCast(Loc, tok::kw_static_cast, 8255 S.Context.getTrivialTypeSourceInfo(R, Loc), E, 8256 SourceRange(Loc, Loc), SourceRange(Loc, Loc)); 8257 } 8258 }; 8259 } 8260 8261 /// Perform the unqualified lookups that might be needed to form a defaulted 8262 /// comparison function for the given operator. 8263 static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S, 8264 UnresolvedSetImpl &Operators, 8265 OverloadedOperatorKind Op) { 8266 auto Lookup = [&](OverloadedOperatorKind OO) { 8267 Self.LookupOverloadedOperatorName(OO, S, Operators); 8268 }; 8269 8270 // Every defaulted operator looks up itself. 8271 Lookup(Op); 8272 // ... and the rewritten form of itself, if any. 8273 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op)) 8274 Lookup(ExtraOp); 8275 8276 // For 'operator<=>', we also form a 'cmp != 0' expression, and might 8277 // synthesize a three-way comparison from '<' and '=='. In a dependent 8278 // context, we also need to look up '==' in case we implicitly declare a 8279 // defaulted 'operator=='. 8280 if (Op == OO_Spaceship) { 8281 Lookup(OO_ExclaimEqual); 8282 Lookup(OO_Less); 8283 Lookup(OO_EqualEqual); 8284 } 8285 } 8286 8287 bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD, 8288 DefaultedComparisonKind DCK) { 8289 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison"); 8290 8291 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()); 8292 assert(RD && "defaulted comparison is not defaulted in a class"); 8293 8294 // Perform any unqualified lookups we're going to need to default this 8295 // function. 8296 if (S) { 8297 UnresolvedSet<32> Operators; 8298 lookupOperatorsForDefaultedComparison(*this, S, Operators, 8299 FD->getOverloadedOperator()); 8300 FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create( 8301 Context, Operators.pairs())); 8302 } 8303 8304 // C++2a [class.compare.default]p1: 8305 // A defaulted comparison operator function for some class C shall be a 8306 // non-template function declared in the member-specification of C that is 8307 // -- a non-static const member of C having one parameter of type 8308 // const C&, or 8309 // -- a friend of C having two parameters of type const C& or two 8310 // parameters of type C. 8311 QualType ExpectedParmType1 = Context.getRecordType(RD); 8312 QualType ExpectedParmType2 = 8313 Context.getLValueReferenceType(ExpectedParmType1.withConst()); 8314 if (isa<CXXMethodDecl>(FD)) 8315 ExpectedParmType1 = ExpectedParmType2; 8316 for (const ParmVarDecl *Param : FD->parameters()) { 8317 if (!Param->getType()->isDependentType() && 8318 !Context.hasSameType(Param->getType(), ExpectedParmType1) && 8319 !Context.hasSameType(Param->getType(), ExpectedParmType2)) { 8320 // Don't diagnose an implicit 'operator=='; we will have diagnosed the 8321 // corresponding defaulted 'operator<=>' already. 8322 if (!FD->isImplicit()) { 8323 Diag(FD->getLocation(), diag::err_defaulted_comparison_param) 8324 << (int)DCK << Param->getType() << ExpectedParmType1 8325 << !isa<CXXMethodDecl>(FD) 8326 << ExpectedParmType2 << Param->getSourceRange(); 8327 } 8328 return true; 8329 } 8330 } 8331 if (FD->getNumParams() == 2 && 8332 !Context.hasSameType(FD->getParamDecl(0)->getType(), 8333 FD->getParamDecl(1)->getType())) { 8334 if (!FD->isImplicit()) { 8335 Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch) 8336 << (int)DCK 8337 << FD->getParamDecl(0)->getType() 8338 << FD->getParamDecl(0)->getSourceRange() 8339 << FD->getParamDecl(1)->getType() 8340 << FD->getParamDecl(1)->getSourceRange(); 8341 } 8342 return true; 8343 } 8344 8345 // ... non-static const member ... 8346 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 8347 assert(!MD->isStatic() && "comparison function cannot be a static member"); 8348 if (!MD->isConst()) { 8349 SourceLocation InsertLoc; 8350 if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc()) 8351 InsertLoc = getLocForEndOfToken(Loc.getRParenLoc()); 8352 // Don't diagnose an implicit 'operator=='; we will have diagnosed the 8353 // corresponding defaulted 'operator<=>' already. 8354 if (!MD->isImplicit()) { 8355 Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const) 8356 << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const"); 8357 } 8358 8359 // Add the 'const' to the type to recover. 8360 const auto *FPT = MD->getType()->castAs<FunctionProtoType>(); 8361 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8362 EPI.TypeQuals.addConst(); 8363 MD->setType(Context.getFunctionType(FPT->getReturnType(), 8364 FPT->getParamTypes(), EPI)); 8365 } 8366 } else { 8367 // A non-member function declared in a class must be a friend. 8368 assert(FD->getFriendObjectKind() && "expected a friend declaration"); 8369 } 8370 8371 // C++2a [class.eq]p1, [class.rel]p1: 8372 // A [defaulted comparison other than <=>] shall have a declared return 8373 // type bool. 8374 if (DCK != DefaultedComparisonKind::ThreeWay && 8375 !FD->getDeclaredReturnType()->isDependentType() && 8376 !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) { 8377 Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool) 8378 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy 8379 << FD->getReturnTypeSourceRange(); 8380 return true; 8381 } 8382 // C++2a [class.spaceship]p2 [P2002R0]: 8383 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise, 8384 // R shall not contain a placeholder type. 8385 if (DCK == DefaultedComparisonKind::ThreeWay && 8386 FD->getDeclaredReturnType()->getContainedDeducedType() && 8387 !Context.hasSameType(FD->getDeclaredReturnType(), 8388 Context.getAutoDeductType())) { 8389 Diag(FD->getLocation(), 8390 diag::err_defaulted_comparison_deduced_return_type_not_auto) 8391 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy 8392 << FD->getReturnTypeSourceRange(); 8393 return true; 8394 } 8395 8396 // For a defaulted function in a dependent class, defer all remaining checks 8397 // until instantiation. 8398 if (RD->isDependentType()) 8399 return false; 8400 8401 // Determine whether the function should be defined as deleted. 8402 DefaultedComparisonInfo Info = 8403 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit(); 8404 8405 bool First = FD == FD->getCanonicalDecl(); 8406 8407 // If we want to delete the function, then do so; there's nothing else to 8408 // check in that case. 8409 if (Info.Deleted) { 8410 if (!First) { 8411 // C++11 [dcl.fct.def.default]p4: 8412 // [For a] user-provided explicitly-defaulted function [...] if such a 8413 // function is implicitly defined as deleted, the program is ill-formed. 8414 // 8415 // This is really just a consequence of the general rule that you can 8416 // only delete a function on its first declaration. 8417 Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes) 8418 << FD->isImplicit() << (int)DCK; 8419 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8420 DefaultedComparisonAnalyzer::ExplainDeleted) 8421 .visit(); 8422 return true; 8423 } 8424 8425 SetDeclDeleted(FD, FD->getLocation()); 8426 if (!inTemplateInstantiation() && !FD->isImplicit()) { 8427 Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted) 8428 << (int)DCK; 8429 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8430 DefaultedComparisonAnalyzer::ExplainDeleted) 8431 .visit(); 8432 } 8433 return false; 8434 } 8435 8436 // C++2a [class.spaceship]p2: 8437 // The return type is deduced as the common comparison type of R0, R1, ... 8438 if (DCK == DefaultedComparisonKind::ThreeWay && 8439 FD->getDeclaredReturnType()->isUndeducedAutoType()) { 8440 SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin(); 8441 if (RetLoc.isInvalid()) 8442 RetLoc = FD->getBeginLoc(); 8443 // FIXME: Should we really care whether we have the complete type and the 8444 // 'enumerator' constants here? A forward declaration seems sufficient. 8445 QualType Cat = CheckComparisonCategoryType( 8446 Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator); 8447 if (Cat.isNull()) 8448 return true; 8449 Context.adjustDeducedFunctionResultType( 8450 FD, SubstAutoType(FD->getDeclaredReturnType(), Cat)); 8451 } 8452 8453 // C++2a [dcl.fct.def.default]p3 [P2002R0]: 8454 // An explicitly-defaulted function that is not defined as deleted may be 8455 // declared constexpr or consteval only if it is constexpr-compatible. 8456 // C++2a [class.compare.default]p3 [P2002R0]: 8457 // A defaulted comparison function is constexpr-compatible if it satisfies 8458 // the requirements for a constexpr function [...] 8459 // The only relevant requirements are that the parameter and return types are 8460 // literal types. The remaining conditions are checked by the analyzer. 8461 if (FD->isConstexpr()) { 8462 if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) && 8463 CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) && 8464 !Info.Constexpr) { 8465 Diag(FD->getBeginLoc(), 8466 diag::err_incorrect_defaulted_comparison_constexpr) 8467 << FD->isImplicit() << (int)DCK << FD->isConsteval(); 8468 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8469 DefaultedComparisonAnalyzer::ExplainConstexpr) 8470 .visit(); 8471 } 8472 } 8473 8474 // C++2a [dcl.fct.def.default]p3 [P2002R0]: 8475 // If a constexpr-compatible function is explicitly defaulted on its first 8476 // declaration, it is implicitly considered to be constexpr. 8477 // FIXME: Only applying this to the first declaration seems problematic, as 8478 // simple reorderings can affect the meaning of the program. 8479 if (First && !FD->isConstexpr() && Info.Constexpr) 8480 FD->setConstexprKind(ConstexprSpecKind::Constexpr); 8481 8482 // C++2a [except.spec]p3: 8483 // If a declaration of a function does not have a noexcept-specifier 8484 // [and] is defaulted on its first declaration, [...] the exception 8485 // specification is as specified below 8486 if (FD->getExceptionSpecType() == EST_None) { 8487 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 8488 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8489 EPI.ExceptionSpec.Type = EST_Unevaluated; 8490 EPI.ExceptionSpec.SourceDecl = FD; 8491 FD->setType(Context.getFunctionType(FPT->getReturnType(), 8492 FPT->getParamTypes(), EPI)); 8493 } 8494 8495 return false; 8496 } 8497 8498 void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD, 8499 FunctionDecl *Spaceship) { 8500 Sema::CodeSynthesisContext Ctx; 8501 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison; 8502 Ctx.PointOfInstantiation = Spaceship->getEndLoc(); 8503 Ctx.Entity = Spaceship; 8504 pushCodeSynthesisContext(Ctx); 8505 8506 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship)) 8507 EqualEqual->setImplicit(); 8508 8509 popCodeSynthesisContext(); 8510 } 8511 8512 void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD, 8513 DefaultedComparisonKind DCK) { 8514 assert(FD->isDefaulted() && !FD->isDeleted() && 8515 !FD->doesThisDeclarationHaveABody()); 8516 if (FD->willHaveBody() || FD->isInvalidDecl()) 8517 return; 8518 8519 SynthesizedFunctionScope Scope(*this, FD); 8520 8521 // Add a context note for diagnostics produced after this point. 8522 Scope.addContextNote(UseLoc); 8523 8524 { 8525 // Build and set up the function body. 8526 CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent()); 8527 SourceLocation BodyLoc = 8528 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation(); 8529 StmtResult Body = 8530 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build(); 8531 if (Body.isInvalid()) { 8532 FD->setInvalidDecl(); 8533 return; 8534 } 8535 FD->setBody(Body.get()); 8536 FD->markUsed(Context); 8537 } 8538 8539 // The exception specification is needed because we are defining the 8540 // function. Note that this will reuse the body we just built. 8541 ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>()); 8542 8543 if (ASTMutationListener *L = getASTMutationListener()) 8544 L->CompletedImplicitDefinition(FD); 8545 } 8546 8547 static Sema::ImplicitExceptionSpecification 8548 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, 8549 FunctionDecl *FD, 8550 Sema::DefaultedComparisonKind DCK) { 8551 ComputingExceptionSpec CES(S, FD, Loc); 8552 Sema::ImplicitExceptionSpecification ExceptSpec(S); 8553 8554 if (FD->isInvalidDecl()) 8555 return ExceptSpec; 8556 8557 // The common case is that we just defined the comparison function. In that 8558 // case, just look at whether the body can throw. 8559 if (FD->hasBody()) { 8560 ExceptSpec.CalledStmt(FD->getBody()); 8561 } else { 8562 // Otherwise, build a body so we can check it. This should ideally only 8563 // happen when we're not actually marking the function referenced. (This is 8564 // only really important for efficiency: we don't want to build and throw 8565 // away bodies for comparison functions more than we strictly need to.) 8566 8567 // Pretend to synthesize the function body in an unevaluated context. 8568 // Note that we can't actually just go ahead and define the function here: 8569 // we are not permitted to mark its callees as referenced. 8570 Sema::SynthesizedFunctionScope Scope(S, FD); 8571 EnterExpressionEvaluationContext Context( 8572 S, Sema::ExpressionEvaluationContext::Unevaluated); 8573 8574 CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent()); 8575 SourceLocation BodyLoc = 8576 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation(); 8577 StmtResult Body = 8578 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build(); 8579 if (!Body.isInvalid()) 8580 ExceptSpec.CalledStmt(Body.get()); 8581 8582 // FIXME: Can we hold onto this body and just transform it to potentially 8583 // evaluated when we're asked to define the function rather than rebuilding 8584 // it? Either that, or we should only build the bits of the body that we 8585 // need (the expressions, not the statements). 8586 } 8587 8588 return ExceptSpec; 8589 } 8590 8591 void Sema::CheckDelayedMemberExceptionSpecs() { 8592 decltype(DelayedOverridingExceptionSpecChecks) Overriding; 8593 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent; 8594 8595 std::swap(Overriding, DelayedOverridingExceptionSpecChecks); 8596 std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks); 8597 8598 // Perform any deferred checking of exception specifications for virtual 8599 // destructors. 8600 for (auto &Check : Overriding) 8601 CheckOverridingFunctionExceptionSpec(Check.first, Check.second); 8602 8603 // Perform any deferred checking of exception specifications for befriended 8604 // special members. 8605 for (auto &Check : Equivalent) 8606 CheckEquivalentExceptionSpec(Check.second, Check.first); 8607 } 8608 8609 namespace { 8610 /// CRTP base class for visiting operations performed by a special member 8611 /// function (or inherited constructor). 8612 template<typename Derived> 8613 struct SpecialMemberVisitor { 8614 Sema &S; 8615 CXXMethodDecl *MD; 8616 Sema::CXXSpecialMember CSM; 8617 Sema::InheritedConstructorInfo *ICI; 8618 8619 // Properties of the special member, computed for convenience. 8620 bool IsConstructor = false, IsAssignment = false, ConstArg = false; 8621 8622 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 8623 Sema::InheritedConstructorInfo *ICI) 8624 : S(S), MD(MD), CSM(CSM), ICI(ICI) { 8625 switch (CSM) { 8626 case Sema::CXXDefaultConstructor: 8627 case Sema::CXXCopyConstructor: 8628 case Sema::CXXMoveConstructor: 8629 IsConstructor = true; 8630 break; 8631 case Sema::CXXCopyAssignment: 8632 case Sema::CXXMoveAssignment: 8633 IsAssignment = true; 8634 break; 8635 case Sema::CXXDestructor: 8636 break; 8637 case Sema::CXXInvalid: 8638 llvm_unreachable("invalid special member kind"); 8639 } 8640 8641 if (MD->getNumParams()) { 8642 if (const ReferenceType *RT = 8643 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 8644 ConstArg = RT->getPointeeType().isConstQualified(); 8645 } 8646 } 8647 8648 Derived &getDerived() { return static_cast<Derived&>(*this); } 8649 8650 /// Is this a "move" special member? 8651 bool isMove() const { 8652 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment; 8653 } 8654 8655 /// Look up the corresponding special member in the given class. 8656 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class, 8657 unsigned Quals, bool IsMutable) { 8658 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 8659 ConstArg && !IsMutable); 8660 } 8661 8662 /// Look up the constructor for the specified base class to see if it's 8663 /// overridden due to this being an inherited constructor. 8664 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) { 8665 if (!ICI) 8666 return {}; 8667 assert(CSM == Sema::CXXDefaultConstructor); 8668 auto *BaseCtor = 8669 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor(); 8670 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first) 8671 return MD; 8672 return {}; 8673 } 8674 8675 /// A base or member subobject. 8676 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 8677 8678 /// Get the location to use for a subobject in diagnostics. 8679 static SourceLocation getSubobjectLoc(Subobject Subobj) { 8680 // FIXME: For an indirect virtual base, the direct base leading to 8681 // the indirect virtual base would be a more useful choice. 8682 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>()) 8683 return B->getBaseTypeLoc(); 8684 else 8685 return Subobj.get<FieldDecl*>()->getLocation(); 8686 } 8687 8688 enum BasesToVisit { 8689 /// Visit all non-virtual (direct) bases. 8690 VisitNonVirtualBases, 8691 /// Visit all direct bases, virtual or not. 8692 VisitDirectBases, 8693 /// Visit all non-virtual bases, and all virtual bases if the class 8694 /// is not abstract. 8695 VisitPotentiallyConstructedBases, 8696 /// Visit all direct or virtual bases. 8697 VisitAllBases 8698 }; 8699 8700 // Visit the bases and members of the class. 8701 bool visit(BasesToVisit Bases) { 8702 CXXRecordDecl *RD = MD->getParent(); 8703 8704 if (Bases == VisitPotentiallyConstructedBases) 8705 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases; 8706 8707 for (auto &B : RD->bases()) 8708 if ((Bases == VisitDirectBases || !B.isVirtual()) && 8709 getDerived().visitBase(&B)) 8710 return true; 8711 8712 if (Bases == VisitAllBases) 8713 for (auto &B : RD->vbases()) 8714 if (getDerived().visitBase(&B)) 8715 return true; 8716 8717 for (auto *F : RD->fields()) 8718 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() && 8719 getDerived().visitField(F)) 8720 return true; 8721 8722 return false; 8723 } 8724 }; 8725 } 8726 8727 namespace { 8728 struct SpecialMemberDeletionInfo 8729 : SpecialMemberVisitor<SpecialMemberDeletionInfo> { 8730 bool Diagnose; 8731 8732 SourceLocation Loc; 8733 8734 bool AllFieldsAreConst; 8735 8736 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 8737 Sema::CXXSpecialMember CSM, 8738 Sema::InheritedConstructorInfo *ICI, bool Diagnose) 8739 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose), 8740 Loc(MD->getLocation()), AllFieldsAreConst(true) {} 8741 8742 bool inUnion() const { return MD->getParent()->isUnion(); } 8743 8744 Sema::CXXSpecialMember getEffectiveCSM() { 8745 return ICI ? Sema::CXXInvalid : CSM; 8746 } 8747 8748 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType); 8749 8750 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); } 8751 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); } 8752 8753 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 8754 bool shouldDeleteForField(FieldDecl *FD); 8755 bool shouldDeleteForAllConstMembers(); 8756 8757 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 8758 unsigned Quals); 8759 bool shouldDeleteForSubobjectCall(Subobject Subobj, 8760 Sema::SpecialMemberOverloadResult SMOR, 8761 bool IsDtorCallInCtor); 8762 8763 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 8764 }; 8765 } 8766 8767 /// Is the given special member inaccessible when used on the given 8768 /// sub-object. 8769 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 8770 CXXMethodDecl *target) { 8771 /// If we're operating on a base class, the object type is the 8772 /// type of this special member. 8773 QualType objectTy; 8774 AccessSpecifier access = target->getAccess(); 8775 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 8776 objectTy = S.Context.getTypeDeclType(MD->getParent()); 8777 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 8778 8779 // If we're operating on a field, the object type is the type of the field. 8780 } else { 8781 objectTy = S.Context.getTypeDeclType(target->getParent()); 8782 } 8783 8784 return S.isMemberAccessibleForDeletion( 8785 target->getParent(), DeclAccessPair::make(target, access), objectTy); 8786 } 8787 8788 /// Check whether we should delete a special member due to the implicit 8789 /// definition containing a call to a special member of a subobject. 8790 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 8791 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR, 8792 bool IsDtorCallInCtor) { 8793 CXXMethodDecl *Decl = SMOR.getMethod(); 8794 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 8795 8796 int DiagKind = -1; 8797 8798 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 8799 DiagKind = !Decl ? 0 : 1; 8800 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 8801 DiagKind = 2; 8802 else if (!isAccessible(Subobj, Decl)) 8803 DiagKind = 3; 8804 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 8805 !Decl->isTrivial()) { 8806 // A member of a union must have a trivial corresponding special member. 8807 // As a weird special case, a destructor call from a union's constructor 8808 // must be accessible and non-deleted, but need not be trivial. Such a 8809 // destructor is never actually called, but is semantically checked as 8810 // if it were. 8811 DiagKind = 4; 8812 } 8813 8814 if (DiagKind == -1) 8815 return false; 8816 8817 if (Diagnose) { 8818 if (Field) { 8819 S.Diag(Field->getLocation(), 8820 diag::note_deleted_special_member_class_subobject) 8821 << getEffectiveCSM() << MD->getParent() << /*IsField*/true 8822 << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false; 8823 } else { 8824 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 8825 S.Diag(Base->getBeginLoc(), 8826 diag::note_deleted_special_member_class_subobject) 8827 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 8828 << Base->getType() << DiagKind << IsDtorCallInCtor 8829 << /*IsObjCPtr*/false; 8830 } 8831 8832 if (DiagKind == 1) 8833 S.NoteDeletedFunction(Decl); 8834 // FIXME: Explain inaccessibility if DiagKind == 3. 8835 } 8836 8837 return true; 8838 } 8839 8840 /// Check whether we should delete a special member function due to having a 8841 /// direct or virtual base class or non-static data member of class type M. 8842 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 8843 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 8844 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 8845 bool IsMutable = Field && Field->isMutable(); 8846 8847 // C++11 [class.ctor]p5: 8848 // -- any direct or virtual base class, or non-static data member with no 8849 // brace-or-equal-initializer, has class type M (or array thereof) and 8850 // either M has no default constructor or overload resolution as applied 8851 // to M's default constructor results in an ambiguity or in a function 8852 // that is deleted or inaccessible 8853 // C++11 [class.copy]p11, C++11 [class.copy]p23: 8854 // -- a direct or virtual base class B that cannot be copied/moved because 8855 // overload resolution, as applied to B's corresponding special member, 8856 // results in an ambiguity or a function that is deleted or inaccessible 8857 // from the defaulted special member 8858 // C++11 [class.dtor]p5: 8859 // -- any direct or virtual base class [...] has a type with a destructor 8860 // that is deleted or inaccessible 8861 if (!(CSM == Sema::CXXDefaultConstructor && 8862 Field && Field->hasInClassInitializer()) && 8863 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 8864 false)) 8865 return true; 8866 8867 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 8868 // -- any direct or virtual base class or non-static data member has a 8869 // type with a destructor that is deleted or inaccessible 8870 if (IsConstructor) { 8871 Sema::SpecialMemberOverloadResult SMOR = 8872 S.LookupSpecialMember(Class, Sema::CXXDestructor, 8873 false, false, false, false, false); 8874 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 8875 return true; 8876 } 8877 8878 return false; 8879 } 8880 8881 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember( 8882 FieldDecl *FD, QualType FieldType) { 8883 // The defaulted special functions are defined as deleted if this is a variant 8884 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak 8885 // type under ARC. 8886 if (!FieldType.hasNonTrivialObjCLifetime()) 8887 return false; 8888 8889 // Don't make the defaulted default constructor defined as deleted if the 8890 // member has an in-class initializer. 8891 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) 8892 return false; 8893 8894 if (Diagnose) { 8895 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent()); 8896 S.Diag(FD->getLocation(), 8897 diag::note_deleted_special_member_class_subobject) 8898 << getEffectiveCSM() << ParentClass << /*IsField*/true 8899 << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true; 8900 } 8901 8902 return true; 8903 } 8904 8905 /// Check whether we should delete a special member function due to the class 8906 /// having a particular direct or virtual base class. 8907 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 8908 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 8909 // If program is correct, BaseClass cannot be null, but if it is, the error 8910 // must be reported elsewhere. 8911 if (!BaseClass) 8912 return false; 8913 // If we have an inheriting constructor, check whether we're calling an 8914 // inherited constructor instead of a default constructor. 8915 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 8916 if (auto *BaseCtor = SMOR.getMethod()) { 8917 // Note that we do not check access along this path; other than that, 8918 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false); 8919 // FIXME: Check that the base has a usable destructor! Sink this into 8920 // shouldDeleteForClassSubobject. 8921 if (BaseCtor->isDeleted() && Diagnose) { 8922 S.Diag(Base->getBeginLoc(), 8923 diag::note_deleted_special_member_class_subobject) 8924 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 8925 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false 8926 << /*IsObjCPtr*/false; 8927 S.NoteDeletedFunction(BaseCtor); 8928 } 8929 return BaseCtor->isDeleted(); 8930 } 8931 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 8932 } 8933 8934 /// Check whether we should delete a special member function due to the class 8935 /// having a particular non-static data member. 8936 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 8937 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 8938 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 8939 8940 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType)) 8941 return true; 8942 8943 if (CSM == Sema::CXXDefaultConstructor) { 8944 // For a default constructor, all references must be initialized in-class 8945 // and, if a union, it must have a non-const member. 8946 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 8947 if (Diagnose) 8948 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 8949 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0; 8950 return true; 8951 } 8952 // C++11 [class.ctor]p5: any non-variant non-static data member of 8953 // const-qualified type (or array thereof) with no 8954 // brace-or-equal-initializer does not have a user-provided default 8955 // constructor. 8956 if (!inUnion() && FieldType.isConstQualified() && 8957 !FD->hasInClassInitializer() && 8958 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 8959 if (Diagnose) 8960 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 8961 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1; 8962 return true; 8963 } 8964 8965 if (inUnion() && !FieldType.isConstQualified()) 8966 AllFieldsAreConst = false; 8967 } else if (CSM == Sema::CXXCopyConstructor) { 8968 // For a copy constructor, data members must not be of rvalue reference 8969 // type. 8970 if (FieldType->isRValueReferenceType()) { 8971 if (Diagnose) 8972 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 8973 << MD->getParent() << FD << FieldType; 8974 return true; 8975 } 8976 } else if (IsAssignment) { 8977 // For an assignment operator, data members must not be of reference type. 8978 if (FieldType->isReferenceType()) { 8979 if (Diagnose) 8980 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 8981 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0; 8982 return true; 8983 } 8984 if (!FieldRecord && FieldType.isConstQualified()) { 8985 // C++11 [class.copy]p23: 8986 // -- a non-static data member of const non-class type (or array thereof) 8987 if (Diagnose) 8988 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 8989 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1; 8990 return true; 8991 } 8992 } 8993 8994 if (FieldRecord) { 8995 // Some additional restrictions exist on the variant members. 8996 if (!inUnion() && FieldRecord->isUnion() && 8997 FieldRecord->isAnonymousStructOrUnion()) { 8998 bool AllVariantFieldsAreConst = true; 8999 9000 // FIXME: Handle anonymous unions declared within anonymous unions. 9001 for (auto *UI : FieldRecord->fields()) { 9002 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 9003 9004 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType)) 9005 return true; 9006 9007 if (!UnionFieldType.isConstQualified()) 9008 AllVariantFieldsAreConst = false; 9009 9010 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 9011 if (UnionFieldRecord && 9012 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 9013 UnionFieldType.getCVRQualifiers())) 9014 return true; 9015 } 9016 9017 // At least one member in each anonymous union must be non-const 9018 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 9019 !FieldRecord->field_empty()) { 9020 if (Diagnose) 9021 S.Diag(FieldRecord->getLocation(), 9022 diag::note_deleted_default_ctor_all_const) 9023 << !!ICI << MD->getParent() << /*anonymous union*/1; 9024 return true; 9025 } 9026 9027 // Don't check the implicit member of the anonymous union type. 9028 // This is technically non-conformant, but sanity demands it. 9029 return false; 9030 } 9031 9032 if (shouldDeleteForClassSubobject(FieldRecord, FD, 9033 FieldType.getCVRQualifiers())) 9034 return true; 9035 } 9036 9037 return false; 9038 } 9039 9040 /// C++11 [class.ctor] p5: 9041 /// A defaulted default constructor for a class X is defined as deleted if 9042 /// X is a union and all of its variant members are of const-qualified type. 9043 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 9044 // This is a silly definition, because it gives an empty union a deleted 9045 // default constructor. Don't do that. 9046 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) { 9047 bool AnyFields = false; 9048 for (auto *F : MD->getParent()->fields()) 9049 if ((AnyFields = !F->isUnnamedBitfield())) 9050 break; 9051 if (!AnyFields) 9052 return false; 9053 if (Diagnose) 9054 S.Diag(MD->getParent()->getLocation(), 9055 diag::note_deleted_default_ctor_all_const) 9056 << !!ICI << MD->getParent() << /*not anonymous union*/0; 9057 return true; 9058 } 9059 return false; 9060 } 9061 9062 /// Determine whether a defaulted special member function should be defined as 9063 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 9064 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 9065 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 9066 InheritedConstructorInfo *ICI, 9067 bool Diagnose) { 9068 if (MD->isInvalidDecl()) 9069 return false; 9070 CXXRecordDecl *RD = MD->getParent(); 9071 assert(!RD->isDependentType() && "do deletion after instantiation"); 9072 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 9073 return false; 9074 9075 // C++11 [expr.lambda.prim]p19: 9076 // The closure type associated with a lambda-expression has a 9077 // deleted (8.4.3) default constructor and a deleted copy 9078 // assignment operator. 9079 // C++2a adds back these operators if the lambda has no lambda-capture. 9080 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() && 9081 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 9082 if (Diagnose) 9083 Diag(RD->getLocation(), diag::note_lambda_decl); 9084 return true; 9085 } 9086 9087 // For an anonymous struct or union, the copy and assignment special members 9088 // will never be used, so skip the check. For an anonymous union declared at 9089 // namespace scope, the constructor and destructor are used. 9090 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 9091 RD->isAnonymousStructOrUnion()) 9092 return false; 9093 9094 // C++11 [class.copy]p7, p18: 9095 // If the class definition declares a move constructor or move assignment 9096 // operator, an implicitly declared copy constructor or copy assignment 9097 // operator is defined as deleted. 9098 if (MD->isImplicit() && 9099 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 9100 CXXMethodDecl *UserDeclaredMove = nullptr; 9101 9102 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the 9103 // deletion of the corresponding copy operation, not both copy operations. 9104 // MSVC 2015 has adopted the standards conforming behavior. 9105 bool DeletesOnlyMatchingCopy = 9106 getLangOpts().MSVCCompat && 9107 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015); 9108 9109 if (RD->hasUserDeclaredMoveConstructor() && 9110 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) { 9111 if (!Diagnose) return true; 9112 9113 // Find any user-declared move constructor. 9114 for (auto *I : RD->ctors()) { 9115 if (I->isMoveConstructor()) { 9116 UserDeclaredMove = I; 9117 break; 9118 } 9119 } 9120 assert(UserDeclaredMove); 9121 } else if (RD->hasUserDeclaredMoveAssignment() && 9122 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) { 9123 if (!Diagnose) return true; 9124 9125 // Find any user-declared move assignment operator. 9126 for (auto *I : RD->methods()) { 9127 if (I->isMoveAssignmentOperator()) { 9128 UserDeclaredMove = I; 9129 break; 9130 } 9131 } 9132 assert(UserDeclaredMove); 9133 } 9134 9135 if (UserDeclaredMove) { 9136 Diag(UserDeclaredMove->getLocation(), 9137 diag::note_deleted_copy_user_declared_move) 9138 << (CSM == CXXCopyAssignment) << RD 9139 << UserDeclaredMove->isMoveAssignmentOperator(); 9140 return true; 9141 } 9142 } 9143 9144 // Do access control from the special member function 9145 ContextRAII MethodContext(*this, MD); 9146 9147 // C++11 [class.dtor]p5: 9148 // -- for a virtual destructor, lookup of the non-array deallocation function 9149 // results in an ambiguity or in a function that is deleted or inaccessible 9150 if (CSM == CXXDestructor && MD->isVirtual()) { 9151 FunctionDecl *OperatorDelete = nullptr; 9152 DeclarationName Name = 9153 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 9154 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 9155 OperatorDelete, /*Diagnose*/false)) { 9156 if (Diagnose) 9157 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 9158 return true; 9159 } 9160 } 9161 9162 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose); 9163 9164 // Per DR1611, do not consider virtual bases of constructors of abstract 9165 // classes, since we are not going to construct them. 9166 // Per DR1658, do not consider virtual bases of destructors of abstract 9167 // classes either. 9168 // Per DR2180, for assignment operators we only assign (and thus only 9169 // consider) direct bases. 9170 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases 9171 : SMI.VisitPotentiallyConstructedBases)) 9172 return true; 9173 9174 if (SMI.shouldDeleteForAllConstMembers()) 9175 return true; 9176 9177 if (getLangOpts().CUDA) { 9178 // We should delete the special member in CUDA mode if target inference 9179 // failed. 9180 // For inherited constructors (non-null ICI), CSM may be passed so that MD 9181 // is treated as certain special member, which may not reflect what special 9182 // member MD really is. However inferCUDATargetForImplicitSpecialMember 9183 // expects CSM to match MD, therefore recalculate CSM. 9184 assert(ICI || CSM == getSpecialMember(MD)); 9185 auto RealCSM = CSM; 9186 if (ICI) 9187 RealCSM = getSpecialMember(MD); 9188 9189 return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD, 9190 SMI.ConstArg, Diagnose); 9191 } 9192 9193 return false; 9194 } 9195 9196 void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) { 9197 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD); 9198 assert(DFK && "not a defaultable function"); 9199 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted"); 9200 9201 if (DFK.isSpecialMember()) { 9202 ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), 9203 nullptr, /*Diagnose=*/true); 9204 } else { 9205 DefaultedComparisonAnalyzer( 9206 *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD, 9207 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted) 9208 .visit(); 9209 } 9210 } 9211 9212 /// Perform lookup for a special member of the specified kind, and determine 9213 /// whether it is trivial. If the triviality can be determined without the 9214 /// lookup, skip it. This is intended for use when determining whether a 9215 /// special member of a containing object is trivial, and thus does not ever 9216 /// perform overload resolution for default constructors. 9217 /// 9218 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 9219 /// member that was most likely to be intended to be trivial, if any. 9220 /// 9221 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to 9222 /// determine whether the special member is trivial. 9223 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 9224 Sema::CXXSpecialMember CSM, unsigned Quals, 9225 bool ConstRHS, 9226 Sema::TrivialABIHandling TAH, 9227 CXXMethodDecl **Selected) { 9228 if (Selected) 9229 *Selected = nullptr; 9230 9231 switch (CSM) { 9232 case Sema::CXXInvalid: 9233 llvm_unreachable("not a special member"); 9234 9235 case Sema::CXXDefaultConstructor: 9236 // C++11 [class.ctor]p5: 9237 // A default constructor is trivial if: 9238 // - all the [direct subobjects] have trivial default constructors 9239 // 9240 // Note, no overload resolution is performed in this case. 9241 if (RD->hasTrivialDefaultConstructor()) 9242 return true; 9243 9244 if (Selected) { 9245 // If there's a default constructor which could have been trivial, dig it 9246 // out. Otherwise, if there's any user-provided default constructor, point 9247 // to that as an example of why there's not a trivial one. 9248 CXXConstructorDecl *DefCtor = nullptr; 9249 if (RD->needsImplicitDefaultConstructor()) 9250 S.DeclareImplicitDefaultConstructor(RD); 9251 for (auto *CI : RD->ctors()) { 9252 if (!CI->isDefaultConstructor()) 9253 continue; 9254 DefCtor = CI; 9255 if (!DefCtor->isUserProvided()) 9256 break; 9257 } 9258 9259 *Selected = DefCtor; 9260 } 9261 9262 return false; 9263 9264 case Sema::CXXDestructor: 9265 // C++11 [class.dtor]p5: 9266 // A destructor is trivial if: 9267 // - all the direct [subobjects] have trivial destructors 9268 if (RD->hasTrivialDestructor() || 9269 (TAH == Sema::TAH_ConsiderTrivialABI && 9270 RD->hasTrivialDestructorForCall())) 9271 return true; 9272 9273 if (Selected) { 9274 if (RD->needsImplicitDestructor()) 9275 S.DeclareImplicitDestructor(RD); 9276 *Selected = RD->getDestructor(); 9277 } 9278 9279 return false; 9280 9281 case Sema::CXXCopyConstructor: 9282 // C++11 [class.copy]p12: 9283 // A copy constructor is trivial if: 9284 // - the constructor selected to copy each direct [subobject] is trivial 9285 if (RD->hasTrivialCopyConstructor() || 9286 (TAH == Sema::TAH_ConsiderTrivialABI && 9287 RD->hasTrivialCopyConstructorForCall())) { 9288 if (Quals == Qualifiers::Const) 9289 // We must either select the trivial copy constructor or reach an 9290 // ambiguity; no need to actually perform overload resolution. 9291 return true; 9292 } else if (!Selected) { 9293 return false; 9294 } 9295 // In C++98, we are not supposed to perform overload resolution here, but we 9296 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 9297 // cases like B as having a non-trivial copy constructor: 9298 // struct A { template<typename T> A(T&); }; 9299 // struct B { mutable A a; }; 9300 goto NeedOverloadResolution; 9301 9302 case Sema::CXXCopyAssignment: 9303 // C++11 [class.copy]p25: 9304 // A copy assignment operator is trivial if: 9305 // - the assignment operator selected to copy each direct [subobject] is 9306 // trivial 9307 if (RD->hasTrivialCopyAssignment()) { 9308 if (Quals == Qualifiers::Const) 9309 return true; 9310 } else if (!Selected) { 9311 return false; 9312 } 9313 // In C++98, we are not supposed to perform overload resolution here, but we 9314 // treat that as a language defect. 9315 goto NeedOverloadResolution; 9316 9317 case Sema::CXXMoveConstructor: 9318 case Sema::CXXMoveAssignment: 9319 NeedOverloadResolution: 9320 Sema::SpecialMemberOverloadResult SMOR = 9321 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 9322 9323 // The standard doesn't describe how to behave if the lookup is ambiguous. 9324 // We treat it as not making the member non-trivial, just like the standard 9325 // mandates for the default constructor. This should rarely matter, because 9326 // the member will also be deleted. 9327 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 9328 return true; 9329 9330 if (!SMOR.getMethod()) { 9331 assert(SMOR.getKind() == 9332 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 9333 return false; 9334 } 9335 9336 // We deliberately don't check if we found a deleted special member. We're 9337 // not supposed to! 9338 if (Selected) 9339 *Selected = SMOR.getMethod(); 9340 9341 if (TAH == Sema::TAH_ConsiderTrivialABI && 9342 (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor)) 9343 return SMOR.getMethod()->isTrivialForCall(); 9344 return SMOR.getMethod()->isTrivial(); 9345 } 9346 9347 llvm_unreachable("unknown special method kind"); 9348 } 9349 9350 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 9351 for (auto *CI : RD->ctors()) 9352 if (!CI->isImplicit()) 9353 return CI; 9354 9355 // Look for constructor templates. 9356 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 9357 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 9358 if (CXXConstructorDecl *CD = 9359 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 9360 return CD; 9361 } 9362 9363 return nullptr; 9364 } 9365 9366 /// The kind of subobject we are checking for triviality. The values of this 9367 /// enumeration are used in diagnostics. 9368 enum TrivialSubobjectKind { 9369 /// The subobject is a base class. 9370 TSK_BaseClass, 9371 /// The subobject is a non-static data member. 9372 TSK_Field, 9373 /// The object is actually the complete object. 9374 TSK_CompleteObject 9375 }; 9376 9377 /// Check whether the special member selected for a given type would be trivial. 9378 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 9379 QualType SubType, bool ConstRHS, 9380 Sema::CXXSpecialMember CSM, 9381 TrivialSubobjectKind Kind, 9382 Sema::TrivialABIHandling TAH, bool Diagnose) { 9383 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 9384 if (!SubRD) 9385 return true; 9386 9387 CXXMethodDecl *Selected; 9388 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 9389 ConstRHS, TAH, Diagnose ? &Selected : nullptr)) 9390 return true; 9391 9392 if (Diagnose) { 9393 if (ConstRHS) 9394 SubType.addConst(); 9395 9396 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 9397 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 9398 << Kind << SubType.getUnqualifiedType(); 9399 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 9400 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 9401 } else if (!Selected) 9402 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 9403 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 9404 else if (Selected->isUserProvided()) { 9405 if (Kind == TSK_CompleteObject) 9406 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 9407 << Kind << SubType.getUnqualifiedType() << CSM; 9408 else { 9409 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 9410 << Kind << SubType.getUnqualifiedType() << CSM; 9411 S.Diag(Selected->getLocation(), diag::note_declared_at); 9412 } 9413 } else { 9414 if (Kind != TSK_CompleteObject) 9415 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 9416 << Kind << SubType.getUnqualifiedType() << CSM; 9417 9418 // Explain why the defaulted or deleted special member isn't trivial. 9419 S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI, 9420 Diagnose); 9421 } 9422 } 9423 9424 return false; 9425 } 9426 9427 /// Check whether the members of a class type allow a special member to be 9428 /// trivial. 9429 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 9430 Sema::CXXSpecialMember CSM, 9431 bool ConstArg, 9432 Sema::TrivialABIHandling TAH, 9433 bool Diagnose) { 9434 for (const auto *FI : RD->fields()) { 9435 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 9436 continue; 9437 9438 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 9439 9440 // Pretend anonymous struct or union members are members of this class. 9441 if (FI->isAnonymousStructOrUnion()) { 9442 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 9443 CSM, ConstArg, TAH, Diagnose)) 9444 return false; 9445 continue; 9446 } 9447 9448 // C++11 [class.ctor]p5: 9449 // A default constructor is trivial if [...] 9450 // -- no non-static data member of its class has a 9451 // brace-or-equal-initializer 9452 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 9453 if (Diagnose) 9454 S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init) 9455 << FI; 9456 return false; 9457 } 9458 9459 // Objective C ARC 4.3.5: 9460 // [...] nontrivally ownership-qualified types are [...] not trivially 9461 // default constructible, copy constructible, move constructible, copy 9462 // assignable, move assignable, or destructible [...] 9463 if (FieldType.hasNonTrivialObjCLifetime()) { 9464 if (Diagnose) 9465 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 9466 << RD << FieldType.getObjCLifetime(); 9467 return false; 9468 } 9469 9470 bool ConstRHS = ConstArg && !FI->isMutable(); 9471 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 9472 CSM, TSK_Field, TAH, Diagnose)) 9473 return false; 9474 } 9475 9476 return true; 9477 } 9478 9479 /// Diagnose why the specified class does not have a trivial special member of 9480 /// the given kind. 9481 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 9482 QualType Ty = Context.getRecordType(RD); 9483 9484 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 9485 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 9486 TSK_CompleteObject, TAH_IgnoreTrivialABI, 9487 /*Diagnose*/true); 9488 } 9489 9490 /// Determine whether a defaulted or deleted special member function is trivial, 9491 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 9492 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 9493 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 9494 TrivialABIHandling TAH, bool Diagnose) { 9495 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 9496 9497 CXXRecordDecl *RD = MD->getParent(); 9498 9499 bool ConstArg = false; 9500 9501 // C++11 [class.copy]p12, p25: [DR1593] 9502 // A [special member] is trivial if [...] its parameter-type-list is 9503 // equivalent to the parameter-type-list of an implicit declaration [...] 9504 switch (CSM) { 9505 case CXXDefaultConstructor: 9506 case CXXDestructor: 9507 // Trivial default constructors and destructors cannot have parameters. 9508 break; 9509 9510 case CXXCopyConstructor: 9511 case CXXCopyAssignment: { 9512 // Trivial copy operations always have const, non-volatile parameter types. 9513 ConstArg = true; 9514 const ParmVarDecl *Param0 = MD->getParamDecl(0); 9515 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 9516 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 9517 if (Diagnose) 9518 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 9519 << Param0->getSourceRange() << Param0->getType() 9520 << Context.getLValueReferenceType( 9521 Context.getRecordType(RD).withConst()); 9522 return false; 9523 } 9524 break; 9525 } 9526 9527 case CXXMoveConstructor: 9528 case CXXMoveAssignment: { 9529 // Trivial move operations always have non-cv-qualified parameters. 9530 const ParmVarDecl *Param0 = MD->getParamDecl(0); 9531 const RValueReferenceType *RT = 9532 Param0->getType()->getAs<RValueReferenceType>(); 9533 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 9534 if (Diagnose) 9535 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 9536 << Param0->getSourceRange() << Param0->getType() 9537 << Context.getRValueReferenceType(Context.getRecordType(RD)); 9538 return false; 9539 } 9540 break; 9541 } 9542 9543 case CXXInvalid: 9544 llvm_unreachable("not a special member"); 9545 } 9546 9547 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 9548 if (Diagnose) 9549 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 9550 diag::note_nontrivial_default_arg) 9551 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 9552 return false; 9553 } 9554 if (MD->isVariadic()) { 9555 if (Diagnose) 9556 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 9557 return false; 9558 } 9559 9560 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 9561 // A copy/move [constructor or assignment operator] is trivial if 9562 // -- the [member] selected to copy/move each direct base class subobject 9563 // is trivial 9564 // 9565 // C++11 [class.copy]p12, C++11 [class.copy]p25: 9566 // A [default constructor or destructor] is trivial if 9567 // -- all the direct base classes have trivial [default constructors or 9568 // destructors] 9569 for (const auto &BI : RD->bases()) 9570 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(), 9571 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose)) 9572 return false; 9573 9574 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 9575 // A copy/move [constructor or assignment operator] for a class X is 9576 // trivial if 9577 // -- for each non-static data member of X that is of class type (or array 9578 // thereof), the constructor selected to copy/move that member is 9579 // trivial 9580 // 9581 // C++11 [class.copy]p12, C++11 [class.copy]p25: 9582 // A [default constructor or destructor] is trivial if 9583 // -- for all of the non-static data members of its class that are of class 9584 // type (or array thereof), each such class has a trivial [default 9585 // constructor or destructor] 9586 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose)) 9587 return false; 9588 9589 // C++11 [class.dtor]p5: 9590 // A destructor is trivial if [...] 9591 // -- the destructor is not virtual 9592 if (CSM == CXXDestructor && MD->isVirtual()) { 9593 if (Diagnose) 9594 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 9595 return false; 9596 } 9597 9598 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 9599 // A [special member] for class X is trivial if [...] 9600 // -- class X has no virtual functions and no virtual base classes 9601 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 9602 if (!Diagnose) 9603 return false; 9604 9605 if (RD->getNumVBases()) { 9606 // Check for virtual bases. We already know that the corresponding 9607 // member in all bases is trivial, so vbases must all be direct. 9608 CXXBaseSpecifier &BS = *RD->vbases_begin(); 9609 assert(BS.isVirtual()); 9610 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1; 9611 return false; 9612 } 9613 9614 // Must have a virtual method. 9615 for (const auto *MI : RD->methods()) { 9616 if (MI->isVirtual()) { 9617 SourceLocation MLoc = MI->getBeginLoc(); 9618 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 9619 return false; 9620 } 9621 } 9622 9623 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 9624 } 9625 9626 // Looks like it's trivial! 9627 return true; 9628 } 9629 9630 namespace { 9631 struct FindHiddenVirtualMethod { 9632 Sema *S; 9633 CXXMethodDecl *Method; 9634 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 9635 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 9636 9637 private: 9638 /// Check whether any most overridden method from MD in Methods 9639 static bool CheckMostOverridenMethods( 9640 const CXXMethodDecl *MD, 9641 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) { 9642 if (MD->size_overridden_methods() == 0) 9643 return Methods.count(MD->getCanonicalDecl()); 9644 for (const CXXMethodDecl *O : MD->overridden_methods()) 9645 if (CheckMostOverridenMethods(O, Methods)) 9646 return true; 9647 return false; 9648 } 9649 9650 public: 9651 /// Member lookup function that determines whether a given C++ 9652 /// method overloads virtual methods in a base class without overriding any, 9653 /// to be used with CXXRecordDecl::lookupInBases(). 9654 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 9655 RecordDecl *BaseRecord = 9656 Specifier->getType()->castAs<RecordType>()->getDecl(); 9657 9658 DeclarationName Name = Method->getDeclName(); 9659 assert(Name.getNameKind() == DeclarationName::Identifier); 9660 9661 bool foundSameNameMethod = false; 9662 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 9663 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 9664 Path.Decls = Path.Decls.slice(1)) { 9665 NamedDecl *D = Path.Decls.front(); 9666 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 9667 MD = MD->getCanonicalDecl(); 9668 foundSameNameMethod = true; 9669 // Interested only in hidden virtual methods. 9670 if (!MD->isVirtual()) 9671 continue; 9672 // If the method we are checking overrides a method from its base 9673 // don't warn about the other overloaded methods. Clang deviates from 9674 // GCC by only diagnosing overloads of inherited virtual functions that 9675 // do not override any other virtual functions in the base. GCC's 9676 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 9677 // function from a base class. These cases may be better served by a 9678 // warning (not specific to virtual functions) on call sites when the 9679 // call would select a different function from the base class, were it 9680 // visible. 9681 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 9682 if (!S->IsOverload(Method, MD, false)) 9683 return true; 9684 // Collect the overload only if its hidden. 9685 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods)) 9686 overloadedMethods.push_back(MD); 9687 } 9688 } 9689 9690 if (foundSameNameMethod) 9691 OverloadedMethods.append(overloadedMethods.begin(), 9692 overloadedMethods.end()); 9693 return foundSameNameMethod; 9694 } 9695 }; 9696 } // end anonymous namespace 9697 9698 /// Add the most overriden methods from MD to Methods 9699 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 9700 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 9701 if (MD->size_overridden_methods() == 0) 9702 Methods.insert(MD->getCanonicalDecl()); 9703 else 9704 for (const CXXMethodDecl *O : MD->overridden_methods()) 9705 AddMostOverridenMethods(O, Methods); 9706 } 9707 9708 /// Check if a method overloads virtual methods in a base class without 9709 /// overriding any. 9710 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 9711 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 9712 if (!MD->getDeclName().isIdentifier()) 9713 return; 9714 9715 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 9716 /*bool RecordPaths=*/false, 9717 /*bool DetectVirtual=*/false); 9718 FindHiddenVirtualMethod FHVM; 9719 FHVM.Method = MD; 9720 FHVM.S = this; 9721 9722 // Keep the base methods that were overridden or introduced in the subclass 9723 // by 'using' in a set. A base method not in this set is hidden. 9724 CXXRecordDecl *DC = MD->getParent(); 9725 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 9726 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 9727 NamedDecl *ND = *I; 9728 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 9729 ND = shad->getTargetDecl(); 9730 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 9731 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods); 9732 } 9733 9734 if (DC->lookupInBases(FHVM, Paths)) 9735 OverloadedMethods = FHVM.OverloadedMethods; 9736 } 9737 9738 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 9739 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 9740 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 9741 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 9742 PartialDiagnostic PD = PDiag( 9743 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 9744 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 9745 Diag(overloadedMD->getLocation(), PD); 9746 } 9747 } 9748 9749 /// Diagnose methods which overload virtual methods in a base class 9750 /// without overriding any. 9751 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 9752 if (MD->isInvalidDecl()) 9753 return; 9754 9755 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 9756 return; 9757 9758 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 9759 FindHiddenVirtualMethods(MD, OverloadedMethods); 9760 if (!OverloadedMethods.empty()) { 9761 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 9762 << MD << (OverloadedMethods.size() > 1); 9763 9764 NoteHiddenVirtualMethods(MD, OverloadedMethods); 9765 } 9766 } 9767 9768 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) { 9769 auto PrintDiagAndRemoveAttr = [&](unsigned N) { 9770 // No diagnostics if this is a template instantiation. 9771 if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) { 9772 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), 9773 diag::ext_cannot_use_trivial_abi) << &RD; 9774 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), 9775 diag::note_cannot_use_trivial_abi_reason) << &RD << N; 9776 } 9777 RD.dropAttr<TrivialABIAttr>(); 9778 }; 9779 9780 // Ill-formed if the copy and move constructors are deleted. 9781 auto HasNonDeletedCopyOrMoveConstructor = [&]() { 9782 // If the type is dependent, then assume it might have 9783 // implicit copy or move ctor because we won't know yet at this point. 9784 if (RD.isDependentType()) 9785 return true; 9786 if (RD.needsImplicitCopyConstructor() && 9787 !RD.defaultedCopyConstructorIsDeleted()) 9788 return true; 9789 if (RD.needsImplicitMoveConstructor() && 9790 !RD.defaultedMoveConstructorIsDeleted()) 9791 return true; 9792 for (const CXXConstructorDecl *CD : RD.ctors()) 9793 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted()) 9794 return true; 9795 return false; 9796 }; 9797 9798 if (!HasNonDeletedCopyOrMoveConstructor()) { 9799 PrintDiagAndRemoveAttr(0); 9800 return; 9801 } 9802 9803 // Ill-formed if the struct has virtual functions. 9804 if (RD.isPolymorphic()) { 9805 PrintDiagAndRemoveAttr(1); 9806 return; 9807 } 9808 9809 for (const auto &B : RD.bases()) { 9810 // Ill-formed if the base class is non-trivial for the purpose of calls or a 9811 // virtual base. 9812 if (!B.getType()->isDependentType() && 9813 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) { 9814 PrintDiagAndRemoveAttr(2); 9815 return; 9816 } 9817 9818 if (B.isVirtual()) { 9819 PrintDiagAndRemoveAttr(3); 9820 return; 9821 } 9822 } 9823 9824 for (const auto *FD : RD.fields()) { 9825 // Ill-formed if the field is an ObjectiveC pointer or of a type that is 9826 // non-trivial for the purpose of calls. 9827 QualType FT = FD->getType(); 9828 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) { 9829 PrintDiagAndRemoveAttr(4); 9830 return; 9831 } 9832 9833 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>()) 9834 if (!RT->isDependentType() && 9835 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) { 9836 PrintDiagAndRemoveAttr(5); 9837 return; 9838 } 9839 } 9840 } 9841 9842 void Sema::ActOnFinishCXXMemberSpecification( 9843 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, 9844 SourceLocation RBrac, const ParsedAttributesView &AttrList) { 9845 if (!TagDecl) 9846 return; 9847 9848 AdjustDeclIfTemplate(TagDecl); 9849 9850 for (const ParsedAttr &AL : AttrList) { 9851 if (AL.getKind() != ParsedAttr::AT_Visibility) 9852 continue; 9853 AL.setInvalid(); 9854 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL; 9855 } 9856 9857 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 9858 // strict aliasing violation! 9859 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 9860 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 9861 9862 CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl)); 9863 } 9864 9865 /// Find the equality comparison functions that should be implicitly declared 9866 /// in a given class definition, per C++2a [class.compare.default]p3. 9867 static void findImplicitlyDeclaredEqualityComparisons( 9868 ASTContext &Ctx, CXXRecordDecl *RD, 9869 llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) { 9870 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual); 9871 if (!RD->lookup(EqEq).empty()) 9872 // Member operator== explicitly declared: no implicit operator==s. 9873 return; 9874 9875 // Traverse friends looking for an '==' or a '<=>'. 9876 for (FriendDecl *Friend : RD->friends()) { 9877 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl()); 9878 if (!FD) continue; 9879 9880 if (FD->getOverloadedOperator() == OO_EqualEqual) { 9881 // Friend operator== explicitly declared: no implicit operator==s. 9882 Spaceships.clear(); 9883 return; 9884 } 9885 9886 if (FD->getOverloadedOperator() == OO_Spaceship && 9887 FD->isExplicitlyDefaulted()) 9888 Spaceships.push_back(FD); 9889 } 9890 9891 // Look for members named 'operator<=>'. 9892 DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship); 9893 for (NamedDecl *ND : RD->lookup(Cmp)) { 9894 // Note that we could find a non-function here (either a function template 9895 // or a using-declaration). Neither case results in an implicit 9896 // 'operator=='. 9897 if (auto *FD = dyn_cast<FunctionDecl>(ND)) 9898 if (FD->isExplicitlyDefaulted()) 9899 Spaceships.push_back(FD); 9900 } 9901 } 9902 9903 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 9904 /// special functions, such as the default constructor, copy 9905 /// constructor, or destructor, to the given C++ class (C++ 9906 /// [special]p1). This routine can only be executed just before the 9907 /// definition of the class is complete. 9908 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 9909 // Don't add implicit special members to templated classes. 9910 // FIXME: This means unqualified lookups for 'operator=' within a class 9911 // template don't work properly. 9912 if (!ClassDecl->isDependentType()) { 9913 if (ClassDecl->needsImplicitDefaultConstructor()) { 9914 ++getASTContext().NumImplicitDefaultConstructors; 9915 9916 if (ClassDecl->hasInheritedConstructor()) 9917 DeclareImplicitDefaultConstructor(ClassDecl); 9918 } 9919 9920 if (ClassDecl->needsImplicitCopyConstructor()) { 9921 ++getASTContext().NumImplicitCopyConstructors; 9922 9923 // If the properties or semantics of the copy constructor couldn't be 9924 // determined while the class was being declared, force a declaration 9925 // of it now. 9926 if (ClassDecl->needsOverloadResolutionForCopyConstructor() || 9927 ClassDecl->hasInheritedConstructor()) 9928 DeclareImplicitCopyConstructor(ClassDecl); 9929 // For the MS ABI we need to know whether the copy ctor is deleted. A 9930 // prerequisite for deleting the implicit copy ctor is that the class has 9931 // a move ctor or move assignment that is either user-declared or whose 9932 // semantics are inherited from a subobject. FIXME: We should provide a 9933 // more direct way for CodeGen to ask whether the constructor was deleted. 9934 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 9935 (ClassDecl->hasUserDeclaredMoveConstructor() || 9936 ClassDecl->needsOverloadResolutionForMoveConstructor() || 9937 ClassDecl->hasUserDeclaredMoveAssignment() || 9938 ClassDecl->needsOverloadResolutionForMoveAssignment())) 9939 DeclareImplicitCopyConstructor(ClassDecl); 9940 } 9941 9942 if (getLangOpts().CPlusPlus11 && 9943 ClassDecl->needsImplicitMoveConstructor()) { 9944 ++getASTContext().NumImplicitMoveConstructors; 9945 9946 if (ClassDecl->needsOverloadResolutionForMoveConstructor() || 9947 ClassDecl->hasInheritedConstructor()) 9948 DeclareImplicitMoveConstructor(ClassDecl); 9949 } 9950 9951 if (ClassDecl->needsImplicitCopyAssignment()) { 9952 ++getASTContext().NumImplicitCopyAssignmentOperators; 9953 9954 // If we have a dynamic class, then the copy assignment operator may be 9955 // virtual, so we have to declare it immediately. This ensures that, e.g., 9956 // it shows up in the right place in the vtable and that we diagnose 9957 // problems with the implicit exception specification. 9958 if (ClassDecl->isDynamicClass() || 9959 ClassDecl->needsOverloadResolutionForCopyAssignment() || 9960 ClassDecl->hasInheritedAssignment()) 9961 DeclareImplicitCopyAssignment(ClassDecl); 9962 } 9963 9964 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 9965 ++getASTContext().NumImplicitMoveAssignmentOperators; 9966 9967 // Likewise for the move assignment operator. 9968 if (ClassDecl->isDynamicClass() || 9969 ClassDecl->needsOverloadResolutionForMoveAssignment() || 9970 ClassDecl->hasInheritedAssignment()) 9971 DeclareImplicitMoveAssignment(ClassDecl); 9972 } 9973 9974 if (ClassDecl->needsImplicitDestructor()) { 9975 ++getASTContext().NumImplicitDestructors; 9976 9977 // If we have a dynamic class, then the destructor may be virtual, so we 9978 // have to declare the destructor immediately. This ensures that, e.g., it 9979 // shows up in the right place in the vtable and that we diagnose problems 9980 // with the implicit exception specification. 9981 if (ClassDecl->isDynamicClass() || 9982 ClassDecl->needsOverloadResolutionForDestructor()) 9983 DeclareImplicitDestructor(ClassDecl); 9984 } 9985 } 9986 9987 // C++2a [class.compare.default]p3: 9988 // If the member-specification does not explicitly declare any member or 9989 // friend named operator==, an == operator function is declared implicitly 9990 // for each defaulted three-way comparison operator function defined in 9991 // the member-specification 9992 // FIXME: Consider doing this lazily. 9993 // We do this during the initial parse for a class template, not during 9994 // instantiation, so that we can handle unqualified lookups for 'operator==' 9995 // when parsing the template. 9996 if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) { 9997 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships; 9998 findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl, 9999 DefaultedSpaceships); 10000 for (auto *FD : DefaultedSpaceships) 10001 DeclareImplicitEqualityComparison(ClassDecl, FD); 10002 } 10003 } 10004 10005 unsigned 10006 Sema::ActOnReenterTemplateScope(Decl *D, 10007 llvm::function_ref<Scope *()> EnterScope) { 10008 if (!D) 10009 return 0; 10010 AdjustDeclIfTemplate(D); 10011 10012 // In order to get name lookup right, reenter template scopes in order from 10013 // outermost to innermost. 10014 SmallVector<TemplateParameterList *, 4> ParameterLists; 10015 DeclContext *LookupDC = dyn_cast<DeclContext>(D); 10016 10017 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 10018 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 10019 ParameterLists.push_back(DD->getTemplateParameterList(i)); 10020 10021 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 10022 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 10023 ParameterLists.push_back(FTD->getTemplateParameters()); 10024 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 10025 LookupDC = VD->getDeclContext(); 10026 10027 if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate()) 10028 ParameterLists.push_back(VTD->getTemplateParameters()); 10029 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D)) 10030 ParameterLists.push_back(PSD->getTemplateParameters()); 10031 } 10032 } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 10033 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 10034 ParameterLists.push_back(TD->getTemplateParameterList(i)); 10035 10036 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 10037 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 10038 ParameterLists.push_back(CTD->getTemplateParameters()); 10039 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 10040 ParameterLists.push_back(PSD->getTemplateParameters()); 10041 } 10042 } 10043 // FIXME: Alias declarations and concepts. 10044 10045 unsigned Count = 0; 10046 Scope *InnermostTemplateScope = nullptr; 10047 for (TemplateParameterList *Params : ParameterLists) { 10048 // Ignore explicit specializations; they don't contribute to the template 10049 // depth. 10050 if (Params->size() == 0) 10051 continue; 10052 10053 InnermostTemplateScope = EnterScope(); 10054 for (NamedDecl *Param : *Params) { 10055 if (Param->getDeclName()) { 10056 InnermostTemplateScope->AddDecl(Param); 10057 IdResolver.AddDecl(Param); 10058 } 10059 } 10060 ++Count; 10061 } 10062 10063 // Associate the new template scopes with the corresponding entities. 10064 if (InnermostTemplateScope) { 10065 assert(LookupDC && "no enclosing DeclContext for template lookup"); 10066 EnterTemplatedContext(InnermostTemplateScope, LookupDC); 10067 } 10068 10069 return Count; 10070 } 10071 10072 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 10073 if (!RecordD) return; 10074 AdjustDeclIfTemplate(RecordD); 10075 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 10076 PushDeclContext(S, Record); 10077 } 10078 10079 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 10080 if (!RecordD) return; 10081 PopDeclContext(); 10082 } 10083 10084 /// This is used to implement the constant expression evaluation part of the 10085 /// attribute enable_if extension. There is nothing in standard C++ which would 10086 /// require reentering parameters. 10087 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 10088 if (!Param) 10089 return; 10090 10091 S->AddDecl(Param); 10092 if (Param->getDeclName()) 10093 IdResolver.AddDecl(Param); 10094 } 10095 10096 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 10097 /// parsing a top-level (non-nested) C++ class, and we are now 10098 /// parsing those parts of the given Method declaration that could 10099 /// not be parsed earlier (C++ [class.mem]p2), such as default 10100 /// arguments. This action should enter the scope of the given 10101 /// Method declaration as if we had just parsed the qualified method 10102 /// name. However, it should not bring the parameters into scope; 10103 /// that will be performed by ActOnDelayedCXXMethodParameter. 10104 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 10105 } 10106 10107 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 10108 /// C++ method declaration. We're (re-)introducing the given 10109 /// function parameter into scope for use in parsing later parts of 10110 /// the method declaration. For example, we could see an 10111 /// ActOnParamDefaultArgument event for this parameter. 10112 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 10113 if (!ParamD) 10114 return; 10115 10116 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 10117 10118 S->AddDecl(Param); 10119 if (Param->getDeclName()) 10120 IdResolver.AddDecl(Param); 10121 } 10122 10123 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 10124 /// processing the delayed method declaration for Method. The method 10125 /// declaration is now considered finished. There may be a separate 10126 /// ActOnStartOfFunctionDef action later (not necessarily 10127 /// immediately!) for this method, if it was also defined inside the 10128 /// class body. 10129 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 10130 if (!MethodD) 10131 return; 10132 10133 AdjustDeclIfTemplate(MethodD); 10134 10135 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 10136 10137 // Now that we have our default arguments, check the constructor 10138 // again. It could produce additional diagnostics or affect whether 10139 // the class has implicitly-declared destructors, among other 10140 // things. 10141 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 10142 CheckConstructor(Constructor); 10143 10144 // Check the default arguments, which we may have added. 10145 if (!Method->isInvalidDecl()) 10146 CheckCXXDefaultArguments(Method); 10147 } 10148 10149 // Emit the given diagnostic for each non-address-space qualifier. 10150 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator. 10151 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) { 10152 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10153 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) { 10154 bool DiagOccured = false; 10155 FTI.MethodQualifiers->forEachQualifier( 10156 [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName, 10157 SourceLocation SL) { 10158 // This diagnostic should be emitted on any qualifier except an addr 10159 // space qualifier. However, forEachQualifier currently doesn't visit 10160 // addr space qualifiers, so there's no way to write this condition 10161 // right now; we just diagnose on everything. 10162 S.Diag(SL, DiagID) << QualName << SourceRange(SL); 10163 DiagOccured = true; 10164 }); 10165 if (DiagOccured) 10166 D.setInvalidType(); 10167 } 10168 } 10169 10170 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 10171 /// the well-formedness of the constructor declarator @p D with type @p 10172 /// R. If there are any errors in the declarator, this routine will 10173 /// emit diagnostics and set the invalid bit to true. In any case, the type 10174 /// will be updated to reflect a well-formed type for the constructor and 10175 /// returned. 10176 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 10177 StorageClass &SC) { 10178 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 10179 10180 // C++ [class.ctor]p3: 10181 // A constructor shall not be virtual (10.3) or static (9.4). A 10182 // constructor can be invoked for a const, volatile or const 10183 // volatile object. A constructor shall not be declared const, 10184 // volatile, or const volatile (9.3.2). 10185 if (isVirtual) { 10186 if (!D.isInvalidType()) 10187 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 10188 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 10189 << SourceRange(D.getIdentifierLoc()); 10190 D.setInvalidType(); 10191 } 10192 if (SC == SC_Static) { 10193 if (!D.isInvalidType()) 10194 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 10195 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10196 << SourceRange(D.getIdentifierLoc()); 10197 D.setInvalidType(); 10198 SC = SC_None; 10199 } 10200 10201 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 10202 diagnoseIgnoredQualifiers( 10203 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 10204 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 10205 D.getDeclSpec().getRestrictSpecLoc(), 10206 D.getDeclSpec().getAtomicSpecLoc()); 10207 D.setInvalidType(); 10208 } 10209 10210 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor); 10211 10212 // C++0x [class.ctor]p4: 10213 // A constructor shall not be declared with a ref-qualifier. 10214 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10215 if (FTI.hasRefQualifier()) { 10216 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 10217 << FTI.RefQualifierIsLValueRef 10218 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 10219 D.setInvalidType(); 10220 } 10221 10222 // Rebuild the function type "R" without any type qualifiers (in 10223 // case any of the errors above fired) and with "void" as the 10224 // return type, since constructors don't have return types. 10225 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>(); 10226 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 10227 return R; 10228 10229 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 10230 EPI.TypeQuals = Qualifiers(); 10231 EPI.RefQualifier = RQ_None; 10232 10233 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 10234 } 10235 10236 /// CheckConstructor - Checks a fully-formed constructor for 10237 /// well-formedness, issuing any diagnostics required. Returns true if 10238 /// the constructor declarator is invalid. 10239 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 10240 CXXRecordDecl *ClassDecl 10241 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 10242 if (!ClassDecl) 10243 return Constructor->setInvalidDecl(); 10244 10245 // C++ [class.copy]p3: 10246 // A declaration of a constructor for a class X is ill-formed if 10247 // its first parameter is of type (optionally cv-qualified) X and 10248 // either there are no other parameters or else all other 10249 // parameters have default arguments. 10250 if (!Constructor->isInvalidDecl() && 10251 Constructor->hasOneParamOrDefaultArgs() && 10252 Constructor->getTemplateSpecializationKind() != 10253 TSK_ImplicitInstantiation) { 10254 QualType ParamType = Constructor->getParamDecl(0)->getType(); 10255 QualType ClassTy = Context.getTagDeclType(ClassDecl); 10256 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 10257 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 10258 const char *ConstRef 10259 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 10260 : " const &"; 10261 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 10262 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 10263 10264 // FIXME: Rather that making the constructor invalid, we should endeavor 10265 // to fix the type. 10266 Constructor->setInvalidDecl(); 10267 } 10268 } 10269 } 10270 10271 /// CheckDestructor - Checks a fully-formed destructor definition for 10272 /// well-formedness, issuing any diagnostics required. Returns true 10273 /// on error. 10274 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 10275 CXXRecordDecl *RD = Destructor->getParent(); 10276 10277 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 10278 SourceLocation Loc; 10279 10280 if (!Destructor->isImplicit()) 10281 Loc = Destructor->getLocation(); 10282 else 10283 Loc = RD->getLocation(); 10284 10285 // If we have a virtual destructor, look up the deallocation function 10286 if (FunctionDecl *OperatorDelete = 10287 FindDeallocationFunctionForDestructor(Loc, RD)) { 10288 Expr *ThisArg = nullptr; 10289 10290 // If the notional 'delete this' expression requires a non-trivial 10291 // conversion from 'this' to the type of a destroying operator delete's 10292 // first parameter, perform that conversion now. 10293 if (OperatorDelete->isDestroyingOperatorDelete()) { 10294 QualType ParamType = OperatorDelete->getParamDecl(0)->getType(); 10295 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) { 10296 // C++ [class.dtor]p13: 10297 // ... as if for the expression 'delete this' appearing in a 10298 // non-virtual destructor of the destructor's class. 10299 ContextRAII SwitchContext(*this, Destructor); 10300 ExprResult This = 10301 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation()); 10302 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?"); 10303 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing); 10304 if (This.isInvalid()) { 10305 // FIXME: Register this as a context note so that it comes out 10306 // in the right order. 10307 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here); 10308 return true; 10309 } 10310 ThisArg = This.get(); 10311 } 10312 } 10313 10314 DiagnoseUseOfDecl(OperatorDelete, Loc); 10315 MarkFunctionReferenced(Loc, OperatorDelete); 10316 Destructor->setOperatorDelete(OperatorDelete, ThisArg); 10317 } 10318 } 10319 10320 return false; 10321 } 10322 10323 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 10324 /// the well-formednes of the destructor declarator @p D with type @p 10325 /// R. If there are any errors in the declarator, this routine will 10326 /// emit diagnostics and set the declarator to invalid. Even if this happens, 10327 /// will be updated to reflect a well-formed type for the destructor and 10328 /// returned. 10329 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 10330 StorageClass& SC) { 10331 // C++ [class.dtor]p1: 10332 // [...] A typedef-name that names a class is a class-name 10333 // (7.1.3); however, a typedef-name that names a class shall not 10334 // be used as the identifier in the declarator for a destructor 10335 // declaration. 10336 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 10337 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 10338 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name) 10339 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 10340 else if (const TemplateSpecializationType *TST = 10341 DeclaratorType->getAs<TemplateSpecializationType>()) 10342 if (TST->isTypeAlias()) 10343 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name) 10344 << DeclaratorType << 1; 10345 10346 // C++ [class.dtor]p2: 10347 // A destructor is used to destroy objects of its class type. A 10348 // destructor takes no parameters, and no return type can be 10349 // specified for it (not even void). The address of a destructor 10350 // shall not be taken. A destructor shall not be static. A 10351 // destructor can be invoked for a const, volatile or const 10352 // volatile object. A destructor shall not be declared const, 10353 // volatile or const volatile (9.3.2). 10354 if (SC == SC_Static) { 10355 if (!D.isInvalidType()) 10356 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 10357 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10358 << SourceRange(D.getIdentifierLoc()) 10359 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 10360 10361 SC = SC_None; 10362 } 10363 if (!D.isInvalidType()) { 10364 // Destructors don't have return types, but the parser will 10365 // happily parse something like: 10366 // 10367 // class X { 10368 // float ~X(); 10369 // }; 10370 // 10371 // The return type will be eliminated later. 10372 if (D.getDeclSpec().hasTypeSpecifier()) 10373 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 10374 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 10375 << SourceRange(D.getIdentifierLoc()); 10376 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 10377 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 10378 SourceLocation(), 10379 D.getDeclSpec().getConstSpecLoc(), 10380 D.getDeclSpec().getVolatileSpecLoc(), 10381 D.getDeclSpec().getRestrictSpecLoc(), 10382 D.getDeclSpec().getAtomicSpecLoc()); 10383 D.setInvalidType(); 10384 } 10385 } 10386 10387 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor); 10388 10389 // C++0x [class.dtor]p2: 10390 // A destructor shall not be declared with a ref-qualifier. 10391 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10392 if (FTI.hasRefQualifier()) { 10393 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 10394 << FTI.RefQualifierIsLValueRef 10395 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 10396 D.setInvalidType(); 10397 } 10398 10399 // Make sure we don't have any parameters. 10400 if (FTIHasNonVoidParameters(FTI)) { 10401 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 10402 10403 // Delete the parameters. 10404 FTI.freeParams(); 10405 D.setInvalidType(); 10406 } 10407 10408 // Make sure the destructor isn't variadic. 10409 if (FTI.isVariadic) { 10410 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 10411 D.setInvalidType(); 10412 } 10413 10414 // Rebuild the function type "R" without any type qualifiers or 10415 // parameters (in case any of the errors above fired) and with 10416 // "void" as the return type, since destructors don't have return 10417 // types. 10418 if (!D.isInvalidType()) 10419 return R; 10420 10421 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>(); 10422 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 10423 EPI.Variadic = false; 10424 EPI.TypeQuals = Qualifiers(); 10425 EPI.RefQualifier = RQ_None; 10426 return Context.getFunctionType(Context.VoidTy, None, EPI); 10427 } 10428 10429 static void extendLeft(SourceRange &R, SourceRange Before) { 10430 if (Before.isInvalid()) 10431 return; 10432 R.setBegin(Before.getBegin()); 10433 if (R.getEnd().isInvalid()) 10434 R.setEnd(Before.getEnd()); 10435 } 10436 10437 static void extendRight(SourceRange &R, SourceRange After) { 10438 if (After.isInvalid()) 10439 return; 10440 if (R.getBegin().isInvalid()) 10441 R.setBegin(After.getBegin()); 10442 R.setEnd(After.getEnd()); 10443 } 10444 10445 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 10446 /// well-formednes of the conversion function declarator @p D with 10447 /// type @p R. If there are any errors in the declarator, this routine 10448 /// will emit diagnostics and return true. Otherwise, it will return 10449 /// false. Either way, the type @p R will be updated to reflect a 10450 /// well-formed type for the conversion operator. 10451 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 10452 StorageClass& SC) { 10453 // C++ [class.conv.fct]p1: 10454 // Neither parameter types nor return type can be specified. The 10455 // type of a conversion function (8.3.5) is "function taking no 10456 // parameter returning conversion-type-id." 10457 if (SC == SC_Static) { 10458 if (!D.isInvalidType()) 10459 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 10460 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10461 << D.getName().getSourceRange(); 10462 D.setInvalidType(); 10463 SC = SC_None; 10464 } 10465 10466 TypeSourceInfo *ConvTSI = nullptr; 10467 QualType ConvType = 10468 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); 10469 10470 const DeclSpec &DS = D.getDeclSpec(); 10471 if (DS.hasTypeSpecifier() && !D.isInvalidType()) { 10472 // Conversion functions don't have return types, but the parser will 10473 // happily parse something like: 10474 // 10475 // class X { 10476 // float operator bool(); 10477 // }; 10478 // 10479 // The return type will be changed later anyway. 10480 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 10481 << SourceRange(DS.getTypeSpecTypeLoc()) 10482 << SourceRange(D.getIdentifierLoc()); 10483 D.setInvalidType(); 10484 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) { 10485 // It's also plausible that the user writes type qualifiers in the wrong 10486 // place, such as: 10487 // struct S { const operator int(); }; 10488 // FIXME: we could provide a fixit to move the qualifiers onto the 10489 // conversion type. 10490 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 10491 << SourceRange(D.getIdentifierLoc()) << 0; 10492 D.setInvalidType(); 10493 } 10494 10495 const auto *Proto = R->castAs<FunctionProtoType>(); 10496 10497 // Make sure we don't have any parameters. 10498 if (Proto->getNumParams() > 0) { 10499 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 10500 10501 // Delete the parameters. 10502 D.getFunctionTypeInfo().freeParams(); 10503 D.setInvalidType(); 10504 } else if (Proto->isVariadic()) { 10505 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 10506 D.setInvalidType(); 10507 } 10508 10509 // Diagnose "&operator bool()" and other such nonsense. This 10510 // is actually a gcc extension which we don't support. 10511 if (Proto->getReturnType() != ConvType) { 10512 bool NeedsTypedef = false; 10513 SourceRange Before, After; 10514 10515 // Walk the chunks and extract information on them for our diagnostic. 10516 bool PastFunctionChunk = false; 10517 for (auto &Chunk : D.type_objects()) { 10518 switch (Chunk.Kind) { 10519 case DeclaratorChunk::Function: 10520 if (!PastFunctionChunk) { 10521 if (Chunk.Fun.HasTrailingReturnType) { 10522 TypeSourceInfo *TRT = nullptr; 10523 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); 10524 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); 10525 } 10526 PastFunctionChunk = true; 10527 break; 10528 } 10529 LLVM_FALLTHROUGH; 10530 case DeclaratorChunk::Array: 10531 NeedsTypedef = true; 10532 extendRight(After, Chunk.getSourceRange()); 10533 break; 10534 10535 case DeclaratorChunk::Pointer: 10536 case DeclaratorChunk::BlockPointer: 10537 case DeclaratorChunk::Reference: 10538 case DeclaratorChunk::MemberPointer: 10539 case DeclaratorChunk::Pipe: 10540 extendLeft(Before, Chunk.getSourceRange()); 10541 break; 10542 10543 case DeclaratorChunk::Paren: 10544 extendLeft(Before, Chunk.Loc); 10545 extendRight(After, Chunk.EndLoc); 10546 break; 10547 } 10548 } 10549 10550 SourceLocation Loc = Before.isValid() ? Before.getBegin() : 10551 After.isValid() ? After.getBegin() : 10552 D.getIdentifierLoc(); 10553 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); 10554 DB << Before << After; 10555 10556 if (!NeedsTypedef) { 10557 DB << /*don't need a typedef*/0; 10558 10559 // If we can provide a correct fix-it hint, do so. 10560 if (After.isInvalid() && ConvTSI) { 10561 SourceLocation InsertLoc = 10562 getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc()); 10563 DB << FixItHint::CreateInsertion(InsertLoc, " ") 10564 << FixItHint::CreateInsertionFromRange( 10565 InsertLoc, CharSourceRange::getTokenRange(Before)) 10566 << FixItHint::CreateRemoval(Before); 10567 } 10568 } else if (!Proto->getReturnType()->isDependentType()) { 10569 DB << /*typedef*/1 << Proto->getReturnType(); 10570 } else if (getLangOpts().CPlusPlus11) { 10571 DB << /*alias template*/2 << Proto->getReturnType(); 10572 } else { 10573 DB << /*might not be fixable*/3; 10574 } 10575 10576 // Recover by incorporating the other type chunks into the result type. 10577 // Note, this does *not* change the name of the function. This is compatible 10578 // with the GCC extension: 10579 // struct S { &operator int(); } s; 10580 // int &r = s.operator int(); // ok in GCC 10581 // S::operator int&() {} // error in GCC, function name is 'operator int'. 10582 ConvType = Proto->getReturnType(); 10583 } 10584 10585 // C++ [class.conv.fct]p4: 10586 // The conversion-type-id shall not represent a function type nor 10587 // an array type. 10588 if (ConvType->isArrayType()) { 10589 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 10590 ConvType = Context.getPointerType(ConvType); 10591 D.setInvalidType(); 10592 } else if (ConvType->isFunctionType()) { 10593 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 10594 ConvType = Context.getPointerType(ConvType); 10595 D.setInvalidType(); 10596 } 10597 10598 // Rebuild the function type "R" without any parameters (in case any 10599 // of the errors above fired) and with the conversion type as the 10600 // return type. 10601 if (D.isInvalidType()) 10602 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 10603 10604 // C++0x explicit conversion operators. 10605 if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20) 10606 Diag(DS.getExplicitSpecLoc(), 10607 getLangOpts().CPlusPlus11 10608 ? diag::warn_cxx98_compat_explicit_conversion_functions 10609 : diag::ext_explicit_conversion_functions) 10610 << SourceRange(DS.getExplicitSpecRange()); 10611 } 10612 10613 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 10614 /// the declaration of the given C++ conversion function. This routine 10615 /// is responsible for recording the conversion function in the C++ 10616 /// class, if possible. 10617 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 10618 assert(Conversion && "Expected to receive a conversion function declaration"); 10619 10620 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 10621 10622 // Make sure we aren't redeclaring the conversion function. 10623 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 10624 // C++ [class.conv.fct]p1: 10625 // [...] A conversion function is never used to convert a 10626 // (possibly cv-qualified) object to the (possibly cv-qualified) 10627 // same object type (or a reference to it), to a (possibly 10628 // cv-qualified) base class of that type (or a reference to it), 10629 // or to (possibly cv-qualified) void. 10630 QualType ClassType 10631 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 10632 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 10633 ConvType = ConvTypeRef->getPointeeType(); 10634 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 10635 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 10636 /* Suppress diagnostics for instantiations. */; 10637 else if (Conversion->size_overridden_methods() != 0) 10638 /* Suppress diagnostics for overriding virtual function in a base class. */; 10639 else if (ConvType->isRecordType()) { 10640 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 10641 if (ConvType == ClassType) 10642 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 10643 << ClassType; 10644 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType)) 10645 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 10646 << ClassType << ConvType; 10647 } else if (ConvType->isVoidType()) { 10648 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 10649 << ClassType << ConvType; 10650 } 10651 10652 if (FunctionTemplateDecl *ConversionTemplate 10653 = Conversion->getDescribedFunctionTemplate()) 10654 return ConversionTemplate; 10655 10656 return Conversion; 10657 } 10658 10659 namespace { 10660 /// Utility class to accumulate and print a diagnostic listing the invalid 10661 /// specifier(s) on a declaration. 10662 struct BadSpecifierDiagnoser { 10663 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID) 10664 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {} 10665 ~BadSpecifierDiagnoser() { 10666 Diagnostic << Specifiers; 10667 } 10668 10669 template<typename T> void check(SourceLocation SpecLoc, T Spec) { 10670 return check(SpecLoc, DeclSpec::getSpecifierName(Spec)); 10671 } 10672 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) { 10673 return check(SpecLoc, 10674 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy())); 10675 } 10676 void check(SourceLocation SpecLoc, const char *Spec) { 10677 if (SpecLoc.isInvalid()) return; 10678 Diagnostic << SourceRange(SpecLoc, SpecLoc); 10679 if (!Specifiers.empty()) Specifiers += " "; 10680 Specifiers += Spec; 10681 } 10682 10683 Sema &S; 10684 Sema::SemaDiagnosticBuilder Diagnostic; 10685 std::string Specifiers; 10686 }; 10687 } 10688 10689 /// Check the validity of a declarator that we parsed for a deduction-guide. 10690 /// These aren't actually declarators in the grammar, so we need to check that 10691 /// the user didn't specify any pieces that are not part of the deduction-guide 10692 /// grammar. 10693 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R, 10694 StorageClass &SC) { 10695 TemplateName GuidedTemplate = D.getName().TemplateName.get().get(); 10696 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl(); 10697 assert(GuidedTemplateDecl && "missing template decl for deduction guide"); 10698 10699 // C++ [temp.deduct.guide]p3: 10700 // A deduction-gide shall be declared in the same scope as the 10701 // corresponding class template. 10702 if (!CurContext->getRedeclContext()->Equals( 10703 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) { 10704 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope) 10705 << GuidedTemplateDecl; 10706 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here); 10707 } 10708 10709 auto &DS = D.getMutableDeclSpec(); 10710 // We leave 'friend' and 'virtual' to be rejected in the normal way. 10711 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() || 10712 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() || 10713 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) { 10714 BadSpecifierDiagnoser Diagnoser( 10715 *this, D.getIdentifierLoc(), 10716 diag::err_deduction_guide_invalid_specifier); 10717 10718 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec()); 10719 DS.ClearStorageClassSpecs(); 10720 SC = SC_None; 10721 10722 // 'explicit' is permitted. 10723 Diagnoser.check(DS.getInlineSpecLoc(), "inline"); 10724 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn"); 10725 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr"); 10726 DS.ClearConstexprSpec(); 10727 10728 Diagnoser.check(DS.getConstSpecLoc(), "const"); 10729 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict"); 10730 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile"); 10731 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic"); 10732 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned"); 10733 DS.ClearTypeQualifiers(); 10734 10735 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex()); 10736 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign()); 10737 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth()); 10738 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType()); 10739 DS.ClearTypeSpecType(); 10740 } 10741 10742 if (D.isInvalidType()) 10743 return; 10744 10745 // Check the declarator is simple enough. 10746 bool FoundFunction = false; 10747 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) { 10748 if (Chunk.Kind == DeclaratorChunk::Paren) 10749 continue; 10750 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) { 10751 Diag(D.getDeclSpec().getBeginLoc(), 10752 diag::err_deduction_guide_with_complex_decl) 10753 << D.getSourceRange(); 10754 break; 10755 } 10756 if (!Chunk.Fun.hasTrailingReturnType()) { 10757 Diag(D.getName().getBeginLoc(), 10758 diag::err_deduction_guide_no_trailing_return_type); 10759 break; 10760 } 10761 10762 // Check that the return type is written as a specialization of 10763 // the template specified as the deduction-guide's name. 10764 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType(); 10765 TypeSourceInfo *TSI = nullptr; 10766 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI); 10767 assert(TSI && "deduction guide has valid type but invalid return type?"); 10768 bool AcceptableReturnType = false; 10769 bool MightInstantiateToSpecialization = false; 10770 if (auto RetTST = 10771 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) { 10772 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName(); 10773 bool TemplateMatches = 10774 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate); 10775 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches) 10776 AcceptableReturnType = true; 10777 else { 10778 // This could still instantiate to the right type, unless we know it 10779 // names the wrong class template. 10780 auto *TD = SpecifiedName.getAsTemplateDecl(); 10781 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) && 10782 !TemplateMatches); 10783 } 10784 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) { 10785 MightInstantiateToSpecialization = true; 10786 } 10787 10788 if (!AcceptableReturnType) { 10789 Diag(TSI->getTypeLoc().getBeginLoc(), 10790 diag::err_deduction_guide_bad_trailing_return_type) 10791 << GuidedTemplate << TSI->getType() 10792 << MightInstantiateToSpecialization 10793 << TSI->getTypeLoc().getSourceRange(); 10794 } 10795 10796 // Keep going to check that we don't have any inner declarator pieces (we 10797 // could still have a function returning a pointer to a function). 10798 FoundFunction = true; 10799 } 10800 10801 if (D.isFunctionDefinition()) 10802 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function); 10803 } 10804 10805 //===----------------------------------------------------------------------===// 10806 // Namespace Handling 10807 //===----------------------------------------------------------------------===// 10808 10809 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is 10810 /// reopened. 10811 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 10812 SourceLocation Loc, 10813 IdentifierInfo *II, bool *IsInline, 10814 NamespaceDecl *PrevNS) { 10815 assert(*IsInline != PrevNS->isInline()); 10816 10817 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 10818 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 10819 // inline namespaces, with the intention of bringing names into namespace std. 10820 // 10821 // We support this just well enough to get that case working; this is not 10822 // sufficient to support reopening namespaces as inline in general. 10823 if (*IsInline && II && II->getName().startswith("__atomic") && 10824 S.getSourceManager().isInSystemHeader(Loc)) { 10825 // Mark all prior declarations of the namespace as inline. 10826 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 10827 NS = NS->getPreviousDecl()) 10828 NS->setInline(*IsInline); 10829 // Patch up the lookup table for the containing namespace. This isn't really 10830 // correct, but it's good enough for this particular case. 10831 for (auto *I : PrevNS->decls()) 10832 if (auto *ND = dyn_cast<NamedDecl>(I)) 10833 PrevNS->getParent()->makeDeclVisibleInContext(ND); 10834 return; 10835 } 10836 10837 if (PrevNS->isInline()) 10838 // The user probably just forgot the 'inline', so suggest that it 10839 // be added back. 10840 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 10841 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 10842 else 10843 S.Diag(Loc, diag::err_inline_namespace_mismatch); 10844 10845 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 10846 *IsInline = PrevNS->isInline(); 10847 } 10848 10849 /// ActOnStartNamespaceDef - This is called at the start of a namespace 10850 /// definition. 10851 Decl *Sema::ActOnStartNamespaceDef( 10852 Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc, 10853 SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace, 10854 const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) { 10855 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 10856 // For anonymous namespace, take the location of the left brace. 10857 SourceLocation Loc = II ? IdentLoc : LBrace; 10858 bool IsInline = InlineLoc.isValid(); 10859 bool IsInvalid = false; 10860 bool IsStd = false; 10861 bool AddToKnown = false; 10862 Scope *DeclRegionScope = NamespcScope->getParent(); 10863 10864 NamespaceDecl *PrevNS = nullptr; 10865 if (II) { 10866 // C++ [namespace.def]p2: 10867 // The identifier in an original-namespace-definition shall not 10868 // have been previously defined in the declarative region in 10869 // which the original-namespace-definition appears. The 10870 // identifier in an original-namespace-definition is the name of 10871 // the namespace. Subsequently in that declarative region, it is 10872 // treated as an original-namespace-name. 10873 // 10874 // Since namespace names are unique in their scope, and we don't 10875 // look through using directives, just look for any ordinary names 10876 // as if by qualified name lookup. 10877 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, 10878 ForExternalRedeclaration); 10879 LookupQualifiedName(R, CurContext->getRedeclContext()); 10880 NamedDecl *PrevDecl = 10881 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr; 10882 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 10883 10884 if (PrevNS) { 10885 // This is an extended namespace definition. 10886 if (IsInline != PrevNS->isInline()) 10887 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 10888 &IsInline, PrevNS); 10889 } else if (PrevDecl) { 10890 // This is an invalid name redefinition. 10891 Diag(Loc, diag::err_redefinition_different_kind) 10892 << II; 10893 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 10894 IsInvalid = true; 10895 // Continue on to push Namespc as current DeclContext and return it. 10896 } else if (II->isStr("std") && 10897 CurContext->getRedeclContext()->isTranslationUnit()) { 10898 // This is the first "real" definition of the namespace "std", so update 10899 // our cache of the "std" namespace to point at this definition. 10900 PrevNS = getStdNamespace(); 10901 IsStd = true; 10902 AddToKnown = !IsInline; 10903 } else { 10904 // We've seen this namespace for the first time. 10905 AddToKnown = !IsInline; 10906 } 10907 } else { 10908 // Anonymous namespaces. 10909 10910 // Determine whether the parent already has an anonymous namespace. 10911 DeclContext *Parent = CurContext->getRedeclContext(); 10912 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 10913 PrevNS = TU->getAnonymousNamespace(); 10914 } else { 10915 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 10916 PrevNS = ND->getAnonymousNamespace(); 10917 } 10918 10919 if (PrevNS && IsInline != PrevNS->isInline()) 10920 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 10921 &IsInline, PrevNS); 10922 } 10923 10924 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 10925 StartLoc, Loc, II, PrevNS); 10926 if (IsInvalid) 10927 Namespc->setInvalidDecl(); 10928 10929 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 10930 AddPragmaAttributes(DeclRegionScope, Namespc); 10931 10932 // FIXME: Should we be merging attributes? 10933 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 10934 PushNamespaceVisibilityAttr(Attr, Loc); 10935 10936 if (IsStd) 10937 StdNamespace = Namespc; 10938 if (AddToKnown) 10939 KnownNamespaces[Namespc] = false; 10940 10941 if (II) { 10942 PushOnScopeChains(Namespc, DeclRegionScope); 10943 } else { 10944 // Link the anonymous namespace into its parent. 10945 DeclContext *Parent = CurContext->getRedeclContext(); 10946 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 10947 TU->setAnonymousNamespace(Namespc); 10948 } else { 10949 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 10950 } 10951 10952 CurContext->addDecl(Namespc); 10953 10954 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 10955 // behaves as if it were replaced by 10956 // namespace unique { /* empty body */ } 10957 // using namespace unique; 10958 // namespace unique { namespace-body } 10959 // where all occurrences of 'unique' in a translation unit are 10960 // replaced by the same identifier and this identifier differs 10961 // from all other identifiers in the entire program. 10962 10963 // We just create the namespace with an empty name and then add an 10964 // implicit using declaration, just like the standard suggests. 10965 // 10966 // CodeGen enforces the "universally unique" aspect by giving all 10967 // declarations semantically contained within an anonymous 10968 // namespace internal linkage. 10969 10970 if (!PrevNS) { 10971 UD = UsingDirectiveDecl::Create(Context, Parent, 10972 /* 'using' */ LBrace, 10973 /* 'namespace' */ SourceLocation(), 10974 /* qualifier */ NestedNameSpecifierLoc(), 10975 /* identifier */ SourceLocation(), 10976 Namespc, 10977 /* Ancestor */ Parent); 10978 UD->setImplicit(); 10979 Parent->addDecl(UD); 10980 } 10981 } 10982 10983 ActOnDocumentableDecl(Namespc); 10984 10985 // Although we could have an invalid decl (i.e. the namespace name is a 10986 // redefinition), push it as current DeclContext and try to continue parsing. 10987 // FIXME: We should be able to push Namespc here, so that the each DeclContext 10988 // for the namespace has the declarations that showed up in that particular 10989 // namespace definition. 10990 PushDeclContext(NamespcScope, Namespc); 10991 return Namespc; 10992 } 10993 10994 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 10995 /// is a namespace alias, returns the namespace it points to. 10996 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 10997 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 10998 return AD->getNamespace(); 10999 return dyn_cast_or_null<NamespaceDecl>(D); 11000 } 11001 11002 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 11003 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 11004 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 11005 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 11006 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 11007 Namespc->setRBraceLoc(RBrace); 11008 PopDeclContext(); 11009 if (Namespc->hasAttr<VisibilityAttr>()) 11010 PopPragmaVisibility(true, RBrace); 11011 // If this namespace contains an export-declaration, export it now. 11012 if (DeferredExportedNamespaces.erase(Namespc)) 11013 Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported); 11014 } 11015 11016 CXXRecordDecl *Sema::getStdBadAlloc() const { 11017 return cast_or_null<CXXRecordDecl>( 11018 StdBadAlloc.get(Context.getExternalSource())); 11019 } 11020 11021 EnumDecl *Sema::getStdAlignValT() const { 11022 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource())); 11023 } 11024 11025 NamespaceDecl *Sema::getStdNamespace() const { 11026 return cast_or_null<NamespaceDecl>( 11027 StdNamespace.get(Context.getExternalSource())); 11028 } 11029 11030 NamespaceDecl *Sema::lookupStdExperimentalNamespace() { 11031 if (!StdExperimentalNamespaceCache) { 11032 if (auto Std = getStdNamespace()) { 11033 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"), 11034 SourceLocation(), LookupNamespaceName); 11035 if (!LookupQualifiedName(Result, Std) || 11036 !(StdExperimentalNamespaceCache = 11037 Result.getAsSingle<NamespaceDecl>())) 11038 Result.suppressDiagnostics(); 11039 } 11040 } 11041 return StdExperimentalNamespaceCache; 11042 } 11043 11044 namespace { 11045 11046 enum UnsupportedSTLSelect { 11047 USS_InvalidMember, 11048 USS_MissingMember, 11049 USS_NonTrivial, 11050 USS_Other 11051 }; 11052 11053 struct InvalidSTLDiagnoser { 11054 Sema &S; 11055 SourceLocation Loc; 11056 QualType TyForDiags; 11057 11058 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "", 11059 const VarDecl *VD = nullptr) { 11060 { 11061 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported) 11062 << TyForDiags << ((int)Sel); 11063 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) { 11064 assert(!Name.empty()); 11065 D << Name; 11066 } 11067 } 11068 if (Sel == USS_InvalidMember) { 11069 S.Diag(VD->getLocation(), diag::note_var_declared_here) 11070 << VD << VD->getSourceRange(); 11071 } 11072 return QualType(); 11073 } 11074 }; 11075 } // namespace 11076 11077 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind, 11078 SourceLocation Loc, 11079 ComparisonCategoryUsage Usage) { 11080 assert(getLangOpts().CPlusPlus && 11081 "Looking for comparison category type outside of C++."); 11082 11083 // Use an elaborated type for diagnostics which has a name containing the 11084 // prepended 'std' namespace but not any inline namespace names. 11085 auto TyForDiags = [&](ComparisonCategoryInfo *Info) { 11086 auto *NNS = 11087 NestedNameSpecifier::Create(Context, nullptr, getStdNamespace()); 11088 return Context.getElaboratedType(ETK_None, NNS, Info->getType()); 11089 }; 11090 11091 // Check if we've already successfully checked the comparison category type 11092 // before. If so, skip checking it again. 11093 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind); 11094 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) { 11095 // The only thing we need to check is that the type has a reachable 11096 // definition in the current context. 11097 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type)) 11098 return QualType(); 11099 11100 return Info->getType(); 11101 } 11102 11103 // If lookup failed 11104 if (!Info) { 11105 std::string NameForDiags = "std::"; 11106 NameForDiags += ComparisonCategories::getCategoryString(Kind); 11107 Diag(Loc, diag::err_implied_comparison_category_type_not_found) 11108 << NameForDiags << (int)Usage; 11109 return QualType(); 11110 } 11111 11112 assert(Info->Kind == Kind); 11113 assert(Info->Record); 11114 11115 // Update the Record decl in case we encountered a forward declaration on our 11116 // first pass. FIXME: This is a bit of a hack. 11117 if (Info->Record->hasDefinition()) 11118 Info->Record = Info->Record->getDefinition(); 11119 11120 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type)) 11121 return QualType(); 11122 11123 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)}; 11124 11125 if (!Info->Record->isTriviallyCopyable()) 11126 return UnsupportedSTLError(USS_NonTrivial); 11127 11128 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) { 11129 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl(); 11130 // Tolerate empty base classes. 11131 if (Base->isEmpty()) 11132 continue; 11133 // Reject STL implementations which have at least one non-empty base. 11134 return UnsupportedSTLError(); 11135 } 11136 11137 // Check that the STL has implemented the types using a single integer field. 11138 // This expectation allows better codegen for builtin operators. We require: 11139 // (1) The class has exactly one field. 11140 // (2) The field is an integral or enumeration type. 11141 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end(); 11142 if (std::distance(FIt, FEnd) != 1 || 11143 !FIt->getType()->isIntegralOrEnumerationType()) { 11144 return UnsupportedSTLError(); 11145 } 11146 11147 // Build each of the require values and store them in Info. 11148 for (ComparisonCategoryResult CCR : 11149 ComparisonCategories::getPossibleResultsForType(Kind)) { 11150 StringRef MemName = ComparisonCategories::getResultString(CCR); 11151 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR); 11152 11153 if (!ValInfo) 11154 return UnsupportedSTLError(USS_MissingMember, MemName); 11155 11156 VarDecl *VD = ValInfo->VD; 11157 assert(VD && "should not be null!"); 11158 11159 // Attempt to diagnose reasons why the STL definition of this type 11160 // might be foobar, including it failing to be a constant expression. 11161 // TODO Handle more ways the lookup or result can be invalid. 11162 if (!VD->isStaticDataMember() || 11163 !VD->isUsableInConstantExpressions(Context)) 11164 return UnsupportedSTLError(USS_InvalidMember, MemName, VD); 11165 11166 // Attempt to evaluate the var decl as a constant expression and extract 11167 // the value of its first field as a ICE. If this fails, the STL 11168 // implementation is not supported. 11169 if (!ValInfo->hasValidIntValue()) 11170 return UnsupportedSTLError(); 11171 11172 MarkVariableReferenced(Loc, VD); 11173 } 11174 11175 // We've successfully built the required types and expressions. Update 11176 // the cache and return the newly cached value. 11177 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true; 11178 return Info->getType(); 11179 } 11180 11181 /// Retrieve the special "std" namespace, which may require us to 11182 /// implicitly define the namespace. 11183 NamespaceDecl *Sema::getOrCreateStdNamespace() { 11184 if (!StdNamespace) { 11185 // The "std" namespace has not yet been defined, so build one implicitly. 11186 StdNamespace = NamespaceDecl::Create(Context, 11187 Context.getTranslationUnitDecl(), 11188 /*Inline=*/false, 11189 SourceLocation(), SourceLocation(), 11190 &PP.getIdentifierTable().get("std"), 11191 /*PrevDecl=*/nullptr); 11192 getStdNamespace()->setImplicit(true); 11193 } 11194 11195 return getStdNamespace(); 11196 } 11197 11198 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 11199 assert(getLangOpts().CPlusPlus && 11200 "Looking for std::initializer_list outside of C++."); 11201 11202 // We're looking for implicit instantiations of 11203 // template <typename E> class std::initializer_list. 11204 11205 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 11206 return false; 11207 11208 ClassTemplateDecl *Template = nullptr; 11209 const TemplateArgument *Arguments = nullptr; 11210 11211 if (const RecordType *RT = Ty->getAs<RecordType>()) { 11212 11213 ClassTemplateSpecializationDecl *Specialization = 11214 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 11215 if (!Specialization) 11216 return false; 11217 11218 Template = Specialization->getSpecializedTemplate(); 11219 Arguments = Specialization->getTemplateArgs().data(); 11220 } else if (const TemplateSpecializationType *TST = 11221 Ty->getAs<TemplateSpecializationType>()) { 11222 Template = dyn_cast_or_null<ClassTemplateDecl>( 11223 TST->getTemplateName().getAsTemplateDecl()); 11224 Arguments = TST->getArgs(); 11225 } 11226 if (!Template) 11227 return false; 11228 11229 if (!StdInitializerList) { 11230 // Haven't recognized std::initializer_list yet, maybe this is it. 11231 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 11232 if (TemplateClass->getIdentifier() != 11233 &PP.getIdentifierTable().get("initializer_list") || 11234 !getStdNamespace()->InEnclosingNamespaceSetOf( 11235 TemplateClass->getDeclContext())) 11236 return false; 11237 // This is a template called std::initializer_list, but is it the right 11238 // template? 11239 TemplateParameterList *Params = Template->getTemplateParameters(); 11240 if (Params->getMinRequiredArguments() != 1) 11241 return false; 11242 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 11243 return false; 11244 11245 // It's the right template. 11246 StdInitializerList = Template; 11247 } 11248 11249 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) 11250 return false; 11251 11252 // This is an instance of std::initializer_list. Find the argument type. 11253 if (Element) 11254 *Element = Arguments[0].getAsType(); 11255 return true; 11256 } 11257 11258 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 11259 NamespaceDecl *Std = S.getStdNamespace(); 11260 if (!Std) { 11261 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 11262 return nullptr; 11263 } 11264 11265 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 11266 Loc, Sema::LookupOrdinaryName); 11267 if (!S.LookupQualifiedName(Result, Std)) { 11268 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 11269 return nullptr; 11270 } 11271 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 11272 if (!Template) { 11273 Result.suppressDiagnostics(); 11274 // We found something weird. Complain about the first thing we found. 11275 NamedDecl *Found = *Result.begin(); 11276 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 11277 return nullptr; 11278 } 11279 11280 // We found some template called std::initializer_list. Now verify that it's 11281 // correct. 11282 TemplateParameterList *Params = Template->getTemplateParameters(); 11283 if (Params->getMinRequiredArguments() != 1 || 11284 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 11285 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 11286 return nullptr; 11287 } 11288 11289 return Template; 11290 } 11291 11292 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 11293 if (!StdInitializerList) { 11294 StdInitializerList = LookupStdInitializerList(*this, Loc); 11295 if (!StdInitializerList) 11296 return QualType(); 11297 } 11298 11299 TemplateArgumentListInfo Args(Loc, Loc); 11300 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 11301 Context.getTrivialTypeSourceInfo(Element, 11302 Loc))); 11303 return Context.getCanonicalType( 11304 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 11305 } 11306 11307 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) { 11308 // C++ [dcl.init.list]p2: 11309 // A constructor is an initializer-list constructor if its first parameter 11310 // is of type std::initializer_list<E> or reference to possibly cv-qualified 11311 // std::initializer_list<E> for some type E, and either there are no other 11312 // parameters or else all other parameters have default arguments. 11313 if (!Ctor->hasOneParamOrDefaultArgs()) 11314 return false; 11315 11316 QualType ArgType = Ctor->getParamDecl(0)->getType(); 11317 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 11318 ArgType = RT->getPointeeType().getUnqualifiedType(); 11319 11320 return isStdInitializerList(ArgType, nullptr); 11321 } 11322 11323 /// Determine whether a using statement is in a context where it will be 11324 /// apply in all contexts. 11325 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 11326 switch (CurContext->getDeclKind()) { 11327 case Decl::TranslationUnit: 11328 return true; 11329 case Decl::LinkageSpec: 11330 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 11331 default: 11332 return false; 11333 } 11334 } 11335 11336 namespace { 11337 11338 // Callback to only accept typo corrections that are namespaces. 11339 class NamespaceValidatorCCC final : public CorrectionCandidateCallback { 11340 public: 11341 bool ValidateCandidate(const TypoCorrection &candidate) override { 11342 if (NamedDecl *ND = candidate.getCorrectionDecl()) 11343 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 11344 return false; 11345 } 11346 11347 std::unique_ptr<CorrectionCandidateCallback> clone() override { 11348 return std::make_unique<NamespaceValidatorCCC>(*this); 11349 } 11350 }; 11351 11352 } 11353 11354 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 11355 CXXScopeSpec &SS, 11356 SourceLocation IdentLoc, 11357 IdentifierInfo *Ident) { 11358 R.clear(); 11359 NamespaceValidatorCCC CCC{}; 11360 if (TypoCorrection Corrected = 11361 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC, 11362 Sema::CTK_ErrorRecovery)) { 11363 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 11364 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 11365 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 11366 Ident->getName().equals(CorrectedStr); 11367 S.diagnoseTypo(Corrected, 11368 S.PDiag(diag::err_using_directive_member_suggest) 11369 << Ident << DC << DroppedSpecifier << SS.getRange(), 11370 S.PDiag(diag::note_namespace_defined_here)); 11371 } else { 11372 S.diagnoseTypo(Corrected, 11373 S.PDiag(diag::err_using_directive_suggest) << Ident, 11374 S.PDiag(diag::note_namespace_defined_here)); 11375 } 11376 R.addDecl(Corrected.getFoundDecl()); 11377 return true; 11378 } 11379 return false; 11380 } 11381 11382 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc, 11383 SourceLocation NamespcLoc, CXXScopeSpec &SS, 11384 SourceLocation IdentLoc, 11385 IdentifierInfo *NamespcName, 11386 const ParsedAttributesView &AttrList) { 11387 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 11388 assert(NamespcName && "Invalid NamespcName."); 11389 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 11390 11391 // This can only happen along a recovery path. 11392 while (S->isTemplateParamScope()) 11393 S = S->getParent(); 11394 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 11395 11396 UsingDirectiveDecl *UDir = nullptr; 11397 NestedNameSpecifier *Qualifier = nullptr; 11398 if (SS.isSet()) 11399 Qualifier = SS.getScopeRep(); 11400 11401 // Lookup namespace name. 11402 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 11403 LookupParsedName(R, S, &SS); 11404 if (R.isAmbiguous()) 11405 return nullptr; 11406 11407 if (R.empty()) { 11408 R.clear(); 11409 // Allow "using namespace std;" or "using namespace ::std;" even if 11410 // "std" hasn't been defined yet, for GCC compatibility. 11411 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 11412 NamespcName->isStr("std")) { 11413 Diag(IdentLoc, diag::ext_using_undefined_std); 11414 R.addDecl(getOrCreateStdNamespace()); 11415 R.resolveKind(); 11416 } 11417 // Otherwise, attempt typo correction. 11418 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 11419 } 11420 11421 if (!R.empty()) { 11422 NamedDecl *Named = R.getRepresentativeDecl(); 11423 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>(); 11424 assert(NS && "expected namespace decl"); 11425 11426 // The use of a nested name specifier may trigger deprecation warnings. 11427 DiagnoseUseOfDecl(Named, IdentLoc); 11428 11429 // C++ [namespace.udir]p1: 11430 // A using-directive specifies that the names in the nominated 11431 // namespace can be used in the scope in which the 11432 // using-directive appears after the using-directive. During 11433 // unqualified name lookup (3.4.1), the names appear as if they 11434 // were declared in the nearest enclosing namespace which 11435 // contains both the using-directive and the nominated 11436 // namespace. [Note: in this context, "contains" means "contains 11437 // directly or indirectly". ] 11438 11439 // Find enclosing context containing both using-directive and 11440 // nominated namespace. 11441 DeclContext *CommonAncestor = NS; 11442 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 11443 CommonAncestor = CommonAncestor->getParent(); 11444 11445 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 11446 SS.getWithLocInContext(Context), 11447 IdentLoc, Named, CommonAncestor); 11448 11449 if (IsUsingDirectiveInToplevelContext(CurContext) && 11450 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 11451 Diag(IdentLoc, diag::warn_using_directive_in_header); 11452 } 11453 11454 PushUsingDirective(S, UDir); 11455 } else { 11456 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 11457 } 11458 11459 if (UDir) 11460 ProcessDeclAttributeList(S, UDir, AttrList); 11461 11462 return UDir; 11463 } 11464 11465 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 11466 // If the scope has an associated entity and the using directive is at 11467 // namespace or translation unit scope, add the UsingDirectiveDecl into 11468 // its lookup structure so qualified name lookup can find it. 11469 DeclContext *Ctx = S->getEntity(); 11470 if (Ctx && !Ctx->isFunctionOrMethod()) 11471 Ctx->addDecl(UDir); 11472 else 11473 // Otherwise, it is at block scope. The using-directives will affect lookup 11474 // only to the end of the scope. 11475 S->PushUsingDirective(UDir); 11476 } 11477 11478 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS, 11479 SourceLocation UsingLoc, 11480 SourceLocation TypenameLoc, CXXScopeSpec &SS, 11481 UnqualifiedId &Name, 11482 SourceLocation EllipsisLoc, 11483 const ParsedAttributesView &AttrList) { 11484 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 11485 11486 if (SS.isEmpty()) { 11487 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname); 11488 return nullptr; 11489 } 11490 11491 switch (Name.getKind()) { 11492 case UnqualifiedIdKind::IK_ImplicitSelfParam: 11493 case UnqualifiedIdKind::IK_Identifier: 11494 case UnqualifiedIdKind::IK_OperatorFunctionId: 11495 case UnqualifiedIdKind::IK_LiteralOperatorId: 11496 case UnqualifiedIdKind::IK_ConversionFunctionId: 11497 break; 11498 11499 case UnqualifiedIdKind::IK_ConstructorName: 11500 case UnqualifiedIdKind::IK_ConstructorTemplateId: 11501 // C++11 inheriting constructors. 11502 Diag(Name.getBeginLoc(), 11503 getLangOpts().CPlusPlus11 11504 ? diag::warn_cxx98_compat_using_decl_constructor 11505 : diag::err_using_decl_constructor) 11506 << SS.getRange(); 11507 11508 if (getLangOpts().CPlusPlus11) break; 11509 11510 return nullptr; 11511 11512 case UnqualifiedIdKind::IK_DestructorName: 11513 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange(); 11514 return nullptr; 11515 11516 case UnqualifiedIdKind::IK_TemplateId: 11517 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id) 11518 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 11519 return nullptr; 11520 11521 case UnqualifiedIdKind::IK_DeductionGuideName: 11522 llvm_unreachable("cannot parse qualified deduction guide name"); 11523 } 11524 11525 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 11526 DeclarationName TargetName = TargetNameInfo.getName(); 11527 if (!TargetName) 11528 return nullptr; 11529 11530 // Warn about access declarations. 11531 if (UsingLoc.isInvalid()) { 11532 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11 11533 ? diag::err_access_decl 11534 : diag::warn_access_decl_deprecated) 11535 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 11536 } 11537 11538 if (EllipsisLoc.isInvalid()) { 11539 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 11540 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 11541 return nullptr; 11542 } else { 11543 if (!SS.getScopeRep()->containsUnexpandedParameterPack() && 11544 !TargetNameInfo.containsUnexpandedParameterPack()) { 11545 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 11546 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc()); 11547 EllipsisLoc = SourceLocation(); 11548 } 11549 } 11550 11551 NamedDecl *UD = 11552 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc, 11553 SS, TargetNameInfo, EllipsisLoc, AttrList, 11554 /*IsInstantiation*/false); 11555 if (UD) 11556 PushOnScopeChains(UD, S, /*AddToContext*/ false); 11557 11558 return UD; 11559 } 11560 11561 /// Determine whether a using declaration considers the given 11562 /// declarations as "equivalent", e.g., if they are redeclarations of 11563 /// the same entity or are both typedefs of the same type. 11564 static bool 11565 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 11566 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 11567 return true; 11568 11569 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 11570 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 11571 return Context.hasSameType(TD1->getUnderlyingType(), 11572 TD2->getUnderlyingType()); 11573 11574 return false; 11575 } 11576 11577 11578 /// Determines whether to create a using shadow decl for a particular 11579 /// decl, given the set of decls existing prior to this using lookup. 11580 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 11581 const LookupResult &Previous, 11582 UsingShadowDecl *&PrevShadow) { 11583 // Diagnose finding a decl which is not from a base class of the 11584 // current class. We do this now because there are cases where this 11585 // function will silently decide not to build a shadow decl, which 11586 // will pre-empt further diagnostics. 11587 // 11588 // We don't need to do this in C++11 because we do the check once on 11589 // the qualifier. 11590 // 11591 // FIXME: diagnose the following if we care enough: 11592 // struct A { int foo; }; 11593 // struct B : A { using A::foo; }; 11594 // template <class T> struct C : A {}; 11595 // template <class T> struct D : C<T> { using B::foo; } // <--- 11596 // This is invalid (during instantiation) in C++03 because B::foo 11597 // resolves to the using decl in B, which is not a base class of D<T>. 11598 // We can't diagnose it immediately because C<T> is an unknown 11599 // specialization. The UsingShadowDecl in D<T> then points directly 11600 // to A::foo, which will look well-formed when we instantiate. 11601 // The right solution is to not collapse the shadow-decl chain. 11602 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 11603 DeclContext *OrigDC = Orig->getDeclContext(); 11604 11605 // Handle enums and anonymous structs. 11606 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 11607 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 11608 while (OrigRec->isAnonymousStructOrUnion()) 11609 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 11610 11611 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 11612 if (OrigDC == CurContext) { 11613 Diag(Using->getLocation(), 11614 diag::err_using_decl_nested_name_specifier_is_current_class) 11615 << Using->getQualifierLoc().getSourceRange(); 11616 Diag(Orig->getLocation(), diag::note_using_decl_target); 11617 Using->setInvalidDecl(); 11618 return true; 11619 } 11620 11621 Diag(Using->getQualifierLoc().getBeginLoc(), 11622 diag::err_using_decl_nested_name_specifier_is_not_base_class) 11623 << Using->getQualifier() 11624 << cast<CXXRecordDecl>(CurContext) 11625 << Using->getQualifierLoc().getSourceRange(); 11626 Diag(Orig->getLocation(), diag::note_using_decl_target); 11627 Using->setInvalidDecl(); 11628 return true; 11629 } 11630 } 11631 11632 if (Previous.empty()) return false; 11633 11634 NamedDecl *Target = Orig; 11635 if (isa<UsingShadowDecl>(Target)) 11636 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 11637 11638 // If the target happens to be one of the previous declarations, we 11639 // don't have a conflict. 11640 // 11641 // FIXME: but we might be increasing its access, in which case we 11642 // should redeclare it. 11643 NamedDecl *NonTag = nullptr, *Tag = nullptr; 11644 bool FoundEquivalentDecl = false; 11645 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 11646 I != E; ++I) { 11647 NamedDecl *D = (*I)->getUnderlyingDecl(); 11648 // We can have UsingDecls in our Previous results because we use the same 11649 // LookupResult for checking whether the UsingDecl itself is a valid 11650 // redeclaration. 11651 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D)) 11652 continue; 11653 11654 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 11655 // C++ [class.mem]p19: 11656 // If T is the name of a class, then [every named member other than 11657 // a non-static data member] shall have a name different from T 11658 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) && 11659 !isa<IndirectFieldDecl>(Target) && 11660 !isa<UnresolvedUsingValueDecl>(Target) && 11661 DiagnoseClassNameShadow( 11662 CurContext, 11663 DeclarationNameInfo(Using->getDeclName(), Using->getLocation()))) 11664 return true; 11665 } 11666 11667 if (IsEquivalentForUsingDecl(Context, D, Target)) { 11668 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 11669 PrevShadow = Shadow; 11670 FoundEquivalentDecl = true; 11671 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) { 11672 // We don't conflict with an existing using shadow decl of an equivalent 11673 // declaration, but we're not a redeclaration of it. 11674 FoundEquivalentDecl = true; 11675 } 11676 11677 if (isVisible(D)) 11678 (isa<TagDecl>(D) ? Tag : NonTag) = D; 11679 } 11680 11681 if (FoundEquivalentDecl) 11682 return false; 11683 11684 if (FunctionDecl *FD = Target->getAsFunction()) { 11685 NamedDecl *OldDecl = nullptr; 11686 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 11687 /*IsForUsingDecl*/ true)) { 11688 case Ovl_Overload: 11689 return false; 11690 11691 case Ovl_NonFunction: 11692 Diag(Using->getLocation(), diag::err_using_decl_conflict); 11693 break; 11694 11695 // We found a decl with the exact signature. 11696 case Ovl_Match: 11697 // If we're in a record, we want to hide the target, so we 11698 // return true (without a diagnostic) to tell the caller not to 11699 // build a shadow decl. 11700 if (CurContext->isRecord()) 11701 return true; 11702 11703 // If we're not in a record, this is an error. 11704 Diag(Using->getLocation(), diag::err_using_decl_conflict); 11705 break; 11706 } 11707 11708 Diag(Target->getLocation(), diag::note_using_decl_target); 11709 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 11710 Using->setInvalidDecl(); 11711 return true; 11712 } 11713 11714 // Target is not a function. 11715 11716 if (isa<TagDecl>(Target)) { 11717 // No conflict between a tag and a non-tag. 11718 if (!Tag) return false; 11719 11720 Diag(Using->getLocation(), diag::err_using_decl_conflict); 11721 Diag(Target->getLocation(), diag::note_using_decl_target); 11722 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 11723 Using->setInvalidDecl(); 11724 return true; 11725 } 11726 11727 // No conflict between a tag and a non-tag. 11728 if (!NonTag) return false; 11729 11730 Diag(Using->getLocation(), diag::err_using_decl_conflict); 11731 Diag(Target->getLocation(), diag::note_using_decl_target); 11732 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 11733 Using->setInvalidDecl(); 11734 return true; 11735 } 11736 11737 /// Determine whether a direct base class is a virtual base class. 11738 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) { 11739 if (!Derived->getNumVBases()) 11740 return false; 11741 for (auto &B : Derived->bases()) 11742 if (B.getType()->getAsCXXRecordDecl() == Base) 11743 return B.isVirtual(); 11744 llvm_unreachable("not a direct base class"); 11745 } 11746 11747 /// Builds a shadow declaration corresponding to a 'using' declaration. 11748 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 11749 UsingDecl *UD, 11750 NamedDecl *Orig, 11751 UsingShadowDecl *PrevDecl) { 11752 // If we resolved to another shadow declaration, just coalesce them. 11753 NamedDecl *Target = Orig; 11754 if (isa<UsingShadowDecl>(Target)) { 11755 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 11756 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 11757 } 11758 11759 NamedDecl *NonTemplateTarget = Target; 11760 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target)) 11761 NonTemplateTarget = TargetTD->getTemplatedDecl(); 11762 11763 UsingShadowDecl *Shadow; 11764 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) { 11765 bool IsVirtualBase = 11766 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext), 11767 UD->getQualifier()->getAsRecordDecl()); 11768 Shadow = ConstructorUsingShadowDecl::Create( 11769 Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase); 11770 } else { 11771 Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD, 11772 Target); 11773 } 11774 UD->addShadowDecl(Shadow); 11775 11776 Shadow->setAccess(UD->getAccess()); 11777 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 11778 Shadow->setInvalidDecl(); 11779 11780 Shadow->setPreviousDecl(PrevDecl); 11781 11782 if (S) 11783 PushOnScopeChains(Shadow, S); 11784 else 11785 CurContext->addDecl(Shadow); 11786 11787 11788 return Shadow; 11789 } 11790 11791 /// Hides a using shadow declaration. This is required by the current 11792 /// using-decl implementation when a resolvable using declaration in a 11793 /// class is followed by a declaration which would hide or override 11794 /// one or more of the using decl's targets; for example: 11795 /// 11796 /// struct Base { void foo(int); }; 11797 /// struct Derived : Base { 11798 /// using Base::foo; 11799 /// void foo(int); 11800 /// }; 11801 /// 11802 /// The governing language is C++03 [namespace.udecl]p12: 11803 /// 11804 /// When a using-declaration brings names from a base class into a 11805 /// derived class scope, member functions in the derived class 11806 /// override and/or hide member functions with the same name and 11807 /// parameter types in a base class (rather than conflicting). 11808 /// 11809 /// There are two ways to implement this: 11810 /// (1) optimistically create shadow decls when they're not hidden 11811 /// by existing declarations, or 11812 /// (2) don't create any shadow decls (or at least don't make them 11813 /// visible) until we've fully parsed/instantiated the class. 11814 /// The problem with (1) is that we might have to retroactively remove 11815 /// a shadow decl, which requires several O(n) operations because the 11816 /// decl structures are (very reasonably) not designed for removal. 11817 /// (2) avoids this but is very fiddly and phase-dependent. 11818 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 11819 if (Shadow->getDeclName().getNameKind() == 11820 DeclarationName::CXXConversionFunctionName) 11821 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 11822 11823 // Remove it from the DeclContext... 11824 Shadow->getDeclContext()->removeDecl(Shadow); 11825 11826 // ...and the scope, if applicable... 11827 if (S) { 11828 S->RemoveDecl(Shadow); 11829 IdResolver.RemoveDecl(Shadow); 11830 } 11831 11832 // ...and the using decl. 11833 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 11834 11835 // TODO: complain somehow if Shadow was used. It shouldn't 11836 // be possible for this to happen, because...? 11837 } 11838 11839 /// Find the base specifier for a base class with the given type. 11840 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 11841 QualType DesiredBase, 11842 bool &AnyDependentBases) { 11843 // Check whether the named type is a direct base class. 11844 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified() 11845 .getUnqualifiedType(); 11846 for (auto &Base : Derived->bases()) { 11847 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 11848 if (CanonicalDesiredBase == BaseType) 11849 return &Base; 11850 if (BaseType->isDependentType()) 11851 AnyDependentBases = true; 11852 } 11853 return nullptr; 11854 } 11855 11856 namespace { 11857 class UsingValidatorCCC final : public CorrectionCandidateCallback { 11858 public: 11859 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 11860 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 11861 : HasTypenameKeyword(HasTypenameKeyword), 11862 IsInstantiation(IsInstantiation), OldNNS(NNS), 11863 RequireMemberOf(RequireMemberOf) {} 11864 11865 bool ValidateCandidate(const TypoCorrection &Candidate) override { 11866 NamedDecl *ND = Candidate.getCorrectionDecl(); 11867 11868 // Keywords are not valid here. 11869 if (!ND || isa<NamespaceDecl>(ND)) 11870 return false; 11871 11872 // Completely unqualified names are invalid for a 'using' declaration. 11873 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 11874 return false; 11875 11876 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would 11877 // reject. 11878 11879 if (RequireMemberOf) { 11880 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 11881 if (FoundRecord && FoundRecord->isInjectedClassName()) { 11882 // No-one ever wants a using-declaration to name an injected-class-name 11883 // of a base class, unless they're declaring an inheriting constructor. 11884 ASTContext &Ctx = ND->getASTContext(); 11885 if (!Ctx.getLangOpts().CPlusPlus11) 11886 return false; 11887 QualType FoundType = Ctx.getRecordType(FoundRecord); 11888 11889 // Check that the injected-class-name is named as a member of its own 11890 // type; we don't want to suggest 'using Derived::Base;', since that 11891 // means something else. 11892 NestedNameSpecifier *Specifier = 11893 Candidate.WillReplaceSpecifier() 11894 ? Candidate.getCorrectionSpecifier() 11895 : OldNNS; 11896 if (!Specifier->getAsType() || 11897 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 11898 return false; 11899 11900 // Check that this inheriting constructor declaration actually names a 11901 // direct base class of the current class. 11902 bool AnyDependentBases = false; 11903 if (!findDirectBaseWithType(RequireMemberOf, 11904 Ctx.getRecordType(FoundRecord), 11905 AnyDependentBases) && 11906 !AnyDependentBases) 11907 return false; 11908 } else { 11909 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 11910 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 11911 return false; 11912 11913 // FIXME: Check that the base class member is accessible? 11914 } 11915 } else { 11916 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 11917 if (FoundRecord && FoundRecord->isInjectedClassName()) 11918 return false; 11919 } 11920 11921 if (isa<TypeDecl>(ND)) 11922 return HasTypenameKeyword || !IsInstantiation; 11923 11924 return !HasTypenameKeyword; 11925 } 11926 11927 std::unique_ptr<CorrectionCandidateCallback> clone() override { 11928 return std::make_unique<UsingValidatorCCC>(*this); 11929 } 11930 11931 private: 11932 bool HasTypenameKeyword; 11933 bool IsInstantiation; 11934 NestedNameSpecifier *OldNNS; 11935 CXXRecordDecl *RequireMemberOf; 11936 }; 11937 } // end anonymous namespace 11938 11939 /// Builds a using declaration. 11940 /// 11941 /// \param IsInstantiation - Whether this call arises from an 11942 /// instantiation of an unresolved using declaration. We treat 11943 /// the lookup differently for these declarations. 11944 NamedDecl *Sema::BuildUsingDeclaration( 11945 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, 11946 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, 11947 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, 11948 const ParsedAttributesView &AttrList, bool IsInstantiation) { 11949 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 11950 SourceLocation IdentLoc = NameInfo.getLoc(); 11951 assert(IdentLoc.isValid() && "Invalid TargetName location."); 11952 11953 // FIXME: We ignore attributes for now. 11954 11955 // For an inheriting constructor declaration, the name of the using 11956 // declaration is the name of a constructor in this class, not in the 11957 // base class. 11958 DeclarationNameInfo UsingName = NameInfo; 11959 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName) 11960 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext)) 11961 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 11962 Context.getCanonicalType(Context.getRecordType(RD)))); 11963 11964 // Do the redeclaration lookup in the current scope. 11965 LookupResult Previous(*this, UsingName, LookupUsingDeclName, 11966 ForVisibleRedeclaration); 11967 Previous.setHideTags(false); 11968 if (S) { 11969 LookupName(Previous, S); 11970 11971 // It is really dumb that we have to do this. 11972 LookupResult::Filter F = Previous.makeFilter(); 11973 while (F.hasNext()) { 11974 NamedDecl *D = F.next(); 11975 if (!isDeclInScope(D, CurContext, S)) 11976 F.erase(); 11977 // If we found a local extern declaration that's not ordinarily visible, 11978 // and this declaration is being added to a non-block scope, ignore it. 11979 // We're only checking for scope conflicts here, not also for violations 11980 // of the linkage rules. 11981 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 11982 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 11983 F.erase(); 11984 } 11985 F.done(); 11986 } else { 11987 assert(IsInstantiation && "no scope in non-instantiation"); 11988 if (CurContext->isRecord()) 11989 LookupQualifiedName(Previous, CurContext); 11990 else { 11991 // No redeclaration check is needed here; in non-member contexts we 11992 // diagnosed all possible conflicts with other using-declarations when 11993 // building the template: 11994 // 11995 // For a dependent non-type using declaration, the only valid case is 11996 // if we instantiate to a single enumerator. We check for conflicts 11997 // between shadow declarations we introduce, and we check in the template 11998 // definition for conflicts between a non-type using declaration and any 11999 // other declaration, which together covers all cases. 12000 // 12001 // A dependent typename using declaration will never successfully 12002 // instantiate, since it will always name a class member, so we reject 12003 // that in the template definition. 12004 } 12005 } 12006 12007 // Check for invalid redeclarations. 12008 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 12009 SS, IdentLoc, Previous)) 12010 return nullptr; 12011 12012 // Check for bad qualifiers. 12013 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo, 12014 IdentLoc)) 12015 return nullptr; 12016 12017 DeclContext *LookupContext = computeDeclContext(SS); 12018 NamedDecl *D; 12019 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 12020 if (!LookupContext || EllipsisLoc.isValid()) { 12021 if (HasTypenameKeyword) { 12022 // FIXME: not all declaration name kinds are legal here 12023 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 12024 UsingLoc, TypenameLoc, 12025 QualifierLoc, 12026 IdentLoc, NameInfo.getName(), 12027 EllipsisLoc); 12028 } else { 12029 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 12030 QualifierLoc, NameInfo, EllipsisLoc); 12031 } 12032 D->setAccess(AS); 12033 CurContext->addDecl(D); 12034 return D; 12035 } 12036 12037 auto Build = [&](bool Invalid) { 12038 UsingDecl *UD = 12039 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 12040 UsingName, HasTypenameKeyword); 12041 UD->setAccess(AS); 12042 CurContext->addDecl(UD); 12043 UD->setInvalidDecl(Invalid); 12044 return UD; 12045 }; 12046 auto BuildInvalid = [&]{ return Build(true); }; 12047 auto BuildValid = [&]{ return Build(false); }; 12048 12049 if (RequireCompleteDeclContext(SS, LookupContext)) 12050 return BuildInvalid(); 12051 12052 // Look up the target name. 12053 LookupResult R(*this, NameInfo, LookupOrdinaryName); 12054 12055 // Unlike most lookups, we don't always want to hide tag 12056 // declarations: tag names are visible through the using declaration 12057 // even if hidden by ordinary names, *except* in a dependent context 12058 // where it's important for the sanity of two-phase lookup. 12059 if (!IsInstantiation) 12060 R.setHideTags(false); 12061 12062 // For the purposes of this lookup, we have a base object type 12063 // equal to that of the current context. 12064 if (CurContext->isRecord()) { 12065 R.setBaseObjectType( 12066 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 12067 } 12068 12069 LookupQualifiedName(R, LookupContext); 12070 12071 // Try to correct typos if possible. If constructor name lookup finds no 12072 // results, that means the named class has no explicit constructors, and we 12073 // suppressed declaring implicit ones (probably because it's dependent or 12074 // invalid). 12075 if (R.empty() && 12076 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { 12077 // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes 12078 // it will believe that glibc provides a ::gets in cases where it does not, 12079 // and will try to pull it into namespace std with a using-declaration. 12080 // Just ignore the using-declaration in that case. 12081 auto *II = NameInfo.getName().getAsIdentifierInfo(); 12082 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") && 12083 CurContext->isStdNamespace() && 12084 isa<TranslationUnitDecl>(LookupContext) && 12085 getSourceManager().isInSystemHeader(UsingLoc)) 12086 return nullptr; 12087 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 12088 dyn_cast<CXXRecordDecl>(CurContext)); 12089 if (TypoCorrection Corrected = 12090 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 12091 CTK_ErrorRecovery)) { 12092 // We reject candidates where DroppedSpecifier == true, hence the 12093 // literal '0' below. 12094 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 12095 << NameInfo.getName() << LookupContext << 0 12096 << SS.getRange()); 12097 12098 // If we picked a correction with no attached Decl we can't do anything 12099 // useful with it, bail out. 12100 NamedDecl *ND = Corrected.getCorrectionDecl(); 12101 if (!ND) 12102 return BuildInvalid(); 12103 12104 // If we corrected to an inheriting constructor, handle it as one. 12105 auto *RD = dyn_cast<CXXRecordDecl>(ND); 12106 if (RD && RD->isInjectedClassName()) { 12107 // The parent of the injected class name is the class itself. 12108 RD = cast<CXXRecordDecl>(RD->getParent()); 12109 12110 // Fix up the information we'll use to build the using declaration. 12111 if (Corrected.WillReplaceSpecifier()) { 12112 NestedNameSpecifierLocBuilder Builder; 12113 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 12114 QualifierLoc.getSourceRange()); 12115 QualifierLoc = Builder.getWithLocInContext(Context); 12116 } 12117 12118 // In this case, the name we introduce is the name of a derived class 12119 // constructor. 12120 auto *CurClass = cast<CXXRecordDecl>(CurContext); 12121 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 12122 Context.getCanonicalType(Context.getRecordType(CurClass)))); 12123 UsingName.setNamedTypeInfo(nullptr); 12124 for (auto *Ctor : LookupConstructors(RD)) 12125 R.addDecl(Ctor); 12126 R.resolveKind(); 12127 } else { 12128 // FIXME: Pick up all the declarations if we found an overloaded 12129 // function. 12130 UsingName.setName(ND->getDeclName()); 12131 R.addDecl(ND); 12132 } 12133 } else { 12134 Diag(IdentLoc, diag::err_no_member) 12135 << NameInfo.getName() << LookupContext << SS.getRange(); 12136 return BuildInvalid(); 12137 } 12138 } 12139 12140 if (R.isAmbiguous()) 12141 return BuildInvalid(); 12142 12143 if (HasTypenameKeyword) { 12144 // If we asked for a typename and got a non-type decl, error out. 12145 if (!R.getAsSingle<TypeDecl>()) { 12146 Diag(IdentLoc, diag::err_using_typename_non_type); 12147 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 12148 Diag((*I)->getUnderlyingDecl()->getLocation(), 12149 diag::note_using_decl_target); 12150 return BuildInvalid(); 12151 } 12152 } else { 12153 // If we asked for a non-typename and we got a type, error out, 12154 // but only if this is an instantiation of an unresolved using 12155 // decl. Otherwise just silently find the type name. 12156 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 12157 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 12158 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 12159 return BuildInvalid(); 12160 } 12161 } 12162 12163 // C++14 [namespace.udecl]p6: 12164 // A using-declaration shall not name a namespace. 12165 if (R.getAsSingle<NamespaceDecl>()) { 12166 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 12167 << SS.getRange(); 12168 return BuildInvalid(); 12169 } 12170 12171 // C++14 [namespace.udecl]p7: 12172 // A using-declaration shall not name a scoped enumerator. 12173 if (auto *ED = R.getAsSingle<EnumConstantDecl>()) { 12174 if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) { 12175 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum) 12176 << SS.getRange(); 12177 return BuildInvalid(); 12178 } 12179 } 12180 12181 UsingDecl *UD = BuildValid(); 12182 12183 // Some additional rules apply to inheriting constructors. 12184 if (UsingName.getName().getNameKind() == 12185 DeclarationName::CXXConstructorName) { 12186 // Suppress access diagnostics; the access check is instead performed at the 12187 // point of use for an inheriting constructor. 12188 R.suppressDiagnostics(); 12189 if (CheckInheritingConstructorUsingDecl(UD)) 12190 return UD; 12191 } 12192 12193 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 12194 UsingShadowDecl *PrevDecl = nullptr; 12195 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 12196 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 12197 } 12198 12199 return UD; 12200 } 12201 12202 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom, 12203 ArrayRef<NamedDecl *> Expansions) { 12204 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || 12205 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || 12206 isa<UsingPackDecl>(InstantiatedFrom)); 12207 12208 auto *UPD = 12209 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions); 12210 UPD->setAccess(InstantiatedFrom->getAccess()); 12211 CurContext->addDecl(UPD); 12212 return UPD; 12213 } 12214 12215 /// Additional checks for a using declaration referring to a constructor name. 12216 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 12217 assert(!UD->hasTypename() && "expecting a constructor name"); 12218 12219 const Type *SourceType = UD->getQualifier()->getAsType(); 12220 assert(SourceType && 12221 "Using decl naming constructor doesn't have type in scope spec."); 12222 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 12223 12224 // Check whether the named type is a direct base class. 12225 bool AnyDependentBases = false; 12226 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 12227 AnyDependentBases); 12228 if (!Base && !AnyDependentBases) { 12229 Diag(UD->getUsingLoc(), 12230 diag::err_using_decl_constructor_not_in_direct_base) 12231 << UD->getNameInfo().getSourceRange() 12232 << QualType(SourceType, 0) << TargetClass; 12233 UD->setInvalidDecl(); 12234 return true; 12235 } 12236 12237 if (Base) 12238 Base->setInheritConstructors(); 12239 12240 return false; 12241 } 12242 12243 /// Checks that the given using declaration is not an invalid 12244 /// redeclaration. Note that this is checking only for the using decl 12245 /// itself, not for any ill-formedness among the UsingShadowDecls. 12246 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 12247 bool HasTypenameKeyword, 12248 const CXXScopeSpec &SS, 12249 SourceLocation NameLoc, 12250 const LookupResult &Prev) { 12251 NestedNameSpecifier *Qual = SS.getScopeRep(); 12252 12253 // C++03 [namespace.udecl]p8: 12254 // C++0x [namespace.udecl]p10: 12255 // A using-declaration is a declaration and can therefore be used 12256 // repeatedly where (and only where) multiple declarations are 12257 // allowed. 12258 // 12259 // That's in non-member contexts. 12260 if (!CurContext->getRedeclContext()->isRecord()) { 12261 // A dependent qualifier outside a class can only ever resolve to an 12262 // enumeration type. Therefore it conflicts with any other non-type 12263 // declaration in the same scope. 12264 // FIXME: How should we check for dependent type-type conflicts at block 12265 // scope? 12266 if (Qual->isDependent() && !HasTypenameKeyword) { 12267 for (auto *D : Prev) { 12268 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) { 12269 bool OldCouldBeEnumerator = 12270 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D); 12271 Diag(NameLoc, 12272 OldCouldBeEnumerator ? diag::err_redefinition 12273 : diag::err_redefinition_different_kind) 12274 << Prev.getLookupName(); 12275 Diag(D->getLocation(), diag::note_previous_definition); 12276 return true; 12277 } 12278 } 12279 } 12280 return false; 12281 } 12282 12283 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 12284 NamedDecl *D = *I; 12285 12286 bool DTypename; 12287 NestedNameSpecifier *DQual; 12288 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 12289 DTypename = UD->hasTypename(); 12290 DQual = UD->getQualifier(); 12291 } else if (UnresolvedUsingValueDecl *UD 12292 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 12293 DTypename = false; 12294 DQual = UD->getQualifier(); 12295 } else if (UnresolvedUsingTypenameDecl *UD 12296 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 12297 DTypename = true; 12298 DQual = UD->getQualifier(); 12299 } else continue; 12300 12301 // using decls differ if one says 'typename' and the other doesn't. 12302 // FIXME: non-dependent using decls? 12303 if (HasTypenameKeyword != DTypename) continue; 12304 12305 // using decls differ if they name different scopes (but note that 12306 // template instantiation can cause this check to trigger when it 12307 // didn't before instantiation). 12308 if (Context.getCanonicalNestedNameSpecifier(Qual) != 12309 Context.getCanonicalNestedNameSpecifier(DQual)) 12310 continue; 12311 12312 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 12313 Diag(D->getLocation(), diag::note_using_decl) << 1; 12314 return true; 12315 } 12316 12317 return false; 12318 } 12319 12320 12321 /// Checks that the given nested-name qualifier used in a using decl 12322 /// in the current context is appropriately related to the current 12323 /// scope. If an error is found, diagnoses it and returns true. 12324 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 12325 bool HasTypename, 12326 const CXXScopeSpec &SS, 12327 const DeclarationNameInfo &NameInfo, 12328 SourceLocation NameLoc) { 12329 DeclContext *NamedContext = computeDeclContext(SS); 12330 12331 if (!CurContext->isRecord()) { 12332 // C++03 [namespace.udecl]p3: 12333 // C++0x [namespace.udecl]p8: 12334 // A using-declaration for a class member shall be a member-declaration. 12335 12336 // If we weren't able to compute a valid scope, it might validly be a 12337 // dependent class scope or a dependent enumeration unscoped scope. If 12338 // we have a 'typename' keyword, the scope must resolve to a class type. 12339 if ((HasTypename && !NamedContext) || 12340 (NamedContext && NamedContext->getRedeclContext()->isRecord())) { 12341 auto *RD = NamedContext 12342 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext()) 12343 : nullptr; 12344 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) 12345 RD = nullptr; 12346 12347 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 12348 << SS.getRange(); 12349 12350 // If we have a complete, non-dependent source type, try to suggest a 12351 // way to get the same effect. 12352 if (!RD) 12353 return true; 12354 12355 // Find what this using-declaration was referring to. 12356 LookupResult R(*this, NameInfo, LookupOrdinaryName); 12357 R.setHideTags(false); 12358 R.suppressDiagnostics(); 12359 LookupQualifiedName(R, RD); 12360 12361 if (R.getAsSingle<TypeDecl>()) { 12362 if (getLangOpts().CPlusPlus11) { 12363 // Convert 'using X::Y;' to 'using Y = X::Y;'. 12364 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 12365 << 0 // alias declaration 12366 << FixItHint::CreateInsertion(SS.getBeginLoc(), 12367 NameInfo.getName().getAsString() + 12368 " = "); 12369 } else { 12370 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 12371 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc()); 12372 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 12373 << 1 // typedef declaration 12374 << FixItHint::CreateReplacement(UsingLoc, "typedef") 12375 << FixItHint::CreateInsertion( 12376 InsertLoc, " " + NameInfo.getName().getAsString()); 12377 } 12378 } else if (R.getAsSingle<VarDecl>()) { 12379 // Don't provide a fixit outside C++11 mode; we don't want to suggest 12380 // repeating the type of the static data member here. 12381 FixItHint FixIt; 12382 if (getLangOpts().CPlusPlus11) { 12383 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 12384 FixIt = FixItHint::CreateReplacement( 12385 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 12386 } 12387 12388 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 12389 << 2 // reference declaration 12390 << FixIt; 12391 } else if (R.getAsSingle<EnumConstantDecl>()) { 12392 // Don't provide a fixit outside C++11 mode; we don't want to suggest 12393 // repeating the type of the enumeration here, and we can't do so if 12394 // the type is anonymous. 12395 FixItHint FixIt; 12396 if (getLangOpts().CPlusPlus11) { 12397 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 12398 FixIt = FixItHint::CreateReplacement( 12399 UsingLoc, 12400 "constexpr auto " + NameInfo.getName().getAsString() + " = "); 12401 } 12402 12403 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 12404 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable 12405 << FixIt; 12406 } 12407 return true; 12408 } 12409 12410 // Otherwise, this might be valid. 12411 return false; 12412 } 12413 12414 // The current scope is a record. 12415 12416 // If the named context is dependent, we can't decide much. 12417 if (!NamedContext) { 12418 // FIXME: in C++0x, we can diagnose if we can prove that the 12419 // nested-name-specifier does not refer to a base class, which is 12420 // still possible in some cases. 12421 12422 // Otherwise we have to conservatively report that things might be 12423 // okay. 12424 return false; 12425 } 12426 12427 if (!NamedContext->isRecord()) { 12428 // Ideally this would point at the last name in the specifier, 12429 // but we don't have that level of source info. 12430 Diag(SS.getRange().getBegin(), 12431 diag::err_using_decl_nested_name_specifier_is_not_class) 12432 << SS.getScopeRep() << SS.getRange(); 12433 return true; 12434 } 12435 12436 if (!NamedContext->isDependentContext() && 12437 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 12438 return true; 12439 12440 if (getLangOpts().CPlusPlus11) { 12441 // C++11 [namespace.udecl]p3: 12442 // In a using-declaration used as a member-declaration, the 12443 // nested-name-specifier shall name a base class of the class 12444 // being defined. 12445 12446 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 12447 cast<CXXRecordDecl>(NamedContext))) { 12448 if (CurContext == NamedContext) { 12449 Diag(NameLoc, 12450 diag::err_using_decl_nested_name_specifier_is_current_class) 12451 << SS.getRange(); 12452 return true; 12453 } 12454 12455 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) { 12456 Diag(SS.getRange().getBegin(), 12457 diag::err_using_decl_nested_name_specifier_is_not_base_class) 12458 << SS.getScopeRep() 12459 << cast<CXXRecordDecl>(CurContext) 12460 << SS.getRange(); 12461 } 12462 return true; 12463 } 12464 12465 return false; 12466 } 12467 12468 // C++03 [namespace.udecl]p4: 12469 // A using-declaration used as a member-declaration shall refer 12470 // to a member of a base class of the class being defined [etc.]. 12471 12472 // Salient point: SS doesn't have to name a base class as long as 12473 // lookup only finds members from base classes. Therefore we can 12474 // diagnose here only if we can prove that that can't happen, 12475 // i.e. if the class hierarchies provably don't intersect. 12476 12477 // TODO: it would be nice if "definitely valid" results were cached 12478 // in the UsingDecl and UsingShadowDecl so that these checks didn't 12479 // need to be repeated. 12480 12481 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases; 12482 auto Collect = [&Bases](const CXXRecordDecl *Base) { 12483 Bases.insert(Base); 12484 return true; 12485 }; 12486 12487 // Collect all bases. Return false if we find a dependent base. 12488 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect)) 12489 return false; 12490 12491 // Returns true if the base is dependent or is one of the accumulated base 12492 // classes. 12493 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) { 12494 return !Bases.count(Base); 12495 }; 12496 12497 // Return false if the class has a dependent base or if it or one 12498 // of its bases is present in the base set of the current context. 12499 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) || 12500 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase)) 12501 return false; 12502 12503 Diag(SS.getRange().getBegin(), 12504 diag::err_using_decl_nested_name_specifier_is_not_base_class) 12505 << SS.getScopeRep() 12506 << cast<CXXRecordDecl>(CurContext) 12507 << SS.getRange(); 12508 12509 return true; 12510 } 12511 12512 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS, 12513 MultiTemplateParamsArg TemplateParamLists, 12514 SourceLocation UsingLoc, UnqualifiedId &Name, 12515 const ParsedAttributesView &AttrList, 12516 TypeResult Type, Decl *DeclFromDeclSpec) { 12517 // Skip up to the relevant declaration scope. 12518 while (S->isTemplateParamScope()) 12519 S = S->getParent(); 12520 assert((S->getFlags() & Scope::DeclScope) && 12521 "got alias-declaration outside of declaration scope"); 12522 12523 if (Type.isInvalid()) 12524 return nullptr; 12525 12526 bool Invalid = false; 12527 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 12528 TypeSourceInfo *TInfo = nullptr; 12529 GetTypeFromParser(Type.get(), &TInfo); 12530 12531 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 12532 return nullptr; 12533 12534 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 12535 UPPC_DeclarationType)) { 12536 Invalid = true; 12537 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 12538 TInfo->getTypeLoc().getBeginLoc()); 12539 } 12540 12541 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 12542 TemplateParamLists.size() 12543 ? forRedeclarationInCurContext() 12544 : ForVisibleRedeclaration); 12545 LookupName(Previous, S); 12546 12547 // Warn about shadowing the name of a template parameter. 12548 if (Previous.isSingleResult() && 12549 Previous.getFoundDecl()->isTemplateParameter()) { 12550 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 12551 Previous.clear(); 12552 } 12553 12554 assert(Name.Kind == UnqualifiedIdKind::IK_Identifier && 12555 "name in alias declaration must be an identifier"); 12556 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 12557 Name.StartLocation, 12558 Name.Identifier, TInfo); 12559 12560 NewTD->setAccess(AS); 12561 12562 if (Invalid) 12563 NewTD->setInvalidDecl(); 12564 12565 ProcessDeclAttributeList(S, NewTD, AttrList); 12566 AddPragmaAttributes(S, NewTD); 12567 12568 CheckTypedefForVariablyModifiedType(S, NewTD); 12569 Invalid |= NewTD->isInvalidDecl(); 12570 12571 bool Redeclaration = false; 12572 12573 NamedDecl *NewND; 12574 if (TemplateParamLists.size()) { 12575 TypeAliasTemplateDecl *OldDecl = nullptr; 12576 TemplateParameterList *OldTemplateParams = nullptr; 12577 12578 if (TemplateParamLists.size() != 1) { 12579 Diag(UsingLoc, diag::err_alias_template_extra_headers) 12580 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 12581 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 12582 } 12583 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 12584 12585 // Check that we can declare a template here. 12586 if (CheckTemplateDeclScope(S, TemplateParams)) 12587 return nullptr; 12588 12589 // Only consider previous declarations in the same scope. 12590 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 12591 /*ExplicitInstantiationOrSpecialization*/false); 12592 if (!Previous.empty()) { 12593 Redeclaration = true; 12594 12595 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 12596 if (!OldDecl && !Invalid) { 12597 Diag(UsingLoc, diag::err_redefinition_different_kind) 12598 << Name.Identifier; 12599 12600 NamedDecl *OldD = Previous.getRepresentativeDecl(); 12601 if (OldD->getLocation().isValid()) 12602 Diag(OldD->getLocation(), diag::note_previous_definition); 12603 12604 Invalid = true; 12605 } 12606 12607 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 12608 if (TemplateParameterListsAreEqual(TemplateParams, 12609 OldDecl->getTemplateParameters(), 12610 /*Complain=*/true, 12611 TPL_TemplateMatch)) 12612 OldTemplateParams = 12613 OldDecl->getMostRecentDecl()->getTemplateParameters(); 12614 else 12615 Invalid = true; 12616 12617 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 12618 if (!Invalid && 12619 !Context.hasSameType(OldTD->getUnderlyingType(), 12620 NewTD->getUnderlyingType())) { 12621 // FIXME: The C++0x standard does not clearly say this is ill-formed, 12622 // but we can't reasonably accept it. 12623 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 12624 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 12625 if (OldTD->getLocation().isValid()) 12626 Diag(OldTD->getLocation(), diag::note_previous_definition); 12627 Invalid = true; 12628 } 12629 } 12630 } 12631 12632 // Merge any previous default template arguments into our parameters, 12633 // and check the parameter list. 12634 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 12635 TPC_TypeAliasTemplate)) 12636 return nullptr; 12637 12638 TypeAliasTemplateDecl *NewDecl = 12639 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 12640 Name.Identifier, TemplateParams, 12641 NewTD); 12642 NewTD->setDescribedAliasTemplate(NewDecl); 12643 12644 NewDecl->setAccess(AS); 12645 12646 if (Invalid) 12647 NewDecl->setInvalidDecl(); 12648 else if (OldDecl) { 12649 NewDecl->setPreviousDecl(OldDecl); 12650 CheckRedeclarationModuleOwnership(NewDecl, OldDecl); 12651 } 12652 12653 NewND = NewDecl; 12654 } else { 12655 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { 12656 setTagNameForLinkagePurposes(TD, NewTD); 12657 handleTagNumbering(TD, S); 12658 } 12659 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 12660 NewND = NewTD; 12661 } 12662 12663 PushOnScopeChains(NewND, S); 12664 ActOnDocumentableDecl(NewND); 12665 return NewND; 12666 } 12667 12668 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 12669 SourceLocation AliasLoc, 12670 IdentifierInfo *Alias, CXXScopeSpec &SS, 12671 SourceLocation IdentLoc, 12672 IdentifierInfo *Ident) { 12673 12674 // Lookup the namespace name. 12675 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 12676 LookupParsedName(R, S, &SS); 12677 12678 if (R.isAmbiguous()) 12679 return nullptr; 12680 12681 if (R.empty()) { 12682 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 12683 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 12684 return nullptr; 12685 } 12686 } 12687 assert(!R.isAmbiguous() && !R.empty()); 12688 NamedDecl *ND = R.getRepresentativeDecl(); 12689 12690 // Check if we have a previous declaration with the same name. 12691 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName, 12692 ForVisibleRedeclaration); 12693 LookupName(PrevR, S); 12694 12695 // Check we're not shadowing a template parameter. 12696 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) { 12697 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl()); 12698 PrevR.clear(); 12699 } 12700 12701 // Filter out any other lookup result from an enclosing scope. 12702 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false, 12703 /*AllowInlineNamespace*/false); 12704 12705 // Find the previous declaration and check that we can redeclare it. 12706 NamespaceAliasDecl *Prev = nullptr; 12707 if (PrevR.isSingleResult()) { 12708 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl(); 12709 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 12710 // We already have an alias with the same name that points to the same 12711 // namespace; check that it matches. 12712 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) { 12713 Prev = AD; 12714 } else if (isVisible(PrevDecl)) { 12715 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 12716 << Alias; 12717 Diag(AD->getLocation(), diag::note_previous_namespace_alias) 12718 << AD->getNamespace(); 12719 return nullptr; 12720 } 12721 } else if (isVisible(PrevDecl)) { 12722 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl()) 12723 ? diag::err_redefinition 12724 : diag::err_redefinition_different_kind; 12725 Diag(AliasLoc, DiagID) << Alias; 12726 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 12727 return nullptr; 12728 } 12729 } 12730 12731 // The use of a nested name specifier may trigger deprecation warnings. 12732 DiagnoseUseOfDecl(ND, IdentLoc); 12733 12734 NamespaceAliasDecl *AliasDecl = 12735 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 12736 Alias, SS.getWithLocInContext(Context), 12737 IdentLoc, ND); 12738 if (Prev) 12739 AliasDecl->setPreviousDecl(Prev); 12740 12741 PushOnScopeChains(AliasDecl, S); 12742 return AliasDecl; 12743 } 12744 12745 namespace { 12746 struct SpecialMemberExceptionSpecInfo 12747 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> { 12748 SourceLocation Loc; 12749 Sema::ImplicitExceptionSpecification ExceptSpec; 12750 12751 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD, 12752 Sema::CXXSpecialMember CSM, 12753 Sema::InheritedConstructorInfo *ICI, 12754 SourceLocation Loc) 12755 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {} 12756 12757 bool visitBase(CXXBaseSpecifier *Base); 12758 bool visitField(FieldDecl *FD); 12759 12760 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 12761 unsigned Quals); 12762 12763 void visitSubobjectCall(Subobject Subobj, 12764 Sema::SpecialMemberOverloadResult SMOR); 12765 }; 12766 } 12767 12768 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) { 12769 auto *RT = Base->getType()->getAs<RecordType>(); 12770 if (!RT) 12771 return false; 12772 12773 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl()); 12774 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 12775 if (auto *BaseCtor = SMOR.getMethod()) { 12776 visitSubobjectCall(Base, BaseCtor); 12777 return false; 12778 } 12779 12780 visitClassSubobject(BaseClass, Base, 0); 12781 return false; 12782 } 12783 12784 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) { 12785 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) { 12786 Expr *E = FD->getInClassInitializer(); 12787 if (!E) 12788 // FIXME: It's a little wasteful to build and throw away a 12789 // CXXDefaultInitExpr here. 12790 // FIXME: We should have a single context note pointing at Loc, and 12791 // this location should be MD->getLocation() instead, since that's 12792 // the location where we actually use the default init expression. 12793 E = S.BuildCXXDefaultInitExpr(Loc, FD).get(); 12794 if (E) 12795 ExceptSpec.CalledExpr(E); 12796 } else if (auto *RT = S.Context.getBaseElementType(FD->getType()) 12797 ->getAs<RecordType>()) { 12798 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD, 12799 FD->getType().getCVRQualifiers()); 12800 } 12801 return false; 12802 } 12803 12804 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class, 12805 Subobject Subobj, 12806 unsigned Quals) { 12807 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 12808 bool IsMutable = Field && Field->isMutable(); 12809 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable)); 12810 } 12811 12812 void SpecialMemberExceptionSpecInfo::visitSubobjectCall( 12813 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) { 12814 // Note, if lookup fails, it doesn't matter what exception specification we 12815 // choose because the special member will be deleted. 12816 if (CXXMethodDecl *MD = SMOR.getMethod()) 12817 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD); 12818 } 12819 12820 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) { 12821 llvm::APSInt Result; 12822 ExprResult Converted = CheckConvertedConstantExpression( 12823 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool); 12824 ExplicitSpec.setExpr(Converted.get()); 12825 if (Converted.isUsable() && !Converted.get()->isValueDependent()) { 12826 ExplicitSpec.setKind(Result.getBoolValue() 12827 ? ExplicitSpecKind::ResolvedTrue 12828 : ExplicitSpecKind::ResolvedFalse); 12829 return true; 12830 } 12831 ExplicitSpec.setKind(ExplicitSpecKind::Unresolved); 12832 return false; 12833 } 12834 12835 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) { 12836 ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved); 12837 if (!ExplicitExpr->isTypeDependent()) 12838 tryResolveExplicitSpecifier(ES); 12839 return ES; 12840 } 12841 12842 static Sema::ImplicitExceptionSpecification 12843 ComputeDefaultedSpecialMemberExceptionSpec( 12844 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 12845 Sema::InheritedConstructorInfo *ICI) { 12846 ComputingExceptionSpec CES(S, MD, Loc); 12847 12848 CXXRecordDecl *ClassDecl = MD->getParent(); 12849 12850 // C++ [except.spec]p14: 12851 // An implicitly declared special member function (Clause 12) shall have an 12852 // exception-specification. [...] 12853 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation()); 12854 if (ClassDecl->isInvalidDecl()) 12855 return Info.ExceptSpec; 12856 12857 // FIXME: If this diagnostic fires, we're probably missing a check for 12858 // attempting to resolve an exception specification before it's known 12859 // at a higher level. 12860 if (S.RequireCompleteType(MD->getLocation(), 12861 S.Context.getRecordType(ClassDecl), 12862 diag::err_exception_spec_incomplete_type)) 12863 return Info.ExceptSpec; 12864 12865 // C++1z [except.spec]p7: 12866 // [Look for exceptions thrown by] a constructor selected [...] to 12867 // initialize a potentially constructed subobject, 12868 // C++1z [except.spec]p8: 12869 // The exception specification for an implicitly-declared destructor, or a 12870 // destructor without a noexcept-specifier, is potentially-throwing if and 12871 // only if any of the destructors for any of its potentially constructed 12872 // subojects is potentially throwing. 12873 // FIXME: We respect the first rule but ignore the "potentially constructed" 12874 // in the second rule to resolve a core issue (no number yet) that would have 12875 // us reject: 12876 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; }; 12877 // struct B : A {}; 12878 // struct C : B { void f(); }; 12879 // ... due to giving B::~B() a non-throwing exception specification. 12880 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases 12881 : Info.VisitAllBases); 12882 12883 return Info.ExceptSpec; 12884 } 12885 12886 namespace { 12887 /// RAII object to register a special member as being currently declared. 12888 struct DeclaringSpecialMember { 12889 Sema &S; 12890 Sema::SpecialMemberDecl D; 12891 Sema::ContextRAII SavedContext; 12892 bool WasAlreadyBeingDeclared; 12893 12894 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 12895 : S(S), D(RD, CSM), SavedContext(S, RD) { 12896 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 12897 if (WasAlreadyBeingDeclared) 12898 // This almost never happens, but if it does, ensure that our cache 12899 // doesn't contain a stale result. 12900 S.SpecialMemberCache.clear(); 12901 else { 12902 // Register a note to be produced if we encounter an error while 12903 // declaring the special member. 12904 Sema::CodeSynthesisContext Ctx; 12905 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember; 12906 // FIXME: We don't have a location to use here. Using the class's 12907 // location maintains the fiction that we declare all special members 12908 // with the class, but (1) it's not clear that lying about that helps our 12909 // users understand what's going on, and (2) there may be outer contexts 12910 // on the stack (some of which are relevant) and printing them exposes 12911 // our lies. 12912 Ctx.PointOfInstantiation = RD->getLocation(); 12913 Ctx.Entity = RD; 12914 Ctx.SpecialMember = CSM; 12915 S.pushCodeSynthesisContext(Ctx); 12916 } 12917 } 12918 ~DeclaringSpecialMember() { 12919 if (!WasAlreadyBeingDeclared) { 12920 S.SpecialMembersBeingDeclared.erase(D); 12921 S.popCodeSynthesisContext(); 12922 } 12923 } 12924 12925 /// Are we already trying to declare this special member? 12926 bool isAlreadyBeingDeclared() const { 12927 return WasAlreadyBeingDeclared; 12928 } 12929 }; 12930 } 12931 12932 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) { 12933 // Look up any existing declarations, but don't trigger declaration of all 12934 // implicit special members with this name. 12935 DeclarationName Name = FD->getDeclName(); 12936 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName, 12937 ForExternalRedeclaration); 12938 for (auto *D : FD->getParent()->lookup(Name)) 12939 if (auto *Acceptable = R.getAcceptableDecl(D)) 12940 R.addDecl(Acceptable); 12941 R.resolveKind(); 12942 R.suppressDiagnostics(); 12943 12944 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false); 12945 } 12946 12947 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem, 12948 QualType ResultTy, 12949 ArrayRef<QualType> Args) { 12950 // Build an exception specification pointing back at this constructor. 12951 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem); 12952 12953 LangAS AS = getDefaultCXXMethodAddrSpace(); 12954 if (AS != LangAS::Default) { 12955 EPI.TypeQuals.addAddressSpace(AS); 12956 } 12957 12958 auto QT = Context.getFunctionType(ResultTy, Args, EPI); 12959 SpecialMem->setType(QT); 12960 } 12961 12962 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 12963 CXXRecordDecl *ClassDecl) { 12964 // C++ [class.ctor]p5: 12965 // A default constructor for a class X is a constructor of class X 12966 // that can be called without an argument. If there is no 12967 // user-declared constructor for class X, a default constructor is 12968 // implicitly declared. An implicitly-declared default constructor 12969 // is an inline public member of its class. 12970 assert(ClassDecl->needsImplicitDefaultConstructor() && 12971 "Should not build implicit default constructor!"); 12972 12973 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 12974 if (DSM.isAlreadyBeingDeclared()) 12975 return nullptr; 12976 12977 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12978 CXXDefaultConstructor, 12979 false); 12980 12981 // Create the actual constructor declaration. 12982 CanQualType ClassType 12983 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 12984 SourceLocation ClassLoc = ClassDecl->getLocation(); 12985 DeclarationName Name 12986 = Context.DeclarationNames.getCXXConstructorName(ClassType); 12987 DeclarationNameInfo NameInfo(Name, ClassLoc); 12988 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 12989 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(), 12990 /*TInfo=*/nullptr, ExplicitSpecifier(), 12991 /*isInline=*/true, /*isImplicitlyDeclared=*/true, 12992 Constexpr ? ConstexprSpecKind::Constexpr 12993 : ConstexprSpecKind::Unspecified); 12994 DefaultCon->setAccess(AS_public); 12995 DefaultCon->setDefaulted(); 12996 12997 if (getLangOpts().CUDA) { 12998 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 12999 DefaultCon, 13000 /* ConstRHS */ false, 13001 /* Diagnose */ false); 13002 } 13003 13004 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None); 13005 13006 // We don't need to use SpecialMemberIsTrivial here; triviality for default 13007 // constructors is easy to compute. 13008 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 13009 13010 // Note that we have declared this constructor. 13011 ++getASTContext().NumImplicitDefaultConstructorsDeclared; 13012 13013 Scope *S = getScopeForContext(ClassDecl); 13014 CheckImplicitSpecialMemberDeclaration(S, DefaultCon); 13015 13016 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 13017 SetDeclDeleted(DefaultCon, ClassLoc); 13018 13019 if (S) 13020 PushOnScopeChains(DefaultCon, S, false); 13021 ClassDecl->addDecl(DefaultCon); 13022 13023 return DefaultCon; 13024 } 13025 13026 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 13027 CXXConstructorDecl *Constructor) { 13028 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 13029 !Constructor->doesThisDeclarationHaveABody() && 13030 !Constructor->isDeleted()) && 13031 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 13032 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 13033 return; 13034 13035 CXXRecordDecl *ClassDecl = Constructor->getParent(); 13036 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 13037 13038 SynthesizedFunctionScope Scope(*this, Constructor); 13039 13040 // The exception specification is needed because we are defining the 13041 // function. 13042 ResolveExceptionSpec(CurrentLocation, 13043 Constructor->getType()->castAs<FunctionProtoType>()); 13044 MarkVTableUsed(CurrentLocation, ClassDecl); 13045 13046 // Add a context note for diagnostics produced after this point. 13047 Scope.addContextNote(CurrentLocation); 13048 13049 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) { 13050 Constructor->setInvalidDecl(); 13051 return; 13052 } 13053 13054 SourceLocation Loc = Constructor->getEndLoc().isValid() 13055 ? Constructor->getEndLoc() 13056 : Constructor->getLocation(); 13057 Constructor->setBody(new (Context) CompoundStmt(Loc)); 13058 Constructor->markUsed(Context); 13059 13060 if (ASTMutationListener *L = getASTMutationListener()) { 13061 L->CompletedImplicitDefinition(Constructor); 13062 } 13063 13064 DiagnoseUninitializedFields(*this, Constructor); 13065 } 13066 13067 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 13068 // Perform any delayed checks on exception specifications. 13069 CheckDelayedMemberExceptionSpecs(); 13070 } 13071 13072 /// Find or create the fake constructor we synthesize to model constructing an 13073 /// object of a derived class via a constructor of a base class. 13074 CXXConstructorDecl * 13075 Sema::findInheritingConstructor(SourceLocation Loc, 13076 CXXConstructorDecl *BaseCtor, 13077 ConstructorUsingShadowDecl *Shadow) { 13078 CXXRecordDecl *Derived = Shadow->getParent(); 13079 SourceLocation UsingLoc = Shadow->getLocation(); 13080 13081 // FIXME: Add a new kind of DeclarationName for an inherited constructor. 13082 // For now we use the name of the base class constructor as a member of the 13083 // derived class to indicate a (fake) inherited constructor name. 13084 DeclarationName Name = BaseCtor->getDeclName(); 13085 13086 // Check to see if we already have a fake constructor for this inherited 13087 // constructor call. 13088 for (NamedDecl *Ctor : Derived->lookup(Name)) 13089 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor) 13090 ->getInheritedConstructor() 13091 .getConstructor(), 13092 BaseCtor)) 13093 return cast<CXXConstructorDecl>(Ctor); 13094 13095 DeclarationNameInfo NameInfo(Name, UsingLoc); 13096 TypeSourceInfo *TInfo = 13097 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc); 13098 FunctionProtoTypeLoc ProtoLoc = 13099 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 13100 13101 // Check the inherited constructor is valid and find the list of base classes 13102 // from which it was inherited. 13103 InheritedConstructorInfo ICI(*this, Loc, Shadow); 13104 13105 bool Constexpr = 13106 BaseCtor->isConstexpr() && 13107 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor, 13108 false, BaseCtor, &ICI); 13109 13110 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 13111 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo, 13112 BaseCtor->getExplicitSpecifier(), /*isInline=*/true, 13113 /*isImplicitlyDeclared=*/true, 13114 Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified, 13115 InheritedConstructor(Shadow, BaseCtor), 13116 BaseCtor->getTrailingRequiresClause()); 13117 if (Shadow->isInvalidDecl()) 13118 DerivedCtor->setInvalidDecl(); 13119 13120 // Build an unevaluated exception specification for this fake constructor. 13121 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>(); 13122 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 13123 EPI.ExceptionSpec.Type = EST_Unevaluated; 13124 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 13125 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 13126 FPT->getParamTypes(), EPI)); 13127 13128 // Build the parameter declarations. 13129 SmallVector<ParmVarDecl *, 16> ParamDecls; 13130 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 13131 TypeSourceInfo *TInfo = 13132 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 13133 ParmVarDecl *PD = ParmVarDecl::Create( 13134 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 13135 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr); 13136 PD->setScopeInfo(0, I); 13137 PD->setImplicit(); 13138 // Ensure attributes are propagated onto parameters (this matters for 13139 // format, pass_object_size, ...). 13140 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I)); 13141 ParamDecls.push_back(PD); 13142 ProtoLoc.setParam(I, PD); 13143 } 13144 13145 // Set up the new constructor. 13146 assert(!BaseCtor->isDeleted() && "should not use deleted constructor"); 13147 DerivedCtor->setAccess(BaseCtor->getAccess()); 13148 DerivedCtor->setParams(ParamDecls); 13149 Derived->addDecl(DerivedCtor); 13150 13151 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI)) 13152 SetDeclDeleted(DerivedCtor, UsingLoc); 13153 13154 return DerivedCtor; 13155 } 13156 13157 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) { 13158 InheritedConstructorInfo ICI(*this, Ctor->getLocation(), 13159 Ctor->getInheritedConstructor().getShadowDecl()); 13160 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI, 13161 /*Diagnose*/true); 13162 } 13163 13164 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 13165 CXXConstructorDecl *Constructor) { 13166 CXXRecordDecl *ClassDecl = Constructor->getParent(); 13167 assert(Constructor->getInheritedConstructor() && 13168 !Constructor->doesThisDeclarationHaveABody() && 13169 !Constructor->isDeleted()); 13170 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 13171 return; 13172 13173 // Initializations are performed "as if by a defaulted default constructor", 13174 // so enter the appropriate scope. 13175 SynthesizedFunctionScope Scope(*this, Constructor); 13176 13177 // The exception specification is needed because we are defining the 13178 // function. 13179 ResolveExceptionSpec(CurrentLocation, 13180 Constructor->getType()->castAs<FunctionProtoType>()); 13181 MarkVTableUsed(CurrentLocation, ClassDecl); 13182 13183 // Add a context note for diagnostics produced after this point. 13184 Scope.addContextNote(CurrentLocation); 13185 13186 ConstructorUsingShadowDecl *Shadow = 13187 Constructor->getInheritedConstructor().getShadowDecl(); 13188 CXXConstructorDecl *InheritedCtor = 13189 Constructor->getInheritedConstructor().getConstructor(); 13190 13191 // [class.inhctor.init]p1: 13192 // initialization proceeds as if a defaulted default constructor is used to 13193 // initialize the D object and each base class subobject from which the 13194 // constructor was inherited 13195 13196 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow); 13197 CXXRecordDecl *RD = Shadow->getParent(); 13198 SourceLocation InitLoc = Shadow->getLocation(); 13199 13200 // Build explicit initializers for all base classes from which the 13201 // constructor was inherited. 13202 SmallVector<CXXCtorInitializer*, 8> Inits; 13203 for (bool VBase : {false, true}) { 13204 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) { 13205 if (B.isVirtual() != VBase) 13206 continue; 13207 13208 auto *BaseRD = B.getType()->getAsCXXRecordDecl(); 13209 if (!BaseRD) 13210 continue; 13211 13212 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor); 13213 if (!BaseCtor.first) 13214 continue; 13215 13216 MarkFunctionReferenced(CurrentLocation, BaseCtor.first); 13217 ExprResult Init = new (Context) CXXInheritedCtorInitExpr( 13218 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second); 13219 13220 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc); 13221 Inits.push_back(new (Context) CXXCtorInitializer( 13222 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc, 13223 SourceLocation())); 13224 } 13225 } 13226 13227 // We now proceed as if for a defaulted default constructor, with the relevant 13228 // initializers replaced. 13229 13230 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) { 13231 Constructor->setInvalidDecl(); 13232 return; 13233 } 13234 13235 Constructor->setBody(new (Context) CompoundStmt(InitLoc)); 13236 Constructor->markUsed(Context); 13237 13238 if (ASTMutationListener *L = getASTMutationListener()) { 13239 L->CompletedImplicitDefinition(Constructor); 13240 } 13241 13242 DiagnoseUninitializedFields(*this, Constructor); 13243 } 13244 13245 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 13246 // C++ [class.dtor]p2: 13247 // If a class has no user-declared destructor, a destructor is 13248 // declared implicitly. An implicitly-declared destructor is an 13249 // inline public member of its class. 13250 assert(ClassDecl->needsImplicitDestructor()); 13251 13252 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 13253 if (DSM.isAlreadyBeingDeclared()) 13254 return nullptr; 13255 13256 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 13257 CXXDestructor, 13258 false); 13259 13260 // Create the actual destructor declaration. 13261 CanQualType ClassType 13262 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 13263 SourceLocation ClassLoc = ClassDecl->getLocation(); 13264 DeclarationName Name 13265 = Context.DeclarationNames.getCXXDestructorName(ClassType); 13266 DeclarationNameInfo NameInfo(Name, ClassLoc); 13267 CXXDestructorDecl *Destructor = 13268 CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 13269 QualType(), nullptr, /*isInline=*/true, 13270 /*isImplicitlyDeclared=*/true, 13271 Constexpr ? ConstexprSpecKind::Constexpr 13272 : ConstexprSpecKind::Unspecified); 13273 Destructor->setAccess(AS_public); 13274 Destructor->setDefaulted(); 13275 13276 if (getLangOpts().CUDA) { 13277 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 13278 Destructor, 13279 /* ConstRHS */ false, 13280 /* Diagnose */ false); 13281 } 13282 13283 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None); 13284 13285 // We don't need to use SpecialMemberIsTrivial here; triviality for 13286 // destructors is easy to compute. 13287 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 13288 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() || 13289 ClassDecl->hasTrivialDestructorForCall()); 13290 13291 // Note that we have declared this destructor. 13292 ++getASTContext().NumImplicitDestructorsDeclared; 13293 13294 Scope *S = getScopeForContext(ClassDecl); 13295 CheckImplicitSpecialMemberDeclaration(S, Destructor); 13296 13297 // We can't check whether an implicit destructor is deleted before we complete 13298 // the definition of the class, because its validity depends on the alignment 13299 // of the class. We'll check this from ActOnFields once the class is complete. 13300 if (ClassDecl->isCompleteDefinition() && 13301 ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 13302 SetDeclDeleted(Destructor, ClassLoc); 13303 13304 // Introduce this destructor into its scope. 13305 if (S) 13306 PushOnScopeChains(Destructor, S, false); 13307 ClassDecl->addDecl(Destructor); 13308 13309 return Destructor; 13310 } 13311 13312 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 13313 CXXDestructorDecl *Destructor) { 13314 assert((Destructor->isDefaulted() && 13315 !Destructor->doesThisDeclarationHaveABody() && 13316 !Destructor->isDeleted()) && 13317 "DefineImplicitDestructor - call it for implicit default dtor"); 13318 if (Destructor->willHaveBody() || Destructor->isInvalidDecl()) 13319 return; 13320 13321 CXXRecordDecl *ClassDecl = Destructor->getParent(); 13322 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 13323 13324 SynthesizedFunctionScope Scope(*this, Destructor); 13325 13326 // The exception specification is needed because we are defining the 13327 // function. 13328 ResolveExceptionSpec(CurrentLocation, 13329 Destructor->getType()->castAs<FunctionProtoType>()); 13330 MarkVTableUsed(CurrentLocation, ClassDecl); 13331 13332 // Add a context note for diagnostics produced after this point. 13333 Scope.addContextNote(CurrentLocation); 13334 13335 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 13336 Destructor->getParent()); 13337 13338 if (CheckDestructor(Destructor)) { 13339 Destructor->setInvalidDecl(); 13340 return; 13341 } 13342 13343 SourceLocation Loc = Destructor->getEndLoc().isValid() 13344 ? Destructor->getEndLoc() 13345 : Destructor->getLocation(); 13346 Destructor->setBody(new (Context) CompoundStmt(Loc)); 13347 Destructor->markUsed(Context); 13348 13349 if (ASTMutationListener *L = getASTMutationListener()) { 13350 L->CompletedImplicitDefinition(Destructor); 13351 } 13352 } 13353 13354 void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation, 13355 CXXDestructorDecl *Destructor) { 13356 if (Destructor->isInvalidDecl()) 13357 return; 13358 13359 CXXRecordDecl *ClassDecl = Destructor->getParent(); 13360 assert(Context.getTargetInfo().getCXXABI().isMicrosoft() && 13361 "implicit complete dtors unneeded outside MS ABI"); 13362 assert(ClassDecl->getNumVBases() > 0 && 13363 "complete dtor only exists for classes with vbases"); 13364 13365 SynthesizedFunctionScope Scope(*this, Destructor); 13366 13367 // Add a context note for diagnostics produced after this point. 13368 Scope.addContextNote(CurrentLocation); 13369 13370 MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl); 13371 } 13372 13373 /// Perform any semantic analysis which needs to be delayed until all 13374 /// pending class member declarations have been parsed. 13375 void Sema::ActOnFinishCXXMemberDecls() { 13376 // If the context is an invalid C++ class, just suppress these checks. 13377 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 13378 if (Record->isInvalidDecl()) { 13379 DelayedOverridingExceptionSpecChecks.clear(); 13380 DelayedEquivalentExceptionSpecChecks.clear(); 13381 return; 13382 } 13383 checkForMultipleExportedDefaultConstructors(*this, Record); 13384 } 13385 } 13386 13387 void Sema::ActOnFinishCXXNonNestedClass() { 13388 referenceDLLExportedClassMethods(); 13389 13390 if (!DelayedDllExportMemberFunctions.empty()) { 13391 SmallVector<CXXMethodDecl*, 4> WorkList; 13392 std::swap(DelayedDllExportMemberFunctions, WorkList); 13393 for (CXXMethodDecl *M : WorkList) { 13394 DefineDefaultedFunction(*this, M, M->getLocation()); 13395 13396 // Pass the method to the consumer to get emitted. This is not necessary 13397 // for explicit instantiation definitions, as they will get emitted 13398 // anyway. 13399 if (M->getParent()->getTemplateSpecializationKind() != 13400 TSK_ExplicitInstantiationDefinition) 13401 ActOnFinishInlineFunctionDef(M); 13402 } 13403 } 13404 } 13405 13406 void Sema::referenceDLLExportedClassMethods() { 13407 if (!DelayedDllExportClasses.empty()) { 13408 // Calling ReferenceDllExportedMembers might cause the current function to 13409 // be called again, so use a local copy of DelayedDllExportClasses. 13410 SmallVector<CXXRecordDecl *, 4> WorkList; 13411 std::swap(DelayedDllExportClasses, WorkList); 13412 for (CXXRecordDecl *Class : WorkList) 13413 ReferenceDllExportedMembers(*this, Class); 13414 } 13415 } 13416 13417 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) { 13418 assert(getLangOpts().CPlusPlus11 && 13419 "adjusting dtor exception specs was introduced in c++11"); 13420 13421 if (Destructor->isDependentContext()) 13422 return; 13423 13424 // C++11 [class.dtor]p3: 13425 // A declaration of a destructor that does not have an exception- 13426 // specification is implicitly considered to have the same exception- 13427 // specification as an implicit declaration. 13428 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>(); 13429 if (DtorType->hasExceptionSpec()) 13430 return; 13431 13432 // Replace the destructor's type, building off the existing one. Fortunately, 13433 // the only thing of interest in the destructor type is its extended info. 13434 // The return and arguments are fixed. 13435 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 13436 EPI.ExceptionSpec.Type = EST_Unevaluated; 13437 EPI.ExceptionSpec.SourceDecl = Destructor; 13438 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 13439 13440 // FIXME: If the destructor has a body that could throw, and the newly created 13441 // spec doesn't allow exceptions, we should emit a warning, because this 13442 // change in behavior can break conforming C++03 programs at runtime. 13443 // However, we don't have a body or an exception specification yet, so it 13444 // needs to be done somewhere else. 13445 } 13446 13447 namespace { 13448 /// An abstract base class for all helper classes used in building the 13449 // copy/move operators. These classes serve as factory functions and help us 13450 // avoid using the same Expr* in the AST twice. 13451 class ExprBuilder { 13452 ExprBuilder(const ExprBuilder&) = delete; 13453 ExprBuilder &operator=(const ExprBuilder&) = delete; 13454 13455 protected: 13456 static Expr *assertNotNull(Expr *E) { 13457 assert(E && "Expression construction must not fail."); 13458 return E; 13459 } 13460 13461 public: 13462 ExprBuilder() {} 13463 virtual ~ExprBuilder() {} 13464 13465 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 13466 }; 13467 13468 class RefBuilder: public ExprBuilder { 13469 VarDecl *Var; 13470 QualType VarType; 13471 13472 public: 13473 Expr *build(Sema &S, SourceLocation Loc) const override { 13474 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc)); 13475 } 13476 13477 RefBuilder(VarDecl *Var, QualType VarType) 13478 : Var(Var), VarType(VarType) {} 13479 }; 13480 13481 class ThisBuilder: public ExprBuilder { 13482 public: 13483 Expr *build(Sema &S, SourceLocation Loc) const override { 13484 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 13485 } 13486 }; 13487 13488 class CastBuilder: public ExprBuilder { 13489 const ExprBuilder &Builder; 13490 QualType Type; 13491 ExprValueKind Kind; 13492 const CXXCastPath &Path; 13493 13494 public: 13495 Expr *build(Sema &S, SourceLocation Loc) const override { 13496 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 13497 CK_UncheckedDerivedToBase, Kind, 13498 &Path).get()); 13499 } 13500 13501 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 13502 const CXXCastPath &Path) 13503 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 13504 }; 13505 13506 class DerefBuilder: public ExprBuilder { 13507 const ExprBuilder &Builder; 13508 13509 public: 13510 Expr *build(Sema &S, SourceLocation Loc) const override { 13511 return assertNotNull( 13512 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 13513 } 13514 13515 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13516 }; 13517 13518 class MemberBuilder: public ExprBuilder { 13519 const ExprBuilder &Builder; 13520 QualType Type; 13521 CXXScopeSpec SS; 13522 bool IsArrow; 13523 LookupResult &MemberLookup; 13524 13525 public: 13526 Expr *build(Sema &S, SourceLocation Loc) const override { 13527 return assertNotNull(S.BuildMemberReferenceExpr( 13528 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 13529 nullptr, MemberLookup, nullptr, nullptr).get()); 13530 } 13531 13532 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 13533 LookupResult &MemberLookup) 13534 : Builder(Builder), Type(Type), IsArrow(IsArrow), 13535 MemberLookup(MemberLookup) {} 13536 }; 13537 13538 class MoveCastBuilder: public ExprBuilder { 13539 const ExprBuilder &Builder; 13540 13541 public: 13542 Expr *build(Sema &S, SourceLocation Loc) const override { 13543 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 13544 } 13545 13546 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13547 }; 13548 13549 class LvalueConvBuilder: public ExprBuilder { 13550 const ExprBuilder &Builder; 13551 13552 public: 13553 Expr *build(Sema &S, SourceLocation Loc) const override { 13554 return assertNotNull( 13555 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 13556 } 13557 13558 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13559 }; 13560 13561 class SubscriptBuilder: public ExprBuilder { 13562 const ExprBuilder &Base; 13563 const ExprBuilder &Index; 13564 13565 public: 13566 Expr *build(Sema &S, SourceLocation Loc) const override { 13567 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 13568 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 13569 } 13570 13571 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 13572 : Base(Base), Index(Index) {} 13573 }; 13574 13575 } // end anonymous namespace 13576 13577 /// When generating a defaulted copy or move assignment operator, if a field 13578 /// should be copied with __builtin_memcpy rather than via explicit assignments, 13579 /// do so. This optimization only applies for arrays of scalars, and for arrays 13580 /// of class type where the selected copy/move-assignment operator is trivial. 13581 static StmtResult 13582 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 13583 const ExprBuilder &ToB, const ExprBuilder &FromB) { 13584 // Compute the size of the memory buffer to be copied. 13585 QualType SizeType = S.Context.getSizeType(); 13586 llvm::APInt Size(S.Context.getTypeSize(SizeType), 13587 S.Context.getTypeSizeInChars(T).getQuantity()); 13588 13589 // Take the address of the field references for "from" and "to". We 13590 // directly construct UnaryOperators here because semantic analysis 13591 // does not permit us to take the address of an xvalue. 13592 Expr *From = FromB.build(S, Loc); 13593 From = UnaryOperator::Create( 13594 S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()), 13595 VK_RValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides()); 13596 Expr *To = ToB.build(S, Loc); 13597 To = UnaryOperator::Create( 13598 S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()), 13599 VK_RValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides()); 13600 13601 const Type *E = T->getBaseElementTypeUnsafe(); 13602 bool NeedsCollectableMemCpy = 13603 E->isRecordType() && 13604 E->castAs<RecordType>()->getDecl()->hasObjectMember(); 13605 13606 // Create a reference to the __builtin_objc_memmove_collectable function 13607 StringRef MemCpyName = NeedsCollectableMemCpy ? 13608 "__builtin_objc_memmove_collectable" : 13609 "__builtin_memcpy"; 13610 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 13611 Sema::LookupOrdinaryName); 13612 S.LookupName(R, S.TUScope, true); 13613 13614 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 13615 if (!MemCpy) 13616 // Something went horribly wrong earlier, and we will have complained 13617 // about it. 13618 return StmtError(); 13619 13620 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 13621 VK_RValue, Loc, nullptr); 13622 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 13623 13624 Expr *CallArgs[] = { 13625 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 13626 }; 13627 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 13628 Loc, CallArgs, Loc); 13629 13630 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 13631 return Call.getAs<Stmt>(); 13632 } 13633 13634 /// Builds a statement that copies/moves the given entity from \p From to 13635 /// \c To. 13636 /// 13637 /// This routine is used to copy/move the members of a class with an 13638 /// implicitly-declared copy/move assignment operator. When the entities being 13639 /// copied are arrays, this routine builds for loops to copy them. 13640 /// 13641 /// \param S The Sema object used for type-checking. 13642 /// 13643 /// \param Loc The location where the implicit copy/move is being generated. 13644 /// 13645 /// \param T The type of the expressions being copied/moved. Both expressions 13646 /// must have this type. 13647 /// 13648 /// \param To The expression we are copying/moving to. 13649 /// 13650 /// \param From The expression we are copying/moving from. 13651 /// 13652 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 13653 /// Otherwise, it's a non-static member subobject. 13654 /// 13655 /// \param Copying Whether we're copying or moving. 13656 /// 13657 /// \param Depth Internal parameter recording the depth of the recursion. 13658 /// 13659 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 13660 /// if a memcpy should be used instead. 13661 static StmtResult 13662 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 13663 const ExprBuilder &To, const ExprBuilder &From, 13664 bool CopyingBaseSubobject, bool Copying, 13665 unsigned Depth = 0) { 13666 // C++11 [class.copy]p28: 13667 // Each subobject is assigned in the manner appropriate to its type: 13668 // 13669 // - if the subobject is of class type, as if by a call to operator= with 13670 // the subobject as the object expression and the corresponding 13671 // subobject of x as a single function argument (as if by explicit 13672 // qualification; that is, ignoring any possible virtual overriding 13673 // functions in more derived classes); 13674 // 13675 // C++03 [class.copy]p13: 13676 // - if the subobject is of class type, the copy assignment operator for 13677 // the class is used (as if by explicit qualification; that is, 13678 // ignoring any possible virtual overriding functions in more derived 13679 // classes); 13680 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 13681 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 13682 13683 // Look for operator=. 13684 DeclarationName Name 13685 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 13686 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 13687 S.LookupQualifiedName(OpLookup, ClassDecl, false); 13688 13689 // Prior to C++11, filter out any result that isn't a copy/move-assignment 13690 // operator. 13691 if (!S.getLangOpts().CPlusPlus11) { 13692 LookupResult::Filter F = OpLookup.makeFilter(); 13693 while (F.hasNext()) { 13694 NamedDecl *D = F.next(); 13695 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 13696 if (Method->isCopyAssignmentOperator() || 13697 (!Copying && Method->isMoveAssignmentOperator())) 13698 continue; 13699 13700 F.erase(); 13701 } 13702 F.done(); 13703 } 13704 13705 // Suppress the protected check (C++ [class.protected]) for each of the 13706 // assignment operators we found. This strange dance is required when 13707 // we're assigning via a base classes's copy-assignment operator. To 13708 // ensure that we're getting the right base class subobject (without 13709 // ambiguities), we need to cast "this" to that subobject type; to 13710 // ensure that we don't go through the virtual call mechanism, we need 13711 // to qualify the operator= name with the base class (see below). However, 13712 // this means that if the base class has a protected copy assignment 13713 // operator, the protected member access check will fail. So, we 13714 // rewrite "protected" access to "public" access in this case, since we 13715 // know by construction that we're calling from a derived class. 13716 if (CopyingBaseSubobject) { 13717 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 13718 L != LEnd; ++L) { 13719 if (L.getAccess() == AS_protected) 13720 L.setAccess(AS_public); 13721 } 13722 } 13723 13724 // Create the nested-name-specifier that will be used to qualify the 13725 // reference to operator=; this is required to suppress the virtual 13726 // call mechanism. 13727 CXXScopeSpec SS; 13728 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 13729 SS.MakeTrivial(S.Context, 13730 NestedNameSpecifier::Create(S.Context, nullptr, false, 13731 CanonicalT), 13732 Loc); 13733 13734 // Create the reference to operator=. 13735 ExprResult OpEqualRef 13736 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false, 13737 SS, /*TemplateKWLoc=*/SourceLocation(), 13738 /*FirstQualifierInScope=*/nullptr, 13739 OpLookup, 13740 /*TemplateArgs=*/nullptr, /*S*/nullptr, 13741 /*SuppressQualifierCheck=*/true); 13742 if (OpEqualRef.isInvalid()) 13743 return StmtError(); 13744 13745 // Build the call to the assignment operator. 13746 13747 Expr *FromInst = From.build(S, Loc); 13748 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 13749 OpEqualRef.getAs<Expr>(), 13750 Loc, FromInst, Loc); 13751 if (Call.isInvalid()) 13752 return StmtError(); 13753 13754 // If we built a call to a trivial 'operator=' while copying an array, 13755 // bail out. We'll replace the whole shebang with a memcpy. 13756 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 13757 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 13758 return StmtResult((Stmt*)nullptr); 13759 13760 // Convert to an expression-statement, and clean up any produced 13761 // temporaries. 13762 return S.ActOnExprStmt(Call); 13763 } 13764 13765 // - if the subobject is of scalar type, the built-in assignment 13766 // operator is used. 13767 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 13768 if (!ArrayTy) { 13769 ExprResult Assignment = S.CreateBuiltinBinOp( 13770 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 13771 if (Assignment.isInvalid()) 13772 return StmtError(); 13773 return S.ActOnExprStmt(Assignment); 13774 } 13775 13776 // - if the subobject is an array, each element is assigned, in the 13777 // manner appropriate to the element type; 13778 13779 // Construct a loop over the array bounds, e.g., 13780 // 13781 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 13782 // 13783 // that will copy each of the array elements. 13784 QualType SizeType = S.Context.getSizeType(); 13785 13786 // Create the iteration variable. 13787 IdentifierInfo *IterationVarName = nullptr; 13788 { 13789 SmallString<8> Str; 13790 llvm::raw_svector_ostream OS(Str); 13791 OS << "__i" << Depth; 13792 IterationVarName = &S.Context.Idents.get(OS.str()); 13793 } 13794 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 13795 IterationVarName, SizeType, 13796 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 13797 SC_None); 13798 13799 // Initialize the iteration variable to zero. 13800 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 13801 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 13802 13803 // Creates a reference to the iteration variable. 13804 RefBuilder IterationVarRef(IterationVar, SizeType); 13805 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 13806 13807 // Create the DeclStmt that holds the iteration variable. 13808 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 13809 13810 // Subscript the "from" and "to" expressions with the iteration variable. 13811 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 13812 MoveCastBuilder FromIndexMove(FromIndexCopy); 13813 const ExprBuilder *FromIndex; 13814 if (Copying) 13815 FromIndex = &FromIndexCopy; 13816 else 13817 FromIndex = &FromIndexMove; 13818 13819 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 13820 13821 // Build the copy/move for an individual element of the array. 13822 StmtResult Copy = 13823 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 13824 ToIndex, *FromIndex, CopyingBaseSubobject, 13825 Copying, Depth + 1); 13826 // Bail out if copying fails or if we determined that we should use memcpy. 13827 if (Copy.isInvalid() || !Copy.get()) 13828 return Copy; 13829 13830 // Create the comparison against the array bound. 13831 llvm::APInt Upper 13832 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 13833 Expr *Comparison = BinaryOperator::Create( 13834 S.Context, IterationVarRefRVal.build(S, Loc), 13835 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE, 13836 S.Context.BoolTy, VK_RValue, OK_Ordinary, Loc, S.CurFPFeatureOverrides()); 13837 13838 // Create the pre-increment of the iteration variable. We can determine 13839 // whether the increment will overflow based on the value of the array 13840 // bound. 13841 Expr *Increment = UnaryOperator::Create( 13842 S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue, 13843 OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides()); 13844 13845 // Construct the loop that copies all elements of this array. 13846 return S.ActOnForStmt( 13847 Loc, Loc, InitStmt, 13848 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean), 13849 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get()); 13850 } 13851 13852 static StmtResult 13853 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 13854 const ExprBuilder &To, const ExprBuilder &From, 13855 bool CopyingBaseSubobject, bool Copying) { 13856 // Maybe we should use a memcpy? 13857 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 13858 T.isTriviallyCopyableType(S.Context)) 13859 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 13860 13861 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 13862 CopyingBaseSubobject, 13863 Copying, 0)); 13864 13865 // If we ended up picking a trivial assignment operator for an array of a 13866 // non-trivially-copyable class type, just emit a memcpy. 13867 if (!Result.isInvalid() && !Result.get()) 13868 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 13869 13870 return Result; 13871 } 13872 13873 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 13874 // Note: The following rules are largely analoguous to the copy 13875 // constructor rules. Note that virtual bases are not taken into account 13876 // for determining the argument type of the operator. Note also that 13877 // operators taking an object instead of a reference are allowed. 13878 assert(ClassDecl->needsImplicitCopyAssignment()); 13879 13880 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 13881 if (DSM.isAlreadyBeingDeclared()) 13882 return nullptr; 13883 13884 QualType ArgType = Context.getTypeDeclType(ClassDecl); 13885 LangAS AS = getDefaultCXXMethodAddrSpace(); 13886 if (AS != LangAS::Default) 13887 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 13888 QualType RetType = Context.getLValueReferenceType(ArgType); 13889 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 13890 if (Const) 13891 ArgType = ArgType.withConst(); 13892 13893 ArgType = Context.getLValueReferenceType(ArgType); 13894 13895 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 13896 CXXCopyAssignment, 13897 Const); 13898 13899 // An implicitly-declared copy assignment operator is an inline public 13900 // member of its class. 13901 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 13902 SourceLocation ClassLoc = ClassDecl->getLocation(); 13903 DeclarationNameInfo NameInfo(Name, ClassLoc); 13904 CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create( 13905 Context, ClassDecl, ClassLoc, NameInfo, QualType(), 13906 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 13907 /*isInline=*/true, 13908 Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified, 13909 SourceLocation()); 13910 CopyAssignment->setAccess(AS_public); 13911 CopyAssignment->setDefaulted(); 13912 CopyAssignment->setImplicit(); 13913 13914 if (getLangOpts().CUDA) { 13915 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 13916 CopyAssignment, 13917 /* ConstRHS */ Const, 13918 /* Diagnose */ false); 13919 } 13920 13921 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType); 13922 13923 // Add the parameter to the operator. 13924 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 13925 ClassLoc, ClassLoc, 13926 /*Id=*/nullptr, ArgType, 13927 /*TInfo=*/nullptr, SC_None, 13928 nullptr); 13929 CopyAssignment->setParams(FromParam); 13930 13931 CopyAssignment->setTrivial( 13932 ClassDecl->needsOverloadResolutionForCopyAssignment() 13933 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 13934 : ClassDecl->hasTrivialCopyAssignment()); 13935 13936 // Note that we have added this copy-assignment operator. 13937 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared; 13938 13939 Scope *S = getScopeForContext(ClassDecl); 13940 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment); 13941 13942 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) { 13943 ClassDecl->setImplicitCopyAssignmentIsDeleted(); 13944 SetDeclDeleted(CopyAssignment, ClassLoc); 13945 } 13946 13947 if (S) 13948 PushOnScopeChains(CopyAssignment, S, false); 13949 ClassDecl->addDecl(CopyAssignment); 13950 13951 return CopyAssignment; 13952 } 13953 13954 /// Diagnose an implicit copy operation for a class which is odr-used, but 13955 /// which is deprecated because the class has a user-declared copy constructor, 13956 /// copy assignment operator, or destructor. 13957 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) { 13958 assert(CopyOp->isImplicit()); 13959 13960 CXXRecordDecl *RD = CopyOp->getParent(); 13961 CXXMethodDecl *UserDeclaredOperation = nullptr; 13962 13963 // In Microsoft mode, assignment operations don't affect constructors and 13964 // vice versa. 13965 if (RD->hasUserDeclaredDestructor()) { 13966 UserDeclaredOperation = RD->getDestructor(); 13967 } else if (!isa<CXXConstructorDecl>(CopyOp) && 13968 RD->hasUserDeclaredCopyConstructor() && 13969 !S.getLangOpts().MSVCCompat) { 13970 // Find any user-declared copy constructor. 13971 for (auto *I : RD->ctors()) { 13972 if (I->isCopyConstructor()) { 13973 UserDeclaredOperation = I; 13974 break; 13975 } 13976 } 13977 assert(UserDeclaredOperation); 13978 } else if (isa<CXXConstructorDecl>(CopyOp) && 13979 RD->hasUserDeclaredCopyAssignment() && 13980 !S.getLangOpts().MSVCCompat) { 13981 // Find any user-declared move assignment operator. 13982 for (auto *I : RD->methods()) { 13983 if (I->isCopyAssignmentOperator()) { 13984 UserDeclaredOperation = I; 13985 break; 13986 } 13987 } 13988 assert(UserDeclaredOperation); 13989 } 13990 13991 if (UserDeclaredOperation && UserDeclaredOperation->isUserProvided()) { 13992 S.Diag(UserDeclaredOperation->getLocation(), 13993 isa<CXXDestructorDecl>(UserDeclaredOperation) 13994 ? diag::warn_deprecated_copy_dtor_operation 13995 : diag::warn_deprecated_copy_operation) 13996 << RD << /*copy assignment*/ !isa<CXXConstructorDecl>(CopyOp); 13997 } 13998 } 13999 14000 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 14001 CXXMethodDecl *CopyAssignOperator) { 14002 assert((CopyAssignOperator->isDefaulted() && 14003 CopyAssignOperator->isOverloadedOperator() && 14004 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 14005 !CopyAssignOperator->doesThisDeclarationHaveABody() && 14006 !CopyAssignOperator->isDeleted()) && 14007 "DefineImplicitCopyAssignment called for wrong function"); 14008 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl()) 14009 return; 14010 14011 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 14012 if (ClassDecl->isInvalidDecl()) { 14013 CopyAssignOperator->setInvalidDecl(); 14014 return; 14015 } 14016 14017 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 14018 14019 // The exception specification is needed because we are defining the 14020 // function. 14021 ResolveExceptionSpec(CurrentLocation, 14022 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 14023 14024 // Add a context note for diagnostics produced after this point. 14025 Scope.addContextNote(CurrentLocation); 14026 14027 // C++11 [class.copy]p18: 14028 // The [definition of an implicitly declared copy assignment operator] is 14029 // deprecated if the class has a user-declared copy constructor or a 14030 // user-declared destructor. 14031 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 14032 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator); 14033 14034 // C++0x [class.copy]p30: 14035 // The implicitly-defined or explicitly-defaulted copy assignment operator 14036 // for a non-union class X performs memberwise copy assignment of its 14037 // subobjects. The direct base classes of X are assigned first, in the 14038 // order of their declaration in the base-specifier-list, and then the 14039 // immediate non-static data members of X are assigned, in the order in 14040 // which they were declared in the class definition. 14041 14042 // The statements that form the synthesized function body. 14043 SmallVector<Stmt*, 8> Statements; 14044 14045 // The parameter for the "other" object, which we are copying from. 14046 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 14047 Qualifiers OtherQuals = Other->getType().getQualifiers(); 14048 QualType OtherRefType = Other->getType(); 14049 if (const LValueReferenceType *OtherRef 14050 = OtherRefType->getAs<LValueReferenceType>()) { 14051 OtherRefType = OtherRef->getPointeeType(); 14052 OtherQuals = OtherRefType.getQualifiers(); 14053 } 14054 14055 // Our location for everything implicitly-generated. 14056 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid() 14057 ? CopyAssignOperator->getEndLoc() 14058 : CopyAssignOperator->getLocation(); 14059 14060 // Builds a DeclRefExpr for the "other" object. 14061 RefBuilder OtherRef(Other, OtherRefType); 14062 14063 // Builds the "this" pointer. 14064 ThisBuilder This; 14065 14066 // Assign base classes. 14067 bool Invalid = false; 14068 for (auto &Base : ClassDecl->bases()) { 14069 // Form the assignment: 14070 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 14071 QualType BaseType = Base.getType().getUnqualifiedType(); 14072 if (!BaseType->isRecordType()) { 14073 Invalid = true; 14074 continue; 14075 } 14076 14077 CXXCastPath BasePath; 14078 BasePath.push_back(&Base); 14079 14080 // Construct the "from" expression, which is an implicit cast to the 14081 // appropriately-qualified base type. 14082 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 14083 VK_LValue, BasePath); 14084 14085 // Dereference "this". 14086 DerefBuilder DerefThis(This); 14087 CastBuilder To(DerefThis, 14088 Context.getQualifiedType( 14089 BaseType, CopyAssignOperator->getMethodQualifiers()), 14090 VK_LValue, BasePath); 14091 14092 // Build the copy. 14093 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 14094 To, From, 14095 /*CopyingBaseSubobject=*/true, 14096 /*Copying=*/true); 14097 if (Copy.isInvalid()) { 14098 CopyAssignOperator->setInvalidDecl(); 14099 return; 14100 } 14101 14102 // Success! Record the copy. 14103 Statements.push_back(Copy.getAs<Expr>()); 14104 } 14105 14106 // Assign non-static members. 14107 for (auto *Field : ClassDecl->fields()) { 14108 // FIXME: We should form some kind of AST representation for the implied 14109 // memcpy in a union copy operation. 14110 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 14111 continue; 14112 14113 if (Field->isInvalidDecl()) { 14114 Invalid = true; 14115 continue; 14116 } 14117 14118 // Check for members of reference type; we can't copy those. 14119 if (Field->getType()->isReferenceType()) { 14120 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14121 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 14122 Diag(Field->getLocation(), diag::note_declared_at); 14123 Invalid = true; 14124 continue; 14125 } 14126 14127 // Check for members of const-qualified, non-class type. 14128 QualType BaseType = Context.getBaseElementType(Field->getType()); 14129 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 14130 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14131 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 14132 Diag(Field->getLocation(), diag::note_declared_at); 14133 Invalid = true; 14134 continue; 14135 } 14136 14137 // Suppress assigning zero-width bitfields. 14138 if (Field->isZeroLengthBitField(Context)) 14139 continue; 14140 14141 QualType FieldType = Field->getType().getNonReferenceType(); 14142 if (FieldType->isIncompleteArrayType()) { 14143 assert(ClassDecl->hasFlexibleArrayMember() && 14144 "Incomplete array type is not valid"); 14145 continue; 14146 } 14147 14148 // Build references to the field in the object we're copying from and to. 14149 CXXScopeSpec SS; // Intentionally empty 14150 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 14151 LookupMemberName); 14152 MemberLookup.addDecl(Field); 14153 MemberLookup.resolveKind(); 14154 14155 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 14156 14157 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 14158 14159 // Build the copy of this field. 14160 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 14161 To, From, 14162 /*CopyingBaseSubobject=*/false, 14163 /*Copying=*/true); 14164 if (Copy.isInvalid()) { 14165 CopyAssignOperator->setInvalidDecl(); 14166 return; 14167 } 14168 14169 // Success! Record the copy. 14170 Statements.push_back(Copy.getAs<Stmt>()); 14171 } 14172 14173 if (!Invalid) { 14174 // Add a "return *this;" 14175 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 14176 14177 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 14178 if (Return.isInvalid()) 14179 Invalid = true; 14180 else 14181 Statements.push_back(Return.getAs<Stmt>()); 14182 } 14183 14184 if (Invalid) { 14185 CopyAssignOperator->setInvalidDecl(); 14186 return; 14187 } 14188 14189 StmtResult Body; 14190 { 14191 CompoundScopeRAII CompoundScope(*this); 14192 Body = ActOnCompoundStmt(Loc, Loc, Statements, 14193 /*isStmtExpr=*/false); 14194 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 14195 } 14196 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 14197 CopyAssignOperator->markUsed(Context); 14198 14199 if (ASTMutationListener *L = getASTMutationListener()) { 14200 L->CompletedImplicitDefinition(CopyAssignOperator); 14201 } 14202 } 14203 14204 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 14205 assert(ClassDecl->needsImplicitMoveAssignment()); 14206 14207 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 14208 if (DSM.isAlreadyBeingDeclared()) 14209 return nullptr; 14210 14211 // Note: The following rules are largely analoguous to the move 14212 // constructor rules. 14213 14214 QualType ArgType = Context.getTypeDeclType(ClassDecl); 14215 LangAS AS = getDefaultCXXMethodAddrSpace(); 14216 if (AS != LangAS::Default) 14217 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 14218 QualType RetType = Context.getLValueReferenceType(ArgType); 14219 ArgType = Context.getRValueReferenceType(ArgType); 14220 14221 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14222 CXXMoveAssignment, 14223 false); 14224 14225 // An implicitly-declared move assignment operator is an inline public 14226 // member of its class. 14227 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 14228 SourceLocation ClassLoc = ClassDecl->getLocation(); 14229 DeclarationNameInfo NameInfo(Name, ClassLoc); 14230 CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create( 14231 Context, ClassDecl, ClassLoc, NameInfo, QualType(), 14232 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 14233 /*isInline=*/true, 14234 Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified, 14235 SourceLocation()); 14236 MoveAssignment->setAccess(AS_public); 14237 MoveAssignment->setDefaulted(); 14238 MoveAssignment->setImplicit(); 14239 14240 if (getLangOpts().CUDA) { 14241 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 14242 MoveAssignment, 14243 /* ConstRHS */ false, 14244 /* Diagnose */ false); 14245 } 14246 14247 // Build an exception specification pointing back at this member. 14248 FunctionProtoType::ExtProtoInfo EPI = 14249 getImplicitMethodEPI(*this, MoveAssignment); 14250 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 14251 14252 // Add the parameter to the operator. 14253 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 14254 ClassLoc, ClassLoc, 14255 /*Id=*/nullptr, ArgType, 14256 /*TInfo=*/nullptr, SC_None, 14257 nullptr); 14258 MoveAssignment->setParams(FromParam); 14259 14260 MoveAssignment->setTrivial( 14261 ClassDecl->needsOverloadResolutionForMoveAssignment() 14262 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 14263 : ClassDecl->hasTrivialMoveAssignment()); 14264 14265 // Note that we have added this copy-assignment operator. 14266 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared; 14267 14268 Scope *S = getScopeForContext(ClassDecl); 14269 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment); 14270 14271 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 14272 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 14273 SetDeclDeleted(MoveAssignment, ClassLoc); 14274 } 14275 14276 if (S) 14277 PushOnScopeChains(MoveAssignment, S, false); 14278 ClassDecl->addDecl(MoveAssignment); 14279 14280 return MoveAssignment; 14281 } 14282 14283 /// Check if we're implicitly defining a move assignment operator for a class 14284 /// with virtual bases. Such a move assignment might move-assign the virtual 14285 /// base multiple times. 14286 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 14287 SourceLocation CurrentLocation) { 14288 assert(!Class->isDependentContext() && "should not define dependent move"); 14289 14290 // Only a virtual base could get implicitly move-assigned multiple times. 14291 // Only a non-trivial move assignment can observe this. We only want to 14292 // diagnose if we implicitly define an assignment operator that assigns 14293 // two base classes, both of which move-assign the same virtual base. 14294 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 14295 Class->getNumBases() < 2) 14296 return; 14297 14298 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 14299 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 14300 VBaseMap VBases; 14301 14302 for (auto &BI : Class->bases()) { 14303 Worklist.push_back(&BI); 14304 while (!Worklist.empty()) { 14305 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 14306 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 14307 14308 // If the base has no non-trivial move assignment operators, 14309 // we don't care about moves from it. 14310 if (!Base->hasNonTrivialMoveAssignment()) 14311 continue; 14312 14313 // If there's nothing virtual here, skip it. 14314 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 14315 continue; 14316 14317 // If we're not actually going to call a move assignment for this base, 14318 // or the selected move assignment is trivial, skip it. 14319 Sema::SpecialMemberOverloadResult SMOR = 14320 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 14321 /*ConstArg*/false, /*VolatileArg*/false, 14322 /*RValueThis*/true, /*ConstThis*/false, 14323 /*VolatileThis*/false); 14324 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() || 14325 !SMOR.getMethod()->isMoveAssignmentOperator()) 14326 continue; 14327 14328 if (BaseSpec->isVirtual()) { 14329 // We're going to move-assign this virtual base, and its move 14330 // assignment operator is not trivial. If this can happen for 14331 // multiple distinct direct bases of Class, diagnose it. (If it 14332 // only happens in one base, we'll diagnose it when synthesizing 14333 // that base class's move assignment operator.) 14334 CXXBaseSpecifier *&Existing = 14335 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 14336 .first->second; 14337 if (Existing && Existing != &BI) { 14338 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 14339 << Class << Base; 14340 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here) 14341 << (Base->getCanonicalDecl() == 14342 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 14343 << Base << Existing->getType() << Existing->getSourceRange(); 14344 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here) 14345 << (Base->getCanonicalDecl() == 14346 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 14347 << Base << BI.getType() << BaseSpec->getSourceRange(); 14348 14349 // Only diagnose each vbase once. 14350 Existing = nullptr; 14351 } 14352 } else { 14353 // Only walk over bases that have defaulted move assignment operators. 14354 // We assume that any user-provided move assignment operator handles 14355 // the multiple-moves-of-vbase case itself somehow. 14356 if (!SMOR.getMethod()->isDefaulted()) 14357 continue; 14358 14359 // We're going to move the base classes of Base. Add them to the list. 14360 for (auto &BI : Base->bases()) 14361 Worklist.push_back(&BI); 14362 } 14363 } 14364 } 14365 } 14366 14367 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 14368 CXXMethodDecl *MoveAssignOperator) { 14369 assert((MoveAssignOperator->isDefaulted() && 14370 MoveAssignOperator->isOverloadedOperator() && 14371 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 14372 !MoveAssignOperator->doesThisDeclarationHaveABody() && 14373 !MoveAssignOperator->isDeleted()) && 14374 "DefineImplicitMoveAssignment called for wrong function"); 14375 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl()) 14376 return; 14377 14378 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 14379 if (ClassDecl->isInvalidDecl()) { 14380 MoveAssignOperator->setInvalidDecl(); 14381 return; 14382 } 14383 14384 // C++0x [class.copy]p28: 14385 // The implicitly-defined or move assignment operator for a non-union class 14386 // X performs memberwise move assignment of its subobjects. The direct base 14387 // classes of X are assigned first, in the order of their declaration in the 14388 // base-specifier-list, and then the immediate non-static data members of X 14389 // are assigned, in the order in which they were declared in the class 14390 // definition. 14391 14392 // Issue a warning if our implicit move assignment operator will move 14393 // from a virtual base more than once. 14394 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 14395 14396 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 14397 14398 // The exception specification is needed because we are defining the 14399 // function. 14400 ResolveExceptionSpec(CurrentLocation, 14401 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 14402 14403 // Add a context note for diagnostics produced after this point. 14404 Scope.addContextNote(CurrentLocation); 14405 14406 // The statements that form the synthesized function body. 14407 SmallVector<Stmt*, 8> Statements; 14408 14409 // The parameter for the "other" object, which we are move from. 14410 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 14411 QualType OtherRefType = 14412 Other->getType()->castAs<RValueReferenceType>()->getPointeeType(); 14413 14414 // Our location for everything implicitly-generated. 14415 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid() 14416 ? MoveAssignOperator->getEndLoc() 14417 : MoveAssignOperator->getLocation(); 14418 14419 // Builds a reference to the "other" object. 14420 RefBuilder OtherRef(Other, OtherRefType); 14421 // Cast to rvalue. 14422 MoveCastBuilder MoveOther(OtherRef); 14423 14424 // Builds the "this" pointer. 14425 ThisBuilder This; 14426 14427 // Assign base classes. 14428 bool Invalid = false; 14429 for (auto &Base : ClassDecl->bases()) { 14430 // C++11 [class.copy]p28: 14431 // It is unspecified whether subobjects representing virtual base classes 14432 // are assigned more than once by the implicitly-defined copy assignment 14433 // operator. 14434 // FIXME: Do not assign to a vbase that will be assigned by some other base 14435 // class. For a move-assignment, this can result in the vbase being moved 14436 // multiple times. 14437 14438 // Form the assignment: 14439 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 14440 QualType BaseType = Base.getType().getUnqualifiedType(); 14441 if (!BaseType->isRecordType()) { 14442 Invalid = true; 14443 continue; 14444 } 14445 14446 CXXCastPath BasePath; 14447 BasePath.push_back(&Base); 14448 14449 // Construct the "from" expression, which is an implicit cast to the 14450 // appropriately-qualified base type. 14451 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 14452 14453 // Dereference "this". 14454 DerefBuilder DerefThis(This); 14455 14456 // Implicitly cast "this" to the appropriately-qualified base type. 14457 CastBuilder To(DerefThis, 14458 Context.getQualifiedType( 14459 BaseType, MoveAssignOperator->getMethodQualifiers()), 14460 VK_LValue, BasePath); 14461 14462 // Build the move. 14463 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 14464 To, From, 14465 /*CopyingBaseSubobject=*/true, 14466 /*Copying=*/false); 14467 if (Move.isInvalid()) { 14468 MoveAssignOperator->setInvalidDecl(); 14469 return; 14470 } 14471 14472 // Success! Record the move. 14473 Statements.push_back(Move.getAs<Expr>()); 14474 } 14475 14476 // Assign non-static members. 14477 for (auto *Field : ClassDecl->fields()) { 14478 // FIXME: We should form some kind of AST representation for the implied 14479 // memcpy in a union copy operation. 14480 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 14481 continue; 14482 14483 if (Field->isInvalidDecl()) { 14484 Invalid = true; 14485 continue; 14486 } 14487 14488 // Check for members of reference type; we can't move those. 14489 if (Field->getType()->isReferenceType()) { 14490 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14491 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 14492 Diag(Field->getLocation(), diag::note_declared_at); 14493 Invalid = true; 14494 continue; 14495 } 14496 14497 // Check for members of const-qualified, non-class type. 14498 QualType BaseType = Context.getBaseElementType(Field->getType()); 14499 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 14500 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14501 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 14502 Diag(Field->getLocation(), diag::note_declared_at); 14503 Invalid = true; 14504 continue; 14505 } 14506 14507 // Suppress assigning zero-width bitfields. 14508 if (Field->isZeroLengthBitField(Context)) 14509 continue; 14510 14511 QualType FieldType = Field->getType().getNonReferenceType(); 14512 if (FieldType->isIncompleteArrayType()) { 14513 assert(ClassDecl->hasFlexibleArrayMember() && 14514 "Incomplete array type is not valid"); 14515 continue; 14516 } 14517 14518 // Build references to the field in the object we're copying from and to. 14519 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 14520 LookupMemberName); 14521 MemberLookup.addDecl(Field); 14522 MemberLookup.resolveKind(); 14523 MemberBuilder From(MoveOther, OtherRefType, 14524 /*IsArrow=*/false, MemberLookup); 14525 MemberBuilder To(This, getCurrentThisType(), 14526 /*IsArrow=*/true, MemberLookup); 14527 14528 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 14529 "Member reference with rvalue base must be rvalue except for reference " 14530 "members, which aren't allowed for move assignment."); 14531 14532 // Build the move of this field. 14533 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 14534 To, From, 14535 /*CopyingBaseSubobject=*/false, 14536 /*Copying=*/false); 14537 if (Move.isInvalid()) { 14538 MoveAssignOperator->setInvalidDecl(); 14539 return; 14540 } 14541 14542 // Success! Record the copy. 14543 Statements.push_back(Move.getAs<Stmt>()); 14544 } 14545 14546 if (!Invalid) { 14547 // Add a "return *this;" 14548 ExprResult ThisObj = 14549 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 14550 14551 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 14552 if (Return.isInvalid()) 14553 Invalid = true; 14554 else 14555 Statements.push_back(Return.getAs<Stmt>()); 14556 } 14557 14558 if (Invalid) { 14559 MoveAssignOperator->setInvalidDecl(); 14560 return; 14561 } 14562 14563 StmtResult Body; 14564 { 14565 CompoundScopeRAII CompoundScope(*this); 14566 Body = ActOnCompoundStmt(Loc, Loc, Statements, 14567 /*isStmtExpr=*/false); 14568 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 14569 } 14570 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 14571 MoveAssignOperator->markUsed(Context); 14572 14573 if (ASTMutationListener *L = getASTMutationListener()) { 14574 L->CompletedImplicitDefinition(MoveAssignOperator); 14575 } 14576 } 14577 14578 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 14579 CXXRecordDecl *ClassDecl) { 14580 // C++ [class.copy]p4: 14581 // If the class definition does not explicitly declare a copy 14582 // constructor, one is declared implicitly. 14583 assert(ClassDecl->needsImplicitCopyConstructor()); 14584 14585 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 14586 if (DSM.isAlreadyBeingDeclared()) 14587 return nullptr; 14588 14589 QualType ClassType = Context.getTypeDeclType(ClassDecl); 14590 QualType ArgType = ClassType; 14591 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 14592 if (Const) 14593 ArgType = ArgType.withConst(); 14594 14595 LangAS AS = getDefaultCXXMethodAddrSpace(); 14596 if (AS != LangAS::Default) 14597 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 14598 14599 ArgType = Context.getLValueReferenceType(ArgType); 14600 14601 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14602 CXXCopyConstructor, 14603 Const); 14604 14605 DeclarationName Name 14606 = Context.DeclarationNames.getCXXConstructorName( 14607 Context.getCanonicalType(ClassType)); 14608 SourceLocation ClassLoc = ClassDecl->getLocation(); 14609 DeclarationNameInfo NameInfo(Name, ClassLoc); 14610 14611 // An implicitly-declared copy constructor is an inline public 14612 // member of its class. 14613 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 14614 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 14615 ExplicitSpecifier(), 14616 /*isInline=*/true, 14617 /*isImplicitlyDeclared=*/true, 14618 Constexpr ? ConstexprSpecKind::Constexpr 14619 : ConstexprSpecKind::Unspecified); 14620 CopyConstructor->setAccess(AS_public); 14621 CopyConstructor->setDefaulted(); 14622 14623 if (getLangOpts().CUDA) { 14624 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 14625 CopyConstructor, 14626 /* ConstRHS */ Const, 14627 /* Diagnose */ false); 14628 } 14629 14630 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType); 14631 14632 // Add the parameter to the constructor. 14633 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 14634 ClassLoc, ClassLoc, 14635 /*IdentifierInfo=*/nullptr, 14636 ArgType, /*TInfo=*/nullptr, 14637 SC_None, nullptr); 14638 CopyConstructor->setParams(FromParam); 14639 14640 CopyConstructor->setTrivial( 14641 ClassDecl->needsOverloadResolutionForCopyConstructor() 14642 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 14643 : ClassDecl->hasTrivialCopyConstructor()); 14644 14645 CopyConstructor->setTrivialForCall( 14646 ClassDecl->hasAttr<TrivialABIAttr>() || 14647 (ClassDecl->needsOverloadResolutionForCopyConstructor() 14648 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor, 14649 TAH_ConsiderTrivialABI) 14650 : ClassDecl->hasTrivialCopyConstructorForCall())); 14651 14652 // Note that we have declared this constructor. 14653 ++getASTContext().NumImplicitCopyConstructorsDeclared; 14654 14655 Scope *S = getScopeForContext(ClassDecl); 14656 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor); 14657 14658 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) { 14659 ClassDecl->setImplicitCopyConstructorIsDeleted(); 14660 SetDeclDeleted(CopyConstructor, ClassLoc); 14661 } 14662 14663 if (S) 14664 PushOnScopeChains(CopyConstructor, S, false); 14665 ClassDecl->addDecl(CopyConstructor); 14666 14667 return CopyConstructor; 14668 } 14669 14670 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 14671 CXXConstructorDecl *CopyConstructor) { 14672 assert((CopyConstructor->isDefaulted() && 14673 CopyConstructor->isCopyConstructor() && 14674 !CopyConstructor->doesThisDeclarationHaveABody() && 14675 !CopyConstructor->isDeleted()) && 14676 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 14677 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl()) 14678 return; 14679 14680 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 14681 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 14682 14683 SynthesizedFunctionScope Scope(*this, CopyConstructor); 14684 14685 // The exception specification is needed because we are defining the 14686 // function. 14687 ResolveExceptionSpec(CurrentLocation, 14688 CopyConstructor->getType()->castAs<FunctionProtoType>()); 14689 MarkVTableUsed(CurrentLocation, ClassDecl); 14690 14691 // Add a context note for diagnostics produced after this point. 14692 Scope.addContextNote(CurrentLocation); 14693 14694 // C++11 [class.copy]p7: 14695 // The [definition of an implicitly declared copy constructor] is 14696 // deprecated if the class has a user-declared copy assignment operator 14697 // or a user-declared destructor. 14698 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 14699 diagnoseDeprecatedCopyOperation(*this, CopyConstructor); 14700 14701 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) { 14702 CopyConstructor->setInvalidDecl(); 14703 } else { 14704 SourceLocation Loc = CopyConstructor->getEndLoc().isValid() 14705 ? CopyConstructor->getEndLoc() 14706 : CopyConstructor->getLocation(); 14707 Sema::CompoundScopeRAII CompoundScope(*this); 14708 CopyConstructor->setBody( 14709 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 14710 CopyConstructor->markUsed(Context); 14711 } 14712 14713 if (ASTMutationListener *L = getASTMutationListener()) { 14714 L->CompletedImplicitDefinition(CopyConstructor); 14715 } 14716 } 14717 14718 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 14719 CXXRecordDecl *ClassDecl) { 14720 assert(ClassDecl->needsImplicitMoveConstructor()); 14721 14722 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 14723 if (DSM.isAlreadyBeingDeclared()) 14724 return nullptr; 14725 14726 QualType ClassType = Context.getTypeDeclType(ClassDecl); 14727 14728 QualType ArgType = ClassType; 14729 LangAS AS = getDefaultCXXMethodAddrSpace(); 14730 if (AS != LangAS::Default) 14731 ArgType = Context.getAddrSpaceQualType(ClassType, AS); 14732 ArgType = Context.getRValueReferenceType(ArgType); 14733 14734 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14735 CXXMoveConstructor, 14736 false); 14737 14738 DeclarationName Name 14739 = Context.DeclarationNames.getCXXConstructorName( 14740 Context.getCanonicalType(ClassType)); 14741 SourceLocation ClassLoc = ClassDecl->getLocation(); 14742 DeclarationNameInfo NameInfo(Name, ClassLoc); 14743 14744 // C++11 [class.copy]p11: 14745 // An implicitly-declared copy/move constructor is an inline public 14746 // member of its class. 14747 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 14748 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 14749 ExplicitSpecifier(), 14750 /*isInline=*/true, 14751 /*isImplicitlyDeclared=*/true, 14752 Constexpr ? ConstexprSpecKind::Constexpr 14753 : ConstexprSpecKind::Unspecified); 14754 MoveConstructor->setAccess(AS_public); 14755 MoveConstructor->setDefaulted(); 14756 14757 if (getLangOpts().CUDA) { 14758 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 14759 MoveConstructor, 14760 /* ConstRHS */ false, 14761 /* Diagnose */ false); 14762 } 14763 14764 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType); 14765 14766 // Add the parameter to the constructor. 14767 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 14768 ClassLoc, ClassLoc, 14769 /*IdentifierInfo=*/nullptr, 14770 ArgType, /*TInfo=*/nullptr, 14771 SC_None, nullptr); 14772 MoveConstructor->setParams(FromParam); 14773 14774 MoveConstructor->setTrivial( 14775 ClassDecl->needsOverloadResolutionForMoveConstructor() 14776 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 14777 : ClassDecl->hasTrivialMoveConstructor()); 14778 14779 MoveConstructor->setTrivialForCall( 14780 ClassDecl->hasAttr<TrivialABIAttr>() || 14781 (ClassDecl->needsOverloadResolutionForMoveConstructor() 14782 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor, 14783 TAH_ConsiderTrivialABI) 14784 : ClassDecl->hasTrivialMoveConstructorForCall())); 14785 14786 // Note that we have declared this constructor. 14787 ++getASTContext().NumImplicitMoveConstructorsDeclared; 14788 14789 Scope *S = getScopeForContext(ClassDecl); 14790 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor); 14791 14792 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 14793 ClassDecl->setImplicitMoveConstructorIsDeleted(); 14794 SetDeclDeleted(MoveConstructor, ClassLoc); 14795 } 14796 14797 if (S) 14798 PushOnScopeChains(MoveConstructor, S, false); 14799 ClassDecl->addDecl(MoveConstructor); 14800 14801 return MoveConstructor; 14802 } 14803 14804 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 14805 CXXConstructorDecl *MoveConstructor) { 14806 assert((MoveConstructor->isDefaulted() && 14807 MoveConstructor->isMoveConstructor() && 14808 !MoveConstructor->doesThisDeclarationHaveABody() && 14809 !MoveConstructor->isDeleted()) && 14810 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 14811 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl()) 14812 return; 14813 14814 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 14815 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 14816 14817 SynthesizedFunctionScope Scope(*this, MoveConstructor); 14818 14819 // The exception specification is needed because we are defining the 14820 // function. 14821 ResolveExceptionSpec(CurrentLocation, 14822 MoveConstructor->getType()->castAs<FunctionProtoType>()); 14823 MarkVTableUsed(CurrentLocation, ClassDecl); 14824 14825 // Add a context note for diagnostics produced after this point. 14826 Scope.addContextNote(CurrentLocation); 14827 14828 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) { 14829 MoveConstructor->setInvalidDecl(); 14830 } else { 14831 SourceLocation Loc = MoveConstructor->getEndLoc().isValid() 14832 ? MoveConstructor->getEndLoc() 14833 : MoveConstructor->getLocation(); 14834 Sema::CompoundScopeRAII CompoundScope(*this); 14835 MoveConstructor->setBody(ActOnCompoundStmt( 14836 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 14837 MoveConstructor->markUsed(Context); 14838 } 14839 14840 if (ASTMutationListener *L = getASTMutationListener()) { 14841 L->CompletedImplicitDefinition(MoveConstructor); 14842 } 14843 } 14844 14845 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 14846 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 14847 } 14848 14849 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 14850 SourceLocation CurrentLocation, 14851 CXXConversionDecl *Conv) { 14852 SynthesizedFunctionScope Scope(*this, Conv); 14853 assert(!Conv->getReturnType()->isUndeducedType()); 14854 14855 QualType ConvRT = Conv->getType()->getAs<FunctionType>()->getReturnType(); 14856 CallingConv CC = 14857 ConvRT->getPointeeType()->getAs<FunctionType>()->getCallConv(); 14858 14859 CXXRecordDecl *Lambda = Conv->getParent(); 14860 FunctionDecl *CallOp = Lambda->getLambdaCallOperator(); 14861 FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(CC); 14862 14863 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) { 14864 CallOp = InstantiateFunctionDeclaration( 14865 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 14866 if (!CallOp) 14867 return; 14868 14869 Invoker = InstantiateFunctionDeclaration( 14870 Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 14871 if (!Invoker) 14872 return; 14873 } 14874 14875 if (CallOp->isInvalidDecl()) 14876 return; 14877 14878 // Mark the call operator referenced (and add to pending instantiations 14879 // if necessary). 14880 // For both the conversion and static-invoker template specializations 14881 // we construct their body's in this function, so no need to add them 14882 // to the PendingInstantiations. 14883 MarkFunctionReferenced(CurrentLocation, CallOp); 14884 14885 // Fill in the __invoke function with a dummy implementation. IR generation 14886 // will fill in the actual details. Update its type in case it contained 14887 // an 'auto'. 14888 Invoker->markUsed(Context); 14889 Invoker->setReferenced(); 14890 Invoker->setType(Conv->getReturnType()->getPointeeType()); 14891 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 14892 14893 // Construct the body of the conversion function { return __invoke; }. 14894 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 14895 VK_LValue, Conv->getLocation()); 14896 assert(FunctionRef && "Can't refer to __invoke function?"); 14897 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 14898 Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(), 14899 Conv->getLocation())); 14900 Conv->markUsed(Context); 14901 Conv->setReferenced(); 14902 14903 if (ASTMutationListener *L = getASTMutationListener()) { 14904 L->CompletedImplicitDefinition(Conv); 14905 L->CompletedImplicitDefinition(Invoker); 14906 } 14907 } 14908 14909 14910 14911 void Sema::DefineImplicitLambdaToBlockPointerConversion( 14912 SourceLocation CurrentLocation, 14913 CXXConversionDecl *Conv) 14914 { 14915 assert(!Conv->getParent()->isGenericLambda()); 14916 14917 SynthesizedFunctionScope Scope(*this, Conv); 14918 14919 // Copy-initialize the lambda object as needed to capture it. 14920 Expr *This = ActOnCXXThis(CurrentLocation).get(); 14921 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 14922 14923 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 14924 Conv->getLocation(), 14925 Conv, DerefThis); 14926 14927 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 14928 // behavior. Note that only the general conversion function does this 14929 // (since it's unusable otherwise); in the case where we inline the 14930 // block literal, it has block literal lifetime semantics. 14931 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 14932 BuildBlock = ImplicitCastExpr::Create( 14933 Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject, 14934 BuildBlock.get(), nullptr, VK_RValue, FPOptionsOverride()); 14935 14936 if (BuildBlock.isInvalid()) { 14937 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 14938 Conv->setInvalidDecl(); 14939 return; 14940 } 14941 14942 // Create the return statement that returns the block from the conversion 14943 // function. 14944 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 14945 if (Return.isInvalid()) { 14946 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 14947 Conv->setInvalidDecl(); 14948 return; 14949 } 14950 14951 // Set the body of the conversion function. 14952 Stmt *ReturnS = Return.get(); 14953 Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(), 14954 Conv->getLocation())); 14955 Conv->markUsed(Context); 14956 14957 // We're done; notify the mutation listener, if any. 14958 if (ASTMutationListener *L = getASTMutationListener()) { 14959 L->CompletedImplicitDefinition(Conv); 14960 } 14961 } 14962 14963 /// Determine whether the given list arguments contains exactly one 14964 /// "real" (non-default) argument. 14965 static bool hasOneRealArgument(MultiExprArg Args) { 14966 switch (Args.size()) { 14967 case 0: 14968 return false; 14969 14970 default: 14971 if (!Args[1]->isDefaultArgument()) 14972 return false; 14973 14974 LLVM_FALLTHROUGH; 14975 case 1: 14976 return !Args[0]->isDefaultArgument(); 14977 } 14978 14979 return false; 14980 } 14981 14982 ExprResult 14983 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 14984 NamedDecl *FoundDecl, 14985 CXXConstructorDecl *Constructor, 14986 MultiExprArg ExprArgs, 14987 bool HadMultipleCandidates, 14988 bool IsListInitialization, 14989 bool IsStdInitListInitialization, 14990 bool RequiresZeroInit, 14991 unsigned ConstructKind, 14992 SourceRange ParenRange) { 14993 bool Elidable = false; 14994 14995 // C++0x [class.copy]p34: 14996 // When certain criteria are met, an implementation is allowed to 14997 // omit the copy/move construction of a class object, even if the 14998 // copy/move constructor and/or destructor for the object have 14999 // side effects. [...] 15000 // - when a temporary class object that has not been bound to a 15001 // reference (12.2) would be copied/moved to a class object 15002 // with the same cv-unqualified type, the copy/move operation 15003 // can be omitted by constructing the temporary object 15004 // directly into the target of the omitted copy/move 15005 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor && 15006 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 15007 Expr *SubExpr = ExprArgs[0]; 15008 Elidable = SubExpr->isTemporaryObject( 15009 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 15010 } 15011 15012 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, 15013 FoundDecl, Constructor, 15014 Elidable, ExprArgs, HadMultipleCandidates, 15015 IsListInitialization, 15016 IsStdInitListInitialization, RequiresZeroInit, 15017 ConstructKind, ParenRange); 15018 } 15019 15020 ExprResult 15021 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 15022 NamedDecl *FoundDecl, 15023 CXXConstructorDecl *Constructor, 15024 bool Elidable, 15025 MultiExprArg ExprArgs, 15026 bool HadMultipleCandidates, 15027 bool IsListInitialization, 15028 bool IsStdInitListInitialization, 15029 bool RequiresZeroInit, 15030 unsigned ConstructKind, 15031 SourceRange ParenRange) { 15032 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) { 15033 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow); 15034 if (DiagnoseUseOfDecl(Constructor, ConstructLoc)) 15035 return ExprError(); 15036 } 15037 15038 return BuildCXXConstructExpr( 15039 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs, 15040 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 15041 RequiresZeroInit, ConstructKind, ParenRange); 15042 } 15043 15044 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 15045 /// including handling of its default argument expressions. 15046 ExprResult 15047 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 15048 CXXConstructorDecl *Constructor, 15049 bool Elidable, 15050 MultiExprArg ExprArgs, 15051 bool HadMultipleCandidates, 15052 bool IsListInitialization, 15053 bool IsStdInitListInitialization, 15054 bool RequiresZeroInit, 15055 unsigned ConstructKind, 15056 SourceRange ParenRange) { 15057 assert(declaresSameEntity( 15058 Constructor->getParent(), 15059 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && 15060 "given constructor for wrong type"); 15061 MarkFunctionReferenced(ConstructLoc, Constructor); 15062 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor)) 15063 return ExprError(); 15064 if (getLangOpts().SYCLIsDevice && 15065 !checkSYCLDeviceFunction(ConstructLoc, Constructor)) 15066 return ExprError(); 15067 15068 return CheckForImmediateInvocation( 15069 CXXConstructExpr::Create( 15070 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs, 15071 HadMultipleCandidates, IsListInitialization, 15072 IsStdInitListInitialization, RequiresZeroInit, 15073 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 15074 ParenRange), 15075 Constructor); 15076 } 15077 15078 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 15079 assert(Field->hasInClassInitializer()); 15080 15081 // If we already have the in-class initializer nothing needs to be done. 15082 if (Field->getInClassInitializer()) 15083 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext); 15084 15085 // If we might have already tried and failed to instantiate, don't try again. 15086 if (Field->isInvalidDecl()) 15087 return ExprError(); 15088 15089 // Maybe we haven't instantiated the in-class initializer. Go check the 15090 // pattern FieldDecl to see if it has one. 15091 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 15092 15093 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 15094 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 15095 DeclContext::lookup_result Lookup = 15096 ClassPattern->lookup(Field->getDeclName()); 15097 15098 FieldDecl *Pattern = nullptr; 15099 for (auto L : Lookup) { 15100 if (isa<FieldDecl>(L)) { 15101 Pattern = cast<FieldDecl>(L); 15102 break; 15103 } 15104 } 15105 assert(Pattern && "We must have set the Pattern!"); 15106 15107 if (!Pattern->hasInClassInitializer() || 15108 InstantiateInClassInitializer(Loc, Field, Pattern, 15109 getTemplateInstantiationArgs(Field))) { 15110 // Don't diagnose this again. 15111 Field->setInvalidDecl(); 15112 return ExprError(); 15113 } 15114 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext); 15115 } 15116 15117 // DR1351: 15118 // If the brace-or-equal-initializer of a non-static data member 15119 // invokes a defaulted default constructor of its class or of an 15120 // enclosing class in a potentially evaluated subexpression, the 15121 // program is ill-formed. 15122 // 15123 // This resolution is unworkable: the exception specification of the 15124 // default constructor can be needed in an unevaluated context, in 15125 // particular, in the operand of a noexcept-expression, and we can be 15126 // unable to compute an exception specification for an enclosed class. 15127 // 15128 // Any attempt to resolve the exception specification of a defaulted default 15129 // constructor before the initializer is lexically complete will ultimately 15130 // come here at which point we can diagnose it. 15131 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 15132 Diag(Loc, diag::err_default_member_initializer_not_yet_parsed) 15133 << OutermostClass << Field; 15134 Diag(Field->getEndLoc(), 15135 diag::note_default_member_initializer_not_yet_parsed); 15136 // Recover by marking the field invalid, unless we're in a SFINAE context. 15137 if (!isSFINAEContext()) 15138 Field->setInvalidDecl(); 15139 return ExprError(); 15140 } 15141 15142 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 15143 if (VD->isInvalidDecl()) return; 15144 // If initializing the variable failed, don't also diagnose problems with 15145 // the desctructor, they're likely related. 15146 if (VD->getInit() && VD->getInit()->containsErrors()) 15147 return; 15148 15149 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 15150 if (ClassDecl->isInvalidDecl()) return; 15151 if (ClassDecl->hasIrrelevantDestructor()) return; 15152 if (ClassDecl->isDependentContext()) return; 15153 15154 if (VD->isNoDestroy(getASTContext())) 15155 return; 15156 15157 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 15158 15159 // If this is an array, we'll require the destructor during initialization, so 15160 // we can skip over this. We still want to emit exit-time destructor warnings 15161 // though. 15162 if (!VD->getType()->isArrayType()) { 15163 MarkFunctionReferenced(VD->getLocation(), Destructor); 15164 CheckDestructorAccess(VD->getLocation(), Destructor, 15165 PDiag(diag::err_access_dtor_var) 15166 << VD->getDeclName() << VD->getType()); 15167 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 15168 } 15169 15170 if (Destructor->isTrivial()) return; 15171 15172 // If the destructor is constexpr, check whether the variable has constant 15173 // destruction now. 15174 if (Destructor->isConstexpr()) { 15175 bool HasConstantInit = false; 15176 if (VD->getInit() && !VD->getInit()->isValueDependent()) 15177 HasConstantInit = VD->evaluateValue(); 15178 SmallVector<PartialDiagnosticAt, 8> Notes; 15179 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() && 15180 HasConstantInit) { 15181 Diag(VD->getLocation(), 15182 diag::err_constexpr_var_requires_const_destruction) << VD; 15183 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 15184 Diag(Notes[I].first, Notes[I].second); 15185 } 15186 } 15187 15188 if (!VD->hasGlobalStorage()) return; 15189 15190 // Emit warning for non-trivial dtor in global scope (a real global, 15191 // class-static, function-static). 15192 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 15193 15194 // TODO: this should be re-enabled for static locals by !CXAAtExit 15195 if (!VD->isStaticLocal()) 15196 Diag(VD->getLocation(), diag::warn_global_destructor); 15197 } 15198 15199 /// Given a constructor and the set of arguments provided for the 15200 /// constructor, convert the arguments and add any required default arguments 15201 /// to form a proper call to this constructor. 15202 /// 15203 /// \returns true if an error occurred, false otherwise. 15204 bool 15205 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 15206 MultiExprArg ArgsPtr, 15207 SourceLocation Loc, 15208 SmallVectorImpl<Expr*> &ConvertedArgs, 15209 bool AllowExplicit, 15210 bool IsListInitialization) { 15211 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 15212 unsigned NumArgs = ArgsPtr.size(); 15213 Expr **Args = ArgsPtr.data(); 15214 15215 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>(); 15216 unsigned NumParams = Proto->getNumParams(); 15217 15218 // If too few arguments are available, we'll fill in the rest with defaults. 15219 if (NumArgs < NumParams) 15220 ConvertedArgs.reserve(NumParams); 15221 else 15222 ConvertedArgs.reserve(NumArgs); 15223 15224 VariadicCallType CallType = 15225 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 15226 SmallVector<Expr *, 8> AllArgs; 15227 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 15228 Proto, 0, 15229 llvm::makeArrayRef(Args, NumArgs), 15230 AllArgs, 15231 CallType, AllowExplicit, 15232 IsListInitialization); 15233 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 15234 15235 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 15236 15237 CheckConstructorCall(Constructor, 15238 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 15239 Proto, Loc); 15240 15241 return Invalid; 15242 } 15243 15244 static inline bool 15245 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 15246 const FunctionDecl *FnDecl) { 15247 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 15248 if (isa<NamespaceDecl>(DC)) { 15249 return SemaRef.Diag(FnDecl->getLocation(), 15250 diag::err_operator_new_delete_declared_in_namespace) 15251 << FnDecl->getDeclName(); 15252 } 15253 15254 if (isa<TranslationUnitDecl>(DC) && 15255 FnDecl->getStorageClass() == SC_Static) { 15256 return SemaRef.Diag(FnDecl->getLocation(), 15257 diag::err_operator_new_delete_declared_static) 15258 << FnDecl->getDeclName(); 15259 } 15260 15261 return false; 15262 } 15263 15264 static QualType 15265 RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) { 15266 QualType QTy = PtrTy->getPointeeType(); 15267 QTy = SemaRef.Context.removeAddrSpaceQualType(QTy); 15268 return SemaRef.Context.getPointerType(QTy); 15269 } 15270 15271 static inline bool 15272 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 15273 CanQualType ExpectedResultType, 15274 CanQualType ExpectedFirstParamType, 15275 unsigned DependentParamTypeDiag, 15276 unsigned InvalidParamTypeDiag) { 15277 QualType ResultType = 15278 FnDecl->getType()->castAs<FunctionType>()->getReturnType(); 15279 15280 // The operator is valid on any address space for OpenCL. 15281 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 15282 if (auto *PtrTy = ResultType->getAs<PointerType>()) { 15283 ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 15284 } 15285 } 15286 15287 // Check that the result type is what we expect. 15288 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) { 15289 // Reject even if the type is dependent; an operator delete function is 15290 // required to have a non-dependent result type. 15291 return SemaRef.Diag( 15292 FnDecl->getLocation(), 15293 ResultType->isDependentType() 15294 ? diag::err_operator_new_delete_dependent_result_type 15295 : diag::err_operator_new_delete_invalid_result_type) 15296 << FnDecl->getDeclName() << ExpectedResultType; 15297 } 15298 15299 // A function template must have at least 2 parameters. 15300 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 15301 return SemaRef.Diag(FnDecl->getLocation(), 15302 diag::err_operator_new_delete_template_too_few_parameters) 15303 << FnDecl->getDeclName(); 15304 15305 // The function decl must have at least 1 parameter. 15306 if (FnDecl->getNumParams() == 0) 15307 return SemaRef.Diag(FnDecl->getLocation(), 15308 diag::err_operator_new_delete_too_few_parameters) 15309 << FnDecl->getDeclName(); 15310 15311 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 15312 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 15313 // The operator is valid on any address space for OpenCL. 15314 if (auto *PtrTy = 15315 FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) { 15316 FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 15317 } 15318 } 15319 15320 // Check that the first parameter type is what we expect. 15321 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 15322 ExpectedFirstParamType) { 15323 // The first parameter type is not allowed to be dependent. As a tentative 15324 // DR resolution, we allow a dependent parameter type if it is the right 15325 // type anyway, to allow destroying operator delete in class templates. 15326 return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType() 15327 ? DependentParamTypeDiag 15328 : InvalidParamTypeDiag) 15329 << FnDecl->getDeclName() << ExpectedFirstParamType; 15330 } 15331 15332 return false; 15333 } 15334 15335 static bool 15336 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 15337 // C++ [basic.stc.dynamic.allocation]p1: 15338 // A program is ill-formed if an allocation function is declared in a 15339 // namespace scope other than global scope or declared static in global 15340 // scope. 15341 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 15342 return true; 15343 15344 CanQualType SizeTy = 15345 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 15346 15347 // C++ [basic.stc.dynamic.allocation]p1: 15348 // The return type shall be void*. The first parameter shall have type 15349 // std::size_t. 15350 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 15351 SizeTy, 15352 diag::err_operator_new_dependent_param_type, 15353 diag::err_operator_new_param_type)) 15354 return true; 15355 15356 // C++ [basic.stc.dynamic.allocation]p1: 15357 // The first parameter shall not have an associated default argument. 15358 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 15359 return SemaRef.Diag(FnDecl->getLocation(), 15360 diag::err_operator_new_default_arg) 15361 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 15362 15363 return false; 15364 } 15365 15366 static bool 15367 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 15368 // C++ [basic.stc.dynamic.deallocation]p1: 15369 // A program is ill-formed if deallocation functions are declared in a 15370 // namespace scope other than global scope or declared static in global 15371 // scope. 15372 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 15373 return true; 15374 15375 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl); 15376 15377 // C++ P0722: 15378 // Within a class C, the first parameter of a destroying operator delete 15379 // shall be of type C *. The first parameter of any other deallocation 15380 // function shall be of type void *. 15381 CanQualType ExpectedFirstParamType = 15382 MD && MD->isDestroyingOperatorDelete() 15383 ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType( 15384 SemaRef.Context.getRecordType(MD->getParent()))) 15385 : SemaRef.Context.VoidPtrTy; 15386 15387 // C++ [basic.stc.dynamic.deallocation]p2: 15388 // Each deallocation function shall return void 15389 if (CheckOperatorNewDeleteTypes( 15390 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType, 15391 diag::err_operator_delete_dependent_param_type, 15392 diag::err_operator_delete_param_type)) 15393 return true; 15394 15395 // C++ P0722: 15396 // A destroying operator delete shall be a usual deallocation function. 15397 if (MD && !MD->getParent()->isDependentContext() && 15398 MD->isDestroyingOperatorDelete() && 15399 !SemaRef.isUsualDeallocationFunction(MD)) { 15400 SemaRef.Diag(MD->getLocation(), 15401 diag::err_destroying_operator_delete_not_usual); 15402 return true; 15403 } 15404 15405 return false; 15406 } 15407 15408 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 15409 /// of this overloaded operator is well-formed. If so, returns false; 15410 /// otherwise, emits appropriate diagnostics and returns true. 15411 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 15412 assert(FnDecl && FnDecl->isOverloadedOperator() && 15413 "Expected an overloaded operator declaration"); 15414 15415 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 15416 15417 // C++ [over.oper]p5: 15418 // The allocation and deallocation functions, operator new, 15419 // operator new[], operator delete and operator delete[], are 15420 // described completely in 3.7.3. The attributes and restrictions 15421 // found in the rest of this subclause do not apply to them unless 15422 // explicitly stated in 3.7.3. 15423 if (Op == OO_Delete || Op == OO_Array_Delete) 15424 return CheckOperatorDeleteDeclaration(*this, FnDecl); 15425 15426 if (Op == OO_New || Op == OO_Array_New) 15427 return CheckOperatorNewDeclaration(*this, FnDecl); 15428 15429 // C++ [over.oper]p6: 15430 // An operator function shall either be a non-static member 15431 // function or be a non-member function and have at least one 15432 // parameter whose type is a class, a reference to a class, an 15433 // enumeration, or a reference to an enumeration. 15434 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 15435 if (MethodDecl->isStatic()) 15436 return Diag(FnDecl->getLocation(), 15437 diag::err_operator_overload_static) << FnDecl->getDeclName(); 15438 } else { 15439 bool ClassOrEnumParam = false; 15440 for (auto Param : FnDecl->parameters()) { 15441 QualType ParamType = Param->getType().getNonReferenceType(); 15442 if (ParamType->isDependentType() || ParamType->isRecordType() || 15443 ParamType->isEnumeralType()) { 15444 ClassOrEnumParam = true; 15445 break; 15446 } 15447 } 15448 15449 if (!ClassOrEnumParam) 15450 return Diag(FnDecl->getLocation(), 15451 diag::err_operator_overload_needs_class_or_enum) 15452 << FnDecl->getDeclName(); 15453 } 15454 15455 // C++ [over.oper]p8: 15456 // An operator function cannot have default arguments (8.3.6), 15457 // except where explicitly stated below. 15458 // 15459 // Only the function-call operator allows default arguments 15460 // (C++ [over.call]p1). 15461 if (Op != OO_Call) { 15462 for (auto Param : FnDecl->parameters()) { 15463 if (Param->hasDefaultArg()) 15464 return Diag(Param->getLocation(), 15465 diag::err_operator_overload_default_arg) 15466 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 15467 } 15468 } 15469 15470 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 15471 { false, false, false } 15472 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 15473 , { Unary, Binary, MemberOnly } 15474 #include "clang/Basic/OperatorKinds.def" 15475 }; 15476 15477 bool CanBeUnaryOperator = OperatorUses[Op][0]; 15478 bool CanBeBinaryOperator = OperatorUses[Op][1]; 15479 bool MustBeMemberOperator = OperatorUses[Op][2]; 15480 15481 // C++ [over.oper]p8: 15482 // [...] Operator functions cannot have more or fewer parameters 15483 // than the number required for the corresponding operator, as 15484 // described in the rest of this subclause. 15485 unsigned NumParams = FnDecl->getNumParams() 15486 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 15487 if (Op != OO_Call && 15488 ((NumParams == 1 && !CanBeUnaryOperator) || 15489 (NumParams == 2 && !CanBeBinaryOperator) || 15490 (NumParams < 1) || (NumParams > 2))) { 15491 // We have the wrong number of parameters. 15492 unsigned ErrorKind; 15493 if (CanBeUnaryOperator && CanBeBinaryOperator) { 15494 ErrorKind = 2; // 2 -> unary or binary. 15495 } else if (CanBeUnaryOperator) { 15496 ErrorKind = 0; // 0 -> unary 15497 } else { 15498 assert(CanBeBinaryOperator && 15499 "All non-call overloaded operators are unary or binary!"); 15500 ErrorKind = 1; // 1 -> binary 15501 } 15502 15503 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 15504 << FnDecl->getDeclName() << NumParams << ErrorKind; 15505 } 15506 15507 // Overloaded operators other than operator() cannot be variadic. 15508 if (Op != OO_Call && 15509 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) { 15510 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 15511 << FnDecl->getDeclName(); 15512 } 15513 15514 // Some operators must be non-static member functions. 15515 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 15516 return Diag(FnDecl->getLocation(), 15517 diag::err_operator_overload_must_be_member) 15518 << FnDecl->getDeclName(); 15519 } 15520 15521 // C++ [over.inc]p1: 15522 // The user-defined function called operator++ implements the 15523 // prefix and postfix ++ operator. If this function is a member 15524 // function with no parameters, or a non-member function with one 15525 // parameter of class or enumeration type, it defines the prefix 15526 // increment operator ++ for objects of that type. If the function 15527 // is a member function with one parameter (which shall be of type 15528 // int) or a non-member function with two parameters (the second 15529 // of which shall be of type int), it defines the postfix 15530 // increment operator ++ for objects of that type. 15531 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 15532 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 15533 QualType ParamType = LastParam->getType(); 15534 15535 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 15536 !ParamType->isDependentType()) 15537 return Diag(LastParam->getLocation(), 15538 diag::err_operator_overload_post_incdec_must_be_int) 15539 << LastParam->getType() << (Op == OO_MinusMinus); 15540 } 15541 15542 return false; 15543 } 15544 15545 static bool 15546 checkLiteralOperatorTemplateParameterList(Sema &SemaRef, 15547 FunctionTemplateDecl *TpDecl) { 15548 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters(); 15549 15550 // Must have one or two template parameters. 15551 if (TemplateParams->size() == 1) { 15552 NonTypeTemplateParmDecl *PmDecl = 15553 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0)); 15554 15555 // The template parameter must be a char parameter pack. 15556 if (PmDecl && PmDecl->isTemplateParameterPack() && 15557 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy)) 15558 return false; 15559 15560 // C++20 [over.literal]p5: 15561 // A string literal operator template is a literal operator template 15562 // whose template-parameter-list comprises a single non-type 15563 // template-parameter of class type. 15564 // 15565 // As a DR resolution, we also allow placeholders for deduced class 15566 // template specializations. 15567 if (SemaRef.getLangOpts().CPlusPlus20 && 15568 !PmDecl->isTemplateParameterPack() && 15569 (PmDecl->getType()->isRecordType() || 15570 PmDecl->getType()->getAs<DeducedTemplateSpecializationType>())) 15571 return false; 15572 } else if (TemplateParams->size() == 2) { 15573 TemplateTypeParmDecl *PmType = 15574 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0)); 15575 NonTypeTemplateParmDecl *PmArgs = 15576 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1)); 15577 15578 // The second template parameter must be a parameter pack with the 15579 // first template parameter as its type. 15580 if (PmType && PmArgs && !PmType->isTemplateParameterPack() && 15581 PmArgs->isTemplateParameterPack()) { 15582 const TemplateTypeParmType *TArgs = 15583 PmArgs->getType()->getAs<TemplateTypeParmType>(); 15584 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 15585 TArgs->getIndex() == PmType->getIndex()) { 15586 if (!SemaRef.inTemplateInstantiation()) 15587 SemaRef.Diag(TpDecl->getLocation(), 15588 diag::ext_string_literal_operator_template); 15589 return false; 15590 } 15591 } 15592 } 15593 15594 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(), 15595 diag::err_literal_operator_template) 15596 << TpDecl->getTemplateParameters()->getSourceRange(); 15597 return true; 15598 } 15599 15600 /// CheckLiteralOperatorDeclaration - Check whether the declaration 15601 /// of this literal operator function is well-formed. If so, returns 15602 /// false; otherwise, emits appropriate diagnostics and returns true. 15603 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 15604 if (isa<CXXMethodDecl>(FnDecl)) { 15605 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 15606 << FnDecl->getDeclName(); 15607 return true; 15608 } 15609 15610 if (FnDecl->isExternC()) { 15611 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 15612 if (const LinkageSpecDecl *LSD = 15613 FnDecl->getDeclContext()->getExternCContext()) 15614 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here); 15615 return true; 15616 } 15617 15618 // This might be the definition of a literal operator template. 15619 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 15620 15621 // This might be a specialization of a literal operator template. 15622 if (!TpDecl) 15623 TpDecl = FnDecl->getPrimaryTemplate(); 15624 15625 // template <char...> type operator "" name() and 15626 // template <class T, T...> type operator "" name() are the only valid 15627 // template signatures, and the only valid signatures with no parameters. 15628 // 15629 // C++20 also allows template <SomeClass T> type operator "" name(). 15630 if (TpDecl) { 15631 if (FnDecl->param_size() != 0) { 15632 Diag(FnDecl->getLocation(), 15633 diag::err_literal_operator_template_with_params); 15634 return true; 15635 } 15636 15637 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl)) 15638 return true; 15639 15640 } else if (FnDecl->param_size() == 1) { 15641 const ParmVarDecl *Param = FnDecl->getParamDecl(0); 15642 15643 QualType ParamType = Param->getType().getUnqualifiedType(); 15644 15645 // Only unsigned long long int, long double, any character type, and const 15646 // char * are allowed as the only parameters. 15647 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) || 15648 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) || 15649 Context.hasSameType(ParamType, Context.CharTy) || 15650 Context.hasSameType(ParamType, Context.WideCharTy) || 15651 Context.hasSameType(ParamType, Context.Char8Ty) || 15652 Context.hasSameType(ParamType, Context.Char16Ty) || 15653 Context.hasSameType(ParamType, Context.Char32Ty)) { 15654 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) { 15655 QualType InnerType = Ptr->getPointeeType(); 15656 15657 // Pointer parameter must be a const char *. 15658 if (!(Context.hasSameType(InnerType.getUnqualifiedType(), 15659 Context.CharTy) && 15660 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) { 15661 Diag(Param->getSourceRange().getBegin(), 15662 diag::err_literal_operator_param) 15663 << ParamType << "'const char *'" << Param->getSourceRange(); 15664 return true; 15665 } 15666 15667 } else if (ParamType->isRealFloatingType()) { 15668 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 15669 << ParamType << Context.LongDoubleTy << Param->getSourceRange(); 15670 return true; 15671 15672 } else if (ParamType->isIntegerType()) { 15673 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 15674 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange(); 15675 return true; 15676 15677 } else { 15678 Diag(Param->getSourceRange().getBegin(), 15679 diag::err_literal_operator_invalid_param) 15680 << ParamType << Param->getSourceRange(); 15681 return true; 15682 } 15683 15684 } else if (FnDecl->param_size() == 2) { 15685 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 15686 15687 // First, verify that the first parameter is correct. 15688 15689 QualType FirstParamType = (*Param)->getType().getUnqualifiedType(); 15690 15691 // Two parameter function must have a pointer to const as a 15692 // first parameter; let's strip those qualifiers. 15693 const PointerType *PT = FirstParamType->getAs<PointerType>(); 15694 15695 if (!PT) { 15696 Diag((*Param)->getSourceRange().getBegin(), 15697 diag::err_literal_operator_param) 15698 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 15699 return true; 15700 } 15701 15702 QualType PointeeType = PT->getPointeeType(); 15703 // First parameter must be const 15704 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) { 15705 Diag((*Param)->getSourceRange().getBegin(), 15706 diag::err_literal_operator_param) 15707 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 15708 return true; 15709 } 15710 15711 QualType InnerType = PointeeType.getUnqualifiedType(); 15712 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and 15713 // const char32_t* are allowed as the first parameter to a two-parameter 15714 // function 15715 if (!(Context.hasSameType(InnerType, Context.CharTy) || 15716 Context.hasSameType(InnerType, Context.WideCharTy) || 15717 Context.hasSameType(InnerType, Context.Char8Ty) || 15718 Context.hasSameType(InnerType, Context.Char16Ty) || 15719 Context.hasSameType(InnerType, Context.Char32Ty))) { 15720 Diag((*Param)->getSourceRange().getBegin(), 15721 diag::err_literal_operator_param) 15722 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 15723 return true; 15724 } 15725 15726 // Move on to the second and final parameter. 15727 ++Param; 15728 15729 // The second parameter must be a std::size_t. 15730 QualType SecondParamType = (*Param)->getType().getUnqualifiedType(); 15731 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) { 15732 Diag((*Param)->getSourceRange().getBegin(), 15733 diag::err_literal_operator_param) 15734 << SecondParamType << Context.getSizeType() 15735 << (*Param)->getSourceRange(); 15736 return true; 15737 } 15738 } else { 15739 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count); 15740 return true; 15741 } 15742 15743 // Parameters are good. 15744 15745 // A parameter-declaration-clause containing a default argument is not 15746 // equivalent to any of the permitted forms. 15747 for (auto Param : FnDecl->parameters()) { 15748 if (Param->hasDefaultArg()) { 15749 Diag(Param->getDefaultArgRange().getBegin(), 15750 diag::err_literal_operator_default_argument) 15751 << Param->getDefaultArgRange(); 15752 break; 15753 } 15754 } 15755 15756 StringRef LiteralName 15757 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 15758 if (LiteralName[0] != '_' && 15759 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) { 15760 // C++11 [usrlit.suffix]p1: 15761 // Literal suffix identifiers that do not start with an underscore 15762 // are reserved for future standardization. 15763 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 15764 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 15765 } 15766 15767 return false; 15768 } 15769 15770 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 15771 /// linkage specification, including the language and (if present) 15772 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 15773 /// language string literal. LBraceLoc, if valid, provides the location of 15774 /// the '{' brace. Otherwise, this linkage specification does not 15775 /// have any braces. 15776 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 15777 Expr *LangStr, 15778 SourceLocation LBraceLoc) { 15779 StringLiteral *Lit = cast<StringLiteral>(LangStr); 15780 if (!Lit->isAscii()) { 15781 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 15782 << LangStr->getSourceRange(); 15783 return nullptr; 15784 } 15785 15786 StringRef Lang = Lit->getString(); 15787 LinkageSpecDecl::LanguageIDs Language; 15788 if (Lang == "C") 15789 Language = LinkageSpecDecl::lang_c; 15790 else if (Lang == "C++") 15791 Language = LinkageSpecDecl::lang_cxx; 15792 else { 15793 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 15794 << LangStr->getSourceRange(); 15795 return nullptr; 15796 } 15797 15798 // FIXME: Add all the various semantics of linkage specifications 15799 15800 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 15801 LangStr->getExprLoc(), Language, 15802 LBraceLoc.isValid()); 15803 CurContext->addDecl(D); 15804 PushDeclContext(S, D); 15805 return D; 15806 } 15807 15808 /// ActOnFinishLinkageSpecification - Complete the definition of 15809 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 15810 /// valid, it's the position of the closing '}' brace in a linkage 15811 /// specification that uses braces. 15812 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 15813 Decl *LinkageSpec, 15814 SourceLocation RBraceLoc) { 15815 if (RBraceLoc.isValid()) { 15816 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 15817 LSDecl->setRBraceLoc(RBraceLoc); 15818 } 15819 PopDeclContext(); 15820 return LinkageSpec; 15821 } 15822 15823 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 15824 const ParsedAttributesView &AttrList, 15825 SourceLocation SemiLoc) { 15826 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 15827 // Attribute declarations appertain to empty declaration so we handle 15828 // them here. 15829 ProcessDeclAttributeList(S, ED, AttrList); 15830 15831 CurContext->addDecl(ED); 15832 return ED; 15833 } 15834 15835 /// Perform semantic analysis for the variable declaration that 15836 /// occurs within a C++ catch clause, returning the newly-created 15837 /// variable. 15838 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 15839 TypeSourceInfo *TInfo, 15840 SourceLocation StartLoc, 15841 SourceLocation Loc, 15842 IdentifierInfo *Name) { 15843 bool Invalid = false; 15844 QualType ExDeclType = TInfo->getType(); 15845 15846 // Arrays and functions decay. 15847 if (ExDeclType->isArrayType()) 15848 ExDeclType = Context.getArrayDecayedType(ExDeclType); 15849 else if (ExDeclType->isFunctionType()) 15850 ExDeclType = Context.getPointerType(ExDeclType); 15851 15852 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 15853 // The exception-declaration shall not denote a pointer or reference to an 15854 // incomplete type, other than [cv] void*. 15855 // N2844 forbids rvalue references. 15856 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 15857 Diag(Loc, diag::err_catch_rvalue_ref); 15858 Invalid = true; 15859 } 15860 15861 if (ExDeclType->isVariablyModifiedType()) { 15862 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType; 15863 Invalid = true; 15864 } 15865 15866 QualType BaseType = ExDeclType; 15867 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 15868 unsigned DK = diag::err_catch_incomplete; 15869 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 15870 BaseType = Ptr->getPointeeType(); 15871 Mode = 1; 15872 DK = diag::err_catch_incomplete_ptr; 15873 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 15874 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 15875 BaseType = Ref->getPointeeType(); 15876 Mode = 2; 15877 DK = diag::err_catch_incomplete_ref; 15878 } 15879 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 15880 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 15881 Invalid = true; 15882 15883 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) { 15884 Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType; 15885 Invalid = true; 15886 } 15887 15888 if (!Invalid && !ExDeclType->isDependentType() && 15889 RequireNonAbstractType(Loc, ExDeclType, 15890 diag::err_abstract_type_in_decl, 15891 AbstractVariableType)) 15892 Invalid = true; 15893 15894 // Only the non-fragile NeXT runtime currently supports C++ catches 15895 // of ObjC types, and no runtime supports catching ObjC types by value. 15896 if (!Invalid && getLangOpts().ObjC) { 15897 QualType T = ExDeclType; 15898 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 15899 T = RT->getPointeeType(); 15900 15901 if (T->isObjCObjectType()) { 15902 Diag(Loc, diag::err_objc_object_catch); 15903 Invalid = true; 15904 } else if (T->isObjCObjectPointerType()) { 15905 // FIXME: should this be a test for macosx-fragile specifically? 15906 if (getLangOpts().ObjCRuntime.isFragile()) 15907 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 15908 } 15909 } 15910 15911 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 15912 ExDeclType, TInfo, SC_None); 15913 ExDecl->setExceptionVariable(true); 15914 15915 // In ARC, infer 'retaining' for variables of retainable type. 15916 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 15917 Invalid = true; 15918 15919 if (!Invalid && !ExDeclType->isDependentType()) { 15920 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 15921 // Insulate this from anything else we might currently be parsing. 15922 EnterExpressionEvaluationContext scope( 15923 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 15924 15925 // C++ [except.handle]p16: 15926 // The object declared in an exception-declaration or, if the 15927 // exception-declaration does not specify a name, a temporary (12.2) is 15928 // copy-initialized (8.5) from the exception object. [...] 15929 // The object is destroyed when the handler exits, after the destruction 15930 // of any automatic objects initialized within the handler. 15931 // 15932 // We just pretend to initialize the object with itself, then make sure 15933 // it can be destroyed later. 15934 QualType initType = Context.getExceptionObjectType(ExDeclType); 15935 15936 InitializedEntity entity = 15937 InitializedEntity::InitializeVariable(ExDecl); 15938 InitializationKind initKind = 15939 InitializationKind::CreateCopy(Loc, SourceLocation()); 15940 15941 Expr *opaqueValue = 15942 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 15943 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 15944 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 15945 if (result.isInvalid()) 15946 Invalid = true; 15947 else { 15948 // If the constructor used was non-trivial, set this as the 15949 // "initializer". 15950 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 15951 if (!construct->getConstructor()->isTrivial()) { 15952 Expr *init = MaybeCreateExprWithCleanups(construct); 15953 ExDecl->setInit(init); 15954 } 15955 15956 // And make sure it's destructable. 15957 FinalizeVarWithDestructor(ExDecl, recordType); 15958 } 15959 } 15960 } 15961 15962 if (Invalid) 15963 ExDecl->setInvalidDecl(); 15964 15965 return ExDecl; 15966 } 15967 15968 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 15969 /// handler. 15970 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 15971 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 15972 bool Invalid = D.isInvalidType(); 15973 15974 // Check for unexpanded parameter packs. 15975 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 15976 UPPC_ExceptionType)) { 15977 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 15978 D.getIdentifierLoc()); 15979 Invalid = true; 15980 } 15981 15982 IdentifierInfo *II = D.getIdentifier(); 15983 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 15984 LookupOrdinaryName, 15985 ForVisibleRedeclaration)) { 15986 // The scope should be freshly made just for us. There is just no way 15987 // it contains any previous declaration, except for function parameters in 15988 // a function-try-block's catch statement. 15989 assert(!S->isDeclScope(PrevDecl)); 15990 if (isDeclInScope(PrevDecl, CurContext, S)) { 15991 Diag(D.getIdentifierLoc(), diag::err_redefinition) 15992 << D.getIdentifier(); 15993 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 15994 Invalid = true; 15995 } else if (PrevDecl->isTemplateParameter()) 15996 // Maybe we will complain about the shadowed template parameter. 15997 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 15998 } 15999 16000 if (D.getCXXScopeSpec().isSet() && !Invalid) { 16001 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 16002 << D.getCXXScopeSpec().getRange(); 16003 Invalid = true; 16004 } 16005 16006 VarDecl *ExDecl = BuildExceptionDeclaration( 16007 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier()); 16008 if (Invalid) 16009 ExDecl->setInvalidDecl(); 16010 16011 // Add the exception declaration into this scope. 16012 if (II) 16013 PushOnScopeChains(ExDecl, S); 16014 else 16015 CurContext->addDecl(ExDecl); 16016 16017 ProcessDeclAttributes(S, ExDecl, D); 16018 return ExDecl; 16019 } 16020 16021 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 16022 Expr *AssertExpr, 16023 Expr *AssertMessageExpr, 16024 SourceLocation RParenLoc) { 16025 StringLiteral *AssertMessage = 16026 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 16027 16028 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 16029 return nullptr; 16030 16031 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 16032 AssertMessage, RParenLoc, false); 16033 } 16034 16035 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 16036 Expr *AssertExpr, 16037 StringLiteral *AssertMessage, 16038 SourceLocation RParenLoc, 16039 bool Failed) { 16040 assert(AssertExpr != nullptr && "Expected non-null condition"); 16041 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 16042 !Failed) { 16043 // In a static_assert-declaration, the constant-expression shall be a 16044 // constant expression that can be contextually converted to bool. 16045 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 16046 if (Converted.isInvalid()) 16047 Failed = true; 16048 16049 ExprResult FullAssertExpr = 16050 ActOnFinishFullExpr(Converted.get(), StaticAssertLoc, 16051 /*DiscardedValue*/ false, 16052 /*IsConstexpr*/ true); 16053 if (FullAssertExpr.isInvalid()) 16054 Failed = true; 16055 else 16056 AssertExpr = FullAssertExpr.get(); 16057 16058 llvm::APSInt Cond; 16059 if (!Failed && VerifyIntegerConstantExpression( 16060 AssertExpr, &Cond, 16061 diag::err_static_assert_expression_is_not_constant) 16062 .isInvalid()) 16063 Failed = true; 16064 16065 if (!Failed && !Cond) { 16066 SmallString<256> MsgBuffer; 16067 llvm::raw_svector_ostream Msg(MsgBuffer); 16068 if (AssertMessage) 16069 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 16070 16071 Expr *InnerCond = nullptr; 16072 std::string InnerCondDescription; 16073 std::tie(InnerCond, InnerCondDescription) = 16074 findFailedBooleanCondition(Converted.get()); 16075 if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) { 16076 // Drill down into concept specialization expressions to see why they 16077 // weren't satisfied. 16078 Diag(StaticAssertLoc, diag::err_static_assert_failed) 16079 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 16080 ConstraintSatisfaction Satisfaction; 16081 if (!CheckConstraintSatisfaction(InnerCond, Satisfaction)) 16082 DiagnoseUnsatisfiedConstraint(Satisfaction); 16083 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond) 16084 && !isa<IntegerLiteral>(InnerCond)) { 16085 Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed) 16086 << InnerCondDescription << !AssertMessage 16087 << Msg.str() << InnerCond->getSourceRange(); 16088 } else { 16089 Diag(StaticAssertLoc, diag::err_static_assert_failed) 16090 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 16091 } 16092 Failed = true; 16093 } 16094 } else { 16095 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc, 16096 /*DiscardedValue*/false, 16097 /*IsConstexpr*/true); 16098 if (FullAssertExpr.isInvalid()) 16099 Failed = true; 16100 else 16101 AssertExpr = FullAssertExpr.get(); 16102 } 16103 16104 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 16105 AssertExpr, AssertMessage, RParenLoc, 16106 Failed); 16107 16108 CurContext->addDecl(Decl); 16109 return Decl; 16110 } 16111 16112 /// Perform semantic analysis of the given friend type declaration. 16113 /// 16114 /// \returns A friend declaration that. 16115 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 16116 SourceLocation FriendLoc, 16117 TypeSourceInfo *TSInfo) { 16118 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 16119 16120 QualType T = TSInfo->getType(); 16121 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 16122 16123 // C++03 [class.friend]p2: 16124 // An elaborated-type-specifier shall be used in a friend declaration 16125 // for a class.* 16126 // 16127 // * The class-key of the elaborated-type-specifier is required. 16128 if (!CodeSynthesisContexts.empty()) { 16129 // Do not complain about the form of friend template types during any kind 16130 // of code synthesis. For template instantiation, we will have complained 16131 // when the template was defined. 16132 } else { 16133 if (!T->isElaboratedTypeSpecifier()) { 16134 // If we evaluated the type to a record type, suggest putting 16135 // a tag in front. 16136 if (const RecordType *RT = T->getAs<RecordType>()) { 16137 RecordDecl *RD = RT->getDecl(); 16138 16139 SmallString<16> InsertionText(" "); 16140 InsertionText += RD->getKindName(); 16141 16142 Diag(TypeRange.getBegin(), 16143 getLangOpts().CPlusPlus11 ? 16144 diag::warn_cxx98_compat_unelaborated_friend_type : 16145 diag::ext_unelaborated_friend_type) 16146 << (unsigned) RD->getTagKind() 16147 << T 16148 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc), 16149 InsertionText); 16150 } else { 16151 Diag(FriendLoc, 16152 getLangOpts().CPlusPlus11 ? 16153 diag::warn_cxx98_compat_nonclass_type_friend : 16154 diag::ext_nonclass_type_friend) 16155 << T 16156 << TypeRange; 16157 } 16158 } else if (T->getAs<EnumType>()) { 16159 Diag(FriendLoc, 16160 getLangOpts().CPlusPlus11 ? 16161 diag::warn_cxx98_compat_enum_friend : 16162 diag::ext_enum_friend) 16163 << T 16164 << TypeRange; 16165 } 16166 16167 // C++11 [class.friend]p3: 16168 // A friend declaration that does not declare a function shall have one 16169 // of the following forms: 16170 // friend elaborated-type-specifier ; 16171 // friend simple-type-specifier ; 16172 // friend typename-specifier ; 16173 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 16174 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 16175 } 16176 16177 // If the type specifier in a friend declaration designates a (possibly 16178 // cv-qualified) class type, that class is declared as a friend; otherwise, 16179 // the friend declaration is ignored. 16180 return FriendDecl::Create(Context, CurContext, 16181 TSInfo->getTypeLoc().getBeginLoc(), TSInfo, 16182 FriendLoc); 16183 } 16184 16185 /// Handle a friend tag declaration where the scope specifier was 16186 /// templated. 16187 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 16188 unsigned TagSpec, SourceLocation TagLoc, 16189 CXXScopeSpec &SS, IdentifierInfo *Name, 16190 SourceLocation NameLoc, 16191 const ParsedAttributesView &Attr, 16192 MultiTemplateParamsArg TempParamLists) { 16193 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 16194 16195 bool IsMemberSpecialization = false; 16196 bool Invalid = false; 16197 16198 if (TemplateParameterList *TemplateParams = 16199 MatchTemplateParametersToScopeSpecifier( 16200 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 16201 IsMemberSpecialization, Invalid)) { 16202 if (TemplateParams->size() > 0) { 16203 // This is a declaration of a class template. 16204 if (Invalid) 16205 return nullptr; 16206 16207 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 16208 NameLoc, Attr, TemplateParams, AS_public, 16209 /*ModulePrivateLoc=*/SourceLocation(), 16210 FriendLoc, TempParamLists.size() - 1, 16211 TempParamLists.data()).get(); 16212 } else { 16213 // The "template<>" header is extraneous. 16214 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 16215 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 16216 IsMemberSpecialization = true; 16217 } 16218 } 16219 16220 if (Invalid) return nullptr; 16221 16222 bool isAllExplicitSpecializations = true; 16223 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 16224 if (TempParamLists[I]->size()) { 16225 isAllExplicitSpecializations = false; 16226 break; 16227 } 16228 } 16229 16230 // FIXME: don't ignore attributes. 16231 16232 // If it's explicit specializations all the way down, just forget 16233 // about the template header and build an appropriate non-templated 16234 // friend. TODO: for source fidelity, remember the headers. 16235 if (isAllExplicitSpecializations) { 16236 if (SS.isEmpty()) { 16237 bool Owned = false; 16238 bool IsDependent = false; 16239 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 16240 Attr, AS_public, 16241 /*ModulePrivateLoc=*/SourceLocation(), 16242 MultiTemplateParamsArg(), Owned, IsDependent, 16243 /*ScopedEnumKWLoc=*/SourceLocation(), 16244 /*ScopedEnumUsesClassTag=*/false, 16245 /*UnderlyingType=*/TypeResult(), 16246 /*IsTypeSpecifier=*/false, 16247 /*IsTemplateParamOrArg=*/false); 16248 } 16249 16250 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 16251 ElaboratedTypeKeyword Keyword 16252 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 16253 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 16254 *Name, NameLoc); 16255 if (T.isNull()) 16256 return nullptr; 16257 16258 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 16259 if (isa<DependentNameType>(T)) { 16260 DependentNameTypeLoc TL = 16261 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 16262 TL.setElaboratedKeywordLoc(TagLoc); 16263 TL.setQualifierLoc(QualifierLoc); 16264 TL.setNameLoc(NameLoc); 16265 } else { 16266 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 16267 TL.setElaboratedKeywordLoc(TagLoc); 16268 TL.setQualifierLoc(QualifierLoc); 16269 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 16270 } 16271 16272 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 16273 TSI, FriendLoc, TempParamLists); 16274 Friend->setAccess(AS_public); 16275 CurContext->addDecl(Friend); 16276 return Friend; 16277 } 16278 16279 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 16280 16281 16282 16283 // Handle the case of a templated-scope friend class. e.g. 16284 // template <class T> class A<T>::B; 16285 // FIXME: we don't support these right now. 16286 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 16287 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 16288 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 16289 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 16290 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 16291 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 16292 TL.setElaboratedKeywordLoc(TagLoc); 16293 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 16294 TL.setNameLoc(NameLoc); 16295 16296 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 16297 TSI, FriendLoc, TempParamLists); 16298 Friend->setAccess(AS_public); 16299 Friend->setUnsupportedFriend(true); 16300 CurContext->addDecl(Friend); 16301 return Friend; 16302 } 16303 16304 /// Handle a friend type declaration. This works in tandem with 16305 /// ActOnTag. 16306 /// 16307 /// Notes on friend class templates: 16308 /// 16309 /// We generally treat friend class declarations as if they were 16310 /// declaring a class. So, for example, the elaborated type specifier 16311 /// in a friend declaration is required to obey the restrictions of a 16312 /// class-head (i.e. no typedefs in the scope chain), template 16313 /// parameters are required to match up with simple template-ids, &c. 16314 /// However, unlike when declaring a template specialization, it's 16315 /// okay to refer to a template specialization without an empty 16316 /// template parameter declaration, e.g. 16317 /// friend class A<T>::B<unsigned>; 16318 /// We permit this as a special case; if there are any template 16319 /// parameters present at all, require proper matching, i.e. 16320 /// template <> template \<class T> friend class A<int>::B; 16321 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 16322 MultiTemplateParamsArg TempParams) { 16323 SourceLocation Loc = DS.getBeginLoc(); 16324 16325 assert(DS.isFriendSpecified()); 16326 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 16327 16328 // C++ [class.friend]p3: 16329 // A friend declaration that does not declare a function shall have one of 16330 // the following forms: 16331 // friend elaborated-type-specifier ; 16332 // friend simple-type-specifier ; 16333 // friend typename-specifier ; 16334 // 16335 // Any declaration with a type qualifier does not have that form. (It's 16336 // legal to specify a qualified type as a friend, you just can't write the 16337 // keywords.) 16338 if (DS.getTypeQualifiers()) { 16339 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 16340 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const"; 16341 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 16342 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile"; 16343 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 16344 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict"; 16345 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 16346 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic"; 16347 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 16348 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned"; 16349 } 16350 16351 // Try to convert the decl specifier to a type. This works for 16352 // friend templates because ActOnTag never produces a ClassTemplateDecl 16353 // for a TUK_Friend. 16354 Declarator TheDeclarator(DS, DeclaratorContext::Member); 16355 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 16356 QualType T = TSI->getType(); 16357 if (TheDeclarator.isInvalidType()) 16358 return nullptr; 16359 16360 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 16361 return nullptr; 16362 16363 // This is definitely an error in C++98. It's probably meant to 16364 // be forbidden in C++0x, too, but the specification is just 16365 // poorly written. 16366 // 16367 // The problem is with declarations like the following: 16368 // template <T> friend A<T>::foo; 16369 // where deciding whether a class C is a friend or not now hinges 16370 // on whether there exists an instantiation of A that causes 16371 // 'foo' to equal C. There are restrictions on class-heads 16372 // (which we declare (by fiat) elaborated friend declarations to 16373 // be) that makes this tractable. 16374 // 16375 // FIXME: handle "template <> friend class A<T>;", which 16376 // is possibly well-formed? Who even knows? 16377 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 16378 Diag(Loc, diag::err_tagless_friend_type_template) 16379 << DS.getSourceRange(); 16380 return nullptr; 16381 } 16382 16383 // C++98 [class.friend]p1: A friend of a class is a function 16384 // or class that is not a member of the class . . . 16385 // This is fixed in DR77, which just barely didn't make the C++03 16386 // deadline. It's also a very silly restriction that seriously 16387 // affects inner classes and which nobody else seems to implement; 16388 // thus we never diagnose it, not even in -pedantic. 16389 // 16390 // But note that we could warn about it: it's always useless to 16391 // friend one of your own members (it's not, however, worthless to 16392 // friend a member of an arbitrary specialization of your template). 16393 16394 Decl *D; 16395 if (!TempParams.empty()) 16396 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 16397 TempParams, 16398 TSI, 16399 DS.getFriendSpecLoc()); 16400 else 16401 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 16402 16403 if (!D) 16404 return nullptr; 16405 16406 D->setAccess(AS_public); 16407 CurContext->addDecl(D); 16408 16409 return D; 16410 } 16411 16412 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 16413 MultiTemplateParamsArg TemplateParams) { 16414 const DeclSpec &DS = D.getDeclSpec(); 16415 16416 assert(DS.isFriendSpecified()); 16417 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 16418 16419 SourceLocation Loc = D.getIdentifierLoc(); 16420 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16421 16422 // C++ [class.friend]p1 16423 // A friend of a class is a function or class.... 16424 // Note that this sees through typedefs, which is intended. 16425 // It *doesn't* see through dependent types, which is correct 16426 // according to [temp.arg.type]p3: 16427 // If a declaration acquires a function type through a 16428 // type dependent on a template-parameter and this causes 16429 // a declaration that does not use the syntactic form of a 16430 // function declarator to have a function type, the program 16431 // is ill-formed. 16432 if (!TInfo->getType()->isFunctionType()) { 16433 Diag(Loc, diag::err_unexpected_friend); 16434 16435 // It might be worthwhile to try to recover by creating an 16436 // appropriate declaration. 16437 return nullptr; 16438 } 16439 16440 // C++ [namespace.memdef]p3 16441 // - If a friend declaration in a non-local class first declares a 16442 // class or function, the friend class or function is a member 16443 // of the innermost enclosing namespace. 16444 // - The name of the friend is not found by simple name lookup 16445 // until a matching declaration is provided in that namespace 16446 // scope (either before or after the class declaration granting 16447 // friendship). 16448 // - If a friend function is called, its name may be found by the 16449 // name lookup that considers functions from namespaces and 16450 // classes associated with the types of the function arguments. 16451 // - When looking for a prior declaration of a class or a function 16452 // declared as a friend, scopes outside the innermost enclosing 16453 // namespace scope are not considered. 16454 16455 CXXScopeSpec &SS = D.getCXXScopeSpec(); 16456 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 16457 assert(NameInfo.getName()); 16458 16459 // Check for unexpanded parameter packs. 16460 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 16461 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 16462 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 16463 return nullptr; 16464 16465 // The context we found the declaration in, or in which we should 16466 // create the declaration. 16467 DeclContext *DC; 16468 Scope *DCScope = S; 16469 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 16470 ForExternalRedeclaration); 16471 16472 // There are five cases here. 16473 // - There's no scope specifier and we're in a local class. Only look 16474 // for functions declared in the immediately-enclosing block scope. 16475 // We recover from invalid scope qualifiers as if they just weren't there. 16476 FunctionDecl *FunctionContainingLocalClass = nullptr; 16477 if ((SS.isInvalid() || !SS.isSet()) && 16478 (FunctionContainingLocalClass = 16479 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 16480 // C++11 [class.friend]p11: 16481 // If a friend declaration appears in a local class and the name 16482 // specified is an unqualified name, a prior declaration is 16483 // looked up without considering scopes that are outside the 16484 // innermost enclosing non-class scope. For a friend function 16485 // declaration, if there is no prior declaration, the program is 16486 // ill-formed. 16487 16488 // Find the innermost enclosing non-class scope. This is the block 16489 // scope containing the local class definition (or for a nested class, 16490 // the outer local class). 16491 DCScope = S->getFnParent(); 16492 16493 // Look up the function name in the scope. 16494 Previous.clear(LookupLocalFriendName); 16495 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 16496 16497 if (!Previous.empty()) { 16498 // All possible previous declarations must have the same context: 16499 // either they were declared at block scope or they are members of 16500 // one of the enclosing local classes. 16501 DC = Previous.getRepresentativeDecl()->getDeclContext(); 16502 } else { 16503 // This is ill-formed, but provide the context that we would have 16504 // declared the function in, if we were permitted to, for error recovery. 16505 DC = FunctionContainingLocalClass; 16506 } 16507 adjustContextForLocalExternDecl(DC); 16508 16509 // C++ [class.friend]p6: 16510 // A function can be defined in a friend declaration of a class if and 16511 // only if the class is a non-local class (9.8), the function name is 16512 // unqualified, and the function has namespace scope. 16513 if (D.isFunctionDefinition()) { 16514 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 16515 } 16516 16517 // - There's no scope specifier, in which case we just go to the 16518 // appropriate scope and look for a function or function template 16519 // there as appropriate. 16520 } else if (SS.isInvalid() || !SS.isSet()) { 16521 // C++11 [namespace.memdef]p3: 16522 // If the name in a friend declaration is neither qualified nor 16523 // a template-id and the declaration is a function or an 16524 // elaborated-type-specifier, the lookup to determine whether 16525 // the entity has been previously declared shall not consider 16526 // any scopes outside the innermost enclosing namespace. 16527 bool isTemplateId = 16528 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId; 16529 16530 // Find the appropriate context according to the above. 16531 DC = CurContext; 16532 16533 // Skip class contexts. If someone can cite chapter and verse 16534 // for this behavior, that would be nice --- it's what GCC and 16535 // EDG do, and it seems like a reasonable intent, but the spec 16536 // really only says that checks for unqualified existing 16537 // declarations should stop at the nearest enclosing namespace, 16538 // not that they should only consider the nearest enclosing 16539 // namespace. 16540 while (DC->isRecord()) 16541 DC = DC->getParent(); 16542 16543 DeclContext *LookupDC = DC; 16544 while (LookupDC->isTransparentContext()) 16545 LookupDC = LookupDC->getParent(); 16546 16547 while (true) { 16548 LookupQualifiedName(Previous, LookupDC); 16549 16550 if (!Previous.empty()) { 16551 DC = LookupDC; 16552 break; 16553 } 16554 16555 if (isTemplateId) { 16556 if (isa<TranslationUnitDecl>(LookupDC)) break; 16557 } else { 16558 if (LookupDC->isFileContext()) break; 16559 } 16560 LookupDC = LookupDC->getParent(); 16561 } 16562 16563 DCScope = getScopeForDeclContext(S, DC); 16564 16565 // - There's a non-dependent scope specifier, in which case we 16566 // compute it and do a previous lookup there for a function 16567 // or function template. 16568 } else if (!SS.getScopeRep()->isDependent()) { 16569 DC = computeDeclContext(SS); 16570 if (!DC) return nullptr; 16571 16572 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 16573 16574 LookupQualifiedName(Previous, DC); 16575 16576 // C++ [class.friend]p1: A friend of a class is a function or 16577 // class that is not a member of the class . . . 16578 if (DC->Equals(CurContext)) 16579 Diag(DS.getFriendSpecLoc(), 16580 getLangOpts().CPlusPlus11 ? 16581 diag::warn_cxx98_compat_friend_is_member : 16582 diag::err_friend_is_member); 16583 16584 if (D.isFunctionDefinition()) { 16585 // C++ [class.friend]p6: 16586 // A function can be defined in a friend declaration of a class if and 16587 // only if the class is a non-local class (9.8), the function name is 16588 // unqualified, and the function has namespace scope. 16589 // 16590 // FIXME: We should only do this if the scope specifier names the 16591 // innermost enclosing namespace; otherwise the fixit changes the 16592 // meaning of the code. 16593 SemaDiagnosticBuilder DB 16594 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 16595 16596 DB << SS.getScopeRep(); 16597 if (DC->isFileContext()) 16598 DB << FixItHint::CreateRemoval(SS.getRange()); 16599 SS.clear(); 16600 } 16601 16602 // - There's a scope specifier that does not match any template 16603 // parameter lists, in which case we use some arbitrary context, 16604 // create a method or method template, and wait for instantiation. 16605 // - There's a scope specifier that does match some template 16606 // parameter lists, which we don't handle right now. 16607 } else { 16608 if (D.isFunctionDefinition()) { 16609 // C++ [class.friend]p6: 16610 // A function can be defined in a friend declaration of a class if and 16611 // only if the class is a non-local class (9.8), the function name is 16612 // unqualified, and the function has namespace scope. 16613 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 16614 << SS.getScopeRep(); 16615 } 16616 16617 DC = CurContext; 16618 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 16619 } 16620 16621 if (!DC->isRecord()) { 16622 int DiagArg = -1; 16623 switch (D.getName().getKind()) { 16624 case UnqualifiedIdKind::IK_ConstructorTemplateId: 16625 case UnqualifiedIdKind::IK_ConstructorName: 16626 DiagArg = 0; 16627 break; 16628 case UnqualifiedIdKind::IK_DestructorName: 16629 DiagArg = 1; 16630 break; 16631 case UnqualifiedIdKind::IK_ConversionFunctionId: 16632 DiagArg = 2; 16633 break; 16634 case UnqualifiedIdKind::IK_DeductionGuideName: 16635 DiagArg = 3; 16636 break; 16637 case UnqualifiedIdKind::IK_Identifier: 16638 case UnqualifiedIdKind::IK_ImplicitSelfParam: 16639 case UnqualifiedIdKind::IK_LiteralOperatorId: 16640 case UnqualifiedIdKind::IK_OperatorFunctionId: 16641 case UnqualifiedIdKind::IK_TemplateId: 16642 break; 16643 } 16644 // This implies that it has to be an operator or function. 16645 if (DiagArg >= 0) { 16646 Diag(Loc, diag::err_introducing_special_friend) << DiagArg; 16647 return nullptr; 16648 } 16649 } 16650 16651 // FIXME: This is an egregious hack to cope with cases where the scope stack 16652 // does not contain the declaration context, i.e., in an out-of-line 16653 // definition of a class. 16654 Scope FakeDCScope(S, Scope::DeclScope, Diags); 16655 if (!DCScope) { 16656 FakeDCScope.setEntity(DC); 16657 DCScope = &FakeDCScope; 16658 } 16659 16660 bool AddToScope = true; 16661 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 16662 TemplateParams, AddToScope); 16663 if (!ND) return nullptr; 16664 16665 assert(ND->getLexicalDeclContext() == CurContext); 16666 16667 // If we performed typo correction, we might have added a scope specifier 16668 // and changed the decl context. 16669 DC = ND->getDeclContext(); 16670 16671 // Add the function declaration to the appropriate lookup tables, 16672 // adjusting the redeclarations list as necessary. We don't 16673 // want to do this yet if the friending class is dependent. 16674 // 16675 // Also update the scope-based lookup if the target context's 16676 // lookup context is in lexical scope. 16677 if (!CurContext->isDependentContext()) { 16678 DC = DC->getRedeclContext(); 16679 DC->makeDeclVisibleInContext(ND); 16680 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 16681 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 16682 } 16683 16684 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 16685 D.getIdentifierLoc(), ND, 16686 DS.getFriendSpecLoc()); 16687 FrD->setAccess(AS_public); 16688 CurContext->addDecl(FrD); 16689 16690 if (ND->isInvalidDecl()) { 16691 FrD->setInvalidDecl(); 16692 } else { 16693 if (DC->isRecord()) CheckFriendAccess(ND); 16694 16695 FunctionDecl *FD; 16696 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 16697 FD = FTD->getTemplatedDecl(); 16698 else 16699 FD = cast<FunctionDecl>(ND); 16700 16701 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 16702 // default argument expression, that declaration shall be a definition 16703 // and shall be the only declaration of the function or function 16704 // template in the translation unit. 16705 if (functionDeclHasDefaultArgument(FD)) { 16706 // We can't look at FD->getPreviousDecl() because it may not have been set 16707 // if we're in a dependent context. If the function is known to be a 16708 // redeclaration, we will have narrowed Previous down to the right decl. 16709 if (D.isRedeclaration()) { 16710 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 16711 Diag(Previous.getRepresentativeDecl()->getLocation(), 16712 diag::note_previous_declaration); 16713 } else if (!D.isFunctionDefinition()) 16714 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 16715 } 16716 16717 // Mark templated-scope function declarations as unsupported. 16718 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 16719 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 16720 << SS.getScopeRep() << SS.getRange() 16721 << cast<CXXRecordDecl>(CurContext); 16722 FrD->setUnsupportedFriend(true); 16723 } 16724 } 16725 16726 return ND; 16727 } 16728 16729 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 16730 AdjustDeclIfTemplate(Dcl); 16731 16732 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 16733 if (!Fn) { 16734 Diag(DelLoc, diag::err_deleted_non_function); 16735 return; 16736 } 16737 16738 // Deleted function does not have a body. 16739 Fn->setWillHaveBody(false); 16740 16741 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 16742 // Don't consider the implicit declaration we generate for explicit 16743 // specializations. FIXME: Do not generate these implicit declarations. 16744 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 16745 Prev->getPreviousDecl()) && 16746 !Prev->isDefined()) { 16747 Diag(DelLoc, diag::err_deleted_decl_not_first); 16748 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 16749 Prev->isImplicit() ? diag::note_previous_implicit_declaration 16750 : diag::note_previous_declaration); 16751 // We can't recover from this; the declaration might have already 16752 // been used. 16753 Fn->setInvalidDecl(); 16754 return; 16755 } 16756 16757 // To maintain the invariant that functions are only deleted on their first 16758 // declaration, mark the implicitly-instantiated declaration of the 16759 // explicitly-specialized function as deleted instead of marking the 16760 // instantiated redeclaration. 16761 Fn = Fn->getCanonicalDecl(); 16762 } 16763 16764 // dllimport/dllexport cannot be deleted. 16765 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 16766 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 16767 Fn->setInvalidDecl(); 16768 } 16769 16770 // C++11 [basic.start.main]p3: 16771 // A program that defines main as deleted [...] is ill-formed. 16772 if (Fn->isMain()) 16773 Diag(DelLoc, diag::err_deleted_main); 16774 16775 // C++11 [dcl.fct.def.delete]p4: 16776 // A deleted function is implicitly inline. 16777 Fn->setImplicitlyInline(); 16778 Fn->setDeletedAsWritten(); 16779 } 16780 16781 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 16782 if (!Dcl || Dcl->isInvalidDecl()) 16783 return; 16784 16785 auto *FD = dyn_cast<FunctionDecl>(Dcl); 16786 if (!FD) { 16787 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) { 16788 if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) { 16789 Diag(DefaultLoc, diag::err_defaulted_comparison_template); 16790 return; 16791 } 16792 } 16793 16794 Diag(DefaultLoc, diag::err_default_special_members) 16795 << getLangOpts().CPlusPlus20; 16796 return; 16797 } 16798 16799 // Reject if this can't possibly be a defaultable function. 16800 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD); 16801 if (!DefKind && 16802 // A dependent function that doesn't locally look defaultable can 16803 // still instantiate to a defaultable function if it's a constructor 16804 // or assignment operator. 16805 (!FD->isDependentContext() || 16806 (!isa<CXXConstructorDecl>(FD) && 16807 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) { 16808 Diag(DefaultLoc, diag::err_default_special_members) 16809 << getLangOpts().CPlusPlus20; 16810 return; 16811 } 16812 16813 if (DefKind.isComparison() && 16814 !isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 16815 Diag(FD->getLocation(), diag::err_defaulted_comparison_out_of_class) 16816 << (int)DefKind.asComparison(); 16817 return; 16818 } 16819 16820 // Issue compatibility warning. We already warned if the operator is 16821 // 'operator<=>' when parsing the '<=>' token. 16822 if (DefKind.isComparison() && 16823 DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) { 16824 Diag(DefaultLoc, getLangOpts().CPlusPlus20 16825 ? diag::warn_cxx17_compat_defaulted_comparison 16826 : diag::ext_defaulted_comparison); 16827 } 16828 16829 FD->setDefaulted(); 16830 FD->setExplicitlyDefaulted(); 16831 16832 // Defer checking functions that are defaulted in a dependent context. 16833 if (FD->isDependentContext()) 16834 return; 16835 16836 // Unset that we will have a body for this function. We might not, 16837 // if it turns out to be trivial, and we don't need this marking now 16838 // that we've marked it as defaulted. 16839 FD->setWillHaveBody(false); 16840 16841 // If this definition appears within the record, do the checking when 16842 // the record is complete. This is always the case for a defaulted 16843 // comparison. 16844 if (DefKind.isComparison()) 16845 return; 16846 auto *MD = cast<CXXMethodDecl>(FD); 16847 16848 const FunctionDecl *Primary = FD; 16849 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern()) 16850 // Ask the template instantiation pattern that actually had the 16851 // '= default' on it. 16852 Primary = Pattern; 16853 16854 // If the method was defaulted on its first declaration, we will have 16855 // already performed the checking in CheckCompletedCXXClass. Such a 16856 // declaration doesn't trigger an implicit definition. 16857 if (Primary->getCanonicalDecl()->isDefaulted()) 16858 return; 16859 16860 // FIXME: Once we support defining comparisons out of class, check for a 16861 // defaulted comparison here. 16862 if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember())) 16863 MD->setInvalidDecl(); 16864 else 16865 DefineDefaultedFunction(*this, MD, DefaultLoc); 16866 } 16867 16868 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 16869 for (Stmt *SubStmt : S->children()) { 16870 if (!SubStmt) 16871 continue; 16872 if (isa<ReturnStmt>(SubStmt)) 16873 Self.Diag(SubStmt->getBeginLoc(), 16874 diag::err_return_in_constructor_handler); 16875 if (!isa<Expr>(SubStmt)) 16876 SearchForReturnInStmt(Self, SubStmt); 16877 } 16878 } 16879 16880 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 16881 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 16882 CXXCatchStmt *Handler = TryBlock->getHandler(I); 16883 SearchForReturnInStmt(*this, Handler); 16884 } 16885 } 16886 16887 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 16888 const CXXMethodDecl *Old) { 16889 const auto *NewFT = New->getType()->castAs<FunctionProtoType>(); 16890 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>(); 16891 16892 if (OldFT->hasExtParameterInfos()) { 16893 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I) 16894 // A parameter of the overriding method should be annotated with noescape 16895 // if the corresponding parameter of the overridden method is annotated. 16896 if (OldFT->getExtParameterInfo(I).isNoEscape() && 16897 !NewFT->getExtParameterInfo(I).isNoEscape()) { 16898 Diag(New->getParamDecl(I)->getLocation(), 16899 diag::warn_overriding_method_missing_noescape); 16900 Diag(Old->getParamDecl(I)->getLocation(), 16901 diag::note_overridden_marked_noescape); 16902 } 16903 } 16904 16905 // Virtual overrides must have the same code_seg. 16906 const auto *OldCSA = Old->getAttr<CodeSegAttr>(); 16907 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 16908 if ((NewCSA || OldCSA) && 16909 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) { 16910 Diag(New->getLocation(), diag::err_mismatched_code_seg_override); 16911 Diag(Old->getLocation(), diag::note_previous_declaration); 16912 return true; 16913 } 16914 16915 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 16916 16917 // If the calling conventions match, everything is fine 16918 if (NewCC == OldCC) 16919 return false; 16920 16921 // If the calling conventions mismatch because the new function is static, 16922 // suppress the calling convention mismatch error; the error about static 16923 // function override (err_static_overrides_virtual from 16924 // Sema::CheckFunctionDeclaration) is more clear. 16925 if (New->getStorageClass() == SC_Static) 16926 return false; 16927 16928 Diag(New->getLocation(), 16929 diag::err_conflicting_overriding_cc_attributes) 16930 << New->getDeclName() << New->getType() << Old->getType(); 16931 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 16932 return true; 16933 } 16934 16935 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 16936 const CXXMethodDecl *Old) { 16937 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType(); 16938 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType(); 16939 16940 if (Context.hasSameType(NewTy, OldTy) || 16941 NewTy->isDependentType() || OldTy->isDependentType()) 16942 return false; 16943 16944 // Check if the return types are covariant 16945 QualType NewClassTy, OldClassTy; 16946 16947 /// Both types must be pointers or references to classes. 16948 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 16949 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 16950 NewClassTy = NewPT->getPointeeType(); 16951 OldClassTy = OldPT->getPointeeType(); 16952 } 16953 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 16954 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 16955 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 16956 NewClassTy = NewRT->getPointeeType(); 16957 OldClassTy = OldRT->getPointeeType(); 16958 } 16959 } 16960 } 16961 16962 // The return types aren't either both pointers or references to a class type. 16963 if (NewClassTy.isNull()) { 16964 Diag(New->getLocation(), 16965 diag::err_different_return_type_for_overriding_virtual_function) 16966 << New->getDeclName() << NewTy << OldTy 16967 << New->getReturnTypeSourceRange(); 16968 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 16969 << Old->getReturnTypeSourceRange(); 16970 16971 return true; 16972 } 16973 16974 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 16975 // C++14 [class.virtual]p8: 16976 // If the class type in the covariant return type of D::f differs from 16977 // that of B::f, the class type in the return type of D::f shall be 16978 // complete at the point of declaration of D::f or shall be the class 16979 // type D. 16980 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 16981 if (!RT->isBeingDefined() && 16982 RequireCompleteType(New->getLocation(), NewClassTy, 16983 diag::err_covariant_return_incomplete, 16984 New->getDeclName())) 16985 return true; 16986 } 16987 16988 // Check if the new class derives from the old class. 16989 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) { 16990 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 16991 << New->getDeclName() << NewTy << OldTy 16992 << New->getReturnTypeSourceRange(); 16993 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 16994 << Old->getReturnTypeSourceRange(); 16995 return true; 16996 } 16997 16998 // Check if we the conversion from derived to base is valid. 16999 if (CheckDerivedToBaseConversion( 17000 NewClassTy, OldClassTy, 17001 diag::err_covariant_return_inaccessible_base, 17002 diag::err_covariant_return_ambiguous_derived_to_base_conv, 17003 New->getLocation(), New->getReturnTypeSourceRange(), 17004 New->getDeclName(), nullptr)) { 17005 // FIXME: this note won't trigger for delayed access control 17006 // diagnostics, and it's impossible to get an undelayed error 17007 // here from access control during the original parse because 17008 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 17009 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17010 << Old->getReturnTypeSourceRange(); 17011 return true; 17012 } 17013 } 17014 17015 // The qualifiers of the return types must be the same. 17016 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 17017 Diag(New->getLocation(), 17018 diag::err_covariant_return_type_different_qualifications) 17019 << New->getDeclName() << NewTy << OldTy 17020 << New->getReturnTypeSourceRange(); 17021 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17022 << Old->getReturnTypeSourceRange(); 17023 return true; 17024 } 17025 17026 17027 // The new class type must have the same or less qualifiers as the old type. 17028 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 17029 Diag(New->getLocation(), 17030 diag::err_covariant_return_type_class_type_more_qualified) 17031 << New->getDeclName() << NewTy << OldTy 17032 << New->getReturnTypeSourceRange(); 17033 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17034 << Old->getReturnTypeSourceRange(); 17035 return true; 17036 } 17037 17038 return false; 17039 } 17040 17041 /// Mark the given method pure. 17042 /// 17043 /// \param Method the method to be marked pure. 17044 /// 17045 /// \param InitRange the source range that covers the "0" initializer. 17046 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 17047 SourceLocation EndLoc = InitRange.getEnd(); 17048 if (EndLoc.isValid()) 17049 Method->setRangeEnd(EndLoc); 17050 17051 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 17052 Method->setPure(); 17053 return false; 17054 } 17055 17056 if (!Method->isInvalidDecl()) 17057 Diag(Method->getLocation(), diag::err_non_virtual_pure) 17058 << Method->getDeclName() << InitRange; 17059 return true; 17060 } 17061 17062 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) { 17063 if (D->getFriendObjectKind()) 17064 Diag(D->getLocation(), diag::err_pure_friend); 17065 else if (auto *M = dyn_cast<CXXMethodDecl>(D)) 17066 CheckPureMethod(M, ZeroLoc); 17067 else 17068 Diag(D->getLocation(), diag::err_illegal_initializer); 17069 } 17070 17071 /// Determine whether the given declaration is a global variable or 17072 /// static data member. 17073 static bool isNonlocalVariable(const Decl *D) { 17074 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 17075 return Var->hasGlobalStorage(); 17076 17077 return false; 17078 } 17079 17080 /// Invoked when we are about to parse an initializer for the declaration 17081 /// 'Dcl'. 17082 /// 17083 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 17084 /// static data member of class X, names should be looked up in the scope of 17085 /// class X. If the declaration had a scope specifier, a scope will have 17086 /// been created and passed in for this purpose. Otherwise, S will be null. 17087 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 17088 // If there is no declaration, there was an error parsing it. 17089 if (!D || D->isInvalidDecl()) 17090 return; 17091 17092 // We will always have a nested name specifier here, but this declaration 17093 // might not be out of line if the specifier names the current namespace: 17094 // extern int n; 17095 // int ::n = 0; 17096 if (S && D->isOutOfLine()) 17097 EnterDeclaratorContext(S, D->getDeclContext()); 17098 17099 // If we are parsing the initializer for a static data member, push a 17100 // new expression evaluation context that is associated with this static 17101 // data member. 17102 if (isNonlocalVariable(D)) 17103 PushExpressionEvaluationContext( 17104 ExpressionEvaluationContext::PotentiallyEvaluated, D); 17105 } 17106 17107 /// Invoked after we are finished parsing an initializer for the declaration D. 17108 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 17109 // If there is no declaration, there was an error parsing it. 17110 if (!D || D->isInvalidDecl()) 17111 return; 17112 17113 if (isNonlocalVariable(D)) 17114 PopExpressionEvaluationContext(); 17115 17116 if (S && D->isOutOfLine()) 17117 ExitDeclaratorContext(S); 17118 } 17119 17120 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 17121 /// C++ if/switch/while/for statement. 17122 /// e.g: "if (int x = f()) {...}" 17123 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 17124 // C++ 6.4p2: 17125 // The declarator shall not specify a function or an array. 17126 // The type-specifier-seq shall not contain typedef and shall not declare a 17127 // new class or enumeration. 17128 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 17129 "Parser allowed 'typedef' as storage class of condition decl."); 17130 17131 Decl *Dcl = ActOnDeclarator(S, D); 17132 if (!Dcl) 17133 return true; 17134 17135 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 17136 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 17137 << D.getSourceRange(); 17138 return true; 17139 } 17140 17141 return Dcl; 17142 } 17143 17144 void Sema::LoadExternalVTableUses() { 17145 if (!ExternalSource) 17146 return; 17147 17148 SmallVector<ExternalVTableUse, 4> VTables; 17149 ExternalSource->ReadUsedVTables(VTables); 17150 SmallVector<VTableUse, 4> NewUses; 17151 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 17152 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 17153 = VTablesUsed.find(VTables[I].Record); 17154 // Even if a definition wasn't required before, it may be required now. 17155 if (Pos != VTablesUsed.end()) { 17156 if (!Pos->second && VTables[I].DefinitionRequired) 17157 Pos->second = true; 17158 continue; 17159 } 17160 17161 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 17162 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 17163 } 17164 17165 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 17166 } 17167 17168 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 17169 bool DefinitionRequired) { 17170 // Ignore any vtable uses in unevaluated operands or for classes that do 17171 // not have a vtable. 17172 if (!Class->isDynamicClass() || Class->isDependentContext() || 17173 CurContext->isDependentContext() || isUnevaluatedContext()) 17174 return; 17175 // Do not mark as used if compiling for the device outside of the target 17176 // region. 17177 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice && 17178 !isInOpenMPDeclareTargetContext() && 17179 !isInOpenMPTargetExecutionDirective()) { 17180 if (!DefinitionRequired) 17181 MarkVirtualMembersReferenced(Loc, Class); 17182 return; 17183 } 17184 17185 // Try to insert this class into the map. 17186 LoadExternalVTableUses(); 17187 Class = Class->getCanonicalDecl(); 17188 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 17189 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 17190 if (!Pos.second) { 17191 // If we already had an entry, check to see if we are promoting this vtable 17192 // to require a definition. If so, we need to reappend to the VTableUses 17193 // list, since we may have already processed the first entry. 17194 if (DefinitionRequired && !Pos.first->second) { 17195 Pos.first->second = true; 17196 } else { 17197 // Otherwise, we can early exit. 17198 return; 17199 } 17200 } else { 17201 // The Microsoft ABI requires that we perform the destructor body 17202 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 17203 // the deleting destructor is emitted with the vtable, not with the 17204 // destructor definition as in the Itanium ABI. 17205 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 17206 CXXDestructorDecl *DD = Class->getDestructor(); 17207 if (DD && DD->isVirtual() && !DD->isDeleted()) { 17208 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) { 17209 // If this is an out-of-line declaration, marking it referenced will 17210 // not do anything. Manually call CheckDestructor to look up operator 17211 // delete(). 17212 ContextRAII SavedContext(*this, DD); 17213 CheckDestructor(DD); 17214 } else { 17215 MarkFunctionReferenced(Loc, Class->getDestructor()); 17216 } 17217 } 17218 } 17219 } 17220 17221 // Local classes need to have their virtual members marked 17222 // immediately. For all other classes, we mark their virtual members 17223 // at the end of the translation unit. 17224 if (Class->isLocalClass()) 17225 MarkVirtualMembersReferenced(Loc, Class); 17226 else 17227 VTableUses.push_back(std::make_pair(Class, Loc)); 17228 } 17229 17230 bool Sema::DefineUsedVTables() { 17231 LoadExternalVTableUses(); 17232 if (VTableUses.empty()) 17233 return false; 17234 17235 // Note: The VTableUses vector could grow as a result of marking 17236 // the members of a class as "used", so we check the size each 17237 // time through the loop and prefer indices (which are stable) to 17238 // iterators (which are not). 17239 bool DefinedAnything = false; 17240 for (unsigned I = 0; I != VTableUses.size(); ++I) { 17241 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 17242 if (!Class) 17243 continue; 17244 TemplateSpecializationKind ClassTSK = 17245 Class->getTemplateSpecializationKind(); 17246 17247 SourceLocation Loc = VTableUses[I].second; 17248 17249 bool DefineVTable = true; 17250 17251 // If this class has a key function, but that key function is 17252 // defined in another translation unit, we don't need to emit the 17253 // vtable even though we're using it. 17254 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 17255 if (KeyFunction && !KeyFunction->hasBody()) { 17256 // The key function is in another translation unit. 17257 DefineVTable = false; 17258 TemplateSpecializationKind TSK = 17259 KeyFunction->getTemplateSpecializationKind(); 17260 assert(TSK != TSK_ExplicitInstantiationDefinition && 17261 TSK != TSK_ImplicitInstantiation && 17262 "Instantiations don't have key functions"); 17263 (void)TSK; 17264 } else if (!KeyFunction) { 17265 // If we have a class with no key function that is the subject 17266 // of an explicit instantiation declaration, suppress the 17267 // vtable; it will live with the explicit instantiation 17268 // definition. 17269 bool IsExplicitInstantiationDeclaration = 17270 ClassTSK == TSK_ExplicitInstantiationDeclaration; 17271 for (auto R : Class->redecls()) { 17272 TemplateSpecializationKind TSK 17273 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 17274 if (TSK == TSK_ExplicitInstantiationDeclaration) 17275 IsExplicitInstantiationDeclaration = true; 17276 else if (TSK == TSK_ExplicitInstantiationDefinition) { 17277 IsExplicitInstantiationDeclaration = false; 17278 break; 17279 } 17280 } 17281 17282 if (IsExplicitInstantiationDeclaration) 17283 DefineVTable = false; 17284 } 17285 17286 // The exception specifications for all virtual members may be needed even 17287 // if we are not providing an authoritative form of the vtable in this TU. 17288 // We may choose to emit it available_externally anyway. 17289 if (!DefineVTable) { 17290 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 17291 continue; 17292 } 17293 17294 // Mark all of the virtual members of this class as referenced, so 17295 // that we can build a vtable. Then, tell the AST consumer that a 17296 // vtable for this class is required. 17297 DefinedAnything = true; 17298 MarkVirtualMembersReferenced(Loc, Class); 17299 CXXRecordDecl *Canonical = Class->getCanonicalDecl(); 17300 if (VTablesUsed[Canonical]) 17301 Consumer.HandleVTable(Class); 17302 17303 // Warn if we're emitting a weak vtable. The vtable will be weak if there is 17304 // no key function or the key function is inlined. Don't warn in C++ ABIs 17305 // that lack key functions, since the user won't be able to make one. 17306 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() && 17307 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) { 17308 const FunctionDecl *KeyFunctionDef = nullptr; 17309 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) && 17310 KeyFunctionDef->isInlined())) { 17311 Diag(Class->getLocation(), 17312 ClassTSK == TSK_ExplicitInstantiationDefinition 17313 ? diag::warn_weak_template_vtable 17314 : diag::warn_weak_vtable) 17315 << Class; 17316 } 17317 } 17318 } 17319 VTableUses.clear(); 17320 17321 return DefinedAnything; 17322 } 17323 17324 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 17325 const CXXRecordDecl *RD) { 17326 for (const auto *I : RD->methods()) 17327 if (I->isVirtual() && !I->isPure()) 17328 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 17329 } 17330 17331 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 17332 const CXXRecordDecl *RD, 17333 bool ConstexprOnly) { 17334 // Mark all functions which will appear in RD's vtable as used. 17335 CXXFinalOverriderMap FinalOverriders; 17336 RD->getFinalOverriders(FinalOverriders); 17337 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 17338 E = FinalOverriders.end(); 17339 I != E; ++I) { 17340 for (OverridingMethods::const_iterator OI = I->second.begin(), 17341 OE = I->second.end(); 17342 OI != OE; ++OI) { 17343 assert(OI->second.size() > 0 && "no final overrider"); 17344 CXXMethodDecl *Overrider = OI->second.front().Method; 17345 17346 // C++ [basic.def.odr]p2: 17347 // [...] A virtual member function is used if it is not pure. [...] 17348 if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr())) 17349 MarkFunctionReferenced(Loc, Overrider); 17350 } 17351 } 17352 17353 // Only classes that have virtual bases need a VTT. 17354 if (RD->getNumVBases() == 0) 17355 return; 17356 17357 for (const auto &I : RD->bases()) { 17358 const auto *Base = 17359 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 17360 if (Base->getNumVBases() == 0) 17361 continue; 17362 MarkVirtualMembersReferenced(Loc, Base); 17363 } 17364 } 17365 17366 /// SetIvarInitializers - This routine builds initialization ASTs for the 17367 /// Objective-C implementation whose ivars need be initialized. 17368 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 17369 if (!getLangOpts().CPlusPlus) 17370 return; 17371 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 17372 SmallVector<ObjCIvarDecl*, 8> ivars; 17373 CollectIvarsToConstructOrDestruct(OID, ivars); 17374 if (ivars.empty()) 17375 return; 17376 SmallVector<CXXCtorInitializer*, 32> AllToInit; 17377 for (unsigned i = 0; i < ivars.size(); i++) { 17378 FieldDecl *Field = ivars[i]; 17379 if (Field->isInvalidDecl()) 17380 continue; 17381 17382 CXXCtorInitializer *Member; 17383 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 17384 InitializationKind InitKind = 17385 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 17386 17387 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 17388 ExprResult MemberInit = 17389 InitSeq.Perform(*this, InitEntity, InitKind, None); 17390 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 17391 // Note, MemberInit could actually come back empty if no initialization 17392 // is required (e.g., because it would call a trivial default constructor) 17393 if (!MemberInit.get() || MemberInit.isInvalid()) 17394 continue; 17395 17396 Member = 17397 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 17398 SourceLocation(), 17399 MemberInit.getAs<Expr>(), 17400 SourceLocation()); 17401 AllToInit.push_back(Member); 17402 17403 // Be sure that the destructor is accessible and is marked as referenced. 17404 if (const RecordType *RecordTy = 17405 Context.getBaseElementType(Field->getType()) 17406 ->getAs<RecordType>()) { 17407 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 17408 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 17409 MarkFunctionReferenced(Field->getLocation(), Destructor); 17410 CheckDestructorAccess(Field->getLocation(), Destructor, 17411 PDiag(diag::err_access_dtor_ivar) 17412 << Context.getBaseElementType(Field->getType())); 17413 } 17414 } 17415 } 17416 ObjCImplementation->setIvarInitializers(Context, 17417 AllToInit.data(), AllToInit.size()); 17418 } 17419 } 17420 17421 static 17422 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 17423 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid, 17424 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid, 17425 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current, 17426 Sema &S) { 17427 if (Ctor->isInvalidDecl()) 17428 return; 17429 17430 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 17431 17432 // Target may not be determinable yet, for instance if this is a dependent 17433 // call in an uninstantiated template. 17434 if (Target) { 17435 const FunctionDecl *FNTarget = nullptr; 17436 (void)Target->hasBody(FNTarget); 17437 Target = const_cast<CXXConstructorDecl*>( 17438 cast_or_null<CXXConstructorDecl>(FNTarget)); 17439 } 17440 17441 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 17442 // Avoid dereferencing a null pointer here. 17443 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 17444 17445 if (!Current.insert(Canonical).second) 17446 return; 17447 17448 // We know that beyond here, we aren't chaining into a cycle. 17449 if (!Target || !Target->isDelegatingConstructor() || 17450 Target->isInvalidDecl() || Valid.count(TCanonical)) { 17451 Valid.insert(Current.begin(), Current.end()); 17452 Current.clear(); 17453 // We've hit a cycle. 17454 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 17455 Current.count(TCanonical)) { 17456 // If we haven't diagnosed this cycle yet, do so now. 17457 if (!Invalid.count(TCanonical)) { 17458 S.Diag((*Ctor->init_begin())->getSourceLocation(), 17459 diag::warn_delegating_ctor_cycle) 17460 << Ctor; 17461 17462 // Don't add a note for a function delegating directly to itself. 17463 if (TCanonical != Canonical) 17464 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 17465 17466 CXXConstructorDecl *C = Target; 17467 while (C->getCanonicalDecl() != Canonical) { 17468 const FunctionDecl *FNTarget = nullptr; 17469 (void)C->getTargetConstructor()->hasBody(FNTarget); 17470 assert(FNTarget && "Ctor cycle through bodiless function"); 17471 17472 C = const_cast<CXXConstructorDecl*>( 17473 cast<CXXConstructorDecl>(FNTarget)); 17474 S.Diag(C->getLocation(), diag::note_which_delegates_to); 17475 } 17476 } 17477 17478 Invalid.insert(Current.begin(), Current.end()); 17479 Current.clear(); 17480 } else { 17481 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 17482 } 17483 } 17484 17485 17486 void Sema::CheckDelegatingCtorCycles() { 17487 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 17488 17489 for (DelegatingCtorDeclsType::iterator 17490 I = DelegatingCtorDecls.begin(ExternalSource), 17491 E = DelegatingCtorDecls.end(); 17492 I != E; ++I) 17493 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 17494 17495 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI) 17496 (*CI)->setInvalidDecl(); 17497 } 17498 17499 namespace { 17500 /// AST visitor that finds references to the 'this' expression. 17501 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 17502 Sema &S; 17503 17504 public: 17505 explicit FindCXXThisExpr(Sema &S) : S(S) { } 17506 17507 bool VisitCXXThisExpr(CXXThisExpr *E) { 17508 S.Diag(E->getLocation(), diag::err_this_static_member_func) 17509 << E->isImplicit(); 17510 return false; 17511 } 17512 }; 17513 } 17514 17515 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 17516 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 17517 if (!TSInfo) 17518 return false; 17519 17520 TypeLoc TL = TSInfo->getTypeLoc(); 17521 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 17522 if (!ProtoTL) 17523 return false; 17524 17525 // C++11 [expr.prim.general]p3: 17526 // [The expression this] shall not appear before the optional 17527 // cv-qualifier-seq and it shall not appear within the declaration of a 17528 // static member function (although its type and value category are defined 17529 // within a static member function as they are within a non-static member 17530 // function). [ Note: this is because declaration matching does not occur 17531 // until the complete declarator is known. - end note ] 17532 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 17533 FindCXXThisExpr Finder(*this); 17534 17535 // If the return type came after the cv-qualifier-seq, check it now. 17536 if (Proto->hasTrailingReturn() && 17537 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 17538 return true; 17539 17540 // Check the exception specification. 17541 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 17542 return true; 17543 17544 // Check the trailing requires clause 17545 if (Expr *E = Method->getTrailingRequiresClause()) 17546 if (!Finder.TraverseStmt(E)) 17547 return true; 17548 17549 return checkThisInStaticMemberFunctionAttributes(Method); 17550 } 17551 17552 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 17553 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 17554 if (!TSInfo) 17555 return false; 17556 17557 TypeLoc TL = TSInfo->getTypeLoc(); 17558 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 17559 if (!ProtoTL) 17560 return false; 17561 17562 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 17563 FindCXXThisExpr Finder(*this); 17564 17565 switch (Proto->getExceptionSpecType()) { 17566 case EST_Unparsed: 17567 case EST_Uninstantiated: 17568 case EST_Unevaluated: 17569 case EST_BasicNoexcept: 17570 case EST_NoThrow: 17571 case EST_DynamicNone: 17572 case EST_MSAny: 17573 case EST_None: 17574 break; 17575 17576 case EST_DependentNoexcept: 17577 case EST_NoexceptFalse: 17578 case EST_NoexceptTrue: 17579 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 17580 return true; 17581 LLVM_FALLTHROUGH; 17582 17583 case EST_Dynamic: 17584 for (const auto &E : Proto->exceptions()) { 17585 if (!Finder.TraverseType(E)) 17586 return true; 17587 } 17588 break; 17589 } 17590 17591 return false; 17592 } 17593 17594 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 17595 FindCXXThisExpr Finder(*this); 17596 17597 // Check attributes. 17598 for (const auto *A : Method->attrs()) { 17599 // FIXME: This should be emitted by tblgen. 17600 Expr *Arg = nullptr; 17601 ArrayRef<Expr *> Args; 17602 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 17603 Arg = G->getArg(); 17604 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 17605 Arg = G->getArg(); 17606 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 17607 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 17608 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 17609 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 17610 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 17611 Arg = ETLF->getSuccessValue(); 17612 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 17613 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 17614 Arg = STLF->getSuccessValue(); 17615 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 17616 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 17617 Arg = LR->getArg(); 17618 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 17619 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 17620 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 17621 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 17622 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 17623 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 17624 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 17625 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 17626 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 17627 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 17628 17629 if (Arg && !Finder.TraverseStmt(Arg)) 17630 return true; 17631 17632 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 17633 if (!Finder.TraverseStmt(Args[I])) 17634 return true; 17635 } 17636 } 17637 17638 return false; 17639 } 17640 17641 void Sema::checkExceptionSpecification( 17642 bool IsTopLevel, ExceptionSpecificationType EST, 17643 ArrayRef<ParsedType> DynamicExceptions, 17644 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 17645 SmallVectorImpl<QualType> &Exceptions, 17646 FunctionProtoType::ExceptionSpecInfo &ESI) { 17647 Exceptions.clear(); 17648 ESI.Type = EST; 17649 if (EST == EST_Dynamic) { 17650 Exceptions.reserve(DynamicExceptions.size()); 17651 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 17652 // FIXME: Preserve type source info. 17653 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 17654 17655 if (IsTopLevel) { 17656 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 17657 collectUnexpandedParameterPacks(ET, Unexpanded); 17658 if (!Unexpanded.empty()) { 17659 DiagnoseUnexpandedParameterPacks( 17660 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 17661 Unexpanded); 17662 continue; 17663 } 17664 } 17665 17666 // Check that the type is valid for an exception spec, and 17667 // drop it if not. 17668 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 17669 Exceptions.push_back(ET); 17670 } 17671 ESI.Exceptions = Exceptions; 17672 return; 17673 } 17674 17675 if (isComputedNoexcept(EST)) { 17676 assert((NoexceptExpr->isTypeDependent() || 17677 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 17678 Context.BoolTy) && 17679 "Parser should have made sure that the expression is boolean"); 17680 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 17681 ESI.Type = EST_BasicNoexcept; 17682 return; 17683 } 17684 17685 ESI.NoexceptExpr = NoexceptExpr; 17686 return; 17687 } 17688 } 17689 17690 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 17691 ExceptionSpecificationType EST, 17692 SourceRange SpecificationRange, 17693 ArrayRef<ParsedType> DynamicExceptions, 17694 ArrayRef<SourceRange> DynamicExceptionRanges, 17695 Expr *NoexceptExpr) { 17696 if (!MethodD) 17697 return; 17698 17699 // Dig out the method we're referring to. 17700 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 17701 MethodD = FunTmpl->getTemplatedDecl(); 17702 17703 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 17704 if (!Method) 17705 return; 17706 17707 // Check the exception specification. 17708 llvm::SmallVector<QualType, 4> Exceptions; 17709 FunctionProtoType::ExceptionSpecInfo ESI; 17710 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 17711 DynamicExceptionRanges, NoexceptExpr, Exceptions, 17712 ESI); 17713 17714 // Update the exception specification on the function type. 17715 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 17716 17717 if (Method->isStatic()) 17718 checkThisInStaticMemberFunctionExceptionSpec(Method); 17719 17720 if (Method->isVirtual()) { 17721 // Check overrides, which we previously had to delay. 17722 for (const CXXMethodDecl *O : Method->overridden_methods()) 17723 CheckOverridingFunctionExceptionSpec(Method, O); 17724 } 17725 } 17726 17727 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 17728 /// 17729 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 17730 SourceLocation DeclStart, Declarator &D, 17731 Expr *BitWidth, 17732 InClassInitStyle InitStyle, 17733 AccessSpecifier AS, 17734 const ParsedAttr &MSPropertyAttr) { 17735 IdentifierInfo *II = D.getIdentifier(); 17736 if (!II) { 17737 Diag(DeclStart, diag::err_anonymous_property); 17738 return nullptr; 17739 } 17740 SourceLocation Loc = D.getIdentifierLoc(); 17741 17742 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 17743 QualType T = TInfo->getType(); 17744 if (getLangOpts().CPlusPlus) { 17745 CheckExtraCXXDefaultArguments(D); 17746 17747 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 17748 UPPC_DataMemberType)) { 17749 D.setInvalidType(); 17750 T = Context.IntTy; 17751 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 17752 } 17753 } 17754 17755 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 17756 17757 if (D.getDeclSpec().isInlineSpecified()) 17758 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 17759 << getLangOpts().CPlusPlus17; 17760 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 17761 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 17762 diag::err_invalid_thread) 17763 << DeclSpec::getSpecifierName(TSCS); 17764 17765 // Check to see if this name was declared as a member previously 17766 NamedDecl *PrevDecl = nullptr; 17767 LookupResult Previous(*this, II, Loc, LookupMemberName, 17768 ForVisibleRedeclaration); 17769 LookupName(Previous, S); 17770 switch (Previous.getResultKind()) { 17771 case LookupResult::Found: 17772 case LookupResult::FoundUnresolvedValue: 17773 PrevDecl = Previous.getAsSingle<NamedDecl>(); 17774 break; 17775 17776 case LookupResult::FoundOverloaded: 17777 PrevDecl = Previous.getRepresentativeDecl(); 17778 break; 17779 17780 case LookupResult::NotFound: 17781 case LookupResult::NotFoundInCurrentInstantiation: 17782 case LookupResult::Ambiguous: 17783 break; 17784 } 17785 17786 if (PrevDecl && PrevDecl->isTemplateParameter()) { 17787 // Maybe we will complain about the shadowed template parameter. 17788 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 17789 // Just pretend that we didn't see the previous declaration. 17790 PrevDecl = nullptr; 17791 } 17792 17793 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 17794 PrevDecl = nullptr; 17795 17796 SourceLocation TSSL = D.getBeginLoc(); 17797 MSPropertyDecl *NewPD = 17798 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL, 17799 MSPropertyAttr.getPropertyDataGetter(), 17800 MSPropertyAttr.getPropertyDataSetter()); 17801 ProcessDeclAttributes(TUScope, NewPD, D); 17802 NewPD->setAccess(AS); 17803 17804 if (NewPD->isInvalidDecl()) 17805 Record->setInvalidDecl(); 17806 17807 if (D.getDeclSpec().isModulePrivateSpecified()) 17808 NewPD->setModulePrivate(); 17809 17810 if (NewPD->isInvalidDecl() && PrevDecl) { 17811 // Don't introduce NewFD into scope; there's already something 17812 // with the same name in the same scope. 17813 } else if (II) { 17814 PushOnScopeChains(NewPD, S); 17815 } else 17816 Record->addDecl(NewPD); 17817 17818 return NewPD; 17819 } 17820 17821 void Sema::ActOnStartFunctionDeclarationDeclarator( 17822 Declarator &Declarator, unsigned TemplateParameterDepth) { 17823 auto &Info = InventedParameterInfos.emplace_back(); 17824 TemplateParameterList *ExplicitParams = nullptr; 17825 ArrayRef<TemplateParameterList *> ExplicitLists = 17826 Declarator.getTemplateParameterLists(); 17827 if (!ExplicitLists.empty()) { 17828 bool IsMemberSpecialization, IsInvalid; 17829 ExplicitParams = MatchTemplateParametersToScopeSpecifier( 17830 Declarator.getBeginLoc(), Declarator.getIdentifierLoc(), 17831 Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr, 17832 ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid, 17833 /*SuppressDiagnostic=*/true); 17834 } 17835 if (ExplicitParams) { 17836 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth(); 17837 for (NamedDecl *Param : *ExplicitParams) 17838 Info.TemplateParams.push_back(Param); 17839 Info.NumExplicitTemplateParams = ExplicitParams->size(); 17840 } else { 17841 Info.AutoTemplateParameterDepth = TemplateParameterDepth; 17842 Info.NumExplicitTemplateParams = 0; 17843 } 17844 } 17845 17846 void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) { 17847 auto &FSI = InventedParameterInfos.back(); 17848 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) { 17849 if (FSI.NumExplicitTemplateParams != 0) { 17850 TemplateParameterList *ExplicitParams = 17851 Declarator.getTemplateParameterLists().back(); 17852 Declarator.setInventedTemplateParameterList( 17853 TemplateParameterList::Create( 17854 Context, ExplicitParams->getTemplateLoc(), 17855 ExplicitParams->getLAngleLoc(), FSI.TemplateParams, 17856 ExplicitParams->getRAngleLoc(), 17857 ExplicitParams->getRequiresClause())); 17858 } else { 17859 Declarator.setInventedTemplateParameterList( 17860 TemplateParameterList::Create( 17861 Context, SourceLocation(), SourceLocation(), FSI.TemplateParams, 17862 SourceLocation(), /*RequiresClause=*/nullptr)); 17863 } 17864 } 17865 InventedParameterInfos.pop_back(); 17866 } 17867