SemaDeclCXX.cpp revision f6a144f5991c6b29622a31fdab86adede0648d12
1//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements semantic analysis for C++ declarations. 11// 12//===----------------------------------------------------------------------===// 13 14#include "clang/Sema/SemaInternal.h" 15#include "clang/AST/ASTConsumer.h" 16#include "clang/AST/ASTContext.h" 17#include "clang/AST/ASTMutationListener.h" 18#include "clang/AST/CXXInheritance.h" 19#include "clang/AST/CharUnits.h" 20#include "clang/AST/DeclVisitor.h" 21#include "clang/AST/EvaluatedExprVisitor.h" 22#include "clang/AST/ExprCXX.h" 23#include "clang/AST/RecordLayout.h" 24#include "clang/AST/RecursiveASTVisitor.h" 25#include "clang/AST/StmtVisitor.h" 26#include "clang/AST/TypeLoc.h" 27#include "clang/AST/TypeOrdering.h" 28#include "clang/Basic/PartialDiagnostic.h" 29#include "clang/Basic/TargetInfo.h" 30#include "clang/Lex/Preprocessor.h" 31#include "clang/Sema/CXXFieldCollector.h" 32#include "clang/Sema/DeclSpec.h" 33#include "clang/Sema/Initialization.h" 34#include "clang/Sema/Lookup.h" 35#include "clang/Sema/ParsedTemplate.h" 36#include "clang/Sema/Scope.h" 37#include "clang/Sema/ScopeInfo.h" 38#include "llvm/ADT/STLExtras.h" 39#include "llvm/ADT/SmallString.h" 40#include <map> 41#include <set> 42 43using namespace clang; 44 45//===----------------------------------------------------------------------===// 46// CheckDefaultArgumentVisitor 47//===----------------------------------------------------------------------===// 48 49namespace { 50 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 51 /// the default argument of a parameter to determine whether it 52 /// contains any ill-formed subexpressions. For example, this will 53 /// diagnose the use of local variables or parameters within the 54 /// default argument expression. 55 class CheckDefaultArgumentVisitor 56 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 57 Expr *DefaultArg; 58 Sema *S; 59 60 public: 61 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 62 : DefaultArg(defarg), S(s) {} 63 64 bool VisitExpr(Expr *Node); 65 bool VisitDeclRefExpr(DeclRefExpr *DRE); 66 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 67 bool VisitLambdaExpr(LambdaExpr *Lambda); 68 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE); 69 }; 70 71 /// VisitExpr - Visit all of the children of this expression. 72 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 73 bool IsInvalid = false; 74 for (Stmt::child_range I = Node->children(); I; ++I) 75 IsInvalid |= Visit(*I); 76 return IsInvalid; 77 } 78 79 /// VisitDeclRefExpr - Visit a reference to a declaration, to 80 /// determine whether this declaration can be used in the default 81 /// argument expression. 82 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 83 NamedDecl *Decl = DRE->getDecl(); 84 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 85 // C++ [dcl.fct.default]p9 86 // Default arguments are evaluated each time the function is 87 // called. The order of evaluation of function arguments is 88 // unspecified. Consequently, parameters of a function shall not 89 // be used in default argument expressions, even if they are not 90 // evaluated. Parameters of a function declared before a default 91 // argument expression are in scope and can hide namespace and 92 // class member names. 93 return S->Diag(DRE->getLocStart(), 94 diag::err_param_default_argument_references_param) 95 << Param->getDeclName() << DefaultArg->getSourceRange(); 96 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 97 // C++ [dcl.fct.default]p7 98 // Local variables shall not be used in default argument 99 // expressions. 100 if (VDecl->isLocalVarDecl()) 101 return S->Diag(DRE->getLocStart(), 102 diag::err_param_default_argument_references_local) 103 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 104 } 105 106 return false; 107 } 108 109 /// VisitCXXThisExpr - Visit a C++ "this" expression. 110 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 111 // C++ [dcl.fct.default]p8: 112 // The keyword this shall not be used in a default argument of a 113 // member function. 114 return S->Diag(ThisE->getLocStart(), 115 diag::err_param_default_argument_references_this) 116 << ThisE->getSourceRange(); 117 } 118 119 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) { 120 bool Invalid = false; 121 for (PseudoObjectExpr::semantics_iterator 122 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) { 123 Expr *E = *i; 124 125 // Look through bindings. 126 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 127 E = OVE->getSourceExpr(); 128 assert(E && "pseudo-object binding without source expression?"); 129 } 130 131 Invalid |= Visit(E); 132 } 133 return Invalid; 134 } 135 136 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) { 137 // C++11 [expr.lambda.prim]p13: 138 // A lambda-expression appearing in a default argument shall not 139 // implicitly or explicitly capture any entity. 140 if (Lambda->capture_begin() == Lambda->capture_end()) 141 return false; 142 143 return S->Diag(Lambda->getLocStart(), 144 diag::err_lambda_capture_default_arg); 145 } 146} 147 148void 149Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc, 150 const CXXMethodDecl *Method) { 151 // If we have an MSAny spec already, don't bother. 152 if (!Method || ComputedEST == EST_MSAny) 153 return; 154 155 const FunctionProtoType *Proto 156 = Method->getType()->getAs<FunctionProtoType>(); 157 Proto = Self->ResolveExceptionSpec(CallLoc, Proto); 158 if (!Proto) 159 return; 160 161 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 162 163 // If this function can throw any exceptions, make a note of that. 164 if (EST == EST_MSAny || EST == EST_None) { 165 ClearExceptions(); 166 ComputedEST = EST; 167 return; 168 } 169 170 // FIXME: If the call to this decl is using any of its default arguments, we 171 // need to search them for potentially-throwing calls. 172 173 // If this function has a basic noexcept, it doesn't affect the outcome. 174 if (EST == EST_BasicNoexcept) 175 return; 176 177 // If we have a throw-all spec at this point, ignore the function. 178 if (ComputedEST == EST_None) 179 return; 180 181 // If we're still at noexcept(true) and there's a nothrow() callee, 182 // change to that specification. 183 if (EST == EST_DynamicNone) { 184 if (ComputedEST == EST_BasicNoexcept) 185 ComputedEST = EST_DynamicNone; 186 return; 187 } 188 189 // Check out noexcept specs. 190 if (EST == EST_ComputedNoexcept) { 191 FunctionProtoType::NoexceptResult NR = 192 Proto->getNoexceptSpec(Self->Context); 193 assert(NR != FunctionProtoType::NR_NoNoexcept && 194 "Must have noexcept result for EST_ComputedNoexcept."); 195 assert(NR != FunctionProtoType::NR_Dependent && 196 "Should not generate implicit declarations for dependent cases, " 197 "and don't know how to handle them anyway."); 198 199 // noexcept(false) -> no spec on the new function 200 if (NR == FunctionProtoType::NR_Throw) { 201 ClearExceptions(); 202 ComputedEST = EST_None; 203 } 204 // noexcept(true) won't change anything either. 205 return; 206 } 207 208 assert(EST == EST_Dynamic && "EST case not considered earlier."); 209 assert(ComputedEST != EST_None && 210 "Shouldn't collect exceptions when throw-all is guaranteed."); 211 ComputedEST = EST_Dynamic; 212 // Record the exceptions in this function's exception specification. 213 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(), 214 EEnd = Proto->exception_end(); 215 E != EEnd; ++E) 216 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E))) 217 Exceptions.push_back(*E); 218} 219 220void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) { 221 if (!E || ComputedEST == EST_MSAny) 222 return; 223 224 // FIXME: 225 // 226 // C++0x [except.spec]p14: 227 // [An] implicit exception-specification specifies the type-id T if and 228 // only if T is allowed by the exception-specification of a function directly 229 // invoked by f's implicit definition; f shall allow all exceptions if any 230 // function it directly invokes allows all exceptions, and f shall allow no 231 // exceptions if every function it directly invokes allows no exceptions. 232 // 233 // Note in particular that if an implicit exception-specification is generated 234 // for a function containing a throw-expression, that specification can still 235 // be noexcept(true). 236 // 237 // Note also that 'directly invoked' is not defined in the standard, and there 238 // is no indication that we should only consider potentially-evaluated calls. 239 // 240 // Ultimately we should implement the intent of the standard: the exception 241 // specification should be the set of exceptions which can be thrown by the 242 // implicit definition. For now, we assume that any non-nothrow expression can 243 // throw any exception. 244 245 if (Self->canThrow(E)) 246 ComputedEST = EST_None; 247} 248 249bool 250Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 251 SourceLocation EqualLoc) { 252 if (RequireCompleteType(Param->getLocation(), Param->getType(), 253 diag::err_typecheck_decl_incomplete_type)) { 254 Param->setInvalidDecl(); 255 return true; 256 } 257 258 // C++ [dcl.fct.default]p5 259 // A default argument expression is implicitly converted (clause 260 // 4) to the parameter type. The default argument expression has 261 // the same semantic constraints as the initializer expression in 262 // a declaration of a variable of the parameter type, using the 263 // copy-initialization semantics (8.5). 264 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 265 Param); 266 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 267 EqualLoc); 268 InitializationSequence InitSeq(*this, Entity, Kind, Arg); 269 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); 270 if (Result.isInvalid()) 271 return true; 272 Arg = Result.takeAs<Expr>(); 273 274 CheckCompletedExpr(Arg, EqualLoc); 275 Arg = MaybeCreateExprWithCleanups(Arg); 276 277 // Okay: add the default argument to the parameter 278 Param->setDefaultArg(Arg); 279 280 // We have already instantiated this parameter; provide each of the 281 // instantiations with the uninstantiated default argument. 282 UnparsedDefaultArgInstantiationsMap::iterator InstPos 283 = UnparsedDefaultArgInstantiations.find(Param); 284 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 285 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 286 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 287 288 // We're done tracking this parameter's instantiations. 289 UnparsedDefaultArgInstantiations.erase(InstPos); 290 } 291 292 return false; 293} 294 295/// ActOnParamDefaultArgument - Check whether the default argument 296/// provided for a function parameter is well-formed. If so, attach it 297/// to the parameter declaration. 298void 299Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 300 Expr *DefaultArg) { 301 if (!param || !DefaultArg) 302 return; 303 304 ParmVarDecl *Param = cast<ParmVarDecl>(param); 305 UnparsedDefaultArgLocs.erase(Param); 306 307 // Default arguments are only permitted in C++ 308 if (!getLangOpts().CPlusPlus) { 309 Diag(EqualLoc, diag::err_param_default_argument) 310 << DefaultArg->getSourceRange(); 311 Param->setInvalidDecl(); 312 return; 313 } 314 315 // Check for unexpanded parameter packs. 316 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 317 Param->setInvalidDecl(); 318 return; 319 } 320 321 // Check that the default argument is well-formed 322 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this); 323 if (DefaultArgChecker.Visit(DefaultArg)) { 324 Param->setInvalidDecl(); 325 return; 326 } 327 328 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 329} 330 331/// ActOnParamUnparsedDefaultArgument - We've seen a default 332/// argument for a function parameter, but we can't parse it yet 333/// because we're inside a class definition. Note that this default 334/// argument will be parsed later. 335void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 336 SourceLocation EqualLoc, 337 SourceLocation ArgLoc) { 338 if (!param) 339 return; 340 341 ParmVarDecl *Param = cast<ParmVarDecl>(param); 342 if (Param) 343 Param->setUnparsedDefaultArg(); 344 345 UnparsedDefaultArgLocs[Param] = ArgLoc; 346} 347 348/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 349/// the default argument for the parameter param failed. 350void Sema::ActOnParamDefaultArgumentError(Decl *param) { 351 if (!param) 352 return; 353 354 ParmVarDecl *Param = cast<ParmVarDecl>(param); 355 356 Param->setInvalidDecl(); 357 358 UnparsedDefaultArgLocs.erase(Param); 359} 360 361/// CheckExtraCXXDefaultArguments - Check for any extra default 362/// arguments in the declarator, which is not a function declaration 363/// or definition and therefore is not permitted to have default 364/// arguments. This routine should be invoked for every declarator 365/// that is not a function declaration or definition. 366void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 367 // C++ [dcl.fct.default]p3 368 // A default argument expression shall be specified only in the 369 // parameter-declaration-clause of a function declaration or in a 370 // template-parameter (14.1). It shall not be specified for a 371 // parameter pack. If it is specified in a 372 // parameter-declaration-clause, it shall not occur within a 373 // declarator or abstract-declarator of a parameter-declaration. 374 bool MightBeFunction = D.isFunctionDeclarationContext(); 375 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 376 DeclaratorChunk &chunk = D.getTypeObject(i); 377 if (chunk.Kind == DeclaratorChunk::Function) { 378 if (MightBeFunction) { 379 // This is a function declaration. It can have default arguments, but 380 // keep looking in case its return type is a function type with default 381 // arguments. 382 MightBeFunction = false; 383 continue; 384 } 385 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) { 386 ParmVarDecl *Param = 387 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param); 388 if (Param->hasUnparsedDefaultArg()) { 389 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens; 390 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 391 << SourceRange((*Toks)[1].getLocation(), 392 Toks->back().getLocation()); 393 delete Toks; 394 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0; 395 } else if (Param->getDefaultArg()) { 396 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 397 << Param->getDefaultArg()->getSourceRange(); 398 Param->setDefaultArg(0); 399 } 400 } 401 } else if (chunk.Kind != DeclaratorChunk::Paren) { 402 MightBeFunction = false; 403 } 404 } 405} 406 407static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { 408 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) { 409 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1); 410 if (!PVD->hasDefaultArg()) 411 return false; 412 if (!PVD->hasInheritedDefaultArg()) 413 return true; 414 } 415 return false; 416} 417 418/// MergeCXXFunctionDecl - Merge two declarations of the same C++ 419/// function, once we already know that they have the same 420/// type. Subroutine of MergeFunctionDecl. Returns true if there was an 421/// error, false otherwise. 422bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 423 Scope *S) { 424 bool Invalid = false; 425 426 // C++ [dcl.fct.default]p4: 427 // For non-template functions, default arguments can be added in 428 // later declarations of a function in the same 429 // scope. Declarations in different scopes have completely 430 // distinct sets of default arguments. That is, declarations in 431 // inner scopes do not acquire default arguments from 432 // declarations in outer scopes, and vice versa. In a given 433 // function declaration, all parameters subsequent to a 434 // parameter with a default argument shall have default 435 // arguments supplied in this or previous declarations. A 436 // default argument shall not be redefined by a later 437 // declaration (not even to the same value). 438 // 439 // C++ [dcl.fct.default]p6: 440 // Except for member functions of class templates, the default arguments 441 // in a member function definition that appears outside of the class 442 // definition are added to the set of default arguments provided by the 443 // member function declaration in the class definition. 444 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 445 ParmVarDecl *OldParam = Old->getParamDecl(p); 446 ParmVarDecl *NewParam = New->getParamDecl(p); 447 448 bool OldParamHasDfl = OldParam->hasDefaultArg(); 449 bool NewParamHasDfl = NewParam->hasDefaultArg(); 450 451 NamedDecl *ND = Old; 452 if (S && !isDeclInScope(ND, New->getDeclContext(), S)) 453 // Ignore default parameters of old decl if they are not in 454 // the same scope. 455 OldParamHasDfl = false; 456 457 if (OldParamHasDfl && NewParamHasDfl) { 458 459 unsigned DiagDefaultParamID = 460 diag::err_param_default_argument_redefinition; 461 462 // MSVC accepts that default parameters be redefined for member functions 463 // of template class. The new default parameter's value is ignored. 464 Invalid = true; 465 if (getLangOpts().MicrosoftExt) { 466 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New); 467 if (MD && MD->getParent()->getDescribedClassTemplate()) { 468 // Merge the old default argument into the new parameter. 469 NewParam->setHasInheritedDefaultArg(); 470 if (OldParam->hasUninstantiatedDefaultArg()) 471 NewParam->setUninstantiatedDefaultArg( 472 OldParam->getUninstantiatedDefaultArg()); 473 else 474 NewParam->setDefaultArg(OldParam->getInit()); 475 DiagDefaultParamID = diag::warn_param_default_argument_redefinition; 476 Invalid = false; 477 } 478 } 479 480 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 481 // hint here. Alternatively, we could walk the type-source information 482 // for NewParam to find the last source location in the type... but it 483 // isn't worth the effort right now. This is the kind of test case that 484 // is hard to get right: 485 // int f(int); 486 // void g(int (*fp)(int) = f); 487 // void g(int (*fp)(int) = &f); 488 Diag(NewParam->getLocation(), DiagDefaultParamID) 489 << NewParam->getDefaultArgRange(); 490 491 // Look for the function declaration where the default argument was 492 // actually written, which may be a declaration prior to Old. 493 for (FunctionDecl *Older = Old->getPreviousDecl(); 494 Older; Older = Older->getPreviousDecl()) { 495 if (!Older->getParamDecl(p)->hasDefaultArg()) 496 break; 497 498 OldParam = Older->getParamDecl(p); 499 } 500 501 Diag(OldParam->getLocation(), diag::note_previous_definition) 502 << OldParam->getDefaultArgRange(); 503 } else if (OldParamHasDfl) { 504 // Merge the old default argument into the new parameter. 505 // It's important to use getInit() here; getDefaultArg() 506 // strips off any top-level ExprWithCleanups. 507 NewParam->setHasInheritedDefaultArg(); 508 if (OldParam->hasUninstantiatedDefaultArg()) 509 NewParam->setUninstantiatedDefaultArg( 510 OldParam->getUninstantiatedDefaultArg()); 511 else 512 NewParam->setDefaultArg(OldParam->getInit()); 513 } else if (NewParamHasDfl) { 514 if (New->getDescribedFunctionTemplate()) { 515 // Paragraph 4, quoted above, only applies to non-template functions. 516 Diag(NewParam->getLocation(), 517 diag::err_param_default_argument_template_redecl) 518 << NewParam->getDefaultArgRange(); 519 Diag(Old->getLocation(), diag::note_template_prev_declaration) 520 << false; 521 } else if (New->getTemplateSpecializationKind() 522 != TSK_ImplicitInstantiation && 523 New->getTemplateSpecializationKind() != TSK_Undeclared) { 524 // C++ [temp.expr.spec]p21: 525 // Default function arguments shall not be specified in a declaration 526 // or a definition for one of the following explicit specializations: 527 // - the explicit specialization of a function template; 528 // - the explicit specialization of a member function template; 529 // - the explicit specialization of a member function of a class 530 // template where the class template specialization to which the 531 // member function specialization belongs is implicitly 532 // instantiated. 533 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 534 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 535 << New->getDeclName() 536 << NewParam->getDefaultArgRange(); 537 } else if (New->getDeclContext()->isDependentContext()) { 538 // C++ [dcl.fct.default]p6 (DR217): 539 // Default arguments for a member function of a class template shall 540 // be specified on the initial declaration of the member function 541 // within the class template. 542 // 543 // Reading the tea leaves a bit in DR217 and its reference to DR205 544 // leads me to the conclusion that one cannot add default function 545 // arguments for an out-of-line definition of a member function of a 546 // dependent type. 547 int WhichKind = 2; 548 if (CXXRecordDecl *Record 549 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 550 if (Record->getDescribedClassTemplate()) 551 WhichKind = 0; 552 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 553 WhichKind = 1; 554 else 555 WhichKind = 2; 556 } 557 558 Diag(NewParam->getLocation(), 559 diag::err_param_default_argument_member_template_redecl) 560 << WhichKind 561 << NewParam->getDefaultArgRange(); 562 } 563 } 564 } 565 566 // DR1344: If a default argument is added outside a class definition and that 567 // default argument makes the function a special member function, the program 568 // is ill-formed. This can only happen for constructors. 569 if (isa<CXXConstructorDecl>(New) && 570 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 571 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 572 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 573 if (NewSM != OldSM) { 574 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 575 assert(NewParam->hasDefaultArg()); 576 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 577 << NewParam->getDefaultArgRange() << NewSM; 578 Diag(Old->getLocation(), diag::note_previous_declaration); 579 } 580 } 581 582 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 583 // template has a constexpr specifier then all its declarations shall 584 // contain the constexpr specifier. 585 if (New->isConstexpr() != Old->isConstexpr()) { 586 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 587 << New << New->isConstexpr(); 588 Diag(Old->getLocation(), diag::note_previous_declaration); 589 Invalid = true; 590 } 591 592 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 593 // argument expression, that declaration shall be a definition and shall be 594 // the only declaration of the function or function template in the 595 // translation unit. 596 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 597 functionDeclHasDefaultArgument(Old)) { 598 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 599 Diag(Old->getLocation(), diag::note_previous_declaration); 600 Invalid = true; 601 } 602 603 if (CheckEquivalentExceptionSpec(Old, New)) 604 Invalid = true; 605 606 return Invalid; 607} 608 609/// \brief Merge the exception specifications of two variable declarations. 610/// 611/// This is called when there's a redeclaration of a VarDecl. The function 612/// checks if the redeclaration might have an exception specification and 613/// validates compatibility and merges the specs if necessary. 614void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 615 // Shortcut if exceptions are disabled. 616 if (!getLangOpts().CXXExceptions) 617 return; 618 619 assert(Context.hasSameType(New->getType(), Old->getType()) && 620 "Should only be called if types are otherwise the same."); 621 622 QualType NewType = New->getType(); 623 QualType OldType = Old->getType(); 624 625 // We're only interested in pointers and references to functions, as well 626 // as pointers to member functions. 627 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 628 NewType = R->getPointeeType(); 629 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 630 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 631 NewType = P->getPointeeType(); 632 OldType = OldType->getAs<PointerType>()->getPointeeType(); 633 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 634 NewType = M->getPointeeType(); 635 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 636 } 637 638 if (!NewType->isFunctionProtoType()) 639 return; 640 641 // There's lots of special cases for functions. For function pointers, system 642 // libraries are hopefully not as broken so that we don't need these 643 // workarounds. 644 if (CheckEquivalentExceptionSpec( 645 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 646 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 647 New->setInvalidDecl(); 648 } 649} 650 651/// CheckCXXDefaultArguments - Verify that the default arguments for a 652/// function declaration are well-formed according to C++ 653/// [dcl.fct.default]. 654void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 655 unsigned NumParams = FD->getNumParams(); 656 unsigned p; 657 658 // Find first parameter with a default argument 659 for (p = 0; p < NumParams; ++p) { 660 ParmVarDecl *Param = FD->getParamDecl(p); 661 if (Param->hasDefaultArg()) 662 break; 663 } 664 665 // C++ [dcl.fct.default]p4: 666 // In a given function declaration, all parameters 667 // subsequent to a parameter with a default argument shall 668 // have default arguments supplied in this or previous 669 // declarations. A default argument shall not be redefined 670 // by a later declaration (not even to the same value). 671 unsigned LastMissingDefaultArg = 0; 672 for (; p < NumParams; ++p) { 673 ParmVarDecl *Param = FD->getParamDecl(p); 674 if (!Param->hasDefaultArg()) { 675 if (Param->isInvalidDecl()) 676 /* We already complained about this parameter. */; 677 else if (Param->getIdentifier()) 678 Diag(Param->getLocation(), 679 diag::err_param_default_argument_missing_name) 680 << Param->getIdentifier(); 681 else 682 Diag(Param->getLocation(), 683 diag::err_param_default_argument_missing); 684 685 LastMissingDefaultArg = p; 686 } 687 } 688 689 if (LastMissingDefaultArg > 0) { 690 // Some default arguments were missing. Clear out all of the 691 // default arguments up to (and including) the last missing 692 // default argument, so that we leave the function parameters 693 // in a semantically valid state. 694 for (p = 0; p <= LastMissingDefaultArg; ++p) { 695 ParmVarDecl *Param = FD->getParamDecl(p); 696 if (Param->hasDefaultArg()) { 697 Param->setDefaultArg(0); 698 } 699 } 700 } 701} 702 703// CheckConstexprParameterTypes - Check whether a function's parameter types 704// are all literal types. If so, return true. If not, produce a suitable 705// diagnostic and return false. 706static bool CheckConstexprParameterTypes(Sema &SemaRef, 707 const FunctionDecl *FD) { 708 unsigned ArgIndex = 0; 709 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 710 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(), 711 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) { 712 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 713 SourceLocation ParamLoc = PD->getLocation(); 714 if (!(*i)->isDependentType() && 715 SemaRef.RequireLiteralType(ParamLoc, *i, 716 diag::err_constexpr_non_literal_param, 717 ArgIndex+1, PD->getSourceRange(), 718 isa<CXXConstructorDecl>(FD))) 719 return false; 720 } 721 return true; 722} 723 724/// \brief Get diagnostic %select index for tag kind for 725/// record diagnostic message. 726/// WARNING: Indexes apply to particular diagnostics only! 727/// 728/// \returns diagnostic %select index. 729static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 730 switch (Tag) { 731 case TTK_Struct: return 0; 732 case TTK_Interface: return 1; 733 case TTK_Class: return 2; 734 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 735 } 736} 737 738// CheckConstexprFunctionDecl - Check whether a function declaration satisfies 739// the requirements of a constexpr function definition or a constexpr 740// constructor definition. If so, return true. If not, produce appropriate 741// diagnostics and return false. 742// 743// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 744bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) { 745 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 746 if (MD && MD->isInstance()) { 747 // C++11 [dcl.constexpr]p4: 748 // The definition of a constexpr constructor shall satisfy the following 749 // constraints: 750 // - the class shall not have any virtual base classes; 751 const CXXRecordDecl *RD = MD->getParent(); 752 if (RD->getNumVBases()) { 753 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 754 << isa<CXXConstructorDecl>(NewFD) 755 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 756 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(), 757 E = RD->vbases_end(); I != E; ++I) 758 Diag(I->getLocStart(), 759 diag::note_constexpr_virtual_base_here) << I->getSourceRange(); 760 return false; 761 } 762 } 763 764 if (!isa<CXXConstructorDecl>(NewFD)) { 765 // C++11 [dcl.constexpr]p3: 766 // The definition of a constexpr function shall satisfy the following 767 // constraints: 768 // - it shall not be virtual; 769 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 770 if (Method && Method->isVirtual()) { 771 Diag(NewFD->getLocation(), diag::err_constexpr_virtual); 772 773 // If it's not obvious why this function is virtual, find an overridden 774 // function which uses the 'virtual' keyword. 775 const CXXMethodDecl *WrittenVirtual = Method; 776 while (!WrittenVirtual->isVirtualAsWritten()) 777 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 778 if (WrittenVirtual != Method) 779 Diag(WrittenVirtual->getLocation(), 780 diag::note_overridden_virtual_function); 781 return false; 782 } 783 784 // - its return type shall be a literal type; 785 QualType RT = NewFD->getResultType(); 786 if (!RT->isDependentType() && 787 RequireLiteralType(NewFD->getLocation(), RT, 788 diag::err_constexpr_non_literal_return)) 789 return false; 790 } 791 792 // - each of its parameter types shall be a literal type; 793 if (!CheckConstexprParameterTypes(*this, NewFD)) 794 return false; 795 796 return true; 797} 798 799/// Check the given declaration statement is legal within a constexpr function 800/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 801/// 802/// \return true if the body is OK (maybe only as an extension), false if we 803/// have diagnosed a problem. 804static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 805 DeclStmt *DS, SourceLocation &Cxx1yLoc) { 806 // C++11 [dcl.constexpr]p3 and p4: 807 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 808 // contain only 809 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(), 810 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) { 811 switch ((*DclIt)->getKind()) { 812 case Decl::StaticAssert: 813 case Decl::Using: 814 case Decl::UsingShadow: 815 case Decl::UsingDirective: 816 case Decl::UnresolvedUsingTypename: 817 case Decl::UnresolvedUsingValue: 818 // - static_assert-declarations 819 // - using-declarations, 820 // - using-directives, 821 continue; 822 823 case Decl::Typedef: 824 case Decl::TypeAlias: { 825 // - typedef declarations and alias-declarations that do not define 826 // classes or enumerations, 827 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt); 828 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 829 // Don't allow variably-modified types in constexpr functions. 830 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 831 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 832 << TL.getSourceRange() << TL.getType() 833 << isa<CXXConstructorDecl>(Dcl); 834 return false; 835 } 836 continue; 837 } 838 839 case Decl::Enum: 840 case Decl::CXXRecord: 841 // C++1y allows types to be defined, not just declared. 842 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) 843 SemaRef.Diag(DS->getLocStart(), 844 SemaRef.getLangOpts().CPlusPlus1y 845 ? diag::warn_cxx11_compat_constexpr_type_definition 846 : diag::ext_constexpr_type_definition) 847 << isa<CXXConstructorDecl>(Dcl); 848 continue; 849 850 case Decl::EnumConstant: 851 case Decl::IndirectField: 852 case Decl::ParmVar: 853 // These can only appear with other declarations which are banned in 854 // C++11 and permitted in C++1y, so ignore them. 855 continue; 856 857 case Decl::Var: { 858 // C++1y [dcl.constexpr]p3 allows anything except: 859 // a definition of a variable of non-literal type or of static or 860 // thread storage duration or for which no initialization is performed. 861 VarDecl *VD = cast<VarDecl>(*DclIt); 862 if (VD->isThisDeclarationADefinition()) { 863 if (VD->isStaticLocal()) { 864 SemaRef.Diag(VD->getLocation(), 865 diag::err_constexpr_local_var_static) 866 << isa<CXXConstructorDecl>(Dcl) 867 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 868 return false; 869 } 870 if (!VD->getType()->isDependentType() && 871 SemaRef.RequireLiteralType( 872 VD->getLocation(), VD->getType(), 873 diag::err_constexpr_local_var_non_literal_type, 874 isa<CXXConstructorDecl>(Dcl))) 875 return false; 876 if (!VD->hasInit()) { 877 SemaRef.Diag(VD->getLocation(), 878 diag::err_constexpr_local_var_no_init) 879 << isa<CXXConstructorDecl>(Dcl); 880 return false; 881 } 882 } 883 SemaRef.Diag(VD->getLocation(), 884 SemaRef.getLangOpts().CPlusPlus1y 885 ? diag::warn_cxx11_compat_constexpr_local_var 886 : diag::ext_constexpr_local_var) 887 << isa<CXXConstructorDecl>(Dcl); 888 continue; 889 } 890 891 case Decl::NamespaceAlias: 892 case Decl::Function: 893 // These are disallowed in C++11 and permitted in C++1y. Allow them 894 // everywhere as an extension. 895 if (!Cxx1yLoc.isValid()) 896 Cxx1yLoc = DS->getLocStart(); 897 continue; 898 899 default: 900 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt) 901 << isa<CXXConstructorDecl>(Dcl); 902 return false; 903 } 904 } 905 906 return true; 907} 908 909/// Check that the given field is initialized within a constexpr constructor. 910/// 911/// \param Dcl The constexpr constructor being checked. 912/// \param Field The field being checked. This may be a member of an anonymous 913/// struct or union nested within the class being checked. 914/// \param Inits All declarations, including anonymous struct/union members and 915/// indirect members, for which any initialization was provided. 916/// \param Diagnosed Set to true if an error is produced. 917static void CheckConstexprCtorInitializer(Sema &SemaRef, 918 const FunctionDecl *Dcl, 919 FieldDecl *Field, 920 llvm::SmallSet<Decl*, 16> &Inits, 921 bool &Diagnosed) { 922 if (Field->isUnnamedBitfield()) 923 return; 924 925 if (Field->isAnonymousStructOrUnion() && 926 Field->getType()->getAsCXXRecordDecl()->isEmpty()) 927 return; 928 929 if (!Inits.count(Field)) { 930 if (!Diagnosed) { 931 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init); 932 Diagnosed = true; 933 } 934 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init); 935 } else if (Field->isAnonymousStructOrUnion()) { 936 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 937 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end(); 938 I != E; ++I) 939 // If an anonymous union contains an anonymous struct of which any member 940 // is initialized, all members must be initialized. 941 if (!RD->isUnion() || Inits.count(*I)) 942 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed); 943 } 944} 945 946/// Check the provided statement is allowed in a constexpr function 947/// definition. 948static bool 949CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 950 llvm::SmallVectorImpl<SourceLocation> &ReturnStmts, 951 SourceLocation &Cxx1yLoc) { 952 // - its function-body shall be [...] a compound-statement that contains only 953 switch (S->getStmtClass()) { 954 case Stmt::NullStmtClass: 955 // - null statements, 956 return true; 957 958 case Stmt::DeclStmtClass: 959 // - static_assert-declarations 960 // - using-declarations, 961 // - using-directives, 962 // - typedef declarations and alias-declarations that do not define 963 // classes or enumerations, 964 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc)) 965 return false; 966 return true; 967 968 case Stmt::ReturnStmtClass: 969 // - and exactly one return statement; 970 if (isa<CXXConstructorDecl>(Dcl)) { 971 // C++1y allows return statements in constexpr constructors. 972 if (!Cxx1yLoc.isValid()) 973 Cxx1yLoc = S->getLocStart(); 974 return true; 975 } 976 977 ReturnStmts.push_back(S->getLocStart()); 978 return true; 979 980 case Stmt::CompoundStmtClass: { 981 // C++1y allows compound-statements. 982 if (!Cxx1yLoc.isValid()) 983 Cxx1yLoc = S->getLocStart(); 984 985 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 986 for (CompoundStmt::body_iterator BodyIt = CompStmt->body_begin(), 987 BodyEnd = CompStmt->body_end(); BodyIt != BodyEnd; ++BodyIt) { 988 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, *BodyIt, ReturnStmts, 989 Cxx1yLoc)) 990 return false; 991 } 992 return true; 993 } 994 995 case Stmt::AttributedStmtClass: 996 if (!Cxx1yLoc.isValid()) 997 Cxx1yLoc = S->getLocStart(); 998 return true; 999 1000 case Stmt::IfStmtClass: { 1001 // C++1y allows if-statements. 1002 if (!Cxx1yLoc.isValid()) 1003 Cxx1yLoc = S->getLocStart(); 1004 1005 IfStmt *If = cast<IfStmt>(S); 1006 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 1007 Cxx1yLoc)) 1008 return false; 1009 if (If->getElse() && 1010 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 1011 Cxx1yLoc)) 1012 return false; 1013 return true; 1014 } 1015 1016 case Stmt::WhileStmtClass: 1017 case Stmt::DoStmtClass: 1018 case Stmt::ForStmtClass: 1019 case Stmt::CXXForRangeStmtClass: 1020 case Stmt::ContinueStmtClass: 1021 // C++1y allows all of these. We don't allow them as extensions in C++11, 1022 // because they don't make sense without variable mutation. 1023 if (!SemaRef.getLangOpts().CPlusPlus1y) 1024 break; 1025 if (!Cxx1yLoc.isValid()) 1026 Cxx1yLoc = S->getLocStart(); 1027 for (Stmt::child_range Children = S->children(); Children; ++Children) 1028 if (*Children && 1029 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts, 1030 Cxx1yLoc)) 1031 return false; 1032 return true; 1033 1034 case Stmt::SwitchStmtClass: 1035 case Stmt::CaseStmtClass: 1036 case Stmt::DefaultStmtClass: 1037 case Stmt::BreakStmtClass: 1038 // C++1y allows switch-statements, and since they don't need variable 1039 // mutation, we can reasonably allow them in C++11 as an extension. 1040 if (!Cxx1yLoc.isValid()) 1041 Cxx1yLoc = S->getLocStart(); 1042 for (Stmt::child_range Children = S->children(); Children; ++Children) 1043 if (*Children && 1044 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts, 1045 Cxx1yLoc)) 1046 return false; 1047 return true; 1048 1049 default: 1050 if (!isa<Expr>(S)) 1051 break; 1052 1053 // C++1y allows expression-statements. 1054 if (!Cxx1yLoc.isValid()) 1055 Cxx1yLoc = S->getLocStart(); 1056 return true; 1057 } 1058 1059 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt) 1060 << isa<CXXConstructorDecl>(Dcl); 1061 return false; 1062} 1063 1064/// Check the body for the given constexpr function declaration only contains 1065/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 1066/// 1067/// \return true if the body is OK, false if we have diagnosed a problem. 1068bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) { 1069 if (isa<CXXTryStmt>(Body)) { 1070 // C++11 [dcl.constexpr]p3: 1071 // The definition of a constexpr function shall satisfy the following 1072 // constraints: [...] 1073 // - its function-body shall be = delete, = default, or a 1074 // compound-statement 1075 // 1076 // C++11 [dcl.constexpr]p4: 1077 // In the definition of a constexpr constructor, [...] 1078 // - its function-body shall not be a function-try-block; 1079 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block) 1080 << isa<CXXConstructorDecl>(Dcl); 1081 return false; 1082 } 1083 1084 SmallVector<SourceLocation, 4> ReturnStmts; 1085 1086 // - its function-body shall be [...] a compound-statement that contains only 1087 // [... list of cases ...] 1088 CompoundStmt *CompBody = cast<CompoundStmt>(Body); 1089 SourceLocation Cxx1yLoc; 1090 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(), 1091 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) { 1092 if (!CheckConstexprFunctionStmt(*this, Dcl, *BodyIt, ReturnStmts, Cxx1yLoc)) 1093 return false; 1094 } 1095 1096 if (Cxx1yLoc.isValid()) 1097 Diag(Cxx1yLoc, 1098 getLangOpts().CPlusPlus1y 1099 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 1100 : diag::ext_constexpr_body_invalid_stmt) 1101 << isa<CXXConstructorDecl>(Dcl); 1102 1103 if (const CXXConstructorDecl *Constructor 1104 = dyn_cast<CXXConstructorDecl>(Dcl)) { 1105 const CXXRecordDecl *RD = Constructor->getParent(); 1106 // DR1359: 1107 // - every non-variant non-static data member and base class sub-object 1108 // shall be initialized; 1109 // - if the class is a non-empty union, or for each non-empty anonymous 1110 // union member of a non-union class, exactly one non-static data member 1111 // shall be initialized; 1112 if (RD->isUnion()) { 1113 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) { 1114 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init); 1115 return false; 1116 } 1117 } else if (!Constructor->isDependentContext() && 1118 !Constructor->isDelegatingConstructor()) { 1119 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 1120 1121 // Skip detailed checking if we have enough initializers, and we would 1122 // allow at most one initializer per member. 1123 bool AnyAnonStructUnionMembers = false; 1124 unsigned Fields = 0; 1125 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 1126 E = RD->field_end(); I != E; ++I, ++Fields) { 1127 if (I->isAnonymousStructOrUnion()) { 1128 AnyAnonStructUnionMembers = true; 1129 break; 1130 } 1131 } 1132 if (AnyAnonStructUnionMembers || 1133 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 1134 // Check initialization of non-static data members. Base classes are 1135 // always initialized so do not need to be checked. Dependent bases 1136 // might not have initializers in the member initializer list. 1137 llvm::SmallSet<Decl*, 16> Inits; 1138 for (CXXConstructorDecl::init_const_iterator 1139 I = Constructor->init_begin(), E = Constructor->init_end(); 1140 I != E; ++I) { 1141 if (FieldDecl *FD = (*I)->getMember()) 1142 Inits.insert(FD); 1143 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember()) 1144 Inits.insert(ID->chain_begin(), ID->chain_end()); 1145 } 1146 1147 bool Diagnosed = false; 1148 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 1149 E = RD->field_end(); I != E; ++I) 1150 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed); 1151 if (Diagnosed) 1152 return false; 1153 } 1154 } 1155 } else { 1156 if (ReturnStmts.empty()) { 1157 // C++1y doesn't require constexpr functions to contain a 'return' 1158 // statement. We still do, unless the return type is void, because 1159 // otherwise if there's no return statement, the function cannot 1160 // be used in a core constant expression. 1161 bool OK = getLangOpts().CPlusPlus1y && Dcl->getResultType()->isVoidType(); 1162 Diag(Dcl->getLocation(), 1163 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 1164 : diag::err_constexpr_body_no_return); 1165 return OK; 1166 } 1167 if (ReturnStmts.size() > 1) { 1168 Diag(ReturnStmts.back(), 1169 getLangOpts().CPlusPlus1y 1170 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 1171 : diag::ext_constexpr_body_multiple_return); 1172 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 1173 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return); 1174 } 1175 } 1176 1177 // C++11 [dcl.constexpr]p5: 1178 // if no function argument values exist such that the function invocation 1179 // substitution would produce a constant expression, the program is 1180 // ill-formed; no diagnostic required. 1181 // C++11 [dcl.constexpr]p3: 1182 // - every constructor call and implicit conversion used in initializing the 1183 // return value shall be one of those allowed in a constant expression. 1184 // C++11 [dcl.constexpr]p4: 1185 // - every constructor involved in initializing non-static data members and 1186 // base class sub-objects shall be a constexpr constructor. 1187 SmallVector<PartialDiagnosticAt, 8> Diags; 1188 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) { 1189 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr) 1190 << isa<CXXConstructorDecl>(Dcl); 1191 for (size_t I = 0, N = Diags.size(); I != N; ++I) 1192 Diag(Diags[I].first, Diags[I].second); 1193 // Don't return false here: we allow this for compatibility in 1194 // system headers. 1195 } 1196 1197 return true; 1198} 1199 1200/// isCurrentClassName - Determine whether the identifier II is the 1201/// name of the class type currently being defined. In the case of 1202/// nested classes, this will only return true if II is the name of 1203/// the innermost class. 1204bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 1205 const CXXScopeSpec *SS) { 1206 assert(getLangOpts().CPlusPlus && "No class names in C!"); 1207 1208 CXXRecordDecl *CurDecl; 1209 if (SS && SS->isSet() && !SS->isInvalid()) { 1210 DeclContext *DC = computeDeclContext(*SS, true); 1211 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 1212 } else 1213 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1214 1215 if (CurDecl && CurDecl->getIdentifier()) 1216 return &II == CurDecl->getIdentifier(); 1217 else 1218 return false; 1219} 1220 1221/// \brief Determine whether the given class is a base class of the given 1222/// class, including looking at dependent bases. 1223static bool findCircularInheritance(const CXXRecordDecl *Class, 1224 const CXXRecordDecl *Current) { 1225 SmallVector<const CXXRecordDecl*, 8> Queue; 1226 1227 Class = Class->getCanonicalDecl(); 1228 while (true) { 1229 for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(), 1230 E = Current->bases_end(); 1231 I != E; ++I) { 1232 CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 1233 if (!Base) 1234 continue; 1235 1236 Base = Base->getDefinition(); 1237 if (!Base) 1238 continue; 1239 1240 if (Base->getCanonicalDecl() == Class) 1241 return true; 1242 1243 Queue.push_back(Base); 1244 } 1245 1246 if (Queue.empty()) 1247 return false; 1248 1249 Current = Queue.back(); 1250 Queue.pop_back(); 1251 } 1252 1253 return false; 1254} 1255 1256/// \brief Check the validity of a C++ base class specifier. 1257/// 1258/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 1259/// and returns NULL otherwise. 1260CXXBaseSpecifier * 1261Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 1262 SourceRange SpecifierRange, 1263 bool Virtual, AccessSpecifier Access, 1264 TypeSourceInfo *TInfo, 1265 SourceLocation EllipsisLoc) { 1266 QualType BaseType = TInfo->getType(); 1267 1268 // C++ [class.union]p1: 1269 // A union shall not have base classes. 1270 if (Class->isUnion()) { 1271 Diag(Class->getLocation(), diag::err_base_clause_on_union) 1272 << SpecifierRange; 1273 return 0; 1274 } 1275 1276 if (EllipsisLoc.isValid() && 1277 !TInfo->getType()->containsUnexpandedParameterPack()) { 1278 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 1279 << TInfo->getTypeLoc().getSourceRange(); 1280 EllipsisLoc = SourceLocation(); 1281 } 1282 1283 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 1284 1285 if (BaseType->isDependentType()) { 1286 // Make sure that we don't have circular inheritance among our dependent 1287 // bases. For non-dependent bases, the check for completeness below handles 1288 // this. 1289 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 1290 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 1291 ((BaseDecl = BaseDecl->getDefinition()) && 1292 findCircularInheritance(Class, BaseDecl))) { 1293 Diag(BaseLoc, diag::err_circular_inheritance) 1294 << BaseType << Context.getTypeDeclType(Class); 1295 1296 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 1297 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 1298 << BaseType; 1299 1300 return 0; 1301 } 1302 } 1303 1304 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1305 Class->getTagKind() == TTK_Class, 1306 Access, TInfo, EllipsisLoc); 1307 } 1308 1309 // Base specifiers must be record types. 1310 if (!BaseType->isRecordType()) { 1311 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 1312 return 0; 1313 } 1314 1315 // C++ [class.union]p1: 1316 // A union shall not be used as a base class. 1317 if (BaseType->isUnionType()) { 1318 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 1319 return 0; 1320 } 1321 1322 // C++ [class.derived]p2: 1323 // The class-name in a base-specifier shall not be an incompletely 1324 // defined class. 1325 if (RequireCompleteType(BaseLoc, BaseType, 1326 diag::err_incomplete_base_class, SpecifierRange)) { 1327 Class->setInvalidDecl(); 1328 return 0; 1329 } 1330 1331 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 1332 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 1333 assert(BaseDecl && "Record type has no declaration"); 1334 BaseDecl = BaseDecl->getDefinition(); 1335 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 1336 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 1337 assert(CXXBaseDecl && "Base type is not a C++ type"); 1338 1339 // C++ [class]p3: 1340 // If a class is marked final and it appears as a base-type-specifier in 1341 // base-clause, the program is ill-formed. 1342 if (CXXBaseDecl->hasAttr<FinalAttr>()) { 1343 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 1344 << CXXBaseDecl->getDeclName(); 1345 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl) 1346 << CXXBaseDecl->getDeclName(); 1347 return 0; 1348 } 1349 1350 if (BaseDecl->isInvalidDecl()) 1351 Class->setInvalidDecl(); 1352 1353 // Create the base specifier. 1354 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1355 Class->getTagKind() == TTK_Class, 1356 Access, TInfo, EllipsisLoc); 1357} 1358 1359/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 1360/// one entry in the base class list of a class specifier, for 1361/// example: 1362/// class foo : public bar, virtual private baz { 1363/// 'public bar' and 'virtual private baz' are each base-specifiers. 1364BaseResult 1365Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 1366 ParsedAttributes &Attributes, 1367 bool Virtual, AccessSpecifier Access, 1368 ParsedType basetype, SourceLocation BaseLoc, 1369 SourceLocation EllipsisLoc) { 1370 if (!classdecl) 1371 return true; 1372 1373 AdjustDeclIfTemplate(classdecl); 1374 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 1375 if (!Class) 1376 return true; 1377 1378 // We do not support any C++11 attributes on base-specifiers yet. 1379 // Diagnose any attributes we see. 1380 if (!Attributes.empty()) { 1381 for (AttributeList *Attr = Attributes.getList(); Attr; 1382 Attr = Attr->getNext()) { 1383 if (Attr->isInvalid() || 1384 Attr->getKind() == AttributeList::IgnoredAttribute) 1385 continue; 1386 Diag(Attr->getLoc(), 1387 Attr->getKind() == AttributeList::UnknownAttribute 1388 ? diag::warn_unknown_attribute_ignored 1389 : diag::err_base_specifier_attribute) 1390 << Attr->getName(); 1391 } 1392 } 1393 1394 TypeSourceInfo *TInfo = 0; 1395 GetTypeFromParser(basetype, &TInfo); 1396 1397 if (EllipsisLoc.isInvalid() && 1398 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 1399 UPPC_BaseType)) 1400 return true; 1401 1402 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 1403 Virtual, Access, TInfo, 1404 EllipsisLoc)) 1405 return BaseSpec; 1406 else 1407 Class->setInvalidDecl(); 1408 1409 return true; 1410} 1411 1412/// \brief Performs the actual work of attaching the given base class 1413/// specifiers to a C++ class. 1414bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 1415 unsigned NumBases) { 1416 if (NumBases == 0) 1417 return false; 1418 1419 // Used to keep track of which base types we have already seen, so 1420 // that we can properly diagnose redundant direct base types. Note 1421 // that the key is always the unqualified canonical type of the base 1422 // class. 1423 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 1424 1425 // Copy non-redundant base specifiers into permanent storage. 1426 unsigned NumGoodBases = 0; 1427 bool Invalid = false; 1428 for (unsigned idx = 0; idx < NumBases; ++idx) { 1429 QualType NewBaseType 1430 = Context.getCanonicalType(Bases[idx]->getType()); 1431 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 1432 1433 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 1434 if (KnownBase) { 1435 // C++ [class.mi]p3: 1436 // A class shall not be specified as a direct base class of a 1437 // derived class more than once. 1438 Diag(Bases[idx]->getLocStart(), 1439 diag::err_duplicate_base_class) 1440 << KnownBase->getType() 1441 << Bases[idx]->getSourceRange(); 1442 1443 // Delete the duplicate base class specifier; we're going to 1444 // overwrite its pointer later. 1445 Context.Deallocate(Bases[idx]); 1446 1447 Invalid = true; 1448 } else { 1449 // Okay, add this new base class. 1450 KnownBase = Bases[idx]; 1451 Bases[NumGoodBases++] = Bases[idx]; 1452 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 1453 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 1454 if (Class->isInterface() && 1455 (!RD->isInterface() || 1456 KnownBase->getAccessSpecifier() != AS_public)) { 1457 // The Microsoft extension __interface does not permit bases that 1458 // are not themselves public interfaces. 1459 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface) 1460 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName() 1461 << RD->getSourceRange(); 1462 Invalid = true; 1463 } 1464 if (RD->hasAttr<WeakAttr>()) 1465 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context)); 1466 } 1467 } 1468 } 1469 1470 // Attach the remaining base class specifiers to the derived class. 1471 Class->setBases(Bases, NumGoodBases); 1472 1473 // Delete the remaining (good) base class specifiers, since their 1474 // data has been copied into the CXXRecordDecl. 1475 for (unsigned idx = 0; idx < NumGoodBases; ++idx) 1476 Context.Deallocate(Bases[idx]); 1477 1478 return Invalid; 1479} 1480 1481/// ActOnBaseSpecifiers - Attach the given base specifiers to the 1482/// class, after checking whether there are any duplicate base 1483/// classes. 1484void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases, 1485 unsigned NumBases) { 1486 if (!ClassDecl || !Bases || !NumBases) 1487 return; 1488 1489 AdjustDeclIfTemplate(ClassDecl); 1490 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), 1491 (CXXBaseSpecifier**)(Bases), NumBases); 1492} 1493 1494/// \brief Determine whether the type \p Derived is a C++ class that is 1495/// derived from the type \p Base. 1496bool Sema::IsDerivedFrom(QualType Derived, QualType Base) { 1497 if (!getLangOpts().CPlusPlus) 1498 return false; 1499 1500 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1501 if (!DerivedRD) 1502 return false; 1503 1504 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1505 if (!BaseRD) 1506 return false; 1507 1508 // If either the base or the derived type is invalid, don't try to 1509 // check whether one is derived from the other. 1510 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 1511 return false; 1512 1513 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this. 1514 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD); 1515} 1516 1517/// \brief Determine whether the type \p Derived is a C++ class that is 1518/// derived from the type \p Base. 1519bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) { 1520 if (!getLangOpts().CPlusPlus) 1521 return false; 1522 1523 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1524 if (!DerivedRD) 1525 return false; 1526 1527 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1528 if (!BaseRD) 1529 return false; 1530 1531 return DerivedRD->isDerivedFrom(BaseRD, Paths); 1532} 1533 1534void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 1535 CXXCastPath &BasePathArray) { 1536 assert(BasePathArray.empty() && "Base path array must be empty!"); 1537 assert(Paths.isRecordingPaths() && "Must record paths!"); 1538 1539 const CXXBasePath &Path = Paths.front(); 1540 1541 // We first go backward and check if we have a virtual base. 1542 // FIXME: It would be better if CXXBasePath had the base specifier for 1543 // the nearest virtual base. 1544 unsigned Start = 0; 1545 for (unsigned I = Path.size(); I != 0; --I) { 1546 if (Path[I - 1].Base->isVirtual()) { 1547 Start = I - 1; 1548 break; 1549 } 1550 } 1551 1552 // Now add all bases. 1553 for (unsigned I = Start, E = Path.size(); I != E; ++I) 1554 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 1555} 1556 1557/// \brief Determine whether the given base path includes a virtual 1558/// base class. 1559bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) { 1560 for (CXXCastPath::const_iterator B = BasePath.begin(), 1561 BEnd = BasePath.end(); 1562 B != BEnd; ++B) 1563 if ((*B)->isVirtual()) 1564 return true; 1565 1566 return false; 1567} 1568 1569/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 1570/// conversion (where Derived and Base are class types) is 1571/// well-formed, meaning that the conversion is unambiguous (and 1572/// that all of the base classes are accessible). Returns true 1573/// and emits a diagnostic if the code is ill-formed, returns false 1574/// otherwise. Loc is the location where this routine should point to 1575/// if there is an error, and Range is the source range to highlight 1576/// if there is an error. 1577bool 1578Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1579 unsigned InaccessibleBaseID, 1580 unsigned AmbigiousBaseConvID, 1581 SourceLocation Loc, SourceRange Range, 1582 DeclarationName Name, 1583 CXXCastPath *BasePath) { 1584 // First, determine whether the path from Derived to Base is 1585 // ambiguous. This is slightly more expensive than checking whether 1586 // the Derived to Base conversion exists, because here we need to 1587 // explore multiple paths to determine if there is an ambiguity. 1588 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1589 /*DetectVirtual=*/false); 1590 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths); 1591 assert(DerivationOkay && 1592 "Can only be used with a derived-to-base conversion"); 1593 (void)DerivationOkay; 1594 1595 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 1596 if (InaccessibleBaseID) { 1597 // Check that the base class can be accessed. 1598 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(), 1599 InaccessibleBaseID)) { 1600 case AR_inaccessible: 1601 return true; 1602 case AR_accessible: 1603 case AR_dependent: 1604 case AR_delayed: 1605 break; 1606 } 1607 } 1608 1609 // Build a base path if necessary. 1610 if (BasePath) 1611 BuildBasePathArray(Paths, *BasePath); 1612 return false; 1613 } 1614 1615 if (AmbigiousBaseConvID) { 1616 // We know that the derived-to-base conversion is ambiguous, and 1617 // we're going to produce a diagnostic. Perform the derived-to-base 1618 // search just one more time to compute all of the possible paths so 1619 // that we can print them out. This is more expensive than any of 1620 // the previous derived-to-base checks we've done, but at this point 1621 // performance isn't as much of an issue. 1622 Paths.clear(); 1623 Paths.setRecordingPaths(true); 1624 bool StillOkay = IsDerivedFrom(Derived, Base, Paths); 1625 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 1626 (void)StillOkay; 1627 1628 // Build up a textual representation of the ambiguous paths, e.g., 1629 // D -> B -> A, that will be used to illustrate the ambiguous 1630 // conversions in the diagnostic. We only print one of the paths 1631 // to each base class subobject. 1632 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 1633 1634 Diag(Loc, AmbigiousBaseConvID) 1635 << Derived << Base << PathDisplayStr << Range << Name; 1636 } 1637 return true; 1638} 1639 1640bool 1641Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1642 SourceLocation Loc, SourceRange Range, 1643 CXXCastPath *BasePath, 1644 bool IgnoreAccess) { 1645 return CheckDerivedToBaseConversion(Derived, Base, 1646 IgnoreAccess ? 0 1647 : diag::err_upcast_to_inaccessible_base, 1648 diag::err_ambiguous_derived_to_base_conv, 1649 Loc, Range, DeclarationName(), 1650 BasePath); 1651} 1652 1653 1654/// @brief Builds a string representing ambiguous paths from a 1655/// specific derived class to different subobjects of the same base 1656/// class. 1657/// 1658/// This function builds a string that can be used in error messages 1659/// to show the different paths that one can take through the 1660/// inheritance hierarchy to go from the derived class to different 1661/// subobjects of a base class. The result looks something like this: 1662/// @code 1663/// struct D -> struct B -> struct A 1664/// struct D -> struct C -> struct A 1665/// @endcode 1666std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 1667 std::string PathDisplayStr; 1668 std::set<unsigned> DisplayedPaths; 1669 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 1670 Path != Paths.end(); ++Path) { 1671 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 1672 // We haven't displayed a path to this particular base 1673 // class subobject yet. 1674 PathDisplayStr += "\n "; 1675 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 1676 for (CXXBasePath::const_iterator Element = Path->begin(); 1677 Element != Path->end(); ++Element) 1678 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 1679 } 1680 } 1681 1682 return PathDisplayStr; 1683} 1684 1685//===----------------------------------------------------------------------===// 1686// C++ class member Handling 1687//===----------------------------------------------------------------------===// 1688 1689/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 1690bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, 1691 SourceLocation ASLoc, 1692 SourceLocation ColonLoc, 1693 AttributeList *Attrs) { 1694 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 1695 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 1696 ASLoc, ColonLoc); 1697 CurContext->addHiddenDecl(ASDecl); 1698 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 1699} 1700 1701/// CheckOverrideControl - Check C++11 override control semantics. 1702void Sema::CheckOverrideControl(Decl *D) { 1703 if (D->isInvalidDecl()) 1704 return; 1705 1706 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 1707 1708 // Do we know which functions this declaration might be overriding? 1709 bool OverridesAreKnown = !MD || 1710 (!MD->getParent()->hasAnyDependentBases() && 1711 !MD->getType()->isDependentType()); 1712 1713 if (!MD || !MD->isVirtual()) { 1714 if (OverridesAreKnown) { 1715 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1716 Diag(OA->getLocation(), 1717 diag::override_keyword_only_allowed_on_virtual_member_functions) 1718 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 1719 D->dropAttr<OverrideAttr>(); 1720 } 1721 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1722 Diag(FA->getLocation(), 1723 diag::override_keyword_only_allowed_on_virtual_member_functions) 1724 << "final" << FixItHint::CreateRemoval(FA->getLocation()); 1725 D->dropAttr<FinalAttr>(); 1726 } 1727 } 1728 return; 1729 } 1730 1731 if (!OverridesAreKnown) 1732 return; 1733 1734 // C++11 [class.virtual]p5: 1735 // If a virtual function is marked with the virt-specifier override and 1736 // does not override a member function of a base class, the program is 1737 // ill-formed. 1738 bool HasOverriddenMethods = 1739 MD->begin_overridden_methods() != MD->end_overridden_methods(); 1740 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 1741 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 1742 << MD->getDeclName(); 1743} 1744 1745/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 1746/// function overrides a virtual member function marked 'final', according to 1747/// C++11 [class.virtual]p4. 1748bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 1749 const CXXMethodDecl *Old) { 1750 if (!Old->hasAttr<FinalAttr>()) 1751 return false; 1752 1753 Diag(New->getLocation(), diag::err_final_function_overridden) 1754 << New->getDeclName(); 1755 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 1756 return true; 1757} 1758 1759static bool InitializationHasSideEffects(const FieldDecl &FD) { 1760 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 1761 // FIXME: Destruction of ObjC lifetime types has side-effects. 1762 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 1763 return !RD->isCompleteDefinition() || 1764 !RD->hasTrivialDefaultConstructor() || 1765 !RD->hasTrivialDestructor(); 1766 return false; 1767} 1768 1769static AttributeList *getMSPropertyAttr(AttributeList *list) { 1770 for (AttributeList* it = list; it != 0; it = it->getNext()) 1771 if (it->isDeclspecPropertyAttribute()) 1772 return it; 1773 return 0; 1774} 1775 1776/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 1777/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 1778/// bitfield width if there is one, 'InitExpr' specifies the initializer if 1779/// one has been parsed, and 'InitStyle' is set if an in-class initializer is 1780/// present (but parsing it has been deferred). 1781NamedDecl * 1782Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 1783 MultiTemplateParamsArg TemplateParameterLists, 1784 Expr *BW, const VirtSpecifiers &VS, 1785 InClassInitStyle InitStyle) { 1786 const DeclSpec &DS = D.getDeclSpec(); 1787 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 1788 DeclarationName Name = NameInfo.getName(); 1789 SourceLocation Loc = NameInfo.getLoc(); 1790 1791 // For anonymous bitfields, the location should point to the type. 1792 if (Loc.isInvalid()) 1793 Loc = D.getLocStart(); 1794 1795 Expr *BitWidth = static_cast<Expr*>(BW); 1796 1797 assert(isa<CXXRecordDecl>(CurContext)); 1798 assert(!DS.isFriendSpecified()); 1799 1800 bool isFunc = D.isDeclarationOfFunction(); 1801 1802 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 1803 // The Microsoft extension __interface only permits public member functions 1804 // and prohibits constructors, destructors, operators, non-public member 1805 // functions, static methods and data members. 1806 unsigned InvalidDecl; 1807 bool ShowDeclName = true; 1808 if (!isFunc) 1809 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1; 1810 else if (AS != AS_public) 1811 InvalidDecl = 2; 1812 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 1813 InvalidDecl = 3; 1814 else switch (Name.getNameKind()) { 1815 case DeclarationName::CXXConstructorName: 1816 InvalidDecl = 4; 1817 ShowDeclName = false; 1818 break; 1819 1820 case DeclarationName::CXXDestructorName: 1821 InvalidDecl = 5; 1822 ShowDeclName = false; 1823 break; 1824 1825 case DeclarationName::CXXOperatorName: 1826 case DeclarationName::CXXConversionFunctionName: 1827 InvalidDecl = 6; 1828 break; 1829 1830 default: 1831 InvalidDecl = 0; 1832 break; 1833 } 1834 1835 if (InvalidDecl) { 1836 if (ShowDeclName) 1837 Diag(Loc, diag::err_invalid_member_in_interface) 1838 << (InvalidDecl-1) << Name; 1839 else 1840 Diag(Loc, diag::err_invalid_member_in_interface) 1841 << (InvalidDecl-1) << ""; 1842 return 0; 1843 } 1844 } 1845 1846 // C++ 9.2p6: A member shall not be declared to have automatic storage 1847 // duration (auto, register) or with the extern storage-class-specifier. 1848 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 1849 // data members and cannot be applied to names declared const or static, 1850 // and cannot be applied to reference members. 1851 switch (DS.getStorageClassSpec()) { 1852 case DeclSpec::SCS_unspecified: 1853 case DeclSpec::SCS_typedef: 1854 case DeclSpec::SCS_static: 1855 break; 1856 case DeclSpec::SCS_mutable: 1857 if (isFunc) { 1858 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 1859 1860 // FIXME: It would be nicer if the keyword was ignored only for this 1861 // declarator. Otherwise we could get follow-up errors. 1862 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1863 } 1864 break; 1865 default: 1866 Diag(DS.getStorageClassSpecLoc(), 1867 diag::err_storageclass_invalid_for_member); 1868 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1869 break; 1870 } 1871 1872 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 1873 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 1874 !isFunc); 1875 1876 if (DS.isConstexprSpecified() && isInstField) { 1877 SemaDiagnosticBuilder B = 1878 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 1879 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 1880 if (InitStyle == ICIS_NoInit) { 1881 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const"); 1882 D.getMutableDeclSpec().ClearConstexprSpec(); 1883 const char *PrevSpec; 1884 unsigned DiagID; 1885 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc, 1886 PrevSpec, DiagID, getLangOpts()); 1887 (void)Failed; 1888 assert(!Failed && "Making a constexpr member const shouldn't fail"); 1889 } else { 1890 B << 1; 1891 const char *PrevSpec; 1892 unsigned DiagID; 1893 if (D.getMutableDeclSpec().SetStorageClassSpec( 1894 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) { 1895 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 1896 "This is the only DeclSpec that should fail to be applied"); 1897 B << 1; 1898 } else { 1899 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 1900 isInstField = false; 1901 } 1902 } 1903 } 1904 1905 NamedDecl *Member; 1906 if (isInstField) { 1907 CXXScopeSpec &SS = D.getCXXScopeSpec(); 1908 1909 // Data members must have identifiers for names. 1910 if (!Name.isIdentifier()) { 1911 Diag(Loc, diag::err_bad_variable_name) 1912 << Name; 1913 return 0; 1914 } 1915 1916 IdentifierInfo *II = Name.getAsIdentifierInfo(); 1917 1918 // Member field could not be with "template" keyword. 1919 // So TemplateParameterLists should be empty in this case. 1920 if (TemplateParameterLists.size()) { 1921 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 1922 if (TemplateParams->size()) { 1923 // There is no such thing as a member field template. 1924 Diag(D.getIdentifierLoc(), diag::err_template_member) 1925 << II 1926 << SourceRange(TemplateParams->getTemplateLoc(), 1927 TemplateParams->getRAngleLoc()); 1928 } else { 1929 // There is an extraneous 'template<>' for this member. 1930 Diag(TemplateParams->getTemplateLoc(), 1931 diag::err_template_member_noparams) 1932 << II 1933 << SourceRange(TemplateParams->getTemplateLoc(), 1934 TemplateParams->getRAngleLoc()); 1935 } 1936 return 0; 1937 } 1938 1939 if (SS.isSet() && !SS.isInvalid()) { 1940 // The user provided a superfluous scope specifier inside a class 1941 // definition: 1942 // 1943 // class X { 1944 // int X::member; 1945 // }; 1946 if (DeclContext *DC = computeDeclContext(SS, false)) 1947 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc()); 1948 else 1949 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 1950 << Name << SS.getRange(); 1951 1952 SS.clear(); 1953 } 1954 1955 AttributeList *MSPropertyAttr = 1956 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList()); 1957 if (MSPropertyAttr) { 1958 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 1959 BitWidth, InitStyle, AS, MSPropertyAttr); 1960 isInstField = false; 1961 } else { 1962 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 1963 BitWidth, InitStyle, AS); 1964 } 1965 assert(Member && "HandleField never returns null"); 1966 } else { 1967 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static); 1968 1969 Member = HandleDeclarator(S, D, TemplateParameterLists); 1970 if (!Member) { 1971 return 0; 1972 } 1973 1974 // Non-instance-fields can't have a bitfield. 1975 if (BitWidth) { 1976 if (Member->isInvalidDecl()) { 1977 // don't emit another diagnostic. 1978 } else if (isa<VarDecl>(Member)) { 1979 // C++ 9.6p3: A bit-field shall not be a static member. 1980 // "static member 'A' cannot be a bit-field" 1981 Diag(Loc, diag::err_static_not_bitfield) 1982 << Name << BitWidth->getSourceRange(); 1983 } else if (isa<TypedefDecl>(Member)) { 1984 // "typedef member 'x' cannot be a bit-field" 1985 Diag(Loc, diag::err_typedef_not_bitfield) 1986 << Name << BitWidth->getSourceRange(); 1987 } else { 1988 // A function typedef ("typedef int f(); f a;"). 1989 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 1990 Diag(Loc, diag::err_not_integral_type_bitfield) 1991 << Name << cast<ValueDecl>(Member)->getType() 1992 << BitWidth->getSourceRange(); 1993 } 1994 1995 BitWidth = 0; 1996 Member->setInvalidDecl(); 1997 } 1998 1999 Member->setAccess(AS); 2000 2001 // If we have declared a member function template, set the access of the 2002 // templated declaration as well. 2003 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 2004 FunTmpl->getTemplatedDecl()->setAccess(AS); 2005 } 2006 2007 if (VS.isOverrideSpecified()) 2008 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context)); 2009 if (VS.isFinalSpecified()) 2010 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context)); 2011 2012 if (VS.getLastLocation().isValid()) { 2013 // Update the end location of a method that has a virt-specifiers. 2014 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 2015 MD->setRangeEnd(VS.getLastLocation()); 2016 } 2017 2018 CheckOverrideControl(Member); 2019 2020 assert((Name || isInstField) && "No identifier for non-field ?"); 2021 2022 if (isInstField) { 2023 FieldDecl *FD = cast<FieldDecl>(Member); 2024 FieldCollector->Add(FD); 2025 2026 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field, 2027 FD->getLocation()) 2028 != DiagnosticsEngine::Ignored) { 2029 // Remember all explicit private FieldDecls that have a name, no side 2030 // effects and are not part of a dependent type declaration. 2031 if (!FD->isImplicit() && FD->getDeclName() && 2032 FD->getAccess() == AS_private && 2033 !FD->hasAttr<UnusedAttr>() && 2034 !FD->getParent()->isDependentContext() && 2035 !InitializationHasSideEffects(*FD)) 2036 UnusedPrivateFields.insert(FD); 2037 } 2038 } 2039 2040 return Member; 2041} 2042 2043namespace { 2044 class UninitializedFieldVisitor 2045 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 2046 Sema &S; 2047 ValueDecl *VD; 2048 public: 2049 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 2050 UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context), 2051 S(S) { 2052 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD)) 2053 this->VD = IFD->getAnonField(); 2054 else 2055 this->VD = VD; 2056 } 2057 2058 void HandleExpr(Expr *E) { 2059 if (!E) return; 2060 2061 // Expressions like x(x) sometimes lack the surrounding expressions 2062 // but need to be checked anyways. 2063 HandleValue(E); 2064 Visit(E); 2065 } 2066 2067 void HandleValue(Expr *E) { 2068 E = E->IgnoreParens(); 2069 2070 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 2071 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 2072 return; 2073 2074 // FieldME is the inner-most MemberExpr that is not an anonymous struct 2075 // or union. 2076 MemberExpr *FieldME = ME; 2077 2078 Expr *Base = E; 2079 while (isa<MemberExpr>(Base)) { 2080 ME = cast<MemberExpr>(Base); 2081 2082 if (isa<VarDecl>(ME->getMemberDecl())) 2083 return; 2084 2085 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 2086 if (!FD->isAnonymousStructOrUnion()) 2087 FieldME = ME; 2088 2089 Base = ME->getBase(); 2090 } 2091 2092 if (VD == FieldME->getMemberDecl() && isa<CXXThisExpr>(Base)) { 2093 unsigned diag = VD->getType()->isReferenceType() 2094 ? diag::warn_reference_field_is_uninit 2095 : diag::warn_field_is_uninit; 2096 S.Diag(FieldME->getExprLoc(), diag) << VD; 2097 } 2098 return; 2099 } 2100 2101 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 2102 HandleValue(CO->getTrueExpr()); 2103 HandleValue(CO->getFalseExpr()); 2104 return; 2105 } 2106 2107 if (BinaryConditionalOperator *BCO = 2108 dyn_cast<BinaryConditionalOperator>(E)) { 2109 HandleValue(BCO->getCommon()); 2110 HandleValue(BCO->getFalseExpr()); 2111 return; 2112 } 2113 2114 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 2115 switch (BO->getOpcode()) { 2116 default: 2117 return; 2118 case(BO_PtrMemD): 2119 case(BO_PtrMemI): 2120 HandleValue(BO->getLHS()); 2121 return; 2122 case(BO_Comma): 2123 HandleValue(BO->getRHS()); 2124 return; 2125 } 2126 } 2127 } 2128 2129 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 2130 if (E->getCastKind() == CK_LValueToRValue) 2131 HandleValue(E->getSubExpr()); 2132 2133 Inherited::VisitImplicitCastExpr(E); 2134 } 2135 2136 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 2137 Expr *Callee = E->getCallee(); 2138 if (isa<MemberExpr>(Callee)) 2139 HandleValue(Callee); 2140 2141 Inherited::VisitCXXMemberCallExpr(E); 2142 } 2143 }; 2144 static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E, 2145 ValueDecl *VD) { 2146 UninitializedFieldVisitor(S, VD).HandleExpr(E); 2147 } 2148} // namespace 2149 2150/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an 2151/// in-class initializer for a non-static C++ class member, and after 2152/// instantiating an in-class initializer in a class template. Such actions 2153/// are deferred until the class is complete. 2154void 2155Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc, 2156 Expr *InitExpr) { 2157 FieldDecl *FD = cast<FieldDecl>(D); 2158 assert(FD->getInClassInitStyle() != ICIS_NoInit && 2159 "must set init style when field is created"); 2160 2161 if (!InitExpr) { 2162 FD->setInvalidDecl(); 2163 FD->removeInClassInitializer(); 2164 return; 2165 } 2166 2167 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 2168 FD->setInvalidDecl(); 2169 FD->removeInClassInitializer(); 2170 return; 2171 } 2172 2173 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, InitLoc) 2174 != DiagnosticsEngine::Ignored) { 2175 CheckInitExprContainsUninitializedFields(*this, InitExpr, FD); 2176 } 2177 2178 ExprResult Init = InitExpr; 2179 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 2180 InitializedEntity Entity = InitializedEntity::InitializeMember(FD); 2181 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit 2182 ? InitializationKind::CreateDirectList(InitExpr->getLocStart()) 2183 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc); 2184 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 2185 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 2186 if (Init.isInvalid()) { 2187 FD->setInvalidDecl(); 2188 return; 2189 } 2190 } 2191 2192 // C++11 [class.base.init]p7: 2193 // The initialization of each base and member constitutes a 2194 // full-expression. 2195 Init = ActOnFinishFullExpr(Init.take(), InitLoc); 2196 if (Init.isInvalid()) { 2197 FD->setInvalidDecl(); 2198 return; 2199 } 2200 2201 InitExpr = Init.release(); 2202 2203 FD->setInClassInitializer(InitExpr); 2204} 2205 2206/// \brief Find the direct and/or virtual base specifiers that 2207/// correspond to the given base type, for use in base initialization 2208/// within a constructor. 2209static bool FindBaseInitializer(Sema &SemaRef, 2210 CXXRecordDecl *ClassDecl, 2211 QualType BaseType, 2212 const CXXBaseSpecifier *&DirectBaseSpec, 2213 const CXXBaseSpecifier *&VirtualBaseSpec) { 2214 // First, check for a direct base class. 2215 DirectBaseSpec = 0; 2216 for (CXXRecordDecl::base_class_const_iterator Base 2217 = ClassDecl->bases_begin(); 2218 Base != ClassDecl->bases_end(); ++Base) { 2219 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) { 2220 // We found a direct base of this type. That's what we're 2221 // initializing. 2222 DirectBaseSpec = &*Base; 2223 break; 2224 } 2225 } 2226 2227 // Check for a virtual base class. 2228 // FIXME: We might be able to short-circuit this if we know in advance that 2229 // there are no virtual bases. 2230 VirtualBaseSpec = 0; 2231 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 2232 // We haven't found a base yet; search the class hierarchy for a 2233 // virtual base class. 2234 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2235 /*DetectVirtual=*/false); 2236 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl), 2237 BaseType, Paths)) { 2238 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2239 Path != Paths.end(); ++Path) { 2240 if (Path->back().Base->isVirtual()) { 2241 VirtualBaseSpec = Path->back().Base; 2242 break; 2243 } 2244 } 2245 } 2246 } 2247 2248 return DirectBaseSpec || VirtualBaseSpec; 2249} 2250 2251/// \brief Handle a C++ member initializer using braced-init-list syntax. 2252MemInitResult 2253Sema::ActOnMemInitializer(Decl *ConstructorD, 2254 Scope *S, 2255 CXXScopeSpec &SS, 2256 IdentifierInfo *MemberOrBase, 2257 ParsedType TemplateTypeTy, 2258 const DeclSpec &DS, 2259 SourceLocation IdLoc, 2260 Expr *InitList, 2261 SourceLocation EllipsisLoc) { 2262 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2263 DS, IdLoc, InitList, 2264 EllipsisLoc); 2265} 2266 2267/// \brief Handle a C++ member initializer using parentheses syntax. 2268MemInitResult 2269Sema::ActOnMemInitializer(Decl *ConstructorD, 2270 Scope *S, 2271 CXXScopeSpec &SS, 2272 IdentifierInfo *MemberOrBase, 2273 ParsedType TemplateTypeTy, 2274 const DeclSpec &DS, 2275 SourceLocation IdLoc, 2276 SourceLocation LParenLoc, 2277 ArrayRef<Expr *> Args, 2278 SourceLocation RParenLoc, 2279 SourceLocation EllipsisLoc) { 2280 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, 2281 Args, RParenLoc); 2282 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2283 DS, IdLoc, List, EllipsisLoc); 2284} 2285 2286namespace { 2287 2288// Callback to only accept typo corrections that can be a valid C++ member 2289// intializer: either a non-static field member or a base class. 2290class MemInitializerValidatorCCC : public CorrectionCandidateCallback { 2291 public: 2292 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 2293 : ClassDecl(ClassDecl) {} 2294 2295 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 2296 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 2297 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 2298 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 2299 else 2300 return isa<TypeDecl>(ND); 2301 } 2302 return false; 2303 } 2304 2305 private: 2306 CXXRecordDecl *ClassDecl; 2307}; 2308 2309} 2310 2311/// \brief Handle a C++ member initializer. 2312MemInitResult 2313Sema::BuildMemInitializer(Decl *ConstructorD, 2314 Scope *S, 2315 CXXScopeSpec &SS, 2316 IdentifierInfo *MemberOrBase, 2317 ParsedType TemplateTypeTy, 2318 const DeclSpec &DS, 2319 SourceLocation IdLoc, 2320 Expr *Init, 2321 SourceLocation EllipsisLoc) { 2322 if (!ConstructorD) 2323 return true; 2324 2325 AdjustDeclIfTemplate(ConstructorD); 2326 2327 CXXConstructorDecl *Constructor 2328 = dyn_cast<CXXConstructorDecl>(ConstructorD); 2329 if (!Constructor) { 2330 // The user wrote a constructor initializer on a function that is 2331 // not a C++ constructor. Ignore the error for now, because we may 2332 // have more member initializers coming; we'll diagnose it just 2333 // once in ActOnMemInitializers. 2334 return true; 2335 } 2336 2337 CXXRecordDecl *ClassDecl = Constructor->getParent(); 2338 2339 // C++ [class.base.init]p2: 2340 // Names in a mem-initializer-id are looked up in the scope of the 2341 // constructor's class and, if not found in that scope, are looked 2342 // up in the scope containing the constructor's definition. 2343 // [Note: if the constructor's class contains a member with the 2344 // same name as a direct or virtual base class of the class, a 2345 // mem-initializer-id naming the member or base class and composed 2346 // of a single identifier refers to the class member. A 2347 // mem-initializer-id for the hidden base class may be specified 2348 // using a qualified name. ] 2349 if (!SS.getScopeRep() && !TemplateTypeTy) { 2350 // Look for a member, first. 2351 DeclContext::lookup_result Result 2352 = ClassDecl->lookup(MemberOrBase); 2353 if (!Result.empty()) { 2354 ValueDecl *Member; 2355 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 2356 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) { 2357 if (EllipsisLoc.isValid()) 2358 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 2359 << MemberOrBase 2360 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 2361 2362 return BuildMemberInitializer(Member, Init, IdLoc); 2363 } 2364 } 2365 } 2366 // It didn't name a member, so see if it names a class. 2367 QualType BaseType; 2368 TypeSourceInfo *TInfo = 0; 2369 2370 if (TemplateTypeTy) { 2371 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 2372 } else if (DS.getTypeSpecType() == TST_decltype) { 2373 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 2374 } else { 2375 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 2376 LookupParsedName(R, S, &SS); 2377 2378 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 2379 if (!TyD) { 2380 if (R.isAmbiguous()) return true; 2381 2382 // We don't want access-control diagnostics here. 2383 R.suppressDiagnostics(); 2384 2385 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 2386 bool NotUnknownSpecialization = false; 2387 DeclContext *DC = computeDeclContext(SS, false); 2388 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 2389 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 2390 2391 if (!NotUnknownSpecialization) { 2392 // When the scope specifier can refer to a member of an unknown 2393 // specialization, we take it as a type name. 2394 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 2395 SS.getWithLocInContext(Context), 2396 *MemberOrBase, IdLoc); 2397 if (BaseType.isNull()) 2398 return true; 2399 2400 R.clear(); 2401 R.setLookupName(MemberOrBase); 2402 } 2403 } 2404 2405 // If no results were found, try to correct typos. 2406 TypoCorrection Corr; 2407 MemInitializerValidatorCCC Validator(ClassDecl); 2408 if (R.empty() && BaseType.isNull() && 2409 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 2410 Validator, ClassDecl))) { 2411 std::string CorrectedStr(Corr.getAsString(getLangOpts())); 2412 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts())); 2413 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 2414 // We have found a non-static data member with a similar 2415 // name to what was typed; complain and initialize that 2416 // member. 2417 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest) 2418 << MemberOrBase << true << CorrectedQuotedStr 2419 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr); 2420 Diag(Member->getLocation(), diag::note_previous_decl) 2421 << CorrectedQuotedStr; 2422 2423 return BuildMemberInitializer(Member, Init, IdLoc); 2424 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 2425 const CXXBaseSpecifier *DirectBaseSpec; 2426 const CXXBaseSpecifier *VirtualBaseSpec; 2427 if (FindBaseInitializer(*this, ClassDecl, 2428 Context.getTypeDeclType(Type), 2429 DirectBaseSpec, VirtualBaseSpec)) { 2430 // We have found a direct or virtual base class with a 2431 // similar name to what was typed; complain and initialize 2432 // that base class. 2433 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest) 2434 << MemberOrBase << false << CorrectedQuotedStr 2435 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr); 2436 2437 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec 2438 : VirtualBaseSpec; 2439 Diag(BaseSpec->getLocStart(), 2440 diag::note_base_class_specified_here) 2441 << BaseSpec->getType() 2442 << BaseSpec->getSourceRange(); 2443 2444 TyD = Type; 2445 } 2446 } 2447 } 2448 2449 if (!TyD && BaseType.isNull()) { 2450 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 2451 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 2452 return true; 2453 } 2454 } 2455 2456 if (BaseType.isNull()) { 2457 BaseType = Context.getTypeDeclType(TyD); 2458 if (SS.isSet()) { 2459 NestedNameSpecifier *Qualifier = 2460 static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 2461 2462 // FIXME: preserve source range information 2463 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType); 2464 } 2465 } 2466 } 2467 2468 if (!TInfo) 2469 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 2470 2471 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 2472} 2473 2474/// Checks a member initializer expression for cases where reference (or 2475/// pointer) members are bound to by-value parameters (or their addresses). 2476static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member, 2477 Expr *Init, 2478 SourceLocation IdLoc) { 2479 QualType MemberTy = Member->getType(); 2480 2481 // We only handle pointers and references currently. 2482 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers? 2483 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType()) 2484 return; 2485 2486 const bool IsPointer = MemberTy->isPointerType(); 2487 if (IsPointer) { 2488 if (const UnaryOperator *Op 2489 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) { 2490 // The only case we're worried about with pointers requires taking the 2491 // address. 2492 if (Op->getOpcode() != UO_AddrOf) 2493 return; 2494 2495 Init = Op->getSubExpr(); 2496 } else { 2497 // We only handle address-of expression initializers for pointers. 2498 return; 2499 } 2500 } 2501 2502 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) { 2503 // We only warn when referring to a non-reference parameter declaration. 2504 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl()); 2505 if (!Parameter || Parameter->getType()->isReferenceType()) 2506 return; 2507 2508 S.Diag(Init->getExprLoc(), 2509 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr 2510 : diag::warn_bind_ref_member_to_parameter) 2511 << Member << Parameter << Init->getSourceRange(); 2512 } else { 2513 // Other initializers are fine. 2514 return; 2515 } 2516 2517 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here) 2518 << (unsigned)IsPointer; 2519} 2520 2521MemInitResult 2522Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 2523 SourceLocation IdLoc) { 2524 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 2525 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 2526 assert((DirectMember || IndirectMember) && 2527 "Member must be a FieldDecl or IndirectFieldDecl"); 2528 2529 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 2530 return true; 2531 2532 if (Member->isInvalidDecl()) 2533 return true; 2534 2535 // Diagnose value-uses of fields to initialize themselves, e.g. 2536 // foo(foo) 2537 // where foo is not also a parameter to the constructor. 2538 // TODO: implement -Wuninitialized and fold this into that framework. 2539 MultiExprArg Args; 2540 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2541 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 2542 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 2543 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 2544 } else { 2545 // Template instantiation doesn't reconstruct ParenListExprs for us. 2546 Args = Init; 2547 } 2548 2549 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc) 2550 != DiagnosticsEngine::Ignored) 2551 for (unsigned i = 0, e = Args.size(); i != e; ++i) 2552 // FIXME: Warn about the case when other fields are used before being 2553 // initialized. For example, let this field be the i'th field. When 2554 // initializing the i'th field, throw a warning if any of the >= i'th 2555 // fields are used, as they are not yet initialized. 2556 // Right now we are only handling the case where the i'th field uses 2557 // itself in its initializer. 2558 // Also need to take into account that some fields may be initialized by 2559 // in-class initializers, see C++11 [class.base.init]p9. 2560 CheckInitExprContainsUninitializedFields(*this, Args[i], Member); 2561 2562 SourceRange InitRange = Init->getSourceRange(); 2563 2564 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 2565 // Can't check initialization for a member of dependent type or when 2566 // any of the arguments are type-dependent expressions. 2567 DiscardCleanupsInEvaluationContext(); 2568 } else { 2569 bool InitList = false; 2570 if (isa<InitListExpr>(Init)) { 2571 InitList = true; 2572 Args = Init; 2573 } 2574 2575 // Initialize the member. 2576 InitializedEntity MemberEntity = 2577 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0) 2578 : InitializedEntity::InitializeMember(IndirectMember, 0); 2579 InitializationKind Kind = 2580 InitList ? InitializationKind::CreateDirectList(IdLoc) 2581 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 2582 InitRange.getEnd()); 2583 2584 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 2585 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 0); 2586 if (MemberInit.isInvalid()) 2587 return true; 2588 2589 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc); 2590 2591 // C++11 [class.base.init]p7: 2592 // The initialization of each base and member constitutes a 2593 // full-expression. 2594 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin()); 2595 if (MemberInit.isInvalid()) 2596 return true; 2597 2598 Init = MemberInit.get(); 2599 } 2600 2601 if (DirectMember) { 2602 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 2603 InitRange.getBegin(), Init, 2604 InitRange.getEnd()); 2605 } else { 2606 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 2607 InitRange.getBegin(), Init, 2608 InitRange.getEnd()); 2609 } 2610} 2611 2612MemInitResult 2613Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 2614 CXXRecordDecl *ClassDecl) { 2615 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 2616 if (!LangOpts.CPlusPlus11) 2617 return Diag(NameLoc, diag::err_delegating_ctor) 2618 << TInfo->getTypeLoc().getLocalSourceRange(); 2619 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 2620 2621 bool InitList = true; 2622 MultiExprArg Args = Init; 2623 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2624 InitList = false; 2625 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 2626 } 2627 2628 SourceRange InitRange = Init->getSourceRange(); 2629 // Initialize the object. 2630 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 2631 QualType(ClassDecl->getTypeForDecl(), 0)); 2632 InitializationKind Kind = 2633 InitList ? InitializationKind::CreateDirectList(NameLoc) 2634 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 2635 InitRange.getEnd()); 2636 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 2637 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 2638 Args, 0); 2639 if (DelegationInit.isInvalid()) 2640 return true; 2641 2642 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 2643 "Delegating constructor with no target?"); 2644 2645 // C++11 [class.base.init]p7: 2646 // The initialization of each base and member constitutes a 2647 // full-expression. 2648 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(), 2649 InitRange.getBegin()); 2650 if (DelegationInit.isInvalid()) 2651 return true; 2652 2653 // If we are in a dependent context, template instantiation will 2654 // perform this type-checking again. Just save the arguments that we 2655 // received in a ParenListExpr. 2656 // FIXME: This isn't quite ideal, since our ASTs don't capture all 2657 // of the information that we have about the base 2658 // initializer. However, deconstructing the ASTs is a dicey process, 2659 // and this approach is far more likely to get the corner cases right. 2660 if (CurContext->isDependentContext()) 2661 DelegationInit = Owned(Init); 2662 2663 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 2664 DelegationInit.takeAs<Expr>(), 2665 InitRange.getEnd()); 2666} 2667 2668MemInitResult 2669Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 2670 Expr *Init, CXXRecordDecl *ClassDecl, 2671 SourceLocation EllipsisLoc) { 2672 SourceLocation BaseLoc 2673 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 2674 2675 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 2676 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 2677 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2678 2679 // C++ [class.base.init]p2: 2680 // [...] Unless the mem-initializer-id names a nonstatic data 2681 // member of the constructor's class or a direct or virtual base 2682 // of that class, the mem-initializer is ill-formed. A 2683 // mem-initializer-list can initialize a base class using any 2684 // name that denotes that base class type. 2685 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 2686 2687 SourceRange InitRange = Init->getSourceRange(); 2688 if (EllipsisLoc.isValid()) { 2689 // This is a pack expansion. 2690 if (!BaseType->containsUnexpandedParameterPack()) { 2691 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2692 << SourceRange(BaseLoc, InitRange.getEnd()); 2693 2694 EllipsisLoc = SourceLocation(); 2695 } 2696 } else { 2697 // Check for any unexpanded parameter packs. 2698 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 2699 return true; 2700 2701 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 2702 return true; 2703 } 2704 2705 // Check for direct and virtual base classes. 2706 const CXXBaseSpecifier *DirectBaseSpec = 0; 2707 const CXXBaseSpecifier *VirtualBaseSpec = 0; 2708 if (!Dependent) { 2709 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 2710 BaseType)) 2711 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 2712 2713 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 2714 VirtualBaseSpec); 2715 2716 // C++ [base.class.init]p2: 2717 // Unless the mem-initializer-id names a nonstatic data member of the 2718 // constructor's class or a direct or virtual base of that class, the 2719 // mem-initializer is ill-formed. 2720 if (!DirectBaseSpec && !VirtualBaseSpec) { 2721 // If the class has any dependent bases, then it's possible that 2722 // one of those types will resolve to the same type as 2723 // BaseType. Therefore, just treat this as a dependent base 2724 // class initialization. FIXME: Should we try to check the 2725 // initialization anyway? It seems odd. 2726 if (ClassDecl->hasAnyDependentBases()) 2727 Dependent = true; 2728 else 2729 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 2730 << BaseType << Context.getTypeDeclType(ClassDecl) 2731 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2732 } 2733 } 2734 2735 if (Dependent) { 2736 DiscardCleanupsInEvaluationContext(); 2737 2738 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 2739 /*IsVirtual=*/false, 2740 InitRange.getBegin(), Init, 2741 InitRange.getEnd(), EllipsisLoc); 2742 } 2743 2744 // C++ [base.class.init]p2: 2745 // If a mem-initializer-id is ambiguous because it designates both 2746 // a direct non-virtual base class and an inherited virtual base 2747 // class, the mem-initializer is ill-formed. 2748 if (DirectBaseSpec && VirtualBaseSpec) 2749 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 2750 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2751 2752 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec); 2753 if (!BaseSpec) 2754 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec); 2755 2756 // Initialize the base. 2757 bool InitList = true; 2758 MultiExprArg Args = Init; 2759 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2760 InitList = false; 2761 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 2762 } 2763 2764 InitializedEntity BaseEntity = 2765 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 2766 InitializationKind Kind = 2767 InitList ? InitializationKind::CreateDirectList(BaseLoc) 2768 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 2769 InitRange.getEnd()); 2770 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 2771 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 0); 2772 if (BaseInit.isInvalid()) 2773 return true; 2774 2775 // C++11 [class.base.init]p7: 2776 // The initialization of each base and member constitutes a 2777 // full-expression. 2778 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin()); 2779 if (BaseInit.isInvalid()) 2780 return true; 2781 2782 // If we are in a dependent context, template instantiation will 2783 // perform this type-checking again. Just save the arguments that we 2784 // received in a ParenListExpr. 2785 // FIXME: This isn't quite ideal, since our ASTs don't capture all 2786 // of the information that we have about the base 2787 // initializer. However, deconstructing the ASTs is a dicey process, 2788 // and this approach is far more likely to get the corner cases right. 2789 if (CurContext->isDependentContext()) 2790 BaseInit = Owned(Init); 2791 2792 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 2793 BaseSpec->isVirtual(), 2794 InitRange.getBegin(), 2795 BaseInit.takeAs<Expr>(), 2796 InitRange.getEnd(), EllipsisLoc); 2797} 2798 2799// Create a static_cast\<T&&>(expr). 2800static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 2801 if (T.isNull()) T = E->getType(); 2802 QualType TargetType = SemaRef.BuildReferenceType( 2803 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 2804 SourceLocation ExprLoc = E->getLocStart(); 2805 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 2806 TargetType, ExprLoc); 2807 2808 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 2809 SourceRange(ExprLoc, ExprLoc), 2810 E->getSourceRange()).take(); 2811} 2812 2813/// ImplicitInitializerKind - How an implicit base or member initializer should 2814/// initialize its base or member. 2815enum ImplicitInitializerKind { 2816 IIK_Default, 2817 IIK_Copy, 2818 IIK_Move, 2819 IIK_Inherit 2820}; 2821 2822static bool 2823BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 2824 ImplicitInitializerKind ImplicitInitKind, 2825 CXXBaseSpecifier *BaseSpec, 2826 bool IsInheritedVirtualBase, 2827 CXXCtorInitializer *&CXXBaseInit) { 2828 InitializedEntity InitEntity 2829 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 2830 IsInheritedVirtualBase); 2831 2832 ExprResult BaseInit; 2833 2834 switch (ImplicitInitKind) { 2835 case IIK_Inherit: { 2836 const CXXRecordDecl *Inherited = 2837 Constructor->getInheritedConstructor()->getParent(); 2838 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 2839 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) { 2840 // C++11 [class.inhctor]p8: 2841 // Each expression in the expression-list is of the form 2842 // static_cast<T&&>(p), where p is the name of the corresponding 2843 // constructor parameter and T is the declared type of p. 2844 SmallVector<Expr*, 16> Args; 2845 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) { 2846 ParmVarDecl *PD = Constructor->getParamDecl(I); 2847 ExprResult ArgExpr = 2848 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(), 2849 VK_LValue, SourceLocation()); 2850 if (ArgExpr.isInvalid()) 2851 return true; 2852 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType())); 2853 } 2854 2855 InitializationKind InitKind = InitializationKind::CreateDirect( 2856 Constructor->getLocation(), SourceLocation(), SourceLocation()); 2857 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args); 2858 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args); 2859 break; 2860 } 2861 } 2862 // Fall through. 2863 case IIK_Default: { 2864 InitializationKind InitKind 2865 = InitializationKind::CreateDefault(Constructor->getLocation()); 2866 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 2867 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 2868 break; 2869 } 2870 2871 case IIK_Move: 2872 case IIK_Copy: { 2873 bool Moving = ImplicitInitKind == IIK_Move; 2874 ParmVarDecl *Param = Constructor->getParamDecl(0); 2875 QualType ParamType = Param->getType().getNonReferenceType(); 2876 2877 Expr *CopyCtorArg = 2878 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 2879 SourceLocation(), Param, false, 2880 Constructor->getLocation(), ParamType, 2881 VK_LValue, 0); 2882 2883 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 2884 2885 // Cast to the base class to avoid ambiguities. 2886 QualType ArgTy = 2887 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 2888 ParamType.getQualifiers()); 2889 2890 if (Moving) { 2891 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 2892 } 2893 2894 CXXCastPath BasePath; 2895 BasePath.push_back(BaseSpec); 2896 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 2897 CK_UncheckedDerivedToBase, 2898 Moving ? VK_XValue : VK_LValue, 2899 &BasePath).take(); 2900 2901 InitializationKind InitKind 2902 = InitializationKind::CreateDirect(Constructor->getLocation(), 2903 SourceLocation(), SourceLocation()); 2904 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 2905 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 2906 break; 2907 } 2908 } 2909 2910 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 2911 if (BaseInit.isInvalid()) 2912 return true; 2913 2914 CXXBaseInit = 2915 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 2916 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 2917 SourceLocation()), 2918 BaseSpec->isVirtual(), 2919 SourceLocation(), 2920 BaseInit.takeAs<Expr>(), 2921 SourceLocation(), 2922 SourceLocation()); 2923 2924 return false; 2925} 2926 2927static bool RefersToRValueRef(Expr *MemRef) { 2928 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 2929 return Referenced->getType()->isRValueReferenceType(); 2930} 2931 2932static bool 2933BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 2934 ImplicitInitializerKind ImplicitInitKind, 2935 FieldDecl *Field, IndirectFieldDecl *Indirect, 2936 CXXCtorInitializer *&CXXMemberInit) { 2937 if (Field->isInvalidDecl()) 2938 return true; 2939 2940 SourceLocation Loc = Constructor->getLocation(); 2941 2942 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 2943 bool Moving = ImplicitInitKind == IIK_Move; 2944 ParmVarDecl *Param = Constructor->getParamDecl(0); 2945 QualType ParamType = Param->getType().getNonReferenceType(); 2946 2947 // Suppress copying zero-width bitfields. 2948 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0) 2949 return false; 2950 2951 Expr *MemberExprBase = 2952 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 2953 SourceLocation(), Param, false, 2954 Loc, ParamType, VK_LValue, 0); 2955 2956 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 2957 2958 if (Moving) { 2959 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 2960 } 2961 2962 // Build a reference to this field within the parameter. 2963 CXXScopeSpec SS; 2964 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 2965 Sema::LookupMemberName); 2966 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 2967 : cast<ValueDecl>(Field), AS_public); 2968 MemberLookup.resolveKind(); 2969 ExprResult CtorArg 2970 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 2971 ParamType, Loc, 2972 /*IsArrow=*/false, 2973 SS, 2974 /*TemplateKWLoc=*/SourceLocation(), 2975 /*FirstQualifierInScope=*/0, 2976 MemberLookup, 2977 /*TemplateArgs=*/0); 2978 if (CtorArg.isInvalid()) 2979 return true; 2980 2981 // C++11 [class.copy]p15: 2982 // - if a member m has rvalue reference type T&&, it is direct-initialized 2983 // with static_cast<T&&>(x.m); 2984 if (RefersToRValueRef(CtorArg.get())) { 2985 CtorArg = CastForMoving(SemaRef, CtorArg.take()); 2986 } 2987 2988 // When the field we are copying is an array, create index variables for 2989 // each dimension of the array. We use these index variables to subscript 2990 // the source array, and other clients (e.g., CodeGen) will perform the 2991 // necessary iteration with these index variables. 2992 SmallVector<VarDecl *, 4> IndexVariables; 2993 QualType BaseType = Field->getType(); 2994 QualType SizeType = SemaRef.Context.getSizeType(); 2995 bool InitializingArray = false; 2996 while (const ConstantArrayType *Array 2997 = SemaRef.Context.getAsConstantArrayType(BaseType)) { 2998 InitializingArray = true; 2999 // Create the iteration variable for this array index. 3000 IdentifierInfo *IterationVarName = 0; 3001 { 3002 SmallString<8> Str; 3003 llvm::raw_svector_ostream OS(Str); 3004 OS << "__i" << IndexVariables.size(); 3005 IterationVarName = &SemaRef.Context.Idents.get(OS.str()); 3006 } 3007 VarDecl *IterationVar 3008 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc, 3009 IterationVarName, SizeType, 3010 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc), 3011 SC_None); 3012 IndexVariables.push_back(IterationVar); 3013 3014 // Create a reference to the iteration variable. 3015 ExprResult IterationVarRef 3016 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 3017 assert(!IterationVarRef.isInvalid() && 3018 "Reference to invented variable cannot fail!"); 3019 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take()); 3020 assert(!IterationVarRef.isInvalid() && 3021 "Conversion of invented variable cannot fail!"); 3022 3023 // Subscript the array with this iteration variable. 3024 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc, 3025 IterationVarRef.take(), 3026 Loc); 3027 if (CtorArg.isInvalid()) 3028 return true; 3029 3030 BaseType = Array->getElementType(); 3031 } 3032 3033 // The array subscript expression is an lvalue, which is wrong for moving. 3034 if (Moving && InitializingArray) 3035 CtorArg = CastForMoving(SemaRef, CtorArg.take()); 3036 3037 // Construct the entity that we will be initializing. For an array, this 3038 // will be first element in the array, which may require several levels 3039 // of array-subscript entities. 3040 SmallVector<InitializedEntity, 4> Entities; 3041 Entities.reserve(1 + IndexVariables.size()); 3042 if (Indirect) 3043 Entities.push_back(InitializedEntity::InitializeMember(Indirect)); 3044 else 3045 Entities.push_back(InitializedEntity::InitializeMember(Field)); 3046 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 3047 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context, 3048 0, 3049 Entities.back())); 3050 3051 // Direct-initialize to use the copy constructor. 3052 InitializationKind InitKind = 3053 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 3054 3055 Expr *CtorArgE = CtorArg.takeAs<Expr>(); 3056 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE); 3057 3058 ExprResult MemberInit 3059 = InitSeq.Perform(SemaRef, Entities.back(), InitKind, 3060 MultiExprArg(&CtorArgE, 1)); 3061 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3062 if (MemberInit.isInvalid()) 3063 return true; 3064 3065 if (Indirect) { 3066 assert(IndexVariables.size() == 0 && 3067 "Indirect field improperly initialized"); 3068 CXXMemberInit 3069 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 3070 Loc, Loc, 3071 MemberInit.takeAs<Expr>(), 3072 Loc); 3073 } else 3074 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, 3075 Loc, MemberInit.takeAs<Expr>(), 3076 Loc, 3077 IndexVariables.data(), 3078 IndexVariables.size()); 3079 return false; 3080 } 3081 3082 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 3083 "Unhandled implicit init kind!"); 3084 3085 QualType FieldBaseElementType = 3086 SemaRef.Context.getBaseElementType(Field->getType()); 3087 3088 if (FieldBaseElementType->isRecordType()) { 3089 InitializedEntity InitEntity 3090 = Indirect? InitializedEntity::InitializeMember(Indirect) 3091 : InitializedEntity::InitializeMember(Field); 3092 InitializationKind InitKind = 3093 InitializationKind::CreateDefault(Loc); 3094 3095 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 3096 ExprResult MemberInit = 3097 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 3098 3099 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3100 if (MemberInit.isInvalid()) 3101 return true; 3102 3103 if (Indirect) 3104 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3105 Indirect, Loc, 3106 Loc, 3107 MemberInit.get(), 3108 Loc); 3109 else 3110 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3111 Field, Loc, Loc, 3112 MemberInit.get(), 3113 Loc); 3114 return false; 3115 } 3116 3117 if (!Field->getParent()->isUnion()) { 3118 if (FieldBaseElementType->isReferenceType()) { 3119 SemaRef.Diag(Constructor->getLocation(), 3120 diag::err_uninitialized_member_in_ctor) 3121 << (int)Constructor->isImplicit() 3122 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3123 << 0 << Field->getDeclName(); 3124 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3125 return true; 3126 } 3127 3128 if (FieldBaseElementType.isConstQualified()) { 3129 SemaRef.Diag(Constructor->getLocation(), 3130 diag::err_uninitialized_member_in_ctor) 3131 << (int)Constructor->isImplicit() 3132 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3133 << 1 << Field->getDeclName(); 3134 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3135 return true; 3136 } 3137 } 3138 3139 if (SemaRef.getLangOpts().ObjCAutoRefCount && 3140 FieldBaseElementType->isObjCRetainableType() && 3141 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None && 3142 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) { 3143 // ARC: 3144 // Default-initialize Objective-C pointers to NULL. 3145 CXXMemberInit 3146 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 3147 Loc, Loc, 3148 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 3149 Loc); 3150 return false; 3151 } 3152 3153 // Nothing to initialize. 3154 CXXMemberInit = 0; 3155 return false; 3156} 3157 3158namespace { 3159struct BaseAndFieldInfo { 3160 Sema &S; 3161 CXXConstructorDecl *Ctor; 3162 bool AnyErrorsInInits; 3163 ImplicitInitializerKind IIK; 3164 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 3165 SmallVector<CXXCtorInitializer*, 8> AllToInit; 3166 3167 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 3168 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 3169 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 3170 if (Generated && Ctor->isCopyConstructor()) 3171 IIK = IIK_Copy; 3172 else if (Generated && Ctor->isMoveConstructor()) 3173 IIK = IIK_Move; 3174 else if (Ctor->getInheritedConstructor()) 3175 IIK = IIK_Inherit; 3176 else 3177 IIK = IIK_Default; 3178 } 3179 3180 bool isImplicitCopyOrMove() const { 3181 switch (IIK) { 3182 case IIK_Copy: 3183 case IIK_Move: 3184 return true; 3185 3186 case IIK_Default: 3187 case IIK_Inherit: 3188 return false; 3189 } 3190 3191 llvm_unreachable("Invalid ImplicitInitializerKind!"); 3192 } 3193 3194 bool addFieldInitializer(CXXCtorInitializer *Init) { 3195 AllToInit.push_back(Init); 3196 3197 // Check whether this initializer makes the field "used". 3198 if (Init->getInit()->HasSideEffects(S.Context)) 3199 S.UnusedPrivateFields.remove(Init->getAnyMember()); 3200 3201 return false; 3202 } 3203}; 3204} 3205 3206/// \brief Determine whether the given indirect field declaration is somewhere 3207/// within an anonymous union. 3208static bool isWithinAnonymousUnion(IndirectFieldDecl *F) { 3209 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(), 3210 CEnd = F->chain_end(); 3211 C != CEnd; ++C) 3212 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext())) 3213 if (Record->isUnion()) 3214 return true; 3215 3216 return false; 3217} 3218 3219/// \brief Determine whether the given type is an incomplete or zero-lenfgth 3220/// array type. 3221static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 3222 if (T->isIncompleteArrayType()) 3223 return true; 3224 3225 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 3226 if (!ArrayT->getSize()) 3227 return true; 3228 3229 T = ArrayT->getElementType(); 3230 } 3231 3232 return false; 3233} 3234 3235static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 3236 FieldDecl *Field, 3237 IndirectFieldDecl *Indirect = 0) { 3238 3239 // Overwhelmingly common case: we have a direct initializer for this field. 3240 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) 3241 return Info.addFieldInitializer(Init); 3242 3243 // C++11 [class.base.init]p8: if the entity is a non-static data member that 3244 // has a brace-or-equal-initializer, the entity is initialized as specified 3245 // in [dcl.init]. 3246 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 3247 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context, 3248 Info.Ctor->getLocation(), Field); 3249 CXXCtorInitializer *Init; 3250 if (Indirect) 3251 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 3252 SourceLocation(), 3253 SourceLocation(), DIE, 3254 SourceLocation()); 3255 else 3256 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 3257 SourceLocation(), 3258 SourceLocation(), DIE, 3259 SourceLocation()); 3260 return Info.addFieldInitializer(Init); 3261 } 3262 3263 // Don't build an implicit initializer for union members if none was 3264 // explicitly specified. 3265 if (Field->getParent()->isUnion() || 3266 (Indirect && isWithinAnonymousUnion(Indirect))) 3267 return false; 3268 3269 // Don't initialize incomplete or zero-length arrays. 3270 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 3271 return false; 3272 3273 // Don't try to build an implicit initializer if there were semantic 3274 // errors in any of the initializers (and therefore we might be 3275 // missing some that the user actually wrote). 3276 if (Info.AnyErrorsInInits || Field->isInvalidDecl()) 3277 return false; 3278 3279 CXXCtorInitializer *Init = 0; 3280 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 3281 Indirect, Init)) 3282 return true; 3283 3284 if (!Init) 3285 return false; 3286 3287 return Info.addFieldInitializer(Init); 3288} 3289 3290bool 3291Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 3292 CXXCtorInitializer *Initializer) { 3293 assert(Initializer->isDelegatingInitializer()); 3294 Constructor->setNumCtorInitializers(1); 3295 CXXCtorInitializer **initializer = 3296 new (Context) CXXCtorInitializer*[1]; 3297 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 3298 Constructor->setCtorInitializers(initializer); 3299 3300 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 3301 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 3302 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 3303 } 3304 3305 DelegatingCtorDecls.push_back(Constructor); 3306 3307 return false; 3308} 3309 3310bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 3311 ArrayRef<CXXCtorInitializer *> Initializers) { 3312 if (Constructor->isDependentContext()) { 3313 // Just store the initializers as written, they will be checked during 3314 // instantiation. 3315 if (!Initializers.empty()) { 3316 Constructor->setNumCtorInitializers(Initializers.size()); 3317 CXXCtorInitializer **baseOrMemberInitializers = 3318 new (Context) CXXCtorInitializer*[Initializers.size()]; 3319 memcpy(baseOrMemberInitializers, Initializers.data(), 3320 Initializers.size() * sizeof(CXXCtorInitializer*)); 3321 Constructor->setCtorInitializers(baseOrMemberInitializers); 3322 } 3323 3324 // Let template instantiation know whether we had errors. 3325 if (AnyErrors) 3326 Constructor->setInvalidDecl(); 3327 3328 return false; 3329 } 3330 3331 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 3332 3333 // We need to build the initializer AST according to order of construction 3334 // and not what user specified in the Initializers list. 3335 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 3336 if (!ClassDecl) 3337 return true; 3338 3339 bool HadError = false; 3340 3341 for (unsigned i = 0; i < Initializers.size(); i++) { 3342 CXXCtorInitializer *Member = Initializers[i]; 3343 3344 if (Member->isBaseInitializer()) 3345 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 3346 else 3347 Info.AllBaseFields[Member->getAnyMember()] = Member; 3348 } 3349 3350 // Keep track of the direct virtual bases. 3351 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 3352 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(), 3353 E = ClassDecl->bases_end(); I != E; ++I) { 3354 if (I->isVirtual()) 3355 DirectVBases.insert(I); 3356 } 3357 3358 // Push virtual bases before others. 3359 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 3360 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 3361 3362 if (CXXCtorInitializer *Value 3363 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) { 3364 Info.AllToInit.push_back(Value); 3365 } else if (!AnyErrors) { 3366 bool IsInheritedVirtualBase = !DirectVBases.count(VBase); 3367 CXXCtorInitializer *CXXBaseInit; 3368 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3369 VBase, IsInheritedVirtualBase, 3370 CXXBaseInit)) { 3371 HadError = true; 3372 continue; 3373 } 3374 3375 Info.AllToInit.push_back(CXXBaseInit); 3376 } 3377 } 3378 3379 // Non-virtual bases. 3380 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 3381 E = ClassDecl->bases_end(); Base != E; ++Base) { 3382 // Virtuals are in the virtual base list and already constructed. 3383 if (Base->isVirtual()) 3384 continue; 3385 3386 if (CXXCtorInitializer *Value 3387 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) { 3388 Info.AllToInit.push_back(Value); 3389 } else if (!AnyErrors) { 3390 CXXCtorInitializer *CXXBaseInit; 3391 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3392 Base, /*IsInheritedVirtualBase=*/false, 3393 CXXBaseInit)) { 3394 HadError = true; 3395 continue; 3396 } 3397 3398 Info.AllToInit.push_back(CXXBaseInit); 3399 } 3400 } 3401 3402 // Fields. 3403 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(), 3404 MemEnd = ClassDecl->decls_end(); 3405 Mem != MemEnd; ++Mem) { 3406 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) { 3407 // C++ [class.bit]p2: 3408 // A declaration for a bit-field that omits the identifier declares an 3409 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 3410 // initialized. 3411 if (F->isUnnamedBitfield()) 3412 continue; 3413 3414 // If we're not generating the implicit copy/move constructor, then we'll 3415 // handle anonymous struct/union fields based on their individual 3416 // indirect fields. 3417 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 3418 continue; 3419 3420 if (CollectFieldInitializer(*this, Info, F)) 3421 HadError = true; 3422 continue; 3423 } 3424 3425 // Beyond this point, we only consider default initialization. 3426 if (Info.isImplicitCopyOrMove()) 3427 continue; 3428 3429 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) { 3430 if (F->getType()->isIncompleteArrayType()) { 3431 assert(ClassDecl->hasFlexibleArrayMember() && 3432 "Incomplete array type is not valid"); 3433 continue; 3434 } 3435 3436 // Initialize each field of an anonymous struct individually. 3437 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 3438 HadError = true; 3439 3440 continue; 3441 } 3442 } 3443 3444 unsigned NumInitializers = Info.AllToInit.size(); 3445 if (NumInitializers > 0) { 3446 Constructor->setNumCtorInitializers(NumInitializers); 3447 CXXCtorInitializer **baseOrMemberInitializers = 3448 new (Context) CXXCtorInitializer*[NumInitializers]; 3449 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 3450 NumInitializers * sizeof(CXXCtorInitializer*)); 3451 Constructor->setCtorInitializers(baseOrMemberInitializers); 3452 3453 // Constructors implicitly reference the base and member 3454 // destructors. 3455 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 3456 Constructor->getParent()); 3457 } 3458 3459 return HadError; 3460} 3461 3462static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 3463 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 3464 const RecordDecl *RD = RT->getDecl(); 3465 if (RD->isAnonymousStructOrUnion()) { 3466 for (RecordDecl::field_iterator Field = RD->field_begin(), 3467 E = RD->field_end(); Field != E; ++Field) 3468 PopulateKeysForFields(*Field, IdealInits); 3469 return; 3470 } 3471 } 3472 IdealInits.push_back(Field); 3473} 3474 3475static void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 3476 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr()); 3477} 3478 3479static void *GetKeyForMember(ASTContext &Context, 3480 CXXCtorInitializer *Member) { 3481 if (!Member->isAnyMemberInitializer()) 3482 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 3483 3484 return Member->getAnyMember(); 3485} 3486 3487static void DiagnoseBaseOrMemInitializerOrder( 3488 Sema &SemaRef, const CXXConstructorDecl *Constructor, 3489 ArrayRef<CXXCtorInitializer *> Inits) { 3490 if (Constructor->getDeclContext()->isDependentContext()) 3491 return; 3492 3493 // Don't check initializers order unless the warning is enabled at the 3494 // location of at least one initializer. 3495 bool ShouldCheckOrder = false; 3496 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 3497 CXXCtorInitializer *Init = Inits[InitIndex]; 3498 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order, 3499 Init->getSourceLocation()) 3500 != DiagnosticsEngine::Ignored) { 3501 ShouldCheckOrder = true; 3502 break; 3503 } 3504 } 3505 if (!ShouldCheckOrder) 3506 return; 3507 3508 // Build the list of bases and members in the order that they'll 3509 // actually be initialized. The explicit initializers should be in 3510 // this same order but may be missing things. 3511 SmallVector<const void*, 32> IdealInitKeys; 3512 3513 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 3514 3515 // 1. Virtual bases. 3516 for (CXXRecordDecl::base_class_const_iterator VBase = 3517 ClassDecl->vbases_begin(), 3518 E = ClassDecl->vbases_end(); VBase != E; ++VBase) 3519 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType())); 3520 3521 // 2. Non-virtual bases. 3522 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(), 3523 E = ClassDecl->bases_end(); Base != E; ++Base) { 3524 if (Base->isVirtual()) 3525 continue; 3526 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType())); 3527 } 3528 3529 // 3. Direct fields. 3530 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 3531 E = ClassDecl->field_end(); Field != E; ++Field) { 3532 if (Field->isUnnamedBitfield()) 3533 continue; 3534 3535 PopulateKeysForFields(*Field, IdealInitKeys); 3536 } 3537 3538 unsigned NumIdealInits = IdealInitKeys.size(); 3539 unsigned IdealIndex = 0; 3540 3541 CXXCtorInitializer *PrevInit = 0; 3542 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 3543 CXXCtorInitializer *Init = Inits[InitIndex]; 3544 void *InitKey = GetKeyForMember(SemaRef.Context, Init); 3545 3546 // Scan forward to try to find this initializer in the idealized 3547 // initializers list. 3548 for (; IdealIndex != NumIdealInits; ++IdealIndex) 3549 if (InitKey == IdealInitKeys[IdealIndex]) 3550 break; 3551 3552 // If we didn't find this initializer, it must be because we 3553 // scanned past it on a previous iteration. That can only 3554 // happen if we're out of order; emit a warning. 3555 if (IdealIndex == NumIdealInits && PrevInit) { 3556 Sema::SemaDiagnosticBuilder D = 3557 SemaRef.Diag(PrevInit->getSourceLocation(), 3558 diag::warn_initializer_out_of_order); 3559 3560 if (PrevInit->isAnyMemberInitializer()) 3561 D << 0 << PrevInit->getAnyMember()->getDeclName(); 3562 else 3563 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 3564 3565 if (Init->isAnyMemberInitializer()) 3566 D << 0 << Init->getAnyMember()->getDeclName(); 3567 else 3568 D << 1 << Init->getTypeSourceInfo()->getType(); 3569 3570 // Move back to the initializer's location in the ideal list. 3571 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 3572 if (InitKey == IdealInitKeys[IdealIndex]) 3573 break; 3574 3575 assert(IdealIndex != NumIdealInits && 3576 "initializer not found in initializer list"); 3577 } 3578 3579 PrevInit = Init; 3580 } 3581} 3582 3583namespace { 3584bool CheckRedundantInit(Sema &S, 3585 CXXCtorInitializer *Init, 3586 CXXCtorInitializer *&PrevInit) { 3587 if (!PrevInit) { 3588 PrevInit = Init; 3589 return false; 3590 } 3591 3592 if (FieldDecl *Field = Init->getAnyMember()) 3593 S.Diag(Init->getSourceLocation(), 3594 diag::err_multiple_mem_initialization) 3595 << Field->getDeclName() 3596 << Init->getSourceRange(); 3597 else { 3598 const Type *BaseClass = Init->getBaseClass(); 3599 assert(BaseClass && "neither field nor base"); 3600 S.Diag(Init->getSourceLocation(), 3601 diag::err_multiple_base_initialization) 3602 << QualType(BaseClass, 0) 3603 << Init->getSourceRange(); 3604 } 3605 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 3606 << 0 << PrevInit->getSourceRange(); 3607 3608 return true; 3609} 3610 3611typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 3612typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 3613 3614bool CheckRedundantUnionInit(Sema &S, 3615 CXXCtorInitializer *Init, 3616 RedundantUnionMap &Unions) { 3617 FieldDecl *Field = Init->getAnyMember(); 3618 RecordDecl *Parent = Field->getParent(); 3619 NamedDecl *Child = Field; 3620 3621 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 3622 if (Parent->isUnion()) { 3623 UnionEntry &En = Unions[Parent]; 3624 if (En.first && En.first != Child) { 3625 S.Diag(Init->getSourceLocation(), 3626 diag::err_multiple_mem_union_initialization) 3627 << Field->getDeclName() 3628 << Init->getSourceRange(); 3629 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 3630 << 0 << En.second->getSourceRange(); 3631 return true; 3632 } 3633 if (!En.first) { 3634 En.first = Child; 3635 En.second = Init; 3636 } 3637 if (!Parent->isAnonymousStructOrUnion()) 3638 return false; 3639 } 3640 3641 Child = Parent; 3642 Parent = cast<RecordDecl>(Parent->getDeclContext()); 3643 } 3644 3645 return false; 3646} 3647} 3648 3649/// ActOnMemInitializers - Handle the member initializers for a constructor. 3650void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 3651 SourceLocation ColonLoc, 3652 ArrayRef<CXXCtorInitializer*> MemInits, 3653 bool AnyErrors) { 3654 if (!ConstructorDecl) 3655 return; 3656 3657 AdjustDeclIfTemplate(ConstructorDecl); 3658 3659 CXXConstructorDecl *Constructor 3660 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 3661 3662 if (!Constructor) { 3663 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 3664 return; 3665 } 3666 3667 // Mapping for the duplicate initializers check. 3668 // For member initializers, this is keyed with a FieldDecl*. 3669 // For base initializers, this is keyed with a Type*. 3670 llvm::DenseMap<void*, CXXCtorInitializer *> Members; 3671 3672 // Mapping for the inconsistent anonymous-union initializers check. 3673 RedundantUnionMap MemberUnions; 3674 3675 bool HadError = false; 3676 for (unsigned i = 0; i < MemInits.size(); i++) { 3677 CXXCtorInitializer *Init = MemInits[i]; 3678 3679 // Set the source order index. 3680 Init->setSourceOrder(i); 3681 3682 if (Init->isAnyMemberInitializer()) { 3683 FieldDecl *Field = Init->getAnyMember(); 3684 if (CheckRedundantInit(*this, Init, Members[Field]) || 3685 CheckRedundantUnionInit(*this, Init, MemberUnions)) 3686 HadError = true; 3687 } else if (Init->isBaseInitializer()) { 3688 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0)); 3689 if (CheckRedundantInit(*this, Init, Members[Key])) 3690 HadError = true; 3691 } else { 3692 assert(Init->isDelegatingInitializer()); 3693 // This must be the only initializer 3694 if (MemInits.size() != 1) { 3695 Diag(Init->getSourceLocation(), 3696 diag::err_delegating_initializer_alone) 3697 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 3698 // We will treat this as being the only initializer. 3699 } 3700 SetDelegatingInitializer(Constructor, MemInits[i]); 3701 // Return immediately as the initializer is set. 3702 return; 3703 } 3704 } 3705 3706 if (HadError) 3707 return; 3708 3709 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 3710 3711 SetCtorInitializers(Constructor, AnyErrors, MemInits); 3712} 3713 3714void 3715Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 3716 CXXRecordDecl *ClassDecl) { 3717 // Ignore dependent contexts. Also ignore unions, since their members never 3718 // have destructors implicitly called. 3719 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 3720 return; 3721 3722 // FIXME: all the access-control diagnostics are positioned on the 3723 // field/base declaration. That's probably good; that said, the 3724 // user might reasonably want to know why the destructor is being 3725 // emitted, and we currently don't say. 3726 3727 // Non-static data members. 3728 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(), 3729 E = ClassDecl->field_end(); I != E; ++I) { 3730 FieldDecl *Field = *I; 3731 if (Field->isInvalidDecl()) 3732 continue; 3733 3734 // Don't destroy incomplete or zero-length arrays. 3735 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 3736 continue; 3737 3738 QualType FieldType = Context.getBaseElementType(Field->getType()); 3739 3740 const RecordType* RT = FieldType->getAs<RecordType>(); 3741 if (!RT) 3742 continue; 3743 3744 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3745 if (FieldClassDecl->isInvalidDecl()) 3746 continue; 3747 if (FieldClassDecl->hasIrrelevantDestructor()) 3748 continue; 3749 // The destructor for an implicit anonymous union member is never invoked. 3750 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 3751 continue; 3752 3753 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 3754 assert(Dtor && "No dtor found for FieldClassDecl!"); 3755 CheckDestructorAccess(Field->getLocation(), Dtor, 3756 PDiag(diag::err_access_dtor_field) 3757 << Field->getDeclName() 3758 << FieldType); 3759 3760 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 3761 DiagnoseUseOfDecl(Dtor, Location); 3762 } 3763 3764 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 3765 3766 // Bases. 3767 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 3768 E = ClassDecl->bases_end(); Base != E; ++Base) { 3769 // Bases are always records in a well-formed non-dependent class. 3770 const RecordType *RT = Base->getType()->getAs<RecordType>(); 3771 3772 // Remember direct virtual bases. 3773 if (Base->isVirtual()) 3774 DirectVirtualBases.insert(RT); 3775 3776 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3777 // If our base class is invalid, we probably can't get its dtor anyway. 3778 if (BaseClassDecl->isInvalidDecl()) 3779 continue; 3780 if (BaseClassDecl->hasIrrelevantDestructor()) 3781 continue; 3782 3783 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 3784 assert(Dtor && "No dtor found for BaseClassDecl!"); 3785 3786 // FIXME: caret should be on the start of the class name 3787 CheckDestructorAccess(Base->getLocStart(), Dtor, 3788 PDiag(diag::err_access_dtor_base) 3789 << Base->getType() 3790 << Base->getSourceRange(), 3791 Context.getTypeDeclType(ClassDecl)); 3792 3793 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 3794 DiagnoseUseOfDecl(Dtor, Location); 3795 } 3796 3797 // Virtual bases. 3798 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 3799 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 3800 3801 // Bases are always records in a well-formed non-dependent class. 3802 const RecordType *RT = VBase->getType()->castAs<RecordType>(); 3803 3804 // Ignore direct virtual bases. 3805 if (DirectVirtualBases.count(RT)) 3806 continue; 3807 3808 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3809 // If our base class is invalid, we probably can't get its dtor anyway. 3810 if (BaseClassDecl->isInvalidDecl()) 3811 continue; 3812 if (BaseClassDecl->hasIrrelevantDestructor()) 3813 continue; 3814 3815 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 3816 assert(Dtor && "No dtor found for BaseClassDecl!"); 3817 if (CheckDestructorAccess( 3818 ClassDecl->getLocation(), Dtor, 3819 PDiag(diag::err_access_dtor_vbase) 3820 << Context.getTypeDeclType(ClassDecl) << VBase->getType(), 3821 Context.getTypeDeclType(ClassDecl)) == 3822 AR_accessible) { 3823 CheckDerivedToBaseConversion( 3824 Context.getTypeDeclType(ClassDecl), VBase->getType(), 3825 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 3826 SourceRange(), DeclarationName(), 0); 3827 } 3828 3829 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 3830 DiagnoseUseOfDecl(Dtor, Location); 3831 } 3832} 3833 3834void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 3835 if (!CDtorDecl) 3836 return; 3837 3838 if (CXXConstructorDecl *Constructor 3839 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) 3840 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 3841} 3842 3843bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 3844 unsigned DiagID, AbstractDiagSelID SelID) { 3845 class NonAbstractTypeDiagnoser : public TypeDiagnoser { 3846 unsigned DiagID; 3847 AbstractDiagSelID SelID; 3848 3849 public: 3850 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID) 3851 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { } 3852 3853 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 3854 if (Suppressed) return; 3855 if (SelID == -1) 3856 S.Diag(Loc, DiagID) << T; 3857 else 3858 S.Diag(Loc, DiagID) << SelID << T; 3859 } 3860 } Diagnoser(DiagID, SelID); 3861 3862 return RequireNonAbstractType(Loc, T, Diagnoser); 3863} 3864 3865bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 3866 TypeDiagnoser &Diagnoser) { 3867 if (!getLangOpts().CPlusPlus) 3868 return false; 3869 3870 if (const ArrayType *AT = Context.getAsArrayType(T)) 3871 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 3872 3873 if (const PointerType *PT = T->getAs<PointerType>()) { 3874 // Find the innermost pointer type. 3875 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 3876 PT = T; 3877 3878 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 3879 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 3880 } 3881 3882 const RecordType *RT = T->getAs<RecordType>(); 3883 if (!RT) 3884 return false; 3885 3886 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 3887 3888 // We can't answer whether something is abstract until it has a 3889 // definition. If it's currently being defined, we'll walk back 3890 // over all the declarations when we have a full definition. 3891 const CXXRecordDecl *Def = RD->getDefinition(); 3892 if (!Def || Def->isBeingDefined()) 3893 return false; 3894 3895 if (!RD->isAbstract()) 3896 return false; 3897 3898 Diagnoser.diagnose(*this, Loc, T); 3899 DiagnoseAbstractType(RD); 3900 3901 return true; 3902} 3903 3904void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 3905 // Check if we've already emitted the list of pure virtual functions 3906 // for this class. 3907 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 3908 return; 3909 3910 CXXFinalOverriderMap FinalOverriders; 3911 RD->getFinalOverriders(FinalOverriders); 3912 3913 // Keep a set of seen pure methods so we won't diagnose the same method 3914 // more than once. 3915 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 3916 3917 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 3918 MEnd = FinalOverriders.end(); 3919 M != MEnd; 3920 ++M) { 3921 for (OverridingMethods::iterator SO = M->second.begin(), 3922 SOEnd = M->second.end(); 3923 SO != SOEnd; ++SO) { 3924 // C++ [class.abstract]p4: 3925 // A class is abstract if it contains or inherits at least one 3926 // pure virtual function for which the final overrider is pure 3927 // virtual. 3928 3929 // 3930 if (SO->second.size() != 1) 3931 continue; 3932 3933 if (!SO->second.front().Method->isPure()) 3934 continue; 3935 3936 if (!SeenPureMethods.insert(SO->second.front().Method)) 3937 continue; 3938 3939 Diag(SO->second.front().Method->getLocation(), 3940 diag::note_pure_virtual_function) 3941 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 3942 } 3943 } 3944 3945 if (!PureVirtualClassDiagSet) 3946 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 3947 PureVirtualClassDiagSet->insert(RD); 3948} 3949 3950namespace { 3951struct AbstractUsageInfo { 3952 Sema &S; 3953 CXXRecordDecl *Record; 3954 CanQualType AbstractType; 3955 bool Invalid; 3956 3957 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 3958 : S(S), Record(Record), 3959 AbstractType(S.Context.getCanonicalType( 3960 S.Context.getTypeDeclType(Record))), 3961 Invalid(false) {} 3962 3963 void DiagnoseAbstractType() { 3964 if (Invalid) return; 3965 S.DiagnoseAbstractType(Record); 3966 Invalid = true; 3967 } 3968 3969 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 3970}; 3971 3972struct CheckAbstractUsage { 3973 AbstractUsageInfo &Info; 3974 const NamedDecl *Ctx; 3975 3976 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 3977 : Info(Info), Ctx(Ctx) {} 3978 3979 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 3980 switch (TL.getTypeLocClass()) { 3981#define ABSTRACT_TYPELOC(CLASS, PARENT) 3982#define TYPELOC(CLASS, PARENT) \ 3983 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 3984#include "clang/AST/TypeLocNodes.def" 3985 } 3986 } 3987 3988 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 3989 Visit(TL.getResultLoc(), Sema::AbstractReturnType); 3990 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 3991 if (!TL.getArg(I)) 3992 continue; 3993 3994 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo(); 3995 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 3996 } 3997 } 3998 3999 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4000 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 4001 } 4002 4003 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4004 // Visit the type parameters from a permissive context. 4005 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 4006 TemplateArgumentLoc TAL = TL.getArgLoc(I); 4007 if (TAL.getArgument().getKind() == TemplateArgument::Type) 4008 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 4009 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 4010 // TODO: other template argument types? 4011 } 4012 } 4013 4014 // Visit pointee types from a permissive context. 4015#define CheckPolymorphic(Type) \ 4016 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 4017 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 4018 } 4019 CheckPolymorphic(PointerTypeLoc) 4020 CheckPolymorphic(ReferenceTypeLoc) 4021 CheckPolymorphic(MemberPointerTypeLoc) 4022 CheckPolymorphic(BlockPointerTypeLoc) 4023 CheckPolymorphic(AtomicTypeLoc) 4024 4025 /// Handle all the types we haven't given a more specific 4026 /// implementation for above. 4027 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 4028 // Every other kind of type that we haven't called out already 4029 // that has an inner type is either (1) sugar or (2) contains that 4030 // inner type in some way as a subobject. 4031 if (TypeLoc Next = TL.getNextTypeLoc()) 4032 return Visit(Next, Sel); 4033 4034 // If there's no inner type and we're in a permissive context, 4035 // don't diagnose. 4036 if (Sel == Sema::AbstractNone) return; 4037 4038 // Check whether the type matches the abstract type. 4039 QualType T = TL.getType(); 4040 if (T->isArrayType()) { 4041 Sel = Sema::AbstractArrayType; 4042 T = Info.S.Context.getBaseElementType(T); 4043 } 4044 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 4045 if (CT != Info.AbstractType) return; 4046 4047 // It matched; do some magic. 4048 if (Sel == Sema::AbstractArrayType) { 4049 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 4050 << T << TL.getSourceRange(); 4051 } else { 4052 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 4053 << Sel << T << TL.getSourceRange(); 4054 } 4055 Info.DiagnoseAbstractType(); 4056 } 4057}; 4058 4059void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 4060 Sema::AbstractDiagSelID Sel) { 4061 CheckAbstractUsage(*this, D).Visit(TL, Sel); 4062} 4063 4064} 4065 4066/// Check for invalid uses of an abstract type in a method declaration. 4067static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4068 CXXMethodDecl *MD) { 4069 // No need to do the check on definitions, which require that 4070 // the return/param types be complete. 4071 if (MD->doesThisDeclarationHaveABody()) 4072 return; 4073 4074 // For safety's sake, just ignore it if we don't have type source 4075 // information. This should never happen for non-implicit methods, 4076 // but... 4077 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 4078 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 4079} 4080 4081/// Check for invalid uses of an abstract type within a class definition. 4082static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4083 CXXRecordDecl *RD) { 4084 for (CXXRecordDecl::decl_iterator 4085 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) { 4086 Decl *D = *I; 4087 if (D->isImplicit()) continue; 4088 4089 // Methods and method templates. 4090 if (isa<CXXMethodDecl>(D)) { 4091 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 4092 } else if (isa<FunctionTemplateDecl>(D)) { 4093 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 4094 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 4095 4096 // Fields and static variables. 4097 } else if (isa<FieldDecl>(D)) { 4098 FieldDecl *FD = cast<FieldDecl>(D); 4099 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 4100 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 4101 } else if (isa<VarDecl>(D)) { 4102 VarDecl *VD = cast<VarDecl>(D); 4103 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 4104 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 4105 4106 // Nested classes and class templates. 4107 } else if (isa<CXXRecordDecl>(D)) { 4108 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 4109 } else if (isa<ClassTemplateDecl>(D)) { 4110 CheckAbstractClassUsage(Info, 4111 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 4112 } 4113 } 4114} 4115 4116/// \brief Perform semantic checks on a class definition that has been 4117/// completing, introducing implicitly-declared members, checking for 4118/// abstract types, etc. 4119void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 4120 if (!Record) 4121 return; 4122 4123 if (Record->isAbstract() && !Record->isInvalidDecl()) { 4124 AbstractUsageInfo Info(*this, Record); 4125 CheckAbstractClassUsage(Info, Record); 4126 } 4127 4128 // If this is not an aggregate type and has no user-declared constructor, 4129 // complain about any non-static data members of reference or const scalar 4130 // type, since they will never get initializers. 4131 if (!Record->isInvalidDecl() && !Record->isDependentType() && 4132 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 4133 !Record->isLambda()) { 4134 bool Complained = false; 4135 for (RecordDecl::field_iterator F = Record->field_begin(), 4136 FEnd = Record->field_end(); 4137 F != FEnd; ++F) { 4138 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 4139 continue; 4140 4141 if (F->getType()->isReferenceType() || 4142 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 4143 if (!Complained) { 4144 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 4145 << Record->getTagKind() << Record; 4146 Complained = true; 4147 } 4148 4149 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 4150 << F->getType()->isReferenceType() 4151 << F->getDeclName(); 4152 } 4153 } 4154 } 4155 4156 if (Record->isDynamicClass() && !Record->isDependentType()) 4157 DynamicClasses.push_back(Record); 4158 4159 if (Record->getIdentifier()) { 4160 // C++ [class.mem]p13: 4161 // If T is the name of a class, then each of the following shall have a 4162 // name different from T: 4163 // - every member of every anonymous union that is a member of class T. 4164 // 4165 // C++ [class.mem]p14: 4166 // In addition, if class T has a user-declared constructor (12.1), every 4167 // non-static data member of class T shall have a name different from T. 4168 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 4169 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 4170 ++I) { 4171 NamedDecl *D = *I; 4172 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 4173 isa<IndirectFieldDecl>(D)) { 4174 Diag(D->getLocation(), diag::err_member_name_of_class) 4175 << D->getDeclName(); 4176 break; 4177 } 4178 } 4179 } 4180 4181 // Warn if the class has virtual methods but non-virtual public destructor. 4182 if (Record->isPolymorphic() && !Record->isDependentType()) { 4183 CXXDestructorDecl *dtor = Record->getDestructor(); 4184 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) 4185 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 4186 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 4187 } 4188 4189 if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) { 4190 Diag(Record->getLocation(), diag::warn_abstract_final_class); 4191 DiagnoseAbstractType(Record); 4192 } 4193 4194 if (!Record->isDependentType()) { 4195 for (CXXRecordDecl::method_iterator M = Record->method_begin(), 4196 MEnd = Record->method_end(); 4197 M != MEnd; ++M) { 4198 // See if a method overloads virtual methods in a base 4199 // class without overriding any. 4200 if (!M->isStatic()) 4201 DiagnoseHiddenVirtualMethods(Record, *M); 4202 4203 // Check whether the explicitly-defaulted special members are valid. 4204 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) 4205 CheckExplicitlyDefaultedSpecialMember(*M); 4206 4207 // For an explicitly defaulted or deleted special member, we defer 4208 // determining triviality until the class is complete. That time is now! 4209 if (!M->isImplicit() && !M->isUserProvided()) { 4210 CXXSpecialMember CSM = getSpecialMember(*M); 4211 if (CSM != CXXInvalid) { 4212 M->setTrivial(SpecialMemberIsTrivial(*M, CSM)); 4213 4214 // Inform the class that we've finished declaring this member. 4215 Record->finishedDefaultedOrDeletedMember(*M); 4216 } 4217 } 4218 } 4219 } 4220 4221 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member 4222 // function that is not a constructor declares that member function to be 4223 // const. [...] The class of which that function is a member shall be 4224 // a literal type. 4225 // 4226 // If the class has virtual bases, any constexpr members will already have 4227 // been diagnosed by the checks performed on the member declaration, so 4228 // suppress this (less useful) diagnostic. 4229 // 4230 // We delay this until we know whether an explicitly-defaulted (or deleted) 4231 // destructor for the class is trivial. 4232 if (LangOpts.CPlusPlus11 && !Record->isDependentType() && 4233 !Record->isLiteral() && !Record->getNumVBases()) { 4234 for (CXXRecordDecl::method_iterator M = Record->method_begin(), 4235 MEnd = Record->method_end(); 4236 M != MEnd; ++M) { 4237 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) { 4238 switch (Record->getTemplateSpecializationKind()) { 4239 case TSK_ImplicitInstantiation: 4240 case TSK_ExplicitInstantiationDeclaration: 4241 case TSK_ExplicitInstantiationDefinition: 4242 // If a template instantiates to a non-literal type, but its members 4243 // instantiate to constexpr functions, the template is technically 4244 // ill-formed, but we allow it for sanity. 4245 continue; 4246 4247 case TSK_Undeclared: 4248 case TSK_ExplicitSpecialization: 4249 RequireLiteralType(M->getLocation(), Context.getRecordType(Record), 4250 diag::err_constexpr_method_non_literal); 4251 break; 4252 } 4253 4254 // Only produce one error per class. 4255 break; 4256 } 4257 } 4258 } 4259 4260 // Declare inheriting constructors. We do this eagerly here because: 4261 // - The standard requires an eager diagnostic for conflicting inheriting 4262 // constructors from different classes. 4263 // - The lazy declaration of the other implicit constructors is so as to not 4264 // waste space and performance on classes that are not meant to be 4265 // instantiated (e.g. meta-functions). This doesn't apply to classes that 4266 // have inheriting constructors. 4267 DeclareInheritingConstructors(Record); 4268} 4269 4270/// Is the special member function which would be selected to perform the 4271/// specified operation on the specified class type a constexpr constructor? 4272static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 4273 Sema::CXXSpecialMember CSM, 4274 bool ConstArg) { 4275 Sema::SpecialMemberOverloadResult *SMOR = 4276 S.LookupSpecialMember(ClassDecl, CSM, ConstArg, 4277 false, false, false, false); 4278 if (!SMOR || !SMOR->getMethod()) 4279 // A constructor we wouldn't select can't be "involved in initializing" 4280 // anything. 4281 return true; 4282 return SMOR->getMethod()->isConstexpr(); 4283} 4284 4285/// Determine whether the specified special member function would be constexpr 4286/// if it were implicitly defined. 4287static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 4288 Sema::CXXSpecialMember CSM, 4289 bool ConstArg) { 4290 if (!S.getLangOpts().CPlusPlus11) 4291 return false; 4292 4293 // C++11 [dcl.constexpr]p4: 4294 // In the definition of a constexpr constructor [...] 4295 bool Ctor = true; 4296 switch (CSM) { 4297 case Sema::CXXDefaultConstructor: 4298 // Since default constructor lookup is essentially trivial (and cannot 4299 // involve, for instance, template instantiation), we compute whether a 4300 // defaulted default constructor is constexpr directly within CXXRecordDecl. 4301 // 4302 // This is important for performance; we need to know whether the default 4303 // constructor is constexpr to determine whether the type is a literal type. 4304 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 4305 4306 case Sema::CXXCopyConstructor: 4307 case Sema::CXXMoveConstructor: 4308 // For copy or move constructors, we need to perform overload resolution. 4309 break; 4310 4311 case Sema::CXXCopyAssignment: 4312 case Sema::CXXMoveAssignment: 4313 if (!S.getLangOpts().CPlusPlus1y) 4314 return false; 4315 // In C++1y, we need to perform overload resolution. 4316 Ctor = false; 4317 break; 4318 4319 case Sema::CXXDestructor: 4320 case Sema::CXXInvalid: 4321 return false; 4322 } 4323 4324 // -- if the class is a non-empty union, or for each non-empty anonymous 4325 // union member of a non-union class, exactly one non-static data member 4326 // shall be initialized; [DR1359] 4327 // 4328 // If we squint, this is guaranteed, since exactly one non-static data member 4329 // will be initialized (if the constructor isn't deleted), we just don't know 4330 // which one. 4331 if (Ctor && ClassDecl->isUnion()) 4332 return true; 4333 4334 // -- the class shall not have any virtual base classes; 4335 if (Ctor && ClassDecl->getNumVBases()) 4336 return false; 4337 4338 // C++1y [class.copy]p26: 4339 // -- [the class] is a literal type, and 4340 if (!Ctor && !ClassDecl->isLiteral()) 4341 return false; 4342 4343 // -- every constructor involved in initializing [...] base class 4344 // sub-objects shall be a constexpr constructor; 4345 // -- the assignment operator selected to copy/move each direct base 4346 // class is a constexpr function, and 4347 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 4348 BEnd = ClassDecl->bases_end(); 4349 B != BEnd; ++B) { 4350 const RecordType *BaseType = B->getType()->getAs<RecordType>(); 4351 if (!BaseType) continue; 4352 4353 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 4354 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg)) 4355 return false; 4356 } 4357 4358 // -- every constructor involved in initializing non-static data members 4359 // [...] shall be a constexpr constructor; 4360 // -- every non-static data member and base class sub-object shall be 4361 // initialized 4362 // -- for each non-stastic data member of X that is of class type (or array 4363 // thereof), the assignment operator selected to copy/move that member is 4364 // a constexpr function 4365 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 4366 FEnd = ClassDecl->field_end(); 4367 F != FEnd; ++F) { 4368 if (F->isInvalidDecl()) 4369 continue; 4370 if (const RecordType *RecordTy = 4371 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 4372 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 4373 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg)) 4374 return false; 4375 } 4376 } 4377 4378 // All OK, it's constexpr! 4379 return true; 4380} 4381 4382static Sema::ImplicitExceptionSpecification 4383computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 4384 switch (S.getSpecialMember(MD)) { 4385 case Sema::CXXDefaultConstructor: 4386 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD); 4387 case Sema::CXXCopyConstructor: 4388 return S.ComputeDefaultedCopyCtorExceptionSpec(MD); 4389 case Sema::CXXCopyAssignment: 4390 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD); 4391 case Sema::CXXMoveConstructor: 4392 return S.ComputeDefaultedMoveCtorExceptionSpec(MD); 4393 case Sema::CXXMoveAssignment: 4394 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD); 4395 case Sema::CXXDestructor: 4396 return S.ComputeDefaultedDtorExceptionSpec(MD); 4397 case Sema::CXXInvalid: 4398 break; 4399 } 4400 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() && 4401 "only special members have implicit exception specs"); 4402 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD)); 4403} 4404 4405static void 4406updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT, 4407 const Sema::ImplicitExceptionSpecification &ExceptSpec) { 4408 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 4409 ExceptSpec.getEPI(EPI); 4410 FD->setType(S.Context.getFunctionType(FPT->getResultType(), 4411 FPT->getArgTypes(), EPI)); 4412} 4413 4414void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 4415 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 4416 if (FPT->getExceptionSpecType() != EST_Unevaluated) 4417 return; 4418 4419 // Evaluate the exception specification. 4420 ImplicitExceptionSpecification ExceptSpec = 4421 computeImplicitExceptionSpec(*this, Loc, MD); 4422 4423 // Update the type of the special member to use it. 4424 updateExceptionSpec(*this, MD, FPT, ExceptSpec); 4425 4426 // A user-provided destructor can be defined outside the class. When that 4427 // happens, be sure to update the exception specification on both 4428 // declarations. 4429 const FunctionProtoType *CanonicalFPT = 4430 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 4431 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 4432 updateExceptionSpec(*this, MD->getCanonicalDecl(), 4433 CanonicalFPT, ExceptSpec); 4434} 4435 4436void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 4437 CXXRecordDecl *RD = MD->getParent(); 4438 CXXSpecialMember CSM = getSpecialMember(MD); 4439 4440 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 4441 "not an explicitly-defaulted special member"); 4442 4443 // Whether this was the first-declared instance of the constructor. 4444 // This affects whether we implicitly add an exception spec and constexpr. 4445 bool First = MD == MD->getCanonicalDecl(); 4446 4447 bool HadError = false; 4448 4449 // C++11 [dcl.fct.def.default]p1: 4450 // A function that is explicitly defaulted shall 4451 // -- be a special member function (checked elsewhere), 4452 // -- have the same type (except for ref-qualifiers, and except that a 4453 // copy operation can take a non-const reference) as an implicit 4454 // declaration, and 4455 // -- not have default arguments. 4456 unsigned ExpectedParams = 1; 4457 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 4458 ExpectedParams = 0; 4459 if (MD->getNumParams() != ExpectedParams) { 4460 // This also checks for default arguments: a copy or move constructor with a 4461 // default argument is classified as a default constructor, and assignment 4462 // operations and destructors can't have default arguments. 4463 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 4464 << CSM << MD->getSourceRange(); 4465 HadError = true; 4466 } else if (MD->isVariadic()) { 4467 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 4468 << CSM << MD->getSourceRange(); 4469 HadError = true; 4470 } 4471 4472 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 4473 4474 bool CanHaveConstParam = false; 4475 if (CSM == CXXCopyConstructor) 4476 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 4477 else if (CSM == CXXCopyAssignment) 4478 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 4479 4480 QualType ReturnType = Context.VoidTy; 4481 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 4482 // Check for return type matching. 4483 ReturnType = Type->getResultType(); 4484 QualType ExpectedReturnType = 4485 Context.getLValueReferenceType(Context.getTypeDeclType(RD)); 4486 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 4487 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 4488 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 4489 HadError = true; 4490 } 4491 4492 // A defaulted special member cannot have cv-qualifiers. 4493 if (Type->getTypeQuals()) { 4494 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 4495 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y; 4496 HadError = true; 4497 } 4498 } 4499 4500 // Check for parameter type matching. 4501 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType(); 4502 bool HasConstParam = false; 4503 if (ExpectedParams && ArgType->isReferenceType()) { 4504 // Argument must be reference to possibly-const T. 4505 QualType ReferentType = ArgType->getPointeeType(); 4506 HasConstParam = ReferentType.isConstQualified(); 4507 4508 if (ReferentType.isVolatileQualified()) { 4509 Diag(MD->getLocation(), 4510 diag::err_defaulted_special_member_volatile_param) << CSM; 4511 HadError = true; 4512 } 4513 4514 if (HasConstParam && !CanHaveConstParam) { 4515 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 4516 Diag(MD->getLocation(), 4517 diag::err_defaulted_special_member_copy_const_param) 4518 << (CSM == CXXCopyAssignment); 4519 // FIXME: Explain why this special member can't be const. 4520 } else { 4521 Diag(MD->getLocation(), 4522 diag::err_defaulted_special_member_move_const_param) 4523 << (CSM == CXXMoveAssignment); 4524 } 4525 HadError = true; 4526 } 4527 } else if (ExpectedParams) { 4528 // A copy assignment operator can take its argument by value, but a 4529 // defaulted one cannot. 4530 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 4531 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 4532 HadError = true; 4533 } 4534 4535 // C++11 [dcl.fct.def.default]p2: 4536 // An explicitly-defaulted function may be declared constexpr only if it 4537 // would have been implicitly declared as constexpr, 4538 // Do not apply this rule to members of class templates, since core issue 1358 4539 // makes such functions always instantiate to constexpr functions. For 4540 // functions which cannot be constexpr (for non-constructors in C++11 and for 4541 // destructors in C++1y), this is checked elsewhere. 4542 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 4543 HasConstParam); 4544 if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD) 4545 : isa<CXXConstructorDecl>(MD)) && 4546 MD->isConstexpr() && !Constexpr && 4547 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 4548 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM; 4549 // FIXME: Explain why the special member can't be constexpr. 4550 HadError = true; 4551 } 4552 4553 // and may have an explicit exception-specification only if it is compatible 4554 // with the exception-specification on the implicit declaration. 4555 if (Type->hasExceptionSpec()) { 4556 // Delay the check if this is the first declaration of the special member, 4557 // since we may not have parsed some necessary in-class initializers yet. 4558 if (First) { 4559 // If the exception specification needs to be instantiated, do so now, 4560 // before we clobber it with an EST_Unevaluated specification below. 4561 if (Type->getExceptionSpecType() == EST_Uninstantiated) { 4562 InstantiateExceptionSpec(MD->getLocStart(), MD); 4563 Type = MD->getType()->getAs<FunctionProtoType>(); 4564 } 4565 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type)); 4566 } else 4567 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type); 4568 } 4569 4570 // If a function is explicitly defaulted on its first declaration, 4571 if (First) { 4572 // -- it is implicitly considered to be constexpr if the implicit 4573 // definition would be, 4574 MD->setConstexpr(Constexpr); 4575 4576 // -- it is implicitly considered to have the same exception-specification 4577 // as if it had been implicitly declared, 4578 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 4579 EPI.ExceptionSpecType = EST_Unevaluated; 4580 EPI.ExceptionSpecDecl = MD; 4581 MD->setType(Context.getFunctionType(ReturnType, 4582 ArrayRef<QualType>(&ArgType, 4583 ExpectedParams), 4584 EPI)); 4585 } 4586 4587 if (ShouldDeleteSpecialMember(MD, CSM)) { 4588 if (First) { 4589 SetDeclDeleted(MD, MD->getLocation()); 4590 } else { 4591 // C++11 [dcl.fct.def.default]p4: 4592 // [For a] user-provided explicitly-defaulted function [...] if such a 4593 // function is implicitly defined as deleted, the program is ill-formed. 4594 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 4595 HadError = true; 4596 } 4597 } 4598 4599 if (HadError) 4600 MD->setInvalidDecl(); 4601} 4602 4603/// Check whether the exception specification provided for an 4604/// explicitly-defaulted special member matches the exception specification 4605/// that would have been generated for an implicit special member, per 4606/// C++11 [dcl.fct.def.default]p2. 4607void Sema::CheckExplicitlyDefaultedMemberExceptionSpec( 4608 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) { 4609 // Compute the implicit exception specification. 4610 FunctionProtoType::ExtProtoInfo EPI; 4611 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI); 4612 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>( 4613 Context.getFunctionType(Context.VoidTy, None, EPI)); 4614 4615 // Ensure that it matches. 4616 CheckEquivalentExceptionSpec( 4617 PDiag(diag::err_incorrect_defaulted_exception_spec) 4618 << getSpecialMember(MD), PDiag(), 4619 ImplicitType, SourceLocation(), 4620 SpecifiedType, MD->getLocation()); 4621} 4622 4623void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() { 4624 for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size(); 4625 I != N; ++I) 4626 CheckExplicitlyDefaultedMemberExceptionSpec( 4627 DelayedDefaultedMemberExceptionSpecs[I].first, 4628 DelayedDefaultedMemberExceptionSpecs[I].second); 4629 4630 DelayedDefaultedMemberExceptionSpecs.clear(); 4631} 4632 4633namespace { 4634struct SpecialMemberDeletionInfo { 4635 Sema &S; 4636 CXXMethodDecl *MD; 4637 Sema::CXXSpecialMember CSM; 4638 bool Diagnose; 4639 4640 // Properties of the special member, computed for convenience. 4641 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg; 4642 SourceLocation Loc; 4643 4644 bool AllFieldsAreConst; 4645 4646 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 4647 Sema::CXXSpecialMember CSM, bool Diagnose) 4648 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose), 4649 IsConstructor(false), IsAssignment(false), IsMove(false), 4650 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()), 4651 AllFieldsAreConst(true) { 4652 switch (CSM) { 4653 case Sema::CXXDefaultConstructor: 4654 case Sema::CXXCopyConstructor: 4655 IsConstructor = true; 4656 break; 4657 case Sema::CXXMoveConstructor: 4658 IsConstructor = true; 4659 IsMove = true; 4660 break; 4661 case Sema::CXXCopyAssignment: 4662 IsAssignment = true; 4663 break; 4664 case Sema::CXXMoveAssignment: 4665 IsAssignment = true; 4666 IsMove = true; 4667 break; 4668 case Sema::CXXDestructor: 4669 break; 4670 case Sema::CXXInvalid: 4671 llvm_unreachable("invalid special member kind"); 4672 } 4673 4674 if (MD->getNumParams()) { 4675 ConstArg = MD->getParamDecl(0)->getType().isConstQualified(); 4676 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified(); 4677 } 4678 } 4679 4680 bool inUnion() const { return MD->getParent()->isUnion(); } 4681 4682 /// Look up the corresponding special member in the given class. 4683 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class, 4684 unsigned Quals) { 4685 unsigned TQ = MD->getTypeQualifiers(); 4686 // cv-qualifiers on class members don't affect default ctor / dtor calls. 4687 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 4688 Quals = 0; 4689 return S.LookupSpecialMember(Class, CSM, 4690 ConstArg || (Quals & Qualifiers::Const), 4691 VolatileArg || (Quals & Qualifiers::Volatile), 4692 MD->getRefQualifier() == RQ_RValue, 4693 TQ & Qualifiers::Const, 4694 TQ & Qualifiers::Volatile); 4695 } 4696 4697 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 4698 4699 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 4700 bool shouldDeleteForField(FieldDecl *FD); 4701 bool shouldDeleteForAllConstMembers(); 4702 4703 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 4704 unsigned Quals); 4705 bool shouldDeleteForSubobjectCall(Subobject Subobj, 4706 Sema::SpecialMemberOverloadResult *SMOR, 4707 bool IsDtorCallInCtor); 4708 4709 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 4710}; 4711} 4712 4713/// Is the given special member inaccessible when used on the given 4714/// sub-object. 4715bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 4716 CXXMethodDecl *target) { 4717 /// If we're operating on a base class, the object type is the 4718 /// type of this special member. 4719 QualType objectTy; 4720 AccessSpecifier access = target->getAccess(); 4721 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 4722 objectTy = S.Context.getTypeDeclType(MD->getParent()); 4723 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 4724 4725 // If we're operating on a field, the object type is the type of the field. 4726 } else { 4727 objectTy = S.Context.getTypeDeclType(target->getParent()); 4728 } 4729 4730 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 4731} 4732 4733/// Check whether we should delete a special member due to the implicit 4734/// definition containing a call to a special member of a subobject. 4735bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 4736 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR, 4737 bool IsDtorCallInCtor) { 4738 CXXMethodDecl *Decl = SMOR->getMethod(); 4739 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 4740 4741 int DiagKind = -1; 4742 4743 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 4744 DiagKind = !Decl ? 0 : 1; 4745 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 4746 DiagKind = 2; 4747 else if (!isAccessible(Subobj, Decl)) 4748 DiagKind = 3; 4749 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 4750 !Decl->isTrivial()) { 4751 // A member of a union must have a trivial corresponding special member. 4752 // As a weird special case, a destructor call from a union's constructor 4753 // must be accessible and non-deleted, but need not be trivial. Such a 4754 // destructor is never actually called, but is semantically checked as 4755 // if it were. 4756 DiagKind = 4; 4757 } 4758 4759 if (DiagKind == -1) 4760 return false; 4761 4762 if (Diagnose) { 4763 if (Field) { 4764 S.Diag(Field->getLocation(), 4765 diag::note_deleted_special_member_class_subobject) 4766 << CSM << MD->getParent() << /*IsField*/true 4767 << Field << DiagKind << IsDtorCallInCtor; 4768 } else { 4769 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 4770 S.Diag(Base->getLocStart(), 4771 diag::note_deleted_special_member_class_subobject) 4772 << CSM << MD->getParent() << /*IsField*/false 4773 << Base->getType() << DiagKind << IsDtorCallInCtor; 4774 } 4775 4776 if (DiagKind == 1) 4777 S.NoteDeletedFunction(Decl); 4778 // FIXME: Explain inaccessibility if DiagKind == 3. 4779 } 4780 4781 return true; 4782} 4783 4784/// Check whether we should delete a special member function due to having a 4785/// direct or virtual base class or non-static data member of class type M. 4786bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 4787 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 4788 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 4789 4790 // C++11 [class.ctor]p5: 4791 // -- any direct or virtual base class, or non-static data member with no 4792 // brace-or-equal-initializer, has class type M (or array thereof) and 4793 // either M has no default constructor or overload resolution as applied 4794 // to M's default constructor results in an ambiguity or in a function 4795 // that is deleted or inaccessible 4796 // C++11 [class.copy]p11, C++11 [class.copy]p23: 4797 // -- a direct or virtual base class B that cannot be copied/moved because 4798 // overload resolution, as applied to B's corresponding special member, 4799 // results in an ambiguity or a function that is deleted or inaccessible 4800 // from the defaulted special member 4801 // C++11 [class.dtor]p5: 4802 // -- any direct or virtual base class [...] has a type with a destructor 4803 // that is deleted or inaccessible 4804 if (!(CSM == Sema::CXXDefaultConstructor && 4805 Field && Field->hasInClassInitializer()) && 4806 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false)) 4807 return true; 4808 4809 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 4810 // -- any direct or virtual base class or non-static data member has a 4811 // type with a destructor that is deleted or inaccessible 4812 if (IsConstructor) { 4813 Sema::SpecialMemberOverloadResult *SMOR = 4814 S.LookupSpecialMember(Class, Sema::CXXDestructor, 4815 false, false, false, false, false); 4816 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 4817 return true; 4818 } 4819 4820 return false; 4821} 4822 4823/// Check whether we should delete a special member function due to the class 4824/// having a particular direct or virtual base class. 4825bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 4826 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 4827 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 4828} 4829 4830/// Check whether we should delete a special member function due to the class 4831/// having a particular non-static data member. 4832bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 4833 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 4834 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 4835 4836 if (CSM == Sema::CXXDefaultConstructor) { 4837 // For a default constructor, all references must be initialized in-class 4838 // and, if a union, it must have a non-const member. 4839 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 4840 if (Diagnose) 4841 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 4842 << MD->getParent() << FD << FieldType << /*Reference*/0; 4843 return true; 4844 } 4845 // C++11 [class.ctor]p5: any non-variant non-static data member of 4846 // const-qualified type (or array thereof) with no 4847 // brace-or-equal-initializer does not have a user-provided default 4848 // constructor. 4849 if (!inUnion() && FieldType.isConstQualified() && 4850 !FD->hasInClassInitializer() && 4851 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 4852 if (Diagnose) 4853 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 4854 << MD->getParent() << FD << FD->getType() << /*Const*/1; 4855 return true; 4856 } 4857 4858 if (inUnion() && !FieldType.isConstQualified()) 4859 AllFieldsAreConst = false; 4860 } else if (CSM == Sema::CXXCopyConstructor) { 4861 // For a copy constructor, data members must not be of rvalue reference 4862 // type. 4863 if (FieldType->isRValueReferenceType()) { 4864 if (Diagnose) 4865 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 4866 << MD->getParent() << FD << FieldType; 4867 return true; 4868 } 4869 } else if (IsAssignment) { 4870 // For an assignment operator, data members must not be of reference type. 4871 if (FieldType->isReferenceType()) { 4872 if (Diagnose) 4873 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 4874 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0; 4875 return true; 4876 } 4877 if (!FieldRecord && FieldType.isConstQualified()) { 4878 // C++11 [class.copy]p23: 4879 // -- a non-static data member of const non-class type (or array thereof) 4880 if (Diagnose) 4881 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 4882 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1; 4883 return true; 4884 } 4885 } 4886 4887 if (FieldRecord) { 4888 // Some additional restrictions exist on the variant members. 4889 if (!inUnion() && FieldRecord->isUnion() && 4890 FieldRecord->isAnonymousStructOrUnion()) { 4891 bool AllVariantFieldsAreConst = true; 4892 4893 // FIXME: Handle anonymous unions declared within anonymous unions. 4894 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(), 4895 UE = FieldRecord->field_end(); 4896 UI != UE; ++UI) { 4897 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 4898 4899 if (!UnionFieldType.isConstQualified()) 4900 AllVariantFieldsAreConst = false; 4901 4902 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 4903 if (UnionFieldRecord && 4904 shouldDeleteForClassSubobject(UnionFieldRecord, *UI, 4905 UnionFieldType.getCVRQualifiers())) 4906 return true; 4907 } 4908 4909 // At least one member in each anonymous union must be non-const 4910 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 4911 FieldRecord->field_begin() != FieldRecord->field_end()) { 4912 if (Diagnose) 4913 S.Diag(FieldRecord->getLocation(), 4914 diag::note_deleted_default_ctor_all_const) 4915 << MD->getParent() << /*anonymous union*/1; 4916 return true; 4917 } 4918 4919 // Don't check the implicit member of the anonymous union type. 4920 // This is technically non-conformant, but sanity demands it. 4921 return false; 4922 } 4923 4924 if (shouldDeleteForClassSubobject(FieldRecord, FD, 4925 FieldType.getCVRQualifiers())) 4926 return true; 4927 } 4928 4929 return false; 4930} 4931 4932/// C++11 [class.ctor] p5: 4933/// A defaulted default constructor for a class X is defined as deleted if 4934/// X is a union and all of its variant members are of const-qualified type. 4935bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 4936 // This is a silly definition, because it gives an empty union a deleted 4937 // default constructor. Don't do that. 4938 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst && 4939 (MD->getParent()->field_begin() != MD->getParent()->field_end())) { 4940 if (Diagnose) 4941 S.Diag(MD->getParent()->getLocation(), 4942 diag::note_deleted_default_ctor_all_const) 4943 << MD->getParent() << /*not anonymous union*/0; 4944 return true; 4945 } 4946 return false; 4947} 4948 4949/// Determine whether a defaulted special member function should be defined as 4950/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 4951/// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 4952bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 4953 bool Diagnose) { 4954 if (MD->isInvalidDecl()) 4955 return false; 4956 CXXRecordDecl *RD = MD->getParent(); 4957 assert(!RD->isDependentType() && "do deletion after instantiation"); 4958 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 4959 return false; 4960 4961 // C++11 [expr.lambda.prim]p19: 4962 // The closure type associated with a lambda-expression has a 4963 // deleted (8.4.3) default constructor and a deleted copy 4964 // assignment operator. 4965 if (RD->isLambda() && 4966 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 4967 if (Diagnose) 4968 Diag(RD->getLocation(), diag::note_lambda_decl); 4969 return true; 4970 } 4971 4972 // For an anonymous struct or union, the copy and assignment special members 4973 // will never be used, so skip the check. For an anonymous union declared at 4974 // namespace scope, the constructor and destructor are used. 4975 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 4976 RD->isAnonymousStructOrUnion()) 4977 return false; 4978 4979 // C++11 [class.copy]p7, p18: 4980 // If the class definition declares a move constructor or move assignment 4981 // operator, an implicitly declared copy constructor or copy assignment 4982 // operator is defined as deleted. 4983 if (MD->isImplicit() && 4984 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 4985 CXXMethodDecl *UserDeclaredMove = 0; 4986 4987 // In Microsoft mode, a user-declared move only causes the deletion of the 4988 // corresponding copy operation, not both copy operations. 4989 if (RD->hasUserDeclaredMoveConstructor() && 4990 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) { 4991 if (!Diagnose) return true; 4992 4993 // Find any user-declared move constructor. 4994 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(), 4995 E = RD->ctor_end(); I != E; ++I) { 4996 if (I->isMoveConstructor()) { 4997 UserDeclaredMove = *I; 4998 break; 4999 } 5000 } 5001 assert(UserDeclaredMove); 5002 } else if (RD->hasUserDeclaredMoveAssignment() && 5003 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) { 5004 if (!Diagnose) return true; 5005 5006 // Find any user-declared move assignment operator. 5007 for (CXXRecordDecl::method_iterator I = RD->method_begin(), 5008 E = RD->method_end(); I != E; ++I) { 5009 if (I->isMoveAssignmentOperator()) { 5010 UserDeclaredMove = *I; 5011 break; 5012 } 5013 } 5014 assert(UserDeclaredMove); 5015 } 5016 5017 if (UserDeclaredMove) { 5018 Diag(UserDeclaredMove->getLocation(), 5019 diag::note_deleted_copy_user_declared_move) 5020 << (CSM == CXXCopyAssignment) << RD 5021 << UserDeclaredMove->isMoveAssignmentOperator(); 5022 return true; 5023 } 5024 } 5025 5026 // Do access control from the special member function 5027 ContextRAII MethodContext(*this, MD); 5028 5029 // C++11 [class.dtor]p5: 5030 // -- for a virtual destructor, lookup of the non-array deallocation function 5031 // results in an ambiguity or in a function that is deleted or inaccessible 5032 if (CSM == CXXDestructor && MD->isVirtual()) { 5033 FunctionDecl *OperatorDelete = 0; 5034 DeclarationName Name = 5035 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 5036 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 5037 OperatorDelete, false)) { 5038 if (Diagnose) 5039 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 5040 return true; 5041 } 5042 } 5043 5044 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose); 5045 5046 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 5047 BE = RD->bases_end(); BI != BE; ++BI) 5048 if (!BI->isVirtual() && 5049 SMI.shouldDeleteForBase(BI)) 5050 return true; 5051 5052 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(), 5053 BE = RD->vbases_end(); BI != BE; ++BI) 5054 if (SMI.shouldDeleteForBase(BI)) 5055 return true; 5056 5057 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 5058 FE = RD->field_end(); FI != FE; ++FI) 5059 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() && 5060 SMI.shouldDeleteForField(*FI)) 5061 return true; 5062 5063 if (SMI.shouldDeleteForAllConstMembers()) 5064 return true; 5065 5066 return false; 5067} 5068 5069/// Perform lookup for a special member of the specified kind, and determine 5070/// whether it is trivial. If the triviality can be determined without the 5071/// lookup, skip it. This is intended for use when determining whether a 5072/// special member of a containing object is trivial, and thus does not ever 5073/// perform overload resolution for default constructors. 5074/// 5075/// If \p Selected is not \c NULL, \c *Selected will be filled in with the 5076/// member that was most likely to be intended to be trivial, if any. 5077static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 5078 Sema::CXXSpecialMember CSM, unsigned Quals, 5079 CXXMethodDecl **Selected) { 5080 if (Selected) 5081 *Selected = 0; 5082 5083 switch (CSM) { 5084 case Sema::CXXInvalid: 5085 llvm_unreachable("not a special member"); 5086 5087 case Sema::CXXDefaultConstructor: 5088 // C++11 [class.ctor]p5: 5089 // A default constructor is trivial if: 5090 // - all the [direct subobjects] have trivial default constructors 5091 // 5092 // Note, no overload resolution is performed in this case. 5093 if (RD->hasTrivialDefaultConstructor()) 5094 return true; 5095 5096 if (Selected) { 5097 // If there's a default constructor which could have been trivial, dig it 5098 // out. Otherwise, if there's any user-provided default constructor, point 5099 // to that as an example of why there's not a trivial one. 5100 CXXConstructorDecl *DefCtor = 0; 5101 if (RD->needsImplicitDefaultConstructor()) 5102 S.DeclareImplicitDefaultConstructor(RD); 5103 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), 5104 CE = RD->ctor_end(); CI != CE; ++CI) { 5105 if (!CI->isDefaultConstructor()) 5106 continue; 5107 DefCtor = *CI; 5108 if (!DefCtor->isUserProvided()) 5109 break; 5110 } 5111 5112 *Selected = DefCtor; 5113 } 5114 5115 return false; 5116 5117 case Sema::CXXDestructor: 5118 // C++11 [class.dtor]p5: 5119 // A destructor is trivial if: 5120 // - all the direct [subobjects] have trivial destructors 5121 if (RD->hasTrivialDestructor()) 5122 return true; 5123 5124 if (Selected) { 5125 if (RD->needsImplicitDestructor()) 5126 S.DeclareImplicitDestructor(RD); 5127 *Selected = RD->getDestructor(); 5128 } 5129 5130 return false; 5131 5132 case Sema::CXXCopyConstructor: 5133 // C++11 [class.copy]p12: 5134 // A copy constructor is trivial if: 5135 // - the constructor selected to copy each direct [subobject] is trivial 5136 if (RD->hasTrivialCopyConstructor()) { 5137 if (Quals == Qualifiers::Const) 5138 // We must either select the trivial copy constructor or reach an 5139 // ambiguity; no need to actually perform overload resolution. 5140 return true; 5141 } else if (!Selected) { 5142 return false; 5143 } 5144 // In C++98, we are not supposed to perform overload resolution here, but we 5145 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 5146 // cases like B as having a non-trivial copy constructor: 5147 // struct A { template<typename T> A(T&); }; 5148 // struct B { mutable A a; }; 5149 goto NeedOverloadResolution; 5150 5151 case Sema::CXXCopyAssignment: 5152 // C++11 [class.copy]p25: 5153 // A copy assignment operator is trivial if: 5154 // - the assignment operator selected to copy each direct [subobject] is 5155 // trivial 5156 if (RD->hasTrivialCopyAssignment()) { 5157 if (Quals == Qualifiers::Const) 5158 return true; 5159 } else if (!Selected) { 5160 return false; 5161 } 5162 // In C++98, we are not supposed to perform overload resolution here, but we 5163 // treat that as a language defect. 5164 goto NeedOverloadResolution; 5165 5166 case Sema::CXXMoveConstructor: 5167 case Sema::CXXMoveAssignment: 5168 NeedOverloadResolution: 5169 Sema::SpecialMemberOverloadResult *SMOR = 5170 S.LookupSpecialMember(RD, CSM, 5171 Quals & Qualifiers::Const, 5172 Quals & Qualifiers::Volatile, 5173 /*RValueThis*/false, /*ConstThis*/false, 5174 /*VolatileThis*/false); 5175 5176 // The standard doesn't describe how to behave if the lookup is ambiguous. 5177 // We treat it as not making the member non-trivial, just like the standard 5178 // mandates for the default constructor. This should rarely matter, because 5179 // the member will also be deleted. 5180 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 5181 return true; 5182 5183 if (!SMOR->getMethod()) { 5184 assert(SMOR->getKind() == 5185 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 5186 return false; 5187 } 5188 5189 // We deliberately don't check if we found a deleted special member. We're 5190 // not supposed to! 5191 if (Selected) 5192 *Selected = SMOR->getMethod(); 5193 return SMOR->getMethod()->isTrivial(); 5194 } 5195 5196 llvm_unreachable("unknown special method kind"); 5197} 5198 5199static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 5200 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end(); 5201 CI != CE; ++CI) 5202 if (!CI->isImplicit()) 5203 return *CI; 5204 5205 // Look for constructor templates. 5206 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 5207 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 5208 if (CXXConstructorDecl *CD = 5209 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 5210 return CD; 5211 } 5212 5213 return 0; 5214} 5215 5216/// The kind of subobject we are checking for triviality. The values of this 5217/// enumeration are used in diagnostics. 5218enum TrivialSubobjectKind { 5219 /// The subobject is a base class. 5220 TSK_BaseClass, 5221 /// The subobject is a non-static data member. 5222 TSK_Field, 5223 /// The object is actually the complete object. 5224 TSK_CompleteObject 5225}; 5226 5227/// Check whether the special member selected for a given type would be trivial. 5228static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 5229 QualType SubType, 5230 Sema::CXXSpecialMember CSM, 5231 TrivialSubobjectKind Kind, 5232 bool Diagnose) { 5233 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 5234 if (!SubRD) 5235 return true; 5236 5237 CXXMethodDecl *Selected; 5238 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 5239 Diagnose ? &Selected : 0)) 5240 return true; 5241 5242 if (Diagnose) { 5243 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 5244 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 5245 << Kind << SubType.getUnqualifiedType(); 5246 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 5247 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 5248 } else if (!Selected) 5249 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 5250 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 5251 else if (Selected->isUserProvided()) { 5252 if (Kind == TSK_CompleteObject) 5253 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 5254 << Kind << SubType.getUnqualifiedType() << CSM; 5255 else { 5256 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 5257 << Kind << SubType.getUnqualifiedType() << CSM; 5258 S.Diag(Selected->getLocation(), diag::note_declared_at); 5259 } 5260 } else { 5261 if (Kind != TSK_CompleteObject) 5262 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 5263 << Kind << SubType.getUnqualifiedType() << CSM; 5264 5265 // Explain why the defaulted or deleted special member isn't trivial. 5266 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose); 5267 } 5268 } 5269 5270 return false; 5271} 5272 5273/// Check whether the members of a class type allow a special member to be 5274/// trivial. 5275static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 5276 Sema::CXXSpecialMember CSM, 5277 bool ConstArg, bool Diagnose) { 5278 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 5279 FE = RD->field_end(); FI != FE; ++FI) { 5280 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 5281 continue; 5282 5283 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 5284 5285 // Pretend anonymous struct or union members are members of this class. 5286 if (FI->isAnonymousStructOrUnion()) { 5287 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 5288 CSM, ConstArg, Diagnose)) 5289 return false; 5290 continue; 5291 } 5292 5293 // C++11 [class.ctor]p5: 5294 // A default constructor is trivial if [...] 5295 // -- no non-static data member of its class has a 5296 // brace-or-equal-initializer 5297 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 5298 if (Diagnose) 5299 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI; 5300 return false; 5301 } 5302 5303 // Objective C ARC 4.3.5: 5304 // [...] nontrivally ownership-qualified types are [...] not trivially 5305 // default constructible, copy constructible, move constructible, copy 5306 // assignable, move assignable, or destructible [...] 5307 if (S.getLangOpts().ObjCAutoRefCount && 5308 FieldType.hasNonTrivialObjCLifetime()) { 5309 if (Diagnose) 5310 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 5311 << RD << FieldType.getObjCLifetime(); 5312 return false; 5313 } 5314 5315 if (ConstArg && !FI->isMutable()) 5316 FieldType.addConst(); 5317 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM, 5318 TSK_Field, Diagnose)) 5319 return false; 5320 } 5321 5322 return true; 5323} 5324 5325/// Diagnose why the specified class does not have a trivial special member of 5326/// the given kind. 5327void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 5328 QualType Ty = Context.getRecordType(RD); 5329 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) 5330 Ty.addConst(); 5331 5332 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM, 5333 TSK_CompleteObject, /*Diagnose*/true); 5334} 5335 5336/// Determine whether a defaulted or deleted special member function is trivial, 5337/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 5338/// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 5339bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 5340 bool Diagnose) { 5341 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 5342 5343 CXXRecordDecl *RD = MD->getParent(); 5344 5345 bool ConstArg = false; 5346 5347 // C++11 [class.copy]p12, p25: 5348 // A [special member] is trivial if its declared parameter type is the same 5349 // as if it had been implicitly declared [...] 5350 switch (CSM) { 5351 case CXXDefaultConstructor: 5352 case CXXDestructor: 5353 // Trivial default constructors and destructors cannot have parameters. 5354 break; 5355 5356 case CXXCopyConstructor: 5357 case CXXCopyAssignment: { 5358 // Trivial copy operations always have const, non-volatile parameter types. 5359 ConstArg = true; 5360 const ParmVarDecl *Param0 = MD->getParamDecl(0); 5361 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 5362 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 5363 if (Diagnose) 5364 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 5365 << Param0->getSourceRange() << Param0->getType() 5366 << Context.getLValueReferenceType( 5367 Context.getRecordType(RD).withConst()); 5368 return false; 5369 } 5370 break; 5371 } 5372 5373 case CXXMoveConstructor: 5374 case CXXMoveAssignment: { 5375 // Trivial move operations always have non-cv-qualified parameters. 5376 const ParmVarDecl *Param0 = MD->getParamDecl(0); 5377 const RValueReferenceType *RT = 5378 Param0->getType()->getAs<RValueReferenceType>(); 5379 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 5380 if (Diagnose) 5381 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 5382 << Param0->getSourceRange() << Param0->getType() 5383 << Context.getRValueReferenceType(Context.getRecordType(RD)); 5384 return false; 5385 } 5386 break; 5387 } 5388 5389 case CXXInvalid: 5390 llvm_unreachable("not a special member"); 5391 } 5392 5393 // FIXME: We require that the parameter-declaration-clause is equivalent to 5394 // that of an implicit declaration, not just that the declared parameter type 5395 // matches, in order to prevent absuridities like a function simultaneously 5396 // being a trivial copy constructor and a non-trivial default constructor. 5397 // This issue has not yet been assigned a core issue number. 5398 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 5399 if (Diagnose) 5400 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 5401 diag::note_nontrivial_default_arg) 5402 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 5403 return false; 5404 } 5405 if (MD->isVariadic()) { 5406 if (Diagnose) 5407 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 5408 return false; 5409 } 5410 5411 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 5412 // A copy/move [constructor or assignment operator] is trivial if 5413 // -- the [member] selected to copy/move each direct base class subobject 5414 // is trivial 5415 // 5416 // C++11 [class.copy]p12, C++11 [class.copy]p25: 5417 // A [default constructor or destructor] is trivial if 5418 // -- all the direct base classes have trivial [default constructors or 5419 // destructors] 5420 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 5421 BE = RD->bases_end(); BI != BE; ++BI) 5422 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(), 5423 ConstArg ? BI->getType().withConst() 5424 : BI->getType(), 5425 CSM, TSK_BaseClass, Diagnose)) 5426 return false; 5427 5428 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 5429 // A copy/move [constructor or assignment operator] for a class X is 5430 // trivial if 5431 // -- for each non-static data member of X that is of class type (or array 5432 // thereof), the constructor selected to copy/move that member is 5433 // trivial 5434 // 5435 // C++11 [class.copy]p12, C++11 [class.copy]p25: 5436 // A [default constructor or destructor] is trivial if 5437 // -- for all of the non-static data members of its class that are of class 5438 // type (or array thereof), each such class has a trivial [default 5439 // constructor or destructor] 5440 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose)) 5441 return false; 5442 5443 // C++11 [class.dtor]p5: 5444 // A destructor is trivial if [...] 5445 // -- the destructor is not virtual 5446 if (CSM == CXXDestructor && MD->isVirtual()) { 5447 if (Diagnose) 5448 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 5449 return false; 5450 } 5451 5452 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 5453 // A [special member] for class X is trivial if [...] 5454 // -- class X has no virtual functions and no virtual base classes 5455 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 5456 if (!Diagnose) 5457 return false; 5458 5459 if (RD->getNumVBases()) { 5460 // Check for virtual bases. We already know that the corresponding 5461 // member in all bases is trivial, so vbases must all be direct. 5462 CXXBaseSpecifier &BS = *RD->vbases_begin(); 5463 assert(BS.isVirtual()); 5464 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1; 5465 return false; 5466 } 5467 5468 // Must have a virtual method. 5469 for (CXXRecordDecl::method_iterator MI = RD->method_begin(), 5470 ME = RD->method_end(); MI != ME; ++MI) { 5471 if (MI->isVirtual()) { 5472 SourceLocation MLoc = MI->getLocStart(); 5473 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 5474 return false; 5475 } 5476 } 5477 5478 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 5479 } 5480 5481 // Looks like it's trivial! 5482 return true; 5483} 5484 5485/// \brief Data used with FindHiddenVirtualMethod 5486namespace { 5487 struct FindHiddenVirtualMethodData { 5488 Sema *S; 5489 CXXMethodDecl *Method; 5490 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 5491 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 5492 }; 5493} 5494 5495/// \brief Check whether any most overriden method from MD in Methods 5496static bool CheckMostOverridenMethods(const CXXMethodDecl *MD, 5497 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) { 5498 if (MD->size_overridden_methods() == 0) 5499 return Methods.count(MD->getCanonicalDecl()); 5500 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 5501 E = MD->end_overridden_methods(); 5502 I != E; ++I) 5503 if (CheckMostOverridenMethods(*I, Methods)) 5504 return true; 5505 return false; 5506} 5507 5508/// \brief Member lookup function that determines whether a given C++ 5509/// method overloads virtual methods in a base class without overriding any, 5510/// to be used with CXXRecordDecl::lookupInBases(). 5511static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier, 5512 CXXBasePath &Path, 5513 void *UserData) { 5514 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 5515 5516 FindHiddenVirtualMethodData &Data 5517 = *static_cast<FindHiddenVirtualMethodData*>(UserData); 5518 5519 DeclarationName Name = Data.Method->getDeclName(); 5520 assert(Name.getNameKind() == DeclarationName::Identifier); 5521 5522 bool foundSameNameMethod = false; 5523 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 5524 for (Path.Decls = BaseRecord->lookup(Name); 5525 !Path.Decls.empty(); 5526 Path.Decls = Path.Decls.slice(1)) { 5527 NamedDecl *D = Path.Decls.front(); 5528 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 5529 MD = MD->getCanonicalDecl(); 5530 foundSameNameMethod = true; 5531 // Interested only in hidden virtual methods. 5532 if (!MD->isVirtual()) 5533 continue; 5534 // If the method we are checking overrides a method from its base 5535 // don't warn about the other overloaded methods. 5536 if (!Data.S->IsOverload(Data.Method, MD, false)) 5537 return true; 5538 // Collect the overload only if its hidden. 5539 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods)) 5540 overloadedMethods.push_back(MD); 5541 } 5542 } 5543 5544 if (foundSameNameMethod) 5545 Data.OverloadedMethods.append(overloadedMethods.begin(), 5546 overloadedMethods.end()); 5547 return foundSameNameMethod; 5548} 5549 5550/// \brief Add the most overriden methods from MD to Methods 5551static void AddMostOverridenMethods(const CXXMethodDecl *MD, 5552 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) { 5553 if (MD->size_overridden_methods() == 0) 5554 Methods.insert(MD->getCanonicalDecl()); 5555 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 5556 E = MD->end_overridden_methods(); 5557 I != E; ++I) 5558 AddMostOverridenMethods(*I, Methods); 5559} 5560 5561/// \brief See if a method overloads virtual methods in a base class without 5562/// overriding any. 5563void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 5564 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual, 5565 MD->getLocation()) == DiagnosticsEngine::Ignored) 5566 return; 5567 if (!MD->getDeclName().isIdentifier()) 5568 return; 5569 5570 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 5571 /*bool RecordPaths=*/false, 5572 /*bool DetectVirtual=*/false); 5573 FindHiddenVirtualMethodData Data; 5574 Data.Method = MD; 5575 Data.S = this; 5576 5577 // Keep the base methods that were overriden or introduced in the subclass 5578 // by 'using' in a set. A base method not in this set is hidden. 5579 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 5580 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 5581 NamedDecl *ND = *I; 5582 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 5583 ND = shad->getTargetDecl(); 5584 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 5585 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods); 5586 } 5587 5588 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) && 5589 !Data.OverloadedMethods.empty()) { 5590 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 5591 << MD << (Data.OverloadedMethods.size() > 1); 5592 5593 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) { 5594 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i]; 5595 PartialDiagnostic PD = PDiag( 5596 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 5597 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 5598 Diag(overloadedMD->getLocation(), PD); 5599 } 5600 } 5601} 5602 5603void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 5604 Decl *TagDecl, 5605 SourceLocation LBrac, 5606 SourceLocation RBrac, 5607 AttributeList *AttrList) { 5608 if (!TagDecl) 5609 return; 5610 5611 AdjustDeclIfTemplate(TagDecl); 5612 5613 for (const AttributeList* l = AttrList; l; l = l->getNext()) { 5614 if (l->getKind() != AttributeList::AT_Visibility) 5615 continue; 5616 l->setInvalid(); 5617 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) << 5618 l->getName(); 5619 } 5620 5621 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 5622 // strict aliasing violation! 5623 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 5624 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 5625 5626 CheckCompletedCXXClass( 5627 dyn_cast_or_null<CXXRecordDecl>(TagDecl)); 5628} 5629 5630/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 5631/// special functions, such as the default constructor, copy 5632/// constructor, or destructor, to the given C++ class (C++ 5633/// [special]p1). This routine can only be executed just before the 5634/// definition of the class is complete. 5635void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 5636 if (!ClassDecl->hasUserDeclaredConstructor()) 5637 ++ASTContext::NumImplicitDefaultConstructors; 5638 5639 if (!ClassDecl->hasUserDeclaredCopyConstructor()) { 5640 ++ASTContext::NumImplicitCopyConstructors; 5641 5642 // If the properties or semantics of the copy constructor couldn't be 5643 // determined while the class was being declared, force a declaration 5644 // of it now. 5645 if (ClassDecl->needsOverloadResolutionForCopyConstructor()) 5646 DeclareImplicitCopyConstructor(ClassDecl); 5647 } 5648 5649 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 5650 ++ASTContext::NumImplicitMoveConstructors; 5651 5652 if (ClassDecl->needsOverloadResolutionForMoveConstructor()) 5653 DeclareImplicitMoveConstructor(ClassDecl); 5654 } 5655 5656 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 5657 ++ASTContext::NumImplicitCopyAssignmentOperators; 5658 5659 // If we have a dynamic class, then the copy assignment operator may be 5660 // virtual, so we have to declare it immediately. This ensures that, e.g., 5661 // it shows up in the right place in the vtable and that we diagnose 5662 // problems with the implicit exception specification. 5663 if (ClassDecl->isDynamicClass() || 5664 ClassDecl->needsOverloadResolutionForCopyAssignment()) 5665 DeclareImplicitCopyAssignment(ClassDecl); 5666 } 5667 5668 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 5669 ++ASTContext::NumImplicitMoveAssignmentOperators; 5670 5671 // Likewise for the move assignment operator. 5672 if (ClassDecl->isDynamicClass() || 5673 ClassDecl->needsOverloadResolutionForMoveAssignment()) 5674 DeclareImplicitMoveAssignment(ClassDecl); 5675 } 5676 5677 if (!ClassDecl->hasUserDeclaredDestructor()) { 5678 ++ASTContext::NumImplicitDestructors; 5679 5680 // If we have a dynamic class, then the destructor may be virtual, so we 5681 // have to declare the destructor immediately. This ensures that, e.g., it 5682 // shows up in the right place in the vtable and that we diagnose problems 5683 // with the implicit exception specification. 5684 if (ClassDecl->isDynamicClass() || 5685 ClassDecl->needsOverloadResolutionForDestructor()) 5686 DeclareImplicitDestructor(ClassDecl); 5687 } 5688} 5689 5690void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) { 5691 if (!D) 5692 return; 5693 5694 int NumParamList = D->getNumTemplateParameterLists(); 5695 for (int i = 0; i < NumParamList; i++) { 5696 TemplateParameterList* Params = D->getTemplateParameterList(i); 5697 for (TemplateParameterList::iterator Param = Params->begin(), 5698 ParamEnd = Params->end(); 5699 Param != ParamEnd; ++Param) { 5700 NamedDecl *Named = cast<NamedDecl>(*Param); 5701 if (Named->getDeclName()) { 5702 S->AddDecl(Named); 5703 IdResolver.AddDecl(Named); 5704 } 5705 } 5706 } 5707} 5708 5709void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 5710 if (!D) 5711 return; 5712 5713 TemplateParameterList *Params = 0; 5714 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) 5715 Params = Template->getTemplateParameters(); 5716 else if (ClassTemplatePartialSpecializationDecl *PartialSpec 5717 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 5718 Params = PartialSpec->getTemplateParameters(); 5719 else 5720 return; 5721 5722 for (TemplateParameterList::iterator Param = Params->begin(), 5723 ParamEnd = Params->end(); 5724 Param != ParamEnd; ++Param) { 5725 NamedDecl *Named = cast<NamedDecl>(*Param); 5726 if (Named->getDeclName()) { 5727 S->AddDecl(Named); 5728 IdResolver.AddDecl(Named); 5729 } 5730 } 5731} 5732 5733void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 5734 if (!RecordD) return; 5735 AdjustDeclIfTemplate(RecordD); 5736 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 5737 PushDeclContext(S, Record); 5738} 5739 5740void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 5741 if (!RecordD) return; 5742 PopDeclContext(); 5743} 5744 5745/// ActOnStartDelayedCXXMethodDeclaration - We have completed 5746/// parsing a top-level (non-nested) C++ class, and we are now 5747/// parsing those parts of the given Method declaration that could 5748/// not be parsed earlier (C++ [class.mem]p2), such as default 5749/// arguments. This action should enter the scope of the given 5750/// Method declaration as if we had just parsed the qualified method 5751/// name. However, it should not bring the parameters into scope; 5752/// that will be performed by ActOnDelayedCXXMethodParameter. 5753void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 5754} 5755 5756/// ActOnDelayedCXXMethodParameter - We've already started a delayed 5757/// C++ method declaration. We're (re-)introducing the given 5758/// function parameter into scope for use in parsing later parts of 5759/// the method declaration. For example, we could see an 5760/// ActOnParamDefaultArgument event for this parameter. 5761void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 5762 if (!ParamD) 5763 return; 5764 5765 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 5766 5767 // If this parameter has an unparsed default argument, clear it out 5768 // to make way for the parsed default argument. 5769 if (Param->hasUnparsedDefaultArg()) 5770 Param->setDefaultArg(0); 5771 5772 S->AddDecl(Param); 5773 if (Param->getDeclName()) 5774 IdResolver.AddDecl(Param); 5775} 5776 5777/// ActOnFinishDelayedCXXMethodDeclaration - We have finished 5778/// processing the delayed method declaration for Method. The method 5779/// declaration is now considered finished. There may be a separate 5780/// ActOnStartOfFunctionDef action later (not necessarily 5781/// immediately!) for this method, if it was also defined inside the 5782/// class body. 5783void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 5784 if (!MethodD) 5785 return; 5786 5787 AdjustDeclIfTemplate(MethodD); 5788 5789 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 5790 5791 // Now that we have our default arguments, check the constructor 5792 // again. It could produce additional diagnostics or affect whether 5793 // the class has implicitly-declared destructors, among other 5794 // things. 5795 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 5796 CheckConstructor(Constructor); 5797 5798 // Check the default arguments, which we may have added. 5799 if (!Method->isInvalidDecl()) 5800 CheckCXXDefaultArguments(Method); 5801} 5802 5803/// CheckConstructorDeclarator - Called by ActOnDeclarator to check 5804/// the well-formedness of the constructor declarator @p D with type @p 5805/// R. If there are any errors in the declarator, this routine will 5806/// emit diagnostics and set the invalid bit to true. In any case, the type 5807/// will be updated to reflect a well-formed type for the constructor and 5808/// returned. 5809QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 5810 StorageClass &SC) { 5811 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 5812 5813 // C++ [class.ctor]p3: 5814 // A constructor shall not be virtual (10.3) or static (9.4). A 5815 // constructor can be invoked for a const, volatile or const 5816 // volatile object. A constructor shall not be declared const, 5817 // volatile, or const volatile (9.3.2). 5818 if (isVirtual) { 5819 if (!D.isInvalidType()) 5820 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 5821 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 5822 << SourceRange(D.getIdentifierLoc()); 5823 D.setInvalidType(); 5824 } 5825 if (SC == SC_Static) { 5826 if (!D.isInvalidType()) 5827 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 5828 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 5829 << SourceRange(D.getIdentifierLoc()); 5830 D.setInvalidType(); 5831 SC = SC_None; 5832 } 5833 5834 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 5835 if (FTI.TypeQuals != 0) { 5836 if (FTI.TypeQuals & Qualifiers::Const) 5837 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 5838 << "const" << SourceRange(D.getIdentifierLoc()); 5839 if (FTI.TypeQuals & Qualifiers::Volatile) 5840 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 5841 << "volatile" << SourceRange(D.getIdentifierLoc()); 5842 if (FTI.TypeQuals & Qualifiers::Restrict) 5843 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 5844 << "restrict" << SourceRange(D.getIdentifierLoc()); 5845 D.setInvalidType(); 5846 } 5847 5848 // C++0x [class.ctor]p4: 5849 // A constructor shall not be declared with a ref-qualifier. 5850 if (FTI.hasRefQualifier()) { 5851 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 5852 << FTI.RefQualifierIsLValueRef 5853 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 5854 D.setInvalidType(); 5855 } 5856 5857 // Rebuild the function type "R" without any type qualifiers (in 5858 // case any of the errors above fired) and with "void" as the 5859 // return type, since constructors don't have return types. 5860 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 5861 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType()) 5862 return R; 5863 5864 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 5865 EPI.TypeQuals = 0; 5866 EPI.RefQualifier = RQ_None; 5867 5868 return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI); 5869} 5870 5871/// CheckConstructor - Checks a fully-formed constructor for 5872/// well-formedness, issuing any diagnostics required. Returns true if 5873/// the constructor declarator is invalid. 5874void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 5875 CXXRecordDecl *ClassDecl 5876 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 5877 if (!ClassDecl) 5878 return Constructor->setInvalidDecl(); 5879 5880 // C++ [class.copy]p3: 5881 // A declaration of a constructor for a class X is ill-formed if 5882 // its first parameter is of type (optionally cv-qualified) X and 5883 // either there are no other parameters or else all other 5884 // parameters have default arguments. 5885 if (!Constructor->isInvalidDecl() && 5886 ((Constructor->getNumParams() == 1) || 5887 (Constructor->getNumParams() > 1 && 5888 Constructor->getParamDecl(1)->hasDefaultArg())) && 5889 Constructor->getTemplateSpecializationKind() 5890 != TSK_ImplicitInstantiation) { 5891 QualType ParamType = Constructor->getParamDecl(0)->getType(); 5892 QualType ClassTy = Context.getTagDeclType(ClassDecl); 5893 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 5894 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 5895 const char *ConstRef 5896 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 5897 : " const &"; 5898 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 5899 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 5900 5901 // FIXME: Rather that making the constructor invalid, we should endeavor 5902 // to fix the type. 5903 Constructor->setInvalidDecl(); 5904 } 5905 } 5906} 5907 5908/// CheckDestructor - Checks a fully-formed destructor definition for 5909/// well-formedness, issuing any diagnostics required. Returns true 5910/// on error. 5911bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 5912 CXXRecordDecl *RD = Destructor->getParent(); 5913 5914 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 5915 SourceLocation Loc; 5916 5917 if (!Destructor->isImplicit()) 5918 Loc = Destructor->getLocation(); 5919 else 5920 Loc = RD->getLocation(); 5921 5922 // If we have a virtual destructor, look up the deallocation function 5923 FunctionDecl *OperatorDelete = 0; 5924 DeclarationName Name = 5925 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 5926 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 5927 return true; 5928 5929 MarkFunctionReferenced(Loc, OperatorDelete); 5930 5931 Destructor->setOperatorDelete(OperatorDelete); 5932 } 5933 5934 return false; 5935} 5936 5937static inline bool 5938FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) { 5939 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 5940 FTI.ArgInfo[0].Param && 5941 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()); 5942} 5943 5944/// CheckDestructorDeclarator - Called by ActOnDeclarator to check 5945/// the well-formednes of the destructor declarator @p D with type @p 5946/// R. If there are any errors in the declarator, this routine will 5947/// emit diagnostics and set the declarator to invalid. Even if this happens, 5948/// will be updated to reflect a well-formed type for the destructor and 5949/// returned. 5950QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 5951 StorageClass& SC) { 5952 // C++ [class.dtor]p1: 5953 // [...] A typedef-name that names a class is a class-name 5954 // (7.1.3); however, a typedef-name that names a class shall not 5955 // be used as the identifier in the declarator for a destructor 5956 // declaration. 5957 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 5958 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 5959 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 5960 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 5961 else if (const TemplateSpecializationType *TST = 5962 DeclaratorType->getAs<TemplateSpecializationType>()) 5963 if (TST->isTypeAlias()) 5964 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 5965 << DeclaratorType << 1; 5966 5967 // C++ [class.dtor]p2: 5968 // A destructor is used to destroy objects of its class type. A 5969 // destructor takes no parameters, and no return type can be 5970 // specified for it (not even void). The address of a destructor 5971 // shall not be taken. A destructor shall not be static. A 5972 // destructor can be invoked for a const, volatile or const 5973 // volatile object. A destructor shall not be declared const, 5974 // volatile or const volatile (9.3.2). 5975 if (SC == SC_Static) { 5976 if (!D.isInvalidType()) 5977 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 5978 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 5979 << SourceRange(D.getIdentifierLoc()) 5980 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5981 5982 SC = SC_None; 5983 } 5984 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 5985 // Destructors don't have return types, but the parser will 5986 // happily parse something like: 5987 // 5988 // class X { 5989 // float ~X(); 5990 // }; 5991 // 5992 // The return type will be eliminated later. 5993 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 5994 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 5995 << SourceRange(D.getIdentifierLoc()); 5996 } 5997 5998 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 5999 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 6000 if (FTI.TypeQuals & Qualifiers::Const) 6001 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6002 << "const" << SourceRange(D.getIdentifierLoc()); 6003 if (FTI.TypeQuals & Qualifiers::Volatile) 6004 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6005 << "volatile" << SourceRange(D.getIdentifierLoc()); 6006 if (FTI.TypeQuals & Qualifiers::Restrict) 6007 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6008 << "restrict" << SourceRange(D.getIdentifierLoc()); 6009 D.setInvalidType(); 6010 } 6011 6012 // C++0x [class.dtor]p2: 6013 // A destructor shall not be declared with a ref-qualifier. 6014 if (FTI.hasRefQualifier()) { 6015 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 6016 << FTI.RefQualifierIsLValueRef 6017 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 6018 D.setInvalidType(); 6019 } 6020 6021 // Make sure we don't have any parameters. 6022 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) { 6023 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 6024 6025 // Delete the parameters. 6026 FTI.freeArgs(); 6027 D.setInvalidType(); 6028 } 6029 6030 // Make sure the destructor isn't variadic. 6031 if (FTI.isVariadic) { 6032 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 6033 D.setInvalidType(); 6034 } 6035 6036 // Rebuild the function type "R" without any type qualifiers or 6037 // parameters (in case any of the errors above fired) and with 6038 // "void" as the return type, since destructors don't have return 6039 // types. 6040 if (!D.isInvalidType()) 6041 return R; 6042 6043 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6044 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 6045 EPI.Variadic = false; 6046 EPI.TypeQuals = 0; 6047 EPI.RefQualifier = RQ_None; 6048 return Context.getFunctionType(Context.VoidTy, None, EPI); 6049} 6050 6051/// CheckConversionDeclarator - Called by ActOnDeclarator to check the 6052/// well-formednes of the conversion function declarator @p D with 6053/// type @p R. If there are any errors in the declarator, this routine 6054/// will emit diagnostics and return true. Otherwise, it will return 6055/// false. Either way, the type @p R will be updated to reflect a 6056/// well-formed type for the conversion operator. 6057void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 6058 StorageClass& SC) { 6059 // C++ [class.conv.fct]p1: 6060 // Neither parameter types nor return type can be specified. The 6061 // type of a conversion function (8.3.5) is "function taking no 6062 // parameter returning conversion-type-id." 6063 if (SC == SC_Static) { 6064 if (!D.isInvalidType()) 6065 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 6066 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6067 << D.getName().getSourceRange(); 6068 D.setInvalidType(); 6069 SC = SC_None; 6070 } 6071 6072 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId); 6073 6074 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 6075 // Conversion functions don't have return types, but the parser will 6076 // happily parse something like: 6077 // 6078 // class X { 6079 // float operator bool(); 6080 // }; 6081 // 6082 // The return type will be changed later anyway. 6083 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 6084 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6085 << SourceRange(D.getIdentifierLoc()); 6086 D.setInvalidType(); 6087 } 6088 6089 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6090 6091 // Make sure we don't have any parameters. 6092 if (Proto->getNumArgs() > 0) { 6093 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 6094 6095 // Delete the parameters. 6096 D.getFunctionTypeInfo().freeArgs(); 6097 D.setInvalidType(); 6098 } else if (Proto->isVariadic()) { 6099 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 6100 D.setInvalidType(); 6101 } 6102 6103 // Diagnose "&operator bool()" and other such nonsense. This 6104 // is actually a gcc extension which we don't support. 6105 if (Proto->getResultType() != ConvType) { 6106 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 6107 << Proto->getResultType(); 6108 D.setInvalidType(); 6109 ConvType = Proto->getResultType(); 6110 } 6111 6112 // C++ [class.conv.fct]p4: 6113 // The conversion-type-id shall not represent a function type nor 6114 // an array type. 6115 if (ConvType->isArrayType()) { 6116 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 6117 ConvType = Context.getPointerType(ConvType); 6118 D.setInvalidType(); 6119 } else if (ConvType->isFunctionType()) { 6120 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 6121 ConvType = Context.getPointerType(ConvType); 6122 D.setInvalidType(); 6123 } 6124 6125 // Rebuild the function type "R" without any parameters (in case any 6126 // of the errors above fired) and with the conversion type as the 6127 // return type. 6128 if (D.isInvalidType()) 6129 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 6130 6131 // C++0x explicit conversion operators. 6132 if (D.getDeclSpec().isExplicitSpecified()) 6133 Diag(D.getDeclSpec().getExplicitSpecLoc(), 6134 getLangOpts().CPlusPlus11 ? 6135 diag::warn_cxx98_compat_explicit_conversion_functions : 6136 diag::ext_explicit_conversion_functions) 6137 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 6138} 6139 6140/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 6141/// the declaration of the given C++ conversion function. This routine 6142/// is responsible for recording the conversion function in the C++ 6143/// class, if possible. 6144Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 6145 assert(Conversion && "Expected to receive a conversion function declaration"); 6146 6147 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 6148 6149 // Make sure we aren't redeclaring the conversion function. 6150 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 6151 6152 // C++ [class.conv.fct]p1: 6153 // [...] A conversion function is never used to convert a 6154 // (possibly cv-qualified) object to the (possibly cv-qualified) 6155 // same object type (or a reference to it), to a (possibly 6156 // cv-qualified) base class of that type (or a reference to it), 6157 // or to (possibly cv-qualified) void. 6158 // FIXME: Suppress this warning if the conversion function ends up being a 6159 // virtual function that overrides a virtual function in a base class. 6160 QualType ClassType 6161 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 6162 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 6163 ConvType = ConvTypeRef->getPointeeType(); 6164 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 6165 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 6166 /* Suppress diagnostics for instantiations. */; 6167 else if (ConvType->isRecordType()) { 6168 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 6169 if (ConvType == ClassType) 6170 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 6171 << ClassType; 6172 else if (IsDerivedFrom(ClassType, ConvType)) 6173 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 6174 << ClassType << ConvType; 6175 } else if (ConvType->isVoidType()) { 6176 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 6177 << ClassType << ConvType; 6178 } 6179 6180 if (FunctionTemplateDecl *ConversionTemplate 6181 = Conversion->getDescribedFunctionTemplate()) 6182 return ConversionTemplate; 6183 6184 return Conversion; 6185} 6186 6187//===----------------------------------------------------------------------===// 6188// Namespace Handling 6189//===----------------------------------------------------------------------===// 6190 6191/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is 6192/// reopened. 6193static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 6194 SourceLocation Loc, 6195 IdentifierInfo *II, bool *IsInline, 6196 NamespaceDecl *PrevNS) { 6197 assert(*IsInline != PrevNS->isInline()); 6198 6199 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 6200 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 6201 // inline namespaces, with the intention of bringing names into namespace std. 6202 // 6203 // We support this just well enough to get that case working; this is not 6204 // sufficient to support reopening namespaces as inline in general. 6205 if (*IsInline && II && II->getName().startswith("__atomic") && 6206 S.getSourceManager().isInSystemHeader(Loc)) { 6207 // Mark all prior declarations of the namespace as inline. 6208 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 6209 NS = NS->getPreviousDecl()) 6210 NS->setInline(*IsInline); 6211 // Patch up the lookup table for the containing namespace. This isn't really 6212 // correct, but it's good enough for this particular case. 6213 for (DeclContext::decl_iterator I = PrevNS->decls_begin(), 6214 E = PrevNS->decls_end(); I != E; ++I) 6215 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I)) 6216 PrevNS->getParent()->makeDeclVisibleInContext(ND); 6217 return; 6218 } 6219 6220 if (PrevNS->isInline()) 6221 // The user probably just forgot the 'inline', so suggest that it 6222 // be added back. 6223 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 6224 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 6225 else 6226 S.Diag(Loc, diag::err_inline_namespace_mismatch) 6227 << IsInline; 6228 6229 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 6230 *IsInline = PrevNS->isInline(); 6231} 6232 6233/// ActOnStartNamespaceDef - This is called at the start of a namespace 6234/// definition. 6235Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 6236 SourceLocation InlineLoc, 6237 SourceLocation NamespaceLoc, 6238 SourceLocation IdentLoc, 6239 IdentifierInfo *II, 6240 SourceLocation LBrace, 6241 AttributeList *AttrList) { 6242 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 6243 // For anonymous namespace, take the location of the left brace. 6244 SourceLocation Loc = II ? IdentLoc : LBrace; 6245 bool IsInline = InlineLoc.isValid(); 6246 bool IsInvalid = false; 6247 bool IsStd = false; 6248 bool AddToKnown = false; 6249 Scope *DeclRegionScope = NamespcScope->getParent(); 6250 6251 NamespaceDecl *PrevNS = 0; 6252 if (II) { 6253 // C++ [namespace.def]p2: 6254 // The identifier in an original-namespace-definition shall not 6255 // have been previously defined in the declarative region in 6256 // which the original-namespace-definition appears. The 6257 // identifier in an original-namespace-definition is the name of 6258 // the namespace. Subsequently in that declarative region, it is 6259 // treated as an original-namespace-name. 6260 // 6261 // Since namespace names are unique in their scope, and we don't 6262 // look through using directives, just look for any ordinary names. 6263 6264 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member | 6265 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag | 6266 Decl::IDNS_Namespace; 6267 NamedDecl *PrevDecl = 0; 6268 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II); 6269 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 6270 ++I) { 6271 if ((*I)->getIdentifierNamespace() & IDNS) { 6272 PrevDecl = *I; 6273 break; 6274 } 6275 } 6276 6277 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 6278 6279 if (PrevNS) { 6280 // This is an extended namespace definition. 6281 if (IsInline != PrevNS->isInline()) 6282 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 6283 &IsInline, PrevNS); 6284 } else if (PrevDecl) { 6285 // This is an invalid name redefinition. 6286 Diag(Loc, diag::err_redefinition_different_kind) 6287 << II; 6288 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 6289 IsInvalid = true; 6290 // Continue on to push Namespc as current DeclContext and return it. 6291 } else if (II->isStr("std") && 6292 CurContext->getRedeclContext()->isTranslationUnit()) { 6293 // This is the first "real" definition of the namespace "std", so update 6294 // our cache of the "std" namespace to point at this definition. 6295 PrevNS = getStdNamespace(); 6296 IsStd = true; 6297 AddToKnown = !IsInline; 6298 } else { 6299 // We've seen this namespace for the first time. 6300 AddToKnown = !IsInline; 6301 } 6302 } else { 6303 // Anonymous namespaces. 6304 6305 // Determine whether the parent already has an anonymous namespace. 6306 DeclContext *Parent = CurContext->getRedeclContext(); 6307 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 6308 PrevNS = TU->getAnonymousNamespace(); 6309 } else { 6310 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 6311 PrevNS = ND->getAnonymousNamespace(); 6312 } 6313 6314 if (PrevNS && IsInline != PrevNS->isInline()) 6315 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 6316 &IsInline, PrevNS); 6317 } 6318 6319 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 6320 StartLoc, Loc, II, PrevNS); 6321 if (IsInvalid) 6322 Namespc->setInvalidDecl(); 6323 6324 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 6325 6326 // FIXME: Should we be merging attributes? 6327 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 6328 PushNamespaceVisibilityAttr(Attr, Loc); 6329 6330 if (IsStd) 6331 StdNamespace = Namespc; 6332 if (AddToKnown) 6333 KnownNamespaces[Namespc] = false; 6334 6335 if (II) { 6336 PushOnScopeChains(Namespc, DeclRegionScope); 6337 } else { 6338 // Link the anonymous namespace into its parent. 6339 DeclContext *Parent = CurContext->getRedeclContext(); 6340 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 6341 TU->setAnonymousNamespace(Namespc); 6342 } else { 6343 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 6344 } 6345 6346 CurContext->addDecl(Namespc); 6347 6348 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 6349 // behaves as if it were replaced by 6350 // namespace unique { /* empty body */ } 6351 // using namespace unique; 6352 // namespace unique { namespace-body } 6353 // where all occurrences of 'unique' in a translation unit are 6354 // replaced by the same identifier and this identifier differs 6355 // from all other identifiers in the entire program. 6356 6357 // We just create the namespace with an empty name and then add an 6358 // implicit using declaration, just like the standard suggests. 6359 // 6360 // CodeGen enforces the "universally unique" aspect by giving all 6361 // declarations semantically contained within an anonymous 6362 // namespace internal linkage. 6363 6364 if (!PrevNS) { 6365 UsingDirectiveDecl* UD 6366 = UsingDirectiveDecl::Create(Context, Parent, 6367 /* 'using' */ LBrace, 6368 /* 'namespace' */ SourceLocation(), 6369 /* qualifier */ NestedNameSpecifierLoc(), 6370 /* identifier */ SourceLocation(), 6371 Namespc, 6372 /* Ancestor */ Parent); 6373 UD->setImplicit(); 6374 Parent->addDecl(UD); 6375 } 6376 } 6377 6378 ActOnDocumentableDecl(Namespc); 6379 6380 // Although we could have an invalid decl (i.e. the namespace name is a 6381 // redefinition), push it as current DeclContext and try to continue parsing. 6382 // FIXME: We should be able to push Namespc here, so that the each DeclContext 6383 // for the namespace has the declarations that showed up in that particular 6384 // namespace definition. 6385 PushDeclContext(NamespcScope, Namespc); 6386 return Namespc; 6387} 6388 6389/// getNamespaceDecl - Returns the namespace a decl represents. If the decl 6390/// is a namespace alias, returns the namespace it points to. 6391static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 6392 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 6393 return AD->getNamespace(); 6394 return dyn_cast_or_null<NamespaceDecl>(D); 6395} 6396 6397/// ActOnFinishNamespaceDef - This callback is called after a namespace is 6398/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 6399void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 6400 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 6401 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 6402 Namespc->setRBraceLoc(RBrace); 6403 PopDeclContext(); 6404 if (Namespc->hasAttr<VisibilityAttr>()) 6405 PopPragmaVisibility(true, RBrace); 6406} 6407 6408CXXRecordDecl *Sema::getStdBadAlloc() const { 6409 return cast_or_null<CXXRecordDecl>( 6410 StdBadAlloc.get(Context.getExternalSource())); 6411} 6412 6413NamespaceDecl *Sema::getStdNamespace() const { 6414 return cast_or_null<NamespaceDecl>( 6415 StdNamespace.get(Context.getExternalSource())); 6416} 6417 6418/// \brief Retrieve the special "std" namespace, which may require us to 6419/// implicitly define the namespace. 6420NamespaceDecl *Sema::getOrCreateStdNamespace() { 6421 if (!StdNamespace) { 6422 // The "std" namespace has not yet been defined, so build one implicitly. 6423 StdNamespace = NamespaceDecl::Create(Context, 6424 Context.getTranslationUnitDecl(), 6425 /*Inline=*/false, 6426 SourceLocation(), SourceLocation(), 6427 &PP.getIdentifierTable().get("std"), 6428 /*PrevDecl=*/0); 6429 getStdNamespace()->setImplicit(true); 6430 } 6431 6432 return getStdNamespace(); 6433} 6434 6435bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 6436 assert(getLangOpts().CPlusPlus && 6437 "Looking for std::initializer_list outside of C++."); 6438 6439 // We're looking for implicit instantiations of 6440 // template <typename E> class std::initializer_list. 6441 6442 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 6443 return false; 6444 6445 ClassTemplateDecl *Template = 0; 6446 const TemplateArgument *Arguments = 0; 6447 6448 if (const RecordType *RT = Ty->getAs<RecordType>()) { 6449 6450 ClassTemplateSpecializationDecl *Specialization = 6451 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 6452 if (!Specialization) 6453 return false; 6454 6455 Template = Specialization->getSpecializedTemplate(); 6456 Arguments = Specialization->getTemplateArgs().data(); 6457 } else if (const TemplateSpecializationType *TST = 6458 Ty->getAs<TemplateSpecializationType>()) { 6459 Template = dyn_cast_or_null<ClassTemplateDecl>( 6460 TST->getTemplateName().getAsTemplateDecl()); 6461 Arguments = TST->getArgs(); 6462 } 6463 if (!Template) 6464 return false; 6465 6466 if (!StdInitializerList) { 6467 // Haven't recognized std::initializer_list yet, maybe this is it. 6468 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 6469 if (TemplateClass->getIdentifier() != 6470 &PP.getIdentifierTable().get("initializer_list") || 6471 !getStdNamespace()->InEnclosingNamespaceSetOf( 6472 TemplateClass->getDeclContext())) 6473 return false; 6474 // This is a template called std::initializer_list, but is it the right 6475 // template? 6476 TemplateParameterList *Params = Template->getTemplateParameters(); 6477 if (Params->getMinRequiredArguments() != 1) 6478 return false; 6479 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 6480 return false; 6481 6482 // It's the right template. 6483 StdInitializerList = Template; 6484 } 6485 6486 if (Template != StdInitializerList) 6487 return false; 6488 6489 // This is an instance of std::initializer_list. Find the argument type. 6490 if (Element) 6491 *Element = Arguments[0].getAsType(); 6492 return true; 6493} 6494 6495static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 6496 NamespaceDecl *Std = S.getStdNamespace(); 6497 if (!Std) { 6498 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 6499 return 0; 6500 } 6501 6502 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 6503 Loc, Sema::LookupOrdinaryName); 6504 if (!S.LookupQualifiedName(Result, Std)) { 6505 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 6506 return 0; 6507 } 6508 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 6509 if (!Template) { 6510 Result.suppressDiagnostics(); 6511 // We found something weird. Complain about the first thing we found. 6512 NamedDecl *Found = *Result.begin(); 6513 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 6514 return 0; 6515 } 6516 6517 // We found some template called std::initializer_list. Now verify that it's 6518 // correct. 6519 TemplateParameterList *Params = Template->getTemplateParameters(); 6520 if (Params->getMinRequiredArguments() != 1 || 6521 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 6522 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 6523 return 0; 6524 } 6525 6526 return Template; 6527} 6528 6529QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 6530 if (!StdInitializerList) { 6531 StdInitializerList = LookupStdInitializerList(*this, Loc); 6532 if (!StdInitializerList) 6533 return QualType(); 6534 } 6535 6536 TemplateArgumentListInfo Args(Loc, Loc); 6537 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 6538 Context.getTrivialTypeSourceInfo(Element, 6539 Loc))); 6540 return Context.getCanonicalType( 6541 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 6542} 6543 6544bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) { 6545 // C++ [dcl.init.list]p2: 6546 // A constructor is an initializer-list constructor if its first parameter 6547 // is of type std::initializer_list<E> or reference to possibly cv-qualified 6548 // std::initializer_list<E> for some type E, and either there are no other 6549 // parameters or else all other parameters have default arguments. 6550 if (Ctor->getNumParams() < 1 || 6551 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 6552 return false; 6553 6554 QualType ArgType = Ctor->getParamDecl(0)->getType(); 6555 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 6556 ArgType = RT->getPointeeType().getUnqualifiedType(); 6557 6558 return isStdInitializerList(ArgType, 0); 6559} 6560 6561/// \brief Determine whether a using statement is in a context where it will be 6562/// apply in all contexts. 6563static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 6564 switch (CurContext->getDeclKind()) { 6565 case Decl::TranslationUnit: 6566 return true; 6567 case Decl::LinkageSpec: 6568 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 6569 default: 6570 return false; 6571 } 6572} 6573 6574namespace { 6575 6576// Callback to only accept typo corrections that are namespaces. 6577class NamespaceValidatorCCC : public CorrectionCandidateCallback { 6578 public: 6579 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 6580 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 6581 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 6582 } 6583 return false; 6584 } 6585}; 6586 6587} 6588 6589static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 6590 CXXScopeSpec &SS, 6591 SourceLocation IdentLoc, 6592 IdentifierInfo *Ident) { 6593 NamespaceValidatorCCC Validator; 6594 R.clear(); 6595 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(), 6596 R.getLookupKind(), Sc, &SS, 6597 Validator)) { 6598 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 6599 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts())); 6600 if (DeclContext *DC = S.computeDeclContext(SS, false)) 6601 S.Diag(IdentLoc, diag::err_using_directive_member_suggest) 6602 << Ident << DC << CorrectedQuotedStr << SS.getRange() 6603 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(), 6604 CorrectedStr); 6605 else 6606 S.Diag(IdentLoc, diag::err_using_directive_suggest) 6607 << Ident << CorrectedQuotedStr 6608 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr); 6609 6610 S.Diag(Corrected.getCorrectionDecl()->getLocation(), 6611 diag::note_namespace_defined_here) << CorrectedQuotedStr; 6612 6613 R.addDecl(Corrected.getCorrectionDecl()); 6614 return true; 6615 } 6616 return false; 6617} 6618 6619Decl *Sema::ActOnUsingDirective(Scope *S, 6620 SourceLocation UsingLoc, 6621 SourceLocation NamespcLoc, 6622 CXXScopeSpec &SS, 6623 SourceLocation IdentLoc, 6624 IdentifierInfo *NamespcName, 6625 AttributeList *AttrList) { 6626 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 6627 assert(NamespcName && "Invalid NamespcName."); 6628 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 6629 6630 // This can only happen along a recovery path. 6631 while (S->getFlags() & Scope::TemplateParamScope) 6632 S = S->getParent(); 6633 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 6634 6635 UsingDirectiveDecl *UDir = 0; 6636 NestedNameSpecifier *Qualifier = 0; 6637 if (SS.isSet()) 6638 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 6639 6640 // Lookup namespace name. 6641 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 6642 LookupParsedName(R, S, &SS); 6643 if (R.isAmbiguous()) 6644 return 0; 6645 6646 if (R.empty()) { 6647 R.clear(); 6648 // Allow "using namespace std;" or "using namespace ::std;" even if 6649 // "std" hasn't been defined yet, for GCC compatibility. 6650 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 6651 NamespcName->isStr("std")) { 6652 Diag(IdentLoc, diag::ext_using_undefined_std); 6653 R.addDecl(getOrCreateStdNamespace()); 6654 R.resolveKind(); 6655 } 6656 // Otherwise, attempt typo correction. 6657 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 6658 } 6659 6660 if (!R.empty()) { 6661 NamedDecl *Named = R.getFoundDecl(); 6662 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named)) 6663 && "expected namespace decl"); 6664 // C++ [namespace.udir]p1: 6665 // A using-directive specifies that the names in the nominated 6666 // namespace can be used in the scope in which the 6667 // using-directive appears after the using-directive. During 6668 // unqualified name lookup (3.4.1), the names appear as if they 6669 // were declared in the nearest enclosing namespace which 6670 // contains both the using-directive and the nominated 6671 // namespace. [Note: in this context, "contains" means "contains 6672 // directly or indirectly". ] 6673 6674 // Find enclosing context containing both using-directive and 6675 // nominated namespace. 6676 NamespaceDecl *NS = getNamespaceDecl(Named); 6677 DeclContext *CommonAncestor = cast<DeclContext>(NS); 6678 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 6679 CommonAncestor = CommonAncestor->getParent(); 6680 6681 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 6682 SS.getWithLocInContext(Context), 6683 IdentLoc, Named, CommonAncestor); 6684 6685 if (IsUsingDirectiveInToplevelContext(CurContext) && 6686 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 6687 Diag(IdentLoc, diag::warn_using_directive_in_header); 6688 } 6689 6690 PushUsingDirective(S, UDir); 6691 } else { 6692 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 6693 } 6694 6695 if (UDir) 6696 ProcessDeclAttributeList(S, UDir, AttrList); 6697 6698 return UDir; 6699} 6700 6701void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 6702 // If the scope has an associated entity and the using directive is at 6703 // namespace or translation unit scope, add the UsingDirectiveDecl into 6704 // its lookup structure so qualified name lookup can find it. 6705 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()); 6706 if (Ctx && !Ctx->isFunctionOrMethod()) 6707 Ctx->addDecl(UDir); 6708 else 6709 // Otherwise, it is at block sope. The using-directives will affect lookup 6710 // only to the end of the scope. 6711 S->PushUsingDirective(UDir); 6712} 6713 6714 6715Decl *Sema::ActOnUsingDeclaration(Scope *S, 6716 AccessSpecifier AS, 6717 bool HasUsingKeyword, 6718 SourceLocation UsingLoc, 6719 CXXScopeSpec &SS, 6720 UnqualifiedId &Name, 6721 AttributeList *AttrList, 6722 bool IsTypeName, 6723 SourceLocation TypenameLoc) { 6724 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 6725 6726 switch (Name.getKind()) { 6727 case UnqualifiedId::IK_ImplicitSelfParam: 6728 case UnqualifiedId::IK_Identifier: 6729 case UnqualifiedId::IK_OperatorFunctionId: 6730 case UnqualifiedId::IK_LiteralOperatorId: 6731 case UnqualifiedId::IK_ConversionFunctionId: 6732 break; 6733 6734 case UnqualifiedId::IK_ConstructorName: 6735 case UnqualifiedId::IK_ConstructorTemplateId: 6736 // C++11 inheriting constructors. 6737 Diag(Name.getLocStart(), 6738 getLangOpts().CPlusPlus11 ? 6739 diag::warn_cxx98_compat_using_decl_constructor : 6740 diag::err_using_decl_constructor) 6741 << SS.getRange(); 6742 6743 if (getLangOpts().CPlusPlus11) break; 6744 6745 return 0; 6746 6747 case UnqualifiedId::IK_DestructorName: 6748 Diag(Name.getLocStart(), diag::err_using_decl_destructor) 6749 << SS.getRange(); 6750 return 0; 6751 6752 case UnqualifiedId::IK_TemplateId: 6753 Diag(Name.getLocStart(), diag::err_using_decl_template_id) 6754 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 6755 return 0; 6756 } 6757 6758 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 6759 DeclarationName TargetName = TargetNameInfo.getName(); 6760 if (!TargetName) 6761 return 0; 6762 6763 // Warn about access declarations. 6764 // TODO: store that the declaration was written without 'using' and 6765 // talk about access decls instead of using decls in the 6766 // diagnostics. 6767 if (!HasUsingKeyword) { 6768 UsingLoc = Name.getLocStart(); 6769 6770 Diag(UsingLoc, 6771 getLangOpts().CPlusPlus11 ? diag::err_access_decl 6772 : diag::warn_access_decl_deprecated) 6773 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 6774 } 6775 6776 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 6777 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 6778 return 0; 6779 6780 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 6781 TargetNameInfo, AttrList, 6782 /* IsInstantiation */ false, 6783 IsTypeName, TypenameLoc); 6784 if (UD) 6785 PushOnScopeChains(UD, S, /*AddToContext*/ false); 6786 6787 return UD; 6788} 6789 6790/// \brief Determine whether a using declaration considers the given 6791/// declarations as "equivalent", e.g., if they are redeclarations of 6792/// the same entity or are both typedefs of the same type. 6793static bool 6794IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2, 6795 bool &SuppressRedeclaration) { 6796 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) { 6797 SuppressRedeclaration = false; 6798 return true; 6799 } 6800 6801 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 6802 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) { 6803 SuppressRedeclaration = true; 6804 return Context.hasSameType(TD1->getUnderlyingType(), 6805 TD2->getUnderlyingType()); 6806 } 6807 6808 return false; 6809} 6810 6811 6812/// Determines whether to create a using shadow decl for a particular 6813/// decl, given the set of decls existing prior to this using lookup. 6814bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 6815 const LookupResult &Previous) { 6816 // Diagnose finding a decl which is not from a base class of the 6817 // current class. We do this now because there are cases where this 6818 // function will silently decide not to build a shadow decl, which 6819 // will pre-empt further diagnostics. 6820 // 6821 // We don't need to do this in C++0x because we do the check once on 6822 // the qualifier. 6823 // 6824 // FIXME: diagnose the following if we care enough: 6825 // struct A { int foo; }; 6826 // struct B : A { using A::foo; }; 6827 // template <class T> struct C : A {}; 6828 // template <class T> struct D : C<T> { using B::foo; } // <--- 6829 // This is invalid (during instantiation) in C++03 because B::foo 6830 // resolves to the using decl in B, which is not a base class of D<T>. 6831 // We can't diagnose it immediately because C<T> is an unknown 6832 // specialization. The UsingShadowDecl in D<T> then points directly 6833 // to A::foo, which will look well-formed when we instantiate. 6834 // The right solution is to not collapse the shadow-decl chain. 6835 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 6836 DeclContext *OrigDC = Orig->getDeclContext(); 6837 6838 // Handle enums and anonymous structs. 6839 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 6840 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 6841 while (OrigRec->isAnonymousStructOrUnion()) 6842 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 6843 6844 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 6845 if (OrigDC == CurContext) { 6846 Diag(Using->getLocation(), 6847 diag::err_using_decl_nested_name_specifier_is_current_class) 6848 << Using->getQualifierLoc().getSourceRange(); 6849 Diag(Orig->getLocation(), diag::note_using_decl_target); 6850 return true; 6851 } 6852 6853 Diag(Using->getQualifierLoc().getBeginLoc(), 6854 diag::err_using_decl_nested_name_specifier_is_not_base_class) 6855 << Using->getQualifier() 6856 << cast<CXXRecordDecl>(CurContext) 6857 << Using->getQualifierLoc().getSourceRange(); 6858 Diag(Orig->getLocation(), diag::note_using_decl_target); 6859 return true; 6860 } 6861 } 6862 6863 if (Previous.empty()) return false; 6864 6865 NamedDecl *Target = Orig; 6866 if (isa<UsingShadowDecl>(Target)) 6867 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 6868 6869 // If the target happens to be one of the previous declarations, we 6870 // don't have a conflict. 6871 // 6872 // FIXME: but we might be increasing its access, in which case we 6873 // should redeclare it. 6874 NamedDecl *NonTag = 0, *Tag = 0; 6875 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 6876 I != E; ++I) { 6877 NamedDecl *D = (*I)->getUnderlyingDecl(); 6878 bool Result; 6879 if (IsEquivalentForUsingDecl(Context, D, Target, Result)) 6880 return Result; 6881 6882 (isa<TagDecl>(D) ? Tag : NonTag) = D; 6883 } 6884 6885 if (Target->isFunctionOrFunctionTemplate()) { 6886 FunctionDecl *FD; 6887 if (isa<FunctionTemplateDecl>(Target)) 6888 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl(); 6889 else 6890 FD = cast<FunctionDecl>(Target); 6891 6892 NamedDecl *OldDecl = 0; 6893 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) { 6894 case Ovl_Overload: 6895 return false; 6896 6897 case Ovl_NonFunction: 6898 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6899 break; 6900 6901 // We found a decl with the exact signature. 6902 case Ovl_Match: 6903 // If we're in a record, we want to hide the target, so we 6904 // return true (without a diagnostic) to tell the caller not to 6905 // build a shadow decl. 6906 if (CurContext->isRecord()) 6907 return true; 6908 6909 // If we're not in a record, this is an error. 6910 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6911 break; 6912 } 6913 6914 Diag(Target->getLocation(), diag::note_using_decl_target); 6915 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 6916 return true; 6917 } 6918 6919 // Target is not a function. 6920 6921 if (isa<TagDecl>(Target)) { 6922 // No conflict between a tag and a non-tag. 6923 if (!Tag) return false; 6924 6925 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6926 Diag(Target->getLocation(), diag::note_using_decl_target); 6927 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 6928 return true; 6929 } 6930 6931 // No conflict between a tag and a non-tag. 6932 if (!NonTag) return false; 6933 6934 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6935 Diag(Target->getLocation(), diag::note_using_decl_target); 6936 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 6937 return true; 6938} 6939 6940/// Builds a shadow declaration corresponding to a 'using' declaration. 6941UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 6942 UsingDecl *UD, 6943 NamedDecl *Orig) { 6944 6945 // If we resolved to another shadow declaration, just coalesce them. 6946 NamedDecl *Target = Orig; 6947 if (isa<UsingShadowDecl>(Target)) { 6948 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 6949 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 6950 } 6951 6952 UsingShadowDecl *Shadow 6953 = UsingShadowDecl::Create(Context, CurContext, 6954 UD->getLocation(), UD, Target); 6955 UD->addShadowDecl(Shadow); 6956 6957 Shadow->setAccess(UD->getAccess()); 6958 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 6959 Shadow->setInvalidDecl(); 6960 6961 if (S) 6962 PushOnScopeChains(Shadow, S); 6963 else 6964 CurContext->addDecl(Shadow); 6965 6966 6967 return Shadow; 6968} 6969 6970/// Hides a using shadow declaration. This is required by the current 6971/// using-decl implementation when a resolvable using declaration in a 6972/// class is followed by a declaration which would hide or override 6973/// one or more of the using decl's targets; for example: 6974/// 6975/// struct Base { void foo(int); }; 6976/// struct Derived : Base { 6977/// using Base::foo; 6978/// void foo(int); 6979/// }; 6980/// 6981/// The governing language is C++03 [namespace.udecl]p12: 6982/// 6983/// When a using-declaration brings names from a base class into a 6984/// derived class scope, member functions in the derived class 6985/// override and/or hide member functions with the same name and 6986/// parameter types in a base class (rather than conflicting). 6987/// 6988/// There are two ways to implement this: 6989/// (1) optimistically create shadow decls when they're not hidden 6990/// by existing declarations, or 6991/// (2) don't create any shadow decls (or at least don't make them 6992/// visible) until we've fully parsed/instantiated the class. 6993/// The problem with (1) is that we might have to retroactively remove 6994/// a shadow decl, which requires several O(n) operations because the 6995/// decl structures are (very reasonably) not designed for removal. 6996/// (2) avoids this but is very fiddly and phase-dependent. 6997void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 6998 if (Shadow->getDeclName().getNameKind() == 6999 DeclarationName::CXXConversionFunctionName) 7000 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 7001 7002 // Remove it from the DeclContext... 7003 Shadow->getDeclContext()->removeDecl(Shadow); 7004 7005 // ...and the scope, if applicable... 7006 if (S) { 7007 S->RemoveDecl(Shadow); 7008 IdResolver.RemoveDecl(Shadow); 7009 } 7010 7011 // ...and the using decl. 7012 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 7013 7014 // TODO: complain somehow if Shadow was used. It shouldn't 7015 // be possible for this to happen, because...? 7016} 7017 7018/// Builds a using declaration. 7019/// 7020/// \param IsInstantiation - Whether this call arises from an 7021/// instantiation of an unresolved using declaration. We treat 7022/// the lookup differently for these declarations. 7023NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 7024 SourceLocation UsingLoc, 7025 CXXScopeSpec &SS, 7026 const DeclarationNameInfo &NameInfo, 7027 AttributeList *AttrList, 7028 bool IsInstantiation, 7029 bool IsTypeName, 7030 SourceLocation TypenameLoc) { 7031 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 7032 SourceLocation IdentLoc = NameInfo.getLoc(); 7033 assert(IdentLoc.isValid() && "Invalid TargetName location."); 7034 7035 // FIXME: We ignore attributes for now. 7036 7037 if (SS.isEmpty()) { 7038 Diag(IdentLoc, diag::err_using_requires_qualname); 7039 return 0; 7040 } 7041 7042 // Do the redeclaration lookup in the current scope. 7043 LookupResult Previous(*this, NameInfo, LookupUsingDeclName, 7044 ForRedeclaration); 7045 Previous.setHideTags(false); 7046 if (S) { 7047 LookupName(Previous, S); 7048 7049 // It is really dumb that we have to do this. 7050 LookupResult::Filter F = Previous.makeFilter(); 7051 while (F.hasNext()) { 7052 NamedDecl *D = F.next(); 7053 if (!isDeclInScope(D, CurContext, S)) 7054 F.erase(); 7055 } 7056 F.done(); 7057 } else { 7058 assert(IsInstantiation && "no scope in non-instantiation"); 7059 assert(CurContext->isRecord() && "scope not record in instantiation"); 7060 LookupQualifiedName(Previous, CurContext); 7061 } 7062 7063 // Check for invalid redeclarations. 7064 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous)) 7065 return 0; 7066 7067 // Check for bad qualifiers. 7068 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc)) 7069 return 0; 7070 7071 DeclContext *LookupContext = computeDeclContext(SS); 7072 NamedDecl *D; 7073 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 7074 if (!LookupContext) { 7075 if (IsTypeName) { 7076 // FIXME: not all declaration name kinds are legal here 7077 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 7078 UsingLoc, TypenameLoc, 7079 QualifierLoc, 7080 IdentLoc, NameInfo.getName()); 7081 } else { 7082 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 7083 QualifierLoc, NameInfo); 7084 } 7085 } else { 7086 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 7087 NameInfo, IsTypeName); 7088 } 7089 D->setAccess(AS); 7090 CurContext->addDecl(D); 7091 7092 if (!LookupContext) return D; 7093 UsingDecl *UD = cast<UsingDecl>(D); 7094 7095 if (RequireCompleteDeclContext(SS, LookupContext)) { 7096 UD->setInvalidDecl(); 7097 return UD; 7098 } 7099 7100 // The normal rules do not apply to inheriting constructor declarations. 7101 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) { 7102 if (CheckInheritingConstructorUsingDecl(UD)) 7103 UD->setInvalidDecl(); 7104 return UD; 7105 } 7106 7107 // Otherwise, look up the target name. 7108 7109 LookupResult R(*this, NameInfo, LookupOrdinaryName); 7110 7111 // Unlike most lookups, we don't always want to hide tag 7112 // declarations: tag names are visible through the using declaration 7113 // even if hidden by ordinary names, *except* in a dependent context 7114 // where it's important for the sanity of two-phase lookup. 7115 if (!IsInstantiation) 7116 R.setHideTags(false); 7117 7118 // For the purposes of this lookup, we have a base object type 7119 // equal to that of the current context. 7120 if (CurContext->isRecord()) { 7121 R.setBaseObjectType( 7122 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 7123 } 7124 7125 LookupQualifiedName(R, LookupContext); 7126 7127 if (R.empty()) { 7128 Diag(IdentLoc, diag::err_no_member) 7129 << NameInfo.getName() << LookupContext << SS.getRange(); 7130 UD->setInvalidDecl(); 7131 return UD; 7132 } 7133 7134 if (R.isAmbiguous()) { 7135 UD->setInvalidDecl(); 7136 return UD; 7137 } 7138 7139 if (IsTypeName) { 7140 // If we asked for a typename and got a non-type decl, error out. 7141 if (!R.getAsSingle<TypeDecl>()) { 7142 Diag(IdentLoc, diag::err_using_typename_non_type); 7143 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 7144 Diag((*I)->getUnderlyingDecl()->getLocation(), 7145 diag::note_using_decl_target); 7146 UD->setInvalidDecl(); 7147 return UD; 7148 } 7149 } else { 7150 // If we asked for a non-typename and we got a type, error out, 7151 // but only if this is an instantiation of an unresolved using 7152 // decl. Otherwise just silently find the type name. 7153 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 7154 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 7155 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 7156 UD->setInvalidDecl(); 7157 return UD; 7158 } 7159 } 7160 7161 // C++0x N2914 [namespace.udecl]p6: 7162 // A using-declaration shall not name a namespace. 7163 if (R.getAsSingle<NamespaceDecl>()) { 7164 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 7165 << SS.getRange(); 7166 UD->setInvalidDecl(); 7167 return UD; 7168 } 7169 7170 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 7171 if (!CheckUsingShadowDecl(UD, *I, Previous)) 7172 BuildUsingShadowDecl(S, UD, *I); 7173 } 7174 7175 return UD; 7176} 7177 7178/// Additional checks for a using declaration referring to a constructor name. 7179bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 7180 assert(!UD->isTypeName() && "expecting a constructor name"); 7181 7182 const Type *SourceType = UD->getQualifier()->getAsType(); 7183 assert(SourceType && 7184 "Using decl naming constructor doesn't have type in scope spec."); 7185 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 7186 7187 // Check whether the named type is a direct base class. 7188 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified(); 7189 CXXRecordDecl::base_class_iterator BaseIt, BaseE; 7190 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end(); 7191 BaseIt != BaseE; ++BaseIt) { 7192 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified(); 7193 if (CanonicalSourceType == BaseType) 7194 break; 7195 if (BaseIt->getType()->isDependentType()) 7196 break; 7197 } 7198 7199 if (BaseIt == BaseE) { 7200 // Did not find SourceType in the bases. 7201 Diag(UD->getUsingLocation(), 7202 diag::err_using_decl_constructor_not_in_direct_base) 7203 << UD->getNameInfo().getSourceRange() 7204 << QualType(SourceType, 0) << TargetClass; 7205 return true; 7206 } 7207 7208 if (!CurContext->isDependentContext()) 7209 BaseIt->setInheritConstructors(); 7210 7211 return false; 7212} 7213 7214/// Checks that the given using declaration is not an invalid 7215/// redeclaration. Note that this is checking only for the using decl 7216/// itself, not for any ill-formedness among the UsingShadowDecls. 7217bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 7218 bool isTypeName, 7219 const CXXScopeSpec &SS, 7220 SourceLocation NameLoc, 7221 const LookupResult &Prev) { 7222 // C++03 [namespace.udecl]p8: 7223 // C++0x [namespace.udecl]p10: 7224 // A using-declaration is a declaration and can therefore be used 7225 // repeatedly where (and only where) multiple declarations are 7226 // allowed. 7227 // 7228 // That's in non-member contexts. 7229 if (!CurContext->getRedeclContext()->isRecord()) 7230 return false; 7231 7232 NestedNameSpecifier *Qual 7233 = static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 7234 7235 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 7236 NamedDecl *D = *I; 7237 7238 bool DTypename; 7239 NestedNameSpecifier *DQual; 7240 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 7241 DTypename = UD->isTypeName(); 7242 DQual = UD->getQualifier(); 7243 } else if (UnresolvedUsingValueDecl *UD 7244 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 7245 DTypename = false; 7246 DQual = UD->getQualifier(); 7247 } else if (UnresolvedUsingTypenameDecl *UD 7248 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 7249 DTypename = true; 7250 DQual = UD->getQualifier(); 7251 } else continue; 7252 7253 // using decls differ if one says 'typename' and the other doesn't. 7254 // FIXME: non-dependent using decls? 7255 if (isTypeName != DTypename) continue; 7256 7257 // using decls differ if they name different scopes (but note that 7258 // template instantiation can cause this check to trigger when it 7259 // didn't before instantiation). 7260 if (Context.getCanonicalNestedNameSpecifier(Qual) != 7261 Context.getCanonicalNestedNameSpecifier(DQual)) 7262 continue; 7263 7264 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 7265 Diag(D->getLocation(), diag::note_using_decl) << 1; 7266 return true; 7267 } 7268 7269 return false; 7270} 7271 7272 7273/// Checks that the given nested-name qualifier used in a using decl 7274/// in the current context is appropriately related to the current 7275/// scope. If an error is found, diagnoses it and returns true. 7276bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 7277 const CXXScopeSpec &SS, 7278 SourceLocation NameLoc) { 7279 DeclContext *NamedContext = computeDeclContext(SS); 7280 7281 if (!CurContext->isRecord()) { 7282 // C++03 [namespace.udecl]p3: 7283 // C++0x [namespace.udecl]p8: 7284 // A using-declaration for a class member shall be a member-declaration. 7285 7286 // If we weren't able to compute a valid scope, it must be a 7287 // dependent class scope. 7288 if (!NamedContext || NamedContext->isRecord()) { 7289 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 7290 << SS.getRange(); 7291 return true; 7292 } 7293 7294 // Otherwise, everything is known to be fine. 7295 return false; 7296 } 7297 7298 // The current scope is a record. 7299 7300 // If the named context is dependent, we can't decide much. 7301 if (!NamedContext) { 7302 // FIXME: in C++0x, we can diagnose if we can prove that the 7303 // nested-name-specifier does not refer to a base class, which is 7304 // still possible in some cases. 7305 7306 // Otherwise we have to conservatively report that things might be 7307 // okay. 7308 return false; 7309 } 7310 7311 if (!NamedContext->isRecord()) { 7312 // Ideally this would point at the last name in the specifier, 7313 // but we don't have that level of source info. 7314 Diag(SS.getRange().getBegin(), 7315 diag::err_using_decl_nested_name_specifier_is_not_class) 7316 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange(); 7317 return true; 7318 } 7319 7320 if (!NamedContext->isDependentContext() && 7321 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 7322 return true; 7323 7324 if (getLangOpts().CPlusPlus11) { 7325 // C++0x [namespace.udecl]p3: 7326 // In a using-declaration used as a member-declaration, the 7327 // nested-name-specifier shall name a base class of the class 7328 // being defined. 7329 7330 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 7331 cast<CXXRecordDecl>(NamedContext))) { 7332 if (CurContext == NamedContext) { 7333 Diag(NameLoc, 7334 diag::err_using_decl_nested_name_specifier_is_current_class) 7335 << SS.getRange(); 7336 return true; 7337 } 7338 7339 Diag(SS.getRange().getBegin(), 7340 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7341 << (NestedNameSpecifier*) SS.getScopeRep() 7342 << cast<CXXRecordDecl>(CurContext) 7343 << SS.getRange(); 7344 return true; 7345 } 7346 7347 return false; 7348 } 7349 7350 // C++03 [namespace.udecl]p4: 7351 // A using-declaration used as a member-declaration shall refer 7352 // to a member of a base class of the class being defined [etc.]. 7353 7354 // Salient point: SS doesn't have to name a base class as long as 7355 // lookup only finds members from base classes. Therefore we can 7356 // diagnose here only if we can prove that that can't happen, 7357 // i.e. if the class hierarchies provably don't intersect. 7358 7359 // TODO: it would be nice if "definitely valid" results were cached 7360 // in the UsingDecl and UsingShadowDecl so that these checks didn't 7361 // need to be repeated. 7362 7363 struct UserData { 7364 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases; 7365 7366 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) { 7367 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 7368 Data->Bases.insert(Base); 7369 return true; 7370 } 7371 7372 bool hasDependentBases(const CXXRecordDecl *Class) { 7373 return !Class->forallBases(collect, this); 7374 } 7375 7376 /// Returns true if the base is dependent or is one of the 7377 /// accumulated base classes. 7378 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) { 7379 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 7380 return !Data->Bases.count(Base); 7381 } 7382 7383 bool mightShareBases(const CXXRecordDecl *Class) { 7384 return Bases.count(Class) || !Class->forallBases(doesNotContain, this); 7385 } 7386 }; 7387 7388 UserData Data; 7389 7390 // Returns false if we find a dependent base. 7391 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext))) 7392 return false; 7393 7394 // Returns false if the class has a dependent base or if it or one 7395 // of its bases is present in the base set of the current context. 7396 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext))) 7397 return false; 7398 7399 Diag(SS.getRange().getBegin(), 7400 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7401 << (NestedNameSpecifier*) SS.getScopeRep() 7402 << cast<CXXRecordDecl>(CurContext) 7403 << SS.getRange(); 7404 7405 return true; 7406} 7407 7408Decl *Sema::ActOnAliasDeclaration(Scope *S, 7409 AccessSpecifier AS, 7410 MultiTemplateParamsArg TemplateParamLists, 7411 SourceLocation UsingLoc, 7412 UnqualifiedId &Name, 7413 AttributeList *AttrList, 7414 TypeResult Type) { 7415 // Skip up to the relevant declaration scope. 7416 while (S->getFlags() & Scope::TemplateParamScope) 7417 S = S->getParent(); 7418 assert((S->getFlags() & Scope::DeclScope) && 7419 "got alias-declaration outside of declaration scope"); 7420 7421 if (Type.isInvalid()) 7422 return 0; 7423 7424 bool Invalid = false; 7425 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 7426 TypeSourceInfo *TInfo = 0; 7427 GetTypeFromParser(Type.get(), &TInfo); 7428 7429 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 7430 return 0; 7431 7432 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 7433 UPPC_DeclarationType)) { 7434 Invalid = true; 7435 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 7436 TInfo->getTypeLoc().getBeginLoc()); 7437 } 7438 7439 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration); 7440 LookupName(Previous, S); 7441 7442 // Warn about shadowing the name of a template parameter. 7443 if (Previous.isSingleResult() && 7444 Previous.getFoundDecl()->isTemplateParameter()) { 7445 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 7446 Previous.clear(); 7447 } 7448 7449 assert(Name.Kind == UnqualifiedId::IK_Identifier && 7450 "name in alias declaration must be an identifier"); 7451 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 7452 Name.StartLocation, 7453 Name.Identifier, TInfo); 7454 7455 NewTD->setAccess(AS); 7456 7457 if (Invalid) 7458 NewTD->setInvalidDecl(); 7459 7460 ProcessDeclAttributeList(S, NewTD, AttrList); 7461 7462 CheckTypedefForVariablyModifiedType(S, NewTD); 7463 Invalid |= NewTD->isInvalidDecl(); 7464 7465 bool Redeclaration = false; 7466 7467 NamedDecl *NewND; 7468 if (TemplateParamLists.size()) { 7469 TypeAliasTemplateDecl *OldDecl = 0; 7470 TemplateParameterList *OldTemplateParams = 0; 7471 7472 if (TemplateParamLists.size() != 1) { 7473 Diag(UsingLoc, diag::err_alias_template_extra_headers) 7474 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 7475 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 7476 } 7477 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 7478 7479 // Only consider previous declarations in the same scope. 7480 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 7481 /*ExplicitInstantiationOrSpecialization*/false); 7482 if (!Previous.empty()) { 7483 Redeclaration = true; 7484 7485 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 7486 if (!OldDecl && !Invalid) { 7487 Diag(UsingLoc, diag::err_redefinition_different_kind) 7488 << Name.Identifier; 7489 7490 NamedDecl *OldD = Previous.getRepresentativeDecl(); 7491 if (OldD->getLocation().isValid()) 7492 Diag(OldD->getLocation(), diag::note_previous_definition); 7493 7494 Invalid = true; 7495 } 7496 7497 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 7498 if (TemplateParameterListsAreEqual(TemplateParams, 7499 OldDecl->getTemplateParameters(), 7500 /*Complain=*/true, 7501 TPL_TemplateMatch)) 7502 OldTemplateParams = OldDecl->getTemplateParameters(); 7503 else 7504 Invalid = true; 7505 7506 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 7507 if (!Invalid && 7508 !Context.hasSameType(OldTD->getUnderlyingType(), 7509 NewTD->getUnderlyingType())) { 7510 // FIXME: The C++0x standard does not clearly say this is ill-formed, 7511 // but we can't reasonably accept it. 7512 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 7513 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 7514 if (OldTD->getLocation().isValid()) 7515 Diag(OldTD->getLocation(), diag::note_previous_definition); 7516 Invalid = true; 7517 } 7518 } 7519 } 7520 7521 // Merge any previous default template arguments into our parameters, 7522 // and check the parameter list. 7523 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 7524 TPC_TypeAliasTemplate)) 7525 return 0; 7526 7527 TypeAliasTemplateDecl *NewDecl = 7528 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 7529 Name.Identifier, TemplateParams, 7530 NewTD); 7531 7532 NewDecl->setAccess(AS); 7533 7534 if (Invalid) 7535 NewDecl->setInvalidDecl(); 7536 else if (OldDecl) 7537 NewDecl->setPreviousDeclaration(OldDecl); 7538 7539 NewND = NewDecl; 7540 } else { 7541 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 7542 NewND = NewTD; 7543 } 7544 7545 if (!Redeclaration) 7546 PushOnScopeChains(NewND, S); 7547 7548 ActOnDocumentableDecl(NewND); 7549 return NewND; 7550} 7551 7552Decl *Sema::ActOnNamespaceAliasDef(Scope *S, 7553 SourceLocation NamespaceLoc, 7554 SourceLocation AliasLoc, 7555 IdentifierInfo *Alias, 7556 CXXScopeSpec &SS, 7557 SourceLocation IdentLoc, 7558 IdentifierInfo *Ident) { 7559 7560 // Lookup the namespace name. 7561 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 7562 LookupParsedName(R, S, &SS); 7563 7564 // Check if we have a previous declaration with the same name. 7565 NamedDecl *PrevDecl 7566 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName, 7567 ForRedeclaration); 7568 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S)) 7569 PrevDecl = 0; 7570 7571 if (PrevDecl) { 7572 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 7573 // We already have an alias with the same name that points to the same 7574 // namespace, so don't create a new one. 7575 // FIXME: At some point, we'll want to create the (redundant) 7576 // declaration to maintain better source information. 7577 if (!R.isAmbiguous() && !R.empty() && 7578 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl()))) 7579 return 0; 7580 } 7581 7582 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition : 7583 diag::err_redefinition_different_kind; 7584 Diag(AliasLoc, DiagID) << Alias; 7585 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 7586 return 0; 7587 } 7588 7589 if (R.isAmbiguous()) 7590 return 0; 7591 7592 if (R.empty()) { 7593 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 7594 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 7595 return 0; 7596 } 7597 } 7598 7599 NamespaceAliasDecl *AliasDecl = 7600 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 7601 Alias, SS.getWithLocInContext(Context), 7602 IdentLoc, R.getFoundDecl()); 7603 7604 PushOnScopeChains(AliasDecl, S); 7605 return AliasDecl; 7606} 7607 7608Sema::ImplicitExceptionSpecification 7609Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, 7610 CXXMethodDecl *MD) { 7611 CXXRecordDecl *ClassDecl = MD->getParent(); 7612 7613 // C++ [except.spec]p14: 7614 // An implicitly declared special member function (Clause 12) shall have an 7615 // exception-specification. [...] 7616 ImplicitExceptionSpecification ExceptSpec(*this); 7617 if (ClassDecl->isInvalidDecl()) 7618 return ExceptSpec; 7619 7620 // Direct base-class constructors. 7621 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 7622 BEnd = ClassDecl->bases_end(); 7623 B != BEnd; ++B) { 7624 if (B->isVirtual()) // Handled below. 7625 continue; 7626 7627 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 7628 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7629 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 7630 // If this is a deleted function, add it anyway. This might be conformant 7631 // with the standard. This might not. I'm not sure. It might not matter. 7632 if (Constructor) 7633 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 7634 } 7635 } 7636 7637 // Virtual base-class constructors. 7638 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 7639 BEnd = ClassDecl->vbases_end(); 7640 B != BEnd; ++B) { 7641 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 7642 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7643 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 7644 // If this is a deleted function, add it anyway. This might be conformant 7645 // with the standard. This might not. I'm not sure. It might not matter. 7646 if (Constructor) 7647 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 7648 } 7649 } 7650 7651 // Field constructors. 7652 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 7653 FEnd = ClassDecl->field_end(); 7654 F != FEnd; ++F) { 7655 if (F->hasInClassInitializer()) { 7656 if (Expr *E = F->getInClassInitializer()) 7657 ExceptSpec.CalledExpr(E); 7658 else if (!F->isInvalidDecl()) 7659 // DR1351: 7660 // If the brace-or-equal-initializer of a non-static data member 7661 // invokes a defaulted default constructor of its class or of an 7662 // enclosing class in a potentially evaluated subexpression, the 7663 // program is ill-formed. 7664 // 7665 // This resolution is unworkable: the exception specification of the 7666 // default constructor can be needed in an unevaluated context, in 7667 // particular, in the operand of a noexcept-expression, and we can be 7668 // unable to compute an exception specification for an enclosed class. 7669 // 7670 // We do not allow an in-class initializer to require the evaluation 7671 // of the exception specification for any in-class initializer whose 7672 // definition is not lexically complete. 7673 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD; 7674 } else if (const RecordType *RecordTy 7675 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 7676 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 7677 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 7678 // If this is a deleted function, add it anyway. This might be conformant 7679 // with the standard. This might not. I'm not sure. It might not matter. 7680 // In particular, the problem is that this function never gets called. It 7681 // might just be ill-formed because this function attempts to refer to 7682 // a deleted function here. 7683 if (Constructor) 7684 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 7685 } 7686 } 7687 7688 return ExceptSpec; 7689} 7690 7691Sema::ImplicitExceptionSpecification 7692Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) { 7693 CXXRecordDecl *ClassDecl = CD->getParent(); 7694 7695 // C++ [except.spec]p14: 7696 // An inheriting constructor [...] shall have an exception-specification. [...] 7697 ImplicitExceptionSpecification ExceptSpec(*this); 7698 if (ClassDecl->isInvalidDecl()) 7699 return ExceptSpec; 7700 7701 // Inherited constructor. 7702 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor(); 7703 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent(); 7704 // FIXME: Copying or moving the parameters could add extra exceptions to the 7705 // set, as could the default arguments for the inherited constructor. This 7706 // will be addressed when we implement the resolution of core issue 1351. 7707 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD); 7708 7709 // Direct base-class constructors. 7710 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 7711 BEnd = ClassDecl->bases_end(); 7712 B != BEnd; ++B) { 7713 if (B->isVirtual()) // Handled below. 7714 continue; 7715 7716 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 7717 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7718 if (BaseClassDecl == InheritedDecl) 7719 continue; 7720 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 7721 if (Constructor) 7722 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 7723 } 7724 } 7725 7726 // Virtual base-class constructors. 7727 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 7728 BEnd = ClassDecl->vbases_end(); 7729 B != BEnd; ++B) { 7730 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 7731 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7732 if (BaseClassDecl == InheritedDecl) 7733 continue; 7734 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 7735 if (Constructor) 7736 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 7737 } 7738 } 7739 7740 // Field constructors. 7741 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 7742 FEnd = ClassDecl->field_end(); 7743 F != FEnd; ++F) { 7744 if (F->hasInClassInitializer()) { 7745 if (Expr *E = F->getInClassInitializer()) 7746 ExceptSpec.CalledExpr(E); 7747 else if (!F->isInvalidDecl()) 7748 Diag(CD->getLocation(), 7749 diag::err_in_class_initializer_references_def_ctor) << CD; 7750 } else if (const RecordType *RecordTy 7751 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 7752 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 7753 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 7754 if (Constructor) 7755 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 7756 } 7757 } 7758 7759 return ExceptSpec; 7760} 7761 7762namespace { 7763/// RAII object to register a special member as being currently declared. 7764struct DeclaringSpecialMember { 7765 Sema &S; 7766 Sema::SpecialMemberDecl D; 7767 bool WasAlreadyBeingDeclared; 7768 7769 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 7770 : S(S), D(RD, CSM) { 7771 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D); 7772 if (WasAlreadyBeingDeclared) 7773 // This almost never happens, but if it does, ensure that our cache 7774 // doesn't contain a stale result. 7775 S.SpecialMemberCache.clear(); 7776 7777 // FIXME: Register a note to be produced if we encounter an error while 7778 // declaring the special member. 7779 } 7780 ~DeclaringSpecialMember() { 7781 if (!WasAlreadyBeingDeclared) 7782 S.SpecialMembersBeingDeclared.erase(D); 7783 } 7784 7785 /// \brief Are we already trying to declare this special member? 7786 bool isAlreadyBeingDeclared() const { 7787 return WasAlreadyBeingDeclared; 7788 } 7789}; 7790} 7791 7792CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 7793 CXXRecordDecl *ClassDecl) { 7794 // C++ [class.ctor]p5: 7795 // A default constructor for a class X is a constructor of class X 7796 // that can be called without an argument. If there is no 7797 // user-declared constructor for class X, a default constructor is 7798 // implicitly declared. An implicitly-declared default constructor 7799 // is an inline public member of its class. 7800 assert(ClassDecl->needsImplicitDefaultConstructor() && 7801 "Should not build implicit default constructor!"); 7802 7803 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 7804 if (DSM.isAlreadyBeingDeclared()) 7805 return 0; 7806 7807 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 7808 CXXDefaultConstructor, 7809 false); 7810 7811 // Create the actual constructor declaration. 7812 CanQualType ClassType 7813 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 7814 SourceLocation ClassLoc = ClassDecl->getLocation(); 7815 DeclarationName Name 7816 = Context.DeclarationNames.getCXXConstructorName(ClassType); 7817 DeclarationNameInfo NameInfo(Name, ClassLoc); 7818 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 7819 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0, 7820 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 7821 Constexpr); 7822 DefaultCon->setAccess(AS_public); 7823 DefaultCon->setDefaulted(); 7824 DefaultCon->setImplicit(); 7825 7826 // Build an exception specification pointing back at this constructor. 7827 FunctionProtoType::ExtProtoInfo EPI; 7828 EPI.ExceptionSpecType = EST_Unevaluated; 7829 EPI.ExceptionSpecDecl = DefaultCon; 7830 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 7831 7832 // We don't need to use SpecialMemberIsTrivial here; triviality for default 7833 // constructors is easy to compute. 7834 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 7835 7836 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 7837 SetDeclDeleted(DefaultCon, ClassLoc); 7838 7839 // Note that we have declared this constructor. 7840 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 7841 7842 if (Scope *S = getScopeForContext(ClassDecl)) 7843 PushOnScopeChains(DefaultCon, S, false); 7844 ClassDecl->addDecl(DefaultCon); 7845 7846 return DefaultCon; 7847} 7848 7849void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 7850 CXXConstructorDecl *Constructor) { 7851 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 7852 !Constructor->doesThisDeclarationHaveABody() && 7853 !Constructor->isDeleted()) && 7854 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 7855 7856 CXXRecordDecl *ClassDecl = Constructor->getParent(); 7857 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 7858 7859 SynthesizedFunctionScope Scope(*this, Constructor); 7860 DiagnosticErrorTrap Trap(Diags); 7861 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 7862 Trap.hasErrorOccurred()) { 7863 Diag(CurrentLocation, diag::note_member_synthesized_at) 7864 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl); 7865 Constructor->setInvalidDecl(); 7866 return; 7867 } 7868 7869 SourceLocation Loc = Constructor->getLocation(); 7870 Constructor->setBody(new (Context) CompoundStmt(Loc)); 7871 7872 Constructor->setUsed(); 7873 MarkVTableUsed(CurrentLocation, ClassDecl); 7874 7875 if (ASTMutationListener *L = getASTMutationListener()) { 7876 L->CompletedImplicitDefinition(Constructor); 7877 } 7878} 7879 7880void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 7881 // Check that any explicitly-defaulted methods have exception specifications 7882 // compatible with their implicit exception specifications. 7883 CheckDelayedExplicitlyDefaultedMemberExceptionSpecs(); 7884} 7885 7886namespace { 7887/// Information on inheriting constructors to declare. 7888class InheritingConstructorInfo { 7889public: 7890 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived) 7891 : SemaRef(SemaRef), Derived(Derived) { 7892 // Mark the constructors that we already have in the derived class. 7893 // 7894 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...] 7895 // unless there is a user-declared constructor with the same signature in 7896 // the class where the using-declaration appears. 7897 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived); 7898 } 7899 7900 void inheritAll(CXXRecordDecl *RD) { 7901 visitAll(RD, &InheritingConstructorInfo::inherit); 7902 } 7903 7904private: 7905 /// Information about an inheriting constructor. 7906 struct InheritingConstructor { 7907 InheritingConstructor() 7908 : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {} 7909 7910 /// If \c true, a constructor with this signature is already declared 7911 /// in the derived class. 7912 bool DeclaredInDerived; 7913 7914 /// The constructor which is inherited. 7915 const CXXConstructorDecl *BaseCtor; 7916 7917 /// The derived constructor we declared. 7918 CXXConstructorDecl *DerivedCtor; 7919 }; 7920 7921 /// Inheriting constructors with a given canonical type. There can be at 7922 /// most one such non-template constructor, and any number of templated 7923 /// constructors. 7924 struct InheritingConstructorsForType { 7925 InheritingConstructor NonTemplate; 7926 llvm::SmallVector< 7927 std::pair<TemplateParameterList*, InheritingConstructor>, 4> Templates; 7928 7929 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) { 7930 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) { 7931 TemplateParameterList *ParamList = FTD->getTemplateParameters(); 7932 for (unsigned I = 0, N = Templates.size(); I != N; ++I) 7933 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first, 7934 false, S.TPL_TemplateMatch)) 7935 return Templates[I].second; 7936 Templates.push_back(std::make_pair(ParamList, InheritingConstructor())); 7937 return Templates.back().second; 7938 } 7939 7940 return NonTemplate; 7941 } 7942 }; 7943 7944 /// Get or create the inheriting constructor record for a constructor. 7945 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor, 7946 QualType CtorType) { 7947 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()] 7948 .getEntry(SemaRef, Ctor); 7949 } 7950 7951 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*); 7952 7953 /// Process all constructors for a class. 7954 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) { 7955 for (CXXRecordDecl::ctor_iterator CtorIt = RD->ctor_begin(), 7956 CtorE = RD->ctor_end(); 7957 CtorIt != CtorE; ++CtorIt) 7958 (this->*Callback)(*CtorIt); 7959 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> 7960 I(RD->decls_begin()), E(RD->decls_end()); 7961 I != E; ++I) { 7962 const FunctionDecl *FD = (*I)->getTemplatedDecl(); 7963 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) 7964 (this->*Callback)(CD); 7965 } 7966 } 7967 7968 /// Note that a constructor (or constructor template) was declared in Derived. 7969 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) { 7970 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true; 7971 } 7972 7973 /// Inherit a single constructor. 7974 void inherit(const CXXConstructorDecl *Ctor) { 7975 const FunctionProtoType *CtorType = 7976 Ctor->getType()->castAs<FunctionProtoType>(); 7977 ArrayRef<QualType> ArgTypes(CtorType->getArgTypes()); 7978 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo(); 7979 7980 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent()); 7981 7982 // Core issue (no number yet): the ellipsis is always discarded. 7983 if (EPI.Variadic) { 7984 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis); 7985 SemaRef.Diag(Ctor->getLocation(), 7986 diag::note_using_decl_constructor_ellipsis); 7987 EPI.Variadic = false; 7988 } 7989 7990 // Declare a constructor for each number of parameters. 7991 // 7992 // C++11 [class.inhctor]p1: 7993 // The candidate set of inherited constructors from the class X named in 7994 // the using-declaration consists of [... modulo defects ...] for each 7995 // constructor or constructor template of X, the set of constructors or 7996 // constructor templates that results from omitting any ellipsis parameter 7997 // specification and successively omitting parameters with a default 7998 // argument from the end of the parameter-type-list 7999 unsigned MinParams = minParamsToInherit(Ctor); 8000 unsigned Params = Ctor->getNumParams(); 8001 if (Params >= MinParams) { 8002 do 8003 declareCtor(UsingLoc, Ctor, 8004 SemaRef.Context.getFunctionType( 8005 Ctor->getResultType(), ArgTypes.slice(0, Params), EPI)); 8006 while (Params > MinParams && 8007 Ctor->getParamDecl(--Params)->hasDefaultArg()); 8008 } 8009 } 8010 8011 /// Find the using-declaration which specified that we should inherit the 8012 /// constructors of \p Base. 8013 SourceLocation getUsingLoc(const CXXRecordDecl *Base) { 8014 // No fancy lookup required; just look for the base constructor name 8015 // directly within the derived class. 8016 ASTContext &Context = SemaRef.Context; 8017 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 8018 Context.getCanonicalType(Context.getRecordType(Base))); 8019 DeclContext::lookup_const_result Decls = Derived->lookup(Name); 8020 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation(); 8021 } 8022 8023 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) { 8024 // C++11 [class.inhctor]p3: 8025 // [F]or each constructor template in the candidate set of inherited 8026 // constructors, a constructor template is implicitly declared 8027 if (Ctor->getDescribedFunctionTemplate()) 8028 return 0; 8029 8030 // For each non-template constructor in the candidate set of inherited 8031 // constructors other than a constructor having no parameters or a 8032 // copy/move constructor having a single parameter, a constructor is 8033 // implicitly declared [...] 8034 if (Ctor->getNumParams() == 0) 8035 return 1; 8036 if (Ctor->isCopyOrMoveConstructor()) 8037 return 2; 8038 8039 // Per discussion on core reflector, never inherit a constructor which 8040 // would become a default, copy, or move constructor of Derived either. 8041 const ParmVarDecl *PD = Ctor->getParamDecl(0); 8042 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>(); 8043 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1; 8044 } 8045 8046 /// Declare a single inheriting constructor, inheriting the specified 8047 /// constructor, with the given type. 8048 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor, 8049 QualType DerivedType) { 8050 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType); 8051 8052 // C++11 [class.inhctor]p3: 8053 // ... a constructor is implicitly declared with the same constructor 8054 // characteristics unless there is a user-declared constructor with 8055 // the same signature in the class where the using-declaration appears 8056 if (Entry.DeclaredInDerived) 8057 return; 8058 8059 // C++11 [class.inhctor]p7: 8060 // If two using-declarations declare inheriting constructors with the 8061 // same signature, the program is ill-formed 8062 if (Entry.DerivedCtor) { 8063 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) { 8064 // Only diagnose this once per constructor. 8065 if (Entry.DerivedCtor->isInvalidDecl()) 8066 return; 8067 Entry.DerivedCtor->setInvalidDecl(); 8068 8069 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict); 8070 SemaRef.Diag(BaseCtor->getLocation(), 8071 diag::note_using_decl_constructor_conflict_current_ctor); 8072 SemaRef.Diag(Entry.BaseCtor->getLocation(), 8073 diag::note_using_decl_constructor_conflict_previous_ctor); 8074 SemaRef.Diag(Entry.DerivedCtor->getLocation(), 8075 diag::note_using_decl_constructor_conflict_previous_using); 8076 } else { 8077 // Core issue (no number): if the same inheriting constructor is 8078 // produced by multiple base class constructors from the same base 8079 // class, the inheriting constructor is defined as deleted. 8080 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc); 8081 } 8082 8083 return; 8084 } 8085 8086 ASTContext &Context = SemaRef.Context; 8087 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 8088 Context.getCanonicalType(Context.getRecordType(Derived))); 8089 DeclarationNameInfo NameInfo(Name, UsingLoc); 8090 8091 TemplateParameterList *TemplateParams = 0; 8092 if (const FunctionTemplateDecl *FTD = 8093 BaseCtor->getDescribedFunctionTemplate()) { 8094 TemplateParams = FTD->getTemplateParameters(); 8095 // We're reusing template parameters from a different DeclContext. This 8096 // is questionable at best, but works out because the template depth in 8097 // both places is guaranteed to be 0. 8098 // FIXME: Rebuild the template parameters in the new context, and 8099 // transform the function type to refer to them. 8100 } 8101 8102 // Build type source info pointing at the using-declaration. This is 8103 // required by template instantiation. 8104 TypeSourceInfo *TInfo = 8105 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc); 8106 FunctionProtoTypeLoc ProtoLoc = 8107 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 8108 8109 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 8110 Context, Derived, UsingLoc, NameInfo, DerivedType, 8111 TInfo, BaseCtor->isExplicit(), /*Inline=*/true, 8112 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr()); 8113 8114 // Build an unevaluated exception specification for this constructor. 8115 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>(); 8116 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8117 EPI.ExceptionSpecType = EST_Unevaluated; 8118 EPI.ExceptionSpecDecl = DerivedCtor; 8119 DerivedCtor->setType(Context.getFunctionType(FPT->getResultType(), 8120 FPT->getArgTypes(), EPI)); 8121 8122 // Build the parameter declarations. 8123 SmallVector<ParmVarDecl *, 16> ParamDecls; 8124 for (unsigned I = 0, N = FPT->getNumArgs(); I != N; ++I) { 8125 TypeSourceInfo *TInfo = 8126 Context.getTrivialTypeSourceInfo(FPT->getArgType(I), UsingLoc); 8127 ParmVarDecl *PD = ParmVarDecl::Create( 8128 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0, 8129 FPT->getArgType(I), TInfo, SC_None, /*DefaultArg=*/0); 8130 PD->setScopeInfo(0, I); 8131 PD->setImplicit(); 8132 ParamDecls.push_back(PD); 8133 ProtoLoc.setArg(I, PD); 8134 } 8135 8136 // Set up the new constructor. 8137 DerivedCtor->setAccess(BaseCtor->getAccess()); 8138 DerivedCtor->setParams(ParamDecls); 8139 DerivedCtor->setInheritedConstructor(BaseCtor); 8140 if (BaseCtor->isDeleted()) 8141 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc); 8142 8143 // If this is a constructor template, build the template declaration. 8144 if (TemplateParams) { 8145 FunctionTemplateDecl *DerivedTemplate = 8146 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name, 8147 TemplateParams, DerivedCtor); 8148 DerivedTemplate->setAccess(BaseCtor->getAccess()); 8149 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate); 8150 Derived->addDecl(DerivedTemplate); 8151 } else { 8152 Derived->addDecl(DerivedCtor); 8153 } 8154 8155 Entry.BaseCtor = BaseCtor; 8156 Entry.DerivedCtor = DerivedCtor; 8157 } 8158 8159 Sema &SemaRef; 8160 CXXRecordDecl *Derived; 8161 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType; 8162 MapType Map; 8163}; 8164} 8165 8166void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) { 8167 // Defer declaring the inheriting constructors until the class is 8168 // instantiated. 8169 if (ClassDecl->isDependentContext()) 8170 return; 8171 8172 // Find base classes from which we might inherit constructors. 8173 SmallVector<CXXRecordDecl*, 4> InheritedBases; 8174 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(), 8175 BaseE = ClassDecl->bases_end(); 8176 BaseIt != BaseE; ++BaseIt) 8177 if (BaseIt->getInheritConstructors()) 8178 InheritedBases.push_back(BaseIt->getType()->getAsCXXRecordDecl()); 8179 8180 // Go no further if we're not inheriting any constructors. 8181 if (InheritedBases.empty()) 8182 return; 8183 8184 // Declare the inherited constructors. 8185 InheritingConstructorInfo ICI(*this, ClassDecl); 8186 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I) 8187 ICI.inheritAll(InheritedBases[I]); 8188} 8189 8190void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 8191 CXXConstructorDecl *Constructor) { 8192 CXXRecordDecl *ClassDecl = Constructor->getParent(); 8193 assert(Constructor->getInheritedConstructor() && 8194 !Constructor->doesThisDeclarationHaveABody() && 8195 !Constructor->isDeleted()); 8196 8197 SynthesizedFunctionScope Scope(*this, Constructor); 8198 DiagnosticErrorTrap Trap(Diags); 8199 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 8200 Trap.hasErrorOccurred()) { 8201 Diag(CurrentLocation, diag::note_inhctor_synthesized_at) 8202 << Context.getTagDeclType(ClassDecl); 8203 Constructor->setInvalidDecl(); 8204 return; 8205 } 8206 8207 SourceLocation Loc = Constructor->getLocation(); 8208 Constructor->setBody(new (Context) CompoundStmt(Loc)); 8209 8210 Constructor->setUsed(); 8211 MarkVTableUsed(CurrentLocation, ClassDecl); 8212 8213 if (ASTMutationListener *L = getASTMutationListener()) { 8214 L->CompletedImplicitDefinition(Constructor); 8215 } 8216} 8217 8218 8219Sema::ImplicitExceptionSpecification 8220Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) { 8221 CXXRecordDecl *ClassDecl = MD->getParent(); 8222 8223 // C++ [except.spec]p14: 8224 // An implicitly declared special member function (Clause 12) shall have 8225 // an exception-specification. 8226 ImplicitExceptionSpecification ExceptSpec(*this); 8227 if (ClassDecl->isInvalidDecl()) 8228 return ExceptSpec; 8229 8230 // Direct base-class destructors. 8231 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 8232 BEnd = ClassDecl->bases_end(); 8233 B != BEnd; ++B) { 8234 if (B->isVirtual()) // Handled below. 8235 continue; 8236 8237 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) 8238 ExceptSpec.CalledDecl(B->getLocStart(), 8239 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 8240 } 8241 8242 // Virtual base-class destructors. 8243 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 8244 BEnd = ClassDecl->vbases_end(); 8245 B != BEnd; ++B) { 8246 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) 8247 ExceptSpec.CalledDecl(B->getLocStart(), 8248 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 8249 } 8250 8251 // Field destructors. 8252 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 8253 FEnd = ClassDecl->field_end(); 8254 F != FEnd; ++F) { 8255 if (const RecordType *RecordTy 8256 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) 8257 ExceptSpec.CalledDecl(F->getLocation(), 8258 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl()))); 8259 } 8260 8261 return ExceptSpec; 8262} 8263 8264CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 8265 // C++ [class.dtor]p2: 8266 // If a class has no user-declared destructor, a destructor is 8267 // declared implicitly. An implicitly-declared destructor is an 8268 // inline public member of its class. 8269 assert(ClassDecl->needsImplicitDestructor()); 8270 8271 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 8272 if (DSM.isAlreadyBeingDeclared()) 8273 return 0; 8274 8275 // Create the actual destructor declaration. 8276 CanQualType ClassType 8277 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8278 SourceLocation ClassLoc = ClassDecl->getLocation(); 8279 DeclarationName Name 8280 = Context.DeclarationNames.getCXXDestructorName(ClassType); 8281 DeclarationNameInfo NameInfo(Name, ClassLoc); 8282 CXXDestructorDecl *Destructor 8283 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 8284 QualType(), 0, /*isInline=*/true, 8285 /*isImplicitlyDeclared=*/true); 8286 Destructor->setAccess(AS_public); 8287 Destructor->setDefaulted(); 8288 Destructor->setImplicit(); 8289 8290 // Build an exception specification pointing back at this destructor. 8291 FunctionProtoType::ExtProtoInfo EPI; 8292 EPI.ExceptionSpecType = EST_Unevaluated; 8293 EPI.ExceptionSpecDecl = Destructor; 8294 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 8295 8296 AddOverriddenMethods(ClassDecl, Destructor); 8297 8298 // We don't need to use SpecialMemberIsTrivial here; triviality for 8299 // destructors is easy to compute. 8300 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 8301 8302 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 8303 SetDeclDeleted(Destructor, ClassLoc); 8304 8305 // Note that we have declared this destructor. 8306 ++ASTContext::NumImplicitDestructorsDeclared; 8307 8308 // Introduce this destructor into its scope. 8309 if (Scope *S = getScopeForContext(ClassDecl)) 8310 PushOnScopeChains(Destructor, S, false); 8311 ClassDecl->addDecl(Destructor); 8312 8313 return Destructor; 8314} 8315 8316void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 8317 CXXDestructorDecl *Destructor) { 8318 assert((Destructor->isDefaulted() && 8319 !Destructor->doesThisDeclarationHaveABody() && 8320 !Destructor->isDeleted()) && 8321 "DefineImplicitDestructor - call it for implicit default dtor"); 8322 CXXRecordDecl *ClassDecl = Destructor->getParent(); 8323 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 8324 8325 if (Destructor->isInvalidDecl()) 8326 return; 8327 8328 SynthesizedFunctionScope Scope(*this, Destructor); 8329 8330 DiagnosticErrorTrap Trap(Diags); 8331 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 8332 Destructor->getParent()); 8333 8334 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) { 8335 Diag(CurrentLocation, diag::note_member_synthesized_at) 8336 << CXXDestructor << Context.getTagDeclType(ClassDecl); 8337 8338 Destructor->setInvalidDecl(); 8339 return; 8340 } 8341 8342 SourceLocation Loc = Destructor->getLocation(); 8343 Destructor->setBody(new (Context) CompoundStmt(Loc)); 8344 Destructor->setImplicitlyDefined(true); 8345 Destructor->setUsed(); 8346 MarkVTableUsed(CurrentLocation, ClassDecl); 8347 8348 if (ASTMutationListener *L = getASTMutationListener()) { 8349 L->CompletedImplicitDefinition(Destructor); 8350 } 8351} 8352 8353/// \brief Perform any semantic analysis which needs to be delayed until all 8354/// pending class member declarations have been parsed. 8355void Sema::ActOnFinishCXXMemberDecls() { 8356 // If the context is an invalid C++ class, just suppress these checks. 8357 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 8358 if (Record->isInvalidDecl()) { 8359 DelayedDestructorExceptionSpecChecks.clear(); 8360 return; 8361 } 8362 } 8363 8364 // Perform any deferred checking of exception specifications for virtual 8365 // destructors. 8366 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size(); 8367 i != e; ++i) { 8368 const CXXDestructorDecl *Dtor = 8369 DelayedDestructorExceptionSpecChecks[i].first; 8370 assert(!Dtor->getParent()->isDependentType() && 8371 "Should not ever add destructors of templates into the list."); 8372 CheckOverridingFunctionExceptionSpec(Dtor, 8373 DelayedDestructorExceptionSpecChecks[i].second); 8374 } 8375 DelayedDestructorExceptionSpecChecks.clear(); 8376} 8377 8378void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 8379 CXXDestructorDecl *Destructor) { 8380 assert(getLangOpts().CPlusPlus11 && 8381 "adjusting dtor exception specs was introduced in c++11"); 8382 8383 // C++11 [class.dtor]p3: 8384 // A declaration of a destructor that does not have an exception- 8385 // specification is implicitly considered to have the same exception- 8386 // specification as an implicit declaration. 8387 const FunctionProtoType *DtorType = Destructor->getType()-> 8388 getAs<FunctionProtoType>(); 8389 if (DtorType->hasExceptionSpec()) 8390 return; 8391 8392 // Replace the destructor's type, building off the existing one. Fortunately, 8393 // the only thing of interest in the destructor type is its extended info. 8394 // The return and arguments are fixed. 8395 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 8396 EPI.ExceptionSpecType = EST_Unevaluated; 8397 EPI.ExceptionSpecDecl = Destructor; 8398 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 8399 8400 // FIXME: If the destructor has a body that could throw, and the newly created 8401 // spec doesn't allow exceptions, we should emit a warning, because this 8402 // change in behavior can break conforming C++03 programs at runtime. 8403 // However, we don't have a body or an exception specification yet, so it 8404 // needs to be done somewhere else. 8405} 8406 8407/// When generating a defaulted copy or move assignment operator, if a field 8408/// should be copied with __builtin_memcpy rather than via explicit assignments, 8409/// do so. This optimization only applies for arrays of scalars, and for arrays 8410/// of class type where the selected copy/move-assignment operator is trivial. 8411static StmtResult 8412buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 8413 Expr *To, Expr *From) { 8414 // Compute the size of the memory buffer to be copied. 8415 QualType SizeType = S.Context.getSizeType(); 8416 llvm::APInt Size(S.Context.getTypeSize(SizeType), 8417 S.Context.getTypeSizeInChars(T).getQuantity()); 8418 8419 // Take the address of the field references for "from" and "to". We 8420 // directly construct UnaryOperators here because semantic analysis 8421 // does not permit us to take the address of an xvalue. 8422 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 8423 S.Context.getPointerType(From->getType()), 8424 VK_RValue, OK_Ordinary, Loc); 8425 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 8426 S.Context.getPointerType(To->getType()), 8427 VK_RValue, OK_Ordinary, Loc); 8428 8429 const Type *E = T->getBaseElementTypeUnsafe(); 8430 bool NeedsCollectableMemCpy = 8431 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 8432 8433 // Create a reference to the __builtin_objc_memmove_collectable function 8434 StringRef MemCpyName = NeedsCollectableMemCpy ? 8435 "__builtin_objc_memmove_collectable" : 8436 "__builtin_memcpy"; 8437 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 8438 Sema::LookupOrdinaryName); 8439 S.LookupName(R, S.TUScope, true); 8440 8441 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 8442 if (!MemCpy) 8443 // Something went horribly wrong earlier, and we will have complained 8444 // about it. 8445 return StmtError(); 8446 8447 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 8448 VK_RValue, Loc, 0); 8449 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 8450 8451 Expr *CallArgs[] = { 8452 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 8453 }; 8454 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(), 8455 Loc, CallArgs, Loc); 8456 8457 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 8458 return S.Owned(Call.takeAs<Stmt>()); 8459} 8460 8461/// \brief Builds a statement that copies/moves the given entity from \p From to 8462/// \c To. 8463/// 8464/// This routine is used to copy/move the members of a class with an 8465/// implicitly-declared copy/move assignment operator. When the entities being 8466/// copied are arrays, this routine builds for loops to copy them. 8467/// 8468/// \param S The Sema object used for type-checking. 8469/// 8470/// \param Loc The location where the implicit copy/move is being generated. 8471/// 8472/// \param T The type of the expressions being copied/moved. Both expressions 8473/// must have this type. 8474/// 8475/// \param To The expression we are copying/moving to. 8476/// 8477/// \param From The expression we are copying/moving from. 8478/// 8479/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 8480/// Otherwise, it's a non-static member subobject. 8481/// 8482/// \param Copying Whether we're copying or moving. 8483/// 8484/// \param Depth Internal parameter recording the depth of the recursion. 8485/// 8486/// \returns A statement or a loop that copies the expressions, or StmtResult(0) 8487/// if a memcpy should be used instead. 8488static StmtResult 8489buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 8490 Expr *To, Expr *From, 8491 bool CopyingBaseSubobject, bool Copying, 8492 unsigned Depth = 0) { 8493 // C++11 [class.copy]p28: 8494 // Each subobject is assigned in the manner appropriate to its type: 8495 // 8496 // - if the subobject is of class type, as if by a call to operator= with 8497 // the subobject as the object expression and the corresponding 8498 // subobject of x as a single function argument (as if by explicit 8499 // qualification; that is, ignoring any possible virtual overriding 8500 // functions in more derived classes); 8501 // 8502 // C++03 [class.copy]p13: 8503 // - if the subobject is of class type, the copy assignment operator for 8504 // the class is used (as if by explicit qualification; that is, 8505 // ignoring any possible virtual overriding functions in more derived 8506 // classes); 8507 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 8508 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8509 8510 // Look for operator=. 8511 DeclarationName Name 8512 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 8513 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 8514 S.LookupQualifiedName(OpLookup, ClassDecl, false); 8515 8516 // Prior to C++11, filter out any result that isn't a copy/move-assignment 8517 // operator. 8518 if (!S.getLangOpts().CPlusPlus11) { 8519 LookupResult::Filter F = OpLookup.makeFilter(); 8520 while (F.hasNext()) { 8521 NamedDecl *D = F.next(); 8522 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 8523 if (Method->isCopyAssignmentOperator() || 8524 (!Copying && Method->isMoveAssignmentOperator())) 8525 continue; 8526 8527 F.erase(); 8528 } 8529 F.done(); 8530 } 8531 8532 // Suppress the protected check (C++ [class.protected]) for each of the 8533 // assignment operators we found. This strange dance is required when 8534 // we're assigning via a base classes's copy-assignment operator. To 8535 // ensure that we're getting the right base class subobject (without 8536 // ambiguities), we need to cast "this" to that subobject type; to 8537 // ensure that we don't go through the virtual call mechanism, we need 8538 // to qualify the operator= name with the base class (see below). However, 8539 // this means that if the base class has a protected copy assignment 8540 // operator, the protected member access check will fail. So, we 8541 // rewrite "protected" access to "public" access in this case, since we 8542 // know by construction that we're calling from a derived class. 8543 if (CopyingBaseSubobject) { 8544 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 8545 L != LEnd; ++L) { 8546 if (L.getAccess() == AS_protected) 8547 L.setAccess(AS_public); 8548 } 8549 } 8550 8551 // Create the nested-name-specifier that will be used to qualify the 8552 // reference to operator=; this is required to suppress the virtual 8553 // call mechanism. 8554 CXXScopeSpec SS; 8555 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 8556 SS.MakeTrivial(S.Context, 8557 NestedNameSpecifier::Create(S.Context, 0, false, 8558 CanonicalT), 8559 Loc); 8560 8561 // Create the reference to operator=. 8562 ExprResult OpEqualRef 8563 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS, 8564 /*TemplateKWLoc=*/SourceLocation(), 8565 /*FirstQualifierInScope=*/0, 8566 OpLookup, 8567 /*TemplateArgs=*/0, 8568 /*SuppressQualifierCheck=*/true); 8569 if (OpEqualRef.isInvalid()) 8570 return StmtError(); 8571 8572 // Build the call to the assignment operator. 8573 8574 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0, 8575 OpEqualRef.takeAs<Expr>(), 8576 Loc, From, Loc); 8577 if (Call.isInvalid()) 8578 return StmtError(); 8579 8580 // If we built a call to a trivial 'operator=' while copying an array, 8581 // bail out. We'll replace the whole shebang with a memcpy. 8582 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 8583 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 8584 return StmtResult((Stmt*)0); 8585 8586 // Convert to an expression-statement, and clean up any produced 8587 // temporaries. 8588 return S.ActOnExprStmt(Call); 8589 } 8590 8591 // - if the subobject is of scalar type, the built-in assignment 8592 // operator is used. 8593 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 8594 if (!ArrayTy) { 8595 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From); 8596 if (Assignment.isInvalid()) 8597 return StmtError(); 8598 return S.ActOnExprStmt(Assignment); 8599 } 8600 8601 // - if the subobject is an array, each element is assigned, in the 8602 // manner appropriate to the element type; 8603 8604 // Construct a loop over the array bounds, e.g., 8605 // 8606 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 8607 // 8608 // that will copy each of the array elements. 8609 QualType SizeType = S.Context.getSizeType(); 8610 8611 // Create the iteration variable. 8612 IdentifierInfo *IterationVarName = 0; 8613 { 8614 SmallString<8> Str; 8615 llvm::raw_svector_ostream OS(Str); 8616 OS << "__i" << Depth; 8617 IterationVarName = &S.Context.Idents.get(OS.str()); 8618 } 8619 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 8620 IterationVarName, SizeType, 8621 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 8622 SC_None); 8623 8624 // Initialize the iteration variable to zero. 8625 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 8626 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 8627 8628 // Create a reference to the iteration variable; we'll use this several 8629 // times throughout. 8630 Expr *IterationVarRef 8631 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take(); 8632 assert(IterationVarRef && "Reference to invented variable cannot fail!"); 8633 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take(); 8634 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!"); 8635 8636 // Create the DeclStmt that holds the iteration variable. 8637 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 8638 8639 // Subscript the "from" and "to" expressions with the iteration variable. 8640 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc, 8641 IterationVarRefRVal, 8642 Loc)); 8643 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc, 8644 IterationVarRefRVal, 8645 Loc)); 8646 if (!Copying) // Cast to rvalue 8647 From = CastForMoving(S, From); 8648 8649 // Build the copy/move for an individual element of the array. 8650 StmtResult Copy = 8651 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 8652 To, From, CopyingBaseSubobject, 8653 Copying, Depth + 1); 8654 // Bail out if copying fails or if we determined that we should use memcpy. 8655 if (Copy.isInvalid() || !Copy.get()) 8656 return Copy; 8657 8658 // Create the comparison against the array bound. 8659 llvm::APInt Upper 8660 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 8661 Expr *Comparison 8662 = new (S.Context) BinaryOperator(IterationVarRefRVal, 8663 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 8664 BO_NE, S.Context.BoolTy, 8665 VK_RValue, OK_Ordinary, Loc, false); 8666 8667 // Create the pre-increment of the iteration variable. 8668 Expr *Increment 8669 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType, 8670 VK_LValue, OK_Ordinary, Loc); 8671 8672 // Construct the loop that copies all elements of this array. 8673 return S.ActOnForStmt(Loc, Loc, InitStmt, 8674 S.MakeFullExpr(Comparison), 8675 0, S.MakeFullDiscardedValueExpr(Increment), 8676 Loc, Copy.take()); 8677} 8678 8679static StmtResult 8680buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 8681 Expr *To, Expr *From, 8682 bool CopyingBaseSubobject, bool Copying) { 8683 // Maybe we should use a memcpy? 8684 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 8685 T.isTriviallyCopyableType(S.Context)) 8686 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 8687 8688 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 8689 CopyingBaseSubobject, 8690 Copying, 0)); 8691 8692 // If we ended up picking a trivial assignment operator for an array of a 8693 // non-trivially-copyable class type, just emit a memcpy. 8694 if (!Result.isInvalid() && !Result.get()) 8695 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 8696 8697 return Result; 8698} 8699 8700Sema::ImplicitExceptionSpecification 8701Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) { 8702 CXXRecordDecl *ClassDecl = MD->getParent(); 8703 8704 ImplicitExceptionSpecification ExceptSpec(*this); 8705 if (ClassDecl->isInvalidDecl()) 8706 return ExceptSpec; 8707 8708 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 8709 assert(T->getNumArgs() == 1 && "not a copy assignment op"); 8710 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers(); 8711 8712 // C++ [except.spec]p14: 8713 // An implicitly declared special member function (Clause 12) shall have an 8714 // exception-specification. [...] 8715 8716 // It is unspecified whether or not an implicit copy assignment operator 8717 // attempts to deduplicate calls to assignment operators of virtual bases are 8718 // made. As such, this exception specification is effectively unspecified. 8719 // Based on a similar decision made for constness in C++0x, we're erring on 8720 // the side of assuming such calls to be made regardless of whether they 8721 // actually happen. 8722 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 8723 BaseEnd = ClassDecl->bases_end(); 8724 Base != BaseEnd; ++Base) { 8725 if (Base->isVirtual()) 8726 continue; 8727 8728 CXXRecordDecl *BaseClassDecl 8729 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8730 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 8731 ArgQuals, false, 0)) 8732 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign); 8733 } 8734 8735 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 8736 BaseEnd = ClassDecl->vbases_end(); 8737 Base != BaseEnd; ++Base) { 8738 CXXRecordDecl *BaseClassDecl 8739 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8740 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 8741 ArgQuals, false, 0)) 8742 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign); 8743 } 8744 8745 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8746 FieldEnd = ClassDecl->field_end(); 8747 Field != FieldEnd; 8748 ++Field) { 8749 QualType FieldType = Context.getBaseElementType(Field->getType()); 8750 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 8751 if (CXXMethodDecl *CopyAssign = 8752 LookupCopyingAssignment(FieldClassDecl, 8753 ArgQuals | FieldType.getCVRQualifiers(), 8754 false, 0)) 8755 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign); 8756 } 8757 } 8758 8759 return ExceptSpec; 8760} 8761 8762CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 8763 // Note: The following rules are largely analoguous to the copy 8764 // constructor rules. Note that virtual bases are not taken into account 8765 // for determining the argument type of the operator. Note also that 8766 // operators taking an object instead of a reference are allowed. 8767 assert(ClassDecl->needsImplicitCopyAssignment()); 8768 8769 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 8770 if (DSM.isAlreadyBeingDeclared()) 8771 return 0; 8772 8773 QualType ArgType = Context.getTypeDeclType(ClassDecl); 8774 QualType RetType = Context.getLValueReferenceType(ArgType); 8775 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 8776 if (Const) 8777 ArgType = ArgType.withConst(); 8778 ArgType = Context.getLValueReferenceType(ArgType); 8779 8780 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 8781 CXXCopyAssignment, 8782 Const); 8783 8784 // An implicitly-declared copy assignment operator is an inline public 8785 // member of its class. 8786 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 8787 SourceLocation ClassLoc = ClassDecl->getLocation(); 8788 DeclarationNameInfo NameInfo(Name, ClassLoc); 8789 CXXMethodDecl *CopyAssignment = 8790 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 8791 /*TInfo=*/ 0, /*StorageClass=*/ SC_None, 8792 /*isInline=*/ true, Constexpr, SourceLocation()); 8793 CopyAssignment->setAccess(AS_public); 8794 CopyAssignment->setDefaulted(); 8795 CopyAssignment->setImplicit(); 8796 8797 // Build an exception specification pointing back at this member. 8798 FunctionProtoType::ExtProtoInfo EPI; 8799 EPI.ExceptionSpecType = EST_Unevaluated; 8800 EPI.ExceptionSpecDecl = CopyAssignment; 8801 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 8802 8803 // Add the parameter to the operator. 8804 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 8805 ClassLoc, ClassLoc, /*Id=*/0, 8806 ArgType, /*TInfo=*/0, 8807 SC_None, 0); 8808 CopyAssignment->setParams(FromParam); 8809 8810 AddOverriddenMethods(ClassDecl, CopyAssignment); 8811 8812 CopyAssignment->setTrivial( 8813 ClassDecl->needsOverloadResolutionForCopyAssignment() 8814 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 8815 : ClassDecl->hasTrivialCopyAssignment()); 8816 8817 // C++11 [class.copy]p19: 8818 // .... If the class definition does not explicitly declare a copy 8819 // assignment operator, there is no user-declared move constructor, and 8820 // there is no user-declared move assignment operator, a copy assignment 8821 // operator is implicitly declared as defaulted. 8822 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 8823 SetDeclDeleted(CopyAssignment, ClassLoc); 8824 8825 // Note that we have added this copy-assignment operator. 8826 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 8827 8828 if (Scope *S = getScopeForContext(ClassDecl)) 8829 PushOnScopeChains(CopyAssignment, S, false); 8830 ClassDecl->addDecl(CopyAssignment); 8831 8832 return CopyAssignment; 8833} 8834 8835/// Diagnose an implicit copy operation for a class which is odr-used, but 8836/// which is deprecated because the class has a user-declared copy constructor, 8837/// copy assignment operator, or destructor. 8838static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp, 8839 SourceLocation UseLoc) { 8840 assert(CopyOp->isImplicit()); 8841 8842 CXXRecordDecl *RD = CopyOp->getParent(); 8843 CXXMethodDecl *UserDeclaredOperation = 0; 8844 8845 // In Microsoft mode, assignment operations don't affect constructors and 8846 // vice versa. 8847 if (RD->hasUserDeclaredDestructor()) { 8848 UserDeclaredOperation = RD->getDestructor(); 8849 } else if (!isa<CXXConstructorDecl>(CopyOp) && 8850 RD->hasUserDeclaredCopyConstructor() && 8851 !S.getLangOpts().MicrosoftMode) { 8852 // Find any user-declared copy constructor. 8853 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(), 8854 E = RD->ctor_end(); I != E; ++I) { 8855 if (I->isCopyConstructor()) { 8856 UserDeclaredOperation = *I; 8857 break; 8858 } 8859 } 8860 assert(UserDeclaredOperation); 8861 } else if (isa<CXXConstructorDecl>(CopyOp) && 8862 RD->hasUserDeclaredCopyAssignment() && 8863 !S.getLangOpts().MicrosoftMode) { 8864 // Find any user-declared move assignment operator. 8865 for (CXXRecordDecl::method_iterator I = RD->method_begin(), 8866 E = RD->method_end(); I != E; ++I) { 8867 if (I->isCopyAssignmentOperator()) { 8868 UserDeclaredOperation = *I; 8869 break; 8870 } 8871 } 8872 assert(UserDeclaredOperation); 8873 } 8874 8875 if (UserDeclaredOperation) { 8876 S.Diag(UserDeclaredOperation->getLocation(), 8877 diag::warn_deprecated_copy_operation) 8878 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp) 8879 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation); 8880 S.Diag(UseLoc, diag::note_member_synthesized_at) 8881 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor 8882 : Sema::CXXCopyAssignment) 8883 << RD; 8884 } 8885} 8886 8887void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 8888 CXXMethodDecl *CopyAssignOperator) { 8889 assert((CopyAssignOperator->isDefaulted() && 8890 CopyAssignOperator->isOverloadedOperator() && 8891 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 8892 !CopyAssignOperator->doesThisDeclarationHaveABody() && 8893 !CopyAssignOperator->isDeleted()) && 8894 "DefineImplicitCopyAssignment called for wrong function"); 8895 8896 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 8897 8898 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) { 8899 CopyAssignOperator->setInvalidDecl(); 8900 return; 8901 } 8902 8903 // C++11 [class.copy]p18: 8904 // The [definition of an implicitly declared copy assignment operator] is 8905 // deprecated if the class has a user-declared copy constructor or a 8906 // user-declared destructor. 8907 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 8908 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation); 8909 8910 CopyAssignOperator->setUsed(); 8911 8912 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 8913 DiagnosticErrorTrap Trap(Diags); 8914 8915 // C++0x [class.copy]p30: 8916 // The implicitly-defined or explicitly-defaulted copy assignment operator 8917 // for a non-union class X performs memberwise copy assignment of its 8918 // subobjects. The direct base classes of X are assigned first, in the 8919 // order of their declaration in the base-specifier-list, and then the 8920 // immediate non-static data members of X are assigned, in the order in 8921 // which they were declared in the class definition. 8922 8923 // The statements that form the synthesized function body. 8924 SmallVector<Stmt*, 8> Statements; 8925 8926 // The parameter for the "other" object, which we are copying from. 8927 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 8928 Qualifiers OtherQuals = Other->getType().getQualifiers(); 8929 QualType OtherRefType = Other->getType(); 8930 if (const LValueReferenceType *OtherRef 8931 = OtherRefType->getAs<LValueReferenceType>()) { 8932 OtherRefType = OtherRef->getPointeeType(); 8933 OtherQuals = OtherRefType.getQualifiers(); 8934 } 8935 8936 // Our location for everything implicitly-generated. 8937 SourceLocation Loc = CopyAssignOperator->getLocation(); 8938 8939 // Construct a reference to the "other" object. We'll be using this 8940 // throughout the generated ASTs. 8941 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take(); 8942 assert(OtherRef && "Reference to parameter cannot fail!"); 8943 8944 // Construct the "this" pointer. We'll be using this throughout the generated 8945 // ASTs. 8946 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>(); 8947 assert(This && "Reference to this cannot fail!"); 8948 8949 // Assign base classes. 8950 bool Invalid = false; 8951 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 8952 E = ClassDecl->bases_end(); Base != E; ++Base) { 8953 // Form the assignment: 8954 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 8955 QualType BaseType = Base->getType().getUnqualifiedType(); 8956 if (!BaseType->isRecordType()) { 8957 Invalid = true; 8958 continue; 8959 } 8960 8961 CXXCastPath BasePath; 8962 BasePath.push_back(Base); 8963 8964 // Construct the "from" expression, which is an implicit cast to the 8965 // appropriately-qualified base type. 8966 Expr *From = OtherRef; 8967 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals), 8968 CK_UncheckedDerivedToBase, 8969 VK_LValue, &BasePath).take(); 8970 8971 // Dereference "this". 8972 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 8973 8974 // Implicitly cast "this" to the appropriately-qualified base type. 8975 To = ImpCastExprToType(To.take(), 8976 Context.getCVRQualifiedType(BaseType, 8977 CopyAssignOperator->getTypeQualifiers()), 8978 CK_UncheckedDerivedToBase, 8979 VK_LValue, &BasePath); 8980 8981 // Build the copy. 8982 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 8983 To.get(), From, 8984 /*CopyingBaseSubobject=*/true, 8985 /*Copying=*/true); 8986 if (Copy.isInvalid()) { 8987 Diag(CurrentLocation, diag::note_member_synthesized_at) 8988 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 8989 CopyAssignOperator->setInvalidDecl(); 8990 return; 8991 } 8992 8993 // Success! Record the copy. 8994 Statements.push_back(Copy.takeAs<Expr>()); 8995 } 8996 8997 // Assign non-static members. 8998 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8999 FieldEnd = ClassDecl->field_end(); 9000 Field != FieldEnd; ++Field) { 9001 if (Field->isUnnamedBitfield()) 9002 continue; 9003 9004 if (Field->isInvalidDecl()) { 9005 Invalid = true; 9006 continue; 9007 } 9008 9009 // Check for members of reference type; we can't copy those. 9010 if (Field->getType()->isReferenceType()) { 9011 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9012 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 9013 Diag(Field->getLocation(), diag::note_declared_at); 9014 Diag(CurrentLocation, diag::note_member_synthesized_at) 9015 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9016 Invalid = true; 9017 continue; 9018 } 9019 9020 // Check for members of const-qualified, non-class type. 9021 QualType BaseType = Context.getBaseElementType(Field->getType()); 9022 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 9023 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9024 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 9025 Diag(Field->getLocation(), diag::note_declared_at); 9026 Diag(CurrentLocation, diag::note_member_synthesized_at) 9027 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9028 Invalid = true; 9029 continue; 9030 } 9031 9032 // Suppress assigning zero-width bitfields. 9033 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 9034 continue; 9035 9036 QualType FieldType = Field->getType().getNonReferenceType(); 9037 if (FieldType->isIncompleteArrayType()) { 9038 assert(ClassDecl->hasFlexibleArrayMember() && 9039 "Incomplete array type is not valid"); 9040 continue; 9041 } 9042 9043 // Build references to the field in the object we're copying from and to. 9044 CXXScopeSpec SS; // Intentionally empty 9045 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 9046 LookupMemberName); 9047 MemberLookup.addDecl(*Field); 9048 MemberLookup.resolveKind(); 9049 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType, 9050 Loc, /*IsArrow=*/false, 9051 SS, SourceLocation(), 0, 9052 MemberLookup, 0); 9053 ExprResult To = BuildMemberReferenceExpr(This, This->getType(), 9054 Loc, /*IsArrow=*/true, 9055 SS, SourceLocation(), 0, 9056 MemberLookup, 0); 9057 assert(!From.isInvalid() && "Implicit field reference cannot fail"); 9058 assert(!To.isInvalid() && "Implicit field reference cannot fail"); 9059 9060 // Build the copy of this field. 9061 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 9062 To.get(), From.get(), 9063 /*CopyingBaseSubobject=*/false, 9064 /*Copying=*/true); 9065 if (Copy.isInvalid()) { 9066 Diag(CurrentLocation, diag::note_member_synthesized_at) 9067 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9068 CopyAssignOperator->setInvalidDecl(); 9069 return; 9070 } 9071 9072 // Success! Record the copy. 9073 Statements.push_back(Copy.takeAs<Stmt>()); 9074 } 9075 9076 if (!Invalid) { 9077 // Add a "return *this;" 9078 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 9079 9080 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get()); 9081 if (Return.isInvalid()) 9082 Invalid = true; 9083 else { 9084 Statements.push_back(Return.takeAs<Stmt>()); 9085 9086 if (Trap.hasErrorOccurred()) { 9087 Diag(CurrentLocation, diag::note_member_synthesized_at) 9088 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9089 Invalid = true; 9090 } 9091 } 9092 } 9093 9094 if (Invalid) { 9095 CopyAssignOperator->setInvalidDecl(); 9096 return; 9097 } 9098 9099 StmtResult Body; 9100 { 9101 CompoundScopeRAII CompoundScope(*this); 9102 Body = ActOnCompoundStmt(Loc, Loc, Statements, 9103 /*isStmtExpr=*/false); 9104 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 9105 } 9106 CopyAssignOperator->setBody(Body.takeAs<Stmt>()); 9107 9108 if (ASTMutationListener *L = getASTMutationListener()) { 9109 L->CompletedImplicitDefinition(CopyAssignOperator); 9110 } 9111} 9112 9113Sema::ImplicitExceptionSpecification 9114Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) { 9115 CXXRecordDecl *ClassDecl = MD->getParent(); 9116 9117 ImplicitExceptionSpecification ExceptSpec(*this); 9118 if (ClassDecl->isInvalidDecl()) 9119 return ExceptSpec; 9120 9121 // C++0x [except.spec]p14: 9122 // An implicitly declared special member function (Clause 12) shall have an 9123 // exception-specification. [...] 9124 9125 // It is unspecified whether or not an implicit move assignment operator 9126 // attempts to deduplicate calls to assignment operators of virtual bases are 9127 // made. As such, this exception specification is effectively unspecified. 9128 // Based on a similar decision made for constness in C++0x, we're erring on 9129 // the side of assuming such calls to be made regardless of whether they 9130 // actually happen. 9131 // Note that a move constructor is not implicitly declared when there are 9132 // virtual bases, but it can still be user-declared and explicitly defaulted. 9133 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 9134 BaseEnd = ClassDecl->bases_end(); 9135 Base != BaseEnd; ++Base) { 9136 if (Base->isVirtual()) 9137 continue; 9138 9139 CXXRecordDecl *BaseClassDecl 9140 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9141 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 9142 0, false, 0)) 9143 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign); 9144 } 9145 9146 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 9147 BaseEnd = ClassDecl->vbases_end(); 9148 Base != BaseEnd; ++Base) { 9149 CXXRecordDecl *BaseClassDecl 9150 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9151 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 9152 0, false, 0)) 9153 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign); 9154 } 9155 9156 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 9157 FieldEnd = ClassDecl->field_end(); 9158 Field != FieldEnd; 9159 ++Field) { 9160 QualType FieldType = Context.getBaseElementType(Field->getType()); 9161 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 9162 if (CXXMethodDecl *MoveAssign = 9163 LookupMovingAssignment(FieldClassDecl, 9164 FieldType.getCVRQualifiers(), 9165 false, 0)) 9166 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign); 9167 } 9168 } 9169 9170 return ExceptSpec; 9171} 9172 9173/// Determine whether the class type has any direct or indirect virtual base 9174/// classes which have a non-trivial move assignment operator. 9175static bool 9176hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) { 9177 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 9178 BaseEnd = ClassDecl->vbases_end(); 9179 Base != BaseEnd; ++Base) { 9180 CXXRecordDecl *BaseClass = 9181 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9182 9183 // Try to declare the move assignment. If it would be deleted, then the 9184 // class does not have a non-trivial move assignment. 9185 if (BaseClass->needsImplicitMoveAssignment()) 9186 S.DeclareImplicitMoveAssignment(BaseClass); 9187 9188 if (BaseClass->hasNonTrivialMoveAssignment()) 9189 return true; 9190 } 9191 9192 return false; 9193} 9194 9195/// Determine whether the given type either has a move constructor or is 9196/// trivially copyable. 9197static bool 9198hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) { 9199 Type = S.Context.getBaseElementType(Type); 9200 9201 // FIXME: Technically, non-trivially-copyable non-class types, such as 9202 // reference types, are supposed to return false here, but that appears 9203 // to be a standard defect. 9204 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl(); 9205 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl()) 9206 return true; 9207 9208 if (Type.isTriviallyCopyableType(S.Context)) 9209 return true; 9210 9211 if (IsConstructor) { 9212 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to 9213 // give the right answer. 9214 if (ClassDecl->needsImplicitMoveConstructor()) 9215 S.DeclareImplicitMoveConstructor(ClassDecl); 9216 return ClassDecl->hasMoveConstructor(); 9217 } 9218 9219 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to 9220 // give the right answer. 9221 if (ClassDecl->needsImplicitMoveAssignment()) 9222 S.DeclareImplicitMoveAssignment(ClassDecl); 9223 return ClassDecl->hasMoveAssignment(); 9224} 9225 9226/// Determine whether all non-static data members and direct or virtual bases 9227/// of class \p ClassDecl have either a move operation, or are trivially 9228/// copyable. 9229static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl, 9230 bool IsConstructor) { 9231 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 9232 BaseEnd = ClassDecl->bases_end(); 9233 Base != BaseEnd; ++Base) { 9234 if (Base->isVirtual()) 9235 continue; 9236 9237 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor)) 9238 return false; 9239 } 9240 9241 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 9242 BaseEnd = ClassDecl->vbases_end(); 9243 Base != BaseEnd; ++Base) { 9244 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor)) 9245 return false; 9246 } 9247 9248 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 9249 FieldEnd = ClassDecl->field_end(); 9250 Field != FieldEnd; ++Field) { 9251 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor)) 9252 return false; 9253 } 9254 9255 return true; 9256} 9257 9258CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 9259 // C++11 [class.copy]p20: 9260 // If the definition of a class X does not explicitly declare a move 9261 // assignment operator, one will be implicitly declared as defaulted 9262 // if and only if: 9263 // 9264 // - [first 4 bullets] 9265 assert(ClassDecl->needsImplicitMoveAssignment()); 9266 9267 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 9268 if (DSM.isAlreadyBeingDeclared()) 9269 return 0; 9270 9271 // [Checked after we build the declaration] 9272 // - the move assignment operator would not be implicitly defined as 9273 // deleted, 9274 9275 // [DR1402]: 9276 // - X has no direct or indirect virtual base class with a non-trivial 9277 // move assignment operator, and 9278 // - each of X's non-static data members and direct or virtual base classes 9279 // has a type that either has a move assignment operator or is trivially 9280 // copyable. 9281 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) || 9282 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) { 9283 ClassDecl->setFailedImplicitMoveAssignment(); 9284 return 0; 9285 } 9286 9287 // Note: The following rules are largely analoguous to the move 9288 // constructor rules. 9289 9290 QualType ArgType = Context.getTypeDeclType(ClassDecl); 9291 QualType RetType = Context.getLValueReferenceType(ArgType); 9292 ArgType = Context.getRValueReferenceType(ArgType); 9293 9294 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9295 CXXMoveAssignment, 9296 false); 9297 9298 // An implicitly-declared move assignment operator is an inline public 9299 // member of its class. 9300 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9301 SourceLocation ClassLoc = ClassDecl->getLocation(); 9302 DeclarationNameInfo NameInfo(Name, ClassLoc); 9303 CXXMethodDecl *MoveAssignment = 9304 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 9305 /*TInfo=*/0, /*StorageClass=*/SC_None, 9306 /*isInline=*/true, Constexpr, SourceLocation()); 9307 MoveAssignment->setAccess(AS_public); 9308 MoveAssignment->setDefaulted(); 9309 MoveAssignment->setImplicit(); 9310 9311 // Build an exception specification pointing back at this member. 9312 FunctionProtoType::ExtProtoInfo EPI; 9313 EPI.ExceptionSpecType = EST_Unevaluated; 9314 EPI.ExceptionSpecDecl = MoveAssignment; 9315 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 9316 9317 // Add the parameter to the operator. 9318 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 9319 ClassLoc, ClassLoc, /*Id=*/0, 9320 ArgType, /*TInfo=*/0, 9321 SC_None, 0); 9322 MoveAssignment->setParams(FromParam); 9323 9324 AddOverriddenMethods(ClassDecl, MoveAssignment); 9325 9326 MoveAssignment->setTrivial( 9327 ClassDecl->needsOverloadResolutionForMoveAssignment() 9328 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 9329 : ClassDecl->hasTrivialMoveAssignment()); 9330 9331 // C++0x [class.copy]p9: 9332 // If the definition of a class X does not explicitly declare a move 9333 // assignment operator, one will be implicitly declared as defaulted if and 9334 // only if: 9335 // [...] 9336 // - the move assignment operator would not be implicitly defined as 9337 // deleted. 9338 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 9339 // Cache this result so that we don't try to generate this over and over 9340 // on every lookup, leaking memory and wasting time. 9341 ClassDecl->setFailedImplicitMoveAssignment(); 9342 return 0; 9343 } 9344 9345 // Note that we have added this copy-assignment operator. 9346 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 9347 9348 if (Scope *S = getScopeForContext(ClassDecl)) 9349 PushOnScopeChains(MoveAssignment, S, false); 9350 ClassDecl->addDecl(MoveAssignment); 9351 9352 return MoveAssignment; 9353} 9354 9355void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 9356 CXXMethodDecl *MoveAssignOperator) { 9357 assert((MoveAssignOperator->isDefaulted() && 9358 MoveAssignOperator->isOverloadedOperator() && 9359 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 9360 !MoveAssignOperator->doesThisDeclarationHaveABody() && 9361 !MoveAssignOperator->isDeleted()) && 9362 "DefineImplicitMoveAssignment called for wrong function"); 9363 9364 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 9365 9366 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) { 9367 MoveAssignOperator->setInvalidDecl(); 9368 return; 9369 } 9370 9371 MoveAssignOperator->setUsed(); 9372 9373 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 9374 DiagnosticErrorTrap Trap(Diags); 9375 9376 // C++0x [class.copy]p28: 9377 // The implicitly-defined or move assignment operator for a non-union class 9378 // X performs memberwise move assignment of its subobjects. The direct base 9379 // classes of X are assigned first, in the order of their declaration in the 9380 // base-specifier-list, and then the immediate non-static data members of X 9381 // are assigned, in the order in which they were declared in the class 9382 // definition. 9383 9384 // The statements that form the synthesized function body. 9385 SmallVector<Stmt*, 8> Statements; 9386 9387 // The parameter for the "other" object, which we are move from. 9388 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 9389 QualType OtherRefType = Other->getType()-> 9390 getAs<RValueReferenceType>()->getPointeeType(); 9391 assert(!OtherRefType.getQualifiers() && 9392 "Bad argument type of defaulted move assignment"); 9393 9394 // Our location for everything implicitly-generated. 9395 SourceLocation Loc = MoveAssignOperator->getLocation(); 9396 9397 // Construct a reference to the "other" object. We'll be using this 9398 // throughout the generated ASTs. 9399 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take(); 9400 assert(OtherRef && "Reference to parameter cannot fail!"); 9401 // Cast to rvalue. 9402 OtherRef = CastForMoving(*this, OtherRef); 9403 9404 // Construct the "this" pointer. We'll be using this throughout the generated 9405 // ASTs. 9406 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>(); 9407 assert(This && "Reference to this cannot fail!"); 9408 9409 // Assign base classes. 9410 bool Invalid = false; 9411 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 9412 E = ClassDecl->bases_end(); Base != E; ++Base) { 9413 // Form the assignment: 9414 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 9415 QualType BaseType = Base->getType().getUnqualifiedType(); 9416 if (!BaseType->isRecordType()) { 9417 Invalid = true; 9418 continue; 9419 } 9420 9421 CXXCastPath BasePath; 9422 BasePath.push_back(Base); 9423 9424 // Construct the "from" expression, which is an implicit cast to the 9425 // appropriately-qualified base type. 9426 Expr *From = OtherRef; 9427 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase, 9428 VK_XValue, &BasePath).take(); 9429 9430 // Dereference "this". 9431 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 9432 9433 // Implicitly cast "this" to the appropriately-qualified base type. 9434 To = ImpCastExprToType(To.take(), 9435 Context.getCVRQualifiedType(BaseType, 9436 MoveAssignOperator->getTypeQualifiers()), 9437 CK_UncheckedDerivedToBase, 9438 VK_LValue, &BasePath); 9439 9440 // Build the move. 9441 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 9442 To.get(), From, 9443 /*CopyingBaseSubobject=*/true, 9444 /*Copying=*/false); 9445 if (Move.isInvalid()) { 9446 Diag(CurrentLocation, diag::note_member_synthesized_at) 9447 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9448 MoveAssignOperator->setInvalidDecl(); 9449 return; 9450 } 9451 9452 // Success! Record the move. 9453 Statements.push_back(Move.takeAs<Expr>()); 9454 } 9455 9456 // Assign non-static members. 9457 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 9458 FieldEnd = ClassDecl->field_end(); 9459 Field != FieldEnd; ++Field) { 9460 if (Field->isUnnamedBitfield()) 9461 continue; 9462 9463 if (Field->isInvalidDecl()) { 9464 Invalid = true; 9465 continue; 9466 } 9467 9468 // Check for members of reference type; we can't move those. 9469 if (Field->getType()->isReferenceType()) { 9470 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9471 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 9472 Diag(Field->getLocation(), diag::note_declared_at); 9473 Diag(CurrentLocation, diag::note_member_synthesized_at) 9474 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9475 Invalid = true; 9476 continue; 9477 } 9478 9479 // Check for members of const-qualified, non-class type. 9480 QualType BaseType = Context.getBaseElementType(Field->getType()); 9481 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 9482 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9483 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 9484 Diag(Field->getLocation(), diag::note_declared_at); 9485 Diag(CurrentLocation, diag::note_member_synthesized_at) 9486 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9487 Invalid = true; 9488 continue; 9489 } 9490 9491 // Suppress assigning zero-width bitfields. 9492 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 9493 continue; 9494 9495 QualType FieldType = Field->getType().getNonReferenceType(); 9496 if (FieldType->isIncompleteArrayType()) { 9497 assert(ClassDecl->hasFlexibleArrayMember() && 9498 "Incomplete array type is not valid"); 9499 continue; 9500 } 9501 9502 // Build references to the field in the object we're copying from and to. 9503 CXXScopeSpec SS; // Intentionally empty 9504 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 9505 LookupMemberName); 9506 MemberLookup.addDecl(*Field); 9507 MemberLookup.resolveKind(); 9508 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType, 9509 Loc, /*IsArrow=*/false, 9510 SS, SourceLocation(), 0, 9511 MemberLookup, 0); 9512 ExprResult To = BuildMemberReferenceExpr(This, This->getType(), 9513 Loc, /*IsArrow=*/true, 9514 SS, SourceLocation(), 0, 9515 MemberLookup, 0); 9516 assert(!From.isInvalid() && "Implicit field reference cannot fail"); 9517 assert(!To.isInvalid() && "Implicit field reference cannot fail"); 9518 9519 assert(!From.get()->isLValue() && // could be xvalue or prvalue 9520 "Member reference with rvalue base must be rvalue except for reference " 9521 "members, which aren't allowed for move assignment."); 9522 9523 // Build the move of this field. 9524 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 9525 To.get(), From.get(), 9526 /*CopyingBaseSubobject=*/false, 9527 /*Copying=*/false); 9528 if (Move.isInvalid()) { 9529 Diag(CurrentLocation, diag::note_member_synthesized_at) 9530 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9531 MoveAssignOperator->setInvalidDecl(); 9532 return; 9533 } 9534 9535 // Success! Record the copy. 9536 Statements.push_back(Move.takeAs<Stmt>()); 9537 } 9538 9539 if (!Invalid) { 9540 // Add a "return *this;" 9541 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 9542 9543 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get()); 9544 if (Return.isInvalid()) 9545 Invalid = true; 9546 else { 9547 Statements.push_back(Return.takeAs<Stmt>()); 9548 9549 if (Trap.hasErrorOccurred()) { 9550 Diag(CurrentLocation, diag::note_member_synthesized_at) 9551 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9552 Invalid = true; 9553 } 9554 } 9555 } 9556 9557 if (Invalid) { 9558 MoveAssignOperator->setInvalidDecl(); 9559 return; 9560 } 9561 9562 StmtResult Body; 9563 { 9564 CompoundScopeRAII CompoundScope(*this); 9565 Body = ActOnCompoundStmt(Loc, Loc, Statements, 9566 /*isStmtExpr=*/false); 9567 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 9568 } 9569 MoveAssignOperator->setBody(Body.takeAs<Stmt>()); 9570 9571 if (ASTMutationListener *L = getASTMutationListener()) { 9572 L->CompletedImplicitDefinition(MoveAssignOperator); 9573 } 9574} 9575 9576Sema::ImplicitExceptionSpecification 9577Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) { 9578 CXXRecordDecl *ClassDecl = MD->getParent(); 9579 9580 ImplicitExceptionSpecification ExceptSpec(*this); 9581 if (ClassDecl->isInvalidDecl()) 9582 return ExceptSpec; 9583 9584 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 9585 assert(T->getNumArgs() >= 1 && "not a copy ctor"); 9586 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers(); 9587 9588 // C++ [except.spec]p14: 9589 // An implicitly declared special member function (Clause 12) shall have an 9590 // exception-specification. [...] 9591 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 9592 BaseEnd = ClassDecl->bases_end(); 9593 Base != BaseEnd; 9594 ++Base) { 9595 // Virtual bases are handled below. 9596 if (Base->isVirtual()) 9597 continue; 9598 9599 CXXRecordDecl *BaseClassDecl 9600 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9601 if (CXXConstructorDecl *CopyConstructor = 9602 LookupCopyingConstructor(BaseClassDecl, Quals)) 9603 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor); 9604 } 9605 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 9606 BaseEnd = ClassDecl->vbases_end(); 9607 Base != BaseEnd; 9608 ++Base) { 9609 CXXRecordDecl *BaseClassDecl 9610 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9611 if (CXXConstructorDecl *CopyConstructor = 9612 LookupCopyingConstructor(BaseClassDecl, Quals)) 9613 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor); 9614 } 9615 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 9616 FieldEnd = ClassDecl->field_end(); 9617 Field != FieldEnd; 9618 ++Field) { 9619 QualType FieldType = Context.getBaseElementType(Field->getType()); 9620 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 9621 if (CXXConstructorDecl *CopyConstructor = 9622 LookupCopyingConstructor(FieldClassDecl, 9623 Quals | FieldType.getCVRQualifiers())) 9624 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor); 9625 } 9626 } 9627 9628 return ExceptSpec; 9629} 9630 9631CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 9632 CXXRecordDecl *ClassDecl) { 9633 // C++ [class.copy]p4: 9634 // If the class definition does not explicitly declare a copy 9635 // constructor, one is declared implicitly. 9636 assert(ClassDecl->needsImplicitCopyConstructor()); 9637 9638 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 9639 if (DSM.isAlreadyBeingDeclared()) 9640 return 0; 9641 9642 QualType ClassType = Context.getTypeDeclType(ClassDecl); 9643 QualType ArgType = ClassType; 9644 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 9645 if (Const) 9646 ArgType = ArgType.withConst(); 9647 ArgType = Context.getLValueReferenceType(ArgType); 9648 9649 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9650 CXXCopyConstructor, 9651 Const); 9652 9653 DeclarationName Name 9654 = Context.DeclarationNames.getCXXConstructorName( 9655 Context.getCanonicalType(ClassType)); 9656 SourceLocation ClassLoc = ClassDecl->getLocation(); 9657 DeclarationNameInfo NameInfo(Name, ClassLoc); 9658 9659 // An implicitly-declared copy constructor is an inline public 9660 // member of its class. 9661 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 9662 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0, 9663 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 9664 Constexpr); 9665 CopyConstructor->setAccess(AS_public); 9666 CopyConstructor->setDefaulted(); 9667 9668 // Build an exception specification pointing back at this member. 9669 FunctionProtoType::ExtProtoInfo EPI; 9670 EPI.ExceptionSpecType = EST_Unevaluated; 9671 EPI.ExceptionSpecDecl = CopyConstructor; 9672 CopyConstructor->setType( 9673 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 9674 9675 // Add the parameter to the constructor. 9676 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 9677 ClassLoc, ClassLoc, 9678 /*IdentifierInfo=*/0, 9679 ArgType, /*TInfo=*/0, 9680 SC_None, 0); 9681 CopyConstructor->setParams(FromParam); 9682 9683 CopyConstructor->setTrivial( 9684 ClassDecl->needsOverloadResolutionForCopyConstructor() 9685 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 9686 : ClassDecl->hasTrivialCopyConstructor()); 9687 9688 // C++11 [class.copy]p8: 9689 // ... If the class definition does not explicitly declare a copy 9690 // constructor, there is no user-declared move constructor, and there is no 9691 // user-declared move assignment operator, a copy constructor is implicitly 9692 // declared as defaulted. 9693 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) 9694 SetDeclDeleted(CopyConstructor, ClassLoc); 9695 9696 // Note that we have declared this constructor. 9697 ++ASTContext::NumImplicitCopyConstructorsDeclared; 9698 9699 if (Scope *S = getScopeForContext(ClassDecl)) 9700 PushOnScopeChains(CopyConstructor, S, false); 9701 ClassDecl->addDecl(CopyConstructor); 9702 9703 return CopyConstructor; 9704} 9705 9706void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 9707 CXXConstructorDecl *CopyConstructor) { 9708 assert((CopyConstructor->isDefaulted() && 9709 CopyConstructor->isCopyConstructor() && 9710 !CopyConstructor->doesThisDeclarationHaveABody() && 9711 !CopyConstructor->isDeleted()) && 9712 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 9713 9714 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 9715 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 9716 9717 // C++11 [class.copy]p7: 9718 // The [definition of an implicitly declared copy constructro] is 9719 // deprecated if the class has a user-declared copy assignment operator 9720 // or a user-declared destructor. 9721 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 9722 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation); 9723 9724 SynthesizedFunctionScope Scope(*this, CopyConstructor); 9725 DiagnosticErrorTrap Trap(Diags); 9726 9727 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) || 9728 Trap.hasErrorOccurred()) { 9729 Diag(CurrentLocation, diag::note_member_synthesized_at) 9730 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl); 9731 CopyConstructor->setInvalidDecl(); 9732 } else { 9733 Sema::CompoundScopeRAII CompoundScope(*this); 9734 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(), 9735 CopyConstructor->getLocation(), 9736 MultiStmtArg(), 9737 /*isStmtExpr=*/false) 9738 .takeAs<Stmt>()); 9739 CopyConstructor->setImplicitlyDefined(true); 9740 } 9741 9742 CopyConstructor->setUsed(); 9743 if (ASTMutationListener *L = getASTMutationListener()) { 9744 L->CompletedImplicitDefinition(CopyConstructor); 9745 } 9746} 9747 9748Sema::ImplicitExceptionSpecification 9749Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) { 9750 CXXRecordDecl *ClassDecl = MD->getParent(); 9751 9752 // C++ [except.spec]p14: 9753 // An implicitly declared special member function (Clause 12) shall have an 9754 // exception-specification. [...] 9755 ImplicitExceptionSpecification ExceptSpec(*this); 9756 if (ClassDecl->isInvalidDecl()) 9757 return ExceptSpec; 9758 9759 // Direct base-class constructors. 9760 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 9761 BEnd = ClassDecl->bases_end(); 9762 B != BEnd; ++B) { 9763 if (B->isVirtual()) // Handled below. 9764 continue; 9765 9766 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 9767 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 9768 CXXConstructorDecl *Constructor = 9769 LookupMovingConstructor(BaseClassDecl, 0); 9770 // If this is a deleted function, add it anyway. This might be conformant 9771 // with the standard. This might not. I'm not sure. It might not matter. 9772 if (Constructor) 9773 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 9774 } 9775 } 9776 9777 // Virtual base-class constructors. 9778 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 9779 BEnd = ClassDecl->vbases_end(); 9780 B != BEnd; ++B) { 9781 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 9782 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 9783 CXXConstructorDecl *Constructor = 9784 LookupMovingConstructor(BaseClassDecl, 0); 9785 // If this is a deleted function, add it anyway. This might be conformant 9786 // with the standard. This might not. I'm not sure. It might not matter. 9787 if (Constructor) 9788 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 9789 } 9790 } 9791 9792 // Field constructors. 9793 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 9794 FEnd = ClassDecl->field_end(); 9795 F != FEnd; ++F) { 9796 QualType FieldType = Context.getBaseElementType(F->getType()); 9797 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) { 9798 CXXConstructorDecl *Constructor = 9799 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers()); 9800 // If this is a deleted function, add it anyway. This might be conformant 9801 // with the standard. This might not. I'm not sure. It might not matter. 9802 // In particular, the problem is that this function never gets called. It 9803 // might just be ill-formed because this function attempts to refer to 9804 // a deleted function here. 9805 if (Constructor) 9806 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 9807 } 9808 } 9809 9810 return ExceptSpec; 9811} 9812 9813CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 9814 CXXRecordDecl *ClassDecl) { 9815 // C++11 [class.copy]p9: 9816 // If the definition of a class X does not explicitly declare a move 9817 // constructor, one will be implicitly declared as defaulted if and only if: 9818 // 9819 // - [first 4 bullets] 9820 assert(ClassDecl->needsImplicitMoveConstructor()); 9821 9822 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 9823 if (DSM.isAlreadyBeingDeclared()) 9824 return 0; 9825 9826 // [Checked after we build the declaration] 9827 // - the move assignment operator would not be implicitly defined as 9828 // deleted, 9829 9830 // [DR1402]: 9831 // - each of X's non-static data members and direct or virtual base classes 9832 // has a type that either has a move constructor or is trivially copyable. 9833 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) { 9834 ClassDecl->setFailedImplicitMoveConstructor(); 9835 return 0; 9836 } 9837 9838 QualType ClassType = Context.getTypeDeclType(ClassDecl); 9839 QualType ArgType = Context.getRValueReferenceType(ClassType); 9840 9841 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9842 CXXMoveConstructor, 9843 false); 9844 9845 DeclarationName Name 9846 = Context.DeclarationNames.getCXXConstructorName( 9847 Context.getCanonicalType(ClassType)); 9848 SourceLocation ClassLoc = ClassDecl->getLocation(); 9849 DeclarationNameInfo NameInfo(Name, ClassLoc); 9850 9851 // C++11 [class.copy]p11: 9852 // An implicitly-declared copy/move constructor is an inline public 9853 // member of its class. 9854 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 9855 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0, 9856 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 9857 Constexpr); 9858 MoveConstructor->setAccess(AS_public); 9859 MoveConstructor->setDefaulted(); 9860 9861 // Build an exception specification pointing back at this member. 9862 FunctionProtoType::ExtProtoInfo EPI; 9863 EPI.ExceptionSpecType = EST_Unevaluated; 9864 EPI.ExceptionSpecDecl = MoveConstructor; 9865 MoveConstructor->setType( 9866 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 9867 9868 // Add the parameter to the constructor. 9869 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 9870 ClassLoc, ClassLoc, 9871 /*IdentifierInfo=*/0, 9872 ArgType, /*TInfo=*/0, 9873 SC_None, 0); 9874 MoveConstructor->setParams(FromParam); 9875 9876 MoveConstructor->setTrivial( 9877 ClassDecl->needsOverloadResolutionForMoveConstructor() 9878 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 9879 : ClassDecl->hasTrivialMoveConstructor()); 9880 9881 // C++0x [class.copy]p9: 9882 // If the definition of a class X does not explicitly declare a move 9883 // constructor, one will be implicitly declared as defaulted if and only if: 9884 // [...] 9885 // - the move constructor would not be implicitly defined as deleted. 9886 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 9887 // Cache this result so that we don't try to generate this over and over 9888 // on every lookup, leaking memory and wasting time. 9889 ClassDecl->setFailedImplicitMoveConstructor(); 9890 return 0; 9891 } 9892 9893 // Note that we have declared this constructor. 9894 ++ASTContext::NumImplicitMoveConstructorsDeclared; 9895 9896 if (Scope *S = getScopeForContext(ClassDecl)) 9897 PushOnScopeChains(MoveConstructor, S, false); 9898 ClassDecl->addDecl(MoveConstructor); 9899 9900 return MoveConstructor; 9901} 9902 9903void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 9904 CXXConstructorDecl *MoveConstructor) { 9905 assert((MoveConstructor->isDefaulted() && 9906 MoveConstructor->isMoveConstructor() && 9907 !MoveConstructor->doesThisDeclarationHaveABody() && 9908 !MoveConstructor->isDeleted()) && 9909 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 9910 9911 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 9912 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 9913 9914 SynthesizedFunctionScope Scope(*this, MoveConstructor); 9915 DiagnosticErrorTrap Trap(Diags); 9916 9917 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) || 9918 Trap.hasErrorOccurred()) { 9919 Diag(CurrentLocation, diag::note_member_synthesized_at) 9920 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl); 9921 MoveConstructor->setInvalidDecl(); 9922 } else { 9923 Sema::CompoundScopeRAII CompoundScope(*this); 9924 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(), 9925 MoveConstructor->getLocation(), 9926 MultiStmtArg(), 9927 /*isStmtExpr=*/false) 9928 .takeAs<Stmt>()); 9929 MoveConstructor->setImplicitlyDefined(true); 9930 } 9931 9932 MoveConstructor->setUsed(); 9933 9934 if (ASTMutationListener *L = getASTMutationListener()) { 9935 L->CompletedImplicitDefinition(MoveConstructor); 9936 } 9937} 9938 9939bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 9940 return FD->isDeleted() && 9941 (FD->isDefaulted() || FD->isImplicit()) && 9942 isa<CXXMethodDecl>(FD); 9943} 9944 9945/// \brief Mark the call operator of the given lambda closure type as "used". 9946static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) { 9947 CXXMethodDecl *CallOperator 9948 = cast<CXXMethodDecl>( 9949 Lambda->lookup( 9950 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front()); 9951 CallOperator->setReferenced(); 9952 CallOperator->setUsed(); 9953} 9954 9955void Sema::DefineImplicitLambdaToFunctionPointerConversion( 9956 SourceLocation CurrentLocation, 9957 CXXConversionDecl *Conv) 9958{ 9959 CXXRecordDecl *Lambda = Conv->getParent(); 9960 9961 // Make sure that the lambda call operator is marked used. 9962 markLambdaCallOperatorUsed(*this, Lambda); 9963 9964 Conv->setUsed(); 9965 9966 SynthesizedFunctionScope Scope(*this, Conv); 9967 DiagnosticErrorTrap Trap(Diags); 9968 9969 // Return the address of the __invoke function. 9970 DeclarationName InvokeName = &Context.Idents.get("__invoke"); 9971 CXXMethodDecl *Invoke 9972 = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front()); 9973 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(), 9974 VK_LValue, Conv->getLocation()).take(); 9975 assert(FunctionRef && "Can't refer to __invoke function?"); 9976 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take(); 9977 Conv->setBody(new (Context) CompoundStmt(Context, Return, 9978 Conv->getLocation(), 9979 Conv->getLocation())); 9980 9981 // Fill in the __invoke function with a dummy implementation. IR generation 9982 // will fill in the actual details. 9983 Invoke->setUsed(); 9984 Invoke->setReferenced(); 9985 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation())); 9986 9987 if (ASTMutationListener *L = getASTMutationListener()) { 9988 L->CompletedImplicitDefinition(Conv); 9989 L->CompletedImplicitDefinition(Invoke); 9990 } 9991} 9992 9993void Sema::DefineImplicitLambdaToBlockPointerConversion( 9994 SourceLocation CurrentLocation, 9995 CXXConversionDecl *Conv) 9996{ 9997 Conv->setUsed(); 9998 9999 SynthesizedFunctionScope Scope(*this, Conv); 10000 DiagnosticErrorTrap Trap(Diags); 10001 10002 // Copy-initialize the lambda object as needed to capture it. 10003 Expr *This = ActOnCXXThis(CurrentLocation).take(); 10004 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take(); 10005 10006 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 10007 Conv->getLocation(), 10008 Conv, DerefThis); 10009 10010 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 10011 // behavior. Note that only the general conversion function does this 10012 // (since it's unusable otherwise); in the case where we inline the 10013 // block literal, it has block literal lifetime semantics. 10014 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 10015 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 10016 CK_CopyAndAutoreleaseBlockObject, 10017 BuildBlock.get(), 0, VK_RValue); 10018 10019 if (BuildBlock.isInvalid()) { 10020 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 10021 Conv->setInvalidDecl(); 10022 return; 10023 } 10024 10025 // Create the return statement that returns the block from the conversion 10026 // function. 10027 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get()); 10028 if (Return.isInvalid()) { 10029 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 10030 Conv->setInvalidDecl(); 10031 return; 10032 } 10033 10034 // Set the body of the conversion function. 10035 Stmt *ReturnS = Return.take(); 10036 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS, 10037 Conv->getLocation(), 10038 Conv->getLocation())); 10039 10040 // We're done; notify the mutation listener, if any. 10041 if (ASTMutationListener *L = getASTMutationListener()) { 10042 L->CompletedImplicitDefinition(Conv); 10043 } 10044} 10045 10046/// \brief Determine whether the given list arguments contains exactly one 10047/// "real" (non-default) argument. 10048static bool hasOneRealArgument(MultiExprArg Args) { 10049 switch (Args.size()) { 10050 case 0: 10051 return false; 10052 10053 default: 10054 if (!Args[1]->isDefaultArgument()) 10055 return false; 10056 10057 // fall through 10058 case 1: 10059 return !Args[0]->isDefaultArgument(); 10060 } 10061 10062 return false; 10063} 10064 10065ExprResult 10066Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 10067 CXXConstructorDecl *Constructor, 10068 MultiExprArg ExprArgs, 10069 bool HadMultipleCandidates, 10070 bool IsListInitialization, 10071 bool RequiresZeroInit, 10072 unsigned ConstructKind, 10073 SourceRange ParenRange) { 10074 bool Elidable = false; 10075 10076 // C++0x [class.copy]p34: 10077 // When certain criteria are met, an implementation is allowed to 10078 // omit the copy/move construction of a class object, even if the 10079 // copy/move constructor and/or destructor for the object have 10080 // side effects. [...] 10081 // - when a temporary class object that has not been bound to a 10082 // reference (12.2) would be copied/moved to a class object 10083 // with the same cv-unqualified type, the copy/move operation 10084 // can be omitted by constructing the temporary object 10085 // directly into the target of the omitted copy/move 10086 if (ConstructKind == CXXConstructExpr::CK_Complete && 10087 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 10088 Expr *SubExpr = ExprArgs[0]; 10089 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent()); 10090 } 10091 10092 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 10093 Elidable, ExprArgs, HadMultipleCandidates, 10094 IsListInitialization, RequiresZeroInit, 10095 ConstructKind, ParenRange); 10096} 10097 10098/// BuildCXXConstructExpr - Creates a complete call to a constructor, 10099/// including handling of its default argument expressions. 10100ExprResult 10101Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 10102 CXXConstructorDecl *Constructor, bool Elidable, 10103 MultiExprArg ExprArgs, 10104 bool HadMultipleCandidates, 10105 bool IsListInitialization, 10106 bool RequiresZeroInit, 10107 unsigned ConstructKind, 10108 SourceRange ParenRange) { 10109 MarkFunctionReferenced(ConstructLoc, Constructor); 10110 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc, 10111 Constructor, Elidable, ExprArgs, 10112 HadMultipleCandidates, 10113 IsListInitialization, RequiresZeroInit, 10114 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 10115 ParenRange)); 10116} 10117 10118void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 10119 if (VD->isInvalidDecl()) return; 10120 10121 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 10122 if (ClassDecl->isInvalidDecl()) return; 10123 if (ClassDecl->hasIrrelevantDestructor()) return; 10124 if (ClassDecl->isDependentContext()) return; 10125 10126 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 10127 MarkFunctionReferenced(VD->getLocation(), Destructor); 10128 CheckDestructorAccess(VD->getLocation(), Destructor, 10129 PDiag(diag::err_access_dtor_var) 10130 << VD->getDeclName() 10131 << VD->getType()); 10132 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 10133 10134 if (!VD->hasGlobalStorage()) return; 10135 10136 // Emit warning for non-trivial dtor in global scope (a real global, 10137 // class-static, function-static). 10138 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 10139 10140 // TODO: this should be re-enabled for static locals by !CXAAtExit 10141 if (!VD->isStaticLocal()) 10142 Diag(VD->getLocation(), diag::warn_global_destructor); 10143} 10144 10145/// \brief Given a constructor and the set of arguments provided for the 10146/// constructor, convert the arguments and add any required default arguments 10147/// to form a proper call to this constructor. 10148/// 10149/// \returns true if an error occurred, false otherwise. 10150bool 10151Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 10152 MultiExprArg ArgsPtr, 10153 SourceLocation Loc, 10154 SmallVectorImpl<Expr*> &ConvertedArgs, 10155 bool AllowExplicit, 10156 bool IsListInitialization) { 10157 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 10158 unsigned NumArgs = ArgsPtr.size(); 10159 Expr **Args = ArgsPtr.data(); 10160 10161 const FunctionProtoType *Proto 10162 = Constructor->getType()->getAs<FunctionProtoType>(); 10163 assert(Proto && "Constructor without a prototype?"); 10164 unsigned NumArgsInProto = Proto->getNumArgs(); 10165 10166 // If too few arguments are available, we'll fill in the rest with defaults. 10167 if (NumArgs < NumArgsInProto) 10168 ConvertedArgs.reserve(NumArgsInProto); 10169 else 10170 ConvertedArgs.reserve(NumArgs); 10171 10172 VariadicCallType CallType = 10173 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 10174 SmallVector<Expr *, 8> AllArgs; 10175 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 10176 Proto, 0, 10177 llvm::makeArrayRef(Args, NumArgs), 10178 AllArgs, 10179 CallType, AllowExplicit, 10180 IsListInitialization); 10181 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 10182 10183 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 10184 10185 CheckConstructorCall(Constructor, 10186 llvm::makeArrayRef<const Expr *>(AllArgs.data(), 10187 AllArgs.size()), 10188 Proto, Loc); 10189 10190 return Invalid; 10191} 10192 10193static inline bool 10194CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 10195 const FunctionDecl *FnDecl) { 10196 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 10197 if (isa<NamespaceDecl>(DC)) { 10198 return SemaRef.Diag(FnDecl->getLocation(), 10199 diag::err_operator_new_delete_declared_in_namespace) 10200 << FnDecl->getDeclName(); 10201 } 10202 10203 if (isa<TranslationUnitDecl>(DC) && 10204 FnDecl->getStorageClass() == SC_Static) { 10205 return SemaRef.Diag(FnDecl->getLocation(), 10206 diag::err_operator_new_delete_declared_static) 10207 << FnDecl->getDeclName(); 10208 } 10209 10210 return false; 10211} 10212 10213static inline bool 10214CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 10215 CanQualType ExpectedResultType, 10216 CanQualType ExpectedFirstParamType, 10217 unsigned DependentParamTypeDiag, 10218 unsigned InvalidParamTypeDiag) { 10219 QualType ResultType = 10220 FnDecl->getType()->getAs<FunctionType>()->getResultType(); 10221 10222 // Check that the result type is not dependent. 10223 if (ResultType->isDependentType()) 10224 return SemaRef.Diag(FnDecl->getLocation(), 10225 diag::err_operator_new_delete_dependent_result_type) 10226 << FnDecl->getDeclName() << ExpectedResultType; 10227 10228 // Check that the result type is what we expect. 10229 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 10230 return SemaRef.Diag(FnDecl->getLocation(), 10231 diag::err_operator_new_delete_invalid_result_type) 10232 << FnDecl->getDeclName() << ExpectedResultType; 10233 10234 // A function template must have at least 2 parameters. 10235 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 10236 return SemaRef.Diag(FnDecl->getLocation(), 10237 diag::err_operator_new_delete_template_too_few_parameters) 10238 << FnDecl->getDeclName(); 10239 10240 // The function decl must have at least 1 parameter. 10241 if (FnDecl->getNumParams() == 0) 10242 return SemaRef.Diag(FnDecl->getLocation(), 10243 diag::err_operator_new_delete_too_few_parameters) 10244 << FnDecl->getDeclName(); 10245 10246 // Check the first parameter type is not dependent. 10247 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 10248 if (FirstParamType->isDependentType()) 10249 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 10250 << FnDecl->getDeclName() << ExpectedFirstParamType; 10251 10252 // Check that the first parameter type is what we expect. 10253 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 10254 ExpectedFirstParamType) 10255 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 10256 << FnDecl->getDeclName() << ExpectedFirstParamType; 10257 10258 return false; 10259} 10260 10261static bool 10262CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 10263 // C++ [basic.stc.dynamic.allocation]p1: 10264 // A program is ill-formed if an allocation function is declared in a 10265 // namespace scope other than global scope or declared static in global 10266 // scope. 10267 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 10268 return true; 10269 10270 CanQualType SizeTy = 10271 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 10272 10273 // C++ [basic.stc.dynamic.allocation]p1: 10274 // The return type shall be void*. The first parameter shall have type 10275 // std::size_t. 10276 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 10277 SizeTy, 10278 diag::err_operator_new_dependent_param_type, 10279 diag::err_operator_new_param_type)) 10280 return true; 10281 10282 // C++ [basic.stc.dynamic.allocation]p1: 10283 // The first parameter shall not have an associated default argument. 10284 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 10285 return SemaRef.Diag(FnDecl->getLocation(), 10286 diag::err_operator_new_default_arg) 10287 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 10288 10289 return false; 10290} 10291 10292static bool 10293CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 10294 // C++ [basic.stc.dynamic.deallocation]p1: 10295 // A program is ill-formed if deallocation functions are declared in a 10296 // namespace scope other than global scope or declared static in global 10297 // scope. 10298 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 10299 return true; 10300 10301 // C++ [basic.stc.dynamic.deallocation]p2: 10302 // Each deallocation function shall return void and its first parameter 10303 // shall be void*. 10304 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 10305 SemaRef.Context.VoidPtrTy, 10306 diag::err_operator_delete_dependent_param_type, 10307 diag::err_operator_delete_param_type)) 10308 return true; 10309 10310 return false; 10311} 10312 10313/// CheckOverloadedOperatorDeclaration - Check whether the declaration 10314/// of this overloaded operator is well-formed. If so, returns false; 10315/// otherwise, emits appropriate diagnostics and returns true. 10316bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 10317 assert(FnDecl && FnDecl->isOverloadedOperator() && 10318 "Expected an overloaded operator declaration"); 10319 10320 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 10321 10322 // C++ [over.oper]p5: 10323 // The allocation and deallocation functions, operator new, 10324 // operator new[], operator delete and operator delete[], are 10325 // described completely in 3.7.3. The attributes and restrictions 10326 // found in the rest of this subclause do not apply to them unless 10327 // explicitly stated in 3.7.3. 10328 if (Op == OO_Delete || Op == OO_Array_Delete) 10329 return CheckOperatorDeleteDeclaration(*this, FnDecl); 10330 10331 if (Op == OO_New || Op == OO_Array_New) 10332 return CheckOperatorNewDeclaration(*this, FnDecl); 10333 10334 // C++ [over.oper]p6: 10335 // An operator function shall either be a non-static member 10336 // function or be a non-member function and have at least one 10337 // parameter whose type is a class, a reference to a class, an 10338 // enumeration, or a reference to an enumeration. 10339 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 10340 if (MethodDecl->isStatic()) 10341 return Diag(FnDecl->getLocation(), 10342 diag::err_operator_overload_static) << FnDecl->getDeclName(); 10343 } else { 10344 bool ClassOrEnumParam = false; 10345 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 10346 ParamEnd = FnDecl->param_end(); 10347 Param != ParamEnd; ++Param) { 10348 QualType ParamType = (*Param)->getType().getNonReferenceType(); 10349 if (ParamType->isDependentType() || ParamType->isRecordType() || 10350 ParamType->isEnumeralType()) { 10351 ClassOrEnumParam = true; 10352 break; 10353 } 10354 } 10355 10356 if (!ClassOrEnumParam) 10357 return Diag(FnDecl->getLocation(), 10358 diag::err_operator_overload_needs_class_or_enum) 10359 << FnDecl->getDeclName(); 10360 } 10361 10362 // C++ [over.oper]p8: 10363 // An operator function cannot have default arguments (8.3.6), 10364 // except where explicitly stated below. 10365 // 10366 // Only the function-call operator allows default arguments 10367 // (C++ [over.call]p1). 10368 if (Op != OO_Call) { 10369 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(); 10370 Param != FnDecl->param_end(); ++Param) { 10371 if ((*Param)->hasDefaultArg()) 10372 return Diag((*Param)->getLocation(), 10373 diag::err_operator_overload_default_arg) 10374 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange(); 10375 } 10376 } 10377 10378 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 10379 { false, false, false } 10380#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 10381 , { Unary, Binary, MemberOnly } 10382#include "clang/Basic/OperatorKinds.def" 10383 }; 10384 10385 bool CanBeUnaryOperator = OperatorUses[Op][0]; 10386 bool CanBeBinaryOperator = OperatorUses[Op][1]; 10387 bool MustBeMemberOperator = OperatorUses[Op][2]; 10388 10389 // C++ [over.oper]p8: 10390 // [...] Operator functions cannot have more or fewer parameters 10391 // than the number required for the corresponding operator, as 10392 // described in the rest of this subclause. 10393 unsigned NumParams = FnDecl->getNumParams() 10394 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 10395 if (Op != OO_Call && 10396 ((NumParams == 1 && !CanBeUnaryOperator) || 10397 (NumParams == 2 && !CanBeBinaryOperator) || 10398 (NumParams < 1) || (NumParams > 2))) { 10399 // We have the wrong number of parameters. 10400 unsigned ErrorKind; 10401 if (CanBeUnaryOperator && CanBeBinaryOperator) { 10402 ErrorKind = 2; // 2 -> unary or binary. 10403 } else if (CanBeUnaryOperator) { 10404 ErrorKind = 0; // 0 -> unary 10405 } else { 10406 assert(CanBeBinaryOperator && 10407 "All non-call overloaded operators are unary or binary!"); 10408 ErrorKind = 1; // 1 -> binary 10409 } 10410 10411 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 10412 << FnDecl->getDeclName() << NumParams << ErrorKind; 10413 } 10414 10415 // Overloaded operators other than operator() cannot be variadic. 10416 if (Op != OO_Call && 10417 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 10418 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 10419 << FnDecl->getDeclName(); 10420 } 10421 10422 // Some operators must be non-static member functions. 10423 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 10424 return Diag(FnDecl->getLocation(), 10425 diag::err_operator_overload_must_be_member) 10426 << FnDecl->getDeclName(); 10427 } 10428 10429 // C++ [over.inc]p1: 10430 // The user-defined function called operator++ implements the 10431 // prefix and postfix ++ operator. If this function is a member 10432 // function with no parameters, or a non-member function with one 10433 // parameter of class or enumeration type, it defines the prefix 10434 // increment operator ++ for objects of that type. If the function 10435 // is a member function with one parameter (which shall be of type 10436 // int) or a non-member function with two parameters (the second 10437 // of which shall be of type int), it defines the postfix 10438 // increment operator ++ for objects of that type. 10439 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 10440 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 10441 bool ParamIsInt = false; 10442 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>()) 10443 ParamIsInt = BT->getKind() == BuiltinType::Int; 10444 10445 if (!ParamIsInt) 10446 return Diag(LastParam->getLocation(), 10447 diag::err_operator_overload_post_incdec_must_be_int) 10448 << LastParam->getType() << (Op == OO_MinusMinus); 10449 } 10450 10451 return false; 10452} 10453 10454/// CheckLiteralOperatorDeclaration - Check whether the declaration 10455/// of this literal operator function is well-formed. If so, returns 10456/// false; otherwise, emits appropriate diagnostics and returns true. 10457bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 10458 if (isa<CXXMethodDecl>(FnDecl)) { 10459 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 10460 << FnDecl->getDeclName(); 10461 return true; 10462 } 10463 10464 if (FnDecl->isExternC()) { 10465 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 10466 return true; 10467 } 10468 10469 bool Valid = false; 10470 10471 // This might be the definition of a literal operator template. 10472 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 10473 // This might be a specialization of a literal operator template. 10474 if (!TpDecl) 10475 TpDecl = FnDecl->getPrimaryTemplate(); 10476 10477 // template <char...> type operator "" name() is the only valid template 10478 // signature, and the only valid signature with no parameters. 10479 if (TpDecl) { 10480 if (FnDecl->param_size() == 0) { 10481 // Must have only one template parameter 10482 TemplateParameterList *Params = TpDecl->getTemplateParameters(); 10483 if (Params->size() == 1) { 10484 NonTypeTemplateParmDecl *PmDecl = 10485 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0)); 10486 10487 // The template parameter must be a char parameter pack. 10488 if (PmDecl && PmDecl->isTemplateParameterPack() && 10489 Context.hasSameType(PmDecl->getType(), Context.CharTy)) 10490 Valid = true; 10491 } 10492 } 10493 } else if (FnDecl->param_size()) { 10494 // Check the first parameter 10495 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 10496 10497 QualType T = (*Param)->getType().getUnqualifiedType(); 10498 10499 // unsigned long long int, long double, and any character type are allowed 10500 // as the only parameters. 10501 if (Context.hasSameType(T, Context.UnsignedLongLongTy) || 10502 Context.hasSameType(T, Context.LongDoubleTy) || 10503 Context.hasSameType(T, Context.CharTy) || 10504 Context.hasSameType(T, Context.WideCharTy) || 10505 Context.hasSameType(T, Context.Char16Ty) || 10506 Context.hasSameType(T, Context.Char32Ty)) { 10507 if (++Param == FnDecl->param_end()) 10508 Valid = true; 10509 goto FinishedParams; 10510 } 10511 10512 // Otherwise it must be a pointer to const; let's strip those qualifiers. 10513 const PointerType *PT = T->getAs<PointerType>(); 10514 if (!PT) 10515 goto FinishedParams; 10516 T = PT->getPointeeType(); 10517 if (!T.isConstQualified() || T.isVolatileQualified()) 10518 goto FinishedParams; 10519 T = T.getUnqualifiedType(); 10520 10521 // Move on to the second parameter; 10522 ++Param; 10523 10524 // If there is no second parameter, the first must be a const char * 10525 if (Param == FnDecl->param_end()) { 10526 if (Context.hasSameType(T, Context.CharTy)) 10527 Valid = true; 10528 goto FinishedParams; 10529 } 10530 10531 // const char *, const wchar_t*, const char16_t*, and const char32_t* 10532 // are allowed as the first parameter to a two-parameter function 10533 if (!(Context.hasSameType(T, Context.CharTy) || 10534 Context.hasSameType(T, Context.WideCharTy) || 10535 Context.hasSameType(T, Context.Char16Ty) || 10536 Context.hasSameType(T, Context.Char32Ty))) 10537 goto FinishedParams; 10538 10539 // The second and final parameter must be an std::size_t 10540 T = (*Param)->getType().getUnqualifiedType(); 10541 if (Context.hasSameType(T, Context.getSizeType()) && 10542 ++Param == FnDecl->param_end()) 10543 Valid = true; 10544 } 10545 10546 // FIXME: This diagnostic is absolutely terrible. 10547FinishedParams: 10548 if (!Valid) { 10549 Diag(FnDecl->getLocation(), diag::err_literal_operator_params) 10550 << FnDecl->getDeclName(); 10551 return true; 10552 } 10553 10554 // A parameter-declaration-clause containing a default argument is not 10555 // equivalent to any of the permitted forms. 10556 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 10557 ParamEnd = FnDecl->param_end(); 10558 Param != ParamEnd; ++Param) { 10559 if ((*Param)->hasDefaultArg()) { 10560 Diag((*Param)->getDefaultArgRange().getBegin(), 10561 diag::err_literal_operator_default_argument) 10562 << (*Param)->getDefaultArgRange(); 10563 break; 10564 } 10565 } 10566 10567 StringRef LiteralName 10568 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 10569 if (LiteralName[0] != '_') { 10570 // C++11 [usrlit.suffix]p1: 10571 // Literal suffix identifiers that do not start with an underscore 10572 // are reserved for future standardization. 10573 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved); 10574 } 10575 10576 return false; 10577} 10578 10579/// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 10580/// linkage specification, including the language and (if present) 10581/// the '{'. ExternLoc is the location of the 'extern', LangLoc is 10582/// the location of the language string literal, which is provided 10583/// by Lang/StrSize. LBraceLoc, if valid, provides the location of 10584/// the '{' brace. Otherwise, this linkage specification does not 10585/// have any braces. 10586Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 10587 SourceLocation LangLoc, 10588 StringRef Lang, 10589 SourceLocation LBraceLoc) { 10590 LinkageSpecDecl::LanguageIDs Language; 10591 if (Lang == "\"C\"") 10592 Language = LinkageSpecDecl::lang_c; 10593 else if (Lang == "\"C++\"") 10594 Language = LinkageSpecDecl::lang_cxx; 10595 else { 10596 Diag(LangLoc, diag::err_bad_language); 10597 return 0; 10598 } 10599 10600 // FIXME: Add all the various semantics of linkage specifications 10601 10602 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, 10603 ExternLoc, LangLoc, Language, 10604 LBraceLoc.isValid()); 10605 CurContext->addDecl(D); 10606 PushDeclContext(S, D); 10607 return D; 10608} 10609 10610/// ActOnFinishLinkageSpecification - Complete the definition of 10611/// the C++ linkage specification LinkageSpec. If RBraceLoc is 10612/// valid, it's the position of the closing '}' brace in a linkage 10613/// specification that uses braces. 10614Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 10615 Decl *LinkageSpec, 10616 SourceLocation RBraceLoc) { 10617 if (LinkageSpec) { 10618 if (RBraceLoc.isValid()) { 10619 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 10620 LSDecl->setRBraceLoc(RBraceLoc); 10621 } 10622 PopDeclContext(); 10623 } 10624 return LinkageSpec; 10625} 10626 10627Decl *Sema::ActOnEmptyDeclaration(Scope *S, 10628 AttributeList *AttrList, 10629 SourceLocation SemiLoc) { 10630 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 10631 // Attribute declarations appertain to empty declaration so we handle 10632 // them here. 10633 if (AttrList) 10634 ProcessDeclAttributeList(S, ED, AttrList); 10635 10636 CurContext->addDecl(ED); 10637 return ED; 10638} 10639 10640/// \brief Perform semantic analysis for the variable declaration that 10641/// occurs within a C++ catch clause, returning the newly-created 10642/// variable. 10643VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 10644 TypeSourceInfo *TInfo, 10645 SourceLocation StartLoc, 10646 SourceLocation Loc, 10647 IdentifierInfo *Name) { 10648 bool Invalid = false; 10649 QualType ExDeclType = TInfo->getType(); 10650 10651 // Arrays and functions decay. 10652 if (ExDeclType->isArrayType()) 10653 ExDeclType = Context.getArrayDecayedType(ExDeclType); 10654 else if (ExDeclType->isFunctionType()) 10655 ExDeclType = Context.getPointerType(ExDeclType); 10656 10657 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 10658 // The exception-declaration shall not denote a pointer or reference to an 10659 // incomplete type, other than [cv] void*. 10660 // N2844 forbids rvalue references. 10661 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 10662 Diag(Loc, diag::err_catch_rvalue_ref); 10663 Invalid = true; 10664 } 10665 10666 QualType BaseType = ExDeclType; 10667 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 10668 unsigned DK = diag::err_catch_incomplete; 10669 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 10670 BaseType = Ptr->getPointeeType(); 10671 Mode = 1; 10672 DK = diag::err_catch_incomplete_ptr; 10673 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 10674 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 10675 BaseType = Ref->getPointeeType(); 10676 Mode = 2; 10677 DK = diag::err_catch_incomplete_ref; 10678 } 10679 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 10680 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 10681 Invalid = true; 10682 10683 if (!Invalid && !ExDeclType->isDependentType() && 10684 RequireNonAbstractType(Loc, ExDeclType, 10685 diag::err_abstract_type_in_decl, 10686 AbstractVariableType)) 10687 Invalid = true; 10688 10689 // Only the non-fragile NeXT runtime currently supports C++ catches 10690 // of ObjC types, and no runtime supports catching ObjC types by value. 10691 if (!Invalid && getLangOpts().ObjC1) { 10692 QualType T = ExDeclType; 10693 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 10694 T = RT->getPointeeType(); 10695 10696 if (T->isObjCObjectType()) { 10697 Diag(Loc, diag::err_objc_object_catch); 10698 Invalid = true; 10699 } else if (T->isObjCObjectPointerType()) { 10700 // FIXME: should this be a test for macosx-fragile specifically? 10701 if (getLangOpts().ObjCRuntime.isFragile()) 10702 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 10703 } 10704 } 10705 10706 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 10707 ExDeclType, TInfo, SC_None); 10708 ExDecl->setExceptionVariable(true); 10709 10710 // In ARC, infer 'retaining' for variables of retainable type. 10711 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 10712 Invalid = true; 10713 10714 if (!Invalid && !ExDeclType->isDependentType()) { 10715 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 10716 // Insulate this from anything else we might currently be parsing. 10717 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 10718 10719 // C++ [except.handle]p16: 10720 // The object declared in an exception-declaration or, if the 10721 // exception-declaration does not specify a name, a temporary (12.2) is 10722 // copy-initialized (8.5) from the exception object. [...] 10723 // The object is destroyed when the handler exits, after the destruction 10724 // of any automatic objects initialized within the handler. 10725 // 10726 // We just pretend to initialize the object with itself, then make sure 10727 // it can be destroyed later. 10728 QualType initType = ExDeclType; 10729 10730 InitializedEntity entity = 10731 InitializedEntity::InitializeVariable(ExDecl); 10732 InitializationKind initKind = 10733 InitializationKind::CreateCopy(Loc, SourceLocation()); 10734 10735 Expr *opaqueValue = 10736 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 10737 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 10738 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 10739 if (result.isInvalid()) 10740 Invalid = true; 10741 else { 10742 // If the constructor used was non-trivial, set this as the 10743 // "initializer". 10744 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take()); 10745 if (!construct->getConstructor()->isTrivial()) { 10746 Expr *init = MaybeCreateExprWithCleanups(construct); 10747 ExDecl->setInit(init); 10748 } 10749 10750 // And make sure it's destructable. 10751 FinalizeVarWithDestructor(ExDecl, recordType); 10752 } 10753 } 10754 } 10755 10756 if (Invalid) 10757 ExDecl->setInvalidDecl(); 10758 10759 return ExDecl; 10760} 10761 10762/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 10763/// handler. 10764Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 10765 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 10766 bool Invalid = D.isInvalidType(); 10767 10768 // Check for unexpanded parameter packs. 10769 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 10770 UPPC_ExceptionType)) { 10771 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 10772 D.getIdentifierLoc()); 10773 Invalid = true; 10774 } 10775 10776 IdentifierInfo *II = D.getIdentifier(); 10777 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 10778 LookupOrdinaryName, 10779 ForRedeclaration)) { 10780 // The scope should be freshly made just for us. There is just no way 10781 // it contains any previous declaration. 10782 assert(!S->isDeclScope(PrevDecl)); 10783 if (PrevDecl->isTemplateParameter()) { 10784 // Maybe we will complain about the shadowed template parameter. 10785 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 10786 PrevDecl = 0; 10787 } 10788 } 10789 10790 if (D.getCXXScopeSpec().isSet() && !Invalid) { 10791 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 10792 << D.getCXXScopeSpec().getRange(); 10793 Invalid = true; 10794 } 10795 10796 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 10797 D.getLocStart(), 10798 D.getIdentifierLoc(), 10799 D.getIdentifier()); 10800 if (Invalid) 10801 ExDecl->setInvalidDecl(); 10802 10803 // Add the exception declaration into this scope. 10804 if (II) 10805 PushOnScopeChains(ExDecl, S); 10806 else 10807 CurContext->addDecl(ExDecl); 10808 10809 ProcessDeclAttributes(S, ExDecl, D); 10810 return ExDecl; 10811} 10812 10813Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 10814 Expr *AssertExpr, 10815 Expr *AssertMessageExpr, 10816 SourceLocation RParenLoc) { 10817 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr); 10818 10819 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 10820 return 0; 10821 10822 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 10823 AssertMessage, RParenLoc, false); 10824} 10825 10826Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 10827 Expr *AssertExpr, 10828 StringLiteral *AssertMessage, 10829 SourceLocation RParenLoc, 10830 bool Failed) { 10831 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 10832 !Failed) { 10833 // In a static_assert-declaration, the constant-expression shall be a 10834 // constant expression that can be contextually converted to bool. 10835 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 10836 if (Converted.isInvalid()) 10837 Failed = true; 10838 10839 llvm::APSInt Cond; 10840 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 10841 diag::err_static_assert_expression_is_not_constant, 10842 /*AllowFold=*/false).isInvalid()) 10843 Failed = true; 10844 10845 if (!Failed && !Cond) { 10846 SmallString<256> MsgBuffer; 10847 llvm::raw_svector_ostream Msg(MsgBuffer); 10848 AssertMessage->printPretty(Msg, 0, getPrintingPolicy()); 10849 Diag(StaticAssertLoc, diag::err_static_assert_failed) 10850 << Msg.str() << AssertExpr->getSourceRange(); 10851 Failed = true; 10852 } 10853 } 10854 10855 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 10856 AssertExpr, AssertMessage, RParenLoc, 10857 Failed); 10858 10859 CurContext->addDecl(Decl); 10860 return Decl; 10861} 10862 10863/// \brief Perform semantic analysis of the given friend type declaration. 10864/// 10865/// \returns A friend declaration that. 10866FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 10867 SourceLocation FriendLoc, 10868 TypeSourceInfo *TSInfo) { 10869 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 10870 10871 QualType T = TSInfo->getType(); 10872 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 10873 10874 // C++03 [class.friend]p2: 10875 // An elaborated-type-specifier shall be used in a friend declaration 10876 // for a class.* 10877 // 10878 // * The class-key of the elaborated-type-specifier is required. 10879 if (!ActiveTemplateInstantiations.empty()) { 10880 // Do not complain about the form of friend template types during 10881 // template instantiation; we will already have complained when the 10882 // template was declared. 10883 } else { 10884 if (!T->isElaboratedTypeSpecifier()) { 10885 // If we evaluated the type to a record type, suggest putting 10886 // a tag in front. 10887 if (const RecordType *RT = T->getAs<RecordType>()) { 10888 RecordDecl *RD = RT->getDecl(); 10889 10890 std::string InsertionText = std::string(" ") + RD->getKindName(); 10891 10892 Diag(TypeRange.getBegin(), 10893 getLangOpts().CPlusPlus11 ? 10894 diag::warn_cxx98_compat_unelaborated_friend_type : 10895 diag::ext_unelaborated_friend_type) 10896 << (unsigned) RD->getTagKind() 10897 << T 10898 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc), 10899 InsertionText); 10900 } else { 10901 Diag(FriendLoc, 10902 getLangOpts().CPlusPlus11 ? 10903 diag::warn_cxx98_compat_nonclass_type_friend : 10904 diag::ext_nonclass_type_friend) 10905 << T 10906 << TypeRange; 10907 } 10908 } else if (T->getAs<EnumType>()) { 10909 Diag(FriendLoc, 10910 getLangOpts().CPlusPlus11 ? 10911 diag::warn_cxx98_compat_enum_friend : 10912 diag::ext_enum_friend) 10913 << T 10914 << TypeRange; 10915 } 10916 10917 // C++11 [class.friend]p3: 10918 // A friend declaration that does not declare a function shall have one 10919 // of the following forms: 10920 // friend elaborated-type-specifier ; 10921 // friend simple-type-specifier ; 10922 // friend typename-specifier ; 10923 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 10924 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 10925 } 10926 10927 // If the type specifier in a friend declaration designates a (possibly 10928 // cv-qualified) class type, that class is declared as a friend; otherwise, 10929 // the friend declaration is ignored. 10930 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc); 10931} 10932 10933/// Handle a friend tag declaration where the scope specifier was 10934/// templated. 10935Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 10936 unsigned TagSpec, SourceLocation TagLoc, 10937 CXXScopeSpec &SS, 10938 IdentifierInfo *Name, 10939 SourceLocation NameLoc, 10940 AttributeList *Attr, 10941 MultiTemplateParamsArg TempParamLists) { 10942 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 10943 10944 bool isExplicitSpecialization = false; 10945 bool Invalid = false; 10946 10947 if (TemplateParameterList *TemplateParams 10948 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS, 10949 TempParamLists.data(), 10950 TempParamLists.size(), 10951 /*friend*/ true, 10952 isExplicitSpecialization, 10953 Invalid)) { 10954 if (TemplateParams->size() > 0) { 10955 // This is a declaration of a class template. 10956 if (Invalid) 10957 return 0; 10958 10959 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, 10960 SS, Name, NameLoc, Attr, 10961 TemplateParams, AS_public, 10962 /*ModulePrivateLoc=*/SourceLocation(), 10963 TempParamLists.size() - 1, 10964 TempParamLists.data()).take(); 10965 } else { 10966 // The "template<>" header is extraneous. 10967 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 10968 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 10969 isExplicitSpecialization = true; 10970 } 10971 } 10972 10973 if (Invalid) return 0; 10974 10975 bool isAllExplicitSpecializations = true; 10976 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 10977 if (TempParamLists[I]->size()) { 10978 isAllExplicitSpecializations = false; 10979 break; 10980 } 10981 } 10982 10983 // FIXME: don't ignore attributes. 10984 10985 // If it's explicit specializations all the way down, just forget 10986 // about the template header and build an appropriate non-templated 10987 // friend. TODO: for source fidelity, remember the headers. 10988 if (isAllExplicitSpecializations) { 10989 if (SS.isEmpty()) { 10990 bool Owned = false; 10991 bool IsDependent = false; 10992 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 10993 Attr, AS_public, 10994 /*ModulePrivateLoc=*/SourceLocation(), 10995 MultiTemplateParamsArg(), Owned, IsDependent, 10996 /*ScopedEnumKWLoc=*/SourceLocation(), 10997 /*ScopedEnumUsesClassTag=*/false, 10998 /*UnderlyingType=*/TypeResult()); 10999 } 11000 11001 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 11002 ElaboratedTypeKeyword Keyword 11003 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 11004 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 11005 *Name, NameLoc); 11006 if (T.isNull()) 11007 return 0; 11008 11009 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 11010 if (isa<DependentNameType>(T)) { 11011 DependentNameTypeLoc TL = 11012 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 11013 TL.setElaboratedKeywordLoc(TagLoc); 11014 TL.setQualifierLoc(QualifierLoc); 11015 TL.setNameLoc(NameLoc); 11016 } else { 11017 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 11018 TL.setElaboratedKeywordLoc(TagLoc); 11019 TL.setQualifierLoc(QualifierLoc); 11020 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 11021 } 11022 11023 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 11024 TSI, FriendLoc, TempParamLists); 11025 Friend->setAccess(AS_public); 11026 CurContext->addDecl(Friend); 11027 return Friend; 11028 } 11029 11030 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 11031 11032 11033 11034 // Handle the case of a templated-scope friend class. e.g. 11035 // template <class T> class A<T>::B; 11036 // FIXME: we don't support these right now. 11037 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 11038 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 11039 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 11040 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 11041 TL.setElaboratedKeywordLoc(TagLoc); 11042 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 11043 TL.setNameLoc(NameLoc); 11044 11045 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 11046 TSI, FriendLoc, TempParamLists); 11047 Friend->setAccess(AS_public); 11048 Friend->setUnsupportedFriend(true); 11049 CurContext->addDecl(Friend); 11050 return Friend; 11051} 11052 11053 11054/// Handle a friend type declaration. This works in tandem with 11055/// ActOnTag. 11056/// 11057/// Notes on friend class templates: 11058/// 11059/// We generally treat friend class declarations as if they were 11060/// declaring a class. So, for example, the elaborated type specifier 11061/// in a friend declaration is required to obey the restrictions of a 11062/// class-head (i.e. no typedefs in the scope chain), template 11063/// parameters are required to match up with simple template-ids, &c. 11064/// However, unlike when declaring a template specialization, it's 11065/// okay to refer to a template specialization without an empty 11066/// template parameter declaration, e.g. 11067/// friend class A<T>::B<unsigned>; 11068/// We permit this as a special case; if there are any template 11069/// parameters present at all, require proper matching, i.e. 11070/// template <> template \<class T> friend class A<int>::B; 11071Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 11072 MultiTemplateParamsArg TempParams) { 11073 SourceLocation Loc = DS.getLocStart(); 11074 11075 assert(DS.isFriendSpecified()); 11076 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 11077 11078 // Try to convert the decl specifier to a type. This works for 11079 // friend templates because ActOnTag never produces a ClassTemplateDecl 11080 // for a TUK_Friend. 11081 Declarator TheDeclarator(DS, Declarator::MemberContext); 11082 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 11083 QualType T = TSI->getType(); 11084 if (TheDeclarator.isInvalidType()) 11085 return 0; 11086 11087 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 11088 return 0; 11089 11090 // This is definitely an error in C++98. It's probably meant to 11091 // be forbidden in C++0x, too, but the specification is just 11092 // poorly written. 11093 // 11094 // The problem is with declarations like the following: 11095 // template <T> friend A<T>::foo; 11096 // where deciding whether a class C is a friend or not now hinges 11097 // on whether there exists an instantiation of A that causes 11098 // 'foo' to equal C. There are restrictions on class-heads 11099 // (which we declare (by fiat) elaborated friend declarations to 11100 // be) that makes this tractable. 11101 // 11102 // FIXME: handle "template <> friend class A<T>;", which 11103 // is possibly well-formed? Who even knows? 11104 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 11105 Diag(Loc, diag::err_tagless_friend_type_template) 11106 << DS.getSourceRange(); 11107 return 0; 11108 } 11109 11110 // C++98 [class.friend]p1: A friend of a class is a function 11111 // or class that is not a member of the class . . . 11112 // This is fixed in DR77, which just barely didn't make the C++03 11113 // deadline. It's also a very silly restriction that seriously 11114 // affects inner classes and which nobody else seems to implement; 11115 // thus we never diagnose it, not even in -pedantic. 11116 // 11117 // But note that we could warn about it: it's always useless to 11118 // friend one of your own members (it's not, however, worthless to 11119 // friend a member of an arbitrary specialization of your template). 11120 11121 Decl *D; 11122 if (unsigned NumTempParamLists = TempParams.size()) 11123 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 11124 NumTempParamLists, 11125 TempParams.data(), 11126 TSI, 11127 DS.getFriendSpecLoc()); 11128 else 11129 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 11130 11131 if (!D) 11132 return 0; 11133 11134 D->setAccess(AS_public); 11135 CurContext->addDecl(D); 11136 11137 return D; 11138} 11139 11140NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 11141 MultiTemplateParamsArg TemplateParams) { 11142 const DeclSpec &DS = D.getDeclSpec(); 11143 11144 assert(DS.isFriendSpecified()); 11145 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 11146 11147 SourceLocation Loc = D.getIdentifierLoc(); 11148 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11149 11150 // C++ [class.friend]p1 11151 // A friend of a class is a function or class.... 11152 // Note that this sees through typedefs, which is intended. 11153 // It *doesn't* see through dependent types, which is correct 11154 // according to [temp.arg.type]p3: 11155 // If a declaration acquires a function type through a 11156 // type dependent on a template-parameter and this causes 11157 // a declaration that does not use the syntactic form of a 11158 // function declarator to have a function type, the program 11159 // is ill-formed. 11160 if (!TInfo->getType()->isFunctionType()) { 11161 Diag(Loc, diag::err_unexpected_friend); 11162 11163 // It might be worthwhile to try to recover by creating an 11164 // appropriate declaration. 11165 return 0; 11166 } 11167 11168 // C++ [namespace.memdef]p3 11169 // - If a friend declaration in a non-local class first declares a 11170 // class or function, the friend class or function is a member 11171 // of the innermost enclosing namespace. 11172 // - The name of the friend is not found by simple name lookup 11173 // until a matching declaration is provided in that namespace 11174 // scope (either before or after the class declaration granting 11175 // friendship). 11176 // - If a friend function is called, its name may be found by the 11177 // name lookup that considers functions from namespaces and 11178 // classes associated with the types of the function arguments. 11179 // - When looking for a prior declaration of a class or a function 11180 // declared as a friend, scopes outside the innermost enclosing 11181 // namespace scope are not considered. 11182 11183 CXXScopeSpec &SS = D.getCXXScopeSpec(); 11184 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 11185 DeclarationName Name = NameInfo.getName(); 11186 assert(Name); 11187 11188 // Check for unexpanded parameter packs. 11189 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 11190 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 11191 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 11192 return 0; 11193 11194 // The context we found the declaration in, or in which we should 11195 // create the declaration. 11196 DeclContext *DC; 11197 Scope *DCScope = S; 11198 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 11199 ForRedeclaration); 11200 11201 // FIXME: there are different rules in local classes 11202 11203 // There are four cases here. 11204 // - There's no scope specifier, in which case we just go to the 11205 // appropriate scope and look for a function or function template 11206 // there as appropriate. 11207 // Recover from invalid scope qualifiers as if they just weren't there. 11208 if (SS.isInvalid() || !SS.isSet()) { 11209 // C++0x [namespace.memdef]p3: 11210 // If the name in a friend declaration is neither qualified nor 11211 // a template-id and the declaration is a function or an 11212 // elaborated-type-specifier, the lookup to determine whether 11213 // the entity has been previously declared shall not consider 11214 // any scopes outside the innermost enclosing namespace. 11215 // C++0x [class.friend]p11: 11216 // If a friend declaration appears in a local class and the name 11217 // specified is an unqualified name, a prior declaration is 11218 // looked up without considering scopes that are outside the 11219 // innermost enclosing non-class scope. For a friend function 11220 // declaration, if there is no prior declaration, the program is 11221 // ill-formed. 11222 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass(); 11223 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 11224 11225 // Find the appropriate context according to the above. 11226 DC = CurContext; 11227 11228 // Skip class contexts. If someone can cite chapter and verse 11229 // for this behavior, that would be nice --- it's what GCC and 11230 // EDG do, and it seems like a reasonable intent, but the spec 11231 // really only says that checks for unqualified existing 11232 // declarations should stop at the nearest enclosing namespace, 11233 // not that they should only consider the nearest enclosing 11234 // namespace. 11235 while (DC->isRecord()) 11236 DC = DC->getParent(); 11237 11238 DeclContext *LookupDC = DC; 11239 while (LookupDC->isTransparentContext()) 11240 LookupDC = LookupDC->getParent(); 11241 11242 while (true) { 11243 LookupQualifiedName(Previous, LookupDC); 11244 11245 // TODO: decide what we think about using declarations. 11246 if (isLocal) 11247 break; 11248 11249 if (!Previous.empty()) { 11250 DC = LookupDC; 11251 break; 11252 } 11253 11254 if (isTemplateId) { 11255 if (isa<TranslationUnitDecl>(LookupDC)) break; 11256 } else { 11257 if (LookupDC->isFileContext()) break; 11258 } 11259 LookupDC = LookupDC->getParent(); 11260 } 11261 11262 DCScope = getScopeForDeclContext(S, DC); 11263 11264 // C++ [class.friend]p6: 11265 // A function can be defined in a friend declaration of a class if and 11266 // only if the class is a non-local class (9.8), the function name is 11267 // unqualified, and the function has namespace scope. 11268 if (isLocal && D.isFunctionDefinition()) { 11269 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 11270 } 11271 11272 // - There's a non-dependent scope specifier, in which case we 11273 // compute it and do a previous lookup there for a function 11274 // or function template. 11275 } else if (!SS.getScopeRep()->isDependent()) { 11276 DC = computeDeclContext(SS); 11277 if (!DC) return 0; 11278 11279 if (RequireCompleteDeclContext(SS, DC)) return 0; 11280 11281 LookupQualifiedName(Previous, DC); 11282 11283 // Ignore things found implicitly in the wrong scope. 11284 // TODO: better diagnostics for this case. Suggesting the right 11285 // qualified scope would be nice... 11286 LookupResult::Filter F = Previous.makeFilter(); 11287 while (F.hasNext()) { 11288 NamedDecl *D = F.next(); 11289 if (!DC->InEnclosingNamespaceSetOf( 11290 D->getDeclContext()->getRedeclContext())) 11291 F.erase(); 11292 } 11293 F.done(); 11294 11295 if (Previous.empty()) { 11296 D.setInvalidType(); 11297 Diag(Loc, diag::err_qualified_friend_not_found) 11298 << Name << TInfo->getType(); 11299 return 0; 11300 } 11301 11302 // C++ [class.friend]p1: A friend of a class is a function or 11303 // class that is not a member of the class . . . 11304 if (DC->Equals(CurContext)) 11305 Diag(DS.getFriendSpecLoc(), 11306 getLangOpts().CPlusPlus11 ? 11307 diag::warn_cxx98_compat_friend_is_member : 11308 diag::err_friend_is_member); 11309 11310 if (D.isFunctionDefinition()) { 11311 // C++ [class.friend]p6: 11312 // A function can be defined in a friend declaration of a class if and 11313 // only if the class is a non-local class (9.8), the function name is 11314 // unqualified, and the function has namespace scope. 11315 SemaDiagnosticBuilder DB 11316 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 11317 11318 DB << SS.getScopeRep(); 11319 if (DC->isFileContext()) 11320 DB << FixItHint::CreateRemoval(SS.getRange()); 11321 SS.clear(); 11322 } 11323 11324 // - There's a scope specifier that does not match any template 11325 // parameter lists, in which case we use some arbitrary context, 11326 // create a method or method template, and wait for instantiation. 11327 // - There's a scope specifier that does match some template 11328 // parameter lists, which we don't handle right now. 11329 } else { 11330 if (D.isFunctionDefinition()) { 11331 // C++ [class.friend]p6: 11332 // A function can be defined in a friend declaration of a class if and 11333 // only if the class is a non-local class (9.8), the function name is 11334 // unqualified, and the function has namespace scope. 11335 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 11336 << SS.getScopeRep(); 11337 } 11338 11339 DC = CurContext; 11340 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 11341 } 11342 11343 if (!DC->isRecord()) { 11344 // This implies that it has to be an operator or function. 11345 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName || 11346 D.getName().getKind() == UnqualifiedId::IK_DestructorName || 11347 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) { 11348 Diag(Loc, diag::err_introducing_special_friend) << 11349 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 : 11350 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2); 11351 return 0; 11352 } 11353 } 11354 11355 // FIXME: This is an egregious hack to cope with cases where the scope stack 11356 // does not contain the declaration context, i.e., in an out-of-line 11357 // definition of a class. 11358 Scope FakeDCScope(S, Scope::DeclScope, Diags); 11359 if (!DCScope) { 11360 FakeDCScope.setEntity(DC); 11361 DCScope = &FakeDCScope; 11362 } 11363 11364 bool AddToScope = true; 11365 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 11366 TemplateParams, AddToScope); 11367 if (!ND) return 0; 11368 11369 assert(ND->getDeclContext() == DC); 11370 assert(ND->getLexicalDeclContext() == CurContext); 11371 11372 // Add the function declaration to the appropriate lookup tables, 11373 // adjusting the redeclarations list as necessary. We don't 11374 // want to do this yet if the friending class is dependent. 11375 // 11376 // Also update the scope-based lookup if the target context's 11377 // lookup context is in lexical scope. 11378 if (!CurContext->isDependentContext()) { 11379 DC = DC->getRedeclContext(); 11380 DC->makeDeclVisibleInContext(ND); 11381 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 11382 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 11383 } 11384 11385 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 11386 D.getIdentifierLoc(), ND, 11387 DS.getFriendSpecLoc()); 11388 FrD->setAccess(AS_public); 11389 CurContext->addDecl(FrD); 11390 11391 if (ND->isInvalidDecl()) { 11392 FrD->setInvalidDecl(); 11393 } else { 11394 if (DC->isRecord()) CheckFriendAccess(ND); 11395 11396 FunctionDecl *FD; 11397 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 11398 FD = FTD->getTemplatedDecl(); 11399 else 11400 FD = cast<FunctionDecl>(ND); 11401 11402 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 11403 // default argument expression, that declaration shall be a definition 11404 // and shall be the only declaration of the function or function 11405 // template in the translation unit. 11406 if (functionDeclHasDefaultArgument(FD)) { 11407 if (FunctionDecl *OldFD = FD->getPreviousDecl()) { 11408 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 11409 Diag(OldFD->getLocation(), diag::note_previous_declaration); 11410 } else if (!D.isFunctionDefinition()) 11411 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 11412 } 11413 11414 // Mark templated-scope function declarations as unsupported. 11415 if (FD->getNumTemplateParameterLists()) 11416 FrD->setUnsupportedFriend(true); 11417 } 11418 11419 return ND; 11420} 11421 11422void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 11423 AdjustDeclIfTemplate(Dcl); 11424 11425 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 11426 if (!Fn) { 11427 Diag(DelLoc, diag::err_deleted_non_function); 11428 return; 11429 } 11430 11431 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 11432 // Don't consider the implicit declaration we generate for explicit 11433 // specializations. FIXME: Do not generate these implicit declarations. 11434 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization 11435 || Prev->getPreviousDecl()) && !Prev->isDefined()) { 11436 Diag(DelLoc, diag::err_deleted_decl_not_first); 11437 Diag(Prev->getLocation(), diag::note_previous_declaration); 11438 } 11439 // If the declaration wasn't the first, we delete the function anyway for 11440 // recovery. 11441 Fn = Fn->getCanonicalDecl(); 11442 } 11443 11444 if (Fn->isDeleted()) 11445 return; 11446 11447 // See if we're deleting a function which is already known to override a 11448 // non-deleted virtual function. 11449 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 11450 bool IssuedDiagnostic = false; 11451 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 11452 E = MD->end_overridden_methods(); 11453 I != E; ++I) { 11454 if (!(*MD->begin_overridden_methods())->isDeleted()) { 11455 if (!IssuedDiagnostic) { 11456 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 11457 IssuedDiagnostic = true; 11458 } 11459 Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 11460 } 11461 } 11462 } 11463 11464 Fn->setDeletedAsWritten(); 11465} 11466 11467void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 11468 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 11469 11470 if (MD) { 11471 if (MD->getParent()->isDependentType()) { 11472 MD->setDefaulted(); 11473 MD->setExplicitlyDefaulted(); 11474 return; 11475 } 11476 11477 CXXSpecialMember Member = getSpecialMember(MD); 11478 if (Member == CXXInvalid) { 11479 Diag(DefaultLoc, diag::err_default_special_members); 11480 return; 11481 } 11482 11483 MD->setDefaulted(); 11484 MD->setExplicitlyDefaulted(); 11485 11486 // If this definition appears within the record, do the checking when 11487 // the record is complete. 11488 const FunctionDecl *Primary = MD; 11489 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 11490 // Find the uninstantiated declaration that actually had the '= default' 11491 // on it. 11492 Pattern->isDefined(Primary); 11493 11494 // If the method was defaulted on its first declaration, we will have 11495 // already performed the checking in CheckCompletedCXXClass. Such a 11496 // declaration doesn't trigger an implicit definition. 11497 if (Primary == Primary->getCanonicalDecl()) 11498 return; 11499 11500 CheckExplicitlyDefaultedSpecialMember(MD); 11501 11502 // The exception specification is needed because we are defining the 11503 // function. 11504 ResolveExceptionSpec(DefaultLoc, 11505 MD->getType()->castAs<FunctionProtoType>()); 11506 11507 switch (Member) { 11508 case CXXDefaultConstructor: { 11509 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD); 11510 if (!CD->isInvalidDecl()) 11511 DefineImplicitDefaultConstructor(DefaultLoc, CD); 11512 break; 11513 } 11514 11515 case CXXCopyConstructor: { 11516 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD); 11517 if (!CD->isInvalidDecl()) 11518 DefineImplicitCopyConstructor(DefaultLoc, CD); 11519 break; 11520 } 11521 11522 case CXXCopyAssignment: { 11523 if (!MD->isInvalidDecl()) 11524 DefineImplicitCopyAssignment(DefaultLoc, MD); 11525 break; 11526 } 11527 11528 case CXXDestructor: { 11529 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD); 11530 if (!DD->isInvalidDecl()) 11531 DefineImplicitDestructor(DefaultLoc, DD); 11532 break; 11533 } 11534 11535 case CXXMoveConstructor: { 11536 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD); 11537 if (!CD->isInvalidDecl()) 11538 DefineImplicitMoveConstructor(DefaultLoc, CD); 11539 break; 11540 } 11541 11542 case CXXMoveAssignment: { 11543 if (!MD->isInvalidDecl()) 11544 DefineImplicitMoveAssignment(DefaultLoc, MD); 11545 break; 11546 } 11547 11548 case CXXInvalid: 11549 llvm_unreachable("Invalid special member."); 11550 } 11551 } else { 11552 Diag(DefaultLoc, diag::err_default_special_members); 11553 } 11554} 11555 11556static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 11557 for (Stmt::child_range CI = S->children(); CI; ++CI) { 11558 Stmt *SubStmt = *CI; 11559 if (!SubStmt) 11560 continue; 11561 if (isa<ReturnStmt>(SubStmt)) 11562 Self.Diag(SubStmt->getLocStart(), 11563 diag::err_return_in_constructor_handler); 11564 if (!isa<Expr>(SubStmt)) 11565 SearchForReturnInStmt(Self, SubStmt); 11566 } 11567} 11568 11569void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 11570 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 11571 CXXCatchStmt *Handler = TryBlock->getHandler(I); 11572 SearchForReturnInStmt(*this, Handler); 11573 } 11574} 11575 11576bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 11577 const CXXMethodDecl *Old) { 11578 const FunctionType *NewFT = New->getType()->getAs<FunctionType>(); 11579 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>(); 11580 11581 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 11582 11583 // If the calling conventions match, everything is fine 11584 if (NewCC == OldCC) 11585 return false; 11586 11587 // If either of the calling conventions are set to "default", we need to pick 11588 // something more sensible based on the target. This supports code where the 11589 // one method explicitly sets thiscall, and another has no explicit calling 11590 // convention. 11591 CallingConv Default = 11592 Context.getTargetInfo().getDefaultCallingConv(TargetInfo::CCMT_Member); 11593 if (NewCC == CC_Default) 11594 NewCC = Default; 11595 if (OldCC == CC_Default) 11596 OldCC = Default; 11597 11598 // If the calling conventions still don't match, then report the error 11599 if (NewCC != OldCC) { 11600 Diag(New->getLocation(), 11601 diag::err_conflicting_overriding_cc_attributes) 11602 << New->getDeclName() << New->getType() << Old->getType(); 11603 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 11604 return true; 11605 } 11606 11607 return false; 11608} 11609 11610bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 11611 const CXXMethodDecl *Old) { 11612 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType(); 11613 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType(); 11614 11615 if (Context.hasSameType(NewTy, OldTy) || 11616 NewTy->isDependentType() || OldTy->isDependentType()) 11617 return false; 11618 11619 // Check if the return types are covariant 11620 QualType NewClassTy, OldClassTy; 11621 11622 /// Both types must be pointers or references to classes. 11623 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 11624 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 11625 NewClassTy = NewPT->getPointeeType(); 11626 OldClassTy = OldPT->getPointeeType(); 11627 } 11628 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 11629 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 11630 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 11631 NewClassTy = NewRT->getPointeeType(); 11632 OldClassTy = OldRT->getPointeeType(); 11633 } 11634 } 11635 } 11636 11637 // The return types aren't either both pointers or references to a class type. 11638 if (NewClassTy.isNull()) { 11639 Diag(New->getLocation(), 11640 diag::err_different_return_type_for_overriding_virtual_function) 11641 << New->getDeclName() << NewTy << OldTy; 11642 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 11643 11644 return true; 11645 } 11646 11647 // C++ [class.virtual]p6: 11648 // If the return type of D::f differs from the return type of B::f, the 11649 // class type in the return type of D::f shall be complete at the point of 11650 // declaration of D::f or shall be the class type D. 11651 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 11652 if (!RT->isBeingDefined() && 11653 RequireCompleteType(New->getLocation(), NewClassTy, 11654 diag::err_covariant_return_incomplete, 11655 New->getDeclName())) 11656 return true; 11657 } 11658 11659 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 11660 // Check if the new class derives from the old class. 11661 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 11662 Diag(New->getLocation(), 11663 diag::err_covariant_return_not_derived) 11664 << New->getDeclName() << NewTy << OldTy; 11665 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 11666 return true; 11667 } 11668 11669 // Check if we the conversion from derived to base is valid. 11670 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy, 11671 diag::err_covariant_return_inaccessible_base, 11672 diag::err_covariant_return_ambiguous_derived_to_base_conv, 11673 // FIXME: Should this point to the return type? 11674 New->getLocation(), SourceRange(), New->getDeclName(), 0)) { 11675 // FIXME: this note won't trigger for delayed access control 11676 // diagnostics, and it's impossible to get an undelayed error 11677 // here from access control during the original parse because 11678 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 11679 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 11680 return true; 11681 } 11682 } 11683 11684 // The qualifiers of the return types must be the same. 11685 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 11686 Diag(New->getLocation(), 11687 diag::err_covariant_return_type_different_qualifications) 11688 << New->getDeclName() << NewTy << OldTy; 11689 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 11690 return true; 11691 }; 11692 11693 11694 // The new class type must have the same or less qualifiers as the old type. 11695 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 11696 Diag(New->getLocation(), 11697 diag::err_covariant_return_type_class_type_more_qualified) 11698 << New->getDeclName() << NewTy << OldTy; 11699 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 11700 return true; 11701 }; 11702 11703 return false; 11704} 11705 11706/// \brief Mark the given method pure. 11707/// 11708/// \param Method the method to be marked pure. 11709/// 11710/// \param InitRange the source range that covers the "0" initializer. 11711bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 11712 SourceLocation EndLoc = InitRange.getEnd(); 11713 if (EndLoc.isValid()) 11714 Method->setRangeEnd(EndLoc); 11715 11716 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 11717 Method->setPure(); 11718 return false; 11719 } 11720 11721 if (!Method->isInvalidDecl()) 11722 Diag(Method->getLocation(), diag::err_non_virtual_pure) 11723 << Method->getDeclName() << InitRange; 11724 return true; 11725} 11726 11727/// \brief Determine whether the given declaration is a static data member. 11728static bool isStaticDataMember(Decl *D) { 11729 VarDecl *Var = dyn_cast_or_null<VarDecl>(D); 11730 if (!Var) 11731 return false; 11732 11733 return Var->isStaticDataMember(); 11734} 11735/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 11736/// an initializer for the out-of-line declaration 'Dcl'. The scope 11737/// is a fresh scope pushed for just this purpose. 11738/// 11739/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 11740/// static data member of class X, names should be looked up in the scope of 11741/// class X. 11742void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 11743 // If there is no declaration, there was an error parsing it. 11744 if (D == 0 || D->isInvalidDecl()) return; 11745 11746 // We should only get called for declarations with scope specifiers, like: 11747 // int foo::bar; 11748 assert(D->isOutOfLine()); 11749 EnterDeclaratorContext(S, D->getDeclContext()); 11750 11751 // If we are parsing the initializer for a static data member, push a 11752 // new expression evaluation context that is associated with this static 11753 // data member. 11754 if (isStaticDataMember(D)) 11755 PushExpressionEvaluationContext(PotentiallyEvaluated, D); 11756} 11757 11758/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 11759/// initializer for the out-of-line declaration 'D'. 11760void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 11761 // If there is no declaration, there was an error parsing it. 11762 if (D == 0 || D->isInvalidDecl()) return; 11763 11764 if (isStaticDataMember(D)) 11765 PopExpressionEvaluationContext(); 11766 11767 assert(D->isOutOfLine()); 11768 ExitDeclaratorContext(S); 11769} 11770 11771/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 11772/// C++ if/switch/while/for statement. 11773/// e.g: "if (int x = f()) {...}" 11774DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 11775 // C++ 6.4p2: 11776 // The declarator shall not specify a function or an array. 11777 // The type-specifier-seq shall not contain typedef and shall not declare a 11778 // new class or enumeration. 11779 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 11780 "Parser allowed 'typedef' as storage class of condition decl."); 11781 11782 Decl *Dcl = ActOnDeclarator(S, D); 11783 if (!Dcl) 11784 return true; 11785 11786 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 11787 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 11788 << D.getSourceRange(); 11789 return true; 11790 } 11791 11792 return Dcl; 11793} 11794 11795void Sema::LoadExternalVTableUses() { 11796 if (!ExternalSource) 11797 return; 11798 11799 SmallVector<ExternalVTableUse, 4> VTables; 11800 ExternalSource->ReadUsedVTables(VTables); 11801 SmallVector<VTableUse, 4> NewUses; 11802 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 11803 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 11804 = VTablesUsed.find(VTables[I].Record); 11805 // Even if a definition wasn't required before, it may be required now. 11806 if (Pos != VTablesUsed.end()) { 11807 if (!Pos->second && VTables[I].DefinitionRequired) 11808 Pos->second = true; 11809 continue; 11810 } 11811 11812 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 11813 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 11814 } 11815 11816 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 11817} 11818 11819void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 11820 bool DefinitionRequired) { 11821 // Ignore any vtable uses in unevaluated operands or for classes that do 11822 // not have a vtable. 11823 if (!Class->isDynamicClass() || Class->isDependentContext() || 11824 CurContext->isDependentContext() || isUnevaluatedContext()) 11825 return; 11826 11827 // Try to insert this class into the map. 11828 LoadExternalVTableUses(); 11829 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 11830 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 11831 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 11832 if (!Pos.second) { 11833 // If we already had an entry, check to see if we are promoting this vtable 11834 // to required a definition. If so, we need to reappend to the VTableUses 11835 // list, since we may have already processed the first entry. 11836 if (DefinitionRequired && !Pos.first->second) { 11837 Pos.first->second = true; 11838 } else { 11839 // Otherwise, we can early exit. 11840 return; 11841 } 11842 } 11843 11844 // Local classes need to have their virtual members marked 11845 // immediately. For all other classes, we mark their virtual members 11846 // at the end of the translation unit. 11847 if (Class->isLocalClass()) 11848 MarkVirtualMembersReferenced(Loc, Class); 11849 else 11850 VTableUses.push_back(std::make_pair(Class, Loc)); 11851} 11852 11853bool Sema::DefineUsedVTables() { 11854 LoadExternalVTableUses(); 11855 if (VTableUses.empty()) 11856 return false; 11857 11858 // Note: The VTableUses vector could grow as a result of marking 11859 // the members of a class as "used", so we check the size each 11860 // time through the loop and prefer indices (which are stable) to 11861 // iterators (which are not). 11862 bool DefinedAnything = false; 11863 for (unsigned I = 0; I != VTableUses.size(); ++I) { 11864 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 11865 if (!Class) 11866 continue; 11867 11868 SourceLocation Loc = VTableUses[I].second; 11869 11870 bool DefineVTable = true; 11871 11872 // If this class has a key function, but that key function is 11873 // defined in another translation unit, we don't need to emit the 11874 // vtable even though we're using it. 11875 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 11876 if (KeyFunction && !KeyFunction->hasBody()) { 11877 switch (KeyFunction->getTemplateSpecializationKind()) { 11878 case TSK_Undeclared: 11879 case TSK_ExplicitSpecialization: 11880 case TSK_ExplicitInstantiationDeclaration: 11881 // The key function is in another translation unit. 11882 DefineVTable = false; 11883 break; 11884 11885 case TSK_ExplicitInstantiationDefinition: 11886 case TSK_ImplicitInstantiation: 11887 // We will be instantiating the key function. 11888 break; 11889 } 11890 } else if (!KeyFunction) { 11891 // If we have a class with no key function that is the subject 11892 // of an explicit instantiation declaration, suppress the 11893 // vtable; it will live with the explicit instantiation 11894 // definition. 11895 bool IsExplicitInstantiationDeclaration 11896 = Class->getTemplateSpecializationKind() 11897 == TSK_ExplicitInstantiationDeclaration; 11898 for (TagDecl::redecl_iterator R = Class->redecls_begin(), 11899 REnd = Class->redecls_end(); 11900 R != REnd; ++R) { 11901 TemplateSpecializationKind TSK 11902 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind(); 11903 if (TSK == TSK_ExplicitInstantiationDeclaration) 11904 IsExplicitInstantiationDeclaration = true; 11905 else if (TSK == TSK_ExplicitInstantiationDefinition) { 11906 IsExplicitInstantiationDeclaration = false; 11907 break; 11908 } 11909 } 11910 11911 if (IsExplicitInstantiationDeclaration) 11912 DefineVTable = false; 11913 } 11914 11915 // The exception specifications for all virtual members may be needed even 11916 // if we are not providing an authoritative form of the vtable in this TU. 11917 // We may choose to emit it available_externally anyway. 11918 if (!DefineVTable) { 11919 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 11920 continue; 11921 } 11922 11923 // Mark all of the virtual members of this class as referenced, so 11924 // that we can build a vtable. Then, tell the AST consumer that a 11925 // vtable for this class is required. 11926 DefinedAnything = true; 11927 MarkVirtualMembersReferenced(Loc, Class); 11928 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 11929 Consumer.HandleVTable(Class, VTablesUsed[Canonical]); 11930 11931 // Optionally warn if we're emitting a weak vtable. 11932 if (Class->isExternallyVisible() && 11933 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) { 11934 const FunctionDecl *KeyFunctionDef = 0; 11935 if (!KeyFunction || 11936 (KeyFunction->hasBody(KeyFunctionDef) && 11937 KeyFunctionDef->isInlined())) 11938 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() == 11939 TSK_ExplicitInstantiationDefinition 11940 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable) 11941 << Class; 11942 } 11943 } 11944 VTableUses.clear(); 11945 11946 return DefinedAnything; 11947} 11948 11949void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 11950 const CXXRecordDecl *RD) { 11951 for (CXXRecordDecl::method_iterator I = RD->method_begin(), 11952 E = RD->method_end(); I != E; ++I) 11953 if ((*I)->isVirtual() && !(*I)->isPure()) 11954 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>()); 11955} 11956 11957void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 11958 const CXXRecordDecl *RD) { 11959 // Mark all functions which will appear in RD's vtable as used. 11960 CXXFinalOverriderMap FinalOverriders; 11961 RD->getFinalOverriders(FinalOverriders); 11962 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 11963 E = FinalOverriders.end(); 11964 I != E; ++I) { 11965 for (OverridingMethods::const_iterator OI = I->second.begin(), 11966 OE = I->second.end(); 11967 OI != OE; ++OI) { 11968 assert(OI->second.size() > 0 && "no final overrider"); 11969 CXXMethodDecl *Overrider = OI->second.front().Method; 11970 11971 // C++ [basic.def.odr]p2: 11972 // [...] A virtual member function is used if it is not pure. [...] 11973 if (!Overrider->isPure()) 11974 MarkFunctionReferenced(Loc, Overrider); 11975 } 11976 } 11977 11978 // Only classes that have virtual bases need a VTT. 11979 if (RD->getNumVBases() == 0) 11980 return; 11981 11982 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(), 11983 e = RD->bases_end(); i != e; ++i) { 11984 const CXXRecordDecl *Base = 11985 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl()); 11986 if (Base->getNumVBases() == 0) 11987 continue; 11988 MarkVirtualMembersReferenced(Loc, Base); 11989 } 11990} 11991 11992/// SetIvarInitializers - This routine builds initialization ASTs for the 11993/// Objective-C implementation whose ivars need be initialized. 11994void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 11995 if (!getLangOpts().CPlusPlus) 11996 return; 11997 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 11998 SmallVector<ObjCIvarDecl*, 8> ivars; 11999 CollectIvarsToConstructOrDestruct(OID, ivars); 12000 if (ivars.empty()) 12001 return; 12002 SmallVector<CXXCtorInitializer*, 32> AllToInit; 12003 for (unsigned i = 0; i < ivars.size(); i++) { 12004 FieldDecl *Field = ivars[i]; 12005 if (Field->isInvalidDecl()) 12006 continue; 12007 12008 CXXCtorInitializer *Member; 12009 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 12010 InitializationKind InitKind = 12011 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 12012 12013 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 12014 ExprResult MemberInit = 12015 InitSeq.Perform(*this, InitEntity, InitKind, None); 12016 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 12017 // Note, MemberInit could actually come back empty if no initialization 12018 // is required (e.g., because it would call a trivial default constructor) 12019 if (!MemberInit.get() || MemberInit.isInvalid()) 12020 continue; 12021 12022 Member = 12023 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 12024 SourceLocation(), 12025 MemberInit.takeAs<Expr>(), 12026 SourceLocation()); 12027 AllToInit.push_back(Member); 12028 12029 // Be sure that the destructor is accessible and is marked as referenced. 12030 if (const RecordType *RecordTy 12031 = Context.getBaseElementType(Field->getType()) 12032 ->getAs<RecordType>()) { 12033 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 12034 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 12035 MarkFunctionReferenced(Field->getLocation(), Destructor); 12036 CheckDestructorAccess(Field->getLocation(), Destructor, 12037 PDiag(diag::err_access_dtor_ivar) 12038 << Context.getBaseElementType(Field->getType())); 12039 } 12040 } 12041 } 12042 ObjCImplementation->setIvarInitializers(Context, 12043 AllToInit.data(), AllToInit.size()); 12044 } 12045} 12046 12047static 12048void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 12049 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid, 12050 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid, 12051 llvm::SmallSet<CXXConstructorDecl*, 4> &Current, 12052 Sema &S) { 12053 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(), 12054 CE = Current.end(); 12055 if (Ctor->isInvalidDecl()) 12056 return; 12057 12058 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 12059 12060 // Target may not be determinable yet, for instance if this is a dependent 12061 // call in an uninstantiated template. 12062 if (Target) { 12063 const FunctionDecl *FNTarget = 0; 12064 (void)Target->hasBody(FNTarget); 12065 Target = const_cast<CXXConstructorDecl*>( 12066 cast_or_null<CXXConstructorDecl>(FNTarget)); 12067 } 12068 12069 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 12070 // Avoid dereferencing a null pointer here. 12071 *TCanonical = Target ? Target->getCanonicalDecl() : 0; 12072 12073 if (!Current.insert(Canonical)) 12074 return; 12075 12076 // We know that beyond here, we aren't chaining into a cycle. 12077 if (!Target || !Target->isDelegatingConstructor() || 12078 Target->isInvalidDecl() || Valid.count(TCanonical)) { 12079 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI) 12080 Valid.insert(*CI); 12081 Current.clear(); 12082 // We've hit a cycle. 12083 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 12084 Current.count(TCanonical)) { 12085 // If we haven't diagnosed this cycle yet, do so now. 12086 if (!Invalid.count(TCanonical)) { 12087 S.Diag((*Ctor->init_begin())->getSourceLocation(), 12088 diag::warn_delegating_ctor_cycle) 12089 << Ctor; 12090 12091 // Don't add a note for a function delegating directly to itself. 12092 if (TCanonical != Canonical) 12093 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 12094 12095 CXXConstructorDecl *C = Target; 12096 while (C->getCanonicalDecl() != Canonical) { 12097 const FunctionDecl *FNTarget = 0; 12098 (void)C->getTargetConstructor()->hasBody(FNTarget); 12099 assert(FNTarget && "Ctor cycle through bodiless function"); 12100 12101 C = const_cast<CXXConstructorDecl*>( 12102 cast<CXXConstructorDecl>(FNTarget)); 12103 S.Diag(C->getLocation(), diag::note_which_delegates_to); 12104 } 12105 } 12106 12107 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI) 12108 Invalid.insert(*CI); 12109 Current.clear(); 12110 } else { 12111 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 12112 } 12113} 12114 12115 12116void Sema::CheckDelegatingCtorCycles() { 12117 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 12118 12119 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(), 12120 CE = Current.end(); 12121 12122 for (DelegatingCtorDeclsType::iterator 12123 I = DelegatingCtorDecls.begin(ExternalSource), 12124 E = DelegatingCtorDecls.end(); 12125 I != E; ++I) 12126 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 12127 12128 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI) 12129 (*CI)->setInvalidDecl(); 12130} 12131 12132namespace { 12133 /// \brief AST visitor that finds references to the 'this' expression. 12134 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 12135 Sema &S; 12136 12137 public: 12138 explicit FindCXXThisExpr(Sema &S) : S(S) { } 12139 12140 bool VisitCXXThisExpr(CXXThisExpr *E) { 12141 S.Diag(E->getLocation(), diag::err_this_static_member_func) 12142 << E->isImplicit(); 12143 return false; 12144 } 12145 }; 12146} 12147 12148bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 12149 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 12150 if (!TSInfo) 12151 return false; 12152 12153 TypeLoc TL = TSInfo->getTypeLoc(); 12154 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 12155 if (!ProtoTL) 12156 return false; 12157 12158 // C++11 [expr.prim.general]p3: 12159 // [The expression this] shall not appear before the optional 12160 // cv-qualifier-seq and it shall not appear within the declaration of a 12161 // static member function (although its type and value category are defined 12162 // within a static member function as they are within a non-static member 12163 // function). [ Note: this is because declaration matching does not occur 12164 // until the complete declarator is known. - end note ] 12165 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 12166 FindCXXThisExpr Finder(*this); 12167 12168 // If the return type came after the cv-qualifier-seq, check it now. 12169 if (Proto->hasTrailingReturn() && 12170 !Finder.TraverseTypeLoc(ProtoTL.getResultLoc())) 12171 return true; 12172 12173 // Check the exception specification. 12174 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 12175 return true; 12176 12177 return checkThisInStaticMemberFunctionAttributes(Method); 12178} 12179 12180bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 12181 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 12182 if (!TSInfo) 12183 return false; 12184 12185 TypeLoc TL = TSInfo->getTypeLoc(); 12186 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 12187 if (!ProtoTL) 12188 return false; 12189 12190 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 12191 FindCXXThisExpr Finder(*this); 12192 12193 switch (Proto->getExceptionSpecType()) { 12194 case EST_Uninstantiated: 12195 case EST_Unevaluated: 12196 case EST_BasicNoexcept: 12197 case EST_DynamicNone: 12198 case EST_MSAny: 12199 case EST_None: 12200 break; 12201 12202 case EST_ComputedNoexcept: 12203 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 12204 return true; 12205 12206 case EST_Dynamic: 12207 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(), 12208 EEnd = Proto->exception_end(); 12209 E != EEnd; ++E) { 12210 if (!Finder.TraverseType(*E)) 12211 return true; 12212 } 12213 break; 12214 } 12215 12216 return false; 12217} 12218 12219bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 12220 FindCXXThisExpr Finder(*this); 12221 12222 // Check attributes. 12223 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end(); 12224 A != AEnd; ++A) { 12225 // FIXME: This should be emitted by tblgen. 12226 Expr *Arg = 0; 12227 ArrayRef<Expr *> Args; 12228 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A)) 12229 Arg = G->getArg(); 12230 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A)) 12231 Arg = G->getArg(); 12232 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A)) 12233 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size()); 12234 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A)) 12235 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size()); 12236 else if (ExclusiveLockFunctionAttr *ELF 12237 = dyn_cast<ExclusiveLockFunctionAttr>(*A)) 12238 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size()); 12239 else if (SharedLockFunctionAttr *SLF 12240 = dyn_cast<SharedLockFunctionAttr>(*A)) 12241 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size()); 12242 else if (ExclusiveTrylockFunctionAttr *ETLF 12243 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) { 12244 Arg = ETLF->getSuccessValue(); 12245 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size()); 12246 } else if (SharedTrylockFunctionAttr *STLF 12247 = dyn_cast<SharedTrylockFunctionAttr>(*A)) { 12248 Arg = STLF->getSuccessValue(); 12249 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size()); 12250 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A)) 12251 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size()); 12252 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A)) 12253 Arg = LR->getArg(); 12254 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A)) 12255 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size()); 12256 else if (ExclusiveLocksRequiredAttr *ELR 12257 = dyn_cast<ExclusiveLocksRequiredAttr>(*A)) 12258 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size()); 12259 else if (SharedLocksRequiredAttr *SLR 12260 = dyn_cast<SharedLocksRequiredAttr>(*A)) 12261 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size()); 12262 12263 if (Arg && !Finder.TraverseStmt(Arg)) 12264 return true; 12265 12266 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 12267 if (!Finder.TraverseStmt(Args[I])) 12268 return true; 12269 } 12270 } 12271 12272 return false; 12273} 12274 12275void 12276Sema::checkExceptionSpecification(ExceptionSpecificationType EST, 12277 ArrayRef<ParsedType> DynamicExceptions, 12278 ArrayRef<SourceRange> DynamicExceptionRanges, 12279 Expr *NoexceptExpr, 12280 SmallVectorImpl<QualType> &Exceptions, 12281 FunctionProtoType::ExtProtoInfo &EPI) { 12282 Exceptions.clear(); 12283 EPI.ExceptionSpecType = EST; 12284 if (EST == EST_Dynamic) { 12285 Exceptions.reserve(DynamicExceptions.size()); 12286 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 12287 // FIXME: Preserve type source info. 12288 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 12289 12290 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 12291 collectUnexpandedParameterPacks(ET, Unexpanded); 12292 if (!Unexpanded.empty()) { 12293 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(), 12294 UPPC_ExceptionType, 12295 Unexpanded); 12296 continue; 12297 } 12298 12299 // Check that the type is valid for an exception spec, and 12300 // drop it if not. 12301 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 12302 Exceptions.push_back(ET); 12303 } 12304 EPI.NumExceptions = Exceptions.size(); 12305 EPI.Exceptions = Exceptions.data(); 12306 return; 12307 } 12308 12309 if (EST == EST_ComputedNoexcept) { 12310 // If an error occurred, there's no expression here. 12311 if (NoexceptExpr) { 12312 assert((NoexceptExpr->isTypeDependent() || 12313 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 12314 Context.BoolTy) && 12315 "Parser should have made sure that the expression is boolean"); 12316 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 12317 EPI.ExceptionSpecType = EST_BasicNoexcept; 12318 return; 12319 } 12320 12321 if (!NoexceptExpr->isValueDependent()) 12322 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0, 12323 diag::err_noexcept_needs_constant_expression, 12324 /*AllowFold*/ false).take(); 12325 EPI.NoexceptExpr = NoexceptExpr; 12326 } 12327 return; 12328 } 12329} 12330 12331/// IdentifyCUDATarget - Determine the CUDA compilation target for this function 12332Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) { 12333 // Implicitly declared functions (e.g. copy constructors) are 12334 // __host__ __device__ 12335 if (D->isImplicit()) 12336 return CFT_HostDevice; 12337 12338 if (D->hasAttr<CUDAGlobalAttr>()) 12339 return CFT_Global; 12340 12341 if (D->hasAttr<CUDADeviceAttr>()) { 12342 if (D->hasAttr<CUDAHostAttr>()) 12343 return CFT_HostDevice; 12344 else 12345 return CFT_Device; 12346 } 12347 12348 return CFT_Host; 12349} 12350 12351bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget, 12352 CUDAFunctionTarget CalleeTarget) { 12353 // CUDA B.1.1 "The __device__ qualifier declares a function that is... 12354 // Callable from the device only." 12355 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device) 12356 return true; 12357 12358 // CUDA B.1.2 "The __global__ qualifier declares a function that is... 12359 // Callable from the host only." 12360 // CUDA B.1.3 "The __host__ qualifier declares a function that is... 12361 // Callable from the host only." 12362 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) && 12363 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global)) 12364 return true; 12365 12366 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice) 12367 return true; 12368 12369 return false; 12370} 12371 12372/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 12373/// 12374MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 12375 SourceLocation DeclStart, 12376 Declarator &D, Expr *BitWidth, 12377 InClassInitStyle InitStyle, 12378 AccessSpecifier AS, 12379 AttributeList *MSPropertyAttr) { 12380 IdentifierInfo *II = D.getIdentifier(); 12381 if (!II) { 12382 Diag(DeclStart, diag::err_anonymous_property); 12383 return NULL; 12384 } 12385 SourceLocation Loc = D.getIdentifierLoc(); 12386 12387 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12388 QualType T = TInfo->getType(); 12389 if (getLangOpts().CPlusPlus) { 12390 CheckExtraCXXDefaultArguments(D); 12391 12392 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 12393 UPPC_DataMemberType)) { 12394 D.setInvalidType(); 12395 T = Context.IntTy; 12396 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 12397 } 12398 } 12399 12400 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 12401 12402 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 12403 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 12404 diag::err_invalid_thread) 12405 << DeclSpec::getSpecifierName(TSCS); 12406 12407 // Check to see if this name was declared as a member previously 12408 NamedDecl *PrevDecl = 0; 12409 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 12410 LookupName(Previous, S); 12411 switch (Previous.getResultKind()) { 12412 case LookupResult::Found: 12413 case LookupResult::FoundUnresolvedValue: 12414 PrevDecl = Previous.getAsSingle<NamedDecl>(); 12415 break; 12416 12417 case LookupResult::FoundOverloaded: 12418 PrevDecl = Previous.getRepresentativeDecl(); 12419 break; 12420 12421 case LookupResult::NotFound: 12422 case LookupResult::NotFoundInCurrentInstantiation: 12423 case LookupResult::Ambiguous: 12424 break; 12425 } 12426 12427 if (PrevDecl && PrevDecl->isTemplateParameter()) { 12428 // Maybe we will complain about the shadowed template parameter. 12429 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 12430 // Just pretend that we didn't see the previous declaration. 12431 PrevDecl = 0; 12432 } 12433 12434 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 12435 PrevDecl = 0; 12436 12437 SourceLocation TSSL = D.getLocStart(); 12438 MSPropertyDecl *NewPD; 12439 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData(); 12440 NewPD = new (Context) MSPropertyDecl(Record, Loc, 12441 II, T, TInfo, TSSL, 12442 Data.GetterId, Data.SetterId); 12443 ProcessDeclAttributes(TUScope, NewPD, D); 12444 NewPD->setAccess(AS); 12445 12446 if (NewPD->isInvalidDecl()) 12447 Record->setInvalidDecl(); 12448 12449 if (D.getDeclSpec().isModulePrivateSpecified()) 12450 NewPD->setModulePrivate(); 12451 12452 if (NewPD->isInvalidDecl() && PrevDecl) { 12453 // Don't introduce NewFD into scope; there's already something 12454 // with the same name in the same scope. 12455 } else if (II) { 12456 PushOnScopeChains(NewPD, S); 12457 } else 12458 Record->addDecl(NewPD); 12459 12460 return NewPD; 12461} 12462