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