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