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