SemaDeclCXX.cpp revision 383616cd2e61131a534afd9364ef53f643e1f834
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/Sema/CXXFieldCollector.h" 16#include "clang/Sema/Scope.h" 17#include "clang/Sema/Initialization.h" 18#include "clang/Sema/Lookup.h" 19#include "clang/AST/ASTConsumer.h" 20#include "clang/AST/ASTContext.h" 21#include "clang/AST/ASTMutationListener.h" 22#include "clang/AST/CharUnits.h" 23#include "clang/AST/CXXInheritance.h" 24#include "clang/AST/DeclVisitor.h" 25#include "clang/AST/ExprCXX.h" 26#include "clang/AST/RecordLayout.h" 27#include "clang/AST/StmtVisitor.h" 28#include "clang/AST/TypeLoc.h" 29#include "clang/AST/TypeOrdering.h" 30#include "clang/Sema/DeclSpec.h" 31#include "clang/Sema/ParsedTemplate.h" 32#include "clang/Basic/PartialDiagnostic.h" 33#include "clang/Lex/Preprocessor.h" 34#include "llvm/ADT/DenseSet.h" 35#include "llvm/ADT/STLExtras.h" 36#include <map> 37#include <set> 38 39using namespace clang; 40 41//===----------------------------------------------------------------------===// 42// CheckDefaultArgumentVisitor 43//===----------------------------------------------------------------------===// 44 45namespace { 46 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 47 /// the default argument of a parameter to determine whether it 48 /// contains any ill-formed subexpressions. For example, this will 49 /// diagnose the use of local variables or parameters within the 50 /// default argument expression. 51 class CheckDefaultArgumentVisitor 52 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 53 Expr *DefaultArg; 54 Sema *S; 55 56 public: 57 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 58 : DefaultArg(defarg), S(s) {} 59 60 bool VisitExpr(Expr *Node); 61 bool VisitDeclRefExpr(DeclRefExpr *DRE); 62 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 63 }; 64 65 /// VisitExpr - Visit all of the children of this expression. 66 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 67 bool IsInvalid = false; 68 for (Stmt::child_range I = Node->children(); I; ++I) 69 IsInvalid |= Visit(*I); 70 return IsInvalid; 71 } 72 73 /// VisitDeclRefExpr - Visit a reference to a declaration, to 74 /// determine whether this declaration can be used in the default 75 /// argument expression. 76 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 77 NamedDecl *Decl = DRE->getDecl(); 78 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 79 // C++ [dcl.fct.default]p9 80 // Default arguments are evaluated each time the function is 81 // called. The order of evaluation of function arguments is 82 // unspecified. Consequently, parameters of a function shall not 83 // be used in default argument expressions, even if they are not 84 // evaluated. Parameters of a function declared before a default 85 // argument expression are in scope and can hide namespace and 86 // class member names. 87 return S->Diag(DRE->getSourceRange().getBegin(), 88 diag::err_param_default_argument_references_param) 89 << Param->getDeclName() << DefaultArg->getSourceRange(); 90 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 91 // C++ [dcl.fct.default]p7 92 // Local variables shall not be used in default argument 93 // expressions. 94 if (VDecl->isLocalVarDecl()) 95 return S->Diag(DRE->getSourceRange().getBegin(), 96 diag::err_param_default_argument_references_local) 97 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 98 } 99 100 return false; 101 } 102 103 /// VisitCXXThisExpr - Visit a C++ "this" expression. 104 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 105 // C++ [dcl.fct.default]p8: 106 // The keyword this shall not be used in a default argument of a 107 // member function. 108 return S->Diag(ThisE->getSourceRange().getBegin(), 109 diag::err_param_default_argument_references_this) 110 << ThisE->getSourceRange(); 111 } 112} 113 114void Sema::ImplicitExceptionSpecification::CalledDecl(CXXMethodDecl *Method) { 115 assert(Context && "ImplicitExceptionSpecification without an ASTContext"); 116 // If we have an MSAny spec already, don't bother. 117 if (!Method || ComputedEST == EST_MSAny) 118 return; 119 120 const FunctionProtoType *Proto 121 = Method->getType()->getAs<FunctionProtoType>(); 122 123 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 124 125 // If this function can throw any exceptions, make a note of that. 126 if (EST == EST_MSAny || EST == EST_None) { 127 ClearExceptions(); 128 ComputedEST = EST; 129 return; 130 } 131 132 // If this function has a basic noexcept, it doesn't affect the outcome. 133 if (EST == EST_BasicNoexcept) 134 return; 135 136 // If we have a throw-all spec at this point, ignore the function. 137 if (ComputedEST == EST_None) 138 return; 139 140 // If we're still at noexcept(true) and there's a nothrow() callee, 141 // change to that specification. 142 if (EST == EST_DynamicNone) { 143 if (ComputedEST == EST_BasicNoexcept) 144 ComputedEST = EST_DynamicNone; 145 return; 146 } 147 148 // Check out noexcept specs. 149 if (EST == EST_ComputedNoexcept) { 150 FunctionProtoType::NoexceptResult NR = Proto->getNoexceptSpec(*Context); 151 assert(NR != FunctionProtoType::NR_NoNoexcept && 152 "Must have noexcept result for EST_ComputedNoexcept."); 153 assert(NR != FunctionProtoType::NR_Dependent && 154 "Should not generate implicit declarations for dependent cases, " 155 "and don't know how to handle them anyway."); 156 157 // noexcept(false) -> no spec on the new function 158 if (NR == FunctionProtoType::NR_Throw) { 159 ClearExceptions(); 160 ComputedEST = EST_None; 161 } 162 // noexcept(true) won't change anything either. 163 return; 164 } 165 166 assert(EST == EST_Dynamic && "EST case not considered earlier."); 167 assert(ComputedEST != EST_None && 168 "Shouldn't collect exceptions when throw-all is guaranteed."); 169 ComputedEST = EST_Dynamic; 170 // Record the exceptions in this function's exception specification. 171 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(), 172 EEnd = Proto->exception_end(); 173 E != EEnd; ++E) 174 if (ExceptionsSeen.insert(Context->getCanonicalType(*E))) 175 Exceptions.push_back(*E); 176} 177 178bool 179Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 180 SourceLocation EqualLoc) { 181 if (RequireCompleteType(Param->getLocation(), Param->getType(), 182 diag::err_typecheck_decl_incomplete_type)) { 183 Param->setInvalidDecl(); 184 return true; 185 } 186 187 // C++ [dcl.fct.default]p5 188 // A default argument expression is implicitly converted (clause 189 // 4) to the parameter type. The default argument expression has 190 // the same semantic constraints as the initializer expression in 191 // a declaration of a variable of the parameter type, using the 192 // copy-initialization semantics (8.5). 193 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 194 Param); 195 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 196 EqualLoc); 197 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1); 198 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, 199 MultiExprArg(*this, &Arg, 1)); 200 if (Result.isInvalid()) 201 return true; 202 Arg = Result.takeAs<Expr>(); 203 204 CheckImplicitConversions(Arg, EqualLoc); 205 Arg = MaybeCreateExprWithCleanups(Arg); 206 207 // Okay: add the default argument to the parameter 208 Param->setDefaultArg(Arg); 209 210 // We have already instantiated this parameter; provide each of the 211 // instantiations with the uninstantiated default argument. 212 UnparsedDefaultArgInstantiationsMap::iterator InstPos 213 = UnparsedDefaultArgInstantiations.find(Param); 214 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 215 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 216 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 217 218 // We're done tracking this parameter's instantiations. 219 UnparsedDefaultArgInstantiations.erase(InstPos); 220 } 221 222 return false; 223} 224 225/// ActOnParamDefaultArgument - Check whether the default argument 226/// provided for a function parameter is well-formed. If so, attach it 227/// to the parameter declaration. 228void 229Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 230 Expr *DefaultArg) { 231 if (!param || !DefaultArg) 232 return; 233 234 ParmVarDecl *Param = cast<ParmVarDecl>(param); 235 UnparsedDefaultArgLocs.erase(Param); 236 237 // Default arguments are only permitted in C++ 238 if (!getLangOptions().CPlusPlus) { 239 Diag(EqualLoc, diag::err_param_default_argument) 240 << DefaultArg->getSourceRange(); 241 Param->setInvalidDecl(); 242 return; 243 } 244 245 // Check for unexpanded parameter packs. 246 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 247 Param->setInvalidDecl(); 248 return; 249 } 250 251 // Check that the default argument is well-formed 252 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this); 253 if (DefaultArgChecker.Visit(DefaultArg)) { 254 Param->setInvalidDecl(); 255 return; 256 } 257 258 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 259} 260 261/// ActOnParamUnparsedDefaultArgument - We've seen a default 262/// argument for a function parameter, but we can't parse it yet 263/// because we're inside a class definition. Note that this default 264/// argument will be parsed later. 265void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 266 SourceLocation EqualLoc, 267 SourceLocation ArgLoc) { 268 if (!param) 269 return; 270 271 ParmVarDecl *Param = cast<ParmVarDecl>(param); 272 if (Param) 273 Param->setUnparsedDefaultArg(); 274 275 UnparsedDefaultArgLocs[Param] = ArgLoc; 276} 277 278/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 279/// the default argument for the parameter param failed. 280void Sema::ActOnParamDefaultArgumentError(Decl *param) { 281 if (!param) 282 return; 283 284 ParmVarDecl *Param = cast<ParmVarDecl>(param); 285 286 Param->setInvalidDecl(); 287 288 UnparsedDefaultArgLocs.erase(Param); 289} 290 291/// CheckExtraCXXDefaultArguments - Check for any extra default 292/// arguments in the declarator, which is not a function declaration 293/// or definition and therefore is not permitted to have default 294/// arguments. This routine should be invoked for every declarator 295/// that is not a function declaration or definition. 296void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 297 // C++ [dcl.fct.default]p3 298 // A default argument expression shall be specified only in the 299 // parameter-declaration-clause of a function declaration or in a 300 // template-parameter (14.1). It shall not be specified for a 301 // parameter pack. If it is specified in a 302 // parameter-declaration-clause, it shall not occur within a 303 // declarator or abstract-declarator of a parameter-declaration. 304 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 305 DeclaratorChunk &chunk = D.getTypeObject(i); 306 if (chunk.Kind == DeclaratorChunk::Function) { 307 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) { 308 ParmVarDecl *Param = 309 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param); 310 if (Param->hasUnparsedDefaultArg()) { 311 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens; 312 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 313 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation()); 314 delete Toks; 315 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0; 316 } else if (Param->getDefaultArg()) { 317 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 318 << Param->getDefaultArg()->getSourceRange(); 319 Param->setDefaultArg(0); 320 } 321 } 322 } 323 } 324} 325 326// MergeCXXFunctionDecl - Merge two declarations of the same C++ 327// function, once we already know that they have the same 328// type. Subroutine of MergeFunctionDecl. Returns true if there was an 329// error, false otherwise. 330bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) { 331 bool Invalid = false; 332 333 // C++ [dcl.fct.default]p4: 334 // For non-template functions, default arguments can be added in 335 // later declarations of a function in the same 336 // scope. Declarations in different scopes have completely 337 // distinct sets of default arguments. That is, declarations in 338 // inner scopes do not acquire default arguments from 339 // declarations in outer scopes, and vice versa. In a given 340 // function declaration, all parameters subsequent to a 341 // parameter with a default argument shall have default 342 // arguments supplied in this or previous declarations. A 343 // default argument shall not be redefined by a later 344 // declaration (not even to the same value). 345 // 346 // C++ [dcl.fct.default]p6: 347 // Except for member functions of class templates, the default arguments 348 // in a member function definition that appears outside of the class 349 // definition are added to the set of default arguments provided by the 350 // member function declaration in the class definition. 351 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 352 ParmVarDecl *OldParam = Old->getParamDecl(p); 353 ParmVarDecl *NewParam = New->getParamDecl(p); 354 355 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) { 356 357 unsigned DiagDefaultParamID = 358 diag::err_param_default_argument_redefinition; 359 360 // MSVC accepts that default parameters be redefined for member functions 361 // of template class. The new default parameter's value is ignored. 362 Invalid = true; 363 if (getLangOptions().Microsoft) { 364 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New); 365 if (MD && MD->getParent()->getDescribedClassTemplate()) { 366 // Merge the old default argument into the new parameter. 367 NewParam->setHasInheritedDefaultArg(); 368 if (OldParam->hasUninstantiatedDefaultArg()) 369 NewParam->setUninstantiatedDefaultArg( 370 OldParam->getUninstantiatedDefaultArg()); 371 else 372 NewParam->setDefaultArg(OldParam->getInit()); 373 DiagDefaultParamID = diag::warn_param_default_argument_redefinition; 374 Invalid = false; 375 } 376 } 377 378 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 379 // hint here. Alternatively, we could walk the type-source information 380 // for NewParam to find the last source location in the type... but it 381 // isn't worth the effort right now. This is the kind of test case that 382 // is hard to get right: 383 // int f(int); 384 // void g(int (*fp)(int) = f); 385 // void g(int (*fp)(int) = &f); 386 Diag(NewParam->getLocation(), DiagDefaultParamID) 387 << NewParam->getDefaultArgRange(); 388 389 // Look for the function declaration where the default argument was 390 // actually written, which may be a declaration prior to Old. 391 for (FunctionDecl *Older = Old->getPreviousDeclaration(); 392 Older; Older = Older->getPreviousDeclaration()) { 393 if (!Older->getParamDecl(p)->hasDefaultArg()) 394 break; 395 396 OldParam = Older->getParamDecl(p); 397 } 398 399 Diag(OldParam->getLocation(), diag::note_previous_definition) 400 << OldParam->getDefaultArgRange(); 401 } else if (OldParam->hasDefaultArg()) { 402 // Merge the old default argument into the new parameter. 403 // It's important to use getInit() here; getDefaultArg() 404 // strips off any top-level ExprWithCleanups. 405 NewParam->setHasInheritedDefaultArg(); 406 if (OldParam->hasUninstantiatedDefaultArg()) 407 NewParam->setUninstantiatedDefaultArg( 408 OldParam->getUninstantiatedDefaultArg()); 409 else 410 NewParam->setDefaultArg(OldParam->getInit()); 411 } else if (NewParam->hasDefaultArg()) { 412 if (New->getDescribedFunctionTemplate()) { 413 // Paragraph 4, quoted above, only applies to non-template functions. 414 Diag(NewParam->getLocation(), 415 diag::err_param_default_argument_template_redecl) 416 << NewParam->getDefaultArgRange(); 417 Diag(Old->getLocation(), diag::note_template_prev_declaration) 418 << false; 419 } else if (New->getTemplateSpecializationKind() 420 != TSK_ImplicitInstantiation && 421 New->getTemplateSpecializationKind() != TSK_Undeclared) { 422 // C++ [temp.expr.spec]p21: 423 // Default function arguments shall not be specified in a declaration 424 // or a definition for one of the following explicit specializations: 425 // - the explicit specialization of a function template; 426 // - the explicit specialization of a member function template; 427 // - the explicit specialization of a member function of a class 428 // template where the class template specialization to which the 429 // member function specialization belongs is implicitly 430 // instantiated. 431 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 432 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 433 << New->getDeclName() 434 << NewParam->getDefaultArgRange(); 435 } else if (New->getDeclContext()->isDependentContext()) { 436 // C++ [dcl.fct.default]p6 (DR217): 437 // Default arguments for a member function of a class template shall 438 // be specified on the initial declaration of the member function 439 // within the class template. 440 // 441 // Reading the tea leaves a bit in DR217 and its reference to DR205 442 // leads me to the conclusion that one cannot add default function 443 // arguments for an out-of-line definition of a member function of a 444 // dependent type. 445 int WhichKind = 2; 446 if (CXXRecordDecl *Record 447 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 448 if (Record->getDescribedClassTemplate()) 449 WhichKind = 0; 450 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 451 WhichKind = 1; 452 else 453 WhichKind = 2; 454 } 455 456 Diag(NewParam->getLocation(), 457 diag::err_param_default_argument_member_template_redecl) 458 << WhichKind 459 << NewParam->getDefaultArgRange(); 460 } else if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(New)) { 461 CXXSpecialMember NewSM = getSpecialMember(Ctor), 462 OldSM = getSpecialMember(cast<CXXConstructorDecl>(Old)); 463 if (NewSM != OldSM) { 464 Diag(NewParam->getLocation(),diag::warn_default_arg_makes_ctor_special) 465 << NewParam->getDefaultArgRange() << NewSM; 466 Diag(Old->getLocation(), diag::note_previous_declaration_special) 467 << OldSM; 468 } 469 } 470 } 471 } 472 473 if (CheckEquivalentExceptionSpec(Old, New)) 474 Invalid = true; 475 476 return Invalid; 477} 478 479/// \brief Merge the exception specifications of two variable declarations. 480/// 481/// This is called when there's a redeclaration of a VarDecl. The function 482/// checks if the redeclaration might have an exception specification and 483/// validates compatibility and merges the specs if necessary. 484void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 485 // Shortcut if exceptions are disabled. 486 if (!getLangOptions().CXXExceptions) 487 return; 488 489 assert(Context.hasSameType(New->getType(), Old->getType()) && 490 "Should only be called if types are otherwise the same."); 491 492 QualType NewType = New->getType(); 493 QualType OldType = Old->getType(); 494 495 // We're only interested in pointers and references to functions, as well 496 // as pointers to member functions. 497 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 498 NewType = R->getPointeeType(); 499 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 500 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 501 NewType = P->getPointeeType(); 502 OldType = OldType->getAs<PointerType>()->getPointeeType(); 503 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 504 NewType = M->getPointeeType(); 505 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 506 } 507 508 if (!NewType->isFunctionProtoType()) 509 return; 510 511 // There's lots of special cases for functions. For function pointers, system 512 // libraries are hopefully not as broken so that we don't need these 513 // workarounds. 514 if (CheckEquivalentExceptionSpec( 515 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 516 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 517 New->setInvalidDecl(); 518 } 519} 520 521/// CheckCXXDefaultArguments - Verify that the default arguments for a 522/// function declaration are well-formed according to C++ 523/// [dcl.fct.default]. 524void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 525 unsigned NumParams = FD->getNumParams(); 526 unsigned p; 527 528 // Find first parameter with a default argument 529 for (p = 0; p < NumParams; ++p) { 530 ParmVarDecl *Param = FD->getParamDecl(p); 531 if (Param->hasDefaultArg()) 532 break; 533 } 534 535 // C++ [dcl.fct.default]p4: 536 // In a given function declaration, all parameters 537 // subsequent to a parameter with a default argument shall 538 // have default arguments supplied in this or previous 539 // declarations. A default argument shall not be redefined 540 // by a later declaration (not even to the same value). 541 unsigned LastMissingDefaultArg = 0; 542 for (; p < NumParams; ++p) { 543 ParmVarDecl *Param = FD->getParamDecl(p); 544 if (!Param->hasDefaultArg()) { 545 if (Param->isInvalidDecl()) 546 /* We already complained about this parameter. */; 547 else if (Param->getIdentifier()) 548 Diag(Param->getLocation(), 549 diag::err_param_default_argument_missing_name) 550 << Param->getIdentifier(); 551 else 552 Diag(Param->getLocation(), 553 diag::err_param_default_argument_missing); 554 555 LastMissingDefaultArg = p; 556 } 557 } 558 559 if (LastMissingDefaultArg > 0) { 560 // Some default arguments were missing. Clear out all of the 561 // default arguments up to (and including) the last missing 562 // default argument, so that we leave the function parameters 563 // in a semantically valid state. 564 for (p = 0; p <= LastMissingDefaultArg; ++p) { 565 ParmVarDecl *Param = FD->getParamDecl(p); 566 if (Param->hasDefaultArg()) { 567 Param->setDefaultArg(0); 568 } 569 } 570 } 571} 572 573/// isCurrentClassName - Determine whether the identifier II is the 574/// name of the class type currently being defined. In the case of 575/// nested classes, this will only return true if II is the name of 576/// the innermost class. 577bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 578 const CXXScopeSpec *SS) { 579 assert(getLangOptions().CPlusPlus && "No class names in C!"); 580 581 CXXRecordDecl *CurDecl; 582 if (SS && SS->isSet() && !SS->isInvalid()) { 583 DeclContext *DC = computeDeclContext(*SS, true); 584 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 585 } else 586 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 587 588 if (CurDecl && CurDecl->getIdentifier()) 589 return &II == CurDecl->getIdentifier(); 590 else 591 return false; 592} 593 594/// \brief Check the validity of a C++ base class specifier. 595/// 596/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 597/// and returns NULL otherwise. 598CXXBaseSpecifier * 599Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 600 SourceRange SpecifierRange, 601 bool Virtual, AccessSpecifier Access, 602 TypeSourceInfo *TInfo, 603 SourceLocation EllipsisLoc) { 604 QualType BaseType = TInfo->getType(); 605 606 // C++ [class.union]p1: 607 // A union shall not have base classes. 608 if (Class->isUnion()) { 609 Diag(Class->getLocation(), diag::err_base_clause_on_union) 610 << SpecifierRange; 611 return 0; 612 } 613 614 if (EllipsisLoc.isValid() && 615 !TInfo->getType()->containsUnexpandedParameterPack()) { 616 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 617 << TInfo->getTypeLoc().getSourceRange(); 618 EllipsisLoc = SourceLocation(); 619 } 620 621 if (BaseType->isDependentType()) 622 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 623 Class->getTagKind() == TTK_Class, 624 Access, TInfo, EllipsisLoc); 625 626 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 627 628 // Base specifiers must be record types. 629 if (!BaseType->isRecordType()) { 630 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 631 return 0; 632 } 633 634 // C++ [class.union]p1: 635 // A union shall not be used as a base class. 636 if (BaseType->isUnionType()) { 637 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 638 return 0; 639 } 640 641 // C++ [class.derived]p2: 642 // The class-name in a base-specifier shall not be an incompletely 643 // defined class. 644 if (RequireCompleteType(BaseLoc, BaseType, 645 PDiag(diag::err_incomplete_base_class) 646 << SpecifierRange)) { 647 Class->setInvalidDecl(); 648 return 0; 649 } 650 651 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 652 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 653 assert(BaseDecl && "Record type has no declaration"); 654 BaseDecl = BaseDecl->getDefinition(); 655 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 656 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 657 assert(CXXBaseDecl && "Base type is not a C++ type"); 658 659 // C++ [class]p3: 660 // If a class is marked final and it appears as a base-type-specifier in 661 // base-clause, the program is ill-formed. 662 if (CXXBaseDecl->hasAttr<FinalAttr>()) { 663 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 664 << CXXBaseDecl->getDeclName(); 665 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl) 666 << CXXBaseDecl->getDeclName(); 667 return 0; 668 } 669 670 if (BaseDecl->isInvalidDecl()) 671 Class->setInvalidDecl(); 672 673 // Create the base specifier. 674 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 675 Class->getTagKind() == TTK_Class, 676 Access, TInfo, EllipsisLoc); 677} 678 679/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 680/// one entry in the base class list of a class specifier, for 681/// example: 682/// class foo : public bar, virtual private baz { 683/// 'public bar' and 'virtual private baz' are each base-specifiers. 684BaseResult 685Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 686 bool Virtual, AccessSpecifier Access, 687 ParsedType basetype, SourceLocation BaseLoc, 688 SourceLocation EllipsisLoc) { 689 if (!classdecl) 690 return true; 691 692 AdjustDeclIfTemplate(classdecl); 693 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 694 if (!Class) 695 return true; 696 697 TypeSourceInfo *TInfo = 0; 698 GetTypeFromParser(basetype, &TInfo); 699 700 if (EllipsisLoc.isInvalid() && 701 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 702 UPPC_BaseType)) 703 return true; 704 705 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 706 Virtual, Access, TInfo, 707 EllipsisLoc)) 708 return BaseSpec; 709 710 return true; 711} 712 713/// \brief Performs the actual work of attaching the given base class 714/// specifiers to a C++ class. 715bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 716 unsigned NumBases) { 717 if (NumBases == 0) 718 return false; 719 720 // Used to keep track of which base types we have already seen, so 721 // that we can properly diagnose redundant direct base types. Note 722 // that the key is always the unqualified canonical type of the base 723 // class. 724 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 725 726 // Copy non-redundant base specifiers into permanent storage. 727 unsigned NumGoodBases = 0; 728 bool Invalid = false; 729 for (unsigned idx = 0; idx < NumBases; ++idx) { 730 QualType NewBaseType 731 = Context.getCanonicalType(Bases[idx]->getType()); 732 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 733 if (!Class->hasObjectMember()) { 734 if (const RecordType *FDTTy = 735 NewBaseType.getTypePtr()->getAs<RecordType>()) 736 if (FDTTy->getDecl()->hasObjectMember()) 737 Class->setHasObjectMember(true); 738 } 739 740 if (KnownBaseTypes[NewBaseType]) { 741 // C++ [class.mi]p3: 742 // A class shall not be specified as a direct base class of a 743 // derived class more than once. 744 Diag(Bases[idx]->getSourceRange().getBegin(), 745 diag::err_duplicate_base_class) 746 << KnownBaseTypes[NewBaseType]->getType() 747 << Bases[idx]->getSourceRange(); 748 749 // Delete the duplicate base class specifier; we're going to 750 // overwrite its pointer later. 751 Context.Deallocate(Bases[idx]); 752 753 Invalid = true; 754 } else { 755 // Okay, add this new base class. 756 KnownBaseTypes[NewBaseType] = Bases[idx]; 757 Bases[NumGoodBases++] = Bases[idx]; 758 } 759 } 760 761 // Attach the remaining base class specifiers to the derived class. 762 Class->setBases(Bases, NumGoodBases); 763 764 // Delete the remaining (good) base class specifiers, since their 765 // data has been copied into the CXXRecordDecl. 766 for (unsigned idx = 0; idx < NumGoodBases; ++idx) 767 Context.Deallocate(Bases[idx]); 768 769 return Invalid; 770} 771 772/// ActOnBaseSpecifiers - Attach the given base specifiers to the 773/// class, after checking whether there are any duplicate base 774/// classes. 775void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases, 776 unsigned NumBases) { 777 if (!ClassDecl || !Bases || !NumBases) 778 return; 779 780 AdjustDeclIfTemplate(ClassDecl); 781 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), 782 (CXXBaseSpecifier**)(Bases), NumBases); 783} 784 785static CXXRecordDecl *GetClassForType(QualType T) { 786 if (const RecordType *RT = T->getAs<RecordType>()) 787 return cast<CXXRecordDecl>(RT->getDecl()); 788 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>()) 789 return ICT->getDecl(); 790 else 791 return 0; 792} 793 794/// \brief Determine whether the type \p Derived is a C++ class that is 795/// derived from the type \p Base. 796bool Sema::IsDerivedFrom(QualType Derived, QualType Base) { 797 if (!getLangOptions().CPlusPlus) 798 return false; 799 800 CXXRecordDecl *DerivedRD = GetClassForType(Derived); 801 if (!DerivedRD) 802 return false; 803 804 CXXRecordDecl *BaseRD = GetClassForType(Base); 805 if (!BaseRD) 806 return false; 807 808 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this. 809 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD); 810} 811 812/// \brief Determine whether the type \p Derived is a C++ class that is 813/// derived from the type \p Base. 814bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) { 815 if (!getLangOptions().CPlusPlus) 816 return false; 817 818 CXXRecordDecl *DerivedRD = GetClassForType(Derived); 819 if (!DerivedRD) 820 return false; 821 822 CXXRecordDecl *BaseRD = GetClassForType(Base); 823 if (!BaseRD) 824 return false; 825 826 return DerivedRD->isDerivedFrom(BaseRD, Paths); 827} 828 829void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 830 CXXCastPath &BasePathArray) { 831 assert(BasePathArray.empty() && "Base path array must be empty!"); 832 assert(Paths.isRecordingPaths() && "Must record paths!"); 833 834 const CXXBasePath &Path = Paths.front(); 835 836 // We first go backward and check if we have a virtual base. 837 // FIXME: It would be better if CXXBasePath had the base specifier for 838 // the nearest virtual base. 839 unsigned Start = 0; 840 for (unsigned I = Path.size(); I != 0; --I) { 841 if (Path[I - 1].Base->isVirtual()) { 842 Start = I - 1; 843 break; 844 } 845 } 846 847 // Now add all bases. 848 for (unsigned I = Start, E = Path.size(); I != E; ++I) 849 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 850} 851 852/// \brief Determine whether the given base path includes a virtual 853/// base class. 854bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) { 855 for (CXXCastPath::const_iterator B = BasePath.begin(), 856 BEnd = BasePath.end(); 857 B != BEnd; ++B) 858 if ((*B)->isVirtual()) 859 return true; 860 861 return false; 862} 863 864/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 865/// conversion (where Derived and Base are class types) is 866/// well-formed, meaning that the conversion is unambiguous (and 867/// that all of the base classes are accessible). Returns true 868/// and emits a diagnostic if the code is ill-formed, returns false 869/// otherwise. Loc is the location where this routine should point to 870/// if there is an error, and Range is the source range to highlight 871/// if there is an error. 872bool 873Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 874 unsigned InaccessibleBaseID, 875 unsigned AmbigiousBaseConvID, 876 SourceLocation Loc, SourceRange Range, 877 DeclarationName Name, 878 CXXCastPath *BasePath) { 879 // First, determine whether the path from Derived to Base is 880 // ambiguous. This is slightly more expensive than checking whether 881 // the Derived to Base conversion exists, because here we need to 882 // explore multiple paths to determine if there is an ambiguity. 883 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 884 /*DetectVirtual=*/false); 885 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths); 886 assert(DerivationOkay && 887 "Can only be used with a derived-to-base conversion"); 888 (void)DerivationOkay; 889 890 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 891 if (InaccessibleBaseID) { 892 // Check that the base class can be accessed. 893 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(), 894 InaccessibleBaseID)) { 895 case AR_inaccessible: 896 return true; 897 case AR_accessible: 898 case AR_dependent: 899 case AR_delayed: 900 break; 901 } 902 } 903 904 // Build a base path if necessary. 905 if (BasePath) 906 BuildBasePathArray(Paths, *BasePath); 907 return false; 908 } 909 910 // We know that the derived-to-base conversion is ambiguous, and 911 // we're going to produce a diagnostic. Perform the derived-to-base 912 // search just one more time to compute all of the possible paths so 913 // that we can print them out. This is more expensive than any of 914 // the previous derived-to-base checks we've done, but at this point 915 // performance isn't as much of an issue. 916 Paths.clear(); 917 Paths.setRecordingPaths(true); 918 bool StillOkay = IsDerivedFrom(Derived, Base, Paths); 919 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 920 (void)StillOkay; 921 922 // Build up a textual representation of the ambiguous paths, e.g., 923 // D -> B -> A, that will be used to illustrate the ambiguous 924 // conversions in the diagnostic. We only print one of the paths 925 // to each base class subobject. 926 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 927 928 Diag(Loc, AmbigiousBaseConvID) 929 << Derived << Base << PathDisplayStr << Range << Name; 930 return true; 931} 932 933bool 934Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 935 SourceLocation Loc, SourceRange Range, 936 CXXCastPath *BasePath, 937 bool IgnoreAccess) { 938 return CheckDerivedToBaseConversion(Derived, Base, 939 IgnoreAccess ? 0 940 : diag::err_upcast_to_inaccessible_base, 941 diag::err_ambiguous_derived_to_base_conv, 942 Loc, Range, DeclarationName(), 943 BasePath); 944} 945 946 947/// @brief Builds a string representing ambiguous paths from a 948/// specific derived class to different subobjects of the same base 949/// class. 950/// 951/// This function builds a string that can be used in error messages 952/// to show the different paths that one can take through the 953/// inheritance hierarchy to go from the derived class to different 954/// subobjects of a base class. The result looks something like this: 955/// @code 956/// struct D -> struct B -> struct A 957/// struct D -> struct C -> struct A 958/// @endcode 959std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 960 std::string PathDisplayStr; 961 std::set<unsigned> DisplayedPaths; 962 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 963 Path != Paths.end(); ++Path) { 964 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 965 // We haven't displayed a path to this particular base 966 // class subobject yet. 967 PathDisplayStr += "\n "; 968 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 969 for (CXXBasePath::const_iterator Element = Path->begin(); 970 Element != Path->end(); ++Element) 971 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 972 } 973 } 974 975 return PathDisplayStr; 976} 977 978//===----------------------------------------------------------------------===// 979// C++ class member Handling 980//===----------------------------------------------------------------------===// 981 982/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 983Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access, 984 SourceLocation ASLoc, 985 SourceLocation ColonLoc) { 986 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 987 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 988 ASLoc, ColonLoc); 989 CurContext->addHiddenDecl(ASDecl); 990 return ASDecl; 991} 992 993/// CheckOverrideControl - Check C++0x override control semantics. 994void Sema::CheckOverrideControl(const Decl *D) { 995 const CXXMethodDecl *MD = llvm::dyn_cast<CXXMethodDecl>(D); 996 if (!MD || !MD->isVirtual()) 997 return; 998 999 if (MD->isDependentContext()) 1000 return; 1001 1002 // C++0x [class.virtual]p3: 1003 // If a virtual function is marked with the virt-specifier override and does 1004 // not override a member function of a base class, 1005 // the program is ill-formed. 1006 bool HasOverriddenMethods = 1007 MD->begin_overridden_methods() != MD->end_overridden_methods(); 1008 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) { 1009 Diag(MD->getLocation(), 1010 diag::err_function_marked_override_not_overriding) 1011 << MD->getDeclName(); 1012 return; 1013 } 1014} 1015 1016/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 1017/// function overrides a virtual member function marked 'final', according to 1018/// C++0x [class.virtual]p3. 1019bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 1020 const CXXMethodDecl *Old) { 1021 if (!Old->hasAttr<FinalAttr>()) 1022 return false; 1023 1024 Diag(New->getLocation(), diag::err_final_function_overridden) 1025 << New->getDeclName(); 1026 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 1027 return true; 1028} 1029 1030/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 1031/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 1032/// bitfield width if there is one and 'InitExpr' specifies the initializer if 1033/// any. 1034Decl * 1035Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 1036 MultiTemplateParamsArg TemplateParameterLists, 1037 ExprTy *BW, const VirtSpecifiers &VS, 1038 ExprTy *InitExpr, bool IsDefinition) { 1039 const DeclSpec &DS = D.getDeclSpec(); 1040 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 1041 DeclarationName Name = NameInfo.getName(); 1042 SourceLocation Loc = NameInfo.getLoc(); 1043 1044 // For anonymous bitfields, the location should point to the type. 1045 if (Loc.isInvalid()) 1046 Loc = D.getSourceRange().getBegin(); 1047 1048 Expr *BitWidth = static_cast<Expr*>(BW); 1049 Expr *Init = static_cast<Expr*>(InitExpr); 1050 1051 assert(isa<CXXRecordDecl>(CurContext)); 1052 assert(!DS.isFriendSpecified()); 1053 1054 bool isFunc = false; 1055 if (D.isFunctionDeclarator()) 1056 isFunc = true; 1057 else if (D.getNumTypeObjects() == 0 && 1058 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) { 1059 QualType TDType = GetTypeFromParser(DS.getRepAsType()); 1060 isFunc = TDType->isFunctionType(); 1061 } 1062 1063 // C++ 9.2p6: A member shall not be declared to have automatic storage 1064 // duration (auto, register) or with the extern storage-class-specifier. 1065 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 1066 // data members and cannot be applied to names declared const or static, 1067 // and cannot be applied to reference members. 1068 switch (DS.getStorageClassSpec()) { 1069 case DeclSpec::SCS_unspecified: 1070 case DeclSpec::SCS_typedef: 1071 case DeclSpec::SCS_static: 1072 // FALL THROUGH. 1073 break; 1074 case DeclSpec::SCS_mutable: 1075 if (isFunc) { 1076 if (DS.getStorageClassSpecLoc().isValid()) 1077 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 1078 else 1079 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function); 1080 1081 // FIXME: It would be nicer if the keyword was ignored only for this 1082 // declarator. Otherwise we could get follow-up errors. 1083 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1084 } 1085 break; 1086 default: 1087 if (DS.getStorageClassSpecLoc().isValid()) 1088 Diag(DS.getStorageClassSpecLoc(), 1089 diag::err_storageclass_invalid_for_member); 1090 else 1091 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member); 1092 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1093 } 1094 1095 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 1096 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 1097 !isFunc); 1098 1099 Decl *Member; 1100 if (isInstField) { 1101 CXXScopeSpec &SS = D.getCXXScopeSpec(); 1102 1103 if (SS.isSet() && !SS.isInvalid()) { 1104 // The user provided a superfluous scope specifier inside a class 1105 // definition: 1106 // 1107 // class X { 1108 // int X::member; 1109 // }; 1110 DeclContext *DC = 0; 1111 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext)) 1112 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification) 1113 << Name << FixItHint::CreateRemoval(SS.getRange()); 1114 else 1115 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 1116 << Name << SS.getRange(); 1117 1118 SS.clear(); 1119 } 1120 1121 // FIXME: Check for template parameters! 1122 // FIXME: Check that the name is an identifier! 1123 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth, 1124 AS); 1125 assert(Member && "HandleField never returns null"); 1126 } else { 1127 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition); 1128 if (!Member) { 1129 return 0; 1130 } 1131 1132 // Non-instance-fields can't have a bitfield. 1133 if (BitWidth) { 1134 if (Member->isInvalidDecl()) { 1135 // don't emit another diagnostic. 1136 } else if (isa<VarDecl>(Member)) { 1137 // C++ 9.6p3: A bit-field shall not be a static member. 1138 // "static member 'A' cannot be a bit-field" 1139 Diag(Loc, diag::err_static_not_bitfield) 1140 << Name << BitWidth->getSourceRange(); 1141 } else if (isa<TypedefDecl>(Member)) { 1142 // "typedef member 'x' cannot be a bit-field" 1143 Diag(Loc, diag::err_typedef_not_bitfield) 1144 << Name << BitWidth->getSourceRange(); 1145 } else { 1146 // A function typedef ("typedef int f(); f a;"). 1147 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 1148 Diag(Loc, diag::err_not_integral_type_bitfield) 1149 << Name << cast<ValueDecl>(Member)->getType() 1150 << BitWidth->getSourceRange(); 1151 } 1152 1153 BitWidth = 0; 1154 Member->setInvalidDecl(); 1155 } 1156 1157 Member->setAccess(AS); 1158 1159 // If we have declared a member function template, set the access of the 1160 // templated declaration as well. 1161 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 1162 FunTmpl->getTemplatedDecl()->setAccess(AS); 1163 } 1164 1165 if (VS.isOverrideSpecified()) { 1166 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 1167 if (!MD || !MD->isVirtual()) { 1168 Diag(Member->getLocStart(), 1169 diag::override_keyword_only_allowed_on_virtual_member_functions) 1170 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc()); 1171 } else 1172 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context)); 1173 } 1174 if (VS.isFinalSpecified()) { 1175 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 1176 if (!MD || !MD->isVirtual()) { 1177 Diag(Member->getLocStart(), 1178 diag::override_keyword_only_allowed_on_virtual_member_functions) 1179 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc()); 1180 } else 1181 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context)); 1182 } 1183 1184 if (VS.getLastLocation().isValid()) { 1185 // Update the end location of a method that has a virt-specifiers. 1186 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 1187 MD->setRangeEnd(VS.getLastLocation()); 1188 } 1189 1190 CheckOverrideControl(Member); 1191 1192 assert((Name || isInstField) && "No identifier for non-field ?"); 1193 1194 if (Init) 1195 AddInitializerToDecl(Member, Init, false, 1196 DS.getTypeSpecType() == DeclSpec::TST_auto); 1197 1198 FinalizeDeclaration(Member); 1199 1200 if (isInstField) 1201 FieldCollector->Add(cast<FieldDecl>(Member)); 1202 return Member; 1203} 1204 1205/// \brief Find the direct and/or virtual base specifiers that 1206/// correspond to the given base type, for use in base initialization 1207/// within a constructor. 1208static bool FindBaseInitializer(Sema &SemaRef, 1209 CXXRecordDecl *ClassDecl, 1210 QualType BaseType, 1211 const CXXBaseSpecifier *&DirectBaseSpec, 1212 const CXXBaseSpecifier *&VirtualBaseSpec) { 1213 // First, check for a direct base class. 1214 DirectBaseSpec = 0; 1215 for (CXXRecordDecl::base_class_const_iterator Base 1216 = ClassDecl->bases_begin(); 1217 Base != ClassDecl->bases_end(); ++Base) { 1218 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) { 1219 // We found a direct base of this type. That's what we're 1220 // initializing. 1221 DirectBaseSpec = &*Base; 1222 break; 1223 } 1224 } 1225 1226 // Check for a virtual base class. 1227 // FIXME: We might be able to short-circuit this if we know in advance that 1228 // there are no virtual bases. 1229 VirtualBaseSpec = 0; 1230 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 1231 // We haven't found a base yet; search the class hierarchy for a 1232 // virtual base class. 1233 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1234 /*DetectVirtual=*/false); 1235 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl), 1236 BaseType, Paths)) { 1237 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 1238 Path != Paths.end(); ++Path) { 1239 if (Path->back().Base->isVirtual()) { 1240 VirtualBaseSpec = Path->back().Base; 1241 break; 1242 } 1243 } 1244 } 1245 } 1246 1247 return DirectBaseSpec || VirtualBaseSpec; 1248} 1249 1250/// ActOnMemInitializer - Handle a C++ member initializer. 1251MemInitResult 1252Sema::ActOnMemInitializer(Decl *ConstructorD, 1253 Scope *S, 1254 CXXScopeSpec &SS, 1255 IdentifierInfo *MemberOrBase, 1256 ParsedType TemplateTypeTy, 1257 SourceLocation IdLoc, 1258 SourceLocation LParenLoc, 1259 ExprTy **Args, unsigned NumArgs, 1260 SourceLocation RParenLoc, 1261 SourceLocation EllipsisLoc) { 1262 if (!ConstructorD) 1263 return true; 1264 1265 AdjustDeclIfTemplate(ConstructorD); 1266 1267 CXXConstructorDecl *Constructor 1268 = dyn_cast<CXXConstructorDecl>(ConstructorD); 1269 if (!Constructor) { 1270 // The user wrote a constructor initializer on a function that is 1271 // not a C++ constructor. Ignore the error for now, because we may 1272 // have more member initializers coming; we'll diagnose it just 1273 // once in ActOnMemInitializers. 1274 return true; 1275 } 1276 1277 CXXRecordDecl *ClassDecl = Constructor->getParent(); 1278 1279 // C++ [class.base.init]p2: 1280 // Names in a mem-initializer-id are looked up in the scope of the 1281 // constructor's class and, if not found in that scope, are looked 1282 // up in the scope containing the constructor's definition. 1283 // [Note: if the constructor's class contains a member with the 1284 // same name as a direct or virtual base class of the class, a 1285 // mem-initializer-id naming the member or base class and composed 1286 // of a single identifier refers to the class member. A 1287 // mem-initializer-id for the hidden base class may be specified 1288 // using a qualified name. ] 1289 if (!SS.getScopeRep() && !TemplateTypeTy) { 1290 // Look for a member, first. 1291 FieldDecl *Member = 0; 1292 DeclContext::lookup_result Result 1293 = ClassDecl->lookup(MemberOrBase); 1294 if (Result.first != Result.second) { 1295 Member = dyn_cast<FieldDecl>(*Result.first); 1296 1297 if (Member) { 1298 if (EllipsisLoc.isValid()) 1299 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 1300 << MemberOrBase << SourceRange(IdLoc, RParenLoc); 1301 1302 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc, 1303 LParenLoc, RParenLoc); 1304 } 1305 1306 // Handle anonymous union case. 1307 if (IndirectFieldDecl* IndirectField 1308 = dyn_cast<IndirectFieldDecl>(*Result.first)) { 1309 if (EllipsisLoc.isValid()) 1310 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 1311 << MemberOrBase << SourceRange(IdLoc, RParenLoc); 1312 1313 return BuildMemberInitializer(IndirectField, (Expr**)Args, 1314 NumArgs, IdLoc, 1315 LParenLoc, RParenLoc); 1316 } 1317 } 1318 } 1319 // It didn't name a member, so see if it names a class. 1320 QualType BaseType; 1321 TypeSourceInfo *TInfo = 0; 1322 1323 if (TemplateTypeTy) { 1324 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 1325 } else { 1326 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 1327 LookupParsedName(R, S, &SS); 1328 1329 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 1330 if (!TyD) { 1331 if (R.isAmbiguous()) return true; 1332 1333 // We don't want access-control diagnostics here. 1334 R.suppressDiagnostics(); 1335 1336 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 1337 bool NotUnknownSpecialization = false; 1338 DeclContext *DC = computeDeclContext(SS, false); 1339 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 1340 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 1341 1342 if (!NotUnknownSpecialization) { 1343 // When the scope specifier can refer to a member of an unknown 1344 // specialization, we take it as a type name. 1345 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 1346 SS.getWithLocInContext(Context), 1347 *MemberOrBase, IdLoc); 1348 if (BaseType.isNull()) 1349 return true; 1350 1351 R.clear(); 1352 R.setLookupName(MemberOrBase); 1353 } 1354 } 1355 1356 // If no results were found, try to correct typos. 1357 if (R.empty() && BaseType.isNull() && 1358 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) && 1359 R.isSingleResult()) { 1360 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) { 1361 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) { 1362 // We have found a non-static data member with a similar 1363 // name to what was typed; complain and initialize that 1364 // member. 1365 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest) 1366 << MemberOrBase << true << R.getLookupName() 1367 << FixItHint::CreateReplacement(R.getNameLoc(), 1368 R.getLookupName().getAsString()); 1369 Diag(Member->getLocation(), diag::note_previous_decl) 1370 << Member->getDeclName(); 1371 1372 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc, 1373 LParenLoc, RParenLoc); 1374 } 1375 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) { 1376 const CXXBaseSpecifier *DirectBaseSpec; 1377 const CXXBaseSpecifier *VirtualBaseSpec; 1378 if (FindBaseInitializer(*this, ClassDecl, 1379 Context.getTypeDeclType(Type), 1380 DirectBaseSpec, VirtualBaseSpec)) { 1381 // We have found a direct or virtual base class with a 1382 // similar name to what was typed; complain and initialize 1383 // that base class. 1384 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest) 1385 << MemberOrBase << false << R.getLookupName() 1386 << FixItHint::CreateReplacement(R.getNameLoc(), 1387 R.getLookupName().getAsString()); 1388 1389 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec 1390 : VirtualBaseSpec; 1391 Diag(BaseSpec->getSourceRange().getBegin(), 1392 diag::note_base_class_specified_here) 1393 << BaseSpec->getType() 1394 << BaseSpec->getSourceRange(); 1395 1396 TyD = Type; 1397 } 1398 } 1399 } 1400 1401 if (!TyD && BaseType.isNull()) { 1402 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 1403 << MemberOrBase << SourceRange(IdLoc, RParenLoc); 1404 return true; 1405 } 1406 } 1407 1408 if (BaseType.isNull()) { 1409 BaseType = Context.getTypeDeclType(TyD); 1410 if (SS.isSet()) { 1411 NestedNameSpecifier *Qualifier = 1412 static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 1413 1414 // FIXME: preserve source range information 1415 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType); 1416 } 1417 } 1418 } 1419 1420 if (!TInfo) 1421 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 1422 1423 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs, 1424 LParenLoc, RParenLoc, ClassDecl, EllipsisLoc); 1425} 1426 1427/// Checks an initializer expression for use of uninitialized fields, such as 1428/// containing the field that is being initialized. Returns true if there is an 1429/// uninitialized field was used an updates the SourceLocation parameter; false 1430/// otherwise. 1431static bool InitExprContainsUninitializedFields(const Stmt *S, 1432 const ValueDecl *LhsField, 1433 SourceLocation *L) { 1434 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField)); 1435 1436 if (isa<CallExpr>(S)) { 1437 // Do not descend into function calls or constructors, as the use 1438 // of an uninitialized field may be valid. One would have to inspect 1439 // the contents of the function/ctor to determine if it is safe or not. 1440 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers 1441 // may be safe, depending on what the function/ctor does. 1442 return false; 1443 } 1444 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) { 1445 const NamedDecl *RhsField = ME->getMemberDecl(); 1446 1447 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) { 1448 // The member expression points to a static data member. 1449 assert(VD->isStaticDataMember() && 1450 "Member points to non-static data member!"); 1451 (void)VD; 1452 return false; 1453 } 1454 1455 if (isa<EnumConstantDecl>(RhsField)) { 1456 // The member expression points to an enum. 1457 return false; 1458 } 1459 1460 if (RhsField == LhsField) { 1461 // Initializing a field with itself. Throw a warning. 1462 // But wait; there are exceptions! 1463 // Exception #1: The field may not belong to this record. 1464 // e.g. Foo(const Foo& rhs) : A(rhs.A) {} 1465 const Expr *base = ME->getBase(); 1466 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) { 1467 // Even though the field matches, it does not belong to this record. 1468 return false; 1469 } 1470 // None of the exceptions triggered; return true to indicate an 1471 // uninitialized field was used. 1472 *L = ME->getMemberLoc(); 1473 return true; 1474 } 1475 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) { 1476 // sizeof/alignof doesn't reference contents, do not warn. 1477 return false; 1478 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) { 1479 // address-of doesn't reference contents (the pointer may be dereferenced 1480 // in the same expression but it would be rare; and weird). 1481 if (UOE->getOpcode() == UO_AddrOf) 1482 return false; 1483 } 1484 for (Stmt::const_child_range it = S->children(); it; ++it) { 1485 if (!*it) { 1486 // An expression such as 'member(arg ?: "")' may trigger this. 1487 continue; 1488 } 1489 if (InitExprContainsUninitializedFields(*it, LhsField, L)) 1490 return true; 1491 } 1492 return false; 1493} 1494 1495MemInitResult 1496Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args, 1497 unsigned NumArgs, SourceLocation IdLoc, 1498 SourceLocation LParenLoc, 1499 SourceLocation RParenLoc) { 1500 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 1501 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 1502 assert((DirectMember || IndirectMember) && 1503 "Member must be a FieldDecl or IndirectFieldDecl"); 1504 1505 if (Member->isInvalidDecl()) 1506 return true; 1507 1508 // Diagnose value-uses of fields to initialize themselves, e.g. 1509 // foo(foo) 1510 // where foo is not also a parameter to the constructor. 1511 // TODO: implement -Wuninitialized and fold this into that framework. 1512 for (unsigned i = 0; i < NumArgs; ++i) { 1513 SourceLocation L; 1514 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) { 1515 // FIXME: Return true in the case when other fields are used before being 1516 // uninitialized. For example, let this field be the i'th field. When 1517 // initializing the i'th field, throw a warning if any of the >= i'th 1518 // fields are used, as they are not yet initialized. 1519 // Right now we are only handling the case where the i'th field uses 1520 // itself in its initializer. 1521 Diag(L, diag::warn_field_is_uninit); 1522 } 1523 } 1524 1525 bool HasDependentArg = false; 1526 for (unsigned i = 0; i < NumArgs; i++) 1527 HasDependentArg |= Args[i]->isTypeDependent(); 1528 1529 Expr *Init; 1530 if (Member->getType()->isDependentType() || HasDependentArg) { 1531 // Can't check initialization for a member of dependent type or when 1532 // any of the arguments are type-dependent expressions. 1533 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs, 1534 RParenLoc); 1535 1536 // Erase any temporaries within this evaluation context; we're not 1537 // going to track them in the AST, since we'll be rebuilding the 1538 // ASTs during template instantiation. 1539 ExprTemporaries.erase( 1540 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries, 1541 ExprTemporaries.end()); 1542 } else { 1543 // Initialize the member. 1544 InitializedEntity MemberEntity = 1545 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0) 1546 : InitializedEntity::InitializeMember(IndirectMember, 0); 1547 InitializationKind Kind = 1548 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc); 1549 1550 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs); 1551 1552 ExprResult MemberInit = 1553 InitSeq.Perform(*this, MemberEntity, Kind, 1554 MultiExprArg(*this, Args, NumArgs), 0); 1555 if (MemberInit.isInvalid()) 1556 return true; 1557 1558 CheckImplicitConversions(MemberInit.get(), LParenLoc); 1559 1560 // C++0x [class.base.init]p7: 1561 // The initialization of each base and member constitutes a 1562 // full-expression. 1563 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 1564 if (MemberInit.isInvalid()) 1565 return true; 1566 1567 // If we are in a dependent context, template instantiation will 1568 // perform this type-checking again. Just save the arguments that we 1569 // received in a ParenListExpr. 1570 // FIXME: This isn't quite ideal, since our ASTs don't capture all 1571 // of the information that we have about the member 1572 // initializer. However, deconstructing the ASTs is a dicey process, 1573 // and this approach is far more likely to get the corner cases right. 1574 if (CurContext->isDependentContext()) 1575 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs, 1576 RParenLoc); 1577 else 1578 Init = MemberInit.get(); 1579 } 1580 1581 if (DirectMember) { 1582 return new (Context) CXXCtorInitializer(Context, DirectMember, 1583 IdLoc, LParenLoc, Init, 1584 RParenLoc); 1585 } else { 1586 return new (Context) CXXCtorInitializer(Context, IndirectMember, 1587 IdLoc, LParenLoc, Init, 1588 RParenLoc); 1589 } 1590} 1591 1592MemInitResult 1593Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, 1594 Expr **Args, unsigned NumArgs, 1595 SourceLocation NameLoc, 1596 SourceLocation LParenLoc, 1597 SourceLocation RParenLoc, 1598 CXXRecordDecl *ClassDecl) { 1599 SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 1600 if (!LangOpts.CPlusPlus0x) 1601 return Diag(Loc, diag::err_delegation_0x_only) 1602 << TInfo->getTypeLoc().getLocalSourceRange(); 1603 1604 // Initialize the object. 1605 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 1606 QualType(ClassDecl->getTypeForDecl(), 0)); 1607 InitializationKind Kind = 1608 InitializationKind::CreateDirect(NameLoc, LParenLoc, RParenLoc); 1609 1610 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs); 1611 1612 ExprResult DelegationInit = 1613 InitSeq.Perform(*this, DelegationEntity, Kind, 1614 MultiExprArg(*this, Args, NumArgs), 0); 1615 if (DelegationInit.isInvalid()) 1616 return true; 1617 1618 CXXConstructExpr *ConExpr = cast<CXXConstructExpr>(DelegationInit.get()); 1619 CXXConstructorDecl *Constructor 1620 = ConExpr->getConstructor(); 1621 assert(Constructor && "Delegating constructor with no target?"); 1622 1623 CheckImplicitConversions(DelegationInit.get(), LParenLoc); 1624 1625 // C++0x [class.base.init]p7: 1626 // The initialization of each base and member constitutes a 1627 // full-expression. 1628 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit); 1629 if (DelegationInit.isInvalid()) 1630 return true; 1631 1632 // If we are in a dependent context, template instantiation will 1633 // perform this type-checking again. Just save the arguments that we 1634 // received in a ParenListExpr. 1635 // FIXME: This isn't quite ideal, since our ASTs don't capture all 1636 // of the information that we have about the base 1637 // initializer. However, deconstructing the ASTs is a dicey process, 1638 // and this approach is far more likely to get the corner cases right. 1639 if (CurContext->isDependentContext()) { 1640 ExprResult Init 1641 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, 1642 NumArgs, RParenLoc)); 1643 return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc, 1644 Constructor, Init.takeAs<Expr>(), 1645 RParenLoc); 1646 } 1647 1648 return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc, Constructor, 1649 DelegationInit.takeAs<Expr>(), 1650 RParenLoc); 1651} 1652 1653MemInitResult 1654Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 1655 Expr **Args, unsigned NumArgs, 1656 SourceLocation LParenLoc, SourceLocation RParenLoc, 1657 CXXRecordDecl *ClassDecl, 1658 SourceLocation EllipsisLoc) { 1659 bool HasDependentArg = false; 1660 for (unsigned i = 0; i < NumArgs; i++) 1661 HasDependentArg |= Args[i]->isTypeDependent(); 1662 1663 SourceLocation BaseLoc 1664 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 1665 1666 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 1667 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 1668 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 1669 1670 // C++ [class.base.init]p2: 1671 // [...] Unless the mem-initializer-id names a nonstatic data 1672 // member of the constructor's class or a direct or virtual base 1673 // of that class, the mem-initializer is ill-formed. A 1674 // mem-initializer-list can initialize a base class using any 1675 // name that denotes that base class type. 1676 bool Dependent = BaseType->isDependentType() || HasDependentArg; 1677 1678 if (EllipsisLoc.isValid()) { 1679 // This is a pack expansion. 1680 if (!BaseType->containsUnexpandedParameterPack()) { 1681 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 1682 << SourceRange(BaseLoc, RParenLoc); 1683 1684 EllipsisLoc = SourceLocation(); 1685 } 1686 } else { 1687 // Check for any unexpanded parameter packs. 1688 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 1689 return true; 1690 1691 for (unsigned I = 0; I != NumArgs; ++I) 1692 if (DiagnoseUnexpandedParameterPack(Args[I])) 1693 return true; 1694 } 1695 1696 // Check for direct and virtual base classes. 1697 const CXXBaseSpecifier *DirectBaseSpec = 0; 1698 const CXXBaseSpecifier *VirtualBaseSpec = 0; 1699 if (!Dependent) { 1700 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 1701 BaseType)) 1702 return BuildDelegatingInitializer(BaseTInfo, Args, NumArgs, BaseLoc, 1703 LParenLoc, RParenLoc, ClassDecl); 1704 1705 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 1706 VirtualBaseSpec); 1707 1708 // C++ [base.class.init]p2: 1709 // Unless the mem-initializer-id names a nonstatic data member of the 1710 // constructor's class or a direct or virtual base of that class, the 1711 // mem-initializer is ill-formed. 1712 if (!DirectBaseSpec && !VirtualBaseSpec) { 1713 // If the class has any dependent bases, then it's possible that 1714 // one of those types will resolve to the same type as 1715 // BaseType. Therefore, just treat this as a dependent base 1716 // class initialization. FIXME: Should we try to check the 1717 // initialization anyway? It seems odd. 1718 if (ClassDecl->hasAnyDependentBases()) 1719 Dependent = true; 1720 else 1721 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 1722 << BaseType << Context.getTypeDeclType(ClassDecl) 1723 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 1724 } 1725 } 1726 1727 if (Dependent) { 1728 // Can't check initialization for a base of dependent type or when 1729 // any of the arguments are type-dependent expressions. 1730 ExprResult BaseInit 1731 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs, 1732 RParenLoc)); 1733 1734 // Erase any temporaries within this evaluation context; we're not 1735 // going to track them in the AST, since we'll be rebuilding the 1736 // ASTs during template instantiation. 1737 ExprTemporaries.erase( 1738 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries, 1739 ExprTemporaries.end()); 1740 1741 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 1742 /*IsVirtual=*/false, 1743 LParenLoc, 1744 BaseInit.takeAs<Expr>(), 1745 RParenLoc, 1746 EllipsisLoc); 1747 } 1748 1749 // C++ [base.class.init]p2: 1750 // If a mem-initializer-id is ambiguous because it designates both 1751 // a direct non-virtual base class and an inherited virtual base 1752 // class, the mem-initializer is ill-formed. 1753 if (DirectBaseSpec && VirtualBaseSpec) 1754 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 1755 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 1756 1757 CXXBaseSpecifier *BaseSpec 1758 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec); 1759 if (!BaseSpec) 1760 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec); 1761 1762 // Initialize the base. 1763 InitializedEntity BaseEntity = 1764 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 1765 InitializationKind Kind = 1766 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc); 1767 1768 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs); 1769 1770 ExprResult BaseInit = 1771 InitSeq.Perform(*this, BaseEntity, Kind, 1772 MultiExprArg(*this, Args, NumArgs), 0); 1773 if (BaseInit.isInvalid()) 1774 return true; 1775 1776 CheckImplicitConversions(BaseInit.get(), LParenLoc); 1777 1778 // C++0x [class.base.init]p7: 1779 // The initialization of each base and member constitutes a 1780 // full-expression. 1781 BaseInit = MaybeCreateExprWithCleanups(BaseInit); 1782 if (BaseInit.isInvalid()) 1783 return true; 1784 1785 // If we are in a dependent context, template instantiation will 1786 // perform this type-checking again. Just save the arguments that we 1787 // received in a ParenListExpr. 1788 // FIXME: This isn't quite ideal, since our ASTs don't capture all 1789 // of the information that we have about the base 1790 // initializer. However, deconstructing the ASTs is a dicey process, 1791 // and this approach is far more likely to get the corner cases right. 1792 if (CurContext->isDependentContext()) { 1793 ExprResult Init 1794 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs, 1795 RParenLoc)); 1796 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 1797 BaseSpec->isVirtual(), 1798 LParenLoc, 1799 Init.takeAs<Expr>(), 1800 RParenLoc, 1801 EllipsisLoc); 1802 } 1803 1804 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 1805 BaseSpec->isVirtual(), 1806 LParenLoc, 1807 BaseInit.takeAs<Expr>(), 1808 RParenLoc, 1809 EllipsisLoc); 1810} 1811 1812/// ImplicitInitializerKind - How an implicit base or member initializer should 1813/// initialize its base or member. 1814enum ImplicitInitializerKind { 1815 IIK_Default, 1816 IIK_Copy, 1817 IIK_Move 1818}; 1819 1820static bool 1821BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 1822 ImplicitInitializerKind ImplicitInitKind, 1823 CXXBaseSpecifier *BaseSpec, 1824 bool IsInheritedVirtualBase, 1825 CXXCtorInitializer *&CXXBaseInit) { 1826 InitializedEntity InitEntity 1827 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 1828 IsInheritedVirtualBase); 1829 1830 ExprResult BaseInit; 1831 1832 switch (ImplicitInitKind) { 1833 case IIK_Default: { 1834 InitializationKind InitKind 1835 = InitializationKind::CreateDefault(Constructor->getLocation()); 1836 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0); 1837 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, 1838 MultiExprArg(SemaRef, 0, 0)); 1839 break; 1840 } 1841 1842 case IIK_Copy: { 1843 ParmVarDecl *Param = Constructor->getParamDecl(0); 1844 QualType ParamType = Param->getType().getNonReferenceType(); 1845 1846 Expr *CopyCtorArg = 1847 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param, 1848 Constructor->getLocation(), ParamType, 1849 VK_LValue, 0); 1850 1851 // Cast to the base class to avoid ambiguities. 1852 QualType ArgTy = 1853 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 1854 ParamType.getQualifiers()); 1855 1856 CXXCastPath BasePath; 1857 BasePath.push_back(BaseSpec); 1858 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 1859 CK_UncheckedDerivedToBase, 1860 VK_LValue, &BasePath).take(); 1861 1862 InitializationKind InitKind 1863 = InitializationKind::CreateDirect(Constructor->getLocation(), 1864 SourceLocation(), SourceLocation()); 1865 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 1866 &CopyCtorArg, 1); 1867 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, 1868 MultiExprArg(&CopyCtorArg, 1)); 1869 break; 1870 } 1871 1872 case IIK_Move: 1873 assert(false && "Unhandled initializer kind!"); 1874 } 1875 1876 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 1877 if (BaseInit.isInvalid()) 1878 return true; 1879 1880 CXXBaseInit = 1881 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 1882 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 1883 SourceLocation()), 1884 BaseSpec->isVirtual(), 1885 SourceLocation(), 1886 BaseInit.takeAs<Expr>(), 1887 SourceLocation(), 1888 SourceLocation()); 1889 1890 return false; 1891} 1892 1893static bool 1894BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 1895 ImplicitInitializerKind ImplicitInitKind, 1896 FieldDecl *Field, 1897 CXXCtorInitializer *&CXXMemberInit) { 1898 if (Field->isInvalidDecl()) 1899 return true; 1900 1901 SourceLocation Loc = Constructor->getLocation(); 1902 1903 if (ImplicitInitKind == IIK_Copy) { 1904 ParmVarDecl *Param = Constructor->getParamDecl(0); 1905 QualType ParamType = Param->getType().getNonReferenceType(); 1906 1907 Expr *MemberExprBase = 1908 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param, 1909 Loc, ParamType, VK_LValue, 0); 1910 1911 // Build a reference to this field within the parameter. 1912 CXXScopeSpec SS; 1913 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 1914 Sema::LookupMemberName); 1915 MemberLookup.addDecl(Field, AS_public); 1916 MemberLookup.resolveKind(); 1917 ExprResult CopyCtorArg 1918 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 1919 ParamType, Loc, 1920 /*IsArrow=*/false, 1921 SS, 1922 /*FirstQualifierInScope=*/0, 1923 MemberLookup, 1924 /*TemplateArgs=*/0); 1925 if (CopyCtorArg.isInvalid()) 1926 return true; 1927 1928 // When the field we are copying is an array, create index variables for 1929 // each dimension of the array. We use these index variables to subscript 1930 // the source array, and other clients (e.g., CodeGen) will perform the 1931 // necessary iteration with these index variables. 1932 llvm::SmallVector<VarDecl *, 4> IndexVariables; 1933 QualType BaseType = Field->getType(); 1934 QualType SizeType = SemaRef.Context.getSizeType(); 1935 while (const ConstantArrayType *Array 1936 = SemaRef.Context.getAsConstantArrayType(BaseType)) { 1937 // Create the iteration variable for this array index. 1938 IdentifierInfo *IterationVarName = 0; 1939 { 1940 llvm::SmallString<8> Str; 1941 llvm::raw_svector_ostream OS(Str); 1942 OS << "__i" << IndexVariables.size(); 1943 IterationVarName = &SemaRef.Context.Idents.get(OS.str()); 1944 } 1945 VarDecl *IterationVar 1946 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc, 1947 IterationVarName, SizeType, 1948 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc), 1949 SC_None, SC_None); 1950 IndexVariables.push_back(IterationVar); 1951 1952 // Create a reference to the iteration variable. 1953 ExprResult IterationVarRef 1954 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc); 1955 assert(!IterationVarRef.isInvalid() && 1956 "Reference to invented variable cannot fail!"); 1957 1958 // Subscript the array with this iteration variable. 1959 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(), 1960 Loc, 1961 IterationVarRef.take(), 1962 Loc); 1963 if (CopyCtorArg.isInvalid()) 1964 return true; 1965 1966 BaseType = Array->getElementType(); 1967 } 1968 1969 // Construct the entity that we will be initializing. For an array, this 1970 // will be first element in the array, which may require several levels 1971 // of array-subscript entities. 1972 llvm::SmallVector<InitializedEntity, 4> Entities; 1973 Entities.reserve(1 + IndexVariables.size()); 1974 Entities.push_back(InitializedEntity::InitializeMember(Field)); 1975 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 1976 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context, 1977 0, 1978 Entities.back())); 1979 1980 // Direct-initialize to use the copy constructor. 1981 InitializationKind InitKind = 1982 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 1983 1984 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>(); 1985 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, 1986 &CopyCtorArgE, 1); 1987 1988 ExprResult MemberInit 1989 = InitSeq.Perform(SemaRef, Entities.back(), InitKind, 1990 MultiExprArg(&CopyCtorArgE, 1)); 1991 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 1992 if (MemberInit.isInvalid()) 1993 return true; 1994 1995 CXXMemberInit 1996 = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, Loc, 1997 MemberInit.takeAs<Expr>(), Loc, 1998 IndexVariables.data(), 1999 IndexVariables.size()); 2000 return false; 2001 } 2002 2003 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!"); 2004 2005 QualType FieldBaseElementType = 2006 SemaRef.Context.getBaseElementType(Field->getType()); 2007 2008 if (FieldBaseElementType->isRecordType()) { 2009 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 2010 InitializationKind InitKind = 2011 InitializationKind::CreateDefault(Loc); 2012 2013 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0); 2014 ExprResult MemberInit = 2015 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg()); 2016 2017 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 2018 if (MemberInit.isInvalid()) 2019 return true; 2020 2021 CXXMemberInit = 2022 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 2023 Field, Loc, Loc, 2024 MemberInit.get(), 2025 Loc); 2026 return false; 2027 } 2028 2029 if (!Field->getParent()->isUnion()) { 2030 if (FieldBaseElementType->isReferenceType()) { 2031 SemaRef.Diag(Constructor->getLocation(), 2032 diag::err_uninitialized_member_in_ctor) 2033 << (int)Constructor->isImplicit() 2034 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 2035 << 0 << Field->getDeclName(); 2036 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 2037 return true; 2038 } 2039 2040 if (FieldBaseElementType.isConstQualified()) { 2041 SemaRef.Diag(Constructor->getLocation(), 2042 diag::err_uninitialized_member_in_ctor) 2043 << (int)Constructor->isImplicit() 2044 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 2045 << 1 << Field->getDeclName(); 2046 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 2047 return true; 2048 } 2049 } 2050 2051 // Nothing to initialize. 2052 CXXMemberInit = 0; 2053 return false; 2054} 2055 2056namespace { 2057struct BaseAndFieldInfo { 2058 Sema &S; 2059 CXXConstructorDecl *Ctor; 2060 bool AnyErrorsInInits; 2061 ImplicitInitializerKind IIK; 2062 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 2063 llvm::SmallVector<CXXCtorInitializer*, 8> AllToInit; 2064 2065 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 2066 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 2067 // FIXME: Handle implicit move constructors. 2068 if (Ctor->isImplicit() && Ctor->isCopyConstructor()) 2069 IIK = IIK_Copy; 2070 else 2071 IIK = IIK_Default; 2072 } 2073}; 2074} 2075 2076static bool CollectFieldInitializer(BaseAndFieldInfo &Info, 2077 FieldDecl *Top, FieldDecl *Field) { 2078 2079 // Overwhelmingly common case: we have a direct initializer for this field. 2080 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) { 2081 Info.AllToInit.push_back(Init); 2082 return false; 2083 } 2084 2085 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) { 2086 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>(); 2087 assert(FieldClassType && "anonymous struct/union without record type"); 2088 CXXRecordDecl *FieldClassDecl 2089 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 2090 2091 // Even though union members never have non-trivial default 2092 // constructions in C++03, we still build member initializers for aggregate 2093 // record types which can be union members, and C++0x allows non-trivial 2094 // default constructors for union members, so we ensure that only one 2095 // member is initialized for these. 2096 if (FieldClassDecl->isUnion()) { 2097 // First check for an explicit initializer for one field. 2098 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(), 2099 EA = FieldClassDecl->field_end(); FA != EA; FA++) { 2100 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(*FA)) { 2101 Info.AllToInit.push_back(Init); 2102 2103 // Once we've initialized a field of an anonymous union, the union 2104 // field in the class is also initialized, so exit immediately. 2105 return false; 2106 } else if ((*FA)->isAnonymousStructOrUnion()) { 2107 if (CollectFieldInitializer(Info, Top, *FA)) 2108 return true; 2109 } 2110 } 2111 2112 // Fallthrough and construct a default initializer for the union as 2113 // a whole, which can call its default constructor if such a thing exists 2114 // (C++0x perhaps). FIXME: It's not clear that this is the correct 2115 // behavior going forward with C++0x, when anonymous unions there are 2116 // finalized, we should revisit this. 2117 } else { 2118 // For structs, we simply descend through to initialize all members where 2119 // necessary. 2120 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(), 2121 EA = FieldClassDecl->field_end(); FA != EA; FA++) { 2122 if (CollectFieldInitializer(Info, Top, *FA)) 2123 return true; 2124 } 2125 } 2126 } 2127 2128 // Don't try to build an implicit initializer if there were semantic 2129 // errors in any of the initializers (and therefore we might be 2130 // missing some that the user actually wrote). 2131 if (Info.AnyErrorsInInits) 2132 return false; 2133 2134 CXXCtorInitializer *Init = 0; 2135 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init)) 2136 return true; 2137 2138 if (Init) 2139 Info.AllToInit.push_back(Init); 2140 2141 return false; 2142} 2143 2144bool 2145Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 2146 CXXCtorInitializer *Initializer) { 2147 assert(Initializer->isDelegatingInitializer()); 2148 Constructor->setNumCtorInitializers(1); 2149 CXXCtorInitializer **initializer = 2150 new (Context) CXXCtorInitializer*[1]; 2151 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 2152 Constructor->setCtorInitializers(initializer); 2153 2154 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 2155 MarkDeclarationReferenced(Initializer->getSourceLocation(), Dtor); 2156 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 2157 } 2158 2159 DelegatingCtorDecls.push_back(Constructor); 2160 2161 return false; 2162} 2163 2164bool 2165Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, 2166 CXXCtorInitializer **Initializers, 2167 unsigned NumInitializers, 2168 bool AnyErrors) { 2169 if (Constructor->getDeclContext()->isDependentContext()) { 2170 // Just store the initializers as written, they will be checked during 2171 // instantiation. 2172 if (NumInitializers > 0) { 2173 Constructor->setNumCtorInitializers(NumInitializers); 2174 CXXCtorInitializer **baseOrMemberInitializers = 2175 new (Context) CXXCtorInitializer*[NumInitializers]; 2176 memcpy(baseOrMemberInitializers, Initializers, 2177 NumInitializers * sizeof(CXXCtorInitializer*)); 2178 Constructor->setCtorInitializers(baseOrMemberInitializers); 2179 } 2180 2181 return false; 2182 } 2183 2184 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 2185 2186 // We need to build the initializer AST according to order of construction 2187 // and not what user specified in the Initializers list. 2188 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 2189 if (!ClassDecl) 2190 return true; 2191 2192 bool HadError = false; 2193 2194 for (unsigned i = 0; i < NumInitializers; i++) { 2195 CXXCtorInitializer *Member = Initializers[i]; 2196 2197 if (Member->isBaseInitializer()) 2198 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 2199 else 2200 Info.AllBaseFields[Member->getAnyMember()] = Member; 2201 } 2202 2203 // Keep track of the direct virtual bases. 2204 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 2205 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(), 2206 E = ClassDecl->bases_end(); I != E; ++I) { 2207 if (I->isVirtual()) 2208 DirectVBases.insert(I); 2209 } 2210 2211 // Push virtual bases before others. 2212 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 2213 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 2214 2215 if (CXXCtorInitializer *Value 2216 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) { 2217 Info.AllToInit.push_back(Value); 2218 } else if (!AnyErrors) { 2219 bool IsInheritedVirtualBase = !DirectVBases.count(VBase); 2220 CXXCtorInitializer *CXXBaseInit; 2221 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 2222 VBase, IsInheritedVirtualBase, 2223 CXXBaseInit)) { 2224 HadError = true; 2225 continue; 2226 } 2227 2228 Info.AllToInit.push_back(CXXBaseInit); 2229 } 2230 } 2231 2232 // Non-virtual bases. 2233 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 2234 E = ClassDecl->bases_end(); Base != E; ++Base) { 2235 // Virtuals are in the virtual base list and already constructed. 2236 if (Base->isVirtual()) 2237 continue; 2238 2239 if (CXXCtorInitializer *Value 2240 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) { 2241 Info.AllToInit.push_back(Value); 2242 } else if (!AnyErrors) { 2243 CXXCtorInitializer *CXXBaseInit; 2244 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 2245 Base, /*IsInheritedVirtualBase=*/false, 2246 CXXBaseInit)) { 2247 HadError = true; 2248 continue; 2249 } 2250 2251 Info.AllToInit.push_back(CXXBaseInit); 2252 } 2253 } 2254 2255 // Fields. 2256 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 2257 E = ClassDecl->field_end(); Field != E; ++Field) { 2258 if ((*Field)->getType()->isIncompleteArrayType()) { 2259 assert(ClassDecl->hasFlexibleArrayMember() && 2260 "Incomplete array type is not valid"); 2261 continue; 2262 } 2263 if (CollectFieldInitializer(Info, *Field, *Field)) 2264 HadError = true; 2265 } 2266 2267 NumInitializers = Info.AllToInit.size(); 2268 if (NumInitializers > 0) { 2269 Constructor->setNumCtorInitializers(NumInitializers); 2270 CXXCtorInitializer **baseOrMemberInitializers = 2271 new (Context) CXXCtorInitializer*[NumInitializers]; 2272 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 2273 NumInitializers * sizeof(CXXCtorInitializer*)); 2274 Constructor->setCtorInitializers(baseOrMemberInitializers); 2275 2276 // Constructors implicitly reference the base and member 2277 // destructors. 2278 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 2279 Constructor->getParent()); 2280 } 2281 2282 return HadError; 2283} 2284 2285static void *GetKeyForTopLevelField(FieldDecl *Field) { 2286 // For anonymous unions, use the class declaration as the key. 2287 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 2288 if (RT->getDecl()->isAnonymousStructOrUnion()) 2289 return static_cast<void *>(RT->getDecl()); 2290 } 2291 return static_cast<void *>(Field); 2292} 2293 2294static void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 2295 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr()); 2296} 2297 2298static void *GetKeyForMember(ASTContext &Context, 2299 CXXCtorInitializer *Member) { 2300 if (!Member->isAnyMemberInitializer()) 2301 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 2302 2303 // For fields injected into the class via declaration of an anonymous union, 2304 // use its anonymous union class declaration as the unique key. 2305 FieldDecl *Field = Member->getAnyMember(); 2306 2307 // If the field is a member of an anonymous struct or union, our key 2308 // is the anonymous record decl that's a direct child of the class. 2309 RecordDecl *RD = Field->getParent(); 2310 if (RD->isAnonymousStructOrUnion()) { 2311 while (true) { 2312 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext()); 2313 if (Parent->isAnonymousStructOrUnion()) 2314 RD = Parent; 2315 else 2316 break; 2317 } 2318 2319 return static_cast<void *>(RD); 2320 } 2321 2322 return static_cast<void *>(Field); 2323} 2324 2325static void 2326DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef, 2327 const CXXConstructorDecl *Constructor, 2328 CXXCtorInitializer **Inits, 2329 unsigned NumInits) { 2330 if (Constructor->getDeclContext()->isDependentContext()) 2331 return; 2332 2333 // Don't check initializers order unless the warning is enabled at the 2334 // location of at least one initializer. 2335 bool ShouldCheckOrder = false; 2336 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) { 2337 CXXCtorInitializer *Init = Inits[InitIndex]; 2338 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order, 2339 Init->getSourceLocation()) 2340 != Diagnostic::Ignored) { 2341 ShouldCheckOrder = true; 2342 break; 2343 } 2344 } 2345 if (!ShouldCheckOrder) 2346 return; 2347 2348 // Build the list of bases and members in the order that they'll 2349 // actually be initialized. The explicit initializers should be in 2350 // this same order but may be missing things. 2351 llvm::SmallVector<const void*, 32> IdealInitKeys; 2352 2353 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 2354 2355 // 1. Virtual bases. 2356 for (CXXRecordDecl::base_class_const_iterator VBase = 2357 ClassDecl->vbases_begin(), 2358 E = ClassDecl->vbases_end(); VBase != E; ++VBase) 2359 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType())); 2360 2361 // 2. Non-virtual bases. 2362 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(), 2363 E = ClassDecl->bases_end(); Base != E; ++Base) { 2364 if (Base->isVirtual()) 2365 continue; 2366 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType())); 2367 } 2368 2369 // 3. Direct fields. 2370 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 2371 E = ClassDecl->field_end(); Field != E; ++Field) 2372 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field)); 2373 2374 unsigned NumIdealInits = IdealInitKeys.size(); 2375 unsigned IdealIndex = 0; 2376 2377 CXXCtorInitializer *PrevInit = 0; 2378 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) { 2379 CXXCtorInitializer *Init = Inits[InitIndex]; 2380 void *InitKey = GetKeyForMember(SemaRef.Context, Init); 2381 2382 // Scan forward to try to find this initializer in the idealized 2383 // initializers list. 2384 for (; IdealIndex != NumIdealInits; ++IdealIndex) 2385 if (InitKey == IdealInitKeys[IdealIndex]) 2386 break; 2387 2388 // If we didn't find this initializer, it must be because we 2389 // scanned past it on a previous iteration. That can only 2390 // happen if we're out of order; emit a warning. 2391 if (IdealIndex == NumIdealInits && PrevInit) { 2392 Sema::SemaDiagnosticBuilder D = 2393 SemaRef.Diag(PrevInit->getSourceLocation(), 2394 diag::warn_initializer_out_of_order); 2395 2396 if (PrevInit->isAnyMemberInitializer()) 2397 D << 0 << PrevInit->getAnyMember()->getDeclName(); 2398 else 2399 D << 1 << PrevInit->getBaseClassInfo()->getType(); 2400 2401 if (Init->isAnyMemberInitializer()) 2402 D << 0 << Init->getAnyMember()->getDeclName(); 2403 else 2404 D << 1 << Init->getBaseClassInfo()->getType(); 2405 2406 // Move back to the initializer's location in the ideal list. 2407 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 2408 if (InitKey == IdealInitKeys[IdealIndex]) 2409 break; 2410 2411 assert(IdealIndex != NumIdealInits && 2412 "initializer not found in initializer list"); 2413 } 2414 2415 PrevInit = Init; 2416 } 2417} 2418 2419namespace { 2420bool CheckRedundantInit(Sema &S, 2421 CXXCtorInitializer *Init, 2422 CXXCtorInitializer *&PrevInit) { 2423 if (!PrevInit) { 2424 PrevInit = Init; 2425 return false; 2426 } 2427 2428 if (FieldDecl *Field = Init->getMember()) 2429 S.Diag(Init->getSourceLocation(), 2430 diag::err_multiple_mem_initialization) 2431 << Field->getDeclName() 2432 << Init->getSourceRange(); 2433 else { 2434 const Type *BaseClass = Init->getBaseClass(); 2435 assert(BaseClass && "neither field nor base"); 2436 S.Diag(Init->getSourceLocation(), 2437 diag::err_multiple_base_initialization) 2438 << QualType(BaseClass, 0) 2439 << Init->getSourceRange(); 2440 } 2441 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 2442 << 0 << PrevInit->getSourceRange(); 2443 2444 return true; 2445} 2446 2447typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 2448typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 2449 2450bool CheckRedundantUnionInit(Sema &S, 2451 CXXCtorInitializer *Init, 2452 RedundantUnionMap &Unions) { 2453 FieldDecl *Field = Init->getAnyMember(); 2454 RecordDecl *Parent = Field->getParent(); 2455 if (!Parent->isAnonymousStructOrUnion()) 2456 return false; 2457 2458 NamedDecl *Child = Field; 2459 do { 2460 if (Parent->isUnion()) { 2461 UnionEntry &En = Unions[Parent]; 2462 if (En.first && En.first != Child) { 2463 S.Diag(Init->getSourceLocation(), 2464 diag::err_multiple_mem_union_initialization) 2465 << Field->getDeclName() 2466 << Init->getSourceRange(); 2467 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 2468 << 0 << En.second->getSourceRange(); 2469 return true; 2470 } else if (!En.first) { 2471 En.first = Child; 2472 En.second = Init; 2473 } 2474 } 2475 2476 Child = Parent; 2477 Parent = cast<RecordDecl>(Parent->getDeclContext()); 2478 } while (Parent->isAnonymousStructOrUnion()); 2479 2480 return false; 2481} 2482} 2483 2484/// ActOnMemInitializers - Handle the member initializers for a constructor. 2485void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 2486 SourceLocation ColonLoc, 2487 MemInitTy **meminits, unsigned NumMemInits, 2488 bool AnyErrors) { 2489 if (!ConstructorDecl) 2490 return; 2491 2492 AdjustDeclIfTemplate(ConstructorDecl); 2493 2494 CXXConstructorDecl *Constructor 2495 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 2496 2497 if (!Constructor) { 2498 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 2499 return; 2500 } 2501 2502 CXXCtorInitializer **MemInits = 2503 reinterpret_cast<CXXCtorInitializer **>(meminits); 2504 2505 // Mapping for the duplicate initializers check. 2506 // For member initializers, this is keyed with a FieldDecl*. 2507 // For base initializers, this is keyed with a Type*. 2508 llvm::DenseMap<void*, CXXCtorInitializer *> Members; 2509 2510 // Mapping for the inconsistent anonymous-union initializers check. 2511 RedundantUnionMap MemberUnions; 2512 2513 bool HadError = false; 2514 for (unsigned i = 0; i < NumMemInits; i++) { 2515 CXXCtorInitializer *Init = MemInits[i]; 2516 2517 // Set the source order index. 2518 Init->setSourceOrder(i); 2519 2520 if (Init->isAnyMemberInitializer()) { 2521 FieldDecl *Field = Init->getAnyMember(); 2522 if (CheckRedundantInit(*this, Init, Members[Field]) || 2523 CheckRedundantUnionInit(*this, Init, MemberUnions)) 2524 HadError = true; 2525 } else if (Init->isBaseInitializer()) { 2526 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0)); 2527 if (CheckRedundantInit(*this, Init, Members[Key])) 2528 HadError = true; 2529 } else { 2530 assert(Init->isDelegatingInitializer()); 2531 // This must be the only initializer 2532 if (i != 0 || NumMemInits > 1) { 2533 Diag(MemInits[0]->getSourceLocation(), 2534 diag::err_delegating_initializer_alone) 2535 << MemInits[0]->getSourceRange(); 2536 HadError = true; 2537 // We will treat this as being the only initializer. 2538 } 2539 SetDelegatingInitializer(Constructor, MemInits[i]); 2540 // Return immediately as the initializer is set. 2541 return; 2542 } 2543 } 2544 2545 if (HadError) 2546 return; 2547 2548 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits); 2549 2550 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors); 2551} 2552 2553void 2554Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 2555 CXXRecordDecl *ClassDecl) { 2556 // Ignore dependent contexts. 2557 if (ClassDecl->isDependentContext()) 2558 return; 2559 2560 // FIXME: all the access-control diagnostics are positioned on the 2561 // field/base declaration. That's probably good; that said, the 2562 // user might reasonably want to know why the destructor is being 2563 // emitted, and we currently don't say. 2564 2565 // Non-static data members. 2566 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(), 2567 E = ClassDecl->field_end(); I != E; ++I) { 2568 FieldDecl *Field = *I; 2569 if (Field->isInvalidDecl()) 2570 continue; 2571 QualType FieldType = Context.getBaseElementType(Field->getType()); 2572 2573 const RecordType* RT = FieldType->getAs<RecordType>(); 2574 if (!RT) 2575 continue; 2576 2577 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 2578 if (FieldClassDecl->isInvalidDecl()) 2579 continue; 2580 if (FieldClassDecl->hasTrivialDestructor()) 2581 continue; 2582 2583 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 2584 assert(Dtor && "No dtor found for FieldClassDecl!"); 2585 CheckDestructorAccess(Field->getLocation(), Dtor, 2586 PDiag(diag::err_access_dtor_field) 2587 << Field->getDeclName() 2588 << FieldType); 2589 2590 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 2591 } 2592 2593 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 2594 2595 // Bases. 2596 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 2597 E = ClassDecl->bases_end(); Base != E; ++Base) { 2598 // Bases are always records in a well-formed non-dependent class. 2599 const RecordType *RT = Base->getType()->getAs<RecordType>(); 2600 2601 // Remember direct virtual bases. 2602 if (Base->isVirtual()) 2603 DirectVirtualBases.insert(RT); 2604 2605 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 2606 // If our base class is invalid, we probably can't get its dtor anyway. 2607 if (BaseClassDecl->isInvalidDecl()) 2608 continue; 2609 // Ignore trivial destructors. 2610 if (BaseClassDecl->hasTrivialDestructor()) 2611 continue; 2612 2613 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 2614 assert(Dtor && "No dtor found for BaseClassDecl!"); 2615 2616 // FIXME: caret should be on the start of the class name 2617 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor, 2618 PDiag(diag::err_access_dtor_base) 2619 << Base->getType() 2620 << Base->getSourceRange()); 2621 2622 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 2623 } 2624 2625 // Virtual bases. 2626 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 2627 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 2628 2629 // Bases are always records in a well-formed non-dependent class. 2630 const RecordType *RT = VBase->getType()->getAs<RecordType>(); 2631 2632 // Ignore direct virtual bases. 2633 if (DirectVirtualBases.count(RT)) 2634 continue; 2635 2636 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 2637 // If our base class is invalid, we probably can't get its dtor anyway. 2638 if (BaseClassDecl->isInvalidDecl()) 2639 continue; 2640 // Ignore trivial destructors. 2641 if (BaseClassDecl->hasTrivialDestructor()) 2642 continue; 2643 2644 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 2645 assert(Dtor && "No dtor found for BaseClassDecl!"); 2646 CheckDestructorAccess(ClassDecl->getLocation(), Dtor, 2647 PDiag(diag::err_access_dtor_vbase) 2648 << VBase->getType()); 2649 2650 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 2651 } 2652} 2653 2654void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 2655 if (!CDtorDecl) 2656 return; 2657 2658 if (CXXConstructorDecl *Constructor 2659 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) 2660 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false); 2661} 2662 2663bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 2664 unsigned DiagID, AbstractDiagSelID SelID) { 2665 if (SelID == -1) 2666 return RequireNonAbstractType(Loc, T, PDiag(DiagID)); 2667 else 2668 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID); 2669} 2670 2671bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 2672 const PartialDiagnostic &PD) { 2673 if (!getLangOptions().CPlusPlus) 2674 return false; 2675 2676 if (const ArrayType *AT = Context.getAsArrayType(T)) 2677 return RequireNonAbstractType(Loc, AT->getElementType(), PD); 2678 2679 if (const PointerType *PT = T->getAs<PointerType>()) { 2680 // Find the innermost pointer type. 2681 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 2682 PT = T; 2683 2684 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 2685 return RequireNonAbstractType(Loc, AT->getElementType(), PD); 2686 } 2687 2688 const RecordType *RT = T->getAs<RecordType>(); 2689 if (!RT) 2690 return false; 2691 2692 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 2693 2694 // We can't answer whether something is abstract until it has a 2695 // definition. If it's currently being defined, we'll walk back 2696 // over all the declarations when we have a full definition. 2697 const CXXRecordDecl *Def = RD->getDefinition(); 2698 if (!Def || Def->isBeingDefined()) 2699 return false; 2700 2701 if (!RD->isAbstract()) 2702 return false; 2703 2704 Diag(Loc, PD) << RD->getDeclName(); 2705 DiagnoseAbstractType(RD); 2706 2707 return true; 2708} 2709 2710void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 2711 // Check if we've already emitted the list of pure virtual functions 2712 // for this class. 2713 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 2714 return; 2715 2716 CXXFinalOverriderMap FinalOverriders; 2717 RD->getFinalOverriders(FinalOverriders); 2718 2719 // Keep a set of seen pure methods so we won't diagnose the same method 2720 // more than once. 2721 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 2722 2723 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 2724 MEnd = FinalOverriders.end(); 2725 M != MEnd; 2726 ++M) { 2727 for (OverridingMethods::iterator SO = M->second.begin(), 2728 SOEnd = M->second.end(); 2729 SO != SOEnd; ++SO) { 2730 // C++ [class.abstract]p4: 2731 // A class is abstract if it contains or inherits at least one 2732 // pure virtual function for which the final overrider is pure 2733 // virtual. 2734 2735 // 2736 if (SO->second.size() != 1) 2737 continue; 2738 2739 if (!SO->second.front().Method->isPure()) 2740 continue; 2741 2742 if (!SeenPureMethods.insert(SO->second.front().Method)) 2743 continue; 2744 2745 Diag(SO->second.front().Method->getLocation(), 2746 diag::note_pure_virtual_function) 2747 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 2748 } 2749 } 2750 2751 if (!PureVirtualClassDiagSet) 2752 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 2753 PureVirtualClassDiagSet->insert(RD); 2754} 2755 2756namespace { 2757struct AbstractUsageInfo { 2758 Sema &S; 2759 CXXRecordDecl *Record; 2760 CanQualType AbstractType; 2761 bool Invalid; 2762 2763 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 2764 : S(S), Record(Record), 2765 AbstractType(S.Context.getCanonicalType( 2766 S.Context.getTypeDeclType(Record))), 2767 Invalid(false) {} 2768 2769 void DiagnoseAbstractType() { 2770 if (Invalid) return; 2771 S.DiagnoseAbstractType(Record); 2772 Invalid = true; 2773 } 2774 2775 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 2776}; 2777 2778struct CheckAbstractUsage { 2779 AbstractUsageInfo &Info; 2780 const NamedDecl *Ctx; 2781 2782 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 2783 : Info(Info), Ctx(Ctx) {} 2784 2785 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 2786 switch (TL.getTypeLocClass()) { 2787#define ABSTRACT_TYPELOC(CLASS, PARENT) 2788#define TYPELOC(CLASS, PARENT) \ 2789 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break; 2790#include "clang/AST/TypeLocNodes.def" 2791 } 2792 } 2793 2794 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 2795 Visit(TL.getResultLoc(), Sema::AbstractReturnType); 2796 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 2797 if (!TL.getArg(I)) 2798 continue; 2799 2800 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo(); 2801 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 2802 } 2803 } 2804 2805 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 2806 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 2807 } 2808 2809 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 2810 // Visit the type parameters from a permissive context. 2811 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 2812 TemplateArgumentLoc TAL = TL.getArgLoc(I); 2813 if (TAL.getArgument().getKind() == TemplateArgument::Type) 2814 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 2815 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 2816 // TODO: other template argument types? 2817 } 2818 } 2819 2820 // Visit pointee types from a permissive context. 2821#define CheckPolymorphic(Type) \ 2822 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 2823 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 2824 } 2825 CheckPolymorphic(PointerTypeLoc) 2826 CheckPolymorphic(ReferenceTypeLoc) 2827 CheckPolymorphic(MemberPointerTypeLoc) 2828 CheckPolymorphic(BlockPointerTypeLoc) 2829 2830 /// Handle all the types we haven't given a more specific 2831 /// implementation for above. 2832 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 2833 // Every other kind of type that we haven't called out already 2834 // that has an inner type is either (1) sugar or (2) contains that 2835 // inner type in some way as a subobject. 2836 if (TypeLoc Next = TL.getNextTypeLoc()) 2837 return Visit(Next, Sel); 2838 2839 // If there's no inner type and we're in a permissive context, 2840 // don't diagnose. 2841 if (Sel == Sema::AbstractNone) return; 2842 2843 // Check whether the type matches the abstract type. 2844 QualType T = TL.getType(); 2845 if (T->isArrayType()) { 2846 Sel = Sema::AbstractArrayType; 2847 T = Info.S.Context.getBaseElementType(T); 2848 } 2849 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 2850 if (CT != Info.AbstractType) return; 2851 2852 // It matched; do some magic. 2853 if (Sel == Sema::AbstractArrayType) { 2854 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 2855 << T << TL.getSourceRange(); 2856 } else { 2857 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 2858 << Sel << T << TL.getSourceRange(); 2859 } 2860 Info.DiagnoseAbstractType(); 2861 } 2862}; 2863 2864void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 2865 Sema::AbstractDiagSelID Sel) { 2866 CheckAbstractUsage(*this, D).Visit(TL, Sel); 2867} 2868 2869} 2870 2871/// Check for invalid uses of an abstract type in a method declaration. 2872static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 2873 CXXMethodDecl *MD) { 2874 // No need to do the check on definitions, which require that 2875 // the return/param types be complete. 2876 if (MD->doesThisDeclarationHaveABody()) 2877 return; 2878 2879 // For safety's sake, just ignore it if we don't have type source 2880 // information. This should never happen for non-implicit methods, 2881 // but... 2882 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 2883 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 2884} 2885 2886/// Check for invalid uses of an abstract type within a class definition. 2887static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 2888 CXXRecordDecl *RD) { 2889 for (CXXRecordDecl::decl_iterator 2890 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) { 2891 Decl *D = *I; 2892 if (D->isImplicit()) continue; 2893 2894 // Methods and method templates. 2895 if (isa<CXXMethodDecl>(D)) { 2896 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 2897 } else if (isa<FunctionTemplateDecl>(D)) { 2898 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 2899 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 2900 2901 // Fields and static variables. 2902 } else if (isa<FieldDecl>(D)) { 2903 FieldDecl *FD = cast<FieldDecl>(D); 2904 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 2905 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 2906 } else if (isa<VarDecl>(D)) { 2907 VarDecl *VD = cast<VarDecl>(D); 2908 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 2909 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 2910 2911 // Nested classes and class templates. 2912 } else if (isa<CXXRecordDecl>(D)) { 2913 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 2914 } else if (isa<ClassTemplateDecl>(D)) { 2915 CheckAbstractClassUsage(Info, 2916 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 2917 } 2918 } 2919} 2920 2921/// \brief Perform semantic checks on a class definition that has been 2922/// completing, introducing implicitly-declared members, checking for 2923/// abstract types, etc. 2924void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 2925 if (!Record) 2926 return; 2927 2928 if (Record->isAbstract() && !Record->isInvalidDecl()) { 2929 AbstractUsageInfo Info(*this, Record); 2930 CheckAbstractClassUsage(Info, Record); 2931 } 2932 2933 // If this is not an aggregate type and has no user-declared constructor, 2934 // complain about any non-static data members of reference or const scalar 2935 // type, since they will never get initializers. 2936 if (!Record->isInvalidDecl() && !Record->isDependentType() && 2937 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) { 2938 bool Complained = false; 2939 for (RecordDecl::field_iterator F = Record->field_begin(), 2940 FEnd = Record->field_end(); 2941 F != FEnd; ++F) { 2942 if (F->getType()->isReferenceType() || 2943 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 2944 if (!Complained) { 2945 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 2946 << Record->getTagKind() << Record; 2947 Complained = true; 2948 } 2949 2950 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 2951 << F->getType()->isReferenceType() 2952 << F->getDeclName(); 2953 } 2954 } 2955 } 2956 2957 if (Record->isDynamicClass() && !Record->isDependentType()) 2958 DynamicClasses.push_back(Record); 2959 2960 if (Record->getIdentifier()) { 2961 // C++ [class.mem]p13: 2962 // If T is the name of a class, then each of the following shall have a 2963 // name different from T: 2964 // - every member of every anonymous union that is a member of class T. 2965 // 2966 // C++ [class.mem]p14: 2967 // In addition, if class T has a user-declared constructor (12.1), every 2968 // non-static data member of class T shall have a name different from T. 2969 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 2970 R.first != R.second; ++R.first) { 2971 NamedDecl *D = *R.first; 2972 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 2973 isa<IndirectFieldDecl>(D)) { 2974 Diag(D->getLocation(), diag::err_member_name_of_class) 2975 << D->getDeclName(); 2976 break; 2977 } 2978 } 2979 } 2980 2981 // Warn if the class has virtual methods but non-virtual public destructor. 2982 if (Record->isPolymorphic() && !Record->isDependentType()) { 2983 CXXDestructorDecl *dtor = Record->getDestructor(); 2984 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) 2985 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 2986 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 2987 } 2988 2989 // See if a method overloads virtual methods in a base 2990 /// class without overriding any. 2991 if (!Record->isDependentType()) { 2992 for (CXXRecordDecl::method_iterator M = Record->method_begin(), 2993 MEnd = Record->method_end(); 2994 M != MEnd; ++M) { 2995 if (!(*M)->isStatic()) 2996 DiagnoseHiddenVirtualMethods(Record, *M); 2997 } 2998 } 2999 3000 // Declare inherited constructors. We do this eagerly here because: 3001 // - The standard requires an eager diagnostic for conflicting inherited 3002 // constructors from different classes. 3003 // - The lazy declaration of the other implicit constructors is so as to not 3004 // waste space and performance on classes that are not meant to be 3005 // instantiated (e.g. meta-functions). This doesn't apply to classes that 3006 // have inherited constructors. 3007 DeclareInheritedConstructors(Record); 3008 3009 if (!Record->isDependentType()) 3010 CheckExplicitlyDefaultedMethods(Record); 3011} 3012 3013void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) { 3014 for (CXXRecordDecl::method_iterator MI = Record->method_begin(), 3015 ME = Record->method_end(); 3016 MI != ME; ++MI) { 3017 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) { 3018 switch (getSpecialMember(*MI)) { 3019 case CXXDefaultConstructor: 3020 CheckExplicitlyDefaultedDefaultConstructor( 3021 cast<CXXConstructorDecl>(*MI)); 3022 break; 3023 3024 case CXXDestructor: 3025 CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI)); 3026 break; 3027 3028 case CXXCopyConstructor: 3029 CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI)); 3030 break; 3031 3032 case CXXCopyAssignment: 3033 CheckExplicitlyDefaultedCopyAssignment(*MI); 3034 break; 3035 3036 case CXXMoveConstructor: 3037 case CXXMoveAssignment: 3038 Diag(MI->getLocation(), diag::err_defaulted_move_unsupported); 3039 break; 3040 3041 default: 3042 // FIXME: Do moves once they exist 3043 llvm_unreachable("non-special member explicitly defaulted!"); 3044 } 3045 } 3046 } 3047 3048} 3049 3050void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) { 3051 assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor()); 3052 3053 // Whether this was the first-declared instance of the constructor. 3054 // This affects whether we implicitly add an exception spec (and, eventually, 3055 // constexpr). It is also ill-formed to explicitly default a constructor such 3056 // that it would be deleted. (C++0x [decl.fct.def.default]) 3057 bool First = CD == CD->getCanonicalDecl(); 3058 3059 bool HadError = false; 3060 if (CD->getNumParams() != 0) { 3061 Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params) 3062 << CD->getSourceRange(); 3063 HadError = true; 3064 } 3065 3066 ImplicitExceptionSpecification Spec 3067 = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent()); 3068 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 3069 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(), 3070 *ExceptionType = Context.getFunctionType( 3071 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>(); 3072 3073 if (CtorType->hasExceptionSpec()) { 3074 if (CheckEquivalentExceptionSpec( 3075 PDiag(diag::err_incorrect_defaulted_exception_spec) 3076 << CXXDefaultConstructor, 3077 PDiag(), 3078 ExceptionType, SourceLocation(), 3079 CtorType, CD->getLocation())) { 3080 HadError = true; 3081 } 3082 } else if (First) { 3083 // We set the declaration to have the computed exception spec here. 3084 // We know there are no parameters. 3085 EPI.ExtInfo = CtorType->getExtInfo(); 3086 CD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI)); 3087 } 3088 3089 if (HadError) { 3090 CD->setInvalidDecl(); 3091 return; 3092 } 3093 3094 if (ShouldDeleteDefaultConstructor(CD)) { 3095 if (First) { 3096 CD->setDeletedAsWritten(); 3097 } else { 3098 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes) 3099 << CXXDefaultConstructor; 3100 CD->setInvalidDecl(); 3101 } 3102 } 3103} 3104 3105void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) { 3106 assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor()); 3107 3108 // Whether this was the first-declared instance of the constructor. 3109 bool First = CD == CD->getCanonicalDecl(); 3110 3111 bool HadError = false; 3112 if (CD->getNumParams() != 1) { 3113 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params) 3114 << CD->getSourceRange(); 3115 HadError = true; 3116 } 3117 3118 ImplicitExceptionSpecification Spec(Context); 3119 bool Const; 3120 llvm::tie(Spec, Const) = 3121 ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent()); 3122 3123 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 3124 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(), 3125 *ExceptionType = Context.getFunctionType( 3126 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>(); 3127 3128 // Check for parameter type matching. 3129 // This is a copy ctor so we know it's a cv-qualified reference to T. 3130 QualType ArgType = CtorType->getArgType(0); 3131 if (ArgType->getPointeeType().isVolatileQualified()) { 3132 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param); 3133 HadError = true; 3134 } 3135 if (ArgType->getPointeeType().isConstQualified() && !Const) { 3136 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param); 3137 HadError = true; 3138 } 3139 3140 if (CtorType->hasExceptionSpec()) { 3141 if (CheckEquivalentExceptionSpec( 3142 PDiag(diag::err_incorrect_defaulted_exception_spec) 3143 << CXXCopyConstructor, 3144 PDiag(), 3145 ExceptionType, SourceLocation(), 3146 CtorType, CD->getLocation())) { 3147 HadError = true; 3148 } 3149 } else if (First) { 3150 // We set the declaration to have the computed exception spec here. 3151 // We duplicate the one parameter type. 3152 EPI.ExtInfo = CtorType->getExtInfo(); 3153 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI)); 3154 } 3155 3156 if (HadError) { 3157 CD->setInvalidDecl(); 3158 return; 3159 } 3160 3161 if (ShouldDeleteCopyConstructor(CD)) { 3162 if (First) { 3163 CD->setDeletedAsWritten(); 3164 } else { 3165 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes) 3166 << CXXCopyConstructor; 3167 CD->setInvalidDecl(); 3168 } 3169 } 3170} 3171 3172void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) { 3173 assert(MD->isExplicitlyDefaulted()); 3174 3175 // Whether this was the first-declared instance of the operator 3176 bool First = MD == MD->getCanonicalDecl(); 3177 3178 bool HadError = false; 3179 if (MD->getNumParams() != 1) { 3180 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params) 3181 << MD->getSourceRange(); 3182 HadError = true; 3183 } 3184 3185 QualType ReturnType = 3186 MD->getType()->getAs<FunctionType>()->getResultType(); 3187 if (!ReturnType->isLValueReferenceType() || 3188 !Context.hasSameType( 3189 Context.getCanonicalType(ReturnType->getPointeeType()), 3190 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) { 3191 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type); 3192 HadError = true; 3193 } 3194 3195 ImplicitExceptionSpecification Spec(Context); 3196 bool Const; 3197 llvm::tie(Spec, Const) = 3198 ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent()); 3199 3200 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 3201 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(), 3202 *ExceptionType = Context.getFunctionType( 3203 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>(); 3204 3205 QualType ArgType = OperType->getArgType(0); 3206 if (!ArgType->isReferenceType()) { 3207 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 3208 HadError = true; 3209 } else { 3210 if (ArgType->getPointeeType().isVolatileQualified()) { 3211 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param); 3212 HadError = true; 3213 } 3214 if (ArgType->getPointeeType().isConstQualified() && !Const) { 3215 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param); 3216 HadError = true; 3217 } 3218 } 3219 3220 if (OperType->getTypeQuals()) { 3221 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals); 3222 HadError = true; 3223 } 3224 3225 if (OperType->hasExceptionSpec()) { 3226 if (CheckEquivalentExceptionSpec( 3227 PDiag(diag::err_incorrect_defaulted_exception_spec) 3228 << CXXCopyAssignment, 3229 PDiag(), 3230 ExceptionType, SourceLocation(), 3231 OperType, MD->getLocation())) { 3232 HadError = true; 3233 } 3234 } else if (First) { 3235 // We set the declaration to have the computed exception spec here. 3236 // We duplicate the one parameter type. 3237 EPI.RefQualifier = OperType->getRefQualifier(); 3238 EPI.ExtInfo = OperType->getExtInfo(); 3239 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI)); 3240 } 3241 3242 if (HadError) { 3243 MD->setInvalidDecl(); 3244 return; 3245 } 3246 3247 if (ShouldDeleteCopyAssignmentOperator(MD)) { 3248 if (First) { 3249 MD->setDeletedAsWritten(); 3250 } else { 3251 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) 3252 << CXXCopyAssignment; 3253 MD->setInvalidDecl(); 3254 } 3255 } 3256} 3257 3258void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) { 3259 assert(DD->isExplicitlyDefaulted()); 3260 3261 // Whether this was the first-declared instance of the destructor. 3262 bool First = DD == DD->getCanonicalDecl(); 3263 3264 ImplicitExceptionSpecification Spec 3265 = ComputeDefaultedDtorExceptionSpec(DD->getParent()); 3266 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 3267 const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(), 3268 *ExceptionType = Context.getFunctionType( 3269 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>(); 3270 3271 if (DtorType->hasExceptionSpec()) { 3272 if (CheckEquivalentExceptionSpec( 3273 PDiag(diag::err_incorrect_defaulted_exception_spec) 3274 << CXXDestructor, 3275 PDiag(), 3276 ExceptionType, SourceLocation(), 3277 DtorType, DD->getLocation())) { 3278 DD->setInvalidDecl(); 3279 return; 3280 } 3281 } else if (First) { 3282 // We set the declaration to have the computed exception spec here. 3283 // There are no parameters. 3284 EPI.ExtInfo = DtorType->getExtInfo(); 3285 DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI)); 3286 } 3287 3288 if (ShouldDeleteDestructor(DD)) { 3289 if (First) { 3290 DD->setDeletedAsWritten(); 3291 } else { 3292 Diag(DD->getLocation(), diag::err_out_of_line_default_deletes) 3293 << CXXDestructor; 3294 DD->setInvalidDecl(); 3295 } 3296 } 3297} 3298 3299bool Sema::ShouldDeleteDefaultConstructor(CXXConstructorDecl *CD) { 3300 CXXRecordDecl *RD = CD->getParent(); 3301 assert(!RD->isDependentType() && "do deletion after instantiation"); 3302 if (!LangOpts.CPlusPlus0x) 3303 return false; 3304 3305 SourceLocation Loc = CD->getLocation(); 3306 3307 // Do access control from the constructor 3308 ContextRAII CtorContext(*this, CD); 3309 3310 bool Union = RD->isUnion(); 3311 bool AllConst = true; 3312 3313 // We do this because we should never actually use an anonymous 3314 // union's constructor. 3315 if (Union && RD->isAnonymousStructOrUnion()) 3316 return false; 3317 3318 // FIXME: We should put some diagnostic logic right into this function. 3319 3320 // C++0x [class.ctor]/5 3321 // A defaulted default constructor for class X is defined as delete if: 3322 3323 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 3324 BE = RD->bases_end(); 3325 BI != BE; ++BI) { 3326 // We'll handle this one later 3327 if (BI->isVirtual()) 3328 continue; 3329 3330 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl(); 3331 assert(BaseDecl && "base isn't a CXXRecordDecl"); 3332 3333 // -- any [direct base class] has a type with a destructor that is 3334 // delete or inaccessible from the defaulted default constructor 3335 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl); 3336 if (BaseDtor->isDeleted()) 3337 return true; 3338 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) != 3339 AR_accessible) 3340 return true; 3341 3342 // -- any [direct base class either] has no default constructor or 3343 // overload resolution as applied to [its] default constructor 3344 // results in an ambiguity or in a function that is deleted or 3345 // inaccessible from the defaulted default constructor 3346 InitializedEntity BaseEntity = 3347 InitializedEntity::InitializeBase(Context, BI, 0); 3348 InitializationKind Kind = 3349 InitializationKind::CreateDirect(Loc, Loc, Loc); 3350 3351 InitializationSequence InitSeq(*this, BaseEntity, Kind, 0, 0); 3352 3353 if (InitSeq.Failed()) 3354 return true; 3355 } 3356 3357 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(), 3358 BE = RD->vbases_end(); 3359 BI != BE; ++BI) { 3360 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl(); 3361 assert(BaseDecl && "base isn't a CXXRecordDecl"); 3362 3363 // -- any [virtual base class] has a type with a destructor that is 3364 // delete or inaccessible from the defaulted default constructor 3365 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl); 3366 if (BaseDtor->isDeleted()) 3367 return true; 3368 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) != 3369 AR_accessible) 3370 return true; 3371 3372 // -- any [virtual base class either] has no default constructor or 3373 // overload resolution as applied to [its] default constructor 3374 // results in an ambiguity or in a function that is deleted or 3375 // inaccessible from the defaulted default constructor 3376 InitializedEntity BaseEntity = 3377 InitializedEntity::InitializeBase(Context, BI, BI); 3378 InitializationKind Kind = 3379 InitializationKind::CreateDirect(Loc, Loc, Loc); 3380 3381 InitializationSequence InitSeq(*this, BaseEntity, Kind, 0, 0); 3382 3383 if (InitSeq.Failed()) 3384 return true; 3385 } 3386 3387 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 3388 FE = RD->field_end(); 3389 FI != FE; ++FI) { 3390 QualType FieldType = Context.getBaseElementType(FI->getType()); 3391 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 3392 3393 // -- any non-static data member with no brace-or-equal-initializer is of 3394 // reference type 3395 if (FieldType->isReferenceType()) 3396 return true; 3397 3398 // -- X is a union and all its variant members are of const-qualified type 3399 // (or array thereof) 3400 if (Union && !FieldType.isConstQualified()) 3401 AllConst = false; 3402 3403 if (FieldRecord) { 3404 // -- X is a union-like class that has a variant member with a non-trivial 3405 // default constructor 3406 if (Union && !FieldRecord->hasTrivialDefaultConstructor()) 3407 return true; 3408 3409 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord); 3410 if (FieldDtor->isDeleted()) 3411 return true; 3412 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) != 3413 AR_accessible) 3414 return true; 3415 3416 // -- any non-variant non-static data member of const-qualified type (or 3417 // array thereof) with no brace-or-equal-initializer does not have a 3418 // user-provided default constructor 3419 if (FieldType.isConstQualified() && 3420 !FieldRecord->hasUserProvidedDefaultConstructor()) 3421 return true; 3422 3423 if (!Union && FieldRecord->isUnion() && 3424 FieldRecord->isAnonymousStructOrUnion()) { 3425 // We're okay to reuse AllConst here since we only care about the 3426 // value otherwise if we're in a union. 3427 AllConst = true; 3428 3429 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(), 3430 UE = FieldRecord->field_end(); 3431 UI != UE; ++UI) { 3432 QualType UnionFieldType = Context.getBaseElementType(UI->getType()); 3433 CXXRecordDecl *UnionFieldRecord = 3434 UnionFieldType->getAsCXXRecordDecl(); 3435 3436 if (!UnionFieldType.isConstQualified()) 3437 AllConst = false; 3438 3439 if (UnionFieldRecord && 3440 !UnionFieldRecord->hasTrivialDefaultConstructor()) 3441 return true; 3442 } 3443 3444 if (AllConst) 3445 return true; 3446 3447 // Don't try to initialize the anonymous union 3448 // This is technically non-conformant, but sanity demands it. 3449 continue; 3450 } 3451 } else if (!Union && FieldType.isConstQualified()) { 3452 // -- any non-variant non-static data member of const-qualified type (or 3453 // array thereof) with no brace-or-equal-initializer does not have a 3454 // user-provided default constructor 3455 return true; 3456 } 3457 3458 InitializedEntity MemberEntity = 3459 InitializedEntity::InitializeMember(*FI, 0); 3460 InitializationKind Kind = 3461 InitializationKind::CreateDirect(Loc, Loc, Loc); 3462 3463 InitializationSequence InitSeq(*this, MemberEntity, Kind, 0, 0); 3464 3465 if (InitSeq.Failed()) 3466 return true; 3467 } 3468 3469 if (Union && AllConst) 3470 return true; 3471 3472 return false; 3473} 3474 3475bool Sema::ShouldDeleteCopyConstructor(CXXConstructorDecl *CD) { 3476 CXXRecordDecl *RD = CD->getParent(); 3477 assert(!RD->isDependentType() && "do deletion after instantiation"); 3478 if (!LangOpts.CPlusPlus0x) 3479 return false; 3480 3481 SourceLocation Loc = CD->getLocation(); 3482 3483 // Do access control from the constructor 3484 ContextRAII CtorContext(*this, CD); 3485 3486 bool Union = RD->isUnion(); 3487 3488 assert(!CD->getParamDecl(0)->getType()->getPointeeType().isNull() && 3489 "copy assignment arg has no pointee type"); 3490 bool ConstArg = 3491 CD->getParamDecl(0)->getType()->getPointeeType().isConstQualified(); 3492 3493 // We do this because we should never actually use an anonymous 3494 // union's constructor. 3495 if (Union && RD->isAnonymousStructOrUnion()) 3496 return false; 3497 3498 // FIXME: We should put some diagnostic logic right into this function. 3499 3500 // C++0x [class.copy]/11 3501 // A defaulted [copy] constructor for class X is defined as delete if X has: 3502 3503 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 3504 BE = RD->bases_end(); 3505 BI != BE; ++BI) { 3506 // We'll handle this one later 3507 if (BI->isVirtual()) 3508 continue; 3509 3510 QualType BaseType = BI->getType(); 3511 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl(); 3512 assert(BaseDecl && "base isn't a CXXRecordDecl"); 3513 3514 // -- any [direct base class] of a type with a destructor that is deleted or 3515 // inaccessible from the defaulted constructor 3516 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl); 3517 if (BaseDtor->isDeleted()) 3518 return true; 3519 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) != 3520 AR_accessible) 3521 return true; 3522 3523 // -- a [direct base class] B that cannot be [copied] because overload 3524 // resolution, as applied to B's [copy] constructor, results in an 3525 // ambiguity or a function that is deleted or inaccessible from the 3526 // defaulted constructor 3527 InitializedEntity BaseEntity = 3528 InitializedEntity::InitializeBase(Context, BI, 0); 3529 InitializationKind Kind = 3530 InitializationKind::CreateDirect(Loc, Loc, Loc); 3531 3532 // Construct a fake expression to perform the copy overloading. 3533 QualType ArgType = BaseType.getUnqualifiedType(); 3534 if (ConstArg) 3535 ArgType.addConst(); 3536 Expr *Arg = new (Context) OpaqueValueExpr(Loc, ArgType, VK_LValue); 3537 3538 InitializationSequence InitSeq(*this, BaseEntity, Kind, &Arg, 1); 3539 3540 if (InitSeq.Failed()) 3541 return true; 3542 } 3543 3544 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(), 3545 BE = RD->vbases_end(); 3546 BI != BE; ++BI) { 3547 QualType BaseType = BI->getType(); 3548 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl(); 3549 assert(BaseDecl && "base isn't a CXXRecordDecl"); 3550 3551 // -- any [direct base class] of a type with a destructor that is deleted or 3552 // inaccessible from the defaulted constructor 3553 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl); 3554 if (BaseDtor->isDeleted()) 3555 return true; 3556 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) != 3557 AR_accessible) 3558 return true; 3559 3560 // -- a [virtual base class] B that cannot be [copied] because overload 3561 // resolution, as applied to B's [copy] constructor, results in an 3562 // ambiguity or a function that is deleted or inaccessible from the 3563 // defaulted constructor 3564 InitializedEntity BaseEntity = 3565 InitializedEntity::InitializeBase(Context, BI, BI); 3566 InitializationKind Kind = 3567 InitializationKind::CreateDirect(Loc, Loc, Loc); 3568 3569 // Construct a fake expression to perform the copy overloading. 3570 QualType ArgType = BaseType.getUnqualifiedType(); 3571 if (ConstArg) 3572 ArgType.addConst(); 3573 Expr *Arg = new (Context) OpaqueValueExpr(Loc, ArgType, VK_LValue); 3574 3575 InitializationSequence InitSeq(*this, BaseEntity, Kind, &Arg, 1); 3576 3577 if (InitSeq.Failed()) 3578 return true; 3579 } 3580 3581 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 3582 FE = RD->field_end(); 3583 FI != FE; ++FI) { 3584 QualType FieldType = Context.getBaseElementType(FI->getType()); 3585 3586 // -- for a copy constructor, a non-static data member of rvalue reference 3587 // type 3588 if (FieldType->isRValueReferenceType()) 3589 return true; 3590 3591 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 3592 3593 if (FieldRecord) { 3594 // This is an anonymous union 3595 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) { 3596 // Anonymous unions inside unions do not variant members create 3597 if (!Union) { 3598 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(), 3599 UE = FieldRecord->field_end(); 3600 UI != UE; ++UI) { 3601 QualType UnionFieldType = Context.getBaseElementType(UI->getType()); 3602 CXXRecordDecl *UnionFieldRecord = 3603 UnionFieldType->getAsCXXRecordDecl(); 3604 3605 // -- a variant member with a non-trivial [copy] constructor and X 3606 // is a union-like class 3607 if (UnionFieldRecord && 3608 !UnionFieldRecord->hasTrivialCopyConstructor()) 3609 return true; 3610 } 3611 } 3612 3613 // Don't try to initalize an anonymous union 3614 continue; 3615 } else { 3616 // -- a variant member with a non-trivial [copy] constructor and X is a 3617 // union-like class 3618 if (Union && !FieldRecord->hasTrivialCopyConstructor()) 3619 return true; 3620 3621 // -- any [non-static data member] of a type with a destructor that is 3622 // deleted or inaccessible from the defaulted constructor 3623 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord); 3624 if (FieldDtor->isDeleted()) 3625 return true; 3626 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) != 3627 AR_accessible) 3628 return true; 3629 } 3630 } 3631 3632 llvm::SmallVector<InitializedEntity, 4> Entities; 3633 QualType CurType = FI->getType(); 3634 Entities.push_back(InitializedEntity::InitializeMember(*FI, 0)); 3635 while (CurType->isArrayType()) { 3636 Entities.push_back(InitializedEntity::InitializeElement(Context, 0, 3637 Entities.back())); 3638 CurType = Context.getAsArrayType(CurType)->getElementType(); 3639 } 3640 3641 InitializationKind Kind = 3642 InitializationKind::CreateDirect(Loc, Loc, Loc); 3643 3644 // Construct a fake expression to perform the copy overloading. 3645 QualType ArgType = FieldType; 3646 if (ArgType->isReferenceType()) 3647 ArgType = ArgType->getPointeeType(); 3648 else if (ConstArg) 3649 ArgType.addConst(); 3650 Expr *Arg = new (Context) OpaqueValueExpr(Loc, ArgType, VK_LValue); 3651 3652 InitializationSequence InitSeq(*this, Entities.back(), Kind, &Arg, 1); 3653 3654 if (InitSeq.Failed()) 3655 return true; 3656 } 3657 3658 return false; 3659} 3660 3661bool Sema::ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD) { 3662 CXXRecordDecl *RD = MD->getParent(); 3663 assert(!RD->isDependentType() && "do deletion after instantiation"); 3664 if (!LangOpts.CPlusPlus0x) 3665 return false; 3666 3667 SourceLocation Loc = MD->getLocation(); 3668 3669 // Do access control from the constructor 3670 ContextRAII MethodContext(*this, MD); 3671 3672 bool Union = RD->isUnion(); 3673 3674 bool ConstArg = 3675 MD->getParamDecl(0)->getType()->getPointeeType().isConstQualified(); 3676 3677 // We do this because we should never actually use an anonymous 3678 // union's constructor. 3679 if (Union && RD->isAnonymousStructOrUnion()) 3680 return false; 3681 3682 DeclarationName OperatorName = 3683 Context.DeclarationNames.getCXXOperatorName(OO_Equal); 3684 LookupResult R(*this, OperatorName, Loc, LookupOrdinaryName); 3685 R.suppressDiagnostics(); 3686 3687 // FIXME: We should put some diagnostic logic right into this function. 3688 3689 // C++0x [class.copy]/11 3690 // A defaulted [copy] assignment operator for class X is defined as deleted 3691 // if X has: 3692 3693 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 3694 BE = RD->bases_end(); 3695 BI != BE; ++BI) { 3696 // We'll handle this one later 3697 if (BI->isVirtual()) 3698 continue; 3699 3700 QualType BaseType = BI->getType(); 3701 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl(); 3702 assert(BaseDecl && "base isn't a CXXRecordDecl"); 3703 3704 // -- a [direct base class] B that cannot be [copied] because overload 3705 // resolution, as applied to B's [copy] assignment operator, results in 3706 // an ambiguity or a function that is deleted or inaccessible from the 3707 // assignment operator 3708 3709 LookupQualifiedName(R, BaseDecl, false); 3710 3711 // Filter out any result that isn't a copy-assignment operator. 3712 LookupResult::Filter F = R.makeFilter(); 3713 while (F.hasNext()) { 3714 NamedDecl *D = F.next(); 3715 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 3716 if (Method->isCopyAssignmentOperator()) 3717 continue; 3718 3719 F.erase(); 3720 } 3721 F.done(); 3722 3723 // Build a fake argument expression 3724 QualType ArgType = BaseType; 3725 QualType ThisType = BaseType; 3726 if (ConstArg) 3727 ArgType.addConst(); 3728 Expr *Args[] = { new (Context) OpaqueValueExpr(Loc, ThisType, VK_LValue) 3729 , new (Context) OpaqueValueExpr(Loc, ArgType, VK_LValue) 3730 }; 3731 3732 OverloadCandidateSet OCS((Loc)); 3733 OverloadCandidateSet::iterator Best; 3734 3735 AddFunctionCandidates(R.asUnresolvedSet(), Args, 2, OCS); 3736 3737 if (OCS.BestViableFunction(*this, Loc, Best, false) != 3738 OR_Success) 3739 return true; 3740 } 3741 3742 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(), 3743 BE = RD->vbases_end(); 3744 BI != BE; ++BI) { 3745 QualType BaseType = BI->getType(); 3746 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl(); 3747 assert(BaseDecl && "base isn't a CXXRecordDecl"); 3748 3749 // -- a [virtual base class] B that cannot be [copied] because overload 3750 // resolution, as applied to B's [copy] assignment operator, results in 3751 // an ambiguity or a function that is deleted or inaccessible from the 3752 // assignment operator 3753 3754 LookupQualifiedName(R, BaseDecl, false); 3755 3756 // Filter out any result that isn't a copy-assignment operator. 3757 LookupResult::Filter F = R.makeFilter(); 3758 while (F.hasNext()) { 3759 NamedDecl *D = F.next(); 3760 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 3761 if (Method->isCopyAssignmentOperator()) 3762 continue; 3763 3764 F.erase(); 3765 } 3766 F.done(); 3767 3768 // Build a fake argument expression 3769 QualType ArgType = BaseType; 3770 QualType ThisType = BaseType; 3771 if (ConstArg) 3772 ArgType.addConst(); 3773 Expr *Args[] = { new (Context) OpaqueValueExpr(Loc, ThisType, VK_LValue) 3774 , new (Context) OpaqueValueExpr(Loc, ArgType, VK_LValue) 3775 }; 3776 3777 OverloadCandidateSet OCS((Loc)); 3778 OverloadCandidateSet::iterator Best; 3779 3780 AddFunctionCandidates(R.asUnresolvedSet(), Args, 2, OCS); 3781 3782 if (OCS.BestViableFunction(*this, Loc, Best, false) != 3783 OR_Success) 3784 return true; 3785 } 3786 3787 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 3788 FE = RD->field_end(); 3789 FI != FE; ++FI) { 3790 QualType FieldType = Context.getBaseElementType(FI->getType()); 3791 3792 // -- a non-static data member of reference type 3793 if (FieldType->isReferenceType()) 3794 return true; 3795 3796 // -- a non-static data member of const non-class type (or array thereof) 3797 if (FieldType.isConstQualified() && !FieldType->isRecordType()) 3798 return true; 3799 3800 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 3801 3802 if (FieldRecord) { 3803 // This is an anonymous union 3804 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) { 3805 // Anonymous unions inside unions do not variant members create 3806 if (!Union) { 3807 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(), 3808 UE = FieldRecord->field_end(); 3809 UI != UE; ++UI) { 3810 QualType UnionFieldType = Context.getBaseElementType(UI->getType()); 3811 CXXRecordDecl *UnionFieldRecord = 3812 UnionFieldType->getAsCXXRecordDecl(); 3813 3814 // -- a variant member with a non-trivial [copy] assignment operator 3815 // and X is a union-like class 3816 if (UnionFieldRecord && 3817 !UnionFieldRecord->hasTrivialCopyAssignment()) 3818 return true; 3819 } 3820 } 3821 3822 // Don't try to initalize an anonymous union 3823 continue; 3824 // -- a variant member with a non-trivial [copy] assignment operator 3825 // and X is a union-like class 3826 } else if (Union && !FieldRecord->hasTrivialCopyAssignment()) { 3827 return true; 3828 } 3829 3830 LookupQualifiedName(R, FieldRecord, false); 3831 3832 // Filter out any result that isn't a copy-assignment operator. 3833 LookupResult::Filter F = R.makeFilter(); 3834 while (F.hasNext()) { 3835 NamedDecl *D = F.next(); 3836 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 3837 if (Method->isCopyAssignmentOperator()) 3838 continue; 3839 3840 F.erase(); 3841 } 3842 F.done(); 3843 3844 // Build a fake argument expression 3845 QualType ArgType = FieldType; 3846 QualType ThisType = FieldType; 3847 if (ConstArg) 3848 ArgType.addConst(); 3849 Expr *Args[] = { new (Context) OpaqueValueExpr(Loc, ThisType, VK_LValue) 3850 , new (Context) OpaqueValueExpr(Loc, ArgType, VK_LValue) 3851 }; 3852 3853 OverloadCandidateSet OCS((Loc)); 3854 OverloadCandidateSet::iterator Best; 3855 3856 AddFunctionCandidates(R.asUnresolvedSet(), Args, 2, OCS); 3857 3858 if (OCS.BestViableFunction(*this, Loc, Best, false) != 3859 OR_Success) 3860 return true; 3861 } 3862 } 3863 3864 return false; 3865} 3866 3867bool Sema::ShouldDeleteDestructor(CXXDestructorDecl *DD) { 3868 CXXRecordDecl *RD = DD->getParent(); 3869 assert(!RD->isDependentType() && "do deletion after instantiation"); 3870 if (!LangOpts.CPlusPlus0x) 3871 return false; 3872 3873 SourceLocation Loc = DD->getLocation(); 3874 3875 // Do access control from the destructor 3876 ContextRAII CtorContext(*this, DD); 3877 3878 bool Union = RD->isUnion(); 3879 3880 // We do this because we should never actually use an anonymous 3881 // union's destructor. 3882 if (Union && RD->isAnonymousStructOrUnion()) 3883 return false; 3884 3885 // C++0x [class.dtor]p5 3886 // A defaulted destructor for a class X is defined as deleted if: 3887 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 3888 BE = RD->bases_end(); 3889 BI != BE; ++BI) { 3890 // We'll handle this one later 3891 if (BI->isVirtual()) 3892 continue; 3893 3894 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl(); 3895 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl); 3896 assert(BaseDtor && "base has no destructor"); 3897 3898 // -- any direct or virtual base class has a deleted destructor or 3899 // a destructor that is inaccessible from the defaulted destructor 3900 if (BaseDtor->isDeleted()) 3901 return true; 3902 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) != 3903 AR_accessible) 3904 return true; 3905 } 3906 3907 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(), 3908 BE = RD->vbases_end(); 3909 BI != BE; ++BI) { 3910 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl(); 3911 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl); 3912 assert(BaseDtor && "base has no destructor"); 3913 3914 // -- any direct or virtual base class has a deleted destructor or 3915 // a destructor that is inaccessible from the defaulted destructor 3916 if (BaseDtor->isDeleted()) 3917 return true; 3918 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) != 3919 AR_accessible) 3920 return true; 3921 } 3922 3923 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 3924 FE = RD->field_end(); 3925 FI != FE; ++FI) { 3926 QualType FieldType = Context.getBaseElementType(FI->getType()); 3927 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 3928 if (FieldRecord) { 3929 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) { 3930 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(), 3931 UE = FieldRecord->field_end(); 3932 UI != UE; ++UI) { 3933 QualType UnionFieldType = Context.getBaseElementType(FI->getType()); 3934 CXXRecordDecl *UnionFieldRecord = 3935 UnionFieldType->getAsCXXRecordDecl(); 3936 3937 // -- X is a union-like class that has a variant member with a non- 3938 // trivial destructor. 3939 if (UnionFieldRecord && !UnionFieldRecord->hasTrivialDestructor()) 3940 return true; 3941 } 3942 // Technically we are supposed to do this next check unconditionally. 3943 // But that makes absolutely no sense. 3944 } else { 3945 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord); 3946 3947 // -- any of the non-static data members has class type M (or array 3948 // thereof) and M has a deleted destructor or a destructor that is 3949 // inaccessible from the defaulted destructor 3950 if (FieldDtor->isDeleted()) 3951 return true; 3952 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) != 3953 AR_accessible) 3954 return true; 3955 3956 // -- X is a union-like class that has a variant member with a non- 3957 // trivial destructor. 3958 if (Union && !FieldDtor->isTrivial()) 3959 return true; 3960 } 3961 } 3962 } 3963 3964 if (DD->isVirtual()) { 3965 FunctionDecl *OperatorDelete = 0; 3966 DeclarationName Name = 3967 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 3968 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete, 3969 false)) 3970 return true; 3971 } 3972 3973 3974 return false; 3975} 3976 3977/// \brief Data used with FindHiddenVirtualMethod 3978namespace { 3979 struct FindHiddenVirtualMethodData { 3980 Sema *S; 3981 CXXMethodDecl *Method; 3982 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 3983 llvm::SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 3984 }; 3985} 3986 3987/// \brief Member lookup function that determines whether a given C++ 3988/// method overloads virtual methods in a base class without overriding any, 3989/// to be used with CXXRecordDecl::lookupInBases(). 3990static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier, 3991 CXXBasePath &Path, 3992 void *UserData) { 3993 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 3994 3995 FindHiddenVirtualMethodData &Data 3996 = *static_cast<FindHiddenVirtualMethodData*>(UserData); 3997 3998 DeclarationName Name = Data.Method->getDeclName(); 3999 assert(Name.getNameKind() == DeclarationName::Identifier); 4000 4001 bool foundSameNameMethod = false; 4002 llvm::SmallVector<CXXMethodDecl *, 8> overloadedMethods; 4003 for (Path.Decls = BaseRecord->lookup(Name); 4004 Path.Decls.first != Path.Decls.second; 4005 ++Path.Decls.first) { 4006 NamedDecl *D = *Path.Decls.first; 4007 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 4008 MD = MD->getCanonicalDecl(); 4009 foundSameNameMethod = true; 4010 // Interested only in hidden virtual methods. 4011 if (!MD->isVirtual()) 4012 continue; 4013 // If the method we are checking overrides a method from its base 4014 // don't warn about the other overloaded methods. 4015 if (!Data.S->IsOverload(Data.Method, MD, false)) 4016 return true; 4017 // Collect the overload only if its hidden. 4018 if (!Data.OverridenAndUsingBaseMethods.count(MD)) 4019 overloadedMethods.push_back(MD); 4020 } 4021 } 4022 4023 if (foundSameNameMethod) 4024 Data.OverloadedMethods.append(overloadedMethods.begin(), 4025 overloadedMethods.end()); 4026 return foundSameNameMethod; 4027} 4028 4029/// \brief See if a method overloads virtual methods in a base class without 4030/// overriding any. 4031void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 4032 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual, 4033 MD->getLocation()) == Diagnostic::Ignored) 4034 return; 4035 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier) 4036 return; 4037 4038 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 4039 /*bool RecordPaths=*/false, 4040 /*bool DetectVirtual=*/false); 4041 FindHiddenVirtualMethodData Data; 4042 Data.Method = MD; 4043 Data.S = this; 4044 4045 // Keep the base methods that were overriden or introduced in the subclass 4046 // by 'using' in a set. A base method not in this set is hidden. 4047 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName()); 4048 res.first != res.second; ++res.first) { 4049 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first)) 4050 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 4051 E = MD->end_overridden_methods(); 4052 I != E; ++I) 4053 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl()); 4054 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first)) 4055 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl())) 4056 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl()); 4057 } 4058 4059 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) && 4060 !Data.OverloadedMethods.empty()) { 4061 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 4062 << MD << (Data.OverloadedMethods.size() > 1); 4063 4064 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) { 4065 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i]; 4066 Diag(overloadedMD->getLocation(), 4067 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 4068 } 4069 } 4070} 4071 4072void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 4073 Decl *TagDecl, 4074 SourceLocation LBrac, 4075 SourceLocation RBrac, 4076 AttributeList *AttrList) { 4077 if (!TagDecl) 4078 return; 4079 4080 AdjustDeclIfTemplate(TagDecl); 4081 4082 ActOnFields(S, RLoc, TagDecl, 4083 // strict aliasing violation! 4084 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 4085 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList); 4086 4087 CheckCompletedCXXClass( 4088 dyn_cast_or_null<CXXRecordDecl>(TagDecl)); 4089} 4090 4091/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 4092/// special functions, such as the default constructor, copy 4093/// constructor, or destructor, to the given C++ class (C++ 4094/// [special]p1). This routine can only be executed just before the 4095/// definition of the class is complete. 4096void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 4097 if (!ClassDecl->hasUserDeclaredConstructor()) 4098 ++ASTContext::NumImplicitDefaultConstructors; 4099 4100 if (!ClassDecl->hasUserDeclaredCopyConstructor()) 4101 ++ASTContext::NumImplicitCopyConstructors; 4102 4103 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 4104 ++ASTContext::NumImplicitCopyAssignmentOperators; 4105 4106 // If we have a dynamic class, then the copy assignment operator may be 4107 // virtual, so we have to declare it immediately. This ensures that, e.g., 4108 // it shows up in the right place in the vtable and that we diagnose 4109 // problems with the implicit exception specification. 4110 if (ClassDecl->isDynamicClass()) 4111 DeclareImplicitCopyAssignment(ClassDecl); 4112 } 4113 4114 if (!ClassDecl->hasUserDeclaredDestructor()) { 4115 ++ASTContext::NumImplicitDestructors; 4116 4117 // If we have a dynamic class, then the destructor may be virtual, so we 4118 // have to declare the destructor immediately. This ensures that, e.g., it 4119 // shows up in the right place in the vtable and that we diagnose problems 4120 // with the implicit exception specification. 4121 if (ClassDecl->isDynamicClass()) 4122 DeclareImplicitDestructor(ClassDecl); 4123 } 4124} 4125 4126void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) { 4127 if (!D) 4128 return; 4129 4130 int NumParamList = D->getNumTemplateParameterLists(); 4131 for (int i = 0; i < NumParamList; i++) { 4132 TemplateParameterList* Params = D->getTemplateParameterList(i); 4133 for (TemplateParameterList::iterator Param = Params->begin(), 4134 ParamEnd = Params->end(); 4135 Param != ParamEnd; ++Param) { 4136 NamedDecl *Named = cast<NamedDecl>(*Param); 4137 if (Named->getDeclName()) { 4138 S->AddDecl(Named); 4139 IdResolver.AddDecl(Named); 4140 } 4141 } 4142 } 4143} 4144 4145void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 4146 if (!D) 4147 return; 4148 4149 TemplateParameterList *Params = 0; 4150 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) 4151 Params = Template->getTemplateParameters(); 4152 else if (ClassTemplatePartialSpecializationDecl *PartialSpec 4153 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 4154 Params = PartialSpec->getTemplateParameters(); 4155 else 4156 return; 4157 4158 for (TemplateParameterList::iterator Param = Params->begin(), 4159 ParamEnd = Params->end(); 4160 Param != ParamEnd; ++Param) { 4161 NamedDecl *Named = cast<NamedDecl>(*Param); 4162 if (Named->getDeclName()) { 4163 S->AddDecl(Named); 4164 IdResolver.AddDecl(Named); 4165 } 4166 } 4167} 4168 4169void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 4170 if (!RecordD) return; 4171 AdjustDeclIfTemplate(RecordD); 4172 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 4173 PushDeclContext(S, Record); 4174} 4175 4176void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 4177 if (!RecordD) return; 4178 PopDeclContext(); 4179} 4180 4181/// ActOnStartDelayedCXXMethodDeclaration - We have completed 4182/// parsing a top-level (non-nested) C++ class, and we are now 4183/// parsing those parts of the given Method declaration that could 4184/// not be parsed earlier (C++ [class.mem]p2), such as default 4185/// arguments. This action should enter the scope of the given 4186/// Method declaration as if we had just parsed the qualified method 4187/// name. However, it should not bring the parameters into scope; 4188/// that will be performed by ActOnDelayedCXXMethodParameter. 4189void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 4190} 4191 4192/// ActOnDelayedCXXMethodParameter - We've already started a delayed 4193/// C++ method declaration. We're (re-)introducing the given 4194/// function parameter into scope for use in parsing later parts of 4195/// the method declaration. For example, we could see an 4196/// ActOnParamDefaultArgument event for this parameter. 4197void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 4198 if (!ParamD) 4199 return; 4200 4201 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 4202 4203 // If this parameter has an unparsed default argument, clear it out 4204 // to make way for the parsed default argument. 4205 if (Param->hasUnparsedDefaultArg()) 4206 Param->setDefaultArg(0); 4207 4208 S->AddDecl(Param); 4209 if (Param->getDeclName()) 4210 IdResolver.AddDecl(Param); 4211} 4212 4213/// ActOnFinishDelayedCXXMethodDeclaration - We have finished 4214/// processing the delayed method declaration for Method. The method 4215/// declaration is now considered finished. There may be a separate 4216/// ActOnStartOfFunctionDef action later (not necessarily 4217/// immediately!) for this method, if it was also defined inside the 4218/// class body. 4219void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 4220 if (!MethodD) 4221 return; 4222 4223 AdjustDeclIfTemplate(MethodD); 4224 4225 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 4226 4227 // Now that we have our default arguments, check the constructor 4228 // again. It could produce additional diagnostics or affect whether 4229 // the class has implicitly-declared destructors, among other 4230 // things. 4231 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 4232 CheckConstructor(Constructor); 4233 4234 // Check the default arguments, which we may have added. 4235 if (!Method->isInvalidDecl()) 4236 CheckCXXDefaultArguments(Method); 4237} 4238 4239/// CheckConstructorDeclarator - Called by ActOnDeclarator to check 4240/// the well-formedness of the constructor declarator @p D with type @p 4241/// R. If there are any errors in the declarator, this routine will 4242/// emit diagnostics and set the invalid bit to true. In any case, the type 4243/// will be updated to reflect a well-formed type for the constructor and 4244/// returned. 4245QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 4246 StorageClass &SC) { 4247 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 4248 4249 // C++ [class.ctor]p3: 4250 // A constructor shall not be virtual (10.3) or static (9.4). A 4251 // constructor can be invoked for a const, volatile or const 4252 // volatile object. A constructor shall not be declared const, 4253 // volatile, or const volatile (9.3.2). 4254 if (isVirtual) { 4255 if (!D.isInvalidType()) 4256 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 4257 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 4258 << SourceRange(D.getIdentifierLoc()); 4259 D.setInvalidType(); 4260 } 4261 if (SC == SC_Static) { 4262 if (!D.isInvalidType()) 4263 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 4264 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 4265 << SourceRange(D.getIdentifierLoc()); 4266 D.setInvalidType(); 4267 SC = SC_None; 4268 } 4269 4270 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 4271 if (FTI.TypeQuals != 0) { 4272 if (FTI.TypeQuals & Qualifiers::Const) 4273 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 4274 << "const" << SourceRange(D.getIdentifierLoc()); 4275 if (FTI.TypeQuals & Qualifiers::Volatile) 4276 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 4277 << "volatile" << SourceRange(D.getIdentifierLoc()); 4278 if (FTI.TypeQuals & Qualifiers::Restrict) 4279 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 4280 << "restrict" << SourceRange(D.getIdentifierLoc()); 4281 D.setInvalidType(); 4282 } 4283 4284 // C++0x [class.ctor]p4: 4285 // A constructor shall not be declared with a ref-qualifier. 4286 if (FTI.hasRefQualifier()) { 4287 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 4288 << FTI.RefQualifierIsLValueRef 4289 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 4290 D.setInvalidType(); 4291 } 4292 4293 // Rebuild the function type "R" without any type qualifiers (in 4294 // case any of the errors above fired) and with "void" as the 4295 // return type, since constructors don't have return types. 4296 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 4297 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType()) 4298 return R; 4299 4300 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 4301 EPI.TypeQuals = 0; 4302 EPI.RefQualifier = RQ_None; 4303 4304 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(), 4305 Proto->getNumArgs(), EPI); 4306} 4307 4308/// CheckConstructor - Checks a fully-formed constructor for 4309/// well-formedness, issuing any diagnostics required. Returns true if 4310/// the constructor declarator is invalid. 4311void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 4312 CXXRecordDecl *ClassDecl 4313 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 4314 if (!ClassDecl) 4315 return Constructor->setInvalidDecl(); 4316 4317 // C++ [class.copy]p3: 4318 // A declaration of a constructor for a class X is ill-formed if 4319 // its first parameter is of type (optionally cv-qualified) X and 4320 // either there are no other parameters or else all other 4321 // parameters have default arguments. 4322 if (!Constructor->isInvalidDecl() && 4323 ((Constructor->getNumParams() == 1) || 4324 (Constructor->getNumParams() > 1 && 4325 Constructor->getParamDecl(1)->hasDefaultArg())) && 4326 Constructor->getTemplateSpecializationKind() 4327 != TSK_ImplicitInstantiation) { 4328 QualType ParamType = Constructor->getParamDecl(0)->getType(); 4329 QualType ClassTy = Context.getTagDeclType(ClassDecl); 4330 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 4331 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 4332 const char *ConstRef 4333 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 4334 : " const &"; 4335 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 4336 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 4337 4338 // FIXME: Rather that making the constructor invalid, we should endeavor 4339 // to fix the type. 4340 Constructor->setInvalidDecl(); 4341 } 4342 } 4343} 4344 4345/// CheckDestructor - Checks a fully-formed destructor definition for 4346/// well-formedness, issuing any diagnostics required. Returns true 4347/// on error. 4348bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 4349 CXXRecordDecl *RD = Destructor->getParent(); 4350 4351 if (Destructor->isVirtual()) { 4352 SourceLocation Loc; 4353 4354 if (!Destructor->isImplicit()) 4355 Loc = Destructor->getLocation(); 4356 else 4357 Loc = RD->getLocation(); 4358 4359 // If we have a virtual destructor, look up the deallocation function 4360 FunctionDecl *OperatorDelete = 0; 4361 DeclarationName Name = 4362 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 4363 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 4364 return true; 4365 4366 MarkDeclarationReferenced(Loc, OperatorDelete); 4367 4368 Destructor->setOperatorDelete(OperatorDelete); 4369 } 4370 4371 return false; 4372} 4373 4374static inline bool 4375FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) { 4376 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 4377 FTI.ArgInfo[0].Param && 4378 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()); 4379} 4380 4381/// CheckDestructorDeclarator - Called by ActOnDeclarator to check 4382/// the well-formednes of the destructor declarator @p D with type @p 4383/// R. If there are any errors in the declarator, this routine will 4384/// emit diagnostics and set the declarator to invalid. Even if this happens, 4385/// will be updated to reflect a well-formed type for the destructor and 4386/// returned. 4387QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 4388 StorageClass& SC) { 4389 // C++ [class.dtor]p1: 4390 // [...] A typedef-name that names a class is a class-name 4391 // (7.1.3); however, a typedef-name that names a class shall not 4392 // be used as the identifier in the declarator for a destructor 4393 // declaration. 4394 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 4395 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 4396 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 4397 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 4398 else if (const TemplateSpecializationType *TST = 4399 DeclaratorType->getAs<TemplateSpecializationType>()) 4400 if (TST->isTypeAlias()) 4401 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 4402 << DeclaratorType << 1; 4403 4404 // C++ [class.dtor]p2: 4405 // A destructor is used to destroy objects of its class type. A 4406 // destructor takes no parameters, and no return type can be 4407 // specified for it (not even void). The address of a destructor 4408 // shall not be taken. A destructor shall not be static. A 4409 // destructor can be invoked for a const, volatile or const 4410 // volatile object. A destructor shall not be declared const, 4411 // volatile or const volatile (9.3.2). 4412 if (SC == SC_Static) { 4413 if (!D.isInvalidType()) 4414 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 4415 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 4416 << SourceRange(D.getIdentifierLoc()) 4417 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 4418 4419 SC = SC_None; 4420 } 4421 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 4422 // Destructors don't have return types, but the parser will 4423 // happily parse something like: 4424 // 4425 // class X { 4426 // float ~X(); 4427 // }; 4428 // 4429 // The return type will be eliminated later. 4430 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 4431 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 4432 << SourceRange(D.getIdentifierLoc()); 4433 } 4434 4435 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 4436 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 4437 if (FTI.TypeQuals & Qualifiers::Const) 4438 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 4439 << "const" << SourceRange(D.getIdentifierLoc()); 4440 if (FTI.TypeQuals & Qualifiers::Volatile) 4441 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 4442 << "volatile" << SourceRange(D.getIdentifierLoc()); 4443 if (FTI.TypeQuals & Qualifiers::Restrict) 4444 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 4445 << "restrict" << SourceRange(D.getIdentifierLoc()); 4446 D.setInvalidType(); 4447 } 4448 4449 // C++0x [class.dtor]p2: 4450 // A destructor shall not be declared with a ref-qualifier. 4451 if (FTI.hasRefQualifier()) { 4452 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 4453 << FTI.RefQualifierIsLValueRef 4454 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 4455 D.setInvalidType(); 4456 } 4457 4458 // Make sure we don't have any parameters. 4459 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) { 4460 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 4461 4462 // Delete the parameters. 4463 FTI.freeArgs(); 4464 D.setInvalidType(); 4465 } 4466 4467 // Make sure the destructor isn't variadic. 4468 if (FTI.isVariadic) { 4469 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 4470 D.setInvalidType(); 4471 } 4472 4473 // Rebuild the function type "R" without any type qualifiers or 4474 // parameters (in case any of the errors above fired) and with 4475 // "void" as the return type, since destructors don't have return 4476 // types. 4477 if (!D.isInvalidType()) 4478 return R; 4479 4480 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 4481 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 4482 EPI.Variadic = false; 4483 EPI.TypeQuals = 0; 4484 EPI.RefQualifier = RQ_None; 4485 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI); 4486} 4487 4488/// CheckConversionDeclarator - Called by ActOnDeclarator to check the 4489/// well-formednes of the conversion function declarator @p D with 4490/// type @p R. If there are any errors in the declarator, this routine 4491/// will emit diagnostics and return true. Otherwise, it will return 4492/// false. Either way, the type @p R will be updated to reflect a 4493/// well-formed type for the conversion operator. 4494void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 4495 StorageClass& SC) { 4496 // C++ [class.conv.fct]p1: 4497 // Neither parameter types nor return type can be specified. The 4498 // type of a conversion function (8.3.5) is "function taking no 4499 // parameter returning conversion-type-id." 4500 if (SC == SC_Static) { 4501 if (!D.isInvalidType()) 4502 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 4503 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 4504 << SourceRange(D.getIdentifierLoc()); 4505 D.setInvalidType(); 4506 SC = SC_None; 4507 } 4508 4509 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId); 4510 4511 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 4512 // Conversion functions don't have return types, but the parser will 4513 // happily parse something like: 4514 // 4515 // class X { 4516 // float operator bool(); 4517 // }; 4518 // 4519 // The return type will be changed later anyway. 4520 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 4521 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 4522 << SourceRange(D.getIdentifierLoc()); 4523 D.setInvalidType(); 4524 } 4525 4526 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 4527 4528 // Make sure we don't have any parameters. 4529 if (Proto->getNumArgs() > 0) { 4530 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 4531 4532 // Delete the parameters. 4533 D.getFunctionTypeInfo().freeArgs(); 4534 D.setInvalidType(); 4535 } else if (Proto->isVariadic()) { 4536 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 4537 D.setInvalidType(); 4538 } 4539 4540 // Diagnose "&operator bool()" and other such nonsense. This 4541 // is actually a gcc extension which we don't support. 4542 if (Proto->getResultType() != ConvType) { 4543 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 4544 << Proto->getResultType(); 4545 D.setInvalidType(); 4546 ConvType = Proto->getResultType(); 4547 } 4548 4549 // C++ [class.conv.fct]p4: 4550 // The conversion-type-id shall not represent a function type nor 4551 // an array type. 4552 if (ConvType->isArrayType()) { 4553 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 4554 ConvType = Context.getPointerType(ConvType); 4555 D.setInvalidType(); 4556 } else if (ConvType->isFunctionType()) { 4557 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 4558 ConvType = Context.getPointerType(ConvType); 4559 D.setInvalidType(); 4560 } 4561 4562 // Rebuild the function type "R" without any parameters (in case any 4563 // of the errors above fired) and with the conversion type as the 4564 // return type. 4565 if (D.isInvalidType()) 4566 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo()); 4567 4568 // C++0x explicit conversion operators. 4569 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x) 4570 Diag(D.getDeclSpec().getExplicitSpecLoc(), 4571 diag::warn_explicit_conversion_functions) 4572 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 4573} 4574 4575/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 4576/// the declaration of the given C++ conversion function. This routine 4577/// is responsible for recording the conversion function in the C++ 4578/// class, if possible. 4579Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 4580 assert(Conversion && "Expected to receive a conversion function declaration"); 4581 4582 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 4583 4584 // Make sure we aren't redeclaring the conversion function. 4585 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 4586 4587 // C++ [class.conv.fct]p1: 4588 // [...] A conversion function is never used to convert a 4589 // (possibly cv-qualified) object to the (possibly cv-qualified) 4590 // same object type (or a reference to it), to a (possibly 4591 // cv-qualified) base class of that type (or a reference to it), 4592 // or to (possibly cv-qualified) void. 4593 // FIXME: Suppress this warning if the conversion function ends up being a 4594 // virtual function that overrides a virtual function in a base class. 4595 QualType ClassType 4596 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 4597 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 4598 ConvType = ConvTypeRef->getPointeeType(); 4599 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 4600 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 4601 /* Suppress diagnostics for instantiations. */; 4602 else if (ConvType->isRecordType()) { 4603 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 4604 if (ConvType == ClassType) 4605 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 4606 << ClassType; 4607 else if (IsDerivedFrom(ClassType, ConvType)) 4608 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 4609 << ClassType << ConvType; 4610 } else if (ConvType->isVoidType()) { 4611 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 4612 << ClassType << ConvType; 4613 } 4614 4615 if (FunctionTemplateDecl *ConversionTemplate 4616 = Conversion->getDescribedFunctionTemplate()) 4617 return ConversionTemplate; 4618 4619 return Conversion; 4620} 4621 4622//===----------------------------------------------------------------------===// 4623// Namespace Handling 4624//===----------------------------------------------------------------------===// 4625 4626 4627 4628/// ActOnStartNamespaceDef - This is called at the start of a namespace 4629/// definition. 4630Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 4631 SourceLocation InlineLoc, 4632 SourceLocation NamespaceLoc, 4633 SourceLocation IdentLoc, 4634 IdentifierInfo *II, 4635 SourceLocation LBrace, 4636 AttributeList *AttrList) { 4637 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 4638 // For anonymous namespace, take the location of the left brace. 4639 SourceLocation Loc = II ? IdentLoc : LBrace; 4640 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, 4641 StartLoc, Loc, II); 4642 Namespc->setInline(InlineLoc.isValid()); 4643 4644 Scope *DeclRegionScope = NamespcScope->getParent(); 4645 4646 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 4647 4648 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 4649 PushNamespaceVisibilityAttr(Attr); 4650 4651 if (II) { 4652 // C++ [namespace.def]p2: 4653 // The identifier in an original-namespace-definition shall not 4654 // have been previously defined in the declarative region in 4655 // which the original-namespace-definition appears. The 4656 // identifier in an original-namespace-definition is the name of 4657 // the namespace. Subsequently in that declarative region, it is 4658 // treated as an original-namespace-name. 4659 // 4660 // Since namespace names are unique in their scope, and we don't 4661 // look through using directives, just look for any ordinary names. 4662 4663 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member | 4664 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag | 4665 Decl::IDNS_Namespace; 4666 NamedDecl *PrevDecl = 0; 4667 for (DeclContext::lookup_result R 4668 = CurContext->getRedeclContext()->lookup(II); 4669 R.first != R.second; ++R.first) { 4670 if ((*R.first)->getIdentifierNamespace() & IDNS) { 4671 PrevDecl = *R.first; 4672 break; 4673 } 4674 } 4675 4676 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) { 4677 // This is an extended namespace definition. 4678 if (Namespc->isInline() != OrigNS->isInline()) { 4679 // inline-ness must match 4680 if (OrigNS->isInline()) { 4681 // The user probably just forgot the 'inline', so suggest that it 4682 // be added back. 4683 Diag(Namespc->getLocation(), 4684 diag::warn_inline_namespace_reopened_noninline) 4685 << FixItHint::CreateInsertion(NamespaceLoc, "inline "); 4686 } else { 4687 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch) 4688 << Namespc->isInline(); 4689 } 4690 Diag(OrigNS->getLocation(), diag::note_previous_definition); 4691 4692 // Recover by ignoring the new namespace's inline status. 4693 Namespc->setInline(OrigNS->isInline()); 4694 } 4695 4696 // Attach this namespace decl to the chain of extended namespace 4697 // definitions. 4698 OrigNS->setNextNamespace(Namespc); 4699 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace()); 4700 4701 // Remove the previous declaration from the scope. 4702 if (DeclRegionScope->isDeclScope(OrigNS)) { 4703 IdResolver.RemoveDecl(OrigNS); 4704 DeclRegionScope->RemoveDecl(OrigNS); 4705 } 4706 } else if (PrevDecl) { 4707 // This is an invalid name redefinition. 4708 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind) 4709 << Namespc->getDeclName(); 4710 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 4711 Namespc->setInvalidDecl(); 4712 // Continue on to push Namespc as current DeclContext and return it. 4713 } else if (II->isStr("std") && 4714 CurContext->getRedeclContext()->isTranslationUnit()) { 4715 // This is the first "real" definition of the namespace "std", so update 4716 // our cache of the "std" namespace to point at this definition. 4717 if (NamespaceDecl *StdNS = getStdNamespace()) { 4718 // We had already defined a dummy namespace "std". Link this new 4719 // namespace definition to the dummy namespace "std". 4720 StdNS->setNextNamespace(Namespc); 4721 StdNS->setLocation(IdentLoc); 4722 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace()); 4723 } 4724 4725 // Make our StdNamespace cache point at the first real definition of the 4726 // "std" namespace. 4727 StdNamespace = Namespc; 4728 } 4729 4730 PushOnScopeChains(Namespc, DeclRegionScope); 4731 } else { 4732 // Anonymous namespaces. 4733 assert(Namespc->isAnonymousNamespace()); 4734 4735 // Link the anonymous namespace into its parent. 4736 NamespaceDecl *PrevDecl; 4737 DeclContext *Parent = CurContext->getRedeclContext(); 4738 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 4739 PrevDecl = TU->getAnonymousNamespace(); 4740 TU->setAnonymousNamespace(Namespc); 4741 } else { 4742 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 4743 PrevDecl = ND->getAnonymousNamespace(); 4744 ND->setAnonymousNamespace(Namespc); 4745 } 4746 4747 // Link the anonymous namespace with its previous declaration. 4748 if (PrevDecl) { 4749 assert(PrevDecl->isAnonymousNamespace()); 4750 assert(!PrevDecl->getNextNamespace()); 4751 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace()); 4752 PrevDecl->setNextNamespace(Namespc); 4753 4754 if (Namespc->isInline() != PrevDecl->isInline()) { 4755 // inline-ness must match 4756 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch) 4757 << Namespc->isInline(); 4758 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 4759 Namespc->setInvalidDecl(); 4760 // Recover by ignoring the new namespace's inline status. 4761 Namespc->setInline(PrevDecl->isInline()); 4762 } 4763 } 4764 4765 CurContext->addDecl(Namespc); 4766 4767 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 4768 // behaves as if it were replaced by 4769 // namespace unique { /* empty body */ } 4770 // using namespace unique; 4771 // namespace unique { namespace-body } 4772 // where all occurrences of 'unique' in a translation unit are 4773 // replaced by the same identifier and this identifier differs 4774 // from all other identifiers in the entire program. 4775 4776 // We just create the namespace with an empty name and then add an 4777 // implicit using declaration, just like the standard suggests. 4778 // 4779 // CodeGen enforces the "universally unique" aspect by giving all 4780 // declarations semantically contained within an anonymous 4781 // namespace internal linkage. 4782 4783 if (!PrevDecl) { 4784 UsingDirectiveDecl* UD 4785 = UsingDirectiveDecl::Create(Context, CurContext, 4786 /* 'using' */ LBrace, 4787 /* 'namespace' */ SourceLocation(), 4788 /* qualifier */ NestedNameSpecifierLoc(), 4789 /* identifier */ SourceLocation(), 4790 Namespc, 4791 /* Ancestor */ CurContext); 4792 UD->setImplicit(); 4793 CurContext->addDecl(UD); 4794 } 4795 } 4796 4797 // Although we could have an invalid decl (i.e. the namespace name is a 4798 // redefinition), push it as current DeclContext and try to continue parsing. 4799 // FIXME: We should be able to push Namespc here, so that the each DeclContext 4800 // for the namespace has the declarations that showed up in that particular 4801 // namespace definition. 4802 PushDeclContext(NamespcScope, Namespc); 4803 return Namespc; 4804} 4805 4806/// getNamespaceDecl - Returns the namespace a decl represents. If the decl 4807/// is a namespace alias, returns the namespace it points to. 4808static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 4809 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 4810 return AD->getNamespace(); 4811 return dyn_cast_or_null<NamespaceDecl>(D); 4812} 4813 4814/// ActOnFinishNamespaceDef - This callback is called after a namespace is 4815/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 4816void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 4817 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 4818 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 4819 Namespc->setRBraceLoc(RBrace); 4820 PopDeclContext(); 4821 if (Namespc->hasAttr<VisibilityAttr>()) 4822 PopPragmaVisibility(); 4823} 4824 4825CXXRecordDecl *Sema::getStdBadAlloc() const { 4826 return cast_or_null<CXXRecordDecl>( 4827 StdBadAlloc.get(Context.getExternalSource())); 4828} 4829 4830NamespaceDecl *Sema::getStdNamespace() const { 4831 return cast_or_null<NamespaceDecl>( 4832 StdNamespace.get(Context.getExternalSource())); 4833} 4834 4835/// \brief Retrieve the special "std" namespace, which may require us to 4836/// implicitly define the namespace. 4837NamespaceDecl *Sema::getOrCreateStdNamespace() { 4838 if (!StdNamespace) { 4839 // The "std" namespace has not yet been defined, so build one implicitly. 4840 StdNamespace = NamespaceDecl::Create(Context, 4841 Context.getTranslationUnitDecl(), 4842 SourceLocation(), SourceLocation(), 4843 &PP.getIdentifierTable().get("std")); 4844 getStdNamespace()->setImplicit(true); 4845 } 4846 4847 return getStdNamespace(); 4848} 4849 4850/// \brief Determine whether a using statement is in a context where it will be 4851/// apply in all contexts. 4852static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 4853 switch (CurContext->getDeclKind()) { 4854 case Decl::TranslationUnit: 4855 return true; 4856 case Decl::LinkageSpec: 4857 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 4858 default: 4859 return false; 4860 } 4861} 4862 4863Decl *Sema::ActOnUsingDirective(Scope *S, 4864 SourceLocation UsingLoc, 4865 SourceLocation NamespcLoc, 4866 CXXScopeSpec &SS, 4867 SourceLocation IdentLoc, 4868 IdentifierInfo *NamespcName, 4869 AttributeList *AttrList) { 4870 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 4871 assert(NamespcName && "Invalid NamespcName."); 4872 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 4873 4874 // This can only happen along a recovery path. 4875 while (S->getFlags() & Scope::TemplateParamScope) 4876 S = S->getParent(); 4877 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 4878 4879 UsingDirectiveDecl *UDir = 0; 4880 NestedNameSpecifier *Qualifier = 0; 4881 if (SS.isSet()) 4882 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 4883 4884 // Lookup namespace name. 4885 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 4886 LookupParsedName(R, S, &SS); 4887 if (R.isAmbiguous()) 4888 return 0; 4889 4890 if (R.empty()) { 4891 // Allow "using namespace std;" or "using namespace ::std;" even if 4892 // "std" hasn't been defined yet, for GCC compatibility. 4893 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 4894 NamespcName->isStr("std")) { 4895 Diag(IdentLoc, diag::ext_using_undefined_std); 4896 R.addDecl(getOrCreateStdNamespace()); 4897 R.resolveKind(); 4898 } 4899 // Otherwise, attempt typo correction. 4900 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false, 4901 CTC_NoKeywords, 0)) { 4902 if (R.getAsSingle<NamespaceDecl>() || 4903 R.getAsSingle<NamespaceAliasDecl>()) { 4904 if (DeclContext *DC = computeDeclContext(SS, false)) 4905 Diag(IdentLoc, diag::err_using_directive_member_suggest) 4906 << NamespcName << DC << Corrected << SS.getRange() 4907 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString()); 4908 else 4909 Diag(IdentLoc, diag::err_using_directive_suggest) 4910 << NamespcName << Corrected 4911 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString()); 4912 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here) 4913 << Corrected; 4914 4915 NamespcName = Corrected.getAsIdentifierInfo(); 4916 } else { 4917 R.clear(); 4918 R.setLookupName(NamespcName); 4919 } 4920 } 4921 } 4922 4923 if (!R.empty()) { 4924 NamedDecl *Named = R.getFoundDecl(); 4925 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named)) 4926 && "expected namespace decl"); 4927 // C++ [namespace.udir]p1: 4928 // A using-directive specifies that the names in the nominated 4929 // namespace can be used in the scope in which the 4930 // using-directive appears after the using-directive. During 4931 // unqualified name lookup (3.4.1), the names appear as if they 4932 // were declared in the nearest enclosing namespace which 4933 // contains both the using-directive and the nominated 4934 // namespace. [Note: in this context, "contains" means "contains 4935 // directly or indirectly". ] 4936 4937 // Find enclosing context containing both using-directive and 4938 // nominated namespace. 4939 NamespaceDecl *NS = getNamespaceDecl(Named); 4940 DeclContext *CommonAncestor = cast<DeclContext>(NS); 4941 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 4942 CommonAncestor = CommonAncestor->getParent(); 4943 4944 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 4945 SS.getWithLocInContext(Context), 4946 IdentLoc, Named, CommonAncestor); 4947 4948 if (IsUsingDirectiveInToplevelContext(CurContext) && 4949 !SourceMgr.isFromMainFile(SourceMgr.getInstantiationLoc(IdentLoc))) { 4950 Diag(IdentLoc, diag::warn_using_directive_in_header); 4951 } 4952 4953 PushUsingDirective(S, UDir); 4954 } else { 4955 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 4956 } 4957 4958 // FIXME: We ignore attributes for now. 4959 return UDir; 4960} 4961 4962void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 4963 // If scope has associated entity, then using directive is at namespace 4964 // or translation unit scope. We add UsingDirectiveDecls, into 4965 // it's lookup structure. 4966 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) 4967 Ctx->addDecl(UDir); 4968 else 4969 // Otherwise it is block-sope. using-directives will affect lookup 4970 // only to the end of scope. 4971 S->PushUsingDirective(UDir); 4972} 4973 4974 4975Decl *Sema::ActOnUsingDeclaration(Scope *S, 4976 AccessSpecifier AS, 4977 bool HasUsingKeyword, 4978 SourceLocation UsingLoc, 4979 CXXScopeSpec &SS, 4980 UnqualifiedId &Name, 4981 AttributeList *AttrList, 4982 bool IsTypeName, 4983 SourceLocation TypenameLoc) { 4984 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 4985 4986 switch (Name.getKind()) { 4987 case UnqualifiedId::IK_Identifier: 4988 case UnqualifiedId::IK_OperatorFunctionId: 4989 case UnqualifiedId::IK_LiteralOperatorId: 4990 case UnqualifiedId::IK_ConversionFunctionId: 4991 break; 4992 4993 case UnqualifiedId::IK_ConstructorName: 4994 case UnqualifiedId::IK_ConstructorTemplateId: 4995 // C++0x inherited constructors. 4996 if (getLangOptions().CPlusPlus0x) break; 4997 4998 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor) 4999 << SS.getRange(); 5000 return 0; 5001 5002 case UnqualifiedId::IK_DestructorName: 5003 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor) 5004 << SS.getRange(); 5005 return 0; 5006 5007 case UnqualifiedId::IK_TemplateId: 5008 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id) 5009 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 5010 return 0; 5011 } 5012 5013 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 5014 DeclarationName TargetName = TargetNameInfo.getName(); 5015 if (!TargetName) 5016 return 0; 5017 5018 // Warn about using declarations. 5019 // TODO: store that the declaration was written without 'using' and 5020 // talk about access decls instead of using decls in the 5021 // diagnostics. 5022 if (!HasUsingKeyword) { 5023 UsingLoc = Name.getSourceRange().getBegin(); 5024 5025 Diag(UsingLoc, diag::warn_access_decl_deprecated) 5026 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 5027 } 5028 5029 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 5030 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 5031 return 0; 5032 5033 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 5034 TargetNameInfo, AttrList, 5035 /* IsInstantiation */ false, 5036 IsTypeName, TypenameLoc); 5037 if (UD) 5038 PushOnScopeChains(UD, S, /*AddToContext*/ false); 5039 5040 return UD; 5041} 5042 5043/// \brief Determine whether a using declaration considers the given 5044/// declarations as "equivalent", e.g., if they are redeclarations of 5045/// the same entity or are both typedefs of the same type. 5046static bool 5047IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2, 5048 bool &SuppressRedeclaration) { 5049 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) { 5050 SuppressRedeclaration = false; 5051 return true; 5052 } 5053 5054 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 5055 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) { 5056 SuppressRedeclaration = true; 5057 return Context.hasSameType(TD1->getUnderlyingType(), 5058 TD2->getUnderlyingType()); 5059 } 5060 5061 return false; 5062} 5063 5064 5065/// Determines whether to create a using shadow decl for a particular 5066/// decl, given the set of decls existing prior to this using lookup. 5067bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 5068 const LookupResult &Previous) { 5069 // Diagnose finding a decl which is not from a base class of the 5070 // current class. We do this now because there are cases where this 5071 // function will silently decide not to build a shadow decl, which 5072 // will pre-empt further diagnostics. 5073 // 5074 // We don't need to do this in C++0x because we do the check once on 5075 // the qualifier. 5076 // 5077 // FIXME: diagnose the following if we care enough: 5078 // struct A { int foo; }; 5079 // struct B : A { using A::foo; }; 5080 // template <class T> struct C : A {}; 5081 // template <class T> struct D : C<T> { using B::foo; } // <--- 5082 // This is invalid (during instantiation) in C++03 because B::foo 5083 // resolves to the using decl in B, which is not a base class of D<T>. 5084 // We can't diagnose it immediately because C<T> is an unknown 5085 // specialization. The UsingShadowDecl in D<T> then points directly 5086 // to A::foo, which will look well-formed when we instantiate. 5087 // The right solution is to not collapse the shadow-decl chain. 5088 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) { 5089 DeclContext *OrigDC = Orig->getDeclContext(); 5090 5091 // Handle enums and anonymous structs. 5092 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 5093 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 5094 while (OrigRec->isAnonymousStructOrUnion()) 5095 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 5096 5097 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 5098 if (OrigDC == CurContext) { 5099 Diag(Using->getLocation(), 5100 diag::err_using_decl_nested_name_specifier_is_current_class) 5101 << Using->getQualifierLoc().getSourceRange(); 5102 Diag(Orig->getLocation(), diag::note_using_decl_target); 5103 return true; 5104 } 5105 5106 Diag(Using->getQualifierLoc().getBeginLoc(), 5107 diag::err_using_decl_nested_name_specifier_is_not_base_class) 5108 << Using->getQualifier() 5109 << cast<CXXRecordDecl>(CurContext) 5110 << Using->getQualifierLoc().getSourceRange(); 5111 Diag(Orig->getLocation(), diag::note_using_decl_target); 5112 return true; 5113 } 5114 } 5115 5116 if (Previous.empty()) return false; 5117 5118 NamedDecl *Target = Orig; 5119 if (isa<UsingShadowDecl>(Target)) 5120 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 5121 5122 // If the target happens to be one of the previous declarations, we 5123 // don't have a conflict. 5124 // 5125 // FIXME: but we might be increasing its access, in which case we 5126 // should redeclare it. 5127 NamedDecl *NonTag = 0, *Tag = 0; 5128 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 5129 I != E; ++I) { 5130 NamedDecl *D = (*I)->getUnderlyingDecl(); 5131 bool Result; 5132 if (IsEquivalentForUsingDecl(Context, D, Target, Result)) 5133 return Result; 5134 5135 (isa<TagDecl>(D) ? Tag : NonTag) = D; 5136 } 5137 5138 if (Target->isFunctionOrFunctionTemplate()) { 5139 FunctionDecl *FD; 5140 if (isa<FunctionTemplateDecl>(Target)) 5141 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl(); 5142 else 5143 FD = cast<FunctionDecl>(Target); 5144 5145 NamedDecl *OldDecl = 0; 5146 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) { 5147 case Ovl_Overload: 5148 return false; 5149 5150 case Ovl_NonFunction: 5151 Diag(Using->getLocation(), diag::err_using_decl_conflict); 5152 break; 5153 5154 // We found a decl with the exact signature. 5155 case Ovl_Match: 5156 // If we're in a record, we want to hide the target, so we 5157 // return true (without a diagnostic) to tell the caller not to 5158 // build a shadow decl. 5159 if (CurContext->isRecord()) 5160 return true; 5161 5162 // If we're not in a record, this is an error. 5163 Diag(Using->getLocation(), diag::err_using_decl_conflict); 5164 break; 5165 } 5166 5167 Diag(Target->getLocation(), diag::note_using_decl_target); 5168 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 5169 return true; 5170 } 5171 5172 // Target is not a function. 5173 5174 if (isa<TagDecl>(Target)) { 5175 // No conflict between a tag and a non-tag. 5176 if (!Tag) return false; 5177 5178 Diag(Using->getLocation(), diag::err_using_decl_conflict); 5179 Diag(Target->getLocation(), diag::note_using_decl_target); 5180 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 5181 return true; 5182 } 5183 5184 // No conflict between a tag and a non-tag. 5185 if (!NonTag) return false; 5186 5187 Diag(Using->getLocation(), diag::err_using_decl_conflict); 5188 Diag(Target->getLocation(), diag::note_using_decl_target); 5189 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 5190 return true; 5191} 5192 5193/// Builds a shadow declaration corresponding to a 'using' declaration. 5194UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 5195 UsingDecl *UD, 5196 NamedDecl *Orig) { 5197 5198 // If we resolved to another shadow declaration, just coalesce them. 5199 NamedDecl *Target = Orig; 5200 if (isa<UsingShadowDecl>(Target)) { 5201 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 5202 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 5203 } 5204 5205 UsingShadowDecl *Shadow 5206 = UsingShadowDecl::Create(Context, CurContext, 5207 UD->getLocation(), UD, Target); 5208 UD->addShadowDecl(Shadow); 5209 5210 Shadow->setAccess(UD->getAccess()); 5211 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 5212 Shadow->setInvalidDecl(); 5213 5214 if (S) 5215 PushOnScopeChains(Shadow, S); 5216 else 5217 CurContext->addDecl(Shadow); 5218 5219 5220 return Shadow; 5221} 5222 5223/// Hides a using shadow declaration. This is required by the current 5224/// using-decl implementation when a resolvable using declaration in a 5225/// class is followed by a declaration which would hide or override 5226/// one or more of the using decl's targets; for example: 5227/// 5228/// struct Base { void foo(int); }; 5229/// struct Derived : Base { 5230/// using Base::foo; 5231/// void foo(int); 5232/// }; 5233/// 5234/// The governing language is C++03 [namespace.udecl]p12: 5235/// 5236/// When a using-declaration brings names from a base class into a 5237/// derived class scope, member functions in the derived class 5238/// override and/or hide member functions with the same name and 5239/// parameter types in a base class (rather than conflicting). 5240/// 5241/// There are two ways to implement this: 5242/// (1) optimistically create shadow decls when they're not hidden 5243/// by existing declarations, or 5244/// (2) don't create any shadow decls (or at least don't make them 5245/// visible) until we've fully parsed/instantiated the class. 5246/// The problem with (1) is that we might have to retroactively remove 5247/// a shadow decl, which requires several O(n) operations because the 5248/// decl structures are (very reasonably) not designed for removal. 5249/// (2) avoids this but is very fiddly and phase-dependent. 5250void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 5251 if (Shadow->getDeclName().getNameKind() == 5252 DeclarationName::CXXConversionFunctionName) 5253 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 5254 5255 // Remove it from the DeclContext... 5256 Shadow->getDeclContext()->removeDecl(Shadow); 5257 5258 // ...and the scope, if applicable... 5259 if (S) { 5260 S->RemoveDecl(Shadow); 5261 IdResolver.RemoveDecl(Shadow); 5262 } 5263 5264 // ...and the using decl. 5265 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 5266 5267 // TODO: complain somehow if Shadow was used. It shouldn't 5268 // be possible for this to happen, because...? 5269} 5270 5271/// Builds a using declaration. 5272/// 5273/// \param IsInstantiation - Whether this call arises from an 5274/// instantiation of an unresolved using declaration. We treat 5275/// the lookup differently for these declarations. 5276NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 5277 SourceLocation UsingLoc, 5278 CXXScopeSpec &SS, 5279 const DeclarationNameInfo &NameInfo, 5280 AttributeList *AttrList, 5281 bool IsInstantiation, 5282 bool IsTypeName, 5283 SourceLocation TypenameLoc) { 5284 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 5285 SourceLocation IdentLoc = NameInfo.getLoc(); 5286 assert(IdentLoc.isValid() && "Invalid TargetName location."); 5287 5288 // FIXME: We ignore attributes for now. 5289 5290 if (SS.isEmpty()) { 5291 Diag(IdentLoc, diag::err_using_requires_qualname); 5292 return 0; 5293 } 5294 5295 // Do the redeclaration lookup in the current scope. 5296 LookupResult Previous(*this, NameInfo, LookupUsingDeclName, 5297 ForRedeclaration); 5298 Previous.setHideTags(false); 5299 if (S) { 5300 LookupName(Previous, S); 5301 5302 // It is really dumb that we have to do this. 5303 LookupResult::Filter F = Previous.makeFilter(); 5304 while (F.hasNext()) { 5305 NamedDecl *D = F.next(); 5306 if (!isDeclInScope(D, CurContext, S)) 5307 F.erase(); 5308 } 5309 F.done(); 5310 } else { 5311 assert(IsInstantiation && "no scope in non-instantiation"); 5312 assert(CurContext->isRecord() && "scope not record in instantiation"); 5313 LookupQualifiedName(Previous, CurContext); 5314 } 5315 5316 // Check for invalid redeclarations. 5317 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous)) 5318 return 0; 5319 5320 // Check for bad qualifiers. 5321 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc)) 5322 return 0; 5323 5324 DeclContext *LookupContext = computeDeclContext(SS); 5325 NamedDecl *D; 5326 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 5327 if (!LookupContext) { 5328 if (IsTypeName) { 5329 // FIXME: not all declaration name kinds are legal here 5330 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 5331 UsingLoc, TypenameLoc, 5332 QualifierLoc, 5333 IdentLoc, NameInfo.getName()); 5334 } else { 5335 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 5336 QualifierLoc, NameInfo); 5337 } 5338 } else { 5339 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 5340 NameInfo, IsTypeName); 5341 } 5342 D->setAccess(AS); 5343 CurContext->addDecl(D); 5344 5345 if (!LookupContext) return D; 5346 UsingDecl *UD = cast<UsingDecl>(D); 5347 5348 if (RequireCompleteDeclContext(SS, LookupContext)) { 5349 UD->setInvalidDecl(); 5350 return UD; 5351 } 5352 5353 // Constructor inheriting using decls get special treatment. 5354 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) { 5355 if (CheckInheritedConstructorUsingDecl(UD)) 5356 UD->setInvalidDecl(); 5357 return UD; 5358 } 5359 5360 // Otherwise, look up the target name. 5361 5362 LookupResult R(*this, NameInfo, LookupOrdinaryName); 5363 R.setUsingDeclaration(true); 5364 5365 // Unlike most lookups, we don't always want to hide tag 5366 // declarations: tag names are visible through the using declaration 5367 // even if hidden by ordinary names, *except* in a dependent context 5368 // where it's important for the sanity of two-phase lookup. 5369 if (!IsInstantiation) 5370 R.setHideTags(false); 5371 5372 LookupQualifiedName(R, LookupContext); 5373 5374 if (R.empty()) { 5375 Diag(IdentLoc, diag::err_no_member) 5376 << NameInfo.getName() << LookupContext << SS.getRange(); 5377 UD->setInvalidDecl(); 5378 return UD; 5379 } 5380 5381 if (R.isAmbiguous()) { 5382 UD->setInvalidDecl(); 5383 return UD; 5384 } 5385 5386 if (IsTypeName) { 5387 // If we asked for a typename and got a non-type decl, error out. 5388 if (!R.getAsSingle<TypeDecl>()) { 5389 Diag(IdentLoc, diag::err_using_typename_non_type); 5390 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 5391 Diag((*I)->getUnderlyingDecl()->getLocation(), 5392 diag::note_using_decl_target); 5393 UD->setInvalidDecl(); 5394 return UD; 5395 } 5396 } else { 5397 // If we asked for a non-typename and we got a type, error out, 5398 // but only if this is an instantiation of an unresolved using 5399 // decl. Otherwise just silently find the type name. 5400 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 5401 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 5402 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 5403 UD->setInvalidDecl(); 5404 return UD; 5405 } 5406 } 5407 5408 // C++0x N2914 [namespace.udecl]p6: 5409 // A using-declaration shall not name a namespace. 5410 if (R.getAsSingle<NamespaceDecl>()) { 5411 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 5412 << SS.getRange(); 5413 UD->setInvalidDecl(); 5414 return UD; 5415 } 5416 5417 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 5418 if (!CheckUsingShadowDecl(UD, *I, Previous)) 5419 BuildUsingShadowDecl(S, UD, *I); 5420 } 5421 5422 return UD; 5423} 5424 5425/// Additional checks for a using declaration referring to a constructor name. 5426bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) { 5427 if (UD->isTypeName()) { 5428 // FIXME: Cannot specify typename when specifying constructor 5429 return true; 5430 } 5431 5432 const Type *SourceType = UD->getQualifier()->getAsType(); 5433 assert(SourceType && 5434 "Using decl naming constructor doesn't have type in scope spec."); 5435 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 5436 5437 // Check whether the named type is a direct base class. 5438 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified(); 5439 CXXRecordDecl::base_class_iterator BaseIt, BaseE; 5440 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end(); 5441 BaseIt != BaseE; ++BaseIt) { 5442 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified(); 5443 if (CanonicalSourceType == BaseType) 5444 break; 5445 } 5446 5447 if (BaseIt == BaseE) { 5448 // Did not find SourceType in the bases. 5449 Diag(UD->getUsingLocation(), 5450 diag::err_using_decl_constructor_not_in_direct_base) 5451 << UD->getNameInfo().getSourceRange() 5452 << QualType(SourceType, 0) << TargetClass; 5453 return true; 5454 } 5455 5456 BaseIt->setInheritConstructors(); 5457 5458 return false; 5459} 5460 5461/// Checks that the given using declaration is not an invalid 5462/// redeclaration. Note that this is checking only for the using decl 5463/// itself, not for any ill-formedness among the UsingShadowDecls. 5464bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 5465 bool isTypeName, 5466 const CXXScopeSpec &SS, 5467 SourceLocation NameLoc, 5468 const LookupResult &Prev) { 5469 // C++03 [namespace.udecl]p8: 5470 // C++0x [namespace.udecl]p10: 5471 // A using-declaration is a declaration and can therefore be used 5472 // repeatedly where (and only where) multiple declarations are 5473 // allowed. 5474 // 5475 // That's in non-member contexts. 5476 if (!CurContext->getRedeclContext()->isRecord()) 5477 return false; 5478 5479 NestedNameSpecifier *Qual 5480 = static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 5481 5482 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 5483 NamedDecl *D = *I; 5484 5485 bool DTypename; 5486 NestedNameSpecifier *DQual; 5487 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 5488 DTypename = UD->isTypeName(); 5489 DQual = UD->getQualifier(); 5490 } else if (UnresolvedUsingValueDecl *UD 5491 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 5492 DTypename = false; 5493 DQual = UD->getQualifier(); 5494 } else if (UnresolvedUsingTypenameDecl *UD 5495 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 5496 DTypename = true; 5497 DQual = UD->getQualifier(); 5498 } else continue; 5499 5500 // using decls differ if one says 'typename' and the other doesn't. 5501 // FIXME: non-dependent using decls? 5502 if (isTypeName != DTypename) continue; 5503 5504 // using decls differ if they name different scopes (but note that 5505 // template instantiation can cause this check to trigger when it 5506 // didn't before instantiation). 5507 if (Context.getCanonicalNestedNameSpecifier(Qual) != 5508 Context.getCanonicalNestedNameSpecifier(DQual)) 5509 continue; 5510 5511 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 5512 Diag(D->getLocation(), diag::note_using_decl) << 1; 5513 return true; 5514 } 5515 5516 return false; 5517} 5518 5519 5520/// Checks that the given nested-name qualifier used in a using decl 5521/// in the current context is appropriately related to the current 5522/// scope. If an error is found, diagnoses it and returns true. 5523bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 5524 const CXXScopeSpec &SS, 5525 SourceLocation NameLoc) { 5526 DeclContext *NamedContext = computeDeclContext(SS); 5527 5528 if (!CurContext->isRecord()) { 5529 // C++03 [namespace.udecl]p3: 5530 // C++0x [namespace.udecl]p8: 5531 // A using-declaration for a class member shall be a member-declaration. 5532 5533 // If we weren't able to compute a valid scope, it must be a 5534 // dependent class scope. 5535 if (!NamedContext || NamedContext->isRecord()) { 5536 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 5537 << SS.getRange(); 5538 return true; 5539 } 5540 5541 // Otherwise, everything is known to be fine. 5542 return false; 5543 } 5544 5545 // The current scope is a record. 5546 5547 // If the named context is dependent, we can't decide much. 5548 if (!NamedContext) { 5549 // FIXME: in C++0x, we can diagnose if we can prove that the 5550 // nested-name-specifier does not refer to a base class, which is 5551 // still possible in some cases. 5552 5553 // Otherwise we have to conservatively report that things might be 5554 // okay. 5555 return false; 5556 } 5557 5558 if (!NamedContext->isRecord()) { 5559 // Ideally this would point at the last name in the specifier, 5560 // but we don't have that level of source info. 5561 Diag(SS.getRange().getBegin(), 5562 diag::err_using_decl_nested_name_specifier_is_not_class) 5563 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange(); 5564 return true; 5565 } 5566 5567 if (!NamedContext->isDependentContext() && 5568 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 5569 return true; 5570 5571 if (getLangOptions().CPlusPlus0x) { 5572 // C++0x [namespace.udecl]p3: 5573 // In a using-declaration used as a member-declaration, the 5574 // nested-name-specifier shall name a base class of the class 5575 // being defined. 5576 5577 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 5578 cast<CXXRecordDecl>(NamedContext))) { 5579 if (CurContext == NamedContext) { 5580 Diag(NameLoc, 5581 diag::err_using_decl_nested_name_specifier_is_current_class) 5582 << SS.getRange(); 5583 return true; 5584 } 5585 5586 Diag(SS.getRange().getBegin(), 5587 diag::err_using_decl_nested_name_specifier_is_not_base_class) 5588 << (NestedNameSpecifier*) SS.getScopeRep() 5589 << cast<CXXRecordDecl>(CurContext) 5590 << SS.getRange(); 5591 return true; 5592 } 5593 5594 return false; 5595 } 5596 5597 // C++03 [namespace.udecl]p4: 5598 // A using-declaration used as a member-declaration shall refer 5599 // to a member of a base class of the class being defined [etc.]. 5600 5601 // Salient point: SS doesn't have to name a base class as long as 5602 // lookup only finds members from base classes. Therefore we can 5603 // diagnose here only if we can prove that that can't happen, 5604 // i.e. if the class hierarchies provably don't intersect. 5605 5606 // TODO: it would be nice if "definitely valid" results were cached 5607 // in the UsingDecl and UsingShadowDecl so that these checks didn't 5608 // need to be repeated. 5609 5610 struct UserData { 5611 llvm::DenseSet<const CXXRecordDecl*> Bases; 5612 5613 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) { 5614 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 5615 Data->Bases.insert(Base); 5616 return true; 5617 } 5618 5619 bool hasDependentBases(const CXXRecordDecl *Class) { 5620 return !Class->forallBases(collect, this); 5621 } 5622 5623 /// Returns true if the base is dependent or is one of the 5624 /// accumulated base classes. 5625 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) { 5626 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 5627 return !Data->Bases.count(Base); 5628 } 5629 5630 bool mightShareBases(const CXXRecordDecl *Class) { 5631 return Bases.count(Class) || !Class->forallBases(doesNotContain, this); 5632 } 5633 }; 5634 5635 UserData Data; 5636 5637 // Returns false if we find a dependent base. 5638 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext))) 5639 return false; 5640 5641 // Returns false if the class has a dependent base or if it or one 5642 // of its bases is present in the base set of the current context. 5643 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext))) 5644 return false; 5645 5646 Diag(SS.getRange().getBegin(), 5647 diag::err_using_decl_nested_name_specifier_is_not_base_class) 5648 << (NestedNameSpecifier*) SS.getScopeRep() 5649 << cast<CXXRecordDecl>(CurContext) 5650 << SS.getRange(); 5651 5652 return true; 5653} 5654 5655Decl *Sema::ActOnAliasDeclaration(Scope *S, 5656 AccessSpecifier AS, 5657 MultiTemplateParamsArg TemplateParamLists, 5658 SourceLocation UsingLoc, 5659 UnqualifiedId &Name, 5660 TypeResult Type) { 5661 // Skip up to the relevant declaration scope. 5662 while (S->getFlags() & Scope::TemplateParamScope) 5663 S = S->getParent(); 5664 assert((S->getFlags() & Scope::DeclScope) && 5665 "got alias-declaration outside of declaration scope"); 5666 5667 if (Type.isInvalid()) 5668 return 0; 5669 5670 bool Invalid = false; 5671 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 5672 TypeSourceInfo *TInfo = 0; 5673 GetTypeFromParser(Type.get(), &TInfo); 5674 5675 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 5676 return 0; 5677 5678 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 5679 UPPC_DeclarationType)) { 5680 Invalid = true; 5681 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 5682 TInfo->getTypeLoc().getBeginLoc()); 5683 } 5684 5685 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration); 5686 LookupName(Previous, S); 5687 5688 // Warn about shadowing the name of a template parameter. 5689 if (Previous.isSingleResult() && 5690 Previous.getFoundDecl()->isTemplateParameter()) { 5691 if (DiagnoseTemplateParameterShadow(Name.StartLocation, 5692 Previous.getFoundDecl())) 5693 Invalid = true; 5694 Previous.clear(); 5695 } 5696 5697 assert(Name.Kind == UnqualifiedId::IK_Identifier && 5698 "name in alias declaration must be an identifier"); 5699 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 5700 Name.StartLocation, 5701 Name.Identifier, TInfo); 5702 5703 NewTD->setAccess(AS); 5704 5705 if (Invalid) 5706 NewTD->setInvalidDecl(); 5707 5708 CheckTypedefForVariablyModifiedType(S, NewTD); 5709 Invalid |= NewTD->isInvalidDecl(); 5710 5711 bool Redeclaration = false; 5712 5713 NamedDecl *NewND; 5714 if (TemplateParamLists.size()) { 5715 TypeAliasTemplateDecl *OldDecl = 0; 5716 TemplateParameterList *OldTemplateParams = 0; 5717 5718 if (TemplateParamLists.size() != 1) { 5719 Diag(UsingLoc, diag::err_alias_template_extra_headers) 5720 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(), 5721 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc()); 5722 } 5723 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0]; 5724 5725 // Only consider previous declarations in the same scope. 5726 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 5727 /*ExplicitInstantiationOrSpecialization*/false); 5728 if (!Previous.empty()) { 5729 Redeclaration = true; 5730 5731 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 5732 if (!OldDecl && !Invalid) { 5733 Diag(UsingLoc, diag::err_redefinition_different_kind) 5734 << Name.Identifier; 5735 5736 NamedDecl *OldD = Previous.getRepresentativeDecl(); 5737 if (OldD->getLocation().isValid()) 5738 Diag(OldD->getLocation(), diag::note_previous_definition); 5739 5740 Invalid = true; 5741 } 5742 5743 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 5744 if (TemplateParameterListsAreEqual(TemplateParams, 5745 OldDecl->getTemplateParameters(), 5746 /*Complain=*/true, 5747 TPL_TemplateMatch)) 5748 OldTemplateParams = OldDecl->getTemplateParameters(); 5749 else 5750 Invalid = true; 5751 5752 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 5753 if (!Invalid && 5754 !Context.hasSameType(OldTD->getUnderlyingType(), 5755 NewTD->getUnderlyingType())) { 5756 // FIXME: The C++0x standard does not clearly say this is ill-formed, 5757 // but we can't reasonably accept it. 5758 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 5759 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 5760 if (OldTD->getLocation().isValid()) 5761 Diag(OldTD->getLocation(), diag::note_previous_definition); 5762 Invalid = true; 5763 } 5764 } 5765 } 5766 5767 // Merge any previous default template arguments into our parameters, 5768 // and check the parameter list. 5769 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 5770 TPC_TypeAliasTemplate)) 5771 return 0; 5772 5773 TypeAliasTemplateDecl *NewDecl = 5774 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 5775 Name.Identifier, TemplateParams, 5776 NewTD); 5777 5778 NewDecl->setAccess(AS); 5779 5780 if (Invalid) 5781 NewDecl->setInvalidDecl(); 5782 else if (OldDecl) 5783 NewDecl->setPreviousDeclaration(OldDecl); 5784 5785 NewND = NewDecl; 5786 } else { 5787 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 5788 NewND = NewTD; 5789 } 5790 5791 if (!Redeclaration) 5792 PushOnScopeChains(NewND, S); 5793 5794 return NewND; 5795} 5796 5797Decl *Sema::ActOnNamespaceAliasDef(Scope *S, 5798 SourceLocation NamespaceLoc, 5799 SourceLocation AliasLoc, 5800 IdentifierInfo *Alias, 5801 CXXScopeSpec &SS, 5802 SourceLocation IdentLoc, 5803 IdentifierInfo *Ident) { 5804 5805 // Lookup the namespace name. 5806 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 5807 LookupParsedName(R, S, &SS); 5808 5809 // Check if we have a previous declaration with the same name. 5810 NamedDecl *PrevDecl 5811 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName, 5812 ForRedeclaration); 5813 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S)) 5814 PrevDecl = 0; 5815 5816 if (PrevDecl) { 5817 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 5818 // We already have an alias with the same name that points to the same 5819 // namespace, so don't create a new one. 5820 // FIXME: At some point, we'll want to create the (redundant) 5821 // declaration to maintain better source information. 5822 if (!R.isAmbiguous() && !R.empty() && 5823 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl()))) 5824 return 0; 5825 } 5826 5827 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition : 5828 diag::err_redefinition_different_kind; 5829 Diag(AliasLoc, DiagID) << Alias; 5830 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 5831 return 0; 5832 } 5833 5834 if (R.isAmbiguous()) 5835 return 0; 5836 5837 if (R.empty()) { 5838 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false, 5839 CTC_NoKeywords, 0)) { 5840 if (R.getAsSingle<NamespaceDecl>() || 5841 R.getAsSingle<NamespaceAliasDecl>()) { 5842 if (DeclContext *DC = computeDeclContext(SS, false)) 5843 Diag(IdentLoc, diag::err_using_directive_member_suggest) 5844 << Ident << DC << Corrected << SS.getRange() 5845 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString()); 5846 else 5847 Diag(IdentLoc, diag::err_using_directive_suggest) 5848 << Ident << Corrected 5849 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString()); 5850 5851 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here) 5852 << Corrected; 5853 5854 Ident = Corrected.getAsIdentifierInfo(); 5855 } else { 5856 R.clear(); 5857 R.setLookupName(Ident); 5858 } 5859 } 5860 5861 if (R.empty()) { 5862 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange(); 5863 return 0; 5864 } 5865 } 5866 5867 NamespaceAliasDecl *AliasDecl = 5868 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 5869 Alias, SS.getWithLocInContext(Context), 5870 IdentLoc, R.getFoundDecl()); 5871 5872 PushOnScopeChains(AliasDecl, S); 5873 return AliasDecl; 5874} 5875 5876namespace { 5877 /// \brief Scoped object used to handle the state changes required in Sema 5878 /// to implicitly define the body of a C++ member function; 5879 class ImplicitlyDefinedFunctionScope { 5880 Sema &S; 5881 Sema::ContextRAII SavedContext; 5882 5883 public: 5884 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method) 5885 : S(S), SavedContext(S, Method) 5886 { 5887 S.PushFunctionScope(); 5888 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated); 5889 } 5890 5891 ~ImplicitlyDefinedFunctionScope() { 5892 S.PopExpressionEvaluationContext(); 5893 S.PopFunctionOrBlockScope(); 5894 } 5895 }; 5896} 5897 5898static CXXConstructorDecl *getDefaultConstructorUnsafe(Sema &Self, 5899 CXXRecordDecl *D) { 5900 ASTContext &Context = Self.Context; 5901 QualType ClassType = Context.getTypeDeclType(D); 5902 DeclarationName ConstructorName 5903 = Context.DeclarationNames.getCXXConstructorName( 5904 Context.getCanonicalType(ClassType.getUnqualifiedType())); 5905 5906 DeclContext::lookup_const_iterator Con, ConEnd; 5907 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName); 5908 Con != ConEnd; ++Con) { 5909 // FIXME: In C++0x, a constructor template can be a default constructor. 5910 if (isa<FunctionTemplateDecl>(*Con)) 5911 continue; 5912 5913 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con); 5914 if (Constructor->isDefaultConstructor()) 5915 return Constructor; 5916 } 5917 return 0; 5918} 5919 5920Sema::ImplicitExceptionSpecification 5921Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) { 5922 // C++ [except.spec]p14: 5923 // An implicitly declared special member function (Clause 12) shall have an 5924 // exception-specification. [...] 5925 ImplicitExceptionSpecification ExceptSpec(Context); 5926 5927 // Direct base-class constructors. 5928 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 5929 BEnd = ClassDecl->bases_end(); 5930 B != BEnd; ++B) { 5931 if (B->isVirtual()) // Handled below. 5932 continue; 5933 5934 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 5935 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 5936 if (BaseClassDecl->needsImplicitDefaultConstructor()) 5937 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl)); 5938 else if (CXXConstructorDecl *Constructor 5939 = getDefaultConstructorUnsafe(*this, BaseClassDecl)) 5940 ExceptSpec.CalledDecl(Constructor); 5941 } 5942 } 5943 5944 // Virtual base-class constructors. 5945 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 5946 BEnd = ClassDecl->vbases_end(); 5947 B != BEnd; ++B) { 5948 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 5949 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 5950 if (BaseClassDecl->needsImplicitDefaultConstructor()) 5951 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl)); 5952 else if (CXXConstructorDecl *Constructor 5953 = getDefaultConstructorUnsafe(*this, BaseClassDecl)) 5954 ExceptSpec.CalledDecl(Constructor); 5955 } 5956 } 5957 5958 // Field constructors. 5959 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 5960 FEnd = ClassDecl->field_end(); 5961 F != FEnd; ++F) { 5962 if (const RecordType *RecordTy 5963 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 5964 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 5965 if (FieldClassDecl->needsImplicitDefaultConstructor()) 5966 ExceptSpec.CalledDecl( 5967 DeclareImplicitDefaultConstructor(FieldClassDecl)); 5968 else if (CXXConstructorDecl *Constructor 5969 = getDefaultConstructorUnsafe(*this, FieldClassDecl)) 5970 ExceptSpec.CalledDecl(Constructor); 5971 } 5972 } 5973 5974 return ExceptSpec; 5975} 5976 5977CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 5978 CXXRecordDecl *ClassDecl) { 5979 // C++ [class.ctor]p5: 5980 // A default constructor for a class X is a constructor of class X 5981 // that can be called without an argument. If there is no 5982 // user-declared constructor for class X, a default constructor is 5983 // implicitly declared. An implicitly-declared default constructor 5984 // is an inline public member of its class. 5985 assert(!ClassDecl->hasUserDeclaredConstructor() && 5986 "Should not build implicit default constructor!"); 5987 5988 ImplicitExceptionSpecification Spec = 5989 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl); 5990 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 5991 5992 // Create the actual constructor declaration. 5993 CanQualType ClassType 5994 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 5995 SourceLocation ClassLoc = ClassDecl->getLocation(); 5996 DeclarationName Name 5997 = Context.DeclarationNames.getCXXConstructorName(ClassType); 5998 DeclarationNameInfo NameInfo(Name, ClassLoc); 5999 CXXConstructorDecl *DefaultCon 6000 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 6001 Context.getFunctionType(Context.VoidTy, 6002 0, 0, EPI), 6003 /*TInfo=*/0, 6004 /*isExplicit=*/false, 6005 /*isInline=*/true, 6006 /*isImplicitlyDeclared=*/true); 6007 DefaultCon->setAccess(AS_public); 6008 DefaultCon->setDefaulted(); 6009 DefaultCon->setImplicit(); 6010 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 6011 6012 // Note that we have declared this constructor. 6013 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 6014 6015 if (Scope *S = getScopeForContext(ClassDecl)) 6016 PushOnScopeChains(DefaultCon, S, false); 6017 ClassDecl->addDecl(DefaultCon); 6018 6019 if (ShouldDeleteDefaultConstructor(DefaultCon)) 6020 DefaultCon->setDeletedAsWritten(); 6021 6022 return DefaultCon; 6023} 6024 6025void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 6026 CXXConstructorDecl *Constructor) { 6027 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 6028 !Constructor->doesThisDeclarationHaveABody() && 6029 !Constructor->isDeleted()) && 6030 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 6031 6032 CXXRecordDecl *ClassDecl = Constructor->getParent(); 6033 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 6034 6035 ImplicitlyDefinedFunctionScope Scope(*this, Constructor); 6036 DiagnosticErrorTrap Trap(Diags); 6037 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) || 6038 Trap.hasErrorOccurred()) { 6039 Diag(CurrentLocation, diag::note_member_synthesized_at) 6040 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl); 6041 Constructor->setInvalidDecl(); 6042 return; 6043 } 6044 6045 SourceLocation Loc = Constructor->getLocation(); 6046 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc)); 6047 6048 Constructor->setUsed(); 6049 MarkVTableUsed(CurrentLocation, ClassDecl); 6050 6051 if (ASTMutationListener *L = getASTMutationListener()) { 6052 L->CompletedImplicitDefinition(Constructor); 6053 } 6054} 6055 6056void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) { 6057 // We start with an initial pass over the base classes to collect those that 6058 // inherit constructors from. If there are none, we can forgo all further 6059 // processing. 6060 typedef llvm::SmallVector<const RecordType *, 4> BasesVector; 6061 BasesVector BasesToInheritFrom; 6062 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(), 6063 BaseE = ClassDecl->bases_end(); 6064 BaseIt != BaseE; ++BaseIt) { 6065 if (BaseIt->getInheritConstructors()) { 6066 QualType Base = BaseIt->getType(); 6067 if (Base->isDependentType()) { 6068 // If we inherit constructors from anything that is dependent, just 6069 // abort processing altogether. We'll get another chance for the 6070 // instantiations. 6071 return; 6072 } 6073 BasesToInheritFrom.push_back(Base->castAs<RecordType>()); 6074 } 6075 } 6076 if (BasesToInheritFrom.empty()) 6077 return; 6078 6079 // Now collect the constructors that we already have in the current class. 6080 // Those take precedence over inherited constructors. 6081 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...] 6082 // unless there is a user-declared constructor with the same signature in 6083 // the class where the using-declaration appears. 6084 llvm::SmallSet<const Type *, 8> ExistingConstructors; 6085 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(), 6086 CtorE = ClassDecl->ctor_end(); 6087 CtorIt != CtorE; ++CtorIt) { 6088 ExistingConstructors.insert( 6089 Context.getCanonicalType(CtorIt->getType()).getTypePtr()); 6090 } 6091 6092 Scope *S = getScopeForContext(ClassDecl); 6093 DeclarationName CreatedCtorName = 6094 Context.DeclarationNames.getCXXConstructorName( 6095 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified()); 6096 6097 // Now comes the true work. 6098 // First, we keep a map from constructor types to the base that introduced 6099 // them. Needed for finding conflicting constructors. We also keep the 6100 // actually inserted declarations in there, for pretty diagnostics. 6101 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo; 6102 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap; 6103 ConstructorToSourceMap InheritedConstructors; 6104 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(), 6105 BaseE = BasesToInheritFrom.end(); 6106 BaseIt != BaseE; ++BaseIt) { 6107 const RecordType *Base = *BaseIt; 6108 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified(); 6109 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl()); 6110 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(), 6111 CtorE = BaseDecl->ctor_end(); 6112 CtorIt != CtorE; ++CtorIt) { 6113 // Find the using declaration for inheriting this base's constructors. 6114 DeclarationName Name = 6115 Context.DeclarationNames.getCXXConstructorName(CanonicalBase); 6116 UsingDecl *UD = dyn_cast_or_null<UsingDecl>( 6117 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName)); 6118 SourceLocation UsingLoc = UD ? UD->getLocation() : 6119 ClassDecl->getLocation(); 6120 6121 // C++0x [class.inhctor]p1: The candidate set of inherited constructors 6122 // from the class X named in the using-declaration consists of actual 6123 // constructors and notional constructors that result from the 6124 // transformation of defaulted parameters as follows: 6125 // - all non-template default constructors of X, and 6126 // - for each non-template constructor of X that has at least one 6127 // parameter with a default argument, the set of constructors that 6128 // results from omitting any ellipsis parameter specification and 6129 // successively omitting parameters with a default argument from the 6130 // end of the parameter-type-list. 6131 CXXConstructorDecl *BaseCtor = *CtorIt; 6132 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor(); 6133 const FunctionProtoType *BaseCtorType = 6134 BaseCtor->getType()->getAs<FunctionProtoType>(); 6135 6136 for (unsigned params = BaseCtor->getMinRequiredArguments(), 6137 maxParams = BaseCtor->getNumParams(); 6138 params <= maxParams; ++params) { 6139 // Skip default constructors. They're never inherited. 6140 if (params == 0) 6141 continue; 6142 // Skip copy and move constructors for the same reason. 6143 if (CanBeCopyOrMove && params == 1) 6144 continue; 6145 6146 // Build up a function type for this particular constructor. 6147 // FIXME: The working paper does not consider that the exception spec 6148 // for the inheriting constructor might be larger than that of the 6149 // source. This code doesn't yet, either. 6150 const Type *NewCtorType; 6151 if (params == maxParams) 6152 NewCtorType = BaseCtorType; 6153 else { 6154 llvm::SmallVector<QualType, 16> Args; 6155 for (unsigned i = 0; i < params; ++i) { 6156 Args.push_back(BaseCtorType->getArgType(i)); 6157 } 6158 FunctionProtoType::ExtProtoInfo ExtInfo = 6159 BaseCtorType->getExtProtoInfo(); 6160 ExtInfo.Variadic = false; 6161 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(), 6162 Args.data(), params, ExtInfo) 6163 .getTypePtr(); 6164 } 6165 const Type *CanonicalNewCtorType = 6166 Context.getCanonicalType(NewCtorType); 6167 6168 // Now that we have the type, first check if the class already has a 6169 // constructor with this signature. 6170 if (ExistingConstructors.count(CanonicalNewCtorType)) 6171 continue; 6172 6173 // Then we check if we have already declared an inherited constructor 6174 // with this signature. 6175 std::pair<ConstructorToSourceMap::iterator, bool> result = 6176 InheritedConstructors.insert(std::make_pair( 6177 CanonicalNewCtorType, 6178 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0))); 6179 if (!result.second) { 6180 // Already in the map. If it came from a different class, that's an 6181 // error. Not if it's from the same. 6182 CanQualType PreviousBase = result.first->second.first; 6183 if (CanonicalBase != PreviousBase) { 6184 const CXXConstructorDecl *PrevCtor = result.first->second.second; 6185 const CXXConstructorDecl *PrevBaseCtor = 6186 PrevCtor->getInheritedConstructor(); 6187 assert(PrevBaseCtor && "Conflicting constructor was not inherited"); 6188 6189 Diag(UsingLoc, diag::err_using_decl_constructor_conflict); 6190 Diag(BaseCtor->getLocation(), 6191 diag::note_using_decl_constructor_conflict_current_ctor); 6192 Diag(PrevBaseCtor->getLocation(), 6193 diag::note_using_decl_constructor_conflict_previous_ctor); 6194 Diag(PrevCtor->getLocation(), 6195 diag::note_using_decl_constructor_conflict_previous_using); 6196 } 6197 continue; 6198 } 6199 6200 // OK, we're there, now add the constructor. 6201 // C++0x [class.inhctor]p8: [...] that would be performed by a 6202 // user-writtern inline constructor [...] 6203 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc); 6204 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create( 6205 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0), 6206 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true, 6207 /*ImplicitlyDeclared=*/true); 6208 NewCtor->setAccess(BaseCtor->getAccess()); 6209 6210 // Build up the parameter decls and add them. 6211 llvm::SmallVector<ParmVarDecl *, 16> ParamDecls; 6212 for (unsigned i = 0; i < params; ++i) { 6213 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor, 6214 UsingLoc, UsingLoc, 6215 /*IdentifierInfo=*/0, 6216 BaseCtorType->getArgType(i), 6217 /*TInfo=*/0, SC_None, 6218 SC_None, /*DefaultArg=*/0)); 6219 } 6220 NewCtor->setParams(ParamDecls.data(), ParamDecls.size()); 6221 NewCtor->setInheritedConstructor(BaseCtor); 6222 6223 PushOnScopeChains(NewCtor, S, false); 6224 ClassDecl->addDecl(NewCtor); 6225 result.first->second.second = NewCtor; 6226 } 6227 } 6228 } 6229} 6230 6231Sema::ImplicitExceptionSpecification 6232Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) { 6233 // C++ [except.spec]p14: 6234 // An implicitly declared special member function (Clause 12) shall have 6235 // an exception-specification. 6236 ImplicitExceptionSpecification ExceptSpec(Context); 6237 6238 // Direct base-class destructors. 6239 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 6240 BEnd = ClassDecl->bases_end(); 6241 B != BEnd; ++B) { 6242 if (B->isVirtual()) // Handled below. 6243 continue; 6244 6245 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) 6246 ExceptSpec.CalledDecl( 6247 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 6248 } 6249 6250 // Virtual base-class destructors. 6251 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 6252 BEnd = ClassDecl->vbases_end(); 6253 B != BEnd; ++B) { 6254 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) 6255 ExceptSpec.CalledDecl( 6256 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 6257 } 6258 6259 // Field destructors. 6260 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 6261 FEnd = ClassDecl->field_end(); 6262 F != FEnd; ++F) { 6263 if (const RecordType *RecordTy 6264 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) 6265 ExceptSpec.CalledDecl( 6266 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl()))); 6267 } 6268 6269 return ExceptSpec; 6270} 6271 6272CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 6273 // C++ [class.dtor]p2: 6274 // If a class has no user-declared destructor, a destructor is 6275 // declared implicitly. An implicitly-declared destructor is an 6276 // inline public member of its class. 6277 6278 ImplicitExceptionSpecification Spec = 6279 ComputeDefaultedDtorExceptionSpec(ClassDecl); 6280 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 6281 6282 // Create the actual destructor declaration. 6283 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI); 6284 6285 CanQualType ClassType 6286 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 6287 SourceLocation ClassLoc = ClassDecl->getLocation(); 6288 DeclarationName Name 6289 = Context.DeclarationNames.getCXXDestructorName(ClassType); 6290 DeclarationNameInfo NameInfo(Name, ClassLoc); 6291 CXXDestructorDecl *Destructor 6292 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0, 6293 /*isInline=*/true, 6294 /*isImplicitlyDeclared=*/true); 6295 Destructor->setAccess(AS_public); 6296 Destructor->setDefaulted(); 6297 Destructor->setImplicit(); 6298 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 6299 6300 // Note that we have declared this destructor. 6301 ++ASTContext::NumImplicitDestructorsDeclared; 6302 6303 // Introduce this destructor into its scope. 6304 if (Scope *S = getScopeForContext(ClassDecl)) 6305 PushOnScopeChains(Destructor, S, false); 6306 ClassDecl->addDecl(Destructor); 6307 6308 // This could be uniqued if it ever proves significant. 6309 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty)); 6310 6311 if (ShouldDeleteDestructor(Destructor)) 6312 Destructor->setDeletedAsWritten(); 6313 6314 AddOverriddenMethods(ClassDecl, Destructor); 6315 6316 return Destructor; 6317} 6318 6319void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 6320 CXXDestructorDecl *Destructor) { 6321 assert((Destructor->isDefaulted() && 6322 !Destructor->doesThisDeclarationHaveABody()) && 6323 "DefineImplicitDestructor - call it for implicit default dtor"); 6324 CXXRecordDecl *ClassDecl = Destructor->getParent(); 6325 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 6326 6327 if (Destructor->isInvalidDecl()) 6328 return; 6329 6330 ImplicitlyDefinedFunctionScope Scope(*this, Destructor); 6331 6332 DiagnosticErrorTrap Trap(Diags); 6333 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 6334 Destructor->getParent()); 6335 6336 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) { 6337 Diag(CurrentLocation, diag::note_member_synthesized_at) 6338 << CXXDestructor << Context.getTagDeclType(ClassDecl); 6339 6340 Destructor->setInvalidDecl(); 6341 return; 6342 } 6343 6344 SourceLocation Loc = Destructor->getLocation(); 6345 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc)); 6346 6347 Destructor->setUsed(); 6348 MarkVTableUsed(CurrentLocation, ClassDecl); 6349 6350 if (ASTMutationListener *L = getASTMutationListener()) { 6351 L->CompletedImplicitDefinition(Destructor); 6352 } 6353} 6354 6355void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl, 6356 CXXDestructorDecl *destructor) { 6357 // C++11 [class.dtor]p3: 6358 // A declaration of a destructor that does not have an exception- 6359 // specification is implicitly considered to have the same exception- 6360 // specification as an implicit declaration. 6361 const FunctionProtoType *dtorType = destructor->getType()-> 6362 getAs<FunctionProtoType>(); 6363 if (dtorType->hasExceptionSpec()) 6364 return; 6365 6366 ImplicitExceptionSpecification exceptSpec = 6367 ComputeDefaultedDtorExceptionSpec(classDecl); 6368 6369 // Replace the destructor's type. 6370 FunctionProtoType::ExtProtoInfo epi; 6371 epi.ExceptionSpecType = exceptSpec.getExceptionSpecType(); 6372 epi.NumExceptions = exceptSpec.size(); 6373 epi.Exceptions = exceptSpec.data(); 6374 QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi); 6375 6376 destructor->setType(ty); 6377 6378 // FIXME: If the destructor has a body that could throw, and the newly created 6379 // spec doesn't allow exceptions, we should emit a warning, because this 6380 // change in behavior can break conforming C++03 programs at runtime. 6381 // However, we don't have a body yet, so it needs to be done somewhere else. 6382} 6383 6384/// \brief Builds a statement that copies the given entity from \p From to 6385/// \c To. 6386/// 6387/// This routine is used to copy the members of a class with an 6388/// implicitly-declared copy assignment operator. When the entities being 6389/// copied are arrays, this routine builds for loops to copy them. 6390/// 6391/// \param S The Sema object used for type-checking. 6392/// 6393/// \param Loc The location where the implicit copy is being generated. 6394/// 6395/// \param T The type of the expressions being copied. Both expressions must 6396/// have this type. 6397/// 6398/// \param To The expression we are copying to. 6399/// 6400/// \param From The expression we are copying from. 6401/// 6402/// \param CopyingBaseSubobject Whether we're copying a base subobject. 6403/// Otherwise, it's a non-static member subobject. 6404/// 6405/// \param Depth Internal parameter recording the depth of the recursion. 6406/// 6407/// \returns A statement or a loop that copies the expressions. 6408static StmtResult 6409BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 6410 Expr *To, Expr *From, 6411 bool CopyingBaseSubobject, unsigned Depth = 0) { 6412 // C++0x [class.copy]p30: 6413 // Each subobject is assigned in the manner appropriate to its type: 6414 // 6415 // - if the subobject is of class type, the copy assignment operator 6416 // for the class is used (as if by explicit qualification; that is, 6417 // ignoring any possible virtual overriding functions in more derived 6418 // classes); 6419 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 6420 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 6421 6422 // Look for operator=. 6423 DeclarationName Name 6424 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 6425 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 6426 S.LookupQualifiedName(OpLookup, ClassDecl, false); 6427 6428 // Filter out any result that isn't a copy-assignment operator. 6429 LookupResult::Filter F = OpLookup.makeFilter(); 6430 while (F.hasNext()) { 6431 NamedDecl *D = F.next(); 6432 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 6433 if (Method->isCopyAssignmentOperator()) 6434 continue; 6435 6436 F.erase(); 6437 } 6438 F.done(); 6439 6440 // Suppress the protected check (C++ [class.protected]) for each of the 6441 // assignment operators we found. This strange dance is required when 6442 // we're assigning via a base classes's copy-assignment operator. To 6443 // ensure that we're getting the right base class subobject (without 6444 // ambiguities), we need to cast "this" to that subobject type; to 6445 // ensure that we don't go through the virtual call mechanism, we need 6446 // to qualify the operator= name with the base class (see below). However, 6447 // this means that if the base class has a protected copy assignment 6448 // operator, the protected member access check will fail. So, we 6449 // rewrite "protected" access to "public" access in this case, since we 6450 // know by construction that we're calling from a derived class. 6451 if (CopyingBaseSubobject) { 6452 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 6453 L != LEnd; ++L) { 6454 if (L.getAccess() == AS_protected) 6455 L.setAccess(AS_public); 6456 } 6457 } 6458 6459 // Create the nested-name-specifier that will be used to qualify the 6460 // reference to operator=; this is required to suppress the virtual 6461 // call mechanism. 6462 CXXScopeSpec SS; 6463 SS.MakeTrivial(S.Context, 6464 NestedNameSpecifier::Create(S.Context, 0, false, 6465 T.getTypePtr()), 6466 Loc); 6467 6468 // Create the reference to operator=. 6469 ExprResult OpEqualRef 6470 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS, 6471 /*FirstQualifierInScope=*/0, OpLookup, 6472 /*TemplateArgs=*/0, 6473 /*SuppressQualifierCheck=*/true); 6474 if (OpEqualRef.isInvalid()) 6475 return StmtError(); 6476 6477 // Build the call to the assignment operator. 6478 6479 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0, 6480 OpEqualRef.takeAs<Expr>(), 6481 Loc, &From, 1, Loc); 6482 if (Call.isInvalid()) 6483 return StmtError(); 6484 6485 return S.Owned(Call.takeAs<Stmt>()); 6486 } 6487 6488 // - if the subobject is of scalar type, the built-in assignment 6489 // operator is used. 6490 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 6491 if (!ArrayTy) { 6492 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From); 6493 if (Assignment.isInvalid()) 6494 return StmtError(); 6495 6496 return S.Owned(Assignment.takeAs<Stmt>()); 6497 } 6498 6499 // - if the subobject is an array, each element is assigned, in the 6500 // manner appropriate to the element type; 6501 6502 // Construct a loop over the array bounds, e.g., 6503 // 6504 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 6505 // 6506 // that will copy each of the array elements. 6507 QualType SizeType = S.Context.getSizeType(); 6508 6509 // Create the iteration variable. 6510 IdentifierInfo *IterationVarName = 0; 6511 { 6512 llvm::SmallString<8> Str; 6513 llvm::raw_svector_ostream OS(Str); 6514 OS << "__i" << Depth; 6515 IterationVarName = &S.Context.Idents.get(OS.str()); 6516 } 6517 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 6518 IterationVarName, SizeType, 6519 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 6520 SC_None, SC_None); 6521 6522 // Initialize the iteration variable to zero. 6523 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 6524 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 6525 6526 // Create a reference to the iteration variable; we'll use this several 6527 // times throughout. 6528 Expr *IterationVarRef 6529 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take(); 6530 assert(IterationVarRef && "Reference to invented variable cannot fail!"); 6531 6532 // Create the DeclStmt that holds the iteration variable. 6533 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 6534 6535 // Create the comparison against the array bound. 6536 llvm::APInt Upper 6537 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 6538 Expr *Comparison 6539 = new (S.Context) BinaryOperator(IterationVarRef, 6540 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 6541 BO_NE, S.Context.BoolTy, 6542 VK_RValue, OK_Ordinary, Loc); 6543 6544 // Create the pre-increment of the iteration variable. 6545 Expr *Increment 6546 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType, 6547 VK_LValue, OK_Ordinary, Loc); 6548 6549 // Subscript the "from" and "to" expressions with the iteration variable. 6550 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc, 6551 IterationVarRef, Loc)); 6552 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc, 6553 IterationVarRef, Loc)); 6554 6555 // Build the copy for an individual element of the array. 6556 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(), 6557 To, From, CopyingBaseSubobject, 6558 Depth + 1); 6559 if (Copy.isInvalid()) 6560 return StmtError(); 6561 6562 // Construct the loop that copies all elements of this array. 6563 return S.ActOnForStmt(Loc, Loc, InitStmt, 6564 S.MakeFullExpr(Comparison), 6565 0, S.MakeFullExpr(Increment), 6566 Loc, Copy.take()); 6567} 6568 6569/// \brief Determine whether the given class has a copy assignment operator 6570/// that accepts a const-qualified argument. 6571static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) { 6572 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass); 6573 6574 if (!Class->hasDeclaredCopyAssignment()) 6575 S.DeclareImplicitCopyAssignment(Class); 6576 6577 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class)); 6578 DeclarationName OpName 6579 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 6580 6581 DeclContext::lookup_const_iterator Op, OpEnd; 6582 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) { 6583 // C++ [class.copy]p9: 6584 // A user-declared copy assignment operator is a non-static non-template 6585 // member function of class X with exactly one parameter of type X, X&, 6586 // const X&, volatile X& or const volatile X&. 6587 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op); 6588 if (!Method) 6589 continue; 6590 6591 if (Method->isStatic()) 6592 continue; 6593 if (Method->getPrimaryTemplate()) 6594 continue; 6595 const FunctionProtoType *FnType = 6596 Method->getType()->getAs<FunctionProtoType>(); 6597 assert(FnType && "Overloaded operator has no prototype."); 6598 // Don't assert on this; an invalid decl might have been left in the AST. 6599 if (FnType->getNumArgs() != 1 || FnType->isVariadic()) 6600 continue; 6601 bool AcceptsConst = true; 6602 QualType ArgType = FnType->getArgType(0); 6603 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){ 6604 ArgType = Ref->getPointeeType(); 6605 // Is it a non-const lvalue reference? 6606 if (!ArgType.isConstQualified()) 6607 AcceptsConst = false; 6608 } 6609 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType)) 6610 continue; 6611 6612 // We have a single argument of type cv X or cv X&, i.e. we've found the 6613 // copy assignment operator. Return whether it accepts const arguments. 6614 return AcceptsConst; 6615 } 6616 assert(Class->isInvalidDecl() && 6617 "No copy assignment operator declared in valid code."); 6618 return false; 6619} 6620 6621std::pair<Sema::ImplicitExceptionSpecification, bool> 6622Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst( 6623 CXXRecordDecl *ClassDecl) { 6624 // C++ [class.copy]p10: 6625 // If the class definition does not explicitly declare a copy 6626 // assignment operator, one is declared implicitly. 6627 // The implicitly-defined copy assignment operator for a class X 6628 // will have the form 6629 // 6630 // X& X::operator=(const X&) 6631 // 6632 // if 6633 bool HasConstCopyAssignment = true; 6634 6635 // -- each direct base class B of X has a copy assignment operator 6636 // whose parameter is of type const B&, const volatile B& or B, 6637 // and 6638 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 6639 BaseEnd = ClassDecl->bases_end(); 6640 HasConstCopyAssignment && Base != BaseEnd; ++Base) { 6641 assert(!Base->getType()->isDependentType() && 6642 "Cannot generate implicit members for class with dependent bases."); 6643 const CXXRecordDecl *BaseClassDecl 6644 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 6645 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl); 6646 } 6647 6648 // -- for all the nonstatic data members of X that are of a class 6649 // type M (or array thereof), each such class type has a copy 6650 // assignment operator whose parameter is of type const M&, 6651 // const volatile M& or M. 6652 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 6653 FieldEnd = ClassDecl->field_end(); 6654 HasConstCopyAssignment && Field != FieldEnd; 6655 ++Field) { 6656 QualType FieldType = Context.getBaseElementType((*Field)->getType()); 6657 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 6658 const CXXRecordDecl *FieldClassDecl 6659 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 6660 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl); 6661 } 6662 } 6663 6664 // Otherwise, the implicitly declared copy assignment operator will 6665 // have the form 6666 // 6667 // X& X::operator=(X&) 6668 6669 // C++ [except.spec]p14: 6670 // An implicitly declared special member function (Clause 12) shall have an 6671 // exception-specification. [...] 6672 ImplicitExceptionSpecification ExceptSpec(Context); 6673 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 6674 BaseEnd = ClassDecl->bases_end(); 6675 Base != BaseEnd; ++Base) { 6676 CXXRecordDecl *BaseClassDecl 6677 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 6678 6679 if (!BaseClassDecl->hasDeclaredCopyAssignment()) 6680 DeclareImplicitCopyAssignment(BaseClassDecl); 6681 6682 if (CXXMethodDecl *CopyAssign 6683 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment)) 6684 ExceptSpec.CalledDecl(CopyAssign); 6685 } 6686 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 6687 FieldEnd = ClassDecl->field_end(); 6688 Field != FieldEnd; 6689 ++Field) { 6690 QualType FieldType = Context.getBaseElementType((*Field)->getType()); 6691 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 6692 CXXRecordDecl *FieldClassDecl 6693 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 6694 6695 if (!FieldClassDecl->hasDeclaredCopyAssignment()) 6696 DeclareImplicitCopyAssignment(FieldClassDecl); 6697 6698 if (CXXMethodDecl *CopyAssign 6699 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment)) 6700 ExceptSpec.CalledDecl(CopyAssign); 6701 } 6702 } 6703 6704 return std::make_pair(ExceptSpec, HasConstCopyAssignment); 6705} 6706 6707CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 6708 // Note: The following rules are largely analoguous to the copy 6709 // constructor rules. Note that virtual bases are not taken into account 6710 // for determining the argument type of the operator. Note also that 6711 // operators taking an object instead of a reference are allowed. 6712 6713 ImplicitExceptionSpecification Spec(Context); 6714 bool Const; 6715 llvm::tie(Spec, Const) = 6716 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl); 6717 6718 QualType ArgType = Context.getTypeDeclType(ClassDecl); 6719 QualType RetType = Context.getLValueReferenceType(ArgType); 6720 if (Const) 6721 ArgType = ArgType.withConst(); 6722 ArgType = Context.getLValueReferenceType(ArgType); 6723 6724 // An implicitly-declared copy assignment operator is an inline public 6725 // member of its class. 6726 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 6727 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 6728 SourceLocation ClassLoc = ClassDecl->getLocation(); 6729 DeclarationNameInfo NameInfo(Name, ClassLoc); 6730 CXXMethodDecl *CopyAssignment 6731 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 6732 Context.getFunctionType(RetType, &ArgType, 1, EPI), 6733 /*TInfo=*/0, /*isStatic=*/false, 6734 /*StorageClassAsWritten=*/SC_None, 6735 /*isInline=*/true, 6736 SourceLocation()); 6737 CopyAssignment->setAccess(AS_public); 6738 CopyAssignment->setDefaulted(); 6739 CopyAssignment->setImplicit(); 6740 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment()); 6741 6742 // Add the parameter to the operator. 6743 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 6744 ClassLoc, ClassLoc, /*Id=*/0, 6745 ArgType, /*TInfo=*/0, 6746 SC_None, 6747 SC_None, 0); 6748 CopyAssignment->setParams(&FromParam, 1); 6749 6750 // Note that we have added this copy-assignment operator. 6751 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 6752 6753 if (Scope *S = getScopeForContext(ClassDecl)) 6754 PushOnScopeChains(CopyAssignment, S, false); 6755 ClassDecl->addDecl(CopyAssignment); 6756 6757 if (ShouldDeleteCopyAssignmentOperator(CopyAssignment)) 6758 CopyAssignment->setDeletedAsWritten(); 6759 6760 AddOverriddenMethods(ClassDecl, CopyAssignment); 6761 return CopyAssignment; 6762} 6763 6764void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 6765 CXXMethodDecl *CopyAssignOperator) { 6766 assert((CopyAssignOperator->isDefaulted() && 6767 CopyAssignOperator->isOverloadedOperator() && 6768 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 6769 !CopyAssignOperator->doesThisDeclarationHaveABody()) && 6770 "DefineImplicitCopyAssignment called for wrong function"); 6771 6772 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 6773 6774 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) { 6775 CopyAssignOperator->setInvalidDecl(); 6776 return; 6777 } 6778 6779 CopyAssignOperator->setUsed(); 6780 6781 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator); 6782 DiagnosticErrorTrap Trap(Diags); 6783 6784 // C++0x [class.copy]p30: 6785 // The implicitly-defined or explicitly-defaulted copy assignment operator 6786 // for a non-union class X performs memberwise copy assignment of its 6787 // subobjects. The direct base classes of X are assigned first, in the 6788 // order of their declaration in the base-specifier-list, and then the 6789 // immediate non-static data members of X are assigned, in the order in 6790 // which they were declared in the class definition. 6791 6792 // The statements that form the synthesized function body. 6793 ASTOwningVector<Stmt*> Statements(*this); 6794 6795 // The parameter for the "other" object, which we are copying from. 6796 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 6797 Qualifiers OtherQuals = Other->getType().getQualifiers(); 6798 QualType OtherRefType = Other->getType(); 6799 if (const LValueReferenceType *OtherRef 6800 = OtherRefType->getAs<LValueReferenceType>()) { 6801 OtherRefType = OtherRef->getPointeeType(); 6802 OtherQuals = OtherRefType.getQualifiers(); 6803 } 6804 6805 // Our location for everything implicitly-generated. 6806 SourceLocation Loc = CopyAssignOperator->getLocation(); 6807 6808 // Construct a reference to the "other" object. We'll be using this 6809 // throughout the generated ASTs. 6810 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take(); 6811 assert(OtherRef && "Reference to parameter cannot fail!"); 6812 6813 // Construct the "this" pointer. We'll be using this throughout the generated 6814 // ASTs. 6815 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>(); 6816 assert(This && "Reference to this cannot fail!"); 6817 6818 // Assign base classes. 6819 bool Invalid = false; 6820 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 6821 E = ClassDecl->bases_end(); Base != E; ++Base) { 6822 // Form the assignment: 6823 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 6824 QualType BaseType = Base->getType().getUnqualifiedType(); 6825 if (!BaseType->isRecordType()) { 6826 Invalid = true; 6827 continue; 6828 } 6829 6830 CXXCastPath BasePath; 6831 BasePath.push_back(Base); 6832 6833 // Construct the "from" expression, which is an implicit cast to the 6834 // appropriately-qualified base type. 6835 Expr *From = OtherRef; 6836 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals), 6837 CK_UncheckedDerivedToBase, 6838 VK_LValue, &BasePath).take(); 6839 6840 // Dereference "this". 6841 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 6842 6843 // Implicitly cast "this" to the appropriately-qualified base type. 6844 To = ImpCastExprToType(To.take(), 6845 Context.getCVRQualifiedType(BaseType, 6846 CopyAssignOperator->getTypeQualifiers()), 6847 CK_UncheckedDerivedToBase, 6848 VK_LValue, &BasePath); 6849 6850 // Build the copy. 6851 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType, 6852 To.get(), From, 6853 /*CopyingBaseSubobject=*/true); 6854 if (Copy.isInvalid()) { 6855 Diag(CurrentLocation, diag::note_member_synthesized_at) 6856 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 6857 CopyAssignOperator->setInvalidDecl(); 6858 return; 6859 } 6860 6861 // Success! Record the copy. 6862 Statements.push_back(Copy.takeAs<Expr>()); 6863 } 6864 6865 // \brief Reference to the __builtin_memcpy function. 6866 Expr *BuiltinMemCpyRef = 0; 6867 // \brief Reference to the __builtin_objc_memmove_collectable function. 6868 Expr *CollectableMemCpyRef = 0; 6869 6870 // Assign non-static members. 6871 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 6872 FieldEnd = ClassDecl->field_end(); 6873 Field != FieldEnd; ++Field) { 6874 // Check for members of reference type; we can't copy those. 6875 if (Field->getType()->isReferenceType()) { 6876 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 6877 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 6878 Diag(Field->getLocation(), diag::note_declared_at); 6879 Diag(CurrentLocation, diag::note_member_synthesized_at) 6880 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 6881 Invalid = true; 6882 continue; 6883 } 6884 6885 // Check for members of const-qualified, non-class type. 6886 QualType BaseType = Context.getBaseElementType(Field->getType()); 6887 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 6888 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 6889 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 6890 Diag(Field->getLocation(), diag::note_declared_at); 6891 Diag(CurrentLocation, diag::note_member_synthesized_at) 6892 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 6893 Invalid = true; 6894 continue; 6895 } 6896 6897 QualType FieldType = Field->getType().getNonReferenceType(); 6898 if (FieldType->isIncompleteArrayType()) { 6899 assert(ClassDecl->hasFlexibleArrayMember() && 6900 "Incomplete array type is not valid"); 6901 continue; 6902 } 6903 6904 // Build references to the field in the object we're copying from and to. 6905 CXXScopeSpec SS; // Intentionally empty 6906 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 6907 LookupMemberName); 6908 MemberLookup.addDecl(*Field); 6909 MemberLookup.resolveKind(); 6910 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType, 6911 Loc, /*IsArrow=*/false, 6912 SS, 0, MemberLookup, 0); 6913 ExprResult To = BuildMemberReferenceExpr(This, This->getType(), 6914 Loc, /*IsArrow=*/true, 6915 SS, 0, MemberLookup, 0); 6916 assert(!From.isInvalid() && "Implicit field reference cannot fail"); 6917 assert(!To.isInvalid() && "Implicit field reference cannot fail"); 6918 6919 // If the field should be copied with __builtin_memcpy rather than via 6920 // explicit assignments, do so. This optimization only applies for arrays 6921 // of scalars and arrays of class type with trivial copy-assignment 6922 // operators. 6923 if (FieldType->isArrayType() && 6924 (!BaseType->isRecordType() || 6925 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl()) 6926 ->hasTrivialCopyAssignment())) { 6927 // Compute the size of the memory buffer to be copied. 6928 QualType SizeType = Context.getSizeType(); 6929 llvm::APInt Size(Context.getTypeSize(SizeType), 6930 Context.getTypeSizeInChars(BaseType).getQuantity()); 6931 for (const ConstantArrayType *Array 6932 = Context.getAsConstantArrayType(FieldType); 6933 Array; 6934 Array = Context.getAsConstantArrayType(Array->getElementType())) { 6935 llvm::APInt ArraySize 6936 = Array->getSize().zextOrTrunc(Size.getBitWidth()); 6937 Size *= ArraySize; 6938 } 6939 6940 // Take the address of the field references for "from" and "to". 6941 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get()); 6942 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get()); 6943 6944 bool NeedsCollectableMemCpy = 6945 (BaseType->isRecordType() && 6946 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()); 6947 6948 if (NeedsCollectableMemCpy) { 6949 if (!CollectableMemCpyRef) { 6950 // Create a reference to the __builtin_objc_memmove_collectable function. 6951 LookupResult R(*this, 6952 &Context.Idents.get("__builtin_objc_memmove_collectable"), 6953 Loc, LookupOrdinaryName); 6954 LookupName(R, TUScope, true); 6955 6956 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>(); 6957 if (!CollectableMemCpy) { 6958 // Something went horribly wrong earlier, and we will have 6959 // complained about it. 6960 Invalid = true; 6961 continue; 6962 } 6963 6964 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy, 6965 CollectableMemCpy->getType(), 6966 VK_LValue, Loc, 0).take(); 6967 assert(CollectableMemCpyRef && "Builtin reference cannot fail"); 6968 } 6969 } 6970 // Create a reference to the __builtin_memcpy builtin function. 6971 else if (!BuiltinMemCpyRef) { 6972 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc, 6973 LookupOrdinaryName); 6974 LookupName(R, TUScope, true); 6975 6976 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>(); 6977 if (!BuiltinMemCpy) { 6978 // Something went horribly wrong earlier, and we will have complained 6979 // about it. 6980 Invalid = true; 6981 continue; 6982 } 6983 6984 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy, 6985 BuiltinMemCpy->getType(), 6986 VK_LValue, Loc, 0).take(); 6987 assert(BuiltinMemCpyRef && "Builtin reference cannot fail"); 6988 } 6989 6990 ASTOwningVector<Expr*> CallArgs(*this); 6991 CallArgs.push_back(To.takeAs<Expr>()); 6992 CallArgs.push_back(From.takeAs<Expr>()); 6993 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc)); 6994 ExprResult Call = ExprError(); 6995 if (NeedsCollectableMemCpy) 6996 Call = ActOnCallExpr(/*Scope=*/0, 6997 CollectableMemCpyRef, 6998 Loc, move_arg(CallArgs), 6999 Loc); 7000 else 7001 Call = ActOnCallExpr(/*Scope=*/0, 7002 BuiltinMemCpyRef, 7003 Loc, move_arg(CallArgs), 7004 Loc); 7005 7006 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 7007 Statements.push_back(Call.takeAs<Expr>()); 7008 continue; 7009 } 7010 7011 // Build the copy of this field. 7012 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType, 7013 To.get(), From.get(), 7014 /*CopyingBaseSubobject=*/false); 7015 if (Copy.isInvalid()) { 7016 Diag(CurrentLocation, diag::note_member_synthesized_at) 7017 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 7018 CopyAssignOperator->setInvalidDecl(); 7019 return; 7020 } 7021 7022 // Success! Record the copy. 7023 Statements.push_back(Copy.takeAs<Stmt>()); 7024 } 7025 7026 if (!Invalid) { 7027 // Add a "return *this;" 7028 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 7029 7030 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get()); 7031 if (Return.isInvalid()) 7032 Invalid = true; 7033 else { 7034 Statements.push_back(Return.takeAs<Stmt>()); 7035 7036 if (Trap.hasErrorOccurred()) { 7037 Diag(CurrentLocation, diag::note_member_synthesized_at) 7038 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 7039 Invalid = true; 7040 } 7041 } 7042 } 7043 7044 if (Invalid) { 7045 CopyAssignOperator->setInvalidDecl(); 7046 return; 7047 } 7048 7049 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements), 7050 /*isStmtExpr=*/false); 7051 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 7052 CopyAssignOperator->setBody(Body.takeAs<Stmt>()); 7053 7054 if (ASTMutationListener *L = getASTMutationListener()) { 7055 L->CompletedImplicitDefinition(CopyAssignOperator); 7056 } 7057} 7058 7059std::pair<Sema::ImplicitExceptionSpecification, bool> 7060Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) { 7061 // C++ [class.copy]p5: 7062 // The implicitly-declared copy constructor for a class X will 7063 // have the form 7064 // 7065 // X::X(const X&) 7066 // 7067 // if 7068 bool HasConstCopyConstructor = true; 7069 7070 // -- each direct or virtual base class B of X has a copy 7071 // constructor whose first parameter is of type const B& or 7072 // const volatile B&, and 7073 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 7074 BaseEnd = ClassDecl->bases_end(); 7075 HasConstCopyConstructor && Base != BaseEnd; 7076 ++Base) { 7077 // Virtual bases are handled below. 7078 if (Base->isVirtual()) 7079 continue; 7080 7081 CXXRecordDecl *BaseClassDecl 7082 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 7083 if (!BaseClassDecl->hasDeclaredCopyConstructor()) 7084 DeclareImplicitCopyConstructor(BaseClassDecl); 7085 7086 HasConstCopyConstructor = BaseClassDecl->hasConstCopyConstructor(); 7087 } 7088 7089 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 7090 BaseEnd = ClassDecl->vbases_end(); 7091 HasConstCopyConstructor && Base != BaseEnd; 7092 ++Base) { 7093 CXXRecordDecl *BaseClassDecl 7094 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 7095 if (!BaseClassDecl->hasDeclaredCopyConstructor()) 7096 DeclareImplicitCopyConstructor(BaseClassDecl); 7097 7098 HasConstCopyConstructor= BaseClassDecl->hasConstCopyConstructor(); 7099 } 7100 7101 // -- for all the nonstatic data members of X that are of a 7102 // class type M (or array thereof), each such class type 7103 // has a copy constructor whose first parameter is of type 7104 // const M& or const volatile M&. 7105 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 7106 FieldEnd = ClassDecl->field_end(); 7107 HasConstCopyConstructor && Field != FieldEnd; 7108 ++Field) { 7109 QualType FieldType = Context.getBaseElementType((*Field)->getType()); 7110 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 7111 CXXRecordDecl *FieldClassDecl 7112 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 7113 if (!FieldClassDecl->hasDeclaredCopyConstructor()) 7114 DeclareImplicitCopyConstructor(FieldClassDecl); 7115 7116 HasConstCopyConstructor = FieldClassDecl->hasConstCopyConstructor(); 7117 } 7118 } 7119 // Otherwise, the implicitly declared copy constructor will have 7120 // the form 7121 // 7122 // X::X(X&) 7123 7124 // C++ [except.spec]p14: 7125 // An implicitly declared special member function (Clause 12) shall have an 7126 // exception-specification. [...] 7127 ImplicitExceptionSpecification ExceptSpec(Context); 7128 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0; 7129 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 7130 BaseEnd = ClassDecl->bases_end(); 7131 Base != BaseEnd; 7132 ++Base) { 7133 // Virtual bases are handled below. 7134 if (Base->isVirtual()) 7135 continue; 7136 7137 CXXRecordDecl *BaseClassDecl 7138 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 7139 if (!BaseClassDecl->hasDeclaredCopyConstructor()) 7140 DeclareImplicitCopyConstructor(BaseClassDecl); 7141 7142 if (CXXConstructorDecl *CopyConstructor 7143 = BaseClassDecl->getCopyConstructor(Quals)) 7144 ExceptSpec.CalledDecl(CopyConstructor); 7145 } 7146 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 7147 BaseEnd = ClassDecl->vbases_end(); 7148 Base != BaseEnd; 7149 ++Base) { 7150 CXXRecordDecl *BaseClassDecl 7151 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 7152 if (!BaseClassDecl->hasDeclaredCopyConstructor()) 7153 DeclareImplicitCopyConstructor(BaseClassDecl); 7154 7155 if (CXXConstructorDecl *CopyConstructor 7156 = BaseClassDecl->getCopyConstructor(Quals)) 7157 ExceptSpec.CalledDecl(CopyConstructor); 7158 } 7159 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 7160 FieldEnd = ClassDecl->field_end(); 7161 Field != FieldEnd; 7162 ++Field) { 7163 QualType FieldType = Context.getBaseElementType((*Field)->getType()); 7164 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 7165 CXXRecordDecl *FieldClassDecl 7166 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 7167 if (!FieldClassDecl->hasDeclaredCopyConstructor()) 7168 DeclareImplicitCopyConstructor(FieldClassDecl); 7169 7170 if (CXXConstructorDecl *CopyConstructor 7171 = FieldClassDecl->getCopyConstructor(Quals)) 7172 ExceptSpec.CalledDecl(CopyConstructor); 7173 } 7174 } 7175 7176 return std::make_pair(ExceptSpec, HasConstCopyConstructor); 7177} 7178 7179CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 7180 CXXRecordDecl *ClassDecl) { 7181 // C++ [class.copy]p4: 7182 // If the class definition does not explicitly declare a copy 7183 // constructor, one is declared implicitly. 7184 7185 ImplicitExceptionSpecification Spec(Context); 7186 bool Const; 7187 llvm::tie(Spec, Const) = 7188 ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl); 7189 7190 QualType ClassType = Context.getTypeDeclType(ClassDecl); 7191 QualType ArgType = ClassType; 7192 if (Const) 7193 ArgType = ArgType.withConst(); 7194 ArgType = Context.getLValueReferenceType(ArgType); 7195 7196 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 7197 7198 DeclarationName Name 7199 = Context.DeclarationNames.getCXXConstructorName( 7200 Context.getCanonicalType(ClassType)); 7201 SourceLocation ClassLoc = ClassDecl->getLocation(); 7202 DeclarationNameInfo NameInfo(Name, ClassLoc); 7203 7204 // An implicitly-declared copy constructor is an inline public 7205 // member of its class. 7206 CXXConstructorDecl *CopyConstructor 7207 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 7208 Context.getFunctionType(Context.VoidTy, 7209 &ArgType, 1, EPI), 7210 /*TInfo=*/0, 7211 /*isExplicit=*/false, 7212 /*isInline=*/true, 7213 /*isImplicitlyDeclared=*/true); 7214 CopyConstructor->setAccess(AS_public); 7215 CopyConstructor->setDefaulted(); 7216 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor()); 7217 7218 // Note that we have declared this constructor. 7219 ++ASTContext::NumImplicitCopyConstructorsDeclared; 7220 7221 // Add the parameter to the constructor. 7222 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 7223 ClassLoc, ClassLoc, 7224 /*IdentifierInfo=*/0, 7225 ArgType, /*TInfo=*/0, 7226 SC_None, 7227 SC_None, 0); 7228 CopyConstructor->setParams(&FromParam, 1); 7229 7230 if (Scope *S = getScopeForContext(ClassDecl)) 7231 PushOnScopeChains(CopyConstructor, S, false); 7232 ClassDecl->addDecl(CopyConstructor); 7233 7234 if (ShouldDeleteCopyConstructor(CopyConstructor)) 7235 CopyConstructor->setDeletedAsWritten(); 7236 7237 return CopyConstructor; 7238} 7239 7240void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 7241 CXXConstructorDecl *CopyConstructor) { 7242 assert((CopyConstructor->isDefaulted() && 7243 CopyConstructor->isCopyConstructor() && 7244 !CopyConstructor->doesThisDeclarationHaveABody()) && 7245 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 7246 7247 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 7248 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 7249 7250 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor); 7251 DiagnosticErrorTrap Trap(Diags); 7252 7253 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) || 7254 Trap.hasErrorOccurred()) { 7255 Diag(CurrentLocation, diag::note_member_synthesized_at) 7256 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl); 7257 CopyConstructor->setInvalidDecl(); 7258 } else { 7259 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(), 7260 CopyConstructor->getLocation(), 7261 MultiStmtArg(*this, 0, 0), 7262 /*isStmtExpr=*/false) 7263 .takeAs<Stmt>()); 7264 } 7265 7266 CopyConstructor->setUsed(); 7267 7268 if (ASTMutationListener *L = getASTMutationListener()) { 7269 L->CompletedImplicitDefinition(CopyConstructor); 7270 } 7271} 7272 7273ExprResult 7274Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 7275 CXXConstructorDecl *Constructor, 7276 MultiExprArg ExprArgs, 7277 bool RequiresZeroInit, 7278 unsigned ConstructKind, 7279 SourceRange ParenRange) { 7280 bool Elidable = false; 7281 7282 // C++0x [class.copy]p34: 7283 // When certain criteria are met, an implementation is allowed to 7284 // omit the copy/move construction of a class object, even if the 7285 // copy/move constructor and/or destructor for the object have 7286 // side effects. [...] 7287 // - when a temporary class object that has not been bound to a 7288 // reference (12.2) would be copied/moved to a class object 7289 // with the same cv-unqualified type, the copy/move operation 7290 // can be omitted by constructing the temporary object 7291 // directly into the target of the omitted copy/move 7292 if (ConstructKind == CXXConstructExpr::CK_Complete && 7293 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) { 7294 Expr *SubExpr = ((Expr **)ExprArgs.get())[0]; 7295 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent()); 7296 } 7297 7298 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 7299 Elidable, move(ExprArgs), RequiresZeroInit, 7300 ConstructKind, ParenRange); 7301} 7302 7303/// BuildCXXConstructExpr - Creates a complete call to a constructor, 7304/// including handling of its default argument expressions. 7305ExprResult 7306Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 7307 CXXConstructorDecl *Constructor, bool Elidable, 7308 MultiExprArg ExprArgs, 7309 bool RequiresZeroInit, 7310 unsigned ConstructKind, 7311 SourceRange ParenRange) { 7312 unsigned NumExprs = ExprArgs.size(); 7313 Expr **Exprs = (Expr **)ExprArgs.release(); 7314 7315 for (specific_attr_iterator<NonNullAttr> 7316 i = Constructor->specific_attr_begin<NonNullAttr>(), 7317 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) { 7318 const NonNullAttr *NonNull = *i; 7319 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc); 7320 } 7321 7322 MarkDeclarationReferenced(ConstructLoc, Constructor); 7323 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc, 7324 Constructor, Elidable, Exprs, NumExprs, 7325 RequiresZeroInit, 7326 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 7327 ParenRange)); 7328} 7329 7330bool Sema::InitializeVarWithConstructor(VarDecl *VD, 7331 CXXConstructorDecl *Constructor, 7332 MultiExprArg Exprs) { 7333 // FIXME: Provide the correct paren SourceRange when available. 7334 ExprResult TempResult = 7335 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor, 7336 move(Exprs), false, CXXConstructExpr::CK_Complete, 7337 SourceRange()); 7338 if (TempResult.isInvalid()) 7339 return true; 7340 7341 Expr *Temp = TempResult.takeAs<Expr>(); 7342 CheckImplicitConversions(Temp, VD->getLocation()); 7343 MarkDeclarationReferenced(VD->getLocation(), Constructor); 7344 Temp = MaybeCreateExprWithCleanups(Temp); 7345 VD->setInit(Temp); 7346 7347 return false; 7348} 7349 7350void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 7351 if (VD->isInvalidDecl()) return; 7352 7353 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 7354 if (ClassDecl->isInvalidDecl()) return; 7355 if (ClassDecl->hasTrivialDestructor()) return; 7356 if (ClassDecl->isDependentContext()) return; 7357 7358 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 7359 MarkDeclarationReferenced(VD->getLocation(), Destructor); 7360 CheckDestructorAccess(VD->getLocation(), Destructor, 7361 PDiag(diag::err_access_dtor_var) 7362 << VD->getDeclName() 7363 << VD->getType()); 7364 7365 if (!VD->hasGlobalStorage()) return; 7366 7367 // Emit warning for non-trivial dtor in global scope (a real global, 7368 // class-static, function-static). 7369 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 7370 7371 // TODO: this should be re-enabled for static locals by !CXAAtExit 7372 if (!VD->isStaticLocal()) 7373 Diag(VD->getLocation(), diag::warn_global_destructor); 7374} 7375 7376/// AddCXXDirectInitializerToDecl - This action is called immediately after 7377/// ActOnDeclarator, when a C++ direct initializer is present. 7378/// e.g: "int x(1);" 7379void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl, 7380 SourceLocation LParenLoc, 7381 MultiExprArg Exprs, 7382 SourceLocation RParenLoc, 7383 bool TypeMayContainAuto) { 7384 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions"); 7385 7386 // If there is no declaration, there was an error parsing it. Just ignore 7387 // the initializer. 7388 if (RealDecl == 0) 7389 return; 7390 7391 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 7392 if (!VDecl) { 7393 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 7394 RealDecl->setInvalidDecl(); 7395 return; 7396 } 7397 7398 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 7399 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) { 7400 // FIXME: n3225 doesn't actually seem to indicate this is ill-formed 7401 if (Exprs.size() > 1) { 7402 Diag(Exprs.get()[1]->getSourceRange().getBegin(), 7403 diag::err_auto_var_init_multiple_expressions) 7404 << VDecl->getDeclName() << VDecl->getType() 7405 << VDecl->getSourceRange(); 7406 RealDecl->setInvalidDecl(); 7407 return; 7408 } 7409 7410 Expr *Init = Exprs.get()[0]; 7411 TypeSourceInfo *DeducedType = 0; 7412 if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType)) 7413 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure) 7414 << VDecl->getDeclName() << VDecl->getType() << Init->getType() 7415 << Init->getSourceRange(); 7416 if (!DeducedType) { 7417 RealDecl->setInvalidDecl(); 7418 return; 7419 } 7420 VDecl->setTypeSourceInfo(DeducedType); 7421 VDecl->setType(DeducedType->getType()); 7422 7423 // If this is a redeclaration, check that the type we just deduced matches 7424 // the previously declared type. 7425 if (VarDecl *Old = VDecl->getPreviousDeclaration()) 7426 MergeVarDeclTypes(VDecl, Old); 7427 } 7428 7429 // We will represent direct-initialization similarly to copy-initialization: 7430 // int x(1); -as-> int x = 1; 7431 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 7432 // 7433 // Clients that want to distinguish between the two forms, can check for 7434 // direct initializer using VarDecl::hasCXXDirectInitializer(). 7435 // A major benefit is that clients that don't particularly care about which 7436 // exactly form was it (like the CodeGen) can handle both cases without 7437 // special case code. 7438 7439 // C++ 8.5p11: 7440 // The form of initialization (using parentheses or '=') is generally 7441 // insignificant, but does matter when the entity being initialized has a 7442 // class type. 7443 7444 if (!VDecl->getType()->isDependentType() && 7445 RequireCompleteType(VDecl->getLocation(), VDecl->getType(), 7446 diag::err_typecheck_decl_incomplete_type)) { 7447 VDecl->setInvalidDecl(); 7448 return; 7449 } 7450 7451 // The variable can not have an abstract class type. 7452 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 7453 diag::err_abstract_type_in_decl, 7454 AbstractVariableType)) 7455 VDecl->setInvalidDecl(); 7456 7457 const VarDecl *Def; 7458 if ((Def = VDecl->getDefinition()) && Def != VDecl) { 7459 Diag(VDecl->getLocation(), diag::err_redefinition) 7460 << VDecl->getDeclName(); 7461 Diag(Def->getLocation(), diag::note_previous_definition); 7462 VDecl->setInvalidDecl(); 7463 return; 7464 } 7465 7466 // C++ [class.static.data]p4 7467 // If a static data member is of const integral or const 7468 // enumeration type, its declaration in the class definition can 7469 // specify a constant-initializer which shall be an integral 7470 // constant expression (5.19). In that case, the member can appear 7471 // in integral constant expressions. The member shall still be 7472 // defined in a namespace scope if it is used in the program and the 7473 // namespace scope definition shall not contain an initializer. 7474 // 7475 // We already performed a redefinition check above, but for static 7476 // data members we also need to check whether there was an in-class 7477 // declaration with an initializer. 7478 const VarDecl* PrevInit = 0; 7479 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) { 7480 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName(); 7481 Diag(PrevInit->getLocation(), diag::note_previous_definition); 7482 return; 7483 } 7484 7485 bool IsDependent = false; 7486 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) { 7487 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) { 7488 VDecl->setInvalidDecl(); 7489 return; 7490 } 7491 7492 if (Exprs.get()[I]->isTypeDependent()) 7493 IsDependent = true; 7494 } 7495 7496 // If either the declaration has a dependent type or if any of the 7497 // expressions is type-dependent, we represent the initialization 7498 // via a ParenListExpr for later use during template instantiation. 7499 if (VDecl->getType()->isDependentType() || IsDependent) { 7500 // Let clients know that initialization was done with a direct initializer. 7501 VDecl->setCXXDirectInitializer(true); 7502 7503 // Store the initialization expressions as a ParenListExpr. 7504 unsigned NumExprs = Exprs.size(); 7505 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc, 7506 (Expr **)Exprs.release(), 7507 NumExprs, RParenLoc)); 7508 return; 7509 } 7510 7511 // Capture the variable that is being initialized and the style of 7512 // initialization. 7513 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 7514 7515 // FIXME: Poor source location information. 7516 InitializationKind Kind 7517 = InitializationKind::CreateDirect(VDecl->getLocation(), 7518 LParenLoc, RParenLoc); 7519 7520 InitializationSequence InitSeq(*this, Entity, Kind, 7521 Exprs.get(), Exprs.size()); 7522 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs)); 7523 if (Result.isInvalid()) { 7524 VDecl->setInvalidDecl(); 7525 return; 7526 } 7527 7528 CheckImplicitConversions(Result.get(), LParenLoc); 7529 7530 Result = MaybeCreateExprWithCleanups(Result); 7531 VDecl->setInit(Result.takeAs<Expr>()); 7532 VDecl->setCXXDirectInitializer(true); 7533 7534 CheckCompleteVariableDeclaration(VDecl); 7535} 7536 7537/// \brief Given a constructor and the set of arguments provided for the 7538/// constructor, convert the arguments and add any required default arguments 7539/// to form a proper call to this constructor. 7540/// 7541/// \returns true if an error occurred, false otherwise. 7542bool 7543Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 7544 MultiExprArg ArgsPtr, 7545 SourceLocation Loc, 7546 ASTOwningVector<Expr*> &ConvertedArgs) { 7547 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 7548 unsigned NumArgs = ArgsPtr.size(); 7549 Expr **Args = (Expr **)ArgsPtr.get(); 7550 7551 const FunctionProtoType *Proto 7552 = Constructor->getType()->getAs<FunctionProtoType>(); 7553 assert(Proto && "Constructor without a prototype?"); 7554 unsigned NumArgsInProto = Proto->getNumArgs(); 7555 7556 // If too few arguments are available, we'll fill in the rest with defaults. 7557 if (NumArgs < NumArgsInProto) 7558 ConvertedArgs.reserve(NumArgsInProto); 7559 else 7560 ConvertedArgs.reserve(NumArgs); 7561 7562 VariadicCallType CallType = 7563 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 7564 llvm::SmallVector<Expr *, 8> AllArgs; 7565 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 7566 Proto, 0, Args, NumArgs, AllArgs, 7567 CallType); 7568 for (unsigned i =0, size = AllArgs.size(); i < size; i++) 7569 ConvertedArgs.push_back(AllArgs[i]); 7570 return Invalid; 7571} 7572 7573static inline bool 7574CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 7575 const FunctionDecl *FnDecl) { 7576 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 7577 if (isa<NamespaceDecl>(DC)) { 7578 return SemaRef.Diag(FnDecl->getLocation(), 7579 diag::err_operator_new_delete_declared_in_namespace) 7580 << FnDecl->getDeclName(); 7581 } 7582 7583 if (isa<TranslationUnitDecl>(DC) && 7584 FnDecl->getStorageClass() == SC_Static) { 7585 return SemaRef.Diag(FnDecl->getLocation(), 7586 diag::err_operator_new_delete_declared_static) 7587 << FnDecl->getDeclName(); 7588 } 7589 7590 return false; 7591} 7592 7593static inline bool 7594CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 7595 CanQualType ExpectedResultType, 7596 CanQualType ExpectedFirstParamType, 7597 unsigned DependentParamTypeDiag, 7598 unsigned InvalidParamTypeDiag) { 7599 QualType ResultType = 7600 FnDecl->getType()->getAs<FunctionType>()->getResultType(); 7601 7602 // Check that the result type is not dependent. 7603 if (ResultType->isDependentType()) 7604 return SemaRef.Diag(FnDecl->getLocation(), 7605 diag::err_operator_new_delete_dependent_result_type) 7606 << FnDecl->getDeclName() << ExpectedResultType; 7607 7608 // Check that the result type is what we expect. 7609 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 7610 return SemaRef.Diag(FnDecl->getLocation(), 7611 diag::err_operator_new_delete_invalid_result_type) 7612 << FnDecl->getDeclName() << ExpectedResultType; 7613 7614 // A function template must have at least 2 parameters. 7615 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 7616 return SemaRef.Diag(FnDecl->getLocation(), 7617 diag::err_operator_new_delete_template_too_few_parameters) 7618 << FnDecl->getDeclName(); 7619 7620 // The function decl must have at least 1 parameter. 7621 if (FnDecl->getNumParams() == 0) 7622 return SemaRef.Diag(FnDecl->getLocation(), 7623 diag::err_operator_new_delete_too_few_parameters) 7624 << FnDecl->getDeclName(); 7625 7626 // Check the the first parameter type is not dependent. 7627 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 7628 if (FirstParamType->isDependentType()) 7629 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 7630 << FnDecl->getDeclName() << ExpectedFirstParamType; 7631 7632 // Check that the first parameter type is what we expect. 7633 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 7634 ExpectedFirstParamType) 7635 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 7636 << FnDecl->getDeclName() << ExpectedFirstParamType; 7637 7638 return false; 7639} 7640 7641static bool 7642CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 7643 // C++ [basic.stc.dynamic.allocation]p1: 7644 // A program is ill-formed if an allocation function is declared in a 7645 // namespace scope other than global scope or declared static in global 7646 // scope. 7647 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 7648 return true; 7649 7650 CanQualType SizeTy = 7651 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 7652 7653 // C++ [basic.stc.dynamic.allocation]p1: 7654 // The return type shall be void*. The first parameter shall have type 7655 // std::size_t. 7656 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 7657 SizeTy, 7658 diag::err_operator_new_dependent_param_type, 7659 diag::err_operator_new_param_type)) 7660 return true; 7661 7662 // C++ [basic.stc.dynamic.allocation]p1: 7663 // The first parameter shall not have an associated default argument. 7664 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 7665 return SemaRef.Diag(FnDecl->getLocation(), 7666 diag::err_operator_new_default_arg) 7667 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 7668 7669 return false; 7670} 7671 7672static bool 7673CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 7674 // C++ [basic.stc.dynamic.deallocation]p1: 7675 // A program is ill-formed if deallocation functions are declared in a 7676 // namespace scope other than global scope or declared static in global 7677 // scope. 7678 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 7679 return true; 7680 7681 // C++ [basic.stc.dynamic.deallocation]p2: 7682 // Each deallocation function shall return void and its first parameter 7683 // shall be void*. 7684 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 7685 SemaRef.Context.VoidPtrTy, 7686 diag::err_operator_delete_dependent_param_type, 7687 diag::err_operator_delete_param_type)) 7688 return true; 7689 7690 return false; 7691} 7692 7693/// CheckOverloadedOperatorDeclaration - Check whether the declaration 7694/// of this overloaded operator is well-formed. If so, returns false; 7695/// otherwise, emits appropriate diagnostics and returns true. 7696bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 7697 assert(FnDecl && FnDecl->isOverloadedOperator() && 7698 "Expected an overloaded operator declaration"); 7699 7700 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 7701 7702 // C++ [over.oper]p5: 7703 // The allocation and deallocation functions, operator new, 7704 // operator new[], operator delete and operator delete[], are 7705 // described completely in 3.7.3. The attributes and restrictions 7706 // found in the rest of this subclause do not apply to them unless 7707 // explicitly stated in 3.7.3. 7708 if (Op == OO_Delete || Op == OO_Array_Delete) 7709 return CheckOperatorDeleteDeclaration(*this, FnDecl); 7710 7711 if (Op == OO_New || Op == OO_Array_New) 7712 return CheckOperatorNewDeclaration(*this, FnDecl); 7713 7714 // C++ [over.oper]p6: 7715 // An operator function shall either be a non-static member 7716 // function or be a non-member function and have at least one 7717 // parameter whose type is a class, a reference to a class, an 7718 // enumeration, or a reference to an enumeration. 7719 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 7720 if (MethodDecl->isStatic()) 7721 return Diag(FnDecl->getLocation(), 7722 diag::err_operator_overload_static) << FnDecl->getDeclName(); 7723 } else { 7724 bool ClassOrEnumParam = false; 7725 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 7726 ParamEnd = FnDecl->param_end(); 7727 Param != ParamEnd; ++Param) { 7728 QualType ParamType = (*Param)->getType().getNonReferenceType(); 7729 if (ParamType->isDependentType() || ParamType->isRecordType() || 7730 ParamType->isEnumeralType()) { 7731 ClassOrEnumParam = true; 7732 break; 7733 } 7734 } 7735 7736 if (!ClassOrEnumParam) 7737 return Diag(FnDecl->getLocation(), 7738 diag::err_operator_overload_needs_class_or_enum) 7739 << FnDecl->getDeclName(); 7740 } 7741 7742 // C++ [over.oper]p8: 7743 // An operator function cannot have default arguments (8.3.6), 7744 // except where explicitly stated below. 7745 // 7746 // Only the function-call operator allows default arguments 7747 // (C++ [over.call]p1). 7748 if (Op != OO_Call) { 7749 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(); 7750 Param != FnDecl->param_end(); ++Param) { 7751 if ((*Param)->hasDefaultArg()) 7752 return Diag((*Param)->getLocation(), 7753 diag::err_operator_overload_default_arg) 7754 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange(); 7755 } 7756 } 7757 7758 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 7759 { false, false, false } 7760#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 7761 , { Unary, Binary, MemberOnly } 7762#include "clang/Basic/OperatorKinds.def" 7763 }; 7764 7765 bool CanBeUnaryOperator = OperatorUses[Op][0]; 7766 bool CanBeBinaryOperator = OperatorUses[Op][1]; 7767 bool MustBeMemberOperator = OperatorUses[Op][2]; 7768 7769 // C++ [over.oper]p8: 7770 // [...] Operator functions cannot have more or fewer parameters 7771 // than the number required for the corresponding operator, as 7772 // described in the rest of this subclause. 7773 unsigned NumParams = FnDecl->getNumParams() 7774 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 7775 if (Op != OO_Call && 7776 ((NumParams == 1 && !CanBeUnaryOperator) || 7777 (NumParams == 2 && !CanBeBinaryOperator) || 7778 (NumParams < 1) || (NumParams > 2))) { 7779 // We have the wrong number of parameters. 7780 unsigned ErrorKind; 7781 if (CanBeUnaryOperator && CanBeBinaryOperator) { 7782 ErrorKind = 2; // 2 -> unary or binary. 7783 } else if (CanBeUnaryOperator) { 7784 ErrorKind = 0; // 0 -> unary 7785 } else { 7786 assert(CanBeBinaryOperator && 7787 "All non-call overloaded operators are unary or binary!"); 7788 ErrorKind = 1; // 1 -> binary 7789 } 7790 7791 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 7792 << FnDecl->getDeclName() << NumParams << ErrorKind; 7793 } 7794 7795 // Overloaded operators other than operator() cannot be variadic. 7796 if (Op != OO_Call && 7797 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 7798 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 7799 << FnDecl->getDeclName(); 7800 } 7801 7802 // Some operators must be non-static member functions. 7803 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 7804 return Diag(FnDecl->getLocation(), 7805 diag::err_operator_overload_must_be_member) 7806 << FnDecl->getDeclName(); 7807 } 7808 7809 // C++ [over.inc]p1: 7810 // The user-defined function called operator++ implements the 7811 // prefix and postfix ++ operator. If this function is a member 7812 // function with no parameters, or a non-member function with one 7813 // parameter of class or enumeration type, it defines the prefix 7814 // increment operator ++ for objects of that type. If the function 7815 // is a member function with one parameter (which shall be of type 7816 // int) or a non-member function with two parameters (the second 7817 // of which shall be of type int), it defines the postfix 7818 // increment operator ++ for objects of that type. 7819 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 7820 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 7821 bool ParamIsInt = false; 7822 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>()) 7823 ParamIsInt = BT->getKind() == BuiltinType::Int; 7824 7825 if (!ParamIsInt) 7826 return Diag(LastParam->getLocation(), 7827 diag::err_operator_overload_post_incdec_must_be_int) 7828 << LastParam->getType() << (Op == OO_MinusMinus); 7829 } 7830 7831 return false; 7832} 7833 7834/// CheckLiteralOperatorDeclaration - Check whether the declaration 7835/// of this literal operator function is well-formed. If so, returns 7836/// false; otherwise, emits appropriate diagnostics and returns true. 7837bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 7838 DeclContext *DC = FnDecl->getDeclContext(); 7839 Decl::Kind Kind = DC->getDeclKind(); 7840 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace && 7841 Kind != Decl::LinkageSpec) { 7842 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 7843 << FnDecl->getDeclName(); 7844 return true; 7845 } 7846 7847 bool Valid = false; 7848 7849 // template <char...> type operator "" name() is the only valid template 7850 // signature, and the only valid signature with no parameters. 7851 if (FnDecl->param_size() == 0) { 7852 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) { 7853 // Must have only one template parameter 7854 TemplateParameterList *Params = TpDecl->getTemplateParameters(); 7855 if (Params->size() == 1) { 7856 NonTypeTemplateParmDecl *PmDecl = 7857 cast<NonTypeTemplateParmDecl>(Params->getParam(0)); 7858 7859 // The template parameter must be a char parameter pack. 7860 if (PmDecl && PmDecl->isTemplateParameterPack() && 7861 Context.hasSameType(PmDecl->getType(), Context.CharTy)) 7862 Valid = true; 7863 } 7864 } 7865 } else { 7866 // Check the first parameter 7867 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 7868 7869 QualType T = (*Param)->getType(); 7870 7871 // unsigned long long int, long double, and any character type are allowed 7872 // as the only parameters. 7873 if (Context.hasSameType(T, Context.UnsignedLongLongTy) || 7874 Context.hasSameType(T, Context.LongDoubleTy) || 7875 Context.hasSameType(T, Context.CharTy) || 7876 Context.hasSameType(T, Context.WCharTy) || 7877 Context.hasSameType(T, Context.Char16Ty) || 7878 Context.hasSameType(T, Context.Char32Ty)) { 7879 if (++Param == FnDecl->param_end()) 7880 Valid = true; 7881 goto FinishedParams; 7882 } 7883 7884 // Otherwise it must be a pointer to const; let's strip those qualifiers. 7885 const PointerType *PT = T->getAs<PointerType>(); 7886 if (!PT) 7887 goto FinishedParams; 7888 T = PT->getPointeeType(); 7889 if (!T.isConstQualified()) 7890 goto FinishedParams; 7891 T = T.getUnqualifiedType(); 7892 7893 // Move on to the second parameter; 7894 ++Param; 7895 7896 // If there is no second parameter, the first must be a const char * 7897 if (Param == FnDecl->param_end()) { 7898 if (Context.hasSameType(T, Context.CharTy)) 7899 Valid = true; 7900 goto FinishedParams; 7901 } 7902 7903 // const char *, const wchar_t*, const char16_t*, and const char32_t* 7904 // are allowed as the first parameter to a two-parameter function 7905 if (!(Context.hasSameType(T, Context.CharTy) || 7906 Context.hasSameType(T, Context.WCharTy) || 7907 Context.hasSameType(T, Context.Char16Ty) || 7908 Context.hasSameType(T, Context.Char32Ty))) 7909 goto FinishedParams; 7910 7911 // The second and final parameter must be an std::size_t 7912 T = (*Param)->getType().getUnqualifiedType(); 7913 if (Context.hasSameType(T, Context.getSizeType()) && 7914 ++Param == FnDecl->param_end()) 7915 Valid = true; 7916 } 7917 7918 // FIXME: This diagnostic is absolutely terrible. 7919FinishedParams: 7920 if (!Valid) { 7921 Diag(FnDecl->getLocation(), diag::err_literal_operator_params) 7922 << FnDecl->getDeclName(); 7923 return true; 7924 } 7925 7926 return false; 7927} 7928 7929/// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 7930/// linkage specification, including the language and (if present) 7931/// the '{'. ExternLoc is the location of the 'extern', LangLoc is 7932/// the location of the language string literal, which is provided 7933/// by Lang/StrSize. LBraceLoc, if valid, provides the location of 7934/// the '{' brace. Otherwise, this linkage specification does not 7935/// have any braces. 7936Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 7937 SourceLocation LangLoc, 7938 llvm::StringRef Lang, 7939 SourceLocation LBraceLoc) { 7940 LinkageSpecDecl::LanguageIDs Language; 7941 if (Lang == "\"C\"") 7942 Language = LinkageSpecDecl::lang_c; 7943 else if (Lang == "\"C++\"") 7944 Language = LinkageSpecDecl::lang_cxx; 7945 else { 7946 Diag(LangLoc, diag::err_bad_language); 7947 return 0; 7948 } 7949 7950 // FIXME: Add all the various semantics of linkage specifications 7951 7952 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, 7953 ExternLoc, LangLoc, Language); 7954 CurContext->addDecl(D); 7955 PushDeclContext(S, D); 7956 return D; 7957} 7958 7959/// ActOnFinishLinkageSpecification - Complete the definition of 7960/// the C++ linkage specification LinkageSpec. If RBraceLoc is 7961/// valid, it's the position of the closing '}' brace in a linkage 7962/// specification that uses braces. 7963Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 7964 Decl *LinkageSpec, 7965 SourceLocation RBraceLoc) { 7966 if (LinkageSpec) { 7967 if (RBraceLoc.isValid()) { 7968 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 7969 LSDecl->setRBraceLoc(RBraceLoc); 7970 } 7971 PopDeclContext(); 7972 } 7973 return LinkageSpec; 7974} 7975 7976/// \brief Perform semantic analysis for the variable declaration that 7977/// occurs within a C++ catch clause, returning the newly-created 7978/// variable. 7979VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 7980 TypeSourceInfo *TInfo, 7981 SourceLocation StartLoc, 7982 SourceLocation Loc, 7983 IdentifierInfo *Name) { 7984 bool Invalid = false; 7985 QualType ExDeclType = TInfo->getType(); 7986 7987 // Arrays and functions decay. 7988 if (ExDeclType->isArrayType()) 7989 ExDeclType = Context.getArrayDecayedType(ExDeclType); 7990 else if (ExDeclType->isFunctionType()) 7991 ExDeclType = Context.getPointerType(ExDeclType); 7992 7993 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 7994 // The exception-declaration shall not denote a pointer or reference to an 7995 // incomplete type, other than [cv] void*. 7996 // N2844 forbids rvalue references. 7997 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 7998 Diag(Loc, diag::err_catch_rvalue_ref); 7999 Invalid = true; 8000 } 8001 8002 // GCC allows catching pointers and references to incomplete types 8003 // as an extension; so do we, but we warn by default. 8004 8005 QualType BaseType = ExDeclType; 8006 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 8007 unsigned DK = diag::err_catch_incomplete; 8008 bool IncompleteCatchIsInvalid = true; 8009 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 8010 BaseType = Ptr->getPointeeType(); 8011 Mode = 1; 8012 DK = diag::ext_catch_incomplete_ptr; 8013 IncompleteCatchIsInvalid = false; 8014 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 8015 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 8016 BaseType = Ref->getPointeeType(); 8017 Mode = 2; 8018 DK = diag::ext_catch_incomplete_ref; 8019 IncompleteCatchIsInvalid = false; 8020 } 8021 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 8022 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) && 8023 IncompleteCatchIsInvalid) 8024 Invalid = true; 8025 8026 if (!Invalid && !ExDeclType->isDependentType() && 8027 RequireNonAbstractType(Loc, ExDeclType, 8028 diag::err_abstract_type_in_decl, 8029 AbstractVariableType)) 8030 Invalid = true; 8031 8032 // Only the non-fragile NeXT runtime currently supports C++ catches 8033 // of ObjC types, and no runtime supports catching ObjC types by value. 8034 if (!Invalid && getLangOptions().ObjC1) { 8035 QualType T = ExDeclType; 8036 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 8037 T = RT->getPointeeType(); 8038 8039 if (T->isObjCObjectType()) { 8040 Diag(Loc, diag::err_objc_object_catch); 8041 Invalid = true; 8042 } else if (T->isObjCObjectPointerType()) { 8043 if (!getLangOptions().ObjCNonFragileABI) { 8044 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile); 8045 Invalid = true; 8046 } 8047 } 8048 } 8049 8050 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 8051 ExDeclType, TInfo, SC_None, SC_None); 8052 ExDecl->setExceptionVariable(true); 8053 8054 if (!Invalid) { 8055 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 8056 // C++ [except.handle]p16: 8057 // The object declared in an exception-declaration or, if the 8058 // exception-declaration does not specify a name, a temporary (12.2) is 8059 // copy-initialized (8.5) from the exception object. [...] 8060 // The object is destroyed when the handler exits, after the destruction 8061 // of any automatic objects initialized within the handler. 8062 // 8063 // We just pretend to initialize the object with itself, then make sure 8064 // it can be destroyed later. 8065 QualType initType = ExDeclType; 8066 8067 InitializedEntity entity = 8068 InitializedEntity::InitializeVariable(ExDecl); 8069 InitializationKind initKind = 8070 InitializationKind::CreateCopy(Loc, SourceLocation()); 8071 8072 Expr *opaqueValue = 8073 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 8074 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1); 8075 ExprResult result = sequence.Perform(*this, entity, initKind, 8076 MultiExprArg(&opaqueValue, 1)); 8077 if (result.isInvalid()) 8078 Invalid = true; 8079 else { 8080 // If the constructor used was non-trivial, set this as the 8081 // "initializer". 8082 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take()); 8083 if (!construct->getConstructor()->isTrivial()) { 8084 Expr *init = MaybeCreateExprWithCleanups(construct); 8085 ExDecl->setInit(init); 8086 } 8087 8088 // And make sure it's destructable. 8089 FinalizeVarWithDestructor(ExDecl, recordType); 8090 } 8091 } 8092 } 8093 8094 if (Invalid) 8095 ExDecl->setInvalidDecl(); 8096 8097 return ExDecl; 8098} 8099 8100/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 8101/// handler. 8102Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 8103 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 8104 bool Invalid = D.isInvalidType(); 8105 8106 // Check for unexpanded parameter packs. 8107 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 8108 UPPC_ExceptionType)) { 8109 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 8110 D.getIdentifierLoc()); 8111 Invalid = true; 8112 } 8113 8114 IdentifierInfo *II = D.getIdentifier(); 8115 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 8116 LookupOrdinaryName, 8117 ForRedeclaration)) { 8118 // The scope should be freshly made just for us. There is just no way 8119 // it contains any previous declaration. 8120 assert(!S->isDeclScope(PrevDecl)); 8121 if (PrevDecl->isTemplateParameter()) { 8122 // Maybe we will complain about the shadowed template parameter. 8123 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 8124 } 8125 } 8126 8127 if (D.getCXXScopeSpec().isSet() && !Invalid) { 8128 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 8129 << D.getCXXScopeSpec().getRange(); 8130 Invalid = true; 8131 } 8132 8133 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 8134 D.getSourceRange().getBegin(), 8135 D.getIdentifierLoc(), 8136 D.getIdentifier()); 8137 if (Invalid) 8138 ExDecl->setInvalidDecl(); 8139 8140 // Add the exception declaration into this scope. 8141 if (II) 8142 PushOnScopeChains(ExDecl, S); 8143 else 8144 CurContext->addDecl(ExDecl); 8145 8146 ProcessDeclAttributes(S, ExDecl, D); 8147 return ExDecl; 8148} 8149 8150Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 8151 Expr *AssertExpr, 8152 Expr *AssertMessageExpr_, 8153 SourceLocation RParenLoc) { 8154 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_); 8155 8156 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) { 8157 llvm::APSInt Value(32); 8158 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) { 8159 Diag(StaticAssertLoc, 8160 diag::err_static_assert_expression_is_not_constant) << 8161 AssertExpr->getSourceRange(); 8162 return 0; 8163 } 8164 8165 if (Value == 0) { 8166 Diag(StaticAssertLoc, diag::err_static_assert_failed) 8167 << AssertMessage->getString() << AssertExpr->getSourceRange(); 8168 } 8169 } 8170 8171 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 8172 return 0; 8173 8174 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 8175 AssertExpr, AssertMessage, RParenLoc); 8176 8177 CurContext->addDecl(Decl); 8178 return Decl; 8179} 8180 8181/// \brief Perform semantic analysis of the given friend type declaration. 8182/// 8183/// \returns A friend declaration that. 8184FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc, 8185 TypeSourceInfo *TSInfo) { 8186 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 8187 8188 QualType T = TSInfo->getType(); 8189 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 8190 8191 if (!getLangOptions().CPlusPlus0x) { 8192 // C++03 [class.friend]p2: 8193 // An elaborated-type-specifier shall be used in a friend declaration 8194 // for a class.* 8195 // 8196 // * The class-key of the elaborated-type-specifier is required. 8197 if (!ActiveTemplateInstantiations.empty()) { 8198 // Do not complain about the form of friend template types during 8199 // template instantiation; we will already have complained when the 8200 // template was declared. 8201 } else if (!T->isElaboratedTypeSpecifier()) { 8202 // If we evaluated the type to a record type, suggest putting 8203 // a tag in front. 8204 if (const RecordType *RT = T->getAs<RecordType>()) { 8205 RecordDecl *RD = RT->getDecl(); 8206 8207 std::string InsertionText = std::string(" ") + RD->getKindName(); 8208 8209 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type) 8210 << (unsigned) RD->getTagKind() 8211 << T 8212 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc), 8213 InsertionText); 8214 } else { 8215 Diag(FriendLoc, diag::ext_nonclass_type_friend) 8216 << T 8217 << SourceRange(FriendLoc, TypeRange.getEnd()); 8218 } 8219 } else if (T->getAs<EnumType>()) { 8220 Diag(FriendLoc, diag::ext_enum_friend) 8221 << T 8222 << SourceRange(FriendLoc, TypeRange.getEnd()); 8223 } 8224 } 8225 8226 // C++0x [class.friend]p3: 8227 // If the type specifier in a friend declaration designates a (possibly 8228 // cv-qualified) class type, that class is declared as a friend; otherwise, 8229 // the friend declaration is ignored. 8230 8231 // FIXME: C++0x has some syntactic restrictions on friend type declarations 8232 // in [class.friend]p3 that we do not implement. 8233 8234 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc); 8235} 8236 8237/// Handle a friend tag declaration where the scope specifier was 8238/// templated. 8239Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 8240 unsigned TagSpec, SourceLocation TagLoc, 8241 CXXScopeSpec &SS, 8242 IdentifierInfo *Name, SourceLocation NameLoc, 8243 AttributeList *Attr, 8244 MultiTemplateParamsArg TempParamLists) { 8245 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 8246 8247 bool isExplicitSpecialization = false; 8248 bool Invalid = false; 8249 8250 if (TemplateParameterList *TemplateParams 8251 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS, 8252 TempParamLists.get(), 8253 TempParamLists.size(), 8254 /*friend*/ true, 8255 isExplicitSpecialization, 8256 Invalid)) { 8257 if (TemplateParams->size() > 0) { 8258 // This is a declaration of a class template. 8259 if (Invalid) 8260 return 0; 8261 8262 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, 8263 SS, Name, NameLoc, Attr, 8264 TemplateParams, AS_public, 8265 TempParamLists.size() - 1, 8266 (TemplateParameterList**) TempParamLists.release()).take(); 8267 } else { 8268 // The "template<>" header is extraneous. 8269 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 8270 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 8271 isExplicitSpecialization = true; 8272 } 8273 } 8274 8275 if (Invalid) return 0; 8276 8277 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 8278 8279 bool isAllExplicitSpecializations = true; 8280 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 8281 if (TempParamLists.get()[I]->size()) { 8282 isAllExplicitSpecializations = false; 8283 break; 8284 } 8285 } 8286 8287 // FIXME: don't ignore attributes. 8288 8289 // If it's explicit specializations all the way down, just forget 8290 // about the template header and build an appropriate non-templated 8291 // friend. TODO: for source fidelity, remember the headers. 8292 if (isAllExplicitSpecializations) { 8293 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 8294 ElaboratedTypeKeyword Keyword 8295 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 8296 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 8297 *Name, NameLoc); 8298 if (T.isNull()) 8299 return 0; 8300 8301 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 8302 if (isa<DependentNameType>(T)) { 8303 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc()); 8304 TL.setKeywordLoc(TagLoc); 8305 TL.setQualifierLoc(QualifierLoc); 8306 TL.setNameLoc(NameLoc); 8307 } else { 8308 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc()); 8309 TL.setKeywordLoc(TagLoc); 8310 TL.setQualifierLoc(QualifierLoc); 8311 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc); 8312 } 8313 8314 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 8315 TSI, FriendLoc); 8316 Friend->setAccess(AS_public); 8317 CurContext->addDecl(Friend); 8318 return Friend; 8319 } 8320 8321 // Handle the case of a templated-scope friend class. e.g. 8322 // template <class T> class A<T>::B; 8323 // FIXME: we don't support these right now. 8324 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 8325 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 8326 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 8327 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc()); 8328 TL.setKeywordLoc(TagLoc); 8329 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 8330 TL.setNameLoc(NameLoc); 8331 8332 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 8333 TSI, FriendLoc); 8334 Friend->setAccess(AS_public); 8335 Friend->setUnsupportedFriend(true); 8336 CurContext->addDecl(Friend); 8337 return Friend; 8338} 8339 8340 8341/// Handle a friend type declaration. This works in tandem with 8342/// ActOnTag. 8343/// 8344/// Notes on friend class templates: 8345/// 8346/// We generally treat friend class declarations as if they were 8347/// declaring a class. So, for example, the elaborated type specifier 8348/// in a friend declaration is required to obey the restrictions of a 8349/// class-head (i.e. no typedefs in the scope chain), template 8350/// parameters are required to match up with simple template-ids, &c. 8351/// However, unlike when declaring a template specialization, it's 8352/// okay to refer to a template specialization without an empty 8353/// template parameter declaration, e.g. 8354/// friend class A<T>::B<unsigned>; 8355/// We permit this as a special case; if there are any template 8356/// parameters present at all, require proper matching, i.e. 8357/// template <> template <class T> friend class A<int>::B; 8358Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 8359 MultiTemplateParamsArg TempParams) { 8360 SourceLocation Loc = DS.getSourceRange().getBegin(); 8361 8362 assert(DS.isFriendSpecified()); 8363 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 8364 8365 // Try to convert the decl specifier to a type. This works for 8366 // friend templates because ActOnTag never produces a ClassTemplateDecl 8367 // for a TUK_Friend. 8368 Declarator TheDeclarator(DS, Declarator::MemberContext); 8369 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 8370 QualType T = TSI->getType(); 8371 if (TheDeclarator.isInvalidType()) 8372 return 0; 8373 8374 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 8375 return 0; 8376 8377 // This is definitely an error in C++98. It's probably meant to 8378 // be forbidden in C++0x, too, but the specification is just 8379 // poorly written. 8380 // 8381 // The problem is with declarations like the following: 8382 // template <T> friend A<T>::foo; 8383 // where deciding whether a class C is a friend or not now hinges 8384 // on whether there exists an instantiation of A that causes 8385 // 'foo' to equal C. There are restrictions on class-heads 8386 // (which we declare (by fiat) elaborated friend declarations to 8387 // be) that makes this tractable. 8388 // 8389 // FIXME: handle "template <> friend class A<T>;", which 8390 // is possibly well-formed? Who even knows? 8391 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 8392 Diag(Loc, diag::err_tagless_friend_type_template) 8393 << DS.getSourceRange(); 8394 return 0; 8395 } 8396 8397 // C++98 [class.friend]p1: A friend of a class is a function 8398 // or class that is not a member of the class . . . 8399 // This is fixed in DR77, which just barely didn't make the C++03 8400 // deadline. It's also a very silly restriction that seriously 8401 // affects inner classes and which nobody else seems to implement; 8402 // thus we never diagnose it, not even in -pedantic. 8403 // 8404 // But note that we could warn about it: it's always useless to 8405 // friend one of your own members (it's not, however, worthless to 8406 // friend a member of an arbitrary specialization of your template). 8407 8408 Decl *D; 8409 if (unsigned NumTempParamLists = TempParams.size()) 8410 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 8411 NumTempParamLists, 8412 TempParams.release(), 8413 TSI, 8414 DS.getFriendSpecLoc()); 8415 else 8416 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI); 8417 8418 if (!D) 8419 return 0; 8420 8421 D->setAccess(AS_public); 8422 CurContext->addDecl(D); 8423 8424 return D; 8425} 8426 8427Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition, 8428 MultiTemplateParamsArg TemplateParams) { 8429 const DeclSpec &DS = D.getDeclSpec(); 8430 8431 assert(DS.isFriendSpecified()); 8432 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 8433 8434 SourceLocation Loc = D.getIdentifierLoc(); 8435 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 8436 QualType T = TInfo->getType(); 8437 8438 // C++ [class.friend]p1 8439 // A friend of a class is a function or class.... 8440 // Note that this sees through typedefs, which is intended. 8441 // It *doesn't* see through dependent types, which is correct 8442 // according to [temp.arg.type]p3: 8443 // If a declaration acquires a function type through a 8444 // type dependent on a template-parameter and this causes 8445 // a declaration that does not use the syntactic form of a 8446 // function declarator to have a function type, the program 8447 // is ill-formed. 8448 if (!T->isFunctionType()) { 8449 Diag(Loc, diag::err_unexpected_friend); 8450 8451 // It might be worthwhile to try to recover by creating an 8452 // appropriate declaration. 8453 return 0; 8454 } 8455 8456 // C++ [namespace.memdef]p3 8457 // - If a friend declaration in a non-local class first declares a 8458 // class or function, the friend class or function is a member 8459 // of the innermost enclosing namespace. 8460 // - The name of the friend is not found by simple name lookup 8461 // until a matching declaration is provided in that namespace 8462 // scope (either before or after the class declaration granting 8463 // friendship). 8464 // - If a friend function is called, its name may be found by the 8465 // name lookup that considers functions from namespaces and 8466 // classes associated with the types of the function arguments. 8467 // - When looking for a prior declaration of a class or a function 8468 // declared as a friend, scopes outside the innermost enclosing 8469 // namespace scope are not considered. 8470 8471 CXXScopeSpec &SS = D.getCXXScopeSpec(); 8472 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 8473 DeclarationName Name = NameInfo.getName(); 8474 assert(Name); 8475 8476 // Check for unexpanded parameter packs. 8477 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 8478 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 8479 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 8480 return 0; 8481 8482 // The context we found the declaration in, or in which we should 8483 // create the declaration. 8484 DeclContext *DC; 8485 Scope *DCScope = S; 8486 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 8487 ForRedeclaration); 8488 8489 // FIXME: there are different rules in local classes 8490 8491 // There are four cases here. 8492 // - There's no scope specifier, in which case we just go to the 8493 // appropriate scope and look for a function or function template 8494 // there as appropriate. 8495 // Recover from invalid scope qualifiers as if they just weren't there. 8496 if (SS.isInvalid() || !SS.isSet()) { 8497 // C++0x [namespace.memdef]p3: 8498 // If the name in a friend declaration is neither qualified nor 8499 // a template-id and the declaration is a function or an 8500 // elaborated-type-specifier, the lookup to determine whether 8501 // the entity has been previously declared shall not consider 8502 // any scopes outside the innermost enclosing namespace. 8503 // C++0x [class.friend]p11: 8504 // If a friend declaration appears in a local class and the name 8505 // specified is an unqualified name, a prior declaration is 8506 // looked up without considering scopes that are outside the 8507 // innermost enclosing non-class scope. For a friend function 8508 // declaration, if there is no prior declaration, the program is 8509 // ill-formed. 8510 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass(); 8511 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 8512 8513 // Find the appropriate context according to the above. 8514 DC = CurContext; 8515 while (true) { 8516 // Skip class contexts. If someone can cite chapter and verse 8517 // for this behavior, that would be nice --- it's what GCC and 8518 // EDG do, and it seems like a reasonable intent, but the spec 8519 // really only says that checks for unqualified existing 8520 // declarations should stop at the nearest enclosing namespace, 8521 // not that they should only consider the nearest enclosing 8522 // namespace. 8523 while (DC->isRecord()) 8524 DC = DC->getParent(); 8525 8526 LookupQualifiedName(Previous, DC); 8527 8528 // TODO: decide what we think about using declarations. 8529 if (isLocal || !Previous.empty()) 8530 break; 8531 8532 if (isTemplateId) { 8533 if (isa<TranslationUnitDecl>(DC)) break; 8534 } else { 8535 if (DC->isFileContext()) break; 8536 } 8537 DC = DC->getParent(); 8538 } 8539 8540 // C++ [class.friend]p1: A friend of a class is a function or 8541 // class that is not a member of the class . . . 8542 // C++0x changes this for both friend types and functions. 8543 // Most C++ 98 compilers do seem to give an error here, so 8544 // we do, too. 8545 if (!Previous.empty() && DC->Equals(CurContext) 8546 && !getLangOptions().CPlusPlus0x) 8547 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member); 8548 8549 DCScope = getScopeForDeclContext(S, DC); 8550 8551 // - There's a non-dependent scope specifier, in which case we 8552 // compute it and do a previous lookup there for a function 8553 // or function template. 8554 } else if (!SS.getScopeRep()->isDependent()) { 8555 DC = computeDeclContext(SS); 8556 if (!DC) return 0; 8557 8558 if (RequireCompleteDeclContext(SS, DC)) return 0; 8559 8560 LookupQualifiedName(Previous, DC); 8561 8562 // Ignore things found implicitly in the wrong scope. 8563 // TODO: better diagnostics for this case. Suggesting the right 8564 // qualified scope would be nice... 8565 LookupResult::Filter F = Previous.makeFilter(); 8566 while (F.hasNext()) { 8567 NamedDecl *D = F.next(); 8568 if (!DC->InEnclosingNamespaceSetOf( 8569 D->getDeclContext()->getRedeclContext())) 8570 F.erase(); 8571 } 8572 F.done(); 8573 8574 if (Previous.empty()) { 8575 D.setInvalidType(); 8576 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T; 8577 return 0; 8578 } 8579 8580 // C++ [class.friend]p1: A friend of a class is a function or 8581 // class that is not a member of the class . . . 8582 if (DC->Equals(CurContext)) 8583 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member); 8584 8585 // - There's a scope specifier that does not match any template 8586 // parameter lists, in which case we use some arbitrary context, 8587 // create a method or method template, and wait for instantiation. 8588 // - There's a scope specifier that does match some template 8589 // parameter lists, which we don't handle right now. 8590 } else { 8591 DC = CurContext; 8592 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 8593 } 8594 8595 if (!DC->isRecord()) { 8596 // This implies that it has to be an operator or function. 8597 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName || 8598 D.getName().getKind() == UnqualifiedId::IK_DestructorName || 8599 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) { 8600 Diag(Loc, diag::err_introducing_special_friend) << 8601 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 : 8602 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2); 8603 return 0; 8604 } 8605 } 8606 8607 bool Redeclaration = false; 8608 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous, 8609 move(TemplateParams), 8610 IsDefinition, 8611 Redeclaration); 8612 if (!ND) return 0; 8613 8614 assert(ND->getDeclContext() == DC); 8615 assert(ND->getLexicalDeclContext() == CurContext); 8616 8617 // Add the function declaration to the appropriate lookup tables, 8618 // adjusting the redeclarations list as necessary. We don't 8619 // want to do this yet if the friending class is dependent. 8620 // 8621 // Also update the scope-based lookup if the target context's 8622 // lookup context is in lexical scope. 8623 if (!CurContext->isDependentContext()) { 8624 DC = DC->getRedeclContext(); 8625 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false); 8626 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 8627 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 8628 } 8629 8630 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 8631 D.getIdentifierLoc(), ND, 8632 DS.getFriendSpecLoc()); 8633 FrD->setAccess(AS_public); 8634 CurContext->addDecl(FrD); 8635 8636 if (ND->isInvalidDecl()) 8637 FrD->setInvalidDecl(); 8638 else { 8639 FunctionDecl *FD; 8640 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 8641 FD = FTD->getTemplatedDecl(); 8642 else 8643 FD = cast<FunctionDecl>(ND); 8644 8645 // Mark templated-scope function declarations as unsupported. 8646 if (FD->getNumTemplateParameterLists()) 8647 FrD->setUnsupportedFriend(true); 8648 } 8649 8650 return ND; 8651} 8652 8653void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 8654 AdjustDeclIfTemplate(Dcl); 8655 8656 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl); 8657 if (!Fn) { 8658 Diag(DelLoc, diag::err_deleted_non_function); 8659 return; 8660 } 8661 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) { 8662 Diag(DelLoc, diag::err_deleted_decl_not_first); 8663 Diag(Prev->getLocation(), diag::note_previous_declaration); 8664 // If the declaration wasn't the first, we delete the function anyway for 8665 // recovery. 8666 } 8667 Fn->setDeletedAsWritten(); 8668} 8669 8670void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 8671 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl); 8672 8673 if (MD) { 8674 if (MD->getParent()->isDependentType()) { 8675 MD->setDefaulted(); 8676 MD->setExplicitlyDefaulted(); 8677 return; 8678 } 8679 8680 CXXSpecialMember Member = getSpecialMember(MD); 8681 if (Member == CXXInvalid) { 8682 Diag(DefaultLoc, diag::err_default_special_members); 8683 return; 8684 } 8685 8686 MD->setDefaulted(); 8687 MD->setExplicitlyDefaulted(); 8688 8689 // If this definition appears within the record, do the checking when 8690 // the record is complete. 8691 const FunctionDecl *Primary = MD; 8692 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate) 8693 // Find the uninstantiated declaration that actually had the '= default' 8694 // on it. 8695 MD->getTemplateInstantiationPattern()->isDefined(Primary); 8696 8697 if (Primary == Primary->getCanonicalDecl()) 8698 return; 8699 8700 switch (Member) { 8701 case CXXDefaultConstructor: { 8702 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD); 8703 CheckExplicitlyDefaultedDefaultConstructor(CD); 8704 if (!CD->isInvalidDecl()) 8705 DefineImplicitDefaultConstructor(DefaultLoc, CD); 8706 break; 8707 } 8708 8709 case CXXCopyConstructor: { 8710 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD); 8711 CheckExplicitlyDefaultedCopyConstructor(CD); 8712 if (!CD->isInvalidDecl()) 8713 DefineImplicitCopyConstructor(DefaultLoc, CD); 8714 break; 8715 } 8716 8717 case CXXCopyAssignment: { 8718 CheckExplicitlyDefaultedCopyAssignment(MD); 8719 if (!MD->isInvalidDecl()) 8720 DefineImplicitCopyAssignment(DefaultLoc, MD); 8721 break; 8722 } 8723 8724 case CXXDestructor: { 8725 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD); 8726 CheckExplicitlyDefaultedDestructor(DD); 8727 if (!DD->isInvalidDecl()) 8728 DefineImplicitDestructor(DefaultLoc, DD); 8729 break; 8730 } 8731 8732 case CXXMoveConstructor: 8733 case CXXMoveAssignment: 8734 Diag(Dcl->getLocation(), diag::err_defaulted_move_unsupported); 8735 break; 8736 8737 default: 8738 // FIXME: Do the rest once we have move functions 8739 break; 8740 } 8741 } else { 8742 Diag(DefaultLoc, diag::err_default_special_members); 8743 } 8744} 8745 8746static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 8747 for (Stmt::child_range CI = S->children(); CI; ++CI) { 8748 Stmt *SubStmt = *CI; 8749 if (!SubStmt) 8750 continue; 8751 if (isa<ReturnStmt>(SubStmt)) 8752 Self.Diag(SubStmt->getSourceRange().getBegin(), 8753 diag::err_return_in_constructor_handler); 8754 if (!isa<Expr>(SubStmt)) 8755 SearchForReturnInStmt(Self, SubStmt); 8756 } 8757} 8758 8759void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 8760 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 8761 CXXCatchStmt *Handler = TryBlock->getHandler(I); 8762 SearchForReturnInStmt(*this, Handler); 8763 } 8764} 8765 8766bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 8767 const CXXMethodDecl *Old) { 8768 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType(); 8769 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType(); 8770 8771 if (Context.hasSameType(NewTy, OldTy) || 8772 NewTy->isDependentType() || OldTy->isDependentType()) 8773 return false; 8774 8775 // Check if the return types are covariant 8776 QualType NewClassTy, OldClassTy; 8777 8778 /// Both types must be pointers or references to classes. 8779 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 8780 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 8781 NewClassTy = NewPT->getPointeeType(); 8782 OldClassTy = OldPT->getPointeeType(); 8783 } 8784 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 8785 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 8786 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 8787 NewClassTy = NewRT->getPointeeType(); 8788 OldClassTy = OldRT->getPointeeType(); 8789 } 8790 } 8791 } 8792 8793 // The return types aren't either both pointers or references to a class type. 8794 if (NewClassTy.isNull()) { 8795 Diag(New->getLocation(), 8796 diag::err_different_return_type_for_overriding_virtual_function) 8797 << New->getDeclName() << NewTy << OldTy; 8798 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 8799 8800 return true; 8801 } 8802 8803 // C++ [class.virtual]p6: 8804 // If the return type of D::f differs from the return type of B::f, the 8805 // class type in the return type of D::f shall be complete at the point of 8806 // declaration of D::f or shall be the class type D. 8807 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 8808 if (!RT->isBeingDefined() && 8809 RequireCompleteType(New->getLocation(), NewClassTy, 8810 PDiag(diag::err_covariant_return_incomplete) 8811 << New->getDeclName())) 8812 return true; 8813 } 8814 8815 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 8816 // Check if the new class derives from the old class. 8817 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 8818 Diag(New->getLocation(), 8819 diag::err_covariant_return_not_derived) 8820 << New->getDeclName() << NewTy << OldTy; 8821 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 8822 return true; 8823 } 8824 8825 // Check if we the conversion from derived to base is valid. 8826 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy, 8827 diag::err_covariant_return_inaccessible_base, 8828 diag::err_covariant_return_ambiguous_derived_to_base_conv, 8829 // FIXME: Should this point to the return type? 8830 New->getLocation(), SourceRange(), New->getDeclName(), 0)) { 8831 // FIXME: this note won't trigger for delayed access control 8832 // diagnostics, and it's impossible to get an undelayed error 8833 // here from access control during the original parse because 8834 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 8835 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 8836 return true; 8837 } 8838 } 8839 8840 // The qualifiers of the return types must be the same. 8841 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 8842 Diag(New->getLocation(), 8843 diag::err_covariant_return_type_different_qualifications) 8844 << New->getDeclName() << NewTy << OldTy; 8845 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 8846 return true; 8847 }; 8848 8849 8850 // The new class type must have the same or less qualifiers as the old type. 8851 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 8852 Diag(New->getLocation(), 8853 diag::err_covariant_return_type_class_type_more_qualified) 8854 << New->getDeclName() << NewTy << OldTy; 8855 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 8856 return true; 8857 }; 8858 8859 return false; 8860} 8861 8862/// \brief Mark the given method pure. 8863/// 8864/// \param Method the method to be marked pure. 8865/// 8866/// \param InitRange the source range that covers the "0" initializer. 8867bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 8868 SourceLocation EndLoc = InitRange.getEnd(); 8869 if (EndLoc.isValid()) 8870 Method->setRangeEnd(EndLoc); 8871 8872 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 8873 Method->setPure(); 8874 return false; 8875 } 8876 8877 if (!Method->isInvalidDecl()) 8878 Diag(Method->getLocation(), diag::err_non_virtual_pure) 8879 << Method->getDeclName() << InitRange; 8880 return true; 8881} 8882 8883/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 8884/// an initializer for the out-of-line declaration 'Dcl'. The scope 8885/// is a fresh scope pushed for just this purpose. 8886/// 8887/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 8888/// static data member of class X, names should be looked up in the scope of 8889/// class X. 8890void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 8891 // If there is no declaration, there was an error parsing it. 8892 if (D == 0 || D->isInvalidDecl()) return; 8893 8894 // We should only get called for declarations with scope specifiers, like: 8895 // int foo::bar; 8896 assert(D->isOutOfLine()); 8897 EnterDeclaratorContext(S, D->getDeclContext()); 8898} 8899 8900/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 8901/// initializer for the out-of-line declaration 'D'. 8902void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 8903 // If there is no declaration, there was an error parsing it. 8904 if (D == 0 || D->isInvalidDecl()) return; 8905 8906 assert(D->isOutOfLine()); 8907 ExitDeclaratorContext(S); 8908} 8909 8910/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 8911/// C++ if/switch/while/for statement. 8912/// e.g: "if (int x = f()) {...}" 8913DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 8914 // C++ 6.4p2: 8915 // The declarator shall not specify a function or an array. 8916 // The type-specifier-seq shall not contain typedef and shall not declare a 8917 // new class or enumeration. 8918 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 8919 "Parser allowed 'typedef' as storage class of condition decl."); 8920 8921 TagDecl *OwnedTag = 0; 8922 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag); 8923 QualType Ty = TInfo->getType(); 8924 8925 if (Ty->isFunctionType()) { // The declarator shall not specify a function... 8926 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl 8927 // would be created and CXXConditionDeclExpr wants a VarDecl. 8928 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type) 8929 << D.getSourceRange(); 8930 return DeclResult(); 8931 } else if (OwnedTag && OwnedTag->isDefinition()) { 8932 // The type-specifier-seq shall not declare a new class or enumeration. 8933 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition); 8934 } 8935 8936 Decl *Dcl = ActOnDeclarator(S, D); 8937 if (!Dcl) 8938 return DeclResult(); 8939 8940 return Dcl; 8941} 8942 8943void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 8944 bool DefinitionRequired) { 8945 // Ignore any vtable uses in unevaluated operands or for classes that do 8946 // not have a vtable. 8947 if (!Class->isDynamicClass() || Class->isDependentContext() || 8948 CurContext->isDependentContext() || 8949 ExprEvalContexts.back().Context == Unevaluated) 8950 return; 8951 8952 // Try to insert this class into the map. 8953 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 8954 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 8955 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 8956 if (!Pos.second) { 8957 // If we already had an entry, check to see if we are promoting this vtable 8958 // to required a definition. If so, we need to reappend to the VTableUses 8959 // list, since we may have already processed the first entry. 8960 if (DefinitionRequired && !Pos.first->second) { 8961 Pos.first->second = true; 8962 } else { 8963 // Otherwise, we can early exit. 8964 return; 8965 } 8966 } 8967 8968 // Local classes need to have their virtual members marked 8969 // immediately. For all other classes, we mark their virtual members 8970 // at the end of the translation unit. 8971 if (Class->isLocalClass()) 8972 MarkVirtualMembersReferenced(Loc, Class); 8973 else 8974 VTableUses.push_back(std::make_pair(Class, Loc)); 8975} 8976 8977bool Sema::DefineUsedVTables() { 8978 if (VTableUses.empty()) 8979 return false; 8980 8981 // Note: The VTableUses vector could grow as a result of marking 8982 // the members of a class as "used", so we check the size each 8983 // time through the loop and prefer indices (with are stable) to 8984 // iterators (which are not). 8985 bool DefinedAnything = false; 8986 for (unsigned I = 0; I != VTableUses.size(); ++I) { 8987 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 8988 if (!Class) 8989 continue; 8990 8991 SourceLocation Loc = VTableUses[I].second; 8992 8993 // If this class has a key function, but that key function is 8994 // defined in another translation unit, we don't need to emit the 8995 // vtable even though we're using it. 8996 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class); 8997 if (KeyFunction && !KeyFunction->hasBody()) { 8998 switch (KeyFunction->getTemplateSpecializationKind()) { 8999 case TSK_Undeclared: 9000 case TSK_ExplicitSpecialization: 9001 case TSK_ExplicitInstantiationDeclaration: 9002 // The key function is in another translation unit. 9003 continue; 9004 9005 case TSK_ExplicitInstantiationDefinition: 9006 case TSK_ImplicitInstantiation: 9007 // We will be instantiating the key function. 9008 break; 9009 } 9010 } else if (!KeyFunction) { 9011 // If we have a class with no key function that is the subject 9012 // of an explicit instantiation declaration, suppress the 9013 // vtable; it will live with the explicit instantiation 9014 // definition. 9015 bool IsExplicitInstantiationDeclaration 9016 = Class->getTemplateSpecializationKind() 9017 == TSK_ExplicitInstantiationDeclaration; 9018 for (TagDecl::redecl_iterator R = Class->redecls_begin(), 9019 REnd = Class->redecls_end(); 9020 R != REnd; ++R) { 9021 TemplateSpecializationKind TSK 9022 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind(); 9023 if (TSK == TSK_ExplicitInstantiationDeclaration) 9024 IsExplicitInstantiationDeclaration = true; 9025 else if (TSK == TSK_ExplicitInstantiationDefinition) { 9026 IsExplicitInstantiationDeclaration = false; 9027 break; 9028 } 9029 } 9030 9031 if (IsExplicitInstantiationDeclaration) 9032 continue; 9033 } 9034 9035 // Mark all of the virtual members of this class as referenced, so 9036 // that we can build a vtable. Then, tell the AST consumer that a 9037 // vtable for this class is required. 9038 DefinedAnything = true; 9039 MarkVirtualMembersReferenced(Loc, Class); 9040 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 9041 Consumer.HandleVTable(Class, VTablesUsed[Canonical]); 9042 9043 // Optionally warn if we're emitting a weak vtable. 9044 if (Class->getLinkage() == ExternalLinkage && 9045 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) { 9046 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined())) 9047 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class; 9048 } 9049 } 9050 VTableUses.clear(); 9051 9052 return DefinedAnything; 9053} 9054 9055void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 9056 const CXXRecordDecl *RD) { 9057 for (CXXRecordDecl::method_iterator i = RD->method_begin(), 9058 e = RD->method_end(); i != e; ++i) { 9059 CXXMethodDecl *MD = *i; 9060 9061 // C++ [basic.def.odr]p2: 9062 // [...] A virtual member function is used if it is not pure. [...] 9063 if (MD->isVirtual() && !MD->isPure()) 9064 MarkDeclarationReferenced(Loc, MD); 9065 } 9066 9067 // Only classes that have virtual bases need a VTT. 9068 if (RD->getNumVBases() == 0) 9069 return; 9070 9071 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(), 9072 e = RD->bases_end(); i != e; ++i) { 9073 const CXXRecordDecl *Base = 9074 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl()); 9075 if (Base->getNumVBases() == 0) 9076 continue; 9077 MarkVirtualMembersReferenced(Loc, Base); 9078 } 9079} 9080 9081/// SetIvarInitializers - This routine builds initialization ASTs for the 9082/// Objective-C implementation whose ivars need be initialized. 9083void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 9084 if (!getLangOptions().CPlusPlus) 9085 return; 9086 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 9087 llvm::SmallVector<ObjCIvarDecl*, 8> ivars; 9088 CollectIvarsToConstructOrDestruct(OID, ivars); 9089 if (ivars.empty()) 9090 return; 9091 llvm::SmallVector<CXXCtorInitializer*, 32> AllToInit; 9092 for (unsigned i = 0; i < ivars.size(); i++) { 9093 FieldDecl *Field = ivars[i]; 9094 if (Field->isInvalidDecl()) 9095 continue; 9096 9097 CXXCtorInitializer *Member; 9098 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 9099 InitializationKind InitKind = 9100 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 9101 9102 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0); 9103 ExprResult MemberInit = 9104 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg()); 9105 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 9106 // Note, MemberInit could actually come back empty if no initialization 9107 // is required (e.g., because it would call a trivial default constructor) 9108 if (!MemberInit.get() || MemberInit.isInvalid()) 9109 continue; 9110 9111 Member = 9112 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 9113 SourceLocation(), 9114 MemberInit.takeAs<Expr>(), 9115 SourceLocation()); 9116 AllToInit.push_back(Member); 9117 9118 // Be sure that the destructor is accessible and is marked as referenced. 9119 if (const RecordType *RecordTy 9120 = Context.getBaseElementType(Field->getType()) 9121 ->getAs<RecordType>()) { 9122 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 9123 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 9124 MarkDeclarationReferenced(Field->getLocation(), Destructor); 9125 CheckDestructorAccess(Field->getLocation(), Destructor, 9126 PDiag(diag::err_access_dtor_ivar) 9127 << Context.getBaseElementType(Field->getType())); 9128 } 9129 } 9130 } 9131 ObjCImplementation->setIvarInitializers(Context, 9132 AllToInit.data(), AllToInit.size()); 9133 } 9134} 9135 9136static 9137void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 9138 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid, 9139 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid, 9140 llvm::SmallSet<CXXConstructorDecl*, 4> &Current, 9141 Sema &S) { 9142 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(), 9143 CE = Current.end(); 9144 if (Ctor->isInvalidDecl()) 9145 return; 9146 9147 const FunctionDecl *FNTarget = 0; 9148 CXXConstructorDecl *Target; 9149 9150 // We ignore the result here since if we don't have a body, Target will be 9151 // null below. 9152 (void)Ctor->getTargetConstructor()->hasBody(FNTarget); 9153 Target 9154= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget)); 9155 9156 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 9157 // Avoid dereferencing a null pointer here. 9158 *TCanonical = Target ? Target->getCanonicalDecl() : 0; 9159 9160 if (!Current.insert(Canonical)) 9161 return; 9162 9163 // We know that beyond here, we aren't chaining into a cycle. 9164 if (!Target || !Target->isDelegatingConstructor() || 9165 Target->isInvalidDecl() || Valid.count(TCanonical)) { 9166 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI) 9167 Valid.insert(*CI); 9168 Current.clear(); 9169 // We've hit a cycle. 9170 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 9171 Current.count(TCanonical)) { 9172 // If we haven't diagnosed this cycle yet, do so now. 9173 if (!Invalid.count(TCanonical)) { 9174 S.Diag((*Ctor->init_begin())->getSourceLocation(), 9175 diag::warn_delegating_ctor_cycle) 9176 << Ctor; 9177 9178 // Don't add a note for a function delegating directo to itself. 9179 if (TCanonical != Canonical) 9180 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 9181 9182 CXXConstructorDecl *C = Target; 9183 while (C->getCanonicalDecl() != Canonical) { 9184 (void)C->getTargetConstructor()->hasBody(FNTarget); 9185 assert(FNTarget && "Ctor cycle through bodiless function"); 9186 9187 C 9188 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget)); 9189 S.Diag(C->getLocation(), diag::note_which_delegates_to); 9190 } 9191 } 9192 9193 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI) 9194 Invalid.insert(*CI); 9195 Current.clear(); 9196 } else { 9197 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 9198 } 9199} 9200 9201 9202void Sema::CheckDelegatingCtorCycles() { 9203 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 9204 9205 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(), 9206 CE = Current.end(); 9207 9208 for (llvm::SmallVector<CXXConstructorDecl*, 4>::iterator 9209 I = DelegatingCtorDecls.begin(), 9210 E = DelegatingCtorDecls.end(); 9211 I != E; ++I) { 9212 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 9213 } 9214 9215 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI) 9216 (*CI)->setInvalidDecl(); 9217} 9218