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