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