SemaDeclCXX.cpp revision 6bc9768408d4b45e00350018b6e3540bc05d267d
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 "Lookup.h" 16#include "clang/AST/ASTConsumer.h" 17#include "clang/AST/ASTContext.h" 18#include "clang/AST/CXXInheritance.h" 19#include "clang/AST/DeclVisitor.h" 20#include "clang/AST/TypeOrdering.h" 21#include "clang/AST/StmtVisitor.h" 22#include "clang/Parse/DeclSpec.h" 23#include "clang/Parse/Template.h" 24#include "clang/Basic/PartialDiagnostic.h" 25#include "clang/Lex/Preprocessor.h" 26#include "llvm/ADT/STLExtras.h" 27#include <map> 28#include <set> 29 30using namespace clang; 31 32//===----------------------------------------------------------------------===// 33// CheckDefaultArgumentVisitor 34//===----------------------------------------------------------------------===// 35 36namespace { 37 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 38 /// the default argument of a parameter to determine whether it 39 /// contains any ill-formed subexpressions. For example, this will 40 /// diagnose the use of local variables or parameters within the 41 /// default argument expression. 42 class CheckDefaultArgumentVisitor 43 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 44 Expr *DefaultArg; 45 Sema *S; 46 47 public: 48 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 49 : DefaultArg(defarg), S(s) {} 50 51 bool VisitExpr(Expr *Node); 52 bool VisitDeclRefExpr(DeclRefExpr *DRE); 53 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 54 }; 55 56 /// VisitExpr - Visit all of the children of this expression. 57 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 58 bool IsInvalid = false; 59 for (Stmt::child_iterator I = Node->child_begin(), 60 E = Node->child_end(); I != E; ++I) 61 IsInvalid |= Visit(*I); 62 return IsInvalid; 63 } 64 65 /// VisitDeclRefExpr - Visit a reference to a declaration, to 66 /// determine whether this declaration can be used in the default 67 /// argument expression. 68 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 69 NamedDecl *Decl = DRE->getDecl(); 70 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 71 // C++ [dcl.fct.default]p9 72 // Default arguments are evaluated each time the function is 73 // called. The order of evaluation of function arguments is 74 // unspecified. Consequently, parameters of a function shall not 75 // be used in default argument expressions, even if they are not 76 // evaluated. Parameters of a function declared before a default 77 // argument expression are in scope and can hide namespace and 78 // class member names. 79 return S->Diag(DRE->getSourceRange().getBegin(), 80 diag::err_param_default_argument_references_param) 81 << Param->getDeclName() << DefaultArg->getSourceRange(); 82 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 83 // C++ [dcl.fct.default]p7 84 // Local variables shall not be used in default argument 85 // expressions. 86 if (VDecl->isBlockVarDecl()) 87 return S->Diag(DRE->getSourceRange().getBegin(), 88 diag::err_param_default_argument_references_local) 89 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 90 } 91 92 return false; 93 } 94 95 /// VisitCXXThisExpr - Visit a C++ "this" expression. 96 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 97 // C++ [dcl.fct.default]p8: 98 // The keyword this shall not be used in a default argument of a 99 // member function. 100 return S->Diag(ThisE->getSourceRange().getBegin(), 101 diag::err_param_default_argument_references_this) 102 << ThisE->getSourceRange(); 103 } 104} 105 106bool 107Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg, 108 SourceLocation EqualLoc) { 109 QualType ParamType = Param->getType(); 110 111 if (RequireCompleteType(Param->getLocation(), Param->getType(), 112 diag::err_typecheck_decl_incomplete_type)) { 113 Param->setInvalidDecl(); 114 return true; 115 } 116 117 Expr *Arg = (Expr *)DefaultArg.get(); 118 119 // C++ [dcl.fct.default]p5 120 // A default argument expression is implicitly converted (clause 121 // 4) to the parameter type. The default argument expression has 122 // the same semantic constraints as the initializer expression in 123 // a declaration of a variable of the parameter type, using the 124 // copy-initialization semantics (8.5). 125 if (CheckInitializerTypes(Arg, ParamType, EqualLoc, 126 Param->getDeclName(), /*DirectInit=*/false)) 127 return true; 128 129 Arg = MaybeCreateCXXExprWithTemporaries(Arg, /*DestroyTemps=*/false); 130 131 // Okay: add the default argument to the parameter 132 Param->setDefaultArg(Arg); 133 134 DefaultArg.release(); 135 136 return false; 137} 138 139/// ActOnParamDefaultArgument - Check whether the default argument 140/// provided for a function parameter is well-formed. If so, attach it 141/// to the parameter declaration. 142void 143Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc, 144 ExprArg defarg) { 145 if (!param || !defarg.get()) 146 return; 147 148 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>()); 149 UnparsedDefaultArgLocs.erase(Param); 150 151 ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>()); 152 QualType ParamType = Param->getType(); 153 154 // Default arguments are only permitted in C++ 155 if (!getLangOptions().CPlusPlus) { 156 Diag(EqualLoc, diag::err_param_default_argument) 157 << DefaultArg->getSourceRange(); 158 Param->setInvalidDecl(); 159 return; 160 } 161 162 // Check that the default argument is well-formed 163 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this); 164 if (DefaultArgChecker.Visit(DefaultArg.get())) { 165 Param->setInvalidDecl(); 166 return; 167 } 168 169 SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc); 170} 171 172/// ActOnParamUnparsedDefaultArgument - We've seen a default 173/// argument for a function parameter, but we can't parse it yet 174/// because we're inside a class definition. Note that this default 175/// argument will be parsed later. 176void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param, 177 SourceLocation EqualLoc, 178 SourceLocation ArgLoc) { 179 if (!param) 180 return; 181 182 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>()); 183 if (Param) 184 Param->setUnparsedDefaultArg(); 185 186 UnparsedDefaultArgLocs[Param] = ArgLoc; 187} 188 189/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 190/// the default argument for the parameter param failed. 191void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) { 192 if (!param) 193 return; 194 195 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>()); 196 197 Param->setInvalidDecl(); 198 199 UnparsedDefaultArgLocs.erase(Param); 200} 201 202/// CheckExtraCXXDefaultArguments - Check for any extra default 203/// arguments in the declarator, which is not a function declaration 204/// or definition and therefore is not permitted to have default 205/// arguments. This routine should be invoked for every declarator 206/// that is not a function declaration or definition. 207void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 208 // C++ [dcl.fct.default]p3 209 // A default argument expression shall be specified only in the 210 // parameter-declaration-clause of a function declaration or in a 211 // template-parameter (14.1). It shall not be specified for a 212 // parameter pack. If it is specified in a 213 // parameter-declaration-clause, it shall not occur within a 214 // declarator or abstract-declarator of a parameter-declaration. 215 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 216 DeclaratorChunk &chunk = D.getTypeObject(i); 217 if (chunk.Kind == DeclaratorChunk::Function) { 218 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) { 219 ParmVarDecl *Param = 220 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>()); 221 if (Param->hasUnparsedDefaultArg()) { 222 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens; 223 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 224 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation()); 225 delete Toks; 226 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0; 227 } else if (Param->getDefaultArg()) { 228 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 229 << Param->getDefaultArg()->getSourceRange(); 230 Param->setDefaultArg(0); 231 } 232 } 233 } 234 } 235} 236 237// MergeCXXFunctionDecl - Merge two declarations of the same C++ 238// function, once we already know that they have the same 239// type. Subroutine of MergeFunctionDecl. Returns true if there was an 240// error, false otherwise. 241bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) { 242 bool Invalid = false; 243 244 // C++ [dcl.fct.default]p4: 245 // For non-template functions, default arguments can be added in 246 // later declarations of a function in the same 247 // scope. Declarations in different scopes have completely 248 // distinct sets of default arguments. That is, declarations in 249 // inner scopes do not acquire default arguments from 250 // declarations in outer scopes, and vice versa. In a given 251 // function declaration, all parameters subsequent to a 252 // parameter with a default argument shall have default 253 // arguments supplied in this or previous declarations. A 254 // default argument shall not be redefined by a later 255 // declaration (not even to the same value). 256 // 257 // C++ [dcl.fct.default]p6: 258 // Except for member functions of class templates, the default arguments 259 // in a member function definition that appears outside of the class 260 // definition are added to the set of default arguments provided by the 261 // member function declaration in the class definition. 262 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 263 ParmVarDecl *OldParam = Old->getParamDecl(p); 264 ParmVarDecl *NewParam = New->getParamDecl(p); 265 266 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) { 267 // FIXME: If the parameter doesn't have an identifier then the location 268 // points to the '=' which means that the fixit hint won't remove any 269 // extra spaces between the type and the '='. 270 SourceLocation Begin = NewParam->getLocation(); 271 if (NewParam->getIdentifier()) 272 Begin = PP.getLocForEndOfToken(Begin); 273 274 Diag(NewParam->getLocation(), 275 diag::err_param_default_argument_redefinition) 276 << NewParam->getDefaultArgRange() 277 << CodeModificationHint::CreateRemoval(SourceRange(Begin, 278 NewParam->getLocEnd())); 279 280 // Look for the function declaration where the default argument was 281 // actually written, which may be a declaration prior to Old. 282 for (FunctionDecl *Older = Old->getPreviousDeclaration(); 283 Older; Older = Older->getPreviousDeclaration()) { 284 if (!Older->getParamDecl(p)->hasDefaultArg()) 285 break; 286 287 OldParam = Older->getParamDecl(p); 288 } 289 290 Diag(OldParam->getLocation(), diag::note_previous_definition) 291 << OldParam->getDefaultArgRange(); 292 Invalid = true; 293 } else if (OldParam->hasDefaultArg()) { 294 // Merge the old default argument into the new parameter 295 if (OldParam->hasUninstantiatedDefaultArg()) 296 NewParam->setUninstantiatedDefaultArg( 297 OldParam->getUninstantiatedDefaultArg()); 298 else 299 NewParam->setDefaultArg(OldParam->getDefaultArg()); 300 } else if (NewParam->hasDefaultArg()) { 301 if (New->getDescribedFunctionTemplate()) { 302 // Paragraph 4, quoted above, only applies to non-template functions. 303 Diag(NewParam->getLocation(), 304 diag::err_param_default_argument_template_redecl) 305 << NewParam->getDefaultArgRange(); 306 Diag(Old->getLocation(), diag::note_template_prev_declaration) 307 << false; 308 } else if (New->getTemplateSpecializationKind() 309 != TSK_ImplicitInstantiation && 310 New->getTemplateSpecializationKind() != TSK_Undeclared) { 311 // C++ [temp.expr.spec]p21: 312 // Default function arguments shall not be specified in a declaration 313 // or a definition for one of the following explicit specializations: 314 // - the explicit specialization of a function template; 315 // - the explicit specialization of a member function template; 316 // - the explicit specialization of a member function of a class 317 // template where the class template specialization to which the 318 // member function specialization belongs is implicitly 319 // instantiated. 320 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 321 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 322 << New->getDeclName() 323 << NewParam->getDefaultArgRange(); 324 } else if (New->getDeclContext()->isDependentContext()) { 325 // C++ [dcl.fct.default]p6 (DR217): 326 // Default arguments for a member function of a class template shall 327 // be specified on the initial declaration of the member function 328 // within the class template. 329 // 330 // Reading the tea leaves a bit in DR217 and its reference to DR205 331 // leads me to the conclusion that one cannot add default function 332 // arguments for an out-of-line definition of a member function of a 333 // dependent type. 334 int WhichKind = 2; 335 if (CXXRecordDecl *Record 336 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 337 if (Record->getDescribedClassTemplate()) 338 WhichKind = 0; 339 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 340 WhichKind = 1; 341 else 342 WhichKind = 2; 343 } 344 345 Diag(NewParam->getLocation(), 346 diag::err_param_default_argument_member_template_redecl) 347 << WhichKind 348 << NewParam->getDefaultArgRange(); 349 } 350 } 351 } 352 353 if (CheckEquivalentExceptionSpec( 354 Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(), 355 New->getType()->getAs<FunctionProtoType>(), New->getLocation())) 356 Invalid = true; 357 358 return Invalid; 359} 360 361/// CheckCXXDefaultArguments - Verify that the default arguments for a 362/// function declaration are well-formed according to C++ 363/// [dcl.fct.default]. 364void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 365 unsigned NumParams = FD->getNumParams(); 366 unsigned p; 367 368 // Find first parameter with a default argument 369 for (p = 0; p < NumParams; ++p) { 370 ParmVarDecl *Param = FD->getParamDecl(p); 371 if (Param->hasDefaultArg()) 372 break; 373 } 374 375 // C++ [dcl.fct.default]p4: 376 // In a given function declaration, all parameters 377 // subsequent to a parameter with a default argument shall 378 // have default arguments supplied in this or previous 379 // declarations. A default argument shall not be redefined 380 // by a later declaration (not even to the same value). 381 unsigned LastMissingDefaultArg = 0; 382 for (; p < NumParams; ++p) { 383 ParmVarDecl *Param = FD->getParamDecl(p); 384 if (!Param->hasDefaultArg()) { 385 if (Param->isInvalidDecl()) 386 /* We already complained about this parameter. */; 387 else if (Param->getIdentifier()) 388 Diag(Param->getLocation(), 389 diag::err_param_default_argument_missing_name) 390 << Param->getIdentifier(); 391 else 392 Diag(Param->getLocation(), 393 diag::err_param_default_argument_missing); 394 395 LastMissingDefaultArg = p; 396 } 397 } 398 399 if (LastMissingDefaultArg > 0) { 400 // Some default arguments were missing. Clear out all of the 401 // default arguments up to (and including) the last missing 402 // default argument, so that we leave the function parameters 403 // in a semantically valid state. 404 for (p = 0; p <= LastMissingDefaultArg; ++p) { 405 ParmVarDecl *Param = FD->getParamDecl(p); 406 if (Param->hasDefaultArg()) { 407 if (!Param->hasUnparsedDefaultArg()) 408 Param->getDefaultArg()->Destroy(Context); 409 Param->setDefaultArg(0); 410 } 411 } 412 } 413} 414 415/// isCurrentClassName - Determine whether the identifier II is the 416/// name of the class type currently being defined. In the case of 417/// nested classes, this will only return true if II is the name of 418/// the innermost class. 419bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 420 const CXXScopeSpec *SS) { 421 CXXRecordDecl *CurDecl; 422 if (SS && SS->isSet() && !SS->isInvalid()) { 423 DeclContext *DC = computeDeclContext(*SS, true); 424 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 425 } else 426 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 427 428 if (CurDecl) 429 return &II == CurDecl->getIdentifier(); 430 else 431 return false; 432} 433 434/// \brief Check the validity of a C++ base class specifier. 435/// 436/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 437/// and returns NULL otherwise. 438CXXBaseSpecifier * 439Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 440 SourceRange SpecifierRange, 441 bool Virtual, AccessSpecifier Access, 442 QualType BaseType, 443 SourceLocation BaseLoc) { 444 // C++ [class.union]p1: 445 // A union shall not have base classes. 446 if (Class->isUnion()) { 447 Diag(Class->getLocation(), diag::err_base_clause_on_union) 448 << SpecifierRange; 449 return 0; 450 } 451 452 if (BaseType->isDependentType()) 453 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 454 Class->getTagKind() == RecordDecl::TK_class, 455 Access, BaseType); 456 457 // Base specifiers must be record types. 458 if (!BaseType->isRecordType()) { 459 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 460 return 0; 461 } 462 463 // C++ [class.union]p1: 464 // A union shall not be used as a base class. 465 if (BaseType->isUnionType()) { 466 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 467 return 0; 468 } 469 470 // C++ [class.derived]p2: 471 // The class-name in a base-specifier shall not be an incompletely 472 // defined class. 473 if (RequireCompleteType(BaseLoc, BaseType, 474 PDiag(diag::err_incomplete_base_class) 475 << SpecifierRange)) 476 return 0; 477 478 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 479 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 480 assert(BaseDecl && "Record type has no declaration"); 481 BaseDecl = BaseDecl->getDefinition(Context); 482 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 483 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 484 assert(CXXBaseDecl && "Base type is not a C++ type"); 485 if (!CXXBaseDecl->isEmpty()) 486 Class->setEmpty(false); 487 if (CXXBaseDecl->isPolymorphic()) 488 Class->setPolymorphic(true); 489 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases. 490 if (CXXBaseDecl->hasAttr<FinalAttr>()) { 491 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString(); 492 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl) 493 << BaseType; 494 return 0; 495 } 496 497 // C++ [dcl.init.aggr]p1: 498 // An aggregate is [...] a class with [...] no base classes [...]. 499 Class->setAggregate(false); 500 Class->setPOD(false); 501 502 if (Virtual) { 503 // C++ [class.ctor]p5: 504 // A constructor is trivial if its class has no virtual base classes. 505 Class->setHasTrivialConstructor(false); 506 507 // C++ [class.copy]p6: 508 // A copy constructor is trivial if its class has no virtual base classes. 509 Class->setHasTrivialCopyConstructor(false); 510 511 // C++ [class.copy]p11: 512 // A copy assignment operator is trivial if its class has no virtual 513 // base classes. 514 Class->setHasTrivialCopyAssignment(false); 515 516 // C++0x [meta.unary.prop] is_empty: 517 // T is a class type, but not a union type, with ... no virtual base 518 // classes 519 Class->setEmpty(false); 520 } else { 521 // C++ [class.ctor]p5: 522 // A constructor is trivial if all the direct base classes of its 523 // class have trivial constructors. 524 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialConstructor()) 525 Class->setHasTrivialConstructor(false); 526 527 // C++ [class.copy]p6: 528 // A copy constructor is trivial if all the direct base classes of its 529 // class have trivial copy constructors. 530 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyConstructor()) 531 Class->setHasTrivialCopyConstructor(false); 532 533 // C++ [class.copy]p11: 534 // A copy assignment operator is trivial if all the direct base classes 535 // of its class have trivial copy assignment operators. 536 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyAssignment()) 537 Class->setHasTrivialCopyAssignment(false); 538 } 539 540 // C++ [class.ctor]p3: 541 // A destructor is trivial if all the direct base classes of its class 542 // have trivial destructors. 543 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialDestructor()) 544 Class->setHasTrivialDestructor(false); 545 546 // Create the base specifier. 547 // FIXME: Allocate via ASTContext? 548 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 549 Class->getTagKind() == RecordDecl::TK_class, 550 Access, BaseType); 551} 552 553/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 554/// one entry in the base class list of a class specifier, for 555/// example: 556/// class foo : public bar, virtual private baz { 557/// 'public bar' and 'virtual private baz' are each base-specifiers. 558Sema::BaseResult 559Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange, 560 bool Virtual, AccessSpecifier Access, 561 TypeTy *basetype, SourceLocation BaseLoc) { 562 if (!classdecl) 563 return true; 564 565 AdjustDeclIfTemplate(classdecl); 566 CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>()); 567 QualType BaseType = GetTypeFromParser(basetype); 568 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 569 Virtual, Access, 570 BaseType, BaseLoc)) 571 return BaseSpec; 572 573 return true; 574} 575 576/// \brief Performs the actual work of attaching the given base class 577/// specifiers to a C++ class. 578bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 579 unsigned NumBases) { 580 if (NumBases == 0) 581 return false; 582 583 // Used to keep track of which base types we have already seen, so 584 // that we can properly diagnose redundant direct base types. Note 585 // that the key is always the unqualified canonical type of the base 586 // class. 587 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 588 589 // Copy non-redundant base specifiers into permanent storage. 590 unsigned NumGoodBases = 0; 591 bool Invalid = false; 592 for (unsigned idx = 0; idx < NumBases; ++idx) { 593 QualType NewBaseType 594 = Context.getCanonicalType(Bases[idx]->getType()); 595 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 596 597 if (KnownBaseTypes[NewBaseType]) { 598 // C++ [class.mi]p3: 599 // A class shall not be specified as a direct base class of a 600 // derived class more than once. 601 Diag(Bases[idx]->getSourceRange().getBegin(), 602 diag::err_duplicate_base_class) 603 << KnownBaseTypes[NewBaseType]->getType() 604 << Bases[idx]->getSourceRange(); 605 606 // Delete the duplicate base class specifier; we're going to 607 // overwrite its pointer later. 608 Context.Deallocate(Bases[idx]); 609 610 Invalid = true; 611 } else { 612 // Okay, add this new base class. 613 KnownBaseTypes[NewBaseType] = Bases[idx]; 614 Bases[NumGoodBases++] = Bases[idx]; 615 } 616 } 617 618 // Attach the remaining base class specifiers to the derived class. 619 Class->setBases(Context, Bases, NumGoodBases); 620 621 // Delete the remaining (good) base class specifiers, since their 622 // data has been copied into the CXXRecordDecl. 623 for (unsigned idx = 0; idx < NumGoodBases; ++idx) 624 Context.Deallocate(Bases[idx]); 625 626 return Invalid; 627} 628 629/// ActOnBaseSpecifiers - Attach the given base specifiers to the 630/// class, after checking whether there are any duplicate base 631/// classes. 632void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases, 633 unsigned NumBases) { 634 if (!ClassDecl || !Bases || !NumBases) 635 return; 636 637 AdjustDeclIfTemplate(ClassDecl); 638 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()), 639 (CXXBaseSpecifier**)(Bases), NumBases); 640} 641 642/// \brief Determine whether the type \p Derived is a C++ class that is 643/// derived from the type \p Base. 644bool Sema::IsDerivedFrom(QualType Derived, QualType Base) { 645 if (!getLangOptions().CPlusPlus) 646 return false; 647 648 const RecordType *DerivedRT = Derived->getAs<RecordType>(); 649 if (!DerivedRT) 650 return false; 651 652 const RecordType *BaseRT = Base->getAs<RecordType>(); 653 if (!BaseRT) 654 return false; 655 656 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl()); 657 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl()); 658 return DerivedRD->isDerivedFrom(BaseRD); 659} 660 661/// \brief Determine whether the type \p Derived is a C++ class that is 662/// derived from the type \p Base. 663bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) { 664 if (!getLangOptions().CPlusPlus) 665 return false; 666 667 const RecordType *DerivedRT = Derived->getAs<RecordType>(); 668 if (!DerivedRT) 669 return false; 670 671 const RecordType *BaseRT = Base->getAs<RecordType>(); 672 if (!BaseRT) 673 return false; 674 675 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl()); 676 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl()); 677 return DerivedRD->isDerivedFrom(BaseRD, Paths); 678} 679 680/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 681/// conversion (where Derived and Base are class types) is 682/// well-formed, meaning that the conversion is unambiguous (and 683/// that all of the base classes are accessible). Returns true 684/// and emits a diagnostic if the code is ill-formed, returns false 685/// otherwise. Loc is the location where this routine should point to 686/// if there is an error, and Range is the source range to highlight 687/// if there is an error. 688bool 689Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 690 unsigned InaccessibleBaseID, 691 unsigned AmbigiousBaseConvID, 692 SourceLocation Loc, SourceRange Range, 693 DeclarationName Name) { 694 // First, determine whether the path from Derived to Base is 695 // ambiguous. This is slightly more expensive than checking whether 696 // the Derived to Base conversion exists, because here we need to 697 // explore multiple paths to determine if there is an ambiguity. 698 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 699 /*DetectVirtual=*/false); 700 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths); 701 assert(DerivationOkay && 702 "Can only be used with a derived-to-base conversion"); 703 (void)DerivationOkay; 704 705 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 706 if (InaccessibleBaseID == 0) 707 return false; 708 // Check that the base class can be accessed. 709 return CheckBaseClassAccess(Derived, Base, InaccessibleBaseID, Paths, Loc, 710 Name); 711 } 712 713 // We know that the derived-to-base conversion is ambiguous, and 714 // we're going to produce a diagnostic. Perform the derived-to-base 715 // search just one more time to compute all of the possible paths so 716 // that we can print them out. This is more expensive than any of 717 // the previous derived-to-base checks we've done, but at this point 718 // performance isn't as much of an issue. 719 Paths.clear(); 720 Paths.setRecordingPaths(true); 721 bool StillOkay = IsDerivedFrom(Derived, Base, Paths); 722 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 723 (void)StillOkay; 724 725 // Build up a textual representation of the ambiguous paths, e.g., 726 // D -> B -> A, that will be used to illustrate the ambiguous 727 // conversions in the diagnostic. We only print one of the paths 728 // to each base class subobject. 729 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 730 731 Diag(Loc, AmbigiousBaseConvID) 732 << Derived << Base << PathDisplayStr << Range << Name; 733 return true; 734} 735 736bool 737Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 738 SourceLocation Loc, SourceRange Range, 739 bool IgnoreAccess) { 740 return CheckDerivedToBaseConversion(Derived, Base, 741 IgnoreAccess ? 0 : 742 diag::err_conv_to_inaccessible_base, 743 diag::err_ambiguous_derived_to_base_conv, 744 Loc, Range, DeclarationName()); 745} 746 747 748/// @brief Builds a string representing ambiguous paths from a 749/// specific derived class to different subobjects of the same base 750/// class. 751/// 752/// This function builds a string that can be used in error messages 753/// to show the different paths that one can take through the 754/// inheritance hierarchy to go from the derived class to different 755/// subobjects of a base class. The result looks something like this: 756/// @code 757/// struct D -> struct B -> struct A 758/// struct D -> struct C -> struct A 759/// @endcode 760std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 761 std::string PathDisplayStr; 762 std::set<unsigned> DisplayedPaths; 763 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 764 Path != Paths.end(); ++Path) { 765 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 766 // We haven't displayed a path to this particular base 767 // class subobject yet. 768 PathDisplayStr += "\n "; 769 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 770 for (CXXBasePath::const_iterator Element = Path->begin(); 771 Element != Path->end(); ++Element) 772 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 773 } 774 } 775 776 return PathDisplayStr; 777} 778 779//===----------------------------------------------------------------------===// 780// C++ class member Handling 781//===----------------------------------------------------------------------===// 782 783/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 784/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 785/// bitfield width if there is one and 'InitExpr' specifies the initializer if 786/// any. 787Sema::DeclPtrTy 788Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 789 MultiTemplateParamsArg TemplateParameterLists, 790 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition, 791 bool Deleted) { 792 const DeclSpec &DS = D.getDeclSpec(); 793 DeclarationName Name = GetNameForDeclarator(D); 794 Expr *BitWidth = static_cast<Expr*>(BW); 795 Expr *Init = static_cast<Expr*>(InitExpr); 796 SourceLocation Loc = D.getIdentifierLoc(); 797 798 bool isFunc = D.isFunctionDeclarator(); 799 800 assert(!DS.isFriendSpecified()); 801 802 // C++ 9.2p6: A member shall not be declared to have automatic storage 803 // duration (auto, register) or with the extern storage-class-specifier. 804 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 805 // data members and cannot be applied to names declared const or static, 806 // and cannot be applied to reference members. 807 switch (DS.getStorageClassSpec()) { 808 case DeclSpec::SCS_unspecified: 809 case DeclSpec::SCS_typedef: 810 case DeclSpec::SCS_static: 811 // FALL THROUGH. 812 break; 813 case DeclSpec::SCS_mutable: 814 if (isFunc) { 815 if (DS.getStorageClassSpecLoc().isValid()) 816 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 817 else 818 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function); 819 820 // FIXME: It would be nicer if the keyword was ignored only for this 821 // declarator. Otherwise we could get follow-up errors. 822 D.getMutableDeclSpec().ClearStorageClassSpecs(); 823 } else { 824 QualType T = GetTypeForDeclarator(D, S); 825 diag::kind err = static_cast<diag::kind>(0); 826 if (T->isReferenceType()) 827 err = diag::err_mutable_reference; 828 else if (T.isConstQualified()) 829 err = diag::err_mutable_const; 830 if (err != 0) { 831 if (DS.getStorageClassSpecLoc().isValid()) 832 Diag(DS.getStorageClassSpecLoc(), err); 833 else 834 Diag(DS.getThreadSpecLoc(), err); 835 // FIXME: It would be nicer if the keyword was ignored only for this 836 // declarator. Otherwise we could get follow-up errors. 837 D.getMutableDeclSpec().ClearStorageClassSpecs(); 838 } 839 } 840 break; 841 default: 842 if (DS.getStorageClassSpecLoc().isValid()) 843 Diag(DS.getStorageClassSpecLoc(), 844 diag::err_storageclass_invalid_for_member); 845 else 846 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member); 847 D.getMutableDeclSpec().ClearStorageClassSpecs(); 848 } 849 850 if (!isFunc && 851 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename && 852 D.getNumTypeObjects() == 0) { 853 // Check also for this case: 854 // 855 // typedef int f(); 856 // f a; 857 // 858 QualType TDType = GetTypeFromParser(DS.getTypeRep()); 859 isFunc = TDType->isFunctionType(); 860 } 861 862 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 863 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 864 !isFunc); 865 866 Decl *Member; 867 if (isInstField) { 868 // FIXME: Check for template parameters! 869 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth, 870 AS); 871 assert(Member && "HandleField never returns null"); 872 } else { 873 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition) 874 .getAs<Decl>(); 875 if (!Member) { 876 if (BitWidth) DeleteExpr(BitWidth); 877 return DeclPtrTy(); 878 } 879 880 // Non-instance-fields can't have a bitfield. 881 if (BitWidth) { 882 if (Member->isInvalidDecl()) { 883 // don't emit another diagnostic. 884 } else if (isa<VarDecl>(Member)) { 885 // C++ 9.6p3: A bit-field shall not be a static member. 886 // "static member 'A' cannot be a bit-field" 887 Diag(Loc, diag::err_static_not_bitfield) 888 << Name << BitWidth->getSourceRange(); 889 } else if (isa<TypedefDecl>(Member)) { 890 // "typedef member 'x' cannot be a bit-field" 891 Diag(Loc, diag::err_typedef_not_bitfield) 892 << Name << BitWidth->getSourceRange(); 893 } else { 894 // A function typedef ("typedef int f(); f a;"). 895 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 896 Diag(Loc, diag::err_not_integral_type_bitfield) 897 << Name << cast<ValueDecl>(Member)->getType() 898 << BitWidth->getSourceRange(); 899 } 900 901 DeleteExpr(BitWidth); 902 BitWidth = 0; 903 Member->setInvalidDecl(); 904 } 905 906 Member->setAccess(AS); 907 908 // If we have declared a member function template, set the access of the 909 // templated declaration as well. 910 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 911 FunTmpl->getTemplatedDecl()->setAccess(AS); 912 } 913 914 assert((Name || isInstField) && "No identifier for non-field ?"); 915 916 if (Init) 917 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false); 918 if (Deleted) // FIXME: Source location is not very good. 919 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin()); 920 921 if (isInstField) { 922 FieldCollector->Add(cast<FieldDecl>(Member)); 923 return DeclPtrTy(); 924 } 925 return DeclPtrTy::make(Member); 926} 927 928/// ActOnMemInitializer - Handle a C++ member initializer. 929Sema::MemInitResult 930Sema::ActOnMemInitializer(DeclPtrTy ConstructorD, 931 Scope *S, 932 const CXXScopeSpec &SS, 933 IdentifierInfo *MemberOrBase, 934 TypeTy *TemplateTypeTy, 935 SourceLocation IdLoc, 936 SourceLocation LParenLoc, 937 ExprTy **Args, unsigned NumArgs, 938 SourceLocation *CommaLocs, 939 SourceLocation RParenLoc) { 940 if (!ConstructorD) 941 return true; 942 943 AdjustDeclIfTemplate(ConstructorD); 944 945 CXXConstructorDecl *Constructor 946 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>()); 947 if (!Constructor) { 948 // The user wrote a constructor initializer on a function that is 949 // not a C++ constructor. Ignore the error for now, because we may 950 // have more member initializers coming; we'll diagnose it just 951 // once in ActOnMemInitializers. 952 return true; 953 } 954 955 CXXRecordDecl *ClassDecl = Constructor->getParent(); 956 957 // C++ [class.base.init]p2: 958 // Names in a mem-initializer-id are looked up in the scope of the 959 // constructor’s class and, if not found in that scope, are looked 960 // up in the scope containing the constructor’s 961 // definition. [Note: if the constructor’s class contains a member 962 // with the same name as a direct or virtual base class of the 963 // class, a mem-initializer-id naming the member or base class and 964 // composed of a single identifier refers to the class member. A 965 // mem-initializer-id for the hidden base class may be specified 966 // using a qualified name. ] 967 if (!SS.getScopeRep() && !TemplateTypeTy) { 968 // Look for a member, first. 969 FieldDecl *Member = 0; 970 DeclContext::lookup_result Result 971 = ClassDecl->lookup(MemberOrBase); 972 if (Result.first != Result.second) 973 Member = dyn_cast<FieldDecl>(*Result.first); 974 975 // FIXME: Handle members of an anonymous union. 976 977 if (Member) 978 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc, 979 RParenLoc); 980 } 981 // It didn't name a member, so see if it names a class. 982 TypeTy *BaseTy = TemplateTypeTy ? TemplateTypeTy 983 : getTypeName(*MemberOrBase, IdLoc, S, &SS); 984 if (!BaseTy) 985 return Diag(IdLoc, diag::err_mem_init_not_member_or_class) 986 << MemberOrBase << SourceRange(IdLoc, RParenLoc); 987 988 QualType BaseType = GetTypeFromParser(BaseTy); 989 990 return BuildBaseInitializer(BaseType, (Expr **)Args, NumArgs, IdLoc, 991 RParenLoc, ClassDecl); 992} 993 994/// Checks an initializer expression for use of uninitialized fields, such as 995/// containing the field that is being initialized. Returns true if there is an 996/// uninitialized field was used an updates the SourceLocation parameter; false 997/// otherwise. 998static bool InitExprContainsUninitializedFields(const Stmt* S, 999 const FieldDecl* LhsField, 1000 SourceLocation* L) { 1001 const MemberExpr* ME = dyn_cast<MemberExpr>(S); 1002 if (ME) { 1003 const NamedDecl* RhsField = ME->getMemberDecl(); 1004 if (RhsField == LhsField) { 1005 // Initializing a field with itself. Throw a warning. 1006 // But wait; there are exceptions! 1007 // Exception #1: The field may not belong to this record. 1008 // e.g. Foo(const Foo& rhs) : A(rhs.A) {} 1009 const Expr* base = ME->getBase(); 1010 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) { 1011 // Even though the field matches, it does not belong to this record. 1012 return false; 1013 } 1014 // None of the exceptions triggered; return true to indicate an 1015 // uninitialized field was used. 1016 *L = ME->getMemberLoc(); 1017 return true; 1018 } 1019 } 1020 bool found = false; 1021 for (Stmt::const_child_iterator it = S->child_begin(); 1022 it != S->child_end() && found == false; 1023 ++it) { 1024 if (isa<CallExpr>(S)) { 1025 // Do not descend into function calls or constructors, as the use 1026 // of an uninitialized field may be valid. One would have to inspect 1027 // the contents of the function/ctor to determine if it is safe or not. 1028 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers 1029 // may be safe, depending on what the function/ctor does. 1030 continue; 1031 } 1032 found = InitExprContainsUninitializedFields(*it, LhsField, L); 1033 } 1034 return found; 1035} 1036 1037Sema::MemInitResult 1038Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args, 1039 unsigned NumArgs, SourceLocation IdLoc, 1040 SourceLocation RParenLoc) { 1041 // FIXME: CXXBaseOrMemberInitializer should only contain a single 1042 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary. 1043 ExprTemporaries.clear(); 1044 1045 // Diagnose value-uses of fields to initialize themselves, e.g. 1046 // foo(foo) 1047 // where foo is not also a parameter to the constructor. 1048 // TODO: implement -Wuninitialized and fold this into that framework. 1049 for (unsigned i = 0; i < NumArgs; ++i) { 1050 SourceLocation L; 1051 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) { 1052 // FIXME: Return true in the case when other fields are used before being 1053 // uninitialized. For example, let this field be the i'th field. When 1054 // initializing the i'th field, throw a warning if any of the >= i'th 1055 // fields are used, as they are not yet initialized. 1056 // Right now we are only handling the case where the i'th field uses 1057 // itself in its initializer. 1058 Diag(L, diag::warn_field_is_uninit); 1059 } 1060 } 1061 1062 bool HasDependentArg = false; 1063 for (unsigned i = 0; i < NumArgs; i++) 1064 HasDependentArg |= Args[i]->isTypeDependent(); 1065 1066 CXXConstructorDecl *C = 0; 1067 QualType FieldType = Member->getType(); 1068 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 1069 FieldType = Array->getElementType(); 1070 if (FieldType->isDependentType()) { 1071 // Can't check init for dependent type. 1072 } else if (FieldType->isRecordType()) { 1073 // Member is a record (struct/union/class), so pass the initializer 1074 // arguments down to the record's constructor. 1075 if (!HasDependentArg) { 1076 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this); 1077 1078 C = PerformInitializationByConstructor(FieldType, 1079 MultiExprArg(*this, 1080 (void**)Args, 1081 NumArgs), 1082 IdLoc, 1083 SourceRange(IdLoc, RParenLoc), 1084 Member->getDeclName(), IK_Direct, 1085 ConstructorArgs); 1086 1087 if (C) { 1088 // Take over the constructor arguments as our own. 1089 NumArgs = ConstructorArgs.size(); 1090 Args = (Expr **)ConstructorArgs.take(); 1091 } 1092 } 1093 } else if (NumArgs != 1 && NumArgs != 0) { 1094 // The member type is not a record type (or an array of record 1095 // types), so it can be only be default- or copy-initialized. 1096 return Diag(IdLoc, diag::err_mem_initializer_mismatch) 1097 << Member->getDeclName() << SourceRange(IdLoc, RParenLoc); 1098 } else if (!HasDependentArg) { 1099 Expr *NewExp; 1100 if (NumArgs == 0) { 1101 if (FieldType->isReferenceType()) { 1102 Diag(IdLoc, diag::err_null_intialized_reference_member) 1103 << Member->getDeclName(); 1104 return Diag(Member->getLocation(), diag::note_declared_at); 1105 } 1106 NewExp = new (Context) CXXZeroInitValueExpr(FieldType, IdLoc, RParenLoc); 1107 NumArgs = 1; 1108 } 1109 else 1110 NewExp = (Expr*)Args[0]; 1111 if (PerformCopyInitialization(NewExp, FieldType, "passing")) 1112 return true; 1113 Args[0] = NewExp; 1114 } 1115 1116 // FIXME: CXXBaseOrMemberInitializer should only contain a single 1117 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary. 1118 ExprTemporaries.clear(); 1119 1120 // FIXME: Perform direct initialization of the member. 1121 return new (Context) CXXBaseOrMemberInitializer(Member, (Expr **)Args, 1122 NumArgs, C, IdLoc, RParenLoc); 1123} 1124 1125Sema::MemInitResult 1126Sema::BuildBaseInitializer(QualType BaseType, Expr **Args, 1127 unsigned NumArgs, SourceLocation IdLoc, 1128 SourceLocation RParenLoc, CXXRecordDecl *ClassDecl) { 1129 bool HasDependentArg = false; 1130 for (unsigned i = 0; i < NumArgs; i++) 1131 HasDependentArg |= Args[i]->isTypeDependent(); 1132 1133 if (!BaseType->isDependentType()) { 1134 if (!BaseType->isRecordType()) 1135 return Diag(IdLoc, diag::err_base_init_does_not_name_class) 1136 << BaseType << SourceRange(IdLoc, RParenLoc); 1137 1138 // C++ [class.base.init]p2: 1139 // [...] Unless the mem-initializer-id names a nonstatic data 1140 // member of the constructor’s class or a direct or virtual base 1141 // of that class, the mem-initializer is ill-formed. A 1142 // mem-initializer-list can initialize a base class using any 1143 // name that denotes that base class type. 1144 1145 // First, check for a direct base class. 1146 const CXXBaseSpecifier *DirectBaseSpec = 0; 1147 for (CXXRecordDecl::base_class_const_iterator Base = 1148 ClassDecl->bases_begin(); Base != ClassDecl->bases_end(); ++Base) { 1149 if (Context.hasSameUnqualifiedType(BaseType, Base->getType())) { 1150 // We found a direct base of this type. That's what we're 1151 // initializing. 1152 DirectBaseSpec = &*Base; 1153 break; 1154 } 1155 } 1156 1157 // Check for a virtual base class. 1158 // FIXME: We might be able to short-circuit this if we know in advance that 1159 // there are no virtual bases. 1160 const CXXBaseSpecifier *VirtualBaseSpec = 0; 1161 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 1162 // We haven't found a base yet; search the class hierarchy for a 1163 // virtual base class. 1164 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1165 /*DetectVirtual=*/false); 1166 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) { 1167 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 1168 Path != Paths.end(); ++Path) { 1169 if (Path->back().Base->isVirtual()) { 1170 VirtualBaseSpec = Path->back().Base; 1171 break; 1172 } 1173 } 1174 } 1175 } 1176 1177 // C++ [base.class.init]p2: 1178 // If a mem-initializer-id is ambiguous because it designates both 1179 // a direct non-virtual base class and an inherited virtual base 1180 // class, the mem-initializer is ill-formed. 1181 if (DirectBaseSpec && VirtualBaseSpec) 1182 return Diag(IdLoc, diag::err_base_init_direct_and_virtual) 1183 << BaseType << SourceRange(IdLoc, RParenLoc); 1184 // C++ [base.class.init]p2: 1185 // Unless the mem-initializer-id names a nonstatic data membeer of the 1186 // constructor's class ot a direst or virtual base of that class, the 1187 // mem-initializer is ill-formed. 1188 if (!DirectBaseSpec && !VirtualBaseSpec) 1189 return Diag(IdLoc, diag::err_not_direct_base_or_virtual) 1190 << BaseType << ClassDecl->getNameAsCString() 1191 << SourceRange(IdLoc, RParenLoc); 1192 } 1193 1194 CXXConstructorDecl *C = 0; 1195 if (!BaseType->isDependentType() && !HasDependentArg) { 1196 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 1197 Context.getCanonicalType(BaseType).getUnqualifiedType()); 1198 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this); 1199 1200 C = PerformInitializationByConstructor(BaseType, 1201 MultiExprArg(*this, 1202 (void**)Args, NumArgs), 1203 IdLoc, SourceRange(IdLoc, RParenLoc), 1204 Name, IK_Direct, 1205 ConstructorArgs); 1206 if (C) { 1207 // Take over the constructor arguments as our own. 1208 NumArgs = ConstructorArgs.size(); 1209 Args = (Expr **)ConstructorArgs.take(); 1210 } 1211 } 1212 1213 // FIXME: CXXBaseOrMemberInitializer should only contain a single 1214 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary. 1215 ExprTemporaries.clear(); 1216 1217 return new (Context) CXXBaseOrMemberInitializer(BaseType, (Expr **)Args, 1218 NumArgs, C, IdLoc, RParenLoc); 1219} 1220 1221bool 1222Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor, 1223 CXXBaseOrMemberInitializer **Initializers, 1224 unsigned NumInitializers, 1225 bool IsImplicitConstructor) { 1226 // We need to build the initializer AST according to order of construction 1227 // and not what user specified in the Initializers list. 1228 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext()); 1229 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit; 1230 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields; 1231 bool HasDependentBaseInit = false; 1232 bool HadError = false; 1233 1234 for (unsigned i = 0; i < NumInitializers; i++) { 1235 CXXBaseOrMemberInitializer *Member = Initializers[i]; 1236 if (Member->isBaseInitializer()) { 1237 if (Member->getBaseClass()->isDependentType()) 1238 HasDependentBaseInit = true; 1239 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 1240 } else { 1241 AllBaseFields[Member->getMember()] = Member; 1242 } 1243 } 1244 1245 if (HasDependentBaseInit) { 1246 // FIXME. This does not preserve the ordering of the initializers. 1247 // Try (with -Wreorder) 1248 // template<class X> struct A {}; 1249 // template<class X> struct B : A<X> { 1250 // B() : x1(10), A<X>() {} 1251 // int x1; 1252 // }; 1253 // B<int> x; 1254 // On seeing one dependent type, we should essentially exit this routine 1255 // while preserving user-declared initializer list. When this routine is 1256 // called during instantiatiation process, this routine will rebuild the 1257 // ordered initializer list correctly. 1258 1259 // If we have a dependent base initialization, we can't determine the 1260 // association between initializers and bases; just dump the known 1261 // initializers into the list, and don't try to deal with other bases. 1262 for (unsigned i = 0; i < NumInitializers; i++) { 1263 CXXBaseOrMemberInitializer *Member = Initializers[i]; 1264 if (Member->isBaseInitializer()) 1265 AllToInit.push_back(Member); 1266 } 1267 } else { 1268 // Push virtual bases before others. 1269 for (CXXRecordDecl::base_class_iterator VBase = 1270 ClassDecl->vbases_begin(), 1271 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 1272 if (VBase->getType()->isDependentType()) 1273 continue; 1274 if (CXXBaseOrMemberInitializer *Value 1275 = AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) { 1276 AllToInit.push_back(Value); 1277 } 1278 else { 1279 CXXRecordDecl *VBaseDecl = 1280 cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl()); 1281 assert(VBaseDecl && "SetBaseOrMemberInitializers - VBaseDecl null"); 1282 CXXConstructorDecl *Ctor = VBaseDecl->getDefaultConstructor(Context); 1283 if (!Ctor) { 1284 Diag(Constructor->getLocation(), diag::err_missing_default_ctor) 1285 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl) 1286 << 0 << VBase->getType(); 1287 Diag(VBaseDecl->getLocation(), diag::note_previous_decl) 1288 << Context.getTagDeclType(VBaseDecl); 1289 HadError = true; 1290 continue; 1291 } 1292 1293 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this); 1294 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0), 1295 Constructor->getLocation(), CtorArgs)) 1296 continue; 1297 1298 MarkDeclarationReferenced(Constructor->getLocation(), Ctor); 1299 1300 // FIXME: CXXBaseOrMemberInitializer should only contain a single 1301 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary. 1302 ExprTemporaries.clear(); 1303 CXXBaseOrMemberInitializer *Member = 1304 new (Context) CXXBaseOrMemberInitializer(VBase->getType(), 1305 CtorArgs.takeAs<Expr>(), 1306 CtorArgs.size(), Ctor, 1307 SourceLocation(), 1308 SourceLocation()); 1309 AllToInit.push_back(Member); 1310 } 1311 } 1312 1313 for (CXXRecordDecl::base_class_iterator Base = 1314 ClassDecl->bases_begin(), 1315 E = ClassDecl->bases_end(); Base != E; ++Base) { 1316 // Virtuals are in the virtual base list and already constructed. 1317 if (Base->isVirtual()) 1318 continue; 1319 // Skip dependent types. 1320 if (Base->getType()->isDependentType()) 1321 continue; 1322 if (CXXBaseOrMemberInitializer *Value 1323 = AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) { 1324 AllToInit.push_back(Value); 1325 } 1326 else { 1327 CXXRecordDecl *BaseDecl = 1328 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 1329 assert(BaseDecl && "SetBaseOrMemberInitializers - BaseDecl null"); 1330 CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context); 1331 if (!Ctor) { 1332 Diag(Constructor->getLocation(), diag::err_missing_default_ctor) 1333 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl) 1334 << 0 << Base->getType(); 1335 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 1336 << Context.getTagDeclType(BaseDecl); 1337 HadError = true; 1338 continue; 1339 } 1340 1341 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this); 1342 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0), 1343 Constructor->getLocation(), CtorArgs)) 1344 continue; 1345 1346 MarkDeclarationReferenced(Constructor->getLocation(), Ctor); 1347 1348 // FIXME: CXXBaseOrMemberInitializer should only contain a single 1349 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary. 1350 ExprTemporaries.clear(); 1351 CXXBaseOrMemberInitializer *Member = 1352 new (Context) CXXBaseOrMemberInitializer(Base->getType(), 1353 CtorArgs.takeAs<Expr>(), 1354 CtorArgs.size(), Ctor, 1355 SourceLocation(), 1356 SourceLocation()); 1357 AllToInit.push_back(Member); 1358 } 1359 } 1360 } 1361 1362 // non-static data members. 1363 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 1364 E = ClassDecl->field_end(); Field != E; ++Field) { 1365 if ((*Field)->isAnonymousStructOrUnion()) { 1366 if (const RecordType *FieldClassType = 1367 Field->getType()->getAs<RecordType>()) { 1368 CXXRecordDecl *FieldClassDecl 1369 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 1370 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(), 1371 EA = FieldClassDecl->field_end(); FA != EA; FA++) { 1372 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) { 1373 // 'Member' is the anonymous union field and 'AnonUnionMember' is 1374 // set to the anonymous union data member used in the initializer 1375 // list. 1376 Value->setMember(*Field); 1377 Value->setAnonUnionMember(*FA); 1378 AllToInit.push_back(Value); 1379 break; 1380 } 1381 } 1382 } 1383 continue; 1384 } 1385 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) { 1386 AllToInit.push_back(Value); 1387 continue; 1388 } 1389 1390 if ((*Field)->getType()->isDependentType()) 1391 continue; 1392 1393 QualType FT = Context.getBaseElementType((*Field)->getType()); 1394 if (const RecordType* RT = FT->getAs<RecordType>()) { 1395 CXXConstructorDecl *Ctor = 1396 cast<CXXRecordDecl>(RT->getDecl())->getDefaultConstructor(Context); 1397 if (!Ctor) { 1398 Diag(Constructor->getLocation(), diag::err_missing_default_ctor) 1399 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl) 1400 << 1 << (*Field)->getDeclName(); 1401 Diag(Field->getLocation(), diag::note_field_decl); 1402 Diag(RT->getDecl()->getLocation(), diag::note_previous_decl) 1403 << Context.getTagDeclType(RT->getDecl()); 1404 HadError = true; 1405 continue; 1406 } 1407 1408 if (FT.isConstQualified() && Ctor->isTrivial()) { 1409 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor) 1410 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl) 1411 << 1 << (*Field)->getDeclName(); 1412 Diag((*Field)->getLocation(), diag::note_declared_at); 1413 HadError = true; 1414 } 1415 1416 // Don't create initializers for trivial constructors, since they don't 1417 // actually need to be run. 1418 if (Ctor->isTrivial()) 1419 continue; 1420 1421 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this); 1422 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0), 1423 Constructor->getLocation(), CtorArgs)) 1424 continue; 1425 1426 // FIXME: CXXBaseOrMemberInitializer should only contain a single 1427 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary. 1428 ExprTemporaries.clear(); 1429 CXXBaseOrMemberInitializer *Member = 1430 new (Context) CXXBaseOrMemberInitializer(*Field,CtorArgs.takeAs<Expr>(), 1431 CtorArgs.size(), Ctor, 1432 SourceLocation(), 1433 SourceLocation()); 1434 1435 AllToInit.push_back(Member); 1436 MarkDeclarationReferenced(Constructor->getLocation(), Ctor); 1437 } 1438 else if (FT->isReferenceType()) { 1439 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor) 1440 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl) 1441 << 0 << (*Field)->getDeclName(); 1442 Diag((*Field)->getLocation(), diag::note_declared_at); 1443 HadError = true; 1444 } 1445 else if (FT.isConstQualified()) { 1446 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor) 1447 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl) 1448 << 1 << (*Field)->getDeclName(); 1449 Diag((*Field)->getLocation(), diag::note_declared_at); 1450 HadError = true; 1451 } 1452 } 1453 1454 NumInitializers = AllToInit.size(); 1455 if (NumInitializers > 0) { 1456 Constructor->setNumBaseOrMemberInitializers(NumInitializers); 1457 CXXBaseOrMemberInitializer **baseOrMemberInitializers = 1458 new (Context) CXXBaseOrMemberInitializer*[NumInitializers]; 1459 1460 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers); 1461 for (unsigned Idx = 0; Idx < NumInitializers; ++Idx) 1462 baseOrMemberInitializers[Idx] = AllToInit[Idx]; 1463 } 1464 1465 return HadError; 1466} 1467 1468static void *GetKeyForTopLevelField(FieldDecl *Field) { 1469 // For anonymous unions, use the class declaration as the key. 1470 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 1471 if (RT->getDecl()->isAnonymousStructOrUnion()) 1472 return static_cast<void *>(RT->getDecl()); 1473 } 1474 return static_cast<void *>(Field); 1475} 1476 1477static void *GetKeyForBase(QualType BaseType) { 1478 if (const RecordType *RT = BaseType->getAs<RecordType>()) 1479 return (void *)RT; 1480 1481 assert(0 && "Unexpected base type!"); 1482 return 0; 1483} 1484 1485static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member, 1486 bool MemberMaybeAnon = false) { 1487 // For fields injected into the class via declaration of an anonymous union, 1488 // use its anonymous union class declaration as the unique key. 1489 if (Member->isMemberInitializer()) { 1490 FieldDecl *Field = Member->getMember(); 1491 1492 // After SetBaseOrMemberInitializers call, Field is the anonymous union 1493 // data member of the class. Data member used in the initializer list is 1494 // in AnonUnionMember field. 1495 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion()) 1496 Field = Member->getAnonUnionMember(); 1497 if (Field->getDeclContext()->isRecord()) { 1498 RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext()); 1499 if (RD->isAnonymousStructOrUnion()) 1500 return static_cast<void *>(RD); 1501 } 1502 return static_cast<void *>(Field); 1503 } 1504 1505 return GetKeyForBase(QualType(Member->getBaseClass(), 0)); 1506} 1507 1508/// ActOnMemInitializers - Handle the member initializers for a constructor. 1509void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl, 1510 SourceLocation ColonLoc, 1511 MemInitTy **MemInits, unsigned NumMemInits) { 1512 if (!ConstructorDecl) 1513 return; 1514 1515 AdjustDeclIfTemplate(ConstructorDecl); 1516 1517 CXXConstructorDecl *Constructor 1518 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>()); 1519 1520 if (!Constructor) { 1521 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 1522 return; 1523 } 1524 1525 if (!Constructor->isDependentContext()) { 1526 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members; 1527 bool err = false; 1528 for (unsigned i = 0; i < NumMemInits; i++) { 1529 CXXBaseOrMemberInitializer *Member = 1530 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]); 1531 void *KeyToMember = GetKeyForMember(Member); 1532 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember]; 1533 if (!PrevMember) { 1534 PrevMember = Member; 1535 continue; 1536 } 1537 if (FieldDecl *Field = Member->getMember()) 1538 Diag(Member->getSourceLocation(), 1539 diag::error_multiple_mem_initialization) 1540 << Field->getNameAsString(); 1541 else { 1542 Type *BaseClass = Member->getBaseClass(); 1543 assert(BaseClass && "ActOnMemInitializers - neither field or base"); 1544 Diag(Member->getSourceLocation(), 1545 diag::error_multiple_base_initialization) 1546 << QualType(BaseClass, 0); 1547 } 1548 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer) 1549 << 0; 1550 err = true; 1551 } 1552 1553 if (err) 1554 return; 1555 } 1556 1557 SetBaseOrMemberInitializers(Constructor, 1558 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits), 1559 NumMemInits, false); 1560 1561 if (Constructor->isDependentContext()) 1562 return; 1563 1564 if (Diags.getDiagnosticLevel(diag::warn_base_initialized) == 1565 Diagnostic::Ignored && 1566 Diags.getDiagnosticLevel(diag::warn_field_initialized) == 1567 Diagnostic::Ignored) 1568 return; 1569 1570 // Also issue warning if order of ctor-initializer list does not match order 1571 // of 1) base class declarations and 2) order of non-static data members. 1572 llvm::SmallVector<const void*, 32> AllBaseOrMembers; 1573 1574 CXXRecordDecl *ClassDecl 1575 = cast<CXXRecordDecl>(Constructor->getDeclContext()); 1576 // Push virtual bases before others. 1577 for (CXXRecordDecl::base_class_iterator VBase = 1578 ClassDecl->vbases_begin(), 1579 E = ClassDecl->vbases_end(); VBase != E; ++VBase) 1580 AllBaseOrMembers.push_back(GetKeyForBase(VBase->getType())); 1581 1582 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 1583 E = ClassDecl->bases_end(); Base != E; ++Base) { 1584 // Virtuals are alread in the virtual base list and are constructed 1585 // first. 1586 if (Base->isVirtual()) 1587 continue; 1588 AllBaseOrMembers.push_back(GetKeyForBase(Base->getType())); 1589 } 1590 1591 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 1592 E = ClassDecl->field_end(); Field != E; ++Field) 1593 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field)); 1594 1595 int Last = AllBaseOrMembers.size(); 1596 int curIndex = 0; 1597 CXXBaseOrMemberInitializer *PrevMember = 0; 1598 for (unsigned i = 0; i < NumMemInits; i++) { 1599 CXXBaseOrMemberInitializer *Member = 1600 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]); 1601 void *MemberInCtorList = GetKeyForMember(Member, true); 1602 1603 for (; curIndex < Last; curIndex++) 1604 if (MemberInCtorList == AllBaseOrMembers[curIndex]) 1605 break; 1606 if (curIndex == Last) { 1607 assert(PrevMember && "Member not in member list?!"); 1608 // Initializer as specified in ctor-initializer list is out of order. 1609 // Issue a warning diagnostic. 1610 if (PrevMember->isBaseInitializer()) { 1611 // Diagnostics is for an initialized base class. 1612 Type *BaseClass = PrevMember->getBaseClass(); 1613 Diag(PrevMember->getSourceLocation(), 1614 diag::warn_base_initialized) 1615 << QualType(BaseClass, 0); 1616 } else { 1617 FieldDecl *Field = PrevMember->getMember(); 1618 Diag(PrevMember->getSourceLocation(), 1619 diag::warn_field_initialized) 1620 << Field->getNameAsString(); 1621 } 1622 // Also the note! 1623 if (FieldDecl *Field = Member->getMember()) 1624 Diag(Member->getSourceLocation(), 1625 diag::note_fieldorbase_initialized_here) << 0 1626 << Field->getNameAsString(); 1627 else { 1628 Type *BaseClass = Member->getBaseClass(); 1629 Diag(Member->getSourceLocation(), 1630 diag::note_fieldorbase_initialized_here) << 1 1631 << QualType(BaseClass, 0); 1632 } 1633 for (curIndex = 0; curIndex < Last; curIndex++) 1634 if (MemberInCtorList == AllBaseOrMembers[curIndex]) 1635 break; 1636 } 1637 PrevMember = Member; 1638 } 1639} 1640 1641void 1642Sema::MarkBaseAndMemberDestructorsReferenced(CXXDestructorDecl *Destructor) { 1643 // Ignore dependent destructors. 1644 if (Destructor->isDependentContext()) 1645 return; 1646 1647 CXXRecordDecl *ClassDecl = Destructor->getParent(); 1648 1649 // Non-static data members. 1650 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(), 1651 E = ClassDecl->field_end(); I != E; ++I) { 1652 FieldDecl *Field = *I; 1653 1654 QualType FieldType = Context.getBaseElementType(Field->getType()); 1655 1656 const RecordType* RT = FieldType->getAs<RecordType>(); 1657 if (!RT) 1658 continue; 1659 1660 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 1661 if (FieldClassDecl->hasTrivialDestructor()) 1662 continue; 1663 1664 const CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor(Context); 1665 MarkDeclarationReferenced(Destructor->getLocation(), 1666 const_cast<CXXDestructorDecl*>(Dtor)); 1667 } 1668 1669 // Bases. 1670 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 1671 E = ClassDecl->bases_end(); Base != E; ++Base) { 1672 // Ignore virtual bases. 1673 if (Base->isVirtual()) 1674 continue; 1675 1676 // Ignore trivial destructors. 1677 CXXRecordDecl *BaseClassDecl 1678 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 1679 if (BaseClassDecl->hasTrivialDestructor()) 1680 continue; 1681 1682 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context); 1683 MarkDeclarationReferenced(Destructor->getLocation(), 1684 const_cast<CXXDestructorDecl*>(Dtor)); 1685 } 1686 1687 // Virtual bases. 1688 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 1689 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 1690 // Ignore trivial destructors. 1691 CXXRecordDecl *BaseClassDecl 1692 = cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl()); 1693 if (BaseClassDecl->hasTrivialDestructor()) 1694 continue; 1695 1696 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context); 1697 MarkDeclarationReferenced(Destructor->getLocation(), 1698 const_cast<CXXDestructorDecl*>(Dtor)); 1699 } 1700} 1701 1702void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) { 1703 if (!CDtorDecl) 1704 return; 1705 1706 AdjustDeclIfTemplate(CDtorDecl); 1707 1708 if (CXXConstructorDecl *Constructor 1709 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>())) 1710 SetBaseOrMemberInitializers(Constructor, 0, 0, false); 1711} 1712 1713namespace { 1714 /// PureVirtualMethodCollector - traverses a class and its superclasses 1715 /// and determines if it has any pure virtual methods. 1716 class PureVirtualMethodCollector { 1717 ASTContext &Context; 1718 1719 public: 1720 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList; 1721 1722 private: 1723 MethodList Methods; 1724 1725 void Collect(const CXXRecordDecl* RD, MethodList& Methods); 1726 1727 public: 1728 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD) 1729 : Context(Ctx) { 1730 1731 MethodList List; 1732 Collect(RD, List); 1733 1734 // Copy the temporary list to methods, and make sure to ignore any 1735 // null entries. 1736 for (size_t i = 0, e = List.size(); i != e; ++i) { 1737 if (List[i]) 1738 Methods.push_back(List[i]); 1739 } 1740 } 1741 1742 bool empty() const { return Methods.empty(); } 1743 1744 MethodList::const_iterator methods_begin() { return Methods.begin(); } 1745 MethodList::const_iterator methods_end() { return Methods.end(); } 1746 }; 1747 1748 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD, 1749 MethodList& Methods) { 1750 // First, collect the pure virtual methods for the base classes. 1751 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(), 1752 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) { 1753 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) { 1754 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl()); 1755 if (BaseDecl && BaseDecl->isAbstract()) 1756 Collect(BaseDecl, Methods); 1757 } 1758 } 1759 1760 // Next, zero out any pure virtual methods that this class overrides. 1761 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy; 1762 1763 MethodSetTy OverriddenMethods; 1764 size_t MethodsSize = Methods.size(); 1765 1766 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end(); 1767 i != e; ++i) { 1768 // Traverse the record, looking for methods. 1769 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) { 1770 // If the method is pure virtual, add it to the methods vector. 1771 if (MD->isPure()) 1772 Methods.push_back(MD); 1773 1774 // Record all the overridden methods in our set. 1775 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 1776 E = MD->end_overridden_methods(); I != E; ++I) { 1777 // Keep track of the overridden methods. 1778 OverriddenMethods.insert(*I); 1779 } 1780 } 1781 } 1782 1783 // Now go through the methods and zero out all the ones we know are 1784 // overridden. 1785 for (size_t i = 0, e = MethodsSize; i != e; ++i) { 1786 if (OverriddenMethods.count(Methods[i])) 1787 Methods[i] = 0; 1788 } 1789 1790 } 1791} 1792 1793 1794bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 1795 unsigned DiagID, AbstractDiagSelID SelID, 1796 const CXXRecordDecl *CurrentRD) { 1797 if (SelID == -1) 1798 return RequireNonAbstractType(Loc, T, 1799 PDiag(DiagID), CurrentRD); 1800 else 1801 return RequireNonAbstractType(Loc, T, 1802 PDiag(DiagID) << SelID, CurrentRD); 1803} 1804 1805bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 1806 const PartialDiagnostic &PD, 1807 const CXXRecordDecl *CurrentRD) { 1808 if (!getLangOptions().CPlusPlus) 1809 return false; 1810 1811 if (const ArrayType *AT = Context.getAsArrayType(T)) 1812 return RequireNonAbstractType(Loc, AT->getElementType(), PD, 1813 CurrentRD); 1814 1815 if (const PointerType *PT = T->getAs<PointerType>()) { 1816 // Find the innermost pointer type. 1817 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 1818 PT = T; 1819 1820 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 1821 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD); 1822 } 1823 1824 const RecordType *RT = T->getAs<RecordType>(); 1825 if (!RT) 1826 return false; 1827 1828 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 1829 if (!RD) 1830 return false; 1831 1832 if (CurrentRD && CurrentRD != RD) 1833 return false; 1834 1835 if (!RD->isAbstract()) 1836 return false; 1837 1838 Diag(Loc, PD) << RD->getDeclName(); 1839 1840 // Check if we've already emitted the list of pure virtual functions for this 1841 // class. 1842 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 1843 return true; 1844 1845 PureVirtualMethodCollector Collector(Context, RD); 1846 1847 for (PureVirtualMethodCollector::MethodList::const_iterator I = 1848 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) { 1849 const CXXMethodDecl *MD = *I; 1850 1851 Diag(MD->getLocation(), diag::note_pure_virtual_function) << 1852 MD->getDeclName(); 1853 } 1854 1855 if (!PureVirtualClassDiagSet) 1856 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 1857 PureVirtualClassDiagSet->insert(RD); 1858 1859 return true; 1860} 1861 1862namespace { 1863 class AbstractClassUsageDiagnoser 1864 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> { 1865 Sema &SemaRef; 1866 CXXRecordDecl *AbstractClass; 1867 1868 bool VisitDeclContext(const DeclContext *DC) { 1869 bool Invalid = false; 1870 1871 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(), 1872 E = DC->decls_end(); I != E; ++I) 1873 Invalid |= Visit(*I); 1874 1875 return Invalid; 1876 } 1877 1878 public: 1879 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac) 1880 : SemaRef(SemaRef), AbstractClass(ac) { 1881 Visit(SemaRef.Context.getTranslationUnitDecl()); 1882 } 1883 1884 bool VisitFunctionDecl(const FunctionDecl *FD) { 1885 if (FD->isThisDeclarationADefinition()) { 1886 // No need to do the check if we're in a definition, because it requires 1887 // that the return/param types are complete. 1888 // because that requires 1889 return VisitDeclContext(FD); 1890 } 1891 1892 // Check the return type. 1893 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType(); 1894 bool Invalid = 1895 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy, 1896 diag::err_abstract_type_in_decl, 1897 Sema::AbstractReturnType, 1898 AbstractClass); 1899 1900 for (FunctionDecl::param_const_iterator I = FD->param_begin(), 1901 E = FD->param_end(); I != E; ++I) { 1902 const ParmVarDecl *VD = *I; 1903 Invalid |= 1904 SemaRef.RequireNonAbstractType(VD->getLocation(), 1905 VD->getOriginalType(), 1906 diag::err_abstract_type_in_decl, 1907 Sema::AbstractParamType, 1908 AbstractClass); 1909 } 1910 1911 return Invalid; 1912 } 1913 1914 bool VisitDecl(const Decl* D) { 1915 if (const DeclContext *DC = dyn_cast<DeclContext>(D)) 1916 return VisitDeclContext(DC); 1917 1918 return false; 1919 } 1920 }; 1921} 1922 1923void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 1924 DeclPtrTy TagDecl, 1925 SourceLocation LBrac, 1926 SourceLocation RBrac) { 1927 if (!TagDecl) 1928 return; 1929 1930 AdjustDeclIfTemplate(TagDecl); 1931 ActOnFields(S, RLoc, TagDecl, 1932 (DeclPtrTy*)FieldCollector->getCurFields(), 1933 FieldCollector->getCurNumFields(), LBrac, RBrac, 0); 1934 1935 CXXRecordDecl *RD = cast<CXXRecordDecl>(TagDecl.getAs<Decl>()); 1936 if (!RD->isAbstract()) { 1937 // Collect all the pure virtual methods and see if this is an abstract 1938 // class after all. 1939 PureVirtualMethodCollector Collector(Context, RD); 1940 if (!Collector.empty()) 1941 RD->setAbstract(true); 1942 } 1943 1944 if (RD->isAbstract()) 1945 (void)AbstractClassUsageDiagnoser(*this, RD); 1946 1947 if (!RD->isDependentType() && !RD->isInvalidDecl()) 1948 AddImplicitlyDeclaredMembersToClass(RD); 1949} 1950 1951/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 1952/// special functions, such as the default constructor, copy 1953/// constructor, or destructor, to the given C++ class (C++ 1954/// [special]p1). This routine can only be executed just before the 1955/// definition of the class is complete. 1956void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 1957 CanQualType ClassType 1958 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 1959 1960 // FIXME: Implicit declarations have exception specifications, which are 1961 // the union of the specifications of the implicitly called functions. 1962 1963 if (!ClassDecl->hasUserDeclaredConstructor()) { 1964 // C++ [class.ctor]p5: 1965 // A default constructor for a class X is a constructor of class X 1966 // that can be called without an argument. If there is no 1967 // user-declared constructor for class X, a default constructor is 1968 // implicitly declared. An implicitly-declared default constructor 1969 // is an inline public member of its class. 1970 DeclarationName Name 1971 = Context.DeclarationNames.getCXXConstructorName(ClassType); 1972 CXXConstructorDecl *DefaultCon = 1973 CXXConstructorDecl::Create(Context, ClassDecl, 1974 ClassDecl->getLocation(), Name, 1975 Context.getFunctionType(Context.VoidTy, 1976 0, 0, false, 0), 1977 /*DInfo=*/0, 1978 /*isExplicit=*/false, 1979 /*isInline=*/true, 1980 /*isImplicitlyDeclared=*/true); 1981 DefaultCon->setAccess(AS_public); 1982 DefaultCon->setImplicit(); 1983 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor()); 1984 ClassDecl->addDecl(DefaultCon); 1985 } 1986 1987 if (!ClassDecl->hasUserDeclaredCopyConstructor()) { 1988 // C++ [class.copy]p4: 1989 // If the class definition does not explicitly declare a copy 1990 // constructor, one is declared implicitly. 1991 1992 // C++ [class.copy]p5: 1993 // The implicitly-declared copy constructor for a class X will 1994 // have the form 1995 // 1996 // X::X(const X&) 1997 // 1998 // if 1999 bool HasConstCopyConstructor = true; 2000 2001 // -- each direct or virtual base class B of X has a copy 2002 // constructor whose first parameter is of type const B& or 2003 // const volatile B&, and 2004 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(); 2005 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) { 2006 const CXXRecordDecl *BaseClassDecl 2007 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 2008 HasConstCopyConstructor 2009 = BaseClassDecl->hasConstCopyConstructor(Context); 2010 } 2011 2012 // -- for all the nonstatic data members of X that are of a 2013 // class type M (or array thereof), each such class type 2014 // has a copy constructor whose first parameter is of type 2015 // const M& or const volatile M&. 2016 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(); 2017 HasConstCopyConstructor && Field != ClassDecl->field_end(); 2018 ++Field) { 2019 QualType FieldType = (*Field)->getType(); 2020 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 2021 FieldType = Array->getElementType(); 2022 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 2023 const CXXRecordDecl *FieldClassDecl 2024 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 2025 HasConstCopyConstructor 2026 = FieldClassDecl->hasConstCopyConstructor(Context); 2027 } 2028 } 2029 2030 // Otherwise, the implicitly declared copy constructor will have 2031 // the form 2032 // 2033 // X::X(X&) 2034 QualType ArgType = ClassType; 2035 if (HasConstCopyConstructor) 2036 ArgType = ArgType.withConst(); 2037 ArgType = Context.getLValueReferenceType(ArgType); 2038 2039 // An implicitly-declared copy constructor is an inline public 2040 // member of its class. 2041 DeclarationName Name 2042 = Context.DeclarationNames.getCXXConstructorName(ClassType); 2043 CXXConstructorDecl *CopyConstructor 2044 = CXXConstructorDecl::Create(Context, ClassDecl, 2045 ClassDecl->getLocation(), Name, 2046 Context.getFunctionType(Context.VoidTy, 2047 &ArgType, 1, 2048 false, 0), 2049 /*DInfo=*/0, 2050 /*isExplicit=*/false, 2051 /*isInline=*/true, 2052 /*isImplicitlyDeclared=*/true); 2053 CopyConstructor->setAccess(AS_public); 2054 CopyConstructor->setImplicit(); 2055 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor()); 2056 2057 // Add the parameter to the constructor. 2058 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 2059 ClassDecl->getLocation(), 2060 /*IdentifierInfo=*/0, 2061 ArgType, /*DInfo=*/0, 2062 VarDecl::None, 0); 2063 CopyConstructor->setParams(Context, &FromParam, 1); 2064 ClassDecl->addDecl(CopyConstructor); 2065 } 2066 2067 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 2068 // Note: The following rules are largely analoguous to the copy 2069 // constructor rules. Note that virtual bases are not taken into account 2070 // for determining the argument type of the operator. Note also that 2071 // operators taking an object instead of a reference are allowed. 2072 // 2073 // C++ [class.copy]p10: 2074 // If the class definition does not explicitly declare a copy 2075 // assignment operator, one is declared implicitly. 2076 // The implicitly-defined copy assignment operator for a class X 2077 // will have the form 2078 // 2079 // X& X::operator=(const X&) 2080 // 2081 // if 2082 bool HasConstCopyAssignment = true; 2083 2084 // -- each direct base class B of X has a copy assignment operator 2085 // whose parameter is of type const B&, const volatile B& or B, 2086 // and 2087 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(); 2088 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) { 2089 assert(!Base->getType()->isDependentType() && 2090 "Cannot generate implicit members for class with dependent bases."); 2091 const CXXRecordDecl *BaseClassDecl 2092 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 2093 const CXXMethodDecl *MD = 0; 2094 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context, 2095 MD); 2096 } 2097 2098 // -- for all the nonstatic data members of X that are of a class 2099 // type M (or array thereof), each such class type has a copy 2100 // assignment operator whose parameter is of type const M&, 2101 // const volatile M& or M. 2102 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(); 2103 HasConstCopyAssignment && Field != ClassDecl->field_end(); 2104 ++Field) { 2105 QualType FieldType = (*Field)->getType(); 2106 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 2107 FieldType = Array->getElementType(); 2108 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 2109 const CXXRecordDecl *FieldClassDecl 2110 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 2111 const CXXMethodDecl *MD = 0; 2112 HasConstCopyAssignment 2113 = FieldClassDecl->hasConstCopyAssignment(Context, MD); 2114 } 2115 } 2116 2117 // Otherwise, the implicitly declared copy assignment operator will 2118 // have the form 2119 // 2120 // X& X::operator=(X&) 2121 QualType ArgType = ClassType; 2122 QualType RetType = Context.getLValueReferenceType(ArgType); 2123 if (HasConstCopyAssignment) 2124 ArgType = ArgType.withConst(); 2125 ArgType = Context.getLValueReferenceType(ArgType); 2126 2127 // An implicitly-declared copy assignment operator is an inline public 2128 // member of its class. 2129 DeclarationName Name = 2130 Context.DeclarationNames.getCXXOperatorName(OO_Equal); 2131 CXXMethodDecl *CopyAssignment = 2132 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name, 2133 Context.getFunctionType(RetType, &ArgType, 1, 2134 false, 0), 2135 /*DInfo=*/0, /*isStatic=*/false, /*isInline=*/true); 2136 CopyAssignment->setAccess(AS_public); 2137 CopyAssignment->setImplicit(); 2138 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment()); 2139 CopyAssignment->setCopyAssignment(true); 2140 2141 // Add the parameter to the operator. 2142 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 2143 ClassDecl->getLocation(), 2144 /*IdentifierInfo=*/0, 2145 ArgType, /*DInfo=*/0, 2146 VarDecl::None, 0); 2147 CopyAssignment->setParams(Context, &FromParam, 1); 2148 2149 // Don't call addedAssignmentOperator. There is no way to distinguish an 2150 // implicit from an explicit assignment operator. 2151 ClassDecl->addDecl(CopyAssignment); 2152 } 2153 2154 if (!ClassDecl->hasUserDeclaredDestructor()) { 2155 // C++ [class.dtor]p2: 2156 // If a class has no user-declared destructor, a destructor is 2157 // declared implicitly. An implicitly-declared destructor is an 2158 // inline public member of its class. 2159 DeclarationName Name 2160 = Context.DeclarationNames.getCXXDestructorName(ClassType); 2161 CXXDestructorDecl *Destructor 2162 = CXXDestructorDecl::Create(Context, ClassDecl, 2163 ClassDecl->getLocation(), Name, 2164 Context.getFunctionType(Context.VoidTy, 2165 0, 0, false, 0), 2166 /*isInline=*/true, 2167 /*isImplicitlyDeclared=*/true); 2168 Destructor->setAccess(AS_public); 2169 Destructor->setImplicit(); 2170 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 2171 ClassDecl->addDecl(Destructor); 2172 2173 AddOverriddenMethods(ClassDecl, Destructor); 2174 CheckDestructor(Destructor, false); 2175 } 2176} 2177 2178void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) { 2179 Decl *D = TemplateD.getAs<Decl>(); 2180 if (!D) 2181 return; 2182 2183 TemplateParameterList *Params = 0; 2184 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) 2185 Params = Template->getTemplateParameters(); 2186 else if (ClassTemplatePartialSpecializationDecl *PartialSpec 2187 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 2188 Params = PartialSpec->getTemplateParameters(); 2189 else 2190 return; 2191 2192 for (TemplateParameterList::iterator Param = Params->begin(), 2193 ParamEnd = Params->end(); 2194 Param != ParamEnd; ++Param) { 2195 NamedDecl *Named = cast<NamedDecl>(*Param); 2196 if (Named->getDeclName()) { 2197 S->AddDecl(DeclPtrTy::make(Named)); 2198 IdResolver.AddDecl(Named); 2199 } 2200 } 2201} 2202 2203/// ActOnStartDelayedCXXMethodDeclaration - We have completed 2204/// parsing a top-level (non-nested) C++ class, and we are now 2205/// parsing those parts of the given Method declaration that could 2206/// not be parsed earlier (C++ [class.mem]p2), such as default 2207/// arguments. This action should enter the scope of the given 2208/// Method declaration as if we had just parsed the qualified method 2209/// name. However, it should not bring the parameters into scope; 2210/// that will be performed by ActOnDelayedCXXMethodParameter. 2211void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) { 2212 if (!MethodD) 2213 return; 2214 2215 AdjustDeclIfTemplate(MethodD); 2216 2217 CXXScopeSpec SS; 2218 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>()); 2219 QualType ClassTy 2220 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 2221 SS.setScopeRep( 2222 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr())); 2223 ActOnCXXEnterDeclaratorScope(S, SS); 2224} 2225 2226/// ActOnDelayedCXXMethodParameter - We've already started a delayed 2227/// C++ method declaration. We're (re-)introducing the given 2228/// function parameter into scope for use in parsing later parts of 2229/// the method declaration. For example, we could see an 2230/// ActOnParamDefaultArgument event for this parameter. 2231void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) { 2232 if (!ParamD) 2233 return; 2234 2235 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>()); 2236 2237 // If this parameter has an unparsed default argument, clear it out 2238 // to make way for the parsed default argument. 2239 if (Param->hasUnparsedDefaultArg()) 2240 Param->setDefaultArg(0); 2241 2242 S->AddDecl(DeclPtrTy::make(Param)); 2243 if (Param->getDeclName()) 2244 IdResolver.AddDecl(Param); 2245} 2246 2247/// ActOnFinishDelayedCXXMethodDeclaration - We have finished 2248/// processing the delayed method declaration for Method. The method 2249/// declaration is now considered finished. There may be a separate 2250/// ActOnStartOfFunctionDef action later (not necessarily 2251/// immediately!) for this method, if it was also defined inside the 2252/// class body. 2253void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) { 2254 if (!MethodD) 2255 return; 2256 2257 AdjustDeclIfTemplate(MethodD); 2258 2259 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>()); 2260 CXXScopeSpec SS; 2261 QualType ClassTy 2262 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 2263 SS.setScopeRep( 2264 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr())); 2265 ActOnCXXExitDeclaratorScope(S, SS); 2266 2267 // Now that we have our default arguments, check the constructor 2268 // again. It could produce additional diagnostics or affect whether 2269 // the class has implicitly-declared destructors, among other 2270 // things. 2271 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 2272 CheckConstructor(Constructor); 2273 2274 // Check the default arguments, which we may have added. 2275 if (!Method->isInvalidDecl()) 2276 CheckCXXDefaultArguments(Method); 2277} 2278 2279/// CheckConstructorDeclarator - Called by ActOnDeclarator to check 2280/// the well-formedness of the constructor declarator @p D with type @p 2281/// R. If there are any errors in the declarator, this routine will 2282/// emit diagnostics and set the invalid bit to true. In any case, the type 2283/// will be updated to reflect a well-formed type for the constructor and 2284/// returned. 2285QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 2286 FunctionDecl::StorageClass &SC) { 2287 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 2288 2289 // C++ [class.ctor]p3: 2290 // A constructor shall not be virtual (10.3) or static (9.4). A 2291 // constructor can be invoked for a const, volatile or const 2292 // volatile object. A constructor shall not be declared const, 2293 // volatile, or const volatile (9.3.2). 2294 if (isVirtual) { 2295 if (!D.isInvalidType()) 2296 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 2297 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 2298 << SourceRange(D.getIdentifierLoc()); 2299 D.setInvalidType(); 2300 } 2301 if (SC == FunctionDecl::Static) { 2302 if (!D.isInvalidType()) 2303 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 2304 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 2305 << SourceRange(D.getIdentifierLoc()); 2306 D.setInvalidType(); 2307 SC = FunctionDecl::None; 2308 } 2309 2310 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 2311 if (FTI.TypeQuals != 0) { 2312 if (FTI.TypeQuals & Qualifiers::Const) 2313 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 2314 << "const" << SourceRange(D.getIdentifierLoc()); 2315 if (FTI.TypeQuals & Qualifiers::Volatile) 2316 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 2317 << "volatile" << SourceRange(D.getIdentifierLoc()); 2318 if (FTI.TypeQuals & Qualifiers::Restrict) 2319 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 2320 << "restrict" << SourceRange(D.getIdentifierLoc()); 2321 } 2322 2323 // Rebuild the function type "R" without any type qualifiers (in 2324 // case any of the errors above fired) and with "void" as the 2325 // return type, since constructors don't have return types. We 2326 // *always* have to do this, because GetTypeForDeclarator will 2327 // put in a result type of "int" when none was specified. 2328 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 2329 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(), 2330 Proto->getNumArgs(), 2331 Proto->isVariadic(), 0); 2332} 2333 2334/// CheckConstructor - Checks a fully-formed constructor for 2335/// well-formedness, issuing any diagnostics required. Returns true if 2336/// the constructor declarator is invalid. 2337void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 2338 CXXRecordDecl *ClassDecl 2339 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 2340 if (!ClassDecl) 2341 return Constructor->setInvalidDecl(); 2342 2343 // C++ [class.copy]p3: 2344 // A declaration of a constructor for a class X is ill-formed if 2345 // its first parameter is of type (optionally cv-qualified) X and 2346 // either there are no other parameters or else all other 2347 // parameters have default arguments. 2348 if (!Constructor->isInvalidDecl() && 2349 ((Constructor->getNumParams() == 1) || 2350 (Constructor->getNumParams() > 1 && 2351 Constructor->getParamDecl(1)->hasDefaultArg())) && 2352 Constructor->getTemplateSpecializationKind() 2353 != TSK_ImplicitInstantiation) { 2354 QualType ParamType = Constructor->getParamDecl(0)->getType(); 2355 QualType ClassTy = Context.getTagDeclType(ClassDecl); 2356 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 2357 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 2358 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 2359 << CodeModificationHint::CreateInsertion(ParamLoc, " const &"); 2360 2361 // FIXME: Rather that making the constructor invalid, we should endeavor 2362 // to fix the type. 2363 Constructor->setInvalidDecl(); 2364 } 2365 } 2366 2367 // Notify the class that we've added a constructor. 2368 ClassDecl->addedConstructor(Context, Constructor); 2369} 2370 2371/// CheckDestructor - Checks a fully-formed destructor for well-formedness, 2372/// issuing any diagnostics required. Returns true on error. 2373bool Sema::CheckDestructor(CXXDestructorDecl *Destructor, bool Diagnose) { 2374 CXXRecordDecl *RD = Destructor->getParent(); 2375 2376 if (Destructor->isVirtual()) { 2377 SourceLocation Loc; 2378 2379 if (!Destructor->isImplicit()) 2380 Loc = Destructor->getLocation(); 2381 else 2382 Loc = RD->getLocation(); 2383 2384 // If we have a virtual destructor, look up the deallocation function 2385 FunctionDecl *OperatorDelete = 0; 2386 DeclarationName Name = 2387 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 2388 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete, Diagnose)) 2389 return true; 2390 2391 Destructor->setOperatorDelete(OperatorDelete); 2392 } 2393 2394 return false; 2395} 2396 2397static inline bool 2398FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) { 2399 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 2400 FTI.ArgInfo[0].Param && 2401 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType()); 2402} 2403 2404/// CheckDestructorDeclarator - Called by ActOnDeclarator to check 2405/// the well-formednes of the destructor declarator @p D with type @p 2406/// R. If there are any errors in the declarator, this routine will 2407/// emit diagnostics and set the declarator to invalid. Even if this happens, 2408/// will be updated to reflect a well-formed type for the destructor and 2409/// returned. 2410QualType Sema::CheckDestructorDeclarator(Declarator &D, 2411 FunctionDecl::StorageClass& SC) { 2412 // C++ [class.dtor]p1: 2413 // [...] A typedef-name that names a class is a class-name 2414 // (7.1.3); however, a typedef-name that names a class shall not 2415 // be used as the identifier in the declarator for a destructor 2416 // declaration. 2417 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 2418 if (isa<TypedefType>(DeclaratorType)) { 2419 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 2420 << DeclaratorType; 2421 D.setInvalidType(); 2422 } 2423 2424 // C++ [class.dtor]p2: 2425 // A destructor is used to destroy objects of its class type. A 2426 // destructor takes no parameters, and no return type can be 2427 // specified for it (not even void). The address of a destructor 2428 // shall not be taken. A destructor shall not be static. A 2429 // destructor can be invoked for a const, volatile or const 2430 // volatile object. A destructor shall not be declared const, 2431 // volatile or const volatile (9.3.2). 2432 if (SC == FunctionDecl::Static) { 2433 if (!D.isInvalidType()) 2434 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 2435 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 2436 << SourceRange(D.getIdentifierLoc()); 2437 SC = FunctionDecl::None; 2438 D.setInvalidType(); 2439 } 2440 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 2441 // Destructors don't have return types, but the parser will 2442 // happily parse something like: 2443 // 2444 // class X { 2445 // float ~X(); 2446 // }; 2447 // 2448 // The return type will be eliminated later. 2449 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 2450 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 2451 << SourceRange(D.getIdentifierLoc()); 2452 } 2453 2454 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 2455 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 2456 if (FTI.TypeQuals & Qualifiers::Const) 2457 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 2458 << "const" << SourceRange(D.getIdentifierLoc()); 2459 if (FTI.TypeQuals & Qualifiers::Volatile) 2460 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 2461 << "volatile" << SourceRange(D.getIdentifierLoc()); 2462 if (FTI.TypeQuals & Qualifiers::Restrict) 2463 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 2464 << "restrict" << SourceRange(D.getIdentifierLoc()); 2465 D.setInvalidType(); 2466 } 2467 2468 // Make sure we don't have any parameters. 2469 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) { 2470 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 2471 2472 // Delete the parameters. 2473 FTI.freeArgs(); 2474 D.setInvalidType(); 2475 } 2476 2477 // Make sure the destructor isn't variadic. 2478 if (FTI.isVariadic) { 2479 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 2480 D.setInvalidType(); 2481 } 2482 2483 // Rebuild the function type "R" without any type qualifiers or 2484 // parameters (in case any of the errors above fired) and with 2485 // "void" as the return type, since destructors don't have return 2486 // types. We *always* have to do this, because GetTypeForDeclarator 2487 // will put in a result type of "int" when none was specified. 2488 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0); 2489} 2490 2491/// CheckConversionDeclarator - Called by ActOnDeclarator to check the 2492/// well-formednes of the conversion function declarator @p D with 2493/// type @p R. If there are any errors in the declarator, this routine 2494/// will emit diagnostics and return true. Otherwise, it will return 2495/// false. Either way, the type @p R will be updated to reflect a 2496/// well-formed type for the conversion operator. 2497void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 2498 FunctionDecl::StorageClass& SC) { 2499 // C++ [class.conv.fct]p1: 2500 // Neither parameter types nor return type can be specified. The 2501 // type of a conversion function (8.3.5) is "function taking no 2502 // parameter returning conversion-type-id." 2503 if (SC == FunctionDecl::Static) { 2504 if (!D.isInvalidType()) 2505 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 2506 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 2507 << SourceRange(D.getIdentifierLoc()); 2508 D.setInvalidType(); 2509 SC = FunctionDecl::None; 2510 } 2511 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 2512 // Conversion functions don't have return types, but the parser will 2513 // happily parse something like: 2514 // 2515 // class X { 2516 // float operator bool(); 2517 // }; 2518 // 2519 // The return type will be changed later anyway. 2520 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 2521 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 2522 << SourceRange(D.getIdentifierLoc()); 2523 } 2524 2525 // Make sure we don't have any parameters. 2526 if (R->getAs<FunctionProtoType>()->getNumArgs() > 0) { 2527 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 2528 2529 // Delete the parameters. 2530 D.getTypeObject(0).Fun.freeArgs(); 2531 D.setInvalidType(); 2532 } 2533 2534 // Make sure the conversion function isn't variadic. 2535 if (R->getAs<FunctionProtoType>()->isVariadic() && !D.isInvalidType()) { 2536 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 2537 D.setInvalidType(); 2538 } 2539 2540 // C++ [class.conv.fct]p4: 2541 // The conversion-type-id shall not represent a function type nor 2542 // an array type. 2543 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId); 2544 if (ConvType->isArrayType()) { 2545 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 2546 ConvType = Context.getPointerType(ConvType); 2547 D.setInvalidType(); 2548 } else if (ConvType->isFunctionType()) { 2549 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 2550 ConvType = Context.getPointerType(ConvType); 2551 D.setInvalidType(); 2552 } 2553 2554 // Rebuild the function type "R" without any parameters (in case any 2555 // of the errors above fired) and with the conversion type as the 2556 // return type. 2557 R = Context.getFunctionType(ConvType, 0, 0, false, 2558 R->getAs<FunctionProtoType>()->getTypeQuals()); 2559 2560 // C++0x explicit conversion operators. 2561 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x) 2562 Diag(D.getDeclSpec().getExplicitSpecLoc(), 2563 diag::warn_explicit_conversion_functions) 2564 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 2565} 2566 2567/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 2568/// the declaration of the given C++ conversion function. This routine 2569/// is responsible for recording the conversion function in the C++ 2570/// class, if possible. 2571Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 2572 assert(Conversion && "Expected to receive a conversion function declaration"); 2573 2574 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 2575 2576 // Make sure we aren't redeclaring the conversion function. 2577 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 2578 2579 // C++ [class.conv.fct]p1: 2580 // [...] A conversion function is never used to convert a 2581 // (possibly cv-qualified) object to the (possibly cv-qualified) 2582 // same object type (or a reference to it), to a (possibly 2583 // cv-qualified) base class of that type (or a reference to it), 2584 // or to (possibly cv-qualified) void. 2585 // FIXME: Suppress this warning if the conversion function ends up being a 2586 // virtual function that overrides a virtual function in a base class. 2587 QualType ClassType 2588 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 2589 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 2590 ConvType = ConvTypeRef->getPointeeType(); 2591 if (ConvType->isRecordType()) { 2592 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 2593 if (ConvType == ClassType) 2594 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 2595 << ClassType; 2596 else if (IsDerivedFrom(ClassType, ConvType)) 2597 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 2598 << ClassType << ConvType; 2599 } else if (ConvType->isVoidType()) { 2600 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 2601 << ClassType << ConvType; 2602 } 2603 2604 if (Conversion->getPreviousDeclaration()) { 2605 const NamedDecl *ExpectedPrevDecl = Conversion->getPreviousDeclaration(); 2606 if (FunctionTemplateDecl *ConversionTemplate 2607 = Conversion->getDescribedFunctionTemplate()) 2608 ExpectedPrevDecl = ConversionTemplate->getPreviousDeclaration(); 2609 if (ClassDecl->replaceConversion(ExpectedPrevDecl, Conversion)) 2610 return DeclPtrTy::make(Conversion); 2611 assert(Conversion->isInvalidDecl() && "Conversion should not get here."); 2612 } else if (FunctionTemplateDecl *ConversionTemplate 2613 = Conversion->getDescribedFunctionTemplate()) 2614 ClassDecl->addConversionFunction(ConversionTemplate); 2615 else if (!Conversion->getPrimaryTemplate()) // ignore specializations 2616 ClassDecl->addConversionFunction(Conversion); 2617 2618 return DeclPtrTy::make(Conversion); 2619} 2620 2621//===----------------------------------------------------------------------===// 2622// Namespace Handling 2623//===----------------------------------------------------------------------===// 2624 2625/// ActOnStartNamespaceDef - This is called at the start of a namespace 2626/// definition. 2627Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 2628 SourceLocation IdentLoc, 2629 IdentifierInfo *II, 2630 SourceLocation LBrace) { 2631 NamespaceDecl *Namespc = 2632 NamespaceDecl::Create(Context, CurContext, IdentLoc, II); 2633 Namespc->setLBracLoc(LBrace); 2634 2635 Scope *DeclRegionScope = NamespcScope->getParent(); 2636 2637 if (II) { 2638 // C++ [namespace.def]p2: 2639 // The identifier in an original-namespace-definition shall not have been 2640 // previously defined in the declarative region in which the 2641 // original-namespace-definition appears. The identifier in an 2642 // original-namespace-definition is the name of the namespace. Subsequently 2643 // in that declarative region, it is treated as an original-namespace-name. 2644 2645 NamedDecl *PrevDecl 2646 = LookupSingleName(DeclRegionScope, II, LookupOrdinaryName, 2647 ForRedeclaration); 2648 2649 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) { 2650 // This is an extended namespace definition. 2651 // Attach this namespace decl to the chain of extended namespace 2652 // definitions. 2653 OrigNS->setNextNamespace(Namespc); 2654 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace()); 2655 2656 // Remove the previous declaration from the scope. 2657 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) { 2658 IdResolver.RemoveDecl(OrigNS); 2659 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS)); 2660 } 2661 } else if (PrevDecl) { 2662 // This is an invalid name redefinition. 2663 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind) 2664 << Namespc->getDeclName(); 2665 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 2666 Namespc->setInvalidDecl(); 2667 // Continue on to push Namespc as current DeclContext and return it. 2668 } else if (II->isStr("std") && 2669 CurContext->getLookupContext()->isTranslationUnit()) { 2670 // This is the first "real" definition of the namespace "std", so update 2671 // our cache of the "std" namespace to point at this definition. 2672 if (StdNamespace) { 2673 // We had already defined a dummy namespace "std". Link this new 2674 // namespace definition to the dummy namespace "std". 2675 StdNamespace->setNextNamespace(Namespc); 2676 StdNamespace->setLocation(IdentLoc); 2677 Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace()); 2678 } 2679 2680 // Make our StdNamespace cache point at the first real definition of the 2681 // "std" namespace. 2682 StdNamespace = Namespc; 2683 } 2684 2685 PushOnScopeChains(Namespc, DeclRegionScope); 2686 } else { 2687 // Anonymous namespaces. 2688 2689 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 2690 // behaves as if it were replaced by 2691 // namespace unique { /* empty body */ } 2692 // using namespace unique; 2693 // namespace unique { namespace-body } 2694 // where all occurrences of 'unique' in a translation unit are 2695 // replaced by the same identifier and this identifier differs 2696 // from all other identifiers in the entire program. 2697 2698 // We just create the namespace with an empty name and then add an 2699 // implicit using declaration, just like the standard suggests. 2700 // 2701 // CodeGen enforces the "universally unique" aspect by giving all 2702 // declarations semantically contained within an anonymous 2703 // namespace internal linkage. 2704 2705 assert(Namespc->isAnonymousNamespace()); 2706 CurContext->addDecl(Namespc); 2707 2708 UsingDirectiveDecl* UD 2709 = UsingDirectiveDecl::Create(Context, CurContext, 2710 /* 'using' */ LBrace, 2711 /* 'namespace' */ SourceLocation(), 2712 /* qualifier */ SourceRange(), 2713 /* NNS */ NULL, 2714 /* identifier */ SourceLocation(), 2715 Namespc, 2716 /* Ancestor */ CurContext); 2717 UD->setImplicit(); 2718 CurContext->addDecl(UD); 2719 } 2720 2721 // Although we could have an invalid decl (i.e. the namespace name is a 2722 // redefinition), push it as current DeclContext and try to continue parsing. 2723 // FIXME: We should be able to push Namespc here, so that the each DeclContext 2724 // for the namespace has the declarations that showed up in that particular 2725 // namespace definition. 2726 PushDeclContext(NamespcScope, Namespc); 2727 return DeclPtrTy::make(Namespc); 2728} 2729 2730/// getNamespaceDecl - Returns the namespace a decl represents. If the decl 2731/// is a namespace alias, returns the namespace it points to. 2732static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 2733 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 2734 return AD->getNamespace(); 2735 return dyn_cast_or_null<NamespaceDecl>(D); 2736} 2737 2738/// ActOnFinishNamespaceDef - This callback is called after a namespace is 2739/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 2740void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) { 2741 Decl *Dcl = D.getAs<Decl>(); 2742 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 2743 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 2744 Namespc->setRBracLoc(RBrace); 2745 PopDeclContext(); 2746} 2747 2748Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S, 2749 SourceLocation UsingLoc, 2750 SourceLocation NamespcLoc, 2751 const CXXScopeSpec &SS, 2752 SourceLocation IdentLoc, 2753 IdentifierInfo *NamespcName, 2754 AttributeList *AttrList) { 2755 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 2756 assert(NamespcName && "Invalid NamespcName."); 2757 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 2758 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 2759 2760 UsingDirectiveDecl *UDir = 0; 2761 2762 // Lookup namespace name. 2763 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 2764 LookupParsedName(R, S, &SS); 2765 if (R.isAmbiguous()) 2766 return DeclPtrTy(); 2767 2768 if (!R.empty()) { 2769 NamedDecl *Named = R.getFoundDecl(); 2770 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named)) 2771 && "expected namespace decl"); 2772 // C++ [namespace.udir]p1: 2773 // A using-directive specifies that the names in the nominated 2774 // namespace can be used in the scope in which the 2775 // using-directive appears after the using-directive. During 2776 // unqualified name lookup (3.4.1), the names appear as if they 2777 // were declared in the nearest enclosing namespace which 2778 // contains both the using-directive and the nominated 2779 // namespace. [Note: in this context, "contains" means "contains 2780 // directly or indirectly". ] 2781 2782 // Find enclosing context containing both using-directive and 2783 // nominated namespace. 2784 NamespaceDecl *NS = getNamespaceDecl(Named); 2785 DeclContext *CommonAncestor = cast<DeclContext>(NS); 2786 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 2787 CommonAncestor = CommonAncestor->getParent(); 2788 2789 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 2790 SS.getRange(), 2791 (NestedNameSpecifier *)SS.getScopeRep(), 2792 IdentLoc, Named, CommonAncestor); 2793 PushUsingDirective(S, UDir); 2794 } else { 2795 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 2796 } 2797 2798 // FIXME: We ignore attributes for now. 2799 delete AttrList; 2800 return DeclPtrTy::make(UDir); 2801} 2802 2803void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 2804 // If scope has associated entity, then using directive is at namespace 2805 // or translation unit scope. We add UsingDirectiveDecls, into 2806 // it's lookup structure. 2807 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) 2808 Ctx->addDecl(UDir); 2809 else 2810 // Otherwise it is block-sope. using-directives will affect lookup 2811 // only to the end of scope. 2812 S->PushUsingDirective(DeclPtrTy::make(UDir)); 2813} 2814 2815 2816Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S, 2817 AccessSpecifier AS, 2818 SourceLocation UsingLoc, 2819 const CXXScopeSpec &SS, 2820 UnqualifiedId &Name, 2821 AttributeList *AttrList, 2822 bool IsTypeName, 2823 SourceLocation TypenameLoc) { 2824 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 2825 2826 switch (Name.getKind()) { 2827 case UnqualifiedId::IK_Identifier: 2828 case UnqualifiedId::IK_OperatorFunctionId: 2829 case UnqualifiedId::IK_LiteralOperatorId: 2830 case UnqualifiedId::IK_ConversionFunctionId: 2831 break; 2832 2833 case UnqualifiedId::IK_ConstructorName: 2834 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor) 2835 << SS.getRange(); 2836 return DeclPtrTy(); 2837 2838 case UnqualifiedId::IK_DestructorName: 2839 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor) 2840 << SS.getRange(); 2841 return DeclPtrTy(); 2842 2843 case UnqualifiedId::IK_TemplateId: 2844 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id) 2845 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 2846 return DeclPtrTy(); 2847 } 2848 2849 DeclarationName TargetName = GetNameFromUnqualifiedId(Name); 2850 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 2851 Name.getSourceRange().getBegin(), 2852 TargetName, AttrList, 2853 /* IsInstantiation */ false, 2854 IsTypeName, TypenameLoc); 2855 if (UD) { 2856 PushOnScopeChains(UD, S); 2857 UD->setAccess(AS); 2858 } 2859 2860 return DeclPtrTy::make(UD); 2861} 2862 2863/// Builds a shadow declaration corresponding to a 'using' declaration. 2864static UsingShadowDecl *BuildUsingShadowDecl(Sema &SemaRef, Scope *S, 2865 AccessSpecifier AS, 2866 UsingDecl *UD, NamedDecl *Orig) { 2867 // FIXME: diagnose hiding, collisions 2868 2869 // If we resolved to another shadow declaration, just coalesce them. 2870 if (isa<UsingShadowDecl>(Orig)) { 2871 Orig = cast<UsingShadowDecl>(Orig)->getTargetDecl(); 2872 assert(!isa<UsingShadowDecl>(Orig) && "nested shadow declaration"); 2873 } 2874 2875 UsingShadowDecl *Shadow 2876 = UsingShadowDecl::Create(SemaRef.Context, SemaRef.CurContext, 2877 UD->getLocation(), UD, Orig); 2878 UD->addShadowDecl(Shadow); 2879 2880 if (S) 2881 SemaRef.PushOnScopeChains(Shadow, S); 2882 else 2883 SemaRef.CurContext->addDecl(Shadow); 2884 Shadow->setAccess(AS); 2885 2886 return Shadow; 2887} 2888 2889/// Builds a using declaration. 2890/// 2891/// \param IsInstantiation - Whether this call arises from an 2892/// instantiation of an unresolved using declaration. We treat 2893/// the lookup differently for these declarations. 2894NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 2895 SourceLocation UsingLoc, 2896 const CXXScopeSpec &SS, 2897 SourceLocation IdentLoc, 2898 DeclarationName Name, 2899 AttributeList *AttrList, 2900 bool IsInstantiation, 2901 bool IsTypeName, 2902 SourceLocation TypenameLoc) { 2903 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 2904 assert(IdentLoc.isValid() && "Invalid TargetName location."); 2905 2906 // FIXME: We ignore attributes for now. 2907 delete AttrList; 2908 2909 if (SS.isEmpty()) { 2910 Diag(IdentLoc, diag::err_using_requires_qualname); 2911 return 0; 2912 } 2913 2914 NestedNameSpecifier *NNS = 2915 static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 2916 2917 DeclContext *LookupContext = computeDeclContext(SS); 2918 if (!LookupContext) { 2919 if (IsTypeName) { 2920 return UnresolvedUsingTypenameDecl::Create(Context, CurContext, 2921 UsingLoc, TypenameLoc, 2922 SS.getRange(), NNS, 2923 IdentLoc, Name); 2924 } else { 2925 return UnresolvedUsingValueDecl::Create(Context, CurContext, 2926 UsingLoc, SS.getRange(), NNS, 2927 IdentLoc, Name); 2928 } 2929 } 2930 2931 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) { 2932 // C++0x N2914 [namespace.udecl]p3: 2933 // A using-declaration used as a member-declaration shall refer to a member 2934 // of a base class of the class being defined, shall refer to a member of an 2935 // anonymous union that is a member of a base class of the class being 2936 // defined, or shall refer to an enumerator for an enumeration type that is 2937 // a member of a base class of the class being defined. 2938 2939 CXXRecordDecl *LookupRD = dyn_cast<CXXRecordDecl>(LookupContext); 2940 if (!LookupRD || !RD->isDerivedFrom(LookupRD)) { 2941 Diag(SS.getRange().getBegin(), 2942 diag::err_using_decl_nested_name_specifier_is_not_a_base_class) 2943 << NNS << RD->getDeclName(); 2944 return 0; 2945 } 2946 } else { 2947 // C++0x N2914 [namespace.udecl]p8: 2948 // A using-declaration for a class member shall be a member-declaration. 2949 if (isa<CXXRecordDecl>(LookupContext)) { 2950 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_class_member) 2951 << SS.getRange(); 2952 return 0; 2953 } 2954 } 2955 2956 // Look up the target name. Unlike most lookups, we do not want to 2957 // hide tag declarations: tag names are visible through the using 2958 // declaration even if hidden by ordinary names. 2959 LookupResult R(*this, Name, IdentLoc, LookupOrdinaryName); 2960 2961 // We don't hide tags behind ordinary decls if we're in a 2962 // non-dependent context, but in a dependent context, this is 2963 // important for the stability of two-phase lookup. 2964 if (!IsInstantiation) 2965 R.setHideTags(false); 2966 2967 LookupQualifiedName(R, LookupContext); 2968 2969 if (R.empty()) { 2970 Diag(IdentLoc, diag::err_no_member) 2971 << Name << LookupContext << SS.getRange(); 2972 return 0; 2973 } 2974 2975 if (R.isAmbiguous()) 2976 return 0; 2977 2978 if (IsTypeName) { 2979 // If we asked for a typename and got a non-type decl, error out. 2980 if (R.getResultKind() != LookupResult::Found 2981 || !isa<TypeDecl>(R.getFoundDecl())) { 2982 Diag(IdentLoc, diag::err_using_typename_non_type); 2983 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 2984 Diag((*I)->getUnderlyingDecl()->getLocation(), 2985 diag::note_using_decl_target); 2986 return 0; 2987 } 2988 } else { 2989 // If we asked for a non-typename and we got a type, error out, 2990 // but only if this is an instantiation of an unresolved using 2991 // decl. Otherwise just silently find the type name. 2992 if (IsInstantiation && 2993 R.getResultKind() == LookupResult::Found && 2994 isa<TypeDecl>(R.getFoundDecl())) { 2995 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 2996 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 2997 return 0; 2998 } 2999 } 3000 3001 // C++0x N2914 [namespace.udecl]p6: 3002 // A using-declaration shall not name a namespace. 3003 if (R.getResultKind() == LookupResult::Found 3004 && isa<NamespaceDecl>(R.getFoundDecl())) { 3005 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 3006 << SS.getRange(); 3007 return 0; 3008 } 3009 3010 UsingDecl *UD = UsingDecl::Create(Context, CurContext, IdentLoc, 3011 SS.getRange(), UsingLoc, NNS, Name, 3012 IsTypeName); 3013 3014 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 3015 BuildUsingShadowDecl(*this, S, AS, UD, *I); 3016 3017 return UD; 3018} 3019 3020Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S, 3021 SourceLocation NamespaceLoc, 3022 SourceLocation AliasLoc, 3023 IdentifierInfo *Alias, 3024 const CXXScopeSpec &SS, 3025 SourceLocation IdentLoc, 3026 IdentifierInfo *Ident) { 3027 3028 // Lookup the namespace name. 3029 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 3030 LookupParsedName(R, S, &SS); 3031 3032 // Check if we have a previous declaration with the same name. 3033 if (NamedDecl *PrevDecl 3034 = LookupSingleName(S, Alias, LookupOrdinaryName, ForRedeclaration)) { 3035 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 3036 // We already have an alias with the same name that points to the same 3037 // namespace, so don't create a new one. 3038 if (!R.isAmbiguous() && !R.empty() && 3039 AD->getNamespace() == getNamespaceDecl(R.getFoundDecl())) 3040 return DeclPtrTy(); 3041 } 3042 3043 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition : 3044 diag::err_redefinition_different_kind; 3045 Diag(AliasLoc, DiagID) << Alias; 3046 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 3047 return DeclPtrTy(); 3048 } 3049 3050 if (R.isAmbiguous()) 3051 return DeclPtrTy(); 3052 3053 if (R.empty()) { 3054 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange(); 3055 return DeclPtrTy(); 3056 } 3057 3058 NamespaceAliasDecl *AliasDecl = 3059 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 3060 Alias, SS.getRange(), 3061 (NestedNameSpecifier *)SS.getScopeRep(), 3062 IdentLoc, R.getFoundDecl()); 3063 3064 CurContext->addDecl(AliasDecl); 3065 return DeclPtrTy::make(AliasDecl); 3066} 3067 3068void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 3069 CXXConstructorDecl *Constructor) { 3070 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() && 3071 !Constructor->isUsed()) && 3072 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 3073 3074 CXXRecordDecl *ClassDecl 3075 = cast<CXXRecordDecl>(Constructor->getDeclContext()); 3076 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 3077 3078 if (SetBaseOrMemberInitializers(Constructor, 0, 0, true)) { 3079 Diag(CurrentLocation, diag::note_member_synthesized_at) 3080 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl); 3081 Constructor->setInvalidDecl(); 3082 } else { 3083 Constructor->setUsed(); 3084 } 3085 return; 3086} 3087 3088void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 3089 CXXDestructorDecl *Destructor) { 3090 assert((Destructor->isImplicit() && !Destructor->isUsed()) && 3091 "DefineImplicitDestructor - call it for implicit default dtor"); 3092 CXXRecordDecl *ClassDecl = Destructor->getParent(); 3093 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 3094 // C++ [class.dtor] p5 3095 // Before the implicitly-declared default destructor for a class is 3096 // implicitly defined, all the implicitly-declared default destructors 3097 // for its base class and its non-static data members shall have been 3098 // implicitly defined. 3099 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 3100 E = ClassDecl->bases_end(); Base != E; ++Base) { 3101 CXXRecordDecl *BaseClassDecl 3102 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 3103 if (!BaseClassDecl->hasTrivialDestructor()) { 3104 if (CXXDestructorDecl *BaseDtor = 3105 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context))) 3106 MarkDeclarationReferenced(CurrentLocation, BaseDtor); 3107 else 3108 assert(false && 3109 "DefineImplicitDestructor - missing dtor in a base class"); 3110 } 3111 } 3112 3113 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 3114 E = ClassDecl->field_end(); Field != E; ++Field) { 3115 QualType FieldType = Context.getCanonicalType((*Field)->getType()); 3116 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 3117 FieldType = Array->getElementType(); 3118 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 3119 CXXRecordDecl *FieldClassDecl 3120 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 3121 if (!FieldClassDecl->hasTrivialDestructor()) { 3122 if (CXXDestructorDecl *FieldDtor = 3123 const_cast<CXXDestructorDecl*>( 3124 FieldClassDecl->getDestructor(Context))) 3125 MarkDeclarationReferenced(CurrentLocation, FieldDtor); 3126 else 3127 assert(false && 3128 "DefineImplicitDestructor - missing dtor in class of a data member"); 3129 } 3130 } 3131 } 3132 3133 // FIXME: If CheckDestructor fails, we should emit a note about where the 3134 // implicit destructor was needed. 3135 if (CheckDestructor(Destructor)) { 3136 Diag(CurrentLocation, diag::note_member_synthesized_at) 3137 << CXXDestructor << Context.getTagDeclType(ClassDecl); 3138 3139 Destructor->setInvalidDecl(); 3140 return; 3141 } 3142 3143 Destructor->setUsed(); 3144} 3145 3146void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation, 3147 CXXMethodDecl *MethodDecl) { 3148 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() && 3149 MethodDecl->getOverloadedOperator() == OO_Equal && 3150 !MethodDecl->isUsed()) && 3151 "DefineImplicitOverloadedAssign - call it for implicit assignment op"); 3152 3153 CXXRecordDecl *ClassDecl 3154 = cast<CXXRecordDecl>(MethodDecl->getDeclContext()); 3155 3156 // C++[class.copy] p12 3157 // Before the implicitly-declared copy assignment operator for a class is 3158 // implicitly defined, all implicitly-declared copy assignment operators 3159 // for its direct base classes and its nonstatic data members shall have 3160 // been implicitly defined. 3161 bool err = false; 3162 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 3163 E = ClassDecl->bases_end(); Base != E; ++Base) { 3164 CXXRecordDecl *BaseClassDecl 3165 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 3166 if (CXXMethodDecl *BaseAssignOpMethod = 3167 getAssignOperatorMethod(MethodDecl->getParamDecl(0), BaseClassDecl)) 3168 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod); 3169 } 3170 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 3171 E = ClassDecl->field_end(); Field != E; ++Field) { 3172 QualType FieldType = Context.getCanonicalType((*Field)->getType()); 3173 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 3174 FieldType = Array->getElementType(); 3175 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 3176 CXXRecordDecl *FieldClassDecl 3177 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 3178 if (CXXMethodDecl *FieldAssignOpMethod = 3179 getAssignOperatorMethod(MethodDecl->getParamDecl(0), FieldClassDecl)) 3180 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod); 3181 } else if (FieldType->isReferenceType()) { 3182 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 3183 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 3184 Diag(Field->getLocation(), diag::note_declared_at); 3185 Diag(CurrentLocation, diag::note_first_required_here); 3186 err = true; 3187 } else if (FieldType.isConstQualified()) { 3188 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 3189 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 3190 Diag(Field->getLocation(), diag::note_declared_at); 3191 Diag(CurrentLocation, diag::note_first_required_here); 3192 err = true; 3193 } 3194 } 3195 if (!err) 3196 MethodDecl->setUsed(); 3197} 3198 3199CXXMethodDecl * 3200Sema::getAssignOperatorMethod(ParmVarDecl *ParmDecl, 3201 CXXRecordDecl *ClassDecl) { 3202 QualType LHSType = Context.getTypeDeclType(ClassDecl); 3203 QualType RHSType(LHSType); 3204 // If class's assignment operator argument is const/volatile qualified, 3205 // look for operator = (const/volatile B&). Otherwise, look for 3206 // operator = (B&). 3207 RHSType = Context.getCVRQualifiedType(RHSType, 3208 ParmDecl->getType().getCVRQualifiers()); 3209 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl, 3210 LHSType, 3211 SourceLocation())); 3212 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl, 3213 RHSType, 3214 SourceLocation())); 3215 Expr *Args[2] = { &*LHS, &*RHS }; 3216 OverloadCandidateSet CandidateSet; 3217 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2, 3218 CandidateSet); 3219 OverloadCandidateSet::iterator Best; 3220 if (BestViableFunction(CandidateSet, 3221 ClassDecl->getLocation(), Best) == OR_Success) 3222 return cast<CXXMethodDecl>(Best->Function); 3223 assert(false && 3224 "getAssignOperatorMethod - copy assignment operator method not found"); 3225 return 0; 3226} 3227 3228void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 3229 CXXConstructorDecl *CopyConstructor, 3230 unsigned TypeQuals) { 3231 assert((CopyConstructor->isImplicit() && 3232 CopyConstructor->isCopyConstructor(Context, TypeQuals) && 3233 !CopyConstructor->isUsed()) && 3234 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 3235 3236 CXXRecordDecl *ClassDecl 3237 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext()); 3238 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 3239 // C++ [class.copy] p209 3240 // Before the implicitly-declared copy constructor for a class is 3241 // implicitly defined, all the implicitly-declared copy constructors 3242 // for its base class and its non-static data members shall have been 3243 // implicitly defined. 3244 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(); 3245 Base != ClassDecl->bases_end(); ++Base) { 3246 CXXRecordDecl *BaseClassDecl 3247 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 3248 if (CXXConstructorDecl *BaseCopyCtor = 3249 BaseClassDecl->getCopyConstructor(Context, TypeQuals)) 3250 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor); 3251 } 3252 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 3253 FieldEnd = ClassDecl->field_end(); 3254 Field != FieldEnd; ++Field) { 3255 QualType FieldType = Context.getCanonicalType((*Field)->getType()); 3256 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 3257 FieldType = Array->getElementType(); 3258 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 3259 CXXRecordDecl *FieldClassDecl 3260 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 3261 if (CXXConstructorDecl *FieldCopyCtor = 3262 FieldClassDecl->getCopyConstructor(Context, TypeQuals)) 3263 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor); 3264 } 3265 } 3266 CopyConstructor->setUsed(); 3267} 3268 3269Sema::OwningExprResult 3270Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 3271 CXXConstructorDecl *Constructor, 3272 MultiExprArg ExprArgs) { 3273 bool Elidable = false; 3274 3275 // C++ [class.copy]p15: 3276 // Whenever a temporary class object is copied using a copy constructor, and 3277 // this object and the copy have the same cv-unqualified type, an 3278 // implementation is permitted to treat the original and the copy as two 3279 // different ways of referring to the same object and not perform a copy at 3280 // all, even if the class copy constructor or destructor have side effects. 3281 3282 // FIXME: Is this enough? 3283 if (Constructor->isCopyConstructor(Context)) { 3284 Expr *E = ((Expr **)ExprArgs.get())[0]; 3285 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E)) 3286 E = BE->getSubExpr(); 3287 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 3288 if (ICE->getCastKind() == CastExpr::CK_NoOp) 3289 E = ICE->getSubExpr(); 3290 3291 if (isa<CallExpr>(E) || isa<CXXTemporaryObjectExpr>(E)) 3292 Elidable = true; 3293 } 3294 3295 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 3296 Elidable, move(ExprArgs)); 3297} 3298 3299/// BuildCXXConstructExpr - Creates a complete call to a constructor, 3300/// including handling of its default argument expressions. 3301Sema::OwningExprResult 3302Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 3303 CXXConstructorDecl *Constructor, bool Elidable, 3304 MultiExprArg ExprArgs) { 3305 unsigned NumExprs = ExprArgs.size(); 3306 Expr **Exprs = (Expr **)ExprArgs.release(); 3307 3308 MarkDeclarationReferenced(ConstructLoc, Constructor); 3309 return Owned(CXXConstructExpr::Create(Context, DeclInitType, Constructor, 3310 Elidable, Exprs, NumExprs)); 3311} 3312 3313Sema::OwningExprResult 3314Sema::BuildCXXTemporaryObjectExpr(CXXConstructorDecl *Constructor, 3315 QualType Ty, 3316 SourceLocation TyBeginLoc, 3317 MultiExprArg Args, 3318 SourceLocation RParenLoc) { 3319 unsigned NumExprs = Args.size(); 3320 Expr **Exprs = (Expr **)Args.release(); 3321 3322 MarkDeclarationReferenced(TyBeginLoc, Constructor); 3323 return Owned(new (Context) CXXTemporaryObjectExpr(Context, Constructor, Ty, 3324 TyBeginLoc, Exprs, 3325 NumExprs, RParenLoc)); 3326} 3327 3328 3329bool Sema::InitializeVarWithConstructor(VarDecl *VD, 3330 CXXConstructorDecl *Constructor, 3331 MultiExprArg Exprs) { 3332 OwningExprResult TempResult = 3333 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor, 3334 move(Exprs)); 3335 if (TempResult.isInvalid()) 3336 return true; 3337 3338 Expr *Temp = TempResult.takeAs<Expr>(); 3339 MarkDeclarationReferenced(VD->getLocation(), Constructor); 3340 Temp = MaybeCreateCXXExprWithTemporaries(Temp, /*DestroyTemps=*/true); 3341 VD->setInit(Context, Temp); 3342 3343 return false; 3344} 3345 3346void Sema::FinalizeVarWithDestructor(VarDecl *VD, QualType DeclInitType) { 3347 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>( 3348 DeclInitType->getAs<RecordType>()->getDecl()); 3349 if (!ClassDecl->hasTrivialDestructor()) 3350 if (CXXDestructorDecl *Destructor = 3351 const_cast<CXXDestructorDecl*>(ClassDecl->getDestructor(Context))) 3352 MarkDeclarationReferenced(VD->getLocation(), Destructor); 3353} 3354 3355/// AddCXXDirectInitializerToDecl - This action is called immediately after 3356/// ActOnDeclarator, when a C++ direct initializer is present. 3357/// e.g: "int x(1);" 3358void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl, 3359 SourceLocation LParenLoc, 3360 MultiExprArg Exprs, 3361 SourceLocation *CommaLocs, 3362 SourceLocation RParenLoc) { 3363 unsigned NumExprs = Exprs.size(); 3364 assert(NumExprs != 0 && Exprs.get() && "missing expressions"); 3365 Decl *RealDecl = Dcl.getAs<Decl>(); 3366 3367 // If there is no declaration, there was an error parsing it. Just ignore 3368 // the initializer. 3369 if (RealDecl == 0) 3370 return; 3371 3372 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 3373 if (!VDecl) { 3374 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 3375 RealDecl->setInvalidDecl(); 3376 return; 3377 } 3378 3379 // We will represent direct-initialization similarly to copy-initialization: 3380 // int x(1); -as-> int x = 1; 3381 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 3382 // 3383 // Clients that want to distinguish between the two forms, can check for 3384 // direct initializer using VarDecl::hasCXXDirectInitializer(). 3385 // A major benefit is that clients that don't particularly care about which 3386 // exactly form was it (like the CodeGen) can handle both cases without 3387 // special case code. 3388 3389 // If either the declaration has a dependent type or if any of the expressions 3390 // is type-dependent, we represent the initialization via a ParenListExpr for 3391 // later use during template instantiation. 3392 if (VDecl->getType()->isDependentType() || 3393 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) { 3394 // Let clients know that initialization was done with a direct initializer. 3395 VDecl->setCXXDirectInitializer(true); 3396 3397 // Store the initialization expressions as a ParenListExpr. 3398 unsigned NumExprs = Exprs.size(); 3399 VDecl->setInit(Context, 3400 new (Context) ParenListExpr(Context, LParenLoc, 3401 (Expr **)Exprs.release(), 3402 NumExprs, RParenLoc)); 3403 return; 3404 } 3405 3406 3407 // C++ 8.5p11: 3408 // The form of initialization (using parentheses or '=') is generally 3409 // insignificant, but does matter when the entity being initialized has a 3410 // class type. 3411 QualType DeclInitType = VDecl->getType(); 3412 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType)) 3413 DeclInitType = Context.getBaseElementType(Array); 3414 3415 // FIXME: This isn't the right place to complete the type. 3416 if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(), 3417 diag::err_typecheck_decl_incomplete_type)) { 3418 VDecl->setInvalidDecl(); 3419 return; 3420 } 3421 3422 if (VDecl->getType()->isRecordType()) { 3423 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this); 3424 3425 CXXConstructorDecl *Constructor 3426 = PerformInitializationByConstructor(DeclInitType, 3427 move(Exprs), 3428 VDecl->getLocation(), 3429 SourceRange(VDecl->getLocation(), 3430 RParenLoc), 3431 VDecl->getDeclName(), 3432 IK_Direct, 3433 ConstructorArgs); 3434 if (!Constructor) 3435 RealDecl->setInvalidDecl(); 3436 else { 3437 VDecl->setCXXDirectInitializer(true); 3438 if (InitializeVarWithConstructor(VDecl, Constructor, 3439 move_arg(ConstructorArgs))) 3440 RealDecl->setInvalidDecl(); 3441 FinalizeVarWithDestructor(VDecl, DeclInitType); 3442 } 3443 return; 3444 } 3445 3446 if (NumExprs > 1) { 3447 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg) 3448 << SourceRange(VDecl->getLocation(), RParenLoc); 3449 RealDecl->setInvalidDecl(); 3450 return; 3451 } 3452 3453 // Let clients know that initialization was done with a direct initializer. 3454 VDecl->setCXXDirectInitializer(true); 3455 3456 assert(NumExprs == 1 && "Expected 1 expression"); 3457 // Set the init expression, handles conversions. 3458 AddInitializerToDecl(Dcl, ExprArg(*this, Exprs.release()[0]), 3459 /*DirectInit=*/true); 3460} 3461 3462/// \brief Add the applicable constructor candidates for an initialization 3463/// by constructor. 3464static void AddConstructorInitializationCandidates(Sema &SemaRef, 3465 QualType ClassType, 3466 Expr **Args, 3467 unsigned NumArgs, 3468 Sema::InitializationKind Kind, 3469 OverloadCandidateSet &CandidateSet) { 3470 // C++ [dcl.init]p14: 3471 // If the initialization is direct-initialization, or if it is 3472 // copy-initialization where the cv-unqualified version of the 3473 // source type is the same class as, or a derived class of, the 3474 // class of the destination, constructors are considered. The 3475 // applicable constructors are enumerated (13.3.1.3), and the 3476 // best one is chosen through overload resolution (13.3). The 3477 // constructor so selected is called to initialize the object, 3478 // with the initializer expression(s) as its argument(s). If no 3479 // constructor applies, or the overload resolution is ambiguous, 3480 // the initialization is ill-formed. 3481 const RecordType *ClassRec = ClassType->getAs<RecordType>(); 3482 assert(ClassRec && "Can only initialize a class type here"); 3483 3484 // FIXME: When we decide not to synthesize the implicitly-declared 3485 // constructors, we'll need to make them appear here. 3486 3487 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl()); 3488 DeclarationName ConstructorName 3489 = SemaRef.Context.DeclarationNames.getCXXConstructorName( 3490 SemaRef.Context.getCanonicalType(ClassType).getUnqualifiedType()); 3491 DeclContext::lookup_const_iterator Con, ConEnd; 3492 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName); 3493 Con != ConEnd; ++Con) { 3494 // Find the constructor (which may be a template). 3495 CXXConstructorDecl *Constructor = 0; 3496 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con); 3497 if (ConstructorTmpl) 3498 Constructor 3499 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 3500 else 3501 Constructor = cast<CXXConstructorDecl>(*Con); 3502 3503 if ((Kind == Sema::IK_Direct) || 3504 (Kind == Sema::IK_Copy && 3505 Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) || 3506 (Kind == Sema::IK_Default && Constructor->isDefaultConstructor())) { 3507 if (ConstructorTmpl) 3508 SemaRef.AddTemplateOverloadCandidate(ConstructorTmpl, 3509 /*ExplicitArgs*/ 0, 3510 Args, NumArgs, CandidateSet); 3511 else 3512 SemaRef.AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet); 3513 } 3514 } 3515} 3516 3517/// \brief Attempt to perform initialization by constructor 3518/// (C++ [dcl.init]p14), which may occur as part of direct-initialization or 3519/// copy-initialization. 3520/// 3521/// This routine determines whether initialization by constructor is possible, 3522/// but it does not emit any diagnostics in the case where the initialization 3523/// is ill-formed. 3524/// 3525/// \param ClassType the type of the object being initialized, which must have 3526/// class type. 3527/// 3528/// \param Args the arguments provided to initialize the object 3529/// 3530/// \param NumArgs the number of arguments provided to initialize the object 3531/// 3532/// \param Kind the type of initialization being performed 3533/// 3534/// \returns the constructor used to initialize the object, if successful. 3535/// Otherwise, emits a diagnostic and returns NULL. 3536CXXConstructorDecl * 3537Sema::TryInitializationByConstructor(QualType ClassType, 3538 Expr **Args, unsigned NumArgs, 3539 SourceLocation Loc, 3540 InitializationKind Kind) { 3541 // Build the overload candidate set 3542 OverloadCandidateSet CandidateSet; 3543 AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind, 3544 CandidateSet); 3545 3546 // Determine whether we found a constructor we can use. 3547 OverloadCandidateSet::iterator Best; 3548 switch (BestViableFunction(CandidateSet, Loc, Best)) { 3549 case OR_Success: 3550 case OR_Deleted: 3551 // We found a constructor. Return it. 3552 return cast<CXXConstructorDecl>(Best->Function); 3553 3554 case OR_No_Viable_Function: 3555 case OR_Ambiguous: 3556 // Overload resolution failed. Return nothing. 3557 return 0; 3558 } 3559 3560 // Silence GCC warning 3561 return 0; 3562} 3563 3564/// \brief Perform initialization by constructor (C++ [dcl.init]p14), which 3565/// may occur as part of direct-initialization or copy-initialization. 3566/// 3567/// \param ClassType the type of the object being initialized, which must have 3568/// class type. 3569/// 3570/// \param ArgsPtr the arguments provided to initialize the object 3571/// 3572/// \param Loc the source location where the initialization occurs 3573/// 3574/// \param Range the source range that covers the entire initialization 3575/// 3576/// \param InitEntity the name of the entity being initialized, if known 3577/// 3578/// \param Kind the type of initialization being performed 3579/// 3580/// \param ConvertedArgs a vector that will be filled in with the 3581/// appropriately-converted arguments to the constructor (if initialization 3582/// succeeded). 3583/// 3584/// \returns the constructor used to initialize the object, if successful. 3585/// Otherwise, emits a diagnostic and returns NULL. 3586CXXConstructorDecl * 3587Sema::PerformInitializationByConstructor(QualType ClassType, 3588 MultiExprArg ArgsPtr, 3589 SourceLocation Loc, SourceRange Range, 3590 DeclarationName InitEntity, 3591 InitializationKind Kind, 3592 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) { 3593 3594 // Build the overload candidate set 3595 Expr **Args = (Expr **)ArgsPtr.get(); 3596 unsigned NumArgs = ArgsPtr.size(); 3597 OverloadCandidateSet CandidateSet; 3598 AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind, 3599 CandidateSet); 3600 3601 OverloadCandidateSet::iterator Best; 3602 switch (BestViableFunction(CandidateSet, Loc, Best)) { 3603 case OR_Success: 3604 // We found a constructor. Break out so that we can convert the arguments 3605 // appropriately. 3606 break; 3607 3608 case OR_No_Viable_Function: 3609 if (InitEntity) 3610 Diag(Loc, diag::err_ovl_no_viable_function_in_init) 3611 << InitEntity << Range; 3612 else 3613 Diag(Loc, diag::err_ovl_no_viable_function_in_init) 3614 << ClassType << Range; 3615 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false); 3616 return 0; 3617 3618 case OR_Ambiguous: 3619 if (InitEntity) 3620 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range; 3621 else 3622 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range; 3623 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 3624 return 0; 3625 3626 case OR_Deleted: 3627 if (InitEntity) 3628 Diag(Loc, diag::err_ovl_deleted_init) 3629 << Best->Function->isDeleted() 3630 << InitEntity << Range; 3631 else { 3632 const CXXRecordDecl *RD = 3633 cast<CXXRecordDecl>(ClassType->getAs<RecordType>()->getDecl()); 3634 Diag(Loc, diag::err_ovl_deleted_init) 3635 << Best->Function->isDeleted() 3636 << RD->getDeclName() << Range; 3637 } 3638 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 3639 return 0; 3640 } 3641 3642 // Convert the arguments, fill in default arguments, etc. 3643 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3644 if (CompleteConstructorCall(Constructor, move(ArgsPtr), Loc, ConvertedArgs)) 3645 return 0; 3646 3647 return Constructor; 3648} 3649 3650/// \brief Given a constructor and the set of arguments provided for the 3651/// constructor, convert the arguments and add any required default arguments 3652/// to form a proper call to this constructor. 3653/// 3654/// \returns true if an error occurred, false otherwise. 3655bool 3656Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 3657 MultiExprArg ArgsPtr, 3658 SourceLocation Loc, 3659 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) { 3660 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 3661 unsigned NumArgs = ArgsPtr.size(); 3662 Expr **Args = (Expr **)ArgsPtr.get(); 3663 3664 const FunctionProtoType *Proto 3665 = Constructor->getType()->getAs<FunctionProtoType>(); 3666 assert(Proto && "Constructor without a prototype?"); 3667 unsigned NumArgsInProto = Proto->getNumArgs(); 3668 3669 // If too few arguments are available, we'll fill in the rest with defaults. 3670 if (NumArgs < NumArgsInProto) 3671 ConvertedArgs.reserve(NumArgsInProto); 3672 else 3673 ConvertedArgs.reserve(NumArgs); 3674 3675 VariadicCallType CallType = 3676 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 3677 llvm::SmallVector<Expr *, 8> AllArgs; 3678 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 3679 Proto, 0, Args, NumArgs, AllArgs, 3680 CallType); 3681 for (unsigned i =0, size = AllArgs.size(); i < size; i++) 3682 ConvertedArgs.push_back(AllArgs[i]); 3683 return Invalid; 3684} 3685 3686/// CompareReferenceRelationship - Compare the two types T1 and T2 to 3687/// determine whether they are reference-related, 3688/// reference-compatible, reference-compatible with added 3689/// qualification, or incompatible, for use in C++ initialization by 3690/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 3691/// type, and the first type (T1) is the pointee type of the reference 3692/// type being initialized. 3693Sema::ReferenceCompareResult 3694Sema::CompareReferenceRelationship(SourceLocation Loc, 3695 QualType OrigT1, QualType OrigT2, 3696 bool& DerivedToBase) { 3697 assert(!OrigT1->isReferenceType() && 3698 "T1 must be the pointee type of the reference type"); 3699 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 3700 3701 QualType T1 = Context.getCanonicalType(OrigT1); 3702 QualType T2 = Context.getCanonicalType(OrigT2); 3703 QualType UnqualT1 = T1.getLocalUnqualifiedType(); 3704 QualType UnqualT2 = T2.getLocalUnqualifiedType(); 3705 3706 // C++ [dcl.init.ref]p4: 3707 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 3708 // reference-related to "cv2 T2" if T1 is the same type as T2, or 3709 // T1 is a base class of T2. 3710 if (UnqualT1 == UnqualT2) 3711 DerivedToBase = false; 3712 else if (!RequireCompleteType(Loc, OrigT1, PDiag()) && 3713 !RequireCompleteType(Loc, OrigT2, PDiag()) && 3714 IsDerivedFrom(UnqualT2, UnqualT1)) 3715 DerivedToBase = true; 3716 else 3717 return Ref_Incompatible; 3718 3719 // At this point, we know that T1 and T2 are reference-related (at 3720 // least). 3721 3722 // C++ [dcl.init.ref]p4: 3723 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 3724 // reference-related to T2 and cv1 is the same cv-qualification 3725 // as, or greater cv-qualification than, cv2. For purposes of 3726 // overload resolution, cases for which cv1 is greater 3727 // cv-qualification than cv2 are identified as 3728 // reference-compatible with added qualification (see 13.3.3.2). 3729 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3730 return Ref_Compatible; 3731 else if (T1.isMoreQualifiedThan(T2)) 3732 return Ref_Compatible_With_Added_Qualification; 3733 else 3734 return Ref_Related; 3735} 3736 3737/// CheckReferenceInit - Check the initialization of a reference 3738/// variable with the given initializer (C++ [dcl.init.ref]). Init is 3739/// the initializer (either a simple initializer or an initializer 3740/// list), and DeclType is the type of the declaration. When ICS is 3741/// non-null, this routine will compute the implicit conversion 3742/// sequence according to C++ [over.ics.ref] and will not produce any 3743/// diagnostics; when ICS is null, it will emit diagnostics when any 3744/// errors are found. Either way, a return value of true indicates 3745/// that there was a failure, a return value of false indicates that 3746/// the reference initialization succeeded. 3747/// 3748/// When @p SuppressUserConversions, user-defined conversions are 3749/// suppressed. 3750/// When @p AllowExplicit, we also permit explicit user-defined 3751/// conversion functions. 3752/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue. 3753/// When @p IgnoreBaseAccess, we don't do access control on to-base conversion. 3754/// This is used when this is called from a C-style cast. 3755bool 3756Sema::CheckReferenceInit(Expr *&Init, QualType DeclType, 3757 SourceLocation DeclLoc, 3758 bool SuppressUserConversions, 3759 bool AllowExplicit, bool ForceRValue, 3760 ImplicitConversionSequence *ICS, 3761 bool IgnoreBaseAccess) { 3762 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 3763 3764 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 3765 QualType T2 = Init->getType(); 3766 3767 // If the initializer is the address of an overloaded function, try 3768 // to resolve the overloaded function. If all goes well, T2 is the 3769 // type of the resulting function. 3770 if (Context.getCanonicalType(T2) == Context.OverloadTy) { 3771 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType, 3772 ICS != 0); 3773 if (Fn) { 3774 // Since we're performing this reference-initialization for 3775 // real, update the initializer with the resulting function. 3776 if (!ICS) { 3777 if (DiagnoseUseOfDecl(Fn, DeclLoc)) 3778 return true; 3779 3780 Init = FixOverloadedFunctionReference(Init, Fn); 3781 } 3782 3783 T2 = Fn->getType(); 3784 } 3785 } 3786 3787 // Compute some basic properties of the types and the initializer. 3788 bool isRValRef = DeclType->isRValueReferenceType(); 3789 bool DerivedToBase = false; 3790 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression : 3791 Init->isLvalue(Context); 3792 ReferenceCompareResult RefRelationship 3793 = CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase); 3794 3795 // Most paths end in a failed conversion. 3796 if (ICS) 3797 ICS->ConversionKind = ImplicitConversionSequence::BadConversion; 3798 3799 // C++ [dcl.init.ref]p5: 3800 // A reference to type "cv1 T1" is initialized by an expression 3801 // of type "cv2 T2" as follows: 3802 3803 // -- If the initializer expression 3804 3805 // Rvalue references cannot bind to lvalues (N2812). 3806 // There is absolutely no situation where they can. In particular, note that 3807 // this is ill-formed, even if B has a user-defined conversion to A&&: 3808 // B b; 3809 // A&& r = b; 3810 if (isRValRef && InitLvalue == Expr::LV_Valid) { 3811 if (!ICS) 3812 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref) 3813 << Init->getSourceRange(); 3814 return true; 3815 } 3816 3817 bool BindsDirectly = false; 3818 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 3819 // reference-compatible with "cv2 T2," or 3820 // 3821 // Note that the bit-field check is skipped if we are just computing 3822 // the implicit conversion sequence (C++ [over.best.ics]p2). 3823 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) && 3824 RefRelationship >= Ref_Compatible_With_Added_Qualification) { 3825 BindsDirectly = true; 3826 3827 if (ICS) { 3828 // C++ [over.ics.ref]p1: 3829 // When a parameter of reference type binds directly (8.5.3) 3830 // to an argument expression, the implicit conversion sequence 3831 // is the identity conversion, unless the argument expression 3832 // has a type that is a derived class of the parameter type, 3833 // in which case the implicit conversion sequence is a 3834 // derived-to-base Conversion (13.3.3.1). 3835 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion; 3836 ICS->Standard.First = ICK_Identity; 3837 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity; 3838 ICS->Standard.Third = ICK_Identity; 3839 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr(); 3840 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr(); 3841 ICS->Standard.ReferenceBinding = true; 3842 ICS->Standard.DirectBinding = true; 3843 ICS->Standard.RRefBinding = false; 3844 ICS->Standard.CopyConstructor = 0; 3845 3846 // Nothing more to do: the inaccessibility/ambiguity check for 3847 // derived-to-base conversions is suppressed when we're 3848 // computing the implicit conversion sequence (C++ 3849 // [over.best.ics]p2). 3850 return false; 3851 } else { 3852 // Perform the conversion. 3853 CastExpr::CastKind CK = CastExpr::CK_NoOp; 3854 if (DerivedToBase) 3855 CK = CastExpr::CK_DerivedToBase; 3856 else if(CheckExceptionSpecCompatibility(Init, T1)) 3857 return true; 3858 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/true); 3859 } 3860 } 3861 3862 // -- has a class type (i.e., T2 is a class type) and can be 3863 // implicitly converted to an lvalue of type "cv3 T3," 3864 // where "cv1 T1" is reference-compatible with "cv3 T3" 3865 // 92) (this conversion is selected by enumerating the 3866 // applicable conversion functions (13.3.1.6) and choosing 3867 // the best one through overload resolution (13.3)), 3868 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() && 3869 !RequireCompleteType(DeclLoc, T2, 0)) { 3870 CXXRecordDecl *T2RecordDecl 3871 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 3872 3873 OverloadCandidateSet CandidateSet; 3874 const UnresolvedSet *Conversions 3875 = T2RecordDecl->getVisibleConversionFunctions(); 3876 for (UnresolvedSet::iterator I = Conversions->begin(), 3877 E = Conversions->end(); I != E; ++I) { 3878 FunctionTemplateDecl *ConvTemplate 3879 = dyn_cast<FunctionTemplateDecl>(*I); 3880 CXXConversionDecl *Conv; 3881 if (ConvTemplate) 3882 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3883 else 3884 Conv = cast<CXXConversionDecl>(*I); 3885 3886 // If the conversion function doesn't return a reference type, 3887 // it can't be considered for this conversion. 3888 if (Conv->getConversionType()->isLValueReferenceType() && 3889 (AllowExplicit || !Conv->isExplicit())) { 3890 if (ConvTemplate) 3891 AddTemplateConversionCandidate(ConvTemplate, Init, DeclType, 3892 CandidateSet); 3893 else 3894 AddConversionCandidate(Conv, Init, DeclType, CandidateSet); 3895 } 3896 } 3897 3898 OverloadCandidateSet::iterator Best; 3899 switch (BestViableFunction(CandidateSet, DeclLoc, Best)) { 3900 case OR_Success: 3901 // This is a direct binding. 3902 BindsDirectly = true; 3903 3904 if (ICS) { 3905 // C++ [over.ics.ref]p1: 3906 // 3907 // [...] If the parameter binds directly to the result of 3908 // applying a conversion function to the argument 3909 // expression, the implicit conversion sequence is a 3910 // user-defined conversion sequence (13.3.3.1.2), with the 3911 // second standard conversion sequence either an identity 3912 // conversion or, if the conversion function returns an 3913 // entity of a type that is a derived class of the parameter 3914 // type, a derived-to-base Conversion. 3915 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion; 3916 ICS->UserDefined.Before = Best->Conversions[0].Standard; 3917 ICS->UserDefined.After = Best->FinalConversion; 3918 ICS->UserDefined.ConversionFunction = Best->Function; 3919 ICS->UserDefined.EllipsisConversion = false; 3920 assert(ICS->UserDefined.After.ReferenceBinding && 3921 ICS->UserDefined.After.DirectBinding && 3922 "Expected a direct reference binding!"); 3923 return false; 3924 } else { 3925 OwningExprResult InitConversion = 3926 BuildCXXCastArgument(DeclLoc, QualType(), 3927 CastExpr::CK_UserDefinedConversion, 3928 cast<CXXMethodDecl>(Best->Function), 3929 Owned(Init)); 3930 Init = InitConversion.takeAs<Expr>(); 3931 3932 if (CheckExceptionSpecCompatibility(Init, T1)) 3933 return true; 3934 ImpCastExprToType(Init, T1, CastExpr::CK_UserDefinedConversion, 3935 /*isLvalue=*/true); 3936 } 3937 break; 3938 3939 case OR_Ambiguous: 3940 if (ICS) { 3941 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 3942 Cand != CandidateSet.end(); ++Cand) 3943 if (Cand->Viable) 3944 ICS->ConversionFunctionSet.push_back(Cand->Function); 3945 break; 3946 } 3947 Diag(DeclLoc, diag::err_ref_init_ambiguous) << DeclType << Init->getType() 3948 << Init->getSourceRange(); 3949 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 3950 return true; 3951 3952 case OR_No_Viable_Function: 3953 case OR_Deleted: 3954 // There was no suitable conversion, or we found a deleted 3955 // conversion; continue with other checks. 3956 break; 3957 } 3958 } 3959 3960 if (BindsDirectly) { 3961 // C++ [dcl.init.ref]p4: 3962 // [...] In all cases where the reference-related or 3963 // reference-compatible relationship of two types is used to 3964 // establish the validity of a reference binding, and T1 is a 3965 // base class of T2, a program that necessitates such a binding 3966 // is ill-formed if T1 is an inaccessible (clause 11) or 3967 // ambiguous (10.2) base class of T2. 3968 // 3969 // Note that we only check this condition when we're allowed to 3970 // complain about errors, because we should not be checking for 3971 // ambiguity (or inaccessibility) unless the reference binding 3972 // actually happens. 3973 if (DerivedToBase) 3974 return CheckDerivedToBaseConversion(T2, T1, DeclLoc, 3975 Init->getSourceRange(), 3976 IgnoreBaseAccess); 3977 else 3978 return false; 3979 } 3980 3981 // -- Otherwise, the reference shall be to a non-volatile const 3982 // type (i.e., cv1 shall be const), or the reference shall be an 3983 // rvalue reference and the initializer expression shall be an rvalue. 3984 if (!isRValRef && T1.getCVRQualifiers() != Qualifiers::Const) { 3985 if (!ICS) 3986 Diag(DeclLoc, diag::err_not_reference_to_const_init) 3987 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value") 3988 << T2 << Init->getSourceRange(); 3989 return true; 3990 } 3991 3992 // -- If the initializer expression is an rvalue, with T2 a 3993 // class type, and "cv1 T1" is reference-compatible with 3994 // "cv2 T2," the reference is bound in one of the 3995 // following ways (the choice is implementation-defined): 3996 // 3997 // -- The reference is bound to the object represented by 3998 // the rvalue (see 3.10) or to a sub-object within that 3999 // object. 4000 // 4001 // -- A temporary of type "cv1 T2" [sic] is created, and 4002 // a constructor is called to copy the entire rvalue 4003 // object into the temporary. The reference is bound to 4004 // the temporary or to a sub-object within the 4005 // temporary. 4006 // 4007 // The constructor that would be used to make the copy 4008 // shall be callable whether or not the copy is actually 4009 // done. 4010 // 4011 // Note that C++0x [dcl.init.ref]p5 takes away this implementation 4012 // freedom, so we will always take the first option and never build 4013 // a temporary in this case. FIXME: We will, however, have to check 4014 // for the presence of a copy constructor in C++98/03 mode. 4015 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() && 4016 RefRelationship >= Ref_Compatible_With_Added_Qualification) { 4017 if (ICS) { 4018 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion; 4019 ICS->Standard.First = ICK_Identity; 4020 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity; 4021 ICS->Standard.Third = ICK_Identity; 4022 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr(); 4023 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr(); 4024 ICS->Standard.ReferenceBinding = true; 4025 ICS->Standard.DirectBinding = false; 4026 ICS->Standard.RRefBinding = isRValRef; 4027 ICS->Standard.CopyConstructor = 0; 4028 } else { 4029 CastExpr::CastKind CK = CastExpr::CK_NoOp; 4030 if (DerivedToBase) 4031 CK = CastExpr::CK_DerivedToBase; 4032 else if(CheckExceptionSpecCompatibility(Init, T1)) 4033 return true; 4034 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/false); 4035 } 4036 return false; 4037 } 4038 4039 // -- Otherwise, a temporary of type "cv1 T1" is created and 4040 // initialized from the initializer expression using the 4041 // rules for a non-reference copy initialization (8.5). The 4042 // reference is then bound to the temporary. If T1 is 4043 // reference-related to T2, cv1 must be the same 4044 // cv-qualification as, or greater cv-qualification than, 4045 // cv2; otherwise, the program is ill-formed. 4046 if (RefRelationship == Ref_Related) { 4047 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4048 // we would be reference-compatible or reference-compatible with 4049 // added qualification. But that wasn't the case, so the reference 4050 // initialization fails. 4051 if (!ICS) 4052 Diag(DeclLoc, diag::err_reference_init_drops_quals) 4053 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value") 4054 << T2 << Init->getSourceRange(); 4055 return true; 4056 } 4057 4058 // If at least one of the types is a class type, the types are not 4059 // related, and we aren't allowed any user conversions, the 4060 // reference binding fails. This case is important for breaking 4061 // recursion, since TryImplicitConversion below will attempt to 4062 // create a temporary through the use of a copy constructor. 4063 if (SuppressUserConversions && RefRelationship == Ref_Incompatible && 4064 (T1->isRecordType() || T2->isRecordType())) { 4065 if (!ICS) 4066 Diag(DeclLoc, diag::err_typecheck_convert_incompatible) 4067 << DeclType << Init->getType() << "initializing" << Init->getSourceRange(); 4068 return true; 4069 } 4070 4071 // Actually try to convert the initializer to T1. 4072 if (ICS) { 4073 // C++ [over.ics.ref]p2: 4074 // 4075 // When a parameter of reference type is not bound directly to 4076 // an argument expression, the conversion sequence is the one 4077 // required to convert the argument expression to the 4078 // underlying type of the reference according to 4079 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4080 // to copy-initializing a temporary of the underlying type with 4081 // the argument expression. Any difference in top-level 4082 // cv-qualification is subsumed by the initialization itself 4083 // and does not constitute a conversion. 4084 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions, 4085 /*AllowExplicit=*/false, 4086 /*ForceRValue=*/false, 4087 /*InOverloadResolution=*/false); 4088 4089 // Of course, that's still a reference binding. 4090 if (ICS->ConversionKind == ImplicitConversionSequence::StandardConversion) { 4091 ICS->Standard.ReferenceBinding = true; 4092 ICS->Standard.RRefBinding = isRValRef; 4093 } else if (ICS->ConversionKind == 4094 ImplicitConversionSequence::UserDefinedConversion) { 4095 ICS->UserDefined.After.ReferenceBinding = true; 4096 ICS->UserDefined.After.RRefBinding = isRValRef; 4097 } 4098 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion; 4099 } else { 4100 ImplicitConversionSequence Conversions; 4101 bool badConversion = PerformImplicitConversion(Init, T1, "initializing", 4102 false, false, 4103 Conversions); 4104 if (badConversion) { 4105 if ((Conversions.ConversionKind == 4106 ImplicitConversionSequence::BadConversion) 4107 && !Conversions.ConversionFunctionSet.empty()) { 4108 Diag(DeclLoc, 4109 diag::err_lvalue_to_rvalue_ambig_ref) << Init->getSourceRange(); 4110 for (int j = Conversions.ConversionFunctionSet.size()-1; 4111 j >= 0; j--) { 4112 FunctionDecl *Func = Conversions.ConversionFunctionSet[j]; 4113 Diag(Func->getLocation(), diag::err_ovl_candidate); 4114 } 4115 } 4116 else { 4117 if (isRValRef) 4118 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref) 4119 << Init->getSourceRange(); 4120 else 4121 Diag(DeclLoc, diag::err_invalid_initialization) 4122 << DeclType << Init->getType() << Init->getSourceRange(); 4123 } 4124 } 4125 return badConversion; 4126 } 4127} 4128 4129/// CheckOverloadedOperatorDeclaration - Check whether the declaration 4130/// of this overloaded operator is well-formed. If so, returns false; 4131/// otherwise, emits appropriate diagnostics and returns true. 4132bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 4133 assert(FnDecl && FnDecl->isOverloadedOperator() && 4134 "Expected an overloaded operator declaration"); 4135 4136 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 4137 4138 // C++ [over.oper]p5: 4139 // The allocation and deallocation functions, operator new, 4140 // operator new[], operator delete and operator delete[], are 4141 // described completely in 3.7.3. The attributes and restrictions 4142 // found in the rest of this subclause do not apply to them unless 4143 // explicitly stated in 3.7.3. 4144 // FIXME: Write a separate routine for checking this. For now, just allow it. 4145 if (Op == OO_Delete || Op == OO_Array_Delete) 4146 return false; 4147 4148 if (Op == OO_New || Op == OO_Array_New) { 4149 bool ret = false; 4150 if (FunctionDecl::param_iterator Param = FnDecl->param_begin()) { 4151 QualType SizeTy = Context.getCanonicalType(Context.getSizeType()); 4152 QualType T = Context.getCanonicalType((*Param)->getType()); 4153 if (!T->isDependentType() && SizeTy != T) { 4154 Diag(FnDecl->getLocation(), 4155 diag::err_operator_new_param_type) << FnDecl->getDeclName() 4156 << SizeTy; 4157 ret = true; 4158 } 4159 } 4160 QualType ResultTy = Context.getCanonicalType(FnDecl->getResultType()); 4161 if (!ResultTy->isDependentType() && ResultTy != Context.VoidPtrTy) 4162 return Diag(FnDecl->getLocation(), 4163 diag::err_operator_new_result_type) << FnDecl->getDeclName() 4164 << static_cast<QualType>(Context.VoidPtrTy); 4165 return ret; 4166 } 4167 4168 // C++ [over.oper]p6: 4169 // An operator function shall either be a non-static member 4170 // function or be a non-member function and have at least one 4171 // parameter whose type is a class, a reference to a class, an 4172 // enumeration, or a reference to an enumeration. 4173 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 4174 if (MethodDecl->isStatic()) 4175 return Diag(FnDecl->getLocation(), 4176 diag::err_operator_overload_static) << FnDecl->getDeclName(); 4177 } else { 4178 bool ClassOrEnumParam = false; 4179 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 4180 ParamEnd = FnDecl->param_end(); 4181 Param != ParamEnd; ++Param) { 4182 QualType ParamType = (*Param)->getType().getNonReferenceType(); 4183 if (ParamType->isDependentType() || ParamType->isRecordType() || 4184 ParamType->isEnumeralType()) { 4185 ClassOrEnumParam = true; 4186 break; 4187 } 4188 } 4189 4190 if (!ClassOrEnumParam) 4191 return Diag(FnDecl->getLocation(), 4192 diag::err_operator_overload_needs_class_or_enum) 4193 << FnDecl->getDeclName(); 4194 } 4195 4196 // C++ [over.oper]p8: 4197 // An operator function cannot have default arguments (8.3.6), 4198 // except where explicitly stated below. 4199 // 4200 // Only the function-call operator allows default arguments 4201 // (C++ [over.call]p1). 4202 if (Op != OO_Call) { 4203 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(); 4204 Param != FnDecl->param_end(); ++Param) { 4205 if ((*Param)->hasUnparsedDefaultArg()) 4206 return Diag((*Param)->getLocation(), 4207 diag::err_operator_overload_default_arg) 4208 << FnDecl->getDeclName(); 4209 else if (Expr *DefArg = (*Param)->getDefaultArg()) 4210 return Diag((*Param)->getLocation(), 4211 diag::err_operator_overload_default_arg) 4212 << FnDecl->getDeclName() << DefArg->getSourceRange(); 4213 } 4214 } 4215 4216 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 4217 { false, false, false } 4218#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 4219 , { Unary, Binary, MemberOnly } 4220#include "clang/Basic/OperatorKinds.def" 4221 }; 4222 4223 bool CanBeUnaryOperator = OperatorUses[Op][0]; 4224 bool CanBeBinaryOperator = OperatorUses[Op][1]; 4225 bool MustBeMemberOperator = OperatorUses[Op][2]; 4226 4227 // C++ [over.oper]p8: 4228 // [...] Operator functions cannot have more or fewer parameters 4229 // than the number required for the corresponding operator, as 4230 // described in the rest of this subclause. 4231 unsigned NumParams = FnDecl->getNumParams() 4232 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 4233 if (Op != OO_Call && 4234 ((NumParams == 1 && !CanBeUnaryOperator) || 4235 (NumParams == 2 && !CanBeBinaryOperator) || 4236 (NumParams < 1) || (NumParams > 2))) { 4237 // We have the wrong number of parameters. 4238 unsigned ErrorKind; 4239 if (CanBeUnaryOperator && CanBeBinaryOperator) { 4240 ErrorKind = 2; // 2 -> unary or binary. 4241 } else if (CanBeUnaryOperator) { 4242 ErrorKind = 0; // 0 -> unary 4243 } else { 4244 assert(CanBeBinaryOperator && 4245 "All non-call overloaded operators are unary or binary!"); 4246 ErrorKind = 1; // 1 -> binary 4247 } 4248 4249 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 4250 << FnDecl->getDeclName() << NumParams << ErrorKind; 4251 } 4252 4253 // Overloaded operators other than operator() cannot be variadic. 4254 if (Op != OO_Call && 4255 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 4256 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 4257 << FnDecl->getDeclName(); 4258 } 4259 4260 // Some operators must be non-static member functions. 4261 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 4262 return Diag(FnDecl->getLocation(), 4263 diag::err_operator_overload_must_be_member) 4264 << FnDecl->getDeclName(); 4265 } 4266 4267 // C++ [over.inc]p1: 4268 // The user-defined function called operator++ implements the 4269 // prefix and postfix ++ operator. If this function is a member 4270 // function with no parameters, or a non-member function with one 4271 // parameter of class or enumeration type, it defines the prefix 4272 // increment operator ++ for objects of that type. If the function 4273 // is a member function with one parameter (which shall be of type 4274 // int) or a non-member function with two parameters (the second 4275 // of which shall be of type int), it defines the postfix 4276 // increment operator ++ for objects of that type. 4277 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 4278 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 4279 bool ParamIsInt = false; 4280 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>()) 4281 ParamIsInt = BT->getKind() == BuiltinType::Int; 4282 4283 if (!ParamIsInt) 4284 return Diag(LastParam->getLocation(), 4285 diag::err_operator_overload_post_incdec_must_be_int) 4286 << LastParam->getType() << (Op == OO_MinusMinus); 4287 } 4288 4289 // Notify the class if it got an assignment operator. 4290 if (Op == OO_Equal) { 4291 // Would have returned earlier otherwise. 4292 assert(isa<CXXMethodDecl>(FnDecl) && 4293 "Overloaded = not member, but not filtered."); 4294 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 4295 Method->getParent()->addedAssignmentOperator(Context, Method); 4296 } 4297 4298 return false; 4299} 4300 4301/// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 4302/// linkage specification, including the language and (if present) 4303/// the '{'. ExternLoc is the location of the 'extern', LangLoc is 4304/// the location of the language string literal, which is provided 4305/// by Lang/StrSize. LBraceLoc, if valid, provides the location of 4306/// the '{' brace. Otherwise, this linkage specification does not 4307/// have any braces. 4308Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S, 4309 SourceLocation ExternLoc, 4310 SourceLocation LangLoc, 4311 const char *Lang, 4312 unsigned StrSize, 4313 SourceLocation LBraceLoc) { 4314 LinkageSpecDecl::LanguageIDs Language; 4315 if (strncmp(Lang, "\"C\"", StrSize) == 0) 4316 Language = LinkageSpecDecl::lang_c; 4317 else if (strncmp(Lang, "\"C++\"", StrSize) == 0) 4318 Language = LinkageSpecDecl::lang_cxx; 4319 else { 4320 Diag(LangLoc, diag::err_bad_language); 4321 return DeclPtrTy(); 4322 } 4323 4324 // FIXME: Add all the various semantics of linkage specifications 4325 4326 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, 4327 LangLoc, Language, 4328 LBraceLoc.isValid()); 4329 CurContext->addDecl(D); 4330 PushDeclContext(S, D); 4331 return DeclPtrTy::make(D); 4332} 4333 4334/// ActOnFinishLinkageSpecification - Completely the definition of 4335/// the C++ linkage specification LinkageSpec. If RBraceLoc is 4336/// valid, it's the position of the closing '}' brace in a linkage 4337/// specification that uses braces. 4338Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S, 4339 DeclPtrTy LinkageSpec, 4340 SourceLocation RBraceLoc) { 4341 if (LinkageSpec) 4342 PopDeclContext(); 4343 return LinkageSpec; 4344} 4345 4346/// \brief Perform semantic analysis for the variable declaration that 4347/// occurs within a C++ catch clause, returning the newly-created 4348/// variable. 4349VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType, 4350 DeclaratorInfo *DInfo, 4351 IdentifierInfo *Name, 4352 SourceLocation Loc, 4353 SourceRange Range) { 4354 bool Invalid = false; 4355 4356 // Arrays and functions decay. 4357 if (ExDeclType->isArrayType()) 4358 ExDeclType = Context.getArrayDecayedType(ExDeclType); 4359 else if (ExDeclType->isFunctionType()) 4360 ExDeclType = Context.getPointerType(ExDeclType); 4361 4362 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 4363 // The exception-declaration shall not denote a pointer or reference to an 4364 // incomplete type, other than [cv] void*. 4365 // N2844 forbids rvalue references. 4366 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 4367 Diag(Loc, diag::err_catch_rvalue_ref) << Range; 4368 Invalid = true; 4369 } 4370 4371 QualType BaseType = ExDeclType; 4372 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 4373 unsigned DK = diag::err_catch_incomplete; 4374 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 4375 BaseType = Ptr->getPointeeType(); 4376 Mode = 1; 4377 DK = diag::err_catch_incomplete_ptr; 4378 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 4379 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 4380 BaseType = Ref->getPointeeType(); 4381 Mode = 2; 4382 DK = diag::err_catch_incomplete_ref; 4383 } 4384 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 4385 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 4386 Invalid = true; 4387 4388 if (!Invalid && !ExDeclType->isDependentType() && 4389 RequireNonAbstractType(Loc, ExDeclType, 4390 diag::err_abstract_type_in_decl, 4391 AbstractVariableType)) 4392 Invalid = true; 4393 4394 // FIXME: Need to test for ability to copy-construct and destroy the 4395 // exception variable. 4396 4397 // FIXME: Need to check for abstract classes. 4398 4399 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc, 4400 Name, ExDeclType, DInfo, VarDecl::None); 4401 4402 if (Invalid) 4403 ExDecl->setInvalidDecl(); 4404 4405 return ExDecl; 4406} 4407 4408/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 4409/// handler. 4410Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 4411 DeclaratorInfo *DInfo = 0; 4412 QualType ExDeclType = GetTypeForDeclarator(D, S, &DInfo); 4413 4414 bool Invalid = D.isInvalidType(); 4415 IdentifierInfo *II = D.getIdentifier(); 4416 if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) { 4417 // The scope should be freshly made just for us. There is just no way 4418 // it contains any previous declaration. 4419 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl))); 4420 if (PrevDecl->isTemplateParameter()) { 4421 // Maybe we will complain about the shadowed template parameter. 4422 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 4423 } 4424 } 4425 4426 if (D.getCXXScopeSpec().isSet() && !Invalid) { 4427 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 4428 << D.getCXXScopeSpec().getRange(); 4429 Invalid = true; 4430 } 4431 4432 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, DInfo, 4433 D.getIdentifier(), 4434 D.getIdentifierLoc(), 4435 D.getDeclSpec().getSourceRange()); 4436 4437 if (Invalid) 4438 ExDecl->setInvalidDecl(); 4439 4440 // Add the exception declaration into this scope. 4441 if (II) 4442 PushOnScopeChains(ExDecl, S); 4443 else 4444 CurContext->addDecl(ExDecl); 4445 4446 ProcessDeclAttributes(S, ExDecl, D); 4447 return DeclPtrTy::make(ExDecl); 4448} 4449 4450Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc, 4451 ExprArg assertexpr, 4452 ExprArg assertmessageexpr) { 4453 Expr *AssertExpr = (Expr *)assertexpr.get(); 4454 StringLiteral *AssertMessage = 4455 cast<StringLiteral>((Expr *)assertmessageexpr.get()); 4456 4457 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) { 4458 llvm::APSInt Value(32); 4459 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) { 4460 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) << 4461 AssertExpr->getSourceRange(); 4462 return DeclPtrTy(); 4463 } 4464 4465 if (Value == 0) { 4466 std::string str(AssertMessage->getStrData(), 4467 AssertMessage->getByteLength()); 4468 Diag(AssertLoc, diag::err_static_assert_failed) 4469 << str << AssertExpr->getSourceRange(); 4470 } 4471 } 4472 4473 assertexpr.release(); 4474 assertmessageexpr.release(); 4475 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc, 4476 AssertExpr, AssertMessage); 4477 4478 CurContext->addDecl(Decl); 4479 return DeclPtrTy::make(Decl); 4480} 4481 4482/// Handle a friend type declaration. This works in tandem with 4483/// ActOnTag. 4484/// 4485/// Notes on friend class templates: 4486/// 4487/// We generally treat friend class declarations as if they were 4488/// declaring a class. So, for example, the elaborated type specifier 4489/// in a friend declaration is required to obey the restrictions of a 4490/// class-head (i.e. no typedefs in the scope chain), template 4491/// parameters are required to match up with simple template-ids, &c. 4492/// However, unlike when declaring a template specialization, it's 4493/// okay to refer to a template specialization without an empty 4494/// template parameter declaration, e.g. 4495/// friend class A<T>::B<unsigned>; 4496/// We permit this as a special case; if there are any template 4497/// parameters present at all, require proper matching, i.e. 4498/// template <> template <class T> friend class A<int>::B; 4499Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 4500 MultiTemplateParamsArg TempParams) { 4501 SourceLocation Loc = DS.getSourceRange().getBegin(); 4502 4503 assert(DS.isFriendSpecified()); 4504 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 4505 4506 // Try to convert the decl specifier to a type. This works for 4507 // friend templates because ActOnTag never produces a ClassTemplateDecl 4508 // for a TUK_Friend. 4509 Declarator TheDeclarator(DS, Declarator::MemberContext); 4510 QualType T = GetTypeForDeclarator(TheDeclarator, S); 4511 if (TheDeclarator.isInvalidType()) 4512 return DeclPtrTy(); 4513 4514 // This is definitely an error in C++98. It's probably meant to 4515 // be forbidden in C++0x, too, but the specification is just 4516 // poorly written. 4517 // 4518 // The problem is with declarations like the following: 4519 // template <T> friend A<T>::foo; 4520 // where deciding whether a class C is a friend or not now hinges 4521 // on whether there exists an instantiation of A that causes 4522 // 'foo' to equal C. There are restrictions on class-heads 4523 // (which we declare (by fiat) elaborated friend declarations to 4524 // be) that makes this tractable. 4525 // 4526 // FIXME: handle "template <> friend class A<T>;", which 4527 // is possibly well-formed? Who even knows? 4528 if (TempParams.size() && !isa<ElaboratedType>(T)) { 4529 Diag(Loc, diag::err_tagless_friend_type_template) 4530 << DS.getSourceRange(); 4531 return DeclPtrTy(); 4532 } 4533 4534 // C++ [class.friend]p2: 4535 // An elaborated-type-specifier shall be used in a friend declaration 4536 // for a class.* 4537 // * The class-key of the elaborated-type-specifier is required. 4538 // This is one of the rare places in Clang where it's legitimate to 4539 // ask about the "spelling" of the type. 4540 if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) { 4541 // If we evaluated the type to a record type, suggest putting 4542 // a tag in front. 4543 if (const RecordType *RT = T->getAs<RecordType>()) { 4544 RecordDecl *RD = RT->getDecl(); 4545 4546 std::string InsertionText = std::string(" ") + RD->getKindName(); 4547 4548 Diag(DS.getTypeSpecTypeLoc(), diag::err_unelaborated_friend_type) 4549 << (unsigned) RD->getTagKind() 4550 << T 4551 << SourceRange(DS.getFriendSpecLoc()) 4552 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(), 4553 InsertionText); 4554 return DeclPtrTy(); 4555 }else { 4556 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend) 4557 << DS.getSourceRange(); 4558 return DeclPtrTy(); 4559 } 4560 } 4561 4562 // Enum types cannot be friends. 4563 if (T->getAs<EnumType>()) { 4564 Diag(DS.getTypeSpecTypeLoc(), diag::err_enum_friend) 4565 << SourceRange(DS.getFriendSpecLoc()); 4566 return DeclPtrTy(); 4567 } 4568 4569 // C++98 [class.friend]p1: A friend of a class is a function 4570 // or class that is not a member of the class . . . 4571 // But that's a silly restriction which nobody implements for 4572 // inner classes, and C++0x removes it anyway, so we only report 4573 // this (as a warning) if we're being pedantic. 4574 if (!getLangOptions().CPlusPlus0x) 4575 if (const RecordType *RT = T->getAs<RecordType>()) 4576 if (RT->getDecl()->getDeclContext() == CurContext) 4577 Diag(DS.getFriendSpecLoc(), diag::ext_friend_inner_class); 4578 4579 Decl *D; 4580 if (TempParams.size()) 4581 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 4582 TempParams.size(), 4583 (TemplateParameterList**) TempParams.release(), 4584 T.getTypePtr(), 4585 DS.getFriendSpecLoc()); 4586 else 4587 D = FriendDecl::Create(Context, CurContext, Loc, T.getTypePtr(), 4588 DS.getFriendSpecLoc()); 4589 D->setAccess(AS_public); 4590 CurContext->addDecl(D); 4591 4592 return DeclPtrTy::make(D); 4593} 4594 4595Sema::DeclPtrTy 4596Sema::ActOnFriendFunctionDecl(Scope *S, 4597 Declarator &D, 4598 bool IsDefinition, 4599 MultiTemplateParamsArg TemplateParams) { 4600 const DeclSpec &DS = D.getDeclSpec(); 4601 4602 assert(DS.isFriendSpecified()); 4603 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 4604 4605 SourceLocation Loc = D.getIdentifierLoc(); 4606 DeclaratorInfo *DInfo = 0; 4607 QualType T = GetTypeForDeclarator(D, S, &DInfo); 4608 4609 // C++ [class.friend]p1 4610 // A friend of a class is a function or class.... 4611 // Note that this sees through typedefs, which is intended. 4612 // It *doesn't* see through dependent types, which is correct 4613 // according to [temp.arg.type]p3: 4614 // If a declaration acquires a function type through a 4615 // type dependent on a template-parameter and this causes 4616 // a declaration that does not use the syntactic form of a 4617 // function declarator to have a function type, the program 4618 // is ill-formed. 4619 if (!T->isFunctionType()) { 4620 Diag(Loc, diag::err_unexpected_friend); 4621 4622 // It might be worthwhile to try to recover by creating an 4623 // appropriate declaration. 4624 return DeclPtrTy(); 4625 } 4626 4627 // C++ [namespace.memdef]p3 4628 // - If a friend declaration in a non-local class first declares a 4629 // class or function, the friend class or function is a member 4630 // of the innermost enclosing namespace. 4631 // - The name of the friend is not found by simple name lookup 4632 // until a matching declaration is provided in that namespace 4633 // scope (either before or after the class declaration granting 4634 // friendship). 4635 // - If a friend function is called, its name may be found by the 4636 // name lookup that considers functions from namespaces and 4637 // classes associated with the types of the function arguments. 4638 // - When looking for a prior declaration of a class or a function 4639 // declared as a friend, scopes outside the innermost enclosing 4640 // namespace scope are not considered. 4641 4642 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec(); 4643 DeclarationName Name = GetNameForDeclarator(D); 4644 assert(Name); 4645 4646 // The context we found the declaration in, or in which we should 4647 // create the declaration. 4648 DeclContext *DC; 4649 4650 // FIXME: handle local classes 4651 4652 // Recover from invalid scope qualifiers as if they just weren't there. 4653 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName, 4654 ForRedeclaration); 4655 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) { 4656 // FIXME: RequireCompleteDeclContext 4657 DC = computeDeclContext(ScopeQual); 4658 4659 // FIXME: handle dependent contexts 4660 if (!DC) return DeclPtrTy(); 4661 4662 LookupQualifiedName(Previous, DC); 4663 4664 // If searching in that context implicitly found a declaration in 4665 // a different context, treat it like it wasn't found at all. 4666 // TODO: better diagnostics for this case. Suggesting the right 4667 // qualified scope would be nice... 4668 // FIXME: getRepresentativeDecl() is not right here at all 4669 if (Previous.empty() || 4670 !Previous.getRepresentativeDecl()->getDeclContext()->Equals(DC)) { 4671 D.setInvalidType(); 4672 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T; 4673 return DeclPtrTy(); 4674 } 4675 4676 // C++ [class.friend]p1: A friend of a class is a function or 4677 // class that is not a member of the class . . . 4678 if (DC->Equals(CurContext)) 4679 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member); 4680 4681 // Otherwise walk out to the nearest namespace scope looking for matches. 4682 } else { 4683 // TODO: handle local class contexts. 4684 4685 DC = CurContext; 4686 while (true) { 4687 // Skip class contexts. If someone can cite chapter and verse 4688 // for this behavior, that would be nice --- it's what GCC and 4689 // EDG do, and it seems like a reasonable intent, but the spec 4690 // really only says that checks for unqualified existing 4691 // declarations should stop at the nearest enclosing namespace, 4692 // not that they should only consider the nearest enclosing 4693 // namespace. 4694 while (DC->isRecord()) 4695 DC = DC->getParent(); 4696 4697 LookupQualifiedName(Previous, DC); 4698 4699 // TODO: decide what we think about using declarations. 4700 if (!Previous.empty()) 4701 break; 4702 4703 if (DC->isFileContext()) break; 4704 DC = DC->getParent(); 4705 } 4706 4707 // C++ [class.friend]p1: A friend of a class is a function or 4708 // class that is not a member of the class . . . 4709 // C++0x changes this for both friend types and functions. 4710 // Most C++ 98 compilers do seem to give an error here, so 4711 // we do, too. 4712 if (!Previous.empty() && DC->Equals(CurContext) 4713 && !getLangOptions().CPlusPlus0x) 4714 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member); 4715 } 4716 4717 if (DC->isFileContext()) { 4718 // This implies that it has to be an operator or function. 4719 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName || 4720 D.getName().getKind() == UnqualifiedId::IK_DestructorName || 4721 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) { 4722 Diag(Loc, diag::err_introducing_special_friend) << 4723 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 : 4724 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2); 4725 return DeclPtrTy(); 4726 } 4727 } 4728 4729 bool Redeclaration = false; 4730 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, DInfo, Previous, 4731 move(TemplateParams), 4732 IsDefinition, 4733 Redeclaration); 4734 if (!ND) return DeclPtrTy(); 4735 4736 assert(ND->getDeclContext() == DC); 4737 assert(ND->getLexicalDeclContext() == CurContext); 4738 4739 // Add the function declaration to the appropriate lookup tables, 4740 // adjusting the redeclarations list as necessary. We don't 4741 // want to do this yet if the friending class is dependent. 4742 // 4743 // Also update the scope-based lookup if the target context's 4744 // lookup context is in lexical scope. 4745 if (!CurContext->isDependentContext()) { 4746 DC = DC->getLookupContext(); 4747 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false); 4748 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 4749 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 4750 } 4751 4752 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 4753 D.getIdentifierLoc(), ND, 4754 DS.getFriendSpecLoc()); 4755 FrD->setAccess(AS_public); 4756 CurContext->addDecl(FrD); 4757 4758 return DeclPtrTy::make(ND); 4759} 4760 4761void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) { 4762 AdjustDeclIfTemplate(dcl); 4763 4764 Decl *Dcl = dcl.getAs<Decl>(); 4765 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl); 4766 if (!Fn) { 4767 Diag(DelLoc, diag::err_deleted_non_function); 4768 return; 4769 } 4770 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) { 4771 Diag(DelLoc, diag::err_deleted_decl_not_first); 4772 Diag(Prev->getLocation(), diag::note_previous_declaration); 4773 // If the declaration wasn't the first, we delete the function anyway for 4774 // recovery. 4775 } 4776 Fn->setDeleted(); 4777} 4778 4779static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 4780 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E; 4781 ++CI) { 4782 Stmt *SubStmt = *CI; 4783 if (!SubStmt) 4784 continue; 4785 if (isa<ReturnStmt>(SubStmt)) 4786 Self.Diag(SubStmt->getSourceRange().getBegin(), 4787 diag::err_return_in_constructor_handler); 4788 if (!isa<Expr>(SubStmt)) 4789 SearchForReturnInStmt(Self, SubStmt); 4790 } 4791} 4792 4793void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 4794 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 4795 CXXCatchStmt *Handler = TryBlock->getHandler(I); 4796 SearchForReturnInStmt(*this, Handler); 4797 } 4798} 4799 4800bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 4801 const CXXMethodDecl *Old) { 4802 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType(); 4803 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType(); 4804 4805 QualType CNewTy = Context.getCanonicalType(NewTy); 4806 QualType COldTy = Context.getCanonicalType(OldTy); 4807 4808 if (CNewTy == COldTy && 4809 CNewTy.getLocalCVRQualifiers() == COldTy.getLocalCVRQualifiers()) 4810 return false; 4811 4812 // Check if the return types are covariant 4813 QualType NewClassTy, OldClassTy; 4814 4815 /// Both types must be pointers or references to classes. 4816 if (PointerType *NewPT = dyn_cast<PointerType>(NewTy)) { 4817 if (PointerType *OldPT = dyn_cast<PointerType>(OldTy)) { 4818 NewClassTy = NewPT->getPointeeType(); 4819 OldClassTy = OldPT->getPointeeType(); 4820 } 4821 } else if (ReferenceType *NewRT = dyn_cast<ReferenceType>(NewTy)) { 4822 if (ReferenceType *OldRT = dyn_cast<ReferenceType>(OldTy)) { 4823 NewClassTy = NewRT->getPointeeType(); 4824 OldClassTy = OldRT->getPointeeType(); 4825 } 4826 } 4827 4828 // The return types aren't either both pointers or references to a class type. 4829 if (NewClassTy.isNull()) { 4830 Diag(New->getLocation(), 4831 diag::err_different_return_type_for_overriding_virtual_function) 4832 << New->getDeclName() << NewTy << OldTy; 4833 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 4834 4835 return true; 4836 } 4837 4838 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 4839 // Check if the new class derives from the old class. 4840 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 4841 Diag(New->getLocation(), 4842 diag::err_covariant_return_not_derived) 4843 << New->getDeclName() << NewTy << OldTy; 4844 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 4845 return true; 4846 } 4847 4848 // Check if we the conversion from derived to base is valid. 4849 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy, 4850 diag::err_covariant_return_inaccessible_base, 4851 diag::err_covariant_return_ambiguous_derived_to_base_conv, 4852 // FIXME: Should this point to the return type? 4853 New->getLocation(), SourceRange(), New->getDeclName())) { 4854 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 4855 return true; 4856 } 4857 } 4858 4859 // The qualifiers of the return types must be the same. 4860 if (CNewTy.getLocalCVRQualifiers() != COldTy.getLocalCVRQualifiers()) { 4861 Diag(New->getLocation(), 4862 diag::err_covariant_return_type_different_qualifications) 4863 << New->getDeclName() << NewTy << OldTy; 4864 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 4865 return true; 4866 }; 4867 4868 4869 // The new class type must have the same or less qualifiers as the old type. 4870 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 4871 Diag(New->getLocation(), 4872 diag::err_covariant_return_type_class_type_more_qualified) 4873 << New->getDeclName() << NewTy << OldTy; 4874 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 4875 return true; 4876 }; 4877 4878 return false; 4879} 4880 4881bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 4882 const CXXMethodDecl *Old) 4883{ 4884 if (Old->hasAttr<FinalAttr>()) { 4885 Diag(New->getLocation(), diag::err_final_function_overridden) 4886 << New->getDeclName(); 4887 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 4888 return true; 4889 } 4890 4891 return false; 4892} 4893 4894/// \brief Mark the given method pure. 4895/// 4896/// \param Method the method to be marked pure. 4897/// 4898/// \param InitRange the source range that covers the "0" initializer. 4899bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 4900 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 4901 Method->setPure(); 4902 4903 // A class is abstract if at least one function is pure virtual. 4904 Method->getParent()->setAbstract(true); 4905 return false; 4906 } 4907 4908 if (!Method->isInvalidDecl()) 4909 Diag(Method->getLocation(), diag::err_non_virtual_pure) 4910 << Method->getDeclName() << InitRange; 4911 return true; 4912} 4913 4914/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an 4915/// initializer for the declaration 'Dcl'. 4916/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 4917/// static data member of class X, names should be looked up in the scope of 4918/// class X. 4919void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) { 4920 AdjustDeclIfTemplate(Dcl); 4921 4922 Decl *D = Dcl.getAs<Decl>(); 4923 // If there is no declaration, there was an error parsing it. 4924 if (D == 0) 4925 return; 4926 4927 // Check whether it is a declaration with a nested name specifier like 4928 // int foo::bar; 4929 if (!D->isOutOfLine()) 4930 return; 4931 4932 // C++ [basic.lookup.unqual]p13 4933 // 4934 // A name used in the definition of a static data member of class X 4935 // (after the qualified-id of the static member) is looked up as if the name 4936 // was used in a member function of X. 4937 4938 // Change current context into the context of the initializing declaration. 4939 EnterDeclaratorContext(S, D->getDeclContext()); 4940} 4941 4942/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 4943/// initializer for the declaration 'Dcl'. 4944void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) { 4945 AdjustDeclIfTemplate(Dcl); 4946 4947 Decl *D = Dcl.getAs<Decl>(); 4948 // If there is no declaration, there was an error parsing it. 4949 if (D == 0) 4950 return; 4951 4952 // Check whether it is a declaration with a nested name specifier like 4953 // int foo::bar; 4954 if (!D->isOutOfLine()) 4955 return; 4956 4957 assert(S->getEntity() == D->getDeclContext() && "Context imbalance!"); 4958 ExitDeclaratorContext(S); 4959} 4960 4961/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 4962/// C++ if/switch/while/for statement. 4963/// e.g: "if (int x = f()) {...}" 4964Action::DeclResult 4965Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 4966 // C++ 6.4p2: 4967 // The declarator shall not specify a function or an array. 4968 // The type-specifier-seq shall not contain typedef and shall not declare a 4969 // new class or enumeration. 4970 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 4971 "Parser allowed 'typedef' as storage class of condition decl."); 4972 4973 DeclaratorInfo *DInfo = 0; 4974 TagDecl *OwnedTag = 0; 4975 QualType Ty = GetTypeForDeclarator(D, S, &DInfo, &OwnedTag); 4976 4977 if (Ty->isFunctionType()) { // The declarator shall not specify a function... 4978 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl 4979 // would be created and CXXConditionDeclExpr wants a VarDecl. 4980 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type) 4981 << D.getSourceRange(); 4982 return DeclResult(); 4983 } else if (OwnedTag && OwnedTag->isDefinition()) { 4984 // The type-specifier-seq shall not declare a new class or enumeration. 4985 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition); 4986 } 4987 4988 DeclPtrTy Dcl = ActOnDeclarator(S, D); 4989 if (!Dcl) 4990 return DeclResult(); 4991 4992 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>()); 4993 VD->setDeclaredInCondition(true); 4994 return Dcl; 4995} 4996