SemaDeclCXX.cpp revision 221345
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 "clang/Sema/SemaInternal.h" 15#include "clang/Sema/CXXFieldCollector.h" 16#include "clang/Sema/Scope.h" 17#include "clang/Sema/Initialization.h" 18#include "clang/Sema/Lookup.h" 19#include "clang/AST/ASTConsumer.h" 20#include "clang/AST/ASTContext.h" 21#include "clang/AST/ASTMutationListener.h" 22#include "clang/AST/CharUnits.h" 23#include "clang/AST/CXXInheritance.h" 24#include "clang/AST/DeclVisitor.h" 25#include "clang/AST/ExprCXX.h" 26#include "clang/AST/RecordLayout.h" 27#include "clang/AST/StmtVisitor.h" 28#include "clang/AST/TypeLoc.h" 29#include "clang/AST/TypeOrdering.h" 30#include "clang/Sema/DeclSpec.h" 31#include "clang/Sema/ParsedTemplate.h" 32#include "clang/Basic/PartialDiagnostic.h" 33#include "clang/Lex/Preprocessor.h" 34#include "llvm/ADT/DenseSet.h" 35#include "llvm/ADT/STLExtras.h" 36#include <map> 37#include <set> 38 39using namespace clang; 40 41//===----------------------------------------------------------------------===// 42// CheckDefaultArgumentVisitor 43//===----------------------------------------------------------------------===// 44 45namespace { 46 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 47 /// the default argument of a parameter to determine whether it 48 /// contains any ill-formed subexpressions. For example, this will 49 /// diagnose the use of local variables or parameters within the 50 /// default argument expression. 51 class CheckDefaultArgumentVisitor 52 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 53 Expr *DefaultArg; 54 Sema *S; 55 56 public: 57 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 58 : DefaultArg(defarg), S(s) {} 59 60 bool VisitExpr(Expr *Node); 61 bool VisitDeclRefExpr(DeclRefExpr *DRE); 62 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 63 }; 64 65 /// VisitExpr - Visit all of the children of this expression. 66 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 67 bool IsInvalid = false; 68 for (Stmt::child_range I = Node->children(); I; ++I) 69 IsInvalid |= Visit(*I); 70 return IsInvalid; 71 } 72 73 /// VisitDeclRefExpr - Visit a reference to a declaration, to 74 /// determine whether this declaration can be used in the default 75 /// argument expression. 76 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 77 NamedDecl *Decl = DRE->getDecl(); 78 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 79 // C++ [dcl.fct.default]p9 80 // Default arguments are evaluated each time the function is 81 // called. The order of evaluation of function arguments is 82 // unspecified. Consequently, parameters of a function shall not 83 // be used in default argument expressions, even if they are not 84 // evaluated. Parameters of a function declared before a default 85 // argument expression are in scope and can hide namespace and 86 // class member names. 87 return S->Diag(DRE->getSourceRange().getBegin(), 88 diag::err_param_default_argument_references_param) 89 << Param->getDeclName() << DefaultArg->getSourceRange(); 90 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 91 // C++ [dcl.fct.default]p7 92 // Local variables shall not be used in default argument 93 // expressions. 94 if (VDecl->isLocalVarDecl()) 95 return S->Diag(DRE->getSourceRange().getBegin(), 96 diag::err_param_default_argument_references_local) 97 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 98 } 99 100 return false; 101 } 102 103 /// VisitCXXThisExpr - Visit a C++ "this" expression. 104 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 105 // C++ [dcl.fct.default]p8: 106 // The keyword this shall not be used in a default argument of a 107 // member function. 108 return S->Diag(ThisE->getSourceRange().getBegin(), 109 diag::err_param_default_argument_references_this) 110 << ThisE->getSourceRange(); 111 } 112} 113 114bool 115Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 116 SourceLocation EqualLoc) { 117 if (RequireCompleteType(Param->getLocation(), Param->getType(), 118 diag::err_typecheck_decl_incomplete_type)) { 119 Param->setInvalidDecl(); 120 return true; 121 } 122 123 // C++ [dcl.fct.default]p5 124 // A default argument expression is implicitly converted (clause 125 // 4) to the parameter type. The default argument expression has 126 // the same semantic constraints as the initializer expression in 127 // a declaration of a variable of the parameter type, using the 128 // copy-initialization semantics (8.5). 129 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 130 Param); 131 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 132 EqualLoc); 133 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1); 134 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, 135 MultiExprArg(*this, &Arg, 1)); 136 if (Result.isInvalid()) 137 return true; 138 Arg = Result.takeAs<Expr>(); 139 140 CheckImplicitConversions(Arg, EqualLoc); 141 Arg = MaybeCreateExprWithCleanups(Arg); 142 143 // Okay: add the default argument to the parameter 144 Param->setDefaultArg(Arg); 145 146 // We have already instantiated this parameter; provide each of the 147 // instantiations with the uninstantiated default argument. 148 UnparsedDefaultArgInstantiationsMap::iterator InstPos 149 = UnparsedDefaultArgInstantiations.find(Param); 150 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 151 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 152 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 153 154 // We're done tracking this parameter's instantiations. 155 UnparsedDefaultArgInstantiations.erase(InstPos); 156 } 157 158 return false; 159} 160 161/// ActOnParamDefaultArgument - Check whether the default argument 162/// provided for a function parameter is well-formed. If so, attach it 163/// to the parameter declaration. 164void 165Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 166 Expr *DefaultArg) { 167 if (!param || !DefaultArg) 168 return; 169 170 ParmVarDecl *Param = cast<ParmVarDecl>(param); 171 UnparsedDefaultArgLocs.erase(Param); 172 173 // Default arguments are only permitted in C++ 174 if (!getLangOptions().CPlusPlus) { 175 Diag(EqualLoc, diag::err_param_default_argument) 176 << DefaultArg->getSourceRange(); 177 Param->setInvalidDecl(); 178 return; 179 } 180 181 // Check for unexpanded parameter packs. 182 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 183 Param->setInvalidDecl(); 184 return; 185 } 186 187 // Check that the default argument is well-formed 188 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this); 189 if (DefaultArgChecker.Visit(DefaultArg)) { 190 Param->setInvalidDecl(); 191 return; 192 } 193 194 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 195} 196 197/// ActOnParamUnparsedDefaultArgument - We've seen a default 198/// argument for a function parameter, but we can't parse it yet 199/// because we're inside a class definition. Note that this default 200/// argument will be parsed later. 201void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 202 SourceLocation EqualLoc, 203 SourceLocation ArgLoc) { 204 if (!param) 205 return; 206 207 ParmVarDecl *Param = cast<ParmVarDecl>(param); 208 if (Param) 209 Param->setUnparsedDefaultArg(); 210 211 UnparsedDefaultArgLocs[Param] = ArgLoc; 212} 213 214/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 215/// the default argument for the parameter param failed. 216void Sema::ActOnParamDefaultArgumentError(Decl *param) { 217 if (!param) 218 return; 219 220 ParmVarDecl *Param = cast<ParmVarDecl>(param); 221 222 Param->setInvalidDecl(); 223 224 UnparsedDefaultArgLocs.erase(Param); 225} 226 227/// CheckExtraCXXDefaultArguments - Check for any extra default 228/// arguments in the declarator, which is not a function declaration 229/// or definition and therefore is not permitted to have default 230/// arguments. This routine should be invoked for every declarator 231/// that is not a function declaration or definition. 232void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 233 // C++ [dcl.fct.default]p3 234 // A default argument expression shall be specified only in the 235 // parameter-declaration-clause of a function declaration or in a 236 // template-parameter (14.1). It shall not be specified for a 237 // parameter pack. If it is specified in a 238 // parameter-declaration-clause, it shall not occur within a 239 // declarator or abstract-declarator of a parameter-declaration. 240 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 241 DeclaratorChunk &chunk = D.getTypeObject(i); 242 if (chunk.Kind == DeclaratorChunk::Function) { 243 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) { 244 ParmVarDecl *Param = 245 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param); 246 if (Param->hasUnparsedDefaultArg()) { 247 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens; 248 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 249 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation()); 250 delete Toks; 251 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0; 252 } else if (Param->getDefaultArg()) { 253 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 254 << Param->getDefaultArg()->getSourceRange(); 255 Param->setDefaultArg(0); 256 } 257 } 258 } 259 } 260} 261 262// MergeCXXFunctionDecl - Merge two declarations of the same C++ 263// function, once we already know that they have the same 264// type. Subroutine of MergeFunctionDecl. Returns true if there was an 265// error, false otherwise. 266bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) { 267 bool Invalid = false; 268 269 // C++ [dcl.fct.default]p4: 270 // For non-template functions, default arguments can be added in 271 // later declarations of a function in the same 272 // scope. Declarations in different scopes have completely 273 // distinct sets of default arguments. That is, declarations in 274 // inner scopes do not acquire default arguments from 275 // declarations in outer scopes, and vice versa. In a given 276 // function declaration, all parameters subsequent to a 277 // parameter with a default argument shall have default 278 // arguments supplied in this or previous declarations. A 279 // default argument shall not be redefined by a later 280 // declaration (not even to the same value). 281 // 282 // C++ [dcl.fct.default]p6: 283 // Except for member functions of class templates, the default arguments 284 // in a member function definition that appears outside of the class 285 // definition are added to the set of default arguments provided by the 286 // member function declaration in the class definition. 287 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 288 ParmVarDecl *OldParam = Old->getParamDecl(p); 289 ParmVarDecl *NewParam = New->getParamDecl(p); 290 291 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) { 292 293 unsigned DiagDefaultParamID = 294 diag::err_param_default_argument_redefinition; 295 296 // MSVC accepts that default parameters be redefined for member functions 297 // of template class. The new default parameter's value is ignored. 298 Invalid = true; 299 if (getLangOptions().Microsoft) { 300 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New); 301 if (MD && MD->getParent()->getDescribedClassTemplate()) { 302 // Merge the old default argument into the new parameter. 303 NewParam->setHasInheritedDefaultArg(); 304 if (OldParam->hasUninstantiatedDefaultArg()) 305 NewParam->setUninstantiatedDefaultArg( 306 OldParam->getUninstantiatedDefaultArg()); 307 else 308 NewParam->setDefaultArg(OldParam->getInit()); 309 DiagDefaultParamID = diag::warn_param_default_argument_redefinition; 310 Invalid = false; 311 } 312 } 313 314 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 315 // hint here. Alternatively, we could walk the type-source information 316 // for NewParam to find the last source location in the type... but it 317 // isn't worth the effort right now. This is the kind of test case that 318 // is hard to get right: 319 // int f(int); 320 // void g(int (*fp)(int) = f); 321 // void g(int (*fp)(int) = &f); 322 Diag(NewParam->getLocation(), DiagDefaultParamID) 323 << NewParam->getDefaultArgRange(); 324 325 // Look for the function declaration where the default argument was 326 // actually written, which may be a declaration prior to Old. 327 for (FunctionDecl *Older = Old->getPreviousDeclaration(); 328 Older; Older = Older->getPreviousDeclaration()) { 329 if (!Older->getParamDecl(p)->hasDefaultArg()) 330 break; 331 332 OldParam = Older->getParamDecl(p); 333 } 334 335 Diag(OldParam->getLocation(), diag::note_previous_definition) 336 << OldParam->getDefaultArgRange(); 337 } else if (OldParam->hasDefaultArg()) { 338 // Merge the old default argument into the new parameter. 339 // It's important to use getInit() here; getDefaultArg() 340 // strips off any top-level ExprWithCleanups. 341 NewParam->setHasInheritedDefaultArg(); 342 if (OldParam->hasUninstantiatedDefaultArg()) 343 NewParam->setUninstantiatedDefaultArg( 344 OldParam->getUninstantiatedDefaultArg()); 345 else 346 NewParam->setDefaultArg(OldParam->getInit()); 347 } else if (NewParam->hasDefaultArg()) { 348 if (New->getDescribedFunctionTemplate()) { 349 // Paragraph 4, quoted above, only applies to non-template functions. 350 Diag(NewParam->getLocation(), 351 diag::err_param_default_argument_template_redecl) 352 << NewParam->getDefaultArgRange(); 353 Diag(Old->getLocation(), diag::note_template_prev_declaration) 354 << false; 355 } else if (New->getTemplateSpecializationKind() 356 != TSK_ImplicitInstantiation && 357 New->getTemplateSpecializationKind() != TSK_Undeclared) { 358 // C++ [temp.expr.spec]p21: 359 // Default function arguments shall not be specified in a declaration 360 // or a definition for one of the following explicit specializations: 361 // - the explicit specialization of a function template; 362 // - the explicit specialization of a member function template; 363 // - the explicit specialization of a member function of a class 364 // template where the class template specialization to which the 365 // member function specialization belongs is implicitly 366 // instantiated. 367 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 368 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 369 << New->getDeclName() 370 << NewParam->getDefaultArgRange(); 371 } else if (New->getDeclContext()->isDependentContext()) { 372 // C++ [dcl.fct.default]p6 (DR217): 373 // Default arguments for a member function of a class template shall 374 // be specified on the initial declaration of the member function 375 // within the class template. 376 // 377 // Reading the tea leaves a bit in DR217 and its reference to DR205 378 // leads me to the conclusion that one cannot add default function 379 // arguments for an out-of-line definition of a member function of a 380 // dependent type. 381 int WhichKind = 2; 382 if (CXXRecordDecl *Record 383 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 384 if (Record->getDescribedClassTemplate()) 385 WhichKind = 0; 386 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 387 WhichKind = 1; 388 else 389 WhichKind = 2; 390 } 391 392 Diag(NewParam->getLocation(), 393 diag::err_param_default_argument_member_template_redecl) 394 << WhichKind 395 << NewParam->getDefaultArgRange(); 396 } 397 } 398 } 399 400 if (CheckEquivalentExceptionSpec(Old, New)) 401 Invalid = true; 402 403 return Invalid; 404} 405 406/// \brief Merge the exception specifications of two variable declarations. 407/// 408/// This is called when there's a redeclaration of a VarDecl. The function 409/// checks if the redeclaration might have an exception specification and 410/// validates compatibility and merges the specs if necessary. 411void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 412 // Shortcut if exceptions are disabled. 413 if (!getLangOptions().CXXExceptions) 414 return; 415 416 assert(Context.hasSameType(New->getType(), Old->getType()) && 417 "Should only be called if types are otherwise the same."); 418 419 QualType NewType = New->getType(); 420 QualType OldType = Old->getType(); 421 422 // We're only interested in pointers and references to functions, as well 423 // as pointers to member functions. 424 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 425 NewType = R->getPointeeType(); 426 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 427 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 428 NewType = P->getPointeeType(); 429 OldType = OldType->getAs<PointerType>()->getPointeeType(); 430 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 431 NewType = M->getPointeeType(); 432 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 433 } 434 435 if (!NewType->isFunctionProtoType()) 436 return; 437 438 // There's lots of special cases for functions. For function pointers, system 439 // libraries are hopefully not as broken so that we don't need these 440 // workarounds. 441 if (CheckEquivalentExceptionSpec( 442 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 443 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 444 New->setInvalidDecl(); 445 } 446} 447 448/// CheckCXXDefaultArguments - Verify that the default arguments for a 449/// function declaration are well-formed according to C++ 450/// [dcl.fct.default]. 451void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 452 unsigned NumParams = FD->getNumParams(); 453 unsigned p; 454 455 // Find first parameter with a default argument 456 for (p = 0; p < NumParams; ++p) { 457 ParmVarDecl *Param = FD->getParamDecl(p); 458 if (Param->hasDefaultArg()) 459 break; 460 } 461 462 // C++ [dcl.fct.default]p4: 463 // In a given function declaration, all parameters 464 // subsequent to a parameter with a default argument shall 465 // have default arguments supplied in this or previous 466 // declarations. A default argument shall not be redefined 467 // by a later declaration (not even to the same value). 468 unsigned LastMissingDefaultArg = 0; 469 for (; p < NumParams; ++p) { 470 ParmVarDecl *Param = FD->getParamDecl(p); 471 if (!Param->hasDefaultArg()) { 472 if (Param->isInvalidDecl()) 473 /* We already complained about this parameter. */; 474 else if (Param->getIdentifier()) 475 Diag(Param->getLocation(), 476 diag::err_param_default_argument_missing_name) 477 << Param->getIdentifier(); 478 else 479 Diag(Param->getLocation(), 480 diag::err_param_default_argument_missing); 481 482 LastMissingDefaultArg = p; 483 } 484 } 485 486 if (LastMissingDefaultArg > 0) { 487 // Some default arguments were missing. Clear out all of the 488 // default arguments up to (and including) the last missing 489 // default argument, so that we leave the function parameters 490 // in a semantically valid state. 491 for (p = 0; p <= LastMissingDefaultArg; ++p) { 492 ParmVarDecl *Param = FD->getParamDecl(p); 493 if (Param->hasDefaultArg()) { 494 Param->setDefaultArg(0); 495 } 496 } 497 } 498} 499 500/// isCurrentClassName - Determine whether the identifier II is the 501/// name of the class type currently being defined. In the case of 502/// nested classes, this will only return true if II is the name of 503/// the innermost class. 504bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 505 const CXXScopeSpec *SS) { 506 assert(getLangOptions().CPlusPlus && "No class names in C!"); 507 508 CXXRecordDecl *CurDecl; 509 if (SS && SS->isSet() && !SS->isInvalid()) { 510 DeclContext *DC = computeDeclContext(*SS, true); 511 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 512 } else 513 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 514 515 if (CurDecl && CurDecl->getIdentifier()) 516 return &II == CurDecl->getIdentifier(); 517 else 518 return false; 519} 520 521/// \brief Check the validity of a C++ base class specifier. 522/// 523/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 524/// and returns NULL otherwise. 525CXXBaseSpecifier * 526Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 527 SourceRange SpecifierRange, 528 bool Virtual, AccessSpecifier Access, 529 TypeSourceInfo *TInfo, 530 SourceLocation EllipsisLoc) { 531 QualType BaseType = TInfo->getType(); 532 533 // C++ [class.union]p1: 534 // A union shall not have base classes. 535 if (Class->isUnion()) { 536 Diag(Class->getLocation(), diag::err_base_clause_on_union) 537 << SpecifierRange; 538 return 0; 539 } 540 541 if (EllipsisLoc.isValid() && 542 !TInfo->getType()->containsUnexpandedParameterPack()) { 543 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 544 << TInfo->getTypeLoc().getSourceRange(); 545 EllipsisLoc = SourceLocation(); 546 } 547 548 if (BaseType->isDependentType()) 549 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 550 Class->getTagKind() == TTK_Class, 551 Access, TInfo, EllipsisLoc); 552 553 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 554 555 // Base specifiers must be record types. 556 if (!BaseType->isRecordType()) { 557 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 558 return 0; 559 } 560 561 // C++ [class.union]p1: 562 // A union shall not be used as a base class. 563 if (BaseType->isUnionType()) { 564 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 565 return 0; 566 } 567 568 // C++ [class.derived]p2: 569 // The class-name in a base-specifier shall not be an incompletely 570 // defined class. 571 if (RequireCompleteType(BaseLoc, BaseType, 572 PDiag(diag::err_incomplete_base_class) 573 << SpecifierRange)) { 574 Class->setInvalidDecl(); 575 return 0; 576 } 577 578 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 579 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 580 assert(BaseDecl && "Record type has no declaration"); 581 BaseDecl = BaseDecl->getDefinition(); 582 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 583 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 584 assert(CXXBaseDecl && "Base type is not a C++ type"); 585 586 // C++ [class]p3: 587 // If a class is marked final and it appears as a base-type-specifier in 588 // base-clause, the program is ill-formed. 589 if (CXXBaseDecl->hasAttr<FinalAttr>()) { 590 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 591 << CXXBaseDecl->getDeclName(); 592 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl) 593 << CXXBaseDecl->getDeclName(); 594 return 0; 595 } 596 597 if (BaseDecl->isInvalidDecl()) 598 Class->setInvalidDecl(); 599 600 // Create the base specifier. 601 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 602 Class->getTagKind() == TTK_Class, 603 Access, TInfo, EllipsisLoc); 604} 605 606/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 607/// one entry in the base class list of a class specifier, for 608/// example: 609/// class foo : public bar, virtual private baz { 610/// 'public bar' and 'virtual private baz' are each base-specifiers. 611BaseResult 612Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 613 bool Virtual, AccessSpecifier Access, 614 ParsedType basetype, SourceLocation BaseLoc, 615 SourceLocation EllipsisLoc) { 616 if (!classdecl) 617 return true; 618 619 AdjustDeclIfTemplate(classdecl); 620 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 621 if (!Class) 622 return true; 623 624 TypeSourceInfo *TInfo = 0; 625 GetTypeFromParser(basetype, &TInfo); 626 627 if (EllipsisLoc.isInvalid() && 628 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 629 UPPC_BaseType)) 630 return true; 631 632 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 633 Virtual, Access, TInfo, 634 EllipsisLoc)) 635 return BaseSpec; 636 637 return true; 638} 639 640/// \brief Performs the actual work of attaching the given base class 641/// specifiers to a C++ class. 642bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 643 unsigned NumBases) { 644 if (NumBases == 0) 645 return false; 646 647 // Used to keep track of which base types we have already seen, so 648 // that we can properly diagnose redundant direct base types. Note 649 // that the key is always the unqualified canonical type of the base 650 // class. 651 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 652 653 // Copy non-redundant base specifiers into permanent storage. 654 unsigned NumGoodBases = 0; 655 bool Invalid = false; 656 for (unsigned idx = 0; idx < NumBases; ++idx) { 657 QualType NewBaseType 658 = Context.getCanonicalType(Bases[idx]->getType()); 659 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 660 if (!Class->hasObjectMember()) { 661 if (const RecordType *FDTTy = 662 NewBaseType.getTypePtr()->getAs<RecordType>()) 663 if (FDTTy->getDecl()->hasObjectMember()) 664 Class->setHasObjectMember(true); 665 } 666 667 if (KnownBaseTypes[NewBaseType]) { 668 // C++ [class.mi]p3: 669 // A class shall not be specified as a direct base class of a 670 // derived class more than once. 671 Diag(Bases[idx]->getSourceRange().getBegin(), 672 diag::err_duplicate_base_class) 673 << KnownBaseTypes[NewBaseType]->getType() 674 << Bases[idx]->getSourceRange(); 675 676 // Delete the duplicate base class specifier; we're going to 677 // overwrite its pointer later. 678 Context.Deallocate(Bases[idx]); 679 680 Invalid = true; 681 } else { 682 // Okay, add this new base class. 683 KnownBaseTypes[NewBaseType] = Bases[idx]; 684 Bases[NumGoodBases++] = Bases[idx]; 685 } 686 } 687 688 // Attach the remaining base class specifiers to the derived class. 689 Class->setBases(Bases, NumGoodBases); 690 691 // Delete the remaining (good) base class specifiers, since their 692 // data has been copied into the CXXRecordDecl. 693 for (unsigned idx = 0; idx < NumGoodBases; ++idx) 694 Context.Deallocate(Bases[idx]); 695 696 return Invalid; 697} 698 699/// ActOnBaseSpecifiers - Attach the given base specifiers to the 700/// class, after checking whether there are any duplicate base 701/// classes. 702void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases, 703 unsigned NumBases) { 704 if (!ClassDecl || !Bases || !NumBases) 705 return; 706 707 AdjustDeclIfTemplate(ClassDecl); 708 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), 709 (CXXBaseSpecifier**)(Bases), NumBases); 710} 711 712static CXXRecordDecl *GetClassForType(QualType T) { 713 if (const RecordType *RT = T->getAs<RecordType>()) 714 return cast<CXXRecordDecl>(RT->getDecl()); 715 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>()) 716 return ICT->getDecl(); 717 else 718 return 0; 719} 720 721/// \brief Determine whether the type \p Derived is a C++ class that is 722/// derived from the type \p Base. 723bool Sema::IsDerivedFrom(QualType Derived, QualType Base) { 724 if (!getLangOptions().CPlusPlus) 725 return false; 726 727 CXXRecordDecl *DerivedRD = GetClassForType(Derived); 728 if (!DerivedRD) 729 return false; 730 731 CXXRecordDecl *BaseRD = GetClassForType(Base); 732 if (!BaseRD) 733 return false; 734 735 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this. 736 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD); 737} 738 739/// \brief Determine whether the type \p Derived is a C++ class that is 740/// derived from the type \p Base. 741bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) { 742 if (!getLangOptions().CPlusPlus) 743 return false; 744 745 CXXRecordDecl *DerivedRD = GetClassForType(Derived); 746 if (!DerivedRD) 747 return false; 748 749 CXXRecordDecl *BaseRD = GetClassForType(Base); 750 if (!BaseRD) 751 return false; 752 753 return DerivedRD->isDerivedFrom(BaseRD, Paths); 754} 755 756void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 757 CXXCastPath &BasePathArray) { 758 assert(BasePathArray.empty() && "Base path array must be empty!"); 759 assert(Paths.isRecordingPaths() && "Must record paths!"); 760 761 const CXXBasePath &Path = Paths.front(); 762 763 // We first go backward and check if we have a virtual base. 764 // FIXME: It would be better if CXXBasePath had the base specifier for 765 // the nearest virtual base. 766 unsigned Start = 0; 767 for (unsigned I = Path.size(); I != 0; --I) { 768 if (Path[I - 1].Base->isVirtual()) { 769 Start = I - 1; 770 break; 771 } 772 } 773 774 // Now add all bases. 775 for (unsigned I = Start, E = Path.size(); I != E; ++I) 776 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 777} 778 779/// \brief Determine whether the given base path includes a virtual 780/// base class. 781bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) { 782 for (CXXCastPath::const_iterator B = BasePath.begin(), 783 BEnd = BasePath.end(); 784 B != BEnd; ++B) 785 if ((*B)->isVirtual()) 786 return true; 787 788 return false; 789} 790 791/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 792/// conversion (where Derived and Base are class types) is 793/// well-formed, meaning that the conversion is unambiguous (and 794/// that all of the base classes are accessible). Returns true 795/// and emits a diagnostic if the code is ill-formed, returns false 796/// otherwise. Loc is the location where this routine should point to 797/// if there is an error, and Range is the source range to highlight 798/// if there is an error. 799bool 800Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 801 unsigned InaccessibleBaseID, 802 unsigned AmbigiousBaseConvID, 803 SourceLocation Loc, SourceRange Range, 804 DeclarationName Name, 805 CXXCastPath *BasePath) { 806 // First, determine whether the path from Derived to Base is 807 // ambiguous. This is slightly more expensive than checking whether 808 // the Derived to Base conversion exists, because here we need to 809 // explore multiple paths to determine if there is an ambiguity. 810 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 811 /*DetectVirtual=*/false); 812 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths); 813 assert(DerivationOkay && 814 "Can only be used with a derived-to-base conversion"); 815 (void)DerivationOkay; 816 817 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 818 if (InaccessibleBaseID) { 819 // Check that the base class can be accessed. 820 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(), 821 InaccessibleBaseID)) { 822 case AR_inaccessible: 823 return true; 824 case AR_accessible: 825 case AR_dependent: 826 case AR_delayed: 827 break; 828 } 829 } 830 831 // Build a base path if necessary. 832 if (BasePath) 833 BuildBasePathArray(Paths, *BasePath); 834 return false; 835 } 836 837 // We know that the derived-to-base conversion is ambiguous, and 838 // we're going to produce a diagnostic. Perform the derived-to-base 839 // search just one more time to compute all of the possible paths so 840 // that we can print them out. This is more expensive than any of 841 // the previous derived-to-base checks we've done, but at this point 842 // performance isn't as much of an issue. 843 Paths.clear(); 844 Paths.setRecordingPaths(true); 845 bool StillOkay = IsDerivedFrom(Derived, Base, Paths); 846 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 847 (void)StillOkay; 848 849 // Build up a textual representation of the ambiguous paths, e.g., 850 // D -> B -> A, that will be used to illustrate the ambiguous 851 // conversions in the diagnostic. We only print one of the paths 852 // to each base class subobject. 853 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 854 855 Diag(Loc, AmbigiousBaseConvID) 856 << Derived << Base << PathDisplayStr << Range << Name; 857 return true; 858} 859 860bool 861Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 862 SourceLocation Loc, SourceRange Range, 863 CXXCastPath *BasePath, 864 bool IgnoreAccess) { 865 return CheckDerivedToBaseConversion(Derived, Base, 866 IgnoreAccess ? 0 867 : diag::err_upcast_to_inaccessible_base, 868 diag::err_ambiguous_derived_to_base_conv, 869 Loc, Range, DeclarationName(), 870 BasePath); 871} 872 873 874/// @brief Builds a string representing ambiguous paths from a 875/// specific derived class to different subobjects of the same base 876/// class. 877/// 878/// This function builds a string that can be used in error messages 879/// to show the different paths that one can take through the 880/// inheritance hierarchy to go from the derived class to different 881/// subobjects of a base class. The result looks something like this: 882/// @code 883/// struct D -> struct B -> struct A 884/// struct D -> struct C -> struct A 885/// @endcode 886std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 887 std::string PathDisplayStr; 888 std::set<unsigned> DisplayedPaths; 889 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 890 Path != Paths.end(); ++Path) { 891 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 892 // We haven't displayed a path to this particular base 893 // class subobject yet. 894 PathDisplayStr += "\n "; 895 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 896 for (CXXBasePath::const_iterator Element = Path->begin(); 897 Element != Path->end(); ++Element) 898 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 899 } 900 } 901 902 return PathDisplayStr; 903} 904 905//===----------------------------------------------------------------------===// 906// C++ class member Handling 907//===----------------------------------------------------------------------===// 908 909/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 910Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access, 911 SourceLocation ASLoc, 912 SourceLocation ColonLoc) { 913 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 914 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 915 ASLoc, ColonLoc); 916 CurContext->addHiddenDecl(ASDecl); 917 return ASDecl; 918} 919 920/// CheckOverrideControl - Check C++0x override control semantics. 921void Sema::CheckOverrideControl(const Decl *D) { 922 const CXXMethodDecl *MD = llvm::dyn_cast<CXXMethodDecl>(D); 923 if (!MD || !MD->isVirtual()) 924 return; 925 926 if (MD->isDependentContext()) 927 return; 928 929 // C++0x [class.virtual]p3: 930 // If a virtual function is marked with the virt-specifier override and does 931 // not override a member function of a base class, 932 // the program is ill-formed. 933 bool HasOverriddenMethods = 934 MD->begin_overridden_methods() != MD->end_overridden_methods(); 935 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) { 936 Diag(MD->getLocation(), 937 diag::err_function_marked_override_not_overriding) 938 << MD->getDeclName(); 939 return; 940 } 941} 942 943/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 944/// function overrides a virtual member function marked 'final', according to 945/// C++0x [class.virtual]p3. 946bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 947 const CXXMethodDecl *Old) { 948 if (!Old->hasAttr<FinalAttr>()) 949 return false; 950 951 Diag(New->getLocation(), diag::err_final_function_overridden) 952 << New->getDeclName(); 953 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 954 return true; 955} 956 957/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 958/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 959/// bitfield width if there is one and 'InitExpr' specifies the initializer if 960/// any. 961Decl * 962Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 963 MultiTemplateParamsArg TemplateParameterLists, 964 ExprTy *BW, const VirtSpecifiers &VS, 965 ExprTy *InitExpr, bool IsDefinition, 966 bool Deleted) { 967 const DeclSpec &DS = D.getDeclSpec(); 968 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 969 DeclarationName Name = NameInfo.getName(); 970 SourceLocation Loc = NameInfo.getLoc(); 971 972 // For anonymous bitfields, the location should point to the type. 973 if (Loc.isInvalid()) 974 Loc = D.getSourceRange().getBegin(); 975 976 Expr *BitWidth = static_cast<Expr*>(BW); 977 Expr *Init = static_cast<Expr*>(InitExpr); 978 979 assert(isa<CXXRecordDecl>(CurContext)); 980 assert(!DS.isFriendSpecified()); 981 982 bool isFunc = false; 983 if (D.isFunctionDeclarator()) 984 isFunc = true; 985 else if (D.getNumTypeObjects() == 0 && 986 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) { 987 QualType TDType = GetTypeFromParser(DS.getRepAsType()); 988 isFunc = TDType->isFunctionType(); 989 } 990 991 // C++ 9.2p6: A member shall not be declared to have automatic storage 992 // duration (auto, register) or with the extern storage-class-specifier. 993 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 994 // data members and cannot be applied to names declared const or static, 995 // and cannot be applied to reference members. 996 switch (DS.getStorageClassSpec()) { 997 case DeclSpec::SCS_unspecified: 998 case DeclSpec::SCS_typedef: 999 case DeclSpec::SCS_static: 1000 // FALL THROUGH. 1001 break; 1002 case DeclSpec::SCS_mutable: 1003 if (isFunc) { 1004 if (DS.getStorageClassSpecLoc().isValid()) 1005 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 1006 else 1007 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function); 1008 1009 // FIXME: It would be nicer if the keyword was ignored only for this 1010 // declarator. Otherwise we could get follow-up errors. 1011 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1012 } 1013 break; 1014 default: 1015 if (DS.getStorageClassSpecLoc().isValid()) 1016 Diag(DS.getStorageClassSpecLoc(), 1017 diag::err_storageclass_invalid_for_member); 1018 else 1019 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member); 1020 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1021 } 1022 1023 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 1024 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 1025 !isFunc); 1026 1027 Decl *Member; 1028 if (isInstField) { 1029 CXXScopeSpec &SS = D.getCXXScopeSpec(); 1030 1031 1032 if (SS.isSet() && !SS.isInvalid()) { 1033 // The user provided a superfluous scope specifier inside a class 1034 // definition: 1035 // 1036 // class X { 1037 // int X::member; 1038 // }; 1039 DeclContext *DC = 0; 1040 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext)) 1041 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification) 1042 << Name << FixItHint::CreateRemoval(SS.getRange()); 1043 else 1044 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 1045 << Name << SS.getRange(); 1046 1047 SS.clear(); 1048 } 1049 1050 // FIXME: Check for template parameters! 1051 // FIXME: Check that the name is an identifier! 1052 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth, 1053 AS); 1054 assert(Member && "HandleField never returns null"); 1055 } else { 1056 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition); 1057 if (!Member) { 1058 return 0; 1059 } 1060 1061 // Non-instance-fields can't have a bitfield. 1062 if (BitWidth) { 1063 if (Member->isInvalidDecl()) { 1064 // don't emit another diagnostic. 1065 } else if (isa<VarDecl>(Member)) { 1066 // C++ 9.6p3: A bit-field shall not be a static member. 1067 // "static member 'A' cannot be a bit-field" 1068 Diag(Loc, diag::err_static_not_bitfield) 1069 << Name << BitWidth->getSourceRange(); 1070 } else if (isa<TypedefDecl>(Member)) { 1071 // "typedef member 'x' cannot be a bit-field" 1072 Diag(Loc, diag::err_typedef_not_bitfield) 1073 << Name << BitWidth->getSourceRange(); 1074 } else { 1075 // A function typedef ("typedef int f(); f a;"). 1076 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 1077 Diag(Loc, diag::err_not_integral_type_bitfield) 1078 << Name << cast<ValueDecl>(Member)->getType() 1079 << BitWidth->getSourceRange(); 1080 } 1081 1082 BitWidth = 0; 1083 Member->setInvalidDecl(); 1084 } 1085 1086 Member->setAccess(AS); 1087 1088 // If we have declared a member function template, set the access of the 1089 // templated declaration as well. 1090 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 1091 FunTmpl->getTemplatedDecl()->setAccess(AS); 1092 } 1093 1094 if (VS.isOverrideSpecified()) { 1095 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 1096 if (!MD || !MD->isVirtual()) { 1097 Diag(Member->getLocStart(), 1098 diag::override_keyword_only_allowed_on_virtual_member_functions) 1099 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc()); 1100 } else 1101 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context)); 1102 } 1103 if (VS.isFinalSpecified()) { 1104 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 1105 if (!MD || !MD->isVirtual()) { 1106 Diag(Member->getLocStart(), 1107 diag::override_keyword_only_allowed_on_virtual_member_functions) 1108 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc()); 1109 } else 1110 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context)); 1111 } 1112 1113 if (VS.getLastLocation().isValid()) { 1114 // Update the end location of a method that has a virt-specifiers. 1115 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 1116 MD->setRangeEnd(VS.getLastLocation()); 1117 } 1118 1119 CheckOverrideControl(Member); 1120 1121 assert((Name || isInstField) && "No identifier for non-field ?"); 1122 1123 if (Init) 1124 AddInitializerToDecl(Member, Init, false, 1125 DS.getTypeSpecType() == DeclSpec::TST_auto); 1126 if (Deleted) // FIXME: Source location is not very good. 1127 SetDeclDeleted(Member, D.getSourceRange().getBegin()); 1128 1129 FinalizeDeclaration(Member); 1130 1131 if (isInstField) 1132 FieldCollector->Add(cast<FieldDecl>(Member)); 1133 return Member; 1134} 1135 1136/// \brief Find the direct and/or virtual base specifiers that 1137/// correspond to the given base type, for use in base initialization 1138/// within a constructor. 1139static bool FindBaseInitializer(Sema &SemaRef, 1140 CXXRecordDecl *ClassDecl, 1141 QualType BaseType, 1142 const CXXBaseSpecifier *&DirectBaseSpec, 1143 const CXXBaseSpecifier *&VirtualBaseSpec) { 1144 // First, check for a direct base class. 1145 DirectBaseSpec = 0; 1146 for (CXXRecordDecl::base_class_const_iterator Base 1147 = ClassDecl->bases_begin(); 1148 Base != ClassDecl->bases_end(); ++Base) { 1149 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) { 1150 // We found a direct base of this type. That's what we're 1151 // initializing. 1152 DirectBaseSpec = &*Base; 1153 break; 1154 } 1155 } 1156 1157 // Check for a virtual base class. 1158 // FIXME: We might be able to short-circuit this if we know in advance that 1159 // there are no virtual bases. 1160 VirtualBaseSpec = 0; 1161 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 1162 // We haven't found a base yet; search the class hierarchy for a 1163 // virtual base class. 1164 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1165 /*DetectVirtual=*/false); 1166 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl), 1167 BaseType, Paths)) { 1168 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 1169 Path != Paths.end(); ++Path) { 1170 if (Path->back().Base->isVirtual()) { 1171 VirtualBaseSpec = Path->back().Base; 1172 break; 1173 } 1174 } 1175 } 1176 } 1177 1178 return DirectBaseSpec || VirtualBaseSpec; 1179} 1180 1181/// ActOnMemInitializer - Handle a C++ member initializer. 1182MemInitResult 1183Sema::ActOnMemInitializer(Decl *ConstructorD, 1184 Scope *S, 1185 CXXScopeSpec &SS, 1186 IdentifierInfo *MemberOrBase, 1187 ParsedType TemplateTypeTy, 1188 SourceLocation IdLoc, 1189 SourceLocation LParenLoc, 1190 ExprTy **Args, unsigned NumArgs, 1191 SourceLocation RParenLoc, 1192 SourceLocation EllipsisLoc) { 1193 if (!ConstructorD) 1194 return true; 1195 1196 AdjustDeclIfTemplate(ConstructorD); 1197 1198 CXXConstructorDecl *Constructor 1199 = dyn_cast<CXXConstructorDecl>(ConstructorD); 1200 if (!Constructor) { 1201 // The user wrote a constructor initializer on a function that is 1202 // not a C++ constructor. Ignore the error for now, because we may 1203 // have more member initializers coming; we'll diagnose it just 1204 // once in ActOnMemInitializers. 1205 return true; 1206 } 1207 1208 CXXRecordDecl *ClassDecl = Constructor->getParent(); 1209 1210 // C++ [class.base.init]p2: 1211 // Names in a mem-initializer-id are looked up in the scope of the 1212 // constructor's class and, if not found in that scope, are looked 1213 // up in the scope containing the constructor's definition. 1214 // [Note: if the constructor's class contains a member with the 1215 // same name as a direct or virtual base class of the class, a 1216 // mem-initializer-id naming the member or base class and composed 1217 // of a single identifier refers to the class member. A 1218 // mem-initializer-id for the hidden base class may be specified 1219 // using a qualified name. ] 1220 if (!SS.getScopeRep() && !TemplateTypeTy) { 1221 // Look for a member, first. 1222 FieldDecl *Member = 0; 1223 DeclContext::lookup_result Result 1224 = ClassDecl->lookup(MemberOrBase); 1225 if (Result.first != Result.second) { 1226 Member = dyn_cast<FieldDecl>(*Result.first); 1227 1228 if (Member) { 1229 if (EllipsisLoc.isValid()) 1230 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 1231 << MemberOrBase << SourceRange(IdLoc, RParenLoc); 1232 1233 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc, 1234 LParenLoc, RParenLoc); 1235 } 1236 1237 // Handle anonymous union case. 1238 if (IndirectFieldDecl* IndirectField 1239 = dyn_cast<IndirectFieldDecl>(*Result.first)) { 1240 if (EllipsisLoc.isValid()) 1241 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 1242 << MemberOrBase << SourceRange(IdLoc, RParenLoc); 1243 1244 return BuildMemberInitializer(IndirectField, (Expr**)Args, 1245 NumArgs, IdLoc, 1246 LParenLoc, RParenLoc); 1247 } 1248 } 1249 } 1250 // It didn't name a member, so see if it names a class. 1251 QualType BaseType; 1252 TypeSourceInfo *TInfo = 0; 1253 1254 if (TemplateTypeTy) { 1255 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 1256 } else { 1257 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 1258 LookupParsedName(R, S, &SS); 1259 1260 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 1261 if (!TyD) { 1262 if (R.isAmbiguous()) return true; 1263 1264 // We don't want access-control diagnostics here. 1265 R.suppressDiagnostics(); 1266 1267 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 1268 bool NotUnknownSpecialization = false; 1269 DeclContext *DC = computeDeclContext(SS, false); 1270 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 1271 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 1272 1273 if (!NotUnknownSpecialization) { 1274 // When the scope specifier can refer to a member of an unknown 1275 // specialization, we take it as a type name. 1276 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 1277 SS.getWithLocInContext(Context), 1278 *MemberOrBase, IdLoc); 1279 if (BaseType.isNull()) 1280 return true; 1281 1282 R.clear(); 1283 R.setLookupName(MemberOrBase); 1284 } 1285 } 1286 1287 // If no results were found, try to correct typos. 1288 if (R.empty() && BaseType.isNull() && 1289 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) && 1290 R.isSingleResult()) { 1291 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) { 1292 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) { 1293 // We have found a non-static data member with a similar 1294 // name to what was typed; complain and initialize that 1295 // member. 1296 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest) 1297 << MemberOrBase << true << R.getLookupName() 1298 << FixItHint::CreateReplacement(R.getNameLoc(), 1299 R.getLookupName().getAsString()); 1300 Diag(Member->getLocation(), diag::note_previous_decl) 1301 << Member->getDeclName(); 1302 1303 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc, 1304 LParenLoc, RParenLoc); 1305 } 1306 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) { 1307 const CXXBaseSpecifier *DirectBaseSpec; 1308 const CXXBaseSpecifier *VirtualBaseSpec; 1309 if (FindBaseInitializer(*this, ClassDecl, 1310 Context.getTypeDeclType(Type), 1311 DirectBaseSpec, VirtualBaseSpec)) { 1312 // We have found a direct or virtual base class with a 1313 // similar name to what was typed; complain and initialize 1314 // that base class. 1315 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest) 1316 << MemberOrBase << false << R.getLookupName() 1317 << FixItHint::CreateReplacement(R.getNameLoc(), 1318 R.getLookupName().getAsString()); 1319 1320 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec 1321 : VirtualBaseSpec; 1322 Diag(BaseSpec->getSourceRange().getBegin(), 1323 diag::note_base_class_specified_here) 1324 << BaseSpec->getType() 1325 << BaseSpec->getSourceRange(); 1326 1327 TyD = Type; 1328 } 1329 } 1330 } 1331 1332 if (!TyD && BaseType.isNull()) { 1333 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 1334 << MemberOrBase << SourceRange(IdLoc, RParenLoc); 1335 return true; 1336 } 1337 } 1338 1339 if (BaseType.isNull()) { 1340 BaseType = Context.getTypeDeclType(TyD); 1341 if (SS.isSet()) { 1342 NestedNameSpecifier *Qualifier = 1343 static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 1344 1345 // FIXME: preserve source range information 1346 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType); 1347 } 1348 } 1349 } 1350 1351 if (!TInfo) 1352 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 1353 1354 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs, 1355 LParenLoc, RParenLoc, ClassDecl, EllipsisLoc); 1356} 1357 1358/// Checks an initializer expression for use of uninitialized fields, such as 1359/// containing the field that is being initialized. Returns true if there is an 1360/// uninitialized field was used an updates the SourceLocation parameter; false 1361/// otherwise. 1362static bool InitExprContainsUninitializedFields(const Stmt *S, 1363 const ValueDecl *LhsField, 1364 SourceLocation *L) { 1365 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField)); 1366 1367 if (isa<CallExpr>(S)) { 1368 // Do not descend into function calls or constructors, as the use 1369 // of an uninitialized field may be valid. One would have to inspect 1370 // the contents of the function/ctor to determine if it is safe or not. 1371 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers 1372 // may be safe, depending on what the function/ctor does. 1373 return false; 1374 } 1375 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) { 1376 const NamedDecl *RhsField = ME->getMemberDecl(); 1377 1378 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) { 1379 // The member expression points to a static data member. 1380 assert(VD->isStaticDataMember() && 1381 "Member points to non-static data member!"); 1382 (void)VD; 1383 return false; 1384 } 1385 1386 if (isa<EnumConstantDecl>(RhsField)) { 1387 // The member expression points to an enum. 1388 return false; 1389 } 1390 1391 if (RhsField == LhsField) { 1392 // Initializing a field with itself. Throw a warning. 1393 // But wait; there are exceptions! 1394 // Exception #1: The field may not belong to this record. 1395 // e.g. Foo(const Foo& rhs) : A(rhs.A) {} 1396 const Expr *base = ME->getBase(); 1397 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) { 1398 // Even though the field matches, it does not belong to this record. 1399 return false; 1400 } 1401 // None of the exceptions triggered; return true to indicate an 1402 // uninitialized field was used. 1403 *L = ME->getMemberLoc(); 1404 return true; 1405 } 1406 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) { 1407 // sizeof/alignof doesn't reference contents, do not warn. 1408 return false; 1409 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) { 1410 // address-of doesn't reference contents (the pointer may be dereferenced 1411 // in the same expression but it would be rare; and weird). 1412 if (UOE->getOpcode() == UO_AddrOf) 1413 return false; 1414 } 1415 for (Stmt::const_child_range it = S->children(); it; ++it) { 1416 if (!*it) { 1417 // An expression such as 'member(arg ?: "")' may trigger this. 1418 continue; 1419 } 1420 if (InitExprContainsUninitializedFields(*it, LhsField, L)) 1421 return true; 1422 } 1423 return false; 1424} 1425 1426MemInitResult 1427Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args, 1428 unsigned NumArgs, SourceLocation IdLoc, 1429 SourceLocation LParenLoc, 1430 SourceLocation RParenLoc) { 1431 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 1432 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 1433 assert((DirectMember || IndirectMember) && 1434 "Member must be a FieldDecl or IndirectFieldDecl"); 1435 1436 if (Member->isInvalidDecl()) 1437 return true; 1438 1439 // Diagnose value-uses of fields to initialize themselves, e.g. 1440 // foo(foo) 1441 // where foo is not also a parameter to the constructor. 1442 // TODO: implement -Wuninitialized and fold this into that framework. 1443 for (unsigned i = 0; i < NumArgs; ++i) { 1444 SourceLocation L; 1445 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) { 1446 // FIXME: Return true in the case when other fields are used before being 1447 // uninitialized. For example, let this field be the i'th field. When 1448 // initializing the i'th field, throw a warning if any of the >= i'th 1449 // fields are used, as they are not yet initialized. 1450 // Right now we are only handling the case where the i'th field uses 1451 // itself in its initializer. 1452 Diag(L, diag::warn_field_is_uninit); 1453 } 1454 } 1455 1456 bool HasDependentArg = false; 1457 for (unsigned i = 0; i < NumArgs; i++) 1458 HasDependentArg |= Args[i]->isTypeDependent(); 1459 1460 Expr *Init; 1461 if (Member->getType()->isDependentType() || HasDependentArg) { 1462 // Can't check initialization for a member of dependent type or when 1463 // any of the arguments are type-dependent expressions. 1464 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs, 1465 RParenLoc); 1466 1467 // Erase any temporaries within this evaluation context; we're not 1468 // going to track them in the AST, since we'll be rebuilding the 1469 // ASTs during template instantiation. 1470 ExprTemporaries.erase( 1471 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries, 1472 ExprTemporaries.end()); 1473 } else { 1474 // Initialize the member. 1475 InitializedEntity MemberEntity = 1476 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0) 1477 : InitializedEntity::InitializeMember(IndirectMember, 0); 1478 InitializationKind Kind = 1479 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc); 1480 1481 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs); 1482 1483 ExprResult MemberInit = 1484 InitSeq.Perform(*this, MemberEntity, Kind, 1485 MultiExprArg(*this, Args, NumArgs), 0); 1486 if (MemberInit.isInvalid()) 1487 return true; 1488 1489 CheckImplicitConversions(MemberInit.get(), LParenLoc); 1490 1491 // C++0x [class.base.init]p7: 1492 // The initialization of each base and member constitutes a 1493 // full-expression. 1494 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 1495 if (MemberInit.isInvalid()) 1496 return true; 1497 1498 // If we are in a dependent context, template instantiation will 1499 // perform this type-checking again. Just save the arguments that we 1500 // received in a ParenListExpr. 1501 // FIXME: This isn't quite ideal, since our ASTs don't capture all 1502 // of the information that we have about the member 1503 // initializer. However, deconstructing the ASTs is a dicey process, 1504 // and this approach is far more likely to get the corner cases right. 1505 if (CurContext->isDependentContext()) 1506 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs, 1507 RParenLoc); 1508 else 1509 Init = MemberInit.get(); 1510 } 1511 1512 if (DirectMember) { 1513 return new (Context) CXXCtorInitializer(Context, DirectMember, 1514 IdLoc, LParenLoc, Init, 1515 RParenLoc); 1516 } else { 1517 return new (Context) CXXCtorInitializer(Context, IndirectMember, 1518 IdLoc, LParenLoc, Init, 1519 RParenLoc); 1520 } 1521} 1522 1523MemInitResult 1524Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, 1525 Expr **Args, unsigned NumArgs, 1526 SourceLocation NameLoc, 1527 SourceLocation LParenLoc, 1528 SourceLocation RParenLoc, 1529 CXXRecordDecl *ClassDecl) { 1530 SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 1531 if (!LangOpts.CPlusPlus0x) 1532 return Diag(Loc, diag::err_delegation_0x_only) 1533 << TInfo->getTypeLoc().getLocalSourceRange(); 1534 1535 // Initialize the object. 1536 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 1537 QualType(ClassDecl->getTypeForDecl(), 0)); 1538 InitializationKind Kind = 1539 InitializationKind::CreateDirect(NameLoc, LParenLoc, RParenLoc); 1540 1541 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs); 1542 1543 ExprResult DelegationInit = 1544 InitSeq.Perform(*this, DelegationEntity, Kind, 1545 MultiExprArg(*this, Args, NumArgs), 0); 1546 if (DelegationInit.isInvalid()) 1547 return true; 1548 1549 CXXConstructExpr *ConExpr = cast<CXXConstructExpr>(DelegationInit.get()); 1550 CXXConstructorDecl *Constructor = ConExpr->getConstructor(); 1551 assert(Constructor && "Delegating constructor with no target?"); 1552 1553 CheckImplicitConversions(DelegationInit.get(), LParenLoc); 1554 1555 // C++0x [class.base.init]p7: 1556 // The initialization of each base and member constitutes a 1557 // full-expression. 1558 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit); 1559 if (DelegationInit.isInvalid()) 1560 return true; 1561 1562 // If we are in a dependent context, template instantiation will 1563 // perform this type-checking again. Just save the arguments that we 1564 // received in a ParenListExpr. 1565 // FIXME: This isn't quite ideal, since our ASTs don't capture all 1566 // of the information that we have about the base 1567 // initializer. However, deconstructing the ASTs is a dicey process, 1568 // and this approach is far more likely to get the corner cases right. 1569 if (CurContext->isDependentContext()) { 1570 ExprResult Init 1571 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, 1572 NumArgs, RParenLoc)); 1573 return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc, 1574 Constructor, Init.takeAs<Expr>(), 1575 RParenLoc); 1576 } 1577 1578 return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc, Constructor, 1579 DelegationInit.takeAs<Expr>(), 1580 RParenLoc); 1581} 1582 1583MemInitResult 1584Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 1585 Expr **Args, unsigned NumArgs, 1586 SourceLocation LParenLoc, SourceLocation RParenLoc, 1587 CXXRecordDecl *ClassDecl, 1588 SourceLocation EllipsisLoc) { 1589 bool HasDependentArg = false; 1590 for (unsigned i = 0; i < NumArgs; i++) 1591 HasDependentArg |= Args[i]->isTypeDependent(); 1592 1593 SourceLocation BaseLoc 1594 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 1595 1596 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 1597 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 1598 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 1599 1600 // C++ [class.base.init]p2: 1601 // [...] Unless the mem-initializer-id names a nonstatic data 1602 // member of the constructor's class or a direct or virtual base 1603 // of that class, the mem-initializer is ill-formed. A 1604 // mem-initializer-list can initialize a base class using any 1605 // name that denotes that base class type. 1606 bool Dependent = BaseType->isDependentType() || HasDependentArg; 1607 1608 if (EllipsisLoc.isValid()) { 1609 // This is a pack expansion. 1610 if (!BaseType->containsUnexpandedParameterPack()) { 1611 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 1612 << SourceRange(BaseLoc, RParenLoc); 1613 1614 EllipsisLoc = SourceLocation(); 1615 } 1616 } else { 1617 // Check for any unexpanded parameter packs. 1618 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 1619 return true; 1620 1621 for (unsigned I = 0; I != NumArgs; ++I) 1622 if (DiagnoseUnexpandedParameterPack(Args[I])) 1623 return true; 1624 } 1625 1626 // Check for direct and virtual base classes. 1627 const CXXBaseSpecifier *DirectBaseSpec = 0; 1628 const CXXBaseSpecifier *VirtualBaseSpec = 0; 1629 if (!Dependent) { 1630 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 1631 BaseType)) 1632 return BuildDelegatingInitializer(BaseTInfo, Args, NumArgs, BaseLoc, 1633 LParenLoc, RParenLoc, ClassDecl); 1634 1635 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 1636 VirtualBaseSpec); 1637 1638 // C++ [base.class.init]p2: 1639 // Unless the mem-initializer-id names a nonstatic data member of the 1640 // constructor's class or a direct or virtual base of that class, the 1641 // mem-initializer is ill-formed. 1642 if (!DirectBaseSpec && !VirtualBaseSpec) { 1643 // If the class has any dependent bases, then it's possible that 1644 // one of those types will resolve to the same type as 1645 // BaseType. Therefore, just treat this as a dependent base 1646 // class initialization. FIXME: Should we try to check the 1647 // initialization anyway? It seems odd. 1648 if (ClassDecl->hasAnyDependentBases()) 1649 Dependent = true; 1650 else 1651 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 1652 << BaseType << Context.getTypeDeclType(ClassDecl) 1653 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 1654 } 1655 } 1656 1657 if (Dependent) { 1658 // Can't check initialization for a base of dependent type or when 1659 // any of the arguments are type-dependent expressions. 1660 ExprResult BaseInit 1661 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs, 1662 RParenLoc)); 1663 1664 // Erase any temporaries within this evaluation context; we're not 1665 // going to track them in the AST, since we'll be rebuilding the 1666 // ASTs during template instantiation. 1667 ExprTemporaries.erase( 1668 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries, 1669 ExprTemporaries.end()); 1670 1671 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 1672 /*IsVirtual=*/false, 1673 LParenLoc, 1674 BaseInit.takeAs<Expr>(), 1675 RParenLoc, 1676 EllipsisLoc); 1677 } 1678 1679 // C++ [base.class.init]p2: 1680 // If a mem-initializer-id is ambiguous because it designates both 1681 // a direct non-virtual base class and an inherited virtual base 1682 // class, the mem-initializer is ill-formed. 1683 if (DirectBaseSpec && VirtualBaseSpec) 1684 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 1685 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 1686 1687 CXXBaseSpecifier *BaseSpec 1688 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec); 1689 if (!BaseSpec) 1690 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec); 1691 1692 // Initialize the base. 1693 InitializedEntity BaseEntity = 1694 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 1695 InitializationKind Kind = 1696 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc); 1697 1698 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs); 1699 1700 ExprResult BaseInit = 1701 InitSeq.Perform(*this, BaseEntity, Kind, 1702 MultiExprArg(*this, Args, NumArgs), 0); 1703 if (BaseInit.isInvalid()) 1704 return true; 1705 1706 CheckImplicitConversions(BaseInit.get(), LParenLoc); 1707 1708 // C++0x [class.base.init]p7: 1709 // The initialization of each base and member constitutes a 1710 // full-expression. 1711 BaseInit = MaybeCreateExprWithCleanups(BaseInit); 1712 if (BaseInit.isInvalid()) 1713 return true; 1714 1715 // If we are in a dependent context, template instantiation will 1716 // perform this type-checking again. Just save the arguments that we 1717 // received in a ParenListExpr. 1718 // FIXME: This isn't quite ideal, since our ASTs don't capture all 1719 // of the information that we have about the base 1720 // initializer. However, deconstructing the ASTs is a dicey process, 1721 // and this approach is far more likely to get the corner cases right. 1722 if (CurContext->isDependentContext()) { 1723 ExprResult Init 1724 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs, 1725 RParenLoc)); 1726 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 1727 BaseSpec->isVirtual(), 1728 LParenLoc, 1729 Init.takeAs<Expr>(), 1730 RParenLoc, 1731 EllipsisLoc); 1732 } 1733 1734 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 1735 BaseSpec->isVirtual(), 1736 LParenLoc, 1737 BaseInit.takeAs<Expr>(), 1738 RParenLoc, 1739 EllipsisLoc); 1740} 1741 1742/// ImplicitInitializerKind - How an implicit base or member initializer should 1743/// initialize its base or member. 1744enum ImplicitInitializerKind { 1745 IIK_Default, 1746 IIK_Copy, 1747 IIK_Move 1748}; 1749 1750static bool 1751BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 1752 ImplicitInitializerKind ImplicitInitKind, 1753 CXXBaseSpecifier *BaseSpec, 1754 bool IsInheritedVirtualBase, 1755 CXXCtorInitializer *&CXXBaseInit) { 1756 InitializedEntity InitEntity 1757 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 1758 IsInheritedVirtualBase); 1759 1760 ExprResult BaseInit; 1761 1762 switch (ImplicitInitKind) { 1763 case IIK_Default: { 1764 InitializationKind InitKind 1765 = InitializationKind::CreateDefault(Constructor->getLocation()); 1766 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0); 1767 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, 1768 MultiExprArg(SemaRef, 0, 0)); 1769 break; 1770 } 1771 1772 case IIK_Copy: { 1773 ParmVarDecl *Param = Constructor->getParamDecl(0); 1774 QualType ParamType = Param->getType().getNonReferenceType(); 1775 1776 Expr *CopyCtorArg = 1777 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param, 1778 Constructor->getLocation(), ParamType, 1779 VK_LValue, 0); 1780 1781 // Cast to the base class to avoid ambiguities. 1782 QualType ArgTy = 1783 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 1784 ParamType.getQualifiers()); 1785 1786 CXXCastPath BasePath; 1787 BasePath.push_back(BaseSpec); 1788 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 1789 CK_UncheckedDerivedToBase, 1790 VK_LValue, &BasePath).take(); 1791 1792 InitializationKind InitKind 1793 = InitializationKind::CreateDirect(Constructor->getLocation(), 1794 SourceLocation(), SourceLocation()); 1795 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 1796 &CopyCtorArg, 1); 1797 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, 1798 MultiExprArg(&CopyCtorArg, 1)); 1799 break; 1800 } 1801 1802 case IIK_Move: 1803 assert(false && "Unhandled initializer kind!"); 1804 } 1805 1806 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 1807 if (BaseInit.isInvalid()) 1808 return true; 1809 1810 CXXBaseInit = 1811 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 1812 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 1813 SourceLocation()), 1814 BaseSpec->isVirtual(), 1815 SourceLocation(), 1816 BaseInit.takeAs<Expr>(), 1817 SourceLocation(), 1818 SourceLocation()); 1819 1820 return false; 1821} 1822 1823static bool 1824BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 1825 ImplicitInitializerKind ImplicitInitKind, 1826 FieldDecl *Field, 1827 CXXCtorInitializer *&CXXMemberInit) { 1828 if (Field->isInvalidDecl()) 1829 return true; 1830 1831 SourceLocation Loc = Constructor->getLocation(); 1832 1833 if (ImplicitInitKind == IIK_Copy) { 1834 ParmVarDecl *Param = Constructor->getParamDecl(0); 1835 QualType ParamType = Param->getType().getNonReferenceType(); 1836 1837 Expr *MemberExprBase = 1838 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param, 1839 Loc, ParamType, VK_LValue, 0); 1840 1841 // Build a reference to this field within the parameter. 1842 CXXScopeSpec SS; 1843 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 1844 Sema::LookupMemberName); 1845 MemberLookup.addDecl(Field, AS_public); 1846 MemberLookup.resolveKind(); 1847 ExprResult CopyCtorArg 1848 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 1849 ParamType, Loc, 1850 /*IsArrow=*/false, 1851 SS, 1852 /*FirstQualifierInScope=*/0, 1853 MemberLookup, 1854 /*TemplateArgs=*/0); 1855 if (CopyCtorArg.isInvalid()) 1856 return true; 1857 1858 // When the field we are copying is an array, create index variables for 1859 // each dimension of the array. We use these index variables to subscript 1860 // the source array, and other clients (e.g., CodeGen) will perform the 1861 // necessary iteration with these index variables. 1862 llvm::SmallVector<VarDecl *, 4> IndexVariables; 1863 QualType BaseType = Field->getType(); 1864 QualType SizeType = SemaRef.Context.getSizeType(); 1865 while (const ConstantArrayType *Array 1866 = SemaRef.Context.getAsConstantArrayType(BaseType)) { 1867 // Create the iteration variable for this array index. 1868 IdentifierInfo *IterationVarName = 0; 1869 { 1870 llvm::SmallString<8> Str; 1871 llvm::raw_svector_ostream OS(Str); 1872 OS << "__i" << IndexVariables.size(); 1873 IterationVarName = &SemaRef.Context.Idents.get(OS.str()); 1874 } 1875 VarDecl *IterationVar 1876 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc, 1877 IterationVarName, SizeType, 1878 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc), 1879 SC_None, SC_None); 1880 IndexVariables.push_back(IterationVar); 1881 1882 // Create a reference to the iteration variable. 1883 ExprResult IterationVarRef 1884 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc); 1885 assert(!IterationVarRef.isInvalid() && 1886 "Reference to invented variable cannot fail!"); 1887 1888 // Subscript the array with this iteration variable. 1889 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(), 1890 Loc, 1891 IterationVarRef.take(), 1892 Loc); 1893 if (CopyCtorArg.isInvalid()) 1894 return true; 1895 1896 BaseType = Array->getElementType(); 1897 } 1898 1899 // Construct the entity that we will be initializing. For an array, this 1900 // will be first element in the array, which may require several levels 1901 // of array-subscript entities. 1902 llvm::SmallVector<InitializedEntity, 4> Entities; 1903 Entities.reserve(1 + IndexVariables.size()); 1904 Entities.push_back(InitializedEntity::InitializeMember(Field)); 1905 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 1906 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context, 1907 0, 1908 Entities.back())); 1909 1910 // Direct-initialize to use the copy constructor. 1911 InitializationKind InitKind = 1912 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 1913 1914 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>(); 1915 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, 1916 &CopyCtorArgE, 1); 1917 1918 ExprResult MemberInit 1919 = InitSeq.Perform(SemaRef, Entities.back(), InitKind, 1920 MultiExprArg(&CopyCtorArgE, 1)); 1921 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 1922 if (MemberInit.isInvalid()) 1923 return true; 1924 1925 CXXMemberInit 1926 = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, Loc, 1927 MemberInit.takeAs<Expr>(), Loc, 1928 IndexVariables.data(), 1929 IndexVariables.size()); 1930 return false; 1931 } 1932 1933 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!"); 1934 1935 QualType FieldBaseElementType = 1936 SemaRef.Context.getBaseElementType(Field->getType()); 1937 1938 if (FieldBaseElementType->isRecordType()) { 1939 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 1940 InitializationKind InitKind = 1941 InitializationKind::CreateDefault(Loc); 1942 1943 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0); 1944 ExprResult MemberInit = 1945 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg()); 1946 1947 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 1948 if (MemberInit.isInvalid()) 1949 return true; 1950 1951 CXXMemberInit = 1952 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 1953 Field, Loc, Loc, 1954 MemberInit.get(), 1955 Loc); 1956 return false; 1957 } 1958 1959 if (FieldBaseElementType->isReferenceType()) { 1960 SemaRef.Diag(Constructor->getLocation(), 1961 diag::err_uninitialized_member_in_ctor) 1962 << (int)Constructor->isImplicit() 1963 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 1964 << 0 << Field->getDeclName(); 1965 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 1966 return true; 1967 } 1968 1969 if (FieldBaseElementType.isConstQualified()) { 1970 SemaRef.Diag(Constructor->getLocation(), 1971 diag::err_uninitialized_member_in_ctor) 1972 << (int)Constructor->isImplicit() 1973 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 1974 << 1 << Field->getDeclName(); 1975 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 1976 return true; 1977 } 1978 1979 // Nothing to initialize. 1980 CXXMemberInit = 0; 1981 return false; 1982} 1983 1984namespace { 1985struct BaseAndFieldInfo { 1986 Sema &S; 1987 CXXConstructorDecl *Ctor; 1988 bool AnyErrorsInInits; 1989 ImplicitInitializerKind IIK; 1990 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 1991 llvm::SmallVector<CXXCtorInitializer*, 8> AllToInit; 1992 1993 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 1994 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 1995 // FIXME: Handle implicit move constructors. 1996 if (Ctor->isImplicit() && Ctor->isCopyConstructor()) 1997 IIK = IIK_Copy; 1998 else 1999 IIK = IIK_Default; 2000 } 2001}; 2002} 2003 2004static bool CollectFieldInitializer(BaseAndFieldInfo &Info, 2005 FieldDecl *Top, FieldDecl *Field) { 2006 2007 // Overwhelmingly common case: we have a direct initializer for this field. 2008 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) { 2009 Info.AllToInit.push_back(Init); 2010 return false; 2011 } 2012 2013 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) { 2014 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>(); 2015 assert(FieldClassType && "anonymous struct/union without record type"); 2016 CXXRecordDecl *FieldClassDecl 2017 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 2018 2019 // Even though union members never have non-trivial default 2020 // constructions in C++03, we still build member initializers for aggregate 2021 // record types which can be union members, and C++0x allows non-trivial 2022 // default constructors for union members, so we ensure that only one 2023 // member is initialized for these. 2024 if (FieldClassDecl->isUnion()) { 2025 // First check for an explicit initializer for one field. 2026 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(), 2027 EA = FieldClassDecl->field_end(); FA != EA; FA++) { 2028 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(*FA)) { 2029 Info.AllToInit.push_back(Init); 2030 2031 // Once we've initialized a field of an anonymous union, the union 2032 // field in the class is also initialized, so exit immediately. 2033 return false; 2034 } else if ((*FA)->isAnonymousStructOrUnion()) { 2035 if (CollectFieldInitializer(Info, Top, *FA)) 2036 return true; 2037 } 2038 } 2039 2040 // Fallthrough and construct a default initializer for the union as 2041 // a whole, which can call its default constructor if such a thing exists 2042 // (C++0x perhaps). FIXME: It's not clear that this is the correct 2043 // behavior going forward with C++0x, when anonymous unions there are 2044 // finalized, we should revisit this. 2045 } else { 2046 // For structs, we simply descend through to initialize all members where 2047 // necessary. 2048 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(), 2049 EA = FieldClassDecl->field_end(); FA != EA; FA++) { 2050 if (CollectFieldInitializer(Info, Top, *FA)) 2051 return true; 2052 } 2053 } 2054 } 2055 2056 // Don't try to build an implicit initializer if there were semantic 2057 // errors in any of the initializers (and therefore we might be 2058 // missing some that the user actually wrote). 2059 if (Info.AnyErrorsInInits) 2060 return false; 2061 2062 CXXCtorInitializer *Init = 0; 2063 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init)) 2064 return true; 2065 2066 if (Init) 2067 Info.AllToInit.push_back(Init); 2068 2069 return false; 2070} 2071 2072bool 2073Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 2074 CXXCtorInitializer *Initializer) { 2075 Constructor->setNumCtorInitializers(1); 2076 CXXCtorInitializer **initializer = 2077 new (Context) CXXCtorInitializer*[1]; 2078 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 2079 Constructor->setCtorInitializers(initializer); 2080 2081 // FIXME: This doesn't catch indirect loops yet 2082 CXXConstructorDecl *Target = Initializer->getTargetConstructor(); 2083 while (Target) { 2084 if (Target == Constructor) { 2085 Diag(Initializer->getSourceLocation(), diag::err_delegating_ctor_loop) 2086 << Constructor; 2087 return true; 2088 } 2089 Target = Target->getTargetConstructor(); 2090 } 2091 2092 return false; 2093} 2094 2095 2096bool 2097Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, 2098 CXXCtorInitializer **Initializers, 2099 unsigned NumInitializers, 2100 bool AnyErrors) { 2101 if (Constructor->getDeclContext()->isDependentContext()) { 2102 // Just store the initializers as written, they will be checked during 2103 // instantiation. 2104 if (NumInitializers > 0) { 2105 Constructor->setNumCtorInitializers(NumInitializers); 2106 CXXCtorInitializer **baseOrMemberInitializers = 2107 new (Context) CXXCtorInitializer*[NumInitializers]; 2108 memcpy(baseOrMemberInitializers, Initializers, 2109 NumInitializers * sizeof(CXXCtorInitializer*)); 2110 Constructor->setCtorInitializers(baseOrMemberInitializers); 2111 } 2112 2113 return false; 2114 } 2115 2116 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 2117 2118 // We need to build the initializer AST according to order of construction 2119 // and not what user specified in the Initializers list. 2120 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 2121 if (!ClassDecl) 2122 return true; 2123 2124 bool HadError = false; 2125 2126 for (unsigned i = 0; i < NumInitializers; i++) { 2127 CXXCtorInitializer *Member = Initializers[i]; 2128 2129 if (Member->isBaseInitializer()) 2130 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 2131 else 2132 Info.AllBaseFields[Member->getAnyMember()] = Member; 2133 } 2134 2135 // Keep track of the direct virtual bases. 2136 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 2137 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(), 2138 E = ClassDecl->bases_end(); I != E; ++I) { 2139 if (I->isVirtual()) 2140 DirectVBases.insert(I); 2141 } 2142 2143 // Push virtual bases before others. 2144 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 2145 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 2146 2147 if (CXXCtorInitializer *Value 2148 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) { 2149 Info.AllToInit.push_back(Value); 2150 } else if (!AnyErrors) { 2151 bool IsInheritedVirtualBase = !DirectVBases.count(VBase); 2152 CXXCtorInitializer *CXXBaseInit; 2153 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 2154 VBase, IsInheritedVirtualBase, 2155 CXXBaseInit)) { 2156 HadError = true; 2157 continue; 2158 } 2159 2160 Info.AllToInit.push_back(CXXBaseInit); 2161 } 2162 } 2163 2164 // Non-virtual bases. 2165 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 2166 E = ClassDecl->bases_end(); Base != E; ++Base) { 2167 // Virtuals are in the virtual base list and already constructed. 2168 if (Base->isVirtual()) 2169 continue; 2170 2171 if (CXXCtorInitializer *Value 2172 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) { 2173 Info.AllToInit.push_back(Value); 2174 } else if (!AnyErrors) { 2175 CXXCtorInitializer *CXXBaseInit; 2176 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 2177 Base, /*IsInheritedVirtualBase=*/false, 2178 CXXBaseInit)) { 2179 HadError = true; 2180 continue; 2181 } 2182 2183 Info.AllToInit.push_back(CXXBaseInit); 2184 } 2185 } 2186 2187 // Fields. 2188 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 2189 E = ClassDecl->field_end(); Field != E; ++Field) { 2190 if ((*Field)->getType()->isIncompleteArrayType()) { 2191 assert(ClassDecl->hasFlexibleArrayMember() && 2192 "Incomplete array type is not valid"); 2193 continue; 2194 } 2195 if (CollectFieldInitializer(Info, *Field, *Field)) 2196 HadError = true; 2197 } 2198 2199 NumInitializers = Info.AllToInit.size(); 2200 if (NumInitializers > 0) { 2201 Constructor->setNumCtorInitializers(NumInitializers); 2202 CXXCtorInitializer **baseOrMemberInitializers = 2203 new (Context) CXXCtorInitializer*[NumInitializers]; 2204 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 2205 NumInitializers * sizeof(CXXCtorInitializer*)); 2206 Constructor->setCtorInitializers(baseOrMemberInitializers); 2207 2208 // Constructors implicitly reference the base and member 2209 // destructors. 2210 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 2211 Constructor->getParent()); 2212 } 2213 2214 return HadError; 2215} 2216 2217static void *GetKeyForTopLevelField(FieldDecl *Field) { 2218 // For anonymous unions, use the class declaration as the key. 2219 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 2220 if (RT->getDecl()->isAnonymousStructOrUnion()) 2221 return static_cast<void *>(RT->getDecl()); 2222 } 2223 return static_cast<void *>(Field); 2224} 2225 2226static void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 2227 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr()); 2228} 2229 2230static void *GetKeyForMember(ASTContext &Context, 2231 CXXCtorInitializer *Member) { 2232 if (!Member->isAnyMemberInitializer()) 2233 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 2234 2235 // For fields injected into the class via declaration of an anonymous union, 2236 // use its anonymous union class declaration as the unique key. 2237 FieldDecl *Field = Member->getAnyMember(); 2238 2239 // If the field is a member of an anonymous struct or union, our key 2240 // is the anonymous record decl that's a direct child of the class. 2241 RecordDecl *RD = Field->getParent(); 2242 if (RD->isAnonymousStructOrUnion()) { 2243 while (true) { 2244 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext()); 2245 if (Parent->isAnonymousStructOrUnion()) 2246 RD = Parent; 2247 else 2248 break; 2249 } 2250 2251 return static_cast<void *>(RD); 2252 } 2253 2254 return static_cast<void *>(Field); 2255} 2256 2257static void 2258DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef, 2259 const CXXConstructorDecl *Constructor, 2260 CXXCtorInitializer **Inits, 2261 unsigned NumInits) { 2262 if (Constructor->getDeclContext()->isDependentContext()) 2263 return; 2264 2265 // Don't check initializers order unless the warning is enabled at the 2266 // location of at least one initializer. 2267 bool ShouldCheckOrder = false; 2268 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) { 2269 CXXCtorInitializer *Init = Inits[InitIndex]; 2270 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order, 2271 Init->getSourceLocation()) 2272 != Diagnostic::Ignored) { 2273 ShouldCheckOrder = true; 2274 break; 2275 } 2276 } 2277 if (!ShouldCheckOrder) 2278 return; 2279 2280 // Build the list of bases and members in the order that they'll 2281 // actually be initialized. The explicit initializers should be in 2282 // this same order but may be missing things. 2283 llvm::SmallVector<const void*, 32> IdealInitKeys; 2284 2285 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 2286 2287 // 1. Virtual bases. 2288 for (CXXRecordDecl::base_class_const_iterator VBase = 2289 ClassDecl->vbases_begin(), 2290 E = ClassDecl->vbases_end(); VBase != E; ++VBase) 2291 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType())); 2292 2293 // 2. Non-virtual bases. 2294 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(), 2295 E = ClassDecl->bases_end(); Base != E; ++Base) { 2296 if (Base->isVirtual()) 2297 continue; 2298 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType())); 2299 } 2300 2301 // 3. Direct fields. 2302 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 2303 E = ClassDecl->field_end(); Field != E; ++Field) 2304 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field)); 2305 2306 unsigned NumIdealInits = IdealInitKeys.size(); 2307 unsigned IdealIndex = 0; 2308 2309 CXXCtorInitializer *PrevInit = 0; 2310 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) { 2311 CXXCtorInitializer *Init = Inits[InitIndex]; 2312 void *InitKey = GetKeyForMember(SemaRef.Context, Init); 2313 2314 // Scan forward to try to find this initializer in the idealized 2315 // initializers list. 2316 for (; IdealIndex != NumIdealInits; ++IdealIndex) 2317 if (InitKey == IdealInitKeys[IdealIndex]) 2318 break; 2319 2320 // If we didn't find this initializer, it must be because we 2321 // scanned past it on a previous iteration. That can only 2322 // happen if we're out of order; emit a warning. 2323 if (IdealIndex == NumIdealInits && PrevInit) { 2324 Sema::SemaDiagnosticBuilder D = 2325 SemaRef.Diag(PrevInit->getSourceLocation(), 2326 diag::warn_initializer_out_of_order); 2327 2328 if (PrevInit->isAnyMemberInitializer()) 2329 D << 0 << PrevInit->getAnyMember()->getDeclName(); 2330 else 2331 D << 1 << PrevInit->getBaseClassInfo()->getType(); 2332 2333 if (Init->isAnyMemberInitializer()) 2334 D << 0 << Init->getAnyMember()->getDeclName(); 2335 else 2336 D << 1 << Init->getBaseClassInfo()->getType(); 2337 2338 // Move back to the initializer's location in the ideal list. 2339 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 2340 if (InitKey == IdealInitKeys[IdealIndex]) 2341 break; 2342 2343 assert(IdealIndex != NumIdealInits && 2344 "initializer not found in initializer list"); 2345 } 2346 2347 PrevInit = Init; 2348 } 2349} 2350 2351namespace { 2352bool CheckRedundantInit(Sema &S, 2353 CXXCtorInitializer *Init, 2354 CXXCtorInitializer *&PrevInit) { 2355 if (!PrevInit) { 2356 PrevInit = Init; 2357 return false; 2358 } 2359 2360 if (FieldDecl *Field = Init->getMember()) 2361 S.Diag(Init->getSourceLocation(), 2362 diag::err_multiple_mem_initialization) 2363 << Field->getDeclName() 2364 << Init->getSourceRange(); 2365 else { 2366 const Type *BaseClass = Init->getBaseClass(); 2367 assert(BaseClass && "neither field nor base"); 2368 S.Diag(Init->getSourceLocation(), 2369 diag::err_multiple_base_initialization) 2370 << QualType(BaseClass, 0) 2371 << Init->getSourceRange(); 2372 } 2373 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 2374 << 0 << PrevInit->getSourceRange(); 2375 2376 return true; 2377} 2378 2379typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 2380typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 2381 2382bool CheckRedundantUnionInit(Sema &S, 2383 CXXCtorInitializer *Init, 2384 RedundantUnionMap &Unions) { 2385 FieldDecl *Field = Init->getAnyMember(); 2386 RecordDecl *Parent = Field->getParent(); 2387 if (!Parent->isAnonymousStructOrUnion()) 2388 return false; 2389 2390 NamedDecl *Child = Field; 2391 do { 2392 if (Parent->isUnion()) { 2393 UnionEntry &En = Unions[Parent]; 2394 if (En.first && En.first != Child) { 2395 S.Diag(Init->getSourceLocation(), 2396 diag::err_multiple_mem_union_initialization) 2397 << Field->getDeclName() 2398 << Init->getSourceRange(); 2399 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 2400 << 0 << En.second->getSourceRange(); 2401 return true; 2402 } else if (!En.first) { 2403 En.first = Child; 2404 En.second = Init; 2405 } 2406 } 2407 2408 Child = Parent; 2409 Parent = cast<RecordDecl>(Parent->getDeclContext()); 2410 } while (Parent->isAnonymousStructOrUnion()); 2411 2412 return false; 2413} 2414} 2415 2416/// ActOnMemInitializers - Handle the member initializers for a constructor. 2417void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 2418 SourceLocation ColonLoc, 2419 MemInitTy **meminits, unsigned NumMemInits, 2420 bool AnyErrors) { 2421 if (!ConstructorDecl) 2422 return; 2423 2424 AdjustDeclIfTemplate(ConstructorDecl); 2425 2426 CXXConstructorDecl *Constructor 2427 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 2428 2429 if (!Constructor) { 2430 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 2431 return; 2432 } 2433 2434 CXXCtorInitializer **MemInits = 2435 reinterpret_cast<CXXCtorInitializer **>(meminits); 2436 2437 // Mapping for the duplicate initializers check. 2438 // For member initializers, this is keyed with a FieldDecl*. 2439 // For base initializers, this is keyed with a Type*. 2440 llvm::DenseMap<void*, CXXCtorInitializer *> Members; 2441 2442 // Mapping for the inconsistent anonymous-union initializers check. 2443 RedundantUnionMap MemberUnions; 2444 2445 bool HadError = false; 2446 for (unsigned i = 0; i < NumMemInits; i++) { 2447 CXXCtorInitializer *Init = MemInits[i]; 2448 2449 // Set the source order index. 2450 Init->setSourceOrder(i); 2451 2452 if (Init->isAnyMemberInitializer()) { 2453 FieldDecl *Field = Init->getAnyMember(); 2454 if (CheckRedundantInit(*this, Init, Members[Field]) || 2455 CheckRedundantUnionInit(*this, Init, MemberUnions)) 2456 HadError = true; 2457 } else if (Init->isBaseInitializer()) { 2458 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0)); 2459 if (CheckRedundantInit(*this, Init, Members[Key])) 2460 HadError = true; 2461 } else { 2462 assert(Init->isDelegatingInitializer()); 2463 // This must be the only initializer 2464 if (i != 0 || NumMemInits > 1) { 2465 Diag(MemInits[0]->getSourceLocation(), 2466 diag::err_delegating_initializer_alone) 2467 << MemInits[0]->getSourceRange(); 2468 HadError = true; 2469 // We will treat this as being the only initializer. 2470 } 2471 SetDelegatingInitializer(Constructor, *MemInits); 2472 // Return immediately as the initializer is set. 2473 return; 2474 } 2475 } 2476 2477 if (HadError) 2478 return; 2479 2480 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits); 2481 2482 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors); 2483} 2484 2485void 2486Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 2487 CXXRecordDecl *ClassDecl) { 2488 // Ignore dependent contexts. 2489 if (ClassDecl->isDependentContext()) 2490 return; 2491 2492 // FIXME: all the access-control diagnostics are positioned on the 2493 // field/base declaration. That's probably good; that said, the 2494 // user might reasonably want to know why the destructor is being 2495 // emitted, and we currently don't say. 2496 2497 // Non-static data members. 2498 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(), 2499 E = ClassDecl->field_end(); I != E; ++I) { 2500 FieldDecl *Field = *I; 2501 if (Field->isInvalidDecl()) 2502 continue; 2503 QualType FieldType = Context.getBaseElementType(Field->getType()); 2504 2505 const RecordType* RT = FieldType->getAs<RecordType>(); 2506 if (!RT) 2507 continue; 2508 2509 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 2510 if (FieldClassDecl->isInvalidDecl()) 2511 continue; 2512 if (FieldClassDecl->hasTrivialDestructor()) 2513 continue; 2514 2515 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 2516 assert(Dtor && "No dtor found for FieldClassDecl!"); 2517 CheckDestructorAccess(Field->getLocation(), Dtor, 2518 PDiag(diag::err_access_dtor_field) 2519 << Field->getDeclName() 2520 << FieldType); 2521 2522 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 2523 } 2524 2525 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 2526 2527 // Bases. 2528 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 2529 E = ClassDecl->bases_end(); Base != E; ++Base) { 2530 // Bases are always records in a well-formed non-dependent class. 2531 const RecordType *RT = Base->getType()->getAs<RecordType>(); 2532 2533 // Remember direct virtual bases. 2534 if (Base->isVirtual()) 2535 DirectVirtualBases.insert(RT); 2536 2537 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 2538 // If our base class is invalid, we probably can't get its dtor anyway. 2539 if (BaseClassDecl->isInvalidDecl()) 2540 continue; 2541 // Ignore trivial destructors. 2542 if (BaseClassDecl->hasTrivialDestructor()) 2543 continue; 2544 2545 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 2546 assert(Dtor && "No dtor found for BaseClassDecl!"); 2547 2548 // FIXME: caret should be on the start of the class name 2549 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor, 2550 PDiag(diag::err_access_dtor_base) 2551 << Base->getType() 2552 << Base->getSourceRange()); 2553 2554 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 2555 } 2556 2557 // Virtual bases. 2558 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 2559 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 2560 2561 // Bases are always records in a well-formed non-dependent class. 2562 const RecordType *RT = VBase->getType()->getAs<RecordType>(); 2563 2564 // Ignore direct virtual bases. 2565 if (DirectVirtualBases.count(RT)) 2566 continue; 2567 2568 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 2569 // If our base class is invalid, we probably can't get its dtor anyway. 2570 if (BaseClassDecl->isInvalidDecl()) 2571 continue; 2572 // Ignore trivial destructors. 2573 if (BaseClassDecl->hasTrivialDestructor()) 2574 continue; 2575 2576 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 2577 assert(Dtor && "No dtor found for BaseClassDecl!"); 2578 CheckDestructorAccess(ClassDecl->getLocation(), Dtor, 2579 PDiag(diag::err_access_dtor_vbase) 2580 << VBase->getType()); 2581 2582 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 2583 } 2584} 2585 2586void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 2587 if (!CDtorDecl) 2588 return; 2589 2590 if (CXXConstructorDecl *Constructor 2591 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) 2592 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false); 2593} 2594 2595bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 2596 unsigned DiagID, AbstractDiagSelID SelID) { 2597 if (SelID == -1) 2598 return RequireNonAbstractType(Loc, T, PDiag(DiagID)); 2599 else 2600 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID); 2601} 2602 2603bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 2604 const PartialDiagnostic &PD) { 2605 if (!getLangOptions().CPlusPlus) 2606 return false; 2607 2608 if (const ArrayType *AT = Context.getAsArrayType(T)) 2609 return RequireNonAbstractType(Loc, AT->getElementType(), PD); 2610 2611 if (const PointerType *PT = T->getAs<PointerType>()) { 2612 // Find the innermost pointer type. 2613 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 2614 PT = T; 2615 2616 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 2617 return RequireNonAbstractType(Loc, AT->getElementType(), PD); 2618 } 2619 2620 const RecordType *RT = T->getAs<RecordType>(); 2621 if (!RT) 2622 return false; 2623 2624 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 2625 2626 // We can't answer whether something is abstract until it has a 2627 // definition. If it's currently being defined, we'll walk back 2628 // over all the declarations when we have a full definition. 2629 const CXXRecordDecl *Def = RD->getDefinition(); 2630 if (!Def || Def->isBeingDefined()) 2631 return false; 2632 2633 if (!RD->isAbstract()) 2634 return false; 2635 2636 Diag(Loc, PD) << RD->getDeclName(); 2637 DiagnoseAbstractType(RD); 2638 2639 return true; 2640} 2641 2642void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 2643 // Check if we've already emitted the list of pure virtual functions 2644 // for this class. 2645 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 2646 return; 2647 2648 CXXFinalOverriderMap FinalOverriders; 2649 RD->getFinalOverriders(FinalOverriders); 2650 2651 // Keep a set of seen pure methods so we won't diagnose the same method 2652 // more than once. 2653 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 2654 2655 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 2656 MEnd = FinalOverriders.end(); 2657 M != MEnd; 2658 ++M) { 2659 for (OverridingMethods::iterator SO = M->second.begin(), 2660 SOEnd = M->second.end(); 2661 SO != SOEnd; ++SO) { 2662 // C++ [class.abstract]p4: 2663 // A class is abstract if it contains or inherits at least one 2664 // pure virtual function for which the final overrider is pure 2665 // virtual. 2666 2667 // 2668 if (SO->second.size() != 1) 2669 continue; 2670 2671 if (!SO->second.front().Method->isPure()) 2672 continue; 2673 2674 if (!SeenPureMethods.insert(SO->second.front().Method)) 2675 continue; 2676 2677 Diag(SO->second.front().Method->getLocation(), 2678 diag::note_pure_virtual_function) 2679 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 2680 } 2681 } 2682 2683 if (!PureVirtualClassDiagSet) 2684 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 2685 PureVirtualClassDiagSet->insert(RD); 2686} 2687 2688namespace { 2689struct AbstractUsageInfo { 2690 Sema &S; 2691 CXXRecordDecl *Record; 2692 CanQualType AbstractType; 2693 bool Invalid; 2694 2695 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 2696 : S(S), Record(Record), 2697 AbstractType(S.Context.getCanonicalType( 2698 S.Context.getTypeDeclType(Record))), 2699 Invalid(false) {} 2700 2701 void DiagnoseAbstractType() { 2702 if (Invalid) return; 2703 S.DiagnoseAbstractType(Record); 2704 Invalid = true; 2705 } 2706 2707 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 2708}; 2709 2710struct CheckAbstractUsage { 2711 AbstractUsageInfo &Info; 2712 const NamedDecl *Ctx; 2713 2714 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 2715 : Info(Info), Ctx(Ctx) {} 2716 2717 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 2718 switch (TL.getTypeLocClass()) { 2719#define ABSTRACT_TYPELOC(CLASS, PARENT) 2720#define TYPELOC(CLASS, PARENT) \ 2721 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break; 2722#include "clang/AST/TypeLocNodes.def" 2723 } 2724 } 2725 2726 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 2727 Visit(TL.getResultLoc(), Sema::AbstractReturnType); 2728 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 2729 if (!TL.getArg(I)) 2730 continue; 2731 2732 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo(); 2733 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 2734 } 2735 } 2736 2737 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 2738 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 2739 } 2740 2741 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 2742 // Visit the type parameters from a permissive context. 2743 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 2744 TemplateArgumentLoc TAL = TL.getArgLoc(I); 2745 if (TAL.getArgument().getKind() == TemplateArgument::Type) 2746 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 2747 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 2748 // TODO: other template argument types? 2749 } 2750 } 2751 2752 // Visit pointee types from a permissive context. 2753#define CheckPolymorphic(Type) \ 2754 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 2755 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 2756 } 2757 CheckPolymorphic(PointerTypeLoc) 2758 CheckPolymorphic(ReferenceTypeLoc) 2759 CheckPolymorphic(MemberPointerTypeLoc) 2760 CheckPolymorphic(BlockPointerTypeLoc) 2761 2762 /// Handle all the types we haven't given a more specific 2763 /// implementation for above. 2764 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 2765 // Every other kind of type that we haven't called out already 2766 // that has an inner type is either (1) sugar or (2) contains that 2767 // inner type in some way as a subobject. 2768 if (TypeLoc Next = TL.getNextTypeLoc()) 2769 return Visit(Next, Sel); 2770 2771 // If there's no inner type and we're in a permissive context, 2772 // don't diagnose. 2773 if (Sel == Sema::AbstractNone) return; 2774 2775 // Check whether the type matches the abstract type. 2776 QualType T = TL.getType(); 2777 if (T->isArrayType()) { 2778 Sel = Sema::AbstractArrayType; 2779 T = Info.S.Context.getBaseElementType(T); 2780 } 2781 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 2782 if (CT != Info.AbstractType) return; 2783 2784 // It matched; do some magic. 2785 if (Sel == Sema::AbstractArrayType) { 2786 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 2787 << T << TL.getSourceRange(); 2788 } else { 2789 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 2790 << Sel << T << TL.getSourceRange(); 2791 } 2792 Info.DiagnoseAbstractType(); 2793 } 2794}; 2795 2796void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 2797 Sema::AbstractDiagSelID Sel) { 2798 CheckAbstractUsage(*this, D).Visit(TL, Sel); 2799} 2800 2801} 2802 2803/// Check for invalid uses of an abstract type in a method declaration. 2804static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 2805 CXXMethodDecl *MD) { 2806 // No need to do the check on definitions, which require that 2807 // the return/param types be complete. 2808 if (MD->isThisDeclarationADefinition()) 2809 return; 2810 2811 // For safety's sake, just ignore it if we don't have type source 2812 // information. This should never happen for non-implicit methods, 2813 // but... 2814 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 2815 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 2816} 2817 2818/// Check for invalid uses of an abstract type within a class definition. 2819static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 2820 CXXRecordDecl *RD) { 2821 for (CXXRecordDecl::decl_iterator 2822 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) { 2823 Decl *D = *I; 2824 if (D->isImplicit()) continue; 2825 2826 // Methods and method templates. 2827 if (isa<CXXMethodDecl>(D)) { 2828 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 2829 } else if (isa<FunctionTemplateDecl>(D)) { 2830 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 2831 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 2832 2833 // Fields and static variables. 2834 } else if (isa<FieldDecl>(D)) { 2835 FieldDecl *FD = cast<FieldDecl>(D); 2836 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 2837 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 2838 } else if (isa<VarDecl>(D)) { 2839 VarDecl *VD = cast<VarDecl>(D); 2840 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 2841 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 2842 2843 // Nested classes and class templates. 2844 } else if (isa<CXXRecordDecl>(D)) { 2845 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 2846 } else if (isa<ClassTemplateDecl>(D)) { 2847 CheckAbstractClassUsage(Info, 2848 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 2849 } 2850 } 2851} 2852 2853/// \brief Perform semantic checks on a class definition that has been 2854/// completing, introducing implicitly-declared members, checking for 2855/// abstract types, etc. 2856void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 2857 if (!Record) 2858 return; 2859 2860 if (Record->isAbstract() && !Record->isInvalidDecl()) { 2861 AbstractUsageInfo Info(*this, Record); 2862 CheckAbstractClassUsage(Info, Record); 2863 } 2864 2865 // If this is not an aggregate type and has no user-declared constructor, 2866 // complain about any non-static data members of reference or const scalar 2867 // type, since they will never get initializers. 2868 if (!Record->isInvalidDecl() && !Record->isDependentType() && 2869 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) { 2870 bool Complained = false; 2871 for (RecordDecl::field_iterator F = Record->field_begin(), 2872 FEnd = Record->field_end(); 2873 F != FEnd; ++F) { 2874 if (F->getType()->isReferenceType() || 2875 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 2876 if (!Complained) { 2877 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 2878 << Record->getTagKind() << Record; 2879 Complained = true; 2880 } 2881 2882 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 2883 << F->getType()->isReferenceType() 2884 << F->getDeclName(); 2885 } 2886 } 2887 } 2888 2889 if (Record->isDynamicClass() && !Record->isDependentType()) 2890 DynamicClasses.push_back(Record); 2891 2892 if (Record->getIdentifier()) { 2893 // C++ [class.mem]p13: 2894 // If T is the name of a class, then each of the following shall have a 2895 // name different from T: 2896 // - every member of every anonymous union that is a member of class T. 2897 // 2898 // C++ [class.mem]p14: 2899 // In addition, if class T has a user-declared constructor (12.1), every 2900 // non-static data member of class T shall have a name different from T. 2901 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 2902 R.first != R.second; ++R.first) { 2903 NamedDecl *D = *R.first; 2904 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 2905 isa<IndirectFieldDecl>(D)) { 2906 Diag(D->getLocation(), diag::err_member_name_of_class) 2907 << D->getDeclName(); 2908 break; 2909 } 2910 } 2911 } 2912 2913 // Warn if the class has virtual methods but non-virtual public destructor. 2914 if (Record->isPolymorphic() && !Record->isDependentType()) { 2915 CXXDestructorDecl *dtor = Record->getDestructor(); 2916 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) 2917 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 2918 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 2919 } 2920 2921 // See if a method overloads virtual methods in a base 2922 /// class without overriding any. 2923 if (!Record->isDependentType()) { 2924 for (CXXRecordDecl::method_iterator M = Record->method_begin(), 2925 MEnd = Record->method_end(); 2926 M != MEnd; ++M) { 2927 if (!(*M)->isStatic()) 2928 DiagnoseHiddenVirtualMethods(Record, *M); 2929 } 2930 } 2931 2932 // Declare inherited constructors. We do this eagerly here because: 2933 // - The standard requires an eager diagnostic for conflicting inherited 2934 // constructors from different classes. 2935 // - The lazy declaration of the other implicit constructors is so as to not 2936 // waste space and performance on classes that are not meant to be 2937 // instantiated (e.g. meta-functions). This doesn't apply to classes that 2938 // have inherited constructors. 2939 DeclareInheritedConstructors(Record); 2940} 2941 2942/// \brief Data used with FindHiddenVirtualMethod 2943namespace { 2944 struct FindHiddenVirtualMethodData { 2945 Sema *S; 2946 CXXMethodDecl *Method; 2947 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 2948 llvm::SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 2949 }; 2950} 2951 2952/// \brief Member lookup function that determines whether a given C++ 2953/// method overloads virtual methods in a base class without overriding any, 2954/// to be used with CXXRecordDecl::lookupInBases(). 2955static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier, 2956 CXXBasePath &Path, 2957 void *UserData) { 2958 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 2959 2960 FindHiddenVirtualMethodData &Data 2961 = *static_cast<FindHiddenVirtualMethodData*>(UserData); 2962 2963 DeclarationName Name = Data.Method->getDeclName(); 2964 assert(Name.getNameKind() == DeclarationName::Identifier); 2965 2966 bool foundSameNameMethod = false; 2967 llvm::SmallVector<CXXMethodDecl *, 8> overloadedMethods; 2968 for (Path.Decls = BaseRecord->lookup(Name); 2969 Path.Decls.first != Path.Decls.second; 2970 ++Path.Decls.first) { 2971 NamedDecl *D = *Path.Decls.first; 2972 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 2973 MD = MD->getCanonicalDecl(); 2974 foundSameNameMethod = true; 2975 // Interested only in hidden virtual methods. 2976 if (!MD->isVirtual()) 2977 continue; 2978 // If the method we are checking overrides a method from its base 2979 // don't warn about the other overloaded methods. 2980 if (!Data.S->IsOverload(Data.Method, MD, false)) 2981 return true; 2982 // Collect the overload only if its hidden. 2983 if (!Data.OverridenAndUsingBaseMethods.count(MD)) 2984 overloadedMethods.push_back(MD); 2985 } 2986 } 2987 2988 if (foundSameNameMethod) 2989 Data.OverloadedMethods.append(overloadedMethods.begin(), 2990 overloadedMethods.end()); 2991 return foundSameNameMethod; 2992} 2993 2994/// \brief See if a method overloads virtual methods in a base class without 2995/// overriding any. 2996void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 2997 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual, 2998 MD->getLocation()) == Diagnostic::Ignored) 2999 return; 3000 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier) 3001 return; 3002 3003 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 3004 /*bool RecordPaths=*/false, 3005 /*bool DetectVirtual=*/false); 3006 FindHiddenVirtualMethodData Data; 3007 Data.Method = MD; 3008 Data.S = this; 3009 3010 // Keep the base methods that were overriden or introduced in the subclass 3011 // by 'using' in a set. A base method not in this set is hidden. 3012 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName()); 3013 res.first != res.second; ++res.first) { 3014 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first)) 3015 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 3016 E = MD->end_overridden_methods(); 3017 I != E; ++I) 3018 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl()); 3019 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first)) 3020 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl())) 3021 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl()); 3022 } 3023 3024 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) && 3025 !Data.OverloadedMethods.empty()) { 3026 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 3027 << MD << (Data.OverloadedMethods.size() > 1); 3028 3029 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) { 3030 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i]; 3031 Diag(overloadedMD->getLocation(), 3032 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 3033 } 3034 } 3035} 3036 3037void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 3038 Decl *TagDecl, 3039 SourceLocation LBrac, 3040 SourceLocation RBrac, 3041 AttributeList *AttrList) { 3042 if (!TagDecl) 3043 return; 3044 3045 AdjustDeclIfTemplate(TagDecl); 3046 3047 ActOnFields(S, RLoc, TagDecl, 3048 // strict aliasing violation! 3049 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 3050 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList); 3051 3052 CheckCompletedCXXClass( 3053 dyn_cast_or_null<CXXRecordDecl>(TagDecl)); 3054} 3055 3056namespace { 3057 /// \brief Helper class that collects exception specifications for 3058 /// implicitly-declared special member functions. 3059 class ImplicitExceptionSpecification { 3060 ASTContext &Context; 3061 // We order exception specifications thus: 3062 // noexcept is the most restrictive, but is only used in C++0x. 3063 // throw() comes next. 3064 // Then a throw(collected exceptions) 3065 // Finally no specification. 3066 // throw(...) is used instead if any called function uses it. 3067 ExceptionSpecificationType ComputedEST; 3068 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen; 3069 llvm::SmallVector<QualType, 4> Exceptions; 3070 3071 void ClearExceptions() { 3072 ExceptionsSeen.clear(); 3073 Exceptions.clear(); 3074 } 3075 3076 public: 3077 explicit ImplicitExceptionSpecification(ASTContext &Context) 3078 : Context(Context), ComputedEST(EST_BasicNoexcept) { 3079 if (!Context.getLangOptions().CPlusPlus0x) 3080 ComputedEST = EST_DynamicNone; 3081 } 3082 3083 /// \brief Get the computed exception specification type. 3084 ExceptionSpecificationType getExceptionSpecType() const { 3085 assert(ComputedEST != EST_ComputedNoexcept && 3086 "noexcept(expr) should not be a possible result"); 3087 return ComputedEST; 3088 } 3089 3090 /// \brief The number of exceptions in the exception specification. 3091 unsigned size() const { return Exceptions.size(); } 3092 3093 /// \brief The set of exceptions in the exception specification. 3094 const QualType *data() const { return Exceptions.data(); } 3095 3096 /// \brief Integrate another called method into the collected data. 3097 void CalledDecl(CXXMethodDecl *Method) { 3098 // If we have an MSAny spec already, don't bother. 3099 if (!Method || ComputedEST == EST_MSAny) 3100 return; 3101 3102 const FunctionProtoType *Proto 3103 = Method->getType()->getAs<FunctionProtoType>(); 3104 3105 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 3106 3107 // If this function can throw any exceptions, make a note of that. 3108 if (EST == EST_MSAny || EST == EST_None) { 3109 ClearExceptions(); 3110 ComputedEST = EST; 3111 return; 3112 } 3113 3114 // If this function has a basic noexcept, it doesn't affect the outcome. 3115 if (EST == EST_BasicNoexcept) 3116 return; 3117 3118 // If we have a throw-all spec at this point, ignore the function. 3119 if (ComputedEST == EST_None) 3120 return; 3121 3122 // If we're still at noexcept(true) and there's a nothrow() callee, 3123 // change to that specification. 3124 if (EST == EST_DynamicNone) { 3125 if (ComputedEST == EST_BasicNoexcept) 3126 ComputedEST = EST_DynamicNone; 3127 return; 3128 } 3129 3130 // Check out noexcept specs. 3131 if (EST == EST_ComputedNoexcept) { 3132 FunctionProtoType::NoexceptResult NR = Proto->getNoexceptSpec(Context); 3133 assert(NR != FunctionProtoType::NR_NoNoexcept && 3134 "Must have noexcept result for EST_ComputedNoexcept."); 3135 assert(NR != FunctionProtoType::NR_Dependent && 3136 "Should not generate implicit declarations for dependent cases, " 3137 "and don't know how to handle them anyway."); 3138 3139 // noexcept(false) -> no spec on the new function 3140 if (NR == FunctionProtoType::NR_Throw) { 3141 ClearExceptions(); 3142 ComputedEST = EST_None; 3143 } 3144 // noexcept(true) won't change anything either. 3145 return; 3146 } 3147 3148 assert(EST == EST_Dynamic && "EST case not considered earlier."); 3149 assert(ComputedEST != EST_None && 3150 "Shouldn't collect exceptions when throw-all is guaranteed."); 3151 ComputedEST = EST_Dynamic; 3152 // Record the exceptions in this function's exception specification. 3153 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(), 3154 EEnd = Proto->exception_end(); 3155 E != EEnd; ++E) 3156 if (ExceptionsSeen.insert(Context.getCanonicalType(*E))) 3157 Exceptions.push_back(*E); 3158 } 3159 }; 3160} 3161 3162 3163/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 3164/// special functions, such as the default constructor, copy 3165/// constructor, or destructor, to the given C++ class (C++ 3166/// [special]p1). This routine can only be executed just before the 3167/// definition of the class is complete. 3168void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 3169 if (!ClassDecl->hasUserDeclaredConstructor()) 3170 ++ASTContext::NumImplicitDefaultConstructors; 3171 3172 if (!ClassDecl->hasUserDeclaredCopyConstructor()) 3173 ++ASTContext::NumImplicitCopyConstructors; 3174 3175 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 3176 ++ASTContext::NumImplicitCopyAssignmentOperators; 3177 3178 // If we have a dynamic class, then the copy assignment operator may be 3179 // virtual, so we have to declare it immediately. This ensures that, e.g., 3180 // it shows up in the right place in the vtable and that we diagnose 3181 // problems with the implicit exception specification. 3182 if (ClassDecl->isDynamicClass()) 3183 DeclareImplicitCopyAssignment(ClassDecl); 3184 } 3185 3186 if (!ClassDecl->hasUserDeclaredDestructor()) { 3187 ++ASTContext::NumImplicitDestructors; 3188 3189 // If we have a dynamic class, then the destructor may be virtual, so we 3190 // have to declare the destructor immediately. This ensures that, e.g., it 3191 // shows up in the right place in the vtable and that we diagnose problems 3192 // with the implicit exception specification. 3193 if (ClassDecl->isDynamicClass()) 3194 DeclareImplicitDestructor(ClassDecl); 3195 } 3196} 3197 3198void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) { 3199 if (!D) 3200 return; 3201 3202 int NumParamList = D->getNumTemplateParameterLists(); 3203 for (int i = 0; i < NumParamList; i++) { 3204 TemplateParameterList* Params = D->getTemplateParameterList(i); 3205 for (TemplateParameterList::iterator Param = Params->begin(), 3206 ParamEnd = Params->end(); 3207 Param != ParamEnd; ++Param) { 3208 NamedDecl *Named = cast<NamedDecl>(*Param); 3209 if (Named->getDeclName()) { 3210 S->AddDecl(Named); 3211 IdResolver.AddDecl(Named); 3212 } 3213 } 3214 } 3215} 3216 3217void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 3218 if (!D) 3219 return; 3220 3221 TemplateParameterList *Params = 0; 3222 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) 3223 Params = Template->getTemplateParameters(); 3224 else if (ClassTemplatePartialSpecializationDecl *PartialSpec 3225 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 3226 Params = PartialSpec->getTemplateParameters(); 3227 else 3228 return; 3229 3230 for (TemplateParameterList::iterator Param = Params->begin(), 3231 ParamEnd = Params->end(); 3232 Param != ParamEnd; ++Param) { 3233 NamedDecl *Named = cast<NamedDecl>(*Param); 3234 if (Named->getDeclName()) { 3235 S->AddDecl(Named); 3236 IdResolver.AddDecl(Named); 3237 } 3238 } 3239} 3240 3241void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 3242 if (!RecordD) return; 3243 AdjustDeclIfTemplate(RecordD); 3244 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 3245 PushDeclContext(S, Record); 3246} 3247 3248void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 3249 if (!RecordD) return; 3250 PopDeclContext(); 3251} 3252 3253/// ActOnStartDelayedCXXMethodDeclaration - We have completed 3254/// parsing a top-level (non-nested) C++ class, and we are now 3255/// parsing those parts of the given Method declaration that could 3256/// not be parsed earlier (C++ [class.mem]p2), such as default 3257/// arguments. This action should enter the scope of the given 3258/// Method declaration as if we had just parsed the qualified method 3259/// name. However, it should not bring the parameters into scope; 3260/// that will be performed by ActOnDelayedCXXMethodParameter. 3261void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 3262} 3263 3264/// ActOnDelayedCXXMethodParameter - We've already started a delayed 3265/// C++ method declaration. We're (re-)introducing the given 3266/// function parameter into scope for use in parsing later parts of 3267/// the method declaration. For example, we could see an 3268/// ActOnParamDefaultArgument event for this parameter. 3269void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 3270 if (!ParamD) 3271 return; 3272 3273 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 3274 3275 // If this parameter has an unparsed default argument, clear it out 3276 // to make way for the parsed default argument. 3277 if (Param->hasUnparsedDefaultArg()) 3278 Param->setDefaultArg(0); 3279 3280 S->AddDecl(Param); 3281 if (Param->getDeclName()) 3282 IdResolver.AddDecl(Param); 3283} 3284 3285/// ActOnFinishDelayedCXXMethodDeclaration - We have finished 3286/// processing the delayed method declaration for Method. The method 3287/// declaration is now considered finished. There may be a separate 3288/// ActOnStartOfFunctionDef action later (not necessarily 3289/// immediately!) for this method, if it was also defined inside the 3290/// class body. 3291void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 3292 if (!MethodD) 3293 return; 3294 3295 AdjustDeclIfTemplate(MethodD); 3296 3297 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 3298 3299 // Now that we have our default arguments, check the constructor 3300 // again. It could produce additional diagnostics or affect whether 3301 // the class has implicitly-declared destructors, among other 3302 // things. 3303 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 3304 CheckConstructor(Constructor); 3305 3306 // Check the default arguments, which we may have added. 3307 if (!Method->isInvalidDecl()) 3308 CheckCXXDefaultArguments(Method); 3309} 3310 3311/// CheckConstructorDeclarator - Called by ActOnDeclarator to check 3312/// the well-formedness of the constructor declarator @p D with type @p 3313/// R. If there are any errors in the declarator, this routine will 3314/// emit diagnostics and set the invalid bit to true. In any case, the type 3315/// will be updated to reflect a well-formed type for the constructor and 3316/// returned. 3317QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 3318 StorageClass &SC) { 3319 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 3320 3321 // C++ [class.ctor]p3: 3322 // A constructor shall not be virtual (10.3) or static (9.4). A 3323 // constructor can be invoked for a const, volatile or const 3324 // volatile object. A constructor shall not be declared const, 3325 // volatile, or const volatile (9.3.2). 3326 if (isVirtual) { 3327 if (!D.isInvalidType()) 3328 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 3329 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 3330 << SourceRange(D.getIdentifierLoc()); 3331 D.setInvalidType(); 3332 } 3333 if (SC == SC_Static) { 3334 if (!D.isInvalidType()) 3335 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 3336 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 3337 << SourceRange(D.getIdentifierLoc()); 3338 D.setInvalidType(); 3339 SC = SC_None; 3340 } 3341 3342 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 3343 if (FTI.TypeQuals != 0) { 3344 if (FTI.TypeQuals & Qualifiers::Const) 3345 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 3346 << "const" << SourceRange(D.getIdentifierLoc()); 3347 if (FTI.TypeQuals & Qualifiers::Volatile) 3348 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 3349 << "volatile" << SourceRange(D.getIdentifierLoc()); 3350 if (FTI.TypeQuals & Qualifiers::Restrict) 3351 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 3352 << "restrict" << SourceRange(D.getIdentifierLoc()); 3353 D.setInvalidType(); 3354 } 3355 3356 // C++0x [class.ctor]p4: 3357 // A constructor shall not be declared with a ref-qualifier. 3358 if (FTI.hasRefQualifier()) { 3359 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 3360 << FTI.RefQualifierIsLValueRef 3361 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 3362 D.setInvalidType(); 3363 } 3364 3365 // Rebuild the function type "R" without any type qualifiers (in 3366 // case any of the errors above fired) and with "void" as the 3367 // return type, since constructors don't have return types. 3368 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 3369 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType()) 3370 return R; 3371 3372 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 3373 EPI.TypeQuals = 0; 3374 EPI.RefQualifier = RQ_None; 3375 3376 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(), 3377 Proto->getNumArgs(), EPI); 3378} 3379 3380/// CheckConstructor - Checks a fully-formed constructor for 3381/// well-formedness, issuing any diagnostics required. Returns true if 3382/// the constructor declarator is invalid. 3383void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 3384 CXXRecordDecl *ClassDecl 3385 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 3386 if (!ClassDecl) 3387 return Constructor->setInvalidDecl(); 3388 3389 // C++ [class.copy]p3: 3390 // A declaration of a constructor for a class X is ill-formed if 3391 // its first parameter is of type (optionally cv-qualified) X and 3392 // either there are no other parameters or else all other 3393 // parameters have default arguments. 3394 if (!Constructor->isInvalidDecl() && 3395 ((Constructor->getNumParams() == 1) || 3396 (Constructor->getNumParams() > 1 && 3397 Constructor->getParamDecl(1)->hasDefaultArg())) && 3398 Constructor->getTemplateSpecializationKind() 3399 != TSK_ImplicitInstantiation) { 3400 QualType ParamType = Constructor->getParamDecl(0)->getType(); 3401 QualType ClassTy = Context.getTagDeclType(ClassDecl); 3402 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 3403 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 3404 const char *ConstRef 3405 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 3406 : " const &"; 3407 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 3408 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 3409 3410 // FIXME: Rather that making the constructor invalid, we should endeavor 3411 // to fix the type. 3412 Constructor->setInvalidDecl(); 3413 } 3414 } 3415} 3416 3417/// CheckDestructor - Checks a fully-formed destructor definition for 3418/// well-formedness, issuing any diagnostics required. Returns true 3419/// on error. 3420bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 3421 CXXRecordDecl *RD = Destructor->getParent(); 3422 3423 if (Destructor->isVirtual()) { 3424 SourceLocation Loc; 3425 3426 if (!Destructor->isImplicit()) 3427 Loc = Destructor->getLocation(); 3428 else 3429 Loc = RD->getLocation(); 3430 3431 // If we have a virtual destructor, look up the deallocation function 3432 FunctionDecl *OperatorDelete = 0; 3433 DeclarationName Name = 3434 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 3435 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 3436 return true; 3437 3438 MarkDeclarationReferenced(Loc, OperatorDelete); 3439 3440 Destructor->setOperatorDelete(OperatorDelete); 3441 } 3442 3443 return false; 3444} 3445 3446static inline bool 3447FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) { 3448 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 3449 FTI.ArgInfo[0].Param && 3450 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()); 3451} 3452 3453/// CheckDestructorDeclarator - Called by ActOnDeclarator to check 3454/// the well-formednes of the destructor declarator @p D with type @p 3455/// R. If there are any errors in the declarator, this routine will 3456/// emit diagnostics and set the declarator to invalid. Even if this happens, 3457/// will be updated to reflect a well-formed type for the destructor and 3458/// returned. 3459QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 3460 StorageClass& SC) { 3461 // C++ [class.dtor]p1: 3462 // [...] A typedef-name that names a class is a class-name 3463 // (7.1.3); however, a typedef-name that names a class shall not 3464 // be used as the identifier in the declarator for a destructor 3465 // declaration. 3466 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 3467 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 3468 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 3469 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 3470 3471 // C++ [class.dtor]p2: 3472 // A destructor is used to destroy objects of its class type. A 3473 // destructor takes no parameters, and no return type can be 3474 // specified for it (not even void). The address of a destructor 3475 // shall not be taken. A destructor shall not be static. A 3476 // destructor can be invoked for a const, volatile or const 3477 // volatile object. A destructor shall not be declared const, 3478 // volatile or const volatile (9.3.2). 3479 if (SC == SC_Static) { 3480 if (!D.isInvalidType()) 3481 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 3482 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 3483 << SourceRange(D.getIdentifierLoc()) 3484 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 3485 3486 SC = SC_None; 3487 } 3488 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 3489 // Destructors don't have return types, but the parser will 3490 // happily parse something like: 3491 // 3492 // class X { 3493 // float ~X(); 3494 // }; 3495 // 3496 // The return type will be eliminated later. 3497 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 3498 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 3499 << SourceRange(D.getIdentifierLoc()); 3500 } 3501 3502 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 3503 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 3504 if (FTI.TypeQuals & Qualifiers::Const) 3505 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 3506 << "const" << SourceRange(D.getIdentifierLoc()); 3507 if (FTI.TypeQuals & Qualifiers::Volatile) 3508 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 3509 << "volatile" << SourceRange(D.getIdentifierLoc()); 3510 if (FTI.TypeQuals & Qualifiers::Restrict) 3511 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 3512 << "restrict" << SourceRange(D.getIdentifierLoc()); 3513 D.setInvalidType(); 3514 } 3515 3516 // C++0x [class.dtor]p2: 3517 // A destructor shall not be declared with a ref-qualifier. 3518 if (FTI.hasRefQualifier()) { 3519 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 3520 << FTI.RefQualifierIsLValueRef 3521 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 3522 D.setInvalidType(); 3523 } 3524 3525 // Make sure we don't have any parameters. 3526 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) { 3527 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 3528 3529 // Delete the parameters. 3530 FTI.freeArgs(); 3531 D.setInvalidType(); 3532 } 3533 3534 // Make sure the destructor isn't variadic. 3535 if (FTI.isVariadic) { 3536 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 3537 D.setInvalidType(); 3538 } 3539 3540 // Rebuild the function type "R" without any type qualifiers or 3541 // parameters (in case any of the errors above fired) and with 3542 // "void" as the return type, since destructors don't have return 3543 // types. 3544 if (!D.isInvalidType()) 3545 return R; 3546 3547 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 3548 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 3549 EPI.Variadic = false; 3550 EPI.TypeQuals = 0; 3551 EPI.RefQualifier = RQ_None; 3552 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI); 3553} 3554 3555/// CheckConversionDeclarator - Called by ActOnDeclarator to check the 3556/// well-formednes of the conversion function declarator @p D with 3557/// type @p R. If there are any errors in the declarator, this routine 3558/// will emit diagnostics and return true. Otherwise, it will return 3559/// false. Either way, the type @p R will be updated to reflect a 3560/// well-formed type for the conversion operator. 3561void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 3562 StorageClass& SC) { 3563 // C++ [class.conv.fct]p1: 3564 // Neither parameter types nor return type can be specified. The 3565 // type of a conversion function (8.3.5) is "function taking no 3566 // parameter returning conversion-type-id." 3567 if (SC == SC_Static) { 3568 if (!D.isInvalidType()) 3569 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 3570 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 3571 << SourceRange(D.getIdentifierLoc()); 3572 D.setInvalidType(); 3573 SC = SC_None; 3574 } 3575 3576 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId); 3577 3578 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 3579 // Conversion functions don't have return types, but the parser will 3580 // happily parse something like: 3581 // 3582 // class X { 3583 // float operator bool(); 3584 // }; 3585 // 3586 // The return type will be changed later anyway. 3587 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 3588 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 3589 << SourceRange(D.getIdentifierLoc()); 3590 D.setInvalidType(); 3591 } 3592 3593 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 3594 3595 // Make sure we don't have any parameters. 3596 if (Proto->getNumArgs() > 0) { 3597 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 3598 3599 // Delete the parameters. 3600 D.getFunctionTypeInfo().freeArgs(); 3601 D.setInvalidType(); 3602 } else if (Proto->isVariadic()) { 3603 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 3604 D.setInvalidType(); 3605 } 3606 3607 // Diagnose "&operator bool()" and other such nonsense. This 3608 // is actually a gcc extension which we don't support. 3609 if (Proto->getResultType() != ConvType) { 3610 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 3611 << Proto->getResultType(); 3612 D.setInvalidType(); 3613 ConvType = Proto->getResultType(); 3614 } 3615 3616 // C++ [class.conv.fct]p4: 3617 // The conversion-type-id shall not represent a function type nor 3618 // an array type. 3619 if (ConvType->isArrayType()) { 3620 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 3621 ConvType = Context.getPointerType(ConvType); 3622 D.setInvalidType(); 3623 } else if (ConvType->isFunctionType()) { 3624 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 3625 ConvType = Context.getPointerType(ConvType); 3626 D.setInvalidType(); 3627 } 3628 3629 // Rebuild the function type "R" without any parameters (in case any 3630 // of the errors above fired) and with the conversion type as the 3631 // return type. 3632 if (D.isInvalidType()) 3633 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo()); 3634 3635 // C++0x explicit conversion operators. 3636 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x) 3637 Diag(D.getDeclSpec().getExplicitSpecLoc(), 3638 diag::warn_explicit_conversion_functions) 3639 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 3640} 3641 3642/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 3643/// the declaration of the given C++ conversion function. This routine 3644/// is responsible for recording the conversion function in the C++ 3645/// class, if possible. 3646Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 3647 assert(Conversion && "Expected to receive a conversion function declaration"); 3648 3649 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 3650 3651 // Make sure we aren't redeclaring the conversion function. 3652 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 3653 3654 // C++ [class.conv.fct]p1: 3655 // [...] A conversion function is never used to convert a 3656 // (possibly cv-qualified) object to the (possibly cv-qualified) 3657 // same object type (or a reference to it), to a (possibly 3658 // cv-qualified) base class of that type (or a reference to it), 3659 // or to (possibly cv-qualified) void. 3660 // FIXME: Suppress this warning if the conversion function ends up being a 3661 // virtual function that overrides a virtual function in a base class. 3662 QualType ClassType 3663 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 3664 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 3665 ConvType = ConvTypeRef->getPointeeType(); 3666 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 3667 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 3668 /* Suppress diagnostics for instantiations. */; 3669 else if (ConvType->isRecordType()) { 3670 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 3671 if (ConvType == ClassType) 3672 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 3673 << ClassType; 3674 else if (IsDerivedFrom(ClassType, ConvType)) 3675 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 3676 << ClassType << ConvType; 3677 } else if (ConvType->isVoidType()) { 3678 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 3679 << ClassType << ConvType; 3680 } 3681 3682 if (FunctionTemplateDecl *ConversionTemplate 3683 = Conversion->getDescribedFunctionTemplate()) 3684 return ConversionTemplate; 3685 3686 return Conversion; 3687} 3688 3689//===----------------------------------------------------------------------===// 3690// Namespace Handling 3691//===----------------------------------------------------------------------===// 3692 3693 3694 3695/// ActOnStartNamespaceDef - This is called at the start of a namespace 3696/// definition. 3697Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 3698 SourceLocation InlineLoc, 3699 SourceLocation NamespaceLoc, 3700 SourceLocation IdentLoc, 3701 IdentifierInfo *II, 3702 SourceLocation LBrace, 3703 AttributeList *AttrList) { 3704 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 3705 // For anonymous namespace, take the location of the left brace. 3706 SourceLocation Loc = II ? IdentLoc : LBrace; 3707 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, 3708 StartLoc, Loc, II); 3709 Namespc->setInline(InlineLoc.isValid()); 3710 3711 Scope *DeclRegionScope = NamespcScope->getParent(); 3712 3713 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 3714 3715 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 3716 PushNamespaceVisibilityAttr(Attr); 3717 3718 if (II) { 3719 // C++ [namespace.def]p2: 3720 // The identifier in an original-namespace-definition shall not 3721 // have been previously defined in the declarative region in 3722 // which the original-namespace-definition appears. The 3723 // identifier in an original-namespace-definition is the name of 3724 // the namespace. Subsequently in that declarative region, it is 3725 // treated as an original-namespace-name. 3726 // 3727 // Since namespace names are unique in their scope, and we don't 3728 // look through using directives, just 3729 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II); 3730 NamedDecl *PrevDecl = R.first == R.second? 0 : *R.first; 3731 3732 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) { 3733 // This is an extended namespace definition. 3734 if (Namespc->isInline() != OrigNS->isInline()) { 3735 // inline-ness must match 3736 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch) 3737 << Namespc->isInline(); 3738 Diag(OrigNS->getLocation(), diag::note_previous_definition); 3739 Namespc->setInvalidDecl(); 3740 // Recover by ignoring the new namespace's inline status. 3741 Namespc->setInline(OrigNS->isInline()); 3742 } 3743 3744 // Attach this namespace decl to the chain of extended namespace 3745 // definitions. 3746 OrigNS->setNextNamespace(Namespc); 3747 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace()); 3748 3749 // Remove the previous declaration from the scope. 3750 if (DeclRegionScope->isDeclScope(OrigNS)) { 3751 IdResolver.RemoveDecl(OrigNS); 3752 DeclRegionScope->RemoveDecl(OrigNS); 3753 } 3754 } else if (PrevDecl) { 3755 // This is an invalid name redefinition. 3756 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind) 3757 << Namespc->getDeclName(); 3758 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 3759 Namespc->setInvalidDecl(); 3760 // Continue on to push Namespc as current DeclContext and return it. 3761 } else if (II->isStr("std") && 3762 CurContext->getRedeclContext()->isTranslationUnit()) { 3763 // This is the first "real" definition of the namespace "std", so update 3764 // our cache of the "std" namespace to point at this definition. 3765 if (NamespaceDecl *StdNS = getStdNamespace()) { 3766 // We had already defined a dummy namespace "std". Link this new 3767 // namespace definition to the dummy namespace "std". 3768 StdNS->setNextNamespace(Namespc); 3769 StdNS->setLocation(IdentLoc); 3770 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace()); 3771 } 3772 3773 // Make our StdNamespace cache point at the first real definition of the 3774 // "std" namespace. 3775 StdNamespace = Namespc; 3776 } 3777 3778 PushOnScopeChains(Namespc, DeclRegionScope); 3779 } else { 3780 // Anonymous namespaces. 3781 assert(Namespc->isAnonymousNamespace()); 3782 3783 // Link the anonymous namespace into its parent. 3784 NamespaceDecl *PrevDecl; 3785 DeclContext *Parent = CurContext->getRedeclContext(); 3786 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 3787 PrevDecl = TU->getAnonymousNamespace(); 3788 TU->setAnonymousNamespace(Namespc); 3789 } else { 3790 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 3791 PrevDecl = ND->getAnonymousNamespace(); 3792 ND->setAnonymousNamespace(Namespc); 3793 } 3794 3795 // Link the anonymous namespace with its previous declaration. 3796 if (PrevDecl) { 3797 assert(PrevDecl->isAnonymousNamespace()); 3798 assert(!PrevDecl->getNextNamespace()); 3799 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace()); 3800 PrevDecl->setNextNamespace(Namespc); 3801 3802 if (Namespc->isInline() != PrevDecl->isInline()) { 3803 // inline-ness must match 3804 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch) 3805 << Namespc->isInline(); 3806 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 3807 Namespc->setInvalidDecl(); 3808 // Recover by ignoring the new namespace's inline status. 3809 Namespc->setInline(PrevDecl->isInline()); 3810 } 3811 } 3812 3813 CurContext->addDecl(Namespc); 3814 3815 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 3816 // behaves as if it were replaced by 3817 // namespace unique { /* empty body */ } 3818 // using namespace unique; 3819 // namespace unique { namespace-body } 3820 // where all occurrences of 'unique' in a translation unit are 3821 // replaced by the same identifier and this identifier differs 3822 // from all other identifiers in the entire program. 3823 3824 // We just create the namespace with an empty name and then add an 3825 // implicit using declaration, just like the standard suggests. 3826 // 3827 // CodeGen enforces the "universally unique" aspect by giving all 3828 // declarations semantically contained within an anonymous 3829 // namespace internal linkage. 3830 3831 if (!PrevDecl) { 3832 UsingDirectiveDecl* UD 3833 = UsingDirectiveDecl::Create(Context, CurContext, 3834 /* 'using' */ LBrace, 3835 /* 'namespace' */ SourceLocation(), 3836 /* qualifier */ NestedNameSpecifierLoc(), 3837 /* identifier */ SourceLocation(), 3838 Namespc, 3839 /* Ancestor */ CurContext); 3840 UD->setImplicit(); 3841 CurContext->addDecl(UD); 3842 } 3843 } 3844 3845 // Although we could have an invalid decl (i.e. the namespace name is a 3846 // redefinition), push it as current DeclContext and try to continue parsing. 3847 // FIXME: We should be able to push Namespc here, so that the each DeclContext 3848 // for the namespace has the declarations that showed up in that particular 3849 // namespace definition. 3850 PushDeclContext(NamespcScope, Namespc); 3851 return Namespc; 3852} 3853 3854/// getNamespaceDecl - Returns the namespace a decl represents. If the decl 3855/// is a namespace alias, returns the namespace it points to. 3856static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 3857 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 3858 return AD->getNamespace(); 3859 return dyn_cast_or_null<NamespaceDecl>(D); 3860} 3861 3862/// ActOnFinishNamespaceDef - This callback is called after a namespace is 3863/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 3864void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 3865 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 3866 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 3867 Namespc->setRBraceLoc(RBrace); 3868 PopDeclContext(); 3869 if (Namespc->hasAttr<VisibilityAttr>()) 3870 PopPragmaVisibility(); 3871} 3872 3873CXXRecordDecl *Sema::getStdBadAlloc() const { 3874 return cast_or_null<CXXRecordDecl>( 3875 StdBadAlloc.get(Context.getExternalSource())); 3876} 3877 3878NamespaceDecl *Sema::getStdNamespace() const { 3879 return cast_or_null<NamespaceDecl>( 3880 StdNamespace.get(Context.getExternalSource())); 3881} 3882 3883/// \brief Retrieve the special "std" namespace, which may require us to 3884/// implicitly define the namespace. 3885NamespaceDecl *Sema::getOrCreateStdNamespace() { 3886 if (!StdNamespace) { 3887 // The "std" namespace has not yet been defined, so build one implicitly. 3888 StdNamespace = NamespaceDecl::Create(Context, 3889 Context.getTranslationUnitDecl(), 3890 SourceLocation(), SourceLocation(), 3891 &PP.getIdentifierTable().get("std")); 3892 getStdNamespace()->setImplicit(true); 3893 } 3894 3895 return getStdNamespace(); 3896} 3897 3898/// \brief Determine whether a using statement is in a context where it will be 3899/// apply in all contexts. 3900static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 3901 switch (CurContext->getDeclKind()) { 3902 case Decl::TranslationUnit: 3903 return true; 3904 case Decl::LinkageSpec: 3905 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 3906 default: 3907 return false; 3908 } 3909} 3910 3911Decl *Sema::ActOnUsingDirective(Scope *S, 3912 SourceLocation UsingLoc, 3913 SourceLocation NamespcLoc, 3914 CXXScopeSpec &SS, 3915 SourceLocation IdentLoc, 3916 IdentifierInfo *NamespcName, 3917 AttributeList *AttrList) { 3918 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 3919 assert(NamespcName && "Invalid NamespcName."); 3920 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 3921 3922 // This can only happen along a recovery path. 3923 while (S->getFlags() & Scope::TemplateParamScope) 3924 S = S->getParent(); 3925 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 3926 3927 UsingDirectiveDecl *UDir = 0; 3928 NestedNameSpecifier *Qualifier = 0; 3929 if (SS.isSet()) 3930 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 3931 3932 // Lookup namespace name. 3933 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 3934 LookupParsedName(R, S, &SS); 3935 if (R.isAmbiguous()) 3936 return 0; 3937 3938 if (R.empty()) { 3939 // Allow "using namespace std;" or "using namespace ::std;" even if 3940 // "std" hasn't been defined yet, for GCC compatibility. 3941 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 3942 NamespcName->isStr("std")) { 3943 Diag(IdentLoc, diag::ext_using_undefined_std); 3944 R.addDecl(getOrCreateStdNamespace()); 3945 R.resolveKind(); 3946 } 3947 // Otherwise, attempt typo correction. 3948 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false, 3949 CTC_NoKeywords, 0)) { 3950 if (R.getAsSingle<NamespaceDecl>() || 3951 R.getAsSingle<NamespaceAliasDecl>()) { 3952 if (DeclContext *DC = computeDeclContext(SS, false)) 3953 Diag(IdentLoc, diag::err_using_directive_member_suggest) 3954 << NamespcName << DC << Corrected << SS.getRange() 3955 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString()); 3956 else 3957 Diag(IdentLoc, diag::err_using_directive_suggest) 3958 << NamespcName << Corrected 3959 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString()); 3960 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here) 3961 << Corrected; 3962 3963 NamespcName = Corrected.getAsIdentifierInfo(); 3964 } else { 3965 R.clear(); 3966 R.setLookupName(NamespcName); 3967 } 3968 } 3969 } 3970 3971 if (!R.empty()) { 3972 NamedDecl *Named = R.getFoundDecl(); 3973 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named)) 3974 && "expected namespace decl"); 3975 // C++ [namespace.udir]p1: 3976 // A using-directive specifies that the names in the nominated 3977 // namespace can be used in the scope in which the 3978 // using-directive appears after the using-directive. During 3979 // unqualified name lookup (3.4.1), the names appear as if they 3980 // were declared in the nearest enclosing namespace which 3981 // contains both the using-directive and the nominated 3982 // namespace. [Note: in this context, "contains" means "contains 3983 // directly or indirectly". ] 3984 3985 // Find enclosing context containing both using-directive and 3986 // nominated namespace. 3987 NamespaceDecl *NS = getNamespaceDecl(Named); 3988 DeclContext *CommonAncestor = cast<DeclContext>(NS); 3989 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 3990 CommonAncestor = CommonAncestor->getParent(); 3991 3992 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 3993 SS.getWithLocInContext(Context), 3994 IdentLoc, Named, CommonAncestor); 3995 3996 if (IsUsingDirectiveInToplevelContext(CurContext) && 3997 !SourceMgr.isFromMainFile(SourceMgr.getInstantiationLoc(IdentLoc))) { 3998 Diag(IdentLoc, diag::warn_using_directive_in_header); 3999 } 4000 4001 PushUsingDirective(S, UDir); 4002 } else { 4003 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 4004 } 4005 4006 // FIXME: We ignore attributes for now. 4007 return UDir; 4008} 4009 4010void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 4011 // If scope has associated entity, then using directive is at namespace 4012 // or translation unit scope. We add UsingDirectiveDecls, into 4013 // it's lookup structure. 4014 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) 4015 Ctx->addDecl(UDir); 4016 else 4017 // Otherwise it is block-sope. using-directives will affect lookup 4018 // only to the end of scope. 4019 S->PushUsingDirective(UDir); 4020} 4021 4022 4023Decl *Sema::ActOnUsingDeclaration(Scope *S, 4024 AccessSpecifier AS, 4025 bool HasUsingKeyword, 4026 SourceLocation UsingLoc, 4027 CXXScopeSpec &SS, 4028 UnqualifiedId &Name, 4029 AttributeList *AttrList, 4030 bool IsTypeName, 4031 SourceLocation TypenameLoc) { 4032 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 4033 4034 switch (Name.getKind()) { 4035 case UnqualifiedId::IK_Identifier: 4036 case UnqualifiedId::IK_OperatorFunctionId: 4037 case UnqualifiedId::IK_LiteralOperatorId: 4038 case UnqualifiedId::IK_ConversionFunctionId: 4039 break; 4040 4041 case UnqualifiedId::IK_ConstructorName: 4042 case UnqualifiedId::IK_ConstructorTemplateId: 4043 // C++0x inherited constructors. 4044 if (getLangOptions().CPlusPlus0x) break; 4045 4046 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor) 4047 << SS.getRange(); 4048 return 0; 4049 4050 case UnqualifiedId::IK_DestructorName: 4051 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor) 4052 << SS.getRange(); 4053 return 0; 4054 4055 case UnqualifiedId::IK_TemplateId: 4056 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id) 4057 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 4058 return 0; 4059 } 4060 4061 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 4062 DeclarationName TargetName = TargetNameInfo.getName(); 4063 if (!TargetName) 4064 return 0; 4065 4066 // Warn about using declarations. 4067 // TODO: store that the declaration was written without 'using' and 4068 // talk about access decls instead of using decls in the 4069 // diagnostics. 4070 if (!HasUsingKeyword) { 4071 UsingLoc = Name.getSourceRange().getBegin(); 4072 4073 Diag(UsingLoc, diag::warn_access_decl_deprecated) 4074 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 4075 } 4076 4077 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 4078 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 4079 return 0; 4080 4081 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 4082 TargetNameInfo, AttrList, 4083 /* IsInstantiation */ false, 4084 IsTypeName, TypenameLoc); 4085 if (UD) 4086 PushOnScopeChains(UD, S, /*AddToContext*/ false); 4087 4088 return UD; 4089} 4090 4091/// \brief Determine whether a using declaration considers the given 4092/// declarations as "equivalent", e.g., if they are redeclarations of 4093/// the same entity or are both typedefs of the same type. 4094static bool 4095IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2, 4096 bool &SuppressRedeclaration) { 4097 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) { 4098 SuppressRedeclaration = false; 4099 return true; 4100 } 4101 4102 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 4103 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) { 4104 SuppressRedeclaration = true; 4105 return Context.hasSameType(TD1->getUnderlyingType(), 4106 TD2->getUnderlyingType()); 4107 } 4108 4109 return false; 4110} 4111 4112 4113/// Determines whether to create a using shadow decl for a particular 4114/// decl, given the set of decls existing prior to this using lookup. 4115bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 4116 const LookupResult &Previous) { 4117 // Diagnose finding a decl which is not from a base class of the 4118 // current class. We do this now because there are cases where this 4119 // function will silently decide not to build a shadow decl, which 4120 // will pre-empt further diagnostics. 4121 // 4122 // We don't need to do this in C++0x because we do the check once on 4123 // the qualifier. 4124 // 4125 // FIXME: diagnose the following if we care enough: 4126 // struct A { int foo; }; 4127 // struct B : A { using A::foo; }; 4128 // template <class T> struct C : A {}; 4129 // template <class T> struct D : C<T> { using B::foo; } // <--- 4130 // This is invalid (during instantiation) in C++03 because B::foo 4131 // resolves to the using decl in B, which is not a base class of D<T>. 4132 // We can't diagnose it immediately because C<T> is an unknown 4133 // specialization. The UsingShadowDecl in D<T> then points directly 4134 // to A::foo, which will look well-formed when we instantiate. 4135 // The right solution is to not collapse the shadow-decl chain. 4136 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) { 4137 DeclContext *OrigDC = Orig->getDeclContext(); 4138 4139 // Handle enums and anonymous structs. 4140 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 4141 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 4142 while (OrigRec->isAnonymousStructOrUnion()) 4143 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 4144 4145 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 4146 if (OrigDC == CurContext) { 4147 Diag(Using->getLocation(), 4148 diag::err_using_decl_nested_name_specifier_is_current_class) 4149 << Using->getQualifierLoc().getSourceRange(); 4150 Diag(Orig->getLocation(), diag::note_using_decl_target); 4151 return true; 4152 } 4153 4154 Diag(Using->getQualifierLoc().getBeginLoc(), 4155 diag::err_using_decl_nested_name_specifier_is_not_base_class) 4156 << Using->getQualifier() 4157 << cast<CXXRecordDecl>(CurContext) 4158 << Using->getQualifierLoc().getSourceRange(); 4159 Diag(Orig->getLocation(), diag::note_using_decl_target); 4160 return true; 4161 } 4162 } 4163 4164 if (Previous.empty()) return false; 4165 4166 NamedDecl *Target = Orig; 4167 if (isa<UsingShadowDecl>(Target)) 4168 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 4169 4170 // If the target happens to be one of the previous declarations, we 4171 // don't have a conflict. 4172 // 4173 // FIXME: but we might be increasing its access, in which case we 4174 // should redeclare it. 4175 NamedDecl *NonTag = 0, *Tag = 0; 4176 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 4177 I != E; ++I) { 4178 NamedDecl *D = (*I)->getUnderlyingDecl(); 4179 bool Result; 4180 if (IsEquivalentForUsingDecl(Context, D, Target, Result)) 4181 return Result; 4182 4183 (isa<TagDecl>(D) ? Tag : NonTag) = D; 4184 } 4185 4186 if (Target->isFunctionOrFunctionTemplate()) { 4187 FunctionDecl *FD; 4188 if (isa<FunctionTemplateDecl>(Target)) 4189 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl(); 4190 else 4191 FD = cast<FunctionDecl>(Target); 4192 4193 NamedDecl *OldDecl = 0; 4194 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) { 4195 case Ovl_Overload: 4196 return false; 4197 4198 case Ovl_NonFunction: 4199 Diag(Using->getLocation(), diag::err_using_decl_conflict); 4200 break; 4201 4202 // We found a decl with the exact signature. 4203 case Ovl_Match: 4204 // If we're in a record, we want to hide the target, so we 4205 // return true (without a diagnostic) to tell the caller not to 4206 // build a shadow decl. 4207 if (CurContext->isRecord()) 4208 return true; 4209 4210 // If we're not in a record, this is an error. 4211 Diag(Using->getLocation(), diag::err_using_decl_conflict); 4212 break; 4213 } 4214 4215 Diag(Target->getLocation(), diag::note_using_decl_target); 4216 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 4217 return true; 4218 } 4219 4220 // Target is not a function. 4221 4222 if (isa<TagDecl>(Target)) { 4223 // No conflict between a tag and a non-tag. 4224 if (!Tag) return false; 4225 4226 Diag(Using->getLocation(), diag::err_using_decl_conflict); 4227 Diag(Target->getLocation(), diag::note_using_decl_target); 4228 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 4229 return true; 4230 } 4231 4232 // No conflict between a tag and a non-tag. 4233 if (!NonTag) return false; 4234 4235 Diag(Using->getLocation(), diag::err_using_decl_conflict); 4236 Diag(Target->getLocation(), diag::note_using_decl_target); 4237 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 4238 return true; 4239} 4240 4241/// Builds a shadow declaration corresponding to a 'using' declaration. 4242UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 4243 UsingDecl *UD, 4244 NamedDecl *Orig) { 4245 4246 // If we resolved to another shadow declaration, just coalesce them. 4247 NamedDecl *Target = Orig; 4248 if (isa<UsingShadowDecl>(Target)) { 4249 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 4250 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 4251 } 4252 4253 UsingShadowDecl *Shadow 4254 = UsingShadowDecl::Create(Context, CurContext, 4255 UD->getLocation(), UD, Target); 4256 UD->addShadowDecl(Shadow); 4257 4258 Shadow->setAccess(UD->getAccess()); 4259 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 4260 Shadow->setInvalidDecl(); 4261 4262 if (S) 4263 PushOnScopeChains(Shadow, S); 4264 else 4265 CurContext->addDecl(Shadow); 4266 4267 4268 return Shadow; 4269} 4270 4271/// Hides a using shadow declaration. This is required by the current 4272/// using-decl implementation when a resolvable using declaration in a 4273/// class is followed by a declaration which would hide or override 4274/// one or more of the using decl's targets; for example: 4275/// 4276/// struct Base { void foo(int); }; 4277/// struct Derived : Base { 4278/// using Base::foo; 4279/// void foo(int); 4280/// }; 4281/// 4282/// The governing language is C++03 [namespace.udecl]p12: 4283/// 4284/// When a using-declaration brings names from a base class into a 4285/// derived class scope, member functions in the derived class 4286/// override and/or hide member functions with the same name and 4287/// parameter types in a base class (rather than conflicting). 4288/// 4289/// There are two ways to implement this: 4290/// (1) optimistically create shadow decls when they're not hidden 4291/// by existing declarations, or 4292/// (2) don't create any shadow decls (or at least don't make them 4293/// visible) until we've fully parsed/instantiated the class. 4294/// The problem with (1) is that we might have to retroactively remove 4295/// a shadow decl, which requires several O(n) operations because the 4296/// decl structures are (very reasonably) not designed for removal. 4297/// (2) avoids this but is very fiddly and phase-dependent. 4298void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 4299 if (Shadow->getDeclName().getNameKind() == 4300 DeclarationName::CXXConversionFunctionName) 4301 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 4302 4303 // Remove it from the DeclContext... 4304 Shadow->getDeclContext()->removeDecl(Shadow); 4305 4306 // ...and the scope, if applicable... 4307 if (S) { 4308 S->RemoveDecl(Shadow); 4309 IdResolver.RemoveDecl(Shadow); 4310 } 4311 4312 // ...and the using decl. 4313 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 4314 4315 // TODO: complain somehow if Shadow was used. It shouldn't 4316 // be possible for this to happen, because...? 4317} 4318 4319/// Builds a using declaration. 4320/// 4321/// \param IsInstantiation - Whether this call arises from an 4322/// instantiation of an unresolved using declaration. We treat 4323/// the lookup differently for these declarations. 4324NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 4325 SourceLocation UsingLoc, 4326 CXXScopeSpec &SS, 4327 const DeclarationNameInfo &NameInfo, 4328 AttributeList *AttrList, 4329 bool IsInstantiation, 4330 bool IsTypeName, 4331 SourceLocation TypenameLoc) { 4332 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 4333 SourceLocation IdentLoc = NameInfo.getLoc(); 4334 assert(IdentLoc.isValid() && "Invalid TargetName location."); 4335 4336 // FIXME: We ignore attributes for now. 4337 4338 if (SS.isEmpty()) { 4339 Diag(IdentLoc, diag::err_using_requires_qualname); 4340 return 0; 4341 } 4342 4343 // Do the redeclaration lookup in the current scope. 4344 LookupResult Previous(*this, NameInfo, LookupUsingDeclName, 4345 ForRedeclaration); 4346 Previous.setHideTags(false); 4347 if (S) { 4348 LookupName(Previous, S); 4349 4350 // It is really dumb that we have to do this. 4351 LookupResult::Filter F = Previous.makeFilter(); 4352 while (F.hasNext()) { 4353 NamedDecl *D = F.next(); 4354 if (!isDeclInScope(D, CurContext, S)) 4355 F.erase(); 4356 } 4357 F.done(); 4358 } else { 4359 assert(IsInstantiation && "no scope in non-instantiation"); 4360 assert(CurContext->isRecord() && "scope not record in instantiation"); 4361 LookupQualifiedName(Previous, CurContext); 4362 } 4363 4364 // Check for invalid redeclarations. 4365 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous)) 4366 return 0; 4367 4368 // Check for bad qualifiers. 4369 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc)) 4370 return 0; 4371 4372 DeclContext *LookupContext = computeDeclContext(SS); 4373 NamedDecl *D; 4374 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 4375 if (!LookupContext) { 4376 if (IsTypeName) { 4377 // FIXME: not all declaration name kinds are legal here 4378 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 4379 UsingLoc, TypenameLoc, 4380 QualifierLoc, 4381 IdentLoc, NameInfo.getName()); 4382 } else { 4383 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 4384 QualifierLoc, NameInfo); 4385 } 4386 } else { 4387 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 4388 NameInfo, IsTypeName); 4389 } 4390 D->setAccess(AS); 4391 CurContext->addDecl(D); 4392 4393 if (!LookupContext) return D; 4394 UsingDecl *UD = cast<UsingDecl>(D); 4395 4396 if (RequireCompleteDeclContext(SS, LookupContext)) { 4397 UD->setInvalidDecl(); 4398 return UD; 4399 } 4400 4401 // Constructor inheriting using decls get special treatment. 4402 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) { 4403 if (CheckInheritedConstructorUsingDecl(UD)) 4404 UD->setInvalidDecl(); 4405 return UD; 4406 } 4407 4408 // Otherwise, look up the target name. 4409 4410 LookupResult R(*this, NameInfo, LookupOrdinaryName); 4411 4412 // Unlike most lookups, we don't always want to hide tag 4413 // declarations: tag names are visible through the using declaration 4414 // even if hidden by ordinary names, *except* in a dependent context 4415 // where it's important for the sanity of two-phase lookup. 4416 if (!IsInstantiation) 4417 R.setHideTags(false); 4418 4419 LookupQualifiedName(R, LookupContext); 4420 4421 if (R.empty()) { 4422 Diag(IdentLoc, diag::err_no_member) 4423 << NameInfo.getName() << LookupContext << SS.getRange(); 4424 UD->setInvalidDecl(); 4425 return UD; 4426 } 4427 4428 if (R.isAmbiguous()) { 4429 UD->setInvalidDecl(); 4430 return UD; 4431 } 4432 4433 if (IsTypeName) { 4434 // If we asked for a typename and got a non-type decl, error out. 4435 if (!R.getAsSingle<TypeDecl>()) { 4436 Diag(IdentLoc, diag::err_using_typename_non_type); 4437 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 4438 Diag((*I)->getUnderlyingDecl()->getLocation(), 4439 diag::note_using_decl_target); 4440 UD->setInvalidDecl(); 4441 return UD; 4442 } 4443 } else { 4444 // If we asked for a non-typename and we got a type, error out, 4445 // but only if this is an instantiation of an unresolved using 4446 // decl. Otherwise just silently find the type name. 4447 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 4448 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 4449 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 4450 UD->setInvalidDecl(); 4451 return UD; 4452 } 4453 } 4454 4455 // C++0x N2914 [namespace.udecl]p6: 4456 // A using-declaration shall not name a namespace. 4457 if (R.getAsSingle<NamespaceDecl>()) { 4458 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 4459 << SS.getRange(); 4460 UD->setInvalidDecl(); 4461 return UD; 4462 } 4463 4464 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 4465 if (!CheckUsingShadowDecl(UD, *I, Previous)) 4466 BuildUsingShadowDecl(S, UD, *I); 4467 } 4468 4469 return UD; 4470} 4471 4472/// Additional checks for a using declaration referring to a constructor name. 4473bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) { 4474 if (UD->isTypeName()) { 4475 // FIXME: Cannot specify typename when specifying constructor 4476 return true; 4477 } 4478 4479 const Type *SourceType = UD->getQualifier()->getAsType(); 4480 assert(SourceType && 4481 "Using decl naming constructor doesn't have type in scope spec."); 4482 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 4483 4484 // Check whether the named type is a direct base class. 4485 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified(); 4486 CXXRecordDecl::base_class_iterator BaseIt, BaseE; 4487 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end(); 4488 BaseIt != BaseE; ++BaseIt) { 4489 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified(); 4490 if (CanonicalSourceType == BaseType) 4491 break; 4492 } 4493 4494 if (BaseIt == BaseE) { 4495 // Did not find SourceType in the bases. 4496 Diag(UD->getUsingLocation(), 4497 diag::err_using_decl_constructor_not_in_direct_base) 4498 << UD->getNameInfo().getSourceRange() 4499 << QualType(SourceType, 0) << TargetClass; 4500 return true; 4501 } 4502 4503 BaseIt->setInheritConstructors(); 4504 4505 return false; 4506} 4507 4508/// Checks that the given using declaration is not an invalid 4509/// redeclaration. Note that this is checking only for the using decl 4510/// itself, not for any ill-formedness among the UsingShadowDecls. 4511bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 4512 bool isTypeName, 4513 const CXXScopeSpec &SS, 4514 SourceLocation NameLoc, 4515 const LookupResult &Prev) { 4516 // C++03 [namespace.udecl]p8: 4517 // C++0x [namespace.udecl]p10: 4518 // A using-declaration is a declaration and can therefore be used 4519 // repeatedly where (and only where) multiple declarations are 4520 // allowed. 4521 // 4522 // That's in non-member contexts. 4523 if (!CurContext->getRedeclContext()->isRecord()) 4524 return false; 4525 4526 NestedNameSpecifier *Qual 4527 = static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 4528 4529 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 4530 NamedDecl *D = *I; 4531 4532 bool DTypename; 4533 NestedNameSpecifier *DQual; 4534 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 4535 DTypename = UD->isTypeName(); 4536 DQual = UD->getQualifier(); 4537 } else if (UnresolvedUsingValueDecl *UD 4538 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 4539 DTypename = false; 4540 DQual = UD->getQualifier(); 4541 } else if (UnresolvedUsingTypenameDecl *UD 4542 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 4543 DTypename = true; 4544 DQual = UD->getQualifier(); 4545 } else continue; 4546 4547 // using decls differ if one says 'typename' and the other doesn't. 4548 // FIXME: non-dependent using decls? 4549 if (isTypeName != DTypename) continue; 4550 4551 // using decls differ if they name different scopes (but note that 4552 // template instantiation can cause this check to trigger when it 4553 // didn't before instantiation). 4554 if (Context.getCanonicalNestedNameSpecifier(Qual) != 4555 Context.getCanonicalNestedNameSpecifier(DQual)) 4556 continue; 4557 4558 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 4559 Diag(D->getLocation(), diag::note_using_decl) << 1; 4560 return true; 4561 } 4562 4563 return false; 4564} 4565 4566 4567/// Checks that the given nested-name qualifier used in a using decl 4568/// in the current context is appropriately related to the current 4569/// scope. If an error is found, diagnoses it and returns true. 4570bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 4571 const CXXScopeSpec &SS, 4572 SourceLocation NameLoc) { 4573 DeclContext *NamedContext = computeDeclContext(SS); 4574 4575 if (!CurContext->isRecord()) { 4576 // C++03 [namespace.udecl]p3: 4577 // C++0x [namespace.udecl]p8: 4578 // A using-declaration for a class member shall be a member-declaration. 4579 4580 // If we weren't able to compute a valid scope, it must be a 4581 // dependent class scope. 4582 if (!NamedContext || NamedContext->isRecord()) { 4583 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 4584 << SS.getRange(); 4585 return true; 4586 } 4587 4588 // Otherwise, everything is known to be fine. 4589 return false; 4590 } 4591 4592 // The current scope is a record. 4593 4594 // If the named context is dependent, we can't decide much. 4595 if (!NamedContext) { 4596 // FIXME: in C++0x, we can diagnose if we can prove that the 4597 // nested-name-specifier does not refer to a base class, which is 4598 // still possible in some cases. 4599 4600 // Otherwise we have to conservatively report that things might be 4601 // okay. 4602 return false; 4603 } 4604 4605 if (!NamedContext->isRecord()) { 4606 // Ideally this would point at the last name in the specifier, 4607 // but we don't have that level of source info. 4608 Diag(SS.getRange().getBegin(), 4609 diag::err_using_decl_nested_name_specifier_is_not_class) 4610 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange(); 4611 return true; 4612 } 4613 4614 if (!NamedContext->isDependentContext() && 4615 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 4616 return true; 4617 4618 if (getLangOptions().CPlusPlus0x) { 4619 // C++0x [namespace.udecl]p3: 4620 // In a using-declaration used as a member-declaration, the 4621 // nested-name-specifier shall name a base class of the class 4622 // being defined. 4623 4624 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 4625 cast<CXXRecordDecl>(NamedContext))) { 4626 if (CurContext == NamedContext) { 4627 Diag(NameLoc, 4628 diag::err_using_decl_nested_name_specifier_is_current_class) 4629 << SS.getRange(); 4630 return true; 4631 } 4632 4633 Diag(SS.getRange().getBegin(), 4634 diag::err_using_decl_nested_name_specifier_is_not_base_class) 4635 << (NestedNameSpecifier*) SS.getScopeRep() 4636 << cast<CXXRecordDecl>(CurContext) 4637 << SS.getRange(); 4638 return true; 4639 } 4640 4641 return false; 4642 } 4643 4644 // C++03 [namespace.udecl]p4: 4645 // A using-declaration used as a member-declaration shall refer 4646 // to a member of a base class of the class being defined [etc.]. 4647 4648 // Salient point: SS doesn't have to name a base class as long as 4649 // lookup only finds members from base classes. Therefore we can 4650 // diagnose here only if we can prove that that can't happen, 4651 // i.e. if the class hierarchies provably don't intersect. 4652 4653 // TODO: it would be nice if "definitely valid" results were cached 4654 // in the UsingDecl and UsingShadowDecl so that these checks didn't 4655 // need to be repeated. 4656 4657 struct UserData { 4658 llvm::DenseSet<const CXXRecordDecl*> Bases; 4659 4660 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) { 4661 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 4662 Data->Bases.insert(Base); 4663 return true; 4664 } 4665 4666 bool hasDependentBases(const CXXRecordDecl *Class) { 4667 return !Class->forallBases(collect, this); 4668 } 4669 4670 /// Returns true if the base is dependent or is one of the 4671 /// accumulated base classes. 4672 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) { 4673 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 4674 return !Data->Bases.count(Base); 4675 } 4676 4677 bool mightShareBases(const CXXRecordDecl *Class) { 4678 return Bases.count(Class) || !Class->forallBases(doesNotContain, this); 4679 } 4680 }; 4681 4682 UserData Data; 4683 4684 // Returns false if we find a dependent base. 4685 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext))) 4686 return false; 4687 4688 // Returns false if the class has a dependent base or if it or one 4689 // of its bases is present in the base set of the current context. 4690 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext))) 4691 return false; 4692 4693 Diag(SS.getRange().getBegin(), 4694 diag::err_using_decl_nested_name_specifier_is_not_base_class) 4695 << (NestedNameSpecifier*) SS.getScopeRep() 4696 << cast<CXXRecordDecl>(CurContext) 4697 << SS.getRange(); 4698 4699 return true; 4700} 4701 4702Decl *Sema::ActOnAliasDeclaration(Scope *S, 4703 AccessSpecifier AS, 4704 SourceLocation UsingLoc, 4705 UnqualifiedId &Name, 4706 TypeResult Type) { 4707 assert((S->getFlags() & Scope::DeclScope) && 4708 "got alias-declaration outside of declaration scope"); 4709 4710 if (Type.isInvalid()) 4711 return 0; 4712 4713 bool Invalid = false; 4714 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 4715 TypeSourceInfo *TInfo = 0; 4716 GetTypeFromParser(Type.get(), &TInfo); 4717 4718 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 4719 return 0; 4720 4721 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 4722 UPPC_DeclarationType)) 4723 Invalid = true; 4724 4725 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration); 4726 LookupName(Previous, S); 4727 4728 // Warn about shadowing the name of a template parameter. 4729 if (Previous.isSingleResult() && 4730 Previous.getFoundDecl()->isTemplateParameter()) { 4731 if (DiagnoseTemplateParameterShadow(Name.StartLocation, 4732 Previous.getFoundDecl())) 4733 Invalid = true; 4734 Previous.clear(); 4735 } 4736 4737 assert(Name.Kind == UnqualifiedId::IK_Identifier && 4738 "name in alias declaration must be an identifier"); 4739 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 4740 Name.StartLocation, 4741 Name.Identifier, TInfo); 4742 4743 NewTD->setAccess(AS); 4744 4745 if (Invalid) 4746 NewTD->setInvalidDecl(); 4747 4748 bool Redeclaration = false; 4749 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 4750 4751 if (!Redeclaration) 4752 PushOnScopeChains(NewTD, S); 4753 4754 return NewTD; 4755} 4756 4757Decl *Sema::ActOnNamespaceAliasDef(Scope *S, 4758 SourceLocation NamespaceLoc, 4759 SourceLocation AliasLoc, 4760 IdentifierInfo *Alias, 4761 CXXScopeSpec &SS, 4762 SourceLocation IdentLoc, 4763 IdentifierInfo *Ident) { 4764 4765 // Lookup the namespace name. 4766 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 4767 LookupParsedName(R, S, &SS); 4768 4769 // Check if we have a previous declaration with the same name. 4770 NamedDecl *PrevDecl 4771 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName, 4772 ForRedeclaration); 4773 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S)) 4774 PrevDecl = 0; 4775 4776 if (PrevDecl) { 4777 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 4778 // We already have an alias with the same name that points to the same 4779 // namespace, so don't create a new one. 4780 // FIXME: At some point, we'll want to create the (redundant) 4781 // declaration to maintain better source information. 4782 if (!R.isAmbiguous() && !R.empty() && 4783 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl()))) 4784 return 0; 4785 } 4786 4787 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition : 4788 diag::err_redefinition_different_kind; 4789 Diag(AliasLoc, DiagID) << Alias; 4790 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 4791 return 0; 4792 } 4793 4794 if (R.isAmbiguous()) 4795 return 0; 4796 4797 if (R.empty()) { 4798 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false, 4799 CTC_NoKeywords, 0)) { 4800 if (R.getAsSingle<NamespaceDecl>() || 4801 R.getAsSingle<NamespaceAliasDecl>()) { 4802 if (DeclContext *DC = computeDeclContext(SS, false)) 4803 Diag(IdentLoc, diag::err_using_directive_member_suggest) 4804 << Ident << DC << Corrected << SS.getRange() 4805 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString()); 4806 else 4807 Diag(IdentLoc, diag::err_using_directive_suggest) 4808 << Ident << Corrected 4809 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString()); 4810 4811 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here) 4812 << Corrected; 4813 4814 Ident = Corrected.getAsIdentifierInfo(); 4815 } else { 4816 R.clear(); 4817 R.setLookupName(Ident); 4818 } 4819 } 4820 4821 if (R.empty()) { 4822 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange(); 4823 return 0; 4824 } 4825 } 4826 4827 NamespaceAliasDecl *AliasDecl = 4828 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 4829 Alias, SS.getWithLocInContext(Context), 4830 IdentLoc, R.getFoundDecl()); 4831 4832 PushOnScopeChains(AliasDecl, S); 4833 return AliasDecl; 4834} 4835 4836namespace { 4837 /// \brief Scoped object used to handle the state changes required in Sema 4838 /// to implicitly define the body of a C++ member function; 4839 class ImplicitlyDefinedFunctionScope { 4840 Sema &S; 4841 Sema::ContextRAII SavedContext; 4842 4843 public: 4844 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method) 4845 : S(S), SavedContext(S, Method) 4846 { 4847 S.PushFunctionScope(); 4848 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated); 4849 } 4850 4851 ~ImplicitlyDefinedFunctionScope() { 4852 S.PopExpressionEvaluationContext(); 4853 S.PopFunctionOrBlockScope(); 4854 } 4855 }; 4856} 4857 4858static CXXConstructorDecl *getDefaultConstructorUnsafe(Sema &Self, 4859 CXXRecordDecl *D) { 4860 ASTContext &Context = Self.Context; 4861 QualType ClassType = Context.getTypeDeclType(D); 4862 DeclarationName ConstructorName 4863 = Context.DeclarationNames.getCXXConstructorName( 4864 Context.getCanonicalType(ClassType.getUnqualifiedType())); 4865 4866 DeclContext::lookup_const_iterator Con, ConEnd; 4867 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName); 4868 Con != ConEnd; ++Con) { 4869 // FIXME: In C++0x, a constructor template can be a default constructor. 4870 if (isa<FunctionTemplateDecl>(*Con)) 4871 continue; 4872 4873 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con); 4874 if (Constructor->isDefaultConstructor()) 4875 return Constructor; 4876 } 4877 return 0; 4878} 4879 4880CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 4881 CXXRecordDecl *ClassDecl) { 4882 // C++ [class.ctor]p5: 4883 // A default constructor for a class X is a constructor of class X 4884 // that can be called without an argument. If there is no 4885 // user-declared constructor for class X, a default constructor is 4886 // implicitly declared. An implicitly-declared default constructor 4887 // is an inline public member of its class. 4888 assert(!ClassDecl->hasUserDeclaredConstructor() && 4889 "Should not build implicit default constructor!"); 4890 4891 // C++ [except.spec]p14: 4892 // An implicitly declared special member function (Clause 12) shall have an 4893 // exception-specification. [...] 4894 ImplicitExceptionSpecification ExceptSpec(Context); 4895 4896 // Direct base-class constructors. 4897 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 4898 BEnd = ClassDecl->bases_end(); 4899 B != BEnd; ++B) { 4900 if (B->isVirtual()) // Handled below. 4901 continue; 4902 4903 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 4904 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 4905 if (!BaseClassDecl->hasDeclaredDefaultConstructor()) 4906 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl)); 4907 else if (CXXConstructorDecl *Constructor 4908 = getDefaultConstructorUnsafe(*this, BaseClassDecl)) 4909 ExceptSpec.CalledDecl(Constructor); 4910 } 4911 } 4912 4913 // Virtual base-class constructors. 4914 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 4915 BEnd = ClassDecl->vbases_end(); 4916 B != BEnd; ++B) { 4917 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 4918 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 4919 if (!BaseClassDecl->hasDeclaredDefaultConstructor()) 4920 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl)); 4921 else if (CXXConstructorDecl *Constructor 4922 = getDefaultConstructorUnsafe(*this, BaseClassDecl)) 4923 ExceptSpec.CalledDecl(Constructor); 4924 } 4925 } 4926 4927 // Field constructors. 4928 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 4929 FEnd = ClassDecl->field_end(); 4930 F != FEnd; ++F) { 4931 if (const RecordType *RecordTy 4932 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 4933 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 4934 if (!FieldClassDecl->hasDeclaredDefaultConstructor()) 4935 ExceptSpec.CalledDecl( 4936 DeclareImplicitDefaultConstructor(FieldClassDecl)); 4937 else if (CXXConstructorDecl *Constructor 4938 = getDefaultConstructorUnsafe(*this, FieldClassDecl)) 4939 ExceptSpec.CalledDecl(Constructor); 4940 } 4941 } 4942 4943 FunctionProtoType::ExtProtoInfo EPI; 4944 EPI.ExceptionSpecType = ExceptSpec.getExceptionSpecType(); 4945 EPI.NumExceptions = ExceptSpec.size(); 4946 EPI.Exceptions = ExceptSpec.data(); 4947 4948 // Create the actual constructor declaration. 4949 CanQualType ClassType 4950 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 4951 SourceLocation ClassLoc = ClassDecl->getLocation(); 4952 DeclarationName Name 4953 = Context.DeclarationNames.getCXXConstructorName(ClassType); 4954 DeclarationNameInfo NameInfo(Name, ClassLoc); 4955 CXXConstructorDecl *DefaultCon 4956 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 4957 Context.getFunctionType(Context.VoidTy, 4958 0, 0, EPI), 4959 /*TInfo=*/0, 4960 /*isExplicit=*/false, 4961 /*isInline=*/true, 4962 /*isImplicitlyDeclared=*/true); 4963 DefaultCon->setAccess(AS_public); 4964 DefaultCon->setImplicit(); 4965 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor()); 4966 4967 // Note that we have declared this constructor. 4968 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 4969 4970 if (Scope *S = getScopeForContext(ClassDecl)) 4971 PushOnScopeChains(DefaultCon, S, false); 4972 ClassDecl->addDecl(DefaultCon); 4973 4974 return DefaultCon; 4975} 4976 4977void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 4978 CXXConstructorDecl *Constructor) { 4979 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() && 4980 !Constructor->isUsed(false)) && 4981 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 4982 4983 CXXRecordDecl *ClassDecl = Constructor->getParent(); 4984 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 4985 4986 ImplicitlyDefinedFunctionScope Scope(*this, Constructor); 4987 DiagnosticErrorTrap Trap(Diags); 4988 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) || 4989 Trap.hasErrorOccurred()) { 4990 Diag(CurrentLocation, diag::note_member_synthesized_at) 4991 << CXXConstructor << Context.getTagDeclType(ClassDecl); 4992 Constructor->setInvalidDecl(); 4993 return; 4994 } 4995 4996 SourceLocation Loc = Constructor->getLocation(); 4997 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc)); 4998 4999 Constructor->setUsed(); 5000 MarkVTableUsed(CurrentLocation, ClassDecl); 5001 5002 if (ASTMutationListener *L = getASTMutationListener()) { 5003 L->CompletedImplicitDefinition(Constructor); 5004 } 5005} 5006 5007void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) { 5008 // We start with an initial pass over the base classes to collect those that 5009 // inherit constructors from. If there are none, we can forgo all further 5010 // processing. 5011 typedef llvm::SmallVector<const RecordType *, 4> BasesVector; 5012 BasesVector BasesToInheritFrom; 5013 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(), 5014 BaseE = ClassDecl->bases_end(); 5015 BaseIt != BaseE; ++BaseIt) { 5016 if (BaseIt->getInheritConstructors()) { 5017 QualType Base = BaseIt->getType(); 5018 if (Base->isDependentType()) { 5019 // If we inherit constructors from anything that is dependent, just 5020 // abort processing altogether. We'll get another chance for the 5021 // instantiations. 5022 return; 5023 } 5024 BasesToInheritFrom.push_back(Base->castAs<RecordType>()); 5025 } 5026 } 5027 if (BasesToInheritFrom.empty()) 5028 return; 5029 5030 // Now collect the constructors that we already have in the current class. 5031 // Those take precedence over inherited constructors. 5032 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...] 5033 // unless there is a user-declared constructor with the same signature in 5034 // the class where the using-declaration appears. 5035 llvm::SmallSet<const Type *, 8> ExistingConstructors; 5036 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(), 5037 CtorE = ClassDecl->ctor_end(); 5038 CtorIt != CtorE; ++CtorIt) { 5039 ExistingConstructors.insert( 5040 Context.getCanonicalType(CtorIt->getType()).getTypePtr()); 5041 } 5042 5043 Scope *S = getScopeForContext(ClassDecl); 5044 DeclarationName CreatedCtorName = 5045 Context.DeclarationNames.getCXXConstructorName( 5046 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified()); 5047 5048 // Now comes the true work. 5049 // First, we keep a map from constructor types to the base that introduced 5050 // them. Needed for finding conflicting constructors. We also keep the 5051 // actually inserted declarations in there, for pretty diagnostics. 5052 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo; 5053 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap; 5054 ConstructorToSourceMap InheritedConstructors; 5055 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(), 5056 BaseE = BasesToInheritFrom.end(); 5057 BaseIt != BaseE; ++BaseIt) { 5058 const RecordType *Base = *BaseIt; 5059 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified(); 5060 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl()); 5061 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(), 5062 CtorE = BaseDecl->ctor_end(); 5063 CtorIt != CtorE; ++CtorIt) { 5064 // Find the using declaration for inheriting this base's constructors. 5065 DeclarationName Name = 5066 Context.DeclarationNames.getCXXConstructorName(CanonicalBase); 5067 UsingDecl *UD = dyn_cast_or_null<UsingDecl>( 5068 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName)); 5069 SourceLocation UsingLoc = UD ? UD->getLocation() : 5070 ClassDecl->getLocation(); 5071 5072 // C++0x [class.inhctor]p1: The candidate set of inherited constructors 5073 // from the class X named in the using-declaration consists of actual 5074 // constructors and notional constructors that result from the 5075 // transformation of defaulted parameters as follows: 5076 // - all non-template default constructors of X, and 5077 // - for each non-template constructor of X that has at least one 5078 // parameter with a default argument, the set of constructors that 5079 // results from omitting any ellipsis parameter specification and 5080 // successively omitting parameters with a default argument from the 5081 // end of the parameter-type-list. 5082 CXXConstructorDecl *BaseCtor = *CtorIt; 5083 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor(); 5084 const FunctionProtoType *BaseCtorType = 5085 BaseCtor->getType()->getAs<FunctionProtoType>(); 5086 5087 for (unsigned params = BaseCtor->getMinRequiredArguments(), 5088 maxParams = BaseCtor->getNumParams(); 5089 params <= maxParams; ++params) { 5090 // Skip default constructors. They're never inherited. 5091 if (params == 0) 5092 continue; 5093 // Skip copy and move constructors for the same reason. 5094 if (CanBeCopyOrMove && params == 1) 5095 continue; 5096 5097 // Build up a function type for this particular constructor. 5098 // FIXME: The working paper does not consider that the exception spec 5099 // for the inheriting constructor might be larger than that of the 5100 // source. This code doesn't yet, either. 5101 const Type *NewCtorType; 5102 if (params == maxParams) 5103 NewCtorType = BaseCtorType; 5104 else { 5105 llvm::SmallVector<QualType, 16> Args; 5106 for (unsigned i = 0; i < params; ++i) { 5107 Args.push_back(BaseCtorType->getArgType(i)); 5108 } 5109 FunctionProtoType::ExtProtoInfo ExtInfo = 5110 BaseCtorType->getExtProtoInfo(); 5111 ExtInfo.Variadic = false; 5112 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(), 5113 Args.data(), params, ExtInfo) 5114 .getTypePtr(); 5115 } 5116 const Type *CanonicalNewCtorType = 5117 Context.getCanonicalType(NewCtorType); 5118 5119 // Now that we have the type, first check if the class already has a 5120 // constructor with this signature. 5121 if (ExistingConstructors.count(CanonicalNewCtorType)) 5122 continue; 5123 5124 // Then we check if we have already declared an inherited constructor 5125 // with this signature. 5126 std::pair<ConstructorToSourceMap::iterator, bool> result = 5127 InheritedConstructors.insert(std::make_pair( 5128 CanonicalNewCtorType, 5129 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0))); 5130 if (!result.second) { 5131 // Already in the map. If it came from a different class, that's an 5132 // error. Not if it's from the same. 5133 CanQualType PreviousBase = result.first->second.first; 5134 if (CanonicalBase != PreviousBase) { 5135 const CXXConstructorDecl *PrevCtor = result.first->second.second; 5136 const CXXConstructorDecl *PrevBaseCtor = 5137 PrevCtor->getInheritedConstructor(); 5138 assert(PrevBaseCtor && "Conflicting constructor was not inherited"); 5139 5140 Diag(UsingLoc, diag::err_using_decl_constructor_conflict); 5141 Diag(BaseCtor->getLocation(), 5142 diag::note_using_decl_constructor_conflict_current_ctor); 5143 Diag(PrevBaseCtor->getLocation(), 5144 diag::note_using_decl_constructor_conflict_previous_ctor); 5145 Diag(PrevCtor->getLocation(), 5146 diag::note_using_decl_constructor_conflict_previous_using); 5147 } 5148 continue; 5149 } 5150 5151 // OK, we're there, now add the constructor. 5152 // C++0x [class.inhctor]p8: [...] that would be performed by a 5153 // user-writtern inline constructor [...] 5154 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc); 5155 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create( 5156 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0), 5157 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true, 5158 /*ImplicitlyDeclared=*/true); 5159 NewCtor->setAccess(BaseCtor->getAccess()); 5160 5161 // Build up the parameter decls and add them. 5162 llvm::SmallVector<ParmVarDecl *, 16> ParamDecls; 5163 for (unsigned i = 0; i < params; ++i) { 5164 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor, 5165 UsingLoc, UsingLoc, 5166 /*IdentifierInfo=*/0, 5167 BaseCtorType->getArgType(i), 5168 /*TInfo=*/0, SC_None, 5169 SC_None, /*DefaultArg=*/0)); 5170 } 5171 NewCtor->setParams(ParamDecls.data(), ParamDecls.size()); 5172 NewCtor->setInheritedConstructor(BaseCtor); 5173 5174 PushOnScopeChains(NewCtor, S, false); 5175 ClassDecl->addDecl(NewCtor); 5176 result.first->second.second = NewCtor; 5177 } 5178 } 5179 } 5180} 5181 5182CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 5183 // C++ [class.dtor]p2: 5184 // If a class has no user-declared destructor, a destructor is 5185 // declared implicitly. An implicitly-declared destructor is an 5186 // inline public member of its class. 5187 5188 // C++ [except.spec]p14: 5189 // An implicitly declared special member function (Clause 12) shall have 5190 // an exception-specification. 5191 ImplicitExceptionSpecification ExceptSpec(Context); 5192 5193 // Direct base-class destructors. 5194 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 5195 BEnd = ClassDecl->bases_end(); 5196 B != BEnd; ++B) { 5197 if (B->isVirtual()) // Handled below. 5198 continue; 5199 5200 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) 5201 ExceptSpec.CalledDecl( 5202 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 5203 } 5204 5205 // Virtual base-class destructors. 5206 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 5207 BEnd = ClassDecl->vbases_end(); 5208 B != BEnd; ++B) { 5209 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) 5210 ExceptSpec.CalledDecl( 5211 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 5212 } 5213 5214 // Field destructors. 5215 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 5216 FEnd = ClassDecl->field_end(); 5217 F != FEnd; ++F) { 5218 if (const RecordType *RecordTy 5219 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) 5220 ExceptSpec.CalledDecl( 5221 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl()))); 5222 } 5223 5224 // Create the actual destructor declaration. 5225 FunctionProtoType::ExtProtoInfo EPI; 5226 EPI.ExceptionSpecType = ExceptSpec.getExceptionSpecType(); 5227 EPI.NumExceptions = ExceptSpec.size(); 5228 EPI.Exceptions = ExceptSpec.data(); 5229 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI); 5230 5231 CanQualType ClassType 5232 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 5233 SourceLocation ClassLoc = ClassDecl->getLocation(); 5234 DeclarationName Name 5235 = Context.DeclarationNames.getCXXDestructorName(ClassType); 5236 DeclarationNameInfo NameInfo(Name, ClassLoc); 5237 CXXDestructorDecl *Destructor 5238 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0, 5239 /*isInline=*/true, 5240 /*isImplicitlyDeclared=*/true); 5241 Destructor->setAccess(AS_public); 5242 Destructor->setImplicit(); 5243 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 5244 5245 // Note that we have declared this destructor. 5246 ++ASTContext::NumImplicitDestructorsDeclared; 5247 5248 // Introduce this destructor into its scope. 5249 if (Scope *S = getScopeForContext(ClassDecl)) 5250 PushOnScopeChains(Destructor, S, false); 5251 ClassDecl->addDecl(Destructor); 5252 5253 // This could be uniqued if it ever proves significant. 5254 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty)); 5255 5256 AddOverriddenMethods(ClassDecl, Destructor); 5257 5258 return Destructor; 5259} 5260 5261void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 5262 CXXDestructorDecl *Destructor) { 5263 assert((Destructor->isImplicit() && !Destructor->isUsed(false)) && 5264 "DefineImplicitDestructor - call it for implicit default dtor"); 5265 CXXRecordDecl *ClassDecl = Destructor->getParent(); 5266 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 5267 5268 if (Destructor->isInvalidDecl()) 5269 return; 5270 5271 ImplicitlyDefinedFunctionScope Scope(*this, Destructor); 5272 5273 DiagnosticErrorTrap Trap(Diags); 5274 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 5275 Destructor->getParent()); 5276 5277 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) { 5278 Diag(CurrentLocation, diag::note_member_synthesized_at) 5279 << CXXDestructor << Context.getTagDeclType(ClassDecl); 5280 5281 Destructor->setInvalidDecl(); 5282 return; 5283 } 5284 5285 SourceLocation Loc = Destructor->getLocation(); 5286 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc)); 5287 5288 Destructor->setUsed(); 5289 MarkVTableUsed(CurrentLocation, ClassDecl); 5290 5291 if (ASTMutationListener *L = getASTMutationListener()) { 5292 L->CompletedImplicitDefinition(Destructor); 5293 } 5294} 5295 5296/// \brief Builds a statement that copies the given entity from \p From to 5297/// \c To. 5298/// 5299/// This routine is used to copy the members of a class with an 5300/// implicitly-declared copy assignment operator. When the entities being 5301/// copied are arrays, this routine builds for loops to copy them. 5302/// 5303/// \param S The Sema object used for type-checking. 5304/// 5305/// \param Loc The location where the implicit copy is being generated. 5306/// 5307/// \param T The type of the expressions being copied. Both expressions must 5308/// have this type. 5309/// 5310/// \param To The expression we are copying to. 5311/// 5312/// \param From The expression we are copying from. 5313/// 5314/// \param CopyingBaseSubobject Whether we're copying a base subobject. 5315/// Otherwise, it's a non-static member subobject. 5316/// 5317/// \param Depth Internal parameter recording the depth of the recursion. 5318/// 5319/// \returns A statement or a loop that copies the expressions. 5320static StmtResult 5321BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 5322 Expr *To, Expr *From, 5323 bool CopyingBaseSubobject, unsigned Depth = 0) { 5324 // C++0x [class.copy]p30: 5325 // Each subobject is assigned in the manner appropriate to its type: 5326 // 5327 // - if the subobject is of class type, the copy assignment operator 5328 // for the class is used (as if by explicit qualification; that is, 5329 // ignoring any possible virtual overriding functions in more derived 5330 // classes); 5331 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 5332 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 5333 5334 // Look for operator=. 5335 DeclarationName Name 5336 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 5337 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 5338 S.LookupQualifiedName(OpLookup, ClassDecl, false); 5339 5340 // Filter out any result that isn't a copy-assignment operator. 5341 LookupResult::Filter F = OpLookup.makeFilter(); 5342 while (F.hasNext()) { 5343 NamedDecl *D = F.next(); 5344 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 5345 if (Method->isCopyAssignmentOperator()) 5346 continue; 5347 5348 F.erase(); 5349 } 5350 F.done(); 5351 5352 // Suppress the protected check (C++ [class.protected]) for each of the 5353 // assignment operators we found. This strange dance is required when 5354 // we're assigning via a base classes's copy-assignment operator. To 5355 // ensure that we're getting the right base class subobject (without 5356 // ambiguities), we need to cast "this" to that subobject type; to 5357 // ensure that we don't go through the virtual call mechanism, we need 5358 // to qualify the operator= name with the base class (see below). However, 5359 // this means that if the base class has a protected copy assignment 5360 // operator, the protected member access check will fail. So, we 5361 // rewrite "protected" access to "public" access in this case, since we 5362 // know by construction that we're calling from a derived class. 5363 if (CopyingBaseSubobject) { 5364 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 5365 L != LEnd; ++L) { 5366 if (L.getAccess() == AS_protected) 5367 L.setAccess(AS_public); 5368 } 5369 } 5370 5371 // Create the nested-name-specifier that will be used to qualify the 5372 // reference to operator=; this is required to suppress the virtual 5373 // call mechanism. 5374 CXXScopeSpec SS; 5375 SS.MakeTrivial(S.Context, 5376 NestedNameSpecifier::Create(S.Context, 0, false, 5377 T.getTypePtr()), 5378 Loc); 5379 5380 // Create the reference to operator=. 5381 ExprResult OpEqualRef 5382 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS, 5383 /*FirstQualifierInScope=*/0, OpLookup, 5384 /*TemplateArgs=*/0, 5385 /*SuppressQualifierCheck=*/true); 5386 if (OpEqualRef.isInvalid()) 5387 return StmtError(); 5388 5389 // Build the call to the assignment operator. 5390 5391 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0, 5392 OpEqualRef.takeAs<Expr>(), 5393 Loc, &From, 1, Loc); 5394 if (Call.isInvalid()) 5395 return StmtError(); 5396 5397 return S.Owned(Call.takeAs<Stmt>()); 5398 } 5399 5400 // - if the subobject is of scalar type, the built-in assignment 5401 // operator is used. 5402 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 5403 if (!ArrayTy) { 5404 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From); 5405 if (Assignment.isInvalid()) 5406 return StmtError(); 5407 5408 return S.Owned(Assignment.takeAs<Stmt>()); 5409 } 5410 5411 // - if the subobject is an array, each element is assigned, in the 5412 // manner appropriate to the element type; 5413 5414 // Construct a loop over the array bounds, e.g., 5415 // 5416 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 5417 // 5418 // that will copy each of the array elements. 5419 QualType SizeType = S.Context.getSizeType(); 5420 5421 // Create the iteration variable. 5422 IdentifierInfo *IterationVarName = 0; 5423 { 5424 llvm::SmallString<8> Str; 5425 llvm::raw_svector_ostream OS(Str); 5426 OS << "__i" << Depth; 5427 IterationVarName = &S.Context.Idents.get(OS.str()); 5428 } 5429 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 5430 IterationVarName, SizeType, 5431 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 5432 SC_None, SC_None); 5433 5434 // Initialize the iteration variable to zero. 5435 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 5436 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 5437 5438 // Create a reference to the iteration variable; we'll use this several 5439 // times throughout. 5440 Expr *IterationVarRef 5441 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take(); 5442 assert(IterationVarRef && "Reference to invented variable cannot fail!"); 5443 5444 // Create the DeclStmt that holds the iteration variable. 5445 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 5446 5447 // Create the comparison against the array bound. 5448 llvm::APInt Upper 5449 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 5450 Expr *Comparison 5451 = new (S.Context) BinaryOperator(IterationVarRef, 5452 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 5453 BO_NE, S.Context.BoolTy, 5454 VK_RValue, OK_Ordinary, Loc); 5455 5456 // Create the pre-increment of the iteration variable. 5457 Expr *Increment 5458 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType, 5459 VK_LValue, OK_Ordinary, Loc); 5460 5461 // Subscript the "from" and "to" expressions with the iteration variable. 5462 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc, 5463 IterationVarRef, Loc)); 5464 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc, 5465 IterationVarRef, Loc)); 5466 5467 // Build the copy for an individual element of the array. 5468 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(), 5469 To, From, CopyingBaseSubobject, 5470 Depth + 1); 5471 if (Copy.isInvalid()) 5472 return StmtError(); 5473 5474 // Construct the loop that copies all elements of this array. 5475 return S.ActOnForStmt(Loc, Loc, InitStmt, 5476 S.MakeFullExpr(Comparison), 5477 0, S.MakeFullExpr(Increment), 5478 Loc, Copy.take()); 5479} 5480 5481/// \brief Determine whether the given class has a copy assignment operator 5482/// that accepts a const-qualified argument. 5483static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) { 5484 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass); 5485 5486 if (!Class->hasDeclaredCopyAssignment()) 5487 S.DeclareImplicitCopyAssignment(Class); 5488 5489 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class)); 5490 DeclarationName OpName 5491 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 5492 5493 DeclContext::lookup_const_iterator Op, OpEnd; 5494 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) { 5495 // C++ [class.copy]p9: 5496 // A user-declared copy assignment operator is a non-static non-template 5497 // member function of class X with exactly one parameter of type X, X&, 5498 // const X&, volatile X& or const volatile X&. 5499 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op); 5500 if (!Method) 5501 continue; 5502 5503 if (Method->isStatic()) 5504 continue; 5505 if (Method->getPrimaryTemplate()) 5506 continue; 5507 const FunctionProtoType *FnType = 5508 Method->getType()->getAs<FunctionProtoType>(); 5509 assert(FnType && "Overloaded operator has no prototype."); 5510 // Don't assert on this; an invalid decl might have been left in the AST. 5511 if (FnType->getNumArgs() != 1 || FnType->isVariadic()) 5512 continue; 5513 bool AcceptsConst = true; 5514 QualType ArgType = FnType->getArgType(0); 5515 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){ 5516 ArgType = Ref->getPointeeType(); 5517 // Is it a non-const lvalue reference? 5518 if (!ArgType.isConstQualified()) 5519 AcceptsConst = false; 5520 } 5521 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType)) 5522 continue; 5523 5524 // We have a single argument of type cv X or cv X&, i.e. we've found the 5525 // copy assignment operator. Return whether it accepts const arguments. 5526 return AcceptsConst; 5527 } 5528 assert(Class->isInvalidDecl() && 5529 "No copy assignment operator declared in valid code."); 5530 return false; 5531} 5532 5533CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 5534 // Note: The following rules are largely analoguous to the copy 5535 // constructor rules. Note that virtual bases are not taken into account 5536 // for determining the argument type of the operator. Note also that 5537 // operators taking an object instead of a reference are allowed. 5538 5539 5540 // C++ [class.copy]p10: 5541 // If the class definition does not explicitly declare a copy 5542 // assignment operator, one is declared implicitly. 5543 // The implicitly-defined copy assignment operator for a class X 5544 // will have the form 5545 // 5546 // X& X::operator=(const X&) 5547 // 5548 // if 5549 bool HasConstCopyAssignment = true; 5550 5551 // -- each direct base class B of X has a copy assignment operator 5552 // whose parameter is of type const B&, const volatile B& or B, 5553 // and 5554 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 5555 BaseEnd = ClassDecl->bases_end(); 5556 HasConstCopyAssignment && Base != BaseEnd; ++Base) { 5557 assert(!Base->getType()->isDependentType() && 5558 "Cannot generate implicit members for class with dependent bases."); 5559 const CXXRecordDecl *BaseClassDecl 5560 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 5561 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl); 5562 } 5563 5564 // -- for all the nonstatic data members of X that are of a class 5565 // type M (or array thereof), each such class type has a copy 5566 // assignment operator whose parameter is of type const M&, 5567 // const volatile M& or M. 5568 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 5569 FieldEnd = ClassDecl->field_end(); 5570 HasConstCopyAssignment && Field != FieldEnd; 5571 ++Field) { 5572 QualType FieldType = Context.getBaseElementType((*Field)->getType()); 5573 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 5574 const CXXRecordDecl *FieldClassDecl 5575 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 5576 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl); 5577 } 5578 } 5579 5580 // Otherwise, the implicitly declared copy assignment operator will 5581 // have the form 5582 // 5583 // X& X::operator=(X&) 5584 QualType ArgType = Context.getTypeDeclType(ClassDecl); 5585 QualType RetType = Context.getLValueReferenceType(ArgType); 5586 if (HasConstCopyAssignment) 5587 ArgType = ArgType.withConst(); 5588 ArgType = Context.getLValueReferenceType(ArgType); 5589 5590 // C++ [except.spec]p14: 5591 // An implicitly declared special member function (Clause 12) shall have an 5592 // exception-specification. [...] 5593 ImplicitExceptionSpecification ExceptSpec(Context); 5594 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 5595 BaseEnd = ClassDecl->bases_end(); 5596 Base != BaseEnd; ++Base) { 5597 CXXRecordDecl *BaseClassDecl 5598 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 5599 5600 if (!BaseClassDecl->hasDeclaredCopyAssignment()) 5601 DeclareImplicitCopyAssignment(BaseClassDecl); 5602 5603 if (CXXMethodDecl *CopyAssign 5604 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment)) 5605 ExceptSpec.CalledDecl(CopyAssign); 5606 } 5607 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 5608 FieldEnd = ClassDecl->field_end(); 5609 Field != FieldEnd; 5610 ++Field) { 5611 QualType FieldType = Context.getBaseElementType((*Field)->getType()); 5612 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 5613 CXXRecordDecl *FieldClassDecl 5614 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 5615 5616 if (!FieldClassDecl->hasDeclaredCopyAssignment()) 5617 DeclareImplicitCopyAssignment(FieldClassDecl); 5618 5619 if (CXXMethodDecl *CopyAssign 5620 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment)) 5621 ExceptSpec.CalledDecl(CopyAssign); 5622 } 5623 } 5624 5625 // An implicitly-declared copy assignment operator is an inline public 5626 // member of its class. 5627 FunctionProtoType::ExtProtoInfo EPI; 5628 EPI.ExceptionSpecType = ExceptSpec.getExceptionSpecType(); 5629 EPI.NumExceptions = ExceptSpec.size(); 5630 EPI.Exceptions = ExceptSpec.data(); 5631 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 5632 SourceLocation ClassLoc = ClassDecl->getLocation(); 5633 DeclarationNameInfo NameInfo(Name, ClassLoc); 5634 CXXMethodDecl *CopyAssignment 5635 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 5636 Context.getFunctionType(RetType, &ArgType, 1, EPI), 5637 /*TInfo=*/0, /*isStatic=*/false, 5638 /*StorageClassAsWritten=*/SC_None, 5639 /*isInline=*/true, 5640 SourceLocation()); 5641 CopyAssignment->setAccess(AS_public); 5642 CopyAssignment->setImplicit(); 5643 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment()); 5644 5645 // Add the parameter to the operator. 5646 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 5647 ClassLoc, ClassLoc, /*Id=*/0, 5648 ArgType, /*TInfo=*/0, 5649 SC_None, 5650 SC_None, 0); 5651 CopyAssignment->setParams(&FromParam, 1); 5652 5653 // Note that we have added this copy-assignment operator. 5654 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 5655 5656 if (Scope *S = getScopeForContext(ClassDecl)) 5657 PushOnScopeChains(CopyAssignment, S, false); 5658 ClassDecl->addDecl(CopyAssignment); 5659 5660 AddOverriddenMethods(ClassDecl, CopyAssignment); 5661 return CopyAssignment; 5662} 5663 5664void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 5665 CXXMethodDecl *CopyAssignOperator) { 5666 assert((CopyAssignOperator->isImplicit() && 5667 CopyAssignOperator->isOverloadedOperator() && 5668 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 5669 !CopyAssignOperator->isUsed(false)) && 5670 "DefineImplicitCopyAssignment called for wrong function"); 5671 5672 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 5673 5674 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) { 5675 CopyAssignOperator->setInvalidDecl(); 5676 return; 5677 } 5678 5679 CopyAssignOperator->setUsed(); 5680 5681 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator); 5682 DiagnosticErrorTrap Trap(Diags); 5683 5684 // C++0x [class.copy]p30: 5685 // The implicitly-defined or explicitly-defaulted copy assignment operator 5686 // for a non-union class X performs memberwise copy assignment of its 5687 // subobjects. The direct base classes of X are assigned first, in the 5688 // order of their declaration in the base-specifier-list, and then the 5689 // immediate non-static data members of X are assigned, in the order in 5690 // which they were declared in the class definition. 5691 5692 // The statements that form the synthesized function body. 5693 ASTOwningVector<Stmt*> Statements(*this); 5694 5695 // The parameter for the "other" object, which we are copying from. 5696 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 5697 Qualifiers OtherQuals = Other->getType().getQualifiers(); 5698 QualType OtherRefType = Other->getType(); 5699 if (const LValueReferenceType *OtherRef 5700 = OtherRefType->getAs<LValueReferenceType>()) { 5701 OtherRefType = OtherRef->getPointeeType(); 5702 OtherQuals = OtherRefType.getQualifiers(); 5703 } 5704 5705 // Our location for everything implicitly-generated. 5706 SourceLocation Loc = CopyAssignOperator->getLocation(); 5707 5708 // Construct a reference to the "other" object. We'll be using this 5709 // throughout the generated ASTs. 5710 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take(); 5711 assert(OtherRef && "Reference to parameter cannot fail!"); 5712 5713 // Construct the "this" pointer. We'll be using this throughout the generated 5714 // ASTs. 5715 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>(); 5716 assert(This && "Reference to this cannot fail!"); 5717 5718 // Assign base classes. 5719 bool Invalid = false; 5720 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 5721 E = ClassDecl->bases_end(); Base != E; ++Base) { 5722 // Form the assignment: 5723 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 5724 QualType BaseType = Base->getType().getUnqualifiedType(); 5725 if (!BaseType->isRecordType()) { 5726 Invalid = true; 5727 continue; 5728 } 5729 5730 CXXCastPath BasePath; 5731 BasePath.push_back(Base); 5732 5733 // Construct the "from" expression, which is an implicit cast to the 5734 // appropriately-qualified base type. 5735 Expr *From = OtherRef; 5736 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals), 5737 CK_UncheckedDerivedToBase, 5738 VK_LValue, &BasePath).take(); 5739 5740 // Dereference "this". 5741 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 5742 5743 // Implicitly cast "this" to the appropriately-qualified base type. 5744 To = ImpCastExprToType(To.take(), 5745 Context.getCVRQualifiedType(BaseType, 5746 CopyAssignOperator->getTypeQualifiers()), 5747 CK_UncheckedDerivedToBase, 5748 VK_LValue, &BasePath); 5749 5750 // Build the copy. 5751 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType, 5752 To.get(), From, 5753 /*CopyingBaseSubobject=*/true); 5754 if (Copy.isInvalid()) { 5755 Diag(CurrentLocation, diag::note_member_synthesized_at) 5756 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 5757 CopyAssignOperator->setInvalidDecl(); 5758 return; 5759 } 5760 5761 // Success! Record the copy. 5762 Statements.push_back(Copy.takeAs<Expr>()); 5763 } 5764 5765 // \brief Reference to the __builtin_memcpy function. 5766 Expr *BuiltinMemCpyRef = 0; 5767 // \brief Reference to the __builtin_objc_memmove_collectable function. 5768 Expr *CollectableMemCpyRef = 0; 5769 5770 // Assign non-static members. 5771 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 5772 FieldEnd = ClassDecl->field_end(); 5773 Field != FieldEnd; ++Field) { 5774 // Check for members of reference type; we can't copy those. 5775 if (Field->getType()->isReferenceType()) { 5776 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 5777 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 5778 Diag(Field->getLocation(), diag::note_declared_at); 5779 Diag(CurrentLocation, diag::note_member_synthesized_at) 5780 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 5781 Invalid = true; 5782 continue; 5783 } 5784 5785 // Check for members of const-qualified, non-class type. 5786 QualType BaseType = Context.getBaseElementType(Field->getType()); 5787 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 5788 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 5789 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 5790 Diag(Field->getLocation(), diag::note_declared_at); 5791 Diag(CurrentLocation, diag::note_member_synthesized_at) 5792 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 5793 Invalid = true; 5794 continue; 5795 } 5796 5797 QualType FieldType = Field->getType().getNonReferenceType(); 5798 if (FieldType->isIncompleteArrayType()) { 5799 assert(ClassDecl->hasFlexibleArrayMember() && 5800 "Incomplete array type is not valid"); 5801 continue; 5802 } 5803 5804 // Build references to the field in the object we're copying from and to. 5805 CXXScopeSpec SS; // Intentionally empty 5806 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 5807 LookupMemberName); 5808 MemberLookup.addDecl(*Field); 5809 MemberLookup.resolveKind(); 5810 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType, 5811 Loc, /*IsArrow=*/false, 5812 SS, 0, MemberLookup, 0); 5813 ExprResult To = BuildMemberReferenceExpr(This, This->getType(), 5814 Loc, /*IsArrow=*/true, 5815 SS, 0, MemberLookup, 0); 5816 assert(!From.isInvalid() && "Implicit field reference cannot fail"); 5817 assert(!To.isInvalid() && "Implicit field reference cannot fail"); 5818 5819 // If the field should be copied with __builtin_memcpy rather than via 5820 // explicit assignments, do so. This optimization only applies for arrays 5821 // of scalars and arrays of class type with trivial copy-assignment 5822 // operators. 5823 if (FieldType->isArrayType() && 5824 (!BaseType->isRecordType() || 5825 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl()) 5826 ->hasTrivialCopyAssignment())) { 5827 // Compute the size of the memory buffer to be copied. 5828 QualType SizeType = Context.getSizeType(); 5829 llvm::APInt Size(Context.getTypeSize(SizeType), 5830 Context.getTypeSizeInChars(BaseType).getQuantity()); 5831 for (const ConstantArrayType *Array 5832 = Context.getAsConstantArrayType(FieldType); 5833 Array; 5834 Array = Context.getAsConstantArrayType(Array->getElementType())) { 5835 llvm::APInt ArraySize 5836 = Array->getSize().zextOrTrunc(Size.getBitWidth()); 5837 Size *= ArraySize; 5838 } 5839 5840 // Take the address of the field references for "from" and "to". 5841 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get()); 5842 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get()); 5843 5844 bool NeedsCollectableMemCpy = 5845 (BaseType->isRecordType() && 5846 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()); 5847 5848 if (NeedsCollectableMemCpy) { 5849 if (!CollectableMemCpyRef) { 5850 // Create a reference to the __builtin_objc_memmove_collectable function. 5851 LookupResult R(*this, 5852 &Context.Idents.get("__builtin_objc_memmove_collectable"), 5853 Loc, LookupOrdinaryName); 5854 LookupName(R, TUScope, true); 5855 5856 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>(); 5857 if (!CollectableMemCpy) { 5858 // Something went horribly wrong earlier, and we will have 5859 // complained about it. 5860 Invalid = true; 5861 continue; 5862 } 5863 5864 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy, 5865 CollectableMemCpy->getType(), 5866 VK_LValue, Loc, 0).take(); 5867 assert(CollectableMemCpyRef && "Builtin reference cannot fail"); 5868 } 5869 } 5870 // Create a reference to the __builtin_memcpy builtin function. 5871 else if (!BuiltinMemCpyRef) { 5872 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc, 5873 LookupOrdinaryName); 5874 LookupName(R, TUScope, true); 5875 5876 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>(); 5877 if (!BuiltinMemCpy) { 5878 // Something went horribly wrong earlier, and we will have complained 5879 // about it. 5880 Invalid = true; 5881 continue; 5882 } 5883 5884 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy, 5885 BuiltinMemCpy->getType(), 5886 VK_LValue, Loc, 0).take(); 5887 assert(BuiltinMemCpyRef && "Builtin reference cannot fail"); 5888 } 5889 5890 ASTOwningVector<Expr*> CallArgs(*this); 5891 CallArgs.push_back(To.takeAs<Expr>()); 5892 CallArgs.push_back(From.takeAs<Expr>()); 5893 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc)); 5894 ExprResult Call = ExprError(); 5895 if (NeedsCollectableMemCpy) 5896 Call = ActOnCallExpr(/*Scope=*/0, 5897 CollectableMemCpyRef, 5898 Loc, move_arg(CallArgs), 5899 Loc); 5900 else 5901 Call = ActOnCallExpr(/*Scope=*/0, 5902 BuiltinMemCpyRef, 5903 Loc, move_arg(CallArgs), 5904 Loc); 5905 5906 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 5907 Statements.push_back(Call.takeAs<Expr>()); 5908 continue; 5909 } 5910 5911 // Build the copy of this field. 5912 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType, 5913 To.get(), From.get(), 5914 /*CopyingBaseSubobject=*/false); 5915 if (Copy.isInvalid()) { 5916 Diag(CurrentLocation, diag::note_member_synthesized_at) 5917 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 5918 CopyAssignOperator->setInvalidDecl(); 5919 return; 5920 } 5921 5922 // Success! Record the copy. 5923 Statements.push_back(Copy.takeAs<Stmt>()); 5924 } 5925 5926 if (!Invalid) { 5927 // Add a "return *this;" 5928 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 5929 5930 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get()); 5931 if (Return.isInvalid()) 5932 Invalid = true; 5933 else { 5934 Statements.push_back(Return.takeAs<Stmt>()); 5935 5936 if (Trap.hasErrorOccurred()) { 5937 Diag(CurrentLocation, diag::note_member_synthesized_at) 5938 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 5939 Invalid = true; 5940 } 5941 } 5942 } 5943 5944 if (Invalid) { 5945 CopyAssignOperator->setInvalidDecl(); 5946 return; 5947 } 5948 5949 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements), 5950 /*isStmtExpr=*/false); 5951 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 5952 CopyAssignOperator->setBody(Body.takeAs<Stmt>()); 5953 5954 if (ASTMutationListener *L = getASTMutationListener()) { 5955 L->CompletedImplicitDefinition(CopyAssignOperator); 5956 } 5957} 5958 5959CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 5960 CXXRecordDecl *ClassDecl) { 5961 // C++ [class.copy]p4: 5962 // If the class definition does not explicitly declare a copy 5963 // constructor, one is declared implicitly. 5964 5965 // C++ [class.copy]p5: 5966 // The implicitly-declared copy constructor for a class X will 5967 // have the form 5968 // 5969 // X::X(const X&) 5970 // 5971 // if 5972 bool HasConstCopyConstructor = true; 5973 5974 // -- each direct or virtual base class B of X has a copy 5975 // constructor whose first parameter is of type const B& or 5976 // const volatile B&, and 5977 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 5978 BaseEnd = ClassDecl->bases_end(); 5979 HasConstCopyConstructor && Base != BaseEnd; 5980 ++Base) { 5981 // Virtual bases are handled below. 5982 if (Base->isVirtual()) 5983 continue; 5984 5985 CXXRecordDecl *BaseClassDecl 5986 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 5987 if (!BaseClassDecl->hasDeclaredCopyConstructor()) 5988 DeclareImplicitCopyConstructor(BaseClassDecl); 5989 5990 HasConstCopyConstructor 5991 = BaseClassDecl->hasConstCopyConstructor(Context); 5992 } 5993 5994 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 5995 BaseEnd = ClassDecl->vbases_end(); 5996 HasConstCopyConstructor && Base != BaseEnd; 5997 ++Base) { 5998 CXXRecordDecl *BaseClassDecl 5999 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 6000 if (!BaseClassDecl->hasDeclaredCopyConstructor()) 6001 DeclareImplicitCopyConstructor(BaseClassDecl); 6002 6003 HasConstCopyConstructor 6004 = BaseClassDecl->hasConstCopyConstructor(Context); 6005 } 6006 6007 // -- for all the nonstatic data members of X that are of a 6008 // class type M (or array thereof), each such class type 6009 // has a copy constructor whose first parameter is of type 6010 // const M& or const volatile M&. 6011 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 6012 FieldEnd = ClassDecl->field_end(); 6013 HasConstCopyConstructor && Field != FieldEnd; 6014 ++Field) { 6015 QualType FieldType = Context.getBaseElementType((*Field)->getType()); 6016 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 6017 CXXRecordDecl *FieldClassDecl 6018 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 6019 if (!FieldClassDecl->hasDeclaredCopyConstructor()) 6020 DeclareImplicitCopyConstructor(FieldClassDecl); 6021 6022 HasConstCopyConstructor 6023 = FieldClassDecl->hasConstCopyConstructor(Context); 6024 } 6025 } 6026 6027 // Otherwise, the implicitly declared copy constructor will have 6028 // the form 6029 // 6030 // X::X(X&) 6031 QualType ClassType = Context.getTypeDeclType(ClassDecl); 6032 QualType ArgType = ClassType; 6033 if (HasConstCopyConstructor) 6034 ArgType = ArgType.withConst(); 6035 ArgType = Context.getLValueReferenceType(ArgType); 6036 6037 // C++ [except.spec]p14: 6038 // An implicitly declared special member function (Clause 12) shall have an 6039 // exception-specification. [...] 6040 ImplicitExceptionSpecification ExceptSpec(Context); 6041 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0; 6042 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 6043 BaseEnd = ClassDecl->bases_end(); 6044 Base != BaseEnd; 6045 ++Base) { 6046 // Virtual bases are handled below. 6047 if (Base->isVirtual()) 6048 continue; 6049 6050 CXXRecordDecl *BaseClassDecl 6051 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 6052 if (!BaseClassDecl->hasDeclaredCopyConstructor()) 6053 DeclareImplicitCopyConstructor(BaseClassDecl); 6054 6055 if (CXXConstructorDecl *CopyConstructor 6056 = BaseClassDecl->getCopyConstructor(Context, Quals)) 6057 ExceptSpec.CalledDecl(CopyConstructor); 6058 } 6059 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 6060 BaseEnd = ClassDecl->vbases_end(); 6061 Base != BaseEnd; 6062 ++Base) { 6063 CXXRecordDecl *BaseClassDecl 6064 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 6065 if (!BaseClassDecl->hasDeclaredCopyConstructor()) 6066 DeclareImplicitCopyConstructor(BaseClassDecl); 6067 6068 if (CXXConstructorDecl *CopyConstructor 6069 = BaseClassDecl->getCopyConstructor(Context, Quals)) 6070 ExceptSpec.CalledDecl(CopyConstructor); 6071 } 6072 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 6073 FieldEnd = ClassDecl->field_end(); 6074 Field != FieldEnd; 6075 ++Field) { 6076 QualType FieldType = Context.getBaseElementType((*Field)->getType()); 6077 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 6078 CXXRecordDecl *FieldClassDecl 6079 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 6080 if (!FieldClassDecl->hasDeclaredCopyConstructor()) 6081 DeclareImplicitCopyConstructor(FieldClassDecl); 6082 6083 if (CXXConstructorDecl *CopyConstructor 6084 = FieldClassDecl->getCopyConstructor(Context, Quals)) 6085 ExceptSpec.CalledDecl(CopyConstructor); 6086 } 6087 } 6088 6089 // An implicitly-declared copy constructor is an inline public 6090 // member of its class. 6091 FunctionProtoType::ExtProtoInfo EPI; 6092 EPI.ExceptionSpecType = ExceptSpec.getExceptionSpecType(); 6093 EPI.NumExceptions = ExceptSpec.size(); 6094 EPI.Exceptions = ExceptSpec.data(); 6095 DeclarationName Name 6096 = Context.DeclarationNames.getCXXConstructorName( 6097 Context.getCanonicalType(ClassType)); 6098 SourceLocation ClassLoc = ClassDecl->getLocation(); 6099 DeclarationNameInfo NameInfo(Name, ClassLoc); 6100 CXXConstructorDecl *CopyConstructor 6101 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 6102 Context.getFunctionType(Context.VoidTy, 6103 &ArgType, 1, EPI), 6104 /*TInfo=*/0, 6105 /*isExplicit=*/false, 6106 /*isInline=*/true, 6107 /*isImplicitlyDeclared=*/true); 6108 CopyConstructor->setAccess(AS_public); 6109 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor()); 6110 6111 // Note that we have declared this constructor. 6112 ++ASTContext::NumImplicitCopyConstructorsDeclared; 6113 6114 // Add the parameter to the constructor. 6115 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 6116 ClassLoc, ClassLoc, 6117 /*IdentifierInfo=*/0, 6118 ArgType, /*TInfo=*/0, 6119 SC_None, 6120 SC_None, 0); 6121 CopyConstructor->setParams(&FromParam, 1); 6122 if (Scope *S = getScopeForContext(ClassDecl)) 6123 PushOnScopeChains(CopyConstructor, S, false); 6124 ClassDecl->addDecl(CopyConstructor); 6125 6126 return CopyConstructor; 6127} 6128 6129void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 6130 CXXConstructorDecl *CopyConstructor, 6131 unsigned TypeQuals) { 6132 assert((CopyConstructor->isImplicit() && 6133 CopyConstructor->isCopyConstructor(TypeQuals) && 6134 !CopyConstructor->isUsed(false)) && 6135 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 6136 6137 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 6138 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 6139 6140 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor); 6141 DiagnosticErrorTrap Trap(Diags); 6142 6143 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) || 6144 Trap.hasErrorOccurred()) { 6145 Diag(CurrentLocation, diag::note_member_synthesized_at) 6146 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl); 6147 CopyConstructor->setInvalidDecl(); 6148 } else { 6149 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(), 6150 CopyConstructor->getLocation(), 6151 MultiStmtArg(*this, 0, 0), 6152 /*isStmtExpr=*/false) 6153 .takeAs<Stmt>()); 6154 } 6155 6156 CopyConstructor->setUsed(); 6157 6158 if (ASTMutationListener *L = getASTMutationListener()) { 6159 L->CompletedImplicitDefinition(CopyConstructor); 6160 } 6161} 6162 6163ExprResult 6164Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 6165 CXXConstructorDecl *Constructor, 6166 MultiExprArg ExprArgs, 6167 bool RequiresZeroInit, 6168 unsigned ConstructKind, 6169 SourceRange ParenRange) { 6170 bool Elidable = false; 6171 6172 // C++0x [class.copy]p34: 6173 // When certain criteria are met, an implementation is allowed to 6174 // omit the copy/move construction of a class object, even if the 6175 // copy/move constructor and/or destructor for the object have 6176 // side effects. [...] 6177 // - when a temporary class object that has not been bound to a 6178 // reference (12.2) would be copied/moved to a class object 6179 // with the same cv-unqualified type, the copy/move operation 6180 // can be omitted by constructing the temporary object 6181 // directly into the target of the omitted copy/move 6182 if (ConstructKind == CXXConstructExpr::CK_Complete && 6183 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) { 6184 Expr *SubExpr = ((Expr **)ExprArgs.get())[0]; 6185 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent()); 6186 } 6187 6188 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 6189 Elidable, move(ExprArgs), RequiresZeroInit, 6190 ConstructKind, ParenRange); 6191} 6192 6193/// BuildCXXConstructExpr - Creates a complete call to a constructor, 6194/// including handling of its default argument expressions. 6195ExprResult 6196Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 6197 CXXConstructorDecl *Constructor, bool Elidable, 6198 MultiExprArg ExprArgs, 6199 bool RequiresZeroInit, 6200 unsigned ConstructKind, 6201 SourceRange ParenRange) { 6202 unsigned NumExprs = ExprArgs.size(); 6203 Expr **Exprs = (Expr **)ExprArgs.release(); 6204 6205 for (specific_attr_iterator<NonNullAttr> 6206 i = Constructor->specific_attr_begin<NonNullAttr>(), 6207 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) { 6208 const NonNullAttr *NonNull = *i; 6209 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc); 6210 } 6211 6212 MarkDeclarationReferenced(ConstructLoc, Constructor); 6213 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc, 6214 Constructor, Elidable, Exprs, NumExprs, 6215 RequiresZeroInit, 6216 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 6217 ParenRange)); 6218} 6219 6220bool Sema::InitializeVarWithConstructor(VarDecl *VD, 6221 CXXConstructorDecl *Constructor, 6222 MultiExprArg Exprs) { 6223 // FIXME: Provide the correct paren SourceRange when available. 6224 ExprResult TempResult = 6225 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor, 6226 move(Exprs), false, CXXConstructExpr::CK_Complete, 6227 SourceRange()); 6228 if (TempResult.isInvalid()) 6229 return true; 6230 6231 Expr *Temp = TempResult.takeAs<Expr>(); 6232 CheckImplicitConversions(Temp, VD->getLocation()); 6233 MarkDeclarationReferenced(VD->getLocation(), Constructor); 6234 Temp = MaybeCreateExprWithCleanups(Temp); 6235 VD->setInit(Temp); 6236 6237 return false; 6238} 6239 6240void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 6241 if (VD->isInvalidDecl()) return; 6242 6243 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 6244 if (ClassDecl->isInvalidDecl()) return; 6245 if (ClassDecl->hasTrivialDestructor()) return; 6246 if (ClassDecl->isDependentContext()) return; 6247 6248 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 6249 MarkDeclarationReferenced(VD->getLocation(), Destructor); 6250 CheckDestructorAccess(VD->getLocation(), Destructor, 6251 PDiag(diag::err_access_dtor_var) 6252 << VD->getDeclName() 6253 << VD->getType()); 6254 6255 if (!VD->hasGlobalStorage()) return; 6256 6257 // Emit warning for non-trivial dtor in global scope (a real global, 6258 // class-static, function-static). 6259 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 6260 6261 // TODO: this should be re-enabled for static locals by !CXAAtExit 6262 if (!VD->isStaticLocal()) 6263 Diag(VD->getLocation(), diag::warn_global_destructor); 6264} 6265 6266/// AddCXXDirectInitializerToDecl - This action is called immediately after 6267/// ActOnDeclarator, when a C++ direct initializer is present. 6268/// e.g: "int x(1);" 6269void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl, 6270 SourceLocation LParenLoc, 6271 MultiExprArg Exprs, 6272 SourceLocation RParenLoc, 6273 bool TypeMayContainAuto) { 6274 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions"); 6275 6276 // If there is no declaration, there was an error parsing it. Just ignore 6277 // the initializer. 6278 if (RealDecl == 0) 6279 return; 6280 6281 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 6282 if (!VDecl) { 6283 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 6284 RealDecl->setInvalidDecl(); 6285 return; 6286 } 6287 6288 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 6289 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) { 6290 // FIXME: n3225 doesn't actually seem to indicate this is ill-formed 6291 if (Exprs.size() > 1) { 6292 Diag(Exprs.get()[1]->getSourceRange().getBegin(), 6293 diag::err_auto_var_init_multiple_expressions) 6294 << VDecl->getDeclName() << VDecl->getType() 6295 << VDecl->getSourceRange(); 6296 RealDecl->setInvalidDecl(); 6297 return; 6298 } 6299 6300 Expr *Init = Exprs.get()[0]; 6301 TypeSourceInfo *DeducedType = 0; 6302 if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType)) 6303 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure) 6304 << VDecl->getDeclName() << VDecl->getType() << Init->getType() 6305 << Init->getSourceRange(); 6306 if (!DeducedType) { 6307 RealDecl->setInvalidDecl(); 6308 return; 6309 } 6310 VDecl->setTypeSourceInfo(DeducedType); 6311 VDecl->setType(DeducedType->getType()); 6312 6313 // If this is a redeclaration, check that the type we just deduced matches 6314 // the previously declared type. 6315 if (VarDecl *Old = VDecl->getPreviousDeclaration()) 6316 MergeVarDeclTypes(VDecl, Old); 6317 } 6318 6319 // We will represent direct-initialization similarly to copy-initialization: 6320 // int x(1); -as-> int x = 1; 6321 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 6322 // 6323 // Clients that want to distinguish between the two forms, can check for 6324 // direct initializer using VarDecl::hasCXXDirectInitializer(). 6325 // A major benefit is that clients that don't particularly care about which 6326 // exactly form was it (like the CodeGen) can handle both cases without 6327 // special case code. 6328 6329 // C++ 8.5p11: 6330 // The form of initialization (using parentheses or '=') is generally 6331 // insignificant, but does matter when the entity being initialized has a 6332 // class type. 6333 6334 if (!VDecl->getType()->isDependentType() && 6335 RequireCompleteType(VDecl->getLocation(), VDecl->getType(), 6336 diag::err_typecheck_decl_incomplete_type)) { 6337 VDecl->setInvalidDecl(); 6338 return; 6339 } 6340 6341 // The variable can not have an abstract class type. 6342 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 6343 diag::err_abstract_type_in_decl, 6344 AbstractVariableType)) 6345 VDecl->setInvalidDecl(); 6346 6347 const VarDecl *Def; 6348 if ((Def = VDecl->getDefinition()) && Def != VDecl) { 6349 Diag(VDecl->getLocation(), diag::err_redefinition) 6350 << VDecl->getDeclName(); 6351 Diag(Def->getLocation(), diag::note_previous_definition); 6352 VDecl->setInvalidDecl(); 6353 return; 6354 } 6355 6356 // C++ [class.static.data]p4 6357 // If a static data member is of const integral or const 6358 // enumeration type, its declaration in the class definition can 6359 // specify a constant-initializer which shall be an integral 6360 // constant expression (5.19). In that case, the member can appear 6361 // in integral constant expressions. The member shall still be 6362 // defined in a namespace scope if it is used in the program and the 6363 // namespace scope definition shall not contain an initializer. 6364 // 6365 // We already performed a redefinition check above, but for static 6366 // data members we also need to check whether there was an in-class 6367 // declaration with an initializer. 6368 const VarDecl* PrevInit = 0; 6369 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) { 6370 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName(); 6371 Diag(PrevInit->getLocation(), diag::note_previous_definition); 6372 return; 6373 } 6374 6375 bool IsDependent = false; 6376 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) { 6377 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) { 6378 VDecl->setInvalidDecl(); 6379 return; 6380 } 6381 6382 if (Exprs.get()[I]->isTypeDependent()) 6383 IsDependent = true; 6384 } 6385 6386 // If either the declaration has a dependent type or if any of the 6387 // expressions is type-dependent, we represent the initialization 6388 // via a ParenListExpr for later use during template instantiation. 6389 if (VDecl->getType()->isDependentType() || IsDependent) { 6390 // Let clients know that initialization was done with a direct initializer. 6391 VDecl->setCXXDirectInitializer(true); 6392 6393 // Store the initialization expressions as a ParenListExpr. 6394 unsigned NumExprs = Exprs.size(); 6395 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc, 6396 (Expr **)Exprs.release(), 6397 NumExprs, RParenLoc)); 6398 return; 6399 } 6400 6401 // Capture the variable that is being initialized and the style of 6402 // initialization. 6403 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 6404 6405 // FIXME: Poor source location information. 6406 InitializationKind Kind 6407 = InitializationKind::CreateDirect(VDecl->getLocation(), 6408 LParenLoc, RParenLoc); 6409 6410 InitializationSequence InitSeq(*this, Entity, Kind, 6411 Exprs.get(), Exprs.size()); 6412 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs)); 6413 if (Result.isInvalid()) { 6414 VDecl->setInvalidDecl(); 6415 return; 6416 } 6417 6418 CheckImplicitConversions(Result.get(), LParenLoc); 6419 6420 Result = MaybeCreateExprWithCleanups(Result); 6421 VDecl->setInit(Result.takeAs<Expr>()); 6422 VDecl->setCXXDirectInitializer(true); 6423 6424 CheckCompleteVariableDeclaration(VDecl); 6425} 6426 6427/// \brief Given a constructor and the set of arguments provided for the 6428/// constructor, convert the arguments and add any required default arguments 6429/// to form a proper call to this constructor. 6430/// 6431/// \returns true if an error occurred, false otherwise. 6432bool 6433Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 6434 MultiExprArg ArgsPtr, 6435 SourceLocation Loc, 6436 ASTOwningVector<Expr*> &ConvertedArgs) { 6437 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 6438 unsigned NumArgs = ArgsPtr.size(); 6439 Expr **Args = (Expr **)ArgsPtr.get(); 6440 6441 const FunctionProtoType *Proto 6442 = Constructor->getType()->getAs<FunctionProtoType>(); 6443 assert(Proto && "Constructor without a prototype?"); 6444 unsigned NumArgsInProto = Proto->getNumArgs(); 6445 6446 // If too few arguments are available, we'll fill in the rest with defaults. 6447 if (NumArgs < NumArgsInProto) 6448 ConvertedArgs.reserve(NumArgsInProto); 6449 else 6450 ConvertedArgs.reserve(NumArgs); 6451 6452 VariadicCallType CallType = 6453 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 6454 llvm::SmallVector<Expr *, 8> AllArgs; 6455 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 6456 Proto, 0, Args, NumArgs, AllArgs, 6457 CallType); 6458 for (unsigned i =0, size = AllArgs.size(); i < size; i++) 6459 ConvertedArgs.push_back(AllArgs[i]); 6460 return Invalid; 6461} 6462 6463static inline bool 6464CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 6465 const FunctionDecl *FnDecl) { 6466 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 6467 if (isa<NamespaceDecl>(DC)) { 6468 return SemaRef.Diag(FnDecl->getLocation(), 6469 diag::err_operator_new_delete_declared_in_namespace) 6470 << FnDecl->getDeclName(); 6471 } 6472 6473 if (isa<TranslationUnitDecl>(DC) && 6474 FnDecl->getStorageClass() == SC_Static) { 6475 return SemaRef.Diag(FnDecl->getLocation(), 6476 diag::err_operator_new_delete_declared_static) 6477 << FnDecl->getDeclName(); 6478 } 6479 6480 return false; 6481} 6482 6483static inline bool 6484CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 6485 CanQualType ExpectedResultType, 6486 CanQualType ExpectedFirstParamType, 6487 unsigned DependentParamTypeDiag, 6488 unsigned InvalidParamTypeDiag) { 6489 QualType ResultType = 6490 FnDecl->getType()->getAs<FunctionType>()->getResultType(); 6491 6492 // Check that the result type is not dependent. 6493 if (ResultType->isDependentType()) 6494 return SemaRef.Diag(FnDecl->getLocation(), 6495 diag::err_operator_new_delete_dependent_result_type) 6496 << FnDecl->getDeclName() << ExpectedResultType; 6497 6498 // Check that the result type is what we expect. 6499 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 6500 return SemaRef.Diag(FnDecl->getLocation(), 6501 diag::err_operator_new_delete_invalid_result_type) 6502 << FnDecl->getDeclName() << ExpectedResultType; 6503 6504 // A function template must have at least 2 parameters. 6505 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 6506 return SemaRef.Diag(FnDecl->getLocation(), 6507 diag::err_operator_new_delete_template_too_few_parameters) 6508 << FnDecl->getDeclName(); 6509 6510 // The function decl must have at least 1 parameter. 6511 if (FnDecl->getNumParams() == 0) 6512 return SemaRef.Diag(FnDecl->getLocation(), 6513 diag::err_operator_new_delete_too_few_parameters) 6514 << FnDecl->getDeclName(); 6515 6516 // Check the the first parameter type is not dependent. 6517 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 6518 if (FirstParamType->isDependentType()) 6519 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 6520 << FnDecl->getDeclName() << ExpectedFirstParamType; 6521 6522 // Check that the first parameter type is what we expect. 6523 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 6524 ExpectedFirstParamType) 6525 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 6526 << FnDecl->getDeclName() << ExpectedFirstParamType; 6527 6528 return false; 6529} 6530 6531static bool 6532CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 6533 // C++ [basic.stc.dynamic.allocation]p1: 6534 // A program is ill-formed if an allocation function is declared in a 6535 // namespace scope other than global scope or declared static in global 6536 // scope. 6537 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 6538 return true; 6539 6540 CanQualType SizeTy = 6541 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 6542 6543 // C++ [basic.stc.dynamic.allocation]p1: 6544 // The return type shall be void*. The first parameter shall have type 6545 // std::size_t. 6546 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 6547 SizeTy, 6548 diag::err_operator_new_dependent_param_type, 6549 diag::err_operator_new_param_type)) 6550 return true; 6551 6552 // C++ [basic.stc.dynamic.allocation]p1: 6553 // The first parameter shall not have an associated default argument. 6554 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 6555 return SemaRef.Diag(FnDecl->getLocation(), 6556 diag::err_operator_new_default_arg) 6557 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 6558 6559 return false; 6560} 6561 6562static bool 6563CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 6564 // C++ [basic.stc.dynamic.deallocation]p1: 6565 // A program is ill-formed if deallocation functions are declared in a 6566 // namespace scope other than global scope or declared static in global 6567 // scope. 6568 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 6569 return true; 6570 6571 // C++ [basic.stc.dynamic.deallocation]p2: 6572 // Each deallocation function shall return void and its first parameter 6573 // shall be void*. 6574 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 6575 SemaRef.Context.VoidPtrTy, 6576 diag::err_operator_delete_dependent_param_type, 6577 diag::err_operator_delete_param_type)) 6578 return true; 6579 6580 return false; 6581} 6582 6583/// CheckOverloadedOperatorDeclaration - Check whether the declaration 6584/// of this overloaded operator is well-formed. If so, returns false; 6585/// otherwise, emits appropriate diagnostics and returns true. 6586bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 6587 assert(FnDecl && FnDecl->isOverloadedOperator() && 6588 "Expected an overloaded operator declaration"); 6589 6590 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 6591 6592 // C++ [over.oper]p5: 6593 // The allocation and deallocation functions, operator new, 6594 // operator new[], operator delete and operator delete[], are 6595 // described completely in 3.7.3. The attributes and restrictions 6596 // found in the rest of this subclause do not apply to them unless 6597 // explicitly stated in 3.7.3. 6598 if (Op == OO_Delete || Op == OO_Array_Delete) 6599 return CheckOperatorDeleteDeclaration(*this, FnDecl); 6600 6601 if (Op == OO_New || Op == OO_Array_New) 6602 return CheckOperatorNewDeclaration(*this, FnDecl); 6603 6604 // C++ [over.oper]p6: 6605 // An operator function shall either be a non-static member 6606 // function or be a non-member function and have at least one 6607 // parameter whose type is a class, a reference to a class, an 6608 // enumeration, or a reference to an enumeration. 6609 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 6610 if (MethodDecl->isStatic()) 6611 return Diag(FnDecl->getLocation(), 6612 diag::err_operator_overload_static) << FnDecl->getDeclName(); 6613 } else { 6614 bool ClassOrEnumParam = false; 6615 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 6616 ParamEnd = FnDecl->param_end(); 6617 Param != ParamEnd; ++Param) { 6618 QualType ParamType = (*Param)->getType().getNonReferenceType(); 6619 if (ParamType->isDependentType() || ParamType->isRecordType() || 6620 ParamType->isEnumeralType()) { 6621 ClassOrEnumParam = true; 6622 break; 6623 } 6624 } 6625 6626 if (!ClassOrEnumParam) 6627 return Diag(FnDecl->getLocation(), 6628 diag::err_operator_overload_needs_class_or_enum) 6629 << FnDecl->getDeclName(); 6630 } 6631 6632 // C++ [over.oper]p8: 6633 // An operator function cannot have default arguments (8.3.6), 6634 // except where explicitly stated below. 6635 // 6636 // Only the function-call operator allows default arguments 6637 // (C++ [over.call]p1). 6638 if (Op != OO_Call) { 6639 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(); 6640 Param != FnDecl->param_end(); ++Param) { 6641 if ((*Param)->hasDefaultArg()) 6642 return Diag((*Param)->getLocation(), 6643 diag::err_operator_overload_default_arg) 6644 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange(); 6645 } 6646 } 6647 6648 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 6649 { false, false, false } 6650#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 6651 , { Unary, Binary, MemberOnly } 6652#include "clang/Basic/OperatorKinds.def" 6653 }; 6654 6655 bool CanBeUnaryOperator = OperatorUses[Op][0]; 6656 bool CanBeBinaryOperator = OperatorUses[Op][1]; 6657 bool MustBeMemberOperator = OperatorUses[Op][2]; 6658 6659 // C++ [over.oper]p8: 6660 // [...] Operator functions cannot have more or fewer parameters 6661 // than the number required for the corresponding operator, as 6662 // described in the rest of this subclause. 6663 unsigned NumParams = FnDecl->getNumParams() 6664 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 6665 if (Op != OO_Call && 6666 ((NumParams == 1 && !CanBeUnaryOperator) || 6667 (NumParams == 2 && !CanBeBinaryOperator) || 6668 (NumParams < 1) || (NumParams > 2))) { 6669 // We have the wrong number of parameters. 6670 unsigned ErrorKind; 6671 if (CanBeUnaryOperator && CanBeBinaryOperator) { 6672 ErrorKind = 2; // 2 -> unary or binary. 6673 } else if (CanBeUnaryOperator) { 6674 ErrorKind = 0; // 0 -> unary 6675 } else { 6676 assert(CanBeBinaryOperator && 6677 "All non-call overloaded operators are unary or binary!"); 6678 ErrorKind = 1; // 1 -> binary 6679 } 6680 6681 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 6682 << FnDecl->getDeclName() << NumParams << ErrorKind; 6683 } 6684 6685 // Overloaded operators other than operator() cannot be variadic. 6686 if (Op != OO_Call && 6687 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 6688 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 6689 << FnDecl->getDeclName(); 6690 } 6691 6692 // Some operators must be non-static member functions. 6693 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 6694 return Diag(FnDecl->getLocation(), 6695 diag::err_operator_overload_must_be_member) 6696 << FnDecl->getDeclName(); 6697 } 6698 6699 // C++ [over.inc]p1: 6700 // The user-defined function called operator++ implements the 6701 // prefix and postfix ++ operator. If this function is a member 6702 // function with no parameters, or a non-member function with one 6703 // parameter of class or enumeration type, it defines the prefix 6704 // increment operator ++ for objects of that type. If the function 6705 // is a member function with one parameter (which shall be of type 6706 // int) or a non-member function with two parameters (the second 6707 // of which shall be of type int), it defines the postfix 6708 // increment operator ++ for objects of that type. 6709 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 6710 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 6711 bool ParamIsInt = false; 6712 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>()) 6713 ParamIsInt = BT->getKind() == BuiltinType::Int; 6714 6715 if (!ParamIsInt) 6716 return Diag(LastParam->getLocation(), 6717 diag::err_operator_overload_post_incdec_must_be_int) 6718 << LastParam->getType() << (Op == OO_MinusMinus); 6719 } 6720 6721 return false; 6722} 6723 6724/// CheckLiteralOperatorDeclaration - Check whether the declaration 6725/// of this literal operator function is well-formed. If so, returns 6726/// false; otherwise, emits appropriate diagnostics and returns true. 6727bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 6728 DeclContext *DC = FnDecl->getDeclContext(); 6729 Decl::Kind Kind = DC->getDeclKind(); 6730 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace && 6731 Kind != Decl::LinkageSpec) { 6732 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 6733 << FnDecl->getDeclName(); 6734 return true; 6735 } 6736 6737 bool Valid = false; 6738 6739 // template <char...> type operator "" name() is the only valid template 6740 // signature, and the only valid signature with no parameters. 6741 if (FnDecl->param_size() == 0) { 6742 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) { 6743 // Must have only one template parameter 6744 TemplateParameterList *Params = TpDecl->getTemplateParameters(); 6745 if (Params->size() == 1) { 6746 NonTypeTemplateParmDecl *PmDecl = 6747 cast<NonTypeTemplateParmDecl>(Params->getParam(0)); 6748 6749 // The template parameter must be a char parameter pack. 6750 if (PmDecl && PmDecl->isTemplateParameterPack() && 6751 Context.hasSameType(PmDecl->getType(), Context.CharTy)) 6752 Valid = true; 6753 } 6754 } 6755 } else { 6756 // Check the first parameter 6757 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 6758 6759 QualType T = (*Param)->getType(); 6760 6761 // unsigned long long int, long double, and any character type are allowed 6762 // as the only parameters. 6763 if (Context.hasSameType(T, Context.UnsignedLongLongTy) || 6764 Context.hasSameType(T, Context.LongDoubleTy) || 6765 Context.hasSameType(T, Context.CharTy) || 6766 Context.hasSameType(T, Context.WCharTy) || 6767 Context.hasSameType(T, Context.Char16Ty) || 6768 Context.hasSameType(T, Context.Char32Ty)) { 6769 if (++Param == FnDecl->param_end()) 6770 Valid = true; 6771 goto FinishedParams; 6772 } 6773 6774 // Otherwise it must be a pointer to const; let's strip those qualifiers. 6775 const PointerType *PT = T->getAs<PointerType>(); 6776 if (!PT) 6777 goto FinishedParams; 6778 T = PT->getPointeeType(); 6779 if (!T.isConstQualified()) 6780 goto FinishedParams; 6781 T = T.getUnqualifiedType(); 6782 6783 // Move on to the second parameter; 6784 ++Param; 6785 6786 // If there is no second parameter, the first must be a const char * 6787 if (Param == FnDecl->param_end()) { 6788 if (Context.hasSameType(T, Context.CharTy)) 6789 Valid = true; 6790 goto FinishedParams; 6791 } 6792 6793 // const char *, const wchar_t*, const char16_t*, and const char32_t* 6794 // are allowed as the first parameter to a two-parameter function 6795 if (!(Context.hasSameType(T, Context.CharTy) || 6796 Context.hasSameType(T, Context.WCharTy) || 6797 Context.hasSameType(T, Context.Char16Ty) || 6798 Context.hasSameType(T, Context.Char32Ty))) 6799 goto FinishedParams; 6800 6801 // The second and final parameter must be an std::size_t 6802 T = (*Param)->getType().getUnqualifiedType(); 6803 if (Context.hasSameType(T, Context.getSizeType()) && 6804 ++Param == FnDecl->param_end()) 6805 Valid = true; 6806 } 6807 6808 // FIXME: This diagnostic is absolutely terrible. 6809FinishedParams: 6810 if (!Valid) { 6811 Diag(FnDecl->getLocation(), diag::err_literal_operator_params) 6812 << FnDecl->getDeclName(); 6813 return true; 6814 } 6815 6816 return false; 6817} 6818 6819/// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 6820/// linkage specification, including the language and (if present) 6821/// the '{'. ExternLoc is the location of the 'extern', LangLoc is 6822/// the location of the language string literal, which is provided 6823/// by Lang/StrSize. LBraceLoc, if valid, provides the location of 6824/// the '{' brace. Otherwise, this linkage specification does not 6825/// have any braces. 6826Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 6827 SourceLocation LangLoc, 6828 llvm::StringRef Lang, 6829 SourceLocation LBraceLoc) { 6830 LinkageSpecDecl::LanguageIDs Language; 6831 if (Lang == "\"C\"") 6832 Language = LinkageSpecDecl::lang_c; 6833 else if (Lang == "\"C++\"") 6834 Language = LinkageSpecDecl::lang_cxx; 6835 else { 6836 Diag(LangLoc, diag::err_bad_language); 6837 return 0; 6838 } 6839 6840 // FIXME: Add all the various semantics of linkage specifications 6841 6842 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, 6843 ExternLoc, LangLoc, Language); 6844 CurContext->addDecl(D); 6845 PushDeclContext(S, D); 6846 return D; 6847} 6848 6849/// ActOnFinishLinkageSpecification - Complete the definition of 6850/// the C++ linkage specification LinkageSpec. If RBraceLoc is 6851/// valid, it's the position of the closing '}' brace in a linkage 6852/// specification that uses braces. 6853Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 6854 Decl *LinkageSpec, 6855 SourceLocation RBraceLoc) { 6856 if (LinkageSpec) { 6857 if (RBraceLoc.isValid()) { 6858 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 6859 LSDecl->setRBraceLoc(RBraceLoc); 6860 } 6861 PopDeclContext(); 6862 } 6863 return LinkageSpec; 6864} 6865 6866/// \brief Perform semantic analysis for the variable declaration that 6867/// occurs within a C++ catch clause, returning the newly-created 6868/// variable. 6869VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 6870 TypeSourceInfo *TInfo, 6871 SourceLocation StartLoc, 6872 SourceLocation Loc, 6873 IdentifierInfo *Name) { 6874 bool Invalid = false; 6875 QualType ExDeclType = TInfo->getType(); 6876 6877 // Arrays and functions decay. 6878 if (ExDeclType->isArrayType()) 6879 ExDeclType = Context.getArrayDecayedType(ExDeclType); 6880 else if (ExDeclType->isFunctionType()) 6881 ExDeclType = Context.getPointerType(ExDeclType); 6882 6883 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 6884 // The exception-declaration shall not denote a pointer or reference to an 6885 // incomplete type, other than [cv] void*. 6886 // N2844 forbids rvalue references. 6887 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 6888 Diag(Loc, diag::err_catch_rvalue_ref); 6889 Invalid = true; 6890 } 6891 6892 // GCC allows catching pointers and references to incomplete types 6893 // as an extension; so do we, but we warn by default. 6894 6895 QualType BaseType = ExDeclType; 6896 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 6897 unsigned DK = diag::err_catch_incomplete; 6898 bool IncompleteCatchIsInvalid = true; 6899 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 6900 BaseType = Ptr->getPointeeType(); 6901 Mode = 1; 6902 DK = diag::ext_catch_incomplete_ptr; 6903 IncompleteCatchIsInvalid = false; 6904 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 6905 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 6906 BaseType = Ref->getPointeeType(); 6907 Mode = 2; 6908 DK = diag::ext_catch_incomplete_ref; 6909 IncompleteCatchIsInvalid = false; 6910 } 6911 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 6912 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) && 6913 IncompleteCatchIsInvalid) 6914 Invalid = true; 6915 6916 if (!Invalid && !ExDeclType->isDependentType() && 6917 RequireNonAbstractType(Loc, ExDeclType, 6918 diag::err_abstract_type_in_decl, 6919 AbstractVariableType)) 6920 Invalid = true; 6921 6922 // Only the non-fragile NeXT runtime currently supports C++ catches 6923 // of ObjC types, and no runtime supports catching ObjC types by value. 6924 if (!Invalid && getLangOptions().ObjC1) { 6925 QualType T = ExDeclType; 6926 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 6927 T = RT->getPointeeType(); 6928 6929 if (T->isObjCObjectType()) { 6930 Diag(Loc, diag::err_objc_object_catch); 6931 Invalid = true; 6932 } else if (T->isObjCObjectPointerType()) { 6933 if (!getLangOptions().ObjCNonFragileABI) { 6934 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile); 6935 Invalid = true; 6936 } 6937 } 6938 } 6939 6940 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 6941 ExDeclType, TInfo, SC_None, SC_None); 6942 ExDecl->setExceptionVariable(true); 6943 6944 if (!Invalid) { 6945 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 6946 // C++ [except.handle]p16: 6947 // The object declared in an exception-declaration or, if the 6948 // exception-declaration does not specify a name, a temporary (12.2) is 6949 // copy-initialized (8.5) from the exception object. [...] 6950 // The object is destroyed when the handler exits, after the destruction 6951 // of any automatic objects initialized within the handler. 6952 // 6953 // We just pretend to initialize the object with itself, then make sure 6954 // it can be destroyed later. 6955 QualType initType = ExDeclType; 6956 6957 InitializedEntity entity = 6958 InitializedEntity::InitializeVariable(ExDecl); 6959 InitializationKind initKind = 6960 InitializationKind::CreateCopy(Loc, SourceLocation()); 6961 6962 Expr *opaqueValue = 6963 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 6964 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1); 6965 ExprResult result = sequence.Perform(*this, entity, initKind, 6966 MultiExprArg(&opaqueValue, 1)); 6967 if (result.isInvalid()) 6968 Invalid = true; 6969 else { 6970 // If the constructor used was non-trivial, set this as the 6971 // "initializer". 6972 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take()); 6973 if (!construct->getConstructor()->isTrivial()) { 6974 Expr *init = MaybeCreateExprWithCleanups(construct); 6975 ExDecl->setInit(init); 6976 } 6977 6978 // And make sure it's destructable. 6979 FinalizeVarWithDestructor(ExDecl, recordType); 6980 } 6981 } 6982 } 6983 6984 if (Invalid) 6985 ExDecl->setInvalidDecl(); 6986 6987 return ExDecl; 6988} 6989 6990/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 6991/// handler. 6992Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 6993 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 6994 bool Invalid = D.isInvalidType(); 6995 6996 // Check for unexpanded parameter packs. 6997 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 6998 UPPC_ExceptionType)) { 6999 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 7000 D.getIdentifierLoc()); 7001 Invalid = true; 7002 } 7003 7004 IdentifierInfo *II = D.getIdentifier(); 7005 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 7006 LookupOrdinaryName, 7007 ForRedeclaration)) { 7008 // The scope should be freshly made just for us. There is just no way 7009 // it contains any previous declaration. 7010 assert(!S->isDeclScope(PrevDecl)); 7011 if (PrevDecl->isTemplateParameter()) { 7012 // Maybe we will complain about the shadowed template parameter. 7013 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 7014 } 7015 } 7016 7017 if (D.getCXXScopeSpec().isSet() && !Invalid) { 7018 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 7019 << D.getCXXScopeSpec().getRange(); 7020 Invalid = true; 7021 } 7022 7023 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 7024 D.getSourceRange().getBegin(), 7025 D.getIdentifierLoc(), 7026 D.getIdentifier()); 7027 if (Invalid) 7028 ExDecl->setInvalidDecl(); 7029 7030 // Add the exception declaration into this scope. 7031 if (II) 7032 PushOnScopeChains(ExDecl, S); 7033 else 7034 CurContext->addDecl(ExDecl); 7035 7036 ProcessDeclAttributes(S, ExDecl, D); 7037 return ExDecl; 7038} 7039 7040Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 7041 Expr *AssertExpr, 7042 Expr *AssertMessageExpr_, 7043 SourceLocation RParenLoc) { 7044 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_); 7045 7046 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) { 7047 llvm::APSInt Value(32); 7048 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) { 7049 Diag(StaticAssertLoc, 7050 diag::err_static_assert_expression_is_not_constant) << 7051 AssertExpr->getSourceRange(); 7052 return 0; 7053 } 7054 7055 if (Value == 0) { 7056 Diag(StaticAssertLoc, diag::err_static_assert_failed) 7057 << AssertMessage->getString() << AssertExpr->getSourceRange(); 7058 } 7059 } 7060 7061 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 7062 return 0; 7063 7064 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 7065 AssertExpr, AssertMessage, RParenLoc); 7066 7067 CurContext->addDecl(Decl); 7068 return Decl; 7069} 7070 7071/// \brief Perform semantic analysis of the given friend type declaration. 7072/// 7073/// \returns A friend declaration that. 7074FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc, 7075 TypeSourceInfo *TSInfo) { 7076 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 7077 7078 QualType T = TSInfo->getType(); 7079 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 7080 7081 if (!getLangOptions().CPlusPlus0x) { 7082 // C++03 [class.friend]p2: 7083 // An elaborated-type-specifier shall be used in a friend declaration 7084 // for a class.* 7085 // 7086 // * The class-key of the elaborated-type-specifier is required. 7087 if (!ActiveTemplateInstantiations.empty()) { 7088 // Do not complain about the form of friend template types during 7089 // template instantiation; we will already have complained when the 7090 // template was declared. 7091 } else if (!T->isElaboratedTypeSpecifier()) { 7092 // If we evaluated the type to a record type, suggest putting 7093 // a tag in front. 7094 if (const RecordType *RT = T->getAs<RecordType>()) { 7095 RecordDecl *RD = RT->getDecl(); 7096 7097 std::string InsertionText = std::string(" ") + RD->getKindName(); 7098 7099 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type) 7100 << (unsigned) RD->getTagKind() 7101 << T 7102 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc), 7103 InsertionText); 7104 } else { 7105 Diag(FriendLoc, diag::ext_nonclass_type_friend) 7106 << T 7107 << SourceRange(FriendLoc, TypeRange.getEnd()); 7108 } 7109 } else if (T->getAs<EnumType>()) { 7110 Diag(FriendLoc, diag::ext_enum_friend) 7111 << T 7112 << SourceRange(FriendLoc, TypeRange.getEnd()); 7113 } 7114 } 7115 7116 // C++0x [class.friend]p3: 7117 // If the type specifier in a friend declaration designates a (possibly 7118 // cv-qualified) class type, that class is declared as a friend; otherwise, 7119 // the friend declaration is ignored. 7120 7121 // FIXME: C++0x has some syntactic restrictions on friend type declarations 7122 // in [class.friend]p3 that we do not implement. 7123 7124 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc); 7125} 7126 7127/// Handle a friend tag declaration where the scope specifier was 7128/// templated. 7129Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 7130 unsigned TagSpec, SourceLocation TagLoc, 7131 CXXScopeSpec &SS, 7132 IdentifierInfo *Name, SourceLocation NameLoc, 7133 AttributeList *Attr, 7134 MultiTemplateParamsArg TempParamLists) { 7135 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 7136 7137 bool isExplicitSpecialization = false; 7138 bool Invalid = false; 7139 7140 if (TemplateParameterList *TemplateParams 7141 = MatchTemplateParametersToScopeSpecifier(TagLoc, SS, 7142 TempParamLists.get(), 7143 TempParamLists.size(), 7144 /*friend*/ true, 7145 isExplicitSpecialization, 7146 Invalid)) { 7147 if (TemplateParams->size() > 0) { 7148 // This is a declaration of a class template. 7149 if (Invalid) 7150 return 0; 7151 7152 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, 7153 SS, Name, NameLoc, Attr, 7154 TemplateParams, AS_public, 7155 TempParamLists.size() - 1, 7156 (TemplateParameterList**) TempParamLists.release()).take(); 7157 } else { 7158 // The "template<>" header is extraneous. 7159 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 7160 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 7161 isExplicitSpecialization = true; 7162 } 7163 } 7164 7165 if (Invalid) return 0; 7166 7167 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 7168 7169 bool isAllExplicitSpecializations = true; 7170 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 7171 if (TempParamLists.get()[I]->size()) { 7172 isAllExplicitSpecializations = false; 7173 break; 7174 } 7175 } 7176 7177 // FIXME: don't ignore attributes. 7178 7179 // If it's explicit specializations all the way down, just forget 7180 // about the template header and build an appropriate non-templated 7181 // friend. TODO: for source fidelity, remember the headers. 7182 if (isAllExplicitSpecializations) { 7183 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 7184 ElaboratedTypeKeyword Keyword 7185 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 7186 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 7187 *Name, NameLoc); 7188 if (T.isNull()) 7189 return 0; 7190 7191 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 7192 if (isa<DependentNameType>(T)) { 7193 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc()); 7194 TL.setKeywordLoc(TagLoc); 7195 TL.setQualifierLoc(QualifierLoc); 7196 TL.setNameLoc(NameLoc); 7197 } else { 7198 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc()); 7199 TL.setKeywordLoc(TagLoc); 7200 TL.setQualifierLoc(QualifierLoc); 7201 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc); 7202 } 7203 7204 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 7205 TSI, FriendLoc); 7206 Friend->setAccess(AS_public); 7207 CurContext->addDecl(Friend); 7208 return Friend; 7209 } 7210 7211 // Handle the case of a templated-scope friend class. e.g. 7212 // template <class T> class A<T>::B; 7213 // FIXME: we don't support these right now. 7214 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 7215 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 7216 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 7217 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc()); 7218 TL.setKeywordLoc(TagLoc); 7219 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 7220 TL.setNameLoc(NameLoc); 7221 7222 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 7223 TSI, FriendLoc); 7224 Friend->setAccess(AS_public); 7225 Friend->setUnsupportedFriend(true); 7226 CurContext->addDecl(Friend); 7227 return Friend; 7228} 7229 7230 7231/// Handle a friend type declaration. This works in tandem with 7232/// ActOnTag. 7233/// 7234/// Notes on friend class templates: 7235/// 7236/// We generally treat friend class declarations as if they were 7237/// declaring a class. So, for example, the elaborated type specifier 7238/// in a friend declaration is required to obey the restrictions of a 7239/// class-head (i.e. no typedefs in the scope chain), template 7240/// parameters are required to match up with simple template-ids, &c. 7241/// However, unlike when declaring a template specialization, it's 7242/// okay to refer to a template specialization without an empty 7243/// template parameter declaration, e.g. 7244/// friend class A<T>::B<unsigned>; 7245/// We permit this as a special case; if there are any template 7246/// parameters present at all, require proper matching, i.e. 7247/// template <> template <class T> friend class A<int>::B; 7248Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 7249 MultiTemplateParamsArg TempParams) { 7250 SourceLocation Loc = DS.getSourceRange().getBegin(); 7251 7252 assert(DS.isFriendSpecified()); 7253 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 7254 7255 // Try to convert the decl specifier to a type. This works for 7256 // friend templates because ActOnTag never produces a ClassTemplateDecl 7257 // for a TUK_Friend. 7258 Declarator TheDeclarator(DS, Declarator::MemberContext); 7259 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 7260 QualType T = TSI->getType(); 7261 if (TheDeclarator.isInvalidType()) 7262 return 0; 7263 7264 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 7265 return 0; 7266 7267 // This is definitely an error in C++98. It's probably meant to 7268 // be forbidden in C++0x, too, but the specification is just 7269 // poorly written. 7270 // 7271 // The problem is with declarations like the following: 7272 // template <T> friend A<T>::foo; 7273 // where deciding whether a class C is a friend or not now hinges 7274 // on whether there exists an instantiation of A that causes 7275 // 'foo' to equal C. There are restrictions on class-heads 7276 // (which we declare (by fiat) elaborated friend declarations to 7277 // be) that makes this tractable. 7278 // 7279 // FIXME: handle "template <> friend class A<T>;", which 7280 // is possibly well-formed? Who even knows? 7281 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 7282 Diag(Loc, diag::err_tagless_friend_type_template) 7283 << DS.getSourceRange(); 7284 return 0; 7285 } 7286 7287 // C++98 [class.friend]p1: A friend of a class is a function 7288 // or class that is not a member of the class . . . 7289 // This is fixed in DR77, which just barely didn't make the C++03 7290 // deadline. It's also a very silly restriction that seriously 7291 // affects inner classes and which nobody else seems to implement; 7292 // thus we never diagnose it, not even in -pedantic. 7293 // 7294 // But note that we could warn about it: it's always useless to 7295 // friend one of your own members (it's not, however, worthless to 7296 // friend a member of an arbitrary specialization of your template). 7297 7298 Decl *D; 7299 if (unsigned NumTempParamLists = TempParams.size()) 7300 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 7301 NumTempParamLists, 7302 TempParams.release(), 7303 TSI, 7304 DS.getFriendSpecLoc()); 7305 else 7306 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI); 7307 7308 if (!D) 7309 return 0; 7310 7311 D->setAccess(AS_public); 7312 CurContext->addDecl(D); 7313 7314 return D; 7315} 7316 7317Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition, 7318 MultiTemplateParamsArg TemplateParams) { 7319 const DeclSpec &DS = D.getDeclSpec(); 7320 7321 assert(DS.isFriendSpecified()); 7322 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 7323 7324 SourceLocation Loc = D.getIdentifierLoc(); 7325 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 7326 QualType T = TInfo->getType(); 7327 7328 // C++ [class.friend]p1 7329 // A friend of a class is a function or class.... 7330 // Note that this sees through typedefs, which is intended. 7331 // It *doesn't* see through dependent types, which is correct 7332 // according to [temp.arg.type]p3: 7333 // If a declaration acquires a function type through a 7334 // type dependent on a template-parameter and this causes 7335 // a declaration that does not use the syntactic form of a 7336 // function declarator to have a function type, the program 7337 // is ill-formed. 7338 if (!T->isFunctionType()) { 7339 Diag(Loc, diag::err_unexpected_friend); 7340 7341 // It might be worthwhile to try to recover by creating an 7342 // appropriate declaration. 7343 return 0; 7344 } 7345 7346 // C++ [namespace.memdef]p3 7347 // - If a friend declaration in a non-local class first declares a 7348 // class or function, the friend class or function is a member 7349 // of the innermost enclosing namespace. 7350 // - The name of the friend is not found by simple name lookup 7351 // until a matching declaration is provided in that namespace 7352 // scope (either before or after the class declaration granting 7353 // friendship). 7354 // - If a friend function is called, its name may be found by the 7355 // name lookup that considers functions from namespaces and 7356 // classes associated with the types of the function arguments. 7357 // - When looking for a prior declaration of a class or a function 7358 // declared as a friend, scopes outside the innermost enclosing 7359 // namespace scope are not considered. 7360 7361 CXXScopeSpec &SS = D.getCXXScopeSpec(); 7362 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 7363 DeclarationName Name = NameInfo.getName(); 7364 assert(Name); 7365 7366 // Check for unexpanded parameter packs. 7367 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 7368 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 7369 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 7370 return 0; 7371 7372 // The context we found the declaration in, or in which we should 7373 // create the declaration. 7374 DeclContext *DC; 7375 Scope *DCScope = S; 7376 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 7377 ForRedeclaration); 7378 7379 // FIXME: there are different rules in local classes 7380 7381 // There are four cases here. 7382 // - There's no scope specifier, in which case we just go to the 7383 // appropriate scope and look for a function or function template 7384 // there as appropriate. 7385 // Recover from invalid scope qualifiers as if they just weren't there. 7386 if (SS.isInvalid() || !SS.isSet()) { 7387 // C++0x [namespace.memdef]p3: 7388 // If the name in a friend declaration is neither qualified nor 7389 // a template-id and the declaration is a function or an 7390 // elaborated-type-specifier, the lookup to determine whether 7391 // the entity has been previously declared shall not consider 7392 // any scopes outside the innermost enclosing namespace. 7393 // C++0x [class.friend]p11: 7394 // If a friend declaration appears in a local class and the name 7395 // specified is an unqualified name, a prior declaration is 7396 // looked up without considering scopes that are outside the 7397 // innermost enclosing non-class scope. For a friend function 7398 // declaration, if there is no prior declaration, the program is 7399 // ill-formed. 7400 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass(); 7401 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 7402 7403 // Find the appropriate context according to the above. 7404 DC = CurContext; 7405 while (true) { 7406 // Skip class contexts. If someone can cite chapter and verse 7407 // for this behavior, that would be nice --- it's what GCC and 7408 // EDG do, and it seems like a reasonable intent, but the spec 7409 // really only says that checks for unqualified existing 7410 // declarations should stop at the nearest enclosing namespace, 7411 // not that they should only consider the nearest enclosing 7412 // namespace. 7413 while (DC->isRecord()) 7414 DC = DC->getParent(); 7415 7416 LookupQualifiedName(Previous, DC); 7417 7418 // TODO: decide what we think about using declarations. 7419 if (isLocal || !Previous.empty()) 7420 break; 7421 7422 if (isTemplateId) { 7423 if (isa<TranslationUnitDecl>(DC)) break; 7424 } else { 7425 if (DC->isFileContext()) break; 7426 } 7427 DC = DC->getParent(); 7428 } 7429 7430 // C++ [class.friend]p1: A friend of a class is a function or 7431 // class that is not a member of the class . . . 7432 // C++0x changes this for both friend types and functions. 7433 // Most C++ 98 compilers do seem to give an error here, so 7434 // we do, too. 7435 if (!Previous.empty() && DC->Equals(CurContext) 7436 && !getLangOptions().CPlusPlus0x) 7437 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member); 7438 7439 DCScope = getScopeForDeclContext(S, DC); 7440 7441 // - There's a non-dependent scope specifier, in which case we 7442 // compute it and do a previous lookup there for a function 7443 // or function template. 7444 } else if (!SS.getScopeRep()->isDependent()) { 7445 DC = computeDeclContext(SS); 7446 if (!DC) return 0; 7447 7448 if (RequireCompleteDeclContext(SS, DC)) return 0; 7449 7450 LookupQualifiedName(Previous, DC); 7451 7452 // Ignore things found implicitly in the wrong scope. 7453 // TODO: better diagnostics for this case. Suggesting the right 7454 // qualified scope would be nice... 7455 LookupResult::Filter F = Previous.makeFilter(); 7456 while (F.hasNext()) { 7457 NamedDecl *D = F.next(); 7458 if (!DC->InEnclosingNamespaceSetOf( 7459 D->getDeclContext()->getRedeclContext())) 7460 F.erase(); 7461 } 7462 F.done(); 7463 7464 if (Previous.empty()) { 7465 D.setInvalidType(); 7466 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T; 7467 return 0; 7468 } 7469 7470 // C++ [class.friend]p1: A friend of a class is a function or 7471 // class that is not a member of the class . . . 7472 if (DC->Equals(CurContext)) 7473 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member); 7474 7475 // - There's a scope specifier that does not match any template 7476 // parameter lists, in which case we use some arbitrary context, 7477 // create a method or method template, and wait for instantiation. 7478 // - There's a scope specifier that does match some template 7479 // parameter lists, which we don't handle right now. 7480 } else { 7481 DC = CurContext; 7482 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 7483 } 7484 7485 if (!DC->isRecord()) { 7486 // This implies that it has to be an operator or function. 7487 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName || 7488 D.getName().getKind() == UnqualifiedId::IK_DestructorName || 7489 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) { 7490 Diag(Loc, diag::err_introducing_special_friend) << 7491 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 : 7492 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2); 7493 return 0; 7494 } 7495 } 7496 7497 bool Redeclaration = false; 7498 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous, 7499 move(TemplateParams), 7500 IsDefinition, 7501 Redeclaration); 7502 if (!ND) return 0; 7503 7504 assert(ND->getDeclContext() == DC); 7505 assert(ND->getLexicalDeclContext() == CurContext); 7506 7507 // Add the function declaration to the appropriate lookup tables, 7508 // adjusting the redeclarations list as necessary. We don't 7509 // want to do this yet if the friending class is dependent. 7510 // 7511 // Also update the scope-based lookup if the target context's 7512 // lookup context is in lexical scope. 7513 if (!CurContext->isDependentContext()) { 7514 DC = DC->getRedeclContext(); 7515 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false); 7516 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 7517 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 7518 } 7519 7520 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 7521 D.getIdentifierLoc(), ND, 7522 DS.getFriendSpecLoc()); 7523 FrD->setAccess(AS_public); 7524 CurContext->addDecl(FrD); 7525 7526 if (ND->isInvalidDecl()) 7527 FrD->setInvalidDecl(); 7528 else { 7529 FunctionDecl *FD; 7530 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 7531 FD = FTD->getTemplatedDecl(); 7532 else 7533 FD = cast<FunctionDecl>(ND); 7534 7535 // Mark templated-scope function declarations as unsupported. 7536 if (FD->getNumTemplateParameterLists()) 7537 FrD->setUnsupportedFriend(true); 7538 } 7539 7540 return ND; 7541} 7542 7543void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 7544 AdjustDeclIfTemplate(Dcl); 7545 7546 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl); 7547 if (!Fn) { 7548 Diag(DelLoc, diag::err_deleted_non_function); 7549 return; 7550 } 7551 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) { 7552 Diag(DelLoc, diag::err_deleted_decl_not_first); 7553 Diag(Prev->getLocation(), diag::note_previous_declaration); 7554 // If the declaration wasn't the first, we delete the function anyway for 7555 // recovery. 7556 } 7557 Fn->setDeleted(); 7558} 7559 7560static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 7561 for (Stmt::child_range CI = S->children(); CI; ++CI) { 7562 Stmt *SubStmt = *CI; 7563 if (!SubStmt) 7564 continue; 7565 if (isa<ReturnStmt>(SubStmt)) 7566 Self.Diag(SubStmt->getSourceRange().getBegin(), 7567 diag::err_return_in_constructor_handler); 7568 if (!isa<Expr>(SubStmt)) 7569 SearchForReturnInStmt(Self, SubStmt); 7570 } 7571} 7572 7573void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 7574 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 7575 CXXCatchStmt *Handler = TryBlock->getHandler(I); 7576 SearchForReturnInStmt(*this, Handler); 7577 } 7578} 7579 7580bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 7581 const CXXMethodDecl *Old) { 7582 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType(); 7583 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType(); 7584 7585 if (Context.hasSameType(NewTy, OldTy) || 7586 NewTy->isDependentType() || OldTy->isDependentType()) 7587 return false; 7588 7589 // Check if the return types are covariant 7590 QualType NewClassTy, OldClassTy; 7591 7592 /// Both types must be pointers or references to classes. 7593 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 7594 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 7595 NewClassTy = NewPT->getPointeeType(); 7596 OldClassTy = OldPT->getPointeeType(); 7597 } 7598 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 7599 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 7600 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 7601 NewClassTy = NewRT->getPointeeType(); 7602 OldClassTy = OldRT->getPointeeType(); 7603 } 7604 } 7605 } 7606 7607 // The return types aren't either both pointers or references to a class type. 7608 if (NewClassTy.isNull()) { 7609 Diag(New->getLocation(), 7610 diag::err_different_return_type_for_overriding_virtual_function) 7611 << New->getDeclName() << NewTy << OldTy; 7612 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 7613 7614 return true; 7615 } 7616 7617 // C++ [class.virtual]p6: 7618 // If the return type of D::f differs from the return type of B::f, the 7619 // class type in the return type of D::f shall be complete at the point of 7620 // declaration of D::f or shall be the class type D. 7621 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 7622 if (!RT->isBeingDefined() && 7623 RequireCompleteType(New->getLocation(), NewClassTy, 7624 PDiag(diag::err_covariant_return_incomplete) 7625 << New->getDeclName())) 7626 return true; 7627 } 7628 7629 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 7630 // Check if the new class derives from the old class. 7631 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 7632 Diag(New->getLocation(), 7633 diag::err_covariant_return_not_derived) 7634 << New->getDeclName() << NewTy << OldTy; 7635 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 7636 return true; 7637 } 7638 7639 // Check if we the conversion from derived to base is valid. 7640 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy, 7641 diag::err_covariant_return_inaccessible_base, 7642 diag::err_covariant_return_ambiguous_derived_to_base_conv, 7643 // FIXME: Should this point to the return type? 7644 New->getLocation(), SourceRange(), New->getDeclName(), 0)) { 7645 // FIXME: this note won't trigger for delayed access control 7646 // diagnostics, and it's impossible to get an undelayed error 7647 // here from access control during the original parse because 7648 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 7649 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 7650 return true; 7651 } 7652 } 7653 7654 // The qualifiers of the return types must be the same. 7655 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 7656 Diag(New->getLocation(), 7657 diag::err_covariant_return_type_different_qualifications) 7658 << New->getDeclName() << NewTy << OldTy; 7659 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 7660 return true; 7661 }; 7662 7663 7664 // The new class type must have the same or less qualifiers as the old type. 7665 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 7666 Diag(New->getLocation(), 7667 diag::err_covariant_return_type_class_type_more_qualified) 7668 << New->getDeclName() << NewTy << OldTy; 7669 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 7670 return true; 7671 }; 7672 7673 return false; 7674} 7675 7676/// \brief Mark the given method pure. 7677/// 7678/// \param Method the method to be marked pure. 7679/// 7680/// \param InitRange the source range that covers the "0" initializer. 7681bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 7682 SourceLocation EndLoc = InitRange.getEnd(); 7683 if (EndLoc.isValid()) 7684 Method->setRangeEnd(EndLoc); 7685 7686 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 7687 Method->setPure(); 7688 return false; 7689 } 7690 7691 if (!Method->isInvalidDecl()) 7692 Diag(Method->getLocation(), diag::err_non_virtual_pure) 7693 << Method->getDeclName() << InitRange; 7694 return true; 7695} 7696 7697/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 7698/// an initializer for the out-of-line declaration 'Dcl'. The scope 7699/// is a fresh scope pushed for just this purpose. 7700/// 7701/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 7702/// static data member of class X, names should be looked up in the scope of 7703/// class X. 7704void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 7705 // If there is no declaration, there was an error parsing it. 7706 if (D == 0 || D->isInvalidDecl()) return; 7707 7708 // We should only get called for declarations with scope specifiers, like: 7709 // int foo::bar; 7710 assert(D->isOutOfLine()); 7711 EnterDeclaratorContext(S, D->getDeclContext()); 7712} 7713 7714/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 7715/// initializer for the out-of-line declaration 'D'. 7716void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 7717 // If there is no declaration, there was an error parsing it. 7718 if (D == 0 || D->isInvalidDecl()) return; 7719 7720 assert(D->isOutOfLine()); 7721 ExitDeclaratorContext(S); 7722} 7723 7724/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 7725/// C++ if/switch/while/for statement. 7726/// e.g: "if (int x = f()) {...}" 7727DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 7728 // C++ 6.4p2: 7729 // The declarator shall not specify a function or an array. 7730 // The type-specifier-seq shall not contain typedef and shall not declare a 7731 // new class or enumeration. 7732 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 7733 "Parser allowed 'typedef' as storage class of condition decl."); 7734 7735 TagDecl *OwnedTag = 0; 7736 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag); 7737 QualType Ty = TInfo->getType(); 7738 7739 if (Ty->isFunctionType()) { // The declarator shall not specify a function... 7740 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl 7741 // would be created and CXXConditionDeclExpr wants a VarDecl. 7742 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type) 7743 << D.getSourceRange(); 7744 return DeclResult(); 7745 } else if (OwnedTag && OwnedTag->isDefinition()) { 7746 // The type-specifier-seq shall not declare a new class or enumeration. 7747 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition); 7748 } 7749 7750 Decl *Dcl = ActOnDeclarator(S, D); 7751 if (!Dcl) 7752 return DeclResult(); 7753 7754 return Dcl; 7755} 7756 7757void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 7758 bool DefinitionRequired) { 7759 // Ignore any vtable uses in unevaluated operands or for classes that do 7760 // not have a vtable. 7761 if (!Class->isDynamicClass() || Class->isDependentContext() || 7762 CurContext->isDependentContext() || 7763 ExprEvalContexts.back().Context == Unevaluated) 7764 return; 7765 7766 // Try to insert this class into the map. 7767 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 7768 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 7769 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 7770 if (!Pos.second) { 7771 // If we already had an entry, check to see if we are promoting this vtable 7772 // to required a definition. If so, we need to reappend to the VTableUses 7773 // list, since we may have already processed the first entry. 7774 if (DefinitionRequired && !Pos.first->second) { 7775 Pos.first->second = true; 7776 } else { 7777 // Otherwise, we can early exit. 7778 return; 7779 } 7780 } 7781 7782 // Local classes need to have their virtual members marked 7783 // immediately. For all other classes, we mark their virtual members 7784 // at the end of the translation unit. 7785 if (Class->isLocalClass()) 7786 MarkVirtualMembersReferenced(Loc, Class); 7787 else 7788 VTableUses.push_back(std::make_pair(Class, Loc)); 7789} 7790 7791bool Sema::DefineUsedVTables() { 7792 if (VTableUses.empty()) 7793 return false; 7794 7795 // Note: The VTableUses vector could grow as a result of marking 7796 // the members of a class as "used", so we check the size each 7797 // time through the loop and prefer indices (with are stable) to 7798 // iterators (which are not). 7799 bool DefinedAnything = false; 7800 for (unsigned I = 0; I != VTableUses.size(); ++I) { 7801 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 7802 if (!Class) 7803 continue; 7804 7805 SourceLocation Loc = VTableUses[I].second; 7806 7807 // If this class has a key function, but that key function is 7808 // defined in another translation unit, we don't need to emit the 7809 // vtable even though we're using it. 7810 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class); 7811 if (KeyFunction && !KeyFunction->hasBody()) { 7812 switch (KeyFunction->getTemplateSpecializationKind()) { 7813 case TSK_Undeclared: 7814 case TSK_ExplicitSpecialization: 7815 case TSK_ExplicitInstantiationDeclaration: 7816 // The key function is in another translation unit. 7817 continue; 7818 7819 case TSK_ExplicitInstantiationDefinition: 7820 case TSK_ImplicitInstantiation: 7821 // We will be instantiating the key function. 7822 break; 7823 } 7824 } else if (!KeyFunction) { 7825 // If we have a class with no key function that is the subject 7826 // of an explicit instantiation declaration, suppress the 7827 // vtable; it will live with the explicit instantiation 7828 // definition. 7829 bool IsExplicitInstantiationDeclaration 7830 = Class->getTemplateSpecializationKind() 7831 == TSK_ExplicitInstantiationDeclaration; 7832 for (TagDecl::redecl_iterator R = Class->redecls_begin(), 7833 REnd = Class->redecls_end(); 7834 R != REnd; ++R) { 7835 TemplateSpecializationKind TSK 7836 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind(); 7837 if (TSK == TSK_ExplicitInstantiationDeclaration) 7838 IsExplicitInstantiationDeclaration = true; 7839 else if (TSK == TSK_ExplicitInstantiationDefinition) { 7840 IsExplicitInstantiationDeclaration = false; 7841 break; 7842 } 7843 } 7844 7845 if (IsExplicitInstantiationDeclaration) 7846 continue; 7847 } 7848 7849 // Mark all of the virtual members of this class as referenced, so 7850 // that we can build a vtable. Then, tell the AST consumer that a 7851 // vtable for this class is required. 7852 DefinedAnything = true; 7853 MarkVirtualMembersReferenced(Loc, Class); 7854 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 7855 Consumer.HandleVTable(Class, VTablesUsed[Canonical]); 7856 7857 // Optionally warn if we're emitting a weak vtable. 7858 if (Class->getLinkage() == ExternalLinkage && 7859 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) { 7860 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined())) 7861 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class; 7862 } 7863 } 7864 VTableUses.clear(); 7865 7866 return DefinedAnything; 7867} 7868 7869void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 7870 const CXXRecordDecl *RD) { 7871 for (CXXRecordDecl::method_iterator i = RD->method_begin(), 7872 e = RD->method_end(); i != e; ++i) { 7873 CXXMethodDecl *MD = *i; 7874 7875 // C++ [basic.def.odr]p2: 7876 // [...] A virtual member function is used if it is not pure. [...] 7877 if (MD->isVirtual() && !MD->isPure()) 7878 MarkDeclarationReferenced(Loc, MD); 7879 } 7880 7881 // Only classes that have virtual bases need a VTT. 7882 if (RD->getNumVBases() == 0) 7883 return; 7884 7885 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(), 7886 e = RD->bases_end(); i != e; ++i) { 7887 const CXXRecordDecl *Base = 7888 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl()); 7889 if (Base->getNumVBases() == 0) 7890 continue; 7891 MarkVirtualMembersReferenced(Loc, Base); 7892 } 7893} 7894 7895/// SetIvarInitializers - This routine builds initialization ASTs for the 7896/// Objective-C implementation whose ivars need be initialized. 7897void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 7898 if (!getLangOptions().CPlusPlus) 7899 return; 7900 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 7901 llvm::SmallVector<ObjCIvarDecl*, 8> ivars; 7902 CollectIvarsToConstructOrDestruct(OID, ivars); 7903 if (ivars.empty()) 7904 return; 7905 llvm::SmallVector<CXXCtorInitializer*, 32> AllToInit; 7906 for (unsigned i = 0; i < ivars.size(); i++) { 7907 FieldDecl *Field = ivars[i]; 7908 if (Field->isInvalidDecl()) 7909 continue; 7910 7911 CXXCtorInitializer *Member; 7912 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 7913 InitializationKind InitKind = 7914 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 7915 7916 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0); 7917 ExprResult MemberInit = 7918 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg()); 7919 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 7920 // Note, MemberInit could actually come back empty if no initialization 7921 // is required (e.g., because it would call a trivial default constructor) 7922 if (!MemberInit.get() || MemberInit.isInvalid()) 7923 continue; 7924 7925 Member = 7926 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 7927 SourceLocation(), 7928 MemberInit.takeAs<Expr>(), 7929 SourceLocation()); 7930 AllToInit.push_back(Member); 7931 7932 // Be sure that the destructor is accessible and is marked as referenced. 7933 if (const RecordType *RecordTy 7934 = Context.getBaseElementType(Field->getType()) 7935 ->getAs<RecordType>()) { 7936 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 7937 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 7938 MarkDeclarationReferenced(Field->getLocation(), Destructor); 7939 CheckDestructorAccess(Field->getLocation(), Destructor, 7940 PDiag(diag::err_access_dtor_ivar) 7941 << Context.getBaseElementType(Field->getType())); 7942 } 7943 } 7944 } 7945 ObjCImplementation->setIvarInitializers(Context, 7946 AllToInit.data(), AllToInit.size()); 7947 } 7948} 7949