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