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