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