SemaDeclCXX.cpp revision 72b505b7904b3c9320a1312998800ba76e4f5841
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/TypeOrdering.h" 19#include "clang/AST/StmtVisitor.h" 20#include "clang/Lex/Preprocessor.h" 21#include "clang/Basic/Diagnostic.h" 22#include "clang/Parse/DeclSpec.h" 23#include "llvm/Support/Compiler.h" 24#include <algorithm> // for std::equal 25#include <map> 26 27using namespace clang; 28 29//===----------------------------------------------------------------------===// 30// CheckDefaultArgumentVisitor 31//===----------------------------------------------------------------------===// 32 33namespace { 34 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 35 /// the default argument of a parameter to determine whether it 36 /// contains any ill-formed subexpressions. For example, this will 37 /// diagnose the use of local variables or parameters within the 38 /// default argument expression. 39 class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor 40 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 41 Expr *DefaultArg; 42 Sema *S; 43 44 public: 45 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 46 : DefaultArg(defarg), S(s) {} 47 48 bool VisitExpr(Expr *Node); 49 bool VisitDeclRefExpr(DeclRefExpr *DRE); 50 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 51 }; 52 53 /// VisitExpr - Visit all of the children of this expression. 54 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 55 bool IsInvalid = false; 56 for (Stmt::child_iterator I = Node->child_begin(), 57 E = Node->child_end(); I != E; ++I) 58 IsInvalid |= Visit(*I); 59 return IsInvalid; 60 } 61 62 /// VisitDeclRefExpr - Visit a reference to a declaration, to 63 /// determine whether this declaration can be used in the default 64 /// argument expression. 65 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 66 NamedDecl *Decl = DRE->getDecl(); 67 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 68 // C++ [dcl.fct.default]p9 69 // Default arguments are evaluated each time the function is 70 // called. The order of evaluation of function arguments is 71 // unspecified. Consequently, parameters of a function shall not 72 // be used in default argument expressions, even if they are not 73 // evaluated. Parameters of a function declared before a default 74 // argument expression are in scope and can hide namespace and 75 // class member names. 76 return S->Diag(DRE->getSourceRange().getBegin(), 77 diag::err_param_default_argument_references_param) 78 << Param->getDeclName() << DefaultArg->getSourceRange(); 79 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 80 // C++ [dcl.fct.default]p7 81 // Local variables shall not be used in default argument 82 // expressions. 83 if (VDecl->isBlockVarDecl()) 84 return S->Diag(DRE->getSourceRange().getBegin(), 85 diag::err_param_default_argument_references_local) 86 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 87 } 88 89 return false; 90 } 91 92 /// VisitCXXThisExpr - Visit a C++ "this" expression. 93 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 94 // C++ [dcl.fct.default]p8: 95 // The keyword this shall not be used in a default argument of a 96 // member function. 97 return S->Diag(ThisE->getSourceRange().getBegin(), 98 diag::err_param_default_argument_references_this) 99 << ThisE->getSourceRange(); 100 } 101} 102 103/// ActOnParamDefaultArgument - Check whether the default argument 104/// provided for a function parameter is well-formed. If so, attach it 105/// to the parameter declaration. 106void 107Sema::ActOnParamDefaultArgument(DeclTy *param, SourceLocation EqualLoc, 108 ExprTy *defarg) { 109 ParmVarDecl *Param = (ParmVarDecl *)param; 110 llvm::OwningPtr<Expr> DefaultArg((Expr *)defarg); 111 QualType ParamType = Param->getType(); 112 113 // Default arguments are only permitted in C++ 114 if (!getLangOptions().CPlusPlus) { 115 Diag(EqualLoc, diag::err_param_default_argument) 116 << DefaultArg->getSourceRange(); 117 Param->setInvalidDecl(); 118 return; 119 } 120 121 // C++ [dcl.fct.default]p5 122 // A default argument expression is implicitly converted (clause 123 // 4) to the parameter type. The default argument expression has 124 // the same semantic constraints as the initializer expression in 125 // a declaration of a variable of the parameter type, using the 126 // copy-initialization semantics (8.5). 127 Expr *DefaultArgPtr = DefaultArg.get(); 128 bool DefaultInitFailed = PerformCopyInitialization(DefaultArgPtr, ParamType, 129 "in default argument"); 130 if (DefaultArgPtr != DefaultArg.get()) { 131 DefaultArg.take(); 132 DefaultArg.reset(DefaultArgPtr); 133 } 134 if (DefaultInitFailed) { 135 return; 136 } 137 138 // Check that the default argument is well-formed 139 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this); 140 if (DefaultArgChecker.Visit(DefaultArg.get())) { 141 Param->setInvalidDecl(); 142 return; 143 } 144 145 // Okay: add the default argument to the parameter 146 Param->setDefaultArg(DefaultArg.take()); 147} 148 149/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 150/// the default argument for the parameter param failed. 151void Sema::ActOnParamDefaultArgumentError(DeclTy *param) { 152 ((ParmVarDecl*)param)->setInvalidDecl(); 153} 154 155/// CheckExtraCXXDefaultArguments - Check for any extra default 156/// arguments in the declarator, which is not a function declaration 157/// or definition and therefore is not permitted to have default 158/// arguments. This routine should be invoked for every declarator 159/// that is not a function declaration or definition. 160void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 161 // C++ [dcl.fct.default]p3 162 // A default argument expression shall be specified only in the 163 // parameter-declaration-clause of a function declaration or in a 164 // template-parameter (14.1). It shall not be specified for a 165 // parameter pack. If it is specified in a 166 // parameter-declaration-clause, it shall not occur within a 167 // declarator or abstract-declarator of a parameter-declaration. 168 for (unsigned i = 0; i < D.getNumTypeObjects(); ++i) { 169 DeclaratorChunk &chunk = D.getTypeObject(i); 170 if (chunk.Kind == DeclaratorChunk::Function) { 171 for (unsigned argIdx = 0; argIdx < chunk.Fun.NumArgs; ++argIdx) { 172 ParmVarDecl *Param = (ParmVarDecl *)chunk.Fun.ArgInfo[argIdx].Param; 173 if (Param->getDefaultArg()) { 174 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 175 << Param->getDefaultArg()->getSourceRange(); 176 Param->setDefaultArg(0); 177 } else if (CachedTokens *Toks 178 = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens) { 179 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 180 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation()); 181 delete Toks; 182 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0; 183 } 184 } 185 } 186 } 187} 188 189// MergeCXXFunctionDecl - Merge two declarations of the same C++ 190// function, once we already know that they have the same 191// type. Subroutine of MergeFunctionDecl. 192FunctionDecl * 193Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) { 194 // C++ [dcl.fct.default]p4: 195 // 196 // For non-template functions, default arguments can be added in 197 // later declarations of a function in the same 198 // scope. Declarations in different scopes have completely 199 // distinct sets of default arguments. That is, declarations in 200 // inner scopes do not acquire default arguments from 201 // declarations in outer scopes, and vice versa. In a given 202 // function declaration, all parameters subsequent to a 203 // parameter with a default argument shall have default 204 // arguments supplied in this or previous declarations. A 205 // default argument shall not be redefined by a later 206 // declaration (not even to the same value). 207 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 208 ParmVarDecl *OldParam = Old->getParamDecl(p); 209 ParmVarDecl *NewParam = New->getParamDecl(p); 210 211 if(OldParam->getDefaultArg() && NewParam->getDefaultArg()) { 212 Diag(NewParam->getLocation(), 213 diag::err_param_default_argument_redefinition) 214 << NewParam->getDefaultArg()->getSourceRange(); 215 Diag(OldParam->getLocation(), diag::note_previous_definition); 216 } else if (OldParam->getDefaultArg()) { 217 // Merge the old default argument into the new parameter 218 NewParam->setDefaultArg(OldParam->getDefaultArg()); 219 } 220 } 221 222 return New; 223} 224 225/// CheckCXXDefaultArguments - Verify that the default arguments for a 226/// function declaration are well-formed according to C++ 227/// [dcl.fct.default]. 228void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 229 unsigned NumParams = FD->getNumParams(); 230 unsigned p; 231 232 // Find first parameter with a default argument 233 for (p = 0; p < NumParams; ++p) { 234 ParmVarDecl *Param = FD->getParamDecl(p); 235 if (Param->getDefaultArg()) 236 break; 237 } 238 239 // C++ [dcl.fct.default]p4: 240 // In a given function declaration, all parameters 241 // subsequent to a parameter with a default argument shall 242 // have default arguments supplied in this or previous 243 // declarations. A default argument shall not be redefined 244 // by a later declaration (not even to the same value). 245 unsigned LastMissingDefaultArg = 0; 246 for(; p < NumParams; ++p) { 247 ParmVarDecl *Param = FD->getParamDecl(p); 248 if (!Param->getDefaultArg()) { 249 if (Param->isInvalidDecl()) 250 /* We already complained about this parameter. */; 251 else if (Param->getIdentifier()) 252 Diag(Param->getLocation(), 253 diag::err_param_default_argument_missing_name) 254 << Param->getIdentifier(); 255 else 256 Diag(Param->getLocation(), 257 diag::err_param_default_argument_missing); 258 259 LastMissingDefaultArg = p; 260 } 261 } 262 263 if (LastMissingDefaultArg > 0) { 264 // Some default arguments were missing. Clear out all of the 265 // default arguments up to (and including) the last missing 266 // default argument, so that we leave the function parameters 267 // in a semantically valid state. 268 for (p = 0; p <= LastMissingDefaultArg; ++p) { 269 ParmVarDecl *Param = FD->getParamDecl(p); 270 if (Param->getDefaultArg()) { 271 delete Param->getDefaultArg(); 272 Param->setDefaultArg(0); 273 } 274 } 275 } 276} 277 278/// isCurrentClassName - Determine whether the identifier II is the 279/// name of the class type currently being defined. In the case of 280/// nested classes, this will only return true if II is the name of 281/// the innermost class. 282bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 283 const CXXScopeSpec *SS) { 284 CXXRecordDecl *CurDecl; 285 if (SS) { 286 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep()); 287 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 288 } else 289 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 290 291 if (CurDecl) 292 return &II == CurDecl->getIdentifier(); 293 else 294 return false; 295} 296 297/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 298/// one entry in the base class list of a class specifier, for 299/// example: 300/// class foo : public bar, virtual private baz { 301/// 'public bar' and 'virtual private baz' are each base-specifiers. 302Sema::BaseResult 303Sema::ActOnBaseSpecifier(DeclTy *classdecl, SourceRange SpecifierRange, 304 bool Virtual, AccessSpecifier Access, 305 TypeTy *basetype, SourceLocation BaseLoc) { 306 RecordDecl *Decl = (RecordDecl*)classdecl; 307 QualType BaseType = Context.getTypeDeclType((TypeDecl*)basetype); 308 309 // Base specifiers must be record types. 310 if (!BaseType->isRecordType()) 311 return Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 312 313 // C++ [class.union]p1: 314 // A union shall not be used as a base class. 315 if (BaseType->isUnionType()) 316 return Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 317 318 // C++ [class.union]p1: 319 // A union shall not have base classes. 320 if (Decl->isUnion()) 321 return Diag(Decl->getLocation(), diag::err_base_clause_on_union) 322 << SpecifierRange; 323 324 // C++ [class.derived]p2: 325 // The class-name in a base-specifier shall not be an incompletely 326 // defined class. 327 if (BaseType->isIncompleteType()) 328 return Diag(BaseLoc, diag::err_incomplete_base_class) << SpecifierRange; 329 330 // If the base class is polymorphic, the new one is, too. 331 RecordDecl *BaseDecl = BaseType->getAsRecordType()->getDecl(); 332 assert(BaseDecl && "Record type has no declaration"); 333 BaseDecl = BaseDecl->getDefinition(Context); 334 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 335 if (cast<CXXRecordDecl>(BaseDecl)->isPolymorphic()) 336 cast<CXXRecordDecl>(Decl)->setPolymorphic(true); 337 338 // Create the base specifier. 339 return new CXXBaseSpecifier(SpecifierRange, Virtual, 340 BaseType->isClassType(), Access, BaseType); 341} 342 343/// ActOnBaseSpecifiers - Attach the given base specifiers to the 344/// class, after checking whether there are any duplicate base 345/// classes. 346void Sema::ActOnBaseSpecifiers(DeclTy *ClassDecl, BaseTy **Bases, 347 unsigned NumBases) { 348 if (NumBases == 0) 349 return; 350 351 // Used to keep track of which base types we have already seen, so 352 // that we can properly diagnose redundant direct base types. Note 353 // that the key is always the unqualified canonical type of the base 354 // class. 355 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 356 357 // Copy non-redundant base specifiers into permanent storage. 358 CXXBaseSpecifier **BaseSpecs = (CXXBaseSpecifier **)Bases; 359 unsigned NumGoodBases = 0; 360 for (unsigned idx = 0; idx < NumBases; ++idx) { 361 QualType NewBaseType 362 = Context.getCanonicalType(BaseSpecs[idx]->getType()); 363 NewBaseType = NewBaseType.getUnqualifiedType(); 364 365 if (KnownBaseTypes[NewBaseType]) { 366 // C++ [class.mi]p3: 367 // A class shall not be specified as a direct base class of a 368 // derived class more than once. 369 Diag(BaseSpecs[idx]->getSourceRange().getBegin(), 370 diag::err_duplicate_base_class) 371 << KnownBaseTypes[NewBaseType]->getType() 372 << BaseSpecs[idx]->getSourceRange(); 373 374 // Delete the duplicate base class specifier; we're going to 375 // overwrite its pointer later. 376 delete BaseSpecs[idx]; 377 } else { 378 // Okay, add this new base class. 379 KnownBaseTypes[NewBaseType] = BaseSpecs[idx]; 380 BaseSpecs[NumGoodBases++] = BaseSpecs[idx]; 381 } 382 } 383 384 // Attach the remaining base class specifiers to the derived class. 385 CXXRecordDecl *Decl = (CXXRecordDecl*)ClassDecl; 386 Decl->setBases(BaseSpecs, NumGoodBases); 387 388 // Delete the remaining (good) base class specifiers, since their 389 // data has been copied into the CXXRecordDecl. 390 for (unsigned idx = 0; idx < NumGoodBases; ++idx) 391 delete BaseSpecs[idx]; 392} 393 394//===----------------------------------------------------------------------===// 395// C++ class member Handling 396//===----------------------------------------------------------------------===// 397 398/// ActOnStartCXXClassDef - This is called at the start of a class/struct/union 399/// definition, when on C++. 400void Sema::ActOnStartCXXClassDef(Scope *S, DeclTy *D, SourceLocation LBrace) { 401 CXXRecordDecl *Dcl = cast<CXXRecordDecl>(static_cast<Decl *>(D)); 402 PushDeclContext(S, Dcl); 403 FieldCollector->StartClass(); 404 405 if (Dcl->getIdentifier()) { 406 // C++ [class]p2: 407 // [...] The class-name is also inserted into the scope of the 408 // class itself; this is known as the injected-class-name. For 409 // purposes of access checking, the injected-class-name is treated 410 // as if it were a public member name. 411 PushOnScopeChains(Dcl, S); 412 } 413} 414 415/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 416/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 417/// bitfield width if there is one and 'InitExpr' specifies the initializer if 418/// any. 'LastInGroup' is non-null for cases where one declspec has multiple 419/// declarators on it. 420/// 421/// FIXME: The note below is out-of-date. 422/// NOTE: Because of CXXFieldDecl's inability to be chained like ScopedDecls, if 423/// an instance field is declared, a new CXXFieldDecl is created but the method 424/// does *not* return it; it returns LastInGroup instead. The other C++ members 425/// (which are all ScopedDecls) are returned after appending them to 426/// LastInGroup. 427Sema::DeclTy * 428Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 429 ExprTy *BW, ExprTy *InitExpr, 430 DeclTy *LastInGroup) { 431 const DeclSpec &DS = D.getDeclSpec(); 432 DeclarationName Name = GetNameForDeclarator(D); 433 Expr *BitWidth = static_cast<Expr*>(BW); 434 Expr *Init = static_cast<Expr*>(InitExpr); 435 SourceLocation Loc = D.getIdentifierLoc(); 436 437 bool isFunc = D.isFunctionDeclarator(); 438 439 // C++ 9.2p6: A member shall not be declared to have automatic storage 440 // duration (auto, register) or with the extern storage-class-specifier. 441 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 442 // data members and cannot be applied to names declared const or static, 443 // and cannot be applied to reference members. 444 switch (DS.getStorageClassSpec()) { 445 case DeclSpec::SCS_unspecified: 446 case DeclSpec::SCS_typedef: 447 case DeclSpec::SCS_static: 448 // FALL THROUGH. 449 break; 450 case DeclSpec::SCS_mutable: 451 if (isFunc) { 452 if (DS.getStorageClassSpecLoc().isValid()) 453 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 454 else 455 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function); 456 457 // FIXME: It would be nicer if the keyword was ignored only for this 458 // declarator. Otherwise we could get follow-up errors. 459 D.getMutableDeclSpec().ClearStorageClassSpecs(); 460 } else { 461 QualType T = GetTypeForDeclarator(D, S); 462 diag::kind err = static_cast<diag::kind>(0); 463 if (T->isReferenceType()) 464 err = diag::err_mutable_reference; 465 else if (T.isConstQualified()) 466 err = diag::err_mutable_const; 467 if (err != 0) { 468 if (DS.getStorageClassSpecLoc().isValid()) 469 Diag(DS.getStorageClassSpecLoc(), err); 470 else 471 Diag(DS.getThreadSpecLoc(), err); 472 // FIXME: It would be nicer if the keyword was ignored only for this 473 // declarator. Otherwise we could get follow-up errors. 474 D.getMutableDeclSpec().ClearStorageClassSpecs(); 475 } 476 } 477 break; 478 default: 479 if (DS.getStorageClassSpecLoc().isValid()) 480 Diag(DS.getStorageClassSpecLoc(), 481 diag::err_storageclass_invalid_for_member); 482 else 483 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member); 484 D.getMutableDeclSpec().ClearStorageClassSpecs(); 485 } 486 487 if (!isFunc && 488 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typedef && 489 D.getNumTypeObjects() == 0) { 490 // Check also for this case: 491 // 492 // typedef int f(); 493 // f a; 494 // 495 Decl *TD = static_cast<Decl *>(DS.getTypeRep()); 496 isFunc = Context.getTypeDeclType(cast<TypeDecl>(TD))->isFunctionType(); 497 } 498 499 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 500 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 501 !isFunc); 502 503 Decl *Member; 504 bool InvalidDecl = false; 505 506 if (isInstField) 507 Member = static_cast<Decl*>(ActOnField(S, cast<CXXRecordDecl>(CurContext), 508 Loc, D, BitWidth)); 509 else 510 Member = static_cast<Decl*>(ActOnDeclarator(S, D, LastInGroup)); 511 512 if (!Member) return LastInGroup; 513 514 assert((Name || isInstField) && "No identifier for non-field ?"); 515 516 // set/getAccess is not part of Decl's interface to avoid bloating it with C++ 517 // specific methods. Use a wrapper class that can be used with all C++ class 518 // member decls. 519 CXXClassMemberWrapper(Member).setAccess(AS); 520 521 // C++ [dcl.init.aggr]p1: 522 // An aggregate is an array or a class (clause 9) with [...] no 523 // private or protected non-static data members (clause 11). 524 if (isInstField && (AS == AS_private || AS == AS_protected)) 525 cast<CXXRecordDecl>(CurContext)->setAggregate(false); 526 527 if (DS.isVirtualSpecified()) { 528 if (!isFunc || DS.getStorageClassSpec() == DeclSpec::SCS_static) { 529 Diag(DS.getVirtualSpecLoc(), diag::err_virtual_non_function); 530 InvalidDecl = true; 531 } else { 532 CXXRecordDecl *CurClass = cast<CXXRecordDecl>(CurContext); 533 CurClass->setAggregate(false); 534 CurClass->setPolymorphic(true); 535 } 536 } 537 538 if (BitWidth) { 539 // C++ 9.6p2: Only when declaring an unnamed bit-field may the 540 // constant-expression be a value equal to zero. 541 // FIXME: Check this. 542 543 if (D.isFunctionDeclarator()) { 544 // FIXME: Emit diagnostic about only constructors taking base initializers 545 // or something similar, when constructor support is in place. 546 Diag(Loc, diag::err_not_bitfield_type) 547 << Name << BitWidth->getSourceRange(); 548 InvalidDecl = true; 549 550 } else if (isInstField) { 551 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 552 if (!cast<FieldDecl>(Member)->getType()->isIntegralType()) { 553 Diag(Loc, diag::err_not_integral_type_bitfield) 554 << Name << BitWidth->getSourceRange(); 555 InvalidDecl = true; 556 } 557 558 } else if (isa<FunctionDecl>(Member)) { 559 // A function typedef ("typedef int f(); f a;"). 560 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 561 Diag(Loc, diag::err_not_integral_type_bitfield) 562 << Name << BitWidth->getSourceRange(); 563 InvalidDecl = true; 564 565 } else if (isa<TypedefDecl>(Member)) { 566 // "cannot declare 'A' to be a bit-field type" 567 Diag(Loc, diag::err_not_bitfield_type) 568 << Name << BitWidth->getSourceRange(); 569 InvalidDecl = true; 570 571 } else { 572 assert(isa<CXXClassVarDecl>(Member) && 573 "Didn't we cover all member kinds?"); 574 // C++ 9.6p3: A bit-field shall not be a static member. 575 // "static member 'A' cannot be a bit-field" 576 Diag(Loc, diag::err_static_not_bitfield) 577 << Name << BitWidth->getSourceRange(); 578 InvalidDecl = true; 579 } 580 } 581 582 if (Init) { 583 // C++ 9.2p4: A member-declarator can contain a constant-initializer only 584 // if it declares a static member of const integral or const enumeration 585 // type. 586 if (CXXClassVarDecl *CVD = dyn_cast<CXXClassVarDecl>(Member)) { 587 // ...static member of... 588 CVD->setInit(Init); 589 // ...const integral or const enumeration type. 590 if (Context.getCanonicalType(CVD->getType()).isConstQualified() && 591 CVD->getType()->isIntegralType()) { 592 // constant-initializer 593 if (CheckForConstantInitializer(Init, CVD->getType())) 594 InvalidDecl = true; 595 596 } else { 597 // not const integral. 598 Diag(Loc, diag::err_member_initialization) 599 << Name << Init->getSourceRange(); 600 InvalidDecl = true; 601 } 602 603 } else { 604 // not static member. 605 Diag(Loc, diag::err_member_initialization) 606 << Name << Init->getSourceRange(); 607 InvalidDecl = true; 608 } 609 } 610 611 if (InvalidDecl) 612 Member->setInvalidDecl(); 613 614 if (isInstField) { 615 FieldCollector->Add(cast<FieldDecl>(Member)); 616 return LastInGroup; 617 } 618 return Member; 619} 620 621/// ActOnMemInitializer - Handle a C++ member initializer. 622Sema::MemInitResult 623Sema::ActOnMemInitializer(DeclTy *ConstructorD, 624 Scope *S, 625 IdentifierInfo *MemberOrBase, 626 SourceLocation IdLoc, 627 SourceLocation LParenLoc, 628 ExprTy **Args, unsigned NumArgs, 629 SourceLocation *CommaLocs, 630 SourceLocation RParenLoc) { 631 CXXConstructorDecl *Constructor 632 = dyn_cast<CXXConstructorDecl>((Decl*)ConstructorD); 633 if (!Constructor) { 634 // The user wrote a constructor initializer on a function that is 635 // not a C++ constructor. Ignore the error for now, because we may 636 // have more member initializers coming; we'll diagnose it just 637 // once in ActOnMemInitializers. 638 return true; 639 } 640 641 CXXRecordDecl *ClassDecl = Constructor->getParent(); 642 643 // C++ [class.base.init]p2: 644 // Names in a mem-initializer-id are looked up in the scope of the 645 // constructor’s class and, if not found in that scope, are looked 646 // up in the scope containing the constructor’s 647 // definition. [Note: if the constructor’s class contains a member 648 // with the same name as a direct or virtual base class of the 649 // class, a mem-initializer-id naming the member or base class and 650 // composed of a single identifier refers to the class member. A 651 // mem-initializer-id for the hidden base class may be specified 652 // using a qualified name. ] 653 // Look for a member, first. 654 FieldDecl *Member = 0; 655 DeclContext::lookup_result Result = ClassDecl->lookup(Context, MemberOrBase); 656 if (Result.first != Result.second) 657 Member = dyn_cast<FieldDecl>(*Result.first); 658 659 // FIXME: Handle members of an anonymous union. 660 661 if (Member) { 662 // FIXME: Perform direct initialization of the member. 663 return new CXXBaseOrMemberInitializer(Member, (Expr **)Args, NumArgs); 664 } 665 666 // It didn't name a member, so see if it names a class. 667 TypeTy *BaseTy = isTypeName(*MemberOrBase, S, 0/*SS*/); 668 if (!BaseTy) 669 return Diag(IdLoc, diag::err_mem_init_not_member_or_class) 670 << MemberOrBase << SourceRange(IdLoc, RParenLoc); 671 672 QualType BaseType = Context.getTypeDeclType((TypeDecl *)BaseTy); 673 if (!BaseType->isRecordType()) 674 return Diag(IdLoc, diag::err_base_init_does_not_name_class) 675 << BaseType << SourceRange(IdLoc, RParenLoc); 676 677 // C++ [class.base.init]p2: 678 // [...] Unless the mem-initializer-id names a nonstatic data 679 // member of the constructor’s class or a direct or virtual base 680 // of that class, the mem-initializer is ill-formed. A 681 // mem-initializer-list can initialize a base class using any 682 // name that denotes that base class type. 683 684 // First, check for a direct base class. 685 const CXXBaseSpecifier *DirectBaseSpec = 0; 686 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(); 687 Base != ClassDecl->bases_end(); ++Base) { 688 if (Context.getCanonicalType(BaseType).getUnqualifiedType() == 689 Context.getCanonicalType(Base->getType()).getUnqualifiedType()) { 690 // We found a direct base of this type. That's what we're 691 // initializing. 692 DirectBaseSpec = &*Base; 693 break; 694 } 695 } 696 697 // Check for a virtual base class. 698 // FIXME: We might be able to short-circuit this if we know in 699 // advance that there are no virtual bases. 700 const CXXBaseSpecifier *VirtualBaseSpec = 0; 701 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 702 // We haven't found a base yet; search the class hierarchy for a 703 // virtual base class. 704 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 705 /*DetectVirtual=*/false); 706 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) { 707 for (BasePaths::paths_iterator Path = Paths.begin(); 708 Path != Paths.end(); ++Path) { 709 if (Path->back().Base->isVirtual()) { 710 VirtualBaseSpec = Path->back().Base; 711 break; 712 } 713 } 714 } 715 } 716 717 // C++ [base.class.init]p2: 718 // If a mem-initializer-id is ambiguous because it designates both 719 // a direct non-virtual base class and an inherited virtual base 720 // class, the mem-initializer is ill-formed. 721 if (DirectBaseSpec && VirtualBaseSpec) 722 return Diag(IdLoc, diag::err_base_init_direct_and_virtual) 723 << MemberOrBase << SourceRange(IdLoc, RParenLoc); 724 725 return new CXXBaseOrMemberInitializer(BaseType, (Expr **)Args, NumArgs); 726} 727 728 729void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 730 DeclTy *TagDecl, 731 SourceLocation LBrac, 732 SourceLocation RBrac) { 733 ActOnFields(S, RLoc, TagDecl, 734 (DeclTy**)FieldCollector->getCurFields(), 735 FieldCollector->getCurNumFields(), LBrac, RBrac, 0); 736} 737 738/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 739/// special functions, such as the default constructor, copy 740/// constructor, or destructor, to the given C++ class (C++ 741/// [special]p1). This routine can only be executed just before the 742/// definition of the class is complete. 743void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 744 QualType ClassType = Context.getTypeDeclType(ClassDecl); 745 ClassType = Context.getCanonicalType(ClassType); 746 747 if (!ClassDecl->hasUserDeclaredConstructor()) { 748 // C++ [class.ctor]p5: 749 // A default constructor for a class X is a constructor of class X 750 // that can be called without an argument. If there is no 751 // user-declared constructor for class X, a default constructor is 752 // implicitly declared. An implicitly-declared default constructor 753 // is an inline public member of its class. 754 DeclarationName Name 755 = Context.DeclarationNames.getCXXConstructorName(ClassType); 756 CXXConstructorDecl *DefaultCon = 757 CXXConstructorDecl::Create(Context, ClassDecl, 758 ClassDecl->getLocation(), Name, 759 Context.getFunctionType(Context.VoidTy, 760 0, 0, false, 0), 761 /*isExplicit=*/false, 762 /*isInline=*/true, 763 /*isImplicitlyDeclared=*/true); 764 DefaultCon->setAccess(AS_public); 765 ClassDecl->addDecl(Context, DefaultCon); 766 767 // Notify the class that we've added a constructor. 768 ClassDecl->addedConstructor(Context, DefaultCon); 769 } 770 771 if (!ClassDecl->hasUserDeclaredCopyConstructor()) { 772 // C++ [class.copy]p4: 773 // If the class definition does not explicitly declare a copy 774 // constructor, one is declared implicitly. 775 776 // C++ [class.copy]p5: 777 // The implicitly-declared copy constructor for a class X will 778 // have the form 779 // 780 // X::X(const X&) 781 // 782 // if 783 bool HasConstCopyConstructor = true; 784 785 // -- each direct or virtual base class B of X has a copy 786 // constructor whose first parameter is of type const B& or 787 // const volatile B&, and 788 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(); 789 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) { 790 const CXXRecordDecl *BaseClassDecl 791 = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl()); 792 HasConstCopyConstructor 793 = BaseClassDecl->hasConstCopyConstructor(Context); 794 } 795 796 // -- for all the nonstatic data members of X that are of a 797 // class type M (or array thereof), each such class type 798 // has a copy constructor whose first parameter is of type 799 // const M& or const volatile M&. 800 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(); 801 HasConstCopyConstructor && Field != ClassDecl->field_end(); ++Field) { 802 QualType FieldType = (*Field)->getType(); 803 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 804 FieldType = Array->getElementType(); 805 if (const RecordType *FieldClassType = FieldType->getAsRecordType()) { 806 const CXXRecordDecl *FieldClassDecl 807 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 808 HasConstCopyConstructor 809 = FieldClassDecl->hasConstCopyConstructor(Context); 810 } 811 } 812 813 // Otherwise, the implicitly declared copy constructor will have 814 // the form 815 // 816 // X::X(X&) 817 QualType ArgType = Context.getTypeDeclType(ClassDecl); 818 if (HasConstCopyConstructor) 819 ArgType = ArgType.withConst(); 820 ArgType = Context.getReferenceType(ArgType); 821 822 // An implicitly-declared copy constructor is an inline public 823 // member of its class. 824 DeclarationName Name 825 = Context.DeclarationNames.getCXXConstructorName(ClassType); 826 CXXConstructorDecl *CopyConstructor 827 = CXXConstructorDecl::Create(Context, ClassDecl, 828 ClassDecl->getLocation(), Name, 829 Context.getFunctionType(Context.VoidTy, 830 &ArgType, 1, 831 false, 0), 832 /*isExplicit=*/false, 833 /*isInline=*/true, 834 /*isImplicitlyDeclared=*/true); 835 CopyConstructor->setAccess(AS_public); 836 837 // Add the parameter to the constructor. 838 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 839 ClassDecl->getLocation(), 840 /*IdentifierInfo=*/0, 841 ArgType, VarDecl::None, 0, 0); 842 CopyConstructor->setParams(&FromParam, 1); 843 844 ClassDecl->addedConstructor(Context, CopyConstructor); 845 DeclContext::lookup_result Lookup = ClassDecl->lookup(Context, Name); 846 if (Lookup.first == Lookup.second 847 || (!isa<CXXConstructorDecl>(*Lookup.first) && 848 !isa<OverloadedFunctionDecl>(*Lookup.first))) 849 ClassDecl->addDecl(Context, CopyConstructor); 850 else { 851 OverloadedFunctionDecl *Ovl 852 = dyn_cast<OverloadedFunctionDecl>(*Lookup.first); 853 if (!Ovl) { 854 Ovl = OverloadedFunctionDecl::Create(Context, ClassDecl, Name); 855 Ovl->addOverload(cast<CXXConstructorDecl>(*Lookup.first)); 856 ClassDecl->insert(Context, Ovl); 857 } 858 859 Ovl->addOverload(CopyConstructor); 860 ClassDecl->addDecl(Context, CopyConstructor, false); 861 } 862 } 863 864 if (!ClassDecl->hasUserDeclaredDestructor()) { 865 // C++ [class.dtor]p2: 866 // If a class has no user-declared destructor, a destructor is 867 // declared implicitly. An implicitly-declared destructor is an 868 // inline public member of its class. 869 DeclarationName Name 870 = Context.DeclarationNames.getCXXDestructorName(ClassType); 871 CXXDestructorDecl *Destructor 872 = CXXDestructorDecl::Create(Context, ClassDecl, 873 ClassDecl->getLocation(), Name, 874 Context.getFunctionType(Context.VoidTy, 875 0, 0, false, 0), 876 /*isInline=*/true, 877 /*isImplicitlyDeclared=*/true); 878 Destructor->setAccess(AS_public); 879 ClassDecl->addDecl(Context, Destructor); 880 } 881 882 // FIXME: Implicit copy assignment operator 883} 884 885void Sema::ActOnFinishCXXClassDef(DeclTy *D) { 886 CXXRecordDecl *Rec = cast<CXXRecordDecl>(static_cast<Decl *>(D)); 887 FieldCollector->FinishClass(); 888 AddImplicitlyDeclaredMembersToClass(Rec); 889 PopDeclContext(); 890 891 // Everything, including inline method definitions, have been parsed. 892 // Let the consumer know of the new TagDecl definition. 893 Consumer.HandleTagDeclDefinition(Rec); 894} 895 896/// ActOnStartDelayedCXXMethodDeclaration - We have completed 897/// parsing a top-level (non-nested) C++ class, and we are now 898/// parsing those parts of the given Method declaration that could 899/// not be parsed earlier (C++ [class.mem]p2), such as default 900/// arguments. This action should enter the scope of the given 901/// Method declaration as if we had just parsed the qualified method 902/// name. However, it should not bring the parameters into scope; 903/// that will be performed by ActOnDelayedCXXMethodParameter. 904void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclTy *Method) { 905 CXXScopeSpec SS; 906 SS.setScopeRep(((FunctionDecl*)Method)->getDeclContext()); 907 ActOnCXXEnterDeclaratorScope(S, SS); 908} 909 910/// ActOnDelayedCXXMethodParameter - We've already started a delayed 911/// C++ method declaration. We're (re-)introducing the given 912/// function parameter into scope for use in parsing later parts of 913/// the method declaration. For example, we could see an 914/// ActOnParamDefaultArgument event for this parameter. 915void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclTy *ParamD) { 916 ParmVarDecl *Param = (ParmVarDecl*)ParamD; 917 S->AddDecl(Param); 918 if (Param->getDeclName()) 919 IdResolver.AddDecl(Param); 920} 921 922/// ActOnFinishDelayedCXXMethodDeclaration - We have finished 923/// processing the delayed method declaration for Method. The method 924/// declaration is now considered finished. There may be a separate 925/// ActOnStartOfFunctionDef action later (not necessarily 926/// immediately!) for this method, if it was also defined inside the 927/// class body. 928void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclTy *MethodD) { 929 FunctionDecl *Method = (FunctionDecl*)MethodD; 930 CXXScopeSpec SS; 931 SS.setScopeRep(Method->getDeclContext()); 932 ActOnCXXExitDeclaratorScope(S, SS); 933 934 // Now that we have our default arguments, check the constructor 935 // again. It could produce additional diagnostics or affect whether 936 // the class has implicitly-declared destructors, among other 937 // things. 938 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) { 939 if (CheckConstructor(Constructor)) 940 Constructor->setInvalidDecl(); 941 } 942 943 // Check the default arguments, which we may have added. 944 if (!Method->isInvalidDecl()) 945 CheckCXXDefaultArguments(Method); 946} 947 948/// CheckConstructorDeclarator - Called by ActOnDeclarator to check 949/// the well-formedness of the constructor declarator @p D with type @p 950/// R. If there are any errors in the declarator, this routine will 951/// emit diagnostics and return true. Otherwise, it will return 952/// false. Either way, the type @p R will be updated to reflect a 953/// well-formed type for the constructor. 954bool Sema::CheckConstructorDeclarator(Declarator &D, QualType &R, 955 FunctionDecl::StorageClass& SC) { 956 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 957 bool isInvalid = false; 958 959 // C++ [class.ctor]p3: 960 // A constructor shall not be virtual (10.3) or static (9.4). A 961 // constructor can be invoked for a const, volatile or const 962 // volatile object. A constructor shall not be declared const, 963 // volatile, or const volatile (9.3.2). 964 if (isVirtual) { 965 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 966 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 967 << SourceRange(D.getIdentifierLoc()); 968 isInvalid = true; 969 } 970 if (SC == FunctionDecl::Static) { 971 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 972 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 973 << SourceRange(D.getIdentifierLoc()); 974 isInvalid = true; 975 SC = FunctionDecl::None; 976 } 977 if (D.getDeclSpec().hasTypeSpecifier()) { 978 // Constructors don't have return types, but the parser will 979 // happily parse something like: 980 // 981 // class X { 982 // float X(float); 983 // }; 984 // 985 // The return type will be eliminated later. 986 Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 987 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 988 << SourceRange(D.getIdentifierLoc()); 989 } 990 if (R->getAsFunctionTypeProto()->getTypeQuals() != 0) { 991 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 992 if (FTI.TypeQuals & QualType::Const) 993 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 994 << "const" << SourceRange(D.getIdentifierLoc()); 995 if (FTI.TypeQuals & QualType::Volatile) 996 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 997 << "volatile" << SourceRange(D.getIdentifierLoc()); 998 if (FTI.TypeQuals & QualType::Restrict) 999 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 1000 << "restrict" << SourceRange(D.getIdentifierLoc()); 1001 } 1002 1003 // Rebuild the function type "R" without any type qualifiers (in 1004 // case any of the errors above fired) and with "void" as the 1005 // return type, since constructors don't have return types. We 1006 // *always* have to do this, because GetTypeForDeclarator will 1007 // put in a result type of "int" when none was specified. 1008 const FunctionTypeProto *Proto = R->getAsFunctionTypeProto(); 1009 R = Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(), 1010 Proto->getNumArgs(), 1011 Proto->isVariadic(), 1012 0); 1013 1014 return isInvalid; 1015} 1016 1017/// CheckConstructor - Checks a fully-formed constructor for 1018/// well-formedness, issuing any diagnostics required. Returns true if 1019/// the constructor declarator is invalid. 1020bool Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 1021 if (Constructor->isInvalidDecl()) 1022 return true; 1023 1024 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext()); 1025 bool Invalid = false; 1026 1027 // C++ [class.copy]p3: 1028 // A declaration of a constructor for a class X is ill-formed if 1029 // its first parameter is of type (optionally cv-qualified) X and 1030 // either there are no other parameters or else all other 1031 // parameters have default arguments. 1032 if ((Constructor->getNumParams() == 1) || 1033 (Constructor->getNumParams() > 1 && 1034 Constructor->getParamDecl(1)->getDefaultArg() != 0)) { 1035 QualType ParamType = Constructor->getParamDecl(0)->getType(); 1036 QualType ClassTy = Context.getTagDeclType(ClassDecl); 1037 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 1038 Diag(Constructor->getLocation(), diag::err_constructor_byvalue_arg) 1039 << SourceRange(Constructor->getParamDecl(0)->getLocation()); 1040 Invalid = true; 1041 } 1042 } 1043 1044 // Notify the class that we've added a constructor. 1045 ClassDecl->addedConstructor(Context, Constructor); 1046 1047 return Invalid; 1048} 1049 1050/// CheckDestructorDeclarator - Called by ActOnDeclarator to check 1051/// the well-formednes of the destructor declarator @p D with type @p 1052/// R. If there are any errors in the declarator, this routine will 1053/// emit diagnostics and return true. Otherwise, it will return 1054/// false. Either way, the type @p R will be updated to reflect a 1055/// well-formed type for the destructor. 1056bool Sema::CheckDestructorDeclarator(Declarator &D, QualType &R, 1057 FunctionDecl::StorageClass& SC) { 1058 bool isInvalid = false; 1059 1060 // C++ [class.dtor]p1: 1061 // [...] A typedef-name that names a class is a class-name 1062 // (7.1.3); however, a typedef-name that names a class shall not 1063 // be used as the identifier in the declarator for a destructor 1064 // declaration. 1065 TypeDecl *DeclaratorTypeD = (TypeDecl *)D.getDeclaratorIdType(); 1066 if (const TypedefDecl *TypedefD = dyn_cast<TypedefDecl>(DeclaratorTypeD)) { 1067 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 1068 << TypedefD->getDeclName(); 1069 isInvalid = true; 1070 } 1071 1072 // C++ [class.dtor]p2: 1073 // A destructor is used to destroy objects of its class type. A 1074 // destructor takes no parameters, and no return type can be 1075 // specified for it (not even void). The address of a destructor 1076 // shall not be taken. A destructor shall not be static. A 1077 // destructor can be invoked for a const, volatile or const 1078 // volatile object. A destructor shall not be declared const, 1079 // volatile or const volatile (9.3.2). 1080 if (SC == FunctionDecl::Static) { 1081 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 1082 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 1083 << SourceRange(D.getIdentifierLoc()); 1084 isInvalid = true; 1085 SC = FunctionDecl::None; 1086 } 1087 if (D.getDeclSpec().hasTypeSpecifier()) { 1088 // Destructors don't have return types, but the parser will 1089 // happily parse something like: 1090 // 1091 // class X { 1092 // float ~X(); 1093 // }; 1094 // 1095 // The return type will be eliminated later. 1096 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 1097 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 1098 << SourceRange(D.getIdentifierLoc()); 1099 } 1100 if (R->getAsFunctionTypeProto()->getTypeQuals() != 0) { 1101 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 1102 if (FTI.TypeQuals & QualType::Const) 1103 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 1104 << "const" << SourceRange(D.getIdentifierLoc()); 1105 if (FTI.TypeQuals & QualType::Volatile) 1106 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 1107 << "volatile" << SourceRange(D.getIdentifierLoc()); 1108 if (FTI.TypeQuals & QualType::Restrict) 1109 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 1110 << "restrict" << SourceRange(D.getIdentifierLoc()); 1111 } 1112 1113 // Make sure we don't have any parameters. 1114 if (R->getAsFunctionTypeProto()->getNumArgs() > 0) { 1115 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 1116 1117 // Delete the parameters. 1118 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 1119 if (FTI.NumArgs) { 1120 delete [] FTI.ArgInfo; 1121 FTI.NumArgs = 0; 1122 FTI.ArgInfo = 0; 1123 } 1124 } 1125 1126 // Make sure the destructor isn't variadic. 1127 if (R->getAsFunctionTypeProto()->isVariadic()) 1128 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 1129 1130 // Rebuild the function type "R" without any type qualifiers or 1131 // parameters (in case any of the errors above fired) and with 1132 // "void" as the return type, since destructors don't have return 1133 // types. We *always* have to do this, because GetTypeForDeclarator 1134 // will put in a result type of "int" when none was specified. 1135 R = Context.getFunctionType(Context.VoidTy, 0, 0, false, 0); 1136 1137 return isInvalid; 1138} 1139 1140/// CheckConversionDeclarator - Called by ActOnDeclarator to check the 1141/// well-formednes of the conversion function declarator @p D with 1142/// type @p R. If there are any errors in the declarator, this routine 1143/// will emit diagnostics and return true. Otherwise, it will return 1144/// false. Either way, the type @p R will be updated to reflect a 1145/// well-formed type for the conversion operator. 1146bool Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 1147 FunctionDecl::StorageClass& SC) { 1148 bool isInvalid = false; 1149 1150 // C++ [class.conv.fct]p1: 1151 // Neither parameter types nor return type can be specified. The 1152 // type of a conversion function (8.3.5) is “function taking no 1153 // parameter returning conversion-type-id.” 1154 if (SC == FunctionDecl::Static) { 1155 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 1156 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 1157 << SourceRange(D.getIdentifierLoc()); 1158 isInvalid = true; 1159 SC = FunctionDecl::None; 1160 } 1161 if (D.getDeclSpec().hasTypeSpecifier()) { 1162 // Conversion functions don't have return types, but the parser will 1163 // happily parse something like: 1164 // 1165 // class X { 1166 // float operator bool(); 1167 // }; 1168 // 1169 // The return type will be changed later anyway. 1170 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 1171 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 1172 << SourceRange(D.getIdentifierLoc()); 1173 } 1174 1175 // Make sure we don't have any parameters. 1176 if (R->getAsFunctionTypeProto()->getNumArgs() > 0) { 1177 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 1178 1179 // Delete the parameters. 1180 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 1181 if (FTI.NumArgs) { 1182 delete [] FTI.ArgInfo; 1183 FTI.NumArgs = 0; 1184 FTI.ArgInfo = 0; 1185 } 1186 } 1187 1188 // Make sure the conversion function isn't variadic. 1189 if (R->getAsFunctionTypeProto()->isVariadic()) 1190 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 1191 1192 // C++ [class.conv.fct]p4: 1193 // The conversion-type-id shall not represent a function type nor 1194 // an array type. 1195 QualType ConvType = QualType::getFromOpaquePtr(D.getDeclaratorIdType()); 1196 if (ConvType->isArrayType()) { 1197 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 1198 ConvType = Context.getPointerType(ConvType); 1199 } else if (ConvType->isFunctionType()) { 1200 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 1201 ConvType = Context.getPointerType(ConvType); 1202 } 1203 1204 // Rebuild the function type "R" without any parameters (in case any 1205 // of the errors above fired) and with the conversion type as the 1206 // return type. 1207 R = Context.getFunctionType(ConvType, 0, 0, false, 1208 R->getAsFunctionTypeProto()->getTypeQuals()); 1209 1210 return isInvalid; 1211} 1212 1213/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 1214/// the declaration of the given C++ conversion function. This routine 1215/// is responsible for recording the conversion function in the C++ 1216/// class, if possible. 1217Sema::DeclTy *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 1218 assert(Conversion && "Expected to receive a conversion function declaration"); 1219 1220 // Set the lexical context of this conversion function 1221 Conversion->setLexicalDeclContext(CurContext); 1222 1223 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 1224 1225 // Make sure we aren't redeclaring the conversion function. 1226 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 1227 OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions(); 1228 for (OverloadedFunctionDecl::function_iterator Func 1229 = Conversions->function_begin(); 1230 Func != Conversions->function_end(); ++Func) { 1231 CXXConversionDecl *OtherConv = cast<CXXConversionDecl>(*Func); 1232 if (ConvType == Context.getCanonicalType(OtherConv->getConversionType())) { 1233 Diag(Conversion->getLocation(), diag::err_conv_function_redeclared); 1234 Diag(OtherConv->getLocation(), 1235 OtherConv->isThisDeclarationADefinition()? 1236 diag::note_previous_definition 1237 : diag::note_previous_declaration); 1238 Conversion->setInvalidDecl(); 1239 return (DeclTy *)Conversion; 1240 } 1241 } 1242 1243 // C++ [class.conv.fct]p1: 1244 // [...] A conversion function is never used to convert a 1245 // (possibly cv-qualified) object to the (possibly cv-qualified) 1246 // same object type (or a reference to it), to a (possibly 1247 // cv-qualified) base class of that type (or a reference to it), 1248 // or to (possibly cv-qualified) void. 1249 // FIXME: Suppress this warning if the conversion function ends up 1250 // being a virtual function that overrides a virtual function in a 1251 // base class. 1252 QualType ClassType 1253 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 1254 if (const ReferenceType *ConvTypeRef = ConvType->getAsReferenceType()) 1255 ConvType = ConvTypeRef->getPointeeType(); 1256 if (ConvType->isRecordType()) { 1257 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 1258 if (ConvType == ClassType) 1259 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 1260 << ClassType; 1261 else if (IsDerivedFrom(ClassType, ConvType)) 1262 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 1263 << ClassType << ConvType; 1264 } else if (ConvType->isVoidType()) { 1265 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 1266 << ClassType << ConvType; 1267 } 1268 1269 ClassDecl->addConversionFunction(Context, Conversion); 1270 1271 return (DeclTy *)Conversion; 1272} 1273 1274//===----------------------------------------------------------------------===// 1275// Namespace Handling 1276//===----------------------------------------------------------------------===// 1277 1278/// ActOnStartNamespaceDef - This is called at the start of a namespace 1279/// definition. 1280Sema::DeclTy *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 1281 SourceLocation IdentLoc, 1282 IdentifierInfo *II, 1283 SourceLocation LBrace) { 1284 NamespaceDecl *Namespc = 1285 NamespaceDecl::Create(Context, CurContext, IdentLoc, II); 1286 Namespc->setLBracLoc(LBrace); 1287 1288 Scope *DeclRegionScope = NamespcScope->getParent(); 1289 1290 if (II) { 1291 // C++ [namespace.def]p2: 1292 // The identifier in an original-namespace-definition shall not have been 1293 // previously defined in the declarative region in which the 1294 // original-namespace-definition appears. The identifier in an 1295 // original-namespace-definition is the name of the namespace. Subsequently 1296 // in that declarative region, it is treated as an original-namespace-name. 1297 1298 Decl *PrevDecl = 1299 LookupDecl(II, Decl::IDNS_Tag | Decl::IDNS_Ordinary, DeclRegionScope, 0, 1300 /*enableLazyBuiltinCreation=*/false, 1301 /*LookupInParent=*/false); 1302 1303 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) { 1304 // This is an extended namespace definition. 1305 // Attach this namespace decl to the chain of extended namespace 1306 // definitions. 1307 OrigNS->setNextNamespace(Namespc); 1308 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace()); 1309 1310 // Remove the previous declaration from the scope. 1311 if (DeclRegionScope->isDeclScope(OrigNS)) { 1312 IdResolver.RemoveDecl(OrigNS); 1313 DeclRegionScope->RemoveDecl(OrigNS); 1314 } 1315 } else if (PrevDecl) { 1316 // This is an invalid name redefinition. 1317 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind) 1318 << Namespc->getDeclName(); 1319 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 1320 Namespc->setInvalidDecl(); 1321 // Continue on to push Namespc as current DeclContext and return it. 1322 } 1323 1324 PushOnScopeChains(Namespc, DeclRegionScope); 1325 } else { 1326 // FIXME: Handle anonymous namespaces 1327 } 1328 1329 // Although we could have an invalid decl (i.e. the namespace name is a 1330 // redefinition), push it as current DeclContext and try to continue parsing. 1331 // FIXME: We should be able to push Namespc here, so that the 1332 // each DeclContext for the namespace has the declarations 1333 // that showed up in that particular namespace definition. 1334 PushDeclContext(NamespcScope, Namespc); 1335 return Namespc; 1336} 1337 1338/// ActOnFinishNamespaceDef - This callback is called after a namespace is 1339/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 1340void Sema::ActOnFinishNamespaceDef(DeclTy *D, SourceLocation RBrace) { 1341 Decl *Dcl = static_cast<Decl *>(D); 1342 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 1343 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 1344 Namespc->setRBracLoc(RBrace); 1345 PopDeclContext(); 1346} 1347 1348 1349/// AddCXXDirectInitializerToDecl - This action is called immediately after 1350/// ActOnDeclarator, when a C++ direct initializer is present. 1351/// e.g: "int x(1);" 1352void Sema::AddCXXDirectInitializerToDecl(DeclTy *Dcl, SourceLocation LParenLoc, 1353 ExprTy **ExprTys, unsigned NumExprs, 1354 SourceLocation *CommaLocs, 1355 SourceLocation RParenLoc) { 1356 assert(NumExprs != 0 && ExprTys && "missing expressions"); 1357 Decl *RealDecl = static_cast<Decl *>(Dcl); 1358 1359 // If there is no declaration, there was an error parsing it. Just ignore 1360 // the initializer. 1361 if (RealDecl == 0) { 1362 for (unsigned i = 0; i != NumExprs; ++i) 1363 delete static_cast<Expr *>(ExprTys[i]); 1364 return; 1365 } 1366 1367 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 1368 if (!VDecl) { 1369 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 1370 RealDecl->setInvalidDecl(); 1371 return; 1372 } 1373 1374 // We will treat direct-initialization as a copy-initialization: 1375 // int x(1); -as-> int x = 1; 1376 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 1377 // 1378 // Clients that want to distinguish between the two forms, can check for 1379 // direct initializer using VarDecl::hasCXXDirectInitializer(). 1380 // A major benefit is that clients that don't particularly care about which 1381 // exactly form was it (like the CodeGen) can handle both cases without 1382 // special case code. 1383 1384 // C++ 8.5p11: 1385 // The form of initialization (using parentheses or '=') is generally 1386 // insignificant, but does matter when the entity being initialized has a 1387 // class type. 1388 QualType DeclInitType = VDecl->getType(); 1389 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType)) 1390 DeclInitType = Array->getElementType(); 1391 1392 if (VDecl->getType()->isRecordType()) { 1393 CXXConstructorDecl *Constructor 1394 = PerformInitializationByConstructor(DeclInitType, 1395 (Expr **)ExprTys, NumExprs, 1396 VDecl->getLocation(), 1397 SourceRange(VDecl->getLocation(), 1398 RParenLoc), 1399 VDecl->getDeclName(), 1400 IK_Direct); 1401 if (!Constructor) { 1402 RealDecl->setInvalidDecl(); 1403 } 1404 1405 // Let clients know that initialization was done with a direct 1406 // initializer. 1407 VDecl->setCXXDirectInitializer(true); 1408 1409 // FIXME: Add ExprTys and Constructor to the RealDecl as part of 1410 // the initializer. 1411 return; 1412 } 1413 1414 if (NumExprs > 1) { 1415 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg) 1416 << SourceRange(VDecl->getLocation(), RParenLoc); 1417 RealDecl->setInvalidDecl(); 1418 return; 1419 } 1420 1421 // Let clients know that initialization was done with a direct initializer. 1422 VDecl->setCXXDirectInitializer(true); 1423 1424 assert(NumExprs == 1 && "Expected 1 expression"); 1425 // Set the init expression, handles conversions. 1426 AddInitializerToDecl(Dcl, ExprArg(*this, ExprTys[0])); 1427} 1428 1429/// PerformInitializationByConstructor - Perform initialization by 1430/// constructor (C++ [dcl.init]p14), which may occur as part of 1431/// direct-initialization or copy-initialization. We are initializing 1432/// an object of type @p ClassType with the given arguments @p 1433/// Args. @p Loc is the location in the source code where the 1434/// initializer occurs (e.g., a declaration, member initializer, 1435/// functional cast, etc.) while @p Range covers the whole 1436/// initialization. @p InitEntity is the entity being initialized, 1437/// which may by the name of a declaration or a type. @p Kind is the 1438/// kind of initialization we're performing, which affects whether 1439/// explicit constructors will be considered. When successful, returns 1440/// the constructor that will be used to perform the initialization; 1441/// when the initialization fails, emits a diagnostic and returns 1442/// null. 1443CXXConstructorDecl * 1444Sema::PerformInitializationByConstructor(QualType ClassType, 1445 Expr **Args, unsigned NumArgs, 1446 SourceLocation Loc, SourceRange Range, 1447 DeclarationName InitEntity, 1448 InitializationKind Kind) { 1449 const RecordType *ClassRec = ClassType->getAsRecordType(); 1450 assert(ClassRec && "Can only initialize a class type here"); 1451 1452 // C++ [dcl.init]p14: 1453 // 1454 // If the initialization is direct-initialization, or if it is 1455 // copy-initialization where the cv-unqualified version of the 1456 // source type is the same class as, or a derived class of, the 1457 // class of the destination, constructors are considered. The 1458 // applicable constructors are enumerated (13.3.1.3), and the 1459 // best one is chosen through overload resolution (13.3). The 1460 // constructor so selected is called to initialize the object, 1461 // with the initializer expression(s) as its argument(s). If no 1462 // constructor applies, or the overload resolution is ambiguous, 1463 // the initialization is ill-formed. 1464 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl()); 1465 OverloadCandidateSet CandidateSet; 1466 1467 // Add constructors to the overload set. 1468 DeclarationName ConstructorName 1469 = Context.DeclarationNames.getCXXConstructorName( 1470 Context.getCanonicalType(ClassType.getUnqualifiedType())); 1471 DeclContext::lookup_const_result Lookup 1472 = ClassDecl->lookup(Context, ConstructorName); 1473 if (Lookup.first == Lookup.second) 1474 /* No constructors */; 1475 else if (OverloadedFunctionDecl *Constructors 1476 = dyn_cast<OverloadedFunctionDecl>(*Lookup.first)) { 1477 for (OverloadedFunctionDecl::function_iterator Con 1478 = Constructors->function_begin(); 1479 Con != Constructors->function_end(); ++Con) { 1480 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con); 1481 if ((Kind == IK_Direct) || 1482 (Kind == IK_Copy && Constructor->isConvertingConstructor()) || 1483 (Kind == IK_Default && Constructor->isDefaultConstructor())) 1484 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet); 1485 } 1486 } else if (CXXConstructorDecl *Constructor 1487 = dyn_cast<CXXConstructorDecl>(*Lookup.first)) { 1488 if ((Kind == IK_Direct) || 1489 (Kind == IK_Copy && Constructor->isConvertingConstructor()) || 1490 (Kind == IK_Default && Constructor->isDefaultConstructor())) 1491 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet); 1492 } 1493 1494 // FIXME: When we decide not to synthesize the implicitly-declared 1495 // constructors, we'll need to make them appear here. 1496 1497 OverloadCandidateSet::iterator Best; 1498 switch (BestViableFunction(CandidateSet, Best)) { 1499 case OR_Success: 1500 // We found a constructor. Return it. 1501 return cast<CXXConstructorDecl>(Best->Function); 1502 1503 case OR_No_Viable_Function: 1504 Diag(Loc, diag::err_ovl_no_viable_function_in_init) 1505 << InitEntity << (unsigned)CandidateSet.size() << Range; 1506 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false); 1507 return 0; 1508 1509 case OR_Ambiguous: 1510 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range; 1511 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 1512 return 0; 1513 } 1514 1515 return 0; 1516} 1517 1518/// CompareReferenceRelationship - Compare the two types T1 and T2 to 1519/// determine whether they are reference-related, 1520/// reference-compatible, reference-compatible with added 1521/// qualification, or incompatible, for use in C++ initialization by 1522/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 1523/// type, and the first type (T1) is the pointee type of the reference 1524/// type being initialized. 1525Sema::ReferenceCompareResult 1526Sema::CompareReferenceRelationship(QualType T1, QualType T2, 1527 bool& DerivedToBase) { 1528 assert(!T1->isReferenceType() && "T1 must be the pointee type of the reference type"); 1529 assert(!T2->isReferenceType() && "T2 cannot be a reference type"); 1530 1531 T1 = Context.getCanonicalType(T1); 1532 T2 = Context.getCanonicalType(T2); 1533 QualType UnqualT1 = T1.getUnqualifiedType(); 1534 QualType UnqualT2 = T2.getUnqualifiedType(); 1535 1536 // C++ [dcl.init.ref]p4: 1537 // Given types “cv1 T1” and “cv2 T2,” “cv1 T1” is 1538 // reference-related to “cv2 T2” if T1 is the same type as T2, or 1539 // T1 is a base class of T2. 1540 if (UnqualT1 == UnqualT2) 1541 DerivedToBase = false; 1542 else if (IsDerivedFrom(UnqualT2, UnqualT1)) 1543 DerivedToBase = true; 1544 else 1545 return Ref_Incompatible; 1546 1547 // At this point, we know that T1 and T2 are reference-related (at 1548 // least). 1549 1550 // C++ [dcl.init.ref]p4: 1551 // "cv1 T1” is reference-compatible with “cv2 T2” if T1 is 1552 // reference-related to T2 and cv1 is the same cv-qualification 1553 // as, or greater cv-qualification than, cv2. For purposes of 1554 // overload resolution, cases for which cv1 is greater 1555 // cv-qualification than cv2 are identified as 1556 // reference-compatible with added qualification (see 13.3.3.2). 1557 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 1558 return Ref_Compatible; 1559 else if (T1.isMoreQualifiedThan(T2)) 1560 return Ref_Compatible_With_Added_Qualification; 1561 else 1562 return Ref_Related; 1563} 1564 1565/// CheckReferenceInit - Check the initialization of a reference 1566/// variable with the given initializer (C++ [dcl.init.ref]). Init is 1567/// the initializer (either a simple initializer or an initializer 1568/// list), and DeclType is the type of the declaration. When ICS is 1569/// non-null, this routine will compute the implicit conversion 1570/// sequence according to C++ [over.ics.ref] and will not produce any 1571/// diagnostics; when ICS is null, it will emit diagnostics when any 1572/// errors are found. Either way, a return value of true indicates 1573/// that there was a failure, a return value of false indicates that 1574/// the reference initialization succeeded. 1575/// 1576/// When @p SuppressUserConversions, user-defined conversions are 1577/// suppressed. 1578bool 1579Sema::CheckReferenceInit(Expr *&Init, QualType &DeclType, 1580 ImplicitConversionSequence *ICS, 1581 bool SuppressUserConversions) { 1582 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 1583 1584 QualType T1 = DeclType->getAsReferenceType()->getPointeeType(); 1585 QualType T2 = Init->getType(); 1586 1587 // If the initializer is the address of an overloaded function, try 1588 // to resolve the overloaded function. If all goes well, T2 is the 1589 // type of the resulting function. 1590 if (T2->isOverloadType()) { 1591 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType, 1592 ICS != 0); 1593 if (Fn) { 1594 // Since we're performing this reference-initialization for 1595 // real, update the initializer with the resulting function. 1596 if (!ICS) 1597 FixOverloadedFunctionReference(Init, Fn); 1598 1599 T2 = Fn->getType(); 1600 } 1601 } 1602 1603 // Compute some basic properties of the types and the initializer. 1604 bool DerivedToBase = false; 1605 Expr::isLvalueResult InitLvalue = Init->isLvalue(Context); 1606 ReferenceCompareResult RefRelationship 1607 = CompareReferenceRelationship(T1, T2, DerivedToBase); 1608 1609 // Most paths end in a failed conversion. 1610 if (ICS) 1611 ICS->ConversionKind = ImplicitConversionSequence::BadConversion; 1612 1613 // C++ [dcl.init.ref]p5: 1614 // A reference to type “cv1 T1” is initialized by an expression 1615 // of type “cv2 T2” as follows: 1616 1617 // -- If the initializer expression 1618 1619 bool BindsDirectly = false; 1620 // -- is an lvalue (but is not a bit-field), and “cv1 T1” is 1621 // reference-compatible with “cv2 T2,” or 1622 // 1623 // Note that the bit-field check is skipped if we are just computing 1624 // the implicit conversion sequence (C++ [over.best.ics]p2). 1625 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->isBitField()) && 1626 RefRelationship >= Ref_Compatible_With_Added_Qualification) { 1627 BindsDirectly = true; 1628 1629 if (ICS) { 1630 // C++ [over.ics.ref]p1: 1631 // When a parameter of reference type binds directly (8.5.3) 1632 // to an argument expression, the implicit conversion sequence 1633 // is the identity conversion, unless the argument expression 1634 // has a type that is a derived class of the parameter type, 1635 // in which case the implicit conversion sequence is a 1636 // derived-to-base Conversion (13.3.3.1). 1637 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion; 1638 ICS->Standard.First = ICK_Identity; 1639 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity; 1640 ICS->Standard.Third = ICK_Identity; 1641 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr(); 1642 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr(); 1643 ICS->Standard.ReferenceBinding = true; 1644 ICS->Standard.DirectBinding = true; 1645 1646 // Nothing more to do: the inaccessibility/ambiguity check for 1647 // derived-to-base conversions is suppressed when we're 1648 // computing the implicit conversion sequence (C++ 1649 // [over.best.ics]p2). 1650 return false; 1651 } else { 1652 // Perform the conversion. 1653 // FIXME: Binding to a subobject of the lvalue is going to require 1654 // more AST annotation than this. 1655 ImpCastExprToType(Init, T1, /*isLvalue=*/true); 1656 } 1657 } 1658 1659 // -- has a class type (i.e., T2 is a class type) and can be 1660 // implicitly converted to an lvalue of type “cv3 T3,” 1661 // where “cv1 T1” is reference-compatible with “cv3 T3” 1662 // 92) (this conversion is selected by enumerating the 1663 // applicable conversion functions (13.3.1.6) and choosing 1664 // the best one through overload resolution (13.3)), 1665 if (!SuppressUserConversions && T2->isRecordType()) { 1666 // FIXME: Look for conversions in base classes! 1667 CXXRecordDecl *T2RecordDecl 1668 = dyn_cast<CXXRecordDecl>(T2->getAsRecordType()->getDecl()); 1669 1670 OverloadCandidateSet CandidateSet; 1671 OverloadedFunctionDecl *Conversions 1672 = T2RecordDecl->getConversionFunctions(); 1673 for (OverloadedFunctionDecl::function_iterator Func 1674 = Conversions->function_begin(); 1675 Func != Conversions->function_end(); ++Func) { 1676 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func); 1677 1678 // If the conversion function doesn't return a reference type, 1679 // it can't be considered for this conversion. 1680 // FIXME: This will change when we support rvalue references. 1681 if (Conv->getConversionType()->isReferenceType()) 1682 AddConversionCandidate(Conv, Init, DeclType, CandidateSet); 1683 } 1684 1685 OverloadCandidateSet::iterator Best; 1686 switch (BestViableFunction(CandidateSet, Best)) { 1687 case OR_Success: 1688 // This is a direct binding. 1689 BindsDirectly = true; 1690 1691 if (ICS) { 1692 // C++ [over.ics.ref]p1: 1693 // 1694 // [...] If the parameter binds directly to the result of 1695 // applying a conversion function to the argument 1696 // expression, the implicit conversion sequence is a 1697 // user-defined conversion sequence (13.3.3.1.2), with the 1698 // second standard conversion sequence either an identity 1699 // conversion or, if the conversion function returns an 1700 // entity of a type that is a derived class of the parameter 1701 // type, a derived-to-base Conversion. 1702 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion; 1703 ICS->UserDefined.Before = Best->Conversions[0].Standard; 1704 ICS->UserDefined.After = Best->FinalConversion; 1705 ICS->UserDefined.ConversionFunction = Best->Function; 1706 assert(ICS->UserDefined.After.ReferenceBinding && 1707 ICS->UserDefined.After.DirectBinding && 1708 "Expected a direct reference binding!"); 1709 return false; 1710 } else { 1711 // Perform the conversion. 1712 // FIXME: Binding to a subobject of the lvalue is going to require 1713 // more AST annotation than this. 1714 ImpCastExprToType(Init, T1, /*isLvalue=*/true); 1715 } 1716 break; 1717 1718 case OR_Ambiguous: 1719 assert(false && "Ambiguous reference binding conversions not implemented."); 1720 return true; 1721 1722 case OR_No_Viable_Function: 1723 // There was no suitable conversion; continue with other checks. 1724 break; 1725 } 1726 } 1727 1728 if (BindsDirectly) { 1729 // C++ [dcl.init.ref]p4: 1730 // [...] In all cases where the reference-related or 1731 // reference-compatible relationship of two types is used to 1732 // establish the validity of a reference binding, and T1 is a 1733 // base class of T2, a program that necessitates such a binding 1734 // is ill-formed if T1 is an inaccessible (clause 11) or 1735 // ambiguous (10.2) base class of T2. 1736 // 1737 // Note that we only check this condition when we're allowed to 1738 // complain about errors, because we should not be checking for 1739 // ambiguity (or inaccessibility) unless the reference binding 1740 // actually happens. 1741 if (DerivedToBase) 1742 return CheckDerivedToBaseConversion(T2, T1, 1743 Init->getSourceRange().getBegin(), 1744 Init->getSourceRange()); 1745 else 1746 return false; 1747 } 1748 1749 // -- Otherwise, the reference shall be to a non-volatile const 1750 // type (i.e., cv1 shall be const). 1751 if (T1.getCVRQualifiers() != QualType::Const) { 1752 if (!ICS) 1753 Diag(Init->getSourceRange().getBegin(), 1754 diag::err_not_reference_to_const_init) 1755 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value") 1756 << T2 << Init->getSourceRange(); 1757 return true; 1758 } 1759 1760 // -- If the initializer expression is an rvalue, with T2 a 1761 // class type, and “cv1 T1” is reference-compatible with 1762 // “cv2 T2,” the reference is bound in one of the 1763 // following ways (the choice is implementation-defined): 1764 // 1765 // -- The reference is bound to the object represented by 1766 // the rvalue (see 3.10) or to a sub-object within that 1767 // object. 1768 // 1769 // -- A temporary of type “cv1 T2” [sic] is created, and 1770 // a constructor is called to copy the entire rvalue 1771 // object into the temporary. The reference is bound to 1772 // the temporary or to a sub-object within the 1773 // temporary. 1774 // 1775 // 1776 // The constructor that would be used to make the copy 1777 // shall be callable whether or not the copy is actually 1778 // done. 1779 // 1780 // Note that C++0x [dcl.ref.init]p5 takes away this implementation 1781 // freedom, so we will always take the first option and never build 1782 // a temporary in this case. FIXME: We will, however, have to check 1783 // for the presence of a copy constructor in C++98/03 mode. 1784 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() && 1785 RefRelationship >= Ref_Compatible_With_Added_Qualification) { 1786 if (ICS) { 1787 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion; 1788 ICS->Standard.First = ICK_Identity; 1789 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity; 1790 ICS->Standard.Third = ICK_Identity; 1791 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr(); 1792 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr(); 1793 ICS->Standard.ReferenceBinding = true; 1794 ICS->Standard.DirectBinding = false; 1795 } else { 1796 // FIXME: Binding to a subobject of the rvalue is going to require 1797 // more AST annotation than this. 1798 ImpCastExprToType(Init, T1, /*isLvalue=*/true); 1799 } 1800 return false; 1801 } 1802 1803 // -- Otherwise, a temporary of type “cv1 T1” is created and 1804 // initialized from the initializer expression using the 1805 // rules for a non-reference copy initialization (8.5). The 1806 // reference is then bound to the temporary. If T1 is 1807 // reference-related to T2, cv1 must be the same 1808 // cv-qualification as, or greater cv-qualification than, 1809 // cv2; otherwise, the program is ill-formed. 1810 if (RefRelationship == Ref_Related) { 1811 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 1812 // we would be reference-compatible or reference-compatible with 1813 // added qualification. But that wasn't the case, so the reference 1814 // initialization fails. 1815 if (!ICS) 1816 Diag(Init->getSourceRange().getBegin(), 1817 diag::err_reference_init_drops_quals) 1818 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value") 1819 << T2 << Init->getSourceRange(); 1820 return true; 1821 } 1822 1823 // Actually try to convert the initializer to T1. 1824 if (ICS) { 1825 /// C++ [over.ics.ref]p2: 1826 /// 1827 /// When a parameter of reference type is not bound directly to 1828 /// an argument expression, the conversion sequence is the one 1829 /// required to convert the argument expression to the 1830 /// underlying type of the reference according to 1831 /// 13.3.3.1. Conceptually, this conversion sequence corresponds 1832 /// to copy-initializing a temporary of the underlying type with 1833 /// the argument expression. Any difference in top-level 1834 /// cv-qualification is subsumed by the initialization itself 1835 /// and does not constitute a conversion. 1836 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions); 1837 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion; 1838 } else { 1839 return PerformImplicitConversion(Init, T1); 1840 } 1841} 1842 1843/// CheckOverloadedOperatorDeclaration - Check whether the declaration 1844/// of this overloaded operator is well-formed. If so, returns false; 1845/// otherwise, emits appropriate diagnostics and returns true. 1846bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 1847 assert(FnDecl && FnDecl->isOverloadedOperator() && 1848 "Expected an overloaded operator declaration"); 1849 1850 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 1851 1852 // C++ [over.oper]p5: 1853 // The allocation and deallocation functions, operator new, 1854 // operator new[], operator delete and operator delete[], are 1855 // described completely in 3.7.3. The attributes and restrictions 1856 // found in the rest of this subclause do not apply to them unless 1857 // explicitly stated in 3.7.3. 1858 // FIXME: Write a separate routine for checking this. For now, just 1859 // allow it. 1860 if (Op == OO_New || Op == OO_Array_New || 1861 Op == OO_Delete || Op == OO_Array_Delete) 1862 return false; 1863 1864 // C++ [over.oper]p6: 1865 // An operator function shall either be a non-static member 1866 // function or be a non-member function and have at least one 1867 // parameter whose type is a class, a reference to a class, an 1868 // enumeration, or a reference to an enumeration. 1869 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 1870 if (MethodDecl->isStatic()) 1871 return Diag(FnDecl->getLocation(), 1872 diag::err_operator_overload_static) << FnDecl->getDeclName(); 1873 } else { 1874 bool ClassOrEnumParam = false; 1875 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 1876 ParamEnd = FnDecl->param_end(); 1877 Param != ParamEnd; ++Param) { 1878 QualType ParamType = (*Param)->getType().getNonReferenceType(); 1879 if (ParamType->isRecordType() || ParamType->isEnumeralType()) { 1880 ClassOrEnumParam = true; 1881 break; 1882 } 1883 } 1884 1885 if (!ClassOrEnumParam) 1886 return Diag(FnDecl->getLocation(), 1887 diag::err_operator_overload_needs_class_or_enum) 1888 << FnDecl->getDeclName(); 1889 } 1890 1891 // C++ [over.oper]p8: 1892 // An operator function cannot have default arguments (8.3.6), 1893 // except where explicitly stated below. 1894 // 1895 // Only the function-call operator allows default arguments 1896 // (C++ [over.call]p1). 1897 if (Op != OO_Call) { 1898 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(); 1899 Param != FnDecl->param_end(); ++Param) { 1900 if (Expr *DefArg = (*Param)->getDefaultArg()) 1901 return Diag((*Param)->getLocation(), 1902 diag::err_operator_overload_default_arg) 1903 << FnDecl->getDeclName() << DefArg->getSourceRange(); 1904 } 1905 } 1906 1907 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 1908 { false, false, false } 1909#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 1910 , { Unary, Binary, MemberOnly } 1911#include "clang/Basic/OperatorKinds.def" 1912 }; 1913 1914 bool CanBeUnaryOperator = OperatorUses[Op][0]; 1915 bool CanBeBinaryOperator = OperatorUses[Op][1]; 1916 bool MustBeMemberOperator = OperatorUses[Op][2]; 1917 1918 // C++ [over.oper]p8: 1919 // [...] Operator functions cannot have more or fewer parameters 1920 // than the number required for the corresponding operator, as 1921 // described in the rest of this subclause. 1922 unsigned NumParams = FnDecl->getNumParams() 1923 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 1924 if (Op != OO_Call && 1925 ((NumParams == 1 && !CanBeUnaryOperator) || 1926 (NumParams == 2 && !CanBeBinaryOperator) || 1927 (NumParams < 1) || (NumParams > 2))) { 1928 // We have the wrong number of parameters. 1929 unsigned ErrorKind; 1930 if (CanBeUnaryOperator && CanBeBinaryOperator) { 1931 ErrorKind = 2; // 2 -> unary or binary. 1932 } else if (CanBeUnaryOperator) { 1933 ErrorKind = 0; // 0 -> unary 1934 } else { 1935 assert(CanBeBinaryOperator && 1936 "All non-call overloaded operators are unary or binary!"); 1937 ErrorKind = 1; // 1 -> binary 1938 } 1939 1940 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 1941 << FnDecl->getDeclName() << NumParams << ErrorKind; 1942 } 1943 1944 // Overloaded operators other than operator() cannot be variadic. 1945 if (Op != OO_Call && 1946 FnDecl->getType()->getAsFunctionTypeProto()->isVariadic()) { 1947 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 1948 << FnDecl->getDeclName(); 1949 } 1950 1951 // Some operators must be non-static member functions. 1952 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 1953 return Diag(FnDecl->getLocation(), 1954 diag::err_operator_overload_must_be_member) 1955 << FnDecl->getDeclName(); 1956 } 1957 1958 // C++ [over.inc]p1: 1959 // The user-defined function called operator++ implements the 1960 // prefix and postfix ++ operator. If this function is a member 1961 // function with no parameters, or a non-member function with one 1962 // parameter of class or enumeration type, it defines the prefix 1963 // increment operator ++ for objects of that type. If the function 1964 // is a member function with one parameter (which shall be of type 1965 // int) or a non-member function with two parameters (the second 1966 // of which shall be of type int), it defines the postfix 1967 // increment operator ++ for objects of that type. 1968 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 1969 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 1970 bool ParamIsInt = false; 1971 if (const BuiltinType *BT = LastParam->getType()->getAsBuiltinType()) 1972 ParamIsInt = BT->getKind() == BuiltinType::Int; 1973 1974 if (!ParamIsInt) 1975 return Diag(LastParam->getLocation(), 1976 diag::err_operator_overload_post_incdec_must_be_int) 1977 << LastParam->getType() << (Op == OO_MinusMinus); 1978 } 1979 1980 return false; 1981} 1982