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