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