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