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