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