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