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