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