SemaDeclCXX.cpp revision 8f809f91678d689ac7b71213de48c34c1745cca0
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 "SemaInherit.h" 16#include "clang/AST/ASTConsumer.h" 17#include "clang/AST/ASTContext.h" 18#include "clang/AST/DeclVisitor.h" 19#include "clang/AST/TypeOrdering.h" 20#include "clang/AST/StmtVisitor.h" 21#include "clang/Basic/PartialDiagnostic.h" 22#include "clang/Lex/Preprocessor.h" 23#include "clang/Parse/DeclSpec.h" 24#include "llvm/ADT/STLExtras.h" 25#include "llvm/Support/Compiler.h" 26#include <algorithm> // for std::equal 27#include <map> 28 29using namespace clang; 30 31//===----------------------------------------------------------------------===// 32// CheckDefaultArgumentVisitor 33//===----------------------------------------------------------------------===// 34 35namespace { 36 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 37 /// the default argument of a parameter to determine whether it 38 /// contains any ill-formed subexpressions. For example, this will 39 /// diagnose the use of local variables or parameters within the 40 /// default argument expression. 41 class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor 42 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 43 Expr *DefaultArg; 44 Sema *S; 45 46 public: 47 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 48 : DefaultArg(defarg), S(s) {} 49 50 bool VisitExpr(Expr *Node); 51 bool VisitDeclRefExpr(DeclRefExpr *DRE); 52 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 53 }; 54 55 /// VisitExpr - Visit all of the children of this expression. 56 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 57 bool IsInvalid = false; 58 for (Stmt::child_iterator I = Node->child_begin(), 59 E = Node->child_end(); I != E; ++I) 60 IsInvalid |= Visit(*I); 61 return IsInvalid; 62 } 63 64 /// VisitDeclRefExpr - Visit a reference to a declaration, to 65 /// determine whether this declaration can be used in the default 66 /// argument expression. 67 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 68 NamedDecl *Decl = DRE->getDecl(); 69 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 70 // C++ [dcl.fct.default]p9 71 // Default arguments are evaluated each time the function is 72 // called. The order of evaluation of function arguments is 73 // unspecified. Consequently, parameters of a function shall not 74 // be used in default argument expressions, even if they are not 75 // evaluated. Parameters of a function declared before a default 76 // argument expression are in scope and can hide namespace and 77 // class member names. 78 return S->Diag(DRE->getSourceRange().getBegin(), 79 diag::err_param_default_argument_references_param) 80 << Param->getDeclName() << DefaultArg->getSourceRange(); 81 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 82 // C++ [dcl.fct.default]p7 83 // Local variables shall not be used in default argument 84 // expressions. 85 if (VDecl->isBlockVarDecl()) 86 return S->Diag(DRE->getSourceRange().getBegin(), 87 diag::err_param_default_argument_references_local) 88 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 89 } 90 91 return false; 92 } 93 94 /// VisitCXXThisExpr - Visit a C++ "this" expression. 95 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 96 // C++ [dcl.fct.default]p8: 97 // The keyword this shall not be used in a default argument of a 98 // member function. 99 return S->Diag(ThisE->getSourceRange().getBegin(), 100 diag::err_param_default_argument_references_this) 101 << ThisE->getSourceRange(); 102 } 103} 104 105bool 106Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg, 107 SourceLocation EqualLoc) 108{ 109 QualType ParamType = Param->getType(); 110 111 if (RequireCompleteType(Param->getLocation(), Param->getType(), 112 diag::err_typecheck_decl_incomplete_type)) { 113 Param->setInvalidDecl(); 114 return true; 115 } 116 117 Expr *Arg = (Expr *)DefaultArg.get(); 118 119 // C++ [dcl.fct.default]p5 120 // A default argument expression is implicitly converted (clause 121 // 4) to the parameter type. The default argument expression has 122 // the same semantic constraints as the initializer expression in 123 // a declaration of a variable of the parameter type, using the 124 // copy-initialization semantics (8.5). 125 if (CheckInitializerTypes(Arg, ParamType, EqualLoc, 126 Param->getDeclName(), /*DirectInit=*/false)) 127 return true; 128 129 Arg = MaybeCreateCXXExprWithTemporaries(Arg, /*DestroyTemps=*/false); 130 131 // Okay: add the default argument to the parameter 132 Param->setDefaultArg(Arg); 133 134 DefaultArg.release(); 135 136 return false; 137} 138 139/// ActOnParamDefaultArgument - Check whether the default argument 140/// provided for a function parameter is well-formed. If so, attach it 141/// to the parameter declaration. 142void 143Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc, 144 ExprArg defarg) { 145 if (!param || !defarg.get()) 146 return; 147 148 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>()); 149 UnparsedDefaultArgLocs.erase(Param); 150 151 ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>()); 152 QualType ParamType = Param->getType(); 153 154 // Default arguments are only permitted in C++ 155 if (!getLangOptions().CPlusPlus) { 156 Diag(EqualLoc, diag::err_param_default_argument) 157 << DefaultArg->getSourceRange(); 158 Param->setInvalidDecl(); 159 return; 160 } 161 162 // Check that the default argument is well-formed 163 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this); 164 if (DefaultArgChecker.Visit(DefaultArg.get())) { 165 Param->setInvalidDecl(); 166 return; 167 } 168 169 SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc); 170} 171 172/// ActOnParamUnparsedDefaultArgument - We've seen a default 173/// argument for a function parameter, but we can't parse it yet 174/// because we're inside a class definition. Note that this default 175/// argument will be parsed later. 176void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param, 177 SourceLocation EqualLoc, 178 SourceLocation ArgLoc) { 179 if (!param) 180 return; 181 182 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>()); 183 if (Param) 184 Param->setUnparsedDefaultArg(); 185 186 UnparsedDefaultArgLocs[Param] = ArgLoc; 187} 188 189/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 190/// the default argument for the parameter param failed. 191void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) { 192 if (!param) 193 return; 194 195 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>()); 196 197 Param->setInvalidDecl(); 198 199 UnparsedDefaultArgLocs.erase(Param); 200} 201 202/// CheckExtraCXXDefaultArguments - Check for any extra default 203/// arguments in the declarator, which is not a function declaration 204/// or definition and therefore is not permitted to have default 205/// arguments. This routine should be invoked for every declarator 206/// that is not a function declaration or definition. 207void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 208 // C++ [dcl.fct.default]p3 209 // A default argument expression shall be specified only in the 210 // parameter-declaration-clause of a function declaration or in a 211 // template-parameter (14.1). It shall not be specified for a 212 // parameter pack. If it is specified in a 213 // parameter-declaration-clause, it shall not occur within a 214 // declarator or abstract-declarator of a parameter-declaration. 215 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 216 DeclaratorChunk &chunk = D.getTypeObject(i); 217 if (chunk.Kind == DeclaratorChunk::Function) { 218 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) { 219 ParmVarDecl *Param = 220 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>()); 221 if (Param->hasUnparsedDefaultArg()) { 222 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens; 223 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 224 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation()); 225 delete Toks; 226 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0; 227 } else if (Param->getDefaultArg()) { 228 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 229 << Param->getDefaultArg()->getSourceRange(); 230 Param->setDefaultArg(0); 231 } 232 } 233 } 234 } 235} 236 237// MergeCXXFunctionDecl - Merge two declarations of the same C++ 238// function, once we already know that they have the same 239// type. Subroutine of MergeFunctionDecl. Returns true if there was an 240// error, false otherwise. 241bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) { 242 bool Invalid = false; 243 244 // C++ [dcl.fct.default]p4: 245 // 246 // For non-template functions, default arguments can be added in 247 // later declarations of a function in the same 248 // scope. Declarations in different scopes have completely 249 // distinct sets of default arguments. That is, declarations in 250 // inner scopes do not acquire default arguments from 251 // declarations in outer scopes, and vice versa. In a given 252 // function declaration, all parameters subsequent to a 253 // parameter with a default argument shall have default 254 // arguments supplied in this or previous declarations. A 255 // default argument shall not be redefined by a later 256 // declaration (not even to the same value). 257 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 258 ParmVarDecl *OldParam = Old->getParamDecl(p); 259 ParmVarDecl *NewParam = New->getParamDecl(p); 260 261 if(OldParam->getDefaultArg() && NewParam->getDefaultArg()) { 262 Diag(NewParam->getLocation(), 263 diag::err_param_default_argument_redefinition) 264 << NewParam->getDefaultArg()->getSourceRange(); 265 Diag(OldParam->getLocation(), diag::note_previous_definition); 266 Invalid = true; 267 } else if (OldParam->getDefaultArg()) { 268 // Merge the old default argument into the new parameter 269 NewParam->setDefaultArg(OldParam->getDefaultArg()); 270 } 271 } 272 273 if (CheckEquivalentExceptionSpec( 274 Old->getType()->getAsFunctionProtoType(), Old->getLocation(), 275 New->getType()->getAsFunctionProtoType(), New->getLocation())) { 276 Invalid = true; 277 } 278 279 return Invalid; 280} 281 282/// CheckCXXDefaultArguments - Verify that the default arguments for a 283/// function declaration are well-formed according to C++ 284/// [dcl.fct.default]. 285void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 286 unsigned NumParams = FD->getNumParams(); 287 unsigned p; 288 289 // Find first parameter with a default argument 290 for (p = 0; p < NumParams; ++p) { 291 ParmVarDecl *Param = FD->getParamDecl(p); 292 if (Param->hasDefaultArg()) 293 break; 294 } 295 296 // C++ [dcl.fct.default]p4: 297 // In a given function declaration, all parameters 298 // subsequent to a parameter with a default argument shall 299 // have default arguments supplied in this or previous 300 // declarations. A default argument shall not be redefined 301 // by a later declaration (not even to the same value). 302 unsigned LastMissingDefaultArg = 0; 303 for(; p < NumParams; ++p) { 304 ParmVarDecl *Param = FD->getParamDecl(p); 305 if (!Param->hasDefaultArg()) { 306 if (Param->isInvalidDecl()) 307 /* We already complained about this parameter. */; 308 else if (Param->getIdentifier()) 309 Diag(Param->getLocation(), 310 diag::err_param_default_argument_missing_name) 311 << Param->getIdentifier(); 312 else 313 Diag(Param->getLocation(), 314 diag::err_param_default_argument_missing); 315 316 LastMissingDefaultArg = p; 317 } 318 } 319 320 if (LastMissingDefaultArg > 0) { 321 // Some default arguments were missing. Clear out all of the 322 // default arguments up to (and including) the last missing 323 // default argument, so that we leave the function parameters 324 // in a semantically valid state. 325 for (p = 0; p <= LastMissingDefaultArg; ++p) { 326 ParmVarDecl *Param = FD->getParamDecl(p); 327 if (Param->hasDefaultArg()) { 328 if (!Param->hasUnparsedDefaultArg()) 329 Param->getDefaultArg()->Destroy(Context); 330 Param->setDefaultArg(0); 331 } 332 } 333 } 334} 335 336/// isCurrentClassName - Determine whether the identifier II is the 337/// name of the class type currently being defined. In the case of 338/// nested classes, this will only return true if II is the name of 339/// the innermost class. 340bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 341 const CXXScopeSpec *SS) { 342 CXXRecordDecl *CurDecl; 343 if (SS && SS->isSet() && !SS->isInvalid()) { 344 DeclContext *DC = computeDeclContext(*SS, true); 345 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 346 } else 347 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 348 349 if (CurDecl) 350 return &II == CurDecl->getIdentifier(); 351 else 352 return false; 353} 354 355/// \brief Check the validity of a C++ base class specifier. 356/// 357/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 358/// and returns NULL otherwise. 359CXXBaseSpecifier * 360Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 361 SourceRange SpecifierRange, 362 bool Virtual, AccessSpecifier Access, 363 QualType BaseType, 364 SourceLocation BaseLoc) { 365 // C++ [class.union]p1: 366 // A union shall not have base classes. 367 if (Class->isUnion()) { 368 Diag(Class->getLocation(), diag::err_base_clause_on_union) 369 << SpecifierRange; 370 return 0; 371 } 372 373 if (BaseType->isDependentType()) 374 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 375 Class->getTagKind() == RecordDecl::TK_class, 376 Access, BaseType); 377 378 // Base specifiers must be record types. 379 if (!BaseType->isRecordType()) { 380 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 381 return 0; 382 } 383 384 // C++ [class.union]p1: 385 // A union shall not be used as a base class. 386 if (BaseType->isUnionType()) { 387 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 388 return 0; 389 } 390 391 // C++ [class.derived]p2: 392 // The class-name in a base-specifier shall not be an incompletely 393 // defined class. 394 if (RequireCompleteType(BaseLoc, BaseType, 395 PDiag(diag::err_incomplete_base_class) 396 << SpecifierRange)) 397 return 0; 398 399 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 400 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 401 assert(BaseDecl && "Record type has no declaration"); 402 BaseDecl = BaseDecl->getDefinition(Context); 403 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 404 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 405 assert(CXXBaseDecl && "Base type is not a C++ type"); 406 if (!CXXBaseDecl->isEmpty()) 407 Class->setEmpty(false); 408 if (CXXBaseDecl->isPolymorphic()) 409 Class->setPolymorphic(true); 410 411 // C++ [dcl.init.aggr]p1: 412 // An aggregate is [...] a class with [...] no base classes [...]. 413 Class->setAggregate(false); 414 Class->setPOD(false); 415 416 if (Virtual) { 417 // C++ [class.ctor]p5: 418 // A constructor is trivial if its class has no virtual base classes. 419 Class->setHasTrivialConstructor(false); 420 421 // C++ [class.copy]p6: 422 // A copy constructor is trivial if its class has no virtual base classes. 423 Class->setHasTrivialCopyConstructor(false); 424 425 // C++ [class.copy]p11: 426 // A copy assignment operator is trivial if its class has no virtual 427 // base classes. 428 Class->setHasTrivialCopyAssignment(false); 429 430 // C++0x [meta.unary.prop] is_empty: 431 // T is a class type, but not a union type, with ... no virtual base 432 // classes 433 Class->setEmpty(false); 434 } else { 435 // C++ [class.ctor]p5: 436 // A constructor is trivial if all the direct base classes of its 437 // class have trivial constructors. 438 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialConstructor()) 439 Class->setHasTrivialConstructor(false); 440 441 // C++ [class.copy]p6: 442 // A copy constructor is trivial if all the direct base classes of its 443 // class have trivial copy constructors. 444 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyConstructor()) 445 Class->setHasTrivialCopyConstructor(false); 446 447 // C++ [class.copy]p11: 448 // A copy assignment operator is trivial if all the direct base classes 449 // of its class have trivial copy assignment operators. 450 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyAssignment()) 451 Class->setHasTrivialCopyAssignment(false); 452 } 453 454 // C++ [class.ctor]p3: 455 // A destructor is trivial if all the direct base classes of its class 456 // have trivial destructors. 457 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialDestructor()) 458 Class->setHasTrivialDestructor(false); 459 460 // Create the base specifier. 461 // FIXME: Allocate via ASTContext? 462 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 463 Class->getTagKind() == RecordDecl::TK_class, 464 Access, BaseType); 465} 466 467/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 468/// one entry in the base class list of a class specifier, for 469/// example: 470/// class foo : public bar, virtual private baz { 471/// 'public bar' and 'virtual private baz' are each base-specifiers. 472Sema::BaseResult 473Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange, 474 bool Virtual, AccessSpecifier Access, 475 TypeTy *basetype, SourceLocation BaseLoc) { 476 if (!classdecl) 477 return true; 478 479 AdjustDeclIfTemplate(classdecl); 480 CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>()); 481 QualType BaseType = GetTypeFromParser(basetype); 482 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 483 Virtual, Access, 484 BaseType, BaseLoc)) 485 return BaseSpec; 486 487 return true; 488} 489 490/// \brief Performs the actual work of attaching the given base class 491/// specifiers to a C++ class. 492bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 493 unsigned NumBases) { 494 if (NumBases == 0) 495 return false; 496 497 // Used to keep track of which base types we have already seen, so 498 // that we can properly diagnose redundant direct base types. Note 499 // that the key is always the unqualified canonical type of the base 500 // class. 501 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 502 503 // Copy non-redundant base specifiers into permanent storage. 504 unsigned NumGoodBases = 0; 505 bool Invalid = false; 506 for (unsigned idx = 0; idx < NumBases; ++idx) { 507 QualType NewBaseType 508 = Context.getCanonicalType(Bases[idx]->getType()); 509 NewBaseType = NewBaseType.getUnqualifiedType(); 510 511 if (KnownBaseTypes[NewBaseType]) { 512 // C++ [class.mi]p3: 513 // A class shall not be specified as a direct base class of a 514 // derived class more than once. 515 Diag(Bases[idx]->getSourceRange().getBegin(), 516 diag::err_duplicate_base_class) 517 << KnownBaseTypes[NewBaseType]->getType() 518 << Bases[idx]->getSourceRange(); 519 520 // Delete the duplicate base class specifier; we're going to 521 // overwrite its pointer later. 522 Context.Deallocate(Bases[idx]); 523 524 Invalid = true; 525 } else { 526 // Okay, add this new base class. 527 KnownBaseTypes[NewBaseType] = Bases[idx]; 528 Bases[NumGoodBases++] = Bases[idx]; 529 } 530 } 531 532 // Attach the remaining base class specifiers to the derived class. 533 Class->setBases(Context, Bases, NumGoodBases); 534 535 // Delete the remaining (good) base class specifiers, since their 536 // data has been copied into the CXXRecordDecl. 537 for (unsigned idx = 0; idx < NumGoodBases; ++idx) 538 Context.Deallocate(Bases[idx]); 539 540 return Invalid; 541} 542 543/// ActOnBaseSpecifiers - Attach the given base specifiers to the 544/// class, after checking whether there are any duplicate base 545/// classes. 546void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases, 547 unsigned NumBases) { 548 if (!ClassDecl || !Bases || !NumBases) 549 return; 550 551 AdjustDeclIfTemplate(ClassDecl); 552 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()), 553 (CXXBaseSpecifier**)(Bases), NumBases); 554} 555 556//===----------------------------------------------------------------------===// 557// C++ class member Handling 558//===----------------------------------------------------------------------===// 559 560/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 561/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 562/// bitfield width if there is one and 'InitExpr' specifies the initializer if 563/// any. 564Sema::DeclPtrTy 565Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 566 MultiTemplateParamsArg TemplateParameterLists, 567 ExprTy *BW, ExprTy *InitExpr, bool Deleted) { 568 const DeclSpec &DS = D.getDeclSpec(); 569 DeclarationName Name = GetNameForDeclarator(D); 570 Expr *BitWidth = static_cast<Expr*>(BW); 571 Expr *Init = static_cast<Expr*>(InitExpr); 572 SourceLocation Loc = D.getIdentifierLoc(); 573 574 bool isFunc = D.isFunctionDeclarator(); 575 576 assert(!DS.isFriendSpecified()); 577 578 // C++ 9.2p6: A member shall not be declared to have automatic storage 579 // duration (auto, register) or with the extern storage-class-specifier. 580 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 581 // data members and cannot be applied to names declared const or static, 582 // and cannot be applied to reference members. 583 switch (DS.getStorageClassSpec()) { 584 case DeclSpec::SCS_unspecified: 585 case DeclSpec::SCS_typedef: 586 case DeclSpec::SCS_static: 587 // FALL THROUGH. 588 break; 589 case DeclSpec::SCS_mutable: 590 if (isFunc) { 591 if (DS.getStorageClassSpecLoc().isValid()) 592 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 593 else 594 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function); 595 596 // FIXME: It would be nicer if the keyword was ignored only for this 597 // declarator. Otherwise we could get follow-up errors. 598 D.getMutableDeclSpec().ClearStorageClassSpecs(); 599 } else { 600 QualType T = GetTypeForDeclarator(D, S); 601 diag::kind err = static_cast<diag::kind>(0); 602 if (T->isReferenceType()) 603 err = diag::err_mutable_reference; 604 else if (T.isConstQualified()) 605 err = diag::err_mutable_const; 606 if (err != 0) { 607 if (DS.getStorageClassSpecLoc().isValid()) 608 Diag(DS.getStorageClassSpecLoc(), err); 609 else 610 Diag(DS.getThreadSpecLoc(), err); 611 // FIXME: It would be nicer if the keyword was ignored only for this 612 // declarator. Otherwise we could get follow-up errors. 613 D.getMutableDeclSpec().ClearStorageClassSpecs(); 614 } 615 } 616 break; 617 default: 618 if (DS.getStorageClassSpecLoc().isValid()) 619 Diag(DS.getStorageClassSpecLoc(), 620 diag::err_storageclass_invalid_for_member); 621 else 622 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member); 623 D.getMutableDeclSpec().ClearStorageClassSpecs(); 624 } 625 626 if (!isFunc && 627 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename && 628 D.getNumTypeObjects() == 0) { 629 // Check also for this case: 630 // 631 // typedef int f(); 632 // f a; 633 // 634 QualType TDType = GetTypeFromParser(DS.getTypeRep()); 635 isFunc = TDType->isFunctionType(); 636 } 637 638 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 639 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 640 !isFunc); 641 642 Decl *Member; 643 if (isInstField) { 644 // FIXME: Check for template parameters! 645 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth, 646 AS); 647 assert(Member && "HandleField never returns null"); 648 } else { 649 Member = HandleDeclarator(S, D, move(TemplateParameterLists), false) 650 .getAs<Decl>(); 651 if (!Member) { 652 if (BitWidth) DeleteExpr(BitWidth); 653 return DeclPtrTy(); 654 } 655 656 // Non-instance-fields can't have a bitfield. 657 if (BitWidth) { 658 if (Member->isInvalidDecl()) { 659 // don't emit another diagnostic. 660 } else if (isa<VarDecl>(Member)) { 661 // C++ 9.6p3: A bit-field shall not be a static member. 662 // "static member 'A' cannot be a bit-field" 663 Diag(Loc, diag::err_static_not_bitfield) 664 << Name << BitWidth->getSourceRange(); 665 } else if (isa<TypedefDecl>(Member)) { 666 // "typedef member 'x' cannot be a bit-field" 667 Diag(Loc, diag::err_typedef_not_bitfield) 668 << Name << BitWidth->getSourceRange(); 669 } else { 670 // A function typedef ("typedef int f(); f a;"). 671 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 672 Diag(Loc, diag::err_not_integral_type_bitfield) 673 << Name << cast<ValueDecl>(Member)->getType() 674 << BitWidth->getSourceRange(); 675 } 676 677 DeleteExpr(BitWidth); 678 BitWidth = 0; 679 Member->setInvalidDecl(); 680 } 681 682 Member->setAccess(AS); 683 684 // If we have declared a member function template, set the access of the 685 // templated declaration as well. 686 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 687 FunTmpl->getTemplatedDecl()->setAccess(AS); 688 } 689 690 assert((Name || isInstField) && "No identifier for non-field ?"); 691 692 if (Init) 693 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false); 694 if (Deleted) // FIXME: Source location is not very good. 695 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin()); 696 697 if (isInstField) { 698 FieldCollector->Add(cast<FieldDecl>(Member)); 699 return DeclPtrTy(); 700 } 701 return DeclPtrTy::make(Member); 702} 703 704/// ActOnMemInitializer - Handle a C++ member initializer. 705Sema::MemInitResult 706Sema::ActOnMemInitializer(DeclPtrTy ConstructorD, 707 Scope *S, 708 const CXXScopeSpec &SS, 709 IdentifierInfo *MemberOrBase, 710 TypeTy *TemplateTypeTy, 711 SourceLocation IdLoc, 712 SourceLocation LParenLoc, 713 ExprTy **Args, unsigned NumArgs, 714 SourceLocation *CommaLocs, 715 SourceLocation RParenLoc) { 716 if (!ConstructorD) 717 return true; 718 719 AdjustDeclIfTemplate(ConstructorD); 720 721 CXXConstructorDecl *Constructor 722 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>()); 723 if (!Constructor) { 724 // The user wrote a constructor initializer on a function that is 725 // not a C++ constructor. Ignore the error for now, because we may 726 // have more member initializers coming; we'll diagnose it just 727 // once in ActOnMemInitializers. 728 return true; 729 } 730 731 CXXRecordDecl *ClassDecl = Constructor->getParent(); 732 733 // C++ [class.base.init]p2: 734 // Names in a mem-initializer-id are looked up in the scope of the 735 // constructor’s class and, if not found in that scope, are looked 736 // up in the scope containing the constructor’s 737 // definition. [Note: if the constructor’s class contains a member 738 // with the same name as a direct or virtual base class of the 739 // class, a mem-initializer-id naming the member or base class and 740 // composed of a single identifier refers to the class member. A 741 // mem-initializer-id for the hidden base class may be specified 742 // using a qualified name. ] 743 if (!SS.getScopeRep() && !TemplateTypeTy) { 744 // Look for a member, first. 745 FieldDecl *Member = 0; 746 DeclContext::lookup_result Result 747 = ClassDecl->lookup(MemberOrBase); 748 if (Result.first != Result.second) 749 Member = dyn_cast<FieldDecl>(*Result.first); 750 751 // FIXME: Handle members of an anonymous union. 752 753 if (Member) 754 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc, 755 RParenLoc); 756 } 757 // It didn't name a member, so see if it names a class. 758 TypeTy *BaseTy = TemplateTypeTy ? TemplateTypeTy 759 : getTypeName(*MemberOrBase, IdLoc, S, &SS); 760 if (!BaseTy) 761 return Diag(IdLoc, diag::err_mem_init_not_member_or_class) 762 << MemberOrBase << SourceRange(IdLoc, RParenLoc); 763 764 QualType BaseType = GetTypeFromParser(BaseTy); 765 766 return BuildBaseInitializer(BaseType, (Expr **)Args, NumArgs, IdLoc, 767 RParenLoc, ClassDecl); 768} 769 770Sema::MemInitResult 771Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args, 772 unsigned NumArgs, SourceLocation IdLoc, 773 SourceLocation RParenLoc) { 774 bool HasDependentArg = false; 775 for (unsigned i = 0; i < NumArgs; i++) 776 HasDependentArg |= Args[i]->isTypeDependent(); 777 778 CXXConstructorDecl *C = 0; 779 QualType FieldType = Member->getType(); 780 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 781 FieldType = Array->getElementType(); 782 if (FieldType->isDependentType()) { 783 // Can't check init for dependent type. 784 } else if (FieldType->getAs<RecordType>()) { 785 if (!HasDependentArg) 786 C = PerformInitializationByConstructor( 787 FieldType, (Expr **)Args, NumArgs, IdLoc, 788 SourceRange(IdLoc, RParenLoc), Member->getDeclName(), IK_Direct); 789 } else if (NumArgs != 1) { 790 return Diag(IdLoc, diag::err_mem_initializer_mismatch) 791 << Member->getDeclName() << SourceRange(IdLoc, RParenLoc); 792 } else if (!HasDependentArg) { 793 Expr *NewExp = (Expr*)Args[0]; 794 if (PerformCopyInitialization(NewExp, FieldType, "passing")) 795 return true; 796 Args[0] = NewExp; 797 } 798 // FIXME: Perform direct initialization of the member. 799 return new (Context) CXXBaseOrMemberInitializer(Member, (Expr **)Args, 800 NumArgs, C, IdLoc); 801} 802 803Sema::MemInitResult 804Sema::BuildBaseInitializer(QualType BaseType, Expr **Args, 805 unsigned NumArgs, SourceLocation IdLoc, 806 SourceLocation RParenLoc, CXXRecordDecl *ClassDecl) { 807 bool HasDependentArg = false; 808 for (unsigned i = 0; i < NumArgs; i++) 809 HasDependentArg |= Args[i]->isTypeDependent(); 810 811 if (!BaseType->isDependentType()) { 812 if (!BaseType->isRecordType()) 813 return Diag(IdLoc, diag::err_base_init_does_not_name_class) 814 << BaseType << SourceRange(IdLoc, RParenLoc); 815 816 // C++ [class.base.init]p2: 817 // [...] Unless the mem-initializer-id names a nonstatic data 818 // member of the constructor’s class or a direct or virtual base 819 // of that class, the mem-initializer is ill-formed. A 820 // mem-initializer-list can initialize a base class using any 821 // name that denotes that base class type. 822 823 // First, check for a direct base class. 824 const CXXBaseSpecifier *DirectBaseSpec = 0; 825 for (CXXRecordDecl::base_class_const_iterator Base = 826 ClassDecl->bases_begin(); Base != ClassDecl->bases_end(); ++Base) { 827 if (Context.getCanonicalType(BaseType).getUnqualifiedType() == 828 Context.getCanonicalType(Base->getType()).getUnqualifiedType()) { 829 // We found a direct base of this type. That's what we're 830 // initializing. 831 DirectBaseSpec = &*Base; 832 break; 833 } 834 } 835 836 // Check for a virtual base class. 837 // FIXME: We might be able to short-circuit this if we know in advance that 838 // there are no virtual bases. 839 const CXXBaseSpecifier *VirtualBaseSpec = 0; 840 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 841 // We haven't found a base yet; search the class hierarchy for a 842 // virtual base class. 843 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 844 /*DetectVirtual=*/false); 845 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) { 846 for (BasePaths::paths_iterator Path = Paths.begin(); 847 Path != Paths.end(); ++Path) { 848 if (Path->back().Base->isVirtual()) { 849 VirtualBaseSpec = Path->back().Base; 850 break; 851 } 852 } 853 } 854 } 855 856 // C++ [base.class.init]p2: 857 // If a mem-initializer-id is ambiguous because it designates both 858 // a direct non-virtual base class and an inherited virtual base 859 // class, the mem-initializer is ill-formed. 860 if (DirectBaseSpec && VirtualBaseSpec) 861 return Diag(IdLoc, diag::err_base_init_direct_and_virtual) 862 << BaseType << SourceRange(IdLoc, RParenLoc); 863 // C++ [base.class.init]p2: 864 // Unless the mem-initializer-id names a nonstatic data membeer of the 865 // constructor's class ot a direst or virtual base of that class, the 866 // mem-initializer is ill-formed. 867 if (!DirectBaseSpec && !VirtualBaseSpec) 868 return Diag(IdLoc, diag::err_not_direct_base_or_virtual) 869 << BaseType << ClassDecl->getNameAsCString() 870 << SourceRange(IdLoc, RParenLoc); 871 } 872 873 CXXConstructorDecl *C = 0; 874 if (!BaseType->isDependentType() && !HasDependentArg) { 875 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 876 Context.getCanonicalType(BaseType)); 877 C = PerformInitializationByConstructor(BaseType, (Expr **)Args, NumArgs, 878 IdLoc, SourceRange(IdLoc, RParenLoc), 879 Name, IK_Direct); 880 } 881 882 return new (Context) CXXBaseOrMemberInitializer(BaseType, (Expr **)Args, 883 NumArgs, C, IdLoc); 884} 885 886void 887Sema::BuildBaseOrMemberInitializers(ASTContext &C, 888 CXXConstructorDecl *Constructor, 889 CXXBaseOrMemberInitializer **Initializers, 890 unsigned NumInitializers 891 ) { 892 llvm::SmallVector<CXXBaseSpecifier *, 4>Bases; 893 llvm::SmallVector<FieldDecl *, 4>Members; 894 895 Constructor->setBaseOrMemberInitializers(C, 896 Initializers, NumInitializers, 897 Bases, Members); 898 for (unsigned int i = 0; i < Bases.size(); i++) 899 Diag(Bases[i]->getSourceRange().getBegin(), 900 diag::err_missing_default_constructor) << 0 << Bases[i]->getType(); 901 for (unsigned int i = 0; i < Members.size(); i++) 902 Diag(Members[i]->getLocation(), diag::err_missing_default_constructor) 903 << 1 << Members[i]->getType(); 904} 905 906static void *GetKeyForTopLevelField(FieldDecl *Field) { 907 // For anonymous unions, use the class declaration as the key. 908 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 909 if (RT->getDecl()->isAnonymousStructOrUnion()) 910 return static_cast<void *>(RT->getDecl()); 911 } 912 return static_cast<void *>(Field); 913} 914 915static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member, 916 bool MemberMaybeAnon=false) { 917 // For fields injected into the class via declaration of an anonymous union, 918 // use its anonymous union class declaration as the unique key. 919 if (FieldDecl *Field = Member->getMember()) { 920 // After BuildBaseOrMemberInitializers call, Field is the anonymous union 921 // data member of the class. Data member used in the initializer list is 922 // in AnonUnionMember field. 923 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion()) 924 Field = Member->getAnonUnionMember(); 925 if (Field->getDeclContext()->isRecord()) { 926 RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext()); 927 if (RD->isAnonymousStructOrUnion()) 928 return static_cast<void *>(RD); 929 } 930 return static_cast<void *>(Field); 931 } 932 return static_cast<RecordType *>(Member->getBaseClass()); 933} 934 935void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl, 936 SourceLocation ColonLoc, 937 MemInitTy **MemInits, unsigned NumMemInits) { 938 if (!ConstructorDecl) 939 return; 940 941 AdjustDeclIfTemplate(ConstructorDecl); 942 943 CXXConstructorDecl *Constructor 944 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>()); 945 946 if (!Constructor) { 947 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 948 return; 949 } 950 951 if (!Constructor->isDependentContext()) { 952 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members; 953 bool err = false; 954 for (unsigned i = 0; i < NumMemInits; i++) { 955 CXXBaseOrMemberInitializer *Member = 956 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]); 957 void *KeyToMember = GetKeyForMember(Member); 958 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember]; 959 if (!PrevMember) { 960 PrevMember = Member; 961 continue; 962 } 963 if (FieldDecl *Field = Member->getMember()) 964 Diag(Member->getSourceLocation(), 965 diag::error_multiple_mem_initialization) 966 << Field->getNameAsString(); 967 else { 968 Type *BaseClass = Member->getBaseClass(); 969 assert(BaseClass && "ActOnMemInitializers - neither field or base"); 970 Diag(Member->getSourceLocation(), 971 diag::error_multiple_base_initialization) 972 << BaseClass->getDesugaredType(true); 973 } 974 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer) 975 << 0; 976 err = true; 977 } 978 979 if (err) 980 return; 981 } 982 983 BuildBaseOrMemberInitializers(Context, Constructor, 984 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits), 985 NumMemInits); 986 987 if (Constructor->isDependentContext()) 988 return; 989 990 if (Diags.getDiagnosticLevel(diag::warn_base_initialized) == 991 Diagnostic::Ignored && 992 Diags.getDiagnosticLevel(diag::warn_field_initialized) == 993 Diagnostic::Ignored) 994 return; 995 996 // Also issue warning if order of ctor-initializer list does not match order 997 // of 1) base class declarations and 2) order of non-static data members. 998 llvm::SmallVector<const void*, 32> AllBaseOrMembers; 999 1000 CXXRecordDecl *ClassDecl 1001 = cast<CXXRecordDecl>(Constructor->getDeclContext()); 1002 // Push virtual bases before others. 1003 for (CXXRecordDecl::base_class_iterator VBase = 1004 ClassDecl->vbases_begin(), 1005 E = ClassDecl->vbases_end(); VBase != E; ++VBase) 1006 AllBaseOrMembers.push_back(VBase->getType()->getAs<RecordType>()); 1007 1008 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 1009 E = ClassDecl->bases_end(); Base != E; ++Base) { 1010 // Virtuals are alread in the virtual base list and are constructed 1011 // first. 1012 if (Base->isVirtual()) 1013 continue; 1014 AllBaseOrMembers.push_back(Base->getType()->getAs<RecordType>()); 1015 } 1016 1017 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 1018 E = ClassDecl->field_end(); Field != E; ++Field) 1019 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field)); 1020 1021 int Last = AllBaseOrMembers.size(); 1022 int curIndex = 0; 1023 CXXBaseOrMemberInitializer *PrevMember = 0; 1024 for (unsigned i = 0; i < NumMemInits; i++) { 1025 CXXBaseOrMemberInitializer *Member = 1026 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]); 1027 void *MemberInCtorList = GetKeyForMember(Member, true); 1028 1029 for (; curIndex < Last; curIndex++) 1030 if (MemberInCtorList == AllBaseOrMembers[curIndex]) 1031 break; 1032 if (curIndex == Last) { 1033 assert(PrevMember && "Member not in member list?!"); 1034 // Initializer as specified in ctor-initializer list is out of order. 1035 // Issue a warning diagnostic. 1036 if (PrevMember->isBaseInitializer()) { 1037 // Diagnostics is for an initialized base class. 1038 Type *BaseClass = PrevMember->getBaseClass(); 1039 Diag(PrevMember->getSourceLocation(), 1040 diag::warn_base_initialized) 1041 << BaseClass->getDesugaredType(true); 1042 } else { 1043 FieldDecl *Field = PrevMember->getMember(); 1044 Diag(PrevMember->getSourceLocation(), 1045 diag::warn_field_initialized) 1046 << Field->getNameAsString(); 1047 } 1048 // Also the note! 1049 if (FieldDecl *Field = Member->getMember()) 1050 Diag(Member->getSourceLocation(), 1051 diag::note_fieldorbase_initialized_here) << 0 1052 << Field->getNameAsString(); 1053 else { 1054 Type *BaseClass = Member->getBaseClass(); 1055 Diag(Member->getSourceLocation(), 1056 diag::note_fieldorbase_initialized_here) << 1 1057 << BaseClass->getDesugaredType(true); 1058 } 1059 for (curIndex = 0; curIndex < Last; curIndex++) 1060 if (MemberInCtorList == AllBaseOrMembers[curIndex]) 1061 break; 1062 } 1063 PrevMember = Member; 1064 } 1065} 1066 1067void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) { 1068 if (!CDtorDecl) 1069 return; 1070 1071 AdjustDeclIfTemplate(CDtorDecl); 1072 1073 if (CXXConstructorDecl *Constructor 1074 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>())) 1075 BuildBaseOrMemberInitializers(Context, 1076 Constructor, 1077 (CXXBaseOrMemberInitializer **)0, 0); 1078} 1079 1080namespace { 1081 /// PureVirtualMethodCollector - traverses a class and its superclasses 1082 /// and determines if it has any pure virtual methods. 1083 class VISIBILITY_HIDDEN PureVirtualMethodCollector { 1084 ASTContext &Context; 1085 1086 public: 1087 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList; 1088 1089 private: 1090 MethodList Methods; 1091 1092 void Collect(const CXXRecordDecl* RD, MethodList& Methods); 1093 1094 public: 1095 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD) 1096 : Context(Ctx) { 1097 1098 MethodList List; 1099 Collect(RD, List); 1100 1101 // Copy the temporary list to methods, and make sure to ignore any 1102 // null entries. 1103 for (size_t i = 0, e = List.size(); i != e; ++i) { 1104 if (List[i]) 1105 Methods.push_back(List[i]); 1106 } 1107 } 1108 1109 bool empty() const { return Methods.empty(); } 1110 1111 MethodList::const_iterator methods_begin() { return Methods.begin(); } 1112 MethodList::const_iterator methods_end() { return Methods.end(); } 1113 }; 1114 1115 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD, 1116 MethodList& Methods) { 1117 // First, collect the pure virtual methods for the base classes. 1118 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(), 1119 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) { 1120 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) { 1121 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl()); 1122 if (BaseDecl && BaseDecl->isAbstract()) 1123 Collect(BaseDecl, Methods); 1124 } 1125 } 1126 1127 // Next, zero out any pure virtual methods that this class overrides. 1128 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy; 1129 1130 MethodSetTy OverriddenMethods; 1131 size_t MethodsSize = Methods.size(); 1132 1133 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end(); 1134 i != e; ++i) { 1135 // Traverse the record, looking for methods. 1136 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) { 1137 // If the method is pure virtual, add it to the methods vector. 1138 if (MD->isPure()) { 1139 Methods.push_back(MD); 1140 continue; 1141 } 1142 1143 // Otherwise, record all the overridden methods in our set. 1144 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 1145 E = MD->end_overridden_methods(); I != E; ++I) { 1146 // Keep track of the overridden methods. 1147 OverriddenMethods.insert(*I); 1148 } 1149 } 1150 } 1151 1152 // Now go through the methods and zero out all the ones we know are 1153 // overridden. 1154 for (size_t i = 0, e = MethodsSize; i != e; ++i) { 1155 if (OverriddenMethods.count(Methods[i])) 1156 Methods[i] = 0; 1157 } 1158 1159 } 1160} 1161 1162 1163bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 1164 unsigned DiagID, AbstractDiagSelID SelID, 1165 const CXXRecordDecl *CurrentRD) { 1166 if (SelID == -1) 1167 return RequireNonAbstractType(Loc, T, 1168 PDiag(DiagID), CurrentRD); 1169 else 1170 return RequireNonAbstractType(Loc, T, 1171 PDiag(DiagID) << SelID, CurrentRD); 1172} 1173 1174bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 1175 const PartialDiagnostic &PD, 1176 const CXXRecordDecl *CurrentRD) { 1177 if (!getLangOptions().CPlusPlus) 1178 return false; 1179 1180 if (const ArrayType *AT = Context.getAsArrayType(T)) 1181 return RequireNonAbstractType(Loc, AT->getElementType(), PD, 1182 CurrentRD); 1183 1184 if (const PointerType *PT = T->getAs<PointerType>()) { 1185 // Find the innermost pointer type. 1186 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 1187 PT = T; 1188 1189 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 1190 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD); 1191 } 1192 1193 const RecordType *RT = T->getAs<RecordType>(); 1194 if (!RT) 1195 return false; 1196 1197 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 1198 if (!RD) 1199 return false; 1200 1201 if (CurrentRD && CurrentRD != RD) 1202 return false; 1203 1204 if (!RD->isAbstract()) 1205 return false; 1206 1207 Diag(Loc, PD) << RD->getDeclName(); 1208 1209 // Check if we've already emitted the list of pure virtual functions for this 1210 // class. 1211 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 1212 return true; 1213 1214 PureVirtualMethodCollector Collector(Context, RD); 1215 1216 for (PureVirtualMethodCollector::MethodList::const_iterator I = 1217 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) { 1218 const CXXMethodDecl *MD = *I; 1219 1220 Diag(MD->getLocation(), diag::note_pure_virtual_function) << 1221 MD->getDeclName(); 1222 } 1223 1224 if (!PureVirtualClassDiagSet) 1225 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 1226 PureVirtualClassDiagSet->insert(RD); 1227 1228 return true; 1229} 1230 1231namespace { 1232 class VISIBILITY_HIDDEN AbstractClassUsageDiagnoser 1233 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> { 1234 Sema &SemaRef; 1235 CXXRecordDecl *AbstractClass; 1236 1237 bool VisitDeclContext(const DeclContext *DC) { 1238 bool Invalid = false; 1239 1240 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(), 1241 E = DC->decls_end(); I != E; ++I) 1242 Invalid |= Visit(*I); 1243 1244 return Invalid; 1245 } 1246 1247 public: 1248 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac) 1249 : SemaRef(SemaRef), AbstractClass(ac) { 1250 Visit(SemaRef.Context.getTranslationUnitDecl()); 1251 } 1252 1253 bool VisitFunctionDecl(const FunctionDecl *FD) { 1254 if (FD->isThisDeclarationADefinition()) { 1255 // No need to do the check if we're in a definition, because it requires 1256 // that the return/param types are complete. 1257 // because that requires 1258 return VisitDeclContext(FD); 1259 } 1260 1261 // Check the return type. 1262 QualType RTy = FD->getType()->getAsFunctionType()->getResultType(); 1263 bool Invalid = 1264 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy, 1265 diag::err_abstract_type_in_decl, 1266 Sema::AbstractReturnType, 1267 AbstractClass); 1268 1269 for (FunctionDecl::param_const_iterator I = FD->param_begin(), 1270 E = FD->param_end(); I != E; ++I) { 1271 const ParmVarDecl *VD = *I; 1272 Invalid |= 1273 SemaRef.RequireNonAbstractType(VD->getLocation(), 1274 VD->getOriginalType(), 1275 diag::err_abstract_type_in_decl, 1276 Sema::AbstractParamType, 1277 AbstractClass); 1278 } 1279 1280 return Invalid; 1281 } 1282 1283 bool VisitDecl(const Decl* D) { 1284 if (const DeclContext *DC = dyn_cast<DeclContext>(D)) 1285 return VisitDeclContext(DC); 1286 1287 return false; 1288 } 1289 }; 1290} 1291 1292void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 1293 DeclPtrTy TagDecl, 1294 SourceLocation LBrac, 1295 SourceLocation RBrac) { 1296 if (!TagDecl) 1297 return; 1298 1299 AdjustDeclIfTemplate(TagDecl); 1300 ActOnFields(S, RLoc, TagDecl, 1301 (DeclPtrTy*)FieldCollector->getCurFields(), 1302 FieldCollector->getCurNumFields(), LBrac, RBrac, 0); 1303 1304 CXXRecordDecl *RD = cast<CXXRecordDecl>(TagDecl.getAs<Decl>()); 1305 if (!RD->isAbstract()) { 1306 // Collect all the pure virtual methods and see if this is an abstract 1307 // class after all. 1308 PureVirtualMethodCollector Collector(Context, RD); 1309 if (!Collector.empty()) 1310 RD->setAbstract(true); 1311 } 1312 1313 if (RD->isAbstract()) 1314 AbstractClassUsageDiagnoser(*this, RD); 1315 1316 if (!RD->isDependentType()) 1317 AddImplicitlyDeclaredMembersToClass(RD); 1318} 1319 1320/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 1321/// special functions, such as the default constructor, copy 1322/// constructor, or destructor, to the given C++ class (C++ 1323/// [special]p1). This routine can only be executed just before the 1324/// definition of the class is complete. 1325void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 1326 CanQualType ClassType 1327 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 1328 1329 // FIXME: Implicit declarations have exception specifications, which are 1330 // the union of the specifications of the implicitly called functions. 1331 1332 if (!ClassDecl->hasUserDeclaredConstructor()) { 1333 // C++ [class.ctor]p5: 1334 // A default constructor for a class X is a constructor of class X 1335 // that can be called without an argument. If there is no 1336 // user-declared constructor for class X, a default constructor is 1337 // implicitly declared. An implicitly-declared default constructor 1338 // is an inline public member of its class. 1339 DeclarationName Name 1340 = Context.DeclarationNames.getCXXConstructorName(ClassType); 1341 CXXConstructorDecl *DefaultCon = 1342 CXXConstructorDecl::Create(Context, ClassDecl, 1343 ClassDecl->getLocation(), Name, 1344 Context.getFunctionType(Context.VoidTy, 1345 0, 0, false, 0), 1346 /*DInfo=*/0, 1347 /*isExplicit=*/false, 1348 /*isInline=*/true, 1349 /*isImplicitlyDeclared=*/true); 1350 DefaultCon->setAccess(AS_public); 1351 DefaultCon->setImplicit(); 1352 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor()); 1353 ClassDecl->addDecl(DefaultCon); 1354 } 1355 1356 if (!ClassDecl->hasUserDeclaredCopyConstructor()) { 1357 // C++ [class.copy]p4: 1358 // If the class definition does not explicitly declare a copy 1359 // constructor, one is declared implicitly. 1360 1361 // C++ [class.copy]p5: 1362 // The implicitly-declared copy constructor for a class X will 1363 // have the form 1364 // 1365 // X::X(const X&) 1366 // 1367 // if 1368 bool HasConstCopyConstructor = true; 1369 1370 // -- each direct or virtual base class B of X has a copy 1371 // constructor whose first parameter is of type const B& or 1372 // const volatile B&, and 1373 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(); 1374 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) { 1375 const CXXRecordDecl *BaseClassDecl 1376 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 1377 HasConstCopyConstructor 1378 = BaseClassDecl->hasConstCopyConstructor(Context); 1379 } 1380 1381 // -- for all the nonstatic data members of X that are of a 1382 // class type M (or array thereof), each such class type 1383 // has a copy constructor whose first parameter is of type 1384 // const M& or const volatile M&. 1385 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(); 1386 HasConstCopyConstructor && Field != ClassDecl->field_end(); 1387 ++Field) { 1388 QualType FieldType = (*Field)->getType(); 1389 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 1390 FieldType = Array->getElementType(); 1391 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 1392 const CXXRecordDecl *FieldClassDecl 1393 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 1394 HasConstCopyConstructor 1395 = FieldClassDecl->hasConstCopyConstructor(Context); 1396 } 1397 } 1398 1399 // Otherwise, the implicitly declared copy constructor will have 1400 // the form 1401 // 1402 // X::X(X&) 1403 QualType ArgType = ClassType; 1404 if (HasConstCopyConstructor) 1405 ArgType = ArgType.withConst(); 1406 ArgType = Context.getLValueReferenceType(ArgType); 1407 1408 // An implicitly-declared copy constructor is an inline public 1409 // member of its class. 1410 DeclarationName Name 1411 = Context.DeclarationNames.getCXXConstructorName(ClassType); 1412 CXXConstructorDecl *CopyConstructor 1413 = CXXConstructorDecl::Create(Context, ClassDecl, 1414 ClassDecl->getLocation(), Name, 1415 Context.getFunctionType(Context.VoidTy, 1416 &ArgType, 1, 1417 false, 0), 1418 /*DInfo=*/0, 1419 /*isExplicit=*/false, 1420 /*isInline=*/true, 1421 /*isImplicitlyDeclared=*/true); 1422 CopyConstructor->setAccess(AS_public); 1423 CopyConstructor->setImplicit(); 1424 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor()); 1425 1426 // Add the parameter to the constructor. 1427 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 1428 ClassDecl->getLocation(), 1429 /*IdentifierInfo=*/0, 1430 ArgType, /*DInfo=*/0, 1431 VarDecl::None, 0); 1432 CopyConstructor->setParams(Context, &FromParam, 1); 1433 ClassDecl->addDecl(CopyConstructor); 1434 } 1435 1436 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 1437 // Note: The following rules are largely analoguous to the copy 1438 // constructor rules. Note that virtual bases are not taken into account 1439 // for determining the argument type of the operator. Note also that 1440 // operators taking an object instead of a reference are allowed. 1441 // 1442 // C++ [class.copy]p10: 1443 // If the class definition does not explicitly declare a copy 1444 // assignment operator, one is declared implicitly. 1445 // The implicitly-defined copy assignment operator for a class X 1446 // will have the form 1447 // 1448 // X& X::operator=(const X&) 1449 // 1450 // if 1451 bool HasConstCopyAssignment = true; 1452 1453 // -- each direct base class B of X has a copy assignment operator 1454 // whose parameter is of type const B&, const volatile B& or B, 1455 // and 1456 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(); 1457 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) { 1458 const CXXRecordDecl *BaseClassDecl 1459 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 1460 const CXXMethodDecl *MD = 0; 1461 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context, 1462 MD); 1463 } 1464 1465 // -- for all the nonstatic data members of X that are of a class 1466 // type M (or array thereof), each such class type has a copy 1467 // assignment operator whose parameter is of type const M&, 1468 // const volatile M& or M. 1469 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(); 1470 HasConstCopyAssignment && Field != ClassDecl->field_end(); 1471 ++Field) { 1472 QualType FieldType = (*Field)->getType(); 1473 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 1474 FieldType = Array->getElementType(); 1475 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 1476 const CXXRecordDecl *FieldClassDecl 1477 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 1478 const CXXMethodDecl *MD = 0; 1479 HasConstCopyAssignment 1480 = FieldClassDecl->hasConstCopyAssignment(Context, MD); 1481 } 1482 } 1483 1484 // Otherwise, the implicitly declared copy assignment operator will 1485 // have the form 1486 // 1487 // X& X::operator=(X&) 1488 QualType ArgType = ClassType; 1489 QualType RetType = Context.getLValueReferenceType(ArgType); 1490 if (HasConstCopyAssignment) 1491 ArgType = ArgType.withConst(); 1492 ArgType = Context.getLValueReferenceType(ArgType); 1493 1494 // An implicitly-declared copy assignment operator is an inline public 1495 // member of its class. 1496 DeclarationName Name = 1497 Context.DeclarationNames.getCXXOperatorName(OO_Equal); 1498 CXXMethodDecl *CopyAssignment = 1499 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name, 1500 Context.getFunctionType(RetType, &ArgType, 1, 1501 false, 0), 1502 /*DInfo=*/0, /*isStatic=*/false, /*isInline=*/true); 1503 CopyAssignment->setAccess(AS_public); 1504 CopyAssignment->setImplicit(); 1505 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment()); 1506 CopyAssignment->setCopyAssignment(true); 1507 1508 // Add the parameter to the operator. 1509 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 1510 ClassDecl->getLocation(), 1511 /*IdentifierInfo=*/0, 1512 ArgType, /*DInfo=*/0, 1513 VarDecl::None, 0); 1514 CopyAssignment->setParams(Context, &FromParam, 1); 1515 1516 // Don't call addedAssignmentOperator. There is no way to distinguish an 1517 // implicit from an explicit assignment operator. 1518 ClassDecl->addDecl(CopyAssignment); 1519 } 1520 1521 if (!ClassDecl->hasUserDeclaredDestructor()) { 1522 // C++ [class.dtor]p2: 1523 // If a class has no user-declared destructor, a destructor is 1524 // declared implicitly. An implicitly-declared destructor is an 1525 // inline public member of its class. 1526 DeclarationName Name 1527 = Context.DeclarationNames.getCXXDestructorName(ClassType); 1528 CXXDestructorDecl *Destructor 1529 = CXXDestructorDecl::Create(Context, ClassDecl, 1530 ClassDecl->getLocation(), Name, 1531 Context.getFunctionType(Context.VoidTy, 1532 0, 0, false, 0), 1533 /*isInline=*/true, 1534 /*isImplicitlyDeclared=*/true); 1535 Destructor->setAccess(AS_public); 1536 Destructor->setImplicit(); 1537 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 1538 ClassDecl->addDecl(Destructor); 1539 } 1540} 1541 1542void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) { 1543 TemplateDecl *Template = TemplateD.getAs<TemplateDecl>(); 1544 if (!Template) 1545 return; 1546 1547 TemplateParameterList *Params = Template->getTemplateParameters(); 1548 for (TemplateParameterList::iterator Param = Params->begin(), 1549 ParamEnd = Params->end(); 1550 Param != ParamEnd; ++Param) { 1551 NamedDecl *Named = cast<NamedDecl>(*Param); 1552 if (Named->getDeclName()) { 1553 S->AddDecl(DeclPtrTy::make(Named)); 1554 IdResolver.AddDecl(Named); 1555 } 1556 } 1557} 1558 1559/// ActOnStartDelayedCXXMethodDeclaration - We have completed 1560/// parsing a top-level (non-nested) C++ class, and we are now 1561/// parsing those parts of the given Method declaration that could 1562/// not be parsed earlier (C++ [class.mem]p2), such as default 1563/// arguments. This action should enter the scope of the given 1564/// Method declaration as if we had just parsed the qualified method 1565/// name. However, it should not bring the parameters into scope; 1566/// that will be performed by ActOnDelayedCXXMethodParameter. 1567void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) { 1568 if (!MethodD) 1569 return; 1570 1571 AdjustDeclIfTemplate(MethodD); 1572 1573 CXXScopeSpec SS; 1574 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>()); 1575 QualType ClassTy 1576 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 1577 SS.setScopeRep( 1578 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr())); 1579 ActOnCXXEnterDeclaratorScope(S, SS); 1580} 1581 1582/// ActOnDelayedCXXMethodParameter - We've already started a delayed 1583/// C++ method declaration. We're (re-)introducing the given 1584/// function parameter into scope for use in parsing later parts of 1585/// the method declaration. For example, we could see an 1586/// ActOnParamDefaultArgument event for this parameter. 1587void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) { 1588 if (!ParamD) 1589 return; 1590 1591 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>()); 1592 1593 // If this parameter has an unparsed default argument, clear it out 1594 // to make way for the parsed default argument. 1595 if (Param->hasUnparsedDefaultArg()) 1596 Param->setDefaultArg(0); 1597 1598 S->AddDecl(DeclPtrTy::make(Param)); 1599 if (Param->getDeclName()) 1600 IdResolver.AddDecl(Param); 1601} 1602 1603/// ActOnFinishDelayedCXXMethodDeclaration - We have finished 1604/// processing the delayed method declaration for Method. The method 1605/// declaration is now considered finished. There may be a separate 1606/// ActOnStartOfFunctionDef action later (not necessarily 1607/// immediately!) for this method, if it was also defined inside the 1608/// class body. 1609void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) { 1610 if (!MethodD) 1611 return; 1612 1613 AdjustDeclIfTemplate(MethodD); 1614 1615 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>()); 1616 CXXScopeSpec SS; 1617 QualType ClassTy 1618 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 1619 SS.setScopeRep( 1620 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr())); 1621 ActOnCXXExitDeclaratorScope(S, SS); 1622 1623 // Now that we have our default arguments, check the constructor 1624 // again. It could produce additional diagnostics or affect whether 1625 // the class has implicitly-declared destructors, among other 1626 // things. 1627 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 1628 CheckConstructor(Constructor); 1629 1630 // Check the default arguments, which we may have added. 1631 if (!Method->isInvalidDecl()) 1632 CheckCXXDefaultArguments(Method); 1633} 1634 1635/// CheckConstructorDeclarator - Called by ActOnDeclarator to check 1636/// the well-formedness of the constructor declarator @p D with type @p 1637/// R. If there are any errors in the declarator, this routine will 1638/// emit diagnostics and set the invalid bit to true. In any case, the type 1639/// will be updated to reflect a well-formed type for the constructor and 1640/// returned. 1641QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 1642 FunctionDecl::StorageClass &SC) { 1643 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 1644 1645 // C++ [class.ctor]p3: 1646 // A constructor shall not be virtual (10.3) or static (9.4). A 1647 // constructor can be invoked for a const, volatile or const 1648 // volatile object. A constructor shall not be declared const, 1649 // volatile, or const volatile (9.3.2). 1650 if (isVirtual) { 1651 if (!D.isInvalidType()) 1652 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 1653 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 1654 << SourceRange(D.getIdentifierLoc()); 1655 D.setInvalidType(); 1656 } 1657 if (SC == FunctionDecl::Static) { 1658 if (!D.isInvalidType()) 1659 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 1660 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 1661 << SourceRange(D.getIdentifierLoc()); 1662 D.setInvalidType(); 1663 SC = FunctionDecl::None; 1664 } 1665 1666 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 1667 if (FTI.TypeQuals != 0) { 1668 if (FTI.TypeQuals & QualType::Const) 1669 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 1670 << "const" << SourceRange(D.getIdentifierLoc()); 1671 if (FTI.TypeQuals & QualType::Volatile) 1672 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 1673 << "volatile" << SourceRange(D.getIdentifierLoc()); 1674 if (FTI.TypeQuals & QualType::Restrict) 1675 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 1676 << "restrict" << SourceRange(D.getIdentifierLoc()); 1677 } 1678 1679 // Rebuild the function type "R" without any type qualifiers (in 1680 // case any of the errors above fired) and with "void" as the 1681 // return type, since constructors don't have return types. We 1682 // *always* have to do this, because GetTypeForDeclarator will 1683 // put in a result type of "int" when none was specified. 1684 const FunctionProtoType *Proto = R->getAsFunctionProtoType(); 1685 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(), 1686 Proto->getNumArgs(), 1687 Proto->isVariadic(), 0); 1688} 1689 1690/// CheckConstructor - Checks a fully-formed constructor for 1691/// well-formedness, issuing any diagnostics required. Returns true if 1692/// the constructor declarator is invalid. 1693void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 1694 CXXRecordDecl *ClassDecl 1695 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 1696 if (!ClassDecl) 1697 return Constructor->setInvalidDecl(); 1698 1699 // C++ [class.copy]p3: 1700 // A declaration of a constructor for a class X is ill-formed if 1701 // its first parameter is of type (optionally cv-qualified) X and 1702 // either there are no other parameters or else all other 1703 // parameters have default arguments. 1704 if (!Constructor->isInvalidDecl() && 1705 ((Constructor->getNumParams() == 1) || 1706 (Constructor->getNumParams() > 1 && 1707 Constructor->getParamDecl(1)->hasDefaultArg()))) { 1708 QualType ParamType = Constructor->getParamDecl(0)->getType(); 1709 QualType ClassTy = Context.getTagDeclType(ClassDecl); 1710 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 1711 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 1712 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 1713 << CodeModificationHint::CreateInsertion(ParamLoc, " const &"); 1714 Constructor->setInvalidDecl(); 1715 } 1716 } 1717 1718 // Notify the class that we've added a constructor. 1719 ClassDecl->addedConstructor(Context, Constructor); 1720} 1721 1722static inline bool 1723FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) { 1724 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 1725 FTI.ArgInfo[0].Param && 1726 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType()); 1727} 1728 1729/// CheckDestructorDeclarator - Called by ActOnDeclarator to check 1730/// the well-formednes of the destructor declarator @p D with type @p 1731/// R. If there are any errors in the declarator, this routine will 1732/// emit diagnostics and set the declarator to invalid. Even if this happens, 1733/// will be updated to reflect a well-formed type for the destructor and 1734/// returned. 1735QualType Sema::CheckDestructorDeclarator(Declarator &D, 1736 FunctionDecl::StorageClass& SC) { 1737 // C++ [class.dtor]p1: 1738 // [...] A typedef-name that names a class is a class-name 1739 // (7.1.3); however, a typedef-name that names a class shall not 1740 // be used as the identifier in the declarator for a destructor 1741 // declaration. 1742 QualType DeclaratorType = GetTypeFromParser(D.getDeclaratorIdType()); 1743 if (isa<TypedefType>(DeclaratorType)) { 1744 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 1745 << DeclaratorType; 1746 D.setInvalidType(); 1747 } 1748 1749 // C++ [class.dtor]p2: 1750 // A destructor is used to destroy objects of its class type. A 1751 // destructor takes no parameters, and no return type can be 1752 // specified for it (not even void). The address of a destructor 1753 // shall not be taken. A destructor shall not be static. A 1754 // destructor can be invoked for a const, volatile or const 1755 // volatile object. A destructor shall not be declared const, 1756 // volatile or const volatile (9.3.2). 1757 if (SC == FunctionDecl::Static) { 1758 if (!D.isInvalidType()) 1759 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 1760 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 1761 << SourceRange(D.getIdentifierLoc()); 1762 SC = FunctionDecl::None; 1763 D.setInvalidType(); 1764 } 1765 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 1766 // Destructors don't have return types, but the parser will 1767 // happily parse something like: 1768 // 1769 // class X { 1770 // float ~X(); 1771 // }; 1772 // 1773 // The return type will be eliminated later. 1774 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 1775 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 1776 << SourceRange(D.getIdentifierLoc()); 1777 } 1778 1779 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 1780 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 1781 if (FTI.TypeQuals & QualType::Const) 1782 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 1783 << "const" << SourceRange(D.getIdentifierLoc()); 1784 if (FTI.TypeQuals & QualType::Volatile) 1785 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 1786 << "volatile" << SourceRange(D.getIdentifierLoc()); 1787 if (FTI.TypeQuals & QualType::Restrict) 1788 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 1789 << "restrict" << SourceRange(D.getIdentifierLoc()); 1790 D.setInvalidType(); 1791 } 1792 1793 // Make sure we don't have any parameters. 1794 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) { 1795 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 1796 1797 // Delete the parameters. 1798 FTI.freeArgs(); 1799 D.setInvalidType(); 1800 } 1801 1802 // Make sure the destructor isn't variadic. 1803 if (FTI.isVariadic) { 1804 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 1805 D.setInvalidType(); 1806 } 1807 1808 // Rebuild the function type "R" without any type qualifiers or 1809 // parameters (in case any of the errors above fired) and with 1810 // "void" as the return type, since destructors don't have return 1811 // types. We *always* have to do this, because GetTypeForDeclarator 1812 // will put in a result type of "int" when none was specified. 1813 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0); 1814} 1815 1816/// CheckConversionDeclarator - Called by ActOnDeclarator to check the 1817/// well-formednes of the conversion function declarator @p D with 1818/// type @p R. If there are any errors in the declarator, this routine 1819/// will emit diagnostics and return true. Otherwise, it will return 1820/// false. Either way, the type @p R will be updated to reflect a 1821/// well-formed type for the conversion operator. 1822void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 1823 FunctionDecl::StorageClass& SC) { 1824 // C++ [class.conv.fct]p1: 1825 // Neither parameter types nor return type can be specified. The 1826 // type of a conversion function (8.3.5) is "function taking no 1827 // parameter returning conversion-type-id." 1828 if (SC == FunctionDecl::Static) { 1829 if (!D.isInvalidType()) 1830 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 1831 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 1832 << SourceRange(D.getIdentifierLoc()); 1833 D.setInvalidType(); 1834 SC = FunctionDecl::None; 1835 } 1836 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 1837 // Conversion functions don't have return types, but the parser will 1838 // happily parse something like: 1839 // 1840 // class X { 1841 // float operator bool(); 1842 // }; 1843 // 1844 // The return type will be changed later anyway. 1845 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 1846 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 1847 << SourceRange(D.getIdentifierLoc()); 1848 } 1849 1850 // Make sure we don't have any parameters. 1851 if (R->getAsFunctionProtoType()->getNumArgs() > 0) { 1852 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 1853 1854 // Delete the parameters. 1855 D.getTypeObject(0).Fun.freeArgs(); 1856 D.setInvalidType(); 1857 } 1858 1859 // Make sure the conversion function isn't variadic. 1860 if (R->getAsFunctionProtoType()->isVariadic() && !D.isInvalidType()) { 1861 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 1862 D.setInvalidType(); 1863 } 1864 1865 // C++ [class.conv.fct]p4: 1866 // The conversion-type-id shall not represent a function type nor 1867 // an array type. 1868 QualType ConvType = GetTypeFromParser(D.getDeclaratorIdType()); 1869 if (ConvType->isArrayType()) { 1870 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 1871 ConvType = Context.getPointerType(ConvType); 1872 D.setInvalidType(); 1873 } else if (ConvType->isFunctionType()) { 1874 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 1875 ConvType = Context.getPointerType(ConvType); 1876 D.setInvalidType(); 1877 } 1878 1879 // Rebuild the function type "R" without any parameters (in case any 1880 // of the errors above fired) and with the conversion type as the 1881 // return type. 1882 R = Context.getFunctionType(ConvType, 0, 0, false, 1883 R->getAsFunctionProtoType()->getTypeQuals()); 1884 1885 // C++0x explicit conversion operators. 1886 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x) 1887 Diag(D.getDeclSpec().getExplicitSpecLoc(), 1888 diag::warn_explicit_conversion_functions) 1889 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 1890} 1891 1892/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 1893/// the declaration of the given C++ conversion function. This routine 1894/// is responsible for recording the conversion function in the C++ 1895/// class, if possible. 1896Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 1897 assert(Conversion && "Expected to receive a conversion function declaration"); 1898 1899 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 1900 1901 // Make sure we aren't redeclaring the conversion function. 1902 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 1903 1904 // C++ [class.conv.fct]p1: 1905 // [...] A conversion function is never used to convert a 1906 // (possibly cv-qualified) object to the (possibly cv-qualified) 1907 // same object type (or a reference to it), to a (possibly 1908 // cv-qualified) base class of that type (or a reference to it), 1909 // or to (possibly cv-qualified) void. 1910 // FIXME: Suppress this warning if the conversion function ends up being a 1911 // virtual function that overrides a virtual function in a base class. 1912 QualType ClassType 1913 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 1914 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 1915 ConvType = ConvTypeRef->getPointeeType(); 1916 if (ConvType->isRecordType()) { 1917 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 1918 if (ConvType == ClassType) 1919 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 1920 << ClassType; 1921 else if (IsDerivedFrom(ClassType, ConvType)) 1922 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 1923 << ClassType << ConvType; 1924 } else if (ConvType->isVoidType()) { 1925 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 1926 << ClassType << ConvType; 1927 } 1928 1929 if (Conversion->getPreviousDeclaration()) { 1930 const NamedDecl *ExpectedPrevDecl = Conversion->getPreviousDeclaration(); 1931 if (FunctionTemplateDecl *ConversionTemplate 1932 = Conversion->getDescribedFunctionTemplate()) 1933 ExpectedPrevDecl = ConversionTemplate->getPreviousDeclaration(); 1934 OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions(); 1935 for (OverloadedFunctionDecl::function_iterator 1936 Conv = Conversions->function_begin(), 1937 ConvEnd = Conversions->function_end(); 1938 Conv != ConvEnd; ++Conv) { 1939 if (*Conv == ExpectedPrevDecl) { 1940 *Conv = Conversion; 1941 return DeclPtrTy::make(Conversion); 1942 } 1943 } 1944 assert(Conversion->isInvalidDecl() && "Conversion should not get here."); 1945 } else if (FunctionTemplateDecl *ConversionTemplate 1946 = Conversion->getDescribedFunctionTemplate()) 1947 ClassDecl->addConversionFunction(Context, ConversionTemplate); 1948 else if (!Conversion->getPrimaryTemplate()) // ignore specializations 1949 ClassDecl->addConversionFunction(Context, Conversion); 1950 1951 return DeclPtrTy::make(Conversion); 1952} 1953 1954//===----------------------------------------------------------------------===// 1955// Namespace Handling 1956//===----------------------------------------------------------------------===// 1957 1958/// ActOnStartNamespaceDef - This is called at the start of a namespace 1959/// definition. 1960Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 1961 SourceLocation IdentLoc, 1962 IdentifierInfo *II, 1963 SourceLocation LBrace) { 1964 NamespaceDecl *Namespc = 1965 NamespaceDecl::Create(Context, CurContext, IdentLoc, II); 1966 Namespc->setLBracLoc(LBrace); 1967 1968 Scope *DeclRegionScope = NamespcScope->getParent(); 1969 1970 if (II) { 1971 // C++ [namespace.def]p2: 1972 // The identifier in an original-namespace-definition shall not have been 1973 // previously defined in the declarative region in which the 1974 // original-namespace-definition appears. The identifier in an 1975 // original-namespace-definition is the name of the namespace. Subsequently 1976 // in that declarative region, it is treated as an original-namespace-name. 1977 1978 NamedDecl *PrevDecl = LookupName(DeclRegionScope, II, LookupOrdinaryName, 1979 true); 1980 1981 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) { 1982 // This is an extended namespace definition. 1983 // Attach this namespace decl to the chain of extended namespace 1984 // definitions. 1985 OrigNS->setNextNamespace(Namespc); 1986 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace()); 1987 1988 // Remove the previous declaration from the scope. 1989 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) { 1990 IdResolver.RemoveDecl(OrigNS); 1991 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS)); 1992 } 1993 } else if (PrevDecl) { 1994 // This is an invalid name redefinition. 1995 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind) 1996 << Namespc->getDeclName(); 1997 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 1998 Namespc->setInvalidDecl(); 1999 // Continue on to push Namespc as current DeclContext and return it. 2000 } 2001 2002 PushOnScopeChains(Namespc, DeclRegionScope); 2003 } else { 2004 // FIXME: Handle anonymous namespaces 2005 } 2006 2007 // Although we could have an invalid decl (i.e. the namespace name is a 2008 // redefinition), push it as current DeclContext and try to continue parsing. 2009 // FIXME: We should be able to push Namespc here, so that the each DeclContext 2010 // for the namespace has the declarations that showed up in that particular 2011 // namespace definition. 2012 PushDeclContext(NamespcScope, Namespc); 2013 return DeclPtrTy::make(Namespc); 2014} 2015 2016/// ActOnFinishNamespaceDef - This callback is called after a namespace is 2017/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 2018void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) { 2019 Decl *Dcl = D.getAs<Decl>(); 2020 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 2021 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 2022 Namespc->setRBracLoc(RBrace); 2023 PopDeclContext(); 2024} 2025 2026Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S, 2027 SourceLocation UsingLoc, 2028 SourceLocation NamespcLoc, 2029 const CXXScopeSpec &SS, 2030 SourceLocation IdentLoc, 2031 IdentifierInfo *NamespcName, 2032 AttributeList *AttrList) { 2033 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 2034 assert(NamespcName && "Invalid NamespcName."); 2035 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 2036 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 2037 2038 UsingDirectiveDecl *UDir = 0; 2039 2040 // Lookup namespace name. 2041 LookupResult R = LookupParsedName(S, &SS, NamespcName, 2042 LookupNamespaceName, false); 2043 if (R.isAmbiguous()) { 2044 DiagnoseAmbiguousLookup(R, NamespcName, IdentLoc); 2045 return DeclPtrTy(); 2046 } 2047 if (NamedDecl *NS = R) { 2048 assert(isa<NamespaceDecl>(NS) && "expected namespace decl"); 2049 // C++ [namespace.udir]p1: 2050 // A using-directive specifies that the names in the nominated 2051 // namespace can be used in the scope in which the 2052 // using-directive appears after the using-directive. During 2053 // unqualified name lookup (3.4.1), the names appear as if they 2054 // were declared in the nearest enclosing namespace which 2055 // contains both the using-directive and the nominated 2056 // namespace. [Note: in this context, "contains" means "contains 2057 // directly or indirectly". ] 2058 2059 // Find enclosing context containing both using-directive and 2060 // nominated namespace. 2061 DeclContext *CommonAncestor = cast<DeclContext>(NS); 2062 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 2063 CommonAncestor = CommonAncestor->getParent(); 2064 2065 UDir = UsingDirectiveDecl::Create(Context, 2066 CurContext, UsingLoc, 2067 NamespcLoc, 2068 SS.getRange(), 2069 (NestedNameSpecifier *)SS.getScopeRep(), 2070 IdentLoc, 2071 cast<NamespaceDecl>(NS), 2072 CommonAncestor); 2073 PushUsingDirective(S, UDir); 2074 } else { 2075 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 2076 } 2077 2078 // FIXME: We ignore attributes for now. 2079 delete AttrList; 2080 return DeclPtrTy::make(UDir); 2081} 2082 2083void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 2084 // If scope has associated entity, then using directive is at namespace 2085 // or translation unit scope. We add UsingDirectiveDecls, into 2086 // it's lookup structure. 2087 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) 2088 Ctx->addDecl(UDir); 2089 else 2090 // Otherwise it is block-sope. using-directives will affect lookup 2091 // only to the end of scope. 2092 S->PushUsingDirective(DeclPtrTy::make(UDir)); 2093} 2094 2095 2096Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S, 2097 SourceLocation UsingLoc, 2098 const CXXScopeSpec &SS, 2099 SourceLocation IdentLoc, 2100 IdentifierInfo *TargetName, 2101 OverloadedOperatorKind Op, 2102 AttributeList *AttrList, 2103 bool IsTypeName) { 2104 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 2105 assert((TargetName || Op) && "Invalid TargetName."); 2106 assert(IdentLoc.isValid() && "Invalid TargetName location."); 2107 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 2108 2109 UsingDecl *UsingAlias = 0; 2110 2111 DeclarationName Name; 2112 if (TargetName) 2113 Name = TargetName; 2114 else 2115 Name = Context.DeclarationNames.getCXXOperatorName(Op); 2116 2117 // FIXME: Implement this properly! 2118 if (isUnknownSpecialization(SS)) { 2119 Diag(IdentLoc, diag::err_using_dependent_unsupported); 2120 delete AttrList; 2121 return DeclPtrTy::make((UsingDecl*)0); 2122 } 2123 2124 // Lookup target name. 2125 LookupResult R = LookupParsedName(S, &SS, Name, LookupOrdinaryName, false); 2126 2127 if (NamedDecl *NS = R) { 2128 if (IsTypeName && !isa<TypeDecl>(NS)) { 2129 Diag(IdentLoc, diag::err_using_typename_non_type); 2130 } 2131 UsingAlias = UsingDecl::Create(Context, CurContext, IdentLoc, SS.getRange(), 2132 NS->getLocation(), UsingLoc, NS, 2133 static_cast<NestedNameSpecifier *>(SS.getScopeRep()), 2134 IsTypeName); 2135 PushOnScopeChains(UsingAlias, S); 2136 } else { 2137 Diag(IdentLoc, diag::err_using_requires_qualname) << SS.getRange(); 2138 } 2139 2140 // FIXME: We ignore attributes for now. 2141 delete AttrList; 2142 return DeclPtrTy::make(UsingAlias); 2143} 2144 2145/// getNamespaceDecl - Returns the namespace a decl represents. If the decl 2146/// is a namespace alias, returns the namespace it points to. 2147static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 2148 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 2149 return AD->getNamespace(); 2150 return dyn_cast_or_null<NamespaceDecl>(D); 2151} 2152 2153Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S, 2154 SourceLocation NamespaceLoc, 2155 SourceLocation AliasLoc, 2156 IdentifierInfo *Alias, 2157 const CXXScopeSpec &SS, 2158 SourceLocation IdentLoc, 2159 IdentifierInfo *Ident) { 2160 2161 // Lookup the namespace name. 2162 LookupResult R = LookupParsedName(S, &SS, Ident, LookupNamespaceName, false); 2163 2164 // Check if we have a previous declaration with the same name. 2165 if (NamedDecl *PrevDecl = LookupName(S, Alias, LookupOrdinaryName, true)) { 2166 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 2167 // We already have an alias with the same name that points to the same 2168 // namespace, so don't create a new one. 2169 if (!R.isAmbiguous() && AD->getNamespace() == getNamespaceDecl(R)) 2170 return DeclPtrTy(); 2171 } 2172 2173 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition : 2174 diag::err_redefinition_different_kind; 2175 Diag(AliasLoc, DiagID) << Alias; 2176 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 2177 return DeclPtrTy(); 2178 } 2179 2180 if (R.isAmbiguous()) { 2181 DiagnoseAmbiguousLookup(R, Ident, IdentLoc); 2182 return DeclPtrTy(); 2183 } 2184 2185 if (!R) { 2186 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange(); 2187 return DeclPtrTy(); 2188 } 2189 2190 NamespaceAliasDecl *AliasDecl = 2191 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 2192 Alias, SS.getRange(), 2193 (NestedNameSpecifier *)SS.getScopeRep(), 2194 IdentLoc, R); 2195 2196 CurContext->addDecl(AliasDecl); 2197 return DeclPtrTy::make(AliasDecl); 2198} 2199 2200void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 2201 CXXConstructorDecl *Constructor) { 2202 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() && 2203 !Constructor->isUsed()) && 2204 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 2205 2206 CXXRecordDecl *ClassDecl 2207 = cast<CXXRecordDecl>(Constructor->getDeclContext()); 2208 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 2209 // Before the implicitly-declared default constructor for a class is 2210 // implicitly defined, all the implicitly-declared default constructors 2211 // for its base class and its non-static data members shall have been 2212 // implicitly defined. 2213 bool err = false; 2214 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 2215 E = ClassDecl->bases_end(); Base != E; ++Base) { 2216 CXXRecordDecl *BaseClassDecl 2217 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 2218 if (!BaseClassDecl->hasTrivialConstructor()) { 2219 if (CXXConstructorDecl *BaseCtor = 2220 BaseClassDecl->getDefaultConstructor(Context)) 2221 MarkDeclarationReferenced(CurrentLocation, BaseCtor); 2222 else { 2223 Diag(CurrentLocation, diag::err_defining_default_ctor) 2224 << Context.getTagDeclType(ClassDecl) << 1 2225 << Context.getTagDeclType(BaseClassDecl); 2226 Diag(BaseClassDecl->getLocation(), diag::note_previous_class_decl) 2227 << Context.getTagDeclType(BaseClassDecl); 2228 err = true; 2229 } 2230 } 2231 } 2232 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 2233 E = ClassDecl->field_end(); Field != E; ++Field) { 2234 QualType FieldType = Context.getCanonicalType((*Field)->getType()); 2235 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 2236 FieldType = Array->getElementType(); 2237 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 2238 CXXRecordDecl *FieldClassDecl 2239 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 2240 if (!FieldClassDecl->hasTrivialConstructor()) { 2241 if (CXXConstructorDecl *FieldCtor = 2242 FieldClassDecl->getDefaultConstructor(Context)) 2243 MarkDeclarationReferenced(CurrentLocation, FieldCtor); 2244 else { 2245 Diag(CurrentLocation, diag::err_defining_default_ctor) 2246 << Context.getTagDeclType(ClassDecl) << 0 << 2247 Context.getTagDeclType(FieldClassDecl); 2248 Diag(FieldClassDecl->getLocation(), diag::note_previous_class_decl) 2249 << Context.getTagDeclType(FieldClassDecl); 2250 err = true; 2251 } 2252 } 2253 } else if (FieldType->isReferenceType()) { 2254 Diag(CurrentLocation, diag::err_unintialized_member) 2255 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 2256 Diag((*Field)->getLocation(), diag::note_declared_at); 2257 err = true; 2258 } else if (FieldType.isConstQualified()) { 2259 Diag(CurrentLocation, diag::err_unintialized_member) 2260 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 2261 Diag((*Field)->getLocation(), diag::note_declared_at); 2262 err = true; 2263 } 2264 } 2265 if (!err) 2266 Constructor->setUsed(); 2267 else 2268 Constructor->setInvalidDecl(); 2269} 2270 2271void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 2272 CXXDestructorDecl *Destructor) { 2273 assert((Destructor->isImplicit() && !Destructor->isUsed()) && 2274 "DefineImplicitDestructor - call it for implicit default dtor"); 2275 2276 CXXRecordDecl *ClassDecl 2277 = cast<CXXRecordDecl>(Destructor->getDeclContext()); 2278 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 2279 // C++ [class.dtor] p5 2280 // Before the implicitly-declared default destructor for a class is 2281 // implicitly defined, all the implicitly-declared default destructors 2282 // for its base class and its non-static data members shall have been 2283 // implicitly defined. 2284 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 2285 E = ClassDecl->bases_end(); Base != E; ++Base) { 2286 CXXRecordDecl *BaseClassDecl 2287 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 2288 if (!BaseClassDecl->hasTrivialDestructor()) { 2289 if (CXXDestructorDecl *BaseDtor = 2290 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context))) 2291 MarkDeclarationReferenced(CurrentLocation, BaseDtor); 2292 else 2293 assert(false && 2294 "DefineImplicitDestructor - missing dtor in a base class"); 2295 } 2296 } 2297 2298 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 2299 E = ClassDecl->field_end(); Field != E; ++Field) { 2300 QualType FieldType = Context.getCanonicalType((*Field)->getType()); 2301 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 2302 FieldType = Array->getElementType(); 2303 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 2304 CXXRecordDecl *FieldClassDecl 2305 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 2306 if (!FieldClassDecl->hasTrivialDestructor()) { 2307 if (CXXDestructorDecl *FieldDtor = 2308 const_cast<CXXDestructorDecl*>( 2309 FieldClassDecl->getDestructor(Context))) 2310 MarkDeclarationReferenced(CurrentLocation, FieldDtor); 2311 else 2312 assert(false && 2313 "DefineImplicitDestructor - missing dtor in class of a data member"); 2314 } 2315 } 2316 } 2317 Destructor->setUsed(); 2318} 2319 2320void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation, 2321 CXXMethodDecl *MethodDecl) { 2322 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() && 2323 MethodDecl->getOverloadedOperator() == OO_Equal && 2324 !MethodDecl->isUsed()) && 2325 "DefineImplicitOverloadedAssign - call it for implicit assignment op"); 2326 2327 CXXRecordDecl *ClassDecl 2328 = cast<CXXRecordDecl>(MethodDecl->getDeclContext()); 2329 2330 // C++[class.copy] p12 2331 // Before the implicitly-declared copy assignment operator for a class is 2332 // implicitly defined, all implicitly-declared copy assignment operators 2333 // for its direct base classes and its nonstatic data members shall have 2334 // been implicitly defined. 2335 bool err = false; 2336 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 2337 E = ClassDecl->bases_end(); Base != E; ++Base) { 2338 CXXRecordDecl *BaseClassDecl 2339 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 2340 if (CXXMethodDecl *BaseAssignOpMethod = 2341 getAssignOperatorMethod(MethodDecl->getParamDecl(0), BaseClassDecl)) 2342 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod); 2343 } 2344 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 2345 E = ClassDecl->field_end(); Field != E; ++Field) { 2346 QualType FieldType = Context.getCanonicalType((*Field)->getType()); 2347 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 2348 FieldType = Array->getElementType(); 2349 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 2350 CXXRecordDecl *FieldClassDecl 2351 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 2352 if (CXXMethodDecl *FieldAssignOpMethod = 2353 getAssignOperatorMethod(MethodDecl->getParamDecl(0), FieldClassDecl)) 2354 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod); 2355 } else if (FieldType->isReferenceType()) { 2356 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 2357 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 2358 Diag(Field->getLocation(), diag::note_declared_at); 2359 Diag(CurrentLocation, diag::note_first_required_here); 2360 err = true; 2361 } else if (FieldType.isConstQualified()) { 2362 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 2363 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 2364 Diag(Field->getLocation(), diag::note_declared_at); 2365 Diag(CurrentLocation, diag::note_first_required_here); 2366 err = true; 2367 } 2368 } 2369 if (!err) 2370 MethodDecl->setUsed(); 2371} 2372 2373CXXMethodDecl * 2374Sema::getAssignOperatorMethod(ParmVarDecl *ParmDecl, 2375 CXXRecordDecl *ClassDecl) { 2376 QualType LHSType = Context.getTypeDeclType(ClassDecl); 2377 QualType RHSType(LHSType); 2378 // If class's assignment operator argument is const/volatile qualified, 2379 // look for operator = (const/volatile B&). Otherwise, look for 2380 // operator = (B&). 2381 if (ParmDecl->getType().isConstQualified()) 2382 RHSType.addConst(); 2383 if (ParmDecl->getType().isVolatileQualified()) 2384 RHSType.addVolatile(); 2385 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl, 2386 LHSType, 2387 SourceLocation())); 2388 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl, 2389 RHSType, 2390 SourceLocation())); 2391 Expr *Args[2] = { &*LHS, &*RHS }; 2392 OverloadCandidateSet CandidateSet; 2393 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2, 2394 CandidateSet); 2395 OverloadCandidateSet::iterator Best; 2396 if (BestViableFunction(CandidateSet, 2397 ClassDecl->getLocation(), Best) == OR_Success) 2398 return cast<CXXMethodDecl>(Best->Function); 2399 assert(false && 2400 "getAssignOperatorMethod - copy assignment operator method not found"); 2401 return 0; 2402} 2403 2404void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 2405 CXXConstructorDecl *CopyConstructor, 2406 unsigned TypeQuals) { 2407 assert((CopyConstructor->isImplicit() && 2408 CopyConstructor->isCopyConstructor(Context, TypeQuals) && 2409 !CopyConstructor->isUsed()) && 2410 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 2411 2412 CXXRecordDecl *ClassDecl 2413 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext()); 2414 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 2415 // C++ [class.copy] p209 2416 // Before the implicitly-declared copy constructor for a class is 2417 // implicitly defined, all the implicitly-declared copy constructors 2418 // for its base class and its non-static data members shall have been 2419 // implicitly defined. 2420 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(); 2421 Base != ClassDecl->bases_end(); ++Base) { 2422 CXXRecordDecl *BaseClassDecl 2423 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 2424 if (CXXConstructorDecl *BaseCopyCtor = 2425 BaseClassDecl->getCopyConstructor(Context, TypeQuals)) 2426 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor); 2427 } 2428 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 2429 FieldEnd = ClassDecl->field_end(); 2430 Field != FieldEnd; ++Field) { 2431 QualType FieldType = Context.getCanonicalType((*Field)->getType()); 2432 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 2433 FieldType = Array->getElementType(); 2434 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 2435 CXXRecordDecl *FieldClassDecl 2436 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 2437 if (CXXConstructorDecl *FieldCopyCtor = 2438 FieldClassDecl->getCopyConstructor(Context, TypeQuals)) 2439 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor); 2440 } 2441 } 2442 CopyConstructor->setUsed(); 2443} 2444 2445Sema::OwningExprResult 2446Sema::BuildCXXConstructExpr(QualType DeclInitType, 2447 CXXConstructorDecl *Constructor, 2448 Expr **Exprs, unsigned NumExprs) { 2449 bool Elidable = false; 2450 2451 // [class.copy]p15: 2452 // Whenever a temporary class object is copied using a copy constructor, and 2453 // this object and the copy have the same cv-unqualified type, an 2454 // implementation is permitted to treat the original and the copy as two 2455 // different ways of referring to the same object and not perform a copy at 2456 //all, even if the class copy constructor or destructor have side effects. 2457 2458 // FIXME: Is this enough? 2459 if (Constructor->isCopyConstructor(Context) && NumExprs == 1) { 2460 Expr *E = Exprs[0]; 2461 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E)) 2462 E = BE->getSubExpr(); 2463 2464 if (isa<CallExpr>(E) || isa<CXXTemporaryObjectExpr>(E)) 2465 Elidable = true; 2466 } 2467 2468 return BuildCXXConstructExpr(DeclInitType, Constructor, Elidable, 2469 Exprs, NumExprs); 2470} 2471 2472/// BuildCXXConstructExpr - Creates a complete call to a constructor, 2473/// including handling of its default argument expressions. 2474Sema::OwningExprResult 2475Sema::BuildCXXConstructExpr(QualType DeclInitType, 2476 CXXConstructorDecl *Constructor, 2477 bool Elidable, 2478 Expr **Exprs, 2479 unsigned NumExprs) { 2480 ExprOwningPtr<CXXConstructExpr> Temp(this, 2481 CXXConstructExpr::Create(Context, 2482 DeclInitType, 2483 Constructor, 2484 Elidable, 2485 Exprs, 2486 NumExprs)); 2487 // Default arguments must be added to constructor call expression. 2488 FunctionDecl *FDecl = cast<FunctionDecl>(Constructor); 2489 unsigned NumArgsInProto = FDecl->param_size(); 2490 for (unsigned j = NumExprs; j != NumArgsInProto; j++) { 2491 ParmVarDecl *Param = FDecl->getParamDecl(j); 2492 2493 OwningExprResult ArgExpr = 2494 BuildCXXDefaultArgExpr(/*FIXME:*/SourceLocation(), 2495 FDecl, Param); 2496 if (ArgExpr.isInvalid()) 2497 return ExprError(); 2498 2499 Temp->setArg(j, ArgExpr.takeAs<Expr>()); 2500 } 2501 return move(Temp); 2502} 2503 2504Sema::OwningExprResult 2505Sema::BuildCXXTemporaryObjectExpr(CXXConstructorDecl *Constructor, 2506 QualType Ty, 2507 SourceLocation TyBeginLoc, 2508 MultiExprArg Args, 2509 SourceLocation RParenLoc) { 2510 CXXTemporaryObjectExpr *E 2511 = new (Context) CXXTemporaryObjectExpr(Context, Constructor, Ty, TyBeginLoc, 2512 (Expr **)Args.get(), 2513 Args.size(), RParenLoc); 2514 2515 ExprOwningPtr<CXXTemporaryObjectExpr> Temp(this, E); 2516 2517 // Default arguments must be added to constructor call expression. 2518 FunctionDecl *FDecl = cast<FunctionDecl>(Constructor); 2519 unsigned NumArgsInProto = FDecl->param_size(); 2520 for (unsigned j = Args.size(); j != NumArgsInProto; j++) { 2521 ParmVarDecl *Param = FDecl->getParamDecl(j); 2522 2523 OwningExprResult ArgExpr = BuildCXXDefaultArgExpr(TyBeginLoc, FDecl, Param); 2524 if (ArgExpr.isInvalid()) 2525 return ExprError(); 2526 2527 Temp->setArg(j, ArgExpr.takeAs<Expr>()); 2528 } 2529 2530 Args.release(); 2531 return move(Temp); 2532} 2533 2534 2535bool Sema::InitializeVarWithConstructor(VarDecl *VD, 2536 CXXConstructorDecl *Constructor, 2537 QualType DeclInitType, 2538 Expr **Exprs, unsigned NumExprs) { 2539 OwningExprResult TempResult = BuildCXXConstructExpr(DeclInitType, Constructor, 2540 Exprs, NumExprs); 2541 if (TempResult.isInvalid()) 2542 return true; 2543 2544 Expr *Temp = TempResult.takeAs<Expr>(); 2545 MarkDeclarationReferenced(VD->getLocation(), Constructor); 2546 Temp = MaybeCreateCXXExprWithTemporaries(Temp, /*DestroyTemps=*/true); 2547 VD->setInit(Context, Temp); 2548 2549 return false; 2550} 2551 2552void Sema::FinalizeVarWithDestructor(VarDecl *VD, QualType DeclInitType) 2553{ 2554 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>( 2555 DeclInitType->getAs<RecordType>()->getDecl()); 2556 if (!ClassDecl->hasTrivialDestructor()) 2557 if (CXXDestructorDecl *Destructor = 2558 const_cast<CXXDestructorDecl*>(ClassDecl->getDestructor(Context))) 2559 MarkDeclarationReferenced(VD->getLocation(), Destructor); 2560} 2561 2562/// AddCXXDirectInitializerToDecl - This action is called immediately after 2563/// ActOnDeclarator, when a C++ direct initializer is present. 2564/// e.g: "int x(1);" 2565void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl, 2566 SourceLocation LParenLoc, 2567 MultiExprArg Exprs, 2568 SourceLocation *CommaLocs, 2569 SourceLocation RParenLoc) { 2570 unsigned NumExprs = Exprs.size(); 2571 assert(NumExprs != 0 && Exprs.get() && "missing expressions"); 2572 Decl *RealDecl = Dcl.getAs<Decl>(); 2573 2574 // If there is no declaration, there was an error parsing it. Just ignore 2575 // the initializer. 2576 if (RealDecl == 0) 2577 return; 2578 2579 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 2580 if (!VDecl) { 2581 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 2582 RealDecl->setInvalidDecl(); 2583 return; 2584 } 2585 2586 // We will represent direct-initialization similarly to copy-initialization: 2587 // int x(1); -as-> int x = 1; 2588 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 2589 // 2590 // Clients that want to distinguish between the two forms, can check for 2591 // direct initializer using VarDecl::hasCXXDirectInitializer(). 2592 // A major benefit is that clients that don't particularly care about which 2593 // exactly form was it (like the CodeGen) can handle both cases without 2594 // special case code. 2595 2596 // If either the declaration has a dependent type or if any of the expressions 2597 // is type-dependent, we represent the initialization via a ParenListExpr for 2598 // later use during template instantiation. 2599 if (VDecl->getType()->isDependentType() || 2600 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) { 2601 // Let clients know that initialization was done with a direct initializer. 2602 VDecl->setCXXDirectInitializer(true); 2603 2604 // Store the initialization expressions as a ParenListExpr. 2605 unsigned NumExprs = Exprs.size(); 2606 VDecl->setInit(Context, 2607 new (Context) ParenListExpr(Context, LParenLoc, 2608 (Expr **)Exprs.release(), 2609 NumExprs, RParenLoc)); 2610 return; 2611 } 2612 2613 2614 // C++ 8.5p11: 2615 // The form of initialization (using parentheses or '=') is generally 2616 // insignificant, but does matter when the entity being initialized has a 2617 // class type. 2618 QualType DeclInitType = VDecl->getType(); 2619 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType)) 2620 DeclInitType = Array->getElementType(); 2621 2622 // FIXME: This isn't the right place to complete the type. 2623 if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(), 2624 diag::err_typecheck_decl_incomplete_type)) { 2625 VDecl->setInvalidDecl(); 2626 return; 2627 } 2628 2629 if (VDecl->getType()->isRecordType()) { 2630 CXXConstructorDecl *Constructor 2631 = PerformInitializationByConstructor(DeclInitType, 2632 (Expr **)Exprs.get(), NumExprs, 2633 VDecl->getLocation(), 2634 SourceRange(VDecl->getLocation(), 2635 RParenLoc), 2636 VDecl->getDeclName(), 2637 IK_Direct); 2638 if (!Constructor) 2639 RealDecl->setInvalidDecl(); 2640 else { 2641 VDecl->setCXXDirectInitializer(true); 2642 if (InitializeVarWithConstructor(VDecl, Constructor, DeclInitType, 2643 (Expr**)Exprs.release(), NumExprs)) 2644 RealDecl->setInvalidDecl(); 2645 FinalizeVarWithDestructor(VDecl, DeclInitType); 2646 } 2647 return; 2648 } 2649 2650 if (NumExprs > 1) { 2651 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg) 2652 << SourceRange(VDecl->getLocation(), RParenLoc); 2653 RealDecl->setInvalidDecl(); 2654 return; 2655 } 2656 2657 // Let clients know that initialization was done with a direct initializer. 2658 VDecl->setCXXDirectInitializer(true); 2659 2660 assert(NumExprs == 1 && "Expected 1 expression"); 2661 // Set the init expression, handles conversions. 2662 AddInitializerToDecl(Dcl, ExprArg(*this, Exprs.release()[0]), 2663 /*DirectInit=*/true); 2664} 2665 2666/// PerformInitializationByConstructor - Perform initialization by 2667/// constructor (C++ [dcl.init]p14), which may occur as part of 2668/// direct-initialization or copy-initialization. We are initializing 2669/// an object of type @p ClassType with the given arguments @p 2670/// Args. @p Loc is the location in the source code where the 2671/// initializer occurs (e.g., a declaration, member initializer, 2672/// functional cast, etc.) while @p Range covers the whole 2673/// initialization. @p InitEntity is the entity being initialized, 2674/// which may by the name of a declaration or a type. @p Kind is the 2675/// kind of initialization we're performing, which affects whether 2676/// explicit constructors will be considered. When successful, returns 2677/// the constructor that will be used to perform the initialization; 2678/// when the initialization fails, emits a diagnostic and returns 2679/// null. 2680CXXConstructorDecl * 2681Sema::PerformInitializationByConstructor(QualType ClassType, 2682 Expr **Args, unsigned NumArgs, 2683 SourceLocation Loc, SourceRange Range, 2684 DeclarationName InitEntity, 2685 InitializationKind Kind) { 2686 const RecordType *ClassRec = ClassType->getAs<RecordType>(); 2687 assert(ClassRec && "Can only initialize a class type here"); 2688 2689 // C++ [dcl.init]p14: 2690 // 2691 // If the initialization is direct-initialization, or if it is 2692 // copy-initialization where the cv-unqualified version of the 2693 // source type is the same class as, or a derived class of, the 2694 // class of the destination, constructors are considered. The 2695 // applicable constructors are enumerated (13.3.1.3), and the 2696 // best one is chosen through overload resolution (13.3). The 2697 // constructor so selected is called to initialize the object, 2698 // with the initializer expression(s) as its argument(s). If no 2699 // constructor applies, or the overload resolution is ambiguous, 2700 // the initialization is ill-formed. 2701 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl()); 2702 OverloadCandidateSet CandidateSet; 2703 2704 // Add constructors to the overload set. 2705 DeclarationName ConstructorName 2706 = Context.DeclarationNames.getCXXConstructorName( 2707 Context.getCanonicalType(ClassType.getUnqualifiedType())); 2708 DeclContext::lookup_const_iterator Con, ConEnd; 2709 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName); 2710 Con != ConEnd; ++Con) { 2711 // Find the constructor (which may be a template). 2712 CXXConstructorDecl *Constructor = 0; 2713 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con); 2714 if (ConstructorTmpl) 2715 Constructor 2716 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 2717 else 2718 Constructor = cast<CXXConstructorDecl>(*Con); 2719 2720 if ((Kind == IK_Direct) || 2721 (Kind == IK_Copy && Constructor->isConvertingConstructor()) || 2722 (Kind == IK_Default && Constructor->isDefaultConstructor())) { 2723 if (ConstructorTmpl) 2724 AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0, 2725 Args, NumArgs, CandidateSet); 2726 else 2727 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet); 2728 } 2729 } 2730 2731 // FIXME: When we decide not to synthesize the implicitly-declared 2732 // constructors, we'll need to make them appear here. 2733 2734 OverloadCandidateSet::iterator Best; 2735 switch (BestViableFunction(CandidateSet, Loc, Best)) { 2736 case OR_Success: 2737 // We found a constructor. Return it. 2738 return cast<CXXConstructorDecl>(Best->Function); 2739 2740 case OR_No_Viable_Function: 2741 if (InitEntity) 2742 Diag(Loc, diag::err_ovl_no_viable_function_in_init) 2743 << InitEntity << Range; 2744 else 2745 Diag(Loc, diag::err_ovl_no_viable_function_in_init) 2746 << ClassType << Range; 2747 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false); 2748 return 0; 2749 2750 case OR_Ambiguous: 2751 if (InitEntity) 2752 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range; 2753 else 2754 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range; 2755 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 2756 return 0; 2757 2758 case OR_Deleted: 2759 if (InitEntity) 2760 Diag(Loc, diag::err_ovl_deleted_init) 2761 << Best->Function->isDeleted() 2762 << InitEntity << Range; 2763 else 2764 Diag(Loc, diag::err_ovl_deleted_init) 2765 << Best->Function->isDeleted() 2766 << InitEntity << Range; 2767 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 2768 return 0; 2769 } 2770 2771 return 0; 2772} 2773 2774/// CompareReferenceRelationship - Compare the two types T1 and T2 to 2775/// determine whether they are reference-related, 2776/// reference-compatible, reference-compatible with added 2777/// qualification, or incompatible, for use in C++ initialization by 2778/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 2779/// type, and the first type (T1) is the pointee type of the reference 2780/// type being initialized. 2781Sema::ReferenceCompareResult 2782Sema::CompareReferenceRelationship(QualType T1, QualType T2, 2783 bool& DerivedToBase) { 2784 assert(!T1->isReferenceType() && 2785 "T1 must be the pointee type of the reference type"); 2786 assert(!T2->isReferenceType() && "T2 cannot be a reference type"); 2787 2788 T1 = Context.getCanonicalType(T1); 2789 T2 = Context.getCanonicalType(T2); 2790 QualType UnqualT1 = T1.getUnqualifiedType(); 2791 QualType UnqualT2 = T2.getUnqualifiedType(); 2792 2793 // C++ [dcl.init.ref]p4: 2794 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 2795 // reference-related to "cv2 T2" if T1 is the same type as T2, or 2796 // T1 is a base class of T2. 2797 if (UnqualT1 == UnqualT2) 2798 DerivedToBase = false; 2799 else if (IsDerivedFrom(UnqualT2, UnqualT1)) 2800 DerivedToBase = true; 2801 else 2802 return Ref_Incompatible; 2803 2804 // At this point, we know that T1 and T2 are reference-related (at 2805 // least). 2806 2807 // C++ [dcl.init.ref]p4: 2808 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 2809 // reference-related to T2 and cv1 is the same cv-qualification 2810 // as, or greater cv-qualification than, cv2. For purposes of 2811 // overload resolution, cases for which cv1 is greater 2812 // cv-qualification than cv2 are identified as 2813 // reference-compatible with added qualification (see 13.3.3.2). 2814 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 2815 return Ref_Compatible; 2816 else if (T1.isMoreQualifiedThan(T2)) 2817 return Ref_Compatible_With_Added_Qualification; 2818 else 2819 return Ref_Related; 2820} 2821 2822/// CheckReferenceInit - Check the initialization of a reference 2823/// variable with the given initializer (C++ [dcl.init.ref]). Init is 2824/// the initializer (either a simple initializer or an initializer 2825/// list), and DeclType is the type of the declaration. When ICS is 2826/// non-null, this routine will compute the implicit conversion 2827/// sequence according to C++ [over.ics.ref] and will not produce any 2828/// diagnostics; when ICS is null, it will emit diagnostics when any 2829/// errors are found. Either way, a return value of true indicates 2830/// that there was a failure, a return value of false indicates that 2831/// the reference initialization succeeded. 2832/// 2833/// When @p SuppressUserConversions, user-defined conversions are 2834/// suppressed. 2835/// When @p AllowExplicit, we also permit explicit user-defined 2836/// conversion functions. 2837/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue. 2838bool 2839Sema::CheckReferenceInit(Expr *&Init, QualType DeclType, 2840 bool SuppressUserConversions, 2841 bool AllowExplicit, bool ForceRValue, 2842 ImplicitConversionSequence *ICS) { 2843 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 2844 2845 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 2846 QualType T2 = Init->getType(); 2847 2848 // If the initializer is the address of an overloaded function, try 2849 // to resolve the overloaded function. If all goes well, T2 is the 2850 // type of the resulting function. 2851 if (Context.getCanonicalType(T2) == Context.OverloadTy) { 2852 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType, 2853 ICS != 0); 2854 if (Fn) { 2855 // Since we're performing this reference-initialization for 2856 // real, update the initializer with the resulting function. 2857 if (!ICS) { 2858 if (DiagnoseUseOfDecl(Fn, Init->getSourceRange().getBegin())) 2859 return true; 2860 2861 FixOverloadedFunctionReference(Init, Fn); 2862 } 2863 2864 T2 = Fn->getType(); 2865 } 2866 } 2867 2868 // Compute some basic properties of the types and the initializer. 2869 bool isRValRef = DeclType->isRValueReferenceType(); 2870 bool DerivedToBase = false; 2871 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression : 2872 Init->isLvalue(Context); 2873 ReferenceCompareResult RefRelationship 2874 = CompareReferenceRelationship(T1, T2, DerivedToBase); 2875 2876 // Most paths end in a failed conversion. 2877 if (ICS) 2878 ICS->ConversionKind = ImplicitConversionSequence::BadConversion; 2879 2880 // C++ [dcl.init.ref]p5: 2881 // A reference to type "cv1 T1" is initialized by an expression 2882 // of type "cv2 T2" as follows: 2883 2884 // -- If the initializer expression 2885 2886 // Rvalue references cannot bind to lvalues (N2812). 2887 // There is absolutely no situation where they can. In particular, note that 2888 // this is ill-formed, even if B has a user-defined conversion to A&&: 2889 // B b; 2890 // A&& r = b; 2891 if (isRValRef && InitLvalue == Expr::LV_Valid) { 2892 if (!ICS) 2893 Diag(Init->getSourceRange().getBegin(), diag::err_lvalue_to_rvalue_ref) 2894 << Init->getSourceRange(); 2895 return true; 2896 } 2897 2898 bool BindsDirectly = false; 2899 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 2900 // reference-compatible with "cv2 T2," or 2901 // 2902 // Note that the bit-field check is skipped if we are just computing 2903 // the implicit conversion sequence (C++ [over.best.ics]p2). 2904 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) && 2905 RefRelationship >= Ref_Compatible_With_Added_Qualification) { 2906 BindsDirectly = true; 2907 2908 if (ICS) { 2909 // C++ [over.ics.ref]p1: 2910 // When a parameter of reference type binds directly (8.5.3) 2911 // to an argument expression, the implicit conversion sequence 2912 // is the identity conversion, unless the argument expression 2913 // has a type that is a derived class of the parameter type, 2914 // in which case the implicit conversion sequence is a 2915 // derived-to-base Conversion (13.3.3.1). 2916 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion; 2917 ICS->Standard.First = ICK_Identity; 2918 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity; 2919 ICS->Standard.Third = ICK_Identity; 2920 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr(); 2921 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr(); 2922 ICS->Standard.ReferenceBinding = true; 2923 ICS->Standard.DirectBinding = true; 2924 ICS->Standard.RRefBinding = false; 2925 ICS->Standard.CopyConstructor = 0; 2926 2927 // Nothing more to do: the inaccessibility/ambiguity check for 2928 // derived-to-base conversions is suppressed when we're 2929 // computing the implicit conversion sequence (C++ 2930 // [over.best.ics]p2). 2931 return false; 2932 } else { 2933 // Perform the conversion. 2934 // FIXME: Binding to a subobject of the lvalue is going to require more 2935 // AST annotation than this. 2936 ImpCastExprToType(Init, T1, CastExpr::CK_Unknown, /*isLvalue=*/true); 2937 } 2938 } 2939 2940 // -- has a class type (i.e., T2 is a class type) and can be 2941 // implicitly converted to an lvalue of type "cv3 T3," 2942 // where "cv1 T1" is reference-compatible with "cv3 T3" 2943 // 92) (this conversion is selected by enumerating the 2944 // applicable conversion functions (13.3.1.6) and choosing 2945 // the best one through overload resolution (13.3)), 2946 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() && 2947 !RequireCompleteType(SourceLocation(), T2, 0)) { 2948 // FIXME: Look for conversions in base classes! 2949 CXXRecordDecl *T2RecordDecl 2950 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 2951 2952 OverloadCandidateSet CandidateSet; 2953 OverloadedFunctionDecl *Conversions 2954 = T2RecordDecl->getConversionFunctions(); 2955 for (OverloadedFunctionDecl::function_iterator Func 2956 = Conversions->function_begin(); 2957 Func != Conversions->function_end(); ++Func) { 2958 FunctionTemplateDecl *ConvTemplate 2959 = dyn_cast<FunctionTemplateDecl>(*Func); 2960 CXXConversionDecl *Conv; 2961 if (ConvTemplate) 2962 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 2963 else 2964 Conv = cast<CXXConversionDecl>(*Func); 2965 2966 // If the conversion function doesn't return a reference type, 2967 // it can't be considered for this conversion. 2968 if (Conv->getConversionType()->isLValueReferenceType() && 2969 (AllowExplicit || !Conv->isExplicit())) { 2970 if (ConvTemplate) 2971 AddTemplateConversionCandidate(ConvTemplate, Init, DeclType, 2972 CandidateSet); 2973 else 2974 AddConversionCandidate(Conv, Init, DeclType, CandidateSet); 2975 } 2976 } 2977 2978 OverloadCandidateSet::iterator Best; 2979 switch (BestViableFunction(CandidateSet, Init->getLocStart(), Best)) { 2980 case OR_Success: 2981 // This is a direct binding. 2982 BindsDirectly = true; 2983 2984 if (ICS) { 2985 // C++ [over.ics.ref]p1: 2986 // 2987 // [...] If the parameter binds directly to the result of 2988 // applying a conversion function to the argument 2989 // expression, the implicit conversion sequence is a 2990 // user-defined conversion sequence (13.3.3.1.2), with the 2991 // second standard conversion sequence either an identity 2992 // conversion or, if the conversion function returns an 2993 // entity of a type that is a derived class of the parameter 2994 // type, a derived-to-base Conversion. 2995 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion; 2996 ICS->UserDefined.Before = Best->Conversions[0].Standard; 2997 ICS->UserDefined.After = Best->FinalConversion; 2998 ICS->UserDefined.ConversionFunction = Best->Function; 2999 assert(ICS->UserDefined.After.ReferenceBinding && 3000 ICS->UserDefined.After.DirectBinding && 3001 "Expected a direct reference binding!"); 3002 return false; 3003 } else { 3004 // Perform the conversion. 3005 // FIXME: Binding to a subobject of the lvalue is going to require more 3006 // AST annotation than this. 3007 ImpCastExprToType(Init, T1, CastExpr::CK_Unknown, /*isLvalue=*/true); 3008 } 3009 break; 3010 3011 case OR_Ambiguous: 3012 assert(false && "Ambiguous reference binding conversions not implemented."); 3013 return true; 3014 3015 case OR_No_Viable_Function: 3016 case OR_Deleted: 3017 // There was no suitable conversion, or we found a deleted 3018 // conversion; continue with other checks. 3019 break; 3020 } 3021 } 3022 3023 if (BindsDirectly) { 3024 // C++ [dcl.init.ref]p4: 3025 // [...] In all cases where the reference-related or 3026 // reference-compatible relationship of two types is used to 3027 // establish the validity of a reference binding, and T1 is a 3028 // base class of T2, a program that necessitates such a binding 3029 // is ill-formed if T1 is an inaccessible (clause 11) or 3030 // ambiguous (10.2) base class of T2. 3031 // 3032 // Note that we only check this condition when we're allowed to 3033 // complain about errors, because we should not be checking for 3034 // ambiguity (or inaccessibility) unless the reference binding 3035 // actually happens. 3036 if (DerivedToBase) 3037 return CheckDerivedToBaseConversion(T2, T1, 3038 Init->getSourceRange().getBegin(), 3039 Init->getSourceRange()); 3040 else 3041 return false; 3042 } 3043 3044 // -- Otherwise, the reference shall be to a non-volatile const 3045 // type (i.e., cv1 shall be const), or the reference shall be an 3046 // rvalue reference and the initializer expression shall be an rvalue. 3047 if (!isRValRef && T1.getCVRQualifiers() != QualType::Const) { 3048 if (!ICS) 3049 Diag(Init->getSourceRange().getBegin(), 3050 diag::err_not_reference_to_const_init) 3051 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value") 3052 << T2 << Init->getSourceRange(); 3053 return true; 3054 } 3055 3056 // -- If the initializer expression is an rvalue, with T2 a 3057 // class type, and "cv1 T1" is reference-compatible with 3058 // "cv2 T2," the reference is bound in one of the 3059 // following ways (the choice is implementation-defined): 3060 // 3061 // -- The reference is bound to the object represented by 3062 // the rvalue (see 3.10) or to a sub-object within that 3063 // object. 3064 // 3065 // -- A temporary of type "cv1 T2" [sic] is created, and 3066 // a constructor is called to copy the entire rvalue 3067 // object into the temporary. The reference is bound to 3068 // the temporary or to a sub-object within the 3069 // temporary. 3070 // 3071 // The constructor that would be used to make the copy 3072 // shall be callable whether or not the copy is actually 3073 // done. 3074 // 3075 // Note that C++0x [dcl.init.ref]p5 takes away this implementation 3076 // freedom, so we will always take the first option and never build 3077 // a temporary in this case. FIXME: We will, however, have to check 3078 // for the presence of a copy constructor in C++98/03 mode. 3079 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() && 3080 RefRelationship >= Ref_Compatible_With_Added_Qualification) { 3081 if (ICS) { 3082 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion; 3083 ICS->Standard.First = ICK_Identity; 3084 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity; 3085 ICS->Standard.Third = ICK_Identity; 3086 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr(); 3087 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr(); 3088 ICS->Standard.ReferenceBinding = true; 3089 ICS->Standard.DirectBinding = false; 3090 ICS->Standard.RRefBinding = isRValRef; 3091 ICS->Standard.CopyConstructor = 0; 3092 } else { 3093 // FIXME: Binding to a subobject of the rvalue is going to require more 3094 // AST annotation than this. 3095 ImpCastExprToType(Init, T1, CastExpr::CK_Unknown, /*isLvalue=*/false); 3096 } 3097 return false; 3098 } 3099 3100 // -- Otherwise, a temporary of type "cv1 T1" is created and 3101 // initialized from the initializer expression using the 3102 // rules for a non-reference copy initialization (8.5). The 3103 // reference is then bound to the temporary. If T1 is 3104 // reference-related to T2, cv1 must be the same 3105 // cv-qualification as, or greater cv-qualification than, 3106 // cv2; otherwise, the program is ill-formed. 3107 if (RefRelationship == Ref_Related) { 3108 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 3109 // we would be reference-compatible or reference-compatible with 3110 // added qualification. But that wasn't the case, so the reference 3111 // initialization fails. 3112 if (!ICS) 3113 Diag(Init->getSourceRange().getBegin(), 3114 diag::err_reference_init_drops_quals) 3115 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value") 3116 << T2 << Init->getSourceRange(); 3117 return true; 3118 } 3119 3120 // If at least one of the types is a class type, the types are not 3121 // related, and we aren't allowed any user conversions, the 3122 // reference binding fails. This case is important for breaking 3123 // recursion, since TryImplicitConversion below will attempt to 3124 // create a temporary through the use of a copy constructor. 3125 if (SuppressUserConversions && RefRelationship == Ref_Incompatible && 3126 (T1->isRecordType() || T2->isRecordType())) { 3127 if (!ICS) 3128 Diag(Init->getSourceRange().getBegin(), 3129 diag::err_typecheck_convert_incompatible) 3130 << DeclType << Init->getType() << "initializing" << Init->getSourceRange(); 3131 return true; 3132 } 3133 3134 // Actually try to convert the initializer to T1. 3135 if (ICS) { 3136 // C++ [over.ics.ref]p2: 3137 // 3138 // When a parameter of reference type is not bound directly to 3139 // an argument expression, the conversion sequence is the one 3140 // required to convert the argument expression to the 3141 // underlying type of the reference according to 3142 // 13.3.3.1. Conceptually, this conversion sequence corresponds 3143 // to copy-initializing a temporary of the underlying type with 3144 // the argument expression. Any difference in top-level 3145 // cv-qualification is subsumed by the initialization itself 3146 // and does not constitute a conversion. 3147 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions, 3148 /*AllowExplicit=*/false, 3149 /*ForceRValue=*/false); 3150 3151 // Of course, that's still a reference binding. 3152 if (ICS->ConversionKind == ImplicitConversionSequence::StandardConversion) { 3153 ICS->Standard.ReferenceBinding = true; 3154 ICS->Standard.RRefBinding = isRValRef; 3155 } else if(ICS->ConversionKind == 3156 ImplicitConversionSequence::UserDefinedConversion) { 3157 ICS->UserDefined.After.ReferenceBinding = true; 3158 ICS->UserDefined.After.RRefBinding = isRValRef; 3159 } 3160 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion; 3161 } else { 3162 return PerformImplicitConversion(Init, T1, "initializing"); 3163 } 3164} 3165 3166/// CheckOverloadedOperatorDeclaration - Check whether the declaration 3167/// of this overloaded operator is well-formed. If so, returns false; 3168/// otherwise, emits appropriate diagnostics and returns true. 3169bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 3170 assert(FnDecl && FnDecl->isOverloadedOperator() && 3171 "Expected an overloaded operator declaration"); 3172 3173 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 3174 3175 // C++ [over.oper]p5: 3176 // The allocation and deallocation functions, operator new, 3177 // operator new[], operator delete and operator delete[], are 3178 // described completely in 3.7.3. The attributes and restrictions 3179 // found in the rest of this subclause do not apply to them unless 3180 // explicitly stated in 3.7.3. 3181 // FIXME: Write a separate routine for checking this. For now, just allow it. 3182 if (Op == OO_New || Op == OO_Array_New || 3183 Op == OO_Delete || Op == OO_Array_Delete) 3184 return false; 3185 3186 // C++ [over.oper]p6: 3187 // An operator function shall either be a non-static member 3188 // function or be a non-member function and have at least one 3189 // parameter whose type is a class, a reference to a class, an 3190 // enumeration, or a reference to an enumeration. 3191 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 3192 if (MethodDecl->isStatic()) 3193 return Diag(FnDecl->getLocation(), 3194 diag::err_operator_overload_static) << FnDecl->getDeclName(); 3195 } else { 3196 bool ClassOrEnumParam = false; 3197 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 3198 ParamEnd = FnDecl->param_end(); 3199 Param != ParamEnd; ++Param) { 3200 QualType ParamType = (*Param)->getType().getNonReferenceType(); 3201 if (ParamType->isDependentType() || ParamType->isRecordType() || 3202 ParamType->isEnumeralType()) { 3203 ClassOrEnumParam = true; 3204 break; 3205 } 3206 } 3207 3208 if (!ClassOrEnumParam) 3209 return Diag(FnDecl->getLocation(), 3210 diag::err_operator_overload_needs_class_or_enum) 3211 << FnDecl->getDeclName(); 3212 } 3213 3214 // C++ [over.oper]p8: 3215 // An operator function cannot have default arguments (8.3.6), 3216 // except where explicitly stated below. 3217 // 3218 // Only the function-call operator allows default arguments 3219 // (C++ [over.call]p1). 3220 if (Op != OO_Call) { 3221 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(); 3222 Param != FnDecl->param_end(); ++Param) { 3223 if ((*Param)->hasUnparsedDefaultArg()) 3224 return Diag((*Param)->getLocation(), 3225 diag::err_operator_overload_default_arg) 3226 << FnDecl->getDeclName(); 3227 else if (Expr *DefArg = (*Param)->getDefaultArg()) 3228 return Diag((*Param)->getLocation(), 3229 diag::err_operator_overload_default_arg) 3230 << FnDecl->getDeclName() << DefArg->getSourceRange(); 3231 } 3232 } 3233 3234 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 3235 { false, false, false } 3236#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 3237 , { Unary, Binary, MemberOnly } 3238#include "clang/Basic/OperatorKinds.def" 3239 }; 3240 3241 bool CanBeUnaryOperator = OperatorUses[Op][0]; 3242 bool CanBeBinaryOperator = OperatorUses[Op][1]; 3243 bool MustBeMemberOperator = OperatorUses[Op][2]; 3244 3245 // C++ [over.oper]p8: 3246 // [...] Operator functions cannot have more or fewer parameters 3247 // than the number required for the corresponding operator, as 3248 // described in the rest of this subclause. 3249 unsigned NumParams = FnDecl->getNumParams() 3250 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 3251 if (Op != OO_Call && 3252 ((NumParams == 1 && !CanBeUnaryOperator) || 3253 (NumParams == 2 && !CanBeBinaryOperator) || 3254 (NumParams < 1) || (NumParams > 2))) { 3255 // We have the wrong number of parameters. 3256 unsigned ErrorKind; 3257 if (CanBeUnaryOperator && CanBeBinaryOperator) { 3258 ErrorKind = 2; // 2 -> unary or binary. 3259 } else if (CanBeUnaryOperator) { 3260 ErrorKind = 0; // 0 -> unary 3261 } else { 3262 assert(CanBeBinaryOperator && 3263 "All non-call overloaded operators are unary or binary!"); 3264 ErrorKind = 1; // 1 -> binary 3265 } 3266 3267 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 3268 << FnDecl->getDeclName() << NumParams << ErrorKind; 3269 } 3270 3271 // Overloaded operators other than operator() cannot be variadic. 3272 if (Op != OO_Call && 3273 FnDecl->getType()->getAsFunctionProtoType()->isVariadic()) { 3274 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 3275 << FnDecl->getDeclName(); 3276 } 3277 3278 // Some operators must be non-static member functions. 3279 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 3280 return Diag(FnDecl->getLocation(), 3281 diag::err_operator_overload_must_be_member) 3282 << FnDecl->getDeclName(); 3283 } 3284 3285 // C++ [over.inc]p1: 3286 // The user-defined function called operator++ implements the 3287 // prefix and postfix ++ operator. If this function is a member 3288 // function with no parameters, or a non-member function with one 3289 // parameter of class or enumeration type, it defines the prefix 3290 // increment operator ++ for objects of that type. If the function 3291 // is a member function with one parameter (which shall be of type 3292 // int) or a non-member function with two parameters (the second 3293 // of which shall be of type int), it defines the postfix 3294 // increment operator ++ for objects of that type. 3295 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 3296 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 3297 bool ParamIsInt = false; 3298 if (const BuiltinType *BT = LastParam->getType()->getAsBuiltinType()) 3299 ParamIsInt = BT->getKind() == BuiltinType::Int; 3300 3301 if (!ParamIsInt) 3302 return Diag(LastParam->getLocation(), 3303 diag::err_operator_overload_post_incdec_must_be_int) 3304 << LastParam->getType() << (Op == OO_MinusMinus); 3305 } 3306 3307 // Notify the class if it got an assignment operator. 3308 if (Op == OO_Equal) { 3309 // Would have returned earlier otherwise. 3310 assert(isa<CXXMethodDecl>(FnDecl) && 3311 "Overloaded = not member, but not filtered."); 3312 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 3313 Method->setCopyAssignment(true); 3314 Method->getParent()->addedAssignmentOperator(Context, Method); 3315 } 3316 3317 return false; 3318} 3319 3320/// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 3321/// linkage specification, including the language and (if present) 3322/// the '{'. ExternLoc is the location of the 'extern', LangLoc is 3323/// the location of the language string literal, which is provided 3324/// by Lang/StrSize. LBraceLoc, if valid, provides the location of 3325/// the '{' brace. Otherwise, this linkage specification does not 3326/// have any braces. 3327Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S, 3328 SourceLocation ExternLoc, 3329 SourceLocation LangLoc, 3330 const char *Lang, 3331 unsigned StrSize, 3332 SourceLocation LBraceLoc) { 3333 LinkageSpecDecl::LanguageIDs Language; 3334 if (strncmp(Lang, "\"C\"", StrSize) == 0) 3335 Language = LinkageSpecDecl::lang_c; 3336 else if (strncmp(Lang, "\"C++\"", StrSize) == 0) 3337 Language = LinkageSpecDecl::lang_cxx; 3338 else { 3339 Diag(LangLoc, diag::err_bad_language); 3340 return DeclPtrTy(); 3341 } 3342 3343 // FIXME: Add all the various semantics of linkage specifications 3344 3345 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, 3346 LangLoc, Language, 3347 LBraceLoc.isValid()); 3348 CurContext->addDecl(D); 3349 PushDeclContext(S, D); 3350 return DeclPtrTy::make(D); 3351} 3352 3353/// ActOnFinishLinkageSpecification - Completely the definition of 3354/// the C++ linkage specification LinkageSpec. If RBraceLoc is 3355/// valid, it's the position of the closing '}' brace in a linkage 3356/// specification that uses braces. 3357Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S, 3358 DeclPtrTy LinkageSpec, 3359 SourceLocation RBraceLoc) { 3360 if (LinkageSpec) 3361 PopDeclContext(); 3362 return LinkageSpec; 3363} 3364 3365/// \brief Perform semantic analysis for the variable declaration that 3366/// occurs within a C++ catch clause, returning the newly-created 3367/// variable. 3368VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType, 3369 DeclaratorInfo *DInfo, 3370 IdentifierInfo *Name, 3371 SourceLocation Loc, 3372 SourceRange Range) { 3373 bool Invalid = false; 3374 3375 // Arrays and functions decay. 3376 if (ExDeclType->isArrayType()) 3377 ExDeclType = Context.getArrayDecayedType(ExDeclType); 3378 else if (ExDeclType->isFunctionType()) 3379 ExDeclType = Context.getPointerType(ExDeclType); 3380 3381 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 3382 // The exception-declaration shall not denote a pointer or reference to an 3383 // incomplete type, other than [cv] void*. 3384 // N2844 forbids rvalue references. 3385 if(!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 3386 Diag(Loc, diag::err_catch_rvalue_ref) << Range; 3387 Invalid = true; 3388 } 3389 3390 QualType BaseType = ExDeclType; 3391 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 3392 unsigned DK = diag::err_catch_incomplete; 3393 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 3394 BaseType = Ptr->getPointeeType(); 3395 Mode = 1; 3396 DK = diag::err_catch_incomplete_ptr; 3397 } else if(const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 3398 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 3399 BaseType = Ref->getPointeeType(); 3400 Mode = 2; 3401 DK = diag::err_catch_incomplete_ref; 3402 } 3403 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 3404 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 3405 Invalid = true; 3406 3407 if (!Invalid && !ExDeclType->isDependentType() && 3408 RequireNonAbstractType(Loc, ExDeclType, 3409 diag::err_abstract_type_in_decl, 3410 AbstractVariableType)) 3411 Invalid = true; 3412 3413 // FIXME: Need to test for ability to copy-construct and destroy the 3414 // exception variable. 3415 3416 // FIXME: Need to check for abstract classes. 3417 3418 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc, 3419 Name, ExDeclType, DInfo, VarDecl::None); 3420 3421 if (Invalid) 3422 ExDecl->setInvalidDecl(); 3423 3424 return ExDecl; 3425} 3426 3427/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 3428/// handler. 3429Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 3430 DeclaratorInfo *DInfo = 0; 3431 QualType ExDeclType = GetTypeForDeclarator(D, S, &DInfo); 3432 3433 bool Invalid = D.isInvalidType(); 3434 IdentifierInfo *II = D.getIdentifier(); 3435 if (NamedDecl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) { 3436 // The scope should be freshly made just for us. There is just no way 3437 // it contains any previous declaration. 3438 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl))); 3439 if (PrevDecl->isTemplateParameter()) { 3440 // Maybe we will complain about the shadowed template parameter. 3441 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 3442 } 3443 } 3444 3445 if (D.getCXXScopeSpec().isSet() && !Invalid) { 3446 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 3447 << D.getCXXScopeSpec().getRange(); 3448 Invalid = true; 3449 } 3450 3451 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, DInfo, 3452 D.getIdentifier(), 3453 D.getIdentifierLoc(), 3454 D.getDeclSpec().getSourceRange()); 3455 3456 if (Invalid) 3457 ExDecl->setInvalidDecl(); 3458 3459 // Add the exception declaration into this scope. 3460 if (II) 3461 PushOnScopeChains(ExDecl, S); 3462 else 3463 CurContext->addDecl(ExDecl); 3464 3465 ProcessDeclAttributes(S, ExDecl, D); 3466 return DeclPtrTy::make(ExDecl); 3467} 3468 3469Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc, 3470 ExprArg assertexpr, 3471 ExprArg assertmessageexpr) { 3472 Expr *AssertExpr = (Expr *)assertexpr.get(); 3473 StringLiteral *AssertMessage = 3474 cast<StringLiteral>((Expr *)assertmessageexpr.get()); 3475 3476 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) { 3477 llvm::APSInt Value(32); 3478 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) { 3479 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) << 3480 AssertExpr->getSourceRange(); 3481 return DeclPtrTy(); 3482 } 3483 3484 if (Value == 0) { 3485 std::string str(AssertMessage->getStrData(), 3486 AssertMessage->getByteLength()); 3487 Diag(AssertLoc, diag::err_static_assert_failed) 3488 << str << AssertExpr->getSourceRange(); 3489 } 3490 } 3491 3492 assertexpr.release(); 3493 assertmessageexpr.release(); 3494 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc, 3495 AssertExpr, AssertMessage); 3496 3497 CurContext->addDecl(Decl); 3498 return DeclPtrTy::make(Decl); 3499} 3500 3501Sema::DeclPtrTy Sema::ActOnFriendDecl(Scope *S, 3502 llvm::PointerUnion<const DeclSpec*,Declarator*> DU, 3503 bool IsDefinition) { 3504 Declarator *D = DU.dyn_cast<Declarator*>(); 3505 const DeclSpec &DS = (D ? D->getDeclSpec() : *DU.get<const DeclSpec*>()); 3506 3507 assert(DS.isFriendSpecified()); 3508 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 3509 3510 // If there's no declarator, then this can only be a friend class 3511 // declaration (or else it's just syntactically invalid). 3512 if (!D) { 3513 SourceLocation Loc = DS.getSourceRange().getBegin(); 3514 3515 QualType T; 3516 DeclContext *DC; 3517 3518 // In C++0x, we just accept any old type. 3519 if (getLangOptions().CPlusPlus0x) { 3520 bool invalid = false; 3521 QualType T = ConvertDeclSpecToType(DS, Loc, invalid); 3522 if (invalid) 3523 return DeclPtrTy(); 3524 3525 // The semantic context in which to create the decl. If it's not 3526 // a record decl (or we don't yet know if it is), create it in the 3527 // current context. 3528 DC = CurContext; 3529 if (const RecordType *RT = T->getAs<RecordType>()) 3530 DC = RT->getDecl()->getDeclContext(); 3531 3532 // The C++98 rules are somewhat more complex. 3533 } else { 3534 // C++ [class.friend]p2: 3535 // An elaborated-type-specifier shall be used in a friend declaration 3536 // for a class.* 3537 // * The class-key of the elaborated-type-specifier is required. 3538 CXXRecordDecl *RD = 0; 3539 3540 switch (DS.getTypeSpecType()) { 3541 case DeclSpec::TST_class: 3542 case DeclSpec::TST_struct: 3543 case DeclSpec::TST_union: 3544 RD = dyn_cast_or_null<CXXRecordDecl>((Decl*) DS.getTypeRep()); 3545 if (!RD) return DeclPtrTy(); 3546 break; 3547 3548 case DeclSpec::TST_typename: 3549 if (const RecordType *RT = 3550 ((const Type*) DS.getTypeRep())->getAs<RecordType>()) 3551 RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 3552 // fallthrough 3553 default: 3554 if (RD) { 3555 Diag(DS.getFriendSpecLoc(), diag::err_unelaborated_friend_type) 3556 << (RD->isUnion()) 3557 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(), 3558 RD->isUnion() ? " union" : " class"); 3559 return DeclPtrTy::make(RD); 3560 } 3561 3562 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend) 3563 << DS.getSourceRange(); 3564 return DeclPtrTy(); 3565 } 3566 3567 // The record declaration we get from friend declarations is not 3568 // canonicalized; see ActOnTag. 3569 3570 // C++ [class.friend]p2: A class shall not be defined inside 3571 // a friend declaration. 3572 if (RD->isDefinition()) 3573 Diag(DS.getFriendSpecLoc(), diag::err_friend_decl_defines_class) 3574 << RD->getSourceRange(); 3575 3576 // C++98 [class.friend]p1: A friend of a class is a function 3577 // or class that is not a member of the class . . . 3578 // But that's a silly restriction which nobody implements for 3579 // inner classes, and C++0x removes it anyway, so we only report 3580 // this (as a warning) if we're being pedantic. 3581 // 3582 // Also, definitions currently get treated in a way that causes 3583 // this error, so only report it if we didn't see a definition. 3584 else if (RD->getDeclContext() == CurContext && 3585 !getLangOptions().CPlusPlus0x) 3586 Diag(DS.getFriendSpecLoc(), diag::ext_friend_inner_class); 3587 3588 T = QualType(RD->getTypeForDecl(), 0); 3589 DC = RD->getDeclContext(); 3590 } 3591 3592 FriendClassDecl *FCD = FriendClassDecl::Create(Context, DC, Loc, T, 3593 DS.getFriendSpecLoc()); 3594 FCD->setLexicalDeclContext(CurContext); 3595 3596 if (CurContext->isDependentContext()) 3597 CurContext->addHiddenDecl(FCD); 3598 else 3599 CurContext->addDecl(FCD); 3600 3601 return DeclPtrTy::make(FCD); 3602 } 3603 3604 // We have a declarator. 3605 assert(D); 3606 3607 SourceLocation Loc = D->getIdentifierLoc(); 3608 DeclaratorInfo *DInfo = 0; 3609 QualType T = GetTypeForDeclarator(*D, S, &DInfo); 3610 3611 // C++ [class.friend]p1 3612 // A friend of a class is a function or class.... 3613 // Note that this sees through typedefs, which is intended. 3614 if (!T->isFunctionType()) { 3615 Diag(Loc, diag::err_unexpected_friend); 3616 3617 // It might be worthwhile to try to recover by creating an 3618 // appropriate declaration. 3619 return DeclPtrTy(); 3620 } 3621 3622 // C++ [namespace.memdef]p3 3623 // - If a friend declaration in a non-local class first declares a 3624 // class or function, the friend class or function is a member 3625 // of the innermost enclosing namespace. 3626 // - The name of the friend is not found by simple name lookup 3627 // until a matching declaration is provided in that namespace 3628 // scope (either before or after the class declaration granting 3629 // friendship). 3630 // - If a friend function is called, its name may be found by the 3631 // name lookup that considers functions from namespaces and 3632 // classes associated with the types of the function arguments. 3633 // - When looking for a prior declaration of a class or a function 3634 // declared as a friend, scopes outside the innermost enclosing 3635 // namespace scope are not considered. 3636 3637 CXXScopeSpec &ScopeQual = D->getCXXScopeSpec(); 3638 DeclarationName Name = GetNameForDeclarator(*D); 3639 assert(Name); 3640 3641 // The existing declaration we found. 3642 FunctionDecl *FD = NULL; 3643 3644 // The context we found the declaration in, or in which we should 3645 // create the declaration. 3646 DeclContext *DC; 3647 3648 // FIXME: handle local classes 3649 3650 // Recover from invalid scope qualifiers as if they just weren't there. 3651 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) { 3652 DC = computeDeclContext(ScopeQual); 3653 3654 // FIXME: handle dependent contexts 3655 if (!DC) return DeclPtrTy(); 3656 3657 Decl *Dec = LookupQualifiedNameWithType(DC, Name, T); 3658 3659 // If searching in that context implicitly found a declaration in 3660 // a different context, treat it like it wasn't found at all. 3661 // TODO: better diagnostics for this case. Suggesting the right 3662 // qualified scope would be nice... 3663 if (!Dec || Dec->getDeclContext() != DC) { 3664 D->setInvalidType(); 3665 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T; 3666 return DeclPtrTy(); 3667 } 3668 3669 // C++ [class.friend]p1: A friend of a class is a function or 3670 // class that is not a member of the class . . . 3671 if (DC == CurContext) 3672 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member); 3673 3674 FD = cast<FunctionDecl>(Dec); 3675 3676 // Otherwise walk out to the nearest namespace scope looking for matches. 3677 } else { 3678 // TODO: handle local class contexts. 3679 3680 DC = CurContext; 3681 while (true) { 3682 // Skip class contexts. If someone can cite chapter and verse 3683 // for this behavior, that would be nice --- it's what GCC and 3684 // EDG do, and it seems like a reasonable intent, but the spec 3685 // really only says that checks for unqualified existing 3686 // declarations should stop at the nearest enclosing namespace, 3687 // not that they should only consider the nearest enclosing 3688 // namespace. 3689 while (DC->isRecord()) DC = DC->getParent(); 3690 3691 Decl *Dec = LookupQualifiedNameWithType(DC, Name, T); 3692 3693 // TODO: decide what we think about using declarations. 3694 if (Dec) { 3695 FD = cast<FunctionDecl>(Dec); 3696 break; 3697 } 3698 if (DC->isFileContext()) break; 3699 DC = DC->getParent(); 3700 } 3701 3702 // C++ [class.friend]p1: A friend of a class is a function or 3703 // class that is not a member of the class . . . 3704 // C++0x changes this for both friend types and functions. 3705 // Most C++ 98 compilers do seem to give an error here, so 3706 // we do, too. 3707 if (FD && DC == CurContext && !getLangOptions().CPlusPlus0x) 3708 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member); 3709 } 3710 3711 bool Redeclaration = (FD != 0); 3712 3713 // If we found a match, create a friend function declaration with 3714 // that function as the previous declaration. 3715 if (Redeclaration) { 3716 // Create it in the semantic context of the original declaration. 3717 DC = FD->getDeclContext(); 3718 3719 // If we didn't find something matching the type exactly, create 3720 // a declaration. This declaration should only be findable via 3721 // argument-dependent lookup. 3722 } else { 3723 assert(DC->isFileContext()); 3724 3725 // This implies that it has to be an operator or function. 3726 if (D->getKind() == Declarator::DK_Constructor || 3727 D->getKind() == Declarator::DK_Destructor || 3728 D->getKind() == Declarator::DK_Conversion) { 3729 Diag(Loc, diag::err_introducing_special_friend) << 3730 (D->getKind() == Declarator::DK_Constructor ? 0 : 3731 D->getKind() == Declarator::DK_Destructor ? 1 : 2); 3732 return DeclPtrTy(); 3733 } 3734 } 3735 3736 NamedDecl *ND = ActOnFunctionDeclarator(S, *D, DC, T, DInfo, 3737 /* PrevDecl = */ FD, 3738 MultiTemplateParamsArg(*this), 3739 IsDefinition, 3740 Redeclaration); 3741 FD = cast_or_null<FriendFunctionDecl>(ND); 3742 3743 assert(FD->getDeclContext() == DC); 3744 assert(FD->getLexicalDeclContext() == CurContext); 3745 3746 // If this is a dependent context, just add the decl to the 3747 // class's decl list and don't both with the lookup tables. This 3748 // doesn't affect lookup because any call that might find this 3749 // function via ADL necessarily has to involve dependently-typed 3750 // arguments and hence can't be resolved until 3751 // template-instantiation anyway. 3752 if (CurContext->isDependentContext()) 3753 CurContext->addHiddenDecl(FD); 3754 else 3755 CurContext->addDecl(FD); 3756 3757 return DeclPtrTy::make(FD); 3758} 3759 3760void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) { 3761 AdjustDeclIfTemplate(dcl); 3762 3763 Decl *Dcl = dcl.getAs<Decl>(); 3764 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl); 3765 if (!Fn) { 3766 Diag(DelLoc, diag::err_deleted_non_function); 3767 return; 3768 } 3769 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) { 3770 Diag(DelLoc, diag::err_deleted_decl_not_first); 3771 Diag(Prev->getLocation(), diag::note_previous_declaration); 3772 // If the declaration wasn't the first, we delete the function anyway for 3773 // recovery. 3774 } 3775 Fn->setDeleted(); 3776} 3777 3778static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 3779 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E; 3780 ++CI) { 3781 Stmt *SubStmt = *CI; 3782 if (!SubStmt) 3783 continue; 3784 if (isa<ReturnStmt>(SubStmt)) 3785 Self.Diag(SubStmt->getSourceRange().getBegin(), 3786 diag::err_return_in_constructor_handler); 3787 if (!isa<Expr>(SubStmt)) 3788 SearchForReturnInStmt(Self, SubStmt); 3789 } 3790} 3791 3792void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 3793 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 3794 CXXCatchStmt *Handler = TryBlock->getHandler(I); 3795 SearchForReturnInStmt(*this, Handler); 3796 } 3797} 3798 3799bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 3800 const CXXMethodDecl *Old) { 3801 QualType NewTy = New->getType()->getAsFunctionType()->getResultType(); 3802 QualType OldTy = Old->getType()->getAsFunctionType()->getResultType(); 3803 3804 QualType CNewTy = Context.getCanonicalType(NewTy); 3805 QualType COldTy = Context.getCanonicalType(OldTy); 3806 3807 if (CNewTy == COldTy && 3808 CNewTy.getCVRQualifiers() == COldTy.getCVRQualifiers()) 3809 return false; 3810 3811 // Check if the return types are covariant 3812 QualType NewClassTy, OldClassTy; 3813 3814 /// Both types must be pointers or references to classes. 3815 if (PointerType *NewPT = dyn_cast<PointerType>(NewTy)) { 3816 if (PointerType *OldPT = dyn_cast<PointerType>(OldTy)) { 3817 NewClassTy = NewPT->getPointeeType(); 3818 OldClassTy = OldPT->getPointeeType(); 3819 } 3820 } else if (ReferenceType *NewRT = dyn_cast<ReferenceType>(NewTy)) { 3821 if (ReferenceType *OldRT = dyn_cast<ReferenceType>(OldTy)) { 3822 NewClassTy = NewRT->getPointeeType(); 3823 OldClassTy = OldRT->getPointeeType(); 3824 } 3825 } 3826 3827 // The return types aren't either both pointers or references to a class type. 3828 if (NewClassTy.isNull()) { 3829 Diag(New->getLocation(), 3830 diag::err_different_return_type_for_overriding_virtual_function) 3831 << New->getDeclName() << NewTy << OldTy; 3832 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 3833 3834 return true; 3835 } 3836 3837 if (NewClassTy.getUnqualifiedType() != OldClassTy.getUnqualifiedType()) { 3838 // Check if the new class derives from the old class. 3839 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 3840 Diag(New->getLocation(), 3841 diag::err_covariant_return_not_derived) 3842 << New->getDeclName() << NewTy << OldTy; 3843 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 3844 return true; 3845 } 3846 3847 // Check if we the conversion from derived to base is valid. 3848 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy, 3849 diag::err_covariant_return_inaccessible_base, 3850 diag::err_covariant_return_ambiguous_derived_to_base_conv, 3851 // FIXME: Should this point to the return type? 3852 New->getLocation(), SourceRange(), New->getDeclName())) { 3853 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 3854 return true; 3855 } 3856 } 3857 3858 // The qualifiers of the return types must be the same. 3859 if (CNewTy.getCVRQualifiers() != COldTy.getCVRQualifiers()) { 3860 Diag(New->getLocation(), 3861 diag::err_covariant_return_type_different_qualifications) 3862 << New->getDeclName() << NewTy << OldTy; 3863 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 3864 return true; 3865 }; 3866 3867 3868 // The new class type must have the same or less qualifiers as the old type. 3869 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 3870 Diag(New->getLocation(), 3871 diag::err_covariant_return_type_class_type_more_qualified) 3872 << New->getDeclName() << NewTy << OldTy; 3873 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 3874 return true; 3875 }; 3876 3877 return false; 3878} 3879 3880bool Sema::CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, 3881 const CXXMethodDecl *Old) 3882{ 3883 return CheckExceptionSpecSubset(diag::err_override_exception_spec, 3884 diag::note_overridden_virtual_function, 3885 Old->getType()->getAsFunctionProtoType(), 3886 Old->getLocation(), 3887 New->getType()->getAsFunctionProtoType(), 3888 New->getLocation()); 3889} 3890 3891/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an 3892/// initializer for the declaration 'Dcl'. 3893/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 3894/// static data member of class X, names should be looked up in the scope of 3895/// class X. 3896void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) { 3897 AdjustDeclIfTemplate(Dcl); 3898 3899 Decl *D = Dcl.getAs<Decl>(); 3900 // If there is no declaration, there was an error parsing it. 3901 if (D == 0) 3902 return; 3903 3904 // Check whether it is a declaration with a nested name specifier like 3905 // int foo::bar; 3906 if (!D->isOutOfLine()) 3907 return; 3908 3909 // C++ [basic.lookup.unqual]p13 3910 // 3911 // A name used in the definition of a static data member of class X 3912 // (after the qualified-id of the static member) is looked up as if the name 3913 // was used in a member function of X. 3914 3915 // Change current context into the context of the initializing declaration. 3916 EnterDeclaratorContext(S, D->getDeclContext()); 3917} 3918 3919/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 3920/// initializer for the declaration 'Dcl'. 3921void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) { 3922 AdjustDeclIfTemplate(Dcl); 3923 3924 Decl *D = Dcl.getAs<Decl>(); 3925 // If there is no declaration, there was an error parsing it. 3926 if (D == 0) 3927 return; 3928 3929 // Check whether it is a declaration with a nested name specifier like 3930 // int foo::bar; 3931 if (!D->isOutOfLine()) 3932 return; 3933 3934 assert(S->getEntity() == D->getDeclContext() && "Context imbalance!"); 3935 ExitDeclaratorContext(S); 3936} 3937