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