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