SemaDeclCXX.cpp revision e25a96c0629b6f928d5e8055510789817db827d0
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 "Sema.h" 15#include "SemaInit.h" 16#include "Lookup.h" 17#include "clang/AST/ASTConsumer.h" 18#include "clang/AST/ASTContext.h" 19#include "clang/AST/RecordLayout.h" 20#include "clang/AST/CXXInheritance.h" 21#include "clang/AST/DeclVisitor.h" 22#include "clang/AST/TypeLoc.h" 23#include "clang/AST/TypeOrdering.h" 24#include "clang/AST/StmtVisitor.h" 25#include "clang/Parse/DeclSpec.h" 26#include "clang/Parse/Template.h" 27#include "clang/Basic/PartialDiagnostic.h" 28#include "clang/Lex/Preprocessor.h" 29#include "llvm/ADT/STLExtras.h" 30#include <map> 31#include <set> 32 33using namespace clang; 34 35//===----------------------------------------------------------------------===// 36// CheckDefaultArgumentVisitor 37//===----------------------------------------------------------------------===// 38 39namespace { 40 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 41 /// the default argument of a parameter to determine whether it 42 /// contains any ill-formed subexpressions. For example, this will 43 /// diagnose the use of local variables or parameters within the 44 /// default argument expression. 45 class CheckDefaultArgumentVisitor 46 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 47 Expr *DefaultArg; 48 Sema *S; 49 50 public: 51 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 52 : DefaultArg(defarg), S(s) {} 53 54 bool VisitExpr(Expr *Node); 55 bool VisitDeclRefExpr(DeclRefExpr *DRE); 56 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 57 }; 58 59 /// VisitExpr - Visit all of the children of this expression. 60 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 61 bool IsInvalid = false; 62 for (Stmt::child_iterator I = Node->child_begin(), 63 E = Node->child_end(); I != E; ++I) 64 IsInvalid |= Visit(*I); 65 return IsInvalid; 66 } 67 68 /// VisitDeclRefExpr - Visit a reference to a declaration, to 69 /// determine whether this declaration can be used in the default 70 /// argument expression. 71 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 72 NamedDecl *Decl = DRE->getDecl(); 73 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 74 // C++ [dcl.fct.default]p9 75 // Default arguments are evaluated each time the function is 76 // called. The order of evaluation of function arguments is 77 // unspecified. Consequently, parameters of a function shall not 78 // be used in default argument expressions, even if they are not 79 // evaluated. Parameters of a function declared before a default 80 // argument expression are in scope and can hide namespace and 81 // class member names. 82 return S->Diag(DRE->getSourceRange().getBegin(), 83 diag::err_param_default_argument_references_param) 84 << Param->getDeclName() << DefaultArg->getSourceRange(); 85 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 86 // C++ [dcl.fct.default]p7 87 // Local variables shall not be used in default argument 88 // expressions. 89 if (VDecl->isBlockVarDecl()) 90 return S->Diag(DRE->getSourceRange().getBegin(), 91 diag::err_param_default_argument_references_local) 92 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 93 } 94 95 return false; 96 } 97 98 /// VisitCXXThisExpr - Visit a C++ "this" expression. 99 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 100 // C++ [dcl.fct.default]p8: 101 // The keyword this shall not be used in a default argument of a 102 // member function. 103 return S->Diag(ThisE->getSourceRange().getBegin(), 104 diag::err_param_default_argument_references_this) 105 << ThisE->getSourceRange(); 106 } 107} 108 109bool 110Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg, 111 SourceLocation EqualLoc) { 112 if (RequireCompleteType(Param->getLocation(), Param->getType(), 113 diag::err_typecheck_decl_incomplete_type)) { 114 Param->setInvalidDecl(); 115 return true; 116 } 117 118 Expr *Arg = (Expr *)DefaultArg.get(); 119 120 // C++ [dcl.fct.default]p5 121 // A default argument expression is implicitly converted (clause 122 // 4) to the parameter type. The default argument expression has 123 // the same semantic constraints as the initializer expression in 124 // a declaration of a variable of the parameter type, using the 125 // copy-initialization semantics (8.5). 126 InitializedEntity Entity = InitializedEntity::InitializeParameter(Param); 127 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 128 EqualLoc); 129 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1); 130 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, 131 MultiExprArg(*this, (void**)&Arg, 1)); 132 if (Result.isInvalid()) 133 return true; 134 Arg = Result.takeAs<Expr>(); 135 136 Arg = MaybeCreateCXXExprWithTemporaries(Arg); 137 138 // Okay: add the default argument to the parameter 139 Param->setDefaultArg(Arg); 140 141 DefaultArg.release(); 142 143 return false; 144} 145 146/// ActOnParamDefaultArgument - Check whether the default argument 147/// provided for a function parameter is well-formed. If so, attach it 148/// to the parameter declaration. 149void 150Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc, 151 ExprArg defarg) { 152 if (!param || !defarg.get()) 153 return; 154 155 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>()); 156 UnparsedDefaultArgLocs.erase(Param); 157 158 ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>()); 159 160 // Default arguments are only permitted in C++ 161 if (!getLangOptions().CPlusPlus) { 162 Diag(EqualLoc, diag::err_param_default_argument) 163 << DefaultArg->getSourceRange(); 164 Param->setInvalidDecl(); 165 return; 166 } 167 168 // Check that the default argument is well-formed 169 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this); 170 if (DefaultArgChecker.Visit(DefaultArg.get())) { 171 Param->setInvalidDecl(); 172 return; 173 } 174 175 SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc); 176} 177 178/// ActOnParamUnparsedDefaultArgument - We've seen a default 179/// argument for a function parameter, but we can't parse it yet 180/// because we're inside a class definition. Note that this default 181/// argument will be parsed later. 182void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param, 183 SourceLocation EqualLoc, 184 SourceLocation ArgLoc) { 185 if (!param) 186 return; 187 188 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>()); 189 if (Param) 190 Param->setUnparsedDefaultArg(); 191 192 UnparsedDefaultArgLocs[Param] = ArgLoc; 193} 194 195/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 196/// the default argument for the parameter param failed. 197void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) { 198 if (!param) 199 return; 200 201 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>()); 202 203 Param->setInvalidDecl(); 204 205 UnparsedDefaultArgLocs.erase(Param); 206} 207 208/// CheckExtraCXXDefaultArguments - Check for any extra default 209/// arguments in the declarator, which is not a function declaration 210/// or definition and therefore is not permitted to have default 211/// arguments. This routine should be invoked for every declarator 212/// that is not a function declaration or definition. 213void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 214 // C++ [dcl.fct.default]p3 215 // A default argument expression shall be specified only in the 216 // parameter-declaration-clause of a function declaration or in a 217 // template-parameter (14.1). It shall not be specified for a 218 // parameter pack. If it is specified in a 219 // parameter-declaration-clause, it shall not occur within a 220 // declarator or abstract-declarator of a parameter-declaration. 221 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 222 DeclaratorChunk &chunk = D.getTypeObject(i); 223 if (chunk.Kind == DeclaratorChunk::Function) { 224 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) { 225 ParmVarDecl *Param = 226 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>()); 227 if (Param->hasUnparsedDefaultArg()) { 228 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens; 229 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 230 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation()); 231 delete Toks; 232 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0; 233 } else if (Param->getDefaultArg()) { 234 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 235 << Param->getDefaultArg()->getSourceRange(); 236 Param->setDefaultArg(0); 237 } 238 } 239 } 240 } 241} 242 243// MergeCXXFunctionDecl - Merge two declarations of the same C++ 244// function, once we already know that they have the same 245// type. Subroutine of MergeFunctionDecl. Returns true if there was an 246// error, false otherwise. 247bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) { 248 bool Invalid = false; 249 250 // C++ [dcl.fct.default]p4: 251 // For non-template functions, default arguments can be added in 252 // later declarations of a function in the same 253 // scope. Declarations in different scopes have completely 254 // distinct sets of default arguments. That is, declarations in 255 // inner scopes do not acquire default arguments from 256 // declarations in outer scopes, and vice versa. In a given 257 // function declaration, all parameters subsequent to a 258 // parameter with a default argument shall have default 259 // arguments supplied in this or previous declarations. A 260 // default argument shall not be redefined by a later 261 // declaration (not even to the same value). 262 // 263 // C++ [dcl.fct.default]p6: 264 // Except for member functions of class templates, the default arguments 265 // in a member function definition that appears outside of the class 266 // definition are added to the set of default arguments provided by the 267 // member function declaration in the class definition. 268 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 269 ParmVarDecl *OldParam = Old->getParamDecl(p); 270 ParmVarDecl *NewParam = New->getParamDecl(p); 271 272 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) { 273 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 274 // hint here. Alternatively, we could walk the type-source information 275 // for NewParam to find the last source location in the type... but it 276 // isn't worth the effort right now. This is the kind of test case that 277 // is hard to get right: 278 279 // int f(int); 280 // void g(int (*fp)(int) = f); 281 // void g(int (*fp)(int) = &f); 282 Diag(NewParam->getLocation(), 283 diag::err_param_default_argument_redefinition) 284 << NewParam->getDefaultArgRange(); 285 286 // Look for the function declaration where the default argument was 287 // actually written, which may be a declaration prior to Old. 288 for (FunctionDecl *Older = Old->getPreviousDeclaration(); 289 Older; Older = Older->getPreviousDeclaration()) { 290 if (!Older->getParamDecl(p)->hasDefaultArg()) 291 break; 292 293 OldParam = Older->getParamDecl(p); 294 } 295 296 Diag(OldParam->getLocation(), diag::note_previous_definition) 297 << OldParam->getDefaultArgRange(); 298 Invalid = true; 299 } else if (OldParam->hasDefaultArg()) { 300 // Merge the old default argument into the new parameter 301 NewParam->setHasInheritedDefaultArg(); 302 if (OldParam->hasUninstantiatedDefaultArg()) 303 NewParam->setUninstantiatedDefaultArg( 304 OldParam->getUninstantiatedDefaultArg()); 305 else 306 NewParam->setDefaultArg(OldParam->getDefaultArg()); 307 } else if (NewParam->hasDefaultArg()) { 308 if (New->getDescribedFunctionTemplate()) { 309 // Paragraph 4, quoted above, only applies to non-template functions. 310 Diag(NewParam->getLocation(), 311 diag::err_param_default_argument_template_redecl) 312 << NewParam->getDefaultArgRange(); 313 Diag(Old->getLocation(), diag::note_template_prev_declaration) 314 << false; 315 } else if (New->getTemplateSpecializationKind() 316 != TSK_ImplicitInstantiation && 317 New->getTemplateSpecializationKind() != TSK_Undeclared) { 318 // C++ [temp.expr.spec]p21: 319 // Default function arguments shall not be specified in a declaration 320 // or a definition for one of the following explicit specializations: 321 // - the explicit specialization of a function template; 322 // - the explicit specialization of a member function template; 323 // - the explicit specialization of a member function of a class 324 // template where the class template specialization to which the 325 // member function specialization belongs is implicitly 326 // instantiated. 327 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 328 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 329 << New->getDeclName() 330 << NewParam->getDefaultArgRange(); 331 } else if (New->getDeclContext()->isDependentContext()) { 332 // C++ [dcl.fct.default]p6 (DR217): 333 // Default arguments for a member function of a class template shall 334 // be specified on the initial declaration of the member function 335 // within the class template. 336 // 337 // Reading the tea leaves a bit in DR217 and its reference to DR205 338 // leads me to the conclusion that one cannot add default function 339 // arguments for an out-of-line definition of a member function of a 340 // dependent type. 341 int WhichKind = 2; 342 if (CXXRecordDecl *Record 343 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 344 if (Record->getDescribedClassTemplate()) 345 WhichKind = 0; 346 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 347 WhichKind = 1; 348 else 349 WhichKind = 2; 350 } 351 352 Diag(NewParam->getLocation(), 353 diag::err_param_default_argument_member_template_redecl) 354 << WhichKind 355 << NewParam->getDefaultArgRange(); 356 } 357 } 358 } 359 360 if (CheckEquivalentExceptionSpec(Old, New)) 361 Invalid = true; 362 363 return Invalid; 364} 365 366/// CheckCXXDefaultArguments - Verify that the default arguments for a 367/// function declaration are well-formed according to C++ 368/// [dcl.fct.default]. 369void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 370 unsigned NumParams = FD->getNumParams(); 371 unsigned p; 372 373 // Find first parameter with a default argument 374 for (p = 0; p < NumParams; ++p) { 375 ParmVarDecl *Param = FD->getParamDecl(p); 376 if (Param->hasDefaultArg()) 377 break; 378 } 379 380 // C++ [dcl.fct.default]p4: 381 // In a given function declaration, all parameters 382 // subsequent to a parameter with a default argument shall 383 // have default arguments supplied in this or previous 384 // declarations. A default argument shall not be redefined 385 // by a later declaration (not even to the same value). 386 unsigned LastMissingDefaultArg = 0; 387 for (; p < NumParams; ++p) { 388 ParmVarDecl *Param = FD->getParamDecl(p); 389 if (!Param->hasDefaultArg()) { 390 if (Param->isInvalidDecl()) 391 /* We already complained about this parameter. */; 392 else if (Param->getIdentifier()) 393 Diag(Param->getLocation(), 394 diag::err_param_default_argument_missing_name) 395 << Param->getIdentifier(); 396 else 397 Diag(Param->getLocation(), 398 diag::err_param_default_argument_missing); 399 400 LastMissingDefaultArg = p; 401 } 402 } 403 404 if (LastMissingDefaultArg > 0) { 405 // Some default arguments were missing. Clear out all of the 406 // default arguments up to (and including) the last missing 407 // default argument, so that we leave the function parameters 408 // in a semantically valid state. 409 for (p = 0; p <= LastMissingDefaultArg; ++p) { 410 ParmVarDecl *Param = FD->getParamDecl(p); 411 if (Param->hasDefaultArg()) { 412 if (!Param->hasUnparsedDefaultArg()) 413 Param->getDefaultArg()->Destroy(Context); 414 Param->setDefaultArg(0); 415 } 416 } 417 } 418} 419 420/// isCurrentClassName - Determine whether the identifier II is the 421/// name of the class type currently being defined. In the case of 422/// nested classes, this will only return true if II is the name of 423/// the innermost class. 424bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 425 const CXXScopeSpec *SS) { 426 assert(getLangOptions().CPlusPlus && "No class names in C!"); 427 428 CXXRecordDecl *CurDecl; 429 if (SS && SS->isSet() && !SS->isInvalid()) { 430 DeclContext *DC = computeDeclContext(*SS, true); 431 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 432 } else 433 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 434 435 if (CurDecl && CurDecl->getIdentifier()) 436 return &II == CurDecl->getIdentifier(); 437 else 438 return false; 439} 440 441/// \brief Check the validity of a C++ base class specifier. 442/// 443/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 444/// and returns NULL otherwise. 445CXXBaseSpecifier * 446Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 447 SourceRange SpecifierRange, 448 bool Virtual, AccessSpecifier Access, 449 QualType BaseType, 450 SourceLocation BaseLoc) { 451 // C++ [class.union]p1: 452 // A union shall not have base classes. 453 if (Class->isUnion()) { 454 Diag(Class->getLocation(), diag::err_base_clause_on_union) 455 << SpecifierRange; 456 return 0; 457 } 458 459 if (BaseType->isDependentType()) 460 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 461 Class->getTagKind() == RecordDecl::TK_class, 462 Access, BaseType); 463 464 // Base specifiers must be record types. 465 if (!BaseType->isRecordType()) { 466 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 467 return 0; 468 } 469 470 // C++ [class.union]p1: 471 // A union shall not be used as a base class. 472 if (BaseType->isUnionType()) { 473 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 474 return 0; 475 } 476 477 // C++ [class.derived]p2: 478 // The class-name in a base-specifier shall not be an incompletely 479 // defined class. 480 if (RequireCompleteType(BaseLoc, BaseType, 481 PDiag(diag::err_incomplete_base_class) 482 << SpecifierRange)) 483 return 0; 484 485 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 486 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 487 assert(BaseDecl && "Record type has no declaration"); 488 BaseDecl = BaseDecl->getDefinition(); 489 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 490 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 491 assert(CXXBaseDecl && "Base type is not a C++ type"); 492 493 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases. 494 if (CXXBaseDecl->hasAttr<FinalAttr>()) { 495 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString(); 496 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl) 497 << BaseType; 498 return 0; 499 } 500 501 SetClassDeclAttributesFromBase(Class, CXXBaseDecl, Virtual); 502 503 // Create the base specifier. 504 // FIXME: Allocate via ASTContext? 505 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 506 Class->getTagKind() == RecordDecl::TK_class, 507 Access, BaseType); 508} 509 510void Sema::SetClassDeclAttributesFromBase(CXXRecordDecl *Class, 511 const CXXRecordDecl *BaseClass, 512 bool BaseIsVirtual) { 513 // A class with a non-empty base class is not empty. 514 // FIXME: Standard ref? 515 if (!BaseClass->isEmpty()) 516 Class->setEmpty(false); 517 518 // C++ [class.virtual]p1: 519 // A class that [...] inherits a virtual function is called a polymorphic 520 // class. 521 if (BaseClass->isPolymorphic()) 522 Class->setPolymorphic(true); 523 524 // C++ [dcl.init.aggr]p1: 525 // An aggregate is [...] a class with [...] no base classes [...]. 526 Class->setAggregate(false); 527 528 // C++ [class]p4: 529 // A POD-struct is an aggregate class... 530 Class->setPOD(false); 531 532 if (BaseIsVirtual) { 533 // C++ [class.ctor]p5: 534 // A constructor is trivial if its class has no virtual base classes. 535 Class->setHasTrivialConstructor(false); 536 537 // C++ [class.copy]p6: 538 // A copy constructor is trivial if its class has no virtual base classes. 539 Class->setHasTrivialCopyConstructor(false); 540 541 // C++ [class.copy]p11: 542 // A copy assignment operator is trivial if its class has no virtual 543 // base classes. 544 Class->setHasTrivialCopyAssignment(false); 545 546 // C++0x [meta.unary.prop] is_empty: 547 // T is a class type, but not a union type, with ... no virtual base 548 // classes 549 Class->setEmpty(false); 550 } else { 551 // C++ [class.ctor]p5: 552 // A constructor is trivial if all the direct base classes of its 553 // class have trivial constructors. 554 if (!BaseClass->hasTrivialConstructor()) 555 Class->setHasTrivialConstructor(false); 556 557 // C++ [class.copy]p6: 558 // A copy constructor is trivial if all the direct base classes of its 559 // class have trivial copy constructors. 560 if (!BaseClass->hasTrivialCopyConstructor()) 561 Class->setHasTrivialCopyConstructor(false); 562 563 // C++ [class.copy]p11: 564 // A copy assignment operator is trivial if all the direct base classes 565 // of its class have trivial copy assignment operators. 566 if (!BaseClass->hasTrivialCopyAssignment()) 567 Class->setHasTrivialCopyAssignment(false); 568 } 569 570 // C++ [class.ctor]p3: 571 // A destructor is trivial if all the direct base classes of its class 572 // have trivial destructors. 573 if (!BaseClass->hasTrivialDestructor()) 574 Class->setHasTrivialDestructor(false); 575} 576 577/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 578/// one entry in the base class list of a class specifier, for 579/// example: 580/// class foo : public bar, virtual private baz { 581/// 'public bar' and 'virtual private baz' are each base-specifiers. 582Sema::BaseResult 583Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange, 584 bool Virtual, AccessSpecifier Access, 585 TypeTy *basetype, SourceLocation BaseLoc) { 586 if (!classdecl) 587 return true; 588 589 AdjustDeclIfTemplate(classdecl); 590 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl.getAs<Decl>()); 591 if (!Class) 592 return true; 593 594 QualType BaseType = GetTypeFromParser(basetype); 595 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 596 Virtual, Access, 597 BaseType, BaseLoc)) 598 return BaseSpec; 599 600 return true; 601} 602 603/// \brief Performs the actual work of attaching the given base class 604/// specifiers to a C++ class. 605bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 606 unsigned NumBases) { 607 if (NumBases == 0) 608 return false; 609 610 // Used to keep track of which base types we have already seen, so 611 // that we can properly diagnose redundant direct base types. Note 612 // that the key is always the unqualified canonical type of the base 613 // class. 614 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 615 616 // Copy non-redundant base specifiers into permanent storage. 617 unsigned NumGoodBases = 0; 618 bool Invalid = false; 619 for (unsigned idx = 0; idx < NumBases; ++idx) { 620 QualType NewBaseType 621 = Context.getCanonicalType(Bases[idx]->getType()); 622 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 623 624 if (KnownBaseTypes[NewBaseType]) { 625 // C++ [class.mi]p3: 626 // A class shall not be specified as a direct base class of a 627 // derived class more than once. 628 Diag(Bases[idx]->getSourceRange().getBegin(), 629 diag::err_duplicate_base_class) 630 << KnownBaseTypes[NewBaseType]->getType() 631 << Bases[idx]->getSourceRange(); 632 633 // Delete the duplicate base class specifier; we're going to 634 // overwrite its pointer later. 635 Context.Deallocate(Bases[idx]); 636 637 Invalid = true; 638 } else { 639 // Okay, add this new base class. 640 KnownBaseTypes[NewBaseType] = Bases[idx]; 641 Bases[NumGoodBases++] = Bases[idx]; 642 } 643 } 644 645 // Attach the remaining base class specifiers to the derived class. 646 Class->setBases(Bases, NumGoodBases); 647 648 // Delete the remaining (good) base class specifiers, since their 649 // data has been copied into the CXXRecordDecl. 650 for (unsigned idx = 0; idx < NumGoodBases; ++idx) 651 Context.Deallocate(Bases[idx]); 652 653 return Invalid; 654} 655 656/// ActOnBaseSpecifiers - Attach the given base specifiers to the 657/// class, after checking whether there are any duplicate base 658/// classes. 659void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases, 660 unsigned NumBases) { 661 if (!ClassDecl || !Bases || !NumBases) 662 return; 663 664 AdjustDeclIfTemplate(ClassDecl); 665 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()), 666 (CXXBaseSpecifier**)(Bases), NumBases); 667} 668 669static CXXRecordDecl *GetClassForType(QualType T) { 670 if (const RecordType *RT = T->getAs<RecordType>()) 671 return cast<CXXRecordDecl>(RT->getDecl()); 672 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>()) 673 return ICT->getDecl(); 674 else 675 return 0; 676} 677 678/// \brief Determine whether the type \p Derived is a C++ class that is 679/// derived from the type \p Base. 680bool Sema::IsDerivedFrom(QualType Derived, QualType Base) { 681 if (!getLangOptions().CPlusPlus) 682 return false; 683 684 CXXRecordDecl *DerivedRD = GetClassForType(Derived); 685 if (!DerivedRD) 686 return false; 687 688 CXXRecordDecl *BaseRD = GetClassForType(Base); 689 if (!BaseRD) 690 return false; 691 692 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this. 693 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD); 694} 695 696/// \brief Determine whether the type \p Derived is a C++ class that is 697/// derived from the type \p Base. 698bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) { 699 if (!getLangOptions().CPlusPlus) 700 return false; 701 702 CXXRecordDecl *DerivedRD = GetClassForType(Derived); 703 if (!DerivedRD) 704 return false; 705 706 CXXRecordDecl *BaseRD = GetClassForType(Base); 707 if (!BaseRD) 708 return false; 709 710 return DerivedRD->isDerivedFrom(BaseRD, Paths); 711} 712 713/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 714/// conversion (where Derived and Base are class types) is 715/// well-formed, meaning that the conversion is unambiguous (and 716/// that all of the base classes are accessible). Returns true 717/// and emits a diagnostic if the code is ill-formed, returns false 718/// otherwise. Loc is the location where this routine should point to 719/// if there is an error, and Range is the source range to highlight 720/// if there is an error. 721bool 722Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 723 unsigned InaccessibleBaseID, 724 unsigned AmbigiousBaseConvID, 725 SourceLocation Loc, SourceRange Range, 726 DeclarationName Name, 727 CXXBaseSpecifierArray *BasePath) { 728 // First, determine whether the path from Derived to Base is 729 // ambiguous. This is slightly more expensive than checking whether 730 // the Derived to Base conversion exists, because here we need to 731 // explore multiple paths to determine if there is an ambiguity. 732 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 733 /*DetectVirtual=*/false); 734 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths); 735 assert(DerivationOkay && 736 "Can only be used with a derived-to-base conversion"); 737 (void)DerivationOkay; 738 739 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 740 if (!InaccessibleBaseID) 741 return false; 742 743 // Check that the base class can be accessed. 744 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(), 745 InaccessibleBaseID)) { 746 case AR_inaccessible: 747 return true; 748 case AR_accessible: 749 case AR_dependent: 750 case AR_delayed: 751 // Build a base path if necessary. 752 if (BasePath) { 753 // FIXME: Do this! 754 } 755 return false; 756 } 757 } 758 759 // We know that the derived-to-base conversion is ambiguous, and 760 // we're going to produce a diagnostic. Perform the derived-to-base 761 // search just one more time to compute all of the possible paths so 762 // that we can print them out. This is more expensive than any of 763 // the previous derived-to-base checks we've done, but at this point 764 // performance isn't as much of an issue. 765 Paths.clear(); 766 Paths.setRecordingPaths(true); 767 bool StillOkay = IsDerivedFrom(Derived, Base, Paths); 768 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 769 (void)StillOkay; 770 771 // Build up a textual representation of the ambiguous paths, e.g., 772 // D -> B -> A, that will be used to illustrate the ambiguous 773 // conversions in the diagnostic. We only print one of the paths 774 // to each base class subobject. 775 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 776 777 Diag(Loc, AmbigiousBaseConvID) 778 << Derived << Base << PathDisplayStr << Range << Name; 779 return true; 780} 781 782bool 783Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 784 SourceLocation Loc, SourceRange Range, 785 CXXBaseSpecifierArray *BasePath, 786 bool IgnoreAccess) { 787 return CheckDerivedToBaseConversion(Derived, Base, 788 IgnoreAccess ? 0 789 : diag::err_upcast_to_inaccessible_base, 790 diag::err_ambiguous_derived_to_base_conv, 791 Loc, Range, DeclarationName(), 792 BasePath); 793} 794 795 796/// @brief Builds a string representing ambiguous paths from a 797/// specific derived class to different subobjects of the same base 798/// class. 799/// 800/// This function builds a string that can be used in error messages 801/// to show the different paths that one can take through the 802/// inheritance hierarchy to go from the derived class to different 803/// subobjects of a base class. The result looks something like this: 804/// @code 805/// struct D -> struct B -> struct A 806/// struct D -> struct C -> struct A 807/// @endcode 808std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 809 std::string PathDisplayStr; 810 std::set<unsigned> DisplayedPaths; 811 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 812 Path != Paths.end(); ++Path) { 813 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 814 // We haven't displayed a path to this particular base 815 // class subobject yet. 816 PathDisplayStr += "\n "; 817 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 818 for (CXXBasePath::const_iterator Element = Path->begin(); 819 Element != Path->end(); ++Element) 820 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 821 } 822 } 823 824 return PathDisplayStr; 825} 826 827//===----------------------------------------------------------------------===// 828// C++ class member Handling 829//===----------------------------------------------------------------------===// 830 831/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 832/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 833/// bitfield width if there is one and 'InitExpr' specifies the initializer if 834/// any. 835Sema::DeclPtrTy 836Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 837 MultiTemplateParamsArg TemplateParameterLists, 838 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition, 839 bool Deleted) { 840 const DeclSpec &DS = D.getDeclSpec(); 841 DeclarationName Name = GetNameForDeclarator(D); 842 Expr *BitWidth = static_cast<Expr*>(BW); 843 Expr *Init = static_cast<Expr*>(InitExpr); 844 SourceLocation Loc = D.getIdentifierLoc(); 845 846 bool isFunc = D.isFunctionDeclarator(); 847 848 assert(!DS.isFriendSpecified()); 849 850 // C++ 9.2p6: A member shall not be declared to have automatic storage 851 // duration (auto, register) or with the extern storage-class-specifier. 852 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 853 // data members and cannot be applied to names declared const or static, 854 // and cannot be applied to reference members. 855 switch (DS.getStorageClassSpec()) { 856 case DeclSpec::SCS_unspecified: 857 case DeclSpec::SCS_typedef: 858 case DeclSpec::SCS_static: 859 // FALL THROUGH. 860 break; 861 case DeclSpec::SCS_mutable: 862 if (isFunc) { 863 if (DS.getStorageClassSpecLoc().isValid()) 864 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 865 else 866 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function); 867 868 // FIXME: It would be nicer if the keyword was ignored only for this 869 // declarator. Otherwise we could get follow-up errors. 870 D.getMutableDeclSpec().ClearStorageClassSpecs(); 871 } else { 872 QualType T = GetTypeForDeclarator(D, S); 873 diag::kind err = static_cast<diag::kind>(0); 874 if (T->isReferenceType()) 875 err = diag::err_mutable_reference; 876 else if (T.isConstQualified()) 877 err = diag::err_mutable_const; 878 if (err != 0) { 879 if (DS.getStorageClassSpecLoc().isValid()) 880 Diag(DS.getStorageClassSpecLoc(), err); 881 else 882 Diag(DS.getThreadSpecLoc(), err); 883 // FIXME: It would be nicer if the keyword was ignored only for this 884 // declarator. Otherwise we could get follow-up errors. 885 D.getMutableDeclSpec().ClearStorageClassSpecs(); 886 } 887 } 888 break; 889 default: 890 if (DS.getStorageClassSpecLoc().isValid()) 891 Diag(DS.getStorageClassSpecLoc(), 892 diag::err_storageclass_invalid_for_member); 893 else 894 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member); 895 D.getMutableDeclSpec().ClearStorageClassSpecs(); 896 } 897 898 if (!isFunc && 899 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename && 900 D.getNumTypeObjects() == 0) { 901 // Check also for this case: 902 // 903 // typedef int f(); 904 // f a; 905 // 906 QualType TDType = GetTypeFromParser(DS.getTypeRep()); 907 isFunc = TDType->isFunctionType(); 908 } 909 910 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 911 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 912 !isFunc); 913 914 Decl *Member; 915 if (isInstField) { 916 // FIXME: Check for template parameters! 917 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth, 918 AS); 919 assert(Member && "HandleField never returns null"); 920 } else { 921 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition) 922 .getAs<Decl>(); 923 if (!Member) { 924 if (BitWidth) DeleteExpr(BitWidth); 925 return DeclPtrTy(); 926 } 927 928 // Non-instance-fields can't have a bitfield. 929 if (BitWidth) { 930 if (Member->isInvalidDecl()) { 931 // don't emit another diagnostic. 932 } else if (isa<VarDecl>(Member)) { 933 // C++ 9.6p3: A bit-field shall not be a static member. 934 // "static member 'A' cannot be a bit-field" 935 Diag(Loc, diag::err_static_not_bitfield) 936 << Name << BitWidth->getSourceRange(); 937 } else if (isa<TypedefDecl>(Member)) { 938 // "typedef member 'x' cannot be a bit-field" 939 Diag(Loc, diag::err_typedef_not_bitfield) 940 << Name << BitWidth->getSourceRange(); 941 } else { 942 // A function typedef ("typedef int f(); f a;"). 943 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 944 Diag(Loc, diag::err_not_integral_type_bitfield) 945 << Name << cast<ValueDecl>(Member)->getType() 946 << BitWidth->getSourceRange(); 947 } 948 949 DeleteExpr(BitWidth); 950 BitWidth = 0; 951 Member->setInvalidDecl(); 952 } 953 954 Member->setAccess(AS); 955 956 // If we have declared a member function template, set the access of the 957 // templated declaration as well. 958 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 959 FunTmpl->getTemplatedDecl()->setAccess(AS); 960 } 961 962 assert((Name || isInstField) && "No identifier for non-field ?"); 963 964 if (Init) 965 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false); 966 if (Deleted) // FIXME: Source location is not very good. 967 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin()); 968 969 if (isInstField) { 970 FieldCollector->Add(cast<FieldDecl>(Member)); 971 return DeclPtrTy(); 972 } 973 return DeclPtrTy::make(Member); 974} 975 976/// \brief Find the direct and/or virtual base specifiers that 977/// correspond to the given base type, for use in base initialization 978/// within a constructor. 979static bool FindBaseInitializer(Sema &SemaRef, 980 CXXRecordDecl *ClassDecl, 981 QualType BaseType, 982 const CXXBaseSpecifier *&DirectBaseSpec, 983 const CXXBaseSpecifier *&VirtualBaseSpec) { 984 // First, check for a direct base class. 985 DirectBaseSpec = 0; 986 for (CXXRecordDecl::base_class_const_iterator Base 987 = ClassDecl->bases_begin(); 988 Base != ClassDecl->bases_end(); ++Base) { 989 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) { 990 // We found a direct base of this type. That's what we're 991 // initializing. 992 DirectBaseSpec = &*Base; 993 break; 994 } 995 } 996 997 // Check for a virtual base class. 998 // FIXME: We might be able to short-circuit this if we know in advance that 999 // there are no virtual bases. 1000 VirtualBaseSpec = 0; 1001 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 1002 // We haven't found a base yet; search the class hierarchy for a 1003 // virtual base class. 1004 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1005 /*DetectVirtual=*/false); 1006 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl), 1007 BaseType, Paths)) { 1008 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 1009 Path != Paths.end(); ++Path) { 1010 if (Path->back().Base->isVirtual()) { 1011 VirtualBaseSpec = Path->back().Base; 1012 break; 1013 } 1014 } 1015 } 1016 } 1017 1018 return DirectBaseSpec || VirtualBaseSpec; 1019} 1020 1021/// ActOnMemInitializer - Handle a C++ member initializer. 1022Sema::MemInitResult 1023Sema::ActOnMemInitializer(DeclPtrTy ConstructorD, 1024 Scope *S, 1025 CXXScopeSpec &SS, 1026 IdentifierInfo *MemberOrBase, 1027 TypeTy *TemplateTypeTy, 1028 SourceLocation IdLoc, 1029 SourceLocation LParenLoc, 1030 ExprTy **Args, unsigned NumArgs, 1031 SourceLocation *CommaLocs, 1032 SourceLocation RParenLoc) { 1033 if (!ConstructorD) 1034 return true; 1035 1036 AdjustDeclIfTemplate(ConstructorD); 1037 1038 CXXConstructorDecl *Constructor 1039 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>()); 1040 if (!Constructor) { 1041 // The user wrote a constructor initializer on a function that is 1042 // not a C++ constructor. Ignore the error for now, because we may 1043 // have more member initializers coming; we'll diagnose it just 1044 // once in ActOnMemInitializers. 1045 return true; 1046 } 1047 1048 CXXRecordDecl *ClassDecl = Constructor->getParent(); 1049 1050 // C++ [class.base.init]p2: 1051 // Names in a mem-initializer-id are looked up in the scope of the 1052 // constructor’s class and, if not found in that scope, are looked 1053 // up in the scope containing the constructor’s 1054 // definition. [Note: if the constructor’s class contains a member 1055 // with the same name as a direct or virtual base class of the 1056 // class, a mem-initializer-id naming the member or base class and 1057 // composed of a single identifier refers to the class member. A 1058 // mem-initializer-id for the hidden base class may be specified 1059 // using a qualified name. ] 1060 if (!SS.getScopeRep() && !TemplateTypeTy) { 1061 // Look for a member, first. 1062 FieldDecl *Member = 0; 1063 DeclContext::lookup_result Result 1064 = ClassDecl->lookup(MemberOrBase); 1065 if (Result.first != Result.second) 1066 Member = dyn_cast<FieldDecl>(*Result.first); 1067 1068 // FIXME: Handle members of an anonymous union. 1069 1070 if (Member) 1071 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc, 1072 LParenLoc, RParenLoc); 1073 } 1074 // It didn't name a member, so see if it names a class. 1075 QualType BaseType; 1076 TypeSourceInfo *TInfo = 0; 1077 1078 if (TemplateTypeTy) { 1079 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 1080 } else { 1081 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 1082 LookupParsedName(R, S, &SS); 1083 1084 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 1085 if (!TyD) { 1086 if (R.isAmbiguous()) return true; 1087 1088 // We don't want access-control diagnostics here. 1089 R.suppressDiagnostics(); 1090 1091 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 1092 bool NotUnknownSpecialization = false; 1093 DeclContext *DC = computeDeclContext(SS, false); 1094 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 1095 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 1096 1097 if (!NotUnknownSpecialization) { 1098 // When the scope specifier can refer to a member of an unknown 1099 // specialization, we take it as a type name. 1100 BaseType = CheckTypenameType(ETK_None, 1101 (NestedNameSpecifier *)SS.getScopeRep(), 1102 *MemberOrBase, SS.getRange()); 1103 if (BaseType.isNull()) 1104 return true; 1105 1106 R.clear(); 1107 } 1108 } 1109 1110 // If no results were found, try to correct typos. 1111 if (R.empty() && BaseType.isNull() && 1112 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) && 1113 R.isSingleResult()) { 1114 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) { 1115 if (Member->getDeclContext()->getLookupContext()->Equals(ClassDecl)) { 1116 // We have found a non-static data member with a similar 1117 // name to what was typed; complain and initialize that 1118 // member. 1119 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest) 1120 << MemberOrBase << true << R.getLookupName() 1121 << FixItHint::CreateReplacement(R.getNameLoc(), 1122 R.getLookupName().getAsString()); 1123 Diag(Member->getLocation(), diag::note_previous_decl) 1124 << Member->getDeclName(); 1125 1126 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc, 1127 LParenLoc, RParenLoc); 1128 } 1129 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) { 1130 const CXXBaseSpecifier *DirectBaseSpec; 1131 const CXXBaseSpecifier *VirtualBaseSpec; 1132 if (FindBaseInitializer(*this, ClassDecl, 1133 Context.getTypeDeclType(Type), 1134 DirectBaseSpec, VirtualBaseSpec)) { 1135 // We have found a direct or virtual base class with a 1136 // similar name to what was typed; complain and initialize 1137 // that base class. 1138 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest) 1139 << MemberOrBase << false << R.getLookupName() 1140 << FixItHint::CreateReplacement(R.getNameLoc(), 1141 R.getLookupName().getAsString()); 1142 1143 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec 1144 : VirtualBaseSpec; 1145 Diag(BaseSpec->getSourceRange().getBegin(), 1146 diag::note_base_class_specified_here) 1147 << BaseSpec->getType() 1148 << BaseSpec->getSourceRange(); 1149 1150 TyD = Type; 1151 } 1152 } 1153 } 1154 1155 if (!TyD && BaseType.isNull()) { 1156 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 1157 << MemberOrBase << SourceRange(IdLoc, RParenLoc); 1158 return true; 1159 } 1160 } 1161 1162 if (BaseType.isNull()) { 1163 BaseType = Context.getTypeDeclType(TyD); 1164 if (SS.isSet()) { 1165 NestedNameSpecifier *Qualifier = 1166 static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 1167 1168 // FIXME: preserve source range information 1169 BaseType = Context.getQualifiedNameType(Qualifier, BaseType); 1170 } 1171 } 1172 } 1173 1174 if (!TInfo) 1175 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 1176 1177 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs, 1178 LParenLoc, RParenLoc, ClassDecl); 1179} 1180 1181/// Checks an initializer expression for use of uninitialized fields, such as 1182/// containing the field that is being initialized. Returns true if there is an 1183/// uninitialized field was used an updates the SourceLocation parameter; false 1184/// otherwise. 1185static bool InitExprContainsUninitializedFields(const Stmt* S, 1186 const FieldDecl* LhsField, 1187 SourceLocation* L) { 1188 const MemberExpr* ME = dyn_cast<MemberExpr>(S); 1189 if (ME) { 1190 const NamedDecl* RhsField = ME->getMemberDecl(); 1191 if (RhsField == LhsField) { 1192 // Initializing a field with itself. Throw a warning. 1193 // But wait; there are exceptions! 1194 // Exception #1: The field may not belong to this record. 1195 // e.g. Foo(const Foo& rhs) : A(rhs.A) {} 1196 const Expr* base = ME->getBase(); 1197 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) { 1198 // Even though the field matches, it does not belong to this record. 1199 return false; 1200 } 1201 // None of the exceptions triggered; return true to indicate an 1202 // uninitialized field was used. 1203 *L = ME->getMemberLoc(); 1204 return true; 1205 } 1206 } 1207 bool found = false; 1208 for (Stmt::const_child_iterator it = S->child_begin(); 1209 it != S->child_end() && found == false; 1210 ++it) { 1211 if (isa<CallExpr>(S)) { 1212 // Do not descend into function calls or constructors, as the use 1213 // of an uninitialized field may be valid. One would have to inspect 1214 // the contents of the function/ctor to determine if it is safe or not. 1215 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers 1216 // may be safe, depending on what the function/ctor does. 1217 continue; 1218 } 1219 found = InitExprContainsUninitializedFields(*it, LhsField, L); 1220 } 1221 return found; 1222} 1223 1224Sema::MemInitResult 1225Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args, 1226 unsigned NumArgs, SourceLocation IdLoc, 1227 SourceLocation LParenLoc, 1228 SourceLocation RParenLoc) { 1229 // Diagnose value-uses of fields to initialize themselves, e.g. 1230 // foo(foo) 1231 // where foo is not also a parameter to the constructor. 1232 // TODO: implement -Wuninitialized and fold this into that framework. 1233 for (unsigned i = 0; i < NumArgs; ++i) { 1234 SourceLocation L; 1235 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) { 1236 // FIXME: Return true in the case when other fields are used before being 1237 // uninitialized. For example, let this field be the i'th field. When 1238 // initializing the i'th field, throw a warning if any of the >= i'th 1239 // fields are used, as they are not yet initialized. 1240 // Right now we are only handling the case where the i'th field uses 1241 // itself in its initializer. 1242 Diag(L, diag::warn_field_is_uninit); 1243 } 1244 } 1245 1246 bool HasDependentArg = false; 1247 for (unsigned i = 0; i < NumArgs; i++) 1248 HasDependentArg |= Args[i]->isTypeDependent(); 1249 1250 QualType FieldType = Member->getType(); 1251 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 1252 FieldType = Array->getElementType(); 1253 if (FieldType->isDependentType() || HasDependentArg) { 1254 // Can't check initialization for a member of dependent type or when 1255 // any of the arguments are type-dependent expressions. 1256 OwningExprResult Init 1257 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs, 1258 RParenLoc)); 1259 1260 // Erase any temporaries within this evaluation context; we're not 1261 // going to track them in the AST, since we'll be rebuilding the 1262 // ASTs during template instantiation. 1263 ExprTemporaries.erase( 1264 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries, 1265 ExprTemporaries.end()); 1266 1267 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc, 1268 LParenLoc, 1269 Init.takeAs<Expr>(), 1270 RParenLoc); 1271 1272 } 1273 1274 if (Member->isInvalidDecl()) 1275 return true; 1276 1277 // Initialize the member. 1278 InitializedEntity MemberEntity = 1279 InitializedEntity::InitializeMember(Member, 0); 1280 InitializationKind Kind = 1281 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc); 1282 1283 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs); 1284 1285 OwningExprResult MemberInit = 1286 InitSeq.Perform(*this, MemberEntity, Kind, 1287 MultiExprArg(*this, (void**)Args, NumArgs), 0); 1288 if (MemberInit.isInvalid()) 1289 return true; 1290 1291 // C++0x [class.base.init]p7: 1292 // The initialization of each base and member constitutes a 1293 // full-expression. 1294 MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit)); 1295 if (MemberInit.isInvalid()) 1296 return true; 1297 1298 // If we are in a dependent context, template instantiation will 1299 // perform this type-checking again. Just save the arguments that we 1300 // received in a ParenListExpr. 1301 // FIXME: This isn't quite ideal, since our ASTs don't capture all 1302 // of the information that we have about the member 1303 // initializer. However, deconstructing the ASTs is a dicey process, 1304 // and this approach is far more likely to get the corner cases right. 1305 if (CurContext->isDependentContext()) { 1306 // Bump the reference count of all of the arguments. 1307 for (unsigned I = 0; I != NumArgs; ++I) 1308 Args[I]->Retain(); 1309 1310 OwningExprResult Init 1311 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs, 1312 RParenLoc)); 1313 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc, 1314 LParenLoc, 1315 Init.takeAs<Expr>(), 1316 RParenLoc); 1317 } 1318 1319 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc, 1320 LParenLoc, 1321 MemberInit.takeAs<Expr>(), 1322 RParenLoc); 1323} 1324 1325Sema::MemInitResult 1326Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 1327 Expr **Args, unsigned NumArgs, 1328 SourceLocation LParenLoc, SourceLocation RParenLoc, 1329 CXXRecordDecl *ClassDecl) { 1330 bool HasDependentArg = false; 1331 for (unsigned i = 0; i < NumArgs; i++) 1332 HasDependentArg |= Args[i]->isTypeDependent(); 1333 1334 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getSourceRange().getBegin(); 1335 if (BaseType->isDependentType() || HasDependentArg) { 1336 // Can't check initialization for a base of dependent type or when 1337 // any of the arguments are type-dependent expressions. 1338 OwningExprResult BaseInit 1339 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs, 1340 RParenLoc)); 1341 1342 // Erase any temporaries within this evaluation context; we're not 1343 // going to track them in the AST, since we'll be rebuilding the 1344 // ASTs during template instantiation. 1345 ExprTemporaries.erase( 1346 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries, 1347 ExprTemporaries.end()); 1348 1349 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo, 1350 /*IsVirtual=*/false, 1351 LParenLoc, 1352 BaseInit.takeAs<Expr>(), 1353 RParenLoc); 1354 } 1355 1356 if (!BaseType->isRecordType()) 1357 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 1358 << BaseType << BaseTInfo->getTypeLoc().getSourceRange(); 1359 1360 // C++ [class.base.init]p2: 1361 // [...] Unless the mem-initializer-id names a nonstatic data 1362 // member of the constructor’s class or a direct or virtual base 1363 // of that class, the mem-initializer is ill-formed. A 1364 // mem-initializer-list can initialize a base class using any 1365 // name that denotes that base class type. 1366 1367 // Check for direct and virtual base classes. 1368 const CXXBaseSpecifier *DirectBaseSpec = 0; 1369 const CXXBaseSpecifier *VirtualBaseSpec = 0; 1370 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 1371 VirtualBaseSpec); 1372 1373 // C++ [base.class.init]p2: 1374 // If a mem-initializer-id is ambiguous because it designates both 1375 // a direct non-virtual base class and an inherited virtual base 1376 // class, the mem-initializer is ill-formed. 1377 if (DirectBaseSpec && VirtualBaseSpec) 1378 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 1379 << BaseType << BaseTInfo->getTypeLoc().getSourceRange(); 1380 // C++ [base.class.init]p2: 1381 // Unless the mem-initializer-id names a nonstatic data membeer of the 1382 // constructor's class ot a direst or virtual base of that class, the 1383 // mem-initializer is ill-formed. 1384 if (!DirectBaseSpec && !VirtualBaseSpec) 1385 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 1386 << BaseType << ClassDecl->getNameAsCString() 1387 << BaseTInfo->getTypeLoc().getSourceRange(); 1388 1389 CXXBaseSpecifier *BaseSpec 1390 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec); 1391 if (!BaseSpec) 1392 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec); 1393 1394 // Initialize the base. 1395 InitializedEntity BaseEntity = 1396 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 1397 InitializationKind Kind = 1398 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc); 1399 1400 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs); 1401 1402 OwningExprResult BaseInit = 1403 InitSeq.Perform(*this, BaseEntity, Kind, 1404 MultiExprArg(*this, (void**)Args, NumArgs), 0); 1405 if (BaseInit.isInvalid()) 1406 return true; 1407 1408 // C++0x [class.base.init]p7: 1409 // The initialization of each base and member constitutes a 1410 // full-expression. 1411 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit)); 1412 if (BaseInit.isInvalid()) 1413 return true; 1414 1415 // If we are in a dependent context, template instantiation will 1416 // perform this type-checking again. Just save the arguments that we 1417 // received in a ParenListExpr. 1418 // FIXME: This isn't quite ideal, since our ASTs don't capture all 1419 // of the information that we have about the base 1420 // initializer. However, deconstructing the ASTs is a dicey process, 1421 // and this approach is far more likely to get the corner cases right. 1422 if (CurContext->isDependentContext()) { 1423 // Bump the reference count of all of the arguments. 1424 for (unsigned I = 0; I != NumArgs; ++I) 1425 Args[I]->Retain(); 1426 1427 OwningExprResult Init 1428 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs, 1429 RParenLoc)); 1430 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo, 1431 BaseSpec->isVirtual(), 1432 LParenLoc, 1433 Init.takeAs<Expr>(), 1434 RParenLoc); 1435 } 1436 1437 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo, 1438 BaseSpec->isVirtual(), 1439 LParenLoc, 1440 BaseInit.takeAs<Expr>(), 1441 RParenLoc); 1442} 1443 1444/// ImplicitInitializerKind - How an implicit base or member initializer should 1445/// initialize its base or member. 1446enum ImplicitInitializerKind { 1447 IIK_Default, 1448 IIK_Copy, 1449 IIK_Move 1450}; 1451 1452static bool 1453BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 1454 ImplicitInitializerKind ImplicitInitKind, 1455 CXXBaseSpecifier *BaseSpec, 1456 bool IsInheritedVirtualBase, 1457 CXXBaseOrMemberInitializer *&CXXBaseInit) { 1458 InitializedEntity InitEntity 1459 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 1460 IsInheritedVirtualBase); 1461 1462 Sema::OwningExprResult BaseInit(SemaRef); 1463 1464 switch (ImplicitInitKind) { 1465 case IIK_Default: { 1466 InitializationKind InitKind 1467 = InitializationKind::CreateDefault(Constructor->getLocation()); 1468 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0); 1469 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, 1470 Sema::MultiExprArg(SemaRef, 0, 0)); 1471 break; 1472 } 1473 1474 case IIK_Copy: { 1475 ParmVarDecl *Param = Constructor->getParamDecl(0); 1476 QualType ParamType = Param->getType().getNonReferenceType(); 1477 1478 Expr *CopyCtorArg = 1479 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param, 1480 SourceLocation(), ParamType, 0); 1481 1482 InitializationKind InitKind 1483 = InitializationKind::CreateDirect(Constructor->getLocation(), 1484 SourceLocation(), SourceLocation()); 1485 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 1486 &CopyCtorArg, 1); 1487 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, 1488 Sema::MultiExprArg(SemaRef, 1489 (void**)&CopyCtorArg, 1)); 1490 break; 1491 } 1492 1493 case IIK_Move: 1494 assert(false && "Unhandled initializer kind!"); 1495 } 1496 1497 BaseInit = SemaRef.MaybeCreateCXXExprWithTemporaries(move(BaseInit)); 1498 if (BaseInit.isInvalid()) 1499 return true; 1500 1501 CXXBaseInit = 1502 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context, 1503 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 1504 SourceLocation()), 1505 BaseSpec->isVirtual(), 1506 SourceLocation(), 1507 BaseInit.takeAs<Expr>(), 1508 SourceLocation()); 1509 1510 return false; 1511} 1512 1513static bool 1514BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 1515 ImplicitInitializerKind ImplicitInitKind, 1516 FieldDecl *Field, 1517 CXXBaseOrMemberInitializer *&CXXMemberInit) { 1518 if (ImplicitInitKind == IIK_Copy) { 1519 ParmVarDecl *Param = Constructor->getParamDecl(0); 1520 QualType ParamType = Param->getType().getNonReferenceType(); 1521 1522 Expr *MemberExprBase = 1523 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param, 1524 SourceLocation(), ParamType, 0); 1525 1526 1527 Expr *CopyCtorArg = 1528 MemberExpr::Create(SemaRef.Context, MemberExprBase, /*IsArrow=*/false, 1529 0, SourceRange(), Field, 1530 DeclAccessPair::make(Field, Field->getAccess()), 1531 SourceLocation(), 0, 1532 Field->getType().getNonReferenceType()); 1533 1534 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 1535 InitializationKind InitKind = 1536 InitializationKind::CreateDirect(Constructor->getLocation(), 1537 SourceLocation(), SourceLocation()); 1538 1539 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 1540 &CopyCtorArg, 1); 1541 1542 Sema::OwningExprResult MemberInit = 1543 InitSeq.Perform(SemaRef, InitEntity, InitKind, 1544 Sema::MultiExprArg(SemaRef, (void**)&CopyCtorArg, 1), 0); 1545 if (MemberInit.isInvalid()) 1546 return true; 1547 1548 CXXMemberInit = 0; 1549 return false; 1550 } 1551 1552 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!"); 1553 1554 QualType FieldBaseElementType = 1555 SemaRef.Context.getBaseElementType(Field->getType()); 1556 1557 if (FieldBaseElementType->isRecordType()) { 1558 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 1559 InitializationKind InitKind = 1560 InitializationKind::CreateDefault(Constructor->getLocation()); 1561 1562 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0); 1563 Sema::OwningExprResult MemberInit = 1564 InitSeq.Perform(SemaRef, InitEntity, InitKind, 1565 Sema::MultiExprArg(SemaRef, 0, 0)); 1566 MemberInit = SemaRef.MaybeCreateCXXExprWithTemporaries(move(MemberInit)); 1567 if (MemberInit.isInvalid()) 1568 return true; 1569 1570 CXXMemberInit = 1571 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context, 1572 Field, SourceLocation(), 1573 SourceLocation(), 1574 MemberInit.takeAs<Expr>(), 1575 SourceLocation()); 1576 return false; 1577 } 1578 1579 if (FieldBaseElementType->isReferenceType()) { 1580 SemaRef.Diag(Constructor->getLocation(), 1581 diag::err_uninitialized_member_in_ctor) 1582 << (int)Constructor->isImplicit() 1583 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 1584 << 0 << Field->getDeclName(); 1585 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 1586 return true; 1587 } 1588 1589 if (FieldBaseElementType.isConstQualified()) { 1590 SemaRef.Diag(Constructor->getLocation(), 1591 diag::err_uninitialized_member_in_ctor) 1592 << (int)Constructor->isImplicit() 1593 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 1594 << 1 << Field->getDeclName(); 1595 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 1596 return true; 1597 } 1598 1599 // Nothing to initialize. 1600 CXXMemberInit = 0; 1601 return false; 1602} 1603 1604bool 1605Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor, 1606 CXXBaseOrMemberInitializer **Initializers, 1607 unsigned NumInitializers, 1608 bool AnyErrors) { 1609 if (Constructor->getDeclContext()->isDependentContext()) { 1610 // Just store the initializers as written, they will be checked during 1611 // instantiation. 1612 if (NumInitializers > 0) { 1613 Constructor->setNumBaseOrMemberInitializers(NumInitializers); 1614 CXXBaseOrMemberInitializer **baseOrMemberInitializers = 1615 new (Context) CXXBaseOrMemberInitializer*[NumInitializers]; 1616 memcpy(baseOrMemberInitializers, Initializers, 1617 NumInitializers * sizeof(CXXBaseOrMemberInitializer*)); 1618 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers); 1619 } 1620 1621 return false; 1622 } 1623 1624 ImplicitInitializerKind ImplicitInitKind = IIK_Default; 1625 1626 // FIXME: Handle implicit move constructors. 1627 if (Constructor->isImplicit() && Constructor->isCopyConstructor()) 1628 ImplicitInitKind = IIK_Copy; 1629 1630 // We need to build the initializer AST according to order of construction 1631 // and not what user specified in the Initializers list. 1632 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 1633 if (!ClassDecl) 1634 return true; 1635 1636 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit; 1637 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields; 1638 bool HadError = false; 1639 1640 for (unsigned i = 0; i < NumInitializers; i++) { 1641 CXXBaseOrMemberInitializer *Member = Initializers[i]; 1642 1643 if (Member->isBaseInitializer()) 1644 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 1645 else 1646 AllBaseFields[Member->getMember()] = Member; 1647 } 1648 1649 // Keep track of the direct virtual bases. 1650 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 1651 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(), 1652 E = ClassDecl->bases_end(); I != E; ++I) { 1653 if (I->isVirtual()) 1654 DirectVBases.insert(I); 1655 } 1656 1657 // Push virtual bases before others. 1658 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 1659 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 1660 1661 if (CXXBaseOrMemberInitializer *Value 1662 = AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) { 1663 AllToInit.push_back(Value); 1664 } else if (!AnyErrors) { 1665 bool IsInheritedVirtualBase = !DirectVBases.count(VBase); 1666 CXXBaseOrMemberInitializer *CXXBaseInit; 1667 if (BuildImplicitBaseInitializer(*this, Constructor, ImplicitInitKind, 1668 VBase, IsInheritedVirtualBase, 1669 CXXBaseInit)) { 1670 HadError = true; 1671 continue; 1672 } 1673 1674 AllToInit.push_back(CXXBaseInit); 1675 } 1676 } 1677 1678 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 1679 E = ClassDecl->bases_end(); Base != E; ++Base) { 1680 // Virtuals are in the virtual base list and already constructed. 1681 if (Base->isVirtual()) 1682 continue; 1683 1684 if (CXXBaseOrMemberInitializer *Value 1685 = AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) { 1686 AllToInit.push_back(Value); 1687 } else if (!AnyErrors) { 1688 CXXBaseOrMemberInitializer *CXXBaseInit; 1689 if (BuildImplicitBaseInitializer(*this, Constructor, ImplicitInitKind, 1690 Base, /*IsInheritedVirtualBase=*/false, 1691 CXXBaseInit)) { 1692 HadError = true; 1693 continue; 1694 } 1695 1696 AllToInit.push_back(CXXBaseInit); 1697 } 1698 } 1699 1700 // non-static data members. 1701 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 1702 E = ClassDecl->field_end(); Field != E; ++Field) { 1703 if ((*Field)->isAnonymousStructOrUnion()) { 1704 if (const RecordType *FieldClassType = 1705 Field->getType()->getAs<RecordType>()) { 1706 CXXRecordDecl *FieldClassDecl 1707 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 1708 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(), 1709 EA = FieldClassDecl->field_end(); FA != EA; FA++) { 1710 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) { 1711 // 'Member' is the anonymous union field and 'AnonUnionMember' is 1712 // set to the anonymous union data member used in the initializer 1713 // list. 1714 Value->setMember(*Field); 1715 Value->setAnonUnionMember(*FA); 1716 AllToInit.push_back(Value); 1717 break; 1718 } 1719 } 1720 } 1721 continue; 1722 } 1723 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) { 1724 AllToInit.push_back(Value); 1725 continue; 1726 } 1727 1728 if (AnyErrors) 1729 continue; 1730 1731 CXXBaseOrMemberInitializer *Member; 1732 if (BuildImplicitMemberInitializer(*this, Constructor, ImplicitInitKind, 1733 *Field, Member)) { 1734 HadError = true; 1735 continue; 1736 } 1737 1738 // If the member doesn't need to be initialized, it will be null. 1739 if (Member) 1740 AllToInit.push_back(Member); 1741 } 1742 1743 NumInitializers = AllToInit.size(); 1744 if (NumInitializers > 0) { 1745 Constructor->setNumBaseOrMemberInitializers(NumInitializers); 1746 CXXBaseOrMemberInitializer **baseOrMemberInitializers = 1747 new (Context) CXXBaseOrMemberInitializer*[NumInitializers]; 1748 memcpy(baseOrMemberInitializers, AllToInit.data(), 1749 NumInitializers * sizeof(CXXBaseOrMemberInitializer*)); 1750 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers); 1751 1752 // Constructors implicitly reference the base and member 1753 // destructors. 1754 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 1755 Constructor->getParent()); 1756 } 1757 1758 return HadError; 1759} 1760 1761static void *GetKeyForTopLevelField(FieldDecl *Field) { 1762 // For anonymous unions, use the class declaration as the key. 1763 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 1764 if (RT->getDecl()->isAnonymousStructOrUnion()) 1765 return static_cast<void *>(RT->getDecl()); 1766 } 1767 return static_cast<void *>(Field); 1768} 1769 1770static void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 1771 return Context.getCanonicalType(BaseType).getTypePtr(); 1772} 1773 1774static void *GetKeyForMember(ASTContext &Context, 1775 CXXBaseOrMemberInitializer *Member, 1776 bool MemberMaybeAnon = false) { 1777 if (!Member->isMemberInitializer()) 1778 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 1779 1780 // For fields injected into the class via declaration of an anonymous union, 1781 // use its anonymous union class declaration as the unique key. 1782 FieldDecl *Field = Member->getMember(); 1783 1784 // After SetBaseOrMemberInitializers call, Field is the anonymous union 1785 // data member of the class. Data member used in the initializer list is 1786 // in AnonUnionMember field. 1787 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion()) 1788 Field = Member->getAnonUnionMember(); 1789 1790 // If the field is a member of an anonymous struct or union, our key 1791 // is the anonymous record decl that's a direct child of the class. 1792 RecordDecl *RD = Field->getParent(); 1793 if (RD->isAnonymousStructOrUnion()) { 1794 while (true) { 1795 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext()); 1796 if (Parent->isAnonymousStructOrUnion()) 1797 RD = Parent; 1798 else 1799 break; 1800 } 1801 1802 return static_cast<void *>(RD); 1803 } 1804 1805 return static_cast<void *>(Field); 1806} 1807 1808static void 1809DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef, 1810 const CXXConstructorDecl *Constructor, 1811 CXXBaseOrMemberInitializer **Inits, 1812 unsigned NumInits) { 1813 if (Constructor->getDeclContext()->isDependentContext()) 1814 return; 1815 1816 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order) 1817 == Diagnostic::Ignored) 1818 return; 1819 1820 // Build the list of bases and members in the order that they'll 1821 // actually be initialized. The explicit initializers should be in 1822 // this same order but may be missing things. 1823 llvm::SmallVector<const void*, 32> IdealInitKeys; 1824 1825 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 1826 1827 // 1. Virtual bases. 1828 for (CXXRecordDecl::base_class_const_iterator VBase = 1829 ClassDecl->vbases_begin(), 1830 E = ClassDecl->vbases_end(); VBase != E; ++VBase) 1831 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType())); 1832 1833 // 2. Non-virtual bases. 1834 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(), 1835 E = ClassDecl->bases_end(); Base != E; ++Base) { 1836 if (Base->isVirtual()) 1837 continue; 1838 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType())); 1839 } 1840 1841 // 3. Direct fields. 1842 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 1843 E = ClassDecl->field_end(); Field != E; ++Field) 1844 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field)); 1845 1846 unsigned NumIdealInits = IdealInitKeys.size(); 1847 unsigned IdealIndex = 0; 1848 1849 CXXBaseOrMemberInitializer *PrevInit = 0; 1850 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) { 1851 CXXBaseOrMemberInitializer *Init = Inits[InitIndex]; 1852 void *InitKey = GetKeyForMember(SemaRef.Context, Init, true); 1853 1854 // Scan forward to try to find this initializer in the idealized 1855 // initializers list. 1856 for (; IdealIndex != NumIdealInits; ++IdealIndex) 1857 if (InitKey == IdealInitKeys[IdealIndex]) 1858 break; 1859 1860 // If we didn't find this initializer, it must be because we 1861 // scanned past it on a previous iteration. That can only 1862 // happen if we're out of order; emit a warning. 1863 if (IdealIndex == NumIdealInits) { 1864 assert(PrevInit && "initializer not found in initializer list"); 1865 1866 Sema::SemaDiagnosticBuilder D = 1867 SemaRef.Diag(PrevInit->getSourceLocation(), 1868 diag::warn_initializer_out_of_order); 1869 1870 if (PrevInit->isMemberInitializer()) 1871 D << 0 << PrevInit->getMember()->getDeclName(); 1872 else 1873 D << 1 << PrevInit->getBaseClassInfo()->getType(); 1874 1875 if (Init->isMemberInitializer()) 1876 D << 0 << Init->getMember()->getDeclName(); 1877 else 1878 D << 1 << Init->getBaseClassInfo()->getType(); 1879 1880 // Move back to the initializer's location in the ideal list. 1881 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 1882 if (InitKey == IdealInitKeys[IdealIndex]) 1883 break; 1884 1885 assert(IdealIndex != NumIdealInits && 1886 "initializer not found in initializer list"); 1887 } 1888 1889 PrevInit = Init; 1890 } 1891} 1892 1893namespace { 1894bool CheckRedundantInit(Sema &S, 1895 CXXBaseOrMemberInitializer *Init, 1896 CXXBaseOrMemberInitializer *&PrevInit) { 1897 if (!PrevInit) { 1898 PrevInit = Init; 1899 return false; 1900 } 1901 1902 if (FieldDecl *Field = Init->getMember()) 1903 S.Diag(Init->getSourceLocation(), 1904 diag::err_multiple_mem_initialization) 1905 << Field->getDeclName() 1906 << Init->getSourceRange(); 1907 else { 1908 Type *BaseClass = Init->getBaseClass(); 1909 assert(BaseClass && "neither field nor base"); 1910 S.Diag(Init->getSourceLocation(), 1911 diag::err_multiple_base_initialization) 1912 << QualType(BaseClass, 0) 1913 << Init->getSourceRange(); 1914 } 1915 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 1916 << 0 << PrevInit->getSourceRange(); 1917 1918 return true; 1919} 1920 1921typedef std::pair<NamedDecl *, CXXBaseOrMemberInitializer *> UnionEntry; 1922typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 1923 1924bool CheckRedundantUnionInit(Sema &S, 1925 CXXBaseOrMemberInitializer *Init, 1926 RedundantUnionMap &Unions) { 1927 FieldDecl *Field = Init->getMember(); 1928 RecordDecl *Parent = Field->getParent(); 1929 if (!Parent->isAnonymousStructOrUnion()) 1930 return false; 1931 1932 NamedDecl *Child = Field; 1933 do { 1934 if (Parent->isUnion()) { 1935 UnionEntry &En = Unions[Parent]; 1936 if (En.first && En.first != Child) { 1937 S.Diag(Init->getSourceLocation(), 1938 diag::err_multiple_mem_union_initialization) 1939 << Field->getDeclName() 1940 << Init->getSourceRange(); 1941 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 1942 << 0 << En.second->getSourceRange(); 1943 return true; 1944 } else if (!En.first) { 1945 En.first = Child; 1946 En.second = Init; 1947 } 1948 } 1949 1950 Child = Parent; 1951 Parent = cast<RecordDecl>(Parent->getDeclContext()); 1952 } while (Parent->isAnonymousStructOrUnion()); 1953 1954 return false; 1955} 1956} 1957 1958/// ActOnMemInitializers - Handle the member initializers for a constructor. 1959void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl, 1960 SourceLocation ColonLoc, 1961 MemInitTy **meminits, unsigned NumMemInits, 1962 bool AnyErrors) { 1963 if (!ConstructorDecl) 1964 return; 1965 1966 AdjustDeclIfTemplate(ConstructorDecl); 1967 1968 CXXConstructorDecl *Constructor 1969 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>()); 1970 1971 if (!Constructor) { 1972 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 1973 return; 1974 } 1975 1976 CXXBaseOrMemberInitializer **MemInits = 1977 reinterpret_cast<CXXBaseOrMemberInitializer **>(meminits); 1978 1979 // Mapping for the duplicate initializers check. 1980 // For member initializers, this is keyed with a FieldDecl*. 1981 // For base initializers, this is keyed with a Type*. 1982 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *> Members; 1983 1984 // Mapping for the inconsistent anonymous-union initializers check. 1985 RedundantUnionMap MemberUnions; 1986 1987 bool HadError = false; 1988 for (unsigned i = 0; i < NumMemInits; i++) { 1989 CXXBaseOrMemberInitializer *Init = MemInits[i]; 1990 1991 if (Init->isMemberInitializer()) { 1992 FieldDecl *Field = Init->getMember(); 1993 if (CheckRedundantInit(*this, Init, Members[Field]) || 1994 CheckRedundantUnionInit(*this, Init, MemberUnions)) 1995 HadError = true; 1996 } else { 1997 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0)); 1998 if (CheckRedundantInit(*this, Init, Members[Key])) 1999 HadError = true; 2000 } 2001 } 2002 2003 if (HadError) 2004 return; 2005 2006 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits); 2007 2008 SetBaseOrMemberInitializers(Constructor, MemInits, NumMemInits, AnyErrors); 2009} 2010 2011void 2012Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 2013 CXXRecordDecl *ClassDecl) { 2014 // Ignore dependent contexts. 2015 if (ClassDecl->isDependentContext()) 2016 return; 2017 2018 // FIXME: all the access-control diagnostics are positioned on the 2019 // field/base declaration. That's probably good; that said, the 2020 // user might reasonably want to know why the destructor is being 2021 // emitted, and we currently don't say. 2022 2023 // Non-static data members. 2024 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(), 2025 E = ClassDecl->field_end(); I != E; ++I) { 2026 FieldDecl *Field = *I; 2027 2028 QualType FieldType = Context.getBaseElementType(Field->getType()); 2029 2030 const RecordType* RT = FieldType->getAs<RecordType>(); 2031 if (!RT) 2032 continue; 2033 2034 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 2035 if (FieldClassDecl->hasTrivialDestructor()) 2036 continue; 2037 2038 CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor(Context); 2039 CheckDestructorAccess(Field->getLocation(), Dtor, 2040 PDiag(diag::err_access_dtor_field) 2041 << Field->getDeclName() 2042 << FieldType); 2043 2044 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 2045 } 2046 2047 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 2048 2049 // Bases. 2050 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 2051 E = ClassDecl->bases_end(); Base != E; ++Base) { 2052 // Bases are always records in a well-formed non-dependent class. 2053 const RecordType *RT = Base->getType()->getAs<RecordType>(); 2054 2055 // Remember direct virtual bases. 2056 if (Base->isVirtual()) 2057 DirectVirtualBases.insert(RT); 2058 2059 // Ignore trivial destructors. 2060 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 2061 if (BaseClassDecl->hasTrivialDestructor()) 2062 continue; 2063 2064 CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context); 2065 2066 // FIXME: caret should be on the start of the class name 2067 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor, 2068 PDiag(diag::err_access_dtor_base) 2069 << Base->getType() 2070 << Base->getSourceRange()); 2071 2072 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 2073 } 2074 2075 // Virtual bases. 2076 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 2077 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 2078 2079 // Bases are always records in a well-formed non-dependent class. 2080 const RecordType *RT = VBase->getType()->getAs<RecordType>(); 2081 2082 // Ignore direct virtual bases. 2083 if (DirectVirtualBases.count(RT)) 2084 continue; 2085 2086 // Ignore trivial destructors. 2087 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 2088 if (BaseClassDecl->hasTrivialDestructor()) 2089 continue; 2090 2091 CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context); 2092 CheckDestructorAccess(ClassDecl->getLocation(), Dtor, 2093 PDiag(diag::err_access_dtor_vbase) 2094 << VBase->getType()); 2095 2096 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 2097 } 2098} 2099 2100void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) { 2101 if (!CDtorDecl) 2102 return; 2103 2104 if (CXXConstructorDecl *Constructor 2105 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>())) 2106 SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false); 2107} 2108 2109bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 2110 unsigned DiagID, AbstractDiagSelID SelID, 2111 const CXXRecordDecl *CurrentRD) { 2112 if (SelID == -1) 2113 return RequireNonAbstractType(Loc, T, 2114 PDiag(DiagID), CurrentRD); 2115 else 2116 return RequireNonAbstractType(Loc, T, 2117 PDiag(DiagID) << SelID, CurrentRD); 2118} 2119 2120bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 2121 const PartialDiagnostic &PD, 2122 const CXXRecordDecl *CurrentRD) { 2123 if (!getLangOptions().CPlusPlus) 2124 return false; 2125 2126 if (const ArrayType *AT = Context.getAsArrayType(T)) 2127 return RequireNonAbstractType(Loc, AT->getElementType(), PD, 2128 CurrentRD); 2129 2130 if (const PointerType *PT = T->getAs<PointerType>()) { 2131 // Find the innermost pointer type. 2132 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 2133 PT = T; 2134 2135 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 2136 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD); 2137 } 2138 2139 const RecordType *RT = T->getAs<RecordType>(); 2140 if (!RT) 2141 return false; 2142 2143 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 2144 2145 if (CurrentRD && CurrentRD != RD) 2146 return false; 2147 2148 // FIXME: is this reasonable? It matches current behavior, but.... 2149 if (!RD->getDefinition()) 2150 return false; 2151 2152 if (!RD->isAbstract()) 2153 return false; 2154 2155 Diag(Loc, PD) << RD->getDeclName(); 2156 2157 // Check if we've already emitted the list of pure virtual functions for this 2158 // class. 2159 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 2160 return true; 2161 2162 CXXFinalOverriderMap FinalOverriders; 2163 RD->getFinalOverriders(FinalOverriders); 2164 2165 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 2166 MEnd = FinalOverriders.end(); 2167 M != MEnd; 2168 ++M) { 2169 for (OverridingMethods::iterator SO = M->second.begin(), 2170 SOEnd = M->second.end(); 2171 SO != SOEnd; ++SO) { 2172 // C++ [class.abstract]p4: 2173 // A class is abstract if it contains or inherits at least one 2174 // pure virtual function for which the final overrider is pure 2175 // virtual. 2176 2177 // 2178 if (SO->second.size() != 1) 2179 continue; 2180 2181 if (!SO->second.front().Method->isPure()) 2182 continue; 2183 2184 Diag(SO->second.front().Method->getLocation(), 2185 diag::note_pure_virtual_function) 2186 << SO->second.front().Method->getDeclName(); 2187 } 2188 } 2189 2190 if (!PureVirtualClassDiagSet) 2191 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 2192 PureVirtualClassDiagSet->insert(RD); 2193 2194 return true; 2195} 2196 2197namespace { 2198 class AbstractClassUsageDiagnoser 2199 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> { 2200 Sema &SemaRef; 2201 CXXRecordDecl *AbstractClass; 2202 2203 bool VisitDeclContext(const DeclContext *DC) { 2204 bool Invalid = false; 2205 2206 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(), 2207 E = DC->decls_end(); I != E; ++I) 2208 Invalid |= Visit(*I); 2209 2210 return Invalid; 2211 } 2212 2213 public: 2214 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac) 2215 : SemaRef(SemaRef), AbstractClass(ac) { 2216 Visit(SemaRef.Context.getTranslationUnitDecl()); 2217 } 2218 2219 bool VisitFunctionDecl(const FunctionDecl *FD) { 2220 if (FD->isThisDeclarationADefinition()) { 2221 // No need to do the check if we're in a definition, because it requires 2222 // that the return/param types are complete. 2223 // because that requires 2224 return VisitDeclContext(FD); 2225 } 2226 2227 // Check the return type. 2228 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType(); 2229 bool Invalid = 2230 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy, 2231 diag::err_abstract_type_in_decl, 2232 Sema::AbstractReturnType, 2233 AbstractClass); 2234 2235 for (FunctionDecl::param_const_iterator I = FD->param_begin(), 2236 E = FD->param_end(); I != E; ++I) { 2237 const ParmVarDecl *VD = *I; 2238 Invalid |= 2239 SemaRef.RequireNonAbstractType(VD->getLocation(), 2240 VD->getOriginalType(), 2241 diag::err_abstract_type_in_decl, 2242 Sema::AbstractParamType, 2243 AbstractClass); 2244 } 2245 2246 return Invalid; 2247 } 2248 2249 bool VisitDecl(const Decl* D) { 2250 if (const DeclContext *DC = dyn_cast<DeclContext>(D)) 2251 return VisitDeclContext(DC); 2252 2253 return false; 2254 } 2255 }; 2256} 2257 2258/// \brief Perform semantic checks on a class definition that has been 2259/// completing, introducing implicitly-declared members, checking for 2260/// abstract types, etc. 2261void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) { 2262 if (!Record || Record->isInvalidDecl()) 2263 return; 2264 2265 if (!Record->isDependentType()) 2266 AddImplicitlyDeclaredMembersToClass(S, Record); 2267 2268 if (Record->isInvalidDecl()) 2269 return; 2270 2271 // Set access bits correctly on the directly-declared conversions. 2272 UnresolvedSetImpl *Convs = Record->getConversionFunctions(); 2273 for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end(); I != E; ++I) 2274 Convs->setAccess(I, (*I)->getAccess()); 2275 2276 // Determine whether we need to check for final overriders. We do 2277 // this either when there are virtual base classes (in which case we 2278 // may end up finding multiple final overriders for a given virtual 2279 // function) or any of the base classes is abstract (in which case 2280 // we might detect that this class is abstract). 2281 bool CheckFinalOverriders = false; 2282 if (Record->isPolymorphic() && !Record->isInvalidDecl() && 2283 !Record->isDependentType()) { 2284 if (Record->getNumVBases()) 2285 CheckFinalOverriders = true; 2286 else if (!Record->isAbstract()) { 2287 for (CXXRecordDecl::base_class_const_iterator B = Record->bases_begin(), 2288 BEnd = Record->bases_end(); 2289 B != BEnd; ++B) { 2290 CXXRecordDecl *BaseDecl 2291 = cast<CXXRecordDecl>(B->getType()->getAs<RecordType>()->getDecl()); 2292 if (BaseDecl->isAbstract()) { 2293 CheckFinalOverriders = true; 2294 break; 2295 } 2296 } 2297 } 2298 } 2299 2300 if (CheckFinalOverriders) { 2301 CXXFinalOverriderMap FinalOverriders; 2302 Record->getFinalOverriders(FinalOverriders); 2303 2304 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 2305 MEnd = FinalOverriders.end(); 2306 M != MEnd; ++M) { 2307 for (OverridingMethods::iterator SO = M->second.begin(), 2308 SOEnd = M->second.end(); 2309 SO != SOEnd; ++SO) { 2310 assert(SO->second.size() > 0 && 2311 "All virtual functions have overridding virtual functions"); 2312 if (SO->second.size() == 1) { 2313 // C++ [class.abstract]p4: 2314 // A class is abstract if it contains or inherits at least one 2315 // pure virtual function for which the final overrider is pure 2316 // virtual. 2317 if (SO->second.front().Method->isPure()) 2318 Record->setAbstract(true); 2319 continue; 2320 } 2321 2322 // C++ [class.virtual]p2: 2323 // In a derived class, if a virtual member function of a base 2324 // class subobject has more than one final overrider the 2325 // program is ill-formed. 2326 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 2327 << (NamedDecl *)M->first << Record; 2328 Diag(M->first->getLocation(), diag::note_overridden_virtual_function); 2329 for (OverridingMethods::overriding_iterator OM = SO->second.begin(), 2330 OMEnd = SO->second.end(); 2331 OM != OMEnd; ++OM) 2332 Diag(OM->Method->getLocation(), diag::note_final_overrider) 2333 << (NamedDecl *)M->first << OM->Method->getParent(); 2334 2335 Record->setInvalidDecl(); 2336 } 2337 } 2338 } 2339 2340 if (Record->isAbstract() && !Record->isInvalidDecl()) 2341 (void)AbstractClassUsageDiagnoser(*this, Record); 2342 2343 // If this is not an aggregate type and has no user-declared constructor, 2344 // complain about any non-static data members of reference or const scalar 2345 // type, since they will never get initializers. 2346 if (!Record->isInvalidDecl() && !Record->isDependentType() && 2347 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) { 2348 bool Complained = false; 2349 for (RecordDecl::field_iterator F = Record->field_begin(), 2350 FEnd = Record->field_end(); 2351 F != FEnd; ++F) { 2352 if (F->getType()->isReferenceType() || 2353 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 2354 if (!Complained) { 2355 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 2356 << Record->getTagKind() << Record; 2357 Complained = true; 2358 } 2359 2360 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 2361 << F->getType()->isReferenceType() 2362 << F->getDeclName(); 2363 } 2364 } 2365 } 2366} 2367 2368void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 2369 DeclPtrTy TagDecl, 2370 SourceLocation LBrac, 2371 SourceLocation RBrac, 2372 AttributeList *AttrList) { 2373 if (!TagDecl) 2374 return; 2375 2376 AdjustDeclIfTemplate(TagDecl); 2377 2378 ActOnFields(S, RLoc, TagDecl, 2379 (DeclPtrTy*)FieldCollector->getCurFields(), 2380 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList); 2381 2382 CheckCompletedCXXClass(S, 2383 dyn_cast_or_null<CXXRecordDecl>(TagDecl.getAs<Decl>())); 2384} 2385 2386/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 2387/// special functions, such as the default constructor, copy 2388/// constructor, or destructor, to the given C++ class (C++ 2389/// [special]p1). This routine can only be executed just before the 2390/// definition of the class is complete. 2391/// 2392/// The scope, if provided, is the class scope. 2393void Sema::AddImplicitlyDeclaredMembersToClass(Scope *S, 2394 CXXRecordDecl *ClassDecl) { 2395 CanQualType ClassType 2396 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 2397 2398 // FIXME: Implicit declarations have exception specifications, which are 2399 // the union of the specifications of the implicitly called functions. 2400 2401 if (!ClassDecl->hasUserDeclaredConstructor()) { 2402 // C++ [class.ctor]p5: 2403 // A default constructor for a class X is a constructor of class X 2404 // that can be called without an argument. If there is no 2405 // user-declared constructor for class X, a default constructor is 2406 // implicitly declared. An implicitly-declared default constructor 2407 // is an inline public member of its class. 2408 DeclarationName Name 2409 = Context.DeclarationNames.getCXXConstructorName(ClassType); 2410 CXXConstructorDecl *DefaultCon = 2411 CXXConstructorDecl::Create(Context, ClassDecl, 2412 ClassDecl->getLocation(), Name, 2413 Context.getFunctionType(Context.VoidTy, 2414 0, 0, false, 0, 2415 /*FIXME*/false, false, 2416 0, 0, 2417 FunctionType::ExtInfo()), 2418 /*TInfo=*/0, 2419 /*isExplicit=*/false, 2420 /*isInline=*/true, 2421 /*isImplicitlyDeclared=*/true); 2422 DefaultCon->setAccess(AS_public); 2423 DefaultCon->setImplicit(); 2424 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor()); 2425 if (S) 2426 PushOnScopeChains(DefaultCon, S, true); 2427 else 2428 ClassDecl->addDecl(DefaultCon); 2429 } 2430 2431 if (!ClassDecl->hasUserDeclaredCopyConstructor()) { 2432 // C++ [class.copy]p4: 2433 // If the class definition does not explicitly declare a copy 2434 // constructor, one is declared implicitly. 2435 2436 // C++ [class.copy]p5: 2437 // The implicitly-declared copy constructor for a class X will 2438 // have the form 2439 // 2440 // X::X(const X&) 2441 // 2442 // if 2443 bool HasConstCopyConstructor = true; 2444 2445 // -- each direct or virtual base class B of X has a copy 2446 // constructor whose first parameter is of type const B& or 2447 // const volatile B&, and 2448 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(); 2449 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) { 2450 const CXXRecordDecl *BaseClassDecl 2451 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 2452 HasConstCopyConstructor 2453 = BaseClassDecl->hasConstCopyConstructor(Context); 2454 } 2455 2456 // -- for all the nonstatic data members of X that are of a 2457 // class type M (or array thereof), each such class type 2458 // has a copy constructor whose first parameter is of type 2459 // const M& or const volatile M&. 2460 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(); 2461 HasConstCopyConstructor && Field != ClassDecl->field_end(); 2462 ++Field) { 2463 QualType FieldType = (*Field)->getType(); 2464 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 2465 FieldType = Array->getElementType(); 2466 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 2467 const CXXRecordDecl *FieldClassDecl 2468 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 2469 HasConstCopyConstructor 2470 = FieldClassDecl->hasConstCopyConstructor(Context); 2471 } 2472 } 2473 2474 // Otherwise, the implicitly declared copy constructor will have 2475 // the form 2476 // 2477 // X::X(X&) 2478 QualType ArgType = ClassType; 2479 if (HasConstCopyConstructor) 2480 ArgType = ArgType.withConst(); 2481 ArgType = Context.getLValueReferenceType(ArgType); 2482 2483 // An implicitly-declared copy constructor is an inline public 2484 // member of its class. 2485 DeclarationName Name 2486 = Context.DeclarationNames.getCXXConstructorName(ClassType); 2487 CXXConstructorDecl *CopyConstructor 2488 = CXXConstructorDecl::Create(Context, ClassDecl, 2489 ClassDecl->getLocation(), Name, 2490 Context.getFunctionType(Context.VoidTy, 2491 &ArgType, 1, 2492 false, 0, 2493 /*FIXME:*/false, 2494 false, 0, 0, 2495 FunctionType::ExtInfo()), 2496 /*TInfo=*/0, 2497 /*isExplicit=*/false, 2498 /*isInline=*/true, 2499 /*isImplicitlyDeclared=*/true); 2500 CopyConstructor->setAccess(AS_public); 2501 CopyConstructor->setImplicit(); 2502 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor()); 2503 2504 // Add the parameter to the constructor. 2505 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 2506 ClassDecl->getLocation(), 2507 /*IdentifierInfo=*/0, 2508 ArgType, /*TInfo=*/0, 2509 VarDecl::None, 2510 VarDecl::None, 0); 2511 CopyConstructor->setParams(&FromParam, 1); 2512 if (S) 2513 PushOnScopeChains(CopyConstructor, S, true); 2514 else 2515 ClassDecl->addDecl(CopyConstructor); 2516 } 2517 2518 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 2519 // Note: The following rules are largely analoguous to the copy 2520 // constructor rules. Note that virtual bases are not taken into account 2521 // for determining the argument type of the operator. Note also that 2522 // operators taking an object instead of a reference are allowed. 2523 // 2524 // C++ [class.copy]p10: 2525 // If the class definition does not explicitly declare a copy 2526 // assignment operator, one is declared implicitly. 2527 // The implicitly-defined copy assignment operator for a class X 2528 // will have the form 2529 // 2530 // X& X::operator=(const X&) 2531 // 2532 // if 2533 bool HasConstCopyAssignment = true; 2534 2535 // -- each direct base class B of X has a copy assignment operator 2536 // whose parameter is of type const B&, const volatile B& or B, 2537 // and 2538 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(); 2539 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) { 2540 assert(!Base->getType()->isDependentType() && 2541 "Cannot generate implicit members for class with dependent bases."); 2542 const CXXRecordDecl *BaseClassDecl 2543 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 2544 const CXXMethodDecl *MD = 0; 2545 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context, 2546 MD); 2547 } 2548 2549 // -- for all the nonstatic data members of X that are of a class 2550 // type M (or array thereof), each such class type has a copy 2551 // assignment operator whose parameter is of type const M&, 2552 // const volatile M& or M. 2553 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(); 2554 HasConstCopyAssignment && Field != ClassDecl->field_end(); 2555 ++Field) { 2556 QualType FieldType = (*Field)->getType(); 2557 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 2558 FieldType = Array->getElementType(); 2559 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 2560 const CXXRecordDecl *FieldClassDecl 2561 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 2562 const CXXMethodDecl *MD = 0; 2563 HasConstCopyAssignment 2564 = FieldClassDecl->hasConstCopyAssignment(Context, MD); 2565 } 2566 } 2567 2568 // Otherwise, the implicitly declared copy assignment operator will 2569 // have the form 2570 // 2571 // X& X::operator=(X&) 2572 QualType ArgType = ClassType; 2573 QualType RetType = Context.getLValueReferenceType(ArgType); 2574 if (HasConstCopyAssignment) 2575 ArgType = ArgType.withConst(); 2576 ArgType = Context.getLValueReferenceType(ArgType); 2577 2578 // An implicitly-declared copy assignment operator is an inline public 2579 // member of its class. 2580 DeclarationName Name = 2581 Context.DeclarationNames.getCXXOperatorName(OO_Equal); 2582 CXXMethodDecl *CopyAssignment = 2583 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name, 2584 Context.getFunctionType(RetType, &ArgType, 1, 2585 false, 0, 2586 /*FIXME:*/false, 2587 false, 0, 0, 2588 FunctionType::ExtInfo()), 2589 /*TInfo=*/0, /*isStatic=*/false, 2590 /*StorageClassAsWritten=*/FunctionDecl::None, 2591 /*isInline=*/true); 2592 CopyAssignment->setAccess(AS_public); 2593 CopyAssignment->setImplicit(); 2594 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment()); 2595 CopyAssignment->setCopyAssignment(true); 2596 2597 // Add the parameter to the operator. 2598 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 2599 ClassDecl->getLocation(), 2600 /*IdentifierInfo=*/0, 2601 ArgType, /*TInfo=*/0, 2602 VarDecl::None, 2603 VarDecl::None, 0); 2604 CopyAssignment->setParams(&FromParam, 1); 2605 2606 // Don't call addedAssignmentOperator. There is no way to distinguish an 2607 // implicit from an explicit assignment operator. 2608 if (S) 2609 PushOnScopeChains(CopyAssignment, S, true); 2610 else 2611 ClassDecl->addDecl(CopyAssignment); 2612 AddOverriddenMethods(ClassDecl, CopyAssignment); 2613 } 2614 2615 if (!ClassDecl->hasUserDeclaredDestructor()) { 2616 // C++ [class.dtor]p2: 2617 // If a class has no user-declared destructor, a destructor is 2618 // declared implicitly. An implicitly-declared destructor is an 2619 // inline public member of its class. 2620 QualType Ty = Context.getFunctionType(Context.VoidTy, 2621 0, 0, false, 0, 2622 /*FIXME:*/false, 2623 false, 0, 0, FunctionType::ExtInfo()); 2624 2625 DeclarationName Name 2626 = Context.DeclarationNames.getCXXDestructorName(ClassType); 2627 CXXDestructorDecl *Destructor 2628 = CXXDestructorDecl::Create(Context, ClassDecl, 2629 ClassDecl->getLocation(), Name, Ty, 2630 /*isInline=*/true, 2631 /*isImplicitlyDeclared=*/true); 2632 Destructor->setAccess(AS_public); 2633 Destructor->setImplicit(); 2634 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 2635 if (S) 2636 PushOnScopeChains(Destructor, S, true); 2637 else 2638 ClassDecl->addDecl(Destructor); 2639 2640 // This could be uniqued if it ever proves significant. 2641 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty)); 2642 2643 AddOverriddenMethods(ClassDecl, Destructor); 2644 } 2645} 2646 2647void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) { 2648 Decl *D = TemplateD.getAs<Decl>(); 2649 if (!D) 2650 return; 2651 2652 TemplateParameterList *Params = 0; 2653 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) 2654 Params = Template->getTemplateParameters(); 2655 else if (ClassTemplatePartialSpecializationDecl *PartialSpec 2656 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 2657 Params = PartialSpec->getTemplateParameters(); 2658 else 2659 return; 2660 2661 for (TemplateParameterList::iterator Param = Params->begin(), 2662 ParamEnd = Params->end(); 2663 Param != ParamEnd; ++Param) { 2664 NamedDecl *Named = cast<NamedDecl>(*Param); 2665 if (Named->getDeclName()) { 2666 S->AddDecl(DeclPtrTy::make(Named)); 2667 IdResolver.AddDecl(Named); 2668 } 2669 } 2670} 2671 2672void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) { 2673 if (!RecordD) return; 2674 AdjustDeclIfTemplate(RecordD); 2675 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD.getAs<Decl>()); 2676 PushDeclContext(S, Record); 2677} 2678 2679void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) { 2680 if (!RecordD) return; 2681 PopDeclContext(); 2682} 2683 2684/// ActOnStartDelayedCXXMethodDeclaration - We have completed 2685/// parsing a top-level (non-nested) C++ class, and we are now 2686/// parsing those parts of the given Method declaration that could 2687/// not be parsed earlier (C++ [class.mem]p2), such as default 2688/// arguments. This action should enter the scope of the given 2689/// Method declaration as if we had just parsed the qualified method 2690/// name. However, it should not bring the parameters into scope; 2691/// that will be performed by ActOnDelayedCXXMethodParameter. 2692void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) { 2693} 2694 2695/// ActOnDelayedCXXMethodParameter - We've already started a delayed 2696/// C++ method declaration. We're (re-)introducing the given 2697/// function parameter into scope for use in parsing later parts of 2698/// the method declaration. For example, we could see an 2699/// ActOnParamDefaultArgument event for this parameter. 2700void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) { 2701 if (!ParamD) 2702 return; 2703 2704 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>()); 2705 2706 // If this parameter has an unparsed default argument, clear it out 2707 // to make way for the parsed default argument. 2708 if (Param->hasUnparsedDefaultArg()) 2709 Param->setDefaultArg(0); 2710 2711 S->AddDecl(DeclPtrTy::make(Param)); 2712 if (Param->getDeclName()) 2713 IdResolver.AddDecl(Param); 2714} 2715 2716/// ActOnFinishDelayedCXXMethodDeclaration - We have finished 2717/// processing the delayed method declaration for Method. The method 2718/// declaration is now considered finished. There may be a separate 2719/// ActOnStartOfFunctionDef action later (not necessarily 2720/// immediately!) for this method, if it was also defined inside the 2721/// class body. 2722void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) { 2723 if (!MethodD) 2724 return; 2725 2726 AdjustDeclIfTemplate(MethodD); 2727 2728 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>()); 2729 2730 // Now that we have our default arguments, check the constructor 2731 // again. It could produce additional diagnostics or affect whether 2732 // the class has implicitly-declared destructors, among other 2733 // things. 2734 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 2735 CheckConstructor(Constructor); 2736 2737 // Check the default arguments, which we may have added. 2738 if (!Method->isInvalidDecl()) 2739 CheckCXXDefaultArguments(Method); 2740} 2741 2742/// CheckConstructorDeclarator - Called by ActOnDeclarator to check 2743/// the well-formedness of the constructor declarator @p D with type @p 2744/// R. If there are any errors in the declarator, this routine will 2745/// emit diagnostics and set the invalid bit to true. In any case, the type 2746/// will be updated to reflect a well-formed type for the constructor and 2747/// returned. 2748QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 2749 FunctionDecl::StorageClass &SC) { 2750 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 2751 2752 // C++ [class.ctor]p3: 2753 // A constructor shall not be virtual (10.3) or static (9.4). A 2754 // constructor can be invoked for a const, volatile or const 2755 // volatile object. A constructor shall not be declared const, 2756 // volatile, or const volatile (9.3.2). 2757 if (isVirtual) { 2758 if (!D.isInvalidType()) 2759 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 2760 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 2761 << SourceRange(D.getIdentifierLoc()); 2762 D.setInvalidType(); 2763 } 2764 if (SC == FunctionDecl::Static) { 2765 if (!D.isInvalidType()) 2766 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 2767 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 2768 << SourceRange(D.getIdentifierLoc()); 2769 D.setInvalidType(); 2770 SC = FunctionDecl::None; 2771 } 2772 2773 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 2774 if (FTI.TypeQuals != 0) { 2775 if (FTI.TypeQuals & Qualifiers::Const) 2776 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 2777 << "const" << SourceRange(D.getIdentifierLoc()); 2778 if (FTI.TypeQuals & Qualifiers::Volatile) 2779 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 2780 << "volatile" << SourceRange(D.getIdentifierLoc()); 2781 if (FTI.TypeQuals & Qualifiers::Restrict) 2782 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 2783 << "restrict" << SourceRange(D.getIdentifierLoc()); 2784 } 2785 2786 // Rebuild the function type "R" without any type qualifiers (in 2787 // case any of the errors above fired) and with "void" as the 2788 // return type, since constructors don't have return types. We 2789 // *always* have to do this, because GetTypeForDeclarator will 2790 // put in a result type of "int" when none was specified. 2791 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 2792 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(), 2793 Proto->getNumArgs(), 2794 Proto->isVariadic(), 0, 2795 Proto->hasExceptionSpec(), 2796 Proto->hasAnyExceptionSpec(), 2797 Proto->getNumExceptions(), 2798 Proto->exception_begin(), 2799 Proto->getExtInfo()); 2800} 2801 2802/// CheckConstructor - Checks a fully-formed constructor for 2803/// well-formedness, issuing any diagnostics required. Returns true if 2804/// the constructor declarator is invalid. 2805void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 2806 CXXRecordDecl *ClassDecl 2807 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 2808 if (!ClassDecl) 2809 return Constructor->setInvalidDecl(); 2810 2811 // C++ [class.copy]p3: 2812 // A declaration of a constructor for a class X is ill-formed if 2813 // its first parameter is of type (optionally cv-qualified) X and 2814 // either there are no other parameters or else all other 2815 // parameters have default arguments. 2816 if (!Constructor->isInvalidDecl() && 2817 ((Constructor->getNumParams() == 1) || 2818 (Constructor->getNumParams() > 1 && 2819 Constructor->getParamDecl(1)->hasDefaultArg())) && 2820 Constructor->getTemplateSpecializationKind() 2821 != TSK_ImplicitInstantiation) { 2822 QualType ParamType = Constructor->getParamDecl(0)->getType(); 2823 QualType ClassTy = Context.getTagDeclType(ClassDecl); 2824 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 2825 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 2826 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 2827 << FixItHint::CreateInsertion(ParamLoc, " const &"); 2828 2829 // FIXME: Rather that making the constructor invalid, we should endeavor 2830 // to fix the type. 2831 Constructor->setInvalidDecl(); 2832 } 2833 } 2834 2835 // Notify the class that we've added a constructor. In principle we 2836 // don't need to do this for out-of-line declarations; in practice 2837 // we only instantiate the most recent declaration of a method, so 2838 // we have to call this for everything but friends. 2839 if (!Constructor->getFriendObjectKind()) 2840 ClassDecl->addedConstructor(Context, Constructor); 2841} 2842 2843/// CheckDestructor - Checks a fully-formed destructor for well-formedness, 2844/// issuing any diagnostics required. Returns true on error. 2845bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 2846 CXXRecordDecl *RD = Destructor->getParent(); 2847 2848 if (Destructor->isVirtual()) { 2849 SourceLocation Loc; 2850 2851 if (!Destructor->isImplicit()) 2852 Loc = Destructor->getLocation(); 2853 else 2854 Loc = RD->getLocation(); 2855 2856 // If we have a virtual destructor, look up the deallocation function 2857 FunctionDecl *OperatorDelete = 0; 2858 DeclarationName Name = 2859 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 2860 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 2861 return true; 2862 2863 Destructor->setOperatorDelete(OperatorDelete); 2864 } 2865 2866 return false; 2867} 2868 2869static inline bool 2870FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) { 2871 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 2872 FTI.ArgInfo[0].Param && 2873 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType()); 2874} 2875 2876/// CheckDestructorDeclarator - Called by ActOnDeclarator to check 2877/// the well-formednes of the destructor declarator @p D with type @p 2878/// R. If there are any errors in the declarator, this routine will 2879/// emit diagnostics and set the declarator to invalid. Even if this happens, 2880/// will be updated to reflect a well-formed type for the destructor and 2881/// returned. 2882QualType Sema::CheckDestructorDeclarator(Declarator &D, 2883 FunctionDecl::StorageClass& SC) { 2884 // C++ [class.dtor]p1: 2885 // [...] A typedef-name that names a class is a class-name 2886 // (7.1.3); however, a typedef-name that names a class shall not 2887 // be used as the identifier in the declarator for a destructor 2888 // declaration. 2889 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 2890 if (isa<TypedefType>(DeclaratorType)) { 2891 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 2892 << DeclaratorType; 2893 D.setInvalidType(); 2894 } 2895 2896 // C++ [class.dtor]p2: 2897 // A destructor is used to destroy objects of its class type. A 2898 // destructor takes no parameters, and no return type can be 2899 // specified for it (not even void). The address of a destructor 2900 // shall not be taken. A destructor shall not be static. A 2901 // destructor can be invoked for a const, volatile or const 2902 // volatile object. A destructor shall not be declared const, 2903 // volatile or const volatile (9.3.2). 2904 if (SC == FunctionDecl::Static) { 2905 if (!D.isInvalidType()) 2906 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 2907 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 2908 << SourceRange(D.getIdentifierLoc()); 2909 SC = FunctionDecl::None; 2910 D.setInvalidType(); 2911 } 2912 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 2913 // Destructors don't have return types, but the parser will 2914 // happily parse something like: 2915 // 2916 // class X { 2917 // float ~X(); 2918 // }; 2919 // 2920 // The return type will be eliminated later. 2921 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 2922 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 2923 << SourceRange(D.getIdentifierLoc()); 2924 } 2925 2926 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 2927 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 2928 if (FTI.TypeQuals & Qualifiers::Const) 2929 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 2930 << "const" << SourceRange(D.getIdentifierLoc()); 2931 if (FTI.TypeQuals & Qualifiers::Volatile) 2932 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 2933 << "volatile" << SourceRange(D.getIdentifierLoc()); 2934 if (FTI.TypeQuals & Qualifiers::Restrict) 2935 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 2936 << "restrict" << SourceRange(D.getIdentifierLoc()); 2937 D.setInvalidType(); 2938 } 2939 2940 // Make sure we don't have any parameters. 2941 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) { 2942 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 2943 2944 // Delete the parameters. 2945 FTI.freeArgs(); 2946 D.setInvalidType(); 2947 } 2948 2949 // Make sure the destructor isn't variadic. 2950 if (FTI.isVariadic) { 2951 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 2952 D.setInvalidType(); 2953 } 2954 2955 // Rebuild the function type "R" without any type qualifiers or 2956 // parameters (in case any of the errors above fired) and with 2957 // "void" as the return type, since destructors don't have return 2958 // types. We *always* have to do this, because GetTypeForDeclarator 2959 // will put in a result type of "int" when none was specified. 2960 // FIXME: Exceptions! 2961 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0, 2962 false, false, 0, 0, FunctionType::ExtInfo()); 2963} 2964 2965/// CheckConversionDeclarator - Called by ActOnDeclarator to check the 2966/// well-formednes of the conversion function declarator @p D with 2967/// type @p R. If there are any errors in the declarator, this routine 2968/// will emit diagnostics and return true. Otherwise, it will return 2969/// false. Either way, the type @p R will be updated to reflect a 2970/// well-formed type for the conversion operator. 2971void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 2972 FunctionDecl::StorageClass& SC) { 2973 // C++ [class.conv.fct]p1: 2974 // Neither parameter types nor return type can be specified. The 2975 // type of a conversion function (8.3.5) is "function taking no 2976 // parameter returning conversion-type-id." 2977 if (SC == FunctionDecl::Static) { 2978 if (!D.isInvalidType()) 2979 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 2980 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 2981 << SourceRange(D.getIdentifierLoc()); 2982 D.setInvalidType(); 2983 SC = FunctionDecl::None; 2984 } 2985 2986 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId); 2987 2988 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 2989 // Conversion functions don't have return types, but the parser will 2990 // happily parse something like: 2991 // 2992 // class X { 2993 // float operator bool(); 2994 // }; 2995 // 2996 // The return type will be changed later anyway. 2997 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 2998 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 2999 << SourceRange(D.getIdentifierLoc()); 3000 D.setInvalidType(); 3001 } 3002 3003 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 3004 3005 // Make sure we don't have any parameters. 3006 if (Proto->getNumArgs() > 0) { 3007 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 3008 3009 // Delete the parameters. 3010 D.getTypeObject(0).Fun.freeArgs(); 3011 D.setInvalidType(); 3012 } else if (Proto->isVariadic()) { 3013 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 3014 D.setInvalidType(); 3015 } 3016 3017 // Diagnose "&operator bool()" and other such nonsense. This 3018 // is actually a gcc extension which we don't support. 3019 if (Proto->getResultType() != ConvType) { 3020 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 3021 << Proto->getResultType(); 3022 D.setInvalidType(); 3023 ConvType = Proto->getResultType(); 3024 } 3025 3026 // C++ [class.conv.fct]p4: 3027 // The conversion-type-id shall not represent a function type nor 3028 // an array type. 3029 if (ConvType->isArrayType()) { 3030 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 3031 ConvType = Context.getPointerType(ConvType); 3032 D.setInvalidType(); 3033 } else if (ConvType->isFunctionType()) { 3034 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 3035 ConvType = Context.getPointerType(ConvType); 3036 D.setInvalidType(); 3037 } 3038 3039 // Rebuild the function type "R" without any parameters (in case any 3040 // of the errors above fired) and with the conversion type as the 3041 // return type. 3042 if (D.isInvalidType()) { 3043 R = Context.getFunctionType(ConvType, 0, 0, false, 3044 Proto->getTypeQuals(), 3045 Proto->hasExceptionSpec(), 3046 Proto->hasAnyExceptionSpec(), 3047 Proto->getNumExceptions(), 3048 Proto->exception_begin(), 3049 Proto->getExtInfo()); 3050 } 3051 3052 // C++0x explicit conversion operators. 3053 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x) 3054 Diag(D.getDeclSpec().getExplicitSpecLoc(), 3055 diag::warn_explicit_conversion_functions) 3056 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 3057} 3058 3059/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 3060/// the declaration of the given C++ conversion function. This routine 3061/// is responsible for recording the conversion function in the C++ 3062/// class, if possible. 3063Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 3064 assert(Conversion && "Expected to receive a conversion function declaration"); 3065 3066 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 3067 3068 // Make sure we aren't redeclaring the conversion function. 3069 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 3070 3071 // C++ [class.conv.fct]p1: 3072 // [...] A conversion function is never used to convert a 3073 // (possibly cv-qualified) object to the (possibly cv-qualified) 3074 // same object type (or a reference to it), to a (possibly 3075 // cv-qualified) base class of that type (or a reference to it), 3076 // or to (possibly cv-qualified) void. 3077 // FIXME: Suppress this warning if the conversion function ends up being a 3078 // virtual function that overrides a virtual function in a base class. 3079 QualType ClassType 3080 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 3081 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 3082 ConvType = ConvTypeRef->getPointeeType(); 3083 if (ConvType->isRecordType()) { 3084 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 3085 if (ConvType == ClassType) 3086 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 3087 << ClassType; 3088 else if (IsDerivedFrom(ClassType, ConvType)) 3089 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 3090 << ClassType << ConvType; 3091 } else if (ConvType->isVoidType()) { 3092 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 3093 << ClassType << ConvType; 3094 } 3095 3096 if (Conversion->getPrimaryTemplate()) { 3097 // ignore specializations 3098 } else if (Conversion->getPreviousDeclaration()) { 3099 if (FunctionTemplateDecl *ConversionTemplate 3100 = Conversion->getDescribedFunctionTemplate()) { 3101 if (ClassDecl->replaceConversion( 3102 ConversionTemplate->getPreviousDeclaration(), 3103 ConversionTemplate)) 3104 return DeclPtrTy::make(ConversionTemplate); 3105 } else if (ClassDecl->replaceConversion(Conversion->getPreviousDeclaration(), 3106 Conversion)) 3107 return DeclPtrTy::make(Conversion); 3108 assert(Conversion->isInvalidDecl() && "Conversion should not get here."); 3109 } else if (FunctionTemplateDecl *ConversionTemplate 3110 = Conversion->getDescribedFunctionTemplate()) 3111 ClassDecl->addConversionFunction(ConversionTemplate); 3112 else 3113 ClassDecl->addConversionFunction(Conversion); 3114 3115 return DeclPtrTy::make(Conversion); 3116} 3117 3118//===----------------------------------------------------------------------===// 3119// Namespace Handling 3120//===----------------------------------------------------------------------===// 3121 3122/// ActOnStartNamespaceDef - This is called at the start of a namespace 3123/// definition. 3124Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 3125 SourceLocation IdentLoc, 3126 IdentifierInfo *II, 3127 SourceLocation LBrace, 3128 AttributeList *AttrList) { 3129 NamespaceDecl *Namespc = 3130 NamespaceDecl::Create(Context, CurContext, IdentLoc, II); 3131 Namespc->setLBracLoc(LBrace); 3132 3133 Scope *DeclRegionScope = NamespcScope->getParent(); 3134 3135 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 3136 3137 if (II) { 3138 // C++ [namespace.def]p2: 3139 // The identifier in an original-namespace-definition shall not have been 3140 // previously defined in the declarative region in which the 3141 // original-namespace-definition appears. The identifier in an 3142 // original-namespace-definition is the name of the namespace. Subsequently 3143 // in that declarative region, it is treated as an original-namespace-name. 3144 3145 NamedDecl *PrevDecl 3146 = LookupSingleName(DeclRegionScope, II, IdentLoc, LookupOrdinaryName, 3147 ForRedeclaration); 3148 3149 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) { 3150 // This is an extended namespace definition. 3151 // Attach this namespace decl to the chain of extended namespace 3152 // definitions. 3153 OrigNS->setNextNamespace(Namespc); 3154 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace()); 3155 3156 // Remove the previous declaration from the scope. 3157 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) { 3158 IdResolver.RemoveDecl(OrigNS); 3159 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS)); 3160 } 3161 } else if (PrevDecl) { 3162 // This is an invalid name redefinition. 3163 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind) 3164 << Namespc->getDeclName(); 3165 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 3166 Namespc->setInvalidDecl(); 3167 // Continue on to push Namespc as current DeclContext and return it. 3168 } else if (II->isStr("std") && 3169 CurContext->getLookupContext()->isTranslationUnit()) { 3170 // This is the first "real" definition of the namespace "std", so update 3171 // our cache of the "std" namespace to point at this definition. 3172 if (StdNamespace) { 3173 // We had already defined a dummy namespace "std". Link this new 3174 // namespace definition to the dummy namespace "std". 3175 StdNamespace->setNextNamespace(Namespc); 3176 StdNamespace->setLocation(IdentLoc); 3177 Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace()); 3178 } 3179 3180 // Make our StdNamespace cache point at the first real definition of the 3181 // "std" namespace. 3182 StdNamespace = Namespc; 3183 } 3184 3185 PushOnScopeChains(Namespc, DeclRegionScope); 3186 } else { 3187 // Anonymous namespaces. 3188 assert(Namespc->isAnonymousNamespace()); 3189 3190 // Link the anonymous namespace into its parent. 3191 NamespaceDecl *PrevDecl; 3192 DeclContext *Parent = CurContext->getLookupContext(); 3193 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 3194 PrevDecl = TU->getAnonymousNamespace(); 3195 TU->setAnonymousNamespace(Namespc); 3196 } else { 3197 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 3198 PrevDecl = ND->getAnonymousNamespace(); 3199 ND->setAnonymousNamespace(Namespc); 3200 } 3201 3202 // Link the anonymous namespace with its previous declaration. 3203 if (PrevDecl) { 3204 assert(PrevDecl->isAnonymousNamespace()); 3205 assert(!PrevDecl->getNextNamespace()); 3206 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace()); 3207 PrevDecl->setNextNamespace(Namespc); 3208 } 3209 3210 CurContext->addDecl(Namespc); 3211 3212 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 3213 // behaves as if it were replaced by 3214 // namespace unique { /* empty body */ } 3215 // using namespace unique; 3216 // namespace unique { namespace-body } 3217 // where all occurrences of 'unique' in a translation unit are 3218 // replaced by the same identifier and this identifier differs 3219 // from all other identifiers in the entire program. 3220 3221 // We just create the namespace with an empty name and then add an 3222 // implicit using declaration, just like the standard suggests. 3223 // 3224 // CodeGen enforces the "universally unique" aspect by giving all 3225 // declarations semantically contained within an anonymous 3226 // namespace internal linkage. 3227 3228 if (!PrevDecl) { 3229 UsingDirectiveDecl* UD 3230 = UsingDirectiveDecl::Create(Context, CurContext, 3231 /* 'using' */ LBrace, 3232 /* 'namespace' */ SourceLocation(), 3233 /* qualifier */ SourceRange(), 3234 /* NNS */ NULL, 3235 /* identifier */ SourceLocation(), 3236 Namespc, 3237 /* Ancestor */ CurContext); 3238 UD->setImplicit(); 3239 CurContext->addDecl(UD); 3240 } 3241 } 3242 3243 // Although we could have an invalid decl (i.e. the namespace name is a 3244 // redefinition), push it as current DeclContext and try to continue parsing. 3245 // FIXME: We should be able to push Namespc here, so that the each DeclContext 3246 // for the namespace has the declarations that showed up in that particular 3247 // namespace definition. 3248 PushDeclContext(NamespcScope, Namespc); 3249 return DeclPtrTy::make(Namespc); 3250} 3251 3252/// getNamespaceDecl - Returns the namespace a decl represents. If the decl 3253/// is a namespace alias, returns the namespace it points to. 3254static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 3255 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 3256 return AD->getNamespace(); 3257 return dyn_cast_or_null<NamespaceDecl>(D); 3258} 3259 3260/// ActOnFinishNamespaceDef - This callback is called after a namespace is 3261/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 3262void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) { 3263 Decl *Dcl = D.getAs<Decl>(); 3264 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 3265 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 3266 Namespc->setRBracLoc(RBrace); 3267 PopDeclContext(); 3268} 3269 3270Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S, 3271 SourceLocation UsingLoc, 3272 SourceLocation NamespcLoc, 3273 CXXScopeSpec &SS, 3274 SourceLocation IdentLoc, 3275 IdentifierInfo *NamespcName, 3276 AttributeList *AttrList) { 3277 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 3278 assert(NamespcName && "Invalid NamespcName."); 3279 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 3280 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 3281 3282 UsingDirectiveDecl *UDir = 0; 3283 3284 // Lookup namespace name. 3285 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 3286 LookupParsedName(R, S, &SS); 3287 if (R.isAmbiguous()) 3288 return DeclPtrTy(); 3289 3290 if (!R.empty()) { 3291 NamedDecl *Named = R.getFoundDecl(); 3292 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named)) 3293 && "expected namespace decl"); 3294 // C++ [namespace.udir]p1: 3295 // A using-directive specifies that the names in the nominated 3296 // namespace can be used in the scope in which the 3297 // using-directive appears after the using-directive. During 3298 // unqualified name lookup (3.4.1), the names appear as if they 3299 // were declared in the nearest enclosing namespace which 3300 // contains both the using-directive and the nominated 3301 // namespace. [Note: in this context, "contains" means "contains 3302 // directly or indirectly". ] 3303 3304 // Find enclosing context containing both using-directive and 3305 // nominated namespace. 3306 NamespaceDecl *NS = getNamespaceDecl(Named); 3307 DeclContext *CommonAncestor = cast<DeclContext>(NS); 3308 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 3309 CommonAncestor = CommonAncestor->getParent(); 3310 3311 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 3312 SS.getRange(), 3313 (NestedNameSpecifier *)SS.getScopeRep(), 3314 IdentLoc, Named, CommonAncestor); 3315 PushUsingDirective(S, UDir); 3316 } else { 3317 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 3318 } 3319 3320 // FIXME: We ignore attributes for now. 3321 delete AttrList; 3322 return DeclPtrTy::make(UDir); 3323} 3324 3325void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 3326 // If scope has associated entity, then using directive is at namespace 3327 // or translation unit scope. We add UsingDirectiveDecls, into 3328 // it's lookup structure. 3329 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) 3330 Ctx->addDecl(UDir); 3331 else 3332 // Otherwise it is block-sope. using-directives will affect lookup 3333 // only to the end of scope. 3334 S->PushUsingDirective(DeclPtrTy::make(UDir)); 3335} 3336 3337 3338Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S, 3339 AccessSpecifier AS, 3340 bool HasUsingKeyword, 3341 SourceLocation UsingLoc, 3342 CXXScopeSpec &SS, 3343 UnqualifiedId &Name, 3344 AttributeList *AttrList, 3345 bool IsTypeName, 3346 SourceLocation TypenameLoc) { 3347 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 3348 3349 switch (Name.getKind()) { 3350 case UnqualifiedId::IK_Identifier: 3351 case UnqualifiedId::IK_OperatorFunctionId: 3352 case UnqualifiedId::IK_LiteralOperatorId: 3353 case UnqualifiedId::IK_ConversionFunctionId: 3354 break; 3355 3356 case UnqualifiedId::IK_ConstructorName: 3357 case UnqualifiedId::IK_ConstructorTemplateId: 3358 // C++0x inherited constructors. 3359 if (getLangOptions().CPlusPlus0x) break; 3360 3361 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor) 3362 << SS.getRange(); 3363 return DeclPtrTy(); 3364 3365 case UnqualifiedId::IK_DestructorName: 3366 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor) 3367 << SS.getRange(); 3368 return DeclPtrTy(); 3369 3370 case UnqualifiedId::IK_TemplateId: 3371 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id) 3372 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 3373 return DeclPtrTy(); 3374 } 3375 3376 DeclarationName TargetName = GetNameFromUnqualifiedId(Name); 3377 if (!TargetName) 3378 return DeclPtrTy(); 3379 3380 // Warn about using declarations. 3381 // TODO: store that the declaration was written without 'using' and 3382 // talk about access decls instead of using decls in the 3383 // diagnostics. 3384 if (!HasUsingKeyword) { 3385 UsingLoc = Name.getSourceRange().getBegin(); 3386 3387 Diag(UsingLoc, diag::warn_access_decl_deprecated) 3388 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 3389 } 3390 3391 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 3392 Name.getSourceRange().getBegin(), 3393 TargetName, AttrList, 3394 /* IsInstantiation */ false, 3395 IsTypeName, TypenameLoc); 3396 if (UD) 3397 PushOnScopeChains(UD, S, /*AddToContext*/ false); 3398 3399 return DeclPtrTy::make(UD); 3400} 3401 3402/// Determines whether to create a using shadow decl for a particular 3403/// decl, given the set of decls existing prior to this using lookup. 3404bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 3405 const LookupResult &Previous) { 3406 // Diagnose finding a decl which is not from a base class of the 3407 // current class. We do this now because there are cases where this 3408 // function will silently decide not to build a shadow decl, which 3409 // will pre-empt further diagnostics. 3410 // 3411 // We don't need to do this in C++0x because we do the check once on 3412 // the qualifier. 3413 // 3414 // FIXME: diagnose the following if we care enough: 3415 // struct A { int foo; }; 3416 // struct B : A { using A::foo; }; 3417 // template <class T> struct C : A {}; 3418 // template <class T> struct D : C<T> { using B::foo; } // <--- 3419 // This is invalid (during instantiation) in C++03 because B::foo 3420 // resolves to the using decl in B, which is not a base class of D<T>. 3421 // We can't diagnose it immediately because C<T> is an unknown 3422 // specialization. The UsingShadowDecl in D<T> then points directly 3423 // to A::foo, which will look well-formed when we instantiate. 3424 // The right solution is to not collapse the shadow-decl chain. 3425 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) { 3426 DeclContext *OrigDC = Orig->getDeclContext(); 3427 3428 // Handle enums and anonymous structs. 3429 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 3430 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 3431 while (OrigRec->isAnonymousStructOrUnion()) 3432 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 3433 3434 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 3435 if (OrigDC == CurContext) { 3436 Diag(Using->getLocation(), 3437 diag::err_using_decl_nested_name_specifier_is_current_class) 3438 << Using->getNestedNameRange(); 3439 Diag(Orig->getLocation(), diag::note_using_decl_target); 3440 return true; 3441 } 3442 3443 Diag(Using->getNestedNameRange().getBegin(), 3444 diag::err_using_decl_nested_name_specifier_is_not_base_class) 3445 << Using->getTargetNestedNameDecl() 3446 << cast<CXXRecordDecl>(CurContext) 3447 << Using->getNestedNameRange(); 3448 Diag(Orig->getLocation(), diag::note_using_decl_target); 3449 return true; 3450 } 3451 } 3452 3453 if (Previous.empty()) return false; 3454 3455 NamedDecl *Target = Orig; 3456 if (isa<UsingShadowDecl>(Target)) 3457 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 3458 3459 // If the target happens to be one of the previous declarations, we 3460 // don't have a conflict. 3461 // 3462 // FIXME: but we might be increasing its access, in which case we 3463 // should redeclare it. 3464 NamedDecl *NonTag = 0, *Tag = 0; 3465 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 3466 I != E; ++I) { 3467 NamedDecl *D = (*I)->getUnderlyingDecl(); 3468 if (D->getCanonicalDecl() == Target->getCanonicalDecl()) 3469 return false; 3470 3471 (isa<TagDecl>(D) ? Tag : NonTag) = D; 3472 } 3473 3474 if (Target->isFunctionOrFunctionTemplate()) { 3475 FunctionDecl *FD; 3476 if (isa<FunctionTemplateDecl>(Target)) 3477 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl(); 3478 else 3479 FD = cast<FunctionDecl>(Target); 3480 3481 NamedDecl *OldDecl = 0; 3482 switch (CheckOverload(FD, Previous, OldDecl)) { 3483 case Ovl_Overload: 3484 return false; 3485 3486 case Ovl_NonFunction: 3487 Diag(Using->getLocation(), diag::err_using_decl_conflict); 3488 break; 3489 3490 // We found a decl with the exact signature. 3491 case Ovl_Match: 3492 if (isa<UsingShadowDecl>(OldDecl)) { 3493 // Silently ignore the possible conflict. 3494 return false; 3495 } 3496 3497 // If we're in a record, we want to hide the target, so we 3498 // return true (without a diagnostic) to tell the caller not to 3499 // build a shadow decl. 3500 if (CurContext->isRecord()) 3501 return true; 3502 3503 // If we're not in a record, this is an error. 3504 Diag(Using->getLocation(), diag::err_using_decl_conflict); 3505 break; 3506 } 3507 3508 Diag(Target->getLocation(), diag::note_using_decl_target); 3509 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 3510 return true; 3511 } 3512 3513 // Target is not a function. 3514 3515 if (isa<TagDecl>(Target)) { 3516 // No conflict between a tag and a non-tag. 3517 if (!Tag) return false; 3518 3519 Diag(Using->getLocation(), diag::err_using_decl_conflict); 3520 Diag(Target->getLocation(), diag::note_using_decl_target); 3521 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 3522 return true; 3523 } 3524 3525 // No conflict between a tag and a non-tag. 3526 if (!NonTag) return false; 3527 3528 Diag(Using->getLocation(), diag::err_using_decl_conflict); 3529 Diag(Target->getLocation(), diag::note_using_decl_target); 3530 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 3531 return true; 3532} 3533 3534/// Builds a shadow declaration corresponding to a 'using' declaration. 3535UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 3536 UsingDecl *UD, 3537 NamedDecl *Orig) { 3538 3539 // If we resolved to another shadow declaration, just coalesce them. 3540 NamedDecl *Target = Orig; 3541 if (isa<UsingShadowDecl>(Target)) { 3542 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 3543 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 3544 } 3545 3546 UsingShadowDecl *Shadow 3547 = UsingShadowDecl::Create(Context, CurContext, 3548 UD->getLocation(), UD, Target); 3549 UD->addShadowDecl(Shadow); 3550 3551 if (S) 3552 PushOnScopeChains(Shadow, S); 3553 else 3554 CurContext->addDecl(Shadow); 3555 Shadow->setAccess(UD->getAccess()); 3556 3557 // Register it as a conversion if appropriate. 3558 if (Shadow->getDeclName().getNameKind() 3559 == DeclarationName::CXXConversionFunctionName) 3560 cast<CXXRecordDecl>(CurContext)->addConversionFunction(Shadow); 3561 3562 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 3563 Shadow->setInvalidDecl(); 3564 3565 return Shadow; 3566} 3567 3568/// Hides a using shadow declaration. This is required by the current 3569/// using-decl implementation when a resolvable using declaration in a 3570/// class is followed by a declaration which would hide or override 3571/// one or more of the using decl's targets; for example: 3572/// 3573/// struct Base { void foo(int); }; 3574/// struct Derived : Base { 3575/// using Base::foo; 3576/// void foo(int); 3577/// }; 3578/// 3579/// The governing language is C++03 [namespace.udecl]p12: 3580/// 3581/// When a using-declaration brings names from a base class into a 3582/// derived class scope, member functions in the derived class 3583/// override and/or hide member functions with the same name and 3584/// parameter types in a base class (rather than conflicting). 3585/// 3586/// There are two ways to implement this: 3587/// (1) optimistically create shadow decls when they're not hidden 3588/// by existing declarations, or 3589/// (2) don't create any shadow decls (or at least don't make them 3590/// visible) until we've fully parsed/instantiated the class. 3591/// The problem with (1) is that we might have to retroactively remove 3592/// a shadow decl, which requires several O(n) operations because the 3593/// decl structures are (very reasonably) not designed for removal. 3594/// (2) avoids this but is very fiddly and phase-dependent. 3595void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 3596 if (Shadow->getDeclName().getNameKind() == 3597 DeclarationName::CXXConversionFunctionName) 3598 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 3599 3600 // Remove it from the DeclContext... 3601 Shadow->getDeclContext()->removeDecl(Shadow); 3602 3603 // ...and the scope, if applicable... 3604 if (S) { 3605 S->RemoveDecl(DeclPtrTy::make(static_cast<Decl*>(Shadow))); 3606 IdResolver.RemoveDecl(Shadow); 3607 } 3608 3609 // ...and the using decl. 3610 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 3611 3612 // TODO: complain somehow if Shadow was used. It shouldn't 3613 // be possible for this to happen, because...? 3614} 3615 3616/// Builds a using declaration. 3617/// 3618/// \param IsInstantiation - Whether this call arises from an 3619/// instantiation of an unresolved using declaration. We treat 3620/// the lookup differently for these declarations. 3621NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 3622 SourceLocation UsingLoc, 3623 CXXScopeSpec &SS, 3624 SourceLocation IdentLoc, 3625 DeclarationName Name, 3626 AttributeList *AttrList, 3627 bool IsInstantiation, 3628 bool IsTypeName, 3629 SourceLocation TypenameLoc) { 3630 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 3631 assert(IdentLoc.isValid() && "Invalid TargetName location."); 3632 3633 // FIXME: We ignore attributes for now. 3634 delete AttrList; 3635 3636 if (SS.isEmpty()) { 3637 Diag(IdentLoc, diag::err_using_requires_qualname); 3638 return 0; 3639 } 3640 3641 // Do the redeclaration lookup in the current scope. 3642 LookupResult Previous(*this, Name, IdentLoc, LookupUsingDeclName, 3643 ForRedeclaration); 3644 Previous.setHideTags(false); 3645 if (S) { 3646 LookupName(Previous, S); 3647 3648 // It is really dumb that we have to do this. 3649 LookupResult::Filter F = Previous.makeFilter(); 3650 while (F.hasNext()) { 3651 NamedDecl *D = F.next(); 3652 if (!isDeclInScope(D, CurContext, S)) 3653 F.erase(); 3654 } 3655 F.done(); 3656 } else { 3657 assert(IsInstantiation && "no scope in non-instantiation"); 3658 assert(CurContext->isRecord() && "scope not record in instantiation"); 3659 LookupQualifiedName(Previous, CurContext); 3660 } 3661 3662 NestedNameSpecifier *NNS = 3663 static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 3664 3665 // Check for invalid redeclarations. 3666 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous)) 3667 return 0; 3668 3669 // Check for bad qualifiers. 3670 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc)) 3671 return 0; 3672 3673 DeclContext *LookupContext = computeDeclContext(SS); 3674 NamedDecl *D; 3675 if (!LookupContext) { 3676 if (IsTypeName) { 3677 // FIXME: not all declaration name kinds are legal here 3678 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 3679 UsingLoc, TypenameLoc, 3680 SS.getRange(), NNS, 3681 IdentLoc, Name); 3682 } else { 3683 D = UnresolvedUsingValueDecl::Create(Context, CurContext, 3684 UsingLoc, SS.getRange(), NNS, 3685 IdentLoc, Name); 3686 } 3687 } else { 3688 D = UsingDecl::Create(Context, CurContext, IdentLoc, 3689 SS.getRange(), UsingLoc, NNS, Name, 3690 IsTypeName); 3691 } 3692 D->setAccess(AS); 3693 CurContext->addDecl(D); 3694 3695 if (!LookupContext) return D; 3696 UsingDecl *UD = cast<UsingDecl>(D); 3697 3698 if (RequireCompleteDeclContext(SS)) { 3699 UD->setInvalidDecl(); 3700 return UD; 3701 } 3702 3703 // Look up the target name. 3704 3705 LookupResult R(*this, Name, IdentLoc, LookupOrdinaryName); 3706 3707 // Unlike most lookups, we don't always want to hide tag 3708 // declarations: tag names are visible through the using declaration 3709 // even if hidden by ordinary names, *except* in a dependent context 3710 // where it's important for the sanity of two-phase lookup. 3711 if (!IsInstantiation) 3712 R.setHideTags(false); 3713 3714 LookupQualifiedName(R, LookupContext); 3715 3716 if (R.empty()) { 3717 Diag(IdentLoc, diag::err_no_member) 3718 << Name << LookupContext << SS.getRange(); 3719 UD->setInvalidDecl(); 3720 return UD; 3721 } 3722 3723 if (R.isAmbiguous()) { 3724 UD->setInvalidDecl(); 3725 return UD; 3726 } 3727 3728 if (IsTypeName) { 3729 // If we asked for a typename and got a non-type decl, error out. 3730 if (!R.getAsSingle<TypeDecl>()) { 3731 Diag(IdentLoc, diag::err_using_typename_non_type); 3732 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 3733 Diag((*I)->getUnderlyingDecl()->getLocation(), 3734 diag::note_using_decl_target); 3735 UD->setInvalidDecl(); 3736 return UD; 3737 } 3738 } else { 3739 // If we asked for a non-typename and we got a type, error out, 3740 // but only if this is an instantiation of an unresolved using 3741 // decl. Otherwise just silently find the type name. 3742 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 3743 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 3744 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 3745 UD->setInvalidDecl(); 3746 return UD; 3747 } 3748 } 3749 3750 // C++0x N2914 [namespace.udecl]p6: 3751 // A using-declaration shall not name a namespace. 3752 if (R.getAsSingle<NamespaceDecl>()) { 3753 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 3754 << SS.getRange(); 3755 UD->setInvalidDecl(); 3756 return UD; 3757 } 3758 3759 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 3760 if (!CheckUsingShadowDecl(UD, *I, Previous)) 3761 BuildUsingShadowDecl(S, UD, *I); 3762 } 3763 3764 return UD; 3765} 3766 3767/// Checks that the given using declaration is not an invalid 3768/// redeclaration. Note that this is checking only for the using decl 3769/// itself, not for any ill-formedness among the UsingShadowDecls. 3770bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 3771 bool isTypeName, 3772 const CXXScopeSpec &SS, 3773 SourceLocation NameLoc, 3774 const LookupResult &Prev) { 3775 // C++03 [namespace.udecl]p8: 3776 // C++0x [namespace.udecl]p10: 3777 // A using-declaration is a declaration and can therefore be used 3778 // repeatedly where (and only where) multiple declarations are 3779 // allowed. 3780 // That's only in file contexts. 3781 if (CurContext->getLookupContext()->isFileContext()) 3782 return false; 3783 3784 NestedNameSpecifier *Qual 3785 = static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 3786 3787 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 3788 NamedDecl *D = *I; 3789 3790 bool DTypename; 3791 NestedNameSpecifier *DQual; 3792 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 3793 DTypename = UD->isTypeName(); 3794 DQual = UD->getTargetNestedNameDecl(); 3795 } else if (UnresolvedUsingValueDecl *UD 3796 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 3797 DTypename = false; 3798 DQual = UD->getTargetNestedNameSpecifier(); 3799 } else if (UnresolvedUsingTypenameDecl *UD 3800 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 3801 DTypename = true; 3802 DQual = UD->getTargetNestedNameSpecifier(); 3803 } else continue; 3804 3805 // using decls differ if one says 'typename' and the other doesn't. 3806 // FIXME: non-dependent using decls? 3807 if (isTypeName != DTypename) continue; 3808 3809 // using decls differ if they name different scopes (but note that 3810 // template instantiation can cause this check to trigger when it 3811 // didn't before instantiation). 3812 if (Context.getCanonicalNestedNameSpecifier(Qual) != 3813 Context.getCanonicalNestedNameSpecifier(DQual)) 3814 continue; 3815 3816 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 3817 Diag(D->getLocation(), diag::note_using_decl) << 1; 3818 return true; 3819 } 3820 3821 return false; 3822} 3823 3824 3825/// Checks that the given nested-name qualifier used in a using decl 3826/// in the current context is appropriately related to the current 3827/// scope. If an error is found, diagnoses it and returns true. 3828bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 3829 const CXXScopeSpec &SS, 3830 SourceLocation NameLoc) { 3831 DeclContext *NamedContext = computeDeclContext(SS); 3832 3833 if (!CurContext->isRecord()) { 3834 // C++03 [namespace.udecl]p3: 3835 // C++0x [namespace.udecl]p8: 3836 // A using-declaration for a class member shall be a member-declaration. 3837 3838 // If we weren't able to compute a valid scope, it must be a 3839 // dependent class scope. 3840 if (!NamedContext || NamedContext->isRecord()) { 3841 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 3842 << SS.getRange(); 3843 return true; 3844 } 3845 3846 // Otherwise, everything is known to be fine. 3847 return false; 3848 } 3849 3850 // The current scope is a record. 3851 3852 // If the named context is dependent, we can't decide much. 3853 if (!NamedContext) { 3854 // FIXME: in C++0x, we can diagnose if we can prove that the 3855 // nested-name-specifier does not refer to a base class, which is 3856 // still possible in some cases. 3857 3858 // Otherwise we have to conservatively report that things might be 3859 // okay. 3860 return false; 3861 } 3862 3863 if (!NamedContext->isRecord()) { 3864 // Ideally this would point at the last name in the specifier, 3865 // but we don't have that level of source info. 3866 Diag(SS.getRange().getBegin(), 3867 diag::err_using_decl_nested_name_specifier_is_not_class) 3868 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange(); 3869 return true; 3870 } 3871 3872 if (getLangOptions().CPlusPlus0x) { 3873 // C++0x [namespace.udecl]p3: 3874 // In a using-declaration used as a member-declaration, the 3875 // nested-name-specifier shall name a base class of the class 3876 // being defined. 3877 3878 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 3879 cast<CXXRecordDecl>(NamedContext))) { 3880 if (CurContext == NamedContext) { 3881 Diag(NameLoc, 3882 diag::err_using_decl_nested_name_specifier_is_current_class) 3883 << SS.getRange(); 3884 return true; 3885 } 3886 3887 Diag(SS.getRange().getBegin(), 3888 diag::err_using_decl_nested_name_specifier_is_not_base_class) 3889 << (NestedNameSpecifier*) SS.getScopeRep() 3890 << cast<CXXRecordDecl>(CurContext) 3891 << SS.getRange(); 3892 return true; 3893 } 3894 3895 return false; 3896 } 3897 3898 // C++03 [namespace.udecl]p4: 3899 // A using-declaration used as a member-declaration shall refer 3900 // to a member of a base class of the class being defined [etc.]. 3901 3902 // Salient point: SS doesn't have to name a base class as long as 3903 // lookup only finds members from base classes. Therefore we can 3904 // diagnose here only if we can prove that that can't happen, 3905 // i.e. if the class hierarchies provably don't intersect. 3906 3907 // TODO: it would be nice if "definitely valid" results were cached 3908 // in the UsingDecl and UsingShadowDecl so that these checks didn't 3909 // need to be repeated. 3910 3911 struct UserData { 3912 llvm::DenseSet<const CXXRecordDecl*> Bases; 3913 3914 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) { 3915 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 3916 Data->Bases.insert(Base); 3917 return true; 3918 } 3919 3920 bool hasDependentBases(const CXXRecordDecl *Class) { 3921 return !Class->forallBases(collect, this); 3922 } 3923 3924 /// Returns true if the base is dependent or is one of the 3925 /// accumulated base classes. 3926 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) { 3927 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 3928 return !Data->Bases.count(Base); 3929 } 3930 3931 bool mightShareBases(const CXXRecordDecl *Class) { 3932 return Bases.count(Class) || !Class->forallBases(doesNotContain, this); 3933 } 3934 }; 3935 3936 UserData Data; 3937 3938 // Returns false if we find a dependent base. 3939 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext))) 3940 return false; 3941 3942 // Returns false if the class has a dependent base or if it or one 3943 // of its bases is present in the base set of the current context. 3944 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext))) 3945 return false; 3946 3947 Diag(SS.getRange().getBegin(), 3948 diag::err_using_decl_nested_name_specifier_is_not_base_class) 3949 << (NestedNameSpecifier*) SS.getScopeRep() 3950 << cast<CXXRecordDecl>(CurContext) 3951 << SS.getRange(); 3952 3953 return true; 3954} 3955 3956Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S, 3957 SourceLocation NamespaceLoc, 3958 SourceLocation AliasLoc, 3959 IdentifierInfo *Alias, 3960 CXXScopeSpec &SS, 3961 SourceLocation IdentLoc, 3962 IdentifierInfo *Ident) { 3963 3964 // Lookup the namespace name. 3965 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 3966 LookupParsedName(R, S, &SS); 3967 3968 // Check if we have a previous declaration with the same name. 3969 if (NamedDecl *PrevDecl 3970 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName, 3971 ForRedeclaration)) { 3972 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 3973 // We already have an alias with the same name that points to the same 3974 // namespace, so don't create a new one. 3975 // FIXME: At some point, we'll want to create the (redundant) 3976 // declaration to maintain better source information. 3977 if (!R.isAmbiguous() && !R.empty() && 3978 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl()))) 3979 return DeclPtrTy(); 3980 } 3981 3982 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition : 3983 diag::err_redefinition_different_kind; 3984 Diag(AliasLoc, DiagID) << Alias; 3985 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 3986 return DeclPtrTy(); 3987 } 3988 3989 if (R.isAmbiguous()) 3990 return DeclPtrTy(); 3991 3992 if (R.empty()) { 3993 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange(); 3994 return DeclPtrTy(); 3995 } 3996 3997 NamespaceAliasDecl *AliasDecl = 3998 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 3999 Alias, SS.getRange(), 4000 (NestedNameSpecifier *)SS.getScopeRep(), 4001 IdentLoc, R.getFoundDecl()); 4002 4003 PushOnScopeChains(AliasDecl, S); 4004 return DeclPtrTy::make(AliasDecl); 4005} 4006 4007void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 4008 CXXConstructorDecl *Constructor) { 4009 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() && 4010 !Constructor->isUsed()) && 4011 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 4012 4013 CXXRecordDecl *ClassDecl = Constructor->getParent(); 4014 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 4015 4016 DeclContext *PreviousContext = CurContext; 4017 CurContext = Constructor; 4018 if (SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false)) { 4019 Diag(CurrentLocation, diag::note_member_synthesized_at) 4020 << CXXConstructor << Context.getTagDeclType(ClassDecl); 4021 Constructor->setInvalidDecl(); 4022 } else { 4023 Constructor->setUsed(); 4024 } 4025 CurContext = PreviousContext; 4026} 4027 4028void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 4029 CXXDestructorDecl *Destructor) { 4030 assert((Destructor->isImplicit() && !Destructor->isUsed()) && 4031 "DefineImplicitDestructor - call it for implicit default dtor"); 4032 CXXRecordDecl *ClassDecl = Destructor->getParent(); 4033 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 4034 4035 DeclContext *PreviousContext = CurContext; 4036 CurContext = Destructor; 4037 4038 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 4039 Destructor->getParent()); 4040 4041 // FIXME: If CheckDestructor fails, we should emit a note about where the 4042 // implicit destructor was needed. 4043 if (CheckDestructor(Destructor)) { 4044 Diag(CurrentLocation, diag::note_member_synthesized_at) 4045 << CXXDestructor << Context.getTagDeclType(ClassDecl); 4046 4047 Destructor->setInvalidDecl(); 4048 CurContext = PreviousContext; 4049 4050 return; 4051 } 4052 CurContext = PreviousContext; 4053 4054 Destructor->setUsed(); 4055} 4056 4057void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation, 4058 CXXMethodDecl *MethodDecl) { 4059 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() && 4060 MethodDecl->getOverloadedOperator() == OO_Equal && 4061 !MethodDecl->isUsed()) && 4062 "DefineImplicitOverloadedAssign - call it for implicit assignment op"); 4063 4064 CXXRecordDecl *ClassDecl 4065 = cast<CXXRecordDecl>(MethodDecl->getDeclContext()); 4066 4067 DeclContext *PreviousContext = CurContext; 4068 CurContext = MethodDecl; 4069 4070 // C++[class.copy] p12 4071 // Before the implicitly-declared copy assignment operator for a class is 4072 // implicitly defined, all implicitly-declared copy assignment operators 4073 // for its direct base classes and its nonstatic data members shall have 4074 // been implicitly defined. 4075 bool err = false; 4076 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 4077 E = ClassDecl->bases_end(); Base != E; ++Base) { 4078 CXXRecordDecl *BaseClassDecl 4079 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 4080 if (CXXMethodDecl *BaseAssignOpMethod = 4081 getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0), 4082 BaseClassDecl)) { 4083 CheckDirectMemberAccess(Base->getSourceRange().getBegin(), 4084 BaseAssignOpMethod, 4085 PDiag(diag::err_access_assign_base) 4086 << Base->getType()); 4087 4088 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod); 4089 } 4090 } 4091 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 4092 E = ClassDecl->field_end(); Field != E; ++Field) { 4093 QualType FieldType = Context.getCanonicalType((*Field)->getType()); 4094 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 4095 FieldType = Array->getElementType(); 4096 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 4097 CXXRecordDecl *FieldClassDecl 4098 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 4099 if (CXXMethodDecl *FieldAssignOpMethod = 4100 getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0), 4101 FieldClassDecl)) { 4102 CheckDirectMemberAccess(Field->getLocation(), 4103 FieldAssignOpMethod, 4104 PDiag(diag::err_access_assign_field) 4105 << Field->getDeclName() << Field->getType()); 4106 4107 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod); 4108 } 4109 } else if (FieldType->isReferenceType()) { 4110 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 4111 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 4112 Diag(Field->getLocation(), diag::note_declared_at); 4113 Diag(CurrentLocation, diag::note_first_required_here); 4114 err = true; 4115 } else if (FieldType.isConstQualified()) { 4116 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 4117 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 4118 Diag(Field->getLocation(), diag::note_declared_at); 4119 Diag(CurrentLocation, diag::note_first_required_here); 4120 err = true; 4121 } 4122 } 4123 if (!err) 4124 MethodDecl->setUsed(); 4125 4126 CurContext = PreviousContext; 4127} 4128 4129CXXMethodDecl * 4130Sema::getAssignOperatorMethod(SourceLocation CurrentLocation, 4131 ParmVarDecl *ParmDecl, 4132 CXXRecordDecl *ClassDecl) { 4133 QualType LHSType = Context.getTypeDeclType(ClassDecl); 4134 QualType RHSType(LHSType); 4135 // If class's assignment operator argument is const/volatile qualified, 4136 // look for operator = (const/volatile B&). Otherwise, look for 4137 // operator = (B&). 4138 RHSType = Context.getCVRQualifiedType(RHSType, 4139 ParmDecl->getType().getCVRQualifiers()); 4140 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl, 4141 LHSType, 4142 SourceLocation())); 4143 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl, 4144 RHSType, 4145 CurrentLocation)); 4146 Expr *Args[2] = { &*LHS, &*RHS }; 4147 OverloadCandidateSet CandidateSet(CurrentLocation); 4148 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2, 4149 CandidateSet); 4150 OverloadCandidateSet::iterator Best; 4151 if (BestViableFunction(CandidateSet, CurrentLocation, Best) == OR_Success) 4152 return cast<CXXMethodDecl>(Best->Function); 4153 assert(false && 4154 "getAssignOperatorMethod - copy assignment operator method not found"); 4155 return 0; 4156} 4157 4158void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 4159 CXXConstructorDecl *CopyConstructor, 4160 unsigned TypeQuals) { 4161 assert((CopyConstructor->isImplicit() && 4162 CopyConstructor->isCopyConstructor(TypeQuals) && 4163 !CopyConstructor->isUsed()) && 4164 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 4165 4166 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 4167 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 4168 4169 DeclContext *PreviousContext = CurContext; 4170 CurContext = CopyConstructor; 4171 4172 // C++ [class.copy] p209 4173 // Before the implicitly-declared copy constructor for a class is 4174 // implicitly defined, all the implicitly-declared copy constructors 4175 // for its base class and its non-static data members shall have been 4176 // implicitly defined. 4177 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(); 4178 Base != ClassDecl->bases_end(); ++Base) { 4179 CXXRecordDecl *BaseClassDecl 4180 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 4181 if (CXXConstructorDecl *BaseCopyCtor = 4182 BaseClassDecl->getCopyConstructor(Context, TypeQuals)) { 4183 CheckDirectMemberAccess(Base->getSourceRange().getBegin(), 4184 BaseCopyCtor, 4185 PDiag(diag::err_access_copy_base) 4186 << Base->getType()); 4187 4188 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor); 4189 } 4190 } 4191 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 4192 FieldEnd = ClassDecl->field_end(); 4193 Field != FieldEnd; ++Field) { 4194 QualType FieldType = Context.getCanonicalType((*Field)->getType()); 4195 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 4196 FieldType = Array->getElementType(); 4197 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 4198 CXXRecordDecl *FieldClassDecl 4199 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 4200 if (CXXConstructorDecl *FieldCopyCtor = 4201 FieldClassDecl->getCopyConstructor(Context, TypeQuals)) { 4202 CheckDirectMemberAccess(Field->getLocation(), 4203 FieldCopyCtor, 4204 PDiag(diag::err_access_copy_field) 4205 << Field->getDeclName() << Field->getType()); 4206 4207 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor); 4208 } 4209 } 4210 } 4211 CopyConstructor->setUsed(); 4212 4213 CurContext = PreviousContext; 4214} 4215 4216Sema::OwningExprResult 4217Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 4218 CXXConstructorDecl *Constructor, 4219 MultiExprArg ExprArgs, 4220 bool RequiresZeroInit, 4221 bool BaseInitialization) { 4222 bool Elidable = false; 4223 4224 // C++0x [class.copy]p34: 4225 // When certain criteria are met, an implementation is allowed to 4226 // omit the copy/move construction of a class object, even if the 4227 // copy/move constructor and/or destructor for the object have 4228 // side effects. [...] 4229 // - when a temporary class object that has not been bound to a 4230 // reference (12.2) would be copied/moved to a class object 4231 // with the same cv-unqualified type, the copy/move operation 4232 // can be omitted by constructing the temporary object 4233 // directly into the target of the omitted copy/move 4234 if (Constructor->isCopyConstructor() && ExprArgs.size() >= 1) { 4235 Expr *SubExpr = ((Expr **)ExprArgs.get())[0]; 4236 Elidable = SubExpr->isTemporaryObject() && 4237 Context.hasSameUnqualifiedType(SubExpr->getType(), 4238 Context.getTypeDeclType(Constructor->getParent())); 4239 } 4240 4241 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 4242 Elidable, move(ExprArgs), RequiresZeroInit, 4243 BaseInitialization); 4244} 4245 4246/// BuildCXXConstructExpr - Creates a complete call to a constructor, 4247/// including handling of its default argument expressions. 4248Sema::OwningExprResult 4249Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 4250 CXXConstructorDecl *Constructor, bool Elidable, 4251 MultiExprArg ExprArgs, 4252 bool RequiresZeroInit, 4253 bool BaseInitialization) { 4254 unsigned NumExprs = ExprArgs.size(); 4255 Expr **Exprs = (Expr **)ExprArgs.release(); 4256 4257 MarkDeclarationReferenced(ConstructLoc, Constructor); 4258 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc, 4259 Constructor, Elidable, Exprs, NumExprs, 4260 RequiresZeroInit, BaseInitialization)); 4261} 4262 4263bool Sema::InitializeVarWithConstructor(VarDecl *VD, 4264 CXXConstructorDecl *Constructor, 4265 MultiExprArg Exprs) { 4266 OwningExprResult TempResult = 4267 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor, 4268 move(Exprs)); 4269 if (TempResult.isInvalid()) 4270 return true; 4271 4272 Expr *Temp = TempResult.takeAs<Expr>(); 4273 MarkDeclarationReferenced(VD->getLocation(), Constructor); 4274 Temp = MaybeCreateCXXExprWithTemporaries(Temp); 4275 VD->setInit(Temp); 4276 4277 return false; 4278} 4279 4280void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 4281 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 4282 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() && 4283 !ClassDecl->hasTrivialDestructor()) { 4284 CXXDestructorDecl *Destructor = ClassDecl->getDestructor(Context); 4285 MarkDeclarationReferenced(VD->getLocation(), Destructor); 4286 CheckDestructorAccess(VD->getLocation(), Destructor, 4287 PDiag(diag::err_access_dtor_var) 4288 << VD->getDeclName() 4289 << VD->getType()); 4290 } 4291} 4292 4293/// AddCXXDirectInitializerToDecl - This action is called immediately after 4294/// ActOnDeclarator, when a C++ direct initializer is present. 4295/// e.g: "int x(1);" 4296void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl, 4297 SourceLocation LParenLoc, 4298 MultiExprArg Exprs, 4299 SourceLocation *CommaLocs, 4300 SourceLocation RParenLoc) { 4301 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions"); 4302 Decl *RealDecl = Dcl.getAs<Decl>(); 4303 4304 // If there is no declaration, there was an error parsing it. Just ignore 4305 // the initializer. 4306 if (RealDecl == 0) 4307 return; 4308 4309 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 4310 if (!VDecl) { 4311 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 4312 RealDecl->setInvalidDecl(); 4313 return; 4314 } 4315 4316 // We will represent direct-initialization similarly to copy-initialization: 4317 // int x(1); -as-> int x = 1; 4318 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 4319 // 4320 // Clients that want to distinguish between the two forms, can check for 4321 // direct initializer using VarDecl::hasCXXDirectInitializer(). 4322 // A major benefit is that clients that don't particularly care about which 4323 // exactly form was it (like the CodeGen) can handle both cases without 4324 // special case code. 4325 4326 // C++ 8.5p11: 4327 // The form of initialization (using parentheses or '=') is generally 4328 // insignificant, but does matter when the entity being initialized has a 4329 // class type. 4330 QualType DeclInitType = VDecl->getType(); 4331 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType)) 4332 DeclInitType = Context.getBaseElementType(Array); 4333 4334 if (!VDecl->getType()->isDependentType() && 4335 RequireCompleteType(VDecl->getLocation(), VDecl->getType(), 4336 diag::err_typecheck_decl_incomplete_type)) { 4337 VDecl->setInvalidDecl(); 4338 return; 4339 } 4340 4341 // The variable can not have an abstract class type. 4342 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 4343 diag::err_abstract_type_in_decl, 4344 AbstractVariableType)) 4345 VDecl->setInvalidDecl(); 4346 4347 const VarDecl *Def; 4348 if ((Def = VDecl->getDefinition()) && Def != VDecl) { 4349 Diag(VDecl->getLocation(), diag::err_redefinition) 4350 << VDecl->getDeclName(); 4351 Diag(Def->getLocation(), diag::note_previous_definition); 4352 VDecl->setInvalidDecl(); 4353 return; 4354 } 4355 4356 // If either the declaration has a dependent type or if any of the 4357 // expressions is type-dependent, we represent the initialization 4358 // via a ParenListExpr for later use during template instantiation. 4359 if (VDecl->getType()->isDependentType() || 4360 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) { 4361 // Let clients know that initialization was done with a direct initializer. 4362 VDecl->setCXXDirectInitializer(true); 4363 4364 // Store the initialization expressions as a ParenListExpr. 4365 unsigned NumExprs = Exprs.size(); 4366 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc, 4367 (Expr **)Exprs.release(), 4368 NumExprs, RParenLoc)); 4369 return; 4370 } 4371 4372 // Capture the variable that is being initialized and the style of 4373 // initialization. 4374 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 4375 4376 // FIXME: Poor source location information. 4377 InitializationKind Kind 4378 = InitializationKind::CreateDirect(VDecl->getLocation(), 4379 LParenLoc, RParenLoc); 4380 4381 InitializationSequence InitSeq(*this, Entity, Kind, 4382 (Expr**)Exprs.get(), Exprs.size()); 4383 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs)); 4384 if (Result.isInvalid()) { 4385 VDecl->setInvalidDecl(); 4386 return; 4387 } 4388 4389 Result = MaybeCreateCXXExprWithTemporaries(move(Result)); 4390 VDecl->setInit(Result.takeAs<Expr>()); 4391 VDecl->setCXXDirectInitializer(true); 4392 4393 if (const RecordType *Record = VDecl->getType()->getAs<RecordType>()) 4394 FinalizeVarWithDestructor(VDecl, Record); 4395} 4396 4397/// \brief Given a constructor and the set of arguments provided for the 4398/// constructor, convert the arguments and add any required default arguments 4399/// to form a proper call to this constructor. 4400/// 4401/// \returns true if an error occurred, false otherwise. 4402bool 4403Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 4404 MultiExprArg ArgsPtr, 4405 SourceLocation Loc, 4406 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) { 4407 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 4408 unsigned NumArgs = ArgsPtr.size(); 4409 Expr **Args = (Expr **)ArgsPtr.get(); 4410 4411 const FunctionProtoType *Proto 4412 = Constructor->getType()->getAs<FunctionProtoType>(); 4413 assert(Proto && "Constructor without a prototype?"); 4414 unsigned NumArgsInProto = Proto->getNumArgs(); 4415 4416 // If too few arguments are available, we'll fill in the rest with defaults. 4417 if (NumArgs < NumArgsInProto) 4418 ConvertedArgs.reserve(NumArgsInProto); 4419 else 4420 ConvertedArgs.reserve(NumArgs); 4421 4422 VariadicCallType CallType = 4423 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 4424 llvm::SmallVector<Expr *, 8> AllArgs; 4425 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 4426 Proto, 0, Args, NumArgs, AllArgs, 4427 CallType); 4428 for (unsigned i =0, size = AllArgs.size(); i < size; i++) 4429 ConvertedArgs.push_back(AllArgs[i]); 4430 return Invalid; 4431} 4432 4433static inline bool 4434CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 4435 const FunctionDecl *FnDecl) { 4436 const DeclContext *DC = FnDecl->getDeclContext()->getLookupContext(); 4437 if (isa<NamespaceDecl>(DC)) { 4438 return SemaRef.Diag(FnDecl->getLocation(), 4439 diag::err_operator_new_delete_declared_in_namespace) 4440 << FnDecl->getDeclName(); 4441 } 4442 4443 if (isa<TranslationUnitDecl>(DC) && 4444 FnDecl->getStorageClass() == FunctionDecl::Static) { 4445 return SemaRef.Diag(FnDecl->getLocation(), 4446 diag::err_operator_new_delete_declared_static) 4447 << FnDecl->getDeclName(); 4448 } 4449 4450 return false; 4451} 4452 4453static inline bool 4454CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 4455 CanQualType ExpectedResultType, 4456 CanQualType ExpectedFirstParamType, 4457 unsigned DependentParamTypeDiag, 4458 unsigned InvalidParamTypeDiag) { 4459 QualType ResultType = 4460 FnDecl->getType()->getAs<FunctionType>()->getResultType(); 4461 4462 // Check that the result type is not dependent. 4463 if (ResultType->isDependentType()) 4464 return SemaRef.Diag(FnDecl->getLocation(), 4465 diag::err_operator_new_delete_dependent_result_type) 4466 << FnDecl->getDeclName() << ExpectedResultType; 4467 4468 // Check that the result type is what we expect. 4469 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 4470 return SemaRef.Diag(FnDecl->getLocation(), 4471 diag::err_operator_new_delete_invalid_result_type) 4472 << FnDecl->getDeclName() << ExpectedResultType; 4473 4474 // A function template must have at least 2 parameters. 4475 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 4476 return SemaRef.Diag(FnDecl->getLocation(), 4477 diag::err_operator_new_delete_template_too_few_parameters) 4478 << FnDecl->getDeclName(); 4479 4480 // The function decl must have at least 1 parameter. 4481 if (FnDecl->getNumParams() == 0) 4482 return SemaRef.Diag(FnDecl->getLocation(), 4483 diag::err_operator_new_delete_too_few_parameters) 4484 << FnDecl->getDeclName(); 4485 4486 // Check the the first parameter type is not dependent. 4487 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 4488 if (FirstParamType->isDependentType()) 4489 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 4490 << FnDecl->getDeclName() << ExpectedFirstParamType; 4491 4492 // Check that the first parameter type is what we expect. 4493 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 4494 ExpectedFirstParamType) 4495 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 4496 << FnDecl->getDeclName() << ExpectedFirstParamType; 4497 4498 return false; 4499} 4500 4501static bool 4502CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 4503 // C++ [basic.stc.dynamic.allocation]p1: 4504 // A program is ill-formed if an allocation function is declared in a 4505 // namespace scope other than global scope or declared static in global 4506 // scope. 4507 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 4508 return true; 4509 4510 CanQualType SizeTy = 4511 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 4512 4513 // C++ [basic.stc.dynamic.allocation]p1: 4514 // The return type shall be void*. The first parameter shall have type 4515 // std::size_t. 4516 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 4517 SizeTy, 4518 diag::err_operator_new_dependent_param_type, 4519 diag::err_operator_new_param_type)) 4520 return true; 4521 4522 // C++ [basic.stc.dynamic.allocation]p1: 4523 // The first parameter shall not have an associated default argument. 4524 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 4525 return SemaRef.Diag(FnDecl->getLocation(), 4526 diag::err_operator_new_default_arg) 4527 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 4528 4529 return false; 4530} 4531 4532static bool 4533CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 4534 // C++ [basic.stc.dynamic.deallocation]p1: 4535 // A program is ill-formed if deallocation functions are declared in a 4536 // namespace scope other than global scope or declared static in global 4537 // scope. 4538 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 4539 return true; 4540 4541 // C++ [basic.stc.dynamic.deallocation]p2: 4542 // Each deallocation function shall return void and its first parameter 4543 // shall be void*. 4544 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 4545 SemaRef.Context.VoidPtrTy, 4546 diag::err_operator_delete_dependent_param_type, 4547 diag::err_operator_delete_param_type)) 4548 return true; 4549 4550 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 4551 if (FirstParamType->isDependentType()) 4552 return SemaRef.Diag(FnDecl->getLocation(), 4553 diag::err_operator_delete_dependent_param_type) 4554 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy; 4555 4556 if (SemaRef.Context.getCanonicalType(FirstParamType) != 4557 SemaRef.Context.VoidPtrTy) 4558 return SemaRef.Diag(FnDecl->getLocation(), 4559 diag::err_operator_delete_param_type) 4560 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy; 4561 4562 return false; 4563} 4564 4565/// CheckOverloadedOperatorDeclaration - Check whether the declaration 4566/// of this overloaded operator is well-formed. If so, returns false; 4567/// otherwise, emits appropriate diagnostics and returns true. 4568bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 4569 assert(FnDecl && FnDecl->isOverloadedOperator() && 4570 "Expected an overloaded operator declaration"); 4571 4572 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 4573 4574 // C++ [over.oper]p5: 4575 // The allocation and deallocation functions, operator new, 4576 // operator new[], operator delete and operator delete[], are 4577 // described completely in 3.7.3. The attributes and restrictions 4578 // found in the rest of this subclause do not apply to them unless 4579 // explicitly stated in 3.7.3. 4580 if (Op == OO_Delete || Op == OO_Array_Delete) 4581 return CheckOperatorDeleteDeclaration(*this, FnDecl); 4582 4583 if (Op == OO_New || Op == OO_Array_New) 4584 return CheckOperatorNewDeclaration(*this, FnDecl); 4585 4586 // C++ [over.oper]p6: 4587 // An operator function shall either be a non-static member 4588 // function or be a non-member function and have at least one 4589 // parameter whose type is a class, a reference to a class, an 4590 // enumeration, or a reference to an enumeration. 4591 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 4592 if (MethodDecl->isStatic()) 4593 return Diag(FnDecl->getLocation(), 4594 diag::err_operator_overload_static) << FnDecl->getDeclName(); 4595 } else { 4596 bool ClassOrEnumParam = false; 4597 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 4598 ParamEnd = FnDecl->param_end(); 4599 Param != ParamEnd; ++Param) { 4600 QualType ParamType = (*Param)->getType().getNonReferenceType(); 4601 if (ParamType->isDependentType() || ParamType->isRecordType() || 4602 ParamType->isEnumeralType()) { 4603 ClassOrEnumParam = true; 4604 break; 4605 } 4606 } 4607 4608 if (!ClassOrEnumParam) 4609 return Diag(FnDecl->getLocation(), 4610 diag::err_operator_overload_needs_class_or_enum) 4611 << FnDecl->getDeclName(); 4612 } 4613 4614 // C++ [over.oper]p8: 4615 // An operator function cannot have default arguments (8.3.6), 4616 // except where explicitly stated below. 4617 // 4618 // Only the function-call operator allows default arguments 4619 // (C++ [over.call]p1). 4620 if (Op != OO_Call) { 4621 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(); 4622 Param != FnDecl->param_end(); ++Param) { 4623 if ((*Param)->hasDefaultArg()) 4624 return Diag((*Param)->getLocation(), 4625 diag::err_operator_overload_default_arg) 4626 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange(); 4627 } 4628 } 4629 4630 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 4631 { false, false, false } 4632#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 4633 , { Unary, Binary, MemberOnly } 4634#include "clang/Basic/OperatorKinds.def" 4635 }; 4636 4637 bool CanBeUnaryOperator = OperatorUses[Op][0]; 4638 bool CanBeBinaryOperator = OperatorUses[Op][1]; 4639 bool MustBeMemberOperator = OperatorUses[Op][2]; 4640 4641 // C++ [over.oper]p8: 4642 // [...] Operator functions cannot have more or fewer parameters 4643 // than the number required for the corresponding operator, as 4644 // described in the rest of this subclause. 4645 unsigned NumParams = FnDecl->getNumParams() 4646 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 4647 if (Op != OO_Call && 4648 ((NumParams == 1 && !CanBeUnaryOperator) || 4649 (NumParams == 2 && !CanBeBinaryOperator) || 4650 (NumParams < 1) || (NumParams > 2))) { 4651 // We have the wrong number of parameters. 4652 unsigned ErrorKind; 4653 if (CanBeUnaryOperator && CanBeBinaryOperator) { 4654 ErrorKind = 2; // 2 -> unary or binary. 4655 } else if (CanBeUnaryOperator) { 4656 ErrorKind = 0; // 0 -> unary 4657 } else { 4658 assert(CanBeBinaryOperator && 4659 "All non-call overloaded operators are unary or binary!"); 4660 ErrorKind = 1; // 1 -> binary 4661 } 4662 4663 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 4664 << FnDecl->getDeclName() << NumParams << ErrorKind; 4665 } 4666 4667 // Overloaded operators other than operator() cannot be variadic. 4668 if (Op != OO_Call && 4669 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 4670 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 4671 << FnDecl->getDeclName(); 4672 } 4673 4674 // Some operators must be non-static member functions. 4675 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 4676 return Diag(FnDecl->getLocation(), 4677 diag::err_operator_overload_must_be_member) 4678 << FnDecl->getDeclName(); 4679 } 4680 4681 // C++ [over.inc]p1: 4682 // The user-defined function called operator++ implements the 4683 // prefix and postfix ++ operator. If this function is a member 4684 // function with no parameters, or a non-member function with one 4685 // parameter of class or enumeration type, it defines the prefix 4686 // increment operator ++ for objects of that type. If the function 4687 // is a member function with one parameter (which shall be of type 4688 // int) or a non-member function with two parameters (the second 4689 // of which shall be of type int), it defines the postfix 4690 // increment operator ++ for objects of that type. 4691 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 4692 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 4693 bool ParamIsInt = false; 4694 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>()) 4695 ParamIsInt = BT->getKind() == BuiltinType::Int; 4696 4697 if (!ParamIsInt) 4698 return Diag(LastParam->getLocation(), 4699 diag::err_operator_overload_post_incdec_must_be_int) 4700 << LastParam->getType() << (Op == OO_MinusMinus); 4701 } 4702 4703 // Notify the class if it got an assignment operator. 4704 if (Op == OO_Equal) { 4705 // Would have returned earlier otherwise. 4706 assert(isa<CXXMethodDecl>(FnDecl) && 4707 "Overloaded = not member, but not filtered."); 4708 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 4709 Method->getParent()->addedAssignmentOperator(Context, Method); 4710 } 4711 4712 return false; 4713} 4714 4715/// CheckLiteralOperatorDeclaration - Check whether the declaration 4716/// of this literal operator function is well-formed. If so, returns 4717/// false; otherwise, emits appropriate diagnostics and returns true. 4718bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 4719 DeclContext *DC = FnDecl->getDeclContext(); 4720 Decl::Kind Kind = DC->getDeclKind(); 4721 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace && 4722 Kind != Decl::LinkageSpec) { 4723 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 4724 << FnDecl->getDeclName(); 4725 return true; 4726 } 4727 4728 bool Valid = false; 4729 4730 // template <char...> type operator "" name() is the only valid template 4731 // signature, and the only valid signature with no parameters. 4732 if (FnDecl->param_size() == 0) { 4733 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) { 4734 // Must have only one template parameter 4735 TemplateParameterList *Params = TpDecl->getTemplateParameters(); 4736 if (Params->size() == 1) { 4737 NonTypeTemplateParmDecl *PmDecl = 4738 cast<NonTypeTemplateParmDecl>(Params->getParam(0)); 4739 4740 // The template parameter must be a char parameter pack. 4741 // FIXME: This test will always fail because non-type parameter packs 4742 // have not been implemented. 4743 if (PmDecl && PmDecl->isTemplateParameterPack() && 4744 Context.hasSameType(PmDecl->getType(), Context.CharTy)) 4745 Valid = true; 4746 } 4747 } 4748 } else { 4749 // Check the first parameter 4750 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 4751 4752 QualType T = (*Param)->getType(); 4753 4754 // unsigned long long int, long double, and any character type are allowed 4755 // as the only parameters. 4756 if (Context.hasSameType(T, Context.UnsignedLongLongTy) || 4757 Context.hasSameType(T, Context.LongDoubleTy) || 4758 Context.hasSameType(T, Context.CharTy) || 4759 Context.hasSameType(T, Context.WCharTy) || 4760 Context.hasSameType(T, Context.Char16Ty) || 4761 Context.hasSameType(T, Context.Char32Ty)) { 4762 if (++Param == FnDecl->param_end()) 4763 Valid = true; 4764 goto FinishedParams; 4765 } 4766 4767 // Otherwise it must be a pointer to const; let's strip those qualifiers. 4768 const PointerType *PT = T->getAs<PointerType>(); 4769 if (!PT) 4770 goto FinishedParams; 4771 T = PT->getPointeeType(); 4772 if (!T.isConstQualified()) 4773 goto FinishedParams; 4774 T = T.getUnqualifiedType(); 4775 4776 // Move on to the second parameter; 4777 ++Param; 4778 4779 // If there is no second parameter, the first must be a const char * 4780 if (Param == FnDecl->param_end()) { 4781 if (Context.hasSameType(T, Context.CharTy)) 4782 Valid = true; 4783 goto FinishedParams; 4784 } 4785 4786 // const char *, const wchar_t*, const char16_t*, and const char32_t* 4787 // are allowed as the first parameter to a two-parameter function 4788 if (!(Context.hasSameType(T, Context.CharTy) || 4789 Context.hasSameType(T, Context.WCharTy) || 4790 Context.hasSameType(T, Context.Char16Ty) || 4791 Context.hasSameType(T, Context.Char32Ty))) 4792 goto FinishedParams; 4793 4794 // The second and final parameter must be an std::size_t 4795 T = (*Param)->getType().getUnqualifiedType(); 4796 if (Context.hasSameType(T, Context.getSizeType()) && 4797 ++Param == FnDecl->param_end()) 4798 Valid = true; 4799 } 4800 4801 // FIXME: This diagnostic is absolutely terrible. 4802FinishedParams: 4803 if (!Valid) { 4804 Diag(FnDecl->getLocation(), diag::err_literal_operator_params) 4805 << FnDecl->getDeclName(); 4806 return true; 4807 } 4808 4809 return false; 4810} 4811 4812/// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 4813/// linkage specification, including the language and (if present) 4814/// the '{'. ExternLoc is the location of the 'extern', LangLoc is 4815/// the location of the language string literal, which is provided 4816/// by Lang/StrSize. LBraceLoc, if valid, provides the location of 4817/// the '{' brace. Otherwise, this linkage specification does not 4818/// have any braces. 4819Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S, 4820 SourceLocation ExternLoc, 4821 SourceLocation LangLoc, 4822 const char *Lang, 4823 unsigned StrSize, 4824 SourceLocation LBraceLoc) { 4825 LinkageSpecDecl::LanguageIDs Language; 4826 if (strncmp(Lang, "\"C\"", StrSize) == 0) 4827 Language = LinkageSpecDecl::lang_c; 4828 else if (strncmp(Lang, "\"C++\"", StrSize) == 0) 4829 Language = LinkageSpecDecl::lang_cxx; 4830 else { 4831 Diag(LangLoc, diag::err_bad_language); 4832 return DeclPtrTy(); 4833 } 4834 4835 // FIXME: Add all the various semantics of linkage specifications 4836 4837 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, 4838 LangLoc, Language, 4839 LBraceLoc.isValid()); 4840 CurContext->addDecl(D); 4841 PushDeclContext(S, D); 4842 return DeclPtrTy::make(D); 4843} 4844 4845/// ActOnFinishLinkageSpecification - Completely the definition of 4846/// the C++ linkage specification LinkageSpec. If RBraceLoc is 4847/// valid, it's the position of the closing '}' brace in a linkage 4848/// specification that uses braces. 4849Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S, 4850 DeclPtrTy LinkageSpec, 4851 SourceLocation RBraceLoc) { 4852 if (LinkageSpec) 4853 PopDeclContext(); 4854 return LinkageSpec; 4855} 4856 4857/// \brief Perform semantic analysis for the variable declaration that 4858/// occurs within a C++ catch clause, returning the newly-created 4859/// variable. 4860VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType, 4861 TypeSourceInfo *TInfo, 4862 IdentifierInfo *Name, 4863 SourceLocation Loc, 4864 SourceRange Range) { 4865 bool Invalid = false; 4866 4867 // Arrays and functions decay. 4868 if (ExDeclType->isArrayType()) 4869 ExDeclType = Context.getArrayDecayedType(ExDeclType); 4870 else if (ExDeclType->isFunctionType()) 4871 ExDeclType = Context.getPointerType(ExDeclType); 4872 4873 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 4874 // The exception-declaration shall not denote a pointer or reference to an 4875 // incomplete type, other than [cv] void*. 4876 // N2844 forbids rvalue references. 4877 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 4878 Diag(Loc, diag::err_catch_rvalue_ref) << Range; 4879 Invalid = true; 4880 } 4881 4882 // GCC allows catching pointers and references to incomplete types 4883 // as an extension; so do we, but we warn by default. 4884 4885 QualType BaseType = ExDeclType; 4886 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 4887 unsigned DK = diag::err_catch_incomplete; 4888 bool IncompleteCatchIsInvalid = true; 4889 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 4890 BaseType = Ptr->getPointeeType(); 4891 Mode = 1; 4892 DK = diag::ext_catch_incomplete_ptr; 4893 IncompleteCatchIsInvalid = false; 4894 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 4895 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 4896 BaseType = Ref->getPointeeType(); 4897 Mode = 2; 4898 DK = diag::ext_catch_incomplete_ref; 4899 IncompleteCatchIsInvalid = false; 4900 } 4901 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 4902 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) && 4903 IncompleteCatchIsInvalid) 4904 Invalid = true; 4905 4906 if (!Invalid && !ExDeclType->isDependentType() && 4907 RequireNonAbstractType(Loc, ExDeclType, 4908 diag::err_abstract_type_in_decl, 4909 AbstractVariableType)) 4910 Invalid = true; 4911 4912 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc, 4913 Name, ExDeclType, TInfo, VarDecl::None, 4914 VarDecl::None); 4915 4916 if (!Invalid) { 4917 if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) { 4918 // C++ [except.handle]p16: 4919 // The object declared in an exception-declaration or, if the 4920 // exception-declaration does not specify a name, a temporary (12.2) is 4921 // copy-initialized (8.5) from the exception object. [...] 4922 // The object is destroyed when the handler exits, after the destruction 4923 // of any automatic objects initialized within the handler. 4924 // 4925 // We just pretend to initialize the object with itself, then make sure 4926 // it can be destroyed later. 4927 InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl); 4928 Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl, 4929 Loc, ExDeclType, 0); 4930 InitializationKind Kind = InitializationKind::CreateCopy(Loc, 4931 SourceLocation()); 4932 InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1); 4933 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, 4934 MultiExprArg(*this, (void**)&ExDeclRef, 1)); 4935 if (Result.isInvalid()) 4936 Invalid = true; 4937 else 4938 FinalizeVarWithDestructor(ExDecl, RecordTy); 4939 } 4940 } 4941 4942 if (Invalid) 4943 ExDecl->setInvalidDecl(); 4944 4945 return ExDecl; 4946} 4947 4948/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 4949/// handler. 4950Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 4951 TypeSourceInfo *TInfo = 0; 4952 QualType ExDeclType = GetTypeForDeclarator(D, S, &TInfo); 4953 4954 bool Invalid = D.isInvalidType(); 4955 IdentifierInfo *II = D.getIdentifier(); 4956 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 4957 LookupOrdinaryName, 4958 ForRedeclaration)) { 4959 // The scope should be freshly made just for us. There is just no way 4960 // it contains any previous declaration. 4961 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl))); 4962 if (PrevDecl->isTemplateParameter()) { 4963 // Maybe we will complain about the shadowed template parameter. 4964 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 4965 } 4966 } 4967 4968 if (D.getCXXScopeSpec().isSet() && !Invalid) { 4969 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 4970 << D.getCXXScopeSpec().getRange(); 4971 Invalid = true; 4972 } 4973 4974 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, TInfo, 4975 D.getIdentifier(), 4976 D.getIdentifierLoc(), 4977 D.getDeclSpec().getSourceRange()); 4978 4979 if (Invalid) 4980 ExDecl->setInvalidDecl(); 4981 4982 // Add the exception declaration into this scope. 4983 if (II) 4984 PushOnScopeChains(ExDecl, S); 4985 else 4986 CurContext->addDecl(ExDecl); 4987 4988 ProcessDeclAttributes(S, ExDecl, D); 4989 return DeclPtrTy::make(ExDecl); 4990} 4991 4992Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc, 4993 ExprArg assertexpr, 4994 ExprArg assertmessageexpr) { 4995 Expr *AssertExpr = (Expr *)assertexpr.get(); 4996 StringLiteral *AssertMessage = 4997 cast<StringLiteral>((Expr *)assertmessageexpr.get()); 4998 4999 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) { 5000 llvm::APSInt Value(32); 5001 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) { 5002 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) << 5003 AssertExpr->getSourceRange(); 5004 return DeclPtrTy(); 5005 } 5006 5007 if (Value == 0) { 5008 Diag(AssertLoc, diag::err_static_assert_failed) 5009 << AssertMessage->getString() << AssertExpr->getSourceRange(); 5010 } 5011 } 5012 5013 assertexpr.release(); 5014 assertmessageexpr.release(); 5015 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc, 5016 AssertExpr, AssertMessage); 5017 5018 CurContext->addDecl(Decl); 5019 return DeclPtrTy::make(Decl); 5020} 5021 5022/// \brief Perform semantic analysis of the given friend type declaration. 5023/// 5024/// \returns A friend declaration that. 5025FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc, 5026 TypeSourceInfo *TSInfo) { 5027 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 5028 5029 QualType T = TSInfo->getType(); 5030 SourceRange TypeRange = TSInfo->getTypeLoc().getSourceRange(); 5031 5032 if (!getLangOptions().CPlusPlus0x) { 5033 // C++03 [class.friend]p2: 5034 // An elaborated-type-specifier shall be used in a friend declaration 5035 // for a class.* 5036 // 5037 // * The class-key of the elaborated-type-specifier is required. 5038 if (!ActiveTemplateInstantiations.empty()) { 5039 // Do not complain about the form of friend template types during 5040 // template instantiation; we will already have complained when the 5041 // template was declared. 5042 } else if (!T->isElaboratedTypeSpecifier()) { 5043 // If we evaluated the type to a record type, suggest putting 5044 // a tag in front. 5045 if (const RecordType *RT = T->getAs<RecordType>()) { 5046 RecordDecl *RD = RT->getDecl(); 5047 5048 std::string InsertionText = std::string(" ") + RD->getKindName(); 5049 5050 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type) 5051 << (unsigned) RD->getTagKind() 5052 << T 5053 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc), 5054 InsertionText); 5055 } else { 5056 Diag(FriendLoc, diag::ext_nonclass_type_friend) 5057 << T 5058 << SourceRange(FriendLoc, TypeRange.getEnd()); 5059 } 5060 } else if (T->getAs<EnumType>()) { 5061 Diag(FriendLoc, diag::ext_enum_friend) 5062 << T 5063 << SourceRange(FriendLoc, TypeRange.getEnd()); 5064 } 5065 } 5066 5067 // C++0x [class.friend]p3: 5068 // If the type specifier in a friend declaration designates a (possibly 5069 // cv-qualified) class type, that class is declared as a friend; otherwise, 5070 // the friend declaration is ignored. 5071 5072 // FIXME: C++0x has some syntactic restrictions on friend type declarations 5073 // in [class.friend]p3 that we do not implement. 5074 5075 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc); 5076} 5077 5078/// Handle a friend type declaration. This works in tandem with 5079/// ActOnTag. 5080/// 5081/// Notes on friend class templates: 5082/// 5083/// We generally treat friend class declarations as if they were 5084/// declaring a class. So, for example, the elaborated type specifier 5085/// in a friend declaration is required to obey the restrictions of a 5086/// class-head (i.e. no typedefs in the scope chain), template 5087/// parameters are required to match up with simple template-ids, &c. 5088/// However, unlike when declaring a template specialization, it's 5089/// okay to refer to a template specialization without an empty 5090/// template parameter declaration, e.g. 5091/// friend class A<T>::B<unsigned>; 5092/// We permit this as a special case; if there are any template 5093/// parameters present at all, require proper matching, i.e. 5094/// template <> template <class T> friend class A<int>::B; 5095Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 5096 MultiTemplateParamsArg TempParams) { 5097 SourceLocation Loc = DS.getSourceRange().getBegin(); 5098 5099 assert(DS.isFriendSpecified()); 5100 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 5101 5102 // Try to convert the decl specifier to a type. This works for 5103 // friend templates because ActOnTag never produces a ClassTemplateDecl 5104 // for a TUK_Friend. 5105 Declarator TheDeclarator(DS, Declarator::MemberContext); 5106 TypeSourceInfo *TSI; 5107 QualType T = GetTypeForDeclarator(TheDeclarator, S, &TSI); 5108 if (TheDeclarator.isInvalidType()) 5109 return DeclPtrTy(); 5110 5111 if (!TSI) 5112 TSI = Context.getTrivialTypeSourceInfo(T, DS.getSourceRange().getBegin()); 5113 5114 // This is definitely an error in C++98. It's probably meant to 5115 // be forbidden in C++0x, too, but the specification is just 5116 // poorly written. 5117 // 5118 // The problem is with declarations like the following: 5119 // template <T> friend A<T>::foo; 5120 // where deciding whether a class C is a friend or not now hinges 5121 // on whether there exists an instantiation of A that causes 5122 // 'foo' to equal C. There are restrictions on class-heads 5123 // (which we declare (by fiat) elaborated friend declarations to 5124 // be) that makes this tractable. 5125 // 5126 // FIXME: handle "template <> friend class A<T>;", which 5127 // is possibly well-formed? Who even knows? 5128 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 5129 Diag(Loc, diag::err_tagless_friend_type_template) 5130 << DS.getSourceRange(); 5131 return DeclPtrTy(); 5132 } 5133 5134 // C++98 [class.friend]p1: A friend of a class is a function 5135 // or class that is not a member of the class . . . 5136 // This is fixed in DR77, which just barely didn't make the C++03 5137 // deadline. It's also a very silly restriction that seriously 5138 // affects inner classes and which nobody else seems to implement; 5139 // thus we never diagnose it, not even in -pedantic. 5140 // 5141 // But note that we could warn about it: it's always useless to 5142 // friend one of your own members (it's not, however, worthless to 5143 // friend a member of an arbitrary specialization of your template). 5144 5145 Decl *D; 5146 if (unsigned NumTempParamLists = TempParams.size()) 5147 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 5148 NumTempParamLists, 5149 (TemplateParameterList**) TempParams.release(), 5150 TSI, 5151 DS.getFriendSpecLoc()); 5152 else 5153 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI); 5154 5155 if (!D) 5156 return DeclPtrTy(); 5157 5158 D->setAccess(AS_public); 5159 CurContext->addDecl(D); 5160 5161 return DeclPtrTy::make(D); 5162} 5163 5164Sema::DeclPtrTy 5165Sema::ActOnFriendFunctionDecl(Scope *S, 5166 Declarator &D, 5167 bool IsDefinition, 5168 MultiTemplateParamsArg TemplateParams) { 5169 const DeclSpec &DS = D.getDeclSpec(); 5170 5171 assert(DS.isFriendSpecified()); 5172 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 5173 5174 SourceLocation Loc = D.getIdentifierLoc(); 5175 TypeSourceInfo *TInfo = 0; 5176 QualType T = GetTypeForDeclarator(D, S, &TInfo); 5177 5178 // C++ [class.friend]p1 5179 // A friend of a class is a function or class.... 5180 // Note that this sees through typedefs, which is intended. 5181 // It *doesn't* see through dependent types, which is correct 5182 // according to [temp.arg.type]p3: 5183 // If a declaration acquires a function type through a 5184 // type dependent on a template-parameter and this causes 5185 // a declaration that does not use the syntactic form of a 5186 // function declarator to have a function type, the program 5187 // is ill-formed. 5188 if (!T->isFunctionType()) { 5189 Diag(Loc, diag::err_unexpected_friend); 5190 5191 // It might be worthwhile to try to recover by creating an 5192 // appropriate declaration. 5193 return DeclPtrTy(); 5194 } 5195 5196 // C++ [namespace.memdef]p3 5197 // - If a friend declaration in a non-local class first declares a 5198 // class or function, the friend class or function is a member 5199 // of the innermost enclosing namespace. 5200 // - The name of the friend is not found by simple name lookup 5201 // until a matching declaration is provided in that namespace 5202 // scope (either before or after the class declaration granting 5203 // friendship). 5204 // - If a friend function is called, its name may be found by the 5205 // name lookup that considers functions from namespaces and 5206 // classes associated with the types of the function arguments. 5207 // - When looking for a prior declaration of a class or a function 5208 // declared as a friend, scopes outside the innermost enclosing 5209 // namespace scope are not considered. 5210 5211 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec(); 5212 DeclarationName Name = GetNameForDeclarator(D); 5213 assert(Name); 5214 5215 // The context we found the declaration in, or in which we should 5216 // create the declaration. 5217 DeclContext *DC; 5218 5219 // FIXME: handle local classes 5220 5221 // Recover from invalid scope qualifiers as if they just weren't there. 5222 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName, 5223 ForRedeclaration); 5224 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) { 5225 // FIXME: RequireCompleteDeclContext 5226 DC = computeDeclContext(ScopeQual); 5227 5228 // FIXME: handle dependent contexts 5229 if (!DC) return DeclPtrTy(); 5230 5231 LookupQualifiedName(Previous, DC); 5232 5233 // If searching in that context implicitly found a declaration in 5234 // a different context, treat it like it wasn't found at all. 5235 // TODO: better diagnostics for this case. Suggesting the right 5236 // qualified scope would be nice... 5237 // FIXME: getRepresentativeDecl() is not right here at all 5238 if (Previous.empty() || 5239 !Previous.getRepresentativeDecl()->getDeclContext()->Equals(DC)) { 5240 D.setInvalidType(); 5241 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T; 5242 return DeclPtrTy(); 5243 } 5244 5245 // C++ [class.friend]p1: A friend of a class is a function or 5246 // class that is not a member of the class . . . 5247 if (DC->Equals(CurContext)) 5248 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member); 5249 5250 // Otherwise walk out to the nearest namespace scope looking for matches. 5251 } else { 5252 // TODO: handle local class contexts. 5253 5254 DC = CurContext; 5255 while (true) { 5256 // Skip class contexts. If someone can cite chapter and verse 5257 // for this behavior, that would be nice --- it's what GCC and 5258 // EDG do, and it seems like a reasonable intent, but the spec 5259 // really only says that checks for unqualified existing 5260 // declarations should stop at the nearest enclosing namespace, 5261 // not that they should only consider the nearest enclosing 5262 // namespace. 5263 while (DC->isRecord()) 5264 DC = DC->getParent(); 5265 5266 LookupQualifiedName(Previous, DC); 5267 5268 // TODO: decide what we think about using declarations. 5269 if (!Previous.empty()) 5270 break; 5271 5272 if (DC->isFileContext()) break; 5273 DC = DC->getParent(); 5274 } 5275 5276 // C++ [class.friend]p1: A friend of a class is a function or 5277 // class that is not a member of the class . . . 5278 // C++0x changes this for both friend types and functions. 5279 // Most C++ 98 compilers do seem to give an error here, so 5280 // we do, too. 5281 if (!Previous.empty() && DC->Equals(CurContext) 5282 && !getLangOptions().CPlusPlus0x) 5283 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member); 5284 } 5285 5286 if (DC->isFileContext()) { 5287 // This implies that it has to be an operator or function. 5288 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName || 5289 D.getName().getKind() == UnqualifiedId::IK_DestructorName || 5290 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) { 5291 Diag(Loc, diag::err_introducing_special_friend) << 5292 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 : 5293 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2); 5294 return DeclPtrTy(); 5295 } 5296 } 5297 5298 bool Redeclaration = false; 5299 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, TInfo, Previous, 5300 move(TemplateParams), 5301 IsDefinition, 5302 Redeclaration); 5303 if (!ND) return DeclPtrTy(); 5304 5305 assert(ND->getDeclContext() == DC); 5306 assert(ND->getLexicalDeclContext() == CurContext); 5307 5308 // Add the function declaration to the appropriate lookup tables, 5309 // adjusting the redeclarations list as necessary. We don't 5310 // want to do this yet if the friending class is dependent. 5311 // 5312 // Also update the scope-based lookup if the target context's 5313 // lookup context is in lexical scope. 5314 if (!CurContext->isDependentContext()) { 5315 DC = DC->getLookupContext(); 5316 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false); 5317 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 5318 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 5319 } 5320 5321 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 5322 D.getIdentifierLoc(), ND, 5323 DS.getFriendSpecLoc()); 5324 FrD->setAccess(AS_public); 5325 CurContext->addDecl(FrD); 5326 5327 return DeclPtrTy::make(ND); 5328} 5329 5330void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) { 5331 AdjustDeclIfTemplate(dcl); 5332 5333 Decl *Dcl = dcl.getAs<Decl>(); 5334 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl); 5335 if (!Fn) { 5336 Diag(DelLoc, diag::err_deleted_non_function); 5337 return; 5338 } 5339 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) { 5340 Diag(DelLoc, diag::err_deleted_decl_not_first); 5341 Diag(Prev->getLocation(), diag::note_previous_declaration); 5342 // If the declaration wasn't the first, we delete the function anyway for 5343 // recovery. 5344 } 5345 Fn->setDeleted(); 5346} 5347 5348static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 5349 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E; 5350 ++CI) { 5351 Stmt *SubStmt = *CI; 5352 if (!SubStmt) 5353 continue; 5354 if (isa<ReturnStmt>(SubStmt)) 5355 Self.Diag(SubStmt->getSourceRange().getBegin(), 5356 diag::err_return_in_constructor_handler); 5357 if (!isa<Expr>(SubStmt)) 5358 SearchForReturnInStmt(Self, SubStmt); 5359 } 5360} 5361 5362void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 5363 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 5364 CXXCatchStmt *Handler = TryBlock->getHandler(I); 5365 SearchForReturnInStmt(*this, Handler); 5366 } 5367} 5368 5369bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 5370 const CXXMethodDecl *Old) { 5371 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType(); 5372 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType(); 5373 5374 if (Context.hasSameType(NewTy, OldTy) || 5375 NewTy->isDependentType() || OldTy->isDependentType()) 5376 return false; 5377 5378 // Check if the return types are covariant 5379 QualType NewClassTy, OldClassTy; 5380 5381 /// Both types must be pointers or references to classes. 5382 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 5383 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 5384 NewClassTy = NewPT->getPointeeType(); 5385 OldClassTy = OldPT->getPointeeType(); 5386 } 5387 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 5388 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 5389 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 5390 NewClassTy = NewRT->getPointeeType(); 5391 OldClassTy = OldRT->getPointeeType(); 5392 } 5393 } 5394 } 5395 5396 // The return types aren't either both pointers or references to a class type. 5397 if (NewClassTy.isNull()) { 5398 Diag(New->getLocation(), 5399 diag::err_different_return_type_for_overriding_virtual_function) 5400 << New->getDeclName() << NewTy << OldTy; 5401 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 5402 5403 return true; 5404 } 5405 5406 // C++ [class.virtual]p6: 5407 // If the return type of D::f differs from the return type of B::f, the 5408 // class type in the return type of D::f shall be complete at the point of 5409 // declaration of D::f or shall be the class type D. 5410 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 5411 if (!RT->isBeingDefined() && 5412 RequireCompleteType(New->getLocation(), NewClassTy, 5413 PDiag(diag::err_covariant_return_incomplete) 5414 << New->getDeclName())) 5415 return true; 5416 } 5417 5418 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 5419 // Check if the new class derives from the old class. 5420 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 5421 Diag(New->getLocation(), 5422 diag::err_covariant_return_not_derived) 5423 << New->getDeclName() << NewTy << OldTy; 5424 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 5425 return true; 5426 } 5427 5428 // Check if we the conversion from derived to base is valid. 5429 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy, 5430 diag::err_covariant_return_inaccessible_base, 5431 diag::err_covariant_return_ambiguous_derived_to_base_conv, 5432 // FIXME: Should this point to the return type? 5433 New->getLocation(), SourceRange(), New->getDeclName(), 0)) { 5434 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 5435 return true; 5436 } 5437 } 5438 5439 // The qualifiers of the return types must be the same. 5440 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 5441 Diag(New->getLocation(), 5442 diag::err_covariant_return_type_different_qualifications) 5443 << New->getDeclName() << NewTy << OldTy; 5444 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 5445 return true; 5446 }; 5447 5448 5449 // The new class type must have the same or less qualifiers as the old type. 5450 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 5451 Diag(New->getLocation(), 5452 diag::err_covariant_return_type_class_type_more_qualified) 5453 << New->getDeclName() << NewTy << OldTy; 5454 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 5455 return true; 5456 }; 5457 5458 return false; 5459} 5460 5461bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 5462 const CXXMethodDecl *Old) 5463{ 5464 if (Old->hasAttr<FinalAttr>()) { 5465 Diag(New->getLocation(), diag::err_final_function_overridden) 5466 << New->getDeclName(); 5467 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 5468 return true; 5469 } 5470 5471 return false; 5472} 5473 5474/// \brief Mark the given method pure. 5475/// 5476/// \param Method the method to be marked pure. 5477/// 5478/// \param InitRange the source range that covers the "0" initializer. 5479bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 5480 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 5481 Method->setPure(); 5482 5483 // A class is abstract if at least one function is pure virtual. 5484 Method->getParent()->setAbstract(true); 5485 return false; 5486 } 5487 5488 if (!Method->isInvalidDecl()) 5489 Diag(Method->getLocation(), diag::err_non_virtual_pure) 5490 << Method->getDeclName() << InitRange; 5491 return true; 5492} 5493 5494/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 5495/// an initializer for the out-of-line declaration 'Dcl'. The scope 5496/// is a fresh scope pushed for just this purpose. 5497/// 5498/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 5499/// static data member of class X, names should be looked up in the scope of 5500/// class X. 5501void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) { 5502 // If there is no declaration, there was an error parsing it. 5503 Decl *D = Dcl.getAs<Decl>(); 5504 if (D == 0) return; 5505 5506 // We should only get called for declarations with scope specifiers, like: 5507 // int foo::bar; 5508 assert(D->isOutOfLine()); 5509 EnterDeclaratorContext(S, D->getDeclContext()); 5510} 5511 5512/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 5513/// initializer for the out-of-line declaration 'Dcl'. 5514void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) { 5515 // If there is no declaration, there was an error parsing it. 5516 Decl *D = Dcl.getAs<Decl>(); 5517 if (D == 0) return; 5518 5519 assert(D->isOutOfLine()); 5520 ExitDeclaratorContext(S); 5521} 5522 5523/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 5524/// C++ if/switch/while/for statement. 5525/// e.g: "if (int x = f()) {...}" 5526Action::DeclResult 5527Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 5528 // C++ 6.4p2: 5529 // The declarator shall not specify a function or an array. 5530 // The type-specifier-seq shall not contain typedef and shall not declare a 5531 // new class or enumeration. 5532 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 5533 "Parser allowed 'typedef' as storage class of condition decl."); 5534 5535 TypeSourceInfo *TInfo = 0; 5536 TagDecl *OwnedTag = 0; 5537 QualType Ty = GetTypeForDeclarator(D, S, &TInfo, &OwnedTag); 5538 5539 if (Ty->isFunctionType()) { // The declarator shall not specify a function... 5540 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl 5541 // would be created and CXXConditionDeclExpr wants a VarDecl. 5542 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type) 5543 << D.getSourceRange(); 5544 return DeclResult(); 5545 } else if (OwnedTag && OwnedTag->isDefinition()) { 5546 // The type-specifier-seq shall not declare a new class or enumeration. 5547 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition); 5548 } 5549 5550 DeclPtrTy Dcl = ActOnDeclarator(S, D); 5551 if (!Dcl) 5552 return DeclResult(); 5553 5554 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>()); 5555 VD->setDeclaredInCondition(true); 5556 return Dcl; 5557} 5558 5559static bool needsVTable(CXXMethodDecl *MD, ASTContext &Context) { 5560 // Ignore dependent types. 5561 if (MD->isDependentContext()) 5562 return false; 5563 5564 // Ignore declarations that are not definitions. 5565 if (!MD->isThisDeclarationADefinition()) 5566 return false; 5567 5568 CXXRecordDecl *RD = MD->getParent(); 5569 5570 // Ignore classes without a vtable. 5571 if (!RD->isDynamicClass()) 5572 return false; 5573 5574 switch (MD->getParent()->getTemplateSpecializationKind()) { 5575 case TSK_Undeclared: 5576 case TSK_ExplicitSpecialization: 5577 // Classes that aren't instantiations of templates don't need their 5578 // virtual methods marked until we see the definition of the key 5579 // function. 5580 break; 5581 5582 case TSK_ImplicitInstantiation: 5583 // This is a constructor of a class template; mark all of the virtual 5584 // members as referenced to ensure that they get instantiatied. 5585 if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) 5586 return true; 5587 break; 5588 5589 case TSK_ExplicitInstantiationDeclaration: 5590 return false; 5591 5592 case TSK_ExplicitInstantiationDefinition: 5593 // This is method of a explicit instantiation; mark all of the virtual 5594 // members as referenced to ensure that they get instantiatied. 5595 return true; 5596 } 5597 5598 // Consider only out-of-line definitions of member functions. When we see 5599 // an inline definition, it's too early to compute the key function. 5600 if (!MD->isOutOfLine()) 5601 return false; 5602 5603 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(RD); 5604 5605 // If there is no key function, we will need a copy of the vtable. 5606 if (!KeyFunction) 5607 return true; 5608 5609 // If this is the key function, we need to mark virtual members. 5610 if (KeyFunction->getCanonicalDecl() == MD->getCanonicalDecl()) 5611 return true; 5612 5613 return false; 5614} 5615 5616void Sema::MaybeMarkVirtualMembersReferenced(SourceLocation Loc, 5617 CXXMethodDecl *MD) { 5618 CXXRecordDecl *RD = MD->getParent(); 5619 5620 // We will need to mark all of the virtual members as referenced to build the 5621 // vtable. 5622 if (!needsVTable(MD, Context)) 5623 return; 5624 5625 TemplateSpecializationKind kind = RD->getTemplateSpecializationKind(); 5626 if (kind == TSK_ImplicitInstantiation) 5627 ClassesWithUnmarkedVirtualMembers.push_back(std::make_pair(RD, Loc)); 5628 else 5629 MarkVirtualMembersReferenced(Loc, RD); 5630} 5631 5632bool Sema::ProcessPendingClassesWithUnmarkedVirtualMembers() { 5633 if (ClassesWithUnmarkedVirtualMembers.empty()) 5634 return false; 5635 5636 while (!ClassesWithUnmarkedVirtualMembers.empty()) { 5637 CXXRecordDecl *RD = ClassesWithUnmarkedVirtualMembers.back().first; 5638 SourceLocation Loc = ClassesWithUnmarkedVirtualMembers.back().second; 5639 ClassesWithUnmarkedVirtualMembers.pop_back(); 5640 MarkVirtualMembersReferenced(Loc, RD); 5641 } 5642 5643 return true; 5644} 5645 5646void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 5647 const CXXRecordDecl *RD) { 5648 for (CXXRecordDecl::method_iterator i = RD->method_begin(), 5649 e = RD->method_end(); i != e; ++i) { 5650 CXXMethodDecl *MD = *i; 5651 5652 // C++ [basic.def.odr]p2: 5653 // [...] A virtual member function is used if it is not pure. [...] 5654 if (MD->isVirtual() && !MD->isPure()) 5655 MarkDeclarationReferenced(Loc, MD); 5656 } 5657 5658 // Only classes that have virtual bases need a VTT. 5659 if (RD->getNumVBases() == 0) 5660 return; 5661 5662 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(), 5663 e = RD->bases_end(); i != e; ++i) { 5664 const CXXRecordDecl *Base = 5665 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl()); 5666 if (i->isVirtual()) 5667 continue; 5668 if (Base->getNumVBases() == 0) 5669 continue; 5670 MarkVirtualMembersReferenced(Loc, Base); 5671 } 5672} 5673