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