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