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