SemaDeclCXX.cpp revision 206125
1193326Sed//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===// 2193326Sed// 3193326Sed// The LLVM Compiler Infrastructure 4193326Sed// 5193326Sed// This file is distributed under the University of Illinois Open Source 6193326Sed// License. See LICENSE.TXT for details. 7193326Sed// 8193326Sed//===----------------------------------------------------------------------===// 9193326Sed// 10193326Sed// This file implements semantic analysis for C++ declarations. 11193326Sed// 12193326Sed//===----------------------------------------------------------------------===// 13193326Sed 14193326Sed#include "Sema.h" 15200583Srdivacky#include "SemaInit.h" 16199482Srdivacky#include "Lookup.h" 17193326Sed#include "clang/AST/ASTConsumer.h" 18193326Sed#include "clang/AST/ASTContext.h" 19200583Srdivacky#include "clang/AST/RecordLayout.h" 20198092Srdivacky#include "clang/AST/CXXInheritance.h" 21193326Sed#include "clang/AST/DeclVisitor.h" 22200583Srdivacky#include "clang/AST/TypeLoc.h" 23193326Sed#include "clang/AST/TypeOrdering.h" 24193326Sed#include "clang/AST/StmtVisitor.h" 25199482Srdivacky#include "clang/Parse/DeclSpec.h" 26199482Srdivacky#include "clang/Parse/Template.h" 27198092Srdivacky#include "clang/Basic/PartialDiagnostic.h" 28193326Sed#include "clang/Lex/Preprocessor.h" 29193326Sed#include "llvm/ADT/STLExtras.h" 30193326Sed#include <map> 31198092Srdivacky#include <set> 32193326Sed 33193326Sedusing namespace clang; 34193326Sed 35193326Sed//===----------------------------------------------------------------------===// 36193326Sed// CheckDefaultArgumentVisitor 37193326Sed//===----------------------------------------------------------------------===// 38193326Sed 39193326Sednamespace { 40193326Sed /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 41193326Sed /// the default argument of a parameter to determine whether it 42193326Sed /// contains any ill-formed subexpressions. For example, this will 43193326Sed /// diagnose the use of local variables or parameters within the 44193326Sed /// default argument expression. 45199990Srdivacky class CheckDefaultArgumentVisitor 46193326Sed : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 47193326Sed Expr *DefaultArg; 48193326Sed Sema *S; 49193326Sed 50193326Sed public: 51198092Srdivacky CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 52193326Sed : DefaultArg(defarg), S(s) {} 53193326Sed 54193326Sed bool VisitExpr(Expr *Node); 55193326Sed bool VisitDeclRefExpr(DeclRefExpr *DRE); 56193326Sed bool VisitCXXThisExpr(CXXThisExpr *ThisE); 57193326Sed }; 58193326Sed 59193326Sed /// VisitExpr - Visit all of the children of this expression. 60193326Sed bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 61193326Sed bool IsInvalid = false; 62198092Srdivacky for (Stmt::child_iterator I = Node->child_begin(), 63193326Sed E = Node->child_end(); I != E; ++I) 64193326Sed IsInvalid |= Visit(*I); 65193326Sed return IsInvalid; 66193326Sed } 67193326Sed 68193326Sed /// VisitDeclRefExpr - Visit a reference to a declaration, to 69193326Sed /// determine whether this declaration can be used in the default 70193326Sed /// argument expression. 71193326Sed bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 72193326Sed NamedDecl *Decl = DRE->getDecl(); 73193326Sed if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 74193326Sed // C++ [dcl.fct.default]p9 75193326Sed // Default arguments are evaluated each time the function is 76193326Sed // called. The order of evaluation of function arguments is 77193326Sed // unspecified. Consequently, parameters of a function shall not 78193326Sed // be used in default argument expressions, even if they are not 79193326Sed // evaluated. Parameters of a function declared before a default 80193326Sed // argument expression are in scope and can hide namespace and 81193326Sed // class member names. 82198092Srdivacky return S->Diag(DRE->getSourceRange().getBegin(), 83193326Sed diag::err_param_default_argument_references_param) 84193326Sed << Param->getDeclName() << DefaultArg->getSourceRange(); 85193326Sed } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 86193326Sed // C++ [dcl.fct.default]p7 87193326Sed // Local variables shall not be used in default argument 88193326Sed // expressions. 89193326Sed if (VDecl->isBlockVarDecl()) 90198092Srdivacky return S->Diag(DRE->getSourceRange().getBegin(), 91193326Sed diag::err_param_default_argument_references_local) 92193326Sed << VDecl->getDeclName() << DefaultArg->getSourceRange(); 93193326Sed } 94193326Sed 95193326Sed return false; 96193326Sed } 97193326Sed 98193326Sed /// VisitCXXThisExpr - Visit a C++ "this" expression. 99193326Sed bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 100193326Sed // C++ [dcl.fct.default]p8: 101193326Sed // The keyword this shall not be used in a default argument of a 102193326Sed // member function. 103193326Sed return S->Diag(ThisE->getSourceRange().getBegin(), 104193326Sed diag::err_param_default_argument_references_this) 105193326Sed << ThisE->getSourceRange(); 106193326Sed } 107193326Sed} 108193326Sed 109198092Srdivackybool 110198092SrdivackySema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg, 111198092Srdivacky SourceLocation EqualLoc) { 112198092Srdivacky if (RequireCompleteType(Param->getLocation(), Param->getType(), 113198092Srdivacky diag::err_typecheck_decl_incomplete_type)) { 114198092Srdivacky Param->setInvalidDecl(); 115198092Srdivacky return true; 116198092Srdivacky } 117198092Srdivacky 118198092Srdivacky Expr *Arg = (Expr *)DefaultArg.get(); 119198092Srdivacky 120198092Srdivacky // C++ [dcl.fct.default]p5 121198092Srdivacky // A default argument expression is implicitly converted (clause 122198092Srdivacky // 4) to the parameter type. The default argument expression has 123198092Srdivacky // the same semantic constraints as the initializer expression in 124198092Srdivacky // a declaration of a variable of the parameter type, using the 125198092Srdivacky // copy-initialization semantics (8.5). 126201361Srdivacky InitializedEntity Entity = InitializedEntity::InitializeParameter(Param); 127201361Srdivacky InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 128201361Srdivacky EqualLoc); 129201361Srdivacky InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1); 130201361Srdivacky OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, 131201361Srdivacky MultiExprArg(*this, (void**)&Arg, 1)); 132201361Srdivacky if (Result.isInvalid()) 133198092Srdivacky return true; 134201361Srdivacky Arg = Result.takeAs<Expr>(); 135198092Srdivacky 136201361Srdivacky Arg = MaybeCreateCXXExprWithTemporaries(Arg); 137198092Srdivacky 138198092Srdivacky // Okay: add the default argument to the parameter 139198092Srdivacky Param->setDefaultArg(Arg); 140198092Srdivacky 141198092Srdivacky DefaultArg.release(); 142198092Srdivacky 143198092Srdivacky return false; 144198092Srdivacky} 145198092Srdivacky 146193326Sed/// ActOnParamDefaultArgument - Check whether the default argument 147193326Sed/// provided for a function parameter is well-formed. If so, attach it 148193326Sed/// to the parameter declaration. 149193326Sedvoid 150198092SrdivackySema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc, 151193326Sed ExprArg defarg) { 152194711Sed if (!param || !defarg.get()) 153194711Sed return; 154198092Srdivacky 155193326Sed ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>()); 156194179Sed UnparsedDefaultArgLocs.erase(Param); 157194179Sed 158193326Sed ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>()); 159193326Sed 160193326Sed // Default arguments are only permitted in C++ 161193326Sed if (!getLangOptions().CPlusPlus) { 162193326Sed Diag(EqualLoc, diag::err_param_default_argument) 163193326Sed << DefaultArg->getSourceRange(); 164193326Sed Param->setInvalidDecl(); 165193326Sed return; 166193326Sed } 167193326Sed 168193326Sed // Check that the default argument is well-formed 169193326Sed CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this); 170193326Sed if (DefaultArgChecker.Visit(DefaultArg.get())) { 171193326Sed Param->setInvalidDecl(); 172193326Sed return; 173193326Sed } 174193326Sed 175198092Srdivacky SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc); 176193326Sed} 177193326Sed 178193326Sed/// ActOnParamUnparsedDefaultArgument - We've seen a default 179193326Sed/// argument for a function parameter, but we can't parse it yet 180193326Sed/// because we're inside a class definition. Note that this default 181193326Sed/// argument will be parsed later. 182198092Srdivackyvoid Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param, 183194179Sed SourceLocation EqualLoc, 184194179Sed SourceLocation ArgLoc) { 185194711Sed if (!param) 186194711Sed return; 187198092Srdivacky 188193326Sed ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>()); 189193326Sed if (Param) 190193326Sed Param->setUnparsedDefaultArg(); 191198092Srdivacky 192194179Sed UnparsedDefaultArgLocs[Param] = ArgLoc; 193193326Sed} 194193326Sed 195193326Sed/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 196193326Sed/// the default argument for the parameter param failed. 197193326Sedvoid Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) { 198194711Sed if (!param) 199194711Sed return; 200198092Srdivacky 201194179Sed ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>()); 202198092Srdivacky 203194179Sed Param->setInvalidDecl(); 204198092Srdivacky 205194179Sed UnparsedDefaultArgLocs.erase(Param); 206193326Sed} 207193326Sed 208193326Sed/// CheckExtraCXXDefaultArguments - Check for any extra default 209193326Sed/// arguments in the declarator, which is not a function declaration 210193326Sed/// or definition and therefore is not permitted to have default 211193326Sed/// arguments. This routine should be invoked for every declarator 212193326Sed/// that is not a function declaration or definition. 213193326Sedvoid Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 214193326Sed // C++ [dcl.fct.default]p3 215193326Sed // A default argument expression shall be specified only in the 216193326Sed // parameter-declaration-clause of a function declaration or in a 217193326Sed // template-parameter (14.1). It shall not be specified for a 218193326Sed // parameter pack. If it is specified in a 219193326Sed // parameter-declaration-clause, it shall not occur within a 220193326Sed // declarator or abstract-declarator of a parameter-declaration. 221193326Sed for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 222193326Sed DeclaratorChunk &chunk = D.getTypeObject(i); 223193326Sed if (chunk.Kind == DeclaratorChunk::Function) { 224193326Sed for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) { 225193326Sed ParmVarDecl *Param = 226193326Sed cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>()); 227193326Sed if (Param->hasUnparsedDefaultArg()) { 228193326Sed CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens; 229193326Sed Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 230193326Sed << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation()); 231193326Sed delete Toks; 232193326Sed chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0; 233193326Sed } else if (Param->getDefaultArg()) { 234193326Sed Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 235193326Sed << Param->getDefaultArg()->getSourceRange(); 236193326Sed Param->setDefaultArg(0); 237193326Sed } 238193326Sed } 239193326Sed } 240193326Sed } 241193326Sed} 242193326Sed 243193326Sed// MergeCXXFunctionDecl - Merge two declarations of the same C++ 244193326Sed// function, once we already know that they have the same 245193326Sed// type. Subroutine of MergeFunctionDecl. Returns true if there was an 246193326Sed// error, false otherwise. 247193326Sedbool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) { 248193326Sed bool Invalid = false; 249193326Sed 250193326Sed // C++ [dcl.fct.default]p4: 251193326Sed // For non-template functions, default arguments can be added in 252193326Sed // later declarations of a function in the same 253193326Sed // scope. Declarations in different scopes have completely 254193326Sed // distinct sets of default arguments. That is, declarations in 255193326Sed // inner scopes do not acquire default arguments from 256193326Sed // declarations in outer scopes, and vice versa. In a given 257193326Sed // function declaration, all parameters subsequent to a 258193326Sed // parameter with a default argument shall have default 259193326Sed // arguments supplied in this or previous declarations. A 260193326Sed // default argument shall not be redefined by a later 261193326Sed // declaration (not even to the same value). 262198092Srdivacky // 263198092Srdivacky // C++ [dcl.fct.default]p6: 264198092Srdivacky // Except for member functions of class templates, the default arguments 265198092Srdivacky // in a member function definition that appears outside of the class 266198092Srdivacky // definition are added to the set of default arguments provided by the 267198092Srdivacky // member function declaration in the class definition. 268193326Sed for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 269193326Sed ParmVarDecl *OldParam = Old->getParamDecl(p); 270193326Sed ParmVarDecl *NewParam = New->getParamDecl(p); 271193326Sed 272198092Srdivacky if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) { 273202379Srdivacky // FIXME: If we knew where the '=' was, we could easily provide a fix-it 274202379Srdivacky // hint here. Alternatively, we could walk the type-source information 275202379Srdivacky // for NewParam to find the last source location in the type... but it 276202379Srdivacky // isn't worth the effort right now. This is the kind of test case that 277202379Srdivacky // is hard to get right: 278202379Srdivacky 279202379Srdivacky // int f(int); 280202379Srdivacky // void g(int (*fp)(int) = f); 281202379Srdivacky // void g(int (*fp)(int) = &f); 282198092Srdivacky Diag(NewParam->getLocation(), 283193326Sed diag::err_param_default_argument_redefinition) 284202379Srdivacky << NewParam->getDefaultArgRange(); 285198092Srdivacky 286198092Srdivacky // Look for the function declaration where the default argument was 287198092Srdivacky // actually written, which may be a declaration prior to Old. 288198092Srdivacky for (FunctionDecl *Older = Old->getPreviousDeclaration(); 289198092Srdivacky Older; Older = Older->getPreviousDeclaration()) { 290198092Srdivacky if (!Older->getParamDecl(p)->hasDefaultArg()) 291198092Srdivacky break; 292198092Srdivacky 293198092Srdivacky OldParam = Older->getParamDecl(p); 294198092Srdivacky } 295198092Srdivacky 296198092Srdivacky Diag(OldParam->getLocation(), diag::note_previous_definition) 297198092Srdivacky << OldParam->getDefaultArgRange(); 298193326Sed Invalid = true; 299198092Srdivacky } else if (OldParam->hasDefaultArg()) { 300193326Sed // Merge the old default argument into the new parameter 301205219Srdivacky NewParam->setHasInheritedDefaultArg(); 302198092Srdivacky if (OldParam->hasUninstantiatedDefaultArg()) 303198092Srdivacky NewParam->setUninstantiatedDefaultArg( 304198092Srdivacky OldParam->getUninstantiatedDefaultArg()); 305198092Srdivacky else 306198092Srdivacky NewParam->setDefaultArg(OldParam->getDefaultArg()); 307198092Srdivacky } else if (NewParam->hasDefaultArg()) { 308198092Srdivacky if (New->getDescribedFunctionTemplate()) { 309198092Srdivacky // Paragraph 4, quoted above, only applies to non-template functions. 310198092Srdivacky Diag(NewParam->getLocation(), 311198092Srdivacky diag::err_param_default_argument_template_redecl) 312198092Srdivacky << NewParam->getDefaultArgRange(); 313198092Srdivacky Diag(Old->getLocation(), diag::note_template_prev_declaration) 314198092Srdivacky << false; 315198092Srdivacky } else if (New->getTemplateSpecializationKind() 316198092Srdivacky != TSK_ImplicitInstantiation && 317198092Srdivacky New->getTemplateSpecializationKind() != TSK_Undeclared) { 318198092Srdivacky // C++ [temp.expr.spec]p21: 319198092Srdivacky // Default function arguments shall not be specified in a declaration 320198092Srdivacky // or a definition for one of the following explicit specializations: 321198092Srdivacky // - the explicit specialization of a function template; 322198092Srdivacky // - the explicit specialization of a member function template; 323198092Srdivacky // - the explicit specialization of a member function of a class 324198092Srdivacky // template where the class template specialization to which the 325198092Srdivacky // member function specialization belongs is implicitly 326198092Srdivacky // instantiated. 327198092Srdivacky Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 328198092Srdivacky << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 329198092Srdivacky << New->getDeclName() 330198092Srdivacky << NewParam->getDefaultArgRange(); 331198092Srdivacky } else if (New->getDeclContext()->isDependentContext()) { 332198092Srdivacky // C++ [dcl.fct.default]p6 (DR217): 333198092Srdivacky // Default arguments for a member function of a class template shall 334198092Srdivacky // be specified on the initial declaration of the member function 335198092Srdivacky // within the class template. 336198092Srdivacky // 337198092Srdivacky // Reading the tea leaves a bit in DR217 and its reference to DR205 338198092Srdivacky // leads me to the conclusion that one cannot add default function 339198092Srdivacky // arguments for an out-of-line definition of a member function of a 340198092Srdivacky // dependent type. 341198092Srdivacky int WhichKind = 2; 342198092Srdivacky if (CXXRecordDecl *Record 343198092Srdivacky = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 344198092Srdivacky if (Record->getDescribedClassTemplate()) 345198092Srdivacky WhichKind = 0; 346198092Srdivacky else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 347198092Srdivacky WhichKind = 1; 348198092Srdivacky else 349198092Srdivacky WhichKind = 2; 350198092Srdivacky } 351198092Srdivacky 352198092Srdivacky Diag(NewParam->getLocation(), 353198092Srdivacky diag::err_param_default_argument_member_template_redecl) 354198092Srdivacky << WhichKind 355198092Srdivacky << NewParam->getDefaultArgRange(); 356198092Srdivacky } 357193326Sed } 358193326Sed } 359193326Sed 360203955Srdivacky if (CheckEquivalentExceptionSpec(Old, New)) 361195341Sed Invalid = true; 362195341Sed 363193326Sed return Invalid; 364193326Sed} 365193326Sed 366193326Sed/// CheckCXXDefaultArguments - Verify that the default arguments for a 367193326Sed/// function declaration are well-formed according to C++ 368193326Sed/// [dcl.fct.default]. 369193326Sedvoid Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 370193326Sed unsigned NumParams = FD->getNumParams(); 371193326Sed unsigned p; 372193326Sed 373193326Sed // Find first parameter with a default argument 374193326Sed for (p = 0; p < NumParams; ++p) { 375193326Sed ParmVarDecl *Param = FD->getParamDecl(p); 376198092Srdivacky if (Param->hasDefaultArg()) 377193326Sed break; 378193326Sed } 379193326Sed 380193326Sed // C++ [dcl.fct.default]p4: 381193326Sed // In a given function declaration, all parameters 382193326Sed // subsequent to a parameter with a default argument shall 383193326Sed // have default arguments supplied in this or previous 384193326Sed // declarations. A default argument shall not be redefined 385193326Sed // by a later declaration (not even to the same value). 386193326Sed unsigned LastMissingDefaultArg = 0; 387198092Srdivacky for (; p < NumParams; ++p) { 388193326Sed ParmVarDecl *Param = FD->getParamDecl(p); 389198092Srdivacky if (!Param->hasDefaultArg()) { 390193326Sed if (Param->isInvalidDecl()) 391193326Sed /* We already complained about this parameter. */; 392193326Sed else if (Param->getIdentifier()) 393198092Srdivacky Diag(Param->getLocation(), 394193326Sed diag::err_param_default_argument_missing_name) 395193326Sed << Param->getIdentifier(); 396193326Sed else 397198092Srdivacky Diag(Param->getLocation(), 398193326Sed diag::err_param_default_argument_missing); 399198092Srdivacky 400193326Sed LastMissingDefaultArg = p; 401193326Sed } 402193326Sed } 403193326Sed 404193326Sed if (LastMissingDefaultArg > 0) { 405193326Sed // Some default arguments were missing. Clear out all of the 406193326Sed // default arguments up to (and including) the last missing 407193326Sed // default argument, so that we leave the function parameters 408193326Sed // in a semantically valid state. 409193326Sed for (p = 0; p <= LastMissingDefaultArg; ++p) { 410193326Sed ParmVarDecl *Param = FD->getParamDecl(p); 411194179Sed if (Param->hasDefaultArg()) { 412193326Sed if (!Param->hasUnparsedDefaultArg()) 413193326Sed Param->getDefaultArg()->Destroy(Context); 414193326Sed Param->setDefaultArg(0); 415193326Sed } 416193326Sed } 417193326Sed } 418193326Sed} 419193326Sed 420193326Sed/// isCurrentClassName - Determine whether the identifier II is the 421193326Sed/// name of the class type currently being defined. In the case of 422193326Sed/// nested classes, this will only return true if II is the name of 423193326Sed/// the innermost class. 424193326Sedbool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 425193326Sed const CXXScopeSpec *SS) { 426202379Srdivacky assert(getLangOptions().CPlusPlus && "No class names in C!"); 427202379Srdivacky 428193326Sed CXXRecordDecl *CurDecl; 429193326Sed if (SS && SS->isSet() && !SS->isInvalid()) { 430198092Srdivacky DeclContext *DC = computeDeclContext(*SS, true); 431193326Sed CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 432193326Sed } else 433193326Sed CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 434193326Sed 435203955Srdivacky if (CurDecl && CurDecl->getIdentifier()) 436193326Sed return &II == CurDecl->getIdentifier(); 437193326Sed else 438193326Sed return false; 439193326Sed} 440193326Sed 441198092Srdivacky/// \brief Check the validity of a C++ base class specifier. 442193326Sed/// 443193326Sed/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 444193326Sed/// and returns NULL otherwise. 445193326SedCXXBaseSpecifier * 446193326SedSema::CheckBaseSpecifier(CXXRecordDecl *Class, 447193326Sed SourceRange SpecifierRange, 448193326Sed bool Virtual, AccessSpecifier Access, 449198092Srdivacky QualType BaseType, 450193326Sed SourceLocation BaseLoc) { 451193326Sed // C++ [class.union]p1: 452193326Sed // A union shall not have base classes. 453193326Sed if (Class->isUnion()) { 454193326Sed Diag(Class->getLocation(), diag::err_base_clause_on_union) 455193326Sed << SpecifierRange; 456193326Sed return 0; 457193326Sed } 458193326Sed 459193326Sed if (BaseType->isDependentType()) 460198092Srdivacky return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 461193326Sed Class->getTagKind() == RecordDecl::TK_class, 462193326Sed Access, BaseType); 463193326Sed 464193326Sed // Base specifiers must be record types. 465193326Sed if (!BaseType->isRecordType()) { 466193326Sed Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 467193326Sed return 0; 468193326Sed } 469193326Sed 470193326Sed // C++ [class.union]p1: 471193326Sed // A union shall not be used as a base class. 472193326Sed if (BaseType->isUnionType()) { 473193326Sed Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 474193326Sed return 0; 475193326Sed } 476193326Sed 477193326Sed // C++ [class.derived]p2: 478193326Sed // The class-name in a base-specifier shall not be an incompletely 479193326Sed // defined class. 480198092Srdivacky if (RequireCompleteType(BaseLoc, BaseType, 481198092Srdivacky PDiag(diag::err_incomplete_base_class) 482198092Srdivacky << SpecifierRange)) 483193326Sed return 0; 484193326Sed 485198092Srdivacky // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 486198092Srdivacky RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 487193326Sed assert(BaseDecl && "Record type has no declaration"); 488203955Srdivacky BaseDecl = BaseDecl->getDefinition(); 489193326Sed assert(BaseDecl && "Base type is not incomplete, but has no definition"); 490198092Srdivacky CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 491198092Srdivacky assert(CXXBaseDecl && "Base type is not a C++ type"); 492200583Srdivacky 493199990Srdivacky // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases. 494199990Srdivacky if (CXXBaseDecl->hasAttr<FinalAttr>()) { 495199990Srdivacky Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString(); 496200583Srdivacky Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl) 497200583Srdivacky << BaseType; 498199990Srdivacky return 0; 499199990Srdivacky } 500193326Sed 501200583Srdivacky SetClassDeclAttributesFromBase(Class, CXXBaseDecl, Virtual); 502200583Srdivacky 503200583Srdivacky // Create the base specifier. 504200583Srdivacky // FIXME: Allocate via ASTContext? 505200583Srdivacky return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 506200583Srdivacky Class->getTagKind() == RecordDecl::TK_class, 507200583Srdivacky Access, BaseType); 508200583Srdivacky} 509200583Srdivacky 510200583Srdivackyvoid Sema::SetClassDeclAttributesFromBase(CXXRecordDecl *Class, 511200583Srdivacky const CXXRecordDecl *BaseClass, 512200583Srdivacky bool BaseIsVirtual) { 513200583Srdivacky // A class with a non-empty base class is not empty. 514200583Srdivacky // FIXME: Standard ref? 515200583Srdivacky if (!BaseClass->isEmpty()) 516200583Srdivacky Class->setEmpty(false); 517200583Srdivacky 518200583Srdivacky // C++ [class.virtual]p1: 519200583Srdivacky // A class that [...] inherits a virtual function is called a polymorphic 520200583Srdivacky // class. 521200583Srdivacky if (BaseClass->isPolymorphic()) 522200583Srdivacky Class->setPolymorphic(true); 523200583Srdivacky 524193326Sed // C++ [dcl.init.aggr]p1: 525193326Sed // An aggregate is [...] a class with [...] no base classes [...]. 526193326Sed Class->setAggregate(false); 527200583Srdivacky 528200583Srdivacky // C++ [class]p4: 529200583Srdivacky // A POD-struct is an aggregate class... 530193326Sed Class->setPOD(false); 531193326Sed 532200583Srdivacky if (BaseIsVirtual) { 533193326Sed // C++ [class.ctor]p5: 534193326Sed // A constructor is trivial if its class has no virtual base classes. 535193326Sed Class->setHasTrivialConstructor(false); 536198092Srdivacky 537198092Srdivacky // C++ [class.copy]p6: 538198092Srdivacky // A copy constructor is trivial if its class has no virtual base classes. 539198092Srdivacky Class->setHasTrivialCopyConstructor(false); 540198092Srdivacky 541198092Srdivacky // C++ [class.copy]p11: 542198092Srdivacky // A copy assignment operator is trivial if its class has no virtual 543198092Srdivacky // base classes. 544198092Srdivacky Class->setHasTrivialCopyAssignment(false); 545198092Srdivacky 546198092Srdivacky // C++0x [meta.unary.prop] is_empty: 547198092Srdivacky // T is a class type, but not a union type, with ... no virtual base 548198092Srdivacky // classes 549198092Srdivacky Class->setEmpty(false); 550193326Sed } else { 551193326Sed // C++ [class.ctor]p5: 552198092Srdivacky // A constructor is trivial if all the direct base classes of its 553193326Sed // class have trivial constructors. 554200583Srdivacky if (!BaseClass->hasTrivialConstructor()) 555198092Srdivacky Class->setHasTrivialConstructor(false); 556198092Srdivacky 557198092Srdivacky // C++ [class.copy]p6: 558198092Srdivacky // A copy constructor is trivial if all the direct base classes of its 559198092Srdivacky // class have trivial copy constructors. 560200583Srdivacky if (!BaseClass->hasTrivialCopyConstructor()) 561198092Srdivacky Class->setHasTrivialCopyConstructor(false); 562198092Srdivacky 563198092Srdivacky // C++ [class.copy]p11: 564198092Srdivacky // A copy assignment operator is trivial if all the direct base classes 565198092Srdivacky // of its class have trivial copy assignment operators. 566200583Srdivacky if (!BaseClass->hasTrivialCopyAssignment()) 567198092Srdivacky Class->setHasTrivialCopyAssignment(false); 568193326Sed } 569193326Sed 570193326Sed // C++ [class.ctor]p3: 571193326Sed // A destructor is trivial if all the direct base classes of its class 572193326Sed // have trivial destructors. 573200583Srdivacky if (!BaseClass->hasTrivialDestructor()) 574198092Srdivacky Class->setHasTrivialDestructor(false); 575193326Sed} 576193326Sed 577193326Sed/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 578193326Sed/// one entry in the base class list of a class specifier, for 579198092Srdivacky/// example: 580198092Srdivacky/// class foo : public bar, virtual private baz { 581193326Sed/// 'public bar' and 'virtual private baz' are each base-specifiers. 582198092SrdivackySema::BaseResult 583193326SedSema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange, 584193326Sed bool Virtual, AccessSpecifier Access, 585193326Sed TypeTy *basetype, SourceLocation BaseLoc) { 586194711Sed if (!classdecl) 587194711Sed return true; 588194711Sed 589193326Sed AdjustDeclIfTemplate(classdecl); 590204643Srdivacky CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl.getAs<Decl>()); 591204643Srdivacky if (!Class) 592204643Srdivacky return true; 593204643Srdivacky 594198092Srdivacky QualType BaseType = GetTypeFromParser(basetype); 595193326Sed if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 596193326Sed Virtual, Access, 597193326Sed BaseType, BaseLoc)) 598193326Sed return BaseSpec; 599198092Srdivacky 600193326Sed return true; 601193326Sed} 602193326Sed 603193326Sed/// \brief Performs the actual work of attaching the given base class 604193326Sed/// specifiers to a C++ class. 605193326Sedbool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 606193326Sed unsigned NumBases) { 607193326Sed if (NumBases == 0) 608193326Sed return false; 609193326Sed 610193326Sed // Used to keep track of which base types we have already seen, so 611193326Sed // that we can properly diagnose redundant direct base types. Note 612193326Sed // that the key is always the unqualified canonical type of the base 613193326Sed // class. 614193326Sed std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 615193326Sed 616193326Sed // Copy non-redundant base specifiers into permanent storage. 617193326Sed unsigned NumGoodBases = 0; 618193326Sed bool Invalid = false; 619193326Sed for (unsigned idx = 0; idx < NumBases; ++idx) { 620198092Srdivacky QualType NewBaseType 621193326Sed = Context.getCanonicalType(Bases[idx]->getType()); 622199482Srdivacky NewBaseType = NewBaseType.getLocalUnqualifiedType(); 623193326Sed 624193326Sed if (KnownBaseTypes[NewBaseType]) { 625193326Sed // C++ [class.mi]p3: 626193326Sed // A class shall not be specified as a direct base class of a 627193326Sed // derived class more than once. 628193326Sed Diag(Bases[idx]->getSourceRange().getBegin(), 629193326Sed diag::err_duplicate_base_class) 630193326Sed << KnownBaseTypes[NewBaseType]->getType() 631193326Sed << Bases[idx]->getSourceRange(); 632193326Sed 633193326Sed // Delete the duplicate base class specifier; we're going to 634193326Sed // overwrite its pointer later. 635198092Srdivacky Context.Deallocate(Bases[idx]); 636193326Sed 637193326Sed Invalid = true; 638193326Sed } else { 639193326Sed // Okay, add this new base class. 640193326Sed KnownBaseTypes[NewBaseType] = Bases[idx]; 641193326Sed Bases[NumGoodBases++] = Bases[idx]; 642193326Sed } 643193326Sed } 644193326Sed 645193326Sed // Attach the remaining base class specifiers to the derived class. 646203955Srdivacky Class->setBases(Bases, NumGoodBases); 647193326Sed 648193326Sed // Delete the remaining (good) base class specifiers, since their 649193326Sed // data has been copied into the CXXRecordDecl. 650193326Sed for (unsigned idx = 0; idx < NumGoodBases; ++idx) 651198092Srdivacky Context.Deallocate(Bases[idx]); 652193326Sed 653193326Sed return Invalid; 654193326Sed} 655193326Sed 656193326Sed/// ActOnBaseSpecifiers - Attach the given base specifiers to the 657193326Sed/// class, after checking whether there are any duplicate base 658193326Sed/// classes. 659198092Srdivackyvoid Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases, 660193326Sed unsigned NumBases) { 661193326Sed if (!ClassDecl || !Bases || !NumBases) 662193326Sed return; 663193326Sed 664193326Sed AdjustDeclIfTemplate(ClassDecl); 665193326Sed AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()), 666193326Sed (CXXBaseSpecifier**)(Bases), NumBases); 667193326Sed} 668193326Sed 669204962Srdivackystatic CXXRecordDecl *GetClassForType(QualType T) { 670204962Srdivacky if (const RecordType *RT = T->getAs<RecordType>()) 671204962Srdivacky return cast<CXXRecordDecl>(RT->getDecl()); 672204962Srdivacky else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>()) 673204962Srdivacky return ICT->getDecl(); 674204962Srdivacky else 675204962Srdivacky return 0; 676204962Srdivacky} 677204962Srdivacky 678198092Srdivacky/// \brief Determine whether the type \p Derived is a C++ class that is 679198092Srdivacky/// derived from the type \p Base. 680198092Srdivackybool Sema::IsDerivedFrom(QualType Derived, QualType Base) { 681198092Srdivacky if (!getLangOptions().CPlusPlus) 682198092Srdivacky return false; 683204962Srdivacky 684204962Srdivacky CXXRecordDecl *DerivedRD = GetClassForType(Derived); 685204962Srdivacky if (!DerivedRD) 686198092Srdivacky return false; 687198092Srdivacky 688204962Srdivacky CXXRecordDecl *BaseRD = GetClassForType(Base); 689204962Srdivacky if (!BaseRD) 690198092Srdivacky return false; 691198092Srdivacky 692203955Srdivacky // FIXME: instantiate DerivedRD if necessary. We need a PoI for this. 693203955Srdivacky return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD); 694198092Srdivacky} 695198092Srdivacky 696198092Srdivacky/// \brief Determine whether the type \p Derived is a C++ class that is 697198092Srdivacky/// derived from the type \p Base. 698198092Srdivackybool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) { 699198092Srdivacky if (!getLangOptions().CPlusPlus) 700198092Srdivacky return false; 701198092Srdivacky 702204962Srdivacky CXXRecordDecl *DerivedRD = GetClassForType(Derived); 703204962Srdivacky if (!DerivedRD) 704198092Srdivacky return false; 705198092Srdivacky 706204962Srdivacky CXXRecordDecl *BaseRD = GetClassForType(Base); 707204962Srdivacky if (!BaseRD) 708198092Srdivacky return false; 709198092Srdivacky 710198092Srdivacky return DerivedRD->isDerivedFrom(BaseRD, Paths); 711198092Srdivacky} 712198092Srdivacky 713198092Srdivacky/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 714198092Srdivacky/// conversion (where Derived and Base are class types) is 715198092Srdivacky/// well-formed, meaning that the conversion is unambiguous (and 716198092Srdivacky/// that all of the base classes are accessible). Returns true 717198092Srdivacky/// and emits a diagnostic if the code is ill-formed, returns false 718198092Srdivacky/// otherwise. Loc is the location where this routine should point to 719198092Srdivacky/// if there is an error, and Range is the source range to highlight 720198092Srdivacky/// if there is an error. 721198092Srdivackybool 722198092SrdivackySema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 723205219Srdivacky unsigned InaccessibleBaseID, 724198092Srdivacky unsigned AmbigiousBaseConvID, 725198092Srdivacky SourceLocation Loc, SourceRange Range, 726198092Srdivacky DeclarationName Name) { 727198092Srdivacky // First, determine whether the path from Derived to Base is 728198092Srdivacky // ambiguous. This is slightly more expensive than checking whether 729198092Srdivacky // the Derived to Base conversion exists, because here we need to 730198092Srdivacky // explore multiple paths to determine if there is an ambiguity. 731198092Srdivacky CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 732198092Srdivacky /*DetectVirtual=*/false); 733198092Srdivacky bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths); 734198092Srdivacky assert(DerivationOkay && 735198092Srdivacky "Can only be used with a derived-to-base conversion"); 736198092Srdivacky (void)DerivationOkay; 737198092Srdivacky 738198092Srdivacky if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 739205219Srdivacky if (!InaccessibleBaseID) 740199482Srdivacky return false; 741203955Srdivacky 742198092Srdivacky // Check that the base class can be accessed. 743205219Srdivacky switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(), 744205219Srdivacky InaccessibleBaseID)) { 745203955Srdivacky case AR_accessible: return false; 746203955Srdivacky case AR_inaccessible: return true; 747203955Srdivacky case AR_dependent: return false; 748203955Srdivacky case AR_delayed: return false; 749203955Srdivacky } 750198092Srdivacky } 751198092Srdivacky 752198092Srdivacky // We know that the derived-to-base conversion is ambiguous, and 753198092Srdivacky // we're going to produce a diagnostic. Perform the derived-to-base 754198092Srdivacky // search just one more time to compute all of the possible paths so 755198092Srdivacky // that we can print them out. This is more expensive than any of 756198092Srdivacky // the previous derived-to-base checks we've done, but at this point 757198092Srdivacky // performance isn't as much of an issue. 758198092Srdivacky Paths.clear(); 759198092Srdivacky Paths.setRecordingPaths(true); 760198092Srdivacky bool StillOkay = IsDerivedFrom(Derived, Base, Paths); 761198092Srdivacky assert(StillOkay && "Can only be used with a derived-to-base conversion"); 762198092Srdivacky (void)StillOkay; 763198092Srdivacky 764198092Srdivacky // Build up a textual representation of the ambiguous paths, e.g., 765198092Srdivacky // D -> B -> A, that will be used to illustrate the ambiguous 766198092Srdivacky // conversions in the diagnostic. We only print one of the paths 767198092Srdivacky // to each base class subobject. 768198092Srdivacky std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 769198092Srdivacky 770198092Srdivacky Diag(Loc, AmbigiousBaseConvID) 771198092Srdivacky << Derived << Base << PathDisplayStr << Range << Name; 772198092Srdivacky return true; 773198092Srdivacky} 774198092Srdivacky 775198092Srdivackybool 776198092SrdivackySema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 777199482Srdivacky SourceLocation Loc, SourceRange Range, 778199482Srdivacky bool IgnoreAccess) { 779198092Srdivacky return CheckDerivedToBaseConversion(Derived, Base, 780205219Srdivacky IgnoreAccess ? 0 781205219Srdivacky : diag::err_upcast_to_inaccessible_base, 782198092Srdivacky diag::err_ambiguous_derived_to_base_conv, 783198092Srdivacky Loc, Range, DeclarationName()); 784198092Srdivacky} 785198092Srdivacky 786198092Srdivacky 787198092Srdivacky/// @brief Builds a string representing ambiguous paths from a 788198092Srdivacky/// specific derived class to different subobjects of the same base 789198092Srdivacky/// class. 790198092Srdivacky/// 791198092Srdivacky/// This function builds a string that can be used in error messages 792198092Srdivacky/// to show the different paths that one can take through the 793198092Srdivacky/// inheritance hierarchy to go from the derived class to different 794198092Srdivacky/// subobjects of a base class. The result looks something like this: 795198092Srdivacky/// @code 796198092Srdivacky/// struct D -> struct B -> struct A 797198092Srdivacky/// struct D -> struct C -> struct A 798198092Srdivacky/// @endcode 799198092Srdivackystd::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 800198092Srdivacky std::string PathDisplayStr; 801198092Srdivacky std::set<unsigned> DisplayedPaths; 802198092Srdivacky for (CXXBasePaths::paths_iterator Path = Paths.begin(); 803198092Srdivacky Path != Paths.end(); ++Path) { 804198092Srdivacky if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 805198092Srdivacky // We haven't displayed a path to this particular base 806198092Srdivacky // class subobject yet. 807198092Srdivacky PathDisplayStr += "\n "; 808198092Srdivacky PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 809198092Srdivacky for (CXXBasePath::const_iterator Element = Path->begin(); 810198092Srdivacky Element != Path->end(); ++Element) 811198092Srdivacky PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 812198092Srdivacky } 813198092Srdivacky } 814198092Srdivacky 815198092Srdivacky return PathDisplayStr; 816198092Srdivacky} 817198092Srdivacky 818193326Sed//===----------------------------------------------------------------------===// 819193326Sed// C++ class member Handling 820193326Sed//===----------------------------------------------------------------------===// 821193326Sed 822193326Sed/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 823193326Sed/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 824193326Sed/// bitfield width if there is one and 'InitExpr' specifies the initializer if 825193326Sed/// any. 826193326SedSema::DeclPtrTy 827193326SedSema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 828198092Srdivacky MultiTemplateParamsArg TemplateParameterLists, 829199990Srdivacky ExprTy *BW, ExprTy *InitExpr, bool IsDefinition, 830199990Srdivacky bool Deleted) { 831193326Sed const DeclSpec &DS = D.getDeclSpec(); 832193326Sed DeclarationName Name = GetNameForDeclarator(D); 833193326Sed Expr *BitWidth = static_cast<Expr*>(BW); 834193326Sed Expr *Init = static_cast<Expr*>(InitExpr); 835193326Sed SourceLocation Loc = D.getIdentifierLoc(); 836193326Sed 837193326Sed bool isFunc = D.isFunctionDeclarator(); 838193326Sed 839198092Srdivacky assert(!DS.isFriendSpecified()); 840198092Srdivacky 841193326Sed // C++ 9.2p6: A member shall not be declared to have automatic storage 842193326Sed // duration (auto, register) or with the extern storage-class-specifier. 843193326Sed // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 844193326Sed // data members and cannot be applied to names declared const or static, 845193326Sed // and cannot be applied to reference members. 846193326Sed switch (DS.getStorageClassSpec()) { 847193326Sed case DeclSpec::SCS_unspecified: 848193326Sed case DeclSpec::SCS_typedef: 849193326Sed case DeclSpec::SCS_static: 850193326Sed // FALL THROUGH. 851193326Sed break; 852193326Sed case DeclSpec::SCS_mutable: 853193326Sed if (isFunc) { 854193326Sed if (DS.getStorageClassSpecLoc().isValid()) 855193326Sed Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 856193326Sed else 857193326Sed Diag(DS.getThreadSpecLoc(), diag::err_mutable_function); 858198092Srdivacky 859193326Sed // FIXME: It would be nicer if the keyword was ignored only for this 860193326Sed // declarator. Otherwise we could get follow-up errors. 861193326Sed D.getMutableDeclSpec().ClearStorageClassSpecs(); 862193326Sed } else { 863193326Sed QualType T = GetTypeForDeclarator(D, S); 864193326Sed diag::kind err = static_cast<diag::kind>(0); 865193326Sed if (T->isReferenceType()) 866193326Sed err = diag::err_mutable_reference; 867193326Sed else if (T.isConstQualified()) 868193326Sed err = diag::err_mutable_const; 869193326Sed if (err != 0) { 870193326Sed if (DS.getStorageClassSpecLoc().isValid()) 871193326Sed Diag(DS.getStorageClassSpecLoc(), err); 872193326Sed else 873193326Sed Diag(DS.getThreadSpecLoc(), err); 874193326Sed // FIXME: It would be nicer if the keyword was ignored only for this 875193326Sed // declarator. Otherwise we could get follow-up errors. 876193326Sed D.getMutableDeclSpec().ClearStorageClassSpecs(); 877193326Sed } 878193326Sed } 879193326Sed break; 880193326Sed default: 881193326Sed if (DS.getStorageClassSpecLoc().isValid()) 882193326Sed Diag(DS.getStorageClassSpecLoc(), 883193326Sed diag::err_storageclass_invalid_for_member); 884193326Sed else 885193326Sed Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member); 886193326Sed D.getMutableDeclSpec().ClearStorageClassSpecs(); 887193326Sed } 888193326Sed 889193326Sed if (!isFunc && 890193326Sed D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename && 891193326Sed D.getNumTypeObjects() == 0) { 892193326Sed // Check also for this case: 893193326Sed // 894193326Sed // typedef int f(); 895193326Sed // f a; 896193326Sed // 897198092Srdivacky QualType TDType = GetTypeFromParser(DS.getTypeRep()); 898193326Sed isFunc = TDType->isFunctionType(); 899193326Sed } 900193326Sed 901193326Sed bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 902193326Sed DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 903193326Sed !isFunc); 904193326Sed 905193326Sed Decl *Member; 906193326Sed if (isInstField) { 907198092Srdivacky // FIXME: Check for template parameters! 908193326Sed Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth, 909193326Sed AS); 910193326Sed assert(Member && "HandleField never returns null"); 911193326Sed } else { 912199990Srdivacky Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition) 913198092Srdivacky .getAs<Decl>(); 914193326Sed if (!Member) { 915193326Sed if (BitWidth) DeleteExpr(BitWidth); 916193326Sed return DeclPtrTy(); 917193326Sed } 918193326Sed 919193326Sed // Non-instance-fields can't have a bitfield. 920193326Sed if (BitWidth) { 921193326Sed if (Member->isInvalidDecl()) { 922193326Sed // don't emit another diagnostic. 923193326Sed } else if (isa<VarDecl>(Member)) { 924193326Sed // C++ 9.6p3: A bit-field shall not be a static member. 925193326Sed // "static member 'A' cannot be a bit-field" 926193326Sed Diag(Loc, diag::err_static_not_bitfield) 927193326Sed << Name << BitWidth->getSourceRange(); 928193326Sed } else if (isa<TypedefDecl>(Member)) { 929193326Sed // "typedef member 'x' cannot be a bit-field" 930193326Sed Diag(Loc, diag::err_typedef_not_bitfield) 931193326Sed << Name << BitWidth->getSourceRange(); 932193326Sed } else { 933193326Sed // A function typedef ("typedef int f(); f a;"). 934193326Sed // C++ 9.6p3: A bit-field shall have integral or enumeration type. 935193326Sed Diag(Loc, diag::err_not_integral_type_bitfield) 936198092Srdivacky << Name << cast<ValueDecl>(Member)->getType() 937193326Sed << BitWidth->getSourceRange(); 938193326Sed } 939198092Srdivacky 940193326Sed DeleteExpr(BitWidth); 941193326Sed BitWidth = 0; 942193326Sed Member->setInvalidDecl(); 943193326Sed } 944193326Sed 945193326Sed Member->setAccess(AS); 946198092Srdivacky 947198092Srdivacky // If we have declared a member function template, set the access of the 948198092Srdivacky // templated declaration as well. 949198092Srdivacky if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 950198092Srdivacky FunTmpl->getTemplatedDecl()->setAccess(AS); 951193326Sed } 952193326Sed 953193326Sed assert((Name || isInstField) && "No identifier for non-field ?"); 954193326Sed 955193326Sed if (Init) 956193326Sed AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false); 957193326Sed if (Deleted) // FIXME: Source location is not very good. 958193326Sed SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin()); 959193326Sed 960193326Sed if (isInstField) { 961193326Sed FieldCollector->Add(cast<FieldDecl>(Member)); 962193326Sed return DeclPtrTy(); 963193326Sed } 964193326Sed return DeclPtrTy::make(Member); 965193326Sed} 966193326Sed 967201361Srdivacky/// \brief Find the direct and/or virtual base specifiers that 968201361Srdivacky/// correspond to the given base type, for use in base initialization 969201361Srdivacky/// within a constructor. 970201361Srdivackystatic bool FindBaseInitializer(Sema &SemaRef, 971201361Srdivacky CXXRecordDecl *ClassDecl, 972201361Srdivacky QualType BaseType, 973201361Srdivacky const CXXBaseSpecifier *&DirectBaseSpec, 974201361Srdivacky const CXXBaseSpecifier *&VirtualBaseSpec) { 975201361Srdivacky // First, check for a direct base class. 976201361Srdivacky DirectBaseSpec = 0; 977201361Srdivacky for (CXXRecordDecl::base_class_const_iterator Base 978201361Srdivacky = ClassDecl->bases_begin(); 979201361Srdivacky Base != ClassDecl->bases_end(); ++Base) { 980201361Srdivacky if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) { 981201361Srdivacky // We found a direct base of this type. That's what we're 982201361Srdivacky // initializing. 983201361Srdivacky DirectBaseSpec = &*Base; 984201361Srdivacky break; 985201361Srdivacky } 986201361Srdivacky } 987201361Srdivacky 988201361Srdivacky // Check for a virtual base class. 989201361Srdivacky // FIXME: We might be able to short-circuit this if we know in advance that 990201361Srdivacky // there are no virtual bases. 991201361Srdivacky VirtualBaseSpec = 0; 992201361Srdivacky if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 993201361Srdivacky // We haven't found a base yet; search the class hierarchy for a 994201361Srdivacky // virtual base class. 995201361Srdivacky CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 996201361Srdivacky /*DetectVirtual=*/false); 997201361Srdivacky if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl), 998201361Srdivacky BaseType, Paths)) { 999201361Srdivacky for (CXXBasePaths::paths_iterator Path = Paths.begin(); 1000201361Srdivacky Path != Paths.end(); ++Path) { 1001201361Srdivacky if (Path->back().Base->isVirtual()) { 1002201361Srdivacky VirtualBaseSpec = Path->back().Base; 1003201361Srdivacky break; 1004201361Srdivacky } 1005201361Srdivacky } 1006201361Srdivacky } 1007201361Srdivacky } 1008201361Srdivacky 1009201361Srdivacky return DirectBaseSpec || VirtualBaseSpec; 1010201361Srdivacky} 1011201361Srdivacky 1012193326Sed/// ActOnMemInitializer - Handle a C++ member initializer. 1013198092SrdivackySema::MemInitResult 1014193326SedSema::ActOnMemInitializer(DeclPtrTy ConstructorD, 1015193326Sed Scope *S, 1016195341Sed const CXXScopeSpec &SS, 1017193326Sed IdentifierInfo *MemberOrBase, 1018195341Sed TypeTy *TemplateTypeTy, 1019193326Sed SourceLocation IdLoc, 1020193326Sed SourceLocation LParenLoc, 1021193326Sed ExprTy **Args, unsigned NumArgs, 1022193326Sed SourceLocation *CommaLocs, 1023193326Sed SourceLocation RParenLoc) { 1024194711Sed if (!ConstructorD) 1025194711Sed return true; 1026198092Srdivacky 1027198092Srdivacky AdjustDeclIfTemplate(ConstructorD); 1028198092Srdivacky 1029198092Srdivacky CXXConstructorDecl *Constructor 1030193326Sed = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>()); 1031193326Sed if (!Constructor) { 1032193326Sed // The user wrote a constructor initializer on a function that is 1033193326Sed // not a C++ constructor. Ignore the error for now, because we may 1034193326Sed // have more member initializers coming; we'll diagnose it just 1035193326Sed // once in ActOnMemInitializers. 1036193326Sed return true; 1037193326Sed } 1038193326Sed 1039193326Sed CXXRecordDecl *ClassDecl = Constructor->getParent(); 1040193326Sed 1041193326Sed // C++ [class.base.init]p2: 1042193326Sed // Names in a mem-initializer-id are looked up in the scope of the 1043193326Sed // constructor���s class and, if not found in that scope, are looked 1044193326Sed // up in the scope containing the constructor���s 1045193326Sed // definition. [Note: if the constructor���s class contains a member 1046193326Sed // with the same name as a direct or virtual base class of the 1047193326Sed // class, a mem-initializer-id naming the member or base class and 1048193326Sed // composed of a single identifier refers to the class member. A 1049193326Sed // mem-initializer-id for the hidden base class may be specified 1050193326Sed // using a qualified name. ] 1051195341Sed if (!SS.getScopeRep() && !TemplateTypeTy) { 1052195341Sed // Look for a member, first. 1053195341Sed FieldDecl *Member = 0; 1054198092Srdivacky DeclContext::lookup_result Result 1055195341Sed = ClassDecl->lookup(MemberOrBase); 1056195341Sed if (Result.first != Result.second) 1057195341Sed Member = dyn_cast<FieldDecl>(*Result.first); 1058193326Sed 1059195341Sed // FIXME: Handle members of an anonymous union. 1060193326Sed 1061198092Srdivacky if (Member) 1062198092Srdivacky return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc, 1063200583Srdivacky LParenLoc, RParenLoc); 1064193326Sed } 1065193326Sed // It didn't name a member, so see if it names a class. 1066200583Srdivacky QualType BaseType; 1067201361Srdivacky TypeSourceInfo *TInfo = 0; 1068200583Srdivacky 1069201361Srdivacky if (TemplateTypeTy) { 1070200583Srdivacky BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 1071201361Srdivacky } else { 1072201361Srdivacky LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 1073201361Srdivacky LookupParsedName(R, S, &SS); 1074193326Sed 1075201361Srdivacky TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 1076201361Srdivacky if (!TyD) { 1077201361Srdivacky if (R.isAmbiguous()) return true; 1078201361Srdivacky 1079202879Srdivacky if (SS.isSet() && isDependentScopeSpecifier(SS)) { 1080202879Srdivacky bool NotUnknownSpecialization = false; 1081202879Srdivacky DeclContext *DC = computeDeclContext(SS, false); 1082202879Srdivacky if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 1083202879Srdivacky NotUnknownSpecialization = !Record->hasAnyDependentBases(); 1084202879Srdivacky 1085202879Srdivacky if (!NotUnknownSpecialization) { 1086202879Srdivacky // When the scope specifier can refer to a member of an unknown 1087202879Srdivacky // specialization, we take it as a type name. 1088202879Srdivacky BaseType = CheckTypenameType((NestedNameSpecifier *)SS.getScopeRep(), 1089202879Srdivacky *MemberOrBase, SS.getRange()); 1090204962Srdivacky if (BaseType.isNull()) 1091204962Srdivacky return true; 1092204962Srdivacky 1093202879Srdivacky R.clear(); 1094202879Srdivacky } 1095202879Srdivacky } 1096202879Srdivacky 1097201361Srdivacky // If no results were found, try to correct typos. 1098202879Srdivacky if (R.empty() && BaseType.isNull() && 1099201361Srdivacky CorrectTypo(R, S, &SS, ClassDecl) && R.isSingleResult()) { 1100201361Srdivacky if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) { 1101201361Srdivacky if (Member->getDeclContext()->getLookupContext()->Equals(ClassDecl)) { 1102201361Srdivacky // We have found a non-static data member with a similar 1103201361Srdivacky // name to what was typed; complain and initialize that 1104201361Srdivacky // member. 1105201361Srdivacky Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest) 1106201361Srdivacky << MemberOrBase << true << R.getLookupName() 1107206084Srdivacky << FixItHint::CreateReplacement(R.getNameLoc(), 1108206084Srdivacky R.getLookupName().getAsString()); 1109202379Srdivacky Diag(Member->getLocation(), diag::note_previous_decl) 1110202379Srdivacky << Member->getDeclName(); 1111201361Srdivacky 1112201361Srdivacky return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc, 1113201361Srdivacky LParenLoc, RParenLoc); 1114201361Srdivacky } 1115201361Srdivacky } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) { 1116201361Srdivacky const CXXBaseSpecifier *DirectBaseSpec; 1117201361Srdivacky const CXXBaseSpecifier *VirtualBaseSpec; 1118201361Srdivacky if (FindBaseInitializer(*this, ClassDecl, 1119201361Srdivacky Context.getTypeDeclType(Type), 1120201361Srdivacky DirectBaseSpec, VirtualBaseSpec)) { 1121201361Srdivacky // We have found a direct or virtual base class with a 1122201361Srdivacky // similar name to what was typed; complain and initialize 1123201361Srdivacky // that base class. 1124201361Srdivacky Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest) 1125201361Srdivacky << MemberOrBase << false << R.getLookupName() 1126206084Srdivacky << FixItHint::CreateReplacement(R.getNameLoc(), 1127206084Srdivacky R.getLookupName().getAsString()); 1128202379Srdivacky 1129202379Srdivacky const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec 1130202379Srdivacky : VirtualBaseSpec; 1131202379Srdivacky Diag(BaseSpec->getSourceRange().getBegin(), 1132202379Srdivacky diag::note_base_class_specified_here) 1133202379Srdivacky << BaseSpec->getType() 1134202379Srdivacky << BaseSpec->getSourceRange(); 1135202379Srdivacky 1136201361Srdivacky TyD = Type; 1137201361Srdivacky } 1138201361Srdivacky } 1139201361Srdivacky } 1140201361Srdivacky 1141202879Srdivacky if (!TyD && BaseType.isNull()) { 1142201361Srdivacky Diag(IdLoc, diag::err_mem_init_not_member_or_class) 1143201361Srdivacky << MemberOrBase << SourceRange(IdLoc, RParenLoc); 1144201361Srdivacky return true; 1145201361Srdivacky } 1146201361Srdivacky } 1147201361Srdivacky 1148202879Srdivacky if (BaseType.isNull()) { 1149202879Srdivacky BaseType = Context.getTypeDeclType(TyD); 1150202879Srdivacky if (SS.isSet()) { 1151202879Srdivacky NestedNameSpecifier *Qualifier = 1152202879Srdivacky static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 1153201361Srdivacky 1154202879Srdivacky // FIXME: preserve source range information 1155202879Srdivacky BaseType = Context.getQualifiedNameType(Qualifier, BaseType); 1156202879Srdivacky } 1157201361Srdivacky } 1158201361Srdivacky } 1159201361Srdivacky 1160200583Srdivacky if (!TInfo) 1161200583Srdivacky TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 1162198092Srdivacky 1163200583Srdivacky return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs, 1164200583Srdivacky LParenLoc, RParenLoc, ClassDecl); 1165198092Srdivacky} 1166198092Srdivacky 1167198954Srdivacky/// Checks an initializer expression for use of uninitialized fields, such as 1168198954Srdivacky/// containing the field that is being initialized. Returns true if there is an 1169198954Srdivacky/// uninitialized field was used an updates the SourceLocation parameter; false 1170198954Srdivacky/// otherwise. 1171198954Srdivackystatic bool InitExprContainsUninitializedFields(const Stmt* S, 1172198954Srdivacky const FieldDecl* LhsField, 1173198954Srdivacky SourceLocation* L) { 1174198954Srdivacky const MemberExpr* ME = dyn_cast<MemberExpr>(S); 1175198954Srdivacky if (ME) { 1176198954Srdivacky const NamedDecl* RhsField = ME->getMemberDecl(); 1177198954Srdivacky if (RhsField == LhsField) { 1178198954Srdivacky // Initializing a field with itself. Throw a warning. 1179198954Srdivacky // But wait; there are exceptions! 1180198954Srdivacky // Exception #1: The field may not belong to this record. 1181198954Srdivacky // e.g. Foo(const Foo& rhs) : A(rhs.A) {} 1182198954Srdivacky const Expr* base = ME->getBase(); 1183198954Srdivacky if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) { 1184198954Srdivacky // Even though the field matches, it does not belong to this record. 1185198954Srdivacky return false; 1186198954Srdivacky } 1187198954Srdivacky // None of the exceptions triggered; return true to indicate an 1188198954Srdivacky // uninitialized field was used. 1189198954Srdivacky *L = ME->getMemberLoc(); 1190198954Srdivacky return true; 1191198954Srdivacky } 1192198954Srdivacky } 1193198954Srdivacky bool found = false; 1194198954Srdivacky for (Stmt::const_child_iterator it = S->child_begin(); 1195198954Srdivacky it != S->child_end() && found == false; 1196198954Srdivacky ++it) { 1197198954Srdivacky if (isa<CallExpr>(S)) { 1198198954Srdivacky // Do not descend into function calls or constructors, as the use 1199198954Srdivacky // of an uninitialized field may be valid. One would have to inspect 1200198954Srdivacky // the contents of the function/ctor to determine if it is safe or not. 1201198954Srdivacky // i.e. Pass-by-value is never safe, but pass-by-reference and pointers 1202198954Srdivacky // may be safe, depending on what the function/ctor does. 1203198954Srdivacky continue; 1204198954Srdivacky } 1205198954Srdivacky found = InitExprContainsUninitializedFields(*it, LhsField, L); 1206198954Srdivacky } 1207198954Srdivacky return found; 1208198954Srdivacky} 1209198954Srdivacky 1210198092SrdivackySema::MemInitResult 1211198092SrdivackySema::BuildMemberInitializer(FieldDecl *Member, Expr **Args, 1212198092Srdivacky unsigned NumArgs, SourceLocation IdLoc, 1213200583Srdivacky SourceLocation LParenLoc, 1214198092Srdivacky SourceLocation RParenLoc) { 1215198954Srdivacky // Diagnose value-uses of fields to initialize themselves, e.g. 1216198954Srdivacky // foo(foo) 1217198954Srdivacky // where foo is not also a parameter to the constructor. 1218198954Srdivacky // TODO: implement -Wuninitialized and fold this into that framework. 1219198954Srdivacky for (unsigned i = 0; i < NumArgs; ++i) { 1220198954Srdivacky SourceLocation L; 1221198954Srdivacky if (InitExprContainsUninitializedFields(Args[i], Member, &L)) { 1222198954Srdivacky // FIXME: Return true in the case when other fields are used before being 1223198954Srdivacky // uninitialized. For example, let this field be the i'th field. When 1224198954Srdivacky // initializing the i'th field, throw a warning if any of the >= i'th 1225198954Srdivacky // fields are used, as they are not yet initialized. 1226198954Srdivacky // Right now we are only handling the case where the i'th field uses 1227198954Srdivacky // itself in its initializer. 1228198954Srdivacky Diag(L, diag::warn_field_is_uninit); 1229198954Srdivacky } 1230198954Srdivacky } 1231198954Srdivacky 1232198092Srdivacky bool HasDependentArg = false; 1233198092Srdivacky for (unsigned i = 0; i < NumArgs; i++) 1234198092Srdivacky HasDependentArg |= Args[i]->isTypeDependent(); 1235198092Srdivacky 1236198092Srdivacky QualType FieldType = Member->getType(); 1237198092Srdivacky if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 1238198092Srdivacky FieldType = Array->getElementType(); 1239201361Srdivacky ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this); 1240203955Srdivacky if (FieldType->isDependentType() || HasDependentArg) { 1241203955Srdivacky // Can't check initialization for a member of dependent type or when 1242203955Srdivacky // any of the arguments are type-dependent expressions. 1243203955Srdivacky OwningExprResult Init 1244203955Srdivacky = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs, 1245203955Srdivacky RParenLoc)); 1246203955Srdivacky 1247203955Srdivacky // Erase any temporaries within this evaluation context; we're not 1248203955Srdivacky // going to track them in the AST, since we'll be rebuilding the 1249203955Srdivacky // ASTs during template instantiation. 1250203955Srdivacky ExprTemporaries.erase( 1251203955Srdivacky ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries, 1252203955Srdivacky ExprTemporaries.end()); 1253203955Srdivacky 1254203955Srdivacky return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc, 1255203955Srdivacky LParenLoc, 1256203955Srdivacky Init.takeAs<Expr>(), 1257203955Srdivacky RParenLoc); 1258203955Srdivacky 1259193326Sed } 1260199482Srdivacky 1261203955Srdivacky if (Member->isInvalidDecl()) 1262203955Srdivacky return true; 1263199482Srdivacky 1264203955Srdivacky // Initialize the member. 1265203955Srdivacky InitializedEntity MemberEntity = 1266203955Srdivacky InitializedEntity::InitializeMember(Member, 0); 1267203955Srdivacky InitializationKind Kind = 1268203955Srdivacky InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc); 1269203955Srdivacky 1270203955Srdivacky InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs); 1271203955Srdivacky 1272203955Srdivacky OwningExprResult MemberInit = 1273203955Srdivacky InitSeq.Perform(*this, MemberEntity, Kind, 1274203955Srdivacky MultiExprArg(*this, (void**)Args, NumArgs), 0); 1275203955Srdivacky if (MemberInit.isInvalid()) 1276203955Srdivacky return true; 1277203955Srdivacky 1278203955Srdivacky // C++0x [class.base.init]p7: 1279203955Srdivacky // The initialization of each base and member constitutes a 1280203955Srdivacky // full-expression. 1281203955Srdivacky MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit)); 1282203955Srdivacky if (MemberInit.isInvalid()) 1283203955Srdivacky return true; 1284203955Srdivacky 1285203955Srdivacky // If we are in a dependent context, template instantiation will 1286203955Srdivacky // perform this type-checking again. Just save the arguments that we 1287203955Srdivacky // received in a ParenListExpr. 1288203955Srdivacky // FIXME: This isn't quite ideal, since our ASTs don't capture all 1289203955Srdivacky // of the information that we have about the member 1290203955Srdivacky // initializer. However, deconstructing the ASTs is a dicey process, 1291203955Srdivacky // and this approach is far more likely to get the corner cases right. 1292203955Srdivacky if (CurContext->isDependentContext()) { 1293203955Srdivacky // Bump the reference count of all of the arguments. 1294203955Srdivacky for (unsigned I = 0; I != NumArgs; ++I) 1295203955Srdivacky Args[I]->Retain(); 1296203955Srdivacky 1297203955Srdivacky OwningExprResult Init 1298203955Srdivacky = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs, 1299203955Srdivacky RParenLoc)); 1300203955Srdivacky return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc, 1301203955Srdivacky LParenLoc, 1302203955Srdivacky Init.takeAs<Expr>(), 1303203955Srdivacky RParenLoc); 1304203955Srdivacky } 1305203955Srdivacky 1306200583Srdivacky return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc, 1307203955Srdivacky LParenLoc, 1308203955Srdivacky MemberInit.takeAs<Expr>(), 1309203955Srdivacky RParenLoc); 1310198092Srdivacky} 1311198092Srdivacky 1312198092SrdivackySema::MemInitResult 1313200583SrdivackySema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 1314200583Srdivacky Expr **Args, unsigned NumArgs, 1315200583Srdivacky SourceLocation LParenLoc, SourceLocation RParenLoc, 1316200583Srdivacky CXXRecordDecl *ClassDecl) { 1317198092Srdivacky bool HasDependentArg = false; 1318198092Srdivacky for (unsigned i = 0; i < NumArgs; i++) 1319198092Srdivacky HasDependentArg |= Args[i]->isTypeDependent(); 1320198092Srdivacky 1321200583Srdivacky SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getSourceRange().getBegin(); 1322203955Srdivacky if (BaseType->isDependentType() || HasDependentArg) { 1323203955Srdivacky // Can't check initialization for a base of dependent type or when 1324203955Srdivacky // any of the arguments are type-dependent expressions. 1325203955Srdivacky OwningExprResult BaseInit 1326203955Srdivacky = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs, 1327203955Srdivacky RParenLoc)); 1328198092Srdivacky 1329203955Srdivacky // Erase any temporaries within this evaluation context; we're not 1330203955Srdivacky // going to track them in the AST, since we'll be rebuilding the 1331203955Srdivacky // ASTs during template instantiation. 1332203955Srdivacky ExprTemporaries.erase( 1333203955Srdivacky ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries, 1334203955Srdivacky ExprTemporaries.end()); 1335198092Srdivacky 1336203955Srdivacky return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo, 1337203955Srdivacky LParenLoc, 1338203955Srdivacky BaseInit.takeAs<Expr>(), 1339203955Srdivacky RParenLoc); 1340193326Sed } 1341203955Srdivacky 1342203955Srdivacky if (!BaseType->isRecordType()) 1343203955Srdivacky return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 1344203955Srdivacky << BaseType << BaseTInfo->getTypeLoc().getSourceRange(); 1345193326Sed 1346203955Srdivacky // C++ [class.base.init]p2: 1347203955Srdivacky // [...] Unless the mem-initializer-id names a nonstatic data 1348203955Srdivacky // member of the constructor���s class or a direct or virtual base 1349203955Srdivacky // of that class, the mem-initializer is ill-formed. A 1350203955Srdivacky // mem-initializer-list can initialize a base class using any 1351203955Srdivacky // name that denotes that base class type. 1352193326Sed 1353203955Srdivacky // Check for direct and virtual base classes. 1354203955Srdivacky const CXXBaseSpecifier *DirectBaseSpec = 0; 1355203955Srdivacky const CXXBaseSpecifier *VirtualBaseSpec = 0; 1356203955Srdivacky FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 1357203955Srdivacky VirtualBaseSpec); 1358203955Srdivacky 1359203955Srdivacky // C++ [base.class.init]p2: 1360203955Srdivacky // If a mem-initializer-id is ambiguous because it designates both 1361203955Srdivacky // a direct non-virtual base class and an inherited virtual base 1362203955Srdivacky // class, the mem-initializer is ill-formed. 1363203955Srdivacky if (DirectBaseSpec && VirtualBaseSpec) 1364203955Srdivacky return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 1365203955Srdivacky << BaseType << BaseTInfo->getTypeLoc().getSourceRange(); 1366203955Srdivacky // C++ [base.class.init]p2: 1367203955Srdivacky // Unless the mem-initializer-id names a nonstatic data membeer of the 1368203955Srdivacky // constructor's class ot a direst or virtual base of that class, the 1369203955Srdivacky // mem-initializer is ill-formed. 1370203955Srdivacky if (!DirectBaseSpec && !VirtualBaseSpec) 1371203955Srdivacky return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 1372203955Srdivacky << BaseType << ClassDecl->getNameAsCString() 1373203955Srdivacky << BaseTInfo->getTypeLoc().getSourceRange(); 1374203955Srdivacky 1375203955Srdivacky CXXBaseSpecifier *BaseSpec 1376203955Srdivacky = const_cast<CXXBaseSpecifier *>(DirectBaseSpec); 1377203955Srdivacky if (!BaseSpec) 1378203955Srdivacky BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec); 1379203955Srdivacky 1380203955Srdivacky // Initialize the base. 1381203955Srdivacky InitializedEntity BaseEntity = 1382203955Srdivacky InitializedEntity::InitializeBase(Context, BaseSpec); 1383203955Srdivacky InitializationKind Kind = 1384203955Srdivacky InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc); 1385203955Srdivacky 1386203955Srdivacky InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs); 1387203955Srdivacky 1388203955Srdivacky OwningExprResult BaseInit = 1389203955Srdivacky InitSeq.Perform(*this, BaseEntity, Kind, 1390203955Srdivacky MultiExprArg(*this, (void**)Args, NumArgs), 0); 1391203955Srdivacky if (BaseInit.isInvalid()) 1392203955Srdivacky return true; 1393203955Srdivacky 1394203955Srdivacky // C++0x [class.base.init]p7: 1395203955Srdivacky // The initialization of each base and member constitutes a 1396203955Srdivacky // full-expression. 1397203955Srdivacky BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit)); 1398203955Srdivacky if (BaseInit.isInvalid()) 1399203955Srdivacky return true; 1400203955Srdivacky 1401203955Srdivacky // If we are in a dependent context, template instantiation will 1402203955Srdivacky // perform this type-checking again. Just save the arguments that we 1403203955Srdivacky // received in a ParenListExpr. 1404203955Srdivacky // FIXME: This isn't quite ideal, since our ASTs don't capture all 1405203955Srdivacky // of the information that we have about the base 1406203955Srdivacky // initializer. However, deconstructing the ASTs is a dicey process, 1407203955Srdivacky // and this approach is far more likely to get the corner cases right. 1408203955Srdivacky if (CurContext->isDependentContext()) { 1409203955Srdivacky // Bump the reference count of all of the arguments. 1410203955Srdivacky for (unsigned I = 0; I != NumArgs; ++I) 1411203955Srdivacky Args[I]->Retain(); 1412203955Srdivacky 1413203955Srdivacky OwningExprResult Init 1414203955Srdivacky = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs, 1415203955Srdivacky RParenLoc)); 1416203955Srdivacky return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo, 1417203955Srdivacky LParenLoc, 1418203955Srdivacky Init.takeAs<Expr>(), 1419203955Srdivacky RParenLoc); 1420198092Srdivacky } 1421198092Srdivacky 1422203955Srdivacky return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo, 1423203955Srdivacky LParenLoc, 1424203955Srdivacky BaseInit.takeAs<Expr>(), 1425203955Srdivacky RParenLoc); 1426193326Sed} 1427193326Sed 1428199482Srdivackybool 1429198893SrdivackySema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor, 1430203955Srdivacky CXXBaseOrMemberInitializer **Initializers, 1431203955Srdivacky unsigned NumInitializers, 1432203955Srdivacky bool AnyErrors) { 1433206084Srdivacky if (Constructor->isDependentContext()) { 1434206084Srdivacky // Just store the initializers as written, they will be checked during 1435206084Srdivacky // instantiation. 1436206084Srdivacky if (NumInitializers > 0) { 1437206084Srdivacky Constructor->setNumBaseOrMemberInitializers(NumInitializers); 1438206084Srdivacky CXXBaseOrMemberInitializer **baseOrMemberInitializers = 1439206084Srdivacky new (Context) CXXBaseOrMemberInitializer*[NumInitializers]; 1440206084Srdivacky memcpy(baseOrMemberInitializers, Initializers, 1441206084Srdivacky NumInitializers * sizeof(CXXBaseOrMemberInitializer*)); 1442206084Srdivacky Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers); 1443206084Srdivacky } 1444206084Srdivacky 1445206084Srdivacky return false; 1446206084Srdivacky } 1447206084Srdivacky 1448198092Srdivacky // We need to build the initializer AST according to order of construction 1449198092Srdivacky // and not what user specified in the Initializers list. 1450206084Srdivacky CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 1451206084Srdivacky if (!ClassDecl) 1452206084Srdivacky return true; 1453206084Srdivacky 1454198092Srdivacky llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit; 1455198092Srdivacky llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields; 1456199482Srdivacky bool HadError = false; 1457198092Srdivacky 1458198092Srdivacky for (unsigned i = 0; i < NumInitializers; i++) { 1459198092Srdivacky CXXBaseOrMemberInitializer *Member = Initializers[i]; 1460206084Srdivacky 1461206084Srdivacky if (Member->isBaseInitializer()) 1462198092Srdivacky AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 1463206084Srdivacky else 1464198092Srdivacky AllBaseFields[Member->getMember()] = Member; 1465198092Srdivacky } 1466198092Srdivacky 1467206084Srdivacky llvm::SmallVector<CXXBaseSpecifier *, 4> BasesToDefaultInit; 1468198092Srdivacky 1469206084Srdivacky // Push virtual bases before others. 1470206084Srdivacky for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 1471206084Srdivacky E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 1472206084Srdivacky 1473206084Srdivacky if (CXXBaseOrMemberInitializer *Value 1474206084Srdivacky = AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) { 1475206084Srdivacky AllToInit.push_back(Value); 1476206084Srdivacky } else if (!AnyErrors) { 1477206084Srdivacky InitializedEntity InitEntity 1478206084Srdivacky = InitializedEntity::InitializeBase(Context, VBase); 1479206084Srdivacky InitializationKind InitKind 1480206084Srdivacky = InitializationKind::CreateDefault(Constructor->getLocation()); 1481206084Srdivacky InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0); 1482206084Srdivacky OwningExprResult BaseInit = InitSeq.Perform(*this, InitEntity, InitKind, 1483206084Srdivacky MultiExprArg(*this, 0, 0)); 1484206084Srdivacky BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit)); 1485206084Srdivacky if (BaseInit.isInvalid()) { 1486206084Srdivacky HadError = true; 1487198092Srdivacky continue; 1488206084Srdivacky } 1489198893Srdivacky 1490206084Srdivacky CXXBaseOrMemberInitializer *CXXBaseInit = 1491206084Srdivacky new (Context) CXXBaseOrMemberInitializer(Context, 1492206084Srdivacky Context.getTrivialTypeSourceInfo(VBase->getType(), 1493206084Srdivacky SourceLocation()), 1494206084Srdivacky SourceLocation(), 1495206084Srdivacky BaseInit.takeAs<Expr>(), 1496206084Srdivacky SourceLocation()); 1497206084Srdivacky AllToInit.push_back(CXXBaseInit); 1498198092Srdivacky } 1499206084Srdivacky } 1500198092Srdivacky 1501206084Srdivacky for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 1502206084Srdivacky E = ClassDecl->bases_end(); Base != E; ++Base) { 1503206084Srdivacky // Virtuals are in the virtual base list and already constructed. 1504206084Srdivacky if (Base->isVirtual()) 1505206084Srdivacky continue; 1506206084Srdivacky 1507206084Srdivacky if (CXXBaseOrMemberInitializer *Value 1508206084Srdivacky = AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) { 1509206084Srdivacky AllToInit.push_back(Value); 1510206084Srdivacky } else if (!AnyErrors) { 1511206084Srdivacky InitializedEntity InitEntity 1512206084Srdivacky = InitializedEntity::InitializeBase(Context, Base); 1513206084Srdivacky InitializationKind InitKind 1514206084Srdivacky = InitializationKind::CreateDefault(Constructor->getLocation()); 1515206084Srdivacky InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0); 1516206084Srdivacky OwningExprResult BaseInit = InitSeq.Perform(*this, InitEntity, InitKind, 1517206084Srdivacky MultiExprArg(*this, 0, 0)); 1518206084Srdivacky BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit)); 1519206084Srdivacky if (BaseInit.isInvalid()) { 1520206084Srdivacky HadError = true; 1521198092Srdivacky continue; 1522198092Srdivacky } 1523206084Srdivacky 1524206084Srdivacky CXXBaseOrMemberInitializer *CXXBaseInit = 1525206084Srdivacky new (Context) CXXBaseOrMemberInitializer(Context, 1526206084Srdivacky Context.getTrivialTypeSourceInfo(Base->getType(), 1527206084Srdivacky SourceLocation()), 1528206084Srdivacky SourceLocation(), 1529206084Srdivacky BaseInit.takeAs<Expr>(), 1530206084Srdivacky SourceLocation()); 1531206084Srdivacky AllToInit.push_back(CXXBaseInit); 1532198092Srdivacky } 1533198092Srdivacky } 1534198092Srdivacky 1535198092Srdivacky // non-static data members. 1536198092Srdivacky for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 1537198092Srdivacky E = ClassDecl->field_end(); Field != E; ++Field) { 1538198092Srdivacky if ((*Field)->isAnonymousStructOrUnion()) { 1539198092Srdivacky if (const RecordType *FieldClassType = 1540198092Srdivacky Field->getType()->getAs<RecordType>()) { 1541198092Srdivacky CXXRecordDecl *FieldClassDecl 1542199482Srdivacky = cast<CXXRecordDecl>(FieldClassType->getDecl()); 1543198092Srdivacky for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(), 1544198092Srdivacky EA = FieldClassDecl->field_end(); FA != EA; FA++) { 1545198092Srdivacky if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) { 1546198092Srdivacky // 'Member' is the anonymous union field and 'AnonUnionMember' is 1547198092Srdivacky // set to the anonymous union data member used in the initializer 1548198092Srdivacky // list. 1549198092Srdivacky Value->setMember(*Field); 1550198092Srdivacky Value->setAnonUnionMember(*FA); 1551198092Srdivacky AllToInit.push_back(Value); 1552198092Srdivacky break; 1553198092Srdivacky } 1554198092Srdivacky } 1555198092Srdivacky } 1556198092Srdivacky continue; 1557198092Srdivacky } 1558198092Srdivacky if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) { 1559198092Srdivacky AllToInit.push_back(Value); 1560198092Srdivacky continue; 1561198092Srdivacky } 1562198092Srdivacky 1563203955Srdivacky if ((*Field)->getType()->isDependentType() || AnyErrors) 1564198954Srdivacky continue; 1565198954Srdivacky 1566198092Srdivacky QualType FT = Context.getBaseElementType((*Field)->getType()); 1567203955Srdivacky if (FT->getAs<RecordType>()) { 1568203955Srdivacky InitializedEntity InitEntity 1569203955Srdivacky = InitializedEntity::InitializeMember(*Field); 1570203955Srdivacky InitializationKind InitKind 1571203955Srdivacky = InitializationKind::CreateDefault(Constructor->getLocation()); 1572203955Srdivacky 1573203955Srdivacky InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0); 1574203955Srdivacky OwningExprResult MemberInit = InitSeq.Perform(*this, InitEntity, InitKind, 1575203955Srdivacky MultiExprArg(*this, 0, 0)); 1576203955Srdivacky MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit)); 1577203955Srdivacky if (MemberInit.isInvalid()) { 1578199482Srdivacky HadError = true; 1579198893Srdivacky continue; 1580198893Srdivacky } 1581203955Srdivacky 1582203955Srdivacky // Don't attach synthesized member initializers in a dependent 1583203955Srdivacky // context; they'll be regenerated a template instantiation 1584203955Srdivacky // time. 1585203955Srdivacky if (CurContext->isDependentContext()) 1586199482Srdivacky continue; 1587198893Srdivacky 1588198092Srdivacky CXXBaseOrMemberInitializer *Member = 1589200583Srdivacky new (Context) CXXBaseOrMemberInitializer(Context, 1590200583Srdivacky *Field, SourceLocation(), 1591198893Srdivacky SourceLocation(), 1592203955Srdivacky MemberInit.takeAs<Expr>(), 1593198893Srdivacky SourceLocation()); 1594198893Srdivacky 1595198092Srdivacky AllToInit.push_back(Member); 1596198092Srdivacky } 1597198092Srdivacky else if (FT->isReferenceType()) { 1598203955Srdivacky Diag(Constructor->getLocation(), diag::err_uninitialized_member_in_ctor) 1599206084Srdivacky << (int)Constructor->isImplicit() << Context.getTagDeclType(ClassDecl) 1600199482Srdivacky << 0 << (*Field)->getDeclName(); 1601198092Srdivacky Diag((*Field)->getLocation(), diag::note_declared_at); 1602199482Srdivacky HadError = true; 1603198092Srdivacky } 1604198092Srdivacky else if (FT.isConstQualified()) { 1605203955Srdivacky Diag(Constructor->getLocation(), diag::err_uninitialized_member_in_ctor) 1606206084Srdivacky << (int)Constructor->isImplicit() << Context.getTagDeclType(ClassDecl) 1607199482Srdivacky << 1 << (*Field)->getDeclName(); 1608198092Srdivacky Diag((*Field)->getLocation(), diag::note_declared_at); 1609199482Srdivacky HadError = true; 1610198092Srdivacky } 1611198092Srdivacky } 1612198092Srdivacky 1613198092Srdivacky NumInitializers = AllToInit.size(); 1614198092Srdivacky if (NumInitializers > 0) { 1615198092Srdivacky Constructor->setNumBaseOrMemberInitializers(NumInitializers); 1616198092Srdivacky CXXBaseOrMemberInitializer **baseOrMemberInitializers = 1617198092Srdivacky new (Context) CXXBaseOrMemberInitializer*[NumInitializers]; 1618205408Srdivacky memcpy(baseOrMemberInitializers, AllToInit.data(), 1619205408Srdivacky NumInitializers * sizeof(CXXBaseOrMemberInitializer*)); 1620198092Srdivacky Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers); 1621205219Srdivacky 1622205408Srdivacky // Constructors implicitly reference the base and member 1623205408Srdivacky // destructors. 1624205408Srdivacky MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 1625205408Srdivacky Constructor->getParent()); 1626198092Srdivacky } 1627198092Srdivacky 1628199482Srdivacky return HadError; 1629198092Srdivacky} 1630198092Srdivacky 1631198092Srdivackystatic void *GetKeyForTopLevelField(FieldDecl *Field) { 1632198092Srdivacky // For anonymous unions, use the class declaration as the key. 1633198092Srdivacky if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 1634198092Srdivacky if (RT->getDecl()->isAnonymousStructOrUnion()) 1635198092Srdivacky return static_cast<void *>(RT->getDecl()); 1636198092Srdivacky } 1637198092Srdivacky return static_cast<void *>(Field); 1638198092Srdivacky} 1639198092Srdivacky 1640206084Srdivackystatic void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 1641206084Srdivacky return Context.getCanonicalType(BaseType).getTypePtr(); 1642198092Srdivacky} 1643198092Srdivacky 1644206084Srdivackystatic void *GetKeyForMember(ASTContext &Context, 1645206084Srdivacky CXXBaseOrMemberInitializer *Member, 1646198092Srdivacky bool MemberMaybeAnon = false) { 1647206084Srdivacky if (!Member->isMemberInitializer()) 1648206084Srdivacky return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 1649206084Srdivacky 1650198092Srdivacky // For fields injected into the class via declaration of an anonymous union, 1651198092Srdivacky // use its anonymous union class declaration as the unique key. 1652206084Srdivacky FieldDecl *Field = Member->getMember(); 1653198092Srdivacky 1654206084Srdivacky // After SetBaseOrMemberInitializers call, Field is the anonymous union 1655206084Srdivacky // data member of the class. Data member used in the initializer list is 1656206084Srdivacky // in AnonUnionMember field. 1657206084Srdivacky if (MemberMaybeAnon && Field->isAnonymousStructOrUnion()) 1658206084Srdivacky Field = Member->getAnonUnionMember(); 1659206084Srdivacky 1660206084Srdivacky // If the field is a member of an anonymous union, we use record decl of the 1661206084Srdivacky // union as the key. 1662206084Srdivacky RecordDecl *RD = Field->getParent(); 1663206084Srdivacky if (RD->isAnonymousStructOrUnion() && RD->isUnion()) 1664206084Srdivacky return static_cast<void *>(RD); 1665198092Srdivacky 1666206084Srdivacky return static_cast<void *>(Field); 1667198092Srdivacky} 1668198092Srdivacky 1669206084Srdivackystatic void 1670206084SrdivackyDiagnoseBaseOrMemInitializerOrder(Sema &SemaRef, 1671206084Srdivacky const CXXConstructorDecl *Constructor, 1672206084Srdivacky CXXBaseOrMemberInitializer **MemInits, 1673206084Srdivacky unsigned NumMemInits) { 1674198092Srdivacky if (Constructor->isDependentContext()) 1675198092Srdivacky return; 1676198092Srdivacky 1677206084Srdivacky if (SemaRef.Diags.getDiagnosticLevel(diag::warn_base_initialized) == 1678198092Srdivacky Diagnostic::Ignored && 1679206084Srdivacky SemaRef.Diags.getDiagnosticLevel(diag::warn_field_initialized) == 1680198092Srdivacky Diagnostic::Ignored) 1681198092Srdivacky return; 1682206084Srdivacky 1683198092Srdivacky // Also issue warning if order of ctor-initializer list does not match order 1684198092Srdivacky // of 1) base class declarations and 2) order of non-static data members. 1685198092Srdivacky llvm::SmallVector<const void*, 32> AllBaseOrMembers; 1686198092Srdivacky 1687206084Srdivacky const CXXRecordDecl *ClassDecl = Constructor->getParent(); 1688206084Srdivacky 1689198092Srdivacky // Push virtual bases before others. 1690206084Srdivacky for (CXXRecordDecl::base_class_const_iterator VBase = 1691198092Srdivacky ClassDecl->vbases_begin(), 1692198092Srdivacky E = ClassDecl->vbases_end(); VBase != E; ++VBase) 1693206084Srdivacky AllBaseOrMembers.push_back(GetKeyForBase(SemaRef.Context, 1694206084Srdivacky VBase->getType())); 1695198092Srdivacky 1696206084Srdivacky for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(), 1697198092Srdivacky E = ClassDecl->bases_end(); Base != E; ++Base) { 1698198092Srdivacky // Virtuals are alread in the virtual base list and are constructed 1699198092Srdivacky // first. 1700198092Srdivacky if (Base->isVirtual()) 1701198092Srdivacky continue; 1702206084Srdivacky AllBaseOrMembers.push_back(GetKeyForBase(SemaRef.Context, 1703206084Srdivacky Base->getType())); 1704198092Srdivacky } 1705198092Srdivacky 1706198092Srdivacky for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 1707198092Srdivacky E = ClassDecl->field_end(); Field != E; ++Field) 1708198092Srdivacky AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field)); 1709198092Srdivacky 1710198092Srdivacky int Last = AllBaseOrMembers.size(); 1711198092Srdivacky int curIndex = 0; 1712198092Srdivacky CXXBaseOrMemberInitializer *PrevMember = 0; 1713195341Sed for (unsigned i = 0; i < NumMemInits; i++) { 1714206084Srdivacky CXXBaseOrMemberInitializer *Member = MemInits[i]; 1715206084Srdivacky void *MemberInCtorList = GetKeyForMember(SemaRef.Context, Member, true); 1716198092Srdivacky 1717198092Srdivacky for (; curIndex < Last; curIndex++) 1718198092Srdivacky if (MemberInCtorList == AllBaseOrMembers[curIndex]) 1719198092Srdivacky break; 1720198092Srdivacky if (curIndex == Last) { 1721198092Srdivacky assert(PrevMember && "Member not in member list?!"); 1722198092Srdivacky // Initializer as specified in ctor-initializer list is out of order. 1723198092Srdivacky // Issue a warning diagnostic. 1724198092Srdivacky if (PrevMember->isBaseInitializer()) { 1725198092Srdivacky // Diagnostics is for an initialized base class. 1726198092Srdivacky Type *BaseClass = PrevMember->getBaseClass(); 1727206084Srdivacky SemaRef.Diag(PrevMember->getSourceLocation(), 1728206084Srdivacky diag::warn_base_initialized) 1729198092Srdivacky << QualType(BaseClass, 0); 1730198092Srdivacky } else { 1731198092Srdivacky FieldDecl *Field = PrevMember->getMember(); 1732206084Srdivacky SemaRef.Diag(PrevMember->getSourceLocation(), 1733206084Srdivacky diag::warn_field_initialized) 1734198092Srdivacky << Field->getNameAsString(); 1735198092Srdivacky } 1736198092Srdivacky // Also the note! 1737198092Srdivacky if (FieldDecl *Field = Member->getMember()) 1738206084Srdivacky SemaRef.Diag(Member->getSourceLocation(), 1739206084Srdivacky diag::note_fieldorbase_initialized_here) << 0 1740198092Srdivacky << Field->getNameAsString(); 1741198092Srdivacky else { 1742198092Srdivacky Type *BaseClass = Member->getBaseClass(); 1743206084Srdivacky SemaRef.Diag(Member->getSourceLocation(), 1744198092Srdivacky diag::note_fieldorbase_initialized_here) << 1 1745198092Srdivacky << QualType(BaseClass, 0); 1746198092Srdivacky } 1747198092Srdivacky for (curIndex = 0; curIndex < Last; curIndex++) 1748198092Srdivacky if (MemberInCtorList == AllBaseOrMembers[curIndex]) 1749198092Srdivacky break; 1750198092Srdivacky } 1751198092Srdivacky PrevMember = Member; 1752198092Srdivacky } 1753198092Srdivacky} 1754198092Srdivacky 1755206084Srdivacky/// ActOnMemInitializers - Handle the member initializers for a constructor. 1756206084Srdivackyvoid Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl, 1757206084Srdivacky SourceLocation ColonLoc, 1758206084Srdivacky MemInitTy **meminits, unsigned NumMemInits, 1759206084Srdivacky bool AnyErrors) { 1760206084Srdivacky if (!ConstructorDecl) 1761206084Srdivacky return; 1762206084Srdivacky 1763206084Srdivacky AdjustDeclIfTemplate(ConstructorDecl); 1764206084Srdivacky 1765206084Srdivacky CXXConstructorDecl *Constructor 1766206084Srdivacky = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>()); 1767206084Srdivacky 1768206084Srdivacky if (!Constructor) { 1769206084Srdivacky Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 1770206084Srdivacky return; 1771206084Srdivacky } 1772206084Srdivacky 1773206084Srdivacky CXXBaseOrMemberInitializer **MemInits = 1774206084Srdivacky reinterpret_cast<CXXBaseOrMemberInitializer **>(meminits); 1775206084Srdivacky 1776206084Srdivacky llvm::DenseMap<void*, CXXBaseOrMemberInitializer *> Members; 1777206084Srdivacky bool HadError = false; 1778206084Srdivacky for (unsigned i = 0; i < NumMemInits; i++) { 1779206084Srdivacky CXXBaseOrMemberInitializer *Member = MemInits[i]; 1780206084Srdivacky 1781206084Srdivacky void *KeyToMember = GetKeyForMember(Context, Member); 1782206084Srdivacky CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember]; 1783206084Srdivacky if (!PrevMember) { 1784206084Srdivacky PrevMember = Member; 1785206084Srdivacky continue; 1786206084Srdivacky } 1787206084Srdivacky if (FieldDecl *Field = Member->getMember()) 1788206084Srdivacky Diag(Member->getSourceLocation(), 1789206084Srdivacky diag::error_multiple_mem_initialization) 1790206084Srdivacky << Field->getNameAsString() 1791206084Srdivacky << Member->getSourceRange(); 1792206084Srdivacky else { 1793206084Srdivacky Type *BaseClass = Member->getBaseClass(); 1794206084Srdivacky assert(BaseClass && "ActOnMemInitializers - neither field or base"); 1795206084Srdivacky Diag(Member->getSourceLocation(), 1796206084Srdivacky diag::error_multiple_base_initialization) 1797206084Srdivacky << QualType(BaseClass, 0) 1798206084Srdivacky << Member->getSourceRange(); 1799206084Srdivacky } 1800206084Srdivacky Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer) 1801206084Srdivacky << 0; 1802206084Srdivacky HadError = true; 1803206084Srdivacky } 1804206084Srdivacky 1805206084Srdivacky if (HadError) 1806206084Srdivacky return; 1807206084Srdivacky 1808206084Srdivacky DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits); 1809206084Srdivacky 1810206084Srdivacky SetBaseOrMemberInitializers(Constructor, MemInits, NumMemInits, AnyErrors); 1811206084Srdivacky} 1812206084Srdivacky 1813198092Srdivackyvoid 1814205408SrdivackySema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 1815205408Srdivacky CXXRecordDecl *ClassDecl) { 1816205408Srdivacky // Ignore dependent contexts. 1817205408Srdivacky if (ClassDecl->isDependentContext()) 1818199482Srdivacky return; 1819205219Srdivacky 1820205219Srdivacky // FIXME: all the access-control diagnostics are positioned on the 1821205219Srdivacky // field/base declaration. That's probably good; that said, the 1822205219Srdivacky // user might reasonably want to know why the destructor is being 1823205219Srdivacky // emitted, and we currently don't say. 1824199482Srdivacky 1825199482Srdivacky // Non-static data members. 1826199482Srdivacky for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(), 1827199482Srdivacky E = ClassDecl->field_end(); I != E; ++I) { 1828199482Srdivacky FieldDecl *Field = *I; 1829199482Srdivacky 1830199482Srdivacky QualType FieldType = Context.getBaseElementType(Field->getType()); 1831199482Srdivacky 1832199482Srdivacky const RecordType* RT = FieldType->getAs<RecordType>(); 1833199482Srdivacky if (!RT) 1834195341Sed continue; 1835199482Srdivacky 1836199482Srdivacky CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 1837199482Srdivacky if (FieldClassDecl->hasTrivialDestructor()) 1838198092Srdivacky continue; 1839198092Srdivacky 1840205219Srdivacky CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor(Context); 1841205219Srdivacky CheckDestructorAccess(Field->getLocation(), Dtor, 1842206084Srdivacky PDiag(diag::err_access_dtor_field) 1843205219Srdivacky << Field->getDeclName() 1844205219Srdivacky << FieldType); 1845205219Srdivacky 1846205408Srdivacky MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 1847198092Srdivacky } 1848199482Srdivacky 1849205219Srdivacky llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 1850205219Srdivacky 1851199482Srdivacky // Bases. 1852199482Srdivacky for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 1853198092Srdivacky E = ClassDecl->bases_end(); Base != E; ++Base) { 1854205219Srdivacky // Bases are always records in a well-formed non-dependent class. 1855205219Srdivacky const RecordType *RT = Base->getType()->getAs<RecordType>(); 1856205219Srdivacky 1857205219Srdivacky // Remember direct virtual bases. 1858198092Srdivacky if (Base->isVirtual()) 1859205219Srdivacky DirectVirtualBases.insert(RT); 1860199482Srdivacky 1861199482Srdivacky // Ignore trivial destructors. 1862205219Srdivacky CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 1863199482Srdivacky if (BaseClassDecl->hasTrivialDestructor()) 1864198092Srdivacky continue; 1865205219Srdivacky 1866205219Srdivacky CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context); 1867205219Srdivacky 1868205219Srdivacky // FIXME: caret should be on the start of the class name 1869205219Srdivacky CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor, 1870206084Srdivacky PDiag(diag::err_access_dtor_base) 1871205219Srdivacky << Base->getType() 1872205219Srdivacky << Base->getSourceRange()); 1873199482Srdivacky 1874205408Srdivacky MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 1875199482Srdivacky } 1876199482Srdivacky 1877199482Srdivacky // Virtual bases. 1878199482Srdivacky for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 1879199482Srdivacky E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 1880205219Srdivacky 1881205219Srdivacky // Bases are always records in a well-formed non-dependent class. 1882205219Srdivacky const RecordType *RT = VBase->getType()->getAs<RecordType>(); 1883205219Srdivacky 1884205219Srdivacky // Ignore direct virtual bases. 1885205219Srdivacky if (DirectVirtualBases.count(RT)) 1886205219Srdivacky continue; 1887205219Srdivacky 1888199482Srdivacky // Ignore trivial destructors. 1889205219Srdivacky CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 1890198092Srdivacky if (BaseClassDecl->hasTrivialDestructor()) 1891198092Srdivacky continue; 1892205219Srdivacky 1893205219Srdivacky CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context); 1894205219Srdivacky CheckDestructorAccess(ClassDecl->getLocation(), Dtor, 1895206084Srdivacky PDiag(diag::err_access_dtor_vbase) 1896205219Srdivacky << VBase->getType()); 1897205219Srdivacky 1898205408Srdivacky MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 1899198092Srdivacky } 1900193326Sed} 1901193326Sed 1902198092Srdivackyvoid Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) { 1903198092Srdivacky if (!CDtorDecl) 1904198092Srdivacky return; 1905198092Srdivacky 1906198092Srdivacky if (CXXConstructorDecl *Constructor 1907198092Srdivacky = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>())) 1908206084Srdivacky SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false); 1909198092Srdivacky} 1910198092Srdivacky 1911198092Srdivackybool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 1912193326Sed unsigned DiagID, AbstractDiagSelID SelID, 1913193326Sed const CXXRecordDecl *CurrentRD) { 1914198092Srdivacky if (SelID == -1) 1915198092Srdivacky return RequireNonAbstractType(Loc, T, 1916198092Srdivacky PDiag(DiagID), CurrentRD); 1917198092Srdivacky else 1918198092Srdivacky return RequireNonAbstractType(Loc, T, 1919198092Srdivacky PDiag(DiagID) << SelID, CurrentRD); 1920198092Srdivacky} 1921198092Srdivacky 1922198092Srdivackybool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 1923198092Srdivacky const PartialDiagnostic &PD, 1924198092Srdivacky const CXXRecordDecl *CurrentRD) { 1925193326Sed if (!getLangOptions().CPlusPlus) 1926193326Sed return false; 1927198092Srdivacky 1928193326Sed if (const ArrayType *AT = Context.getAsArrayType(T)) 1929198092Srdivacky return RequireNonAbstractType(Loc, AT->getElementType(), PD, 1930193326Sed CurrentRD); 1931198092Srdivacky 1932198092Srdivacky if (const PointerType *PT = T->getAs<PointerType>()) { 1933193326Sed // Find the innermost pointer type. 1934198092Srdivacky while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 1935193326Sed PT = T; 1936198092Srdivacky 1937193326Sed if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 1938198092Srdivacky return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD); 1939193326Sed } 1940198092Srdivacky 1941198092Srdivacky const RecordType *RT = T->getAs<RecordType>(); 1942193326Sed if (!RT) 1943193326Sed return false; 1944198092Srdivacky 1945203955Srdivacky const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 1946193326Sed 1947193326Sed if (CurrentRD && CurrentRD != RD) 1948193326Sed return false; 1949198092Srdivacky 1950203955Srdivacky // FIXME: is this reasonable? It matches current behavior, but.... 1951203955Srdivacky if (!RD->getDefinition()) 1952203955Srdivacky return false; 1953203955Srdivacky 1954193326Sed if (!RD->isAbstract()) 1955193326Sed return false; 1956198092Srdivacky 1957198092Srdivacky Diag(Loc, PD) << RD->getDeclName(); 1958198092Srdivacky 1959193326Sed // Check if we've already emitted the list of pure virtual functions for this 1960193326Sed // class. 1961193326Sed if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 1962193326Sed return true; 1963198092Srdivacky 1964206084Srdivacky CXXFinalOverriderMap FinalOverriders; 1965206084Srdivacky RD->getFinalOverriders(FinalOverriders); 1966198092Srdivacky 1967206084Srdivacky for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 1968206084Srdivacky MEnd = FinalOverriders.end(); 1969206084Srdivacky M != MEnd; 1970206084Srdivacky ++M) { 1971206084Srdivacky for (OverridingMethods::iterator SO = M->second.begin(), 1972206084Srdivacky SOEnd = M->second.end(); 1973206084Srdivacky SO != SOEnd; ++SO) { 1974206084Srdivacky // C++ [class.abstract]p4: 1975206084Srdivacky // A class is abstract if it contains or inherits at least one 1976206084Srdivacky // pure virtual function for which the final overrider is pure 1977206084Srdivacky // virtual. 1978198092Srdivacky 1979206084Srdivacky // 1980206084Srdivacky if (SO->second.size() != 1) 1981206084Srdivacky continue; 1982206084Srdivacky 1983206084Srdivacky if (!SO->second.front().Method->isPure()) 1984206084Srdivacky continue; 1985206084Srdivacky 1986206084Srdivacky Diag(SO->second.front().Method->getLocation(), 1987206084Srdivacky diag::note_pure_virtual_function) 1988206084Srdivacky << SO->second.front().Method->getDeclName(); 1989206084Srdivacky } 1990193326Sed } 1991193326Sed 1992193326Sed if (!PureVirtualClassDiagSet) 1993193326Sed PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 1994193326Sed PureVirtualClassDiagSet->insert(RD); 1995198092Srdivacky 1996193326Sed return true; 1997193326Sed} 1998193326Sed 1999193326Sednamespace { 2000199990Srdivacky class AbstractClassUsageDiagnoser 2001193326Sed : public DeclVisitor<AbstractClassUsageDiagnoser, bool> { 2002193326Sed Sema &SemaRef; 2003193326Sed CXXRecordDecl *AbstractClass; 2004198092Srdivacky 2005193326Sed bool VisitDeclContext(const DeclContext *DC) { 2006193326Sed bool Invalid = false; 2007193326Sed 2008195341Sed for (CXXRecordDecl::decl_iterator I = DC->decls_begin(), 2009195341Sed E = DC->decls_end(); I != E; ++I) 2010193326Sed Invalid |= Visit(*I); 2011193326Sed 2012193326Sed return Invalid; 2013193326Sed } 2014198092Srdivacky 2015193326Sed public: 2016193326Sed AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac) 2017193326Sed : SemaRef(SemaRef), AbstractClass(ac) { 2018193326Sed Visit(SemaRef.Context.getTranslationUnitDecl()); 2019193326Sed } 2020193326Sed 2021193326Sed bool VisitFunctionDecl(const FunctionDecl *FD) { 2022193326Sed if (FD->isThisDeclarationADefinition()) { 2023193326Sed // No need to do the check if we're in a definition, because it requires 2024193326Sed // that the return/param types are complete. 2025198092Srdivacky // because that requires 2026193326Sed return VisitDeclContext(FD); 2027193326Sed } 2028198092Srdivacky 2029193326Sed // Check the return type. 2030198092Srdivacky QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType(); 2031198092Srdivacky bool Invalid = 2032193326Sed SemaRef.RequireNonAbstractType(FD->getLocation(), RTy, 2033193326Sed diag::err_abstract_type_in_decl, 2034193326Sed Sema::AbstractReturnType, 2035193326Sed AbstractClass); 2036193326Sed 2037198092Srdivacky for (FunctionDecl::param_const_iterator I = FD->param_begin(), 2038193326Sed E = FD->param_end(); I != E; ++I) { 2039193326Sed const ParmVarDecl *VD = *I; 2040198092Srdivacky Invalid |= 2041193326Sed SemaRef.RequireNonAbstractType(VD->getLocation(), 2042198092Srdivacky VD->getOriginalType(), 2043198092Srdivacky diag::err_abstract_type_in_decl, 2044193326Sed Sema::AbstractParamType, 2045193326Sed AbstractClass); 2046193326Sed } 2047193326Sed 2048193326Sed return Invalid; 2049193326Sed } 2050198092Srdivacky 2051193326Sed bool VisitDecl(const Decl* D) { 2052193326Sed if (const DeclContext *DC = dyn_cast<DeclContext>(D)) 2053193326Sed return VisitDeclContext(DC); 2054198092Srdivacky 2055193326Sed return false; 2056193326Sed } 2057193326Sed }; 2058193326Sed} 2059193326Sed 2060200583Srdivacky/// \brief Perform semantic checks on a class definition that has been 2061200583Srdivacky/// completing, introducing implicitly-declared members, checking for 2062200583Srdivacky/// abstract types, etc. 2063200583Srdivackyvoid Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 2064200583Srdivacky if (!Record || Record->isInvalidDecl()) 2065200583Srdivacky return; 2066200583Srdivacky 2067201361Srdivacky if (!Record->isDependentType()) 2068201361Srdivacky AddImplicitlyDeclaredMembersToClass(Record); 2069202379Srdivacky 2070201361Srdivacky if (Record->isInvalidDecl()) 2071201361Srdivacky return; 2072201361Srdivacky 2073203955Srdivacky // Set access bits correctly on the directly-declared conversions. 2074203955Srdivacky UnresolvedSetImpl *Convs = Record->getConversionFunctions(); 2075203955Srdivacky for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end(); I != E; ++I) 2076203955Srdivacky Convs->setAccess(I, (*I)->getAccess()); 2077203955Srdivacky 2078206084Srdivacky // Determine whether we need to check for final overriders. We do 2079206084Srdivacky // this either when there are virtual base classes (in which case we 2080206084Srdivacky // may end up finding multiple final overriders for a given virtual 2081206084Srdivacky // function) or any of the base classes is abstract (in which case 2082206084Srdivacky // we might detect that this class is abstract). 2083206084Srdivacky bool CheckFinalOverriders = false; 2084206084Srdivacky if (Record->isPolymorphic() && !Record->isInvalidDecl() && 2085206084Srdivacky !Record->isDependentType()) { 2086206084Srdivacky if (Record->getNumVBases()) 2087206084Srdivacky CheckFinalOverriders = true; 2088206084Srdivacky else if (!Record->isAbstract()) { 2089206084Srdivacky for (CXXRecordDecl::base_class_const_iterator B = Record->bases_begin(), 2090206084Srdivacky BEnd = Record->bases_end(); 2091206084Srdivacky B != BEnd; ++B) { 2092206084Srdivacky CXXRecordDecl *BaseDecl 2093206084Srdivacky = cast<CXXRecordDecl>(B->getType()->getAs<RecordType>()->getDecl()); 2094206084Srdivacky if (BaseDecl->isAbstract()) { 2095206084Srdivacky CheckFinalOverriders = true; 2096206084Srdivacky break; 2097206084Srdivacky } 2098206084Srdivacky } 2099206084Srdivacky } 2100200583Srdivacky } 2101200583Srdivacky 2102206084Srdivacky if (CheckFinalOverriders) { 2103206084Srdivacky CXXFinalOverriderMap FinalOverriders; 2104206084Srdivacky Record->getFinalOverriders(FinalOverriders); 2105206084Srdivacky 2106206084Srdivacky for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 2107206084Srdivacky MEnd = FinalOverriders.end(); 2108206084Srdivacky M != MEnd; ++M) { 2109206084Srdivacky for (OverridingMethods::iterator SO = M->second.begin(), 2110206084Srdivacky SOEnd = M->second.end(); 2111206084Srdivacky SO != SOEnd; ++SO) { 2112206084Srdivacky assert(SO->second.size() > 0 && 2113206084Srdivacky "All virtual functions have overridding virtual functions"); 2114206084Srdivacky if (SO->second.size() == 1) { 2115206084Srdivacky // C++ [class.abstract]p4: 2116206084Srdivacky // A class is abstract if it contains or inherits at least one 2117206084Srdivacky // pure virtual function for which the final overrider is pure 2118206084Srdivacky // virtual. 2119206084Srdivacky if (SO->second.front().Method->isPure()) 2120206084Srdivacky Record->setAbstract(true); 2121206084Srdivacky continue; 2122206084Srdivacky } 2123206084Srdivacky 2124206084Srdivacky // C++ [class.virtual]p2: 2125206084Srdivacky // In a derived class, if a virtual member function of a base 2126206084Srdivacky // class subobject has more than one final overrider the 2127206084Srdivacky // program is ill-formed. 2128206084Srdivacky Diag(Record->getLocation(), diag::err_multiple_final_overriders) 2129206084Srdivacky << (NamedDecl *)M->first << Record; 2130206084Srdivacky Diag(M->first->getLocation(), diag::note_overridden_virtual_function); 2131206084Srdivacky for (OverridingMethods::overriding_iterator OM = SO->second.begin(), 2132206084Srdivacky OMEnd = SO->second.end(); 2133206084Srdivacky OM != OMEnd; ++OM) 2134206084Srdivacky Diag(OM->Method->getLocation(), diag::note_final_overrider) 2135206084Srdivacky << (NamedDecl *)M->first << OM->Method->getParent(); 2136206084Srdivacky 2137206084Srdivacky Record->setInvalidDecl(); 2138206084Srdivacky } 2139206084Srdivacky } 2140206084Srdivacky } 2141206084Srdivacky 2142206084Srdivacky if (Record->isAbstract() && !Record->isInvalidDecl()) 2143200583Srdivacky (void)AbstractClassUsageDiagnoser(*this, Record); 2144200583Srdivacky} 2145200583Srdivacky 2146193326Sedvoid Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 2147193326Sed DeclPtrTy TagDecl, 2148193326Sed SourceLocation LBrac, 2149206084Srdivacky SourceLocation RBrac, 2150206084Srdivacky AttributeList *AttrList) { 2151194711Sed if (!TagDecl) 2152194711Sed return; 2153198092Srdivacky 2154193326Sed AdjustDeclIfTemplate(TagDecl); 2155200583Srdivacky 2156193326Sed ActOnFields(S, RLoc, TagDecl, 2157193326Sed (DeclPtrTy*)FieldCollector->getCurFields(), 2158206084Srdivacky FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList); 2159193326Sed 2160200583Srdivacky CheckCompletedCXXClass( 2161200583Srdivacky dyn_cast_or_null<CXXRecordDecl>(TagDecl.getAs<Decl>())); 2162193326Sed} 2163193326Sed 2164193326Sed/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 2165193326Sed/// special functions, such as the default constructor, copy 2166193326Sed/// constructor, or destructor, to the given C++ class (C++ 2167193326Sed/// [special]p1). This routine can only be executed just before the 2168193326Sed/// definition of the class is complete. 2169193326Sedvoid Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 2170198092Srdivacky CanQualType ClassType 2171198092Srdivacky = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 2172193326Sed 2173193326Sed // FIXME: Implicit declarations have exception specifications, which are 2174193326Sed // the union of the specifications of the implicitly called functions. 2175193326Sed 2176193326Sed if (!ClassDecl->hasUserDeclaredConstructor()) { 2177193326Sed // C++ [class.ctor]p5: 2178193326Sed // A default constructor for a class X is a constructor of class X 2179193326Sed // that can be called without an argument. If there is no 2180193326Sed // user-declared constructor for class X, a default constructor is 2181193326Sed // implicitly declared. An implicitly-declared default constructor 2182193326Sed // is an inline public member of its class. 2183198092Srdivacky DeclarationName Name 2184193326Sed = Context.DeclarationNames.getCXXConstructorName(ClassType); 2185198092Srdivacky CXXConstructorDecl *DefaultCon = 2186193326Sed CXXConstructorDecl::Create(Context, ClassDecl, 2187193326Sed ClassDecl->getLocation(), Name, 2188193326Sed Context.getFunctionType(Context.VoidTy, 2189204643Srdivacky 0, 0, false, 0, 2190204643Srdivacky /*FIXME*/false, false, 2191206084Srdivacky 0, 0, 2192206084Srdivacky FunctionType::ExtInfo()), 2193200583Srdivacky /*TInfo=*/0, 2194193326Sed /*isExplicit=*/false, 2195193326Sed /*isInline=*/true, 2196193326Sed /*isImplicitlyDeclared=*/true); 2197193326Sed DefaultCon->setAccess(AS_public); 2198193326Sed DefaultCon->setImplicit(); 2199198092Srdivacky DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor()); 2200195341Sed ClassDecl->addDecl(DefaultCon); 2201193326Sed } 2202193326Sed 2203193326Sed if (!ClassDecl->hasUserDeclaredCopyConstructor()) { 2204193326Sed // C++ [class.copy]p4: 2205193326Sed // If the class definition does not explicitly declare a copy 2206193326Sed // constructor, one is declared implicitly. 2207193326Sed 2208193326Sed // C++ [class.copy]p5: 2209193326Sed // The implicitly-declared copy constructor for a class X will 2210193326Sed // have the form 2211193326Sed // 2212193326Sed // X::X(const X&) 2213193326Sed // 2214193326Sed // if 2215193326Sed bool HasConstCopyConstructor = true; 2216193326Sed 2217193326Sed // -- each direct or virtual base class B of X has a copy 2218193326Sed // constructor whose first parameter is of type const B& or 2219193326Sed // const volatile B&, and 2220193326Sed for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(); 2221193326Sed HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) { 2222193326Sed const CXXRecordDecl *BaseClassDecl 2223198092Srdivacky = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 2224198092Srdivacky HasConstCopyConstructor 2225193326Sed = BaseClassDecl->hasConstCopyConstructor(Context); 2226193326Sed } 2227193326Sed 2228193326Sed // -- for all the nonstatic data members of X that are of a 2229193326Sed // class type M (or array thereof), each such class type 2230193326Sed // has a copy constructor whose first parameter is of type 2231193326Sed // const M& or const volatile M&. 2232195341Sed for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(); 2233195341Sed HasConstCopyConstructor && Field != ClassDecl->field_end(); 2234193326Sed ++Field) { 2235193326Sed QualType FieldType = (*Field)->getType(); 2236193326Sed if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 2237193326Sed FieldType = Array->getElementType(); 2238198092Srdivacky if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 2239198092Srdivacky const CXXRecordDecl *FieldClassDecl 2240193326Sed = cast<CXXRecordDecl>(FieldClassType->getDecl()); 2241198092Srdivacky HasConstCopyConstructor 2242193326Sed = FieldClassDecl->hasConstCopyConstructor(Context); 2243193326Sed } 2244193326Sed } 2245193326Sed 2246193326Sed // Otherwise, the implicitly declared copy constructor will have 2247193326Sed // the form 2248193326Sed // 2249193326Sed // X::X(X&) 2250193326Sed QualType ArgType = ClassType; 2251193326Sed if (HasConstCopyConstructor) 2252193326Sed ArgType = ArgType.withConst(); 2253193326Sed ArgType = Context.getLValueReferenceType(ArgType); 2254193326Sed 2255193326Sed // An implicitly-declared copy constructor is an inline public 2256193326Sed // member of its class. 2257198092Srdivacky DeclarationName Name 2258193326Sed = Context.DeclarationNames.getCXXConstructorName(ClassType); 2259193326Sed CXXConstructorDecl *CopyConstructor 2260193326Sed = CXXConstructorDecl::Create(Context, ClassDecl, 2261193326Sed ClassDecl->getLocation(), Name, 2262193326Sed Context.getFunctionType(Context.VoidTy, 2263193326Sed &ArgType, 1, 2264204643Srdivacky false, 0, 2265204643Srdivacky /*FIXME:*/false, 2266206084Srdivacky false, 0, 0, 2267206084Srdivacky FunctionType::ExtInfo()), 2268200583Srdivacky /*TInfo=*/0, 2269193326Sed /*isExplicit=*/false, 2270193326Sed /*isInline=*/true, 2271193326Sed /*isImplicitlyDeclared=*/true); 2272193326Sed CopyConstructor->setAccess(AS_public); 2273193326Sed CopyConstructor->setImplicit(); 2274198092Srdivacky CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor()); 2275193326Sed 2276193326Sed // Add the parameter to the constructor. 2277193326Sed ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 2278193326Sed ClassDecl->getLocation(), 2279193326Sed /*IdentifierInfo=*/0, 2280200583Srdivacky ArgType, /*TInfo=*/0, 2281198092Srdivacky VarDecl::None, 0); 2282203955Srdivacky CopyConstructor->setParams(&FromParam, 1); 2283195341Sed ClassDecl->addDecl(CopyConstructor); 2284193326Sed } 2285193326Sed 2286193326Sed if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 2287193326Sed // Note: The following rules are largely analoguous to the copy 2288193326Sed // constructor rules. Note that virtual bases are not taken into account 2289193326Sed // for determining the argument type of the operator. Note also that 2290193326Sed // operators taking an object instead of a reference are allowed. 2291193326Sed // 2292193326Sed // C++ [class.copy]p10: 2293193326Sed // If the class definition does not explicitly declare a copy 2294193326Sed // assignment operator, one is declared implicitly. 2295193326Sed // The implicitly-defined copy assignment operator for a class X 2296193326Sed // will have the form 2297193326Sed // 2298193326Sed // X& X::operator=(const X&) 2299193326Sed // 2300193326Sed // if 2301193326Sed bool HasConstCopyAssignment = true; 2302193326Sed 2303193326Sed // -- each direct base class B of X has a copy assignment operator 2304193326Sed // whose parameter is of type const B&, const volatile B& or B, 2305193326Sed // and 2306193326Sed for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(); 2307193326Sed HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) { 2308198893Srdivacky assert(!Base->getType()->isDependentType() && 2309198893Srdivacky "Cannot generate implicit members for class with dependent bases."); 2310193326Sed const CXXRecordDecl *BaseClassDecl 2311198092Srdivacky = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 2312198092Srdivacky const CXXMethodDecl *MD = 0; 2313198092Srdivacky HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context, 2314198092Srdivacky MD); 2315193326Sed } 2316193326Sed 2317193326Sed // -- for all the nonstatic data members of X that are of a class 2318193326Sed // type M (or array thereof), each such class type has a copy 2319193326Sed // assignment operator whose parameter is of type const M&, 2320193326Sed // const volatile M& or M. 2321195341Sed for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(); 2322195341Sed HasConstCopyAssignment && Field != ClassDecl->field_end(); 2323193326Sed ++Field) { 2324193326Sed QualType FieldType = (*Field)->getType(); 2325193326Sed if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 2326193326Sed FieldType = Array->getElementType(); 2327198092Srdivacky if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 2328193326Sed const CXXRecordDecl *FieldClassDecl 2329193326Sed = cast<CXXRecordDecl>(FieldClassType->getDecl()); 2330198092Srdivacky const CXXMethodDecl *MD = 0; 2331193326Sed HasConstCopyAssignment 2332198092Srdivacky = FieldClassDecl->hasConstCopyAssignment(Context, MD); 2333193326Sed } 2334193326Sed } 2335193326Sed 2336193326Sed // Otherwise, the implicitly declared copy assignment operator will 2337193326Sed // have the form 2338193326Sed // 2339193326Sed // X& X::operator=(X&) 2340193326Sed QualType ArgType = ClassType; 2341193326Sed QualType RetType = Context.getLValueReferenceType(ArgType); 2342193326Sed if (HasConstCopyAssignment) 2343193326Sed ArgType = ArgType.withConst(); 2344193326Sed ArgType = Context.getLValueReferenceType(ArgType); 2345193326Sed 2346193326Sed // An implicitly-declared copy assignment operator is an inline public 2347193326Sed // member of its class. 2348193326Sed DeclarationName Name = 2349193326Sed Context.DeclarationNames.getCXXOperatorName(OO_Equal); 2350193326Sed CXXMethodDecl *CopyAssignment = 2351193326Sed CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name, 2352193326Sed Context.getFunctionType(RetType, &ArgType, 1, 2353204643Srdivacky false, 0, 2354204643Srdivacky /*FIXME:*/false, 2355206084Srdivacky false, 0, 0, 2356206084Srdivacky FunctionType::ExtInfo()), 2357200583Srdivacky /*TInfo=*/0, /*isStatic=*/false, /*isInline=*/true); 2358193326Sed CopyAssignment->setAccess(AS_public); 2359193326Sed CopyAssignment->setImplicit(); 2360198092Srdivacky CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment()); 2361198092Srdivacky CopyAssignment->setCopyAssignment(true); 2362193326Sed 2363193326Sed // Add the parameter to the operator. 2364193326Sed ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 2365193326Sed ClassDecl->getLocation(), 2366193326Sed /*IdentifierInfo=*/0, 2367200583Srdivacky ArgType, /*TInfo=*/0, 2368198092Srdivacky VarDecl::None, 0); 2369203955Srdivacky CopyAssignment->setParams(&FromParam, 1); 2370193326Sed 2371193326Sed // Don't call addedAssignmentOperator. There is no way to distinguish an 2372193326Sed // implicit from an explicit assignment operator. 2373195341Sed ClassDecl->addDecl(CopyAssignment); 2374200583Srdivacky AddOverriddenMethods(ClassDecl, CopyAssignment); 2375193326Sed } 2376193326Sed 2377193326Sed if (!ClassDecl->hasUserDeclaredDestructor()) { 2378193326Sed // C++ [class.dtor]p2: 2379193326Sed // If a class has no user-declared destructor, a destructor is 2380193326Sed // declared implicitly. An implicitly-declared destructor is an 2381193326Sed // inline public member of its class. 2382205219Srdivacky QualType Ty = Context.getFunctionType(Context.VoidTy, 2383205219Srdivacky 0, 0, false, 0, 2384205219Srdivacky /*FIXME:*/false, 2385206084Srdivacky false, 0, 0, FunctionType::ExtInfo()); 2386205219Srdivacky 2387198092Srdivacky DeclarationName Name 2388193326Sed = Context.DeclarationNames.getCXXDestructorName(ClassType); 2389198092Srdivacky CXXDestructorDecl *Destructor 2390193326Sed = CXXDestructorDecl::Create(Context, ClassDecl, 2391205219Srdivacky ClassDecl->getLocation(), Name, Ty, 2392193326Sed /*isInline=*/true, 2393193326Sed /*isImplicitlyDeclared=*/true); 2394193326Sed Destructor->setAccess(AS_public); 2395193326Sed Destructor->setImplicit(); 2396198092Srdivacky Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 2397195341Sed ClassDecl->addDecl(Destructor); 2398205219Srdivacky 2399205219Srdivacky // This could be uniqued if it ever proves significant. 2400205219Srdivacky Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty)); 2401199990Srdivacky 2402199990Srdivacky AddOverriddenMethods(ClassDecl, Destructor); 2403193326Sed } 2404193326Sed} 2405193326Sed 2406193326Sedvoid Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) { 2407198092Srdivacky Decl *D = TemplateD.getAs<Decl>(); 2408198092Srdivacky if (!D) 2409193326Sed return; 2410198092Srdivacky 2411198092Srdivacky TemplateParameterList *Params = 0; 2412198092Srdivacky if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) 2413198092Srdivacky Params = Template->getTemplateParameters(); 2414198092Srdivacky else if (ClassTemplatePartialSpecializationDecl *PartialSpec 2415198092Srdivacky = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 2416198092Srdivacky Params = PartialSpec->getTemplateParameters(); 2417198092Srdivacky else 2418198092Srdivacky return; 2419193326Sed 2420193326Sed for (TemplateParameterList::iterator Param = Params->begin(), 2421193326Sed ParamEnd = Params->end(); 2422193326Sed Param != ParamEnd; ++Param) { 2423193326Sed NamedDecl *Named = cast<NamedDecl>(*Param); 2424193326Sed if (Named->getDeclName()) { 2425193326Sed S->AddDecl(DeclPtrTy::make(Named)); 2426193326Sed IdResolver.AddDecl(Named); 2427193326Sed } 2428193326Sed } 2429193326Sed} 2430193326Sed 2431201361Srdivackyvoid Sema::ActOnStartDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) { 2432201361Srdivacky if (!RecordD) return; 2433201361Srdivacky AdjustDeclIfTemplate(RecordD); 2434201361Srdivacky CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD.getAs<Decl>()); 2435201361Srdivacky PushDeclContext(S, Record); 2436201361Srdivacky} 2437201361Srdivacky 2438201361Srdivackyvoid Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) { 2439201361Srdivacky if (!RecordD) return; 2440201361Srdivacky PopDeclContext(); 2441201361Srdivacky} 2442201361Srdivacky 2443193326Sed/// ActOnStartDelayedCXXMethodDeclaration - We have completed 2444193326Sed/// parsing a top-level (non-nested) C++ class, and we are now 2445193326Sed/// parsing those parts of the given Method declaration that could 2446193326Sed/// not be parsed earlier (C++ [class.mem]p2), such as default 2447193326Sed/// arguments. This action should enter the scope of the given 2448193326Sed/// Method declaration as if we had just parsed the qualified method 2449193326Sed/// name. However, it should not bring the parameters into scope; 2450193326Sed/// that will be performed by ActOnDelayedCXXMethodParameter. 2451193326Sedvoid Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) { 2452193326Sed} 2453193326Sed 2454193326Sed/// ActOnDelayedCXXMethodParameter - We've already started a delayed 2455193326Sed/// C++ method declaration. We're (re-)introducing the given 2456193326Sed/// function parameter into scope for use in parsing later parts of 2457193326Sed/// the method declaration. For example, we could see an 2458193326Sed/// ActOnParamDefaultArgument event for this parameter. 2459193326Sedvoid Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) { 2460194711Sed if (!ParamD) 2461194711Sed return; 2462198092Srdivacky 2463193326Sed ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>()); 2464193326Sed 2465193326Sed // If this parameter has an unparsed default argument, clear it out 2466193326Sed // to make way for the parsed default argument. 2467193326Sed if (Param->hasUnparsedDefaultArg()) 2468193326Sed Param->setDefaultArg(0); 2469193326Sed 2470193326Sed S->AddDecl(DeclPtrTy::make(Param)); 2471193326Sed if (Param->getDeclName()) 2472193326Sed IdResolver.AddDecl(Param); 2473193326Sed} 2474193326Sed 2475193326Sed/// ActOnFinishDelayedCXXMethodDeclaration - We have finished 2476193326Sed/// processing the delayed method declaration for Method. The method 2477193326Sed/// declaration is now considered finished. There may be a separate 2478193326Sed/// ActOnStartOfFunctionDef action later (not necessarily 2479193326Sed/// immediately!) for this method, if it was also defined inside the 2480193326Sed/// class body. 2481193326Sedvoid Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) { 2482194711Sed if (!MethodD) 2483194711Sed return; 2484198092Srdivacky 2485198092Srdivacky AdjustDeclIfTemplate(MethodD); 2486198092Srdivacky 2487193326Sed FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>()); 2488193326Sed 2489193326Sed // Now that we have our default arguments, check the constructor 2490193326Sed // again. It could produce additional diagnostics or affect whether 2491193326Sed // the class has implicitly-declared destructors, among other 2492193326Sed // things. 2493193326Sed if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 2494193326Sed CheckConstructor(Constructor); 2495193326Sed 2496193326Sed // Check the default arguments, which we may have added. 2497193326Sed if (!Method->isInvalidDecl()) 2498193326Sed CheckCXXDefaultArguments(Method); 2499193326Sed} 2500193326Sed 2501193326Sed/// CheckConstructorDeclarator - Called by ActOnDeclarator to check 2502193326Sed/// the well-formedness of the constructor declarator @p D with type @p 2503193326Sed/// R. If there are any errors in the declarator, this routine will 2504193326Sed/// emit diagnostics and set the invalid bit to true. In any case, the type 2505193326Sed/// will be updated to reflect a well-formed type for the constructor and 2506193326Sed/// returned. 2507193326SedQualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 2508193326Sed FunctionDecl::StorageClass &SC) { 2509193326Sed bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 2510193326Sed 2511193326Sed // C++ [class.ctor]p3: 2512193326Sed // A constructor shall not be virtual (10.3) or static (9.4). A 2513193326Sed // constructor can be invoked for a const, volatile or const 2514193326Sed // volatile object. A constructor shall not be declared const, 2515193326Sed // volatile, or const volatile (9.3.2). 2516193326Sed if (isVirtual) { 2517193326Sed if (!D.isInvalidType()) 2518193326Sed Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 2519193326Sed << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 2520193326Sed << SourceRange(D.getIdentifierLoc()); 2521193326Sed D.setInvalidType(); 2522193326Sed } 2523193326Sed if (SC == FunctionDecl::Static) { 2524193326Sed if (!D.isInvalidType()) 2525193326Sed Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 2526193326Sed << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 2527193326Sed << SourceRange(D.getIdentifierLoc()); 2528193326Sed D.setInvalidType(); 2529193326Sed SC = FunctionDecl::None; 2530193326Sed } 2531198092Srdivacky 2532193326Sed DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 2533193326Sed if (FTI.TypeQuals != 0) { 2534198092Srdivacky if (FTI.TypeQuals & Qualifiers::Const) 2535193326Sed Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 2536193326Sed << "const" << SourceRange(D.getIdentifierLoc()); 2537198092Srdivacky if (FTI.TypeQuals & Qualifiers::Volatile) 2538193326Sed Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 2539193326Sed << "volatile" << SourceRange(D.getIdentifierLoc()); 2540198092Srdivacky if (FTI.TypeQuals & Qualifiers::Restrict) 2541193326Sed Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 2542193326Sed << "restrict" << SourceRange(D.getIdentifierLoc()); 2543193326Sed } 2544198092Srdivacky 2545193326Sed // Rebuild the function type "R" without any type qualifiers (in 2546193326Sed // case any of the errors above fired) and with "void" as the 2547193326Sed // return type, since constructors don't have return types. We 2548193326Sed // *always* have to do this, because GetTypeForDeclarator will 2549193326Sed // put in a result type of "int" when none was specified. 2550198092Srdivacky const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 2551193326Sed return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(), 2552193326Sed Proto->getNumArgs(), 2553204643Srdivacky Proto->isVariadic(), 0, 2554204643Srdivacky Proto->hasExceptionSpec(), 2555204643Srdivacky Proto->hasAnyExceptionSpec(), 2556204643Srdivacky Proto->getNumExceptions(), 2557204643Srdivacky Proto->exception_begin(), 2558206084Srdivacky Proto->getExtInfo()); 2559193326Sed} 2560193326Sed 2561193326Sed/// CheckConstructor - Checks a fully-formed constructor for 2562193326Sed/// well-formedness, issuing any diagnostics required. Returns true if 2563193326Sed/// the constructor declarator is invalid. 2564193326Sedvoid Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 2565198092Srdivacky CXXRecordDecl *ClassDecl 2566193326Sed = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 2567193326Sed if (!ClassDecl) 2568193326Sed return Constructor->setInvalidDecl(); 2569193326Sed 2570193326Sed // C++ [class.copy]p3: 2571193326Sed // A declaration of a constructor for a class X is ill-formed if 2572193326Sed // its first parameter is of type (optionally cv-qualified) X and 2573193326Sed // either there are no other parameters or else all other 2574193326Sed // parameters have default arguments. 2575193326Sed if (!Constructor->isInvalidDecl() && 2576198092Srdivacky ((Constructor->getNumParams() == 1) || 2577198092Srdivacky (Constructor->getNumParams() > 1 && 2578199482Srdivacky Constructor->getParamDecl(1)->hasDefaultArg())) && 2579199482Srdivacky Constructor->getTemplateSpecializationKind() 2580199482Srdivacky != TSK_ImplicitInstantiation) { 2581193326Sed QualType ParamType = Constructor->getParamDecl(0)->getType(); 2582193326Sed QualType ClassTy = Context.getTagDeclType(ClassDecl); 2583193326Sed if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 2584193326Sed SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 2585193326Sed Diag(ParamLoc, diag::err_constructor_byvalue_arg) 2586206084Srdivacky << FixItHint::CreateInsertion(ParamLoc, " const &"); 2587199482Srdivacky 2588199482Srdivacky // FIXME: Rather that making the constructor invalid, we should endeavor 2589199482Srdivacky // to fix the type. 2590193326Sed Constructor->setInvalidDecl(); 2591193326Sed } 2592193326Sed } 2593198092Srdivacky 2594193326Sed // Notify the class that we've added a constructor. 2595193326Sed ClassDecl->addedConstructor(Context, Constructor); 2596193326Sed} 2597193326Sed 2598199990Srdivacky/// CheckDestructor - Checks a fully-formed destructor for well-formedness, 2599199990Srdivacky/// issuing any diagnostics required. Returns true on error. 2600199990Srdivackybool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 2601199482Srdivacky CXXRecordDecl *RD = Destructor->getParent(); 2602199482Srdivacky 2603199482Srdivacky if (Destructor->isVirtual()) { 2604199482Srdivacky SourceLocation Loc; 2605199482Srdivacky 2606199482Srdivacky if (!Destructor->isImplicit()) 2607199482Srdivacky Loc = Destructor->getLocation(); 2608199482Srdivacky else 2609199482Srdivacky Loc = RD->getLocation(); 2610199482Srdivacky 2611199482Srdivacky // If we have a virtual destructor, look up the deallocation function 2612199482Srdivacky FunctionDecl *OperatorDelete = 0; 2613199482Srdivacky DeclarationName Name = 2614199482Srdivacky Context.DeclarationNames.getCXXOperatorName(OO_Delete); 2615199990Srdivacky if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 2616199990Srdivacky return true; 2617199990Srdivacky 2618199990Srdivacky Destructor->setOperatorDelete(OperatorDelete); 2619199482Srdivacky } 2620199990Srdivacky 2621199990Srdivacky return false; 2622199482Srdivacky} 2623199482Srdivacky 2624198092Srdivackystatic inline bool 2625193326SedFTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) { 2626193326Sed return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 2627193326Sed FTI.ArgInfo[0].Param && 2628193326Sed FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType()); 2629193326Sed} 2630193326Sed 2631193326Sed/// CheckDestructorDeclarator - Called by ActOnDeclarator to check 2632193326Sed/// the well-formednes of the destructor declarator @p D with type @p 2633193326Sed/// R. If there are any errors in the declarator, this routine will 2634193326Sed/// emit diagnostics and set the declarator to invalid. Even if this happens, 2635193326Sed/// will be updated to reflect a well-formed type for the destructor and 2636193326Sed/// returned. 2637193326SedQualType Sema::CheckDestructorDeclarator(Declarator &D, 2638193326Sed FunctionDecl::StorageClass& SC) { 2639193326Sed // C++ [class.dtor]p1: 2640193326Sed // [...] A typedef-name that names a class is a class-name 2641193326Sed // (7.1.3); however, a typedef-name that names a class shall not 2642193326Sed // be used as the identifier in the declarator for a destructor 2643193326Sed // declaration. 2644198893Srdivacky QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 2645193326Sed if (isa<TypedefType>(DeclaratorType)) { 2646193326Sed Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 2647193326Sed << DeclaratorType; 2648193326Sed D.setInvalidType(); 2649193326Sed } 2650193326Sed 2651193326Sed // C++ [class.dtor]p2: 2652193326Sed // A destructor is used to destroy objects of its class type. A 2653193326Sed // destructor takes no parameters, and no return type can be 2654193326Sed // specified for it (not even void). The address of a destructor 2655193326Sed // shall not be taken. A destructor shall not be static. A 2656193326Sed // destructor can be invoked for a const, volatile or const 2657193326Sed // volatile object. A destructor shall not be declared const, 2658193326Sed // volatile or const volatile (9.3.2). 2659193326Sed if (SC == FunctionDecl::Static) { 2660193326Sed if (!D.isInvalidType()) 2661193326Sed Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 2662193326Sed << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 2663193326Sed << SourceRange(D.getIdentifierLoc()); 2664193326Sed SC = FunctionDecl::None; 2665193326Sed D.setInvalidType(); 2666193326Sed } 2667193326Sed if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 2668193326Sed // Destructors don't have return types, but the parser will 2669193326Sed // happily parse something like: 2670193326Sed // 2671193326Sed // class X { 2672193326Sed // float ~X(); 2673193326Sed // }; 2674193326Sed // 2675193326Sed // The return type will be eliminated later. 2676193326Sed Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 2677193326Sed << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 2678193326Sed << SourceRange(D.getIdentifierLoc()); 2679193326Sed } 2680198092Srdivacky 2681193326Sed DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 2682193326Sed if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 2683198092Srdivacky if (FTI.TypeQuals & Qualifiers::Const) 2684193326Sed Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 2685193326Sed << "const" << SourceRange(D.getIdentifierLoc()); 2686198092Srdivacky if (FTI.TypeQuals & Qualifiers::Volatile) 2687193326Sed Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 2688193326Sed << "volatile" << SourceRange(D.getIdentifierLoc()); 2689198092Srdivacky if (FTI.TypeQuals & Qualifiers::Restrict) 2690193326Sed Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 2691193326Sed << "restrict" << SourceRange(D.getIdentifierLoc()); 2692193326Sed D.setInvalidType(); 2693193326Sed } 2694193326Sed 2695193326Sed // Make sure we don't have any parameters. 2696193326Sed if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) { 2697193326Sed Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 2698193326Sed 2699193326Sed // Delete the parameters. 2700193326Sed FTI.freeArgs(); 2701193326Sed D.setInvalidType(); 2702193326Sed } 2703193326Sed 2704198092Srdivacky // Make sure the destructor isn't variadic. 2705193326Sed if (FTI.isVariadic) { 2706193326Sed Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 2707193326Sed D.setInvalidType(); 2708193326Sed } 2709193326Sed 2710193326Sed // Rebuild the function type "R" without any type qualifiers or 2711193326Sed // parameters (in case any of the errors above fired) and with 2712193326Sed // "void" as the return type, since destructors don't have return 2713193326Sed // types. We *always* have to do this, because GetTypeForDeclarator 2714193326Sed // will put in a result type of "int" when none was specified. 2715204643Srdivacky // FIXME: Exceptions! 2716204643Srdivacky return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0, 2717206084Srdivacky false, false, 0, 0, FunctionType::ExtInfo()); 2718193326Sed} 2719193326Sed 2720193326Sed/// CheckConversionDeclarator - Called by ActOnDeclarator to check the 2721193326Sed/// well-formednes of the conversion function declarator @p D with 2722193326Sed/// type @p R. If there are any errors in the declarator, this routine 2723193326Sed/// will emit diagnostics and return true. Otherwise, it will return 2724193326Sed/// false. Either way, the type @p R will be updated to reflect a 2725193326Sed/// well-formed type for the conversion operator. 2726193326Sedvoid Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 2727193326Sed FunctionDecl::StorageClass& SC) { 2728193326Sed // C++ [class.conv.fct]p1: 2729193326Sed // Neither parameter types nor return type can be specified. The 2730198092Srdivacky // type of a conversion function (8.3.5) is "function taking no 2731198092Srdivacky // parameter returning conversion-type-id." 2732193326Sed if (SC == FunctionDecl::Static) { 2733193326Sed if (!D.isInvalidType()) 2734193326Sed Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 2735193326Sed << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 2736193326Sed << SourceRange(D.getIdentifierLoc()); 2737193326Sed D.setInvalidType(); 2738193326Sed SC = FunctionDecl::None; 2739193326Sed } 2740193326Sed if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 2741193326Sed // Conversion functions don't have return types, but the parser will 2742193326Sed // happily parse something like: 2743193326Sed // 2744193326Sed // class X { 2745193326Sed // float operator bool(); 2746193326Sed // }; 2747193326Sed // 2748193326Sed // The return type will be changed later anyway. 2749193326Sed Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 2750193326Sed << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 2751193326Sed << SourceRange(D.getIdentifierLoc()); 2752193326Sed } 2753193326Sed 2754193326Sed // Make sure we don't have any parameters. 2755198092Srdivacky if (R->getAs<FunctionProtoType>()->getNumArgs() > 0) { 2756193326Sed Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 2757193326Sed 2758193326Sed // Delete the parameters. 2759193326Sed D.getTypeObject(0).Fun.freeArgs(); 2760193326Sed D.setInvalidType(); 2761193326Sed } 2762193326Sed 2763198092Srdivacky // Make sure the conversion function isn't variadic. 2764198092Srdivacky if (R->getAs<FunctionProtoType>()->isVariadic() && !D.isInvalidType()) { 2765193326Sed Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 2766193326Sed D.setInvalidType(); 2767193326Sed } 2768193326Sed 2769193326Sed // C++ [class.conv.fct]p4: 2770193326Sed // The conversion-type-id shall not represent a function type nor 2771193326Sed // an array type. 2772198893Srdivacky QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId); 2773193326Sed if (ConvType->isArrayType()) { 2774193326Sed Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 2775193326Sed ConvType = Context.getPointerType(ConvType); 2776193326Sed D.setInvalidType(); 2777193326Sed } else if (ConvType->isFunctionType()) { 2778193326Sed Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 2779193326Sed ConvType = Context.getPointerType(ConvType); 2780193326Sed D.setInvalidType(); 2781193326Sed } 2782193326Sed 2783193326Sed // Rebuild the function type "R" without any parameters (in case any 2784193326Sed // of the errors above fired) and with the conversion type as the 2785198092Srdivacky // return type. 2786204643Srdivacky const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 2787198092Srdivacky R = Context.getFunctionType(ConvType, 0, 0, false, 2788204643Srdivacky Proto->getTypeQuals(), 2789204643Srdivacky Proto->hasExceptionSpec(), 2790204643Srdivacky Proto->hasAnyExceptionSpec(), 2791204643Srdivacky Proto->getNumExceptions(), 2792204643Srdivacky Proto->exception_begin(), 2793206084Srdivacky Proto->getExtInfo()); 2794193326Sed 2795193326Sed // C++0x explicit conversion operators. 2796193326Sed if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x) 2797198092Srdivacky Diag(D.getDeclSpec().getExplicitSpecLoc(), 2798193326Sed diag::warn_explicit_conversion_functions) 2799193326Sed << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 2800193326Sed} 2801193326Sed 2802193326Sed/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 2803193326Sed/// the declaration of the given C++ conversion function. This routine 2804193326Sed/// is responsible for recording the conversion function in the C++ 2805193326Sed/// class, if possible. 2806193326SedSema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 2807193326Sed assert(Conversion && "Expected to receive a conversion function declaration"); 2808193326Sed 2809193326Sed CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 2810193326Sed 2811193326Sed // Make sure we aren't redeclaring the conversion function. 2812193326Sed QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 2813193326Sed 2814193326Sed // C++ [class.conv.fct]p1: 2815193326Sed // [...] A conversion function is never used to convert a 2816193326Sed // (possibly cv-qualified) object to the (possibly cv-qualified) 2817193326Sed // same object type (or a reference to it), to a (possibly 2818193326Sed // cv-qualified) base class of that type (or a reference to it), 2819193326Sed // or to (possibly cv-qualified) void. 2820193326Sed // FIXME: Suppress this warning if the conversion function ends up being a 2821193326Sed // virtual function that overrides a virtual function in a base class. 2822198092Srdivacky QualType ClassType 2823193326Sed = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 2824198092Srdivacky if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 2825193326Sed ConvType = ConvTypeRef->getPointeeType(); 2826193326Sed if (ConvType->isRecordType()) { 2827193326Sed ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 2828193326Sed if (ConvType == ClassType) 2829193326Sed Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 2830193326Sed << ClassType; 2831193326Sed else if (IsDerivedFrom(ClassType, ConvType)) 2832193326Sed Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 2833193326Sed << ClassType << ConvType; 2834193326Sed } else if (ConvType->isVoidType()) { 2835193326Sed Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 2836193326Sed << ClassType << ConvType; 2837193326Sed } 2838193326Sed 2839202379Srdivacky if (Conversion->getPrimaryTemplate()) { 2840202379Srdivacky // ignore specializations 2841202379Srdivacky } else if (Conversion->getPreviousDeclaration()) { 2842198092Srdivacky if (FunctionTemplateDecl *ConversionTemplate 2843202379Srdivacky = Conversion->getDescribedFunctionTemplate()) { 2844202379Srdivacky if (ClassDecl->replaceConversion( 2845202379Srdivacky ConversionTemplate->getPreviousDeclaration(), 2846202379Srdivacky ConversionTemplate)) 2847202379Srdivacky return DeclPtrTy::make(ConversionTemplate); 2848202379Srdivacky } else if (ClassDecl->replaceConversion(Conversion->getPreviousDeclaration(), 2849202379Srdivacky Conversion)) 2850199990Srdivacky return DeclPtrTy::make(Conversion); 2851193326Sed assert(Conversion->isInvalidDecl() && "Conversion should not get here."); 2852198092Srdivacky } else if (FunctionTemplateDecl *ConversionTemplate 2853198092Srdivacky = Conversion->getDescribedFunctionTemplate()) 2854198092Srdivacky ClassDecl->addConversionFunction(ConversionTemplate); 2855202379Srdivacky else 2856198092Srdivacky ClassDecl->addConversionFunction(Conversion); 2857193326Sed 2858193326Sed return DeclPtrTy::make(Conversion); 2859193326Sed} 2860193326Sed 2861193326Sed//===----------------------------------------------------------------------===// 2862193326Sed// Namespace Handling 2863193326Sed//===----------------------------------------------------------------------===// 2864193326Sed 2865193326Sed/// ActOnStartNamespaceDef - This is called at the start of a namespace 2866193326Sed/// definition. 2867193326SedSema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 2868193326Sed SourceLocation IdentLoc, 2869193326Sed IdentifierInfo *II, 2870203955Srdivacky SourceLocation LBrace, 2871203955Srdivacky AttributeList *AttrList) { 2872193326Sed NamespaceDecl *Namespc = 2873193326Sed NamespaceDecl::Create(Context, CurContext, IdentLoc, II); 2874193326Sed Namespc->setLBracLoc(LBrace); 2875193326Sed 2876193326Sed Scope *DeclRegionScope = NamespcScope->getParent(); 2877193326Sed 2878203955Srdivacky ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 2879203955Srdivacky 2880193326Sed if (II) { 2881193326Sed // C++ [namespace.def]p2: 2882193326Sed // The identifier in an original-namespace-definition shall not have been 2883193326Sed // previously defined in the declarative region in which the 2884193326Sed // original-namespace-definition appears. The identifier in an 2885193326Sed // original-namespace-definition is the name of the namespace. Subsequently 2886193326Sed // in that declarative region, it is treated as an original-namespace-name. 2887193326Sed 2888198092Srdivacky NamedDecl *PrevDecl 2889199482Srdivacky = LookupSingleName(DeclRegionScope, II, LookupOrdinaryName, 2890199482Srdivacky ForRedeclaration); 2891198092Srdivacky 2892193326Sed if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) { 2893193326Sed // This is an extended namespace definition. 2894193326Sed // Attach this namespace decl to the chain of extended namespace 2895193326Sed // definitions. 2896193326Sed OrigNS->setNextNamespace(Namespc); 2897193326Sed Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace()); 2898193326Sed 2899198092Srdivacky // Remove the previous declaration from the scope. 2900193326Sed if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) { 2901193326Sed IdResolver.RemoveDecl(OrigNS); 2902193326Sed DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS)); 2903193326Sed } 2904193326Sed } else if (PrevDecl) { 2905193326Sed // This is an invalid name redefinition. 2906193326Sed Diag(Namespc->getLocation(), diag::err_redefinition_different_kind) 2907193326Sed << Namespc->getDeclName(); 2908193326Sed Diag(PrevDecl->getLocation(), diag::note_previous_definition); 2909193326Sed Namespc->setInvalidDecl(); 2910193326Sed // Continue on to push Namespc as current DeclContext and return it. 2911198092Srdivacky } else if (II->isStr("std") && 2912198092Srdivacky CurContext->getLookupContext()->isTranslationUnit()) { 2913198092Srdivacky // This is the first "real" definition of the namespace "std", so update 2914198092Srdivacky // our cache of the "std" namespace to point at this definition. 2915198092Srdivacky if (StdNamespace) { 2916198092Srdivacky // We had already defined a dummy namespace "std". Link this new 2917198092Srdivacky // namespace definition to the dummy namespace "std". 2918198092Srdivacky StdNamespace->setNextNamespace(Namespc); 2919198092Srdivacky StdNamespace->setLocation(IdentLoc); 2920198092Srdivacky Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace()); 2921198092Srdivacky } 2922198092Srdivacky 2923198092Srdivacky // Make our StdNamespace cache point at the first real definition of the 2924198092Srdivacky // "std" namespace. 2925198092Srdivacky StdNamespace = Namespc; 2926198092Srdivacky } 2927193326Sed 2928193326Sed PushOnScopeChains(Namespc, DeclRegionScope); 2929193326Sed } else { 2930198092Srdivacky // Anonymous namespaces. 2931201361Srdivacky assert(Namespc->isAnonymousNamespace()); 2932198092Srdivacky 2933201361Srdivacky // Link the anonymous namespace into its parent. 2934201361Srdivacky NamespaceDecl *PrevDecl; 2935201361Srdivacky DeclContext *Parent = CurContext->getLookupContext(); 2936201361Srdivacky if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 2937201361Srdivacky PrevDecl = TU->getAnonymousNamespace(); 2938201361Srdivacky TU->setAnonymousNamespace(Namespc); 2939201361Srdivacky } else { 2940201361Srdivacky NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 2941201361Srdivacky PrevDecl = ND->getAnonymousNamespace(); 2942201361Srdivacky ND->setAnonymousNamespace(Namespc); 2943201361Srdivacky } 2944201361Srdivacky 2945201361Srdivacky // Link the anonymous namespace with its previous declaration. 2946201361Srdivacky if (PrevDecl) { 2947201361Srdivacky assert(PrevDecl->isAnonymousNamespace()); 2948201361Srdivacky assert(!PrevDecl->getNextNamespace()); 2949201361Srdivacky Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace()); 2950201361Srdivacky PrevDecl->setNextNamespace(Namespc); 2951201361Srdivacky } 2952201361Srdivacky 2953206084Srdivacky CurContext->addDecl(Namespc); 2954206084Srdivacky 2955198092Srdivacky // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 2956198092Srdivacky // behaves as if it were replaced by 2957198092Srdivacky // namespace unique { /* empty body */ } 2958198092Srdivacky // using namespace unique; 2959198092Srdivacky // namespace unique { namespace-body } 2960198092Srdivacky // where all occurrences of 'unique' in a translation unit are 2961198092Srdivacky // replaced by the same identifier and this identifier differs 2962198092Srdivacky // from all other identifiers in the entire program. 2963198092Srdivacky 2964198092Srdivacky // We just create the namespace with an empty name and then add an 2965198092Srdivacky // implicit using declaration, just like the standard suggests. 2966198092Srdivacky // 2967198092Srdivacky // CodeGen enforces the "universally unique" aspect by giving all 2968198092Srdivacky // declarations semantically contained within an anonymous 2969198092Srdivacky // namespace internal linkage. 2970198092Srdivacky 2971201361Srdivacky if (!PrevDecl) { 2972201361Srdivacky UsingDirectiveDecl* UD 2973201361Srdivacky = UsingDirectiveDecl::Create(Context, CurContext, 2974201361Srdivacky /* 'using' */ LBrace, 2975201361Srdivacky /* 'namespace' */ SourceLocation(), 2976201361Srdivacky /* qualifier */ SourceRange(), 2977201361Srdivacky /* NNS */ NULL, 2978201361Srdivacky /* identifier */ SourceLocation(), 2979201361Srdivacky Namespc, 2980201361Srdivacky /* Ancestor */ CurContext); 2981201361Srdivacky UD->setImplicit(); 2982201361Srdivacky CurContext->addDecl(UD); 2983201361Srdivacky } 2984193326Sed } 2985193326Sed 2986193326Sed // Although we could have an invalid decl (i.e. the namespace name is a 2987193326Sed // redefinition), push it as current DeclContext and try to continue parsing. 2988193326Sed // FIXME: We should be able to push Namespc here, so that the each DeclContext 2989193326Sed // for the namespace has the declarations that showed up in that particular 2990193326Sed // namespace definition. 2991193326Sed PushDeclContext(NamespcScope, Namespc); 2992193326Sed return DeclPtrTy::make(Namespc); 2993193326Sed} 2994193326Sed 2995199990Srdivacky/// getNamespaceDecl - Returns the namespace a decl represents. If the decl 2996199990Srdivacky/// is a namespace alias, returns the namespace it points to. 2997199990Srdivackystatic inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 2998199990Srdivacky if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 2999199990Srdivacky return AD->getNamespace(); 3000199990Srdivacky return dyn_cast_or_null<NamespaceDecl>(D); 3001199990Srdivacky} 3002199990Srdivacky 3003193326Sed/// ActOnFinishNamespaceDef - This callback is called after a namespace is 3004193326Sed/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 3005193326Sedvoid Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) { 3006193326Sed Decl *Dcl = D.getAs<Decl>(); 3007193326Sed NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 3008193326Sed assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 3009193326Sed Namespc->setRBracLoc(RBrace); 3010193326Sed PopDeclContext(); 3011193326Sed} 3012193326Sed 3013193326SedSema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S, 3014193326Sed SourceLocation UsingLoc, 3015193326Sed SourceLocation NamespcLoc, 3016193326Sed const CXXScopeSpec &SS, 3017193326Sed SourceLocation IdentLoc, 3018193326Sed IdentifierInfo *NamespcName, 3019193326Sed AttributeList *AttrList) { 3020193326Sed assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 3021193326Sed assert(NamespcName && "Invalid NamespcName."); 3022193326Sed assert(IdentLoc.isValid() && "Invalid NamespceName location."); 3023193326Sed assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 3024193326Sed 3025193326Sed UsingDirectiveDecl *UDir = 0; 3026193326Sed 3027193326Sed // Lookup namespace name. 3028199482Srdivacky LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 3029199482Srdivacky LookupParsedName(R, S, &SS); 3030199482Srdivacky if (R.isAmbiguous()) 3031193326Sed return DeclPtrTy(); 3032199482Srdivacky 3033198092Srdivacky if (!R.empty()) { 3034199990Srdivacky NamedDecl *Named = R.getFoundDecl(); 3035199990Srdivacky assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named)) 3036199990Srdivacky && "expected namespace decl"); 3037193326Sed // C++ [namespace.udir]p1: 3038193326Sed // A using-directive specifies that the names in the nominated 3039193326Sed // namespace can be used in the scope in which the 3040193326Sed // using-directive appears after the using-directive. During 3041193326Sed // unqualified name lookup (3.4.1), the names appear as if they 3042193326Sed // were declared in the nearest enclosing namespace which 3043193326Sed // contains both the using-directive and the nominated 3044198092Srdivacky // namespace. [Note: in this context, "contains" means "contains 3045198092Srdivacky // directly or indirectly". ] 3046193326Sed 3047193326Sed // Find enclosing context containing both using-directive and 3048193326Sed // nominated namespace. 3049199990Srdivacky NamespaceDecl *NS = getNamespaceDecl(Named); 3050193326Sed DeclContext *CommonAncestor = cast<DeclContext>(NS); 3051193326Sed while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 3052193326Sed CommonAncestor = CommonAncestor->getParent(); 3053193326Sed 3054199990Srdivacky UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 3055193326Sed SS.getRange(), 3056193326Sed (NestedNameSpecifier *)SS.getScopeRep(), 3057199990Srdivacky IdentLoc, Named, CommonAncestor); 3058193326Sed PushUsingDirective(S, UDir); 3059193326Sed } else { 3060193326Sed Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 3061193326Sed } 3062193326Sed 3063193326Sed // FIXME: We ignore attributes for now. 3064193326Sed delete AttrList; 3065193326Sed return DeclPtrTy::make(UDir); 3066193326Sed} 3067193326Sed 3068193326Sedvoid Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 3069193326Sed // If scope has associated entity, then using directive is at namespace 3070193326Sed // or translation unit scope. We add UsingDirectiveDecls, into 3071193326Sed // it's lookup structure. 3072193326Sed if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) 3073195341Sed Ctx->addDecl(UDir); 3074193326Sed else 3075193326Sed // Otherwise it is block-sope. using-directives will affect lookup 3076193326Sed // only to the end of scope. 3077193326Sed S->PushUsingDirective(DeclPtrTy::make(UDir)); 3078193326Sed} 3079193326Sed 3080194613Sed 3081194613SedSema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S, 3082198092Srdivacky AccessSpecifier AS, 3083200583Srdivacky bool HasUsingKeyword, 3084198092Srdivacky SourceLocation UsingLoc, 3085198092Srdivacky const CXXScopeSpec &SS, 3086198954Srdivacky UnqualifiedId &Name, 3087198092Srdivacky AttributeList *AttrList, 3088199482Srdivacky bool IsTypeName, 3089199482Srdivacky SourceLocation TypenameLoc) { 3090194613Sed assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 3091194613Sed 3092198954Srdivacky switch (Name.getKind()) { 3093198954Srdivacky case UnqualifiedId::IK_Identifier: 3094198954Srdivacky case UnqualifiedId::IK_OperatorFunctionId: 3095199990Srdivacky case UnqualifiedId::IK_LiteralOperatorId: 3096198954Srdivacky case UnqualifiedId::IK_ConversionFunctionId: 3097198954Srdivacky break; 3098198954Srdivacky 3099198954Srdivacky case UnqualifiedId::IK_ConstructorName: 3100202379Srdivacky case UnqualifiedId::IK_ConstructorTemplateId: 3101200583Srdivacky // C++0x inherited constructors. 3102200583Srdivacky if (getLangOptions().CPlusPlus0x) break; 3103200583Srdivacky 3104198954Srdivacky Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor) 3105198954Srdivacky << SS.getRange(); 3106198954Srdivacky return DeclPtrTy(); 3107198954Srdivacky 3108198954Srdivacky case UnqualifiedId::IK_DestructorName: 3109198954Srdivacky Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor) 3110198954Srdivacky << SS.getRange(); 3111198954Srdivacky return DeclPtrTy(); 3112198954Srdivacky 3113198954Srdivacky case UnqualifiedId::IK_TemplateId: 3114198954Srdivacky Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id) 3115198954Srdivacky << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 3116198954Srdivacky return DeclPtrTy(); 3117198954Srdivacky } 3118198954Srdivacky 3119198954Srdivacky DeclarationName TargetName = GetNameFromUnqualifiedId(Name); 3120200583Srdivacky if (!TargetName) 3121200583Srdivacky return DeclPtrTy(); 3122200583Srdivacky 3123200583Srdivacky // Warn about using declarations. 3124200583Srdivacky // TODO: store that the declaration was written without 'using' and 3125200583Srdivacky // talk about access decls instead of using decls in the 3126200583Srdivacky // diagnostics. 3127200583Srdivacky if (!HasUsingKeyword) { 3128200583Srdivacky UsingLoc = Name.getSourceRange().getBegin(); 3129200583Srdivacky 3130200583Srdivacky Diag(UsingLoc, diag::warn_access_decl_deprecated) 3131206084Srdivacky << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 3132200583Srdivacky } 3133200583Srdivacky 3134199482Srdivacky NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 3135198954Srdivacky Name.getSourceRange().getBegin(), 3136199482Srdivacky TargetName, AttrList, 3137199482Srdivacky /* IsInstantiation */ false, 3138199482Srdivacky IsTypeName, TypenameLoc); 3139200583Srdivacky if (UD) 3140200583Srdivacky PushOnScopeChains(UD, S, /*AddToContext*/ false); 3141198092Srdivacky 3142198092Srdivacky return DeclPtrTy::make(UD); 3143198092Srdivacky} 3144198092Srdivacky 3145200583Srdivacky/// Determines whether to create a using shadow decl for a particular 3146200583Srdivacky/// decl, given the set of decls existing prior to this using lookup. 3147200583Srdivackybool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 3148200583Srdivacky const LookupResult &Previous) { 3149200583Srdivacky // Diagnose finding a decl which is not from a base class of the 3150200583Srdivacky // current class. We do this now because there are cases where this 3151200583Srdivacky // function will silently decide not to build a shadow decl, which 3152200583Srdivacky // will pre-empt further diagnostics. 3153200583Srdivacky // 3154200583Srdivacky // We don't need to do this in C++0x because we do the check once on 3155200583Srdivacky // the qualifier. 3156200583Srdivacky // 3157200583Srdivacky // FIXME: diagnose the following if we care enough: 3158200583Srdivacky // struct A { int foo; }; 3159200583Srdivacky // struct B : A { using A::foo; }; 3160200583Srdivacky // template <class T> struct C : A {}; 3161200583Srdivacky // template <class T> struct D : C<T> { using B::foo; } // <--- 3162200583Srdivacky // This is invalid (during instantiation) in C++03 because B::foo 3163200583Srdivacky // resolves to the using decl in B, which is not a base class of D<T>. 3164200583Srdivacky // We can't diagnose it immediately because C<T> is an unknown 3165200583Srdivacky // specialization. The UsingShadowDecl in D<T> then points directly 3166200583Srdivacky // to A::foo, which will look well-formed when we instantiate. 3167200583Srdivacky // The right solution is to not collapse the shadow-decl chain. 3168200583Srdivacky if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) { 3169200583Srdivacky DeclContext *OrigDC = Orig->getDeclContext(); 3170200583Srdivacky 3171200583Srdivacky // Handle enums and anonymous structs. 3172200583Srdivacky if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 3173200583Srdivacky CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 3174200583Srdivacky while (OrigRec->isAnonymousStructOrUnion()) 3175200583Srdivacky OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 3176200583Srdivacky 3177200583Srdivacky if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 3178200583Srdivacky if (OrigDC == CurContext) { 3179200583Srdivacky Diag(Using->getLocation(), 3180200583Srdivacky diag::err_using_decl_nested_name_specifier_is_current_class) 3181200583Srdivacky << Using->getNestedNameRange(); 3182200583Srdivacky Diag(Orig->getLocation(), diag::note_using_decl_target); 3183200583Srdivacky return true; 3184200583Srdivacky } 3185200583Srdivacky 3186200583Srdivacky Diag(Using->getNestedNameRange().getBegin(), 3187200583Srdivacky diag::err_using_decl_nested_name_specifier_is_not_base_class) 3188200583Srdivacky << Using->getTargetNestedNameDecl() 3189200583Srdivacky << cast<CXXRecordDecl>(CurContext) 3190200583Srdivacky << Using->getNestedNameRange(); 3191200583Srdivacky Diag(Orig->getLocation(), diag::note_using_decl_target); 3192200583Srdivacky return true; 3193200583Srdivacky } 3194200583Srdivacky } 3195200583Srdivacky 3196200583Srdivacky if (Previous.empty()) return false; 3197200583Srdivacky 3198200583Srdivacky NamedDecl *Target = Orig; 3199200583Srdivacky if (isa<UsingShadowDecl>(Target)) 3200200583Srdivacky Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 3201200583Srdivacky 3202200583Srdivacky // If the target happens to be one of the previous declarations, we 3203200583Srdivacky // don't have a conflict. 3204200583Srdivacky // 3205200583Srdivacky // FIXME: but we might be increasing its access, in which case we 3206200583Srdivacky // should redeclare it. 3207200583Srdivacky NamedDecl *NonTag = 0, *Tag = 0; 3208200583Srdivacky for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 3209200583Srdivacky I != E; ++I) { 3210200583Srdivacky NamedDecl *D = (*I)->getUnderlyingDecl(); 3211200583Srdivacky if (D->getCanonicalDecl() == Target->getCanonicalDecl()) 3212200583Srdivacky return false; 3213200583Srdivacky 3214200583Srdivacky (isa<TagDecl>(D) ? Tag : NonTag) = D; 3215200583Srdivacky } 3216200583Srdivacky 3217200583Srdivacky if (Target->isFunctionOrFunctionTemplate()) { 3218200583Srdivacky FunctionDecl *FD; 3219200583Srdivacky if (isa<FunctionTemplateDecl>(Target)) 3220200583Srdivacky FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl(); 3221200583Srdivacky else 3222200583Srdivacky FD = cast<FunctionDecl>(Target); 3223200583Srdivacky 3224200583Srdivacky NamedDecl *OldDecl = 0; 3225200583Srdivacky switch (CheckOverload(FD, Previous, OldDecl)) { 3226200583Srdivacky case Ovl_Overload: 3227200583Srdivacky return false; 3228200583Srdivacky 3229200583Srdivacky case Ovl_NonFunction: 3230200583Srdivacky Diag(Using->getLocation(), diag::err_using_decl_conflict); 3231200583Srdivacky break; 3232200583Srdivacky 3233200583Srdivacky // We found a decl with the exact signature. 3234200583Srdivacky case Ovl_Match: 3235200583Srdivacky if (isa<UsingShadowDecl>(OldDecl)) { 3236200583Srdivacky // Silently ignore the possible conflict. 3237200583Srdivacky return false; 3238200583Srdivacky } 3239200583Srdivacky 3240200583Srdivacky // If we're in a record, we want to hide the target, so we 3241200583Srdivacky // return true (without a diagnostic) to tell the caller not to 3242200583Srdivacky // build a shadow decl. 3243200583Srdivacky if (CurContext->isRecord()) 3244200583Srdivacky return true; 3245200583Srdivacky 3246200583Srdivacky // If we're not in a record, this is an error. 3247200583Srdivacky Diag(Using->getLocation(), diag::err_using_decl_conflict); 3248200583Srdivacky break; 3249200583Srdivacky } 3250200583Srdivacky 3251200583Srdivacky Diag(Target->getLocation(), diag::note_using_decl_target); 3252200583Srdivacky Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 3253200583Srdivacky return true; 3254200583Srdivacky } 3255200583Srdivacky 3256200583Srdivacky // Target is not a function. 3257200583Srdivacky 3258200583Srdivacky if (isa<TagDecl>(Target)) { 3259200583Srdivacky // No conflict between a tag and a non-tag. 3260200583Srdivacky if (!Tag) return false; 3261200583Srdivacky 3262200583Srdivacky Diag(Using->getLocation(), diag::err_using_decl_conflict); 3263200583Srdivacky Diag(Target->getLocation(), diag::note_using_decl_target); 3264200583Srdivacky Diag(Tag->getLocation(), diag::note_using_decl_conflict); 3265200583Srdivacky return true; 3266200583Srdivacky } 3267200583Srdivacky 3268200583Srdivacky // No conflict between a tag and a non-tag. 3269200583Srdivacky if (!NonTag) return false; 3270200583Srdivacky 3271200583Srdivacky Diag(Using->getLocation(), diag::err_using_decl_conflict); 3272200583Srdivacky Diag(Target->getLocation(), diag::note_using_decl_target); 3273200583Srdivacky Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 3274200583Srdivacky return true; 3275200583Srdivacky} 3276200583Srdivacky 3277199482Srdivacky/// Builds a shadow declaration corresponding to a 'using' declaration. 3278200583SrdivackyUsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 3279200583Srdivacky UsingDecl *UD, 3280200583Srdivacky NamedDecl *Orig) { 3281199482Srdivacky 3282199482Srdivacky // If we resolved to another shadow declaration, just coalesce them. 3283200583Srdivacky NamedDecl *Target = Orig; 3284200583Srdivacky if (isa<UsingShadowDecl>(Target)) { 3285200583Srdivacky Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 3286200583Srdivacky assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 3287199482Srdivacky } 3288199482Srdivacky 3289199482Srdivacky UsingShadowDecl *Shadow 3290200583Srdivacky = UsingShadowDecl::Create(Context, CurContext, 3291200583Srdivacky UD->getLocation(), UD, Target); 3292199482Srdivacky UD->addShadowDecl(Shadow); 3293199482Srdivacky 3294199482Srdivacky if (S) 3295200583Srdivacky PushOnScopeChains(Shadow, S); 3296199482Srdivacky else 3297200583Srdivacky CurContext->addDecl(Shadow); 3298200583Srdivacky Shadow->setAccess(UD->getAccess()); 3299199482Srdivacky 3300206084Srdivacky // Register it as a conversion if appropriate. 3301206084Srdivacky if (Shadow->getDeclName().getNameKind() 3302206084Srdivacky == DeclarationName::CXXConversionFunctionName) 3303206084Srdivacky cast<CXXRecordDecl>(CurContext)->addConversionFunction(Shadow); 3304206084Srdivacky 3305200583Srdivacky if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 3306200583Srdivacky Shadow->setInvalidDecl(); 3307200583Srdivacky 3308199482Srdivacky return Shadow; 3309199482Srdivacky} 3310199482Srdivacky 3311200583Srdivacky/// Hides a using shadow declaration. This is required by the current 3312200583Srdivacky/// using-decl implementation when a resolvable using declaration in a 3313200583Srdivacky/// class is followed by a declaration which would hide or override 3314200583Srdivacky/// one or more of the using decl's targets; for example: 3315200583Srdivacky/// 3316200583Srdivacky/// struct Base { void foo(int); }; 3317200583Srdivacky/// struct Derived : Base { 3318200583Srdivacky/// using Base::foo; 3319200583Srdivacky/// void foo(int); 3320200583Srdivacky/// }; 3321200583Srdivacky/// 3322200583Srdivacky/// The governing language is C++03 [namespace.udecl]p12: 3323200583Srdivacky/// 3324200583Srdivacky/// When a using-declaration brings names from a base class into a 3325200583Srdivacky/// derived class scope, member functions in the derived class 3326200583Srdivacky/// override and/or hide member functions with the same name and 3327200583Srdivacky/// parameter types in a base class (rather than conflicting). 3328200583Srdivacky/// 3329200583Srdivacky/// There are two ways to implement this: 3330200583Srdivacky/// (1) optimistically create shadow decls when they're not hidden 3331200583Srdivacky/// by existing declarations, or 3332200583Srdivacky/// (2) don't create any shadow decls (or at least don't make them 3333200583Srdivacky/// visible) until we've fully parsed/instantiated the class. 3334200583Srdivacky/// The problem with (1) is that we might have to retroactively remove 3335200583Srdivacky/// a shadow decl, which requires several O(n) operations because the 3336200583Srdivacky/// decl structures are (very reasonably) not designed for removal. 3337200583Srdivacky/// (2) avoids this but is very fiddly and phase-dependent. 3338200583Srdivackyvoid Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 3339206084Srdivacky if (Shadow->getDeclName().getNameKind() == 3340206084Srdivacky DeclarationName::CXXConversionFunctionName) 3341206084Srdivacky cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 3342206084Srdivacky 3343200583Srdivacky // Remove it from the DeclContext... 3344200583Srdivacky Shadow->getDeclContext()->removeDecl(Shadow); 3345200583Srdivacky 3346200583Srdivacky // ...and the scope, if applicable... 3347200583Srdivacky if (S) { 3348200583Srdivacky S->RemoveDecl(DeclPtrTy::make(static_cast<Decl*>(Shadow))); 3349200583Srdivacky IdResolver.RemoveDecl(Shadow); 3350200583Srdivacky } 3351200583Srdivacky 3352200583Srdivacky // ...and the using decl. 3353200583Srdivacky Shadow->getUsingDecl()->removeShadowDecl(Shadow); 3354200583Srdivacky 3355200583Srdivacky // TODO: complain somehow if Shadow was used. It shouldn't 3356206084Srdivacky // be possible for this to happen, because...? 3357200583Srdivacky} 3358200583Srdivacky 3359199482Srdivacky/// Builds a using declaration. 3360199482Srdivacky/// 3361199482Srdivacky/// \param IsInstantiation - Whether this call arises from an 3362199482Srdivacky/// instantiation of an unresolved using declaration. We treat 3363199482Srdivacky/// the lookup differently for these declarations. 3364199482SrdivackyNamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 3365199482Srdivacky SourceLocation UsingLoc, 3366198092Srdivacky const CXXScopeSpec &SS, 3367198092Srdivacky SourceLocation IdentLoc, 3368198092Srdivacky DeclarationName Name, 3369198092Srdivacky AttributeList *AttrList, 3370199482Srdivacky bool IsInstantiation, 3371199482Srdivacky bool IsTypeName, 3372199482Srdivacky SourceLocation TypenameLoc) { 3373198092Srdivacky assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 3374198092Srdivacky assert(IdentLoc.isValid() && "Invalid TargetName location."); 3375198092Srdivacky 3376198092Srdivacky // FIXME: We ignore attributes for now. 3377198092Srdivacky delete AttrList; 3378198092Srdivacky 3379198092Srdivacky if (SS.isEmpty()) { 3380198092Srdivacky Diag(IdentLoc, diag::err_using_requires_qualname); 3381198092Srdivacky return 0; 3382198092Srdivacky } 3383198092Srdivacky 3384200583Srdivacky // Do the redeclaration lookup in the current scope. 3385200583Srdivacky LookupResult Previous(*this, Name, IdentLoc, LookupUsingDeclName, 3386200583Srdivacky ForRedeclaration); 3387200583Srdivacky Previous.setHideTags(false); 3388200583Srdivacky if (S) { 3389200583Srdivacky LookupName(Previous, S); 3390200583Srdivacky 3391200583Srdivacky // It is really dumb that we have to do this. 3392200583Srdivacky LookupResult::Filter F = Previous.makeFilter(); 3393200583Srdivacky while (F.hasNext()) { 3394200583Srdivacky NamedDecl *D = F.next(); 3395200583Srdivacky if (!isDeclInScope(D, CurContext, S)) 3396200583Srdivacky F.erase(); 3397200583Srdivacky } 3398200583Srdivacky F.done(); 3399200583Srdivacky } else { 3400200583Srdivacky assert(IsInstantiation && "no scope in non-instantiation"); 3401200583Srdivacky assert(CurContext->isRecord() && "scope not record in instantiation"); 3402200583Srdivacky LookupQualifiedName(Previous, CurContext); 3403200583Srdivacky } 3404200583Srdivacky 3405198092Srdivacky NestedNameSpecifier *NNS = 3406198092Srdivacky static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 3407198092Srdivacky 3408200583Srdivacky // Check for invalid redeclarations. 3409200583Srdivacky if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous)) 3410200583Srdivacky return 0; 3411200583Srdivacky 3412200583Srdivacky // Check for bad qualifiers. 3413200583Srdivacky if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc)) 3414200583Srdivacky return 0; 3415200583Srdivacky 3416199482Srdivacky DeclContext *LookupContext = computeDeclContext(SS); 3417200583Srdivacky NamedDecl *D; 3418199482Srdivacky if (!LookupContext) { 3419199482Srdivacky if (IsTypeName) { 3420200583Srdivacky // FIXME: not all declaration name kinds are legal here 3421200583Srdivacky D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 3422200583Srdivacky UsingLoc, TypenameLoc, 3423200583Srdivacky SS.getRange(), NNS, 3424200583Srdivacky IdentLoc, Name); 3425199482Srdivacky } else { 3426200583Srdivacky D = UnresolvedUsingValueDecl::Create(Context, CurContext, 3427200583Srdivacky UsingLoc, SS.getRange(), NNS, 3428200583Srdivacky IdentLoc, Name); 3429199482Srdivacky } 3430200583Srdivacky } else { 3431200583Srdivacky D = UsingDecl::Create(Context, CurContext, IdentLoc, 3432200583Srdivacky SS.getRange(), UsingLoc, NNS, Name, 3433200583Srdivacky IsTypeName); 3434198092Srdivacky } 3435200583Srdivacky D->setAccess(AS); 3436200583Srdivacky CurContext->addDecl(D); 3437198092Srdivacky 3438200583Srdivacky if (!LookupContext) return D; 3439200583Srdivacky UsingDecl *UD = cast<UsingDecl>(D); 3440200583Srdivacky 3441200583Srdivacky if (RequireCompleteDeclContext(SS)) { 3442200583Srdivacky UD->setInvalidDecl(); 3443200583Srdivacky return UD; 3444194613Sed } 3445194613Sed 3446200583Srdivacky // Look up the target name. 3447200583Srdivacky 3448199482Srdivacky LookupResult R(*this, Name, IdentLoc, LookupOrdinaryName); 3449198092Srdivacky 3450200583Srdivacky // Unlike most lookups, we don't always want to hide tag 3451200583Srdivacky // declarations: tag names are visible through the using declaration 3452200583Srdivacky // even if hidden by ordinary names, *except* in a dependent context 3453200583Srdivacky // where it's important for the sanity of two-phase lookup. 3454199482Srdivacky if (!IsInstantiation) 3455199482Srdivacky R.setHideTags(false); 3456198092Srdivacky 3457199482Srdivacky LookupQualifiedName(R, LookupContext); 3458199482Srdivacky 3459198092Srdivacky if (R.empty()) { 3460198092Srdivacky Diag(IdentLoc, diag::err_no_member) 3461198092Srdivacky << Name << LookupContext << SS.getRange(); 3462200583Srdivacky UD->setInvalidDecl(); 3463200583Srdivacky return UD; 3464198092Srdivacky } 3465198092Srdivacky 3466200583Srdivacky if (R.isAmbiguous()) { 3467200583Srdivacky UD->setInvalidDecl(); 3468200583Srdivacky return UD; 3469200583Srdivacky } 3470198092Srdivacky 3471199482Srdivacky if (IsTypeName) { 3472199482Srdivacky // If we asked for a typename and got a non-type decl, error out. 3473200583Srdivacky if (!R.getAsSingle<TypeDecl>()) { 3474199482Srdivacky Diag(IdentLoc, diag::err_using_typename_non_type); 3475199482Srdivacky for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 3476199482Srdivacky Diag((*I)->getUnderlyingDecl()->getLocation(), 3477199482Srdivacky diag::note_using_decl_target); 3478200583Srdivacky UD->setInvalidDecl(); 3479200583Srdivacky return UD; 3480199482Srdivacky } 3481199482Srdivacky } else { 3482199482Srdivacky // If we asked for a non-typename and we got a type, error out, 3483199482Srdivacky // but only if this is an instantiation of an unresolved using 3484199482Srdivacky // decl. Otherwise just silently find the type name. 3485200583Srdivacky if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 3486199482Srdivacky Diag(IdentLoc, diag::err_using_dependent_value_is_type); 3487199482Srdivacky Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 3488200583Srdivacky UD->setInvalidDecl(); 3489200583Srdivacky return UD; 3490199482Srdivacky } 3491198092Srdivacky } 3492198092Srdivacky 3493198092Srdivacky // C++0x N2914 [namespace.udecl]p6: 3494198092Srdivacky // A using-declaration shall not name a namespace. 3495200583Srdivacky if (R.getAsSingle<NamespaceDecl>()) { 3496198092Srdivacky Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 3497198092Srdivacky << SS.getRange(); 3498200583Srdivacky UD->setInvalidDecl(); 3499200583Srdivacky return UD; 3500198092Srdivacky } 3501198092Srdivacky 3502200583Srdivacky for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 3503200583Srdivacky if (!CheckUsingShadowDecl(UD, *I, Previous)) 3504200583Srdivacky BuildUsingShadowDecl(S, UD, *I); 3505200583Srdivacky } 3506199482Srdivacky 3507199482Srdivacky return UD; 3508194613Sed} 3509194613Sed 3510200583Srdivacky/// Checks that the given using declaration is not an invalid 3511200583Srdivacky/// redeclaration. Note that this is checking only for the using decl 3512200583Srdivacky/// itself, not for any ill-formedness among the UsingShadowDecls. 3513200583Srdivackybool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 3514200583Srdivacky bool isTypeName, 3515200583Srdivacky const CXXScopeSpec &SS, 3516200583Srdivacky SourceLocation NameLoc, 3517200583Srdivacky const LookupResult &Prev) { 3518200583Srdivacky // C++03 [namespace.udecl]p8: 3519200583Srdivacky // C++0x [namespace.udecl]p10: 3520200583Srdivacky // A using-declaration is a declaration and can therefore be used 3521200583Srdivacky // repeatedly where (and only where) multiple declarations are 3522200583Srdivacky // allowed. 3523200583Srdivacky // That's only in file contexts. 3524200583Srdivacky if (CurContext->getLookupContext()->isFileContext()) 3525200583Srdivacky return false; 3526200583Srdivacky 3527200583Srdivacky NestedNameSpecifier *Qual 3528200583Srdivacky = static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 3529200583Srdivacky 3530200583Srdivacky for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 3531200583Srdivacky NamedDecl *D = *I; 3532200583Srdivacky 3533200583Srdivacky bool DTypename; 3534200583Srdivacky NestedNameSpecifier *DQual; 3535200583Srdivacky if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 3536200583Srdivacky DTypename = UD->isTypeName(); 3537200583Srdivacky DQual = UD->getTargetNestedNameDecl(); 3538200583Srdivacky } else if (UnresolvedUsingValueDecl *UD 3539200583Srdivacky = dyn_cast<UnresolvedUsingValueDecl>(D)) { 3540200583Srdivacky DTypename = false; 3541200583Srdivacky DQual = UD->getTargetNestedNameSpecifier(); 3542200583Srdivacky } else if (UnresolvedUsingTypenameDecl *UD 3543200583Srdivacky = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 3544200583Srdivacky DTypename = true; 3545200583Srdivacky DQual = UD->getTargetNestedNameSpecifier(); 3546200583Srdivacky } else continue; 3547200583Srdivacky 3548200583Srdivacky // using decls differ if one says 'typename' and the other doesn't. 3549200583Srdivacky // FIXME: non-dependent using decls? 3550200583Srdivacky if (isTypeName != DTypename) continue; 3551200583Srdivacky 3552200583Srdivacky // using decls differ if they name different scopes (but note that 3553200583Srdivacky // template instantiation can cause this check to trigger when it 3554200583Srdivacky // didn't before instantiation). 3555200583Srdivacky if (Context.getCanonicalNestedNameSpecifier(Qual) != 3556200583Srdivacky Context.getCanonicalNestedNameSpecifier(DQual)) 3557200583Srdivacky continue; 3558200583Srdivacky 3559200583Srdivacky Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 3560200583Srdivacky Diag(D->getLocation(), diag::note_using_decl) << 1; 3561200583Srdivacky return true; 3562200583Srdivacky } 3563200583Srdivacky 3564200583Srdivacky return false; 3565200583Srdivacky} 3566200583Srdivacky 3567200583Srdivacky 3568200583Srdivacky/// Checks that the given nested-name qualifier used in a using decl 3569200583Srdivacky/// in the current context is appropriately related to the current 3570200583Srdivacky/// scope. If an error is found, diagnoses it and returns true. 3571200583Srdivackybool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 3572200583Srdivacky const CXXScopeSpec &SS, 3573200583Srdivacky SourceLocation NameLoc) { 3574200583Srdivacky DeclContext *NamedContext = computeDeclContext(SS); 3575200583Srdivacky 3576200583Srdivacky if (!CurContext->isRecord()) { 3577200583Srdivacky // C++03 [namespace.udecl]p3: 3578200583Srdivacky // C++0x [namespace.udecl]p8: 3579200583Srdivacky // A using-declaration for a class member shall be a member-declaration. 3580200583Srdivacky 3581200583Srdivacky // If we weren't able to compute a valid scope, it must be a 3582200583Srdivacky // dependent class scope. 3583200583Srdivacky if (!NamedContext || NamedContext->isRecord()) { 3584200583Srdivacky Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 3585200583Srdivacky << SS.getRange(); 3586200583Srdivacky return true; 3587200583Srdivacky } 3588200583Srdivacky 3589200583Srdivacky // Otherwise, everything is known to be fine. 3590200583Srdivacky return false; 3591200583Srdivacky } 3592200583Srdivacky 3593200583Srdivacky // The current scope is a record. 3594200583Srdivacky 3595200583Srdivacky // If the named context is dependent, we can't decide much. 3596200583Srdivacky if (!NamedContext) { 3597200583Srdivacky // FIXME: in C++0x, we can diagnose if we can prove that the 3598200583Srdivacky // nested-name-specifier does not refer to a base class, which is 3599200583Srdivacky // still possible in some cases. 3600200583Srdivacky 3601200583Srdivacky // Otherwise we have to conservatively report that things might be 3602200583Srdivacky // okay. 3603200583Srdivacky return false; 3604200583Srdivacky } 3605200583Srdivacky 3606200583Srdivacky if (!NamedContext->isRecord()) { 3607200583Srdivacky // Ideally this would point at the last name in the specifier, 3608200583Srdivacky // but we don't have that level of source info. 3609200583Srdivacky Diag(SS.getRange().getBegin(), 3610200583Srdivacky diag::err_using_decl_nested_name_specifier_is_not_class) 3611200583Srdivacky << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange(); 3612200583Srdivacky return true; 3613200583Srdivacky } 3614200583Srdivacky 3615200583Srdivacky if (getLangOptions().CPlusPlus0x) { 3616200583Srdivacky // C++0x [namespace.udecl]p3: 3617200583Srdivacky // In a using-declaration used as a member-declaration, the 3618200583Srdivacky // nested-name-specifier shall name a base class of the class 3619200583Srdivacky // being defined. 3620200583Srdivacky 3621200583Srdivacky if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 3622200583Srdivacky cast<CXXRecordDecl>(NamedContext))) { 3623200583Srdivacky if (CurContext == NamedContext) { 3624200583Srdivacky Diag(NameLoc, 3625200583Srdivacky diag::err_using_decl_nested_name_specifier_is_current_class) 3626200583Srdivacky << SS.getRange(); 3627200583Srdivacky return true; 3628200583Srdivacky } 3629200583Srdivacky 3630200583Srdivacky Diag(SS.getRange().getBegin(), 3631200583Srdivacky diag::err_using_decl_nested_name_specifier_is_not_base_class) 3632200583Srdivacky << (NestedNameSpecifier*) SS.getScopeRep() 3633200583Srdivacky << cast<CXXRecordDecl>(CurContext) 3634200583Srdivacky << SS.getRange(); 3635200583Srdivacky return true; 3636200583Srdivacky } 3637200583Srdivacky 3638200583Srdivacky return false; 3639200583Srdivacky } 3640200583Srdivacky 3641200583Srdivacky // C++03 [namespace.udecl]p4: 3642200583Srdivacky // A using-declaration used as a member-declaration shall refer 3643200583Srdivacky // to a member of a base class of the class being defined [etc.]. 3644200583Srdivacky 3645200583Srdivacky // Salient point: SS doesn't have to name a base class as long as 3646200583Srdivacky // lookup only finds members from base classes. Therefore we can 3647200583Srdivacky // diagnose here only if we can prove that that can't happen, 3648200583Srdivacky // i.e. if the class hierarchies provably don't intersect. 3649200583Srdivacky 3650200583Srdivacky // TODO: it would be nice if "definitely valid" results were cached 3651200583Srdivacky // in the UsingDecl and UsingShadowDecl so that these checks didn't 3652200583Srdivacky // need to be repeated. 3653200583Srdivacky 3654200583Srdivacky struct UserData { 3655200583Srdivacky llvm::DenseSet<const CXXRecordDecl*> Bases; 3656200583Srdivacky 3657200583Srdivacky static bool collect(const CXXRecordDecl *Base, void *OpaqueData) { 3658200583Srdivacky UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 3659200583Srdivacky Data->Bases.insert(Base); 3660200583Srdivacky return true; 3661200583Srdivacky } 3662200583Srdivacky 3663200583Srdivacky bool hasDependentBases(const CXXRecordDecl *Class) { 3664200583Srdivacky return !Class->forallBases(collect, this); 3665200583Srdivacky } 3666200583Srdivacky 3667200583Srdivacky /// Returns true if the base is dependent or is one of the 3668200583Srdivacky /// accumulated base classes. 3669200583Srdivacky static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) { 3670200583Srdivacky UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 3671200583Srdivacky return !Data->Bases.count(Base); 3672200583Srdivacky } 3673200583Srdivacky 3674200583Srdivacky bool mightShareBases(const CXXRecordDecl *Class) { 3675200583Srdivacky return Bases.count(Class) || !Class->forallBases(doesNotContain, this); 3676200583Srdivacky } 3677200583Srdivacky }; 3678200583Srdivacky 3679200583Srdivacky UserData Data; 3680200583Srdivacky 3681200583Srdivacky // Returns false if we find a dependent base. 3682200583Srdivacky if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext))) 3683200583Srdivacky return false; 3684200583Srdivacky 3685200583Srdivacky // Returns false if the class has a dependent base or if it or one 3686200583Srdivacky // of its bases is present in the base set of the current context. 3687200583Srdivacky if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext))) 3688200583Srdivacky return false; 3689200583Srdivacky 3690200583Srdivacky Diag(SS.getRange().getBegin(), 3691200583Srdivacky diag::err_using_decl_nested_name_specifier_is_not_base_class) 3692200583Srdivacky << (NestedNameSpecifier*) SS.getScopeRep() 3693200583Srdivacky << cast<CXXRecordDecl>(CurContext) 3694200583Srdivacky << SS.getRange(); 3695200583Srdivacky 3696200583Srdivacky return true; 3697200583Srdivacky} 3698200583Srdivacky 3699198092SrdivackySema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S, 3700193326Sed SourceLocation NamespaceLoc, 3701193326Sed SourceLocation AliasLoc, 3702193326Sed IdentifierInfo *Alias, 3703193326Sed const CXXScopeSpec &SS, 3704193326Sed SourceLocation IdentLoc, 3705193326Sed IdentifierInfo *Ident) { 3706198092Srdivacky 3707193326Sed // Lookup the namespace name. 3708199482Srdivacky LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 3709199482Srdivacky LookupParsedName(R, S, &SS); 3710193326Sed 3711193326Sed // Check if we have a previous declaration with the same name. 3712198092Srdivacky if (NamedDecl *PrevDecl 3713199482Srdivacky = LookupSingleName(S, Alias, LookupOrdinaryName, ForRedeclaration)) { 3714193326Sed if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 3715198092Srdivacky // We already have an alias with the same name that points to the same 3716193326Sed // namespace, so don't create a new one. 3717206084Srdivacky // FIXME: At some point, we'll want to create the (redundant) 3718206084Srdivacky // declaration to maintain better source information. 3719198092Srdivacky if (!R.isAmbiguous() && !R.empty() && 3720206084Srdivacky AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl()))) 3721193326Sed return DeclPtrTy(); 3722193326Sed } 3723198092Srdivacky 3724193326Sed unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition : 3725193326Sed diag::err_redefinition_different_kind; 3726193326Sed Diag(AliasLoc, DiagID) << Alias; 3727193326Sed Diag(PrevDecl->getLocation(), diag::note_previous_definition); 3728193326Sed return DeclPtrTy(); 3729193326Sed } 3730193326Sed 3731199482Srdivacky if (R.isAmbiguous()) 3732193326Sed return DeclPtrTy(); 3733198092Srdivacky 3734198092Srdivacky if (R.empty()) { 3735193326Sed Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange(); 3736193326Sed return DeclPtrTy(); 3737193326Sed } 3738198092Srdivacky 3739194613Sed NamespaceAliasDecl *AliasDecl = 3740198092Srdivacky NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 3741198092Srdivacky Alias, SS.getRange(), 3742193326Sed (NestedNameSpecifier *)SS.getScopeRep(), 3743198092Srdivacky IdentLoc, R.getFoundDecl()); 3744198092Srdivacky 3745203955Srdivacky PushOnScopeChains(AliasDecl, S); 3746193326Sed return DeclPtrTy::make(AliasDecl); 3747193326Sed} 3748193326Sed 3749194613Sedvoid Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 3750194613Sed CXXConstructorDecl *Constructor) { 3751194711Sed assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() && 3752194711Sed !Constructor->isUsed()) && 3753194711Sed "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 3754198092Srdivacky 3755194613Sed CXXRecordDecl *ClassDecl 3756194613Sed = cast<CXXRecordDecl>(Constructor->getDeclContext()); 3757194711Sed assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 3758199482Srdivacky 3759203955Srdivacky DeclContext *PreviousContext = CurContext; 3760203955Srdivacky CurContext = Constructor; 3761206084Srdivacky if (SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false)) { 3762199990Srdivacky Diag(CurrentLocation, diag::note_member_synthesized_at) 3763199990Srdivacky << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl); 3764199482Srdivacky Constructor->setInvalidDecl(); 3765199482Srdivacky } else { 3766199482Srdivacky Constructor->setUsed(); 3767194613Sed } 3768203955Srdivacky CurContext = PreviousContext; 3769194613Sed} 3770194613Sed 3771195099Sedvoid Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 3772198092Srdivacky CXXDestructorDecl *Destructor) { 3773195099Sed assert((Destructor->isImplicit() && !Destructor->isUsed()) && 3774195099Sed "DefineImplicitDestructor - call it for implicit default dtor"); 3775199482Srdivacky CXXRecordDecl *ClassDecl = Destructor->getParent(); 3776195099Sed assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 3777203955Srdivacky 3778203955Srdivacky DeclContext *PreviousContext = CurContext; 3779203955Srdivacky CurContext = Destructor; 3780203955Srdivacky 3781205408Srdivacky MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 3782205408Srdivacky Destructor->getParent()); 3783198092Srdivacky 3784199990Srdivacky // FIXME: If CheckDestructor fails, we should emit a note about where the 3785199990Srdivacky // implicit destructor was needed. 3786199990Srdivacky if (CheckDestructor(Destructor)) { 3787199990Srdivacky Diag(CurrentLocation, diag::note_member_synthesized_at) 3788199990Srdivacky << CXXDestructor << Context.getTagDeclType(ClassDecl); 3789199990Srdivacky 3790199990Srdivacky Destructor->setInvalidDecl(); 3791203955Srdivacky CurContext = PreviousContext; 3792203955Srdivacky 3793199990Srdivacky return; 3794199990Srdivacky } 3795203955Srdivacky CurContext = PreviousContext; 3796199990Srdivacky 3797195099Sed Destructor->setUsed(); 3798195099Sed} 3799195099Sed 3800195099Sedvoid Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation, 3801195099Sed CXXMethodDecl *MethodDecl) { 3802195099Sed assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() && 3803195099Sed MethodDecl->getOverloadedOperator() == OO_Equal && 3804195099Sed !MethodDecl->isUsed()) && 3805195099Sed "DefineImplicitOverloadedAssign - call it for implicit assignment op"); 3806198092Srdivacky 3807195099Sed CXXRecordDecl *ClassDecl 3808195099Sed = cast<CXXRecordDecl>(MethodDecl->getDeclContext()); 3809198092Srdivacky 3810203955Srdivacky DeclContext *PreviousContext = CurContext; 3811203955Srdivacky CurContext = MethodDecl; 3812203955Srdivacky 3813195099Sed // C++[class.copy] p12 3814195099Sed // Before the implicitly-declared copy assignment operator for a class is 3815195099Sed // implicitly defined, all implicitly-declared copy assignment operators 3816195099Sed // for its direct base classes and its nonstatic data members shall have 3817195099Sed // been implicitly defined. 3818195099Sed bool err = false; 3819195341Sed for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 3820195341Sed E = ClassDecl->bases_end(); Base != E; ++Base) { 3821195099Sed CXXRecordDecl *BaseClassDecl 3822198092Srdivacky = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 3823198092Srdivacky if (CXXMethodDecl *BaseAssignOpMethod = 3824200583Srdivacky getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0), 3825205219Srdivacky BaseClassDecl)) { 3826205219Srdivacky CheckDirectMemberAccess(Base->getSourceRange().getBegin(), 3827205219Srdivacky BaseAssignOpMethod, 3828206084Srdivacky PDiag(diag::err_access_assign_base) 3829205219Srdivacky << Base->getType()); 3830205219Srdivacky 3831195099Sed MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod); 3832205219Srdivacky } 3833195099Sed } 3834195341Sed for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 3835195341Sed E = ClassDecl->field_end(); Field != E; ++Field) { 3836195099Sed QualType FieldType = Context.getCanonicalType((*Field)->getType()); 3837195099Sed if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 3838195099Sed FieldType = Array->getElementType(); 3839198092Srdivacky if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 3840195099Sed CXXRecordDecl *FieldClassDecl 3841195099Sed = cast<CXXRecordDecl>(FieldClassType->getDecl()); 3842198092Srdivacky if (CXXMethodDecl *FieldAssignOpMethod = 3843200583Srdivacky getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0), 3844205219Srdivacky FieldClassDecl)) { 3845205219Srdivacky CheckDirectMemberAccess(Field->getLocation(), 3846205219Srdivacky FieldAssignOpMethod, 3847206084Srdivacky PDiag(diag::err_access_assign_field) 3848205219Srdivacky << Field->getDeclName() << Field->getType()); 3849205219Srdivacky 3850195099Sed MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod); 3851205219Srdivacky } 3852198092Srdivacky } else if (FieldType->isReferenceType()) { 3853198092Srdivacky Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 3854198092Srdivacky << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 3855198092Srdivacky Diag(Field->getLocation(), diag::note_declared_at); 3856195099Sed Diag(CurrentLocation, diag::note_first_required_here); 3857195099Sed err = true; 3858198092Srdivacky } else if (FieldType.isConstQualified()) { 3859198092Srdivacky Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 3860198092Srdivacky << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 3861198092Srdivacky Diag(Field->getLocation(), diag::note_declared_at); 3862195099Sed Diag(CurrentLocation, diag::note_first_required_here); 3863195099Sed err = true; 3864195099Sed } 3865195099Sed } 3866195099Sed if (!err) 3867198092Srdivacky MethodDecl->setUsed(); 3868203955Srdivacky 3869203955Srdivacky CurContext = PreviousContext; 3870195099Sed} 3871195099Sed 3872195099SedCXXMethodDecl * 3873200583SrdivackySema::getAssignOperatorMethod(SourceLocation CurrentLocation, 3874200583Srdivacky ParmVarDecl *ParmDecl, 3875195099Sed CXXRecordDecl *ClassDecl) { 3876195099Sed QualType LHSType = Context.getTypeDeclType(ClassDecl); 3877195099Sed QualType RHSType(LHSType); 3878195099Sed // If class's assignment operator argument is const/volatile qualified, 3879198092Srdivacky // look for operator = (const/volatile B&). Otherwise, look for 3880195099Sed // operator = (B&). 3881198092Srdivacky RHSType = Context.getCVRQualifiedType(RHSType, 3882198092Srdivacky ParmDecl->getType().getCVRQualifiers()); 3883198092Srdivacky ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl, 3884200583Srdivacky LHSType, 3885200583Srdivacky SourceLocation())); 3886198092Srdivacky ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl, 3887200583Srdivacky RHSType, 3888200583Srdivacky CurrentLocation)); 3889195099Sed Expr *Args[2] = { &*LHS, &*RHS }; 3890203955Srdivacky OverloadCandidateSet CandidateSet(CurrentLocation); 3891198092Srdivacky AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2, 3892195099Sed CandidateSet); 3893195099Sed OverloadCandidateSet::iterator Best; 3894200583Srdivacky if (BestViableFunction(CandidateSet, CurrentLocation, Best) == OR_Success) 3895195099Sed return cast<CXXMethodDecl>(Best->Function); 3896195099Sed assert(false && 3897195099Sed "getAssignOperatorMethod - copy assignment operator method not found"); 3898195099Sed return 0; 3899195099Sed} 3900195099Sed 3901194711Sedvoid Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 3902194711Sed CXXConstructorDecl *CopyConstructor, 3903194711Sed unsigned TypeQuals) { 3904198092Srdivacky assert((CopyConstructor->isImplicit() && 3905201361Srdivacky CopyConstructor->isCopyConstructor(TypeQuals) && 3906194711Sed !CopyConstructor->isUsed()) && 3907194711Sed "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 3908198092Srdivacky 3909194711Sed CXXRecordDecl *ClassDecl 3910194711Sed = cast<CXXRecordDecl>(CopyConstructor->getDeclContext()); 3911194711Sed assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 3912203955Srdivacky 3913203955Srdivacky DeclContext *PreviousContext = CurContext; 3914203955Srdivacky CurContext = CopyConstructor; 3915203955Srdivacky 3916195099Sed // C++ [class.copy] p209 3917198092Srdivacky // Before the implicitly-declared copy constructor for a class is 3918194711Sed // implicitly defined, all the implicitly-declared copy constructors 3919194711Sed // for its base class and its non-static data members shall have been 3920194711Sed // implicitly defined. 3921194711Sed for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(); 3922194711Sed Base != ClassDecl->bases_end(); ++Base) { 3923194711Sed CXXRecordDecl *BaseClassDecl 3924198092Srdivacky = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 3925198092Srdivacky if (CXXConstructorDecl *BaseCopyCtor = 3926205219Srdivacky BaseClassDecl->getCopyConstructor(Context, TypeQuals)) { 3927205219Srdivacky CheckDirectMemberAccess(Base->getSourceRange().getBegin(), 3928205219Srdivacky BaseCopyCtor, 3929206084Srdivacky PDiag(diag::err_access_copy_base) 3930205219Srdivacky << Base->getType()); 3931205219Srdivacky 3932195099Sed MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor); 3933205219Srdivacky } 3934194711Sed } 3935195341Sed for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 3936195341Sed FieldEnd = ClassDecl->field_end(); 3937195341Sed Field != FieldEnd; ++Field) { 3938194711Sed QualType FieldType = Context.getCanonicalType((*Field)->getType()); 3939194711Sed if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 3940194711Sed FieldType = Array->getElementType(); 3941198092Srdivacky if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 3942194711Sed CXXRecordDecl *FieldClassDecl 3943194711Sed = cast<CXXRecordDecl>(FieldClassType->getDecl()); 3944198092Srdivacky if (CXXConstructorDecl *FieldCopyCtor = 3945205219Srdivacky FieldClassDecl->getCopyConstructor(Context, TypeQuals)) { 3946205219Srdivacky CheckDirectMemberAccess(Field->getLocation(), 3947205219Srdivacky FieldCopyCtor, 3948206084Srdivacky PDiag(diag::err_access_copy_field) 3949205219Srdivacky << Field->getDeclName() << Field->getType()); 3950205219Srdivacky 3951195099Sed MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor); 3952205219Srdivacky } 3953194711Sed } 3954194711Sed } 3955194711Sed CopyConstructor->setUsed(); 3956203955Srdivacky 3957203955Srdivacky CurContext = PreviousContext; 3958194711Sed} 3959194711Sed 3960198092SrdivackySema::OwningExprResult 3961198092SrdivackySema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 3962198092Srdivacky CXXConstructorDecl *Constructor, 3963201361Srdivacky MultiExprArg ExprArgs, 3964203955Srdivacky bool RequiresZeroInit, 3965203955Srdivacky bool BaseInitialization) { 3966198092Srdivacky bool Elidable = false; 3967198092Srdivacky 3968206125Srdivacky // C++0x [class.copy]p34: 3969206125Srdivacky // When certain criteria are met, an implementation is allowed to 3970206125Srdivacky // omit the copy/move construction of a class object, even if the 3971206125Srdivacky // copy/move constructor and/or destructor for the object have 3972206125Srdivacky // side effects. [...] 3973206125Srdivacky // - when a temporary class object that has not been bound to a 3974206125Srdivacky // reference (12.2) would be copied/moved to a class object 3975206125Srdivacky // with the same cv-unqualified type, the copy/move operation 3976206125Srdivacky // can be omitted by constructing the temporary object 3977206125Srdivacky // directly into the target of the omitted copy/move 3978206125Srdivacky if (Constructor->isCopyConstructor() && ExprArgs.size() >= 1) { 3979206125Srdivacky Expr *SubExpr = ((Expr **)ExprArgs.get())[0]; 3980206125Srdivacky Elidable = SubExpr->isTemporaryObject() && 3981206125Srdivacky Context.hasSameUnqualifiedType(SubExpr->getType(), 3982206125Srdivacky Context.getTypeDeclType(Constructor->getParent())); 3983198092Srdivacky } 3984198092Srdivacky 3985198092Srdivacky return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 3986203955Srdivacky Elidable, move(ExprArgs), RequiresZeroInit, 3987203955Srdivacky BaseInitialization); 3988198092Srdivacky} 3989198092Srdivacky 3990198092Srdivacky/// BuildCXXConstructExpr - Creates a complete call to a constructor, 3991198092Srdivacky/// including handling of its default argument expressions. 3992198092SrdivackySema::OwningExprResult 3993198092SrdivackySema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 3994198092Srdivacky CXXConstructorDecl *Constructor, bool Elidable, 3995201361Srdivacky MultiExprArg ExprArgs, 3996203955Srdivacky bool RequiresZeroInit, 3997203955Srdivacky bool BaseInitialization) { 3998198092Srdivacky unsigned NumExprs = ExprArgs.size(); 3999198092Srdivacky Expr **Exprs = (Expr **)ExprArgs.release(); 4000198092Srdivacky 4001199990Srdivacky MarkDeclarationReferenced(ConstructLoc, Constructor); 4002201361Srdivacky return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc, 4003201361Srdivacky Constructor, Elidable, Exprs, NumExprs, 4004203955Srdivacky RequiresZeroInit, BaseInitialization)); 4005198092Srdivacky} 4006198092Srdivacky 4007198092Srdivackybool Sema::InitializeVarWithConstructor(VarDecl *VD, 4008193326Sed CXXConstructorDecl *Constructor, 4009198092Srdivacky MultiExprArg Exprs) { 4010198092Srdivacky OwningExprResult TempResult = 4011198893Srdivacky BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor, 4012198092Srdivacky move(Exprs)); 4013198092Srdivacky if (TempResult.isInvalid()) 4014198092Srdivacky return true; 4015198092Srdivacky 4016198092Srdivacky Expr *Temp = TempResult.takeAs<Expr>(); 4017194711Sed MarkDeclarationReferenced(VD->getLocation(), Constructor); 4018201361Srdivacky Temp = MaybeCreateCXXExprWithTemporaries(Temp); 4019203955Srdivacky VD->setInit(Temp); 4020198092Srdivacky 4021198092Srdivacky return false; 4022193326Sed} 4023193326Sed 4024203955Srdivackyvoid Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 4025203955Srdivacky CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 4026204643Srdivacky if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() && 4027204643Srdivacky !ClassDecl->hasTrivialDestructor()) { 4028203955Srdivacky CXXDestructorDecl *Destructor = ClassDecl->getDestructor(Context); 4029203955Srdivacky MarkDeclarationReferenced(VD->getLocation(), Destructor); 4030205219Srdivacky CheckDestructorAccess(VD->getLocation(), Destructor, 4031206084Srdivacky PDiag(diag::err_access_dtor_var) 4032205219Srdivacky << VD->getDeclName() 4033205219Srdivacky << VD->getType()); 4034203955Srdivacky } 4035195099Sed} 4036195099Sed 4037198092Srdivacky/// AddCXXDirectInitializerToDecl - This action is called immediately after 4038193326Sed/// ActOnDeclarator, when a C++ direct initializer is present. 4039193326Sed/// e.g: "int x(1);" 4040193326Sedvoid Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl, 4041193326Sed SourceLocation LParenLoc, 4042193326Sed MultiExprArg Exprs, 4043193326Sed SourceLocation *CommaLocs, 4044193326Sed SourceLocation RParenLoc) { 4045201361Srdivacky assert(Exprs.size() != 0 && Exprs.get() && "missing expressions"); 4046193326Sed Decl *RealDecl = Dcl.getAs<Decl>(); 4047193326Sed 4048193326Sed // If there is no declaration, there was an error parsing it. Just ignore 4049193326Sed // the initializer. 4050193326Sed if (RealDecl == 0) 4051193326Sed return; 4052198092Srdivacky 4053193326Sed VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 4054193326Sed if (!VDecl) { 4055193326Sed Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 4056193326Sed RealDecl->setInvalidDecl(); 4057193326Sed return; 4058193326Sed } 4059193326Sed 4060198092Srdivacky // We will represent direct-initialization similarly to copy-initialization: 4061193326Sed // int x(1); -as-> int x = 1; 4062193326Sed // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 4063193326Sed // 4064193326Sed // Clients that want to distinguish between the two forms, can check for 4065193326Sed // direct initializer using VarDecl::hasCXXDirectInitializer(). 4066193326Sed // A major benefit is that clients that don't particularly care about which 4067193326Sed // exactly form was it (like the CodeGen) can handle both cases without 4068193326Sed // special case code. 4069193326Sed 4070193326Sed // C++ 8.5p11: 4071193326Sed // The form of initialization (using parentheses or '=') is generally 4072193326Sed // insignificant, but does matter when the entity being initialized has a 4073193326Sed // class type. 4074193326Sed QualType DeclInitType = VDecl->getType(); 4075193326Sed if (const ArrayType *Array = Context.getAsArrayType(DeclInitType)) 4076198893Srdivacky DeclInitType = Context.getBaseElementType(Array); 4077193326Sed 4078203955Srdivacky if (!VDecl->getType()->isDependentType() && 4079203955Srdivacky RequireCompleteType(VDecl->getLocation(), VDecl->getType(), 4080193326Sed diag::err_typecheck_decl_incomplete_type)) { 4081193326Sed VDecl->setInvalidDecl(); 4082193326Sed return; 4083193326Sed } 4084193326Sed 4085201361Srdivacky // The variable can not have an abstract class type. 4086201361Srdivacky if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 4087201361Srdivacky diag::err_abstract_type_in_decl, 4088201361Srdivacky AbstractVariableType)) 4089201361Srdivacky VDecl->setInvalidDecl(); 4090201361Srdivacky 4091203955Srdivacky const VarDecl *Def; 4092203955Srdivacky if ((Def = VDecl->getDefinition()) && Def != VDecl) { 4093201361Srdivacky Diag(VDecl->getLocation(), diag::err_redefinition) 4094201361Srdivacky << VDecl->getDeclName(); 4095201361Srdivacky Diag(Def->getLocation(), diag::note_previous_definition); 4096201361Srdivacky VDecl->setInvalidDecl(); 4097193326Sed return; 4098193326Sed } 4099203955Srdivacky 4100203955Srdivacky // If either the declaration has a dependent type or if any of the 4101203955Srdivacky // expressions is type-dependent, we represent the initialization 4102203955Srdivacky // via a ParenListExpr for later use during template instantiation. 4103203955Srdivacky if (VDecl->getType()->isDependentType() || 4104203955Srdivacky Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) { 4105203955Srdivacky // Let clients know that initialization was done with a direct initializer. 4106203955Srdivacky VDecl->setCXXDirectInitializer(true); 4107203955Srdivacky 4108203955Srdivacky // Store the initialization expressions as a ParenListExpr. 4109203955Srdivacky unsigned NumExprs = Exprs.size(); 4110203955Srdivacky VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc, 4111203955Srdivacky (Expr **)Exprs.release(), 4112203955Srdivacky NumExprs, RParenLoc)); 4113203955Srdivacky return; 4114203955Srdivacky } 4115201361Srdivacky 4116201361Srdivacky // Capture the variable that is being initialized and the style of 4117201361Srdivacky // initialization. 4118201361Srdivacky InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 4119201361Srdivacky 4120201361Srdivacky // FIXME: Poor source location information. 4121201361Srdivacky InitializationKind Kind 4122201361Srdivacky = InitializationKind::CreateDirect(VDecl->getLocation(), 4123201361Srdivacky LParenLoc, RParenLoc); 4124201361Srdivacky 4125201361Srdivacky InitializationSequence InitSeq(*this, Entity, Kind, 4126201361Srdivacky (Expr**)Exprs.get(), Exprs.size()); 4127201361Srdivacky OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs)); 4128201361Srdivacky if (Result.isInvalid()) { 4129201361Srdivacky VDecl->setInvalidDecl(); 4130193326Sed return; 4131193326Sed } 4132201361Srdivacky 4133201361Srdivacky Result = MaybeCreateCXXExprWithTemporaries(move(Result)); 4134203955Srdivacky VDecl->setInit(Result.takeAs<Expr>()); 4135193326Sed VDecl->setCXXDirectInitializer(true); 4136193326Sed 4137203955Srdivacky if (const RecordType *Record = VDecl->getType()->getAs<RecordType>()) 4138203955Srdivacky FinalizeVarWithDestructor(VDecl, Record); 4139193326Sed} 4140193326Sed 4141199482Srdivacky/// \brief Add the applicable constructor candidates for an initialization 4142199482Srdivacky/// by constructor. 4143199482Srdivackystatic void AddConstructorInitializationCandidates(Sema &SemaRef, 4144199482Srdivacky QualType ClassType, 4145199482Srdivacky Expr **Args, 4146199482Srdivacky unsigned NumArgs, 4147200583Srdivacky InitializationKind Kind, 4148199482Srdivacky OverloadCandidateSet &CandidateSet) { 4149199482Srdivacky // C++ [dcl.init]p14: 4150199482Srdivacky // If the initialization is direct-initialization, or if it is 4151199482Srdivacky // copy-initialization where the cv-unqualified version of the 4152199482Srdivacky // source type is the same class as, or a derived class of, the 4153199482Srdivacky // class of the destination, constructors are considered. The 4154199482Srdivacky // applicable constructors are enumerated (13.3.1.3), and the 4155199482Srdivacky // best one is chosen through overload resolution (13.3). The 4156199482Srdivacky // constructor so selected is called to initialize the object, 4157199482Srdivacky // with the initializer expression(s) as its argument(s). If no 4158199482Srdivacky // constructor applies, or the overload resolution is ambiguous, 4159199482Srdivacky // the initialization is ill-formed. 4160199482Srdivacky const RecordType *ClassRec = ClassType->getAs<RecordType>(); 4161199482Srdivacky assert(ClassRec && "Can only initialize a class type here"); 4162199482Srdivacky 4163199482Srdivacky // FIXME: When we decide not to synthesize the implicitly-declared 4164199482Srdivacky // constructors, we'll need to make them appear here. 4165199482Srdivacky 4166199482Srdivacky const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl()); 4167199482Srdivacky DeclarationName ConstructorName 4168199482Srdivacky = SemaRef.Context.DeclarationNames.getCXXConstructorName( 4169199482Srdivacky SemaRef.Context.getCanonicalType(ClassType).getUnqualifiedType()); 4170199482Srdivacky DeclContext::lookup_const_iterator Con, ConEnd; 4171199482Srdivacky for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName); 4172199482Srdivacky Con != ConEnd; ++Con) { 4173205408Srdivacky DeclAccessPair FoundDecl = DeclAccessPair::make(*Con, (*Con)->getAccess()); 4174205408Srdivacky 4175199482Srdivacky // Find the constructor (which may be a template). 4176199482Srdivacky CXXConstructorDecl *Constructor = 0; 4177199482Srdivacky FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con); 4178199482Srdivacky if (ConstructorTmpl) 4179199482Srdivacky Constructor 4180199482Srdivacky = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 4181199482Srdivacky else 4182199482Srdivacky Constructor = cast<CXXConstructorDecl>(*Con); 4183199482Srdivacky 4184200583Srdivacky if ((Kind.getKind() == InitializationKind::IK_Direct) || 4185200583Srdivacky (Kind.getKind() == InitializationKind::IK_Value) || 4186200583Srdivacky (Kind.getKind() == InitializationKind::IK_Copy && 4187199482Srdivacky Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) || 4188200583Srdivacky ((Kind.getKind() == InitializationKind::IK_Default) && 4189200583Srdivacky Constructor->isDefaultConstructor())) { 4190199482Srdivacky if (ConstructorTmpl) 4191205408Srdivacky SemaRef.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 4192199990Srdivacky /*ExplicitArgs*/ 0, 4193199482Srdivacky Args, NumArgs, CandidateSet); 4194199482Srdivacky else 4195205408Srdivacky SemaRef.AddOverloadCandidate(Constructor, FoundDecl, 4196203955Srdivacky Args, NumArgs, CandidateSet); 4197199482Srdivacky } 4198199482Srdivacky } 4199199482Srdivacky} 4200199482Srdivacky 4201199482Srdivacky/// \brief Attempt to perform initialization by constructor 4202199482Srdivacky/// (C++ [dcl.init]p14), which may occur as part of direct-initialization or 4203199482Srdivacky/// copy-initialization. 4204199482Srdivacky/// 4205199482Srdivacky/// This routine determines whether initialization by constructor is possible, 4206199482Srdivacky/// but it does not emit any diagnostics in the case where the initialization 4207199482Srdivacky/// is ill-formed. 4208199482Srdivacky/// 4209199482Srdivacky/// \param ClassType the type of the object being initialized, which must have 4210199482Srdivacky/// class type. 4211199482Srdivacky/// 4212199482Srdivacky/// \param Args the arguments provided to initialize the object 4213199482Srdivacky/// 4214199482Srdivacky/// \param NumArgs the number of arguments provided to initialize the object 4215199482Srdivacky/// 4216199482Srdivacky/// \param Kind the type of initialization being performed 4217199482Srdivacky/// 4218199482Srdivacky/// \returns the constructor used to initialize the object, if successful. 4219199482Srdivacky/// Otherwise, emits a diagnostic and returns NULL. 4220199482SrdivackyCXXConstructorDecl * 4221199482SrdivackySema::TryInitializationByConstructor(QualType ClassType, 4222199482Srdivacky Expr **Args, unsigned NumArgs, 4223199482Srdivacky SourceLocation Loc, 4224199482Srdivacky InitializationKind Kind) { 4225199482Srdivacky // Build the overload candidate set 4226203955Srdivacky OverloadCandidateSet CandidateSet(Loc); 4227199482Srdivacky AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind, 4228199482Srdivacky CandidateSet); 4229199482Srdivacky 4230199482Srdivacky // Determine whether we found a constructor we can use. 4231199482Srdivacky OverloadCandidateSet::iterator Best; 4232199482Srdivacky switch (BestViableFunction(CandidateSet, Loc, Best)) { 4233199482Srdivacky case OR_Success: 4234199482Srdivacky case OR_Deleted: 4235199482Srdivacky // We found a constructor. Return it. 4236199482Srdivacky return cast<CXXConstructorDecl>(Best->Function); 4237199482Srdivacky 4238199482Srdivacky case OR_No_Viable_Function: 4239199482Srdivacky case OR_Ambiguous: 4240199482Srdivacky // Overload resolution failed. Return nothing. 4241199482Srdivacky return 0; 4242199482Srdivacky } 4243199482Srdivacky 4244199482Srdivacky // Silence GCC warning 4245199482Srdivacky return 0; 4246199482Srdivacky} 4247199482Srdivacky 4248198092Srdivacky/// \brief Given a constructor and the set of arguments provided for the 4249198092Srdivacky/// constructor, convert the arguments and add any required default arguments 4250198092Srdivacky/// to form a proper call to this constructor. 4251198092Srdivacky/// 4252198092Srdivacky/// \returns true if an error occurred, false otherwise. 4253198092Srdivackybool 4254198092SrdivackySema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 4255198092Srdivacky MultiExprArg ArgsPtr, 4256198092Srdivacky SourceLocation Loc, 4257198092Srdivacky ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) { 4258198092Srdivacky // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 4259198092Srdivacky unsigned NumArgs = ArgsPtr.size(); 4260198092Srdivacky Expr **Args = (Expr **)ArgsPtr.get(); 4261198092Srdivacky 4262198092Srdivacky const FunctionProtoType *Proto 4263198092Srdivacky = Constructor->getType()->getAs<FunctionProtoType>(); 4264198092Srdivacky assert(Proto && "Constructor without a prototype?"); 4265198092Srdivacky unsigned NumArgsInProto = Proto->getNumArgs(); 4266198092Srdivacky 4267198092Srdivacky // If too few arguments are available, we'll fill in the rest with defaults. 4268199990Srdivacky if (NumArgs < NumArgsInProto) 4269198092Srdivacky ConvertedArgs.reserve(NumArgsInProto); 4270199990Srdivacky else 4271198092Srdivacky ConvertedArgs.reserve(NumArgs); 4272199990Srdivacky 4273199990Srdivacky VariadicCallType CallType = 4274199990Srdivacky Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 4275199990Srdivacky llvm::SmallVector<Expr *, 8> AllArgs; 4276199990Srdivacky bool Invalid = GatherArgumentsForCall(Loc, Constructor, 4277199990Srdivacky Proto, 0, Args, NumArgs, AllArgs, 4278199990Srdivacky CallType); 4279199990Srdivacky for (unsigned i =0, size = AllArgs.size(); i < size; i++) 4280199990Srdivacky ConvertedArgs.push_back(AllArgs[i]); 4281199990Srdivacky return Invalid; 4282198092Srdivacky} 4283198092Srdivacky 4284193326Sed/// CompareReferenceRelationship - Compare the two types T1 and T2 to 4285193326Sed/// determine whether they are reference-related, 4286193326Sed/// reference-compatible, reference-compatible with added 4287193326Sed/// qualification, or incompatible, for use in C++ initialization by 4288193326Sed/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 4289193326Sed/// type, and the first type (T1) is the pointee type of the reference 4290193326Sed/// type being initialized. 4291198092SrdivackySema::ReferenceCompareResult 4292201361SrdivackySema::CompareReferenceRelationship(SourceLocation Loc, 4293198954Srdivacky QualType OrigT1, QualType OrigT2, 4294193326Sed bool& DerivedToBase) { 4295198954Srdivacky assert(!OrigT1->isReferenceType() && 4296193326Sed "T1 must be the pointee type of the reference type"); 4297198954Srdivacky assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4298193326Sed 4299198954Srdivacky QualType T1 = Context.getCanonicalType(OrigT1); 4300198954Srdivacky QualType T2 = Context.getCanonicalType(OrigT2); 4301201361Srdivacky Qualifiers T1Quals, T2Quals; 4302201361Srdivacky QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4303201361Srdivacky QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4304193326Sed 4305193326Sed // C++ [dcl.init.ref]p4: 4306198092Srdivacky // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4307198092Srdivacky // reference-related to "cv2 T2" if T1 is the same type as T2, or 4308193326Sed // T1 is a base class of T2. 4309193326Sed if (UnqualT1 == UnqualT2) 4310193326Sed DerivedToBase = false; 4311198954Srdivacky else if (!RequireCompleteType(Loc, OrigT1, PDiag()) && 4312198954Srdivacky !RequireCompleteType(Loc, OrigT2, PDiag()) && 4313198954Srdivacky IsDerivedFrom(UnqualT2, UnqualT1)) 4314193326Sed DerivedToBase = true; 4315193326Sed else 4316193326Sed return Ref_Incompatible; 4317193326Sed 4318193326Sed // At this point, we know that T1 and T2 are reference-related (at 4319193326Sed // least). 4320193326Sed 4321201361Srdivacky // If the type is an array type, promote the element qualifiers to the type 4322201361Srdivacky // for comparison. 4323201361Srdivacky if (isa<ArrayType>(T1) && T1Quals) 4324201361Srdivacky T1 = Context.getQualifiedType(UnqualT1, T1Quals); 4325201361Srdivacky if (isa<ArrayType>(T2) && T2Quals) 4326201361Srdivacky T2 = Context.getQualifiedType(UnqualT2, T2Quals); 4327201361Srdivacky 4328193326Sed // C++ [dcl.init.ref]p4: 4329198092Srdivacky // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 4330193326Sed // reference-related to T2 and cv1 is the same cv-qualification 4331193326Sed // as, or greater cv-qualification than, cv2. For purposes of 4332193326Sed // overload resolution, cases for which cv1 is greater 4333193326Sed // cv-qualification than cv2 are identified as 4334193326Sed // reference-compatible with added qualification (see 13.3.3.2). 4335201361Srdivacky if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers()) 4336193326Sed return Ref_Compatible; 4337193326Sed else if (T1.isMoreQualifiedThan(T2)) 4338193326Sed return Ref_Compatible_With_Added_Qualification; 4339193326Sed else 4340193326Sed return Ref_Related; 4341193326Sed} 4342193326Sed 4343193326Sed/// CheckReferenceInit - Check the initialization of a reference 4344193326Sed/// variable with the given initializer (C++ [dcl.init.ref]). Init is 4345193326Sed/// the initializer (either a simple initializer or an initializer 4346193326Sed/// list), and DeclType is the type of the declaration. When ICS is 4347193326Sed/// non-null, this routine will compute the implicit conversion 4348193326Sed/// sequence according to C++ [over.ics.ref] and will not produce any 4349193326Sed/// diagnostics; when ICS is null, it will emit diagnostics when any 4350193326Sed/// errors are found. Either way, a return value of true indicates 4351193326Sed/// that there was a failure, a return value of false indicates that 4352193326Sed/// the reference initialization succeeded. 4353193326Sed/// 4354193326Sed/// When @p SuppressUserConversions, user-defined conversions are 4355193326Sed/// suppressed. 4356193326Sed/// When @p AllowExplicit, we also permit explicit user-defined 4357193326Sed/// conversion functions. 4358193326Sed/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue. 4359199482Srdivacky/// When @p IgnoreBaseAccess, we don't do access control on to-base conversion. 4360199482Srdivacky/// This is used when this is called from a C-style cast. 4361198092Srdivackybool 4362193326SedSema::CheckReferenceInit(Expr *&Init, QualType DeclType, 4363198092Srdivacky SourceLocation DeclLoc, 4364193326Sed bool SuppressUserConversions, 4365198092Srdivacky bool AllowExplicit, bool ForceRValue, 4366199482Srdivacky ImplicitConversionSequence *ICS, 4367199482Srdivacky bool IgnoreBaseAccess) { 4368193326Sed assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4369193326Sed 4370198092Srdivacky QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4371193326Sed QualType T2 = Init->getType(); 4372193326Sed 4373193326Sed // If the initializer is the address of an overloaded function, try 4374193326Sed // to resolve the overloaded function. If all goes well, T2 is the 4375193326Sed // type of the resulting function. 4376193326Sed if (Context.getCanonicalType(T2) == Context.OverloadTy) { 4377206084Srdivacky DeclAccessPair Found; 4378198092Srdivacky FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType, 4379206084Srdivacky ICS != 0, Found); 4380193326Sed if (Fn) { 4381193326Sed // Since we're performing this reference-initialization for 4382193326Sed // real, update the initializer with the resulting function. 4383193326Sed if (!ICS) { 4384198092Srdivacky if (DiagnoseUseOfDecl(Fn, DeclLoc)) 4385206084Srdivacky return true; 4386193326Sed 4387206084Srdivacky CheckAddressOfMemberAccess(Init, Found); 4388206084Srdivacky Init = FixOverloadedFunctionReference(Init, Found, Fn); 4389193326Sed } 4390193326Sed 4391193326Sed T2 = Fn->getType(); 4392193326Sed } 4393193326Sed } 4394193326Sed 4395193326Sed // Compute some basic properties of the types and the initializer. 4396193326Sed bool isRValRef = DeclType->isRValueReferenceType(); 4397193326Sed bool DerivedToBase = false; 4398193326Sed Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression : 4399193326Sed Init->isLvalue(Context); 4400198092Srdivacky ReferenceCompareResult RefRelationship 4401198954Srdivacky = CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase); 4402193326Sed 4403193326Sed // Most paths end in a failed conversion. 4404202379Srdivacky if (ICS) { 4405204643Srdivacky ICS->setBad(BadConversionSequence::no_conversion, Init, DeclType); 4406202379Srdivacky } 4407193326Sed 4408193326Sed // C++ [dcl.init.ref]p5: 4409198092Srdivacky // A reference to type "cv1 T1" is initialized by an expression 4410198092Srdivacky // of type "cv2 T2" as follows: 4411193326Sed 4412193326Sed // -- If the initializer expression 4413193326Sed 4414193326Sed // Rvalue references cannot bind to lvalues (N2812). 4415193326Sed // There is absolutely no situation where they can. In particular, note that 4416193326Sed // this is ill-formed, even if B has a user-defined conversion to A&&: 4417193326Sed // B b; 4418193326Sed // A&& r = b; 4419193326Sed if (isRValRef && InitLvalue == Expr::LV_Valid) { 4420193326Sed if (!ICS) 4421198092Srdivacky Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref) 4422193326Sed << Init->getSourceRange(); 4423193326Sed return true; 4424193326Sed } 4425193326Sed 4426193326Sed bool BindsDirectly = false; 4427198092Srdivacky // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4428198092Srdivacky // reference-compatible with "cv2 T2," or 4429193326Sed // 4430193326Sed // Note that the bit-field check is skipped if we are just computing 4431193326Sed // the implicit conversion sequence (C++ [over.best.ics]p2). 4432193326Sed if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) && 4433193326Sed RefRelationship >= Ref_Compatible_With_Added_Qualification) { 4434193326Sed BindsDirectly = true; 4435193326Sed 4436193326Sed if (ICS) { 4437193326Sed // C++ [over.ics.ref]p1: 4438193326Sed // When a parameter of reference type binds directly (8.5.3) 4439193326Sed // to an argument expression, the implicit conversion sequence 4440193326Sed // is the identity conversion, unless the argument expression 4441193326Sed // has a type that is a derived class of the parameter type, 4442193326Sed // in which case the implicit conversion sequence is a 4443193326Sed // derived-to-base Conversion (13.3.3.1). 4444202379Srdivacky ICS->setStandard(); 4445193326Sed ICS->Standard.First = ICK_Identity; 4446193326Sed ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity; 4447193326Sed ICS->Standard.Third = ICK_Identity; 4448193326Sed ICS->Standard.FromTypePtr = T2.getAsOpaquePtr(); 4449203955Srdivacky ICS->Standard.setToType(0, T2); 4450203955Srdivacky ICS->Standard.setToType(1, T1); 4451203955Srdivacky ICS->Standard.setToType(2, T1); 4452193326Sed ICS->Standard.ReferenceBinding = true; 4453193326Sed ICS->Standard.DirectBinding = true; 4454193326Sed ICS->Standard.RRefBinding = false; 4455193326Sed ICS->Standard.CopyConstructor = 0; 4456193326Sed 4457193326Sed // Nothing more to do: the inaccessibility/ambiguity check for 4458193326Sed // derived-to-base conversions is suppressed when we're 4459193326Sed // computing the implicit conversion sequence (C++ 4460193326Sed // [over.best.ics]p2). 4461193326Sed return false; 4462193326Sed } else { 4463193326Sed // Perform the conversion. 4464198092Srdivacky CastExpr::CastKind CK = CastExpr::CK_NoOp; 4465198092Srdivacky if (DerivedToBase) 4466198092Srdivacky CK = CastExpr::CK_DerivedToBase; 4467198092Srdivacky else if(CheckExceptionSpecCompatibility(Init, T1)) 4468198092Srdivacky return true; 4469198092Srdivacky ImpCastExprToType(Init, T1, CK, /*isLvalue=*/true); 4470193326Sed } 4471193326Sed } 4472193326Sed 4473193326Sed // -- has a class type (i.e., T2 is a class type) and can be 4474198092Srdivacky // implicitly converted to an lvalue of type "cv3 T3," 4475198092Srdivacky // where "cv1 T1" is reference-compatible with "cv3 T3" 4476193326Sed // 92) (this conversion is selected by enumerating the 4477193326Sed // applicable conversion functions (13.3.1.6) and choosing 4478193326Sed // the best one through overload resolution (13.3)), 4479198092Srdivacky if (!isRValRef && !SuppressUserConversions && T2->isRecordType() && 4480198398Srdivacky !RequireCompleteType(DeclLoc, T2, 0)) { 4481198092Srdivacky CXXRecordDecl *T2RecordDecl 4482198092Srdivacky = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 4483193326Sed 4484203955Srdivacky OverloadCandidateSet CandidateSet(DeclLoc); 4485202879Srdivacky const UnresolvedSetImpl *Conversions 4486198092Srdivacky = T2RecordDecl->getVisibleConversionFunctions(); 4487202879Srdivacky for (UnresolvedSetImpl::iterator I = Conversions->begin(), 4488199990Srdivacky E = Conversions->end(); I != E; ++I) { 4489200583Srdivacky NamedDecl *D = *I; 4490200583Srdivacky CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4491200583Srdivacky if (isa<UsingShadowDecl>(D)) 4492200583Srdivacky D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4493200583Srdivacky 4494198092Srdivacky FunctionTemplateDecl *ConvTemplate 4495200583Srdivacky = dyn_cast<FunctionTemplateDecl>(D); 4496198092Srdivacky CXXConversionDecl *Conv; 4497198092Srdivacky if (ConvTemplate) 4498198092Srdivacky Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4499198092Srdivacky else 4500200583Srdivacky Conv = cast<CXXConversionDecl>(D); 4501198092Srdivacky 4502193326Sed // If the conversion function doesn't return a reference type, 4503193326Sed // it can't be considered for this conversion. 4504193326Sed if (Conv->getConversionType()->isLValueReferenceType() && 4505198092Srdivacky (AllowExplicit || !Conv->isExplicit())) { 4506198092Srdivacky if (ConvTemplate) 4507205408Srdivacky AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 4508200583Srdivacky Init, DeclType, CandidateSet); 4509198092Srdivacky else 4510205408Srdivacky AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 4511203955Srdivacky DeclType, CandidateSet); 4512198092Srdivacky } 4513193326Sed } 4514193326Sed 4515193326Sed OverloadCandidateSet::iterator Best; 4516198092Srdivacky switch (BestViableFunction(CandidateSet, DeclLoc, Best)) { 4517193326Sed case OR_Success: 4518204962Srdivacky // C++ [over.ics.ref]p1: 4519204962Srdivacky // 4520204962Srdivacky // [...] If the parameter binds directly to the result of 4521204962Srdivacky // applying a conversion function to the argument 4522204962Srdivacky // expression, the implicit conversion sequence is a 4523204962Srdivacky // user-defined conversion sequence (13.3.3.1.2), with the 4524204962Srdivacky // second standard conversion sequence either an identity 4525204962Srdivacky // conversion or, if the conversion function returns an 4526204962Srdivacky // entity of a type that is a derived class of the parameter 4527204962Srdivacky // type, a derived-to-base Conversion. 4528204962Srdivacky if (!Best->FinalConversion.DirectBinding) 4529204962Srdivacky break; 4530204962Srdivacky 4531193326Sed // This is a direct binding. 4532193326Sed BindsDirectly = true; 4533193326Sed 4534193326Sed if (ICS) { 4535202379Srdivacky ICS->setUserDefined(); 4536193326Sed ICS->UserDefined.Before = Best->Conversions[0].Standard; 4537193326Sed ICS->UserDefined.After = Best->FinalConversion; 4538193326Sed ICS->UserDefined.ConversionFunction = Best->Function; 4539199482Srdivacky ICS->UserDefined.EllipsisConversion = false; 4540193326Sed assert(ICS->UserDefined.After.ReferenceBinding && 4541193326Sed ICS->UserDefined.After.DirectBinding && 4542193326Sed "Expected a direct reference binding!"); 4543193326Sed return false; 4544193326Sed } else { 4545198092Srdivacky OwningExprResult InitConversion = 4546198092Srdivacky BuildCXXCastArgument(DeclLoc, QualType(), 4547198092Srdivacky CastExpr::CK_UserDefinedConversion, 4548198092Srdivacky cast<CXXMethodDecl>(Best->Function), 4549198092Srdivacky Owned(Init)); 4550198092Srdivacky Init = InitConversion.takeAs<Expr>(); 4551198092Srdivacky 4552198092Srdivacky if (CheckExceptionSpecCompatibility(Init, T1)) 4553198092Srdivacky return true; 4554198092Srdivacky ImpCastExprToType(Init, T1, CastExpr::CK_UserDefinedConversion, 4555198092Srdivacky /*isLvalue=*/true); 4556193326Sed } 4557193326Sed break; 4558193326Sed 4559193326Sed case OR_Ambiguous: 4560198092Srdivacky if (ICS) { 4561202379Srdivacky ICS->setAmbiguous(); 4562198092Srdivacky for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4563198092Srdivacky Cand != CandidateSet.end(); ++Cand) 4564198092Srdivacky if (Cand->Viable) 4565202379Srdivacky ICS->Ambiguous.addConversion(Cand->Function); 4566198092Srdivacky break; 4567198092Srdivacky } 4568198092Srdivacky Diag(DeclLoc, diag::err_ref_init_ambiguous) << DeclType << Init->getType() 4569198092Srdivacky << Init->getSourceRange(); 4570202379Srdivacky PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Init, 1); 4571193326Sed return true; 4572198092Srdivacky 4573193326Sed case OR_No_Viable_Function: 4574193326Sed case OR_Deleted: 4575193326Sed // There was no suitable conversion, or we found a deleted 4576193326Sed // conversion; continue with other checks. 4577193326Sed break; 4578193326Sed } 4579193326Sed } 4580198092Srdivacky 4581193326Sed if (BindsDirectly) { 4582193326Sed // C++ [dcl.init.ref]p4: 4583193326Sed // [...] In all cases where the reference-related or 4584193326Sed // reference-compatible relationship of two types is used to 4585193326Sed // establish the validity of a reference binding, and T1 is a 4586193326Sed // base class of T2, a program that necessitates such a binding 4587193326Sed // is ill-formed if T1 is an inaccessible (clause 11) or 4588193326Sed // ambiguous (10.2) base class of T2. 4589193326Sed // 4590193326Sed // Note that we only check this condition when we're allowed to 4591193326Sed // complain about errors, because we should not be checking for 4592193326Sed // ambiguity (or inaccessibility) unless the reference binding 4593193326Sed // actually happens. 4594198092Srdivacky if (DerivedToBase) 4595198092Srdivacky return CheckDerivedToBaseConversion(T2, T1, DeclLoc, 4596199482Srdivacky Init->getSourceRange(), 4597199482Srdivacky IgnoreBaseAccess); 4598193326Sed else 4599193326Sed return false; 4600193326Sed } 4601193326Sed 4602193326Sed // -- Otherwise, the reference shall be to a non-volatile const 4603193326Sed // type (i.e., cv1 shall be const), or the reference shall be an 4604193326Sed // rvalue reference and the initializer expression shall be an rvalue. 4605198092Srdivacky if (!isRValRef && T1.getCVRQualifiers() != Qualifiers::Const) { 4606193326Sed if (!ICS) 4607198092Srdivacky Diag(DeclLoc, diag::err_not_reference_to_const_init) 4608203955Srdivacky << T1.isVolatileQualified() 4609201361Srdivacky << T1 << int(InitLvalue != Expr::LV_Valid) 4610193326Sed << T2 << Init->getSourceRange(); 4611193326Sed return true; 4612193326Sed } 4613193326Sed 4614193326Sed // -- If the initializer expression is an rvalue, with T2 a 4615198092Srdivacky // class type, and "cv1 T1" is reference-compatible with 4616198092Srdivacky // "cv2 T2," the reference is bound in one of the 4617193326Sed // following ways (the choice is implementation-defined): 4618193326Sed // 4619193326Sed // -- The reference is bound to the object represented by 4620193326Sed // the rvalue (see 3.10) or to a sub-object within that 4621193326Sed // object. 4622193326Sed // 4623198092Srdivacky // -- A temporary of type "cv1 T2" [sic] is created, and 4624193326Sed // a constructor is called to copy the entire rvalue 4625193326Sed // object into the temporary. The reference is bound to 4626193326Sed // the temporary or to a sub-object within the 4627193326Sed // temporary. 4628193326Sed // 4629193326Sed // The constructor that would be used to make the copy 4630193326Sed // shall be callable whether or not the copy is actually 4631193326Sed // done. 4632193326Sed // 4633193326Sed // Note that C++0x [dcl.init.ref]p5 takes away this implementation 4634193326Sed // freedom, so we will always take the first option and never build 4635193326Sed // a temporary in this case. FIXME: We will, however, have to check 4636193326Sed // for the presence of a copy constructor in C++98/03 mode. 4637193326Sed if (InitLvalue != Expr::LV_Valid && T2->isRecordType() && 4638193326Sed RefRelationship >= Ref_Compatible_With_Added_Qualification) { 4639193326Sed if (ICS) { 4640202379Srdivacky ICS->setStandard(); 4641193326Sed ICS->Standard.First = ICK_Identity; 4642193326Sed ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity; 4643193326Sed ICS->Standard.Third = ICK_Identity; 4644193326Sed ICS->Standard.FromTypePtr = T2.getAsOpaquePtr(); 4645203955Srdivacky ICS->Standard.setToType(0, T2); 4646203955Srdivacky ICS->Standard.setToType(1, T1); 4647203955Srdivacky ICS->Standard.setToType(2, T1); 4648193326Sed ICS->Standard.ReferenceBinding = true; 4649193326Sed ICS->Standard.DirectBinding = false; 4650193326Sed ICS->Standard.RRefBinding = isRValRef; 4651193326Sed ICS->Standard.CopyConstructor = 0; 4652193326Sed } else { 4653198092Srdivacky CastExpr::CastKind CK = CastExpr::CK_NoOp; 4654198092Srdivacky if (DerivedToBase) 4655198092Srdivacky CK = CastExpr::CK_DerivedToBase; 4656198092Srdivacky else if(CheckExceptionSpecCompatibility(Init, T1)) 4657198092Srdivacky return true; 4658198092Srdivacky ImpCastExprToType(Init, T1, CK, /*isLvalue=*/false); 4659193326Sed } 4660193326Sed return false; 4661193326Sed } 4662193326Sed 4663198092Srdivacky // -- Otherwise, a temporary of type "cv1 T1" is created and 4664193326Sed // initialized from the initializer expression using the 4665193326Sed // rules for a non-reference copy initialization (8.5). The 4666193326Sed // reference is then bound to the temporary. If T1 is 4667193326Sed // reference-related to T2, cv1 must be the same 4668193326Sed // cv-qualification as, or greater cv-qualification than, 4669193326Sed // cv2; otherwise, the program is ill-formed. 4670193326Sed if (RefRelationship == Ref_Related) { 4671193326Sed // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4672193326Sed // we would be reference-compatible or reference-compatible with 4673193326Sed // added qualification. But that wasn't the case, so the reference 4674193326Sed // initialization fails. 4675193326Sed if (!ICS) 4676198092Srdivacky Diag(DeclLoc, diag::err_reference_init_drops_quals) 4677201361Srdivacky << T1 << int(InitLvalue != Expr::LV_Valid) 4678193326Sed << T2 << Init->getSourceRange(); 4679193326Sed return true; 4680193326Sed } 4681193326Sed 4682193326Sed // If at least one of the types is a class type, the types are not 4683193326Sed // related, and we aren't allowed any user conversions, the 4684193326Sed // reference binding fails. This case is important for breaking 4685193326Sed // recursion, since TryImplicitConversion below will attempt to 4686193326Sed // create a temporary through the use of a copy constructor. 4687193326Sed if (SuppressUserConversions && RefRelationship == Ref_Incompatible && 4688193326Sed (T1->isRecordType() || T2->isRecordType())) { 4689193326Sed if (!ICS) 4690198092Srdivacky Diag(DeclLoc, diag::err_typecheck_convert_incompatible) 4691201361Srdivacky << DeclType << Init->getType() << AA_Initializing << Init->getSourceRange(); 4692193326Sed return true; 4693193326Sed } 4694193326Sed 4695193326Sed // Actually try to convert the initializer to T1. 4696193326Sed if (ICS) { 4697193326Sed // C++ [over.ics.ref]p2: 4698198092Srdivacky // 4699193326Sed // When a parameter of reference type is not bound directly to 4700193326Sed // an argument expression, the conversion sequence is the one 4701193326Sed // required to convert the argument expression to the 4702193326Sed // underlying type of the reference according to 4703193326Sed // 13.3.3.1. Conceptually, this conversion sequence corresponds 4704193326Sed // to copy-initializing a temporary of the underlying type with 4705193326Sed // the argument expression. Any difference in top-level 4706193326Sed // cv-qualification is subsumed by the initialization itself 4707193326Sed // and does not constitute a conversion. 4708198092Srdivacky *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions, 4709198092Srdivacky /*AllowExplicit=*/false, 4710198092Srdivacky /*ForceRValue=*/false, 4711198092Srdivacky /*InOverloadResolution=*/false); 4712198092Srdivacky 4713193326Sed // Of course, that's still a reference binding. 4714202379Srdivacky if (ICS->isStandard()) { 4715193326Sed ICS->Standard.ReferenceBinding = true; 4716193326Sed ICS->Standard.RRefBinding = isRValRef; 4717202379Srdivacky } else if (ICS->isUserDefined()) { 4718193326Sed ICS->UserDefined.After.ReferenceBinding = true; 4719193326Sed ICS->UserDefined.After.RRefBinding = isRValRef; 4720193326Sed } 4721202379Srdivacky return ICS->isBad(); 4722193326Sed } else { 4723198092Srdivacky ImplicitConversionSequence Conversions; 4724201361Srdivacky bool badConversion = PerformImplicitConversion(Init, T1, AA_Initializing, 4725198092Srdivacky false, false, 4726198092Srdivacky Conversions); 4727198092Srdivacky if (badConversion) { 4728202379Srdivacky if (Conversions.isAmbiguous()) { 4729198092Srdivacky Diag(DeclLoc, 4730198092Srdivacky diag::err_lvalue_to_rvalue_ambig_ref) << Init->getSourceRange(); 4731202379Srdivacky for (int j = Conversions.Ambiguous.conversions().size()-1; 4732198092Srdivacky j >= 0; j--) { 4733202379Srdivacky FunctionDecl *Func = Conversions.Ambiguous.conversions()[j]; 4734202379Srdivacky NoteOverloadCandidate(Func); 4735198092Srdivacky } 4736198092Srdivacky } 4737198092Srdivacky else { 4738198092Srdivacky if (isRValRef) 4739198092Srdivacky Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref) 4740198092Srdivacky << Init->getSourceRange(); 4741198092Srdivacky else 4742198092Srdivacky Diag(DeclLoc, diag::err_invalid_initialization) 4743198092Srdivacky << DeclType << Init->getType() << Init->getSourceRange(); 4744198092Srdivacky } 4745198092Srdivacky } 4746198092Srdivacky return badConversion; 4747193326Sed } 4748193326Sed} 4749193326Sed 4750200583Srdivackystatic inline bool 4751200583SrdivackyCheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 4752200583Srdivacky const FunctionDecl *FnDecl) { 4753200583Srdivacky const DeclContext *DC = FnDecl->getDeclContext()->getLookupContext(); 4754200583Srdivacky if (isa<NamespaceDecl>(DC)) { 4755200583Srdivacky return SemaRef.Diag(FnDecl->getLocation(), 4756200583Srdivacky diag::err_operator_new_delete_declared_in_namespace) 4757200583Srdivacky << FnDecl->getDeclName(); 4758200583Srdivacky } 4759200583Srdivacky 4760200583Srdivacky if (isa<TranslationUnitDecl>(DC) && 4761200583Srdivacky FnDecl->getStorageClass() == FunctionDecl::Static) { 4762200583Srdivacky return SemaRef.Diag(FnDecl->getLocation(), 4763200583Srdivacky diag::err_operator_new_delete_declared_static) 4764200583Srdivacky << FnDecl->getDeclName(); 4765200583Srdivacky } 4766200583Srdivacky 4767200583Srdivacky return false; 4768200583Srdivacky} 4769200583Srdivacky 4770200583Srdivackystatic inline bool 4771200583SrdivackyCheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 4772200583Srdivacky CanQualType ExpectedResultType, 4773200583Srdivacky CanQualType ExpectedFirstParamType, 4774200583Srdivacky unsigned DependentParamTypeDiag, 4775200583Srdivacky unsigned InvalidParamTypeDiag) { 4776200583Srdivacky QualType ResultType = 4777200583Srdivacky FnDecl->getType()->getAs<FunctionType>()->getResultType(); 4778200583Srdivacky 4779200583Srdivacky // Check that the result type is not dependent. 4780200583Srdivacky if (ResultType->isDependentType()) 4781200583Srdivacky return SemaRef.Diag(FnDecl->getLocation(), 4782200583Srdivacky diag::err_operator_new_delete_dependent_result_type) 4783200583Srdivacky << FnDecl->getDeclName() << ExpectedResultType; 4784200583Srdivacky 4785200583Srdivacky // Check that the result type is what we expect. 4786200583Srdivacky if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 4787200583Srdivacky return SemaRef.Diag(FnDecl->getLocation(), 4788200583Srdivacky diag::err_operator_new_delete_invalid_result_type) 4789200583Srdivacky << FnDecl->getDeclName() << ExpectedResultType; 4790200583Srdivacky 4791200583Srdivacky // A function template must have at least 2 parameters. 4792200583Srdivacky if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 4793200583Srdivacky return SemaRef.Diag(FnDecl->getLocation(), 4794200583Srdivacky diag::err_operator_new_delete_template_too_few_parameters) 4795200583Srdivacky << FnDecl->getDeclName(); 4796200583Srdivacky 4797200583Srdivacky // The function decl must have at least 1 parameter. 4798200583Srdivacky if (FnDecl->getNumParams() == 0) 4799200583Srdivacky return SemaRef.Diag(FnDecl->getLocation(), 4800200583Srdivacky diag::err_operator_new_delete_too_few_parameters) 4801200583Srdivacky << FnDecl->getDeclName(); 4802200583Srdivacky 4803200583Srdivacky // Check the the first parameter type is not dependent. 4804200583Srdivacky QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 4805200583Srdivacky if (FirstParamType->isDependentType()) 4806200583Srdivacky return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 4807200583Srdivacky << FnDecl->getDeclName() << ExpectedFirstParamType; 4808200583Srdivacky 4809200583Srdivacky // Check that the first parameter type is what we expect. 4810201361Srdivacky if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 4811200583Srdivacky ExpectedFirstParamType) 4812200583Srdivacky return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 4813200583Srdivacky << FnDecl->getDeclName() << ExpectedFirstParamType; 4814200583Srdivacky 4815200583Srdivacky return false; 4816200583Srdivacky} 4817200583Srdivacky 4818200583Srdivackystatic bool 4819200583SrdivackyCheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 4820200583Srdivacky // C++ [basic.stc.dynamic.allocation]p1: 4821200583Srdivacky // A program is ill-formed if an allocation function is declared in a 4822200583Srdivacky // namespace scope other than global scope or declared static in global 4823200583Srdivacky // scope. 4824200583Srdivacky if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 4825200583Srdivacky return true; 4826200583Srdivacky 4827200583Srdivacky CanQualType SizeTy = 4828200583Srdivacky SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 4829200583Srdivacky 4830200583Srdivacky // C++ [basic.stc.dynamic.allocation]p1: 4831200583Srdivacky // The return type shall be void*. The first parameter shall have type 4832200583Srdivacky // std::size_t. 4833200583Srdivacky if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 4834200583Srdivacky SizeTy, 4835200583Srdivacky diag::err_operator_new_dependent_param_type, 4836200583Srdivacky diag::err_operator_new_param_type)) 4837200583Srdivacky return true; 4838200583Srdivacky 4839200583Srdivacky // C++ [basic.stc.dynamic.allocation]p1: 4840200583Srdivacky // The first parameter shall not have an associated default argument. 4841200583Srdivacky if (FnDecl->getParamDecl(0)->hasDefaultArg()) 4842200583Srdivacky return SemaRef.Diag(FnDecl->getLocation(), 4843200583Srdivacky diag::err_operator_new_default_arg) 4844200583Srdivacky << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 4845200583Srdivacky 4846200583Srdivacky return false; 4847200583Srdivacky} 4848200583Srdivacky 4849200583Srdivackystatic bool 4850200583SrdivackyCheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 4851200583Srdivacky // C++ [basic.stc.dynamic.deallocation]p1: 4852200583Srdivacky // A program is ill-formed if deallocation functions are declared in a 4853200583Srdivacky // namespace scope other than global scope or declared static in global 4854200583Srdivacky // scope. 4855200583Srdivacky if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 4856200583Srdivacky return true; 4857200583Srdivacky 4858200583Srdivacky // C++ [basic.stc.dynamic.deallocation]p2: 4859200583Srdivacky // Each deallocation function shall return void and its first parameter 4860200583Srdivacky // shall be void*. 4861200583Srdivacky if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 4862200583Srdivacky SemaRef.Context.VoidPtrTy, 4863200583Srdivacky diag::err_operator_delete_dependent_param_type, 4864200583Srdivacky diag::err_operator_delete_param_type)) 4865200583Srdivacky return true; 4866200583Srdivacky 4867200583Srdivacky QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 4868200583Srdivacky if (FirstParamType->isDependentType()) 4869200583Srdivacky return SemaRef.Diag(FnDecl->getLocation(), 4870200583Srdivacky diag::err_operator_delete_dependent_param_type) 4871200583Srdivacky << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy; 4872200583Srdivacky 4873200583Srdivacky if (SemaRef.Context.getCanonicalType(FirstParamType) != 4874200583Srdivacky SemaRef.Context.VoidPtrTy) 4875200583Srdivacky return SemaRef.Diag(FnDecl->getLocation(), 4876200583Srdivacky diag::err_operator_delete_param_type) 4877200583Srdivacky << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy; 4878200583Srdivacky 4879200583Srdivacky return false; 4880200583Srdivacky} 4881200583Srdivacky 4882193326Sed/// CheckOverloadedOperatorDeclaration - Check whether the declaration 4883193326Sed/// of this overloaded operator is well-formed. If so, returns false; 4884193326Sed/// otherwise, emits appropriate diagnostics and returns true. 4885193326Sedbool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 4886193326Sed assert(FnDecl && FnDecl->isOverloadedOperator() && 4887193326Sed "Expected an overloaded operator declaration"); 4888193326Sed 4889193326Sed OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 4890193326Sed 4891198092Srdivacky // C++ [over.oper]p5: 4892193326Sed // The allocation and deallocation functions, operator new, 4893193326Sed // operator new[], operator delete and operator delete[], are 4894193326Sed // described completely in 3.7.3. The attributes and restrictions 4895193326Sed // found in the rest of this subclause do not apply to them unless 4896193326Sed // explicitly stated in 3.7.3. 4897199482Srdivacky if (Op == OO_Delete || Op == OO_Array_Delete) 4898200583Srdivacky return CheckOperatorDeleteDeclaration(*this, FnDecl); 4899199482Srdivacky 4900200583Srdivacky if (Op == OO_New || Op == OO_Array_New) 4901200583Srdivacky return CheckOperatorNewDeclaration(*this, FnDecl); 4902193326Sed 4903193326Sed // C++ [over.oper]p6: 4904193326Sed // An operator function shall either be a non-static member 4905193326Sed // function or be a non-member function and have at least one 4906193326Sed // parameter whose type is a class, a reference to a class, an 4907193326Sed // enumeration, or a reference to an enumeration. 4908193326Sed if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 4909193326Sed if (MethodDecl->isStatic()) 4910193326Sed return Diag(FnDecl->getLocation(), 4911193326Sed diag::err_operator_overload_static) << FnDecl->getDeclName(); 4912193326Sed } else { 4913193326Sed bool ClassOrEnumParam = false; 4914193326Sed for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 4915193326Sed ParamEnd = FnDecl->param_end(); 4916193326Sed Param != ParamEnd; ++Param) { 4917193326Sed QualType ParamType = (*Param)->getType().getNonReferenceType(); 4918195099Sed if (ParamType->isDependentType() || ParamType->isRecordType() || 4919195099Sed ParamType->isEnumeralType()) { 4920193326Sed ClassOrEnumParam = true; 4921193326Sed break; 4922193326Sed } 4923193326Sed } 4924193326Sed 4925193326Sed if (!ClassOrEnumParam) 4926193326Sed return Diag(FnDecl->getLocation(), 4927193326Sed diag::err_operator_overload_needs_class_or_enum) 4928193326Sed << FnDecl->getDeclName(); 4929193326Sed } 4930193326Sed 4931193326Sed // C++ [over.oper]p8: 4932193326Sed // An operator function cannot have default arguments (8.3.6), 4933193326Sed // except where explicitly stated below. 4934193326Sed // 4935198092Srdivacky // Only the function-call operator allows default arguments 4936193326Sed // (C++ [over.call]p1). 4937193326Sed if (Op != OO_Call) { 4938193326Sed for (FunctionDecl::param_iterator Param = FnDecl->param_begin(); 4939193326Sed Param != FnDecl->param_end(); ++Param) { 4940200583Srdivacky if ((*Param)->hasDefaultArg()) 4941198092Srdivacky return Diag((*Param)->getLocation(), 4942193326Sed diag::err_operator_overload_default_arg) 4943200583Srdivacky << FnDecl->getDeclName() << (*Param)->getDefaultArgRange(); 4944193326Sed } 4945193326Sed } 4946193326Sed 4947193326Sed static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 4948193326Sed { false, false, false } 4949193326Sed#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 4950193326Sed , { Unary, Binary, MemberOnly } 4951193326Sed#include "clang/Basic/OperatorKinds.def" 4952193326Sed }; 4953193326Sed 4954193326Sed bool CanBeUnaryOperator = OperatorUses[Op][0]; 4955193326Sed bool CanBeBinaryOperator = OperatorUses[Op][1]; 4956193326Sed bool MustBeMemberOperator = OperatorUses[Op][2]; 4957193326Sed 4958193326Sed // C++ [over.oper]p8: 4959193326Sed // [...] Operator functions cannot have more or fewer parameters 4960193326Sed // than the number required for the corresponding operator, as 4961193326Sed // described in the rest of this subclause. 4962198092Srdivacky unsigned NumParams = FnDecl->getNumParams() 4963193326Sed + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 4964193326Sed if (Op != OO_Call && 4965193326Sed ((NumParams == 1 && !CanBeUnaryOperator) || 4966193326Sed (NumParams == 2 && !CanBeBinaryOperator) || 4967193326Sed (NumParams < 1) || (NumParams > 2))) { 4968193326Sed // We have the wrong number of parameters. 4969193326Sed unsigned ErrorKind; 4970193326Sed if (CanBeUnaryOperator && CanBeBinaryOperator) { 4971193326Sed ErrorKind = 2; // 2 -> unary or binary. 4972193326Sed } else if (CanBeUnaryOperator) { 4973193326Sed ErrorKind = 0; // 0 -> unary 4974193326Sed } else { 4975193326Sed assert(CanBeBinaryOperator && 4976193326Sed "All non-call overloaded operators are unary or binary!"); 4977193326Sed ErrorKind = 1; // 1 -> binary 4978193326Sed } 4979193326Sed 4980193326Sed return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 4981193326Sed << FnDecl->getDeclName() << NumParams << ErrorKind; 4982193326Sed } 4983193326Sed 4984193326Sed // Overloaded operators other than operator() cannot be variadic. 4985193326Sed if (Op != OO_Call && 4986198092Srdivacky FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 4987193326Sed return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 4988193326Sed << FnDecl->getDeclName(); 4989193326Sed } 4990193326Sed 4991193326Sed // Some operators must be non-static member functions. 4992193326Sed if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 4993193326Sed return Diag(FnDecl->getLocation(), 4994193326Sed diag::err_operator_overload_must_be_member) 4995193326Sed << FnDecl->getDeclName(); 4996193326Sed } 4997193326Sed 4998193326Sed // C++ [over.inc]p1: 4999193326Sed // The user-defined function called operator++ implements the 5000193326Sed // prefix and postfix ++ operator. If this function is a member 5001193326Sed // function with no parameters, or a non-member function with one 5002193326Sed // parameter of class or enumeration type, it defines the prefix 5003193326Sed // increment operator ++ for objects of that type. If the function 5004193326Sed // is a member function with one parameter (which shall be of type 5005193326Sed // int) or a non-member function with two parameters (the second 5006193326Sed // of which shall be of type int), it defines the postfix 5007193326Sed // increment operator ++ for objects of that type. 5008193326Sed if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 5009193326Sed ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 5010193326Sed bool ParamIsInt = false; 5011198092Srdivacky if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>()) 5012193326Sed ParamIsInt = BT->getKind() == BuiltinType::Int; 5013193326Sed 5014193326Sed if (!ParamIsInt) 5015193326Sed return Diag(LastParam->getLocation(), 5016198092Srdivacky diag::err_operator_overload_post_incdec_must_be_int) 5017193326Sed << LastParam->getType() << (Op == OO_MinusMinus); 5018193326Sed } 5019193326Sed 5020193326Sed // Notify the class if it got an assignment operator. 5021193326Sed if (Op == OO_Equal) { 5022193326Sed // Would have returned earlier otherwise. 5023193326Sed assert(isa<CXXMethodDecl>(FnDecl) && 5024193326Sed "Overloaded = not member, but not filtered."); 5025193326Sed CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 5026193326Sed Method->getParent()->addedAssignmentOperator(Context, Method); 5027193326Sed } 5028193326Sed 5029193326Sed return false; 5030193326Sed} 5031193326Sed 5032202379Srdivacky/// CheckLiteralOperatorDeclaration - Check whether the declaration 5033202379Srdivacky/// of this literal operator function is well-formed. If so, returns 5034202379Srdivacky/// false; otherwise, emits appropriate diagnostics and returns true. 5035202379Srdivackybool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 5036202379Srdivacky DeclContext *DC = FnDecl->getDeclContext(); 5037202379Srdivacky Decl::Kind Kind = DC->getDeclKind(); 5038202379Srdivacky if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace && 5039202379Srdivacky Kind != Decl::LinkageSpec) { 5040202379Srdivacky Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 5041202379Srdivacky << FnDecl->getDeclName(); 5042202379Srdivacky return true; 5043202379Srdivacky } 5044202379Srdivacky 5045202379Srdivacky bool Valid = false; 5046202379Srdivacky 5047202379Srdivacky // FIXME: Check for the one valid template signature 5048202379Srdivacky // template <char...> type operator "" name(); 5049202379Srdivacky 5050202379Srdivacky if (FunctionDecl::param_iterator Param = FnDecl->param_begin()) { 5051202379Srdivacky // Check the first parameter 5052202379Srdivacky QualType T = (*Param)->getType(); 5053202379Srdivacky 5054202379Srdivacky // unsigned long long int and long double are allowed, but only 5055202379Srdivacky // alone. 5056202379Srdivacky // We also allow any character type; their omission seems to be a bug 5057202379Srdivacky // in n3000 5058202379Srdivacky if (Context.hasSameType(T, Context.UnsignedLongLongTy) || 5059202379Srdivacky Context.hasSameType(T, Context.LongDoubleTy) || 5060202379Srdivacky Context.hasSameType(T, Context.CharTy) || 5061202379Srdivacky Context.hasSameType(T, Context.WCharTy) || 5062202379Srdivacky Context.hasSameType(T, Context.Char16Ty) || 5063202379Srdivacky Context.hasSameType(T, Context.Char32Ty)) { 5064202379Srdivacky if (++Param == FnDecl->param_end()) 5065202379Srdivacky Valid = true; 5066202379Srdivacky goto FinishedParams; 5067202379Srdivacky } 5068202379Srdivacky 5069202379Srdivacky // Otherwise it must be a pointer to const; let's strip those. 5070202379Srdivacky const PointerType *PT = T->getAs<PointerType>(); 5071202379Srdivacky if (!PT) 5072202379Srdivacky goto FinishedParams; 5073202379Srdivacky T = PT->getPointeeType(); 5074202379Srdivacky if (!T.isConstQualified()) 5075202379Srdivacky goto FinishedParams; 5076202379Srdivacky T = T.getUnqualifiedType(); 5077202379Srdivacky 5078202379Srdivacky // Move on to the second parameter; 5079202379Srdivacky ++Param; 5080202379Srdivacky 5081202379Srdivacky // If there is no second parameter, the first must be a const char * 5082202379Srdivacky if (Param == FnDecl->param_end()) { 5083202379Srdivacky if (Context.hasSameType(T, Context.CharTy)) 5084202379Srdivacky Valid = true; 5085202379Srdivacky goto FinishedParams; 5086202379Srdivacky } 5087202379Srdivacky 5088202379Srdivacky // const char *, const wchar_t*, const char16_t*, and const char32_t* 5089202379Srdivacky // are allowed as the first parameter to a two-parameter function 5090202379Srdivacky if (!(Context.hasSameType(T, Context.CharTy) || 5091202379Srdivacky Context.hasSameType(T, Context.WCharTy) || 5092202379Srdivacky Context.hasSameType(T, Context.Char16Ty) || 5093202379Srdivacky Context.hasSameType(T, Context.Char32Ty))) 5094202379Srdivacky goto FinishedParams; 5095202379Srdivacky 5096202379Srdivacky // The second and final parameter must be an std::size_t 5097202379Srdivacky T = (*Param)->getType().getUnqualifiedType(); 5098202379Srdivacky if (Context.hasSameType(T, Context.getSizeType()) && 5099202379Srdivacky ++Param == FnDecl->param_end()) 5100202379Srdivacky Valid = true; 5101202379Srdivacky } 5102202379Srdivacky 5103202379Srdivacky // FIXME: This diagnostic is absolutely terrible. 5104202379SrdivackyFinishedParams: 5105202379Srdivacky if (!Valid) { 5106202379Srdivacky Diag(FnDecl->getLocation(), diag::err_literal_operator_params) 5107202379Srdivacky << FnDecl->getDeclName(); 5108202379Srdivacky return true; 5109202379Srdivacky } 5110202379Srdivacky 5111202379Srdivacky return false; 5112202379Srdivacky} 5113202379Srdivacky 5114193326Sed/// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 5115193326Sed/// linkage specification, including the language and (if present) 5116193326Sed/// the '{'. ExternLoc is the location of the 'extern', LangLoc is 5117193326Sed/// the location of the language string literal, which is provided 5118193326Sed/// by Lang/StrSize. LBraceLoc, if valid, provides the location of 5119193326Sed/// the '{' brace. Otherwise, this linkage specification does not 5120193326Sed/// have any braces. 5121193326SedSema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S, 5122193326Sed SourceLocation ExternLoc, 5123193326Sed SourceLocation LangLoc, 5124193326Sed const char *Lang, 5125193326Sed unsigned StrSize, 5126193326Sed SourceLocation LBraceLoc) { 5127193326Sed LinkageSpecDecl::LanguageIDs Language; 5128193326Sed if (strncmp(Lang, "\"C\"", StrSize) == 0) 5129193326Sed Language = LinkageSpecDecl::lang_c; 5130193326Sed else if (strncmp(Lang, "\"C++\"", StrSize) == 0) 5131193326Sed Language = LinkageSpecDecl::lang_cxx; 5132193326Sed else { 5133193326Sed Diag(LangLoc, diag::err_bad_language); 5134193326Sed return DeclPtrTy(); 5135193326Sed } 5136198092Srdivacky 5137193326Sed // FIXME: Add all the various semantics of linkage specifications 5138198092Srdivacky 5139193326Sed LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, 5140198092Srdivacky LangLoc, Language, 5141193326Sed LBraceLoc.isValid()); 5142195341Sed CurContext->addDecl(D); 5143193326Sed PushDeclContext(S, D); 5144193326Sed return DeclPtrTy::make(D); 5145193326Sed} 5146193326Sed 5147193326Sed/// ActOnFinishLinkageSpecification - Completely the definition of 5148193326Sed/// the C++ linkage specification LinkageSpec. If RBraceLoc is 5149193326Sed/// valid, it's the position of the closing '}' brace in a linkage 5150193326Sed/// specification that uses braces. 5151193326SedSema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S, 5152193326Sed DeclPtrTy LinkageSpec, 5153193326Sed SourceLocation RBraceLoc) { 5154193326Sed if (LinkageSpec) 5155193326Sed PopDeclContext(); 5156193326Sed return LinkageSpec; 5157193326Sed} 5158193326Sed 5159193326Sed/// \brief Perform semantic analysis for the variable declaration that 5160193326Sed/// occurs within a C++ catch clause, returning the newly-created 5161193326Sed/// variable. 5162193326SedVarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType, 5163200583Srdivacky TypeSourceInfo *TInfo, 5164193326Sed IdentifierInfo *Name, 5165193326Sed SourceLocation Loc, 5166193326Sed SourceRange Range) { 5167193326Sed bool Invalid = false; 5168193326Sed 5169193326Sed // Arrays and functions decay. 5170193326Sed if (ExDeclType->isArrayType()) 5171193326Sed ExDeclType = Context.getArrayDecayedType(ExDeclType); 5172193326Sed else if (ExDeclType->isFunctionType()) 5173193326Sed ExDeclType = Context.getPointerType(ExDeclType); 5174193326Sed 5175193326Sed // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 5176193326Sed // The exception-declaration shall not denote a pointer or reference to an 5177193326Sed // incomplete type, other than [cv] void*. 5178193326Sed // N2844 forbids rvalue references. 5179198092Srdivacky if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 5180193326Sed Diag(Loc, diag::err_catch_rvalue_ref) << Range; 5181193326Sed Invalid = true; 5182193326Sed } 5183193326Sed 5184204962Srdivacky // GCC allows catching pointers and references to incomplete types 5185204962Srdivacky // as an extension; so do we, but we warn by default. 5186204962Srdivacky 5187193326Sed QualType BaseType = ExDeclType; 5188193326Sed int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 5189193326Sed unsigned DK = diag::err_catch_incomplete; 5190204962Srdivacky bool IncompleteCatchIsInvalid = true; 5191198092Srdivacky if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 5192193326Sed BaseType = Ptr->getPointeeType(); 5193193326Sed Mode = 1; 5194204962Srdivacky DK = diag::ext_catch_incomplete_ptr; 5195204962Srdivacky IncompleteCatchIsInvalid = false; 5196198092Srdivacky } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 5197193326Sed // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 5198193326Sed BaseType = Ref->getPointeeType(); 5199193326Sed Mode = 2; 5200204962Srdivacky DK = diag::ext_catch_incomplete_ref; 5201204962Srdivacky IncompleteCatchIsInvalid = false; 5202193326Sed } 5203193326Sed if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 5204204962Srdivacky !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) && 5205204962Srdivacky IncompleteCatchIsInvalid) 5206193326Sed Invalid = true; 5207193326Sed 5208198092Srdivacky if (!Invalid && !ExDeclType->isDependentType() && 5209193326Sed RequireNonAbstractType(Loc, ExDeclType, 5210193326Sed diag::err_abstract_type_in_decl, 5211193326Sed AbstractVariableType)) 5212193326Sed Invalid = true; 5213193326Sed 5214198092Srdivacky VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc, 5215200583Srdivacky Name, ExDeclType, TInfo, VarDecl::None); 5216193326Sed 5217204793Srdivacky if (!Invalid) { 5218204793Srdivacky if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) { 5219204793Srdivacky // C++ [except.handle]p16: 5220204793Srdivacky // The object declared in an exception-declaration or, if the 5221204793Srdivacky // exception-declaration does not specify a name, a temporary (12.2) is 5222204793Srdivacky // copy-initialized (8.5) from the exception object. [...] 5223204793Srdivacky // The object is destroyed when the handler exits, after the destruction 5224204793Srdivacky // of any automatic objects initialized within the handler. 5225204793Srdivacky // 5226204793Srdivacky // We just pretend to initialize the object with itself, then make sure 5227204793Srdivacky // it can be destroyed later. 5228204793Srdivacky InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl); 5229204793Srdivacky Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl, 5230204793Srdivacky Loc, ExDeclType, 0); 5231204793Srdivacky InitializationKind Kind = InitializationKind::CreateCopy(Loc, 5232204793Srdivacky SourceLocation()); 5233204793Srdivacky InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1); 5234204793Srdivacky OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, 5235204793Srdivacky MultiExprArg(*this, (void**)&ExDeclRef, 1)); 5236204793Srdivacky if (Result.isInvalid()) 5237204793Srdivacky Invalid = true; 5238204793Srdivacky else 5239204793Srdivacky FinalizeVarWithDestructor(ExDecl, RecordTy); 5240204793Srdivacky } 5241204793Srdivacky } 5242204793Srdivacky 5243193326Sed if (Invalid) 5244193326Sed ExDecl->setInvalidDecl(); 5245193326Sed 5246193326Sed return ExDecl; 5247193326Sed} 5248193326Sed 5249193326Sed/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 5250193326Sed/// handler. 5251193326SedSema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 5252200583Srdivacky TypeSourceInfo *TInfo = 0; 5253200583Srdivacky QualType ExDeclType = GetTypeForDeclarator(D, S, &TInfo); 5254193326Sed 5255193326Sed bool Invalid = D.isInvalidType(); 5256193326Sed IdentifierInfo *II = D.getIdentifier(); 5257198092Srdivacky if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) { 5258193326Sed // The scope should be freshly made just for us. There is just no way 5259193326Sed // it contains any previous declaration. 5260193326Sed assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl))); 5261193326Sed if (PrevDecl->isTemplateParameter()) { 5262193326Sed // Maybe we will complain about the shadowed template parameter. 5263193326Sed DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 5264193326Sed } 5265193326Sed } 5266193326Sed 5267193326Sed if (D.getCXXScopeSpec().isSet() && !Invalid) { 5268193326Sed Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 5269193326Sed << D.getCXXScopeSpec().getRange(); 5270193326Sed Invalid = true; 5271193326Sed } 5272193326Sed 5273200583Srdivacky VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, TInfo, 5274193326Sed D.getIdentifier(), 5275193326Sed D.getIdentifierLoc(), 5276193326Sed D.getDeclSpec().getSourceRange()); 5277193326Sed 5278193326Sed if (Invalid) 5279193326Sed ExDecl->setInvalidDecl(); 5280198092Srdivacky 5281193326Sed // Add the exception declaration into this scope. 5282193326Sed if (II) 5283193326Sed PushOnScopeChains(ExDecl, S); 5284193326Sed else 5285195341Sed CurContext->addDecl(ExDecl); 5286193326Sed 5287194613Sed ProcessDeclAttributes(S, ExDecl, D); 5288193326Sed return DeclPtrTy::make(ExDecl); 5289193326Sed} 5290193326Sed 5291198092SrdivackySema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc, 5292193326Sed ExprArg assertexpr, 5293193326Sed ExprArg assertmessageexpr) { 5294193326Sed Expr *AssertExpr = (Expr *)assertexpr.get(); 5295198092Srdivacky StringLiteral *AssertMessage = 5296193326Sed cast<StringLiteral>((Expr *)assertmessageexpr.get()); 5297193326Sed 5298193326Sed if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) { 5299193326Sed llvm::APSInt Value(32); 5300193326Sed if (!AssertExpr->isIntegerConstantExpr(Value, Context)) { 5301193326Sed Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) << 5302193326Sed AssertExpr->getSourceRange(); 5303193326Sed return DeclPtrTy(); 5304193326Sed } 5305193326Sed 5306193326Sed if (Value == 0) { 5307198092Srdivacky Diag(AssertLoc, diag::err_static_assert_failed) 5308200583Srdivacky << AssertMessage->getString() << AssertExpr->getSourceRange(); 5309193326Sed } 5310193326Sed } 5311198092Srdivacky 5312193326Sed assertexpr.release(); 5313193326Sed assertmessageexpr.release(); 5314198092Srdivacky Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc, 5315193326Sed AssertExpr, AssertMessage); 5316198092Srdivacky 5317195341Sed CurContext->addDecl(Decl); 5318193326Sed return DeclPtrTy::make(Decl); 5319193326Sed} 5320193326Sed 5321198092Srdivacky/// Handle a friend type declaration. This works in tandem with 5322198092Srdivacky/// ActOnTag. 5323198092Srdivacky/// 5324198092Srdivacky/// Notes on friend class templates: 5325198092Srdivacky/// 5326198092Srdivacky/// We generally treat friend class declarations as if they were 5327198092Srdivacky/// declaring a class. So, for example, the elaborated type specifier 5328198092Srdivacky/// in a friend declaration is required to obey the restrictions of a 5329198092Srdivacky/// class-head (i.e. no typedefs in the scope chain), template 5330198092Srdivacky/// parameters are required to match up with simple template-ids, &c. 5331198092Srdivacky/// However, unlike when declaring a template specialization, it's 5332198092Srdivacky/// okay to refer to a template specialization without an empty 5333198092Srdivacky/// template parameter declaration, e.g. 5334198092Srdivacky/// friend class A<T>::B<unsigned>; 5335198092Srdivacky/// We permit this as a special case; if there are any template 5336198092Srdivacky/// parameters present at all, require proper matching, i.e. 5337198092Srdivacky/// template <> template <class T> friend class A<int>::B; 5338198893SrdivackySema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 5339198092Srdivacky MultiTemplateParamsArg TempParams) { 5340198092Srdivacky SourceLocation Loc = DS.getSourceRange().getBegin(); 5341198092Srdivacky 5342198092Srdivacky assert(DS.isFriendSpecified()); 5343198092Srdivacky assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 5344198092Srdivacky 5345198092Srdivacky // Try to convert the decl specifier to a type. This works for 5346198092Srdivacky // friend templates because ActOnTag never produces a ClassTemplateDecl 5347198092Srdivacky // for a TUK_Friend. 5348198893Srdivacky Declarator TheDeclarator(DS, Declarator::MemberContext); 5349206084Srdivacky TypeSourceInfo *TSI; 5350206084Srdivacky QualType T = GetTypeForDeclarator(TheDeclarator, S, &TSI); 5351198893Srdivacky if (TheDeclarator.isInvalidType()) 5352198893Srdivacky return DeclPtrTy(); 5353198092Srdivacky 5354198092Srdivacky // This is definitely an error in C++98. It's probably meant to 5355198092Srdivacky // be forbidden in C++0x, too, but the specification is just 5356198092Srdivacky // poorly written. 5357198092Srdivacky // 5358198092Srdivacky // The problem is with declarations like the following: 5359198092Srdivacky // template <T> friend A<T>::foo; 5360198092Srdivacky // where deciding whether a class C is a friend or not now hinges 5361198092Srdivacky // on whether there exists an instantiation of A that causes 5362198092Srdivacky // 'foo' to equal C. There are restrictions on class-heads 5363198092Srdivacky // (which we declare (by fiat) elaborated friend declarations to 5364198092Srdivacky // be) that makes this tractable. 5365198092Srdivacky // 5366198092Srdivacky // FIXME: handle "template <> friend class A<T>;", which 5367198092Srdivacky // is possibly well-formed? Who even knows? 5368206084Srdivacky if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 5369198092Srdivacky Diag(Loc, diag::err_tagless_friend_type_template) 5370198092Srdivacky << DS.getSourceRange(); 5371198092Srdivacky return DeclPtrTy(); 5372193326Sed } 5373198092Srdivacky 5374198092Srdivacky // C++ [class.friend]p2: 5375198092Srdivacky // An elaborated-type-specifier shall be used in a friend declaration 5376198092Srdivacky // for a class.* 5377198092Srdivacky // * The class-key of the elaborated-type-specifier is required. 5378198092Srdivacky // This is one of the rare places in Clang where it's legitimate to 5379198092Srdivacky // ask about the "spelling" of the type. 5380206084Srdivacky if (!getLangOptions().CPlusPlus0x && !T->isElaboratedTypeSpecifier()) { 5381198092Srdivacky // If we evaluated the type to a record type, suggest putting 5382198092Srdivacky // a tag in front. 5383198092Srdivacky if (const RecordType *RT = T->getAs<RecordType>()) { 5384198092Srdivacky RecordDecl *RD = RT->getDecl(); 5385198092Srdivacky 5386198092Srdivacky std::string InsertionText = std::string(" ") + RD->getKindName(); 5387198092Srdivacky 5388198092Srdivacky Diag(DS.getTypeSpecTypeLoc(), diag::err_unelaborated_friend_type) 5389198092Srdivacky << (unsigned) RD->getTagKind() 5390198092Srdivacky << T 5391198092Srdivacky << SourceRange(DS.getFriendSpecLoc()) 5392206084Srdivacky << FixItHint::CreateInsertion(DS.getTypeSpecTypeLoc(), InsertionText); 5393198092Srdivacky return DeclPtrTy(); 5394198092Srdivacky }else { 5395198092Srdivacky Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend) 5396198092Srdivacky << DS.getSourceRange(); 5397198092Srdivacky return DeclPtrTy(); 5398198092Srdivacky } 5399198092Srdivacky } 5400198092Srdivacky 5401198092Srdivacky // Enum types cannot be friends. 5402198092Srdivacky if (T->getAs<EnumType>()) { 5403198092Srdivacky Diag(DS.getTypeSpecTypeLoc(), diag::err_enum_friend) 5404198092Srdivacky << SourceRange(DS.getFriendSpecLoc()); 5405198092Srdivacky return DeclPtrTy(); 5406198092Srdivacky } 5407198092Srdivacky 5408198092Srdivacky // C++98 [class.friend]p1: A friend of a class is a function 5409198092Srdivacky // or class that is not a member of the class . . . 5410201361Srdivacky // This is fixed in DR77, which just barely didn't make the C++03 5411201361Srdivacky // deadline. It's also a very silly restriction that seriously 5412201361Srdivacky // affects inner classes and which nobody else seems to implement; 5413201361Srdivacky // thus we never diagnose it, not even in -pedantic. 5414206084Srdivacky // 5415206084Srdivacky // But note that we could warn about it: it's always useless to 5416206084Srdivacky // friend one of your own members (it's not, however, worthless to 5417206084Srdivacky // friend a member of an arbitrary specialization of your template). 5418198092Srdivacky 5419198092Srdivacky Decl *D; 5420198092Srdivacky if (TempParams.size()) 5421198092Srdivacky D = FriendTemplateDecl::Create(Context, CurContext, Loc, 5422198092Srdivacky TempParams.size(), 5423198092Srdivacky (TemplateParameterList**) TempParams.release(), 5424206084Srdivacky TSI, 5425198092Srdivacky DS.getFriendSpecLoc()); 5426198092Srdivacky else 5427206084Srdivacky D = FriendDecl::Create(Context, CurContext, Loc, TSI, 5428198092Srdivacky DS.getFriendSpecLoc()); 5429198092Srdivacky D->setAccess(AS_public); 5430198092Srdivacky CurContext->addDecl(D); 5431198092Srdivacky 5432198092Srdivacky return DeclPtrTy::make(D); 5433193326Sed} 5434193326Sed 5435198092SrdivackySema::DeclPtrTy 5436198092SrdivackySema::ActOnFriendFunctionDecl(Scope *S, 5437198092Srdivacky Declarator &D, 5438198092Srdivacky bool IsDefinition, 5439198092Srdivacky MultiTemplateParamsArg TemplateParams) { 5440198092Srdivacky const DeclSpec &DS = D.getDeclSpec(); 5441198092Srdivacky 5442198092Srdivacky assert(DS.isFriendSpecified()); 5443198092Srdivacky assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 5444198092Srdivacky 5445198092Srdivacky SourceLocation Loc = D.getIdentifierLoc(); 5446200583Srdivacky TypeSourceInfo *TInfo = 0; 5447200583Srdivacky QualType T = GetTypeForDeclarator(D, S, &TInfo); 5448198092Srdivacky 5449198092Srdivacky // C++ [class.friend]p1 5450198092Srdivacky // A friend of a class is a function or class.... 5451198092Srdivacky // Note that this sees through typedefs, which is intended. 5452198092Srdivacky // It *doesn't* see through dependent types, which is correct 5453198092Srdivacky // according to [temp.arg.type]p3: 5454198092Srdivacky // If a declaration acquires a function type through a 5455198092Srdivacky // type dependent on a template-parameter and this causes 5456198092Srdivacky // a declaration that does not use the syntactic form of a 5457198092Srdivacky // function declarator to have a function type, the program 5458198092Srdivacky // is ill-formed. 5459198092Srdivacky if (!T->isFunctionType()) { 5460198092Srdivacky Diag(Loc, diag::err_unexpected_friend); 5461198092Srdivacky 5462198092Srdivacky // It might be worthwhile to try to recover by creating an 5463198092Srdivacky // appropriate declaration. 5464198092Srdivacky return DeclPtrTy(); 5465198092Srdivacky } 5466198092Srdivacky 5467198092Srdivacky // C++ [namespace.memdef]p3 5468198092Srdivacky // - If a friend declaration in a non-local class first declares a 5469198092Srdivacky // class or function, the friend class or function is a member 5470198092Srdivacky // of the innermost enclosing namespace. 5471198092Srdivacky // - The name of the friend is not found by simple name lookup 5472198092Srdivacky // until a matching declaration is provided in that namespace 5473198092Srdivacky // scope (either before or after the class declaration granting 5474198092Srdivacky // friendship). 5475198092Srdivacky // - If a friend function is called, its name may be found by the 5476198092Srdivacky // name lookup that considers functions from namespaces and 5477198092Srdivacky // classes associated with the types of the function arguments. 5478198092Srdivacky // - When looking for a prior declaration of a class or a function 5479198092Srdivacky // declared as a friend, scopes outside the innermost enclosing 5480198092Srdivacky // namespace scope are not considered. 5481198092Srdivacky 5482198092Srdivacky CXXScopeSpec &ScopeQual = D.getCXXScopeSpec(); 5483198092Srdivacky DeclarationName Name = GetNameForDeclarator(D); 5484198092Srdivacky assert(Name); 5485198092Srdivacky 5486198092Srdivacky // The context we found the declaration in, or in which we should 5487198092Srdivacky // create the declaration. 5488198092Srdivacky DeclContext *DC; 5489198092Srdivacky 5490198092Srdivacky // FIXME: handle local classes 5491198092Srdivacky 5492198092Srdivacky // Recover from invalid scope qualifiers as if they just weren't there. 5493199512Srdivacky LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName, 5494199512Srdivacky ForRedeclaration); 5495198092Srdivacky if (!ScopeQual.isInvalid() && ScopeQual.isSet()) { 5496198092Srdivacky // FIXME: RequireCompleteDeclContext 5497198092Srdivacky DC = computeDeclContext(ScopeQual); 5498198092Srdivacky 5499198092Srdivacky // FIXME: handle dependent contexts 5500198092Srdivacky if (!DC) return DeclPtrTy(); 5501198092Srdivacky 5502199512Srdivacky LookupQualifiedName(Previous, DC); 5503198092Srdivacky 5504198092Srdivacky // If searching in that context implicitly found a declaration in 5505198092Srdivacky // a different context, treat it like it wasn't found at all. 5506198092Srdivacky // TODO: better diagnostics for this case. Suggesting the right 5507198092Srdivacky // qualified scope would be nice... 5508199512Srdivacky // FIXME: getRepresentativeDecl() is not right here at all 5509199512Srdivacky if (Previous.empty() || 5510199512Srdivacky !Previous.getRepresentativeDecl()->getDeclContext()->Equals(DC)) { 5511198092Srdivacky D.setInvalidType(); 5512198092Srdivacky Diag(Loc, diag::err_qualified_friend_not_found) << Name << T; 5513198092Srdivacky return DeclPtrTy(); 5514198092Srdivacky } 5515198092Srdivacky 5516198092Srdivacky // C++ [class.friend]p1: A friend of a class is a function or 5517198092Srdivacky // class that is not a member of the class . . . 5518198092Srdivacky if (DC->Equals(CurContext)) 5519198092Srdivacky Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member); 5520198092Srdivacky 5521198092Srdivacky // Otherwise walk out to the nearest namespace scope looking for matches. 5522198092Srdivacky } else { 5523198092Srdivacky // TODO: handle local class contexts. 5524198092Srdivacky 5525198092Srdivacky DC = CurContext; 5526198092Srdivacky while (true) { 5527198092Srdivacky // Skip class contexts. If someone can cite chapter and verse 5528198092Srdivacky // for this behavior, that would be nice --- it's what GCC and 5529198092Srdivacky // EDG do, and it seems like a reasonable intent, but the spec 5530198092Srdivacky // really only says that checks for unqualified existing 5531198092Srdivacky // declarations should stop at the nearest enclosing namespace, 5532198092Srdivacky // not that they should only consider the nearest enclosing 5533198092Srdivacky // namespace. 5534198092Srdivacky while (DC->isRecord()) 5535198092Srdivacky DC = DC->getParent(); 5536198092Srdivacky 5537199512Srdivacky LookupQualifiedName(Previous, DC); 5538198092Srdivacky 5539198092Srdivacky // TODO: decide what we think about using declarations. 5540199512Srdivacky if (!Previous.empty()) 5541198092Srdivacky break; 5542198092Srdivacky 5543198092Srdivacky if (DC->isFileContext()) break; 5544198092Srdivacky DC = DC->getParent(); 5545198092Srdivacky } 5546198092Srdivacky 5547198092Srdivacky // C++ [class.friend]p1: A friend of a class is a function or 5548198092Srdivacky // class that is not a member of the class . . . 5549198092Srdivacky // C++0x changes this for both friend types and functions. 5550198092Srdivacky // Most C++ 98 compilers do seem to give an error here, so 5551198092Srdivacky // we do, too. 5552199512Srdivacky if (!Previous.empty() && DC->Equals(CurContext) 5553199512Srdivacky && !getLangOptions().CPlusPlus0x) 5554198092Srdivacky Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member); 5555198092Srdivacky } 5556198092Srdivacky 5557198092Srdivacky if (DC->isFileContext()) { 5558198092Srdivacky // This implies that it has to be an operator or function. 5559198893Srdivacky if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName || 5560198893Srdivacky D.getName().getKind() == UnqualifiedId::IK_DestructorName || 5561198893Srdivacky D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) { 5562198092Srdivacky Diag(Loc, diag::err_introducing_special_friend) << 5563198893Srdivacky (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 : 5564198893Srdivacky D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2); 5565198092Srdivacky return DeclPtrTy(); 5566198092Srdivacky } 5567198092Srdivacky } 5568198092Srdivacky 5569198092Srdivacky bool Redeclaration = false; 5570200583Srdivacky NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, TInfo, Previous, 5571198092Srdivacky move(TemplateParams), 5572198092Srdivacky IsDefinition, 5573198092Srdivacky Redeclaration); 5574198092Srdivacky if (!ND) return DeclPtrTy(); 5575198092Srdivacky 5576198092Srdivacky assert(ND->getDeclContext() == DC); 5577198092Srdivacky assert(ND->getLexicalDeclContext() == CurContext); 5578198092Srdivacky 5579198092Srdivacky // Add the function declaration to the appropriate lookup tables, 5580198092Srdivacky // adjusting the redeclarations list as necessary. We don't 5581198092Srdivacky // want to do this yet if the friending class is dependent. 5582198092Srdivacky // 5583198092Srdivacky // Also update the scope-based lookup if the target context's 5584198092Srdivacky // lookup context is in lexical scope. 5585198092Srdivacky if (!CurContext->isDependentContext()) { 5586198092Srdivacky DC = DC->getLookupContext(); 5587198092Srdivacky DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false); 5588198092Srdivacky if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 5589198092Srdivacky PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 5590198092Srdivacky } 5591198092Srdivacky 5592198092Srdivacky FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 5593198092Srdivacky D.getIdentifierLoc(), ND, 5594198092Srdivacky DS.getFriendSpecLoc()); 5595198092Srdivacky FrD->setAccess(AS_public); 5596198092Srdivacky CurContext->addDecl(FrD); 5597198092Srdivacky 5598201361Srdivacky if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) 5599201361Srdivacky FrD->setSpecialization(true); 5600201361Srdivacky 5601198092Srdivacky return DeclPtrTy::make(ND); 5602198092Srdivacky} 5603198092Srdivacky 5604193326Sedvoid Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) { 5605198092Srdivacky AdjustDeclIfTemplate(dcl); 5606198092Srdivacky 5607193326Sed Decl *Dcl = dcl.getAs<Decl>(); 5608193326Sed FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl); 5609193326Sed if (!Fn) { 5610193326Sed Diag(DelLoc, diag::err_deleted_non_function); 5611193326Sed return; 5612193326Sed } 5613193326Sed if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) { 5614193326Sed Diag(DelLoc, diag::err_deleted_decl_not_first); 5615193326Sed Diag(Prev->getLocation(), diag::note_previous_declaration); 5616193326Sed // If the declaration wasn't the first, we delete the function anyway for 5617193326Sed // recovery. 5618193326Sed } 5619193326Sed Fn->setDeleted(); 5620193326Sed} 5621193326Sed 5622193326Sedstatic void SearchForReturnInStmt(Sema &Self, Stmt *S) { 5623193326Sed for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E; 5624193326Sed ++CI) { 5625193326Sed Stmt *SubStmt = *CI; 5626193326Sed if (!SubStmt) 5627193326Sed continue; 5628193326Sed if (isa<ReturnStmt>(SubStmt)) 5629193326Sed Self.Diag(SubStmt->getSourceRange().getBegin(), 5630193326Sed diag::err_return_in_constructor_handler); 5631193326Sed if (!isa<Expr>(SubStmt)) 5632193326Sed SearchForReturnInStmt(Self, SubStmt); 5633193326Sed } 5634193326Sed} 5635193326Sed 5636193326Sedvoid Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 5637193326Sed for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 5638193326Sed CXXCatchStmt *Handler = TryBlock->getHandler(I); 5639193326Sed SearchForReturnInStmt(*this, Handler); 5640193326Sed } 5641193326Sed} 5642193326Sed 5643198092Srdivackybool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 5644193326Sed const CXXMethodDecl *Old) { 5645198092Srdivacky QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType(); 5646198092Srdivacky QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType(); 5647193326Sed 5648203955Srdivacky if (Context.hasSameType(NewTy, OldTy) || 5649203955Srdivacky NewTy->isDependentType() || OldTy->isDependentType()) 5650193326Sed return false; 5651198092Srdivacky 5652193326Sed // Check if the return types are covariant 5653193326Sed QualType NewClassTy, OldClassTy; 5654198092Srdivacky 5655193326Sed /// Both types must be pointers or references to classes. 5656202879Srdivacky if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 5657202879Srdivacky if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 5658193326Sed NewClassTy = NewPT->getPointeeType(); 5659193326Sed OldClassTy = OldPT->getPointeeType(); 5660193326Sed } 5661202879Srdivacky } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 5662202879Srdivacky if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 5663202879Srdivacky if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 5664202879Srdivacky NewClassTy = NewRT->getPointeeType(); 5665202879Srdivacky OldClassTy = OldRT->getPointeeType(); 5666202879Srdivacky } 5667193326Sed } 5668193326Sed } 5669198092Srdivacky 5670193326Sed // The return types aren't either both pointers or references to a class type. 5671193326Sed if (NewClassTy.isNull()) { 5672198092Srdivacky Diag(New->getLocation(), 5673193326Sed diag::err_different_return_type_for_overriding_virtual_function) 5674193326Sed << New->getDeclName() << NewTy << OldTy; 5675193326Sed Diag(Old->getLocation(), diag::note_overridden_virtual_function); 5676198092Srdivacky 5677193326Sed return true; 5678193326Sed } 5679193326Sed 5680201361Srdivacky // C++ [class.virtual]p6: 5681201361Srdivacky // If the return type of D::f differs from the return type of B::f, the 5682201361Srdivacky // class type in the return type of D::f shall be complete at the point of 5683201361Srdivacky // declaration of D::f or shall be the class type D. 5684201361Srdivacky if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 5685201361Srdivacky if (!RT->isBeingDefined() && 5686201361Srdivacky RequireCompleteType(New->getLocation(), NewClassTy, 5687201361Srdivacky PDiag(diag::err_covariant_return_incomplete) 5688201361Srdivacky << New->getDeclName())) 5689201361Srdivacky return true; 5690201361Srdivacky } 5691201361Srdivacky 5692199482Srdivacky if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 5693193326Sed // Check if the new class derives from the old class. 5694193326Sed if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 5695193326Sed Diag(New->getLocation(), 5696193326Sed diag::err_covariant_return_not_derived) 5697193326Sed << New->getDeclName() << NewTy << OldTy; 5698193326Sed Diag(Old->getLocation(), diag::note_overridden_virtual_function); 5699193326Sed return true; 5700193326Sed } 5701198092Srdivacky 5702193326Sed // Check if we the conversion from derived to base is valid. 5703205219Srdivacky if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy, 5704205219Srdivacky diag::err_covariant_return_inaccessible_base, 5705193326Sed diag::err_covariant_return_ambiguous_derived_to_base_conv, 5706193326Sed // FIXME: Should this point to the return type? 5707193326Sed New->getLocation(), SourceRange(), New->getDeclName())) { 5708193326Sed Diag(Old->getLocation(), diag::note_overridden_virtual_function); 5709193326Sed return true; 5710193326Sed } 5711193326Sed } 5712198092Srdivacky 5713193326Sed // The qualifiers of the return types must be the same. 5714202879Srdivacky if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 5715193326Sed Diag(New->getLocation(), 5716193326Sed diag::err_covariant_return_type_different_qualifications) 5717193326Sed << New->getDeclName() << NewTy << OldTy; 5718193326Sed Diag(Old->getLocation(), diag::note_overridden_virtual_function); 5719193326Sed return true; 5720193326Sed }; 5721193326Sed 5722198092Srdivacky 5723193326Sed // The new class type must have the same or less qualifiers as the old type. 5724193326Sed if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 5725193326Sed Diag(New->getLocation(), 5726193326Sed diag::err_covariant_return_type_class_type_more_qualified) 5727193326Sed << New->getDeclName() << NewTy << OldTy; 5728193326Sed Diag(Old->getLocation(), diag::note_overridden_virtual_function); 5729193326Sed return true; 5730193326Sed }; 5731198092Srdivacky 5732193326Sed return false; 5733193326Sed} 5734194613Sed 5735199990Srdivackybool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 5736199990Srdivacky const CXXMethodDecl *Old) 5737199990Srdivacky{ 5738199990Srdivacky if (Old->hasAttr<FinalAttr>()) { 5739199990Srdivacky Diag(New->getLocation(), diag::err_final_function_overridden) 5740199990Srdivacky << New->getDeclName(); 5741199990Srdivacky Diag(Old->getLocation(), diag::note_overridden_virtual_function); 5742199990Srdivacky return true; 5743199990Srdivacky } 5744199990Srdivacky 5745199990Srdivacky return false; 5746199990Srdivacky} 5747199990Srdivacky 5748200583Srdivacky/// \brief Mark the given method pure. 5749200583Srdivacky/// 5750200583Srdivacky/// \param Method the method to be marked pure. 5751200583Srdivacky/// 5752200583Srdivacky/// \param InitRange the source range that covers the "0" initializer. 5753200583Srdivackybool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 5754200583Srdivacky if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 5755200583Srdivacky Method->setPure(); 5756200583Srdivacky 5757200583Srdivacky // A class is abstract if at least one function is pure virtual. 5758200583Srdivacky Method->getParent()->setAbstract(true); 5759200583Srdivacky return false; 5760200583Srdivacky } 5761200583Srdivacky 5762200583Srdivacky if (!Method->isInvalidDecl()) 5763200583Srdivacky Diag(Method->getLocation(), diag::err_non_virtual_pure) 5764200583Srdivacky << Method->getDeclName() << InitRange; 5765200583Srdivacky return true; 5766200583Srdivacky} 5767200583Srdivacky 5768201361Srdivacky/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 5769201361Srdivacky/// an initializer for the out-of-line declaration 'Dcl'. The scope 5770201361Srdivacky/// is a fresh scope pushed for just this purpose. 5771201361Srdivacky/// 5772194613Sed/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 5773194613Sed/// static data member of class X, names should be looked up in the scope of 5774194613Sed/// class X. 5775194613Sedvoid Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) { 5776201361Srdivacky // If there is no declaration, there was an error parsing it. 5777194613Sed Decl *D = Dcl.getAs<Decl>(); 5778201361Srdivacky if (D == 0) return; 5779194613Sed 5780201361Srdivacky // We should only get called for declarations with scope specifiers, like: 5781201361Srdivacky // int foo::bar; 5782201361Srdivacky assert(D->isOutOfLine()); 5783194613Sed EnterDeclaratorContext(S, D->getDeclContext()); 5784194613Sed} 5785194613Sed 5786194613Sed/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 5787201361Srdivacky/// initializer for the out-of-line declaration 'Dcl'. 5788194613Sedvoid Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) { 5789201361Srdivacky // If there is no declaration, there was an error parsing it. 5790194613Sed Decl *D = Dcl.getAs<Decl>(); 5791201361Srdivacky if (D == 0) return; 5792194613Sed 5793201361Srdivacky assert(D->isOutOfLine()); 5794194613Sed ExitDeclaratorContext(S); 5795194613Sed} 5796199990Srdivacky 5797199990Srdivacky/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 5798199990Srdivacky/// C++ if/switch/while/for statement. 5799199990Srdivacky/// e.g: "if (int x = f()) {...}" 5800199990SrdivackyAction::DeclResult 5801199990SrdivackySema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 5802199990Srdivacky // C++ 6.4p2: 5803199990Srdivacky // The declarator shall not specify a function or an array. 5804199990Srdivacky // The type-specifier-seq shall not contain typedef and shall not declare a 5805199990Srdivacky // new class or enumeration. 5806199990Srdivacky assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 5807199990Srdivacky "Parser allowed 'typedef' as storage class of condition decl."); 5808199990Srdivacky 5809200583Srdivacky TypeSourceInfo *TInfo = 0; 5810199990Srdivacky TagDecl *OwnedTag = 0; 5811200583Srdivacky QualType Ty = GetTypeForDeclarator(D, S, &TInfo, &OwnedTag); 5812199990Srdivacky 5813199990Srdivacky if (Ty->isFunctionType()) { // The declarator shall not specify a function... 5814199990Srdivacky // We exit without creating a CXXConditionDeclExpr because a FunctionDecl 5815199990Srdivacky // would be created and CXXConditionDeclExpr wants a VarDecl. 5816199990Srdivacky Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type) 5817199990Srdivacky << D.getSourceRange(); 5818199990Srdivacky return DeclResult(); 5819199990Srdivacky } else if (OwnedTag && OwnedTag->isDefinition()) { 5820199990Srdivacky // The type-specifier-seq shall not declare a new class or enumeration. 5821199990Srdivacky Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition); 5822199990Srdivacky } 5823199990Srdivacky 5824199990Srdivacky DeclPtrTy Dcl = ActOnDeclarator(S, D); 5825199990Srdivacky if (!Dcl) 5826199990Srdivacky return DeclResult(); 5827199990Srdivacky 5828199990Srdivacky VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>()); 5829199990Srdivacky VD->setDeclaredInCondition(true); 5830199990Srdivacky return Dcl; 5831199990Srdivacky} 5832200583Srdivacky 5833204643Srdivackystatic bool needsVtable(CXXMethodDecl *MD, ASTContext &Context) { 5834200583Srdivacky // Ignore dependent types. 5835200583Srdivacky if (MD->isDependentContext()) 5836204643Srdivacky return false; 5837204643Srdivacky 5838204643Srdivacky // Ignore declarations that are not definitions. 5839204643Srdivacky if (!MD->isThisDeclarationADefinition()) 5840204643Srdivacky return false; 5841204643Srdivacky 5842200583Srdivacky CXXRecordDecl *RD = MD->getParent(); 5843204643Srdivacky 5844200583Srdivacky // Ignore classes without a vtable. 5845200583Srdivacky if (!RD->isDynamicClass()) 5846204643Srdivacky return false; 5847200583Srdivacky 5848204643Srdivacky switch (MD->getParent()->getTemplateSpecializationKind()) { 5849204643Srdivacky case TSK_Undeclared: 5850204643Srdivacky case TSK_ExplicitSpecialization: 5851204643Srdivacky // Classes that aren't instantiations of templates don't need their 5852204643Srdivacky // virtual methods marked until we see the definition of the key 5853204643Srdivacky // function. 5854204643Srdivacky break; 5855204643Srdivacky 5856204643Srdivacky case TSK_ImplicitInstantiation: 5857204643Srdivacky // This is a constructor of a class template; mark all of the virtual 5858204643Srdivacky // members as referenced to ensure that they get instantiatied. 5859204643Srdivacky if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) 5860204643Srdivacky return true; 5861204643Srdivacky break; 5862204643Srdivacky 5863204643Srdivacky case TSK_ExplicitInstantiationDeclaration: 5864206084Srdivacky return false; 5865204643Srdivacky 5866204643Srdivacky case TSK_ExplicitInstantiationDefinition: 5867204643Srdivacky // This is method of a explicit instantiation; mark all of the virtual 5868204643Srdivacky // members as referenced to ensure that they get instantiatied. 5869204643Srdivacky return true; 5870200583Srdivacky } 5871204643Srdivacky 5872204643Srdivacky // Consider only out-of-line definitions of member functions. When we see 5873204643Srdivacky // an inline definition, it's too early to compute the key function. 5874204643Srdivacky if (!MD->isOutOfLine()) 5875204643Srdivacky return false; 5876204643Srdivacky 5877204643Srdivacky const CXXMethodDecl *KeyFunction = Context.getKeyFunction(RD); 5878204643Srdivacky 5879204643Srdivacky // If there is no key function, we will need a copy of the vtable. 5880204643Srdivacky if (!KeyFunction) 5881204643Srdivacky return true; 5882204643Srdivacky 5883204643Srdivacky // If this is the key function, we need to mark virtual members. 5884204643Srdivacky if (KeyFunction->getCanonicalDecl() == MD->getCanonicalDecl()) 5885204643Srdivacky return true; 5886204643Srdivacky 5887204643Srdivacky return false; 5888204643Srdivacky} 5889204643Srdivacky 5890204643Srdivackyvoid Sema::MaybeMarkVirtualMembersReferenced(SourceLocation Loc, 5891204643Srdivacky CXXMethodDecl *MD) { 5892204643Srdivacky CXXRecordDecl *RD = MD->getParent(); 5893204643Srdivacky 5894202379Srdivacky // We will need to mark all of the virtual members as referenced to build the 5895202379Srdivacky // vtable. 5896204962Srdivacky if (!needsVtable(MD, Context)) 5897204962Srdivacky return; 5898204962Srdivacky 5899204962Srdivacky TemplateSpecializationKind kind = RD->getTemplateSpecializationKind(); 5900204962Srdivacky if (kind == TSK_ImplicitInstantiation) 5901204962Srdivacky ClassesWithUnmarkedVirtualMembers.push_back(std::make_pair(RD, Loc)); 5902204962Srdivacky else 5903204643Srdivacky MarkVirtualMembersReferenced(Loc, RD); 5904200583Srdivacky} 5905200583Srdivacky 5906200583Srdivackybool Sema::ProcessPendingClassesWithUnmarkedVirtualMembers() { 5907200583Srdivacky if (ClassesWithUnmarkedVirtualMembers.empty()) 5908200583Srdivacky return false; 5909200583Srdivacky 5910202379Srdivacky while (!ClassesWithUnmarkedVirtualMembers.empty()) { 5911202379Srdivacky CXXRecordDecl *RD = ClassesWithUnmarkedVirtualMembers.back().first; 5912202379Srdivacky SourceLocation Loc = ClassesWithUnmarkedVirtualMembers.back().second; 5913202379Srdivacky ClassesWithUnmarkedVirtualMembers.pop_back(); 5914200583Srdivacky MarkVirtualMembersReferenced(Loc, RD); 5915200583Srdivacky } 5916200583Srdivacky 5917200583Srdivacky return true; 5918200583Srdivacky} 5919200583Srdivacky 5920206084Srdivackyvoid Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 5921206084Srdivacky const CXXRecordDecl *RD) { 5922200583Srdivacky for (CXXRecordDecl::method_iterator i = RD->method_begin(), 5923200583Srdivacky e = RD->method_end(); i != e; ++i) { 5924200583Srdivacky CXXMethodDecl *MD = *i; 5925200583Srdivacky 5926200583Srdivacky // C++ [basic.def.odr]p2: 5927200583Srdivacky // [...] A virtual member function is used if it is not pure. [...] 5928200583Srdivacky if (MD->isVirtual() && !MD->isPure()) 5929200583Srdivacky MarkDeclarationReferenced(Loc, MD); 5930200583Srdivacky } 5931206084Srdivacky 5932206084Srdivacky // Only classes that have virtual bases need a VTT. 5933206084Srdivacky if (RD->getNumVBases() == 0) 5934206084Srdivacky return; 5935206084Srdivacky 5936206084Srdivacky for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(), 5937206084Srdivacky e = RD->bases_end(); i != e; ++i) { 5938206084Srdivacky const CXXRecordDecl *Base = 5939206084Srdivacky cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl()); 5940206084Srdivacky if (i->isVirtual()) 5941206084Srdivacky continue; 5942206084Srdivacky if (Base->getNumVBases() == 0) 5943206084Srdivacky continue; 5944206084Srdivacky MarkVirtualMembersReferenced(Loc, Base); 5945206084Srdivacky } 5946200583Srdivacky} 5947