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