SemaDeclCXX.cpp revision ff7fea809bab2badd0cb241703b14ac20ac258cb
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/TypeOrdering.h" 19#include "clang/AST/StmtVisitor.h" 20#include "clang/Lex/Preprocessor.h" 21#include "clang/Parse/DeclSpec.h" 22#include "llvm/ADT/STLExtras.h" 23#include "llvm/Support/Compiler.h" 24#include <algorithm> // for std::equal 25#include <map> 26 27using namespace clang; 28 29//===----------------------------------------------------------------------===// 30// CheckDefaultArgumentVisitor 31//===----------------------------------------------------------------------===// 32 33namespace { 34 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 35 /// the default argument of a parameter to determine whether it 36 /// contains any ill-formed subexpressions. For example, this will 37 /// diagnose the use of local variables or parameters within the 38 /// default argument expression. 39 class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor 40 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 41 Expr *DefaultArg; 42 Sema *S; 43 44 public: 45 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 46 : DefaultArg(defarg), S(s) {} 47 48 bool VisitExpr(Expr *Node); 49 bool VisitDeclRefExpr(DeclRefExpr *DRE); 50 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 51 }; 52 53 /// VisitExpr - Visit all of the children of this expression. 54 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 55 bool IsInvalid = false; 56 for (Stmt::child_iterator I = Node->child_begin(), 57 E = Node->child_end(); I != E; ++I) 58 IsInvalid |= Visit(*I); 59 return IsInvalid; 60 } 61 62 /// VisitDeclRefExpr - Visit a reference to a declaration, to 63 /// determine whether this declaration can be used in the default 64 /// argument expression. 65 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 66 NamedDecl *Decl = DRE->getDecl(); 67 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 68 // C++ [dcl.fct.default]p9 69 // Default arguments are evaluated each time the function is 70 // called. The order of evaluation of function arguments is 71 // unspecified. Consequently, parameters of a function shall not 72 // be used in default argument expressions, even if they are not 73 // evaluated. Parameters of a function declared before a default 74 // argument expression are in scope and can hide namespace and 75 // class member names. 76 return S->Diag(DRE->getSourceRange().getBegin(), 77 diag::err_param_default_argument_references_param) 78 << Param->getDeclName() << DefaultArg->getSourceRange(); 79 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 80 // C++ [dcl.fct.default]p7 81 // Local variables shall not be used in default argument 82 // expressions. 83 if (VDecl->isBlockVarDecl()) 84 return S->Diag(DRE->getSourceRange().getBegin(), 85 diag::err_param_default_argument_references_local) 86 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 87 } 88 89 return false; 90 } 91 92 /// VisitCXXThisExpr - Visit a C++ "this" expression. 93 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 94 // C++ [dcl.fct.default]p8: 95 // The keyword this shall not be used in a default argument of a 96 // member function. 97 return S->Diag(ThisE->getSourceRange().getBegin(), 98 diag::err_param_default_argument_references_this) 99 << ThisE->getSourceRange(); 100 } 101} 102 103/// ActOnParamDefaultArgument - Check whether the default argument 104/// provided for a function parameter is well-formed. If so, attach it 105/// to the parameter declaration. 106void 107Sema::ActOnParamDefaultArgument(DeclTy *param, SourceLocation EqualLoc, 108 ExprTy *defarg) { 109 ParmVarDecl *Param = (ParmVarDecl *)param; 110 ExprOwningPtr<Expr> DefaultArg(this, (Expr *)defarg); 111 QualType ParamType = Param->getType(); 112 113 // Default arguments are only permitted in C++ 114 if (!getLangOptions().CPlusPlus) { 115 Diag(EqualLoc, diag::err_param_default_argument) 116 << DefaultArg->getSourceRange(); 117 Param->setInvalidDecl(); 118 return; 119 } 120 121 // C++ [dcl.fct.default]p5 122 // A default argument expression is implicitly converted (clause 123 // 4) to the parameter type. The default argument expression has 124 // the same semantic constraints as the initializer expression in 125 // a declaration of a variable of the parameter type, using the 126 // copy-initialization semantics (8.5). 127 Expr *DefaultArgPtr = DefaultArg.get(); 128 bool DefaultInitFailed = CheckInitializerTypes(DefaultArgPtr, ParamType, 129 EqualLoc, 130 Param->getDeclName(), 131 /*DirectInit=*/false); 132 if (DefaultArgPtr != DefaultArg.get()) { 133 DefaultArg.take(); 134 DefaultArg.reset(DefaultArgPtr); 135 } 136 if (DefaultInitFailed) { 137 return; 138 } 139 140 // Check that the default argument is well-formed 141 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this); 142 if (DefaultArgChecker.Visit(DefaultArg.get())) { 143 Param->setInvalidDecl(); 144 return; 145 } 146 147 // Okay: add the default argument to the parameter 148 Param->setDefaultArg(DefaultArg.take()); 149} 150 151/// ActOnParamUnparsedDefaultArgument - We've seen a default 152/// argument for a function parameter, but we can't parse it yet 153/// because we're inside a class definition. Note that this default 154/// argument will be parsed later. 155void Sema::ActOnParamUnparsedDefaultArgument(DeclTy *param, 156 SourceLocation EqualLoc) { 157 ParmVarDecl *Param = (ParmVarDecl*)param; 158 if (Param) 159 Param->setUnparsedDefaultArg(); 160} 161 162/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 163/// the default argument for the parameter param failed. 164void Sema::ActOnParamDefaultArgumentError(DeclTy *param) { 165 ((ParmVarDecl*)param)->setInvalidDecl(); 166} 167 168/// CheckExtraCXXDefaultArguments - Check for any extra default 169/// arguments in the declarator, which is not a function declaration 170/// or definition and therefore is not permitted to have default 171/// arguments. This routine should be invoked for every declarator 172/// that is not a function declaration or definition. 173void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 174 // C++ [dcl.fct.default]p3 175 // A default argument expression shall be specified only in the 176 // parameter-declaration-clause of a function declaration or in a 177 // template-parameter (14.1). It shall not be specified for a 178 // parameter pack. If it is specified in a 179 // parameter-declaration-clause, it shall not occur within a 180 // declarator or abstract-declarator of a parameter-declaration. 181 for (unsigned i = 0; i < D.getNumTypeObjects(); ++i) { 182 DeclaratorChunk &chunk = D.getTypeObject(i); 183 if (chunk.Kind == DeclaratorChunk::Function) { 184 for (unsigned argIdx = 0; argIdx < chunk.Fun.NumArgs; ++argIdx) { 185 ParmVarDecl *Param = (ParmVarDecl *)chunk.Fun.ArgInfo[argIdx].Param; 186 if (Param->hasUnparsedDefaultArg()) { 187 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens; 188 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 189 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation()); 190 delete Toks; 191 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0; 192 } else if (Param->getDefaultArg()) { 193 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 194 << Param->getDefaultArg()->getSourceRange(); 195 Param->setDefaultArg(0); 196 } 197 } 198 } 199 } 200} 201 202// MergeCXXFunctionDecl - Merge two declarations of the same C++ 203// function, once we already know that they have the same 204// type. Subroutine of MergeFunctionDecl. Returns true if there was an 205// error, false otherwise. 206bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) { 207 bool Invalid = false; 208 209 // C++ [dcl.fct.default]p4: 210 // 211 // For non-template functions, default arguments can be added in 212 // later declarations of a function in the same 213 // scope. Declarations in different scopes have completely 214 // distinct sets of default arguments. That is, declarations in 215 // inner scopes do not acquire default arguments from 216 // declarations in outer scopes, and vice versa. In a given 217 // function declaration, all parameters subsequent to a 218 // parameter with a default argument shall have default 219 // arguments supplied in this or previous declarations. A 220 // default argument shall not be redefined by a later 221 // declaration (not even to the same value). 222 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 223 ParmVarDecl *OldParam = Old->getParamDecl(p); 224 ParmVarDecl *NewParam = New->getParamDecl(p); 225 226 if(OldParam->getDefaultArg() && NewParam->getDefaultArg()) { 227 Diag(NewParam->getLocation(), 228 diag::err_param_default_argument_redefinition) 229 << NewParam->getDefaultArg()->getSourceRange(); 230 Diag(OldParam->getLocation(), diag::note_previous_definition); 231 Invalid = true; 232 } else if (OldParam->getDefaultArg()) { 233 // Merge the old default argument into the new parameter 234 NewParam->setDefaultArg(OldParam->getDefaultArg()); 235 } 236 } 237 238 return Invalid; 239} 240 241/// CheckCXXDefaultArguments - Verify that the default arguments for a 242/// function declaration are well-formed according to C++ 243/// [dcl.fct.default]. 244void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 245 unsigned NumParams = FD->getNumParams(); 246 unsigned p; 247 248 // Find first parameter with a default argument 249 for (p = 0; p < NumParams; ++p) { 250 ParmVarDecl *Param = FD->getParamDecl(p); 251 if (Param->getDefaultArg()) 252 break; 253 } 254 255 // C++ [dcl.fct.default]p4: 256 // In a given function declaration, all parameters 257 // subsequent to a parameter with a default argument shall 258 // have default arguments supplied in this or previous 259 // declarations. A default argument shall not be redefined 260 // by a later declaration (not even to the same value). 261 unsigned LastMissingDefaultArg = 0; 262 for(; p < NumParams; ++p) { 263 ParmVarDecl *Param = FD->getParamDecl(p); 264 if (!Param->getDefaultArg()) { 265 if (Param->isInvalidDecl()) 266 /* We already complained about this parameter. */; 267 else if (Param->getIdentifier()) 268 Diag(Param->getLocation(), 269 diag::err_param_default_argument_missing_name) 270 << Param->getIdentifier(); 271 else 272 Diag(Param->getLocation(), 273 diag::err_param_default_argument_missing); 274 275 LastMissingDefaultArg = p; 276 } 277 } 278 279 if (LastMissingDefaultArg > 0) { 280 // Some default arguments were missing. Clear out all of the 281 // default arguments up to (and including) the last missing 282 // default argument, so that we leave the function parameters 283 // in a semantically valid state. 284 for (p = 0; p <= LastMissingDefaultArg; ++p) { 285 ParmVarDecl *Param = FD->getParamDecl(p); 286 if (Param->getDefaultArg()) { 287 if (!Param->hasUnparsedDefaultArg()) 288 Param->getDefaultArg()->Destroy(Context); 289 Param->setDefaultArg(0); 290 } 291 } 292 } 293} 294 295/// isCurrentClassName - Determine whether the identifier II is the 296/// name of the class type currently being defined. In the case of 297/// nested classes, this will only return true if II is the name of 298/// the innermost class. 299bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 300 const CXXScopeSpec *SS) { 301 CXXRecordDecl *CurDecl; 302 if (SS) { 303 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep()); 304 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 305 } else 306 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 307 308 if (CurDecl) 309 return &II == CurDecl->getIdentifier(); 310 else 311 return false; 312} 313 314/// \brief Check the validity of a C++ base class specifier. 315/// 316/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 317/// and returns NULL otherwise. 318CXXBaseSpecifier * 319Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 320 SourceRange SpecifierRange, 321 bool Virtual, AccessSpecifier Access, 322 QualType BaseType, 323 SourceLocation BaseLoc) { 324 // C++ [class.union]p1: 325 // A union shall not have base classes. 326 if (Class->isUnion()) { 327 Diag(Class->getLocation(), diag::err_base_clause_on_union) 328 << SpecifierRange; 329 return 0; 330 } 331 332 if (BaseType->isDependentType()) 333 return new CXXBaseSpecifier(SpecifierRange, Virtual, 334 Class->getTagKind() == RecordDecl::TK_class, 335 Access, BaseType); 336 337 // Base specifiers must be record types. 338 if (!BaseType->isRecordType()) { 339 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 340 return 0; 341 } 342 343 // C++ [class.union]p1: 344 // A union shall not be used as a base class. 345 if (BaseType->isUnionType()) { 346 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 347 return 0; 348 } 349 350 // C++ [class.derived]p2: 351 // The class-name in a base-specifier shall not be an incompletely 352 // defined class. 353 if (RequireCompleteType(BaseLoc, BaseType, diag::err_incomplete_base_class, 354 SpecifierRange)) 355 return 0; 356 357 // If the base class is polymorphic, the new one is, too. 358 RecordDecl *BaseDecl = BaseType->getAsRecordType()->getDecl(); 359 assert(BaseDecl && "Record type has no declaration"); 360 BaseDecl = BaseDecl->getDefinition(Context); 361 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 362 if (cast<CXXRecordDecl>(BaseDecl)->isPolymorphic()) 363 Class->setPolymorphic(true); 364 365 // C++ [dcl.init.aggr]p1: 366 // An aggregate is [...] a class with [...] no base classes [...]. 367 Class->setAggregate(false); 368 Class->setPOD(false); 369 370 // Create the base specifier. 371 // FIXME: Allocate via ASTContext? 372 return new CXXBaseSpecifier(SpecifierRange, Virtual, 373 Class->getTagKind() == RecordDecl::TK_class, 374 Access, BaseType); 375} 376 377/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 378/// one entry in the base class list of a class specifier, for 379/// example: 380/// class foo : public bar, virtual private baz { 381/// 'public bar' and 'virtual private baz' are each base-specifiers. 382Sema::BaseResult 383Sema::ActOnBaseSpecifier(DeclTy *classdecl, SourceRange SpecifierRange, 384 bool Virtual, AccessSpecifier Access, 385 TypeTy *basetype, SourceLocation BaseLoc) { 386 AdjustDeclIfTemplate(classdecl); 387 CXXRecordDecl *Class = cast<CXXRecordDecl>((Decl*)classdecl); 388 QualType BaseType = QualType::getFromOpaquePtr(basetype); 389 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 390 Virtual, Access, 391 BaseType, BaseLoc)) 392 return BaseSpec; 393 394 return true; 395} 396 397/// \brief Performs the actual work of attaching the given base class 398/// specifiers to a C++ class. 399bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 400 unsigned NumBases) { 401 if (NumBases == 0) 402 return false; 403 404 // Used to keep track of which base types we have already seen, so 405 // that we can properly diagnose redundant direct base types. Note 406 // that the key is always the unqualified canonical type of the base 407 // class. 408 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 409 410 // Copy non-redundant base specifiers into permanent storage. 411 unsigned NumGoodBases = 0; 412 bool Invalid = false; 413 for (unsigned idx = 0; idx < NumBases; ++idx) { 414 QualType NewBaseType 415 = Context.getCanonicalType(Bases[idx]->getType()); 416 NewBaseType = NewBaseType.getUnqualifiedType(); 417 418 if (KnownBaseTypes[NewBaseType]) { 419 // C++ [class.mi]p3: 420 // A class shall not be specified as a direct base class of a 421 // derived class more than once. 422 Diag(Bases[idx]->getSourceRange().getBegin(), 423 diag::err_duplicate_base_class) 424 << KnownBaseTypes[NewBaseType]->getType() 425 << Bases[idx]->getSourceRange(); 426 427 // Delete the duplicate base class specifier; we're going to 428 // overwrite its pointer later. 429 delete Bases[idx]; 430 431 Invalid = true; 432 } else { 433 // Okay, add this new base class. 434 KnownBaseTypes[NewBaseType] = Bases[idx]; 435 Bases[NumGoodBases++] = Bases[idx]; 436 } 437 } 438 439 // Attach the remaining base class specifiers to the derived class. 440 Class->setBases(Bases, NumGoodBases); 441 442 // Delete the remaining (good) base class specifiers, since their 443 // data has been copied into the CXXRecordDecl. 444 for (unsigned idx = 0; idx < NumGoodBases; ++idx) 445 delete Bases[idx]; 446 447 return Invalid; 448} 449 450/// ActOnBaseSpecifiers - Attach the given base specifiers to the 451/// class, after checking whether there are any duplicate base 452/// classes. 453void Sema::ActOnBaseSpecifiers(DeclTy *ClassDecl, BaseTy **Bases, 454 unsigned NumBases) { 455 if (!ClassDecl || !Bases || !NumBases) 456 return; 457 458 AdjustDeclIfTemplate(ClassDecl); 459 AttachBaseSpecifiers(cast<CXXRecordDecl>((Decl*)ClassDecl), 460 (CXXBaseSpecifier**)(Bases), NumBases); 461} 462 463//===----------------------------------------------------------------------===// 464// C++ class member Handling 465//===----------------------------------------------------------------------===// 466 467/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 468/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 469/// bitfield width if there is one and 'InitExpr' specifies the initializer if 470/// any. 'LastInGroup' is non-null for cases where one declspec has multiple 471/// declarators on it. 472Sema::DeclTy * 473Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 474 ExprTy *BW, ExprTy *InitExpr, 475 DeclTy *LastInGroup) { 476 const DeclSpec &DS = D.getDeclSpec(); 477 DeclarationName Name = GetNameForDeclarator(D); 478 Expr *BitWidth = static_cast<Expr*>(BW); 479 Expr *Init = static_cast<Expr*>(InitExpr); 480 SourceLocation Loc = D.getIdentifierLoc(); 481 482 bool isFunc = D.isFunctionDeclarator(); 483 484 // C++ 9.2p6: A member shall not be declared to have automatic storage 485 // duration (auto, register) or with the extern storage-class-specifier. 486 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 487 // data members and cannot be applied to names declared const or static, 488 // and cannot be applied to reference members. 489 switch (DS.getStorageClassSpec()) { 490 case DeclSpec::SCS_unspecified: 491 case DeclSpec::SCS_typedef: 492 case DeclSpec::SCS_static: 493 // FALL THROUGH. 494 break; 495 case DeclSpec::SCS_mutable: 496 if (isFunc) { 497 if (DS.getStorageClassSpecLoc().isValid()) 498 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 499 else 500 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function); 501 502 // FIXME: It would be nicer if the keyword was ignored only for this 503 // declarator. Otherwise we could get follow-up errors. 504 D.getMutableDeclSpec().ClearStorageClassSpecs(); 505 } else { 506 QualType T = GetTypeForDeclarator(D, S); 507 diag::kind err = static_cast<diag::kind>(0); 508 if (T->isReferenceType()) 509 err = diag::err_mutable_reference; 510 else if (T.isConstQualified()) 511 err = diag::err_mutable_const; 512 if (err != 0) { 513 if (DS.getStorageClassSpecLoc().isValid()) 514 Diag(DS.getStorageClassSpecLoc(), err); 515 else 516 Diag(DS.getThreadSpecLoc(), err); 517 // FIXME: It would be nicer if the keyword was ignored only for this 518 // declarator. Otherwise we could get follow-up errors. 519 D.getMutableDeclSpec().ClearStorageClassSpecs(); 520 } 521 } 522 break; 523 default: 524 if (DS.getStorageClassSpecLoc().isValid()) 525 Diag(DS.getStorageClassSpecLoc(), 526 diag::err_storageclass_invalid_for_member); 527 else 528 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member); 529 D.getMutableDeclSpec().ClearStorageClassSpecs(); 530 } 531 532 if (!isFunc && 533 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename && 534 D.getNumTypeObjects() == 0) { 535 // Check also for this case: 536 // 537 // typedef int f(); 538 // f a; 539 // 540 QualType TDType = QualType::getFromOpaquePtr(DS.getTypeRep()); 541 isFunc = TDType->isFunctionType(); 542 } 543 544 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 545 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 546 !isFunc); 547 548 Decl *Member; 549 if (isInstField) { 550 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth); 551 assert(Member && "HandleField never returns null"); 552 } else { 553 Member = static_cast<Decl*>(ActOnDeclarator(S, D, LastInGroup)); 554 if (!Member) { 555 if (BitWidth) DeleteExpr(BitWidth); 556 return LastInGroup; 557 } 558 559 // Non-instance-fields can't have a bitfield. 560 if (BitWidth) { 561 if (Member->isInvalidDecl()) { 562 // don't emit another diagnostic. 563 } else if (isa<VarDecl>(Member)) { 564 // C++ 9.6p3: A bit-field shall not be a static member. 565 // "static member 'A' cannot be a bit-field" 566 Diag(Loc, diag::err_static_not_bitfield) 567 << Name << BitWidth->getSourceRange(); 568 } else if (isa<TypedefDecl>(Member)) { 569 // "typedef member 'x' cannot be a bit-field" 570 Diag(Loc, diag::err_typedef_not_bitfield) 571 << Name << BitWidth->getSourceRange(); 572 } else { 573 // A function typedef ("typedef int f(); f a;"). 574 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 575 Diag(Loc, diag::err_not_integral_type_bitfield) 576 << Name << cast<ValueDecl>(Member)->getType() 577 << BitWidth->getSourceRange(); 578 } 579 580 DeleteExpr(BitWidth); 581 BitWidth = 0; 582 Member->setInvalidDecl(); 583 } 584 } 585 586 assert((Name || isInstField) && "No identifier for non-field ?"); 587 588 Member->setAccess(AS); 589 590 // C++ [dcl.init.aggr]p1: 591 // An aggregate is an array or a class (clause 9) with [...] no 592 // private or protected non-static data members (clause 11). 593 // A POD must be an aggregate. 594 if (isInstField && (AS == AS_private || AS == AS_protected)) { 595 CXXRecordDecl *Record = cast<CXXRecordDecl>(CurContext); 596 Record->setAggregate(false); 597 Record->setPOD(false); 598 } 599 600 if (DS.isVirtualSpecified()) { 601 if (!isFunc || DS.getStorageClassSpec() == DeclSpec::SCS_static) { 602 Diag(DS.getVirtualSpecLoc(), diag::err_virtual_non_function); 603 Member->setInvalidDecl(); 604 } else { 605 cast<CXXMethodDecl>(Member)->setVirtual(); 606 CXXRecordDecl *CurClass = cast<CXXRecordDecl>(CurContext); 607 CurClass->setAggregate(false); 608 CurClass->setPOD(false); 609 CurClass->setPolymorphic(true); 610 } 611 } 612 613 // FIXME: The above definition of virtual is not sufficient. A function is 614 // also virtual if it overrides an already virtual function. This is important 615 // to do here because it decides the validity of a pure specifier. 616 617 if (Init) { 618 // C++ 9.2p4: A member-declarator can contain a constant-initializer only 619 // if it declares a static member of const integral or const enumeration 620 // type. 621 if (VarDecl *CVD = dyn_cast<VarDecl>(Member)) { 622 // ...static member of... 623 CVD->setInit(Init); 624 // ...const integral or const enumeration type. 625 if (Context.getCanonicalType(CVD->getType()).isConstQualified() && 626 CVD->getType()->isIntegralType()) { 627 // constant-initializer 628 if (CheckForConstantInitializer(Init, CVD->getType())) 629 Member->setInvalidDecl(); 630 631 } else { 632 // not const integral. 633 Diag(Loc, diag::err_member_initialization) 634 << Name << Init->getSourceRange(); 635 Member->setInvalidDecl(); 636 } 637 638 } else { 639 // not static member. perhaps virtual function? 640 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member)) { 641 // With declarators parsed the way they are, the parser cannot 642 // distinguish between a normal initializer and a pure-specifier. 643 // Thus this grotesque test. 644 IntegerLiteral *IL; 645 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 && 646 Context.getCanonicalType(IL->getType()) == Context.IntTy) { 647 if (MD->isVirtual()) 648 MD->setPure(); 649 else { 650 Diag(Loc, diag::err_non_virtual_pure) 651 << Name << Init->getSourceRange(); 652 Member->setInvalidDecl(); 653 } 654 } else { 655 Diag(Loc, diag::err_member_function_initialization) 656 << Name << Init->getSourceRange(); 657 Member->setInvalidDecl(); 658 } 659 } else { 660 Diag(Loc, diag::err_member_initialization) 661 << Name << Init->getSourceRange(); 662 Member->setInvalidDecl(); 663 } 664 } 665 } 666 667 if (isInstField) { 668 FieldCollector->Add(cast<FieldDecl>(Member)); 669 return LastInGroup; 670 } 671 return Member; 672} 673 674/// ActOnMemInitializer - Handle a C++ member initializer. 675Sema::MemInitResult 676Sema::ActOnMemInitializer(DeclTy *ConstructorD, 677 Scope *S, 678 IdentifierInfo *MemberOrBase, 679 SourceLocation IdLoc, 680 SourceLocation LParenLoc, 681 ExprTy **Args, unsigned NumArgs, 682 SourceLocation *CommaLocs, 683 SourceLocation RParenLoc) { 684 CXXConstructorDecl *Constructor 685 = dyn_cast<CXXConstructorDecl>((Decl*)ConstructorD); 686 if (!Constructor) { 687 // The user wrote a constructor initializer on a function that is 688 // not a C++ constructor. Ignore the error for now, because we may 689 // have more member initializers coming; we'll diagnose it just 690 // once in ActOnMemInitializers. 691 return true; 692 } 693 694 CXXRecordDecl *ClassDecl = Constructor->getParent(); 695 696 // C++ [class.base.init]p2: 697 // Names in a mem-initializer-id are looked up in the scope of the 698 // constructor’s class and, if not found in that scope, are looked 699 // up in the scope containing the constructor’s 700 // definition. [Note: if the constructor’s class contains a member 701 // with the same name as a direct or virtual base class of the 702 // class, a mem-initializer-id naming the member or base class and 703 // composed of a single identifier refers to the class member. A 704 // mem-initializer-id for the hidden base class may be specified 705 // using a qualified name. ] 706 // Look for a member, first. 707 FieldDecl *Member = 0; 708 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase); 709 if (Result.first != Result.second) 710 Member = dyn_cast<FieldDecl>(*Result.first); 711 712 // FIXME: Handle members of an anonymous union. 713 714 if (Member) { 715 // FIXME: Perform direct initialization of the member. 716 return new CXXBaseOrMemberInitializer(Member, (Expr **)Args, NumArgs); 717 } 718 719 // It didn't name a member, so see if it names a class. 720 TypeTy *BaseTy = getTypeName(*MemberOrBase, IdLoc, S, 0/*SS*/); 721 if (!BaseTy) 722 return Diag(IdLoc, diag::err_mem_init_not_member_or_class) 723 << MemberOrBase << SourceRange(IdLoc, RParenLoc); 724 725 QualType BaseType = QualType::getFromOpaquePtr(BaseTy); 726 if (!BaseType->isRecordType()) 727 return Diag(IdLoc, diag::err_base_init_does_not_name_class) 728 << BaseType << SourceRange(IdLoc, RParenLoc); 729 730 // C++ [class.base.init]p2: 731 // [...] Unless the mem-initializer-id names a nonstatic data 732 // member of the constructor’s class or a direct or virtual base 733 // of that class, the mem-initializer is ill-formed. A 734 // mem-initializer-list can initialize a base class using any 735 // name that denotes that base class type. 736 737 // First, check for a direct base class. 738 const CXXBaseSpecifier *DirectBaseSpec = 0; 739 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(); 740 Base != ClassDecl->bases_end(); ++Base) { 741 if (Context.getCanonicalType(BaseType).getUnqualifiedType() == 742 Context.getCanonicalType(Base->getType()).getUnqualifiedType()) { 743 // We found a direct base of this type. That's what we're 744 // initializing. 745 DirectBaseSpec = &*Base; 746 break; 747 } 748 } 749 750 // Check for a virtual base class. 751 // FIXME: We might be able to short-circuit this if we know in 752 // advance that there are no virtual bases. 753 const CXXBaseSpecifier *VirtualBaseSpec = 0; 754 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 755 // We haven't found a base yet; search the class hierarchy for a 756 // virtual base class. 757 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 758 /*DetectVirtual=*/false); 759 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) { 760 for (BasePaths::paths_iterator Path = Paths.begin(); 761 Path != Paths.end(); ++Path) { 762 if (Path->back().Base->isVirtual()) { 763 VirtualBaseSpec = Path->back().Base; 764 break; 765 } 766 } 767 } 768 } 769 770 // C++ [base.class.init]p2: 771 // If a mem-initializer-id is ambiguous because it designates both 772 // a direct non-virtual base class and an inherited virtual base 773 // class, the mem-initializer is ill-formed. 774 if (DirectBaseSpec && VirtualBaseSpec) 775 return Diag(IdLoc, diag::err_base_init_direct_and_virtual) 776 << MemberOrBase << SourceRange(IdLoc, RParenLoc); 777 778 return new CXXBaseOrMemberInitializer(BaseType, (Expr **)Args, NumArgs); 779} 780 781 782void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 783 DeclTy *TagDecl, 784 SourceLocation LBrac, 785 SourceLocation RBrac) { 786 TemplateDecl *Template = AdjustDeclIfTemplate(TagDecl); 787 ActOnFields(S, RLoc, TagDecl, 788 (DeclTy**)FieldCollector->getCurFields(), 789 FieldCollector->getCurNumFields(), LBrac, RBrac, 0); 790 791 if (!Template) 792 AddImplicitlyDeclaredMembersToClass(cast<CXXRecordDecl>((Decl*)TagDecl)); 793} 794 795/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 796/// special functions, such as the default constructor, copy 797/// constructor, or destructor, to the given C++ class (C++ 798/// [special]p1). This routine can only be executed just before the 799/// definition of the class is complete. 800void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 801 QualType ClassType = Context.getTypeDeclType(ClassDecl); 802 ClassType = Context.getCanonicalType(ClassType); 803 804 if (!ClassDecl->hasUserDeclaredConstructor()) { 805 // C++ [class.ctor]p5: 806 // A default constructor for a class X is a constructor of class X 807 // that can be called without an argument. If there is no 808 // user-declared constructor for class X, a default constructor is 809 // implicitly declared. An implicitly-declared default constructor 810 // is an inline public member of its class. 811 DeclarationName Name 812 = Context.DeclarationNames.getCXXConstructorName(ClassType); 813 CXXConstructorDecl *DefaultCon = 814 CXXConstructorDecl::Create(Context, ClassDecl, 815 ClassDecl->getLocation(), Name, 816 Context.getFunctionType(Context.VoidTy, 817 0, 0, false, 0), 818 /*isExplicit=*/false, 819 /*isInline=*/true, 820 /*isImplicitlyDeclared=*/true); 821 DefaultCon->setAccess(AS_public); 822 DefaultCon->setImplicit(); 823 ClassDecl->addDecl(DefaultCon); 824 825 // Notify the class that we've added a constructor. 826 ClassDecl->addedConstructor(Context, DefaultCon); 827 } 828 829 if (!ClassDecl->hasUserDeclaredCopyConstructor()) { 830 // C++ [class.copy]p4: 831 // If the class definition does not explicitly declare a copy 832 // constructor, one is declared implicitly. 833 834 // C++ [class.copy]p5: 835 // The implicitly-declared copy constructor for a class X will 836 // have the form 837 // 838 // X::X(const X&) 839 // 840 // if 841 bool HasConstCopyConstructor = true; 842 843 // -- each direct or virtual base class B of X has a copy 844 // constructor whose first parameter is of type const B& or 845 // const volatile B&, and 846 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(); 847 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) { 848 const CXXRecordDecl *BaseClassDecl 849 = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl()); 850 HasConstCopyConstructor 851 = BaseClassDecl->hasConstCopyConstructor(Context); 852 } 853 854 // -- for all the nonstatic data members of X that are of a 855 // class type M (or array thereof), each such class type 856 // has a copy constructor whose first parameter is of type 857 // const M& or const volatile M&. 858 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(); 859 HasConstCopyConstructor && Field != ClassDecl->field_end(); ++Field) { 860 QualType FieldType = (*Field)->getType(); 861 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 862 FieldType = Array->getElementType(); 863 if (const RecordType *FieldClassType = FieldType->getAsRecordType()) { 864 const CXXRecordDecl *FieldClassDecl 865 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 866 HasConstCopyConstructor 867 = FieldClassDecl->hasConstCopyConstructor(Context); 868 } 869 } 870 871 // Otherwise, the implicitly declared copy constructor will have 872 // the form 873 // 874 // X::X(X&) 875 QualType ArgType = ClassType; 876 if (HasConstCopyConstructor) 877 ArgType = ArgType.withConst(); 878 ArgType = Context.getReferenceType(ArgType); 879 880 // An implicitly-declared copy constructor is an inline public 881 // member of its class. 882 DeclarationName Name 883 = Context.DeclarationNames.getCXXConstructorName(ClassType); 884 CXXConstructorDecl *CopyConstructor 885 = CXXConstructorDecl::Create(Context, ClassDecl, 886 ClassDecl->getLocation(), Name, 887 Context.getFunctionType(Context.VoidTy, 888 &ArgType, 1, 889 false, 0), 890 /*isExplicit=*/false, 891 /*isInline=*/true, 892 /*isImplicitlyDeclared=*/true); 893 CopyConstructor->setAccess(AS_public); 894 CopyConstructor->setImplicit(); 895 896 // Add the parameter to the constructor. 897 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 898 ClassDecl->getLocation(), 899 /*IdentifierInfo=*/0, 900 ArgType, VarDecl::None, 0); 901 CopyConstructor->setParams(Context, &FromParam, 1); 902 903 ClassDecl->addedConstructor(Context, CopyConstructor); 904 ClassDecl->addDecl(CopyConstructor); 905 } 906 907 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 908 // Note: The following rules are largely analoguous to the copy 909 // constructor rules. Note that virtual bases are not taken into account 910 // for determining the argument type of the operator. Note also that 911 // operators taking an object instead of a reference are allowed. 912 // 913 // C++ [class.copy]p10: 914 // If the class definition does not explicitly declare a copy 915 // assignment operator, one is declared implicitly. 916 // The implicitly-defined copy assignment operator for a class X 917 // will have the form 918 // 919 // X& X::operator=(const X&) 920 // 921 // if 922 bool HasConstCopyAssignment = true; 923 924 // -- each direct base class B of X has a copy assignment operator 925 // whose parameter is of type const B&, const volatile B& or B, 926 // and 927 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(); 928 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) { 929 const CXXRecordDecl *BaseClassDecl 930 = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl()); 931 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context); 932 } 933 934 // -- for all the nonstatic data members of X that are of a class 935 // type M (or array thereof), each such class type has a copy 936 // assignment operator whose parameter is of type const M&, 937 // const volatile M& or M. 938 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(); 939 HasConstCopyAssignment && Field != ClassDecl->field_end(); ++Field) { 940 QualType FieldType = (*Field)->getType(); 941 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 942 FieldType = Array->getElementType(); 943 if (const RecordType *FieldClassType = FieldType->getAsRecordType()) { 944 const CXXRecordDecl *FieldClassDecl 945 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 946 HasConstCopyAssignment 947 = FieldClassDecl->hasConstCopyAssignment(Context); 948 } 949 } 950 951 // Otherwise, the implicitly declared copy assignment operator will 952 // have the form 953 // 954 // X& X::operator=(X&) 955 QualType ArgType = ClassType; 956 QualType RetType = Context.getReferenceType(ArgType); 957 if (HasConstCopyAssignment) 958 ArgType = ArgType.withConst(); 959 ArgType = Context.getReferenceType(ArgType); 960 961 // An implicitly-declared copy assignment operator is an inline public 962 // member of its class. 963 DeclarationName Name = 964 Context.DeclarationNames.getCXXOperatorName(OO_Equal); 965 CXXMethodDecl *CopyAssignment = 966 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name, 967 Context.getFunctionType(RetType, &ArgType, 1, 968 false, 0), 969 /*isStatic=*/false, /*isInline=*/true); 970 CopyAssignment->setAccess(AS_public); 971 CopyAssignment->setImplicit(); 972 973 // Add the parameter to the operator. 974 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 975 ClassDecl->getLocation(), 976 /*IdentifierInfo=*/0, 977 ArgType, VarDecl::None, 0); 978 CopyAssignment->setParams(Context, &FromParam, 1); 979 980 // Don't call addedAssignmentOperator. There is no way to distinguish an 981 // implicit from an explicit assignment operator. 982 ClassDecl->addDecl(CopyAssignment); 983 } 984 985 if (!ClassDecl->hasUserDeclaredDestructor()) { 986 // C++ [class.dtor]p2: 987 // If a class has no user-declared destructor, a destructor is 988 // declared implicitly. An implicitly-declared destructor is an 989 // inline public member of its class. 990 DeclarationName Name 991 = Context.DeclarationNames.getCXXDestructorName(ClassType); 992 CXXDestructorDecl *Destructor 993 = CXXDestructorDecl::Create(Context, ClassDecl, 994 ClassDecl->getLocation(), Name, 995 Context.getFunctionType(Context.VoidTy, 996 0, 0, false, 0), 997 /*isInline=*/true, 998 /*isImplicitlyDeclared=*/true); 999 Destructor->setAccess(AS_public); 1000 Destructor->setImplicit(); 1001 ClassDecl->addDecl(Destructor); 1002 } 1003} 1004 1005/// ActOnStartDelayedCXXMethodDeclaration - We have completed 1006/// parsing a top-level (non-nested) C++ class, and we are now 1007/// parsing those parts of the given Method declaration that could 1008/// not be parsed earlier (C++ [class.mem]p2), such as default 1009/// arguments. This action should enter the scope of the given 1010/// Method declaration as if we had just parsed the qualified method 1011/// name. However, it should not bring the parameters into scope; 1012/// that will be performed by ActOnDelayedCXXMethodParameter. 1013void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclTy *Method) { 1014 CXXScopeSpec SS; 1015 SS.setScopeRep(((FunctionDecl*)Method)->getDeclContext()); 1016 ActOnCXXEnterDeclaratorScope(S, SS); 1017} 1018 1019/// ActOnDelayedCXXMethodParameter - We've already started a delayed 1020/// C++ method declaration. We're (re-)introducing the given 1021/// function parameter into scope for use in parsing later parts of 1022/// the method declaration. For example, we could see an 1023/// ActOnParamDefaultArgument event for this parameter. 1024void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclTy *ParamD) { 1025 ParmVarDecl *Param = (ParmVarDecl*)ParamD; 1026 1027 // If this parameter has an unparsed default argument, clear it out 1028 // to make way for the parsed default argument. 1029 if (Param->hasUnparsedDefaultArg()) 1030 Param->setDefaultArg(0); 1031 1032 S->AddDecl(Param); 1033 if (Param->getDeclName()) 1034 IdResolver.AddDecl(Param); 1035} 1036 1037/// ActOnFinishDelayedCXXMethodDeclaration - We have finished 1038/// processing the delayed method declaration for Method. The method 1039/// declaration is now considered finished. There may be a separate 1040/// ActOnStartOfFunctionDef action later (not necessarily 1041/// immediately!) for this method, if it was also defined inside the 1042/// class body. 1043void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclTy *MethodD) { 1044 FunctionDecl *Method = (FunctionDecl*)MethodD; 1045 CXXScopeSpec SS; 1046 SS.setScopeRep(Method->getDeclContext()); 1047 ActOnCXXExitDeclaratorScope(S, SS); 1048 1049 // Now that we have our default arguments, check the constructor 1050 // again. It could produce additional diagnostics or affect whether 1051 // the class has implicitly-declared destructors, among other 1052 // things. 1053 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) { 1054 if (CheckConstructor(Constructor)) 1055 Constructor->setInvalidDecl(); 1056 } 1057 1058 // Check the default arguments, which we may have added. 1059 if (!Method->isInvalidDecl()) 1060 CheckCXXDefaultArguments(Method); 1061} 1062 1063/// CheckConstructorDeclarator - Called by ActOnDeclarator to check 1064/// the well-formedness of the constructor declarator @p D with type @p 1065/// R. If there are any errors in the declarator, this routine will 1066/// emit diagnostics and return true. Otherwise, it will return 1067/// false. Either way, the type @p R will be updated to reflect a 1068/// well-formed type for the constructor. 1069bool Sema::CheckConstructorDeclarator(Declarator &D, QualType &R, 1070 FunctionDecl::StorageClass& SC) { 1071 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 1072 bool isInvalid = false; 1073 1074 // C++ [class.ctor]p3: 1075 // A constructor shall not be virtual (10.3) or static (9.4). A 1076 // constructor can be invoked for a const, volatile or const 1077 // volatile object. A constructor shall not be declared const, 1078 // volatile, or const volatile (9.3.2). 1079 if (isVirtual) { 1080 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 1081 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 1082 << SourceRange(D.getIdentifierLoc()); 1083 isInvalid = true; 1084 } 1085 if (SC == FunctionDecl::Static) { 1086 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 1087 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 1088 << SourceRange(D.getIdentifierLoc()); 1089 isInvalid = true; 1090 SC = FunctionDecl::None; 1091 } 1092 if (D.getDeclSpec().hasTypeSpecifier()) { 1093 // Constructors don't have return types, but the parser will 1094 // happily parse something like: 1095 // 1096 // class X { 1097 // float X(float); 1098 // }; 1099 // 1100 // The return type will be eliminated later. 1101 Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 1102 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 1103 << SourceRange(D.getIdentifierLoc()); 1104 } 1105 if (R->getAsFunctionProtoType()->getTypeQuals() != 0) { 1106 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 1107 if (FTI.TypeQuals & QualType::Const) 1108 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 1109 << "const" << SourceRange(D.getIdentifierLoc()); 1110 if (FTI.TypeQuals & QualType::Volatile) 1111 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 1112 << "volatile" << SourceRange(D.getIdentifierLoc()); 1113 if (FTI.TypeQuals & QualType::Restrict) 1114 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 1115 << "restrict" << SourceRange(D.getIdentifierLoc()); 1116 } 1117 1118 // Rebuild the function type "R" without any type qualifiers (in 1119 // case any of the errors above fired) and with "void" as the 1120 // return type, since constructors don't have return types. We 1121 // *always* have to do this, because GetTypeForDeclarator will 1122 // put in a result type of "int" when none was specified. 1123 const FunctionProtoType *Proto = R->getAsFunctionProtoType(); 1124 R = Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(), 1125 Proto->getNumArgs(), 1126 Proto->isVariadic(), 1127 0); 1128 1129 return isInvalid; 1130} 1131 1132/// CheckConstructor - Checks a fully-formed constructor for 1133/// well-formedness, issuing any diagnostics required. Returns true if 1134/// the constructor declarator is invalid. 1135bool Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 1136 if (Constructor->isInvalidDecl()) 1137 return true; 1138 1139 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext()); 1140 bool Invalid = false; 1141 1142 // C++ [class.copy]p3: 1143 // A declaration of a constructor for a class X is ill-formed if 1144 // its first parameter is of type (optionally cv-qualified) X and 1145 // either there are no other parameters or else all other 1146 // parameters have default arguments. 1147 if ((Constructor->getNumParams() == 1) || 1148 (Constructor->getNumParams() > 1 && 1149 Constructor->getParamDecl(1)->getDefaultArg() != 0)) { 1150 QualType ParamType = Constructor->getParamDecl(0)->getType(); 1151 QualType ClassTy = Context.getTagDeclType(ClassDecl); 1152 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 1153 Diag(Constructor->getLocation(), diag::err_constructor_byvalue_arg) 1154 << SourceRange(Constructor->getParamDecl(0)->getLocation()); 1155 Invalid = true; 1156 } 1157 } 1158 1159 // Notify the class that we've added a constructor. 1160 ClassDecl->addedConstructor(Context, Constructor); 1161 1162 return Invalid; 1163} 1164 1165/// CheckDestructorDeclarator - Called by ActOnDeclarator to check 1166/// the well-formednes of the destructor declarator @p D with type @p 1167/// R. If there are any errors in the declarator, this routine will 1168/// emit diagnostics and return true. Otherwise, it will return 1169/// false. Either way, the type @p R will be updated to reflect a 1170/// well-formed type for the destructor. 1171bool Sema::CheckDestructorDeclarator(Declarator &D, QualType &R, 1172 FunctionDecl::StorageClass& SC) { 1173 bool isInvalid = false; 1174 1175 // C++ [class.dtor]p1: 1176 // [...] A typedef-name that names a class is a class-name 1177 // (7.1.3); however, a typedef-name that names a class shall not 1178 // be used as the identifier in the declarator for a destructor 1179 // declaration. 1180 QualType DeclaratorType = QualType::getFromOpaquePtr(D.getDeclaratorIdType()); 1181 if (DeclaratorType->getAsTypedefType()) { 1182 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 1183 << DeclaratorType; 1184 isInvalid = true; 1185 } 1186 1187 // C++ [class.dtor]p2: 1188 // A destructor is used to destroy objects of its class type. A 1189 // destructor takes no parameters, and no return type can be 1190 // specified for it (not even void). The address of a destructor 1191 // shall not be taken. A destructor shall not be static. A 1192 // destructor can be invoked for a const, volatile or const 1193 // volatile object. A destructor shall not be declared const, 1194 // volatile or const volatile (9.3.2). 1195 if (SC == FunctionDecl::Static) { 1196 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 1197 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 1198 << SourceRange(D.getIdentifierLoc()); 1199 isInvalid = true; 1200 SC = FunctionDecl::None; 1201 } 1202 if (D.getDeclSpec().hasTypeSpecifier()) { 1203 // Destructors don't have return types, but the parser will 1204 // happily parse something like: 1205 // 1206 // class X { 1207 // float ~X(); 1208 // }; 1209 // 1210 // The return type will be eliminated later. 1211 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 1212 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 1213 << SourceRange(D.getIdentifierLoc()); 1214 } 1215 if (R->getAsFunctionProtoType()->getTypeQuals() != 0) { 1216 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 1217 if (FTI.TypeQuals & QualType::Const) 1218 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 1219 << "const" << SourceRange(D.getIdentifierLoc()); 1220 if (FTI.TypeQuals & QualType::Volatile) 1221 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 1222 << "volatile" << SourceRange(D.getIdentifierLoc()); 1223 if (FTI.TypeQuals & QualType::Restrict) 1224 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 1225 << "restrict" << SourceRange(D.getIdentifierLoc()); 1226 } 1227 1228 // Make sure we don't have any parameters. 1229 if (R->getAsFunctionProtoType()->getNumArgs() > 0) { 1230 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 1231 1232 // Delete the parameters. 1233 D.getTypeObject(0).Fun.freeArgs(); 1234 } 1235 1236 // Make sure the destructor isn't variadic. 1237 if (R->getAsFunctionProtoType()->isVariadic()) 1238 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 1239 1240 // Rebuild the function type "R" without any type qualifiers or 1241 // parameters (in case any of the errors above fired) and with 1242 // "void" as the return type, since destructors don't have return 1243 // types. We *always* have to do this, because GetTypeForDeclarator 1244 // will put in a result type of "int" when none was specified. 1245 R = Context.getFunctionType(Context.VoidTy, 0, 0, false, 0); 1246 1247 return isInvalid; 1248} 1249 1250/// CheckConversionDeclarator - Called by ActOnDeclarator to check the 1251/// well-formednes of the conversion function declarator @p D with 1252/// type @p R. If there are any errors in the declarator, this routine 1253/// will emit diagnostics and return true. Otherwise, it will return 1254/// false. Either way, the type @p R will be updated to reflect a 1255/// well-formed type for the conversion operator. 1256bool Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 1257 FunctionDecl::StorageClass& SC) { 1258 bool isInvalid = false; 1259 1260 // C++ [class.conv.fct]p1: 1261 // Neither parameter types nor return type can be specified. The 1262 // type of a conversion function (8.3.5) is “function taking no 1263 // parameter returning conversion-type-id.” 1264 if (SC == FunctionDecl::Static) { 1265 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 1266 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 1267 << SourceRange(D.getIdentifierLoc()); 1268 isInvalid = true; 1269 SC = FunctionDecl::None; 1270 } 1271 if (D.getDeclSpec().hasTypeSpecifier()) { 1272 // Conversion functions don't have return types, but the parser will 1273 // happily parse something like: 1274 // 1275 // class X { 1276 // float operator bool(); 1277 // }; 1278 // 1279 // The return type will be changed later anyway. 1280 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 1281 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 1282 << SourceRange(D.getIdentifierLoc()); 1283 } 1284 1285 // Make sure we don't have any parameters. 1286 if (R->getAsFunctionProtoType()->getNumArgs() > 0) { 1287 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 1288 1289 // Delete the parameters. 1290 D.getTypeObject(0).Fun.freeArgs(); 1291 } 1292 1293 // Make sure the conversion function isn't variadic. 1294 if (R->getAsFunctionProtoType()->isVariadic()) 1295 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 1296 1297 // C++ [class.conv.fct]p4: 1298 // The conversion-type-id shall not represent a function type nor 1299 // an array type. 1300 QualType ConvType = QualType::getFromOpaquePtr(D.getDeclaratorIdType()); 1301 if (ConvType->isArrayType()) { 1302 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 1303 ConvType = Context.getPointerType(ConvType); 1304 } else if (ConvType->isFunctionType()) { 1305 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 1306 ConvType = Context.getPointerType(ConvType); 1307 } 1308 1309 // Rebuild the function type "R" without any parameters (in case any 1310 // of the errors above fired) and with the conversion type as the 1311 // return type. 1312 R = Context.getFunctionType(ConvType, 0, 0, false, 1313 R->getAsFunctionProtoType()->getTypeQuals()); 1314 1315 // C++0x explicit conversion operators. 1316 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x) 1317 Diag(D.getDeclSpec().getExplicitSpecLoc(), 1318 diag::warn_explicit_conversion_functions) 1319 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 1320 1321 return isInvalid; 1322} 1323 1324/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 1325/// the declaration of the given C++ conversion function. This routine 1326/// is responsible for recording the conversion function in the C++ 1327/// class, if possible. 1328Sema::DeclTy *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 1329 assert(Conversion && "Expected to receive a conversion function declaration"); 1330 1331 // Set the lexical context of this conversion function 1332 Conversion->setLexicalDeclContext(CurContext); 1333 1334 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 1335 1336 // Make sure we aren't redeclaring the conversion function. 1337 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 1338 1339 // C++ [class.conv.fct]p1: 1340 // [...] A conversion function is never used to convert a 1341 // (possibly cv-qualified) object to the (possibly cv-qualified) 1342 // same object type (or a reference to it), to a (possibly 1343 // cv-qualified) base class of that type (or a reference to it), 1344 // or to (possibly cv-qualified) void. 1345 // FIXME: Suppress this warning if the conversion function ends up 1346 // being a virtual function that overrides a virtual function in a 1347 // base class. 1348 QualType ClassType 1349 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 1350 if (const ReferenceType *ConvTypeRef = ConvType->getAsReferenceType()) 1351 ConvType = ConvTypeRef->getPointeeType(); 1352 if (ConvType->isRecordType()) { 1353 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 1354 if (ConvType == ClassType) 1355 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 1356 << ClassType; 1357 else if (IsDerivedFrom(ClassType, ConvType)) 1358 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 1359 << ClassType << ConvType; 1360 } else if (ConvType->isVoidType()) { 1361 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 1362 << ClassType << ConvType; 1363 } 1364 1365 if (Conversion->getPreviousDeclaration()) { 1366 OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions(); 1367 for (OverloadedFunctionDecl::function_iterator 1368 Conv = Conversions->function_begin(), 1369 ConvEnd = Conversions->function_end(); 1370 Conv != ConvEnd; ++Conv) { 1371 if (*Conv == Conversion->getPreviousDeclaration()) { 1372 *Conv = Conversion; 1373 return (DeclTy *)Conversion; 1374 } 1375 } 1376 assert(Conversion->isInvalidDecl() && "Conversion should not get here."); 1377 } else 1378 ClassDecl->addConversionFunction(Context, Conversion); 1379 1380 return (DeclTy *)Conversion; 1381} 1382 1383//===----------------------------------------------------------------------===// 1384// Namespace Handling 1385//===----------------------------------------------------------------------===// 1386 1387/// ActOnStartNamespaceDef - This is called at the start of a namespace 1388/// definition. 1389Sema::DeclTy *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 1390 SourceLocation IdentLoc, 1391 IdentifierInfo *II, 1392 SourceLocation LBrace) { 1393 NamespaceDecl *Namespc = 1394 NamespaceDecl::Create(Context, CurContext, IdentLoc, II); 1395 Namespc->setLBracLoc(LBrace); 1396 1397 Scope *DeclRegionScope = NamespcScope->getParent(); 1398 1399 if (II) { 1400 // C++ [namespace.def]p2: 1401 // The identifier in an original-namespace-definition shall not have been 1402 // previously defined in the declarative region in which the 1403 // original-namespace-definition appears. The identifier in an 1404 // original-namespace-definition is the name of the namespace. Subsequently 1405 // in that declarative region, it is treated as an original-namespace-name. 1406 1407 NamedDecl *PrevDecl = LookupName(DeclRegionScope, II, LookupOrdinaryName, 1408 true); 1409 1410 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) { 1411 // This is an extended namespace definition. 1412 // Attach this namespace decl to the chain of extended namespace 1413 // definitions. 1414 OrigNS->setNextNamespace(Namespc); 1415 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace()); 1416 1417 // Remove the previous declaration from the scope. 1418 if (DeclRegionScope->isDeclScope(OrigNS)) { 1419 IdResolver.RemoveDecl(OrigNS); 1420 DeclRegionScope->RemoveDecl(OrigNS); 1421 } 1422 } else if (PrevDecl) { 1423 // This is an invalid name redefinition. 1424 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind) 1425 << Namespc->getDeclName(); 1426 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 1427 Namespc->setInvalidDecl(); 1428 // Continue on to push Namespc as current DeclContext and return it. 1429 } 1430 1431 PushOnScopeChains(Namespc, DeclRegionScope); 1432 } else { 1433 // FIXME: Handle anonymous namespaces 1434 } 1435 1436 // Although we could have an invalid decl (i.e. the namespace name is a 1437 // redefinition), push it as current DeclContext and try to continue parsing. 1438 // FIXME: We should be able to push Namespc here, so that the 1439 // each DeclContext for the namespace has the declarations 1440 // that showed up in that particular namespace definition. 1441 PushDeclContext(NamespcScope, Namespc); 1442 return Namespc; 1443} 1444 1445/// ActOnFinishNamespaceDef - This callback is called after a namespace is 1446/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 1447void Sema::ActOnFinishNamespaceDef(DeclTy *D, SourceLocation RBrace) { 1448 Decl *Dcl = static_cast<Decl *>(D); 1449 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 1450 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 1451 Namespc->setRBracLoc(RBrace); 1452 PopDeclContext(); 1453} 1454 1455Sema::DeclTy *Sema::ActOnUsingDirective(Scope *S, 1456 SourceLocation UsingLoc, 1457 SourceLocation NamespcLoc, 1458 const CXXScopeSpec &SS, 1459 SourceLocation IdentLoc, 1460 IdentifierInfo *NamespcName, 1461 AttributeList *AttrList) { 1462 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 1463 assert(NamespcName && "Invalid NamespcName."); 1464 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 1465 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 1466 1467 UsingDirectiveDecl *UDir = 0; 1468 1469 // Lookup namespace name. 1470 LookupResult R = LookupParsedName(S, &SS, NamespcName, 1471 LookupNamespaceName, false); 1472 if (R.isAmbiguous()) { 1473 DiagnoseAmbiguousLookup(R, NamespcName, IdentLoc); 1474 return 0; 1475 } 1476 if (NamedDecl *NS = R) { 1477 assert(isa<NamespaceDecl>(NS) && "expected namespace decl"); 1478 // C++ [namespace.udir]p1: 1479 // A using-directive specifies that the names in the nominated 1480 // namespace can be used in the scope in which the 1481 // using-directive appears after the using-directive. During 1482 // unqualified name lookup (3.4.1), the names appear as if they 1483 // were declared in the nearest enclosing namespace which 1484 // contains both the using-directive and the nominated 1485 // namespace. [Note: in this context, “contains” means “contains 1486 // directly or indirectly”. ] 1487 1488 // Find enclosing context containing both using-directive and 1489 // nominated namespace. 1490 DeclContext *CommonAncestor = cast<DeclContext>(NS); 1491 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 1492 CommonAncestor = CommonAncestor->getParent(); 1493 1494 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, 1495 NamespcLoc, IdentLoc, 1496 cast<NamespaceDecl>(NS), 1497 CommonAncestor); 1498 PushUsingDirective(S, UDir); 1499 } else { 1500 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 1501 } 1502 1503 // FIXME: We ignore attributes for now. 1504 delete AttrList; 1505 return UDir; 1506} 1507 1508void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 1509 // If scope has associated entity, then using directive is at namespace 1510 // or translation unit scope. We add UsingDirectiveDecls, into 1511 // it's lookup structure. 1512 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) 1513 Ctx->addDecl(UDir); 1514 else 1515 // Otherwise it is block-sope. using-directives will affect lookup 1516 // only to the end of scope. 1517 S->PushUsingDirective(UDir); 1518} 1519 1520/// AddCXXDirectInitializerToDecl - This action is called immediately after 1521/// ActOnDeclarator, when a C++ direct initializer is present. 1522/// e.g: "int x(1);" 1523void Sema::AddCXXDirectInitializerToDecl(DeclTy *Dcl, SourceLocation LParenLoc, 1524 ExprTy **ExprTys, unsigned NumExprs, 1525 SourceLocation *CommaLocs, 1526 SourceLocation RParenLoc) { 1527 assert(NumExprs != 0 && ExprTys && "missing expressions"); 1528 Decl *RealDecl = static_cast<Decl *>(Dcl); 1529 1530 // If there is no declaration, there was an error parsing it. Just ignore 1531 // the initializer. 1532 if (RealDecl == 0) { 1533 for (unsigned i = 0; i != NumExprs; ++i) 1534 static_cast<Expr *>(ExprTys[i])->Destroy(Context); 1535 return; 1536 } 1537 1538 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 1539 if (!VDecl) { 1540 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 1541 RealDecl->setInvalidDecl(); 1542 return; 1543 } 1544 1545 // We will treat direct-initialization as a copy-initialization: 1546 // int x(1); -as-> int x = 1; 1547 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 1548 // 1549 // Clients that want to distinguish between the two forms, can check for 1550 // direct initializer using VarDecl::hasCXXDirectInitializer(). 1551 // A major benefit is that clients that don't particularly care about which 1552 // exactly form was it (like the CodeGen) can handle both cases without 1553 // special case code. 1554 1555 // C++ 8.5p11: 1556 // The form of initialization (using parentheses or '=') is generally 1557 // insignificant, but does matter when the entity being initialized has a 1558 // class type. 1559 QualType DeclInitType = VDecl->getType(); 1560 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType)) 1561 DeclInitType = Array->getElementType(); 1562 1563 if (VDecl->getType()->isRecordType()) { 1564 CXXConstructorDecl *Constructor 1565 = PerformInitializationByConstructor(DeclInitType, 1566 (Expr **)ExprTys, NumExprs, 1567 VDecl->getLocation(), 1568 SourceRange(VDecl->getLocation(), 1569 RParenLoc), 1570 VDecl->getDeclName(), 1571 IK_Direct); 1572 if (!Constructor) { 1573 RealDecl->setInvalidDecl(); 1574 } 1575 1576 // Let clients know that initialization was done with a direct 1577 // initializer. 1578 VDecl->setCXXDirectInitializer(true); 1579 1580 // FIXME: Add ExprTys and Constructor to the RealDecl as part of 1581 // the initializer. 1582 return; 1583 } 1584 1585 if (NumExprs > 1) { 1586 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg) 1587 << SourceRange(VDecl->getLocation(), RParenLoc); 1588 RealDecl->setInvalidDecl(); 1589 return; 1590 } 1591 1592 // Let clients know that initialization was done with a direct initializer. 1593 VDecl->setCXXDirectInitializer(true); 1594 1595 assert(NumExprs == 1 && "Expected 1 expression"); 1596 // Set the init expression, handles conversions. 1597 AddInitializerToDecl(Dcl, ExprArg(*this, ExprTys[0]), /*DirectInit=*/true); 1598} 1599 1600/// PerformInitializationByConstructor - Perform initialization by 1601/// constructor (C++ [dcl.init]p14), which may occur as part of 1602/// direct-initialization or copy-initialization. We are initializing 1603/// an object of type @p ClassType with the given arguments @p 1604/// Args. @p Loc is the location in the source code where the 1605/// initializer occurs (e.g., a declaration, member initializer, 1606/// functional cast, etc.) while @p Range covers the whole 1607/// initialization. @p InitEntity is the entity being initialized, 1608/// which may by the name of a declaration or a type. @p Kind is the 1609/// kind of initialization we're performing, which affects whether 1610/// explicit constructors will be considered. When successful, returns 1611/// the constructor that will be used to perform the initialization; 1612/// when the initialization fails, emits a diagnostic and returns 1613/// null. 1614CXXConstructorDecl * 1615Sema::PerformInitializationByConstructor(QualType ClassType, 1616 Expr **Args, unsigned NumArgs, 1617 SourceLocation Loc, SourceRange Range, 1618 DeclarationName InitEntity, 1619 InitializationKind Kind) { 1620 const RecordType *ClassRec = ClassType->getAsRecordType(); 1621 assert(ClassRec && "Can only initialize a class type here"); 1622 1623 // C++ [dcl.init]p14: 1624 // 1625 // If the initialization is direct-initialization, or if it is 1626 // copy-initialization where the cv-unqualified version of the 1627 // source type is the same class as, or a derived class of, the 1628 // class of the destination, constructors are considered. The 1629 // applicable constructors are enumerated (13.3.1.3), and the 1630 // best one is chosen through overload resolution (13.3). The 1631 // constructor so selected is called to initialize the object, 1632 // with the initializer expression(s) as its argument(s). If no 1633 // constructor applies, or the overload resolution is ambiguous, 1634 // the initialization is ill-formed. 1635 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl()); 1636 OverloadCandidateSet CandidateSet; 1637 1638 // Add constructors to the overload set. 1639 DeclarationName ConstructorName 1640 = Context.DeclarationNames.getCXXConstructorName( 1641 Context.getCanonicalType(ClassType.getUnqualifiedType())); 1642 DeclContext::lookup_const_iterator Con, ConEnd; 1643 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName); 1644 Con != ConEnd; ++Con) { 1645 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con); 1646 if ((Kind == IK_Direct) || 1647 (Kind == IK_Copy && Constructor->isConvertingConstructor()) || 1648 (Kind == IK_Default && Constructor->isDefaultConstructor())) 1649 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet); 1650 } 1651 1652 // FIXME: When we decide not to synthesize the implicitly-declared 1653 // constructors, we'll need to make them appear here. 1654 1655 OverloadCandidateSet::iterator Best; 1656 switch (BestViableFunction(CandidateSet, Best)) { 1657 case OR_Success: 1658 // We found a constructor. Return it. 1659 return cast<CXXConstructorDecl>(Best->Function); 1660 1661 case OR_No_Viable_Function: 1662 if (InitEntity) 1663 Diag(Loc, diag::err_ovl_no_viable_function_in_init) 1664 << InitEntity << Range; 1665 else 1666 Diag(Loc, diag::err_ovl_no_viable_function_in_init) 1667 << ClassType << Range; 1668 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false); 1669 return 0; 1670 1671 case OR_Ambiguous: 1672 if (InitEntity) 1673 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range; 1674 else 1675 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range; 1676 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 1677 return 0; 1678 1679 case OR_Deleted: 1680 if (InitEntity) 1681 Diag(Loc, diag::err_ovl_deleted_init) 1682 << Best->Function->isDeleted() 1683 << InitEntity << Range; 1684 else 1685 Diag(Loc, diag::err_ovl_deleted_init) 1686 << Best->Function->isDeleted() 1687 << InitEntity << Range; 1688 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 1689 return 0; 1690 } 1691 1692 return 0; 1693} 1694 1695/// CompareReferenceRelationship - Compare the two types T1 and T2 to 1696/// determine whether they are reference-related, 1697/// reference-compatible, reference-compatible with added 1698/// qualification, or incompatible, for use in C++ initialization by 1699/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 1700/// type, and the first type (T1) is the pointee type of the reference 1701/// type being initialized. 1702Sema::ReferenceCompareResult 1703Sema::CompareReferenceRelationship(QualType T1, QualType T2, 1704 bool& DerivedToBase) { 1705 assert(!T1->isReferenceType() && "T1 must be the pointee type of the reference type"); 1706 assert(!T2->isReferenceType() && "T2 cannot be a reference type"); 1707 1708 T1 = Context.getCanonicalType(T1); 1709 T2 = Context.getCanonicalType(T2); 1710 QualType UnqualT1 = T1.getUnqualifiedType(); 1711 QualType UnqualT2 = T2.getUnqualifiedType(); 1712 1713 // C++ [dcl.init.ref]p4: 1714 // Given types “cv1 T1” and “cv2 T2,” “cv1 T1” is 1715 // reference-related to “cv2 T2” if T1 is the same type as T2, or 1716 // T1 is a base class of T2. 1717 if (UnqualT1 == UnqualT2) 1718 DerivedToBase = false; 1719 else if (IsDerivedFrom(UnqualT2, UnqualT1)) 1720 DerivedToBase = true; 1721 else 1722 return Ref_Incompatible; 1723 1724 // At this point, we know that T1 and T2 are reference-related (at 1725 // least). 1726 1727 // C++ [dcl.init.ref]p4: 1728 // "cv1 T1” is reference-compatible with “cv2 T2” if T1 is 1729 // reference-related to T2 and cv1 is the same cv-qualification 1730 // as, or greater cv-qualification than, cv2. For purposes of 1731 // overload resolution, cases for which cv1 is greater 1732 // cv-qualification than cv2 are identified as 1733 // reference-compatible with added qualification (see 13.3.3.2). 1734 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 1735 return Ref_Compatible; 1736 else if (T1.isMoreQualifiedThan(T2)) 1737 return Ref_Compatible_With_Added_Qualification; 1738 else 1739 return Ref_Related; 1740} 1741 1742/// CheckReferenceInit - Check the initialization of a reference 1743/// variable with the given initializer (C++ [dcl.init.ref]). Init is 1744/// the initializer (either a simple initializer or an initializer 1745/// list), and DeclType is the type of the declaration. When ICS is 1746/// non-null, this routine will compute the implicit conversion 1747/// sequence according to C++ [over.ics.ref] and will not produce any 1748/// diagnostics; when ICS is null, it will emit diagnostics when any 1749/// errors are found. Either way, a return value of true indicates 1750/// that there was a failure, a return value of false indicates that 1751/// the reference initialization succeeded. 1752/// 1753/// When @p SuppressUserConversions, user-defined conversions are 1754/// suppressed. 1755/// When @p AllowExplicit, we also permit explicit user-defined 1756/// conversion functions. 1757bool 1758Sema::CheckReferenceInit(Expr *&Init, QualType &DeclType, 1759 ImplicitConversionSequence *ICS, 1760 bool SuppressUserConversions, 1761 bool AllowExplicit) { 1762 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 1763 1764 QualType T1 = DeclType->getAsReferenceType()->getPointeeType(); 1765 QualType T2 = Init->getType(); 1766 1767 // If the initializer is the address of an overloaded function, try 1768 // to resolve the overloaded function. If all goes well, T2 is the 1769 // type of the resulting function. 1770 if (T2->isOverloadType()) { 1771 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType, 1772 ICS != 0); 1773 if (Fn) { 1774 // Since we're performing this reference-initialization for 1775 // real, update the initializer with the resulting function. 1776 if (!ICS) { 1777 if (DiagnoseUseOfDecl(Fn, Init->getSourceRange().getBegin())) 1778 return true; 1779 1780 FixOverloadedFunctionReference(Init, Fn); 1781 } 1782 1783 T2 = Fn->getType(); 1784 } 1785 } 1786 1787 // Compute some basic properties of the types and the initializer. 1788 bool DerivedToBase = false; 1789 Expr::isLvalueResult InitLvalue = Init->isLvalue(Context); 1790 ReferenceCompareResult RefRelationship 1791 = CompareReferenceRelationship(T1, T2, DerivedToBase); 1792 1793 // Most paths end in a failed conversion. 1794 if (ICS) 1795 ICS->ConversionKind = ImplicitConversionSequence::BadConversion; 1796 1797 // C++ [dcl.init.ref]p5: 1798 // A reference to type “cv1 T1” is initialized by an expression 1799 // of type “cv2 T2” as follows: 1800 1801 // -- If the initializer expression 1802 1803 bool BindsDirectly = false; 1804 // -- is an lvalue (but is not a bit-field), and “cv1 T1” is 1805 // reference-compatible with “cv2 T2,” or 1806 // 1807 // Note that the bit-field check is skipped if we are just computing 1808 // the implicit conversion sequence (C++ [over.best.ics]p2). 1809 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->isBitField()) && 1810 RefRelationship >= Ref_Compatible_With_Added_Qualification) { 1811 BindsDirectly = true; 1812 1813 if (ICS) { 1814 // C++ [over.ics.ref]p1: 1815 // When a parameter of reference type binds directly (8.5.3) 1816 // to an argument expression, the implicit conversion sequence 1817 // is the identity conversion, unless the argument expression 1818 // has a type that is a derived class of the parameter type, 1819 // in which case the implicit conversion sequence is a 1820 // derived-to-base Conversion (13.3.3.1). 1821 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion; 1822 ICS->Standard.First = ICK_Identity; 1823 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity; 1824 ICS->Standard.Third = ICK_Identity; 1825 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr(); 1826 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr(); 1827 ICS->Standard.ReferenceBinding = true; 1828 ICS->Standard.DirectBinding = true; 1829 1830 // Nothing more to do: the inaccessibility/ambiguity check for 1831 // derived-to-base conversions is suppressed when we're 1832 // computing the implicit conversion sequence (C++ 1833 // [over.best.ics]p2). 1834 return false; 1835 } else { 1836 // Perform the conversion. 1837 // FIXME: Binding to a subobject of the lvalue is going to require 1838 // more AST annotation than this. 1839 ImpCastExprToType(Init, T1, /*isLvalue=*/true); 1840 } 1841 } 1842 1843 // -- has a class type (i.e., T2 is a class type) and can be 1844 // implicitly converted to an lvalue of type “cv3 T3,” 1845 // where “cv1 T1” is reference-compatible with “cv3 T3” 1846 // 92) (this conversion is selected by enumerating the 1847 // applicable conversion functions (13.3.1.6) and choosing 1848 // the best one through overload resolution (13.3)), 1849 if (!SuppressUserConversions && T2->isRecordType()) { 1850 // FIXME: Look for conversions in base classes! 1851 CXXRecordDecl *T2RecordDecl 1852 = dyn_cast<CXXRecordDecl>(T2->getAsRecordType()->getDecl()); 1853 1854 OverloadCandidateSet CandidateSet; 1855 OverloadedFunctionDecl *Conversions 1856 = T2RecordDecl->getConversionFunctions(); 1857 for (OverloadedFunctionDecl::function_iterator Func 1858 = Conversions->function_begin(); 1859 Func != Conversions->function_end(); ++Func) { 1860 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func); 1861 1862 // If the conversion function doesn't return a reference type, 1863 // it can't be considered for this conversion. 1864 // FIXME: This will change when we support rvalue references. 1865 if (Conv->getConversionType()->isReferenceType() && 1866 (AllowExplicit || !Conv->isExplicit())) 1867 AddConversionCandidate(Conv, Init, DeclType, CandidateSet); 1868 } 1869 1870 OverloadCandidateSet::iterator Best; 1871 switch (BestViableFunction(CandidateSet, Best)) { 1872 case OR_Success: 1873 // This is a direct binding. 1874 BindsDirectly = true; 1875 1876 if (ICS) { 1877 // C++ [over.ics.ref]p1: 1878 // 1879 // [...] If the parameter binds directly to the result of 1880 // applying a conversion function to the argument 1881 // expression, the implicit conversion sequence is a 1882 // user-defined conversion sequence (13.3.3.1.2), with the 1883 // second standard conversion sequence either an identity 1884 // conversion or, if the conversion function returns an 1885 // entity of a type that is a derived class of the parameter 1886 // type, a derived-to-base Conversion. 1887 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion; 1888 ICS->UserDefined.Before = Best->Conversions[0].Standard; 1889 ICS->UserDefined.After = Best->FinalConversion; 1890 ICS->UserDefined.ConversionFunction = Best->Function; 1891 assert(ICS->UserDefined.After.ReferenceBinding && 1892 ICS->UserDefined.After.DirectBinding && 1893 "Expected a direct reference binding!"); 1894 return false; 1895 } else { 1896 // Perform the conversion. 1897 // FIXME: Binding to a subobject of the lvalue is going to require 1898 // more AST annotation than this. 1899 ImpCastExprToType(Init, T1, /*isLvalue=*/true); 1900 } 1901 break; 1902 1903 case OR_Ambiguous: 1904 assert(false && "Ambiguous reference binding conversions not implemented."); 1905 return true; 1906 1907 case OR_No_Viable_Function: 1908 case OR_Deleted: 1909 // There was no suitable conversion, or we found a deleted 1910 // conversion; continue with other checks. 1911 break; 1912 } 1913 } 1914 1915 if (BindsDirectly) { 1916 // C++ [dcl.init.ref]p4: 1917 // [...] In all cases where the reference-related or 1918 // reference-compatible relationship of two types is used to 1919 // establish the validity of a reference binding, and T1 is a 1920 // base class of T2, a program that necessitates such a binding 1921 // is ill-formed if T1 is an inaccessible (clause 11) or 1922 // ambiguous (10.2) base class of T2. 1923 // 1924 // Note that we only check this condition when we're allowed to 1925 // complain about errors, because we should not be checking for 1926 // ambiguity (or inaccessibility) unless the reference binding 1927 // actually happens. 1928 if (DerivedToBase) 1929 return CheckDerivedToBaseConversion(T2, T1, 1930 Init->getSourceRange().getBegin(), 1931 Init->getSourceRange()); 1932 else 1933 return false; 1934 } 1935 1936 // -- Otherwise, the reference shall be to a non-volatile const 1937 // type (i.e., cv1 shall be const). 1938 if (T1.getCVRQualifiers() != QualType::Const) { 1939 if (!ICS) 1940 Diag(Init->getSourceRange().getBegin(), 1941 diag::err_not_reference_to_const_init) 1942 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value") 1943 << T2 << Init->getSourceRange(); 1944 return true; 1945 } 1946 1947 // -- If the initializer expression is an rvalue, with T2 a 1948 // class type, and “cv1 T1” is reference-compatible with 1949 // “cv2 T2,” the reference is bound in one of the 1950 // following ways (the choice is implementation-defined): 1951 // 1952 // -- The reference is bound to the object represented by 1953 // the rvalue (see 3.10) or to a sub-object within that 1954 // object. 1955 // 1956 // -- A temporary of type “cv1 T2” [sic] is created, and 1957 // a constructor is called to copy the entire rvalue 1958 // object into the temporary. The reference is bound to 1959 // the temporary or to a sub-object within the 1960 // temporary. 1961 // 1962 // The constructor that would be used to make the copy 1963 // shall be callable whether or not the copy is actually 1964 // done. 1965 // 1966 // Note that C++0x [dcl.ref.init]p5 takes away this implementation 1967 // freedom, so we will always take the first option and never build 1968 // a temporary in this case. FIXME: We will, however, have to check 1969 // for the presence of a copy constructor in C++98/03 mode. 1970 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() && 1971 RefRelationship >= Ref_Compatible_With_Added_Qualification) { 1972 if (ICS) { 1973 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion; 1974 ICS->Standard.First = ICK_Identity; 1975 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity; 1976 ICS->Standard.Third = ICK_Identity; 1977 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr(); 1978 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr(); 1979 ICS->Standard.ReferenceBinding = true; 1980 ICS->Standard.DirectBinding = false; 1981 } else { 1982 // FIXME: Binding to a subobject of the rvalue is going to require 1983 // more AST annotation than this. 1984 ImpCastExprToType(Init, T1, /*isLvalue=*/true); 1985 } 1986 return false; 1987 } 1988 1989 // -- Otherwise, a temporary of type “cv1 T1” is created and 1990 // initialized from the initializer expression using the 1991 // rules for a non-reference copy initialization (8.5). The 1992 // reference is then bound to the temporary. If T1 is 1993 // reference-related to T2, cv1 must be the same 1994 // cv-qualification as, or greater cv-qualification than, 1995 // cv2; otherwise, the program is ill-formed. 1996 if (RefRelationship == Ref_Related) { 1997 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 1998 // we would be reference-compatible or reference-compatible with 1999 // added qualification. But that wasn't the case, so the reference 2000 // initialization fails. 2001 if (!ICS) 2002 Diag(Init->getSourceRange().getBegin(), 2003 diag::err_reference_init_drops_quals) 2004 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value") 2005 << T2 << Init->getSourceRange(); 2006 return true; 2007 } 2008 2009 // If at least one of the types is a class type, the types are not 2010 // related, and we aren't allowed any user conversions, the 2011 // reference binding fails. This case is important for breaking 2012 // recursion, since TryImplicitConversion below will attempt to 2013 // create a temporary through the use of a copy constructor. 2014 if (SuppressUserConversions && RefRelationship == Ref_Incompatible && 2015 (T1->isRecordType() || T2->isRecordType())) { 2016 if (!ICS) 2017 Diag(Init->getSourceRange().getBegin(), 2018 diag::err_typecheck_convert_incompatible) 2019 << DeclType << Init->getType() << "initializing" << Init->getSourceRange(); 2020 return true; 2021 } 2022 2023 // Actually try to convert the initializer to T1. 2024 if (ICS) { 2025 /// C++ [over.ics.ref]p2: 2026 /// 2027 /// When a parameter of reference type is not bound directly to 2028 /// an argument expression, the conversion sequence is the one 2029 /// required to convert the argument expression to the 2030 /// underlying type of the reference according to 2031 /// 13.3.3.1. Conceptually, this conversion sequence corresponds 2032 /// to copy-initializing a temporary of the underlying type with 2033 /// the argument expression. Any difference in top-level 2034 /// cv-qualification is subsumed by the initialization itself 2035 /// and does not constitute a conversion. 2036 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions); 2037 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion; 2038 } else { 2039 return PerformImplicitConversion(Init, T1, "initializing"); 2040 } 2041} 2042 2043/// CheckOverloadedOperatorDeclaration - Check whether the declaration 2044/// of this overloaded operator is well-formed. If so, returns false; 2045/// otherwise, emits appropriate diagnostics and returns true. 2046bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 2047 assert(FnDecl && FnDecl->isOverloadedOperator() && 2048 "Expected an overloaded operator declaration"); 2049 2050 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 2051 2052 // C++ [over.oper]p5: 2053 // The allocation and deallocation functions, operator new, 2054 // operator new[], operator delete and operator delete[], are 2055 // described completely in 3.7.3. The attributes and restrictions 2056 // found in the rest of this subclause do not apply to them unless 2057 // explicitly stated in 3.7.3. 2058 // FIXME: Write a separate routine for checking this. For now, just 2059 // allow it. 2060 if (Op == OO_New || Op == OO_Array_New || 2061 Op == OO_Delete || Op == OO_Array_Delete) 2062 return false; 2063 2064 // C++ [over.oper]p6: 2065 // An operator function shall either be a non-static member 2066 // function or be a non-member function and have at least one 2067 // parameter whose type is a class, a reference to a class, an 2068 // enumeration, or a reference to an enumeration. 2069 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 2070 if (MethodDecl->isStatic()) 2071 return Diag(FnDecl->getLocation(), 2072 diag::err_operator_overload_static) << FnDecl->getDeclName(); 2073 } else { 2074 bool ClassOrEnumParam = false; 2075 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 2076 ParamEnd = FnDecl->param_end(); 2077 Param != ParamEnd; ++Param) { 2078 QualType ParamType = (*Param)->getType().getNonReferenceType(); 2079 if (ParamType->isRecordType() || ParamType->isEnumeralType()) { 2080 ClassOrEnumParam = true; 2081 break; 2082 } 2083 } 2084 2085 if (!ClassOrEnumParam) 2086 return Diag(FnDecl->getLocation(), 2087 diag::err_operator_overload_needs_class_or_enum) 2088 << FnDecl->getDeclName(); 2089 } 2090 2091 // C++ [over.oper]p8: 2092 // An operator function cannot have default arguments (8.3.6), 2093 // except where explicitly stated below. 2094 // 2095 // Only the function-call operator allows default arguments 2096 // (C++ [over.call]p1). 2097 if (Op != OO_Call) { 2098 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(); 2099 Param != FnDecl->param_end(); ++Param) { 2100 if ((*Param)->hasUnparsedDefaultArg()) 2101 return Diag((*Param)->getLocation(), 2102 diag::err_operator_overload_default_arg) 2103 << FnDecl->getDeclName(); 2104 else if (Expr *DefArg = (*Param)->getDefaultArg()) 2105 return Diag((*Param)->getLocation(), 2106 diag::err_operator_overload_default_arg) 2107 << FnDecl->getDeclName() << DefArg->getSourceRange(); 2108 } 2109 } 2110 2111 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 2112 { false, false, false } 2113#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 2114 , { Unary, Binary, MemberOnly } 2115#include "clang/Basic/OperatorKinds.def" 2116 }; 2117 2118 bool CanBeUnaryOperator = OperatorUses[Op][0]; 2119 bool CanBeBinaryOperator = OperatorUses[Op][1]; 2120 bool MustBeMemberOperator = OperatorUses[Op][2]; 2121 2122 // C++ [over.oper]p8: 2123 // [...] Operator functions cannot have more or fewer parameters 2124 // than the number required for the corresponding operator, as 2125 // described in the rest of this subclause. 2126 unsigned NumParams = FnDecl->getNumParams() 2127 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 2128 if (Op != OO_Call && 2129 ((NumParams == 1 && !CanBeUnaryOperator) || 2130 (NumParams == 2 && !CanBeBinaryOperator) || 2131 (NumParams < 1) || (NumParams > 2))) { 2132 // We have the wrong number of parameters. 2133 unsigned ErrorKind; 2134 if (CanBeUnaryOperator && CanBeBinaryOperator) { 2135 ErrorKind = 2; // 2 -> unary or binary. 2136 } else if (CanBeUnaryOperator) { 2137 ErrorKind = 0; // 0 -> unary 2138 } else { 2139 assert(CanBeBinaryOperator && 2140 "All non-call overloaded operators are unary or binary!"); 2141 ErrorKind = 1; // 1 -> binary 2142 } 2143 2144 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 2145 << FnDecl->getDeclName() << NumParams << ErrorKind; 2146 } 2147 2148 // Overloaded operators other than operator() cannot be variadic. 2149 if (Op != OO_Call && 2150 FnDecl->getType()->getAsFunctionProtoType()->isVariadic()) { 2151 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 2152 << FnDecl->getDeclName(); 2153 } 2154 2155 // Some operators must be non-static member functions. 2156 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 2157 return Diag(FnDecl->getLocation(), 2158 diag::err_operator_overload_must_be_member) 2159 << FnDecl->getDeclName(); 2160 } 2161 2162 // C++ [over.inc]p1: 2163 // The user-defined function called operator++ implements the 2164 // prefix and postfix ++ operator. If this function is a member 2165 // function with no parameters, or a non-member function with one 2166 // parameter of class or enumeration type, it defines the prefix 2167 // increment operator ++ for objects of that type. If the function 2168 // is a member function with one parameter (which shall be of type 2169 // int) or a non-member function with two parameters (the second 2170 // of which shall be of type int), it defines the postfix 2171 // increment operator ++ for objects of that type. 2172 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 2173 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 2174 bool ParamIsInt = false; 2175 if (const BuiltinType *BT = LastParam->getType()->getAsBuiltinType()) 2176 ParamIsInt = BT->getKind() == BuiltinType::Int; 2177 2178 if (!ParamIsInt) 2179 return Diag(LastParam->getLocation(), 2180 diag::err_operator_overload_post_incdec_must_be_int) 2181 << LastParam->getType() << (Op == OO_MinusMinus); 2182 } 2183 2184 // Notify the class if it got an assignment operator. 2185 if (Op == OO_Equal) { 2186 // Would have returned earlier otherwise. 2187 assert(isa<CXXMethodDecl>(FnDecl) && 2188 "Overloaded = not member, but not filtered."); 2189 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 2190 Method->getParent()->addedAssignmentOperator(Context, Method); 2191 } 2192 2193 return false; 2194} 2195 2196/// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 2197/// linkage specification, including the language and (if present) 2198/// the '{'. ExternLoc is the location of the 'extern', LangLoc is 2199/// the location of the language string literal, which is provided 2200/// by Lang/StrSize. LBraceLoc, if valid, provides the location of 2201/// the '{' brace. Otherwise, this linkage specification does not 2202/// have any braces. 2203Sema::DeclTy *Sema::ActOnStartLinkageSpecification(Scope *S, 2204 SourceLocation ExternLoc, 2205 SourceLocation LangLoc, 2206 const char *Lang, 2207 unsigned StrSize, 2208 SourceLocation LBraceLoc) { 2209 LinkageSpecDecl::LanguageIDs Language; 2210 if (strncmp(Lang, "\"C\"", StrSize) == 0) 2211 Language = LinkageSpecDecl::lang_c; 2212 else if (strncmp(Lang, "\"C++\"", StrSize) == 0) 2213 Language = LinkageSpecDecl::lang_cxx; 2214 else { 2215 Diag(LangLoc, diag::err_bad_language); 2216 return 0; 2217 } 2218 2219 // FIXME: Add all the various semantics of linkage specifications 2220 2221 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, 2222 LangLoc, Language, 2223 LBraceLoc.isValid()); 2224 CurContext->addDecl(D); 2225 PushDeclContext(S, D); 2226 return D; 2227} 2228 2229/// ActOnFinishLinkageSpecification - Completely the definition of 2230/// the C++ linkage specification LinkageSpec. If RBraceLoc is 2231/// valid, it's the position of the closing '}' brace in a linkage 2232/// specification that uses braces. 2233Sema::DeclTy *Sema::ActOnFinishLinkageSpecification(Scope *S, 2234 DeclTy *LinkageSpec, 2235 SourceLocation RBraceLoc) { 2236 if (LinkageSpec) 2237 PopDeclContext(); 2238 return LinkageSpec; 2239} 2240 2241/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 2242/// handler. 2243Sema::DeclTy *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) 2244{ 2245 QualType ExDeclType = GetTypeForDeclarator(D, S); 2246 SourceLocation Begin = D.getDeclSpec().getSourceRange().getBegin(); 2247 2248 bool Invalid = false; 2249 2250 // Arrays and functions decay. 2251 if (ExDeclType->isArrayType()) 2252 ExDeclType = Context.getArrayDecayedType(ExDeclType); 2253 else if (ExDeclType->isFunctionType()) 2254 ExDeclType = Context.getPointerType(ExDeclType); 2255 2256 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 2257 // The exception-declaration shall not denote a pointer or reference to an 2258 // incomplete type, other than [cv] void*. 2259 QualType BaseType = ExDeclType; 2260 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 2261 unsigned DK = diag::err_catch_incomplete; 2262 if (const PointerType *Ptr = BaseType->getAsPointerType()) { 2263 BaseType = Ptr->getPointeeType(); 2264 Mode = 1; 2265 DK = diag::err_catch_incomplete_ptr; 2266 } else if(const ReferenceType *Ref = BaseType->getAsReferenceType()) { 2267 BaseType = Ref->getPointeeType(); 2268 Mode = 2; 2269 DK = diag::err_catch_incomplete_ref; 2270 } 2271 if ((Mode == 0 || !BaseType->isVoidType()) && 2272 RequireCompleteType(Begin, BaseType, DK)) 2273 Invalid = true; 2274 2275 // FIXME: Need to test for ability to copy-construct and destroy the 2276 // exception variable. 2277 // FIXME: Need to check for abstract classes. 2278 2279 IdentifierInfo *II = D.getIdentifier(); 2280 if (NamedDecl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) { 2281 // The scope should be freshly made just for us. There is just no way 2282 // it contains any previous declaration. 2283 assert(!S->isDeclScope(PrevDecl)); 2284 if (PrevDecl->isTemplateParameter()) { 2285 // Maybe we will complain about the shadowed template parameter. 2286 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 2287 2288 } 2289 } 2290 2291 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(), 2292 II, ExDeclType, VarDecl::None, Begin); 2293 if (D.getInvalidType() || Invalid) 2294 ExDecl->setInvalidDecl(); 2295 2296 if (D.getCXXScopeSpec().isSet()) { 2297 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 2298 << D.getCXXScopeSpec().getRange(); 2299 ExDecl->setInvalidDecl(); 2300 } 2301 2302 // Add the exception declaration into this scope. 2303 S->AddDecl(ExDecl); 2304 if (II) 2305 IdResolver.AddDecl(ExDecl); 2306 2307 ProcessDeclAttributes(ExDecl, D); 2308 return ExDecl; 2309} 2310