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