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