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