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