SemaDeclCXX.cpp revision f6e2e0291b8964ed41b4325e21dd90b86e791f10
1//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements semantic analysis for C++ declarations. 11// 12//===----------------------------------------------------------------------===// 13 14#include "clang/Sema/SemaInternal.h" 15#include "clang/Sema/CXXFieldCollector.h" 16#include "clang/Sema/Scope.h" 17#include "clang/Sema/Initialization.h" 18#include "clang/Sema/Lookup.h" 19#include "clang/Sema/ScopeInfo.h" 20#include "clang/AST/ASTConsumer.h" 21#include "clang/AST/ASTContext.h" 22#include "clang/AST/ASTMutationListener.h" 23#include "clang/AST/CharUnits.h" 24#include "clang/AST/CXXInheritance.h" 25#include "clang/AST/DeclVisitor.h" 26#include "clang/AST/ExprCXX.h" 27#include "clang/AST/RecordLayout.h" 28#include "clang/AST/StmtVisitor.h" 29#include "clang/AST/TypeLoc.h" 30#include "clang/AST/TypeOrdering.h" 31#include "clang/Sema/DeclSpec.h" 32#include "clang/Sema/ParsedTemplate.h" 33#include "clang/Basic/PartialDiagnostic.h" 34#include "clang/Lex/Preprocessor.h" 35#include "llvm/ADT/DenseSet.h" 36#include "llvm/ADT/SmallString.h" 37#include "llvm/ADT/STLExtras.h" 38#include <map> 39#include <set> 40 41using namespace clang; 42 43//===----------------------------------------------------------------------===// 44// CheckDefaultArgumentVisitor 45//===----------------------------------------------------------------------===// 46 47namespace { 48 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 49 /// the default argument of a parameter to determine whether it 50 /// contains any ill-formed subexpressions. For example, this will 51 /// diagnose the use of local variables or parameters within the 52 /// default argument expression. 53 class CheckDefaultArgumentVisitor 54 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 55 Expr *DefaultArg; 56 Sema *S; 57 58 public: 59 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 60 : DefaultArg(defarg), S(s) {} 61 62 bool VisitExpr(Expr *Node); 63 bool VisitDeclRefExpr(DeclRefExpr *DRE); 64 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 65 bool VisitLambdaExpr(LambdaExpr *Lambda); 66 }; 67 68 /// VisitExpr - Visit all of the children of this expression. 69 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 70 bool IsInvalid = false; 71 for (Stmt::child_range I = Node->children(); I; ++I) 72 IsInvalid |= Visit(*I); 73 return IsInvalid; 74 } 75 76 /// VisitDeclRefExpr - Visit a reference to a declaration, to 77 /// determine whether this declaration can be used in the default 78 /// argument expression. 79 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 80 NamedDecl *Decl = DRE->getDecl(); 81 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 82 // C++ [dcl.fct.default]p9 83 // Default arguments are evaluated each time the function is 84 // called. The order of evaluation of function arguments is 85 // unspecified. Consequently, parameters of a function shall not 86 // be used in default argument expressions, even if they are not 87 // evaluated. Parameters of a function declared before a default 88 // argument expression are in scope and can hide namespace and 89 // class member names. 90 return S->Diag(DRE->getSourceRange().getBegin(), 91 diag::err_param_default_argument_references_param) 92 << Param->getDeclName() << DefaultArg->getSourceRange(); 93 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 94 // C++ [dcl.fct.default]p7 95 // Local variables shall not be used in default argument 96 // expressions. 97 if (VDecl->isLocalVarDecl()) 98 return S->Diag(DRE->getSourceRange().getBegin(), 99 diag::err_param_default_argument_references_local) 100 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 101 } 102 103 return false; 104 } 105 106 /// VisitCXXThisExpr - Visit a C++ "this" expression. 107 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 108 // C++ [dcl.fct.default]p8: 109 // The keyword this shall not be used in a default argument of a 110 // member function. 111 return S->Diag(ThisE->getSourceRange().getBegin(), 112 diag::err_param_default_argument_references_this) 113 << ThisE->getSourceRange(); 114 } 115 116 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) { 117 // C++11 [expr.lambda.prim]p13: 118 // A lambda-expression appearing in a default argument shall not 119 // implicitly or explicitly capture any entity. 120 if (Lambda->capture_begin() == Lambda->capture_end()) 121 return false; 122 123 return S->Diag(Lambda->getLocStart(), 124 diag::err_lambda_capture_default_arg); 125 } 126} 127 128void Sema::ImplicitExceptionSpecification::CalledDecl(CXXMethodDecl *Method) { 129 assert(Context && "ImplicitExceptionSpecification without an ASTContext"); 130 // If we have an MSAny or unknown spec already, don't bother. 131 if (!Method || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed) 132 return; 133 134 const FunctionProtoType *Proto 135 = Method->getType()->getAs<FunctionProtoType>(); 136 137 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 138 139 // If this function can throw any exceptions, make a note of that. 140 if (EST == EST_Delayed || EST == EST_MSAny || EST == EST_None) { 141 ClearExceptions(); 142 ComputedEST = EST; 143 return; 144 } 145 146 // FIXME: If the call to this decl is using any of its default arguments, we 147 // need to search them for potentially-throwing calls. 148 149 // If this function has a basic noexcept, it doesn't affect the outcome. 150 if (EST == EST_BasicNoexcept) 151 return; 152 153 // If we have a throw-all spec at this point, ignore the function. 154 if (ComputedEST == EST_None) 155 return; 156 157 // If we're still at noexcept(true) and there's a nothrow() callee, 158 // change to that specification. 159 if (EST == EST_DynamicNone) { 160 if (ComputedEST == EST_BasicNoexcept) 161 ComputedEST = EST_DynamicNone; 162 return; 163 } 164 165 // Check out noexcept specs. 166 if (EST == EST_ComputedNoexcept) { 167 FunctionProtoType::NoexceptResult NR = Proto->getNoexceptSpec(*Context); 168 assert(NR != FunctionProtoType::NR_NoNoexcept && 169 "Must have noexcept result for EST_ComputedNoexcept."); 170 assert(NR != FunctionProtoType::NR_Dependent && 171 "Should not generate implicit declarations for dependent cases, " 172 "and don't know how to handle them anyway."); 173 174 // noexcept(false) -> no spec on the new function 175 if (NR == FunctionProtoType::NR_Throw) { 176 ClearExceptions(); 177 ComputedEST = EST_None; 178 } 179 // noexcept(true) won't change anything either. 180 return; 181 } 182 183 assert(EST == EST_Dynamic && "EST case not considered earlier."); 184 assert(ComputedEST != EST_None && 185 "Shouldn't collect exceptions when throw-all is guaranteed."); 186 ComputedEST = EST_Dynamic; 187 // Record the exceptions in this function's exception specification. 188 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(), 189 EEnd = Proto->exception_end(); 190 E != EEnd; ++E) 191 if (ExceptionsSeen.insert(Context->getCanonicalType(*E))) 192 Exceptions.push_back(*E); 193} 194 195void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) { 196 if (!E || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed) 197 return; 198 199 // FIXME: 200 // 201 // C++0x [except.spec]p14: 202 // [An] implicit exception-specification specifies the type-id T if and 203 // only if T is allowed by the exception-specification of a function directly 204 // invoked by f's implicit definition; f shall allow all exceptions if any 205 // function it directly invokes allows all exceptions, and f shall allow no 206 // exceptions if every function it directly invokes allows no exceptions. 207 // 208 // Note in particular that if an implicit exception-specification is generated 209 // for a function containing a throw-expression, that specification can still 210 // be noexcept(true). 211 // 212 // Note also that 'directly invoked' is not defined in the standard, and there 213 // is no indication that we should only consider potentially-evaluated calls. 214 // 215 // Ultimately we should implement the intent of the standard: the exception 216 // specification should be the set of exceptions which can be thrown by the 217 // implicit definition. For now, we assume that any non-nothrow expression can 218 // throw any exception. 219 220 if (E->CanThrow(*Context)) 221 ComputedEST = EST_None; 222} 223 224bool 225Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 226 SourceLocation EqualLoc) { 227 if (RequireCompleteType(Param->getLocation(), Param->getType(), 228 diag::err_typecheck_decl_incomplete_type)) { 229 Param->setInvalidDecl(); 230 return true; 231 } 232 233 // C++ [dcl.fct.default]p5 234 // A default argument expression is implicitly converted (clause 235 // 4) to the parameter type. The default argument expression has 236 // the same semantic constraints as the initializer expression in 237 // a declaration of a variable of the parameter type, using the 238 // copy-initialization semantics (8.5). 239 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 240 Param); 241 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 242 EqualLoc); 243 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1); 244 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, 245 MultiExprArg(*this, &Arg, 1)); 246 if (Result.isInvalid()) 247 return true; 248 Arg = Result.takeAs<Expr>(); 249 250 CheckImplicitConversions(Arg, EqualLoc); 251 Arg = MaybeCreateExprWithCleanups(Arg); 252 253 // Okay: add the default argument to the parameter 254 Param->setDefaultArg(Arg); 255 256 // We have already instantiated this parameter; provide each of the 257 // instantiations with the uninstantiated default argument. 258 UnparsedDefaultArgInstantiationsMap::iterator InstPos 259 = UnparsedDefaultArgInstantiations.find(Param); 260 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 261 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 262 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 263 264 // We're done tracking this parameter's instantiations. 265 UnparsedDefaultArgInstantiations.erase(InstPos); 266 } 267 268 return false; 269} 270 271/// ActOnParamDefaultArgument - Check whether the default argument 272/// provided for a function parameter is well-formed. If so, attach it 273/// to the parameter declaration. 274void 275Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 276 Expr *DefaultArg) { 277 if (!param || !DefaultArg) 278 return; 279 280 ParmVarDecl *Param = cast<ParmVarDecl>(param); 281 UnparsedDefaultArgLocs.erase(Param); 282 283 // Default arguments are only permitted in C++ 284 if (!getLangOptions().CPlusPlus) { 285 Diag(EqualLoc, diag::err_param_default_argument) 286 << DefaultArg->getSourceRange(); 287 Param->setInvalidDecl(); 288 return; 289 } 290 291 // Check for unexpanded parameter packs. 292 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 293 Param->setInvalidDecl(); 294 return; 295 } 296 297 // Check that the default argument is well-formed 298 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this); 299 if (DefaultArgChecker.Visit(DefaultArg)) { 300 Param->setInvalidDecl(); 301 return; 302 } 303 304 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 305} 306 307/// ActOnParamUnparsedDefaultArgument - We've seen a default 308/// argument for a function parameter, but we can't parse it yet 309/// because we're inside a class definition. Note that this default 310/// argument will be parsed later. 311void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 312 SourceLocation EqualLoc, 313 SourceLocation ArgLoc) { 314 if (!param) 315 return; 316 317 ParmVarDecl *Param = cast<ParmVarDecl>(param); 318 if (Param) 319 Param->setUnparsedDefaultArg(); 320 321 UnparsedDefaultArgLocs[Param] = ArgLoc; 322} 323 324/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 325/// the default argument for the parameter param failed. 326void Sema::ActOnParamDefaultArgumentError(Decl *param) { 327 if (!param) 328 return; 329 330 ParmVarDecl *Param = cast<ParmVarDecl>(param); 331 332 Param->setInvalidDecl(); 333 334 UnparsedDefaultArgLocs.erase(Param); 335} 336 337/// CheckExtraCXXDefaultArguments - Check for any extra default 338/// arguments in the declarator, which is not a function declaration 339/// or definition and therefore is not permitted to have default 340/// arguments. This routine should be invoked for every declarator 341/// that is not a function declaration or definition. 342void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 343 // C++ [dcl.fct.default]p3 344 // A default argument expression shall be specified only in the 345 // parameter-declaration-clause of a function declaration or in a 346 // template-parameter (14.1). It shall not be specified for a 347 // parameter pack. If it is specified in a 348 // parameter-declaration-clause, it shall not occur within a 349 // declarator or abstract-declarator of a parameter-declaration. 350 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 351 DeclaratorChunk &chunk = D.getTypeObject(i); 352 if (chunk.Kind == DeclaratorChunk::Function) { 353 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) { 354 ParmVarDecl *Param = 355 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param); 356 if (Param->hasUnparsedDefaultArg()) { 357 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens; 358 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 359 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation()); 360 delete Toks; 361 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0; 362 } else if (Param->getDefaultArg()) { 363 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 364 << Param->getDefaultArg()->getSourceRange(); 365 Param->setDefaultArg(0); 366 } 367 } 368 } 369 } 370} 371 372// MergeCXXFunctionDecl - Merge two declarations of the same C++ 373// function, once we already know that they have the same 374// type. Subroutine of MergeFunctionDecl. Returns true if there was an 375// error, false otherwise. 376bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) { 377 bool Invalid = false; 378 379 // C++ [dcl.fct.default]p4: 380 // For non-template functions, default arguments can be added in 381 // later declarations of a function in the same 382 // scope. Declarations in different scopes have completely 383 // distinct sets of default arguments. That is, declarations in 384 // inner scopes do not acquire default arguments from 385 // declarations in outer scopes, and vice versa. In a given 386 // function declaration, all parameters subsequent to a 387 // parameter with a default argument shall have default 388 // arguments supplied in this or previous declarations. A 389 // default argument shall not be redefined by a later 390 // declaration (not even to the same value). 391 // 392 // C++ [dcl.fct.default]p6: 393 // Except for member functions of class templates, the default arguments 394 // in a member function definition that appears outside of the class 395 // definition are added to the set of default arguments provided by the 396 // member function declaration in the class definition. 397 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 398 ParmVarDecl *OldParam = Old->getParamDecl(p); 399 ParmVarDecl *NewParam = New->getParamDecl(p); 400 401 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) { 402 403 unsigned DiagDefaultParamID = 404 diag::err_param_default_argument_redefinition; 405 406 // MSVC accepts that default parameters be redefined for member functions 407 // of template class. The new default parameter's value is ignored. 408 Invalid = true; 409 if (getLangOptions().MicrosoftExt) { 410 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New); 411 if (MD && MD->getParent()->getDescribedClassTemplate()) { 412 // Merge the old default argument into the new parameter. 413 NewParam->setHasInheritedDefaultArg(); 414 if (OldParam->hasUninstantiatedDefaultArg()) 415 NewParam->setUninstantiatedDefaultArg( 416 OldParam->getUninstantiatedDefaultArg()); 417 else 418 NewParam->setDefaultArg(OldParam->getInit()); 419 DiagDefaultParamID = diag::warn_param_default_argument_redefinition; 420 Invalid = false; 421 } 422 } 423 424 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 425 // hint here. Alternatively, we could walk the type-source information 426 // for NewParam to find the last source location in the type... but it 427 // isn't worth the effort right now. This is the kind of test case that 428 // is hard to get right: 429 // int f(int); 430 // void g(int (*fp)(int) = f); 431 // void g(int (*fp)(int) = &f); 432 Diag(NewParam->getLocation(), DiagDefaultParamID) 433 << NewParam->getDefaultArgRange(); 434 435 // Look for the function declaration where the default argument was 436 // actually written, which may be a declaration prior to Old. 437 for (FunctionDecl *Older = Old->getPreviousDecl(); 438 Older; Older = Older->getPreviousDecl()) { 439 if (!Older->getParamDecl(p)->hasDefaultArg()) 440 break; 441 442 OldParam = Older->getParamDecl(p); 443 } 444 445 Diag(OldParam->getLocation(), diag::note_previous_definition) 446 << OldParam->getDefaultArgRange(); 447 } else if (OldParam->hasDefaultArg()) { 448 // Merge the old default argument into the new parameter. 449 // It's important to use getInit() here; getDefaultArg() 450 // strips off any top-level ExprWithCleanups. 451 NewParam->setHasInheritedDefaultArg(); 452 if (OldParam->hasUninstantiatedDefaultArg()) 453 NewParam->setUninstantiatedDefaultArg( 454 OldParam->getUninstantiatedDefaultArg()); 455 else 456 NewParam->setDefaultArg(OldParam->getInit()); 457 } else if (NewParam->hasDefaultArg()) { 458 if (New->getDescribedFunctionTemplate()) { 459 // Paragraph 4, quoted above, only applies to non-template functions. 460 Diag(NewParam->getLocation(), 461 diag::err_param_default_argument_template_redecl) 462 << NewParam->getDefaultArgRange(); 463 Diag(Old->getLocation(), diag::note_template_prev_declaration) 464 << false; 465 } else if (New->getTemplateSpecializationKind() 466 != TSK_ImplicitInstantiation && 467 New->getTemplateSpecializationKind() != TSK_Undeclared) { 468 // C++ [temp.expr.spec]p21: 469 // Default function arguments shall not be specified in a declaration 470 // or a definition for one of the following explicit specializations: 471 // - the explicit specialization of a function template; 472 // - the explicit specialization of a member function template; 473 // - the explicit specialization of a member function of a class 474 // template where the class template specialization to which the 475 // member function specialization belongs is implicitly 476 // instantiated. 477 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 478 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 479 << New->getDeclName() 480 << NewParam->getDefaultArgRange(); 481 } else if (New->getDeclContext()->isDependentContext()) { 482 // C++ [dcl.fct.default]p6 (DR217): 483 // Default arguments for a member function of a class template shall 484 // be specified on the initial declaration of the member function 485 // within the class template. 486 // 487 // Reading the tea leaves a bit in DR217 and its reference to DR205 488 // leads me to the conclusion that one cannot add default function 489 // arguments for an out-of-line definition of a member function of a 490 // dependent type. 491 int WhichKind = 2; 492 if (CXXRecordDecl *Record 493 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 494 if (Record->getDescribedClassTemplate()) 495 WhichKind = 0; 496 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 497 WhichKind = 1; 498 else 499 WhichKind = 2; 500 } 501 502 Diag(NewParam->getLocation(), 503 diag::err_param_default_argument_member_template_redecl) 504 << WhichKind 505 << NewParam->getDefaultArgRange(); 506 } else if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(New)) { 507 CXXSpecialMember NewSM = getSpecialMember(Ctor), 508 OldSM = getSpecialMember(cast<CXXConstructorDecl>(Old)); 509 if (NewSM != OldSM) { 510 Diag(NewParam->getLocation(),diag::warn_default_arg_makes_ctor_special) 511 << NewParam->getDefaultArgRange() << NewSM; 512 Diag(Old->getLocation(), diag::note_previous_declaration_special) 513 << OldSM; 514 } 515 } 516 } 517 } 518 519 // C++0x [dcl.constexpr]p1: If any declaration of a function or function 520 // template has a constexpr specifier then all its declarations shall 521 // contain the constexpr specifier. [Note: An explicit specialization can 522 // differ from the template declaration with respect to the constexpr 523 // specifier. -- end note] 524 // 525 // FIXME: Don't reject changes in constexpr in explicit specializations. 526 if (New->isConstexpr() != Old->isConstexpr()) { 527 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 528 << New << New->isConstexpr(); 529 Diag(Old->getLocation(), diag::note_previous_declaration); 530 Invalid = true; 531 } 532 533 if (CheckEquivalentExceptionSpec(Old, New)) 534 Invalid = true; 535 536 return Invalid; 537} 538 539/// \brief Merge the exception specifications of two variable declarations. 540/// 541/// This is called when there's a redeclaration of a VarDecl. The function 542/// checks if the redeclaration might have an exception specification and 543/// validates compatibility and merges the specs if necessary. 544void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 545 // Shortcut if exceptions are disabled. 546 if (!getLangOptions().CXXExceptions) 547 return; 548 549 assert(Context.hasSameType(New->getType(), Old->getType()) && 550 "Should only be called if types are otherwise the same."); 551 552 QualType NewType = New->getType(); 553 QualType OldType = Old->getType(); 554 555 // We're only interested in pointers and references to functions, as well 556 // as pointers to member functions. 557 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 558 NewType = R->getPointeeType(); 559 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 560 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 561 NewType = P->getPointeeType(); 562 OldType = OldType->getAs<PointerType>()->getPointeeType(); 563 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 564 NewType = M->getPointeeType(); 565 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 566 } 567 568 if (!NewType->isFunctionProtoType()) 569 return; 570 571 // There's lots of special cases for functions. For function pointers, system 572 // libraries are hopefully not as broken so that we don't need these 573 // workarounds. 574 if (CheckEquivalentExceptionSpec( 575 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 576 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 577 New->setInvalidDecl(); 578 } 579} 580 581/// CheckCXXDefaultArguments - Verify that the default arguments for a 582/// function declaration are well-formed according to C++ 583/// [dcl.fct.default]. 584void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 585 unsigned NumParams = FD->getNumParams(); 586 unsigned p; 587 588 bool IsLambda = FD->getOverloadedOperator() == OO_Call && 589 isa<CXXMethodDecl>(FD) && 590 cast<CXXMethodDecl>(FD)->getParent()->isLambda(); 591 592 // Find first parameter with a default argument 593 for (p = 0; p < NumParams; ++p) { 594 ParmVarDecl *Param = FD->getParamDecl(p); 595 if (Param->hasDefaultArg()) { 596 // C++11 [expr.prim.lambda]p5: 597 // [...] Default arguments (8.3.6) shall not be specified in the 598 // parameter-declaration-clause of a lambda-declarator. 599 // 600 // FIXME: Core issue 974 strikes this sentence, we only provide an 601 // extension warning. 602 if (IsLambda) 603 Diag(Param->getLocation(), diag::ext_lambda_default_arguments) 604 << Param->getDefaultArgRange(); 605 break; 606 } 607 } 608 609 // C++ [dcl.fct.default]p4: 610 // In a given function declaration, all parameters 611 // subsequent to a parameter with a default argument shall 612 // have default arguments supplied in this or previous 613 // declarations. A default argument shall not be redefined 614 // by a later declaration (not even to the same value). 615 unsigned LastMissingDefaultArg = 0; 616 for (; p < NumParams; ++p) { 617 ParmVarDecl *Param = FD->getParamDecl(p); 618 if (!Param->hasDefaultArg()) { 619 if (Param->isInvalidDecl()) 620 /* We already complained about this parameter. */; 621 else if (Param->getIdentifier()) 622 Diag(Param->getLocation(), 623 diag::err_param_default_argument_missing_name) 624 << Param->getIdentifier(); 625 else 626 Diag(Param->getLocation(), 627 diag::err_param_default_argument_missing); 628 629 LastMissingDefaultArg = p; 630 } 631 } 632 633 if (LastMissingDefaultArg > 0) { 634 // Some default arguments were missing. Clear out all of the 635 // default arguments up to (and including) the last missing 636 // default argument, so that we leave the function parameters 637 // in a semantically valid state. 638 for (p = 0; p <= LastMissingDefaultArg; ++p) { 639 ParmVarDecl *Param = FD->getParamDecl(p); 640 if (Param->hasDefaultArg()) { 641 Param->setDefaultArg(0); 642 } 643 } 644 } 645} 646 647// CheckConstexprParameterTypes - Check whether a function's parameter types 648// are all literal types. If so, return true. If not, produce a suitable 649// diagnostic and return false. 650static bool CheckConstexprParameterTypes(Sema &SemaRef, 651 const FunctionDecl *FD) { 652 unsigned ArgIndex = 0; 653 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 654 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(), 655 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) { 656 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 657 SourceLocation ParamLoc = PD->getLocation(); 658 if (!(*i)->isDependentType() && 659 SemaRef.RequireLiteralType(ParamLoc, *i, 660 SemaRef.PDiag(diag::err_constexpr_non_literal_param) 661 << ArgIndex+1 << PD->getSourceRange() 662 << isa<CXXConstructorDecl>(FD))) 663 return false; 664 } 665 return true; 666} 667 668// CheckConstexprFunctionDecl - Check whether a function declaration satisfies 669// the requirements of a constexpr function definition or a constexpr 670// constructor definition. If so, return true. If not, produce appropriate 671// diagnostics and return false. 672// 673// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 674bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) { 675 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 676 if (MD && MD->isInstance()) { 677 // C++11 [dcl.constexpr]p4: 678 // The definition of a constexpr constructor shall satisfy the following 679 // constraints: 680 // - the class shall not have any virtual base classes; 681 const CXXRecordDecl *RD = MD->getParent(); 682 if (RD->getNumVBases()) { 683 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 684 << isa<CXXConstructorDecl>(NewFD) << RD->isStruct() 685 << RD->getNumVBases(); 686 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(), 687 E = RD->vbases_end(); I != E; ++I) 688 Diag(I->getSourceRange().getBegin(), 689 diag::note_constexpr_virtual_base_here) << I->getSourceRange(); 690 return false; 691 } 692 } 693 694 if (!isa<CXXConstructorDecl>(NewFD)) { 695 // C++11 [dcl.constexpr]p3: 696 // The definition of a constexpr function shall satisfy the following 697 // constraints: 698 // - it shall not be virtual; 699 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 700 if (Method && Method->isVirtual()) { 701 Diag(NewFD->getLocation(), diag::err_constexpr_virtual); 702 703 // If it's not obvious why this function is virtual, find an overridden 704 // function which uses the 'virtual' keyword. 705 const CXXMethodDecl *WrittenVirtual = Method; 706 while (!WrittenVirtual->isVirtualAsWritten()) 707 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 708 if (WrittenVirtual != Method) 709 Diag(WrittenVirtual->getLocation(), 710 diag::note_overridden_virtual_function); 711 return false; 712 } 713 714 // - its return type shall be a literal type; 715 QualType RT = NewFD->getResultType(); 716 if (!RT->isDependentType() && 717 RequireLiteralType(NewFD->getLocation(), RT, 718 PDiag(diag::err_constexpr_non_literal_return))) 719 return false; 720 } 721 722 // - each of its parameter types shall be a literal type; 723 if (!CheckConstexprParameterTypes(*this, NewFD)) 724 return false; 725 726 return true; 727} 728 729/// Check the given declaration statement is legal within a constexpr function 730/// body. C++0x [dcl.constexpr]p3,p4. 731/// 732/// \return true if the body is OK, false if we have diagnosed a problem. 733static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 734 DeclStmt *DS) { 735 // C++0x [dcl.constexpr]p3 and p4: 736 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 737 // contain only 738 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(), 739 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) { 740 switch ((*DclIt)->getKind()) { 741 case Decl::StaticAssert: 742 case Decl::Using: 743 case Decl::UsingShadow: 744 case Decl::UsingDirective: 745 case Decl::UnresolvedUsingTypename: 746 // - static_assert-declarations 747 // - using-declarations, 748 // - using-directives, 749 continue; 750 751 case Decl::Typedef: 752 case Decl::TypeAlias: { 753 // - typedef declarations and alias-declarations that do not define 754 // classes or enumerations, 755 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt); 756 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 757 // Don't allow variably-modified types in constexpr functions. 758 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 759 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 760 << TL.getSourceRange() << TL.getType() 761 << isa<CXXConstructorDecl>(Dcl); 762 return false; 763 } 764 continue; 765 } 766 767 case Decl::Enum: 768 case Decl::CXXRecord: 769 // As an extension, we allow the declaration (but not the definition) of 770 // classes and enumerations in all declarations, not just in typedef and 771 // alias declarations. 772 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) { 773 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition) 774 << isa<CXXConstructorDecl>(Dcl); 775 return false; 776 } 777 continue; 778 779 case Decl::Var: 780 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration) 781 << isa<CXXConstructorDecl>(Dcl); 782 return false; 783 784 default: 785 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt) 786 << isa<CXXConstructorDecl>(Dcl); 787 return false; 788 } 789 } 790 791 return true; 792} 793 794/// Check that the given field is initialized within a constexpr constructor. 795/// 796/// \param Dcl The constexpr constructor being checked. 797/// \param Field The field being checked. This may be a member of an anonymous 798/// struct or union nested within the class being checked. 799/// \param Inits All declarations, including anonymous struct/union members and 800/// indirect members, for which any initialization was provided. 801/// \param Diagnosed Set to true if an error is produced. 802static void CheckConstexprCtorInitializer(Sema &SemaRef, 803 const FunctionDecl *Dcl, 804 FieldDecl *Field, 805 llvm::SmallSet<Decl*, 16> &Inits, 806 bool &Diagnosed) { 807 if (Field->isUnnamedBitfield()) 808 return; 809 810 if (Field->isAnonymousStructOrUnion() && 811 Field->getType()->getAsCXXRecordDecl()->isEmpty()) 812 return; 813 814 if (!Inits.count(Field)) { 815 if (!Diagnosed) { 816 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init); 817 Diagnosed = true; 818 } 819 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init); 820 } else if (Field->isAnonymousStructOrUnion()) { 821 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 822 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end(); 823 I != E; ++I) 824 // If an anonymous union contains an anonymous struct of which any member 825 // is initialized, all members must be initialized. 826 if (!RD->isUnion() || Inits.count(*I)) 827 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed); 828 } 829} 830 831/// Check the body for the given constexpr function declaration only contains 832/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 833/// 834/// \return true if the body is OK, false if we have diagnosed a problem. 835bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) { 836 if (isa<CXXTryStmt>(Body)) { 837 // C++11 [dcl.constexpr]p3: 838 // The definition of a constexpr function shall satisfy the following 839 // constraints: [...] 840 // - its function-body shall be = delete, = default, or a 841 // compound-statement 842 // 843 // C++11 [dcl.constexpr]p4: 844 // In the definition of a constexpr constructor, [...] 845 // - its function-body shall not be a function-try-block; 846 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block) 847 << isa<CXXConstructorDecl>(Dcl); 848 return false; 849 } 850 851 // - its function-body shall be [...] a compound-statement that contains only 852 CompoundStmt *CompBody = cast<CompoundStmt>(Body); 853 854 llvm::SmallVector<SourceLocation, 4> ReturnStmts; 855 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(), 856 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) { 857 switch ((*BodyIt)->getStmtClass()) { 858 case Stmt::NullStmtClass: 859 // - null statements, 860 continue; 861 862 case Stmt::DeclStmtClass: 863 // - static_assert-declarations 864 // - using-declarations, 865 // - using-directives, 866 // - typedef declarations and alias-declarations that do not define 867 // classes or enumerations, 868 if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt))) 869 return false; 870 continue; 871 872 case Stmt::ReturnStmtClass: 873 // - and exactly one return statement; 874 if (isa<CXXConstructorDecl>(Dcl)) 875 break; 876 877 ReturnStmts.push_back((*BodyIt)->getLocStart()); 878 // FIXME 879 // - every constructor call and implicit conversion used in initializing 880 // the return value shall be one of those allowed in a constant 881 // expression. 882 // Deal with this as part of a general check that the function can produce 883 // a constant expression (for [dcl.constexpr]p5). 884 continue; 885 886 default: 887 break; 888 } 889 890 Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt) 891 << isa<CXXConstructorDecl>(Dcl); 892 return false; 893 } 894 895 if (const CXXConstructorDecl *Constructor 896 = dyn_cast<CXXConstructorDecl>(Dcl)) { 897 const CXXRecordDecl *RD = Constructor->getParent(); 898 // DR1359: 899 // - every non-variant non-static data member and base class sub-object 900 // shall be initialized; 901 // - if the class is a non-empty union, or for each non-empty anonymous 902 // union member of a non-union class, exactly one non-static data member 903 // shall be initialized; 904 if (RD->isUnion()) { 905 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) { 906 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init); 907 return false; 908 } 909 } else if (!Constructor->isDependentContext() && 910 !Constructor->isDelegatingConstructor()) { 911 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 912 913 // Skip detailed checking if we have enough initializers, and we would 914 // allow at most one initializer per member. 915 bool AnyAnonStructUnionMembers = false; 916 unsigned Fields = 0; 917 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 918 E = RD->field_end(); I != E; ++I, ++Fields) { 919 if ((*I)->isAnonymousStructOrUnion()) { 920 AnyAnonStructUnionMembers = true; 921 break; 922 } 923 } 924 if (AnyAnonStructUnionMembers || 925 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 926 // Check initialization of non-static data members. Base classes are 927 // always initialized so do not need to be checked. Dependent bases 928 // might not have initializers in the member initializer list. 929 llvm::SmallSet<Decl*, 16> Inits; 930 for (CXXConstructorDecl::init_const_iterator 931 I = Constructor->init_begin(), E = Constructor->init_end(); 932 I != E; ++I) { 933 if (FieldDecl *FD = (*I)->getMember()) 934 Inits.insert(FD); 935 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember()) 936 Inits.insert(ID->chain_begin(), ID->chain_end()); 937 } 938 939 bool Diagnosed = false; 940 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 941 E = RD->field_end(); I != E; ++I) 942 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed); 943 if (Diagnosed) 944 return false; 945 } 946 } 947 948 // FIXME 949 // - every constructor involved in initializing non-static data members 950 // and base class sub-objects shall be a constexpr constructor; 951 // - every assignment-expression that is an initializer-clause appearing 952 // directly or indirectly within a brace-or-equal-initializer for 953 // a non-static data member that is not named by a mem-initializer-id 954 // shall be a constant expression; and 955 // - every implicit conversion used in converting a constructor argument 956 // to the corresponding parameter type and converting 957 // a full-expression to the corresponding member type shall be one of 958 // those allowed in a constant expression. 959 // Deal with these as part of a general check that the function can produce 960 // a constant expression (for [dcl.constexpr]p5). 961 } else { 962 if (ReturnStmts.empty()) { 963 Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return); 964 return false; 965 } 966 if (ReturnStmts.size() > 1) { 967 Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return); 968 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 969 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return); 970 return false; 971 } 972 } 973 974 // C++11 [dcl.constexpr]p5: 975 // if no function argument values exist such that the function invocation 976 // substitution would produce a constant expression, the program is 977 // ill-formed; no diagnostic required. 978 // C++11 [dcl.constexpr]p3: 979 // - every constructor call and implicit conversion used in initializing the 980 // return value shall be one of those allowed in a constant expression. 981 // C++11 [dcl.constexpr]p4: 982 // - every constructor involved in initializing non-static data members and 983 // base class sub-objects shall be a constexpr constructor. 984 llvm::SmallVector<PartialDiagnosticAt, 8> Diags; 985 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) { 986 Diag(Dcl->getLocation(), diag::err_constexpr_function_never_constant_expr) 987 << isa<CXXConstructorDecl>(Dcl); 988 for (size_t I = 0, N = Diags.size(); I != N; ++I) 989 Diag(Diags[I].first, Diags[I].second); 990 return false; 991 } 992 993 return true; 994} 995 996/// isCurrentClassName - Determine whether the identifier II is the 997/// name of the class type currently being defined. In the case of 998/// nested classes, this will only return true if II is the name of 999/// the innermost class. 1000bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 1001 const CXXScopeSpec *SS) { 1002 assert(getLangOptions().CPlusPlus && "No class names in C!"); 1003 1004 CXXRecordDecl *CurDecl; 1005 if (SS && SS->isSet() && !SS->isInvalid()) { 1006 DeclContext *DC = computeDeclContext(*SS, true); 1007 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 1008 } else 1009 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1010 1011 if (CurDecl && CurDecl->getIdentifier()) 1012 return &II == CurDecl->getIdentifier(); 1013 else 1014 return false; 1015} 1016 1017/// \brief Check the validity of a C++ base class specifier. 1018/// 1019/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 1020/// and returns NULL otherwise. 1021CXXBaseSpecifier * 1022Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 1023 SourceRange SpecifierRange, 1024 bool Virtual, AccessSpecifier Access, 1025 TypeSourceInfo *TInfo, 1026 SourceLocation EllipsisLoc) { 1027 QualType BaseType = TInfo->getType(); 1028 1029 // C++ [class.union]p1: 1030 // A union shall not have base classes. 1031 if (Class->isUnion()) { 1032 Diag(Class->getLocation(), diag::err_base_clause_on_union) 1033 << SpecifierRange; 1034 return 0; 1035 } 1036 1037 if (EllipsisLoc.isValid() && 1038 !TInfo->getType()->containsUnexpandedParameterPack()) { 1039 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 1040 << TInfo->getTypeLoc().getSourceRange(); 1041 EllipsisLoc = SourceLocation(); 1042 } 1043 1044 if (BaseType->isDependentType()) 1045 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1046 Class->getTagKind() == TTK_Class, 1047 Access, TInfo, EllipsisLoc); 1048 1049 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 1050 1051 // Base specifiers must be record types. 1052 if (!BaseType->isRecordType()) { 1053 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 1054 return 0; 1055 } 1056 1057 // C++ [class.union]p1: 1058 // A union shall not be used as a base class. 1059 if (BaseType->isUnionType()) { 1060 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 1061 return 0; 1062 } 1063 1064 // C++ [class.derived]p2: 1065 // The class-name in a base-specifier shall not be an incompletely 1066 // defined class. 1067 if (RequireCompleteType(BaseLoc, BaseType, 1068 PDiag(diag::err_incomplete_base_class) 1069 << SpecifierRange)) { 1070 Class->setInvalidDecl(); 1071 return 0; 1072 } 1073 1074 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 1075 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 1076 assert(BaseDecl && "Record type has no declaration"); 1077 BaseDecl = BaseDecl->getDefinition(); 1078 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 1079 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 1080 assert(CXXBaseDecl && "Base type is not a C++ type"); 1081 1082 // C++ [class]p3: 1083 // If a class is marked final and it appears as a base-type-specifier in 1084 // base-clause, the program is ill-formed. 1085 if (CXXBaseDecl->hasAttr<FinalAttr>()) { 1086 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 1087 << CXXBaseDecl->getDeclName(); 1088 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl) 1089 << CXXBaseDecl->getDeclName(); 1090 return 0; 1091 } 1092 1093 if (BaseDecl->isInvalidDecl()) 1094 Class->setInvalidDecl(); 1095 1096 // Create the base specifier. 1097 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1098 Class->getTagKind() == TTK_Class, 1099 Access, TInfo, EllipsisLoc); 1100} 1101 1102/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 1103/// one entry in the base class list of a class specifier, for 1104/// example: 1105/// class foo : public bar, virtual private baz { 1106/// 'public bar' and 'virtual private baz' are each base-specifiers. 1107BaseResult 1108Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 1109 bool Virtual, AccessSpecifier Access, 1110 ParsedType basetype, SourceLocation BaseLoc, 1111 SourceLocation EllipsisLoc) { 1112 if (!classdecl) 1113 return true; 1114 1115 AdjustDeclIfTemplate(classdecl); 1116 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 1117 if (!Class) 1118 return true; 1119 1120 TypeSourceInfo *TInfo = 0; 1121 GetTypeFromParser(basetype, &TInfo); 1122 1123 if (EllipsisLoc.isInvalid() && 1124 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 1125 UPPC_BaseType)) 1126 return true; 1127 1128 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 1129 Virtual, Access, TInfo, 1130 EllipsisLoc)) 1131 return BaseSpec; 1132 1133 return true; 1134} 1135 1136/// \brief Performs the actual work of attaching the given base class 1137/// specifiers to a C++ class. 1138bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 1139 unsigned NumBases) { 1140 if (NumBases == 0) 1141 return false; 1142 1143 // Used to keep track of which base types we have already seen, so 1144 // that we can properly diagnose redundant direct base types. Note 1145 // that the key is always the unqualified canonical type of the base 1146 // class. 1147 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 1148 1149 // Copy non-redundant base specifiers into permanent storage. 1150 unsigned NumGoodBases = 0; 1151 bool Invalid = false; 1152 for (unsigned idx = 0; idx < NumBases; ++idx) { 1153 QualType NewBaseType 1154 = Context.getCanonicalType(Bases[idx]->getType()); 1155 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 1156 if (KnownBaseTypes[NewBaseType]) { 1157 // C++ [class.mi]p3: 1158 // A class shall not be specified as a direct base class of a 1159 // derived class more than once. 1160 Diag(Bases[idx]->getSourceRange().getBegin(), 1161 diag::err_duplicate_base_class) 1162 << KnownBaseTypes[NewBaseType]->getType() 1163 << Bases[idx]->getSourceRange(); 1164 1165 // Delete the duplicate base class specifier; we're going to 1166 // overwrite its pointer later. 1167 Context.Deallocate(Bases[idx]); 1168 1169 Invalid = true; 1170 } else { 1171 // Okay, add this new base class. 1172 KnownBaseTypes[NewBaseType] = Bases[idx]; 1173 Bases[NumGoodBases++] = Bases[idx]; 1174 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) 1175 if (const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl())) 1176 if (RD->hasAttr<WeakAttr>()) 1177 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context)); 1178 } 1179 } 1180 1181 // Attach the remaining base class specifiers to the derived class. 1182 Class->setBases(Bases, NumGoodBases); 1183 1184 // Delete the remaining (good) base class specifiers, since their 1185 // data has been copied into the CXXRecordDecl. 1186 for (unsigned idx = 0; idx < NumGoodBases; ++idx) 1187 Context.Deallocate(Bases[idx]); 1188 1189 return Invalid; 1190} 1191 1192/// ActOnBaseSpecifiers - Attach the given base specifiers to the 1193/// class, after checking whether there are any duplicate base 1194/// classes. 1195void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases, 1196 unsigned NumBases) { 1197 if (!ClassDecl || !Bases || !NumBases) 1198 return; 1199 1200 AdjustDeclIfTemplate(ClassDecl); 1201 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), 1202 (CXXBaseSpecifier**)(Bases), NumBases); 1203} 1204 1205static CXXRecordDecl *GetClassForType(QualType T) { 1206 if (const RecordType *RT = T->getAs<RecordType>()) 1207 return cast<CXXRecordDecl>(RT->getDecl()); 1208 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>()) 1209 return ICT->getDecl(); 1210 else 1211 return 0; 1212} 1213 1214/// \brief Determine whether the type \p Derived is a C++ class that is 1215/// derived from the type \p Base. 1216bool Sema::IsDerivedFrom(QualType Derived, QualType Base) { 1217 if (!getLangOptions().CPlusPlus) 1218 return false; 1219 1220 CXXRecordDecl *DerivedRD = GetClassForType(Derived); 1221 if (!DerivedRD) 1222 return false; 1223 1224 CXXRecordDecl *BaseRD = GetClassForType(Base); 1225 if (!BaseRD) 1226 return false; 1227 1228 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this. 1229 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD); 1230} 1231 1232/// \brief Determine whether the type \p Derived is a C++ class that is 1233/// derived from the type \p Base. 1234bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) { 1235 if (!getLangOptions().CPlusPlus) 1236 return false; 1237 1238 CXXRecordDecl *DerivedRD = GetClassForType(Derived); 1239 if (!DerivedRD) 1240 return false; 1241 1242 CXXRecordDecl *BaseRD = GetClassForType(Base); 1243 if (!BaseRD) 1244 return false; 1245 1246 return DerivedRD->isDerivedFrom(BaseRD, Paths); 1247} 1248 1249void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 1250 CXXCastPath &BasePathArray) { 1251 assert(BasePathArray.empty() && "Base path array must be empty!"); 1252 assert(Paths.isRecordingPaths() && "Must record paths!"); 1253 1254 const CXXBasePath &Path = Paths.front(); 1255 1256 // We first go backward and check if we have a virtual base. 1257 // FIXME: It would be better if CXXBasePath had the base specifier for 1258 // the nearest virtual base. 1259 unsigned Start = 0; 1260 for (unsigned I = Path.size(); I != 0; --I) { 1261 if (Path[I - 1].Base->isVirtual()) { 1262 Start = I - 1; 1263 break; 1264 } 1265 } 1266 1267 // Now add all bases. 1268 for (unsigned I = Start, E = Path.size(); I != E; ++I) 1269 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 1270} 1271 1272/// \brief Determine whether the given base path includes a virtual 1273/// base class. 1274bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) { 1275 for (CXXCastPath::const_iterator B = BasePath.begin(), 1276 BEnd = BasePath.end(); 1277 B != BEnd; ++B) 1278 if ((*B)->isVirtual()) 1279 return true; 1280 1281 return false; 1282} 1283 1284/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 1285/// conversion (where Derived and Base are class types) is 1286/// well-formed, meaning that the conversion is unambiguous (and 1287/// that all of the base classes are accessible). Returns true 1288/// and emits a diagnostic if the code is ill-formed, returns false 1289/// otherwise. Loc is the location where this routine should point to 1290/// if there is an error, and Range is the source range to highlight 1291/// if there is an error. 1292bool 1293Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1294 unsigned InaccessibleBaseID, 1295 unsigned AmbigiousBaseConvID, 1296 SourceLocation Loc, SourceRange Range, 1297 DeclarationName Name, 1298 CXXCastPath *BasePath) { 1299 // First, determine whether the path from Derived to Base is 1300 // ambiguous. This is slightly more expensive than checking whether 1301 // the Derived to Base conversion exists, because here we need to 1302 // explore multiple paths to determine if there is an ambiguity. 1303 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1304 /*DetectVirtual=*/false); 1305 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths); 1306 assert(DerivationOkay && 1307 "Can only be used with a derived-to-base conversion"); 1308 (void)DerivationOkay; 1309 1310 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 1311 if (InaccessibleBaseID) { 1312 // Check that the base class can be accessed. 1313 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(), 1314 InaccessibleBaseID)) { 1315 case AR_inaccessible: 1316 return true; 1317 case AR_accessible: 1318 case AR_dependent: 1319 case AR_delayed: 1320 break; 1321 } 1322 } 1323 1324 // Build a base path if necessary. 1325 if (BasePath) 1326 BuildBasePathArray(Paths, *BasePath); 1327 return false; 1328 } 1329 1330 // We know that the derived-to-base conversion is ambiguous, and 1331 // we're going to produce a diagnostic. Perform the derived-to-base 1332 // search just one more time to compute all of the possible paths so 1333 // that we can print them out. This is more expensive than any of 1334 // the previous derived-to-base checks we've done, but at this point 1335 // performance isn't as much of an issue. 1336 Paths.clear(); 1337 Paths.setRecordingPaths(true); 1338 bool StillOkay = IsDerivedFrom(Derived, Base, Paths); 1339 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 1340 (void)StillOkay; 1341 1342 // Build up a textual representation of the ambiguous paths, e.g., 1343 // D -> B -> A, that will be used to illustrate the ambiguous 1344 // conversions in the diagnostic. We only print one of the paths 1345 // to each base class subobject. 1346 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 1347 1348 Diag(Loc, AmbigiousBaseConvID) 1349 << Derived << Base << PathDisplayStr << Range << Name; 1350 return true; 1351} 1352 1353bool 1354Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1355 SourceLocation Loc, SourceRange Range, 1356 CXXCastPath *BasePath, 1357 bool IgnoreAccess) { 1358 return CheckDerivedToBaseConversion(Derived, Base, 1359 IgnoreAccess ? 0 1360 : diag::err_upcast_to_inaccessible_base, 1361 diag::err_ambiguous_derived_to_base_conv, 1362 Loc, Range, DeclarationName(), 1363 BasePath); 1364} 1365 1366 1367/// @brief Builds a string representing ambiguous paths from a 1368/// specific derived class to different subobjects of the same base 1369/// class. 1370/// 1371/// This function builds a string that can be used in error messages 1372/// to show the different paths that one can take through the 1373/// inheritance hierarchy to go from the derived class to different 1374/// subobjects of a base class. The result looks something like this: 1375/// @code 1376/// struct D -> struct B -> struct A 1377/// struct D -> struct C -> struct A 1378/// @endcode 1379std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 1380 std::string PathDisplayStr; 1381 std::set<unsigned> DisplayedPaths; 1382 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 1383 Path != Paths.end(); ++Path) { 1384 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 1385 // We haven't displayed a path to this particular base 1386 // class subobject yet. 1387 PathDisplayStr += "\n "; 1388 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 1389 for (CXXBasePath::const_iterator Element = Path->begin(); 1390 Element != Path->end(); ++Element) 1391 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 1392 } 1393 } 1394 1395 return PathDisplayStr; 1396} 1397 1398//===----------------------------------------------------------------------===// 1399// C++ class member Handling 1400//===----------------------------------------------------------------------===// 1401 1402/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 1403bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, 1404 SourceLocation ASLoc, 1405 SourceLocation ColonLoc, 1406 AttributeList *Attrs) { 1407 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 1408 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 1409 ASLoc, ColonLoc); 1410 CurContext->addHiddenDecl(ASDecl); 1411 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 1412} 1413 1414/// CheckOverrideControl - Check C++0x override control semantics. 1415void Sema::CheckOverrideControl(const Decl *D) { 1416 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 1417 if (!MD || !MD->isVirtual()) 1418 return; 1419 1420 if (MD->isDependentContext()) 1421 return; 1422 1423 // C++0x [class.virtual]p3: 1424 // If a virtual function is marked with the virt-specifier override and does 1425 // not override a member function of a base class, 1426 // the program is ill-formed. 1427 bool HasOverriddenMethods = 1428 MD->begin_overridden_methods() != MD->end_overridden_methods(); 1429 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) { 1430 Diag(MD->getLocation(), 1431 diag::err_function_marked_override_not_overriding) 1432 << MD->getDeclName(); 1433 return; 1434 } 1435} 1436 1437/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 1438/// function overrides a virtual member function marked 'final', according to 1439/// C++0x [class.virtual]p3. 1440bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 1441 const CXXMethodDecl *Old) { 1442 if (!Old->hasAttr<FinalAttr>()) 1443 return false; 1444 1445 Diag(New->getLocation(), diag::err_final_function_overridden) 1446 << New->getDeclName(); 1447 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 1448 return true; 1449} 1450 1451/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 1452/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 1453/// bitfield width if there is one, 'InitExpr' specifies the initializer if 1454/// one has been parsed, and 'HasDeferredInit' is true if an initializer is 1455/// present but parsing it has been deferred. 1456Decl * 1457Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 1458 MultiTemplateParamsArg TemplateParameterLists, 1459 Expr *BW, const VirtSpecifiers &VS, 1460 bool HasDeferredInit) { 1461 const DeclSpec &DS = D.getDeclSpec(); 1462 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 1463 DeclarationName Name = NameInfo.getName(); 1464 SourceLocation Loc = NameInfo.getLoc(); 1465 1466 // For anonymous bitfields, the location should point to the type. 1467 if (Loc.isInvalid()) 1468 Loc = D.getSourceRange().getBegin(); 1469 1470 Expr *BitWidth = static_cast<Expr*>(BW); 1471 1472 assert(isa<CXXRecordDecl>(CurContext)); 1473 assert(!DS.isFriendSpecified()); 1474 1475 bool isFunc = D.isDeclarationOfFunction(); 1476 1477 // C++ 9.2p6: A member shall not be declared to have automatic storage 1478 // duration (auto, register) or with the extern storage-class-specifier. 1479 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 1480 // data members and cannot be applied to names declared const or static, 1481 // and cannot be applied to reference members. 1482 switch (DS.getStorageClassSpec()) { 1483 case DeclSpec::SCS_unspecified: 1484 case DeclSpec::SCS_typedef: 1485 case DeclSpec::SCS_static: 1486 // FALL THROUGH. 1487 break; 1488 case DeclSpec::SCS_mutable: 1489 if (isFunc) { 1490 if (DS.getStorageClassSpecLoc().isValid()) 1491 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 1492 else 1493 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function); 1494 1495 // FIXME: It would be nicer if the keyword was ignored only for this 1496 // declarator. Otherwise we could get follow-up errors. 1497 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1498 } 1499 break; 1500 default: 1501 if (DS.getStorageClassSpecLoc().isValid()) 1502 Diag(DS.getStorageClassSpecLoc(), 1503 diag::err_storageclass_invalid_for_member); 1504 else 1505 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member); 1506 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1507 } 1508 1509 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 1510 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 1511 !isFunc); 1512 1513 Decl *Member; 1514 if (isInstField) { 1515 CXXScopeSpec &SS = D.getCXXScopeSpec(); 1516 1517 // Data members must have identifiers for names. 1518 if (Name.getNameKind() != DeclarationName::Identifier) { 1519 Diag(Loc, diag::err_bad_variable_name) 1520 << Name; 1521 return 0; 1522 } 1523 1524 IdentifierInfo *II = Name.getAsIdentifierInfo(); 1525 1526 // Member field could not be with "template" keyword. 1527 // So TemplateParameterLists should be empty in this case. 1528 if (TemplateParameterLists.size()) { 1529 TemplateParameterList* TemplateParams = TemplateParameterLists.get()[0]; 1530 if (TemplateParams->size()) { 1531 // There is no such thing as a member field template. 1532 Diag(D.getIdentifierLoc(), diag::err_template_member) 1533 << II 1534 << SourceRange(TemplateParams->getTemplateLoc(), 1535 TemplateParams->getRAngleLoc()); 1536 } else { 1537 // There is an extraneous 'template<>' for this member. 1538 Diag(TemplateParams->getTemplateLoc(), 1539 diag::err_template_member_noparams) 1540 << II 1541 << SourceRange(TemplateParams->getTemplateLoc(), 1542 TemplateParams->getRAngleLoc()); 1543 } 1544 return 0; 1545 } 1546 1547 if (SS.isSet() && !SS.isInvalid()) { 1548 // The user provided a superfluous scope specifier inside a class 1549 // definition: 1550 // 1551 // class X { 1552 // int X::member; 1553 // }; 1554 DeclContext *DC = 0; 1555 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext)) 1556 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification) 1557 << Name << FixItHint::CreateRemoval(SS.getRange()); 1558 else 1559 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 1560 << Name << SS.getRange(); 1561 1562 SS.clear(); 1563 } 1564 1565 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth, 1566 HasDeferredInit, AS); 1567 assert(Member && "HandleField never returns null"); 1568 } else { 1569 assert(!HasDeferredInit); 1570 1571 Member = HandleDeclarator(S, D, move(TemplateParameterLists)); 1572 if (!Member) { 1573 return 0; 1574 } 1575 1576 // Non-instance-fields can't have a bitfield. 1577 if (BitWidth) { 1578 if (Member->isInvalidDecl()) { 1579 // don't emit another diagnostic. 1580 } else if (isa<VarDecl>(Member)) { 1581 // C++ 9.6p3: A bit-field shall not be a static member. 1582 // "static member 'A' cannot be a bit-field" 1583 Diag(Loc, diag::err_static_not_bitfield) 1584 << Name << BitWidth->getSourceRange(); 1585 } else if (isa<TypedefDecl>(Member)) { 1586 // "typedef member 'x' cannot be a bit-field" 1587 Diag(Loc, diag::err_typedef_not_bitfield) 1588 << Name << BitWidth->getSourceRange(); 1589 } else { 1590 // A function typedef ("typedef int f(); f a;"). 1591 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 1592 Diag(Loc, diag::err_not_integral_type_bitfield) 1593 << Name << cast<ValueDecl>(Member)->getType() 1594 << BitWidth->getSourceRange(); 1595 } 1596 1597 BitWidth = 0; 1598 Member->setInvalidDecl(); 1599 } 1600 1601 Member->setAccess(AS); 1602 1603 // If we have declared a member function template, set the access of the 1604 // templated declaration as well. 1605 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 1606 FunTmpl->getTemplatedDecl()->setAccess(AS); 1607 } 1608 1609 if (VS.isOverrideSpecified()) { 1610 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 1611 if (!MD || !MD->isVirtual()) { 1612 Diag(Member->getLocStart(), 1613 diag::override_keyword_only_allowed_on_virtual_member_functions) 1614 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc()); 1615 } else 1616 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context)); 1617 } 1618 if (VS.isFinalSpecified()) { 1619 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 1620 if (!MD || !MD->isVirtual()) { 1621 Diag(Member->getLocStart(), 1622 diag::override_keyword_only_allowed_on_virtual_member_functions) 1623 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc()); 1624 } else 1625 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context)); 1626 } 1627 1628 if (VS.getLastLocation().isValid()) { 1629 // Update the end location of a method that has a virt-specifiers. 1630 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 1631 MD->setRangeEnd(VS.getLastLocation()); 1632 } 1633 1634 CheckOverrideControl(Member); 1635 1636 assert((Name || isInstField) && "No identifier for non-field ?"); 1637 1638 if (isInstField) 1639 FieldCollector->Add(cast<FieldDecl>(Member)); 1640 return Member; 1641} 1642 1643/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an 1644/// in-class initializer for a non-static C++ class member, and after 1645/// instantiating an in-class initializer in a class template. Such actions 1646/// are deferred until the class is complete. 1647void 1648Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation EqualLoc, 1649 Expr *InitExpr) { 1650 FieldDecl *FD = cast<FieldDecl>(D); 1651 1652 if (!InitExpr) { 1653 FD->setInvalidDecl(); 1654 FD->removeInClassInitializer(); 1655 return; 1656 } 1657 1658 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 1659 FD->setInvalidDecl(); 1660 FD->removeInClassInitializer(); 1661 return; 1662 } 1663 1664 ExprResult Init = InitExpr; 1665 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 1666 // FIXME: if there is no EqualLoc, this is list-initialization. 1667 Init = PerformCopyInitialization( 1668 InitializedEntity::InitializeMember(FD), EqualLoc, InitExpr); 1669 if (Init.isInvalid()) { 1670 FD->setInvalidDecl(); 1671 return; 1672 } 1673 1674 CheckImplicitConversions(Init.get(), EqualLoc); 1675 } 1676 1677 // C++0x [class.base.init]p7: 1678 // The initialization of each base and member constitutes a 1679 // full-expression. 1680 Init = MaybeCreateExprWithCleanups(Init); 1681 if (Init.isInvalid()) { 1682 FD->setInvalidDecl(); 1683 return; 1684 } 1685 1686 InitExpr = Init.release(); 1687 1688 FD->setInClassInitializer(InitExpr); 1689} 1690 1691/// \brief Find the direct and/or virtual base specifiers that 1692/// correspond to the given base type, for use in base initialization 1693/// within a constructor. 1694static bool FindBaseInitializer(Sema &SemaRef, 1695 CXXRecordDecl *ClassDecl, 1696 QualType BaseType, 1697 const CXXBaseSpecifier *&DirectBaseSpec, 1698 const CXXBaseSpecifier *&VirtualBaseSpec) { 1699 // First, check for a direct base class. 1700 DirectBaseSpec = 0; 1701 for (CXXRecordDecl::base_class_const_iterator Base 1702 = ClassDecl->bases_begin(); 1703 Base != ClassDecl->bases_end(); ++Base) { 1704 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) { 1705 // We found a direct base of this type. That's what we're 1706 // initializing. 1707 DirectBaseSpec = &*Base; 1708 break; 1709 } 1710 } 1711 1712 // Check for a virtual base class. 1713 // FIXME: We might be able to short-circuit this if we know in advance that 1714 // there are no virtual bases. 1715 VirtualBaseSpec = 0; 1716 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 1717 // We haven't found a base yet; search the class hierarchy for a 1718 // virtual base class. 1719 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1720 /*DetectVirtual=*/false); 1721 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl), 1722 BaseType, Paths)) { 1723 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 1724 Path != Paths.end(); ++Path) { 1725 if (Path->back().Base->isVirtual()) { 1726 VirtualBaseSpec = Path->back().Base; 1727 break; 1728 } 1729 } 1730 } 1731 } 1732 1733 return DirectBaseSpec || VirtualBaseSpec; 1734} 1735 1736/// \brief Handle a C++ member initializer using braced-init-list syntax. 1737MemInitResult 1738Sema::ActOnMemInitializer(Decl *ConstructorD, 1739 Scope *S, 1740 CXXScopeSpec &SS, 1741 IdentifierInfo *MemberOrBase, 1742 ParsedType TemplateTypeTy, 1743 const DeclSpec &DS, 1744 SourceLocation IdLoc, 1745 Expr *InitList, 1746 SourceLocation EllipsisLoc) { 1747 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 1748 DS, IdLoc, InitList, 1749 EllipsisLoc); 1750} 1751 1752/// \brief Handle a C++ member initializer using parentheses syntax. 1753MemInitResult 1754Sema::ActOnMemInitializer(Decl *ConstructorD, 1755 Scope *S, 1756 CXXScopeSpec &SS, 1757 IdentifierInfo *MemberOrBase, 1758 ParsedType TemplateTypeTy, 1759 const DeclSpec &DS, 1760 SourceLocation IdLoc, 1761 SourceLocation LParenLoc, 1762 Expr **Args, unsigned NumArgs, 1763 SourceLocation RParenLoc, 1764 SourceLocation EllipsisLoc) { 1765 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs, 1766 RParenLoc); 1767 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 1768 DS, IdLoc, List, EllipsisLoc); 1769} 1770 1771namespace { 1772 1773// Callback to only accept typo corrections that can be a valid C++ member 1774// intializer: either a non-static field member or a base class. 1775class MemInitializerValidatorCCC : public CorrectionCandidateCallback { 1776 public: 1777 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 1778 : ClassDecl(ClassDecl) {} 1779 1780 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 1781 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 1782 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 1783 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 1784 else 1785 return isa<TypeDecl>(ND); 1786 } 1787 return false; 1788 } 1789 1790 private: 1791 CXXRecordDecl *ClassDecl; 1792}; 1793 1794} 1795 1796/// \brief Handle a C++ member initializer. 1797MemInitResult 1798Sema::BuildMemInitializer(Decl *ConstructorD, 1799 Scope *S, 1800 CXXScopeSpec &SS, 1801 IdentifierInfo *MemberOrBase, 1802 ParsedType TemplateTypeTy, 1803 const DeclSpec &DS, 1804 SourceLocation IdLoc, 1805 Expr *Init, 1806 SourceLocation EllipsisLoc) { 1807 if (!ConstructorD) 1808 return true; 1809 1810 AdjustDeclIfTemplate(ConstructorD); 1811 1812 CXXConstructorDecl *Constructor 1813 = dyn_cast<CXXConstructorDecl>(ConstructorD); 1814 if (!Constructor) { 1815 // The user wrote a constructor initializer on a function that is 1816 // not a C++ constructor. Ignore the error for now, because we may 1817 // have more member initializers coming; we'll diagnose it just 1818 // once in ActOnMemInitializers. 1819 return true; 1820 } 1821 1822 CXXRecordDecl *ClassDecl = Constructor->getParent(); 1823 1824 // C++ [class.base.init]p2: 1825 // Names in a mem-initializer-id are looked up in the scope of the 1826 // constructor's class and, if not found in that scope, are looked 1827 // up in the scope containing the constructor's definition. 1828 // [Note: if the constructor's class contains a member with the 1829 // same name as a direct or virtual base class of the class, a 1830 // mem-initializer-id naming the member or base class and composed 1831 // of a single identifier refers to the class member. A 1832 // mem-initializer-id for the hidden base class may be specified 1833 // using a qualified name. ] 1834 if (!SS.getScopeRep() && !TemplateTypeTy) { 1835 // Look for a member, first. 1836 DeclContext::lookup_result Result 1837 = ClassDecl->lookup(MemberOrBase); 1838 if (Result.first != Result.second) { 1839 ValueDecl *Member; 1840 if ((Member = dyn_cast<FieldDecl>(*Result.first)) || 1841 (Member = dyn_cast<IndirectFieldDecl>(*Result.first))) { 1842 if (EllipsisLoc.isValid()) 1843 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 1844 << MemberOrBase 1845 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 1846 1847 return BuildMemberInitializer(Member, Init, IdLoc); 1848 } 1849 } 1850 } 1851 // It didn't name a member, so see if it names a class. 1852 QualType BaseType; 1853 TypeSourceInfo *TInfo = 0; 1854 1855 if (TemplateTypeTy) { 1856 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 1857 } else if (DS.getTypeSpecType() == TST_decltype) { 1858 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 1859 } else { 1860 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 1861 LookupParsedName(R, S, &SS); 1862 1863 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 1864 if (!TyD) { 1865 if (R.isAmbiguous()) return true; 1866 1867 // We don't want access-control diagnostics here. 1868 R.suppressDiagnostics(); 1869 1870 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 1871 bool NotUnknownSpecialization = false; 1872 DeclContext *DC = computeDeclContext(SS, false); 1873 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 1874 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 1875 1876 if (!NotUnknownSpecialization) { 1877 // When the scope specifier can refer to a member of an unknown 1878 // specialization, we take it as a type name. 1879 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 1880 SS.getWithLocInContext(Context), 1881 *MemberOrBase, IdLoc); 1882 if (BaseType.isNull()) 1883 return true; 1884 1885 R.clear(); 1886 R.setLookupName(MemberOrBase); 1887 } 1888 } 1889 1890 // If no results were found, try to correct typos. 1891 TypoCorrection Corr; 1892 MemInitializerValidatorCCC Validator(ClassDecl); 1893 if (R.empty() && BaseType.isNull() && 1894 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 1895 Validator, ClassDecl))) { 1896 std::string CorrectedStr(Corr.getAsString(getLangOptions())); 1897 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOptions())); 1898 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 1899 // We have found a non-static data member with a similar 1900 // name to what was typed; complain and initialize that 1901 // member. 1902 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest) 1903 << MemberOrBase << true << CorrectedQuotedStr 1904 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr); 1905 Diag(Member->getLocation(), diag::note_previous_decl) 1906 << CorrectedQuotedStr; 1907 1908 return BuildMemberInitializer(Member, Init, IdLoc); 1909 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 1910 const CXXBaseSpecifier *DirectBaseSpec; 1911 const CXXBaseSpecifier *VirtualBaseSpec; 1912 if (FindBaseInitializer(*this, ClassDecl, 1913 Context.getTypeDeclType(Type), 1914 DirectBaseSpec, VirtualBaseSpec)) { 1915 // We have found a direct or virtual base class with a 1916 // similar name to what was typed; complain and initialize 1917 // that base class. 1918 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest) 1919 << MemberOrBase << false << CorrectedQuotedStr 1920 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr); 1921 1922 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec 1923 : VirtualBaseSpec; 1924 Diag(BaseSpec->getSourceRange().getBegin(), 1925 diag::note_base_class_specified_here) 1926 << BaseSpec->getType() 1927 << BaseSpec->getSourceRange(); 1928 1929 TyD = Type; 1930 } 1931 } 1932 } 1933 1934 if (!TyD && BaseType.isNull()) { 1935 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 1936 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 1937 return true; 1938 } 1939 } 1940 1941 if (BaseType.isNull()) { 1942 BaseType = Context.getTypeDeclType(TyD); 1943 if (SS.isSet()) { 1944 NestedNameSpecifier *Qualifier = 1945 static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 1946 1947 // FIXME: preserve source range information 1948 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType); 1949 } 1950 } 1951 } 1952 1953 if (!TInfo) 1954 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 1955 1956 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 1957} 1958 1959/// Checks a member initializer expression for cases where reference (or 1960/// pointer) members are bound to by-value parameters (or their addresses). 1961static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member, 1962 Expr *Init, 1963 SourceLocation IdLoc) { 1964 QualType MemberTy = Member->getType(); 1965 1966 // We only handle pointers and references currently. 1967 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers? 1968 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType()) 1969 return; 1970 1971 const bool IsPointer = MemberTy->isPointerType(); 1972 if (IsPointer) { 1973 if (const UnaryOperator *Op 1974 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) { 1975 // The only case we're worried about with pointers requires taking the 1976 // address. 1977 if (Op->getOpcode() != UO_AddrOf) 1978 return; 1979 1980 Init = Op->getSubExpr(); 1981 } else { 1982 // We only handle address-of expression initializers for pointers. 1983 return; 1984 } 1985 } 1986 1987 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) { 1988 // Taking the address of a temporary will be diagnosed as a hard error. 1989 if (IsPointer) 1990 return; 1991 1992 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary) 1993 << Member << Init->getSourceRange(); 1994 } else if (const DeclRefExpr *DRE 1995 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) { 1996 // We only warn when referring to a non-reference parameter declaration. 1997 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl()); 1998 if (!Parameter || Parameter->getType()->isReferenceType()) 1999 return; 2000 2001 S.Diag(Init->getExprLoc(), 2002 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr 2003 : diag::warn_bind_ref_member_to_parameter) 2004 << Member << Parameter << Init->getSourceRange(); 2005 } else { 2006 // Other initializers are fine. 2007 return; 2008 } 2009 2010 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here) 2011 << (unsigned)IsPointer; 2012} 2013 2014/// Checks an initializer expression for use of uninitialized fields, such as 2015/// containing the field that is being initialized. Returns true if there is an 2016/// uninitialized field was used an updates the SourceLocation parameter; false 2017/// otherwise. 2018static bool InitExprContainsUninitializedFields(const Stmt *S, 2019 const ValueDecl *LhsField, 2020 SourceLocation *L) { 2021 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField)); 2022 2023 if (isa<CallExpr>(S)) { 2024 // Do not descend into function calls or constructors, as the use 2025 // of an uninitialized field may be valid. One would have to inspect 2026 // the contents of the function/ctor to determine if it is safe or not. 2027 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers 2028 // may be safe, depending on what the function/ctor does. 2029 return false; 2030 } 2031 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) { 2032 const NamedDecl *RhsField = ME->getMemberDecl(); 2033 2034 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) { 2035 // The member expression points to a static data member. 2036 assert(VD->isStaticDataMember() && 2037 "Member points to non-static data member!"); 2038 (void)VD; 2039 return false; 2040 } 2041 2042 if (isa<EnumConstantDecl>(RhsField)) { 2043 // The member expression points to an enum. 2044 return false; 2045 } 2046 2047 if (RhsField == LhsField) { 2048 // Initializing a field with itself. Throw a warning. 2049 // But wait; there are exceptions! 2050 // Exception #1: The field may not belong to this record. 2051 // e.g. Foo(const Foo& rhs) : A(rhs.A) {} 2052 const Expr *base = ME->getBase(); 2053 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) { 2054 // Even though the field matches, it does not belong to this record. 2055 return false; 2056 } 2057 // None of the exceptions triggered; return true to indicate an 2058 // uninitialized field was used. 2059 *L = ME->getMemberLoc(); 2060 return true; 2061 } 2062 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) { 2063 // sizeof/alignof doesn't reference contents, do not warn. 2064 return false; 2065 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) { 2066 // address-of doesn't reference contents (the pointer may be dereferenced 2067 // in the same expression but it would be rare; and weird). 2068 if (UOE->getOpcode() == UO_AddrOf) 2069 return false; 2070 } 2071 for (Stmt::const_child_range it = S->children(); it; ++it) { 2072 if (!*it) { 2073 // An expression such as 'member(arg ?: "")' may trigger this. 2074 continue; 2075 } 2076 if (InitExprContainsUninitializedFields(*it, LhsField, L)) 2077 return true; 2078 } 2079 return false; 2080} 2081 2082MemInitResult 2083Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 2084 SourceLocation IdLoc) { 2085 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 2086 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 2087 assert((DirectMember || IndirectMember) && 2088 "Member must be a FieldDecl or IndirectFieldDecl"); 2089 2090 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 2091 return true; 2092 2093 if (Member->isInvalidDecl()) 2094 return true; 2095 2096 // Diagnose value-uses of fields to initialize themselves, e.g. 2097 // foo(foo) 2098 // where foo is not also a parameter to the constructor. 2099 // TODO: implement -Wuninitialized and fold this into that framework. 2100 Expr **Args; 2101 unsigned NumArgs; 2102 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2103 Args = ParenList->getExprs(); 2104 NumArgs = ParenList->getNumExprs(); 2105 } else { 2106 InitListExpr *InitList = cast<InitListExpr>(Init); 2107 Args = InitList->getInits(); 2108 NumArgs = InitList->getNumInits(); 2109 } 2110 for (unsigned i = 0; i < NumArgs; ++i) { 2111 SourceLocation L; 2112 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) { 2113 // FIXME: Return true in the case when other fields are used before being 2114 // uninitialized. For example, let this field be the i'th field. When 2115 // initializing the i'th field, throw a warning if any of the >= i'th 2116 // fields are used, as they are not yet initialized. 2117 // Right now we are only handling the case where the i'th field uses 2118 // itself in its initializer. 2119 Diag(L, diag::warn_field_is_uninit); 2120 } 2121 } 2122 2123 SourceRange InitRange = Init->getSourceRange(); 2124 2125 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 2126 // Can't check initialization for a member of dependent type or when 2127 // any of the arguments are type-dependent expressions. 2128 DiscardCleanupsInEvaluationContext(); 2129 } else { 2130 bool InitList = false; 2131 if (isa<InitListExpr>(Init)) { 2132 InitList = true; 2133 Args = &Init; 2134 NumArgs = 1; 2135 } 2136 2137 // Initialize the member. 2138 InitializedEntity MemberEntity = 2139 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0) 2140 : InitializedEntity::InitializeMember(IndirectMember, 0); 2141 InitializationKind Kind = 2142 InitList ? InitializationKind::CreateDirectList(IdLoc) 2143 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 2144 InitRange.getEnd()); 2145 2146 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs); 2147 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, 2148 MultiExprArg(*this, Args, NumArgs), 2149 0); 2150 if (MemberInit.isInvalid()) 2151 return true; 2152 2153 CheckImplicitConversions(MemberInit.get(), 2154 InitRange.getBegin()); 2155 2156 // C++0x [class.base.init]p7: 2157 // The initialization of each base and member constitutes a 2158 // full-expression. 2159 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 2160 if (MemberInit.isInvalid()) 2161 return true; 2162 2163 // If we are in a dependent context, template instantiation will 2164 // perform this type-checking again. Just save the arguments that we 2165 // received. 2166 // FIXME: This isn't quite ideal, since our ASTs don't capture all 2167 // of the information that we have about the member 2168 // initializer. However, deconstructing the ASTs is a dicey process, 2169 // and this approach is far more likely to get the corner cases right. 2170 if (CurContext->isDependentContext()) { 2171 // The existing Init will do fine. 2172 } else { 2173 Init = MemberInit.get(); 2174 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc); 2175 } 2176 } 2177 2178 if (DirectMember) { 2179 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 2180 InitRange.getBegin(), Init, 2181 InitRange.getEnd()); 2182 } else { 2183 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 2184 InitRange.getBegin(), Init, 2185 InitRange.getEnd()); 2186 } 2187} 2188 2189MemInitResult 2190Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 2191 CXXRecordDecl *ClassDecl) { 2192 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 2193 if (!LangOpts.CPlusPlus0x) 2194 return Diag(NameLoc, diag::err_delegating_ctor) 2195 << TInfo->getTypeLoc().getLocalSourceRange(); 2196 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 2197 2198 bool InitList = true; 2199 Expr **Args = &Init; 2200 unsigned NumArgs = 1; 2201 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2202 InitList = false; 2203 Args = ParenList->getExprs(); 2204 NumArgs = ParenList->getNumExprs(); 2205 } 2206 2207 SourceRange InitRange = Init->getSourceRange(); 2208 // Initialize the object. 2209 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 2210 QualType(ClassDecl->getTypeForDecl(), 0)); 2211 InitializationKind Kind = 2212 InitList ? InitializationKind::CreateDirectList(NameLoc) 2213 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 2214 InitRange.getEnd()); 2215 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs); 2216 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 2217 MultiExprArg(*this, Args,NumArgs), 2218 0); 2219 if (DelegationInit.isInvalid()) 2220 return true; 2221 2222 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 2223 "Delegating constructor with no target?"); 2224 2225 CheckImplicitConversions(DelegationInit.get(), InitRange.getBegin()); 2226 2227 // C++0x [class.base.init]p7: 2228 // The initialization of each base and member constitutes a 2229 // full-expression. 2230 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit); 2231 if (DelegationInit.isInvalid()) 2232 return true; 2233 2234 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 2235 DelegationInit.takeAs<Expr>(), 2236 InitRange.getEnd()); 2237} 2238 2239MemInitResult 2240Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 2241 Expr *Init, CXXRecordDecl *ClassDecl, 2242 SourceLocation EllipsisLoc) { 2243 SourceLocation BaseLoc 2244 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 2245 2246 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 2247 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 2248 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2249 2250 // C++ [class.base.init]p2: 2251 // [...] Unless the mem-initializer-id names a nonstatic data 2252 // member of the constructor's class or a direct or virtual base 2253 // of that class, the mem-initializer is ill-formed. A 2254 // mem-initializer-list can initialize a base class using any 2255 // name that denotes that base class type. 2256 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 2257 2258 SourceRange InitRange = Init->getSourceRange(); 2259 if (EllipsisLoc.isValid()) { 2260 // This is a pack expansion. 2261 if (!BaseType->containsUnexpandedParameterPack()) { 2262 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2263 << SourceRange(BaseLoc, InitRange.getEnd()); 2264 2265 EllipsisLoc = SourceLocation(); 2266 } 2267 } else { 2268 // Check for any unexpanded parameter packs. 2269 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 2270 return true; 2271 2272 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 2273 return true; 2274 } 2275 2276 // Check for direct and virtual base classes. 2277 const CXXBaseSpecifier *DirectBaseSpec = 0; 2278 const CXXBaseSpecifier *VirtualBaseSpec = 0; 2279 if (!Dependent) { 2280 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 2281 BaseType)) 2282 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 2283 2284 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 2285 VirtualBaseSpec); 2286 2287 // C++ [base.class.init]p2: 2288 // Unless the mem-initializer-id names a nonstatic data member of the 2289 // constructor's class or a direct or virtual base of that class, the 2290 // mem-initializer is ill-formed. 2291 if (!DirectBaseSpec && !VirtualBaseSpec) { 2292 // If the class has any dependent bases, then it's possible that 2293 // one of those types will resolve to the same type as 2294 // BaseType. Therefore, just treat this as a dependent base 2295 // class initialization. FIXME: Should we try to check the 2296 // initialization anyway? It seems odd. 2297 if (ClassDecl->hasAnyDependentBases()) 2298 Dependent = true; 2299 else 2300 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 2301 << BaseType << Context.getTypeDeclType(ClassDecl) 2302 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2303 } 2304 } 2305 2306 if (Dependent) { 2307 DiscardCleanupsInEvaluationContext(); 2308 2309 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 2310 /*IsVirtual=*/false, 2311 InitRange.getBegin(), Init, 2312 InitRange.getEnd(), EllipsisLoc); 2313 } 2314 2315 // C++ [base.class.init]p2: 2316 // If a mem-initializer-id is ambiguous because it designates both 2317 // a direct non-virtual base class and an inherited virtual base 2318 // class, the mem-initializer is ill-formed. 2319 if (DirectBaseSpec && VirtualBaseSpec) 2320 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 2321 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2322 2323 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec); 2324 if (!BaseSpec) 2325 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec); 2326 2327 // Initialize the base. 2328 bool InitList = true; 2329 Expr **Args = &Init; 2330 unsigned NumArgs = 1; 2331 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2332 InitList = false; 2333 Args = ParenList->getExprs(); 2334 NumArgs = ParenList->getNumExprs(); 2335 } 2336 2337 InitializedEntity BaseEntity = 2338 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 2339 InitializationKind Kind = 2340 InitList ? InitializationKind::CreateDirectList(BaseLoc) 2341 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 2342 InitRange.getEnd()); 2343 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs); 2344 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, 2345 MultiExprArg(*this, Args, NumArgs), 2346 0); 2347 if (BaseInit.isInvalid()) 2348 return true; 2349 2350 CheckImplicitConversions(BaseInit.get(), InitRange.getBegin()); 2351 2352 // C++0x [class.base.init]p7: 2353 // The initialization of each base and member constitutes a 2354 // full-expression. 2355 BaseInit = MaybeCreateExprWithCleanups(BaseInit); 2356 if (BaseInit.isInvalid()) 2357 return true; 2358 2359 // If we are in a dependent context, template instantiation will 2360 // perform this type-checking again. Just save the arguments that we 2361 // received in a ParenListExpr. 2362 // FIXME: This isn't quite ideal, since our ASTs don't capture all 2363 // of the information that we have about the base 2364 // initializer. However, deconstructing the ASTs is a dicey process, 2365 // and this approach is far more likely to get the corner cases right. 2366 if (CurContext->isDependentContext()) 2367 BaseInit = Owned(Init); 2368 2369 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 2370 BaseSpec->isVirtual(), 2371 InitRange.getBegin(), 2372 BaseInit.takeAs<Expr>(), 2373 InitRange.getEnd(), EllipsisLoc); 2374} 2375 2376// Create a static_cast\<T&&>(expr). 2377static Expr *CastForMoving(Sema &SemaRef, Expr *E) { 2378 QualType ExprType = E->getType(); 2379 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType); 2380 SourceLocation ExprLoc = E->getLocStart(); 2381 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 2382 TargetType, ExprLoc); 2383 2384 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 2385 SourceRange(ExprLoc, ExprLoc), 2386 E->getSourceRange()).take(); 2387} 2388 2389/// ImplicitInitializerKind - How an implicit base or member initializer should 2390/// initialize its base or member. 2391enum ImplicitInitializerKind { 2392 IIK_Default, 2393 IIK_Copy, 2394 IIK_Move 2395}; 2396 2397static bool 2398BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 2399 ImplicitInitializerKind ImplicitInitKind, 2400 CXXBaseSpecifier *BaseSpec, 2401 bool IsInheritedVirtualBase, 2402 CXXCtorInitializer *&CXXBaseInit) { 2403 InitializedEntity InitEntity 2404 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 2405 IsInheritedVirtualBase); 2406 2407 ExprResult BaseInit; 2408 2409 switch (ImplicitInitKind) { 2410 case IIK_Default: { 2411 InitializationKind InitKind 2412 = InitializationKind::CreateDefault(Constructor->getLocation()); 2413 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0); 2414 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, 2415 MultiExprArg(SemaRef, 0, 0)); 2416 break; 2417 } 2418 2419 case IIK_Move: 2420 case IIK_Copy: { 2421 bool Moving = ImplicitInitKind == IIK_Move; 2422 ParmVarDecl *Param = Constructor->getParamDecl(0); 2423 QualType ParamType = Param->getType().getNonReferenceType(); 2424 2425 Expr *CopyCtorArg = 2426 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 2427 SourceLocation(), Param, 2428 Constructor->getLocation(), ParamType, 2429 VK_LValue, 0); 2430 2431 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 2432 2433 // Cast to the base class to avoid ambiguities. 2434 QualType ArgTy = 2435 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 2436 ParamType.getQualifiers()); 2437 2438 if (Moving) { 2439 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 2440 } 2441 2442 CXXCastPath BasePath; 2443 BasePath.push_back(BaseSpec); 2444 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 2445 CK_UncheckedDerivedToBase, 2446 Moving ? VK_XValue : VK_LValue, 2447 &BasePath).take(); 2448 2449 InitializationKind InitKind 2450 = InitializationKind::CreateDirect(Constructor->getLocation(), 2451 SourceLocation(), SourceLocation()); 2452 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 2453 &CopyCtorArg, 1); 2454 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, 2455 MultiExprArg(&CopyCtorArg, 1)); 2456 break; 2457 } 2458 } 2459 2460 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 2461 if (BaseInit.isInvalid()) 2462 return true; 2463 2464 CXXBaseInit = 2465 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 2466 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 2467 SourceLocation()), 2468 BaseSpec->isVirtual(), 2469 SourceLocation(), 2470 BaseInit.takeAs<Expr>(), 2471 SourceLocation(), 2472 SourceLocation()); 2473 2474 return false; 2475} 2476 2477static bool RefersToRValueRef(Expr *MemRef) { 2478 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 2479 return Referenced->getType()->isRValueReferenceType(); 2480} 2481 2482static bool 2483BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 2484 ImplicitInitializerKind ImplicitInitKind, 2485 FieldDecl *Field, IndirectFieldDecl *Indirect, 2486 CXXCtorInitializer *&CXXMemberInit) { 2487 if (Field->isInvalidDecl()) 2488 return true; 2489 2490 SourceLocation Loc = Constructor->getLocation(); 2491 2492 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 2493 bool Moving = ImplicitInitKind == IIK_Move; 2494 ParmVarDecl *Param = Constructor->getParamDecl(0); 2495 QualType ParamType = Param->getType().getNonReferenceType(); 2496 2497 // Suppress copying zero-width bitfields. 2498 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0) 2499 return false; 2500 2501 Expr *MemberExprBase = 2502 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 2503 SourceLocation(), Param, 2504 Loc, ParamType, VK_LValue, 0); 2505 2506 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 2507 2508 if (Moving) { 2509 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 2510 } 2511 2512 // Build a reference to this field within the parameter. 2513 CXXScopeSpec SS; 2514 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 2515 Sema::LookupMemberName); 2516 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 2517 : cast<ValueDecl>(Field), AS_public); 2518 MemberLookup.resolveKind(); 2519 ExprResult CtorArg 2520 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 2521 ParamType, Loc, 2522 /*IsArrow=*/false, 2523 SS, 2524 /*TemplateKWLoc=*/SourceLocation(), 2525 /*FirstQualifierInScope=*/0, 2526 MemberLookup, 2527 /*TemplateArgs=*/0); 2528 if (CtorArg.isInvalid()) 2529 return true; 2530 2531 // C++11 [class.copy]p15: 2532 // - if a member m has rvalue reference type T&&, it is direct-initialized 2533 // with static_cast<T&&>(x.m); 2534 if (RefersToRValueRef(CtorArg.get())) { 2535 CtorArg = CastForMoving(SemaRef, CtorArg.take()); 2536 } 2537 2538 // When the field we are copying is an array, create index variables for 2539 // each dimension of the array. We use these index variables to subscript 2540 // the source array, and other clients (e.g., CodeGen) will perform the 2541 // necessary iteration with these index variables. 2542 SmallVector<VarDecl *, 4> IndexVariables; 2543 QualType BaseType = Field->getType(); 2544 QualType SizeType = SemaRef.Context.getSizeType(); 2545 bool InitializingArray = false; 2546 while (const ConstantArrayType *Array 2547 = SemaRef.Context.getAsConstantArrayType(BaseType)) { 2548 InitializingArray = true; 2549 // Create the iteration variable for this array index. 2550 IdentifierInfo *IterationVarName = 0; 2551 { 2552 SmallString<8> Str; 2553 llvm::raw_svector_ostream OS(Str); 2554 OS << "__i" << IndexVariables.size(); 2555 IterationVarName = &SemaRef.Context.Idents.get(OS.str()); 2556 } 2557 VarDecl *IterationVar 2558 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc, 2559 IterationVarName, SizeType, 2560 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc), 2561 SC_None, SC_None); 2562 IndexVariables.push_back(IterationVar); 2563 2564 // Create a reference to the iteration variable. 2565 ExprResult IterationVarRef 2566 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 2567 assert(!IterationVarRef.isInvalid() && 2568 "Reference to invented variable cannot fail!"); 2569 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take()); 2570 assert(!IterationVarRef.isInvalid() && 2571 "Conversion of invented variable cannot fail!"); 2572 2573 // Subscript the array with this iteration variable. 2574 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc, 2575 IterationVarRef.take(), 2576 Loc); 2577 if (CtorArg.isInvalid()) 2578 return true; 2579 2580 BaseType = Array->getElementType(); 2581 } 2582 2583 // The array subscript expression is an lvalue, which is wrong for moving. 2584 if (Moving && InitializingArray) 2585 CtorArg = CastForMoving(SemaRef, CtorArg.take()); 2586 2587 // Construct the entity that we will be initializing. For an array, this 2588 // will be first element in the array, which may require several levels 2589 // of array-subscript entities. 2590 SmallVector<InitializedEntity, 4> Entities; 2591 Entities.reserve(1 + IndexVariables.size()); 2592 if (Indirect) 2593 Entities.push_back(InitializedEntity::InitializeMember(Indirect)); 2594 else 2595 Entities.push_back(InitializedEntity::InitializeMember(Field)); 2596 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 2597 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context, 2598 0, 2599 Entities.back())); 2600 2601 // Direct-initialize to use the copy constructor. 2602 InitializationKind InitKind = 2603 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 2604 2605 Expr *CtorArgE = CtorArg.takeAs<Expr>(); 2606 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, 2607 &CtorArgE, 1); 2608 2609 ExprResult MemberInit 2610 = InitSeq.Perform(SemaRef, Entities.back(), InitKind, 2611 MultiExprArg(&CtorArgE, 1)); 2612 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 2613 if (MemberInit.isInvalid()) 2614 return true; 2615 2616 if (Indirect) { 2617 assert(IndexVariables.size() == 0 && 2618 "Indirect field improperly initialized"); 2619 CXXMemberInit 2620 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 2621 Loc, Loc, 2622 MemberInit.takeAs<Expr>(), 2623 Loc); 2624 } else 2625 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, 2626 Loc, MemberInit.takeAs<Expr>(), 2627 Loc, 2628 IndexVariables.data(), 2629 IndexVariables.size()); 2630 return false; 2631 } 2632 2633 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!"); 2634 2635 QualType FieldBaseElementType = 2636 SemaRef.Context.getBaseElementType(Field->getType()); 2637 2638 if (FieldBaseElementType->isRecordType()) { 2639 InitializedEntity InitEntity 2640 = Indirect? InitializedEntity::InitializeMember(Indirect) 2641 : InitializedEntity::InitializeMember(Field); 2642 InitializationKind InitKind = 2643 InitializationKind::CreateDefault(Loc); 2644 2645 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0); 2646 ExprResult MemberInit = 2647 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg()); 2648 2649 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 2650 if (MemberInit.isInvalid()) 2651 return true; 2652 2653 if (Indirect) 2654 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 2655 Indirect, Loc, 2656 Loc, 2657 MemberInit.get(), 2658 Loc); 2659 else 2660 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 2661 Field, Loc, Loc, 2662 MemberInit.get(), 2663 Loc); 2664 return false; 2665 } 2666 2667 if (!Field->getParent()->isUnion()) { 2668 if (FieldBaseElementType->isReferenceType()) { 2669 SemaRef.Diag(Constructor->getLocation(), 2670 diag::err_uninitialized_member_in_ctor) 2671 << (int)Constructor->isImplicit() 2672 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 2673 << 0 << Field->getDeclName(); 2674 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 2675 return true; 2676 } 2677 2678 if (FieldBaseElementType.isConstQualified()) { 2679 SemaRef.Diag(Constructor->getLocation(), 2680 diag::err_uninitialized_member_in_ctor) 2681 << (int)Constructor->isImplicit() 2682 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 2683 << 1 << Field->getDeclName(); 2684 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 2685 return true; 2686 } 2687 } 2688 2689 if (SemaRef.getLangOptions().ObjCAutoRefCount && 2690 FieldBaseElementType->isObjCRetainableType() && 2691 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None && 2692 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) { 2693 // Instant objects: 2694 // Default-initialize Objective-C pointers to NULL. 2695 CXXMemberInit 2696 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 2697 Loc, Loc, 2698 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 2699 Loc); 2700 return false; 2701 } 2702 2703 // Nothing to initialize. 2704 CXXMemberInit = 0; 2705 return false; 2706} 2707 2708namespace { 2709struct BaseAndFieldInfo { 2710 Sema &S; 2711 CXXConstructorDecl *Ctor; 2712 bool AnyErrorsInInits; 2713 ImplicitInitializerKind IIK; 2714 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 2715 SmallVector<CXXCtorInitializer*, 8> AllToInit; 2716 2717 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 2718 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 2719 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 2720 if (Generated && Ctor->isCopyConstructor()) 2721 IIK = IIK_Copy; 2722 else if (Generated && Ctor->isMoveConstructor()) 2723 IIK = IIK_Move; 2724 else 2725 IIK = IIK_Default; 2726 } 2727 2728 bool isImplicitCopyOrMove() const { 2729 switch (IIK) { 2730 case IIK_Copy: 2731 case IIK_Move: 2732 return true; 2733 2734 case IIK_Default: 2735 return false; 2736 } 2737 2738 llvm_unreachable("Invalid ImplicitInitializerKind!"); 2739 } 2740}; 2741} 2742 2743/// \brief Determine whether the given indirect field declaration is somewhere 2744/// within an anonymous union. 2745static bool isWithinAnonymousUnion(IndirectFieldDecl *F) { 2746 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(), 2747 CEnd = F->chain_end(); 2748 C != CEnd; ++C) 2749 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext())) 2750 if (Record->isUnion()) 2751 return true; 2752 2753 return false; 2754} 2755 2756/// \brief Determine whether the given type is an incomplete or zero-lenfgth 2757/// array type. 2758static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 2759 if (T->isIncompleteArrayType()) 2760 return true; 2761 2762 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 2763 if (!ArrayT->getSize()) 2764 return true; 2765 2766 T = ArrayT->getElementType(); 2767 } 2768 2769 return false; 2770} 2771 2772static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 2773 FieldDecl *Field, 2774 IndirectFieldDecl *Indirect = 0) { 2775 2776 // Overwhelmingly common case: we have a direct initializer for this field. 2777 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) { 2778 Info.AllToInit.push_back(Init); 2779 return false; 2780 } 2781 2782 // C++0x [class.base.init]p8: if the entity is a non-static data member that 2783 // has a brace-or-equal-initializer, the entity is initialized as specified 2784 // in [dcl.init]. 2785 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 2786 CXXCtorInitializer *Init; 2787 if (Indirect) 2788 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 2789 SourceLocation(), 2790 SourceLocation(), 0, 2791 SourceLocation()); 2792 else 2793 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 2794 SourceLocation(), 2795 SourceLocation(), 0, 2796 SourceLocation()); 2797 Info.AllToInit.push_back(Init); 2798 return false; 2799 } 2800 2801 // Don't build an implicit initializer for union members if none was 2802 // explicitly specified. 2803 if (Field->getParent()->isUnion() || 2804 (Indirect && isWithinAnonymousUnion(Indirect))) 2805 return false; 2806 2807 // Don't initialize incomplete or zero-length arrays. 2808 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 2809 return false; 2810 2811 // Don't try to build an implicit initializer if there were semantic 2812 // errors in any of the initializers (and therefore we might be 2813 // missing some that the user actually wrote). 2814 if (Info.AnyErrorsInInits || Field->isInvalidDecl()) 2815 return false; 2816 2817 CXXCtorInitializer *Init = 0; 2818 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 2819 Indirect, Init)) 2820 return true; 2821 2822 if (Init) 2823 Info.AllToInit.push_back(Init); 2824 2825 return false; 2826} 2827 2828bool 2829Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 2830 CXXCtorInitializer *Initializer) { 2831 assert(Initializer->isDelegatingInitializer()); 2832 Constructor->setNumCtorInitializers(1); 2833 CXXCtorInitializer **initializer = 2834 new (Context) CXXCtorInitializer*[1]; 2835 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 2836 Constructor->setCtorInitializers(initializer); 2837 2838 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 2839 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 2840 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 2841 } 2842 2843 DelegatingCtorDecls.push_back(Constructor); 2844 2845 return false; 2846} 2847 2848bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, 2849 CXXCtorInitializer **Initializers, 2850 unsigned NumInitializers, 2851 bool AnyErrors) { 2852 if (Constructor->isDependentContext()) { 2853 // Just store the initializers as written, they will be checked during 2854 // instantiation. 2855 if (NumInitializers > 0) { 2856 Constructor->setNumCtorInitializers(NumInitializers); 2857 CXXCtorInitializer **baseOrMemberInitializers = 2858 new (Context) CXXCtorInitializer*[NumInitializers]; 2859 memcpy(baseOrMemberInitializers, Initializers, 2860 NumInitializers * sizeof(CXXCtorInitializer*)); 2861 Constructor->setCtorInitializers(baseOrMemberInitializers); 2862 } 2863 2864 return false; 2865 } 2866 2867 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 2868 2869 // We need to build the initializer AST according to order of construction 2870 // and not what user specified in the Initializers list. 2871 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 2872 if (!ClassDecl) 2873 return true; 2874 2875 bool HadError = false; 2876 2877 for (unsigned i = 0; i < NumInitializers; i++) { 2878 CXXCtorInitializer *Member = Initializers[i]; 2879 2880 if (Member->isBaseInitializer()) 2881 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 2882 else 2883 Info.AllBaseFields[Member->getAnyMember()] = Member; 2884 } 2885 2886 // Keep track of the direct virtual bases. 2887 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 2888 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(), 2889 E = ClassDecl->bases_end(); I != E; ++I) { 2890 if (I->isVirtual()) 2891 DirectVBases.insert(I); 2892 } 2893 2894 // Push virtual bases before others. 2895 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 2896 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 2897 2898 if (CXXCtorInitializer *Value 2899 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) { 2900 Info.AllToInit.push_back(Value); 2901 } else if (!AnyErrors) { 2902 bool IsInheritedVirtualBase = !DirectVBases.count(VBase); 2903 CXXCtorInitializer *CXXBaseInit; 2904 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 2905 VBase, IsInheritedVirtualBase, 2906 CXXBaseInit)) { 2907 HadError = true; 2908 continue; 2909 } 2910 2911 Info.AllToInit.push_back(CXXBaseInit); 2912 } 2913 } 2914 2915 // Non-virtual bases. 2916 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 2917 E = ClassDecl->bases_end(); Base != E; ++Base) { 2918 // Virtuals are in the virtual base list and already constructed. 2919 if (Base->isVirtual()) 2920 continue; 2921 2922 if (CXXCtorInitializer *Value 2923 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) { 2924 Info.AllToInit.push_back(Value); 2925 } else if (!AnyErrors) { 2926 CXXCtorInitializer *CXXBaseInit; 2927 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 2928 Base, /*IsInheritedVirtualBase=*/false, 2929 CXXBaseInit)) { 2930 HadError = true; 2931 continue; 2932 } 2933 2934 Info.AllToInit.push_back(CXXBaseInit); 2935 } 2936 } 2937 2938 // Fields. 2939 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(), 2940 MemEnd = ClassDecl->decls_end(); 2941 Mem != MemEnd; ++Mem) { 2942 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) { 2943 // C++ [class.bit]p2: 2944 // A declaration for a bit-field that omits the identifier declares an 2945 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 2946 // initialized. 2947 if (F->isUnnamedBitfield()) 2948 continue; 2949 2950 // If we're not generating the implicit copy/move constructor, then we'll 2951 // handle anonymous struct/union fields based on their individual 2952 // indirect fields. 2953 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default) 2954 continue; 2955 2956 if (CollectFieldInitializer(*this, Info, F)) 2957 HadError = true; 2958 continue; 2959 } 2960 2961 // Beyond this point, we only consider default initialization. 2962 if (Info.IIK != IIK_Default) 2963 continue; 2964 2965 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) { 2966 if (F->getType()->isIncompleteArrayType()) { 2967 assert(ClassDecl->hasFlexibleArrayMember() && 2968 "Incomplete array type is not valid"); 2969 continue; 2970 } 2971 2972 // Initialize each field of an anonymous struct individually. 2973 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 2974 HadError = true; 2975 2976 continue; 2977 } 2978 } 2979 2980 NumInitializers = Info.AllToInit.size(); 2981 if (NumInitializers > 0) { 2982 Constructor->setNumCtorInitializers(NumInitializers); 2983 CXXCtorInitializer **baseOrMemberInitializers = 2984 new (Context) CXXCtorInitializer*[NumInitializers]; 2985 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 2986 NumInitializers * sizeof(CXXCtorInitializer*)); 2987 Constructor->setCtorInitializers(baseOrMemberInitializers); 2988 2989 // Constructors implicitly reference the base and member 2990 // destructors. 2991 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 2992 Constructor->getParent()); 2993 } 2994 2995 return HadError; 2996} 2997 2998static void *GetKeyForTopLevelField(FieldDecl *Field) { 2999 // For anonymous unions, use the class declaration as the key. 3000 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 3001 if (RT->getDecl()->isAnonymousStructOrUnion()) 3002 return static_cast<void *>(RT->getDecl()); 3003 } 3004 return static_cast<void *>(Field); 3005} 3006 3007static void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 3008 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr()); 3009} 3010 3011static void *GetKeyForMember(ASTContext &Context, 3012 CXXCtorInitializer *Member) { 3013 if (!Member->isAnyMemberInitializer()) 3014 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 3015 3016 // For fields injected into the class via declaration of an anonymous union, 3017 // use its anonymous union class declaration as the unique key. 3018 FieldDecl *Field = Member->getAnyMember(); 3019 3020 // If the field is a member of an anonymous struct or union, our key 3021 // is the anonymous record decl that's a direct child of the class. 3022 RecordDecl *RD = Field->getParent(); 3023 if (RD->isAnonymousStructOrUnion()) { 3024 while (true) { 3025 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext()); 3026 if (Parent->isAnonymousStructOrUnion()) 3027 RD = Parent; 3028 else 3029 break; 3030 } 3031 3032 return static_cast<void *>(RD); 3033 } 3034 3035 return static_cast<void *>(Field); 3036} 3037 3038static void 3039DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef, 3040 const CXXConstructorDecl *Constructor, 3041 CXXCtorInitializer **Inits, 3042 unsigned NumInits) { 3043 if (Constructor->getDeclContext()->isDependentContext()) 3044 return; 3045 3046 // Don't check initializers order unless the warning is enabled at the 3047 // location of at least one initializer. 3048 bool ShouldCheckOrder = false; 3049 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) { 3050 CXXCtorInitializer *Init = Inits[InitIndex]; 3051 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order, 3052 Init->getSourceLocation()) 3053 != DiagnosticsEngine::Ignored) { 3054 ShouldCheckOrder = true; 3055 break; 3056 } 3057 } 3058 if (!ShouldCheckOrder) 3059 return; 3060 3061 // Build the list of bases and members in the order that they'll 3062 // actually be initialized. The explicit initializers should be in 3063 // this same order but may be missing things. 3064 SmallVector<const void*, 32> IdealInitKeys; 3065 3066 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 3067 3068 // 1. Virtual bases. 3069 for (CXXRecordDecl::base_class_const_iterator VBase = 3070 ClassDecl->vbases_begin(), 3071 E = ClassDecl->vbases_end(); VBase != E; ++VBase) 3072 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType())); 3073 3074 // 2. Non-virtual bases. 3075 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(), 3076 E = ClassDecl->bases_end(); Base != E; ++Base) { 3077 if (Base->isVirtual()) 3078 continue; 3079 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType())); 3080 } 3081 3082 // 3. Direct fields. 3083 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 3084 E = ClassDecl->field_end(); Field != E; ++Field) { 3085 if (Field->isUnnamedBitfield()) 3086 continue; 3087 3088 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field)); 3089 } 3090 3091 unsigned NumIdealInits = IdealInitKeys.size(); 3092 unsigned IdealIndex = 0; 3093 3094 CXXCtorInitializer *PrevInit = 0; 3095 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) { 3096 CXXCtorInitializer *Init = Inits[InitIndex]; 3097 void *InitKey = GetKeyForMember(SemaRef.Context, Init); 3098 3099 // Scan forward to try to find this initializer in the idealized 3100 // initializers list. 3101 for (; IdealIndex != NumIdealInits; ++IdealIndex) 3102 if (InitKey == IdealInitKeys[IdealIndex]) 3103 break; 3104 3105 // If we didn't find this initializer, it must be because we 3106 // scanned past it on a previous iteration. That can only 3107 // happen if we're out of order; emit a warning. 3108 if (IdealIndex == NumIdealInits && PrevInit) { 3109 Sema::SemaDiagnosticBuilder D = 3110 SemaRef.Diag(PrevInit->getSourceLocation(), 3111 diag::warn_initializer_out_of_order); 3112 3113 if (PrevInit->isAnyMemberInitializer()) 3114 D << 0 << PrevInit->getAnyMember()->getDeclName(); 3115 else 3116 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 3117 3118 if (Init->isAnyMemberInitializer()) 3119 D << 0 << Init->getAnyMember()->getDeclName(); 3120 else 3121 D << 1 << Init->getTypeSourceInfo()->getType(); 3122 3123 // Move back to the initializer's location in the ideal list. 3124 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 3125 if (InitKey == IdealInitKeys[IdealIndex]) 3126 break; 3127 3128 assert(IdealIndex != NumIdealInits && 3129 "initializer not found in initializer list"); 3130 } 3131 3132 PrevInit = Init; 3133 } 3134} 3135 3136namespace { 3137bool CheckRedundantInit(Sema &S, 3138 CXXCtorInitializer *Init, 3139 CXXCtorInitializer *&PrevInit) { 3140 if (!PrevInit) { 3141 PrevInit = Init; 3142 return false; 3143 } 3144 3145 if (FieldDecl *Field = Init->getMember()) 3146 S.Diag(Init->getSourceLocation(), 3147 diag::err_multiple_mem_initialization) 3148 << Field->getDeclName() 3149 << Init->getSourceRange(); 3150 else { 3151 const Type *BaseClass = Init->getBaseClass(); 3152 assert(BaseClass && "neither field nor base"); 3153 S.Diag(Init->getSourceLocation(), 3154 diag::err_multiple_base_initialization) 3155 << QualType(BaseClass, 0) 3156 << Init->getSourceRange(); 3157 } 3158 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 3159 << 0 << PrevInit->getSourceRange(); 3160 3161 return true; 3162} 3163 3164typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 3165typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 3166 3167bool CheckRedundantUnionInit(Sema &S, 3168 CXXCtorInitializer *Init, 3169 RedundantUnionMap &Unions) { 3170 FieldDecl *Field = Init->getAnyMember(); 3171 RecordDecl *Parent = Field->getParent(); 3172 NamedDecl *Child = Field; 3173 3174 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 3175 if (Parent->isUnion()) { 3176 UnionEntry &En = Unions[Parent]; 3177 if (En.first && En.first != Child) { 3178 S.Diag(Init->getSourceLocation(), 3179 diag::err_multiple_mem_union_initialization) 3180 << Field->getDeclName() 3181 << Init->getSourceRange(); 3182 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 3183 << 0 << En.second->getSourceRange(); 3184 return true; 3185 } 3186 if (!En.first) { 3187 En.first = Child; 3188 En.second = Init; 3189 } 3190 if (!Parent->isAnonymousStructOrUnion()) 3191 return false; 3192 } 3193 3194 Child = Parent; 3195 Parent = cast<RecordDecl>(Parent->getDeclContext()); 3196 } 3197 3198 return false; 3199} 3200} 3201 3202/// ActOnMemInitializers - Handle the member initializers for a constructor. 3203void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 3204 SourceLocation ColonLoc, 3205 CXXCtorInitializer **meminits, 3206 unsigned NumMemInits, 3207 bool AnyErrors) { 3208 if (!ConstructorDecl) 3209 return; 3210 3211 AdjustDeclIfTemplate(ConstructorDecl); 3212 3213 CXXConstructorDecl *Constructor 3214 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 3215 3216 if (!Constructor) { 3217 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 3218 return; 3219 } 3220 3221 CXXCtorInitializer **MemInits = 3222 reinterpret_cast<CXXCtorInitializer **>(meminits); 3223 3224 // Mapping for the duplicate initializers check. 3225 // For member initializers, this is keyed with a FieldDecl*. 3226 // For base initializers, this is keyed with a Type*. 3227 llvm::DenseMap<void*, CXXCtorInitializer *> Members; 3228 3229 // Mapping for the inconsistent anonymous-union initializers check. 3230 RedundantUnionMap MemberUnions; 3231 3232 bool HadError = false; 3233 for (unsigned i = 0; i < NumMemInits; i++) { 3234 CXXCtorInitializer *Init = MemInits[i]; 3235 3236 // Set the source order index. 3237 Init->setSourceOrder(i); 3238 3239 if (Init->isAnyMemberInitializer()) { 3240 FieldDecl *Field = Init->getAnyMember(); 3241 if (CheckRedundantInit(*this, Init, Members[Field]) || 3242 CheckRedundantUnionInit(*this, Init, MemberUnions)) 3243 HadError = true; 3244 } else if (Init->isBaseInitializer()) { 3245 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0)); 3246 if (CheckRedundantInit(*this, Init, Members[Key])) 3247 HadError = true; 3248 } else { 3249 assert(Init->isDelegatingInitializer()); 3250 // This must be the only initializer 3251 if (i != 0 || NumMemInits > 1) { 3252 Diag(MemInits[0]->getSourceLocation(), 3253 diag::err_delegating_initializer_alone) 3254 << MemInits[0]->getSourceRange(); 3255 HadError = true; 3256 // We will treat this as being the only initializer. 3257 } 3258 SetDelegatingInitializer(Constructor, MemInits[i]); 3259 // Return immediately as the initializer is set. 3260 return; 3261 } 3262 } 3263 3264 if (HadError) 3265 return; 3266 3267 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits); 3268 3269 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors); 3270} 3271 3272void 3273Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 3274 CXXRecordDecl *ClassDecl) { 3275 // Ignore dependent contexts. Also ignore unions, since their members never 3276 // have destructors implicitly called. 3277 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 3278 return; 3279 3280 // FIXME: all the access-control diagnostics are positioned on the 3281 // field/base declaration. That's probably good; that said, the 3282 // user might reasonably want to know why the destructor is being 3283 // emitted, and we currently don't say. 3284 3285 // Non-static data members. 3286 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(), 3287 E = ClassDecl->field_end(); I != E; ++I) { 3288 FieldDecl *Field = *I; 3289 if (Field->isInvalidDecl()) 3290 continue; 3291 3292 // Don't destroy incomplete or zero-length arrays. 3293 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 3294 continue; 3295 3296 QualType FieldType = Context.getBaseElementType(Field->getType()); 3297 3298 const RecordType* RT = FieldType->getAs<RecordType>(); 3299 if (!RT) 3300 continue; 3301 3302 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3303 if (FieldClassDecl->isInvalidDecl()) 3304 continue; 3305 if (FieldClassDecl->hasTrivialDestructor()) 3306 continue; 3307 3308 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 3309 assert(Dtor && "No dtor found for FieldClassDecl!"); 3310 CheckDestructorAccess(Field->getLocation(), Dtor, 3311 PDiag(diag::err_access_dtor_field) 3312 << Field->getDeclName() 3313 << FieldType); 3314 3315 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 3316 } 3317 3318 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 3319 3320 // Bases. 3321 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 3322 E = ClassDecl->bases_end(); Base != E; ++Base) { 3323 // Bases are always records in a well-formed non-dependent class. 3324 const RecordType *RT = Base->getType()->getAs<RecordType>(); 3325 3326 // Remember direct virtual bases. 3327 if (Base->isVirtual()) 3328 DirectVirtualBases.insert(RT); 3329 3330 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3331 // If our base class is invalid, we probably can't get its dtor anyway. 3332 if (BaseClassDecl->isInvalidDecl()) 3333 continue; 3334 // Ignore trivial destructors. 3335 if (BaseClassDecl->hasTrivialDestructor()) 3336 continue; 3337 3338 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 3339 assert(Dtor && "No dtor found for BaseClassDecl!"); 3340 3341 // FIXME: caret should be on the start of the class name 3342 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor, 3343 PDiag(diag::err_access_dtor_base) 3344 << Base->getType() 3345 << Base->getSourceRange()); 3346 3347 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 3348 } 3349 3350 // Virtual bases. 3351 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 3352 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 3353 3354 // Bases are always records in a well-formed non-dependent class. 3355 const RecordType *RT = VBase->getType()->getAs<RecordType>(); 3356 3357 // Ignore direct virtual bases. 3358 if (DirectVirtualBases.count(RT)) 3359 continue; 3360 3361 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3362 // If our base class is invalid, we probably can't get its dtor anyway. 3363 if (BaseClassDecl->isInvalidDecl()) 3364 continue; 3365 // Ignore trivial destructors. 3366 if (BaseClassDecl->hasTrivialDestructor()) 3367 continue; 3368 3369 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 3370 assert(Dtor && "No dtor found for BaseClassDecl!"); 3371 CheckDestructorAccess(ClassDecl->getLocation(), Dtor, 3372 PDiag(diag::err_access_dtor_vbase) 3373 << VBase->getType()); 3374 3375 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 3376 } 3377} 3378 3379void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 3380 if (!CDtorDecl) 3381 return; 3382 3383 if (CXXConstructorDecl *Constructor 3384 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) 3385 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false); 3386} 3387 3388bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 3389 unsigned DiagID, AbstractDiagSelID SelID) { 3390 if (SelID == -1) 3391 return RequireNonAbstractType(Loc, T, PDiag(DiagID)); 3392 else 3393 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID); 3394} 3395 3396bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 3397 const PartialDiagnostic &PD) { 3398 if (!getLangOptions().CPlusPlus) 3399 return false; 3400 3401 if (const ArrayType *AT = Context.getAsArrayType(T)) 3402 return RequireNonAbstractType(Loc, AT->getElementType(), PD); 3403 3404 if (const PointerType *PT = T->getAs<PointerType>()) { 3405 // Find the innermost pointer type. 3406 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 3407 PT = T; 3408 3409 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 3410 return RequireNonAbstractType(Loc, AT->getElementType(), PD); 3411 } 3412 3413 const RecordType *RT = T->getAs<RecordType>(); 3414 if (!RT) 3415 return false; 3416 3417 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 3418 3419 // We can't answer whether something is abstract until it has a 3420 // definition. If it's currently being defined, we'll walk back 3421 // over all the declarations when we have a full definition. 3422 const CXXRecordDecl *Def = RD->getDefinition(); 3423 if (!Def || Def->isBeingDefined()) 3424 return false; 3425 3426 if (!RD->isAbstract()) 3427 return false; 3428 3429 Diag(Loc, PD) << RD->getDeclName(); 3430 DiagnoseAbstractType(RD); 3431 3432 return true; 3433} 3434 3435void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 3436 // Check if we've already emitted the list of pure virtual functions 3437 // for this class. 3438 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 3439 return; 3440 3441 CXXFinalOverriderMap FinalOverriders; 3442 RD->getFinalOverriders(FinalOverriders); 3443 3444 // Keep a set of seen pure methods so we won't diagnose the same method 3445 // more than once. 3446 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 3447 3448 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 3449 MEnd = FinalOverriders.end(); 3450 M != MEnd; 3451 ++M) { 3452 for (OverridingMethods::iterator SO = M->second.begin(), 3453 SOEnd = M->second.end(); 3454 SO != SOEnd; ++SO) { 3455 // C++ [class.abstract]p4: 3456 // A class is abstract if it contains or inherits at least one 3457 // pure virtual function for which the final overrider is pure 3458 // virtual. 3459 3460 // 3461 if (SO->second.size() != 1) 3462 continue; 3463 3464 if (!SO->second.front().Method->isPure()) 3465 continue; 3466 3467 if (!SeenPureMethods.insert(SO->second.front().Method)) 3468 continue; 3469 3470 Diag(SO->second.front().Method->getLocation(), 3471 diag::note_pure_virtual_function) 3472 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 3473 } 3474 } 3475 3476 if (!PureVirtualClassDiagSet) 3477 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 3478 PureVirtualClassDiagSet->insert(RD); 3479} 3480 3481namespace { 3482struct AbstractUsageInfo { 3483 Sema &S; 3484 CXXRecordDecl *Record; 3485 CanQualType AbstractType; 3486 bool Invalid; 3487 3488 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 3489 : S(S), Record(Record), 3490 AbstractType(S.Context.getCanonicalType( 3491 S.Context.getTypeDeclType(Record))), 3492 Invalid(false) {} 3493 3494 void DiagnoseAbstractType() { 3495 if (Invalid) return; 3496 S.DiagnoseAbstractType(Record); 3497 Invalid = true; 3498 } 3499 3500 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 3501}; 3502 3503struct CheckAbstractUsage { 3504 AbstractUsageInfo &Info; 3505 const NamedDecl *Ctx; 3506 3507 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 3508 : Info(Info), Ctx(Ctx) {} 3509 3510 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 3511 switch (TL.getTypeLocClass()) { 3512#define ABSTRACT_TYPELOC(CLASS, PARENT) 3513#define TYPELOC(CLASS, PARENT) \ 3514 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break; 3515#include "clang/AST/TypeLocNodes.def" 3516 } 3517 } 3518 3519 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 3520 Visit(TL.getResultLoc(), Sema::AbstractReturnType); 3521 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 3522 if (!TL.getArg(I)) 3523 continue; 3524 3525 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo(); 3526 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 3527 } 3528 } 3529 3530 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 3531 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 3532 } 3533 3534 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 3535 // Visit the type parameters from a permissive context. 3536 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 3537 TemplateArgumentLoc TAL = TL.getArgLoc(I); 3538 if (TAL.getArgument().getKind() == TemplateArgument::Type) 3539 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 3540 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 3541 // TODO: other template argument types? 3542 } 3543 } 3544 3545 // Visit pointee types from a permissive context. 3546#define CheckPolymorphic(Type) \ 3547 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 3548 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 3549 } 3550 CheckPolymorphic(PointerTypeLoc) 3551 CheckPolymorphic(ReferenceTypeLoc) 3552 CheckPolymorphic(MemberPointerTypeLoc) 3553 CheckPolymorphic(BlockPointerTypeLoc) 3554 CheckPolymorphic(AtomicTypeLoc) 3555 3556 /// Handle all the types we haven't given a more specific 3557 /// implementation for above. 3558 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 3559 // Every other kind of type that we haven't called out already 3560 // that has an inner type is either (1) sugar or (2) contains that 3561 // inner type in some way as a subobject. 3562 if (TypeLoc Next = TL.getNextTypeLoc()) 3563 return Visit(Next, Sel); 3564 3565 // If there's no inner type and we're in a permissive context, 3566 // don't diagnose. 3567 if (Sel == Sema::AbstractNone) return; 3568 3569 // Check whether the type matches the abstract type. 3570 QualType T = TL.getType(); 3571 if (T->isArrayType()) { 3572 Sel = Sema::AbstractArrayType; 3573 T = Info.S.Context.getBaseElementType(T); 3574 } 3575 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 3576 if (CT != Info.AbstractType) return; 3577 3578 // It matched; do some magic. 3579 if (Sel == Sema::AbstractArrayType) { 3580 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 3581 << T << TL.getSourceRange(); 3582 } else { 3583 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 3584 << Sel << T << TL.getSourceRange(); 3585 } 3586 Info.DiagnoseAbstractType(); 3587 } 3588}; 3589 3590void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 3591 Sema::AbstractDiagSelID Sel) { 3592 CheckAbstractUsage(*this, D).Visit(TL, Sel); 3593} 3594 3595} 3596 3597/// Check for invalid uses of an abstract type in a method declaration. 3598static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 3599 CXXMethodDecl *MD) { 3600 // No need to do the check on definitions, which require that 3601 // the return/param types be complete. 3602 if (MD->doesThisDeclarationHaveABody()) 3603 return; 3604 3605 // For safety's sake, just ignore it if we don't have type source 3606 // information. This should never happen for non-implicit methods, 3607 // but... 3608 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 3609 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 3610} 3611 3612/// Check for invalid uses of an abstract type within a class definition. 3613static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 3614 CXXRecordDecl *RD) { 3615 for (CXXRecordDecl::decl_iterator 3616 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) { 3617 Decl *D = *I; 3618 if (D->isImplicit()) continue; 3619 3620 // Methods and method templates. 3621 if (isa<CXXMethodDecl>(D)) { 3622 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 3623 } else if (isa<FunctionTemplateDecl>(D)) { 3624 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 3625 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 3626 3627 // Fields and static variables. 3628 } else if (isa<FieldDecl>(D)) { 3629 FieldDecl *FD = cast<FieldDecl>(D); 3630 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 3631 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 3632 } else if (isa<VarDecl>(D)) { 3633 VarDecl *VD = cast<VarDecl>(D); 3634 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 3635 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 3636 3637 // Nested classes and class templates. 3638 } else if (isa<CXXRecordDecl>(D)) { 3639 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 3640 } else if (isa<ClassTemplateDecl>(D)) { 3641 CheckAbstractClassUsage(Info, 3642 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 3643 } 3644 } 3645} 3646 3647/// \brief Perform semantic checks on a class definition that has been 3648/// completing, introducing implicitly-declared members, checking for 3649/// abstract types, etc. 3650void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 3651 if (!Record) 3652 return; 3653 3654 if (Record->isAbstract() && !Record->isInvalidDecl()) { 3655 AbstractUsageInfo Info(*this, Record); 3656 CheckAbstractClassUsage(Info, Record); 3657 } 3658 3659 // If this is not an aggregate type and has no user-declared constructor, 3660 // complain about any non-static data members of reference or const scalar 3661 // type, since they will never get initializers. 3662 if (!Record->isInvalidDecl() && !Record->isDependentType() && 3663 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 3664 !Record->isLambda()) { 3665 bool Complained = false; 3666 for (RecordDecl::field_iterator F = Record->field_begin(), 3667 FEnd = Record->field_end(); 3668 F != FEnd; ++F) { 3669 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 3670 continue; 3671 3672 if (F->getType()->isReferenceType() || 3673 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 3674 if (!Complained) { 3675 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 3676 << Record->getTagKind() << Record; 3677 Complained = true; 3678 } 3679 3680 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 3681 << F->getType()->isReferenceType() 3682 << F->getDeclName(); 3683 } 3684 } 3685 } 3686 3687 if (Record->isDynamicClass() && !Record->isDependentType()) 3688 DynamicClasses.push_back(Record); 3689 3690 if (Record->getIdentifier()) { 3691 // C++ [class.mem]p13: 3692 // If T is the name of a class, then each of the following shall have a 3693 // name different from T: 3694 // - every member of every anonymous union that is a member of class T. 3695 // 3696 // C++ [class.mem]p14: 3697 // In addition, if class T has a user-declared constructor (12.1), every 3698 // non-static data member of class T shall have a name different from T. 3699 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 3700 R.first != R.second; ++R.first) { 3701 NamedDecl *D = *R.first; 3702 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 3703 isa<IndirectFieldDecl>(D)) { 3704 Diag(D->getLocation(), diag::err_member_name_of_class) 3705 << D->getDeclName(); 3706 break; 3707 } 3708 } 3709 } 3710 3711 // Warn if the class has virtual methods but non-virtual public destructor. 3712 if (Record->isPolymorphic() && !Record->isDependentType()) { 3713 CXXDestructorDecl *dtor = Record->getDestructor(); 3714 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) 3715 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 3716 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 3717 } 3718 3719 // See if a method overloads virtual methods in a base 3720 /// class without overriding any. 3721 if (!Record->isDependentType()) { 3722 for (CXXRecordDecl::method_iterator M = Record->method_begin(), 3723 MEnd = Record->method_end(); 3724 M != MEnd; ++M) { 3725 if (!(*M)->isStatic()) 3726 DiagnoseHiddenVirtualMethods(Record, *M); 3727 } 3728 } 3729 3730 // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member 3731 // function that is not a constructor declares that member function to be 3732 // const. [...] The class of which that function is a member shall be 3733 // a literal type. 3734 // 3735 // If the class has virtual bases, any constexpr members will already have 3736 // been diagnosed by the checks performed on the member declaration, so 3737 // suppress this (less useful) diagnostic. 3738 if (LangOpts.CPlusPlus0x && !Record->isDependentType() && 3739 !Record->isLiteral() && !Record->getNumVBases()) { 3740 for (CXXRecordDecl::method_iterator M = Record->method_begin(), 3741 MEnd = Record->method_end(); 3742 M != MEnd; ++M) { 3743 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) { 3744 switch (Record->getTemplateSpecializationKind()) { 3745 case TSK_ImplicitInstantiation: 3746 case TSK_ExplicitInstantiationDeclaration: 3747 case TSK_ExplicitInstantiationDefinition: 3748 // If a template instantiates to a non-literal type, but its members 3749 // instantiate to constexpr functions, the template is technically 3750 // ill-formed, but we allow it for sanity. 3751 continue; 3752 3753 case TSK_Undeclared: 3754 case TSK_ExplicitSpecialization: 3755 RequireLiteralType((*M)->getLocation(), Context.getRecordType(Record), 3756 PDiag(diag::err_constexpr_method_non_literal)); 3757 break; 3758 } 3759 3760 // Only produce one error per class. 3761 break; 3762 } 3763 } 3764 } 3765 3766 // Declare inherited constructors. We do this eagerly here because: 3767 // - The standard requires an eager diagnostic for conflicting inherited 3768 // constructors from different classes. 3769 // - The lazy declaration of the other implicit constructors is so as to not 3770 // waste space and performance on classes that are not meant to be 3771 // instantiated (e.g. meta-functions). This doesn't apply to classes that 3772 // have inherited constructors. 3773 DeclareInheritedConstructors(Record); 3774 3775 if (!Record->isDependentType()) 3776 CheckExplicitlyDefaultedMethods(Record); 3777} 3778 3779void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) { 3780 for (CXXRecordDecl::method_iterator MI = Record->method_begin(), 3781 ME = Record->method_end(); 3782 MI != ME; ++MI) { 3783 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) { 3784 switch (getSpecialMember(*MI)) { 3785 case CXXDefaultConstructor: 3786 CheckExplicitlyDefaultedDefaultConstructor( 3787 cast<CXXConstructorDecl>(*MI)); 3788 break; 3789 3790 case CXXDestructor: 3791 CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI)); 3792 break; 3793 3794 case CXXCopyConstructor: 3795 CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI)); 3796 break; 3797 3798 case CXXCopyAssignment: 3799 CheckExplicitlyDefaultedCopyAssignment(*MI); 3800 break; 3801 3802 case CXXMoveConstructor: 3803 CheckExplicitlyDefaultedMoveConstructor(cast<CXXConstructorDecl>(*MI)); 3804 break; 3805 3806 case CXXMoveAssignment: 3807 CheckExplicitlyDefaultedMoveAssignment(*MI); 3808 break; 3809 3810 case CXXInvalid: 3811 llvm_unreachable("non-special member explicitly defaulted!"); 3812 } 3813 } 3814 } 3815 3816} 3817 3818void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) { 3819 assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor()); 3820 3821 // Whether this was the first-declared instance of the constructor. 3822 // This affects whether we implicitly add an exception spec (and, eventually, 3823 // constexpr). It is also ill-formed to explicitly default a constructor such 3824 // that it would be deleted. (C++0x [decl.fct.def.default]) 3825 bool First = CD == CD->getCanonicalDecl(); 3826 3827 bool HadError = false; 3828 if (CD->getNumParams() != 0) { 3829 Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params) 3830 << CD->getSourceRange(); 3831 HadError = true; 3832 } 3833 3834 ImplicitExceptionSpecification Spec 3835 = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent()); 3836 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 3837 if (EPI.ExceptionSpecType == EST_Delayed) { 3838 // Exception specification depends on some deferred part of the class. We'll 3839 // try again when the class's definition has been fully processed. 3840 return; 3841 } 3842 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(), 3843 *ExceptionType = Context.getFunctionType( 3844 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>(); 3845 3846 // C++11 [dcl.fct.def.default]p2: 3847 // An explicitly-defaulted function may be declared constexpr only if it 3848 // would have been implicitly declared as constexpr, 3849 // Do not apply this rule to templates, since core issue 1358 makes such 3850 // functions always instantiate to constexpr functions. 3851 if (CD->isConstexpr() && 3852 CD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 3853 if (!CD->getParent()->defaultedDefaultConstructorIsConstexpr()) { 3854 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr) 3855 << CXXDefaultConstructor; 3856 HadError = true; 3857 } 3858 } 3859 // and may have an explicit exception-specification only if it is compatible 3860 // with the exception-specification on the implicit declaration. 3861 if (CtorType->hasExceptionSpec()) { 3862 if (CheckEquivalentExceptionSpec( 3863 PDiag(diag::err_incorrect_defaulted_exception_spec) 3864 << CXXDefaultConstructor, 3865 PDiag(), 3866 ExceptionType, SourceLocation(), 3867 CtorType, CD->getLocation())) { 3868 HadError = true; 3869 } 3870 } 3871 3872 // If a function is explicitly defaulted on its first declaration, 3873 if (First) { 3874 // -- it is implicitly considered to be constexpr if the implicit 3875 // definition would be, 3876 CD->setConstexpr(CD->getParent()->defaultedDefaultConstructorIsConstexpr()); 3877 3878 // -- it is implicitly considered to have the same 3879 // exception-specification as if it had been implicitly declared 3880 // 3881 // FIXME: a compatible, but different, explicit exception specification 3882 // will be silently overridden. We should issue a warning if this happens. 3883 EPI.ExtInfo = CtorType->getExtInfo(); 3884 } 3885 3886 if (HadError) { 3887 CD->setInvalidDecl(); 3888 return; 3889 } 3890 3891 if (ShouldDeleteSpecialMember(CD, CXXDefaultConstructor)) { 3892 if (First) { 3893 CD->setDeletedAsWritten(); 3894 } else { 3895 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes) 3896 << CXXDefaultConstructor; 3897 CD->setInvalidDecl(); 3898 } 3899 } 3900} 3901 3902void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) { 3903 assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor()); 3904 3905 // Whether this was the first-declared instance of the constructor. 3906 bool First = CD == CD->getCanonicalDecl(); 3907 3908 bool HadError = false; 3909 if (CD->getNumParams() != 1) { 3910 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params) 3911 << CD->getSourceRange(); 3912 HadError = true; 3913 } 3914 3915 ImplicitExceptionSpecification Spec(Context); 3916 bool Const; 3917 llvm::tie(Spec, Const) = 3918 ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent()); 3919 3920 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 3921 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(), 3922 *ExceptionType = Context.getFunctionType( 3923 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>(); 3924 3925 // Check for parameter type matching. 3926 // This is a copy ctor so we know it's a cv-qualified reference to T. 3927 QualType ArgType = CtorType->getArgType(0); 3928 if (ArgType->getPointeeType().isVolatileQualified()) { 3929 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param); 3930 HadError = true; 3931 } 3932 if (ArgType->getPointeeType().isConstQualified() && !Const) { 3933 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param); 3934 HadError = true; 3935 } 3936 3937 // C++11 [dcl.fct.def.default]p2: 3938 // An explicitly-defaulted function may be declared constexpr only if it 3939 // would have been implicitly declared as constexpr, 3940 // Do not apply this rule to templates, since core issue 1358 makes such 3941 // functions always instantiate to constexpr functions. 3942 if (CD->isConstexpr() && 3943 CD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 3944 if (!CD->getParent()->defaultedCopyConstructorIsConstexpr()) { 3945 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr) 3946 << CXXCopyConstructor; 3947 HadError = true; 3948 } 3949 } 3950 // and may have an explicit exception-specification only if it is compatible 3951 // with the exception-specification on the implicit declaration. 3952 if (CtorType->hasExceptionSpec()) { 3953 if (CheckEquivalentExceptionSpec( 3954 PDiag(diag::err_incorrect_defaulted_exception_spec) 3955 << CXXCopyConstructor, 3956 PDiag(), 3957 ExceptionType, SourceLocation(), 3958 CtorType, CD->getLocation())) { 3959 HadError = true; 3960 } 3961 } 3962 3963 // If a function is explicitly defaulted on its first declaration, 3964 if (First) { 3965 // -- it is implicitly considered to be constexpr if the implicit 3966 // definition would be, 3967 CD->setConstexpr(CD->getParent()->defaultedCopyConstructorIsConstexpr()); 3968 3969 // -- it is implicitly considered to have the same 3970 // exception-specification as if it had been implicitly declared, and 3971 // 3972 // FIXME: a compatible, but different, explicit exception specification 3973 // will be silently overridden. We should issue a warning if this happens. 3974 EPI.ExtInfo = CtorType->getExtInfo(); 3975 3976 // -- [...] it shall have the same parameter type as if it had been 3977 // implicitly declared. 3978 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI)); 3979 } 3980 3981 if (HadError) { 3982 CD->setInvalidDecl(); 3983 return; 3984 } 3985 3986 if (ShouldDeleteSpecialMember(CD, CXXCopyConstructor)) { 3987 if (First) { 3988 CD->setDeletedAsWritten(); 3989 } else { 3990 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes) 3991 << CXXCopyConstructor; 3992 CD->setInvalidDecl(); 3993 } 3994 } 3995} 3996 3997void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) { 3998 assert(MD->isExplicitlyDefaulted()); 3999 4000 // Whether this was the first-declared instance of the operator 4001 bool First = MD == MD->getCanonicalDecl(); 4002 4003 bool HadError = false; 4004 if (MD->getNumParams() != 1) { 4005 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params) 4006 << MD->getSourceRange(); 4007 HadError = true; 4008 } 4009 4010 QualType ReturnType = 4011 MD->getType()->getAs<FunctionType>()->getResultType(); 4012 if (!ReturnType->isLValueReferenceType() || 4013 !Context.hasSameType( 4014 Context.getCanonicalType(ReturnType->getPointeeType()), 4015 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) { 4016 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type); 4017 HadError = true; 4018 } 4019 4020 ImplicitExceptionSpecification Spec(Context); 4021 bool Const; 4022 llvm::tie(Spec, Const) = 4023 ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent()); 4024 4025 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 4026 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(), 4027 *ExceptionType = Context.getFunctionType( 4028 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>(); 4029 4030 QualType ArgType = OperType->getArgType(0); 4031 if (!ArgType->isLValueReferenceType()) { 4032 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 4033 HadError = true; 4034 } else { 4035 if (ArgType->getPointeeType().isVolatileQualified()) { 4036 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param); 4037 HadError = true; 4038 } 4039 if (ArgType->getPointeeType().isConstQualified() && !Const) { 4040 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param); 4041 HadError = true; 4042 } 4043 } 4044 4045 if (OperType->getTypeQuals()) { 4046 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals); 4047 HadError = true; 4048 } 4049 4050 if (OperType->hasExceptionSpec()) { 4051 if (CheckEquivalentExceptionSpec( 4052 PDiag(diag::err_incorrect_defaulted_exception_spec) 4053 << CXXCopyAssignment, 4054 PDiag(), 4055 ExceptionType, SourceLocation(), 4056 OperType, MD->getLocation())) { 4057 HadError = true; 4058 } 4059 } 4060 if (First) { 4061 // We set the declaration to have the computed exception spec here. 4062 // We duplicate the one parameter type. 4063 EPI.RefQualifier = OperType->getRefQualifier(); 4064 EPI.ExtInfo = OperType->getExtInfo(); 4065 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI)); 4066 } 4067 4068 if (HadError) { 4069 MD->setInvalidDecl(); 4070 return; 4071 } 4072 4073 if (ShouldDeleteCopyAssignmentOperator(MD)) { 4074 if (First) { 4075 MD->setDeletedAsWritten(); 4076 } else { 4077 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) 4078 << CXXCopyAssignment; 4079 MD->setInvalidDecl(); 4080 } 4081 } 4082} 4083 4084void Sema::CheckExplicitlyDefaultedMoveConstructor(CXXConstructorDecl *CD) { 4085 assert(CD->isExplicitlyDefaulted() && CD->isMoveConstructor()); 4086 4087 // Whether this was the first-declared instance of the constructor. 4088 bool First = CD == CD->getCanonicalDecl(); 4089 4090 bool HadError = false; 4091 if (CD->getNumParams() != 1) { 4092 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_params) 4093 << CD->getSourceRange(); 4094 HadError = true; 4095 } 4096 4097 ImplicitExceptionSpecification Spec( 4098 ComputeDefaultedMoveCtorExceptionSpec(CD->getParent())); 4099 4100 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 4101 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(), 4102 *ExceptionType = Context.getFunctionType( 4103 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>(); 4104 4105 // Check for parameter type matching. 4106 // This is a move ctor so we know it's a cv-qualified rvalue reference to T. 4107 QualType ArgType = CtorType->getArgType(0); 4108 if (ArgType->getPointeeType().isVolatileQualified()) { 4109 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_volatile_param); 4110 HadError = true; 4111 } 4112 if (ArgType->getPointeeType().isConstQualified()) { 4113 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_const_param); 4114 HadError = true; 4115 } 4116 4117 // C++11 [dcl.fct.def.default]p2: 4118 // An explicitly-defaulted function may be declared constexpr only if it 4119 // would have been implicitly declared as constexpr, 4120 // Do not apply this rule to templates, since core issue 1358 makes such 4121 // functions always instantiate to constexpr functions. 4122 if (CD->isConstexpr() && 4123 CD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 4124 if (!CD->getParent()->defaultedMoveConstructorIsConstexpr()) { 4125 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr) 4126 << CXXMoveConstructor; 4127 HadError = true; 4128 } 4129 } 4130 // and may have an explicit exception-specification only if it is compatible 4131 // with the exception-specification on the implicit declaration. 4132 if (CtorType->hasExceptionSpec()) { 4133 if (CheckEquivalentExceptionSpec( 4134 PDiag(diag::err_incorrect_defaulted_exception_spec) 4135 << CXXMoveConstructor, 4136 PDiag(), 4137 ExceptionType, SourceLocation(), 4138 CtorType, CD->getLocation())) { 4139 HadError = true; 4140 } 4141 } 4142 4143 // If a function is explicitly defaulted on its first declaration, 4144 if (First) { 4145 // -- it is implicitly considered to be constexpr if the implicit 4146 // definition would be, 4147 CD->setConstexpr(CD->getParent()->defaultedMoveConstructorIsConstexpr()); 4148 4149 // -- it is implicitly considered to have the same 4150 // exception-specification as if it had been implicitly declared, and 4151 // 4152 // FIXME: a compatible, but different, explicit exception specification 4153 // will be silently overridden. We should issue a warning if this happens. 4154 EPI.ExtInfo = CtorType->getExtInfo(); 4155 4156 // -- [...] it shall have the same parameter type as if it had been 4157 // implicitly declared. 4158 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI)); 4159 } 4160 4161 if (HadError) { 4162 CD->setInvalidDecl(); 4163 return; 4164 } 4165 4166 if (ShouldDeleteSpecialMember(CD, CXXMoveConstructor)) { 4167 if (First) { 4168 CD->setDeletedAsWritten(); 4169 } else { 4170 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes) 4171 << CXXMoveConstructor; 4172 CD->setInvalidDecl(); 4173 } 4174 } 4175} 4176 4177void Sema::CheckExplicitlyDefaultedMoveAssignment(CXXMethodDecl *MD) { 4178 assert(MD->isExplicitlyDefaulted()); 4179 4180 // Whether this was the first-declared instance of the operator 4181 bool First = MD == MD->getCanonicalDecl(); 4182 4183 bool HadError = false; 4184 if (MD->getNumParams() != 1) { 4185 Diag(MD->getLocation(), diag::err_defaulted_move_assign_params) 4186 << MD->getSourceRange(); 4187 HadError = true; 4188 } 4189 4190 QualType ReturnType = 4191 MD->getType()->getAs<FunctionType>()->getResultType(); 4192 if (!ReturnType->isLValueReferenceType() || 4193 !Context.hasSameType( 4194 Context.getCanonicalType(ReturnType->getPointeeType()), 4195 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) { 4196 Diag(MD->getLocation(), diag::err_defaulted_move_assign_return_type); 4197 HadError = true; 4198 } 4199 4200 ImplicitExceptionSpecification Spec( 4201 ComputeDefaultedMoveCtorExceptionSpec(MD->getParent())); 4202 4203 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 4204 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(), 4205 *ExceptionType = Context.getFunctionType( 4206 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>(); 4207 4208 QualType ArgType = OperType->getArgType(0); 4209 if (!ArgType->isRValueReferenceType()) { 4210 Diag(MD->getLocation(), diag::err_defaulted_move_assign_not_ref); 4211 HadError = true; 4212 } else { 4213 if (ArgType->getPointeeType().isVolatileQualified()) { 4214 Diag(MD->getLocation(), diag::err_defaulted_move_assign_volatile_param); 4215 HadError = true; 4216 } 4217 if (ArgType->getPointeeType().isConstQualified()) { 4218 Diag(MD->getLocation(), diag::err_defaulted_move_assign_const_param); 4219 HadError = true; 4220 } 4221 } 4222 4223 if (OperType->getTypeQuals()) { 4224 Diag(MD->getLocation(), diag::err_defaulted_move_assign_quals); 4225 HadError = true; 4226 } 4227 4228 if (OperType->hasExceptionSpec()) { 4229 if (CheckEquivalentExceptionSpec( 4230 PDiag(diag::err_incorrect_defaulted_exception_spec) 4231 << CXXMoveAssignment, 4232 PDiag(), 4233 ExceptionType, SourceLocation(), 4234 OperType, MD->getLocation())) { 4235 HadError = true; 4236 } 4237 } 4238 if (First) { 4239 // We set the declaration to have the computed exception spec here. 4240 // We duplicate the one parameter type. 4241 EPI.RefQualifier = OperType->getRefQualifier(); 4242 EPI.ExtInfo = OperType->getExtInfo(); 4243 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI)); 4244 } 4245 4246 if (HadError) { 4247 MD->setInvalidDecl(); 4248 return; 4249 } 4250 4251 if (ShouldDeleteMoveAssignmentOperator(MD)) { 4252 if (First) { 4253 MD->setDeletedAsWritten(); 4254 } else { 4255 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) 4256 << CXXMoveAssignment; 4257 MD->setInvalidDecl(); 4258 } 4259 } 4260} 4261 4262void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) { 4263 assert(DD->isExplicitlyDefaulted()); 4264 4265 // Whether this was the first-declared instance of the destructor. 4266 bool First = DD == DD->getCanonicalDecl(); 4267 4268 ImplicitExceptionSpecification Spec 4269 = ComputeDefaultedDtorExceptionSpec(DD->getParent()); 4270 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 4271 const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(), 4272 *ExceptionType = Context.getFunctionType( 4273 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>(); 4274 4275 if (DtorType->hasExceptionSpec()) { 4276 if (CheckEquivalentExceptionSpec( 4277 PDiag(diag::err_incorrect_defaulted_exception_spec) 4278 << CXXDestructor, 4279 PDiag(), 4280 ExceptionType, SourceLocation(), 4281 DtorType, DD->getLocation())) { 4282 DD->setInvalidDecl(); 4283 return; 4284 } 4285 } 4286 if (First) { 4287 // We set the declaration to have the computed exception spec here. 4288 // There are no parameters. 4289 EPI.ExtInfo = DtorType->getExtInfo(); 4290 DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI)); 4291 } 4292 4293 if (ShouldDeleteDestructor(DD)) { 4294 if (First) { 4295 DD->setDeletedAsWritten(); 4296 } else { 4297 Diag(DD->getLocation(), diag::err_out_of_line_default_deletes) 4298 << CXXDestructor; 4299 DD->setInvalidDecl(); 4300 } 4301 } 4302} 4303 4304/// This function implements the following C++0x paragraphs: 4305/// - [class.ctor]/5 4306/// - [class.copy]/11 4307bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM) { 4308 assert(!MD->isInvalidDecl()); 4309 CXXRecordDecl *RD = MD->getParent(); 4310 assert(!RD->isDependentType() && "do deletion after instantiation"); 4311 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl()) 4312 return false; 4313 4314 bool IsUnion = RD->isUnion(); 4315 bool IsConstructor = false; 4316 bool IsAssignment = false; 4317 bool IsMove = false; 4318 4319 bool ConstArg = false; 4320 4321 switch (CSM) { 4322 case CXXDefaultConstructor: 4323 IsConstructor = true; 4324 4325 // C++11 [expr.lambda.prim]p19: 4326 // The closure type associated with a lambda-expression has a 4327 // deleted (8.4.3) default constructor. 4328 if (RD->isLambda()) 4329 return true; 4330 4331 break; 4332 case CXXCopyConstructor: 4333 IsConstructor = true; 4334 ConstArg = MD->getParamDecl(0)->getType().isConstQualified(); 4335 break; 4336 case CXXMoveConstructor: 4337 IsConstructor = true; 4338 IsMove = true; 4339 break; 4340 default: 4341 llvm_unreachable("function only currently implemented for default ctors"); 4342 } 4343 4344 SourceLocation Loc = MD->getLocation(); 4345 4346 // Do access control from the special member function 4347 ContextRAII MethodContext(*this, MD); 4348 4349 bool AllConst = true; 4350 4351 // We do this because we should never actually use an anonymous 4352 // union's constructor. 4353 if (IsUnion && RD->isAnonymousStructOrUnion()) 4354 return false; 4355 4356 // FIXME: We should put some diagnostic logic right into this function. 4357 4358 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 4359 BE = RD->bases_end(); 4360 BI != BE; ++BI) { 4361 // We'll handle this one later 4362 if (BI->isVirtual()) 4363 continue; 4364 4365 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl(); 4366 assert(BaseDecl && "base isn't a CXXRecordDecl"); 4367 4368 // Unless we have an assignment operator, the base's destructor must 4369 // be accessible and not deleted. 4370 if (!IsAssignment) { 4371 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl); 4372 if (BaseDtor->isDeleted()) 4373 return true; 4374 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) != 4375 AR_accessible) 4376 return true; 4377 } 4378 4379 // Finding the corresponding member in the base should lead to a 4380 // unique, accessible, non-deleted function. If we are doing 4381 // a destructor, we have already checked this case. 4382 if (CSM != CXXDestructor) { 4383 SpecialMemberOverloadResult *SMOR = 4384 LookupSpecialMember(BaseDecl, CSM, ConstArg, false, false, false, 4385 false); 4386 if (!SMOR->hasSuccess()) 4387 return true; 4388 CXXMethodDecl *BaseMember = SMOR->getMethod(); 4389 if (IsConstructor) { 4390 CXXConstructorDecl *BaseCtor = cast<CXXConstructorDecl>(BaseMember); 4391 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), 4392 PDiag()) != AR_accessible) 4393 return true; 4394 4395 // For a move operation, the corresponding operation must actually 4396 // be a move operation (and not a copy selected by overload 4397 // resolution) unless we are working on a trivially copyable class. 4398 if (IsMove && !BaseCtor->isMoveConstructor() && 4399 !BaseDecl->isTriviallyCopyable()) 4400 return true; 4401 } 4402 } 4403 } 4404 4405 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(), 4406 BE = RD->vbases_end(); 4407 BI != BE; ++BI) { 4408 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl(); 4409 assert(BaseDecl && "base isn't a CXXRecordDecl"); 4410 4411 // Unless we have an assignment operator, the base's destructor must 4412 // be accessible and not deleted. 4413 if (!IsAssignment) { 4414 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl); 4415 if (BaseDtor->isDeleted()) 4416 return true; 4417 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) != 4418 AR_accessible) 4419 return true; 4420 } 4421 4422 // Finding the corresponding member in the base should lead to a 4423 // unique, accessible, non-deleted function. 4424 if (CSM != CXXDestructor) { 4425 SpecialMemberOverloadResult *SMOR = 4426 LookupSpecialMember(BaseDecl, CSM, ConstArg, false, false, false, 4427 false); 4428 if (!SMOR->hasSuccess()) 4429 return true; 4430 CXXMethodDecl *BaseMember = SMOR->getMethod(); 4431 if (IsConstructor) { 4432 CXXConstructorDecl *BaseCtor = cast<CXXConstructorDecl>(BaseMember); 4433 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), 4434 PDiag()) != AR_accessible) 4435 return true; 4436 4437 // For a move operation, the corresponding operation must actually 4438 // be a move operation (and not a copy selected by overload 4439 // resolution) unless we are working on a trivially copyable class. 4440 if (IsMove && !BaseCtor->isMoveConstructor() && 4441 !BaseDecl->isTriviallyCopyable()) 4442 return true; 4443 } 4444 } 4445 } 4446 4447 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 4448 FE = RD->field_end(); 4449 FI != FE; ++FI) { 4450 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 4451 continue; 4452 4453 QualType FieldType = Context.getBaseElementType(FI->getType()); 4454 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 4455 4456 // For a default constructor, all references must be initialized in-class 4457 // and, if a union, it must have a non-const member. 4458 if (CSM == CXXDefaultConstructor) { 4459 if (FieldType->isReferenceType() && !FI->hasInClassInitializer()) 4460 return true; 4461 4462 if (IsUnion && !FieldType.isConstQualified()) 4463 AllConst = false; 4464 // For a copy constructor, data members must not be of rvalue reference 4465 // type. 4466 } else if (CSM == CXXCopyConstructor) { 4467 if (FieldType->isRValueReferenceType()) 4468 return true; 4469 } 4470 4471 if (FieldRecord) { 4472 // For a default constructor, a const member must have a user-provided 4473 // default constructor or else be explicitly initialized. 4474 if (CSM == CXXDefaultConstructor && FieldType.isConstQualified() && 4475 !FI->hasInClassInitializer() && 4476 !FieldRecord->hasUserProvidedDefaultConstructor()) 4477 return true; 4478 4479 // Some additional restrictions exist on the variant members. 4480 if (!IsUnion && FieldRecord->isUnion() && 4481 FieldRecord->isAnonymousStructOrUnion()) { 4482 // We're okay to reuse AllConst here since we only care about the 4483 // value otherwise if we're in a union. 4484 AllConst = true; 4485 4486 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(), 4487 UE = FieldRecord->field_end(); 4488 UI != UE; ++UI) { 4489 QualType UnionFieldType = Context.getBaseElementType(UI->getType()); 4490 CXXRecordDecl *UnionFieldRecord = 4491 UnionFieldType->getAsCXXRecordDecl(); 4492 4493 if (!UnionFieldType.isConstQualified()) 4494 AllConst = false; 4495 4496 if (UnionFieldRecord) { 4497 // FIXME: Checking for accessibility and validity of this 4498 // destructor is technically going beyond the 4499 // standard, but this is believed to be a defect. 4500 if (!IsAssignment) { 4501 CXXDestructorDecl *FieldDtor = LookupDestructor(UnionFieldRecord); 4502 if (FieldDtor->isDeleted()) 4503 return true; 4504 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) != 4505 AR_accessible) 4506 return true; 4507 if (!FieldDtor->isTrivial()) 4508 return true; 4509 } 4510 4511 if (CSM != CXXDestructor) { 4512 SpecialMemberOverloadResult *SMOR = 4513 LookupSpecialMember(UnionFieldRecord, CSM, ConstArg, false, 4514 false, false, false); 4515 // FIXME: Checking for accessibility and validity of this 4516 // corresponding member is technically going beyond the 4517 // standard, but this is believed to be a defect. 4518 if (!SMOR->hasSuccess()) 4519 return true; 4520 4521 CXXMethodDecl *FieldMember = SMOR->getMethod(); 4522 // A member of a union must have a trivial corresponding 4523 // constructor. 4524 if (!FieldMember->isTrivial()) 4525 return true; 4526 4527 if (IsConstructor) { 4528 CXXConstructorDecl *FieldCtor = cast<CXXConstructorDecl>(FieldMember); 4529 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(), 4530 PDiag()) != AR_accessible) 4531 return true; 4532 } 4533 } 4534 } 4535 } 4536 4537 // At least one member in each anonymous union must be non-const 4538 if (CSM == CXXDefaultConstructor && AllConst) 4539 return true; 4540 4541 // Don't try to initialize the anonymous union 4542 // This is technically non-conformant, but sanity demands it. 4543 continue; 4544 } 4545 4546 // Unless we're doing assignment, the field's destructor must be 4547 // accessible and not deleted. 4548 if (!IsAssignment) { 4549 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord); 4550 if (FieldDtor->isDeleted()) 4551 return true; 4552 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) != 4553 AR_accessible) 4554 return true; 4555 } 4556 4557 // Check that the corresponding member of the field is accessible, 4558 // unique, and non-deleted. We don't do this if it has an explicit 4559 // initialization when default-constructing. 4560 if (CSM != CXXDestructor && 4561 (CSM != CXXDefaultConstructor || !FI->hasInClassInitializer())) { 4562 SpecialMemberOverloadResult *SMOR = 4563 LookupSpecialMember(FieldRecord, CSM, ConstArg, false, false, false, 4564 false); 4565 if (!SMOR->hasSuccess()) 4566 return true; 4567 4568 CXXMethodDecl *FieldMember = SMOR->getMethod(); 4569 if (IsConstructor) { 4570 CXXConstructorDecl *FieldCtor = cast<CXXConstructorDecl>(FieldMember); 4571 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(), 4572 PDiag()) != AR_accessible) 4573 return true; 4574 4575 // For a move operation, the corresponding operation must actually 4576 // be a move operation (and not a copy selected by overload 4577 // resolution) unless we are working on a trivially copyable class. 4578 if (IsMove && !FieldCtor->isMoveConstructor() && 4579 !FieldRecord->isTriviallyCopyable()) 4580 return true; 4581 } 4582 4583 // We need the corresponding member of a union to be trivial so that 4584 // we can safely copy them all simultaneously. 4585 // FIXME: Note that performing the check here (where we rely on the lack 4586 // of an in-class initializer) is technically ill-formed. However, this 4587 // seems most obviously to be a bug in the standard. 4588 if (IsUnion && !FieldMember->isTrivial()) 4589 return true; 4590 } 4591 } else if (CSM == CXXDefaultConstructor && !IsUnion && 4592 FieldType.isConstQualified() && !FI->hasInClassInitializer()) { 4593 // We can't initialize a const member of non-class type to any value. 4594 return true; 4595 } 4596 } 4597 4598 // We can't have all const members in a union when default-constructing, 4599 // or else they're all nonsensical garbage values that can't be changed. 4600 if (CSM == CXXDefaultConstructor && IsUnion && AllConst) 4601 return true; 4602 4603 return false; 4604} 4605 4606bool Sema::ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD) { 4607 CXXRecordDecl *RD = MD->getParent(); 4608 assert(!RD->isDependentType() && "do deletion after instantiation"); 4609 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl()) 4610 return false; 4611 4612 // C++11 [expr.lambda.prim]p19: 4613 // The closure type associated with a lambda-expression has a 4614 // [...] deleted copy assignment operator. 4615 if (RD->isLambda()) 4616 return true; 4617 4618 SourceLocation Loc = MD->getLocation(); 4619 4620 // Do access control from the constructor 4621 ContextRAII MethodContext(*this, MD); 4622 4623 bool Union = RD->isUnion(); 4624 4625 unsigned ArgQuals = 4626 MD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ? 4627 Qualifiers::Const : 0; 4628 4629 // We do this because we should never actually use an anonymous 4630 // union's constructor. 4631 if (Union && RD->isAnonymousStructOrUnion()) 4632 return false; 4633 4634 // FIXME: We should put some diagnostic logic right into this function. 4635 4636 // C++0x [class.copy]/20 4637 // A defaulted [copy] assignment operator for class X is defined as deleted 4638 // if X has: 4639 4640 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 4641 BE = RD->bases_end(); 4642 BI != BE; ++BI) { 4643 // We'll handle this one later 4644 if (BI->isVirtual()) 4645 continue; 4646 4647 QualType BaseType = BI->getType(); 4648 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl(); 4649 assert(BaseDecl && "base isn't a CXXRecordDecl"); 4650 4651 // -- a [direct base class] B that cannot be [copied] because overload 4652 // resolution, as applied to B's [copy] assignment operator, results in 4653 // an ambiguity or a function that is deleted or inaccessible from the 4654 // assignment operator 4655 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false, 4656 0); 4657 if (!CopyOper || CopyOper->isDeleted()) 4658 return true; 4659 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible) 4660 return true; 4661 } 4662 4663 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(), 4664 BE = RD->vbases_end(); 4665 BI != BE; ++BI) { 4666 QualType BaseType = BI->getType(); 4667 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl(); 4668 assert(BaseDecl && "base isn't a CXXRecordDecl"); 4669 4670 // -- a [virtual base class] B that cannot be [copied] because overload 4671 // resolution, as applied to B's [copy] assignment operator, results in 4672 // an ambiguity or a function that is deleted or inaccessible from the 4673 // assignment operator 4674 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false, 4675 0); 4676 if (!CopyOper || CopyOper->isDeleted()) 4677 return true; 4678 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible) 4679 return true; 4680 } 4681 4682 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 4683 FE = RD->field_end(); 4684 FI != FE; ++FI) { 4685 if (FI->isUnnamedBitfield()) 4686 continue; 4687 4688 QualType FieldType = Context.getBaseElementType(FI->getType()); 4689 4690 // -- a non-static data member of reference type 4691 if (FieldType->isReferenceType()) 4692 return true; 4693 4694 // -- a non-static data member of const non-class type (or array thereof) 4695 if (FieldType.isConstQualified() && !FieldType->isRecordType()) 4696 return true; 4697 4698 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 4699 4700 if (FieldRecord) { 4701 // This is an anonymous union 4702 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) { 4703 // Anonymous unions inside unions do not variant members create 4704 if (!Union) { 4705 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(), 4706 UE = FieldRecord->field_end(); 4707 UI != UE; ++UI) { 4708 QualType UnionFieldType = Context.getBaseElementType(UI->getType()); 4709 CXXRecordDecl *UnionFieldRecord = 4710 UnionFieldType->getAsCXXRecordDecl(); 4711 4712 // -- a variant member with a non-trivial [copy] assignment operator 4713 // and X is a union-like class 4714 if (UnionFieldRecord && 4715 !UnionFieldRecord->hasTrivialCopyAssignment()) 4716 return true; 4717 } 4718 } 4719 4720 // Don't try to initalize an anonymous union 4721 continue; 4722 // -- a variant member with a non-trivial [copy] assignment operator 4723 // and X is a union-like class 4724 } else if (Union && !FieldRecord->hasTrivialCopyAssignment()) { 4725 return true; 4726 } 4727 4728 CXXMethodDecl *CopyOper = LookupCopyingAssignment(FieldRecord, ArgQuals, 4729 false, 0); 4730 if (!CopyOper || CopyOper->isDeleted()) 4731 return true; 4732 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible) 4733 return true; 4734 } 4735 } 4736 4737 return false; 4738} 4739 4740bool Sema::ShouldDeleteMoveAssignmentOperator(CXXMethodDecl *MD) { 4741 CXXRecordDecl *RD = MD->getParent(); 4742 assert(!RD->isDependentType() && "do deletion after instantiation"); 4743 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl()) 4744 return false; 4745 4746 SourceLocation Loc = MD->getLocation(); 4747 4748 // Do access control from the constructor 4749 ContextRAII MethodContext(*this, MD); 4750 4751 bool Union = RD->isUnion(); 4752 4753 // We do this because we should never actually use an anonymous 4754 // union's constructor. 4755 if (Union && RD->isAnonymousStructOrUnion()) 4756 return false; 4757 4758 // C++0x [class.copy]/20 4759 // A defaulted [move] assignment operator for class X is defined as deleted 4760 // if X has: 4761 4762 // -- for the move constructor, [...] any direct or indirect virtual base 4763 // class. 4764 if (RD->getNumVBases() != 0) 4765 return true; 4766 4767 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 4768 BE = RD->bases_end(); 4769 BI != BE; ++BI) { 4770 4771 QualType BaseType = BI->getType(); 4772 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl(); 4773 assert(BaseDecl && "base isn't a CXXRecordDecl"); 4774 4775 // -- a [direct base class] B that cannot be [moved] because overload 4776 // resolution, as applied to B's [move] assignment operator, results in 4777 // an ambiguity or a function that is deleted or inaccessible from the 4778 // assignment operator 4779 CXXMethodDecl *MoveOper = LookupMovingAssignment(BaseDecl, false, 0); 4780 if (!MoveOper || MoveOper->isDeleted()) 4781 return true; 4782 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible) 4783 return true; 4784 4785 // -- for the move assignment operator, a [direct base class] with a type 4786 // that does not have a move assignment operator and is not trivially 4787 // copyable. 4788 if (!MoveOper->isMoveAssignmentOperator() && 4789 !BaseDecl->isTriviallyCopyable()) 4790 return true; 4791 } 4792 4793 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 4794 FE = RD->field_end(); 4795 FI != FE; ++FI) { 4796 if (FI->isUnnamedBitfield()) 4797 continue; 4798 4799 QualType FieldType = Context.getBaseElementType(FI->getType()); 4800 4801 // -- a non-static data member of reference type 4802 if (FieldType->isReferenceType()) 4803 return true; 4804 4805 // -- a non-static data member of const non-class type (or array thereof) 4806 if (FieldType.isConstQualified() && !FieldType->isRecordType()) 4807 return true; 4808 4809 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 4810 4811 if (FieldRecord) { 4812 // This is an anonymous union 4813 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) { 4814 // Anonymous unions inside unions do not variant members create 4815 if (!Union) { 4816 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(), 4817 UE = FieldRecord->field_end(); 4818 UI != UE; ++UI) { 4819 QualType UnionFieldType = Context.getBaseElementType(UI->getType()); 4820 CXXRecordDecl *UnionFieldRecord = 4821 UnionFieldType->getAsCXXRecordDecl(); 4822 4823 // -- a variant member with a non-trivial [move] assignment operator 4824 // and X is a union-like class 4825 if (UnionFieldRecord && 4826 !UnionFieldRecord->hasTrivialMoveAssignment()) 4827 return true; 4828 } 4829 } 4830 4831 // Don't try to initalize an anonymous union 4832 continue; 4833 // -- a variant member with a non-trivial [move] assignment operator 4834 // and X is a union-like class 4835 } else if (Union && !FieldRecord->hasTrivialMoveAssignment()) { 4836 return true; 4837 } 4838 4839 CXXMethodDecl *MoveOper = LookupMovingAssignment(FieldRecord, false, 0); 4840 if (!MoveOper || MoveOper->isDeleted()) 4841 return true; 4842 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible) 4843 return true; 4844 4845 // -- for the move assignment operator, a [non-static data member] with a 4846 // type that does not have a move assignment operator and is not 4847 // trivially copyable. 4848 if (!MoveOper->isMoveAssignmentOperator() && 4849 !FieldRecord->isTriviallyCopyable()) 4850 return true; 4851 } 4852 } 4853 4854 return false; 4855} 4856 4857bool Sema::ShouldDeleteDestructor(CXXDestructorDecl *DD) { 4858 CXXRecordDecl *RD = DD->getParent(); 4859 assert(!RD->isDependentType() && "do deletion after instantiation"); 4860 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl()) 4861 return false; 4862 4863 SourceLocation Loc = DD->getLocation(); 4864 4865 // Do access control from the destructor 4866 ContextRAII CtorContext(*this, DD); 4867 4868 bool Union = RD->isUnion(); 4869 4870 // We do this because we should never actually use an anonymous 4871 // union's destructor. 4872 if (Union && RD->isAnonymousStructOrUnion()) 4873 return false; 4874 4875 // C++0x [class.dtor]p5 4876 // A defaulted destructor for a class X is defined as deleted if: 4877 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 4878 BE = RD->bases_end(); 4879 BI != BE; ++BI) { 4880 // We'll handle this one later 4881 if (BI->isVirtual()) 4882 continue; 4883 4884 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl(); 4885 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl); 4886 assert(BaseDtor && "base has no destructor"); 4887 4888 // -- any direct or virtual base class has a deleted destructor or 4889 // a destructor that is inaccessible from the defaulted destructor 4890 if (BaseDtor->isDeleted()) 4891 return true; 4892 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) != 4893 AR_accessible) 4894 return true; 4895 } 4896 4897 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(), 4898 BE = RD->vbases_end(); 4899 BI != BE; ++BI) { 4900 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl(); 4901 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl); 4902 assert(BaseDtor && "base has no destructor"); 4903 4904 // -- any direct or virtual base class has a deleted destructor or 4905 // a destructor that is inaccessible from the defaulted destructor 4906 if (BaseDtor->isDeleted()) 4907 return true; 4908 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) != 4909 AR_accessible) 4910 return true; 4911 } 4912 4913 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 4914 FE = RD->field_end(); 4915 FI != FE; ++FI) { 4916 QualType FieldType = Context.getBaseElementType(FI->getType()); 4917 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 4918 if (FieldRecord) { 4919 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) { 4920 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(), 4921 UE = FieldRecord->field_end(); 4922 UI != UE; ++UI) { 4923 QualType UnionFieldType = Context.getBaseElementType(FI->getType()); 4924 CXXRecordDecl *UnionFieldRecord = 4925 UnionFieldType->getAsCXXRecordDecl(); 4926 4927 // -- X is a union-like class that has a variant member with a non- 4928 // trivial destructor. 4929 if (UnionFieldRecord && !UnionFieldRecord->hasTrivialDestructor()) 4930 return true; 4931 } 4932 // Technically we are supposed to do this next check unconditionally. 4933 // But that makes absolutely no sense. 4934 } else { 4935 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord); 4936 4937 // -- any of the non-static data members has class type M (or array 4938 // thereof) and M has a deleted destructor or a destructor that is 4939 // inaccessible from the defaulted destructor 4940 if (FieldDtor->isDeleted()) 4941 return true; 4942 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) != 4943 AR_accessible) 4944 return true; 4945 4946 // -- X is a union-like class that has a variant member with a non- 4947 // trivial destructor. 4948 if (Union && !FieldDtor->isTrivial()) 4949 return true; 4950 } 4951 } 4952 } 4953 4954 if (DD->isVirtual()) { 4955 FunctionDecl *OperatorDelete = 0; 4956 DeclarationName Name = 4957 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 4958 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete, 4959 false)) 4960 return true; 4961 } 4962 4963 4964 return false; 4965} 4966 4967/// \brief Data used with FindHiddenVirtualMethod 4968namespace { 4969 struct FindHiddenVirtualMethodData { 4970 Sema *S; 4971 CXXMethodDecl *Method; 4972 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 4973 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 4974 }; 4975} 4976 4977/// \brief Member lookup function that determines whether a given C++ 4978/// method overloads virtual methods in a base class without overriding any, 4979/// to be used with CXXRecordDecl::lookupInBases(). 4980static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier, 4981 CXXBasePath &Path, 4982 void *UserData) { 4983 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 4984 4985 FindHiddenVirtualMethodData &Data 4986 = *static_cast<FindHiddenVirtualMethodData*>(UserData); 4987 4988 DeclarationName Name = Data.Method->getDeclName(); 4989 assert(Name.getNameKind() == DeclarationName::Identifier); 4990 4991 bool foundSameNameMethod = false; 4992 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 4993 for (Path.Decls = BaseRecord->lookup(Name); 4994 Path.Decls.first != Path.Decls.second; 4995 ++Path.Decls.first) { 4996 NamedDecl *D = *Path.Decls.first; 4997 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 4998 MD = MD->getCanonicalDecl(); 4999 foundSameNameMethod = true; 5000 // Interested only in hidden virtual methods. 5001 if (!MD->isVirtual()) 5002 continue; 5003 // If the method we are checking overrides a method from its base 5004 // don't warn about the other overloaded methods. 5005 if (!Data.S->IsOverload(Data.Method, MD, false)) 5006 return true; 5007 // Collect the overload only if its hidden. 5008 if (!Data.OverridenAndUsingBaseMethods.count(MD)) 5009 overloadedMethods.push_back(MD); 5010 } 5011 } 5012 5013 if (foundSameNameMethod) 5014 Data.OverloadedMethods.append(overloadedMethods.begin(), 5015 overloadedMethods.end()); 5016 return foundSameNameMethod; 5017} 5018 5019/// \brief See if a method overloads virtual methods in a base class without 5020/// overriding any. 5021void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 5022 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual, 5023 MD->getLocation()) == DiagnosticsEngine::Ignored) 5024 return; 5025 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier) 5026 return; 5027 5028 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 5029 /*bool RecordPaths=*/false, 5030 /*bool DetectVirtual=*/false); 5031 FindHiddenVirtualMethodData Data; 5032 Data.Method = MD; 5033 Data.S = this; 5034 5035 // Keep the base methods that were overriden or introduced in the subclass 5036 // by 'using' in a set. A base method not in this set is hidden. 5037 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName()); 5038 res.first != res.second; ++res.first) { 5039 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first)) 5040 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 5041 E = MD->end_overridden_methods(); 5042 I != E; ++I) 5043 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl()); 5044 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first)) 5045 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl())) 5046 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl()); 5047 } 5048 5049 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) && 5050 !Data.OverloadedMethods.empty()) { 5051 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 5052 << MD << (Data.OverloadedMethods.size() > 1); 5053 5054 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) { 5055 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i]; 5056 Diag(overloadedMD->getLocation(), 5057 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 5058 } 5059 } 5060} 5061 5062void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 5063 Decl *TagDecl, 5064 SourceLocation LBrac, 5065 SourceLocation RBrac, 5066 AttributeList *AttrList) { 5067 if (!TagDecl) 5068 return; 5069 5070 AdjustDeclIfTemplate(TagDecl); 5071 5072 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 5073 // strict aliasing violation! 5074 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 5075 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 5076 5077 CheckCompletedCXXClass( 5078 dyn_cast_or_null<CXXRecordDecl>(TagDecl)); 5079} 5080 5081/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 5082/// special functions, such as the default constructor, copy 5083/// constructor, or destructor, to the given C++ class (C++ 5084/// [special]p1). This routine can only be executed just before the 5085/// definition of the class is complete. 5086void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 5087 if (!ClassDecl->hasUserDeclaredConstructor()) 5088 ++ASTContext::NumImplicitDefaultConstructors; 5089 5090 if (!ClassDecl->hasUserDeclaredCopyConstructor()) 5091 ++ASTContext::NumImplicitCopyConstructors; 5092 5093 if (getLangOptions().CPlusPlus0x && ClassDecl->needsImplicitMoveConstructor()) 5094 ++ASTContext::NumImplicitMoveConstructors; 5095 5096 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 5097 ++ASTContext::NumImplicitCopyAssignmentOperators; 5098 5099 // If we have a dynamic class, then the copy assignment operator may be 5100 // virtual, so we have to declare it immediately. This ensures that, e.g., 5101 // it shows up in the right place in the vtable and that we diagnose 5102 // problems with the implicit exception specification. 5103 if (ClassDecl->isDynamicClass()) 5104 DeclareImplicitCopyAssignment(ClassDecl); 5105 } 5106 5107 if (getLangOptions().CPlusPlus0x && ClassDecl->needsImplicitMoveAssignment()){ 5108 ++ASTContext::NumImplicitMoveAssignmentOperators; 5109 5110 // Likewise for the move assignment operator. 5111 if (ClassDecl->isDynamicClass()) 5112 DeclareImplicitMoveAssignment(ClassDecl); 5113 } 5114 5115 if (!ClassDecl->hasUserDeclaredDestructor()) { 5116 ++ASTContext::NumImplicitDestructors; 5117 5118 // If we have a dynamic class, then the destructor may be virtual, so we 5119 // have to declare the destructor immediately. This ensures that, e.g., it 5120 // shows up in the right place in the vtable and that we diagnose problems 5121 // with the implicit exception specification. 5122 if (ClassDecl->isDynamicClass()) 5123 DeclareImplicitDestructor(ClassDecl); 5124 } 5125} 5126 5127void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) { 5128 if (!D) 5129 return; 5130 5131 int NumParamList = D->getNumTemplateParameterLists(); 5132 for (int i = 0; i < NumParamList; i++) { 5133 TemplateParameterList* Params = D->getTemplateParameterList(i); 5134 for (TemplateParameterList::iterator Param = Params->begin(), 5135 ParamEnd = Params->end(); 5136 Param != ParamEnd; ++Param) { 5137 NamedDecl *Named = cast<NamedDecl>(*Param); 5138 if (Named->getDeclName()) { 5139 S->AddDecl(Named); 5140 IdResolver.AddDecl(Named); 5141 } 5142 } 5143 } 5144} 5145 5146void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 5147 if (!D) 5148 return; 5149 5150 TemplateParameterList *Params = 0; 5151 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) 5152 Params = Template->getTemplateParameters(); 5153 else if (ClassTemplatePartialSpecializationDecl *PartialSpec 5154 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 5155 Params = PartialSpec->getTemplateParameters(); 5156 else 5157 return; 5158 5159 for (TemplateParameterList::iterator Param = Params->begin(), 5160 ParamEnd = Params->end(); 5161 Param != ParamEnd; ++Param) { 5162 NamedDecl *Named = cast<NamedDecl>(*Param); 5163 if (Named->getDeclName()) { 5164 S->AddDecl(Named); 5165 IdResolver.AddDecl(Named); 5166 } 5167 } 5168} 5169 5170void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 5171 if (!RecordD) return; 5172 AdjustDeclIfTemplate(RecordD); 5173 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 5174 PushDeclContext(S, Record); 5175} 5176 5177void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 5178 if (!RecordD) return; 5179 PopDeclContext(); 5180} 5181 5182/// ActOnStartDelayedCXXMethodDeclaration - We have completed 5183/// parsing a top-level (non-nested) C++ class, and we are now 5184/// parsing those parts of the given Method declaration that could 5185/// not be parsed earlier (C++ [class.mem]p2), such as default 5186/// arguments. This action should enter the scope of the given 5187/// Method declaration as if we had just parsed the qualified method 5188/// name. However, it should not bring the parameters into scope; 5189/// that will be performed by ActOnDelayedCXXMethodParameter. 5190void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 5191} 5192 5193/// ActOnDelayedCXXMethodParameter - We've already started a delayed 5194/// C++ method declaration. We're (re-)introducing the given 5195/// function parameter into scope for use in parsing later parts of 5196/// the method declaration. For example, we could see an 5197/// ActOnParamDefaultArgument event for this parameter. 5198void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 5199 if (!ParamD) 5200 return; 5201 5202 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 5203 5204 // If this parameter has an unparsed default argument, clear it out 5205 // to make way for the parsed default argument. 5206 if (Param->hasUnparsedDefaultArg()) 5207 Param->setDefaultArg(0); 5208 5209 S->AddDecl(Param); 5210 if (Param->getDeclName()) 5211 IdResolver.AddDecl(Param); 5212} 5213 5214/// ActOnFinishDelayedCXXMethodDeclaration - We have finished 5215/// processing the delayed method declaration for Method. The method 5216/// declaration is now considered finished. There may be a separate 5217/// ActOnStartOfFunctionDef action later (not necessarily 5218/// immediately!) for this method, if it was also defined inside the 5219/// class body. 5220void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 5221 if (!MethodD) 5222 return; 5223 5224 AdjustDeclIfTemplate(MethodD); 5225 5226 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 5227 5228 // Now that we have our default arguments, check the constructor 5229 // again. It could produce additional diagnostics or affect whether 5230 // the class has implicitly-declared destructors, among other 5231 // things. 5232 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 5233 CheckConstructor(Constructor); 5234 5235 // Check the default arguments, which we may have added. 5236 if (!Method->isInvalidDecl()) 5237 CheckCXXDefaultArguments(Method); 5238} 5239 5240/// CheckConstructorDeclarator - Called by ActOnDeclarator to check 5241/// the well-formedness of the constructor declarator @p D with type @p 5242/// R. If there are any errors in the declarator, this routine will 5243/// emit diagnostics and set the invalid bit to true. In any case, the type 5244/// will be updated to reflect a well-formed type for the constructor and 5245/// returned. 5246QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 5247 StorageClass &SC) { 5248 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 5249 5250 // C++ [class.ctor]p3: 5251 // A constructor shall not be virtual (10.3) or static (9.4). A 5252 // constructor can be invoked for a const, volatile or const 5253 // volatile object. A constructor shall not be declared const, 5254 // volatile, or const volatile (9.3.2). 5255 if (isVirtual) { 5256 if (!D.isInvalidType()) 5257 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 5258 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 5259 << SourceRange(D.getIdentifierLoc()); 5260 D.setInvalidType(); 5261 } 5262 if (SC == SC_Static) { 5263 if (!D.isInvalidType()) 5264 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 5265 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 5266 << SourceRange(D.getIdentifierLoc()); 5267 D.setInvalidType(); 5268 SC = SC_None; 5269 } 5270 5271 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 5272 if (FTI.TypeQuals != 0) { 5273 if (FTI.TypeQuals & Qualifiers::Const) 5274 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 5275 << "const" << SourceRange(D.getIdentifierLoc()); 5276 if (FTI.TypeQuals & Qualifiers::Volatile) 5277 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 5278 << "volatile" << SourceRange(D.getIdentifierLoc()); 5279 if (FTI.TypeQuals & Qualifiers::Restrict) 5280 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 5281 << "restrict" << SourceRange(D.getIdentifierLoc()); 5282 D.setInvalidType(); 5283 } 5284 5285 // C++0x [class.ctor]p4: 5286 // A constructor shall not be declared with a ref-qualifier. 5287 if (FTI.hasRefQualifier()) { 5288 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 5289 << FTI.RefQualifierIsLValueRef 5290 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 5291 D.setInvalidType(); 5292 } 5293 5294 // Rebuild the function type "R" without any type qualifiers (in 5295 // case any of the errors above fired) and with "void" as the 5296 // return type, since constructors don't have return types. 5297 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 5298 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType()) 5299 return R; 5300 5301 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 5302 EPI.TypeQuals = 0; 5303 EPI.RefQualifier = RQ_None; 5304 5305 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(), 5306 Proto->getNumArgs(), EPI); 5307} 5308 5309/// CheckConstructor - Checks a fully-formed constructor for 5310/// well-formedness, issuing any diagnostics required. Returns true if 5311/// the constructor declarator is invalid. 5312void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 5313 CXXRecordDecl *ClassDecl 5314 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 5315 if (!ClassDecl) 5316 return Constructor->setInvalidDecl(); 5317 5318 // C++ [class.copy]p3: 5319 // A declaration of a constructor for a class X is ill-formed if 5320 // its first parameter is of type (optionally cv-qualified) X and 5321 // either there are no other parameters or else all other 5322 // parameters have default arguments. 5323 if (!Constructor->isInvalidDecl() && 5324 ((Constructor->getNumParams() == 1) || 5325 (Constructor->getNumParams() > 1 && 5326 Constructor->getParamDecl(1)->hasDefaultArg())) && 5327 Constructor->getTemplateSpecializationKind() 5328 != TSK_ImplicitInstantiation) { 5329 QualType ParamType = Constructor->getParamDecl(0)->getType(); 5330 QualType ClassTy = Context.getTagDeclType(ClassDecl); 5331 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 5332 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 5333 const char *ConstRef 5334 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 5335 : " const &"; 5336 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 5337 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 5338 5339 // FIXME: Rather that making the constructor invalid, we should endeavor 5340 // to fix the type. 5341 Constructor->setInvalidDecl(); 5342 } 5343 } 5344} 5345 5346/// CheckDestructor - Checks a fully-formed destructor definition for 5347/// well-formedness, issuing any diagnostics required. Returns true 5348/// on error. 5349bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 5350 CXXRecordDecl *RD = Destructor->getParent(); 5351 5352 if (Destructor->isVirtual()) { 5353 SourceLocation Loc; 5354 5355 if (!Destructor->isImplicit()) 5356 Loc = Destructor->getLocation(); 5357 else 5358 Loc = RD->getLocation(); 5359 5360 // If we have a virtual destructor, look up the deallocation function 5361 FunctionDecl *OperatorDelete = 0; 5362 DeclarationName Name = 5363 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 5364 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 5365 return true; 5366 5367 MarkFunctionReferenced(Loc, OperatorDelete); 5368 5369 Destructor->setOperatorDelete(OperatorDelete); 5370 } 5371 5372 return false; 5373} 5374 5375static inline bool 5376FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) { 5377 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 5378 FTI.ArgInfo[0].Param && 5379 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()); 5380} 5381 5382/// CheckDestructorDeclarator - Called by ActOnDeclarator to check 5383/// the well-formednes of the destructor declarator @p D with type @p 5384/// R. If there are any errors in the declarator, this routine will 5385/// emit diagnostics and set the declarator to invalid. Even if this happens, 5386/// will be updated to reflect a well-formed type for the destructor and 5387/// returned. 5388QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 5389 StorageClass& SC) { 5390 // C++ [class.dtor]p1: 5391 // [...] A typedef-name that names a class is a class-name 5392 // (7.1.3); however, a typedef-name that names a class shall not 5393 // be used as the identifier in the declarator for a destructor 5394 // declaration. 5395 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 5396 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 5397 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 5398 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 5399 else if (const TemplateSpecializationType *TST = 5400 DeclaratorType->getAs<TemplateSpecializationType>()) 5401 if (TST->isTypeAlias()) 5402 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 5403 << DeclaratorType << 1; 5404 5405 // C++ [class.dtor]p2: 5406 // A destructor is used to destroy objects of its class type. A 5407 // destructor takes no parameters, and no return type can be 5408 // specified for it (not even void). The address of a destructor 5409 // shall not be taken. A destructor shall not be static. A 5410 // destructor can be invoked for a const, volatile or const 5411 // volatile object. A destructor shall not be declared const, 5412 // volatile or const volatile (9.3.2). 5413 if (SC == SC_Static) { 5414 if (!D.isInvalidType()) 5415 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 5416 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 5417 << SourceRange(D.getIdentifierLoc()) 5418 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5419 5420 SC = SC_None; 5421 } 5422 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 5423 // Destructors don't have return types, but the parser will 5424 // happily parse something like: 5425 // 5426 // class X { 5427 // float ~X(); 5428 // }; 5429 // 5430 // The return type will be eliminated later. 5431 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 5432 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 5433 << SourceRange(D.getIdentifierLoc()); 5434 } 5435 5436 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 5437 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 5438 if (FTI.TypeQuals & Qualifiers::Const) 5439 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 5440 << "const" << SourceRange(D.getIdentifierLoc()); 5441 if (FTI.TypeQuals & Qualifiers::Volatile) 5442 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 5443 << "volatile" << SourceRange(D.getIdentifierLoc()); 5444 if (FTI.TypeQuals & Qualifiers::Restrict) 5445 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 5446 << "restrict" << SourceRange(D.getIdentifierLoc()); 5447 D.setInvalidType(); 5448 } 5449 5450 // C++0x [class.dtor]p2: 5451 // A destructor shall not be declared with a ref-qualifier. 5452 if (FTI.hasRefQualifier()) { 5453 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 5454 << FTI.RefQualifierIsLValueRef 5455 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 5456 D.setInvalidType(); 5457 } 5458 5459 // Make sure we don't have any parameters. 5460 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) { 5461 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 5462 5463 // Delete the parameters. 5464 FTI.freeArgs(); 5465 D.setInvalidType(); 5466 } 5467 5468 // Make sure the destructor isn't variadic. 5469 if (FTI.isVariadic) { 5470 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 5471 D.setInvalidType(); 5472 } 5473 5474 // Rebuild the function type "R" without any type qualifiers or 5475 // parameters (in case any of the errors above fired) and with 5476 // "void" as the return type, since destructors don't have return 5477 // types. 5478 if (!D.isInvalidType()) 5479 return R; 5480 5481 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 5482 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 5483 EPI.Variadic = false; 5484 EPI.TypeQuals = 0; 5485 EPI.RefQualifier = RQ_None; 5486 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI); 5487} 5488 5489/// CheckConversionDeclarator - Called by ActOnDeclarator to check the 5490/// well-formednes of the conversion function declarator @p D with 5491/// type @p R. If there are any errors in the declarator, this routine 5492/// will emit diagnostics and return true. Otherwise, it will return 5493/// false. Either way, the type @p R will be updated to reflect a 5494/// well-formed type for the conversion operator. 5495void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 5496 StorageClass& SC) { 5497 // C++ [class.conv.fct]p1: 5498 // Neither parameter types nor return type can be specified. The 5499 // type of a conversion function (8.3.5) is "function taking no 5500 // parameter returning conversion-type-id." 5501 if (SC == SC_Static) { 5502 if (!D.isInvalidType()) 5503 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 5504 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 5505 << SourceRange(D.getIdentifierLoc()); 5506 D.setInvalidType(); 5507 SC = SC_None; 5508 } 5509 5510 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId); 5511 5512 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 5513 // Conversion functions don't have return types, but the parser will 5514 // happily parse something like: 5515 // 5516 // class X { 5517 // float operator bool(); 5518 // }; 5519 // 5520 // The return type will be changed later anyway. 5521 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 5522 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 5523 << SourceRange(D.getIdentifierLoc()); 5524 D.setInvalidType(); 5525 } 5526 5527 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 5528 5529 // Make sure we don't have any parameters. 5530 if (Proto->getNumArgs() > 0) { 5531 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 5532 5533 // Delete the parameters. 5534 D.getFunctionTypeInfo().freeArgs(); 5535 D.setInvalidType(); 5536 } else if (Proto->isVariadic()) { 5537 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 5538 D.setInvalidType(); 5539 } 5540 5541 // Diagnose "&operator bool()" and other such nonsense. This 5542 // is actually a gcc extension which we don't support. 5543 if (Proto->getResultType() != ConvType) { 5544 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 5545 << Proto->getResultType(); 5546 D.setInvalidType(); 5547 ConvType = Proto->getResultType(); 5548 } 5549 5550 // C++ [class.conv.fct]p4: 5551 // The conversion-type-id shall not represent a function type nor 5552 // an array type. 5553 if (ConvType->isArrayType()) { 5554 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 5555 ConvType = Context.getPointerType(ConvType); 5556 D.setInvalidType(); 5557 } else if (ConvType->isFunctionType()) { 5558 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 5559 ConvType = Context.getPointerType(ConvType); 5560 D.setInvalidType(); 5561 } 5562 5563 // Rebuild the function type "R" without any parameters (in case any 5564 // of the errors above fired) and with the conversion type as the 5565 // return type. 5566 if (D.isInvalidType()) 5567 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo()); 5568 5569 // C++0x explicit conversion operators. 5570 if (D.getDeclSpec().isExplicitSpecified()) 5571 Diag(D.getDeclSpec().getExplicitSpecLoc(), 5572 getLangOptions().CPlusPlus0x ? 5573 diag::warn_cxx98_compat_explicit_conversion_functions : 5574 diag::ext_explicit_conversion_functions) 5575 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 5576} 5577 5578/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 5579/// the declaration of the given C++ conversion function. This routine 5580/// is responsible for recording the conversion function in the C++ 5581/// class, if possible. 5582Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 5583 assert(Conversion && "Expected to receive a conversion function declaration"); 5584 5585 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 5586 5587 // Make sure we aren't redeclaring the conversion function. 5588 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 5589 5590 // C++ [class.conv.fct]p1: 5591 // [...] A conversion function is never used to convert a 5592 // (possibly cv-qualified) object to the (possibly cv-qualified) 5593 // same object type (or a reference to it), to a (possibly 5594 // cv-qualified) base class of that type (or a reference to it), 5595 // or to (possibly cv-qualified) void. 5596 // FIXME: Suppress this warning if the conversion function ends up being a 5597 // virtual function that overrides a virtual function in a base class. 5598 QualType ClassType 5599 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 5600 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 5601 ConvType = ConvTypeRef->getPointeeType(); 5602 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 5603 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 5604 /* Suppress diagnostics for instantiations. */; 5605 else if (ConvType->isRecordType()) { 5606 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 5607 if (ConvType == ClassType) 5608 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 5609 << ClassType; 5610 else if (IsDerivedFrom(ClassType, ConvType)) 5611 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 5612 << ClassType << ConvType; 5613 } else if (ConvType->isVoidType()) { 5614 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 5615 << ClassType << ConvType; 5616 } 5617 5618 if (FunctionTemplateDecl *ConversionTemplate 5619 = Conversion->getDescribedFunctionTemplate()) 5620 return ConversionTemplate; 5621 5622 return Conversion; 5623} 5624 5625//===----------------------------------------------------------------------===// 5626// Namespace Handling 5627//===----------------------------------------------------------------------===// 5628 5629 5630 5631/// ActOnStartNamespaceDef - This is called at the start of a namespace 5632/// definition. 5633Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 5634 SourceLocation InlineLoc, 5635 SourceLocation NamespaceLoc, 5636 SourceLocation IdentLoc, 5637 IdentifierInfo *II, 5638 SourceLocation LBrace, 5639 AttributeList *AttrList) { 5640 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 5641 // For anonymous namespace, take the location of the left brace. 5642 SourceLocation Loc = II ? IdentLoc : LBrace; 5643 bool IsInline = InlineLoc.isValid(); 5644 bool IsInvalid = false; 5645 bool IsStd = false; 5646 bool AddToKnown = false; 5647 Scope *DeclRegionScope = NamespcScope->getParent(); 5648 5649 NamespaceDecl *PrevNS = 0; 5650 if (II) { 5651 // C++ [namespace.def]p2: 5652 // The identifier in an original-namespace-definition shall not 5653 // have been previously defined in the declarative region in 5654 // which the original-namespace-definition appears. The 5655 // identifier in an original-namespace-definition is the name of 5656 // the namespace. Subsequently in that declarative region, it is 5657 // treated as an original-namespace-name. 5658 // 5659 // Since namespace names are unique in their scope, and we don't 5660 // look through using directives, just look for any ordinary names. 5661 5662 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member | 5663 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag | 5664 Decl::IDNS_Namespace; 5665 NamedDecl *PrevDecl = 0; 5666 for (DeclContext::lookup_result R 5667 = CurContext->getRedeclContext()->lookup(II); 5668 R.first != R.second; ++R.first) { 5669 if ((*R.first)->getIdentifierNamespace() & IDNS) { 5670 PrevDecl = *R.first; 5671 break; 5672 } 5673 } 5674 5675 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 5676 5677 if (PrevNS) { 5678 // This is an extended namespace definition. 5679 if (IsInline != PrevNS->isInline()) { 5680 // inline-ness must match 5681 if (PrevNS->isInline()) { 5682 // The user probably just forgot the 'inline', so suggest that it 5683 // be added back. 5684 Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 5685 << FixItHint::CreateInsertion(NamespaceLoc, "inline "); 5686 } else { 5687 Diag(Loc, diag::err_inline_namespace_mismatch) 5688 << IsInline; 5689 } 5690 Diag(PrevNS->getLocation(), diag::note_previous_definition); 5691 5692 IsInline = PrevNS->isInline(); 5693 } 5694 } else if (PrevDecl) { 5695 // This is an invalid name redefinition. 5696 Diag(Loc, diag::err_redefinition_different_kind) 5697 << II; 5698 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 5699 IsInvalid = true; 5700 // Continue on to push Namespc as current DeclContext and return it. 5701 } else if (II->isStr("std") && 5702 CurContext->getRedeclContext()->isTranslationUnit()) { 5703 // This is the first "real" definition of the namespace "std", so update 5704 // our cache of the "std" namespace to point at this definition. 5705 PrevNS = getStdNamespace(); 5706 IsStd = true; 5707 AddToKnown = !IsInline; 5708 } else { 5709 // We've seen this namespace for the first time. 5710 AddToKnown = !IsInline; 5711 } 5712 } else { 5713 // Anonymous namespaces. 5714 5715 // Determine whether the parent already has an anonymous namespace. 5716 DeclContext *Parent = CurContext->getRedeclContext(); 5717 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 5718 PrevNS = TU->getAnonymousNamespace(); 5719 } else { 5720 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 5721 PrevNS = ND->getAnonymousNamespace(); 5722 } 5723 5724 if (PrevNS && IsInline != PrevNS->isInline()) { 5725 // inline-ness must match 5726 Diag(Loc, diag::err_inline_namespace_mismatch) 5727 << IsInline; 5728 Diag(PrevNS->getLocation(), diag::note_previous_definition); 5729 5730 // Recover by ignoring the new namespace's inline status. 5731 IsInline = PrevNS->isInline(); 5732 } 5733 } 5734 5735 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 5736 StartLoc, Loc, II, PrevNS); 5737 if (IsInvalid) 5738 Namespc->setInvalidDecl(); 5739 5740 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 5741 5742 // FIXME: Should we be merging attributes? 5743 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 5744 PushNamespaceVisibilityAttr(Attr, Loc); 5745 5746 if (IsStd) 5747 StdNamespace = Namespc; 5748 if (AddToKnown) 5749 KnownNamespaces[Namespc] = false; 5750 5751 if (II) { 5752 PushOnScopeChains(Namespc, DeclRegionScope); 5753 } else { 5754 // Link the anonymous namespace into its parent. 5755 DeclContext *Parent = CurContext->getRedeclContext(); 5756 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 5757 TU->setAnonymousNamespace(Namespc); 5758 } else { 5759 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 5760 } 5761 5762 CurContext->addDecl(Namespc); 5763 5764 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 5765 // behaves as if it were replaced by 5766 // namespace unique { /* empty body */ } 5767 // using namespace unique; 5768 // namespace unique { namespace-body } 5769 // where all occurrences of 'unique' in a translation unit are 5770 // replaced by the same identifier and this identifier differs 5771 // from all other identifiers in the entire program. 5772 5773 // We just create the namespace with an empty name and then add an 5774 // implicit using declaration, just like the standard suggests. 5775 // 5776 // CodeGen enforces the "universally unique" aspect by giving all 5777 // declarations semantically contained within an anonymous 5778 // namespace internal linkage. 5779 5780 if (!PrevNS) { 5781 UsingDirectiveDecl* UD 5782 = UsingDirectiveDecl::Create(Context, CurContext, 5783 /* 'using' */ LBrace, 5784 /* 'namespace' */ SourceLocation(), 5785 /* qualifier */ NestedNameSpecifierLoc(), 5786 /* identifier */ SourceLocation(), 5787 Namespc, 5788 /* Ancestor */ CurContext); 5789 UD->setImplicit(); 5790 CurContext->addDecl(UD); 5791 } 5792 } 5793 5794 // Although we could have an invalid decl (i.e. the namespace name is a 5795 // redefinition), push it as current DeclContext and try to continue parsing. 5796 // FIXME: We should be able to push Namespc here, so that the each DeclContext 5797 // for the namespace has the declarations that showed up in that particular 5798 // namespace definition. 5799 PushDeclContext(NamespcScope, Namespc); 5800 return Namespc; 5801} 5802 5803/// getNamespaceDecl - Returns the namespace a decl represents. If the decl 5804/// is a namespace alias, returns the namespace it points to. 5805static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 5806 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 5807 return AD->getNamespace(); 5808 return dyn_cast_or_null<NamespaceDecl>(D); 5809} 5810 5811/// ActOnFinishNamespaceDef - This callback is called after a namespace is 5812/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 5813void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 5814 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 5815 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 5816 Namespc->setRBraceLoc(RBrace); 5817 PopDeclContext(); 5818 if (Namespc->hasAttr<VisibilityAttr>()) 5819 PopPragmaVisibility(true, RBrace); 5820} 5821 5822CXXRecordDecl *Sema::getStdBadAlloc() const { 5823 return cast_or_null<CXXRecordDecl>( 5824 StdBadAlloc.get(Context.getExternalSource())); 5825} 5826 5827NamespaceDecl *Sema::getStdNamespace() const { 5828 return cast_or_null<NamespaceDecl>( 5829 StdNamespace.get(Context.getExternalSource())); 5830} 5831 5832/// \brief Retrieve the special "std" namespace, which may require us to 5833/// implicitly define the namespace. 5834NamespaceDecl *Sema::getOrCreateStdNamespace() { 5835 if (!StdNamespace) { 5836 // The "std" namespace has not yet been defined, so build one implicitly. 5837 StdNamespace = NamespaceDecl::Create(Context, 5838 Context.getTranslationUnitDecl(), 5839 /*Inline=*/false, 5840 SourceLocation(), SourceLocation(), 5841 &PP.getIdentifierTable().get("std"), 5842 /*PrevDecl=*/0); 5843 getStdNamespace()->setImplicit(true); 5844 } 5845 5846 return getStdNamespace(); 5847} 5848 5849bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 5850 assert(getLangOptions().CPlusPlus && 5851 "Looking for std::initializer_list outside of C++."); 5852 5853 // We're looking for implicit instantiations of 5854 // template <typename E> class std::initializer_list. 5855 5856 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 5857 return false; 5858 5859 ClassTemplateDecl *Template = 0; 5860 const TemplateArgument *Arguments = 0; 5861 5862 if (const RecordType *RT = Ty->getAs<RecordType>()) { 5863 5864 ClassTemplateSpecializationDecl *Specialization = 5865 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 5866 if (!Specialization) 5867 return false; 5868 5869 Template = Specialization->getSpecializedTemplate(); 5870 Arguments = Specialization->getTemplateArgs().data(); 5871 } else if (const TemplateSpecializationType *TST = 5872 Ty->getAs<TemplateSpecializationType>()) { 5873 Template = dyn_cast_or_null<ClassTemplateDecl>( 5874 TST->getTemplateName().getAsTemplateDecl()); 5875 Arguments = TST->getArgs(); 5876 } 5877 if (!Template) 5878 return false; 5879 5880 if (!StdInitializerList) { 5881 // Haven't recognized std::initializer_list yet, maybe this is it. 5882 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 5883 if (TemplateClass->getIdentifier() != 5884 &PP.getIdentifierTable().get("initializer_list") || 5885 !getStdNamespace()->InEnclosingNamespaceSetOf( 5886 TemplateClass->getDeclContext())) 5887 return false; 5888 // This is a template called std::initializer_list, but is it the right 5889 // template? 5890 TemplateParameterList *Params = Template->getTemplateParameters(); 5891 if (Params->getMinRequiredArguments() != 1) 5892 return false; 5893 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 5894 return false; 5895 5896 // It's the right template. 5897 StdInitializerList = Template; 5898 } 5899 5900 if (Template != StdInitializerList) 5901 return false; 5902 5903 // This is an instance of std::initializer_list. Find the argument type. 5904 if (Element) 5905 *Element = Arguments[0].getAsType(); 5906 return true; 5907} 5908 5909static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 5910 NamespaceDecl *Std = S.getStdNamespace(); 5911 if (!Std) { 5912 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 5913 return 0; 5914 } 5915 5916 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 5917 Loc, Sema::LookupOrdinaryName); 5918 if (!S.LookupQualifiedName(Result, Std)) { 5919 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 5920 return 0; 5921 } 5922 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 5923 if (!Template) { 5924 Result.suppressDiagnostics(); 5925 // We found something weird. Complain about the first thing we found. 5926 NamedDecl *Found = *Result.begin(); 5927 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 5928 return 0; 5929 } 5930 5931 // We found some template called std::initializer_list. Now verify that it's 5932 // correct. 5933 TemplateParameterList *Params = Template->getTemplateParameters(); 5934 if (Params->getMinRequiredArguments() != 1 || 5935 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 5936 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 5937 return 0; 5938 } 5939 5940 return Template; 5941} 5942 5943QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 5944 if (!StdInitializerList) { 5945 StdInitializerList = LookupStdInitializerList(*this, Loc); 5946 if (!StdInitializerList) 5947 return QualType(); 5948 } 5949 5950 TemplateArgumentListInfo Args(Loc, Loc); 5951 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 5952 Context.getTrivialTypeSourceInfo(Element, 5953 Loc))); 5954 return Context.getCanonicalType( 5955 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 5956} 5957 5958bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) { 5959 // C++ [dcl.init.list]p2: 5960 // A constructor is an initializer-list constructor if its first parameter 5961 // is of type std::initializer_list<E> or reference to possibly cv-qualified 5962 // std::initializer_list<E> for some type E, and either there are no other 5963 // parameters or else all other parameters have default arguments. 5964 if (Ctor->getNumParams() < 1 || 5965 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 5966 return false; 5967 5968 QualType ArgType = Ctor->getParamDecl(0)->getType(); 5969 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 5970 ArgType = RT->getPointeeType().getUnqualifiedType(); 5971 5972 return isStdInitializerList(ArgType, 0); 5973} 5974 5975/// \brief Determine whether a using statement is in a context where it will be 5976/// apply in all contexts. 5977static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 5978 switch (CurContext->getDeclKind()) { 5979 case Decl::TranslationUnit: 5980 return true; 5981 case Decl::LinkageSpec: 5982 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 5983 default: 5984 return false; 5985 } 5986} 5987 5988namespace { 5989 5990// Callback to only accept typo corrections that are namespaces. 5991class NamespaceValidatorCCC : public CorrectionCandidateCallback { 5992 public: 5993 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 5994 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 5995 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 5996 } 5997 return false; 5998 } 5999}; 6000 6001} 6002 6003static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 6004 CXXScopeSpec &SS, 6005 SourceLocation IdentLoc, 6006 IdentifierInfo *Ident) { 6007 NamespaceValidatorCCC Validator; 6008 R.clear(); 6009 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(), 6010 R.getLookupKind(), Sc, &SS, 6011 Validator)) { 6012 std::string CorrectedStr(Corrected.getAsString(S.getLangOptions())); 6013 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOptions())); 6014 if (DeclContext *DC = S.computeDeclContext(SS, false)) 6015 S.Diag(IdentLoc, diag::err_using_directive_member_suggest) 6016 << Ident << DC << CorrectedQuotedStr << SS.getRange() 6017 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr); 6018 else 6019 S.Diag(IdentLoc, diag::err_using_directive_suggest) 6020 << Ident << CorrectedQuotedStr 6021 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr); 6022 6023 S.Diag(Corrected.getCorrectionDecl()->getLocation(), 6024 diag::note_namespace_defined_here) << CorrectedQuotedStr; 6025 6026 Ident = Corrected.getCorrectionAsIdentifierInfo(); 6027 R.addDecl(Corrected.getCorrectionDecl()); 6028 return true; 6029 } 6030 return false; 6031} 6032 6033Decl *Sema::ActOnUsingDirective(Scope *S, 6034 SourceLocation UsingLoc, 6035 SourceLocation NamespcLoc, 6036 CXXScopeSpec &SS, 6037 SourceLocation IdentLoc, 6038 IdentifierInfo *NamespcName, 6039 AttributeList *AttrList) { 6040 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 6041 assert(NamespcName && "Invalid NamespcName."); 6042 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 6043 6044 // This can only happen along a recovery path. 6045 while (S->getFlags() & Scope::TemplateParamScope) 6046 S = S->getParent(); 6047 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 6048 6049 UsingDirectiveDecl *UDir = 0; 6050 NestedNameSpecifier *Qualifier = 0; 6051 if (SS.isSet()) 6052 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 6053 6054 // Lookup namespace name. 6055 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 6056 LookupParsedName(R, S, &SS); 6057 if (R.isAmbiguous()) 6058 return 0; 6059 6060 if (R.empty()) { 6061 R.clear(); 6062 // Allow "using namespace std;" or "using namespace ::std;" even if 6063 // "std" hasn't been defined yet, for GCC compatibility. 6064 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 6065 NamespcName->isStr("std")) { 6066 Diag(IdentLoc, diag::ext_using_undefined_std); 6067 R.addDecl(getOrCreateStdNamespace()); 6068 R.resolveKind(); 6069 } 6070 // Otherwise, attempt typo correction. 6071 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 6072 } 6073 6074 if (!R.empty()) { 6075 NamedDecl *Named = R.getFoundDecl(); 6076 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named)) 6077 && "expected namespace decl"); 6078 // C++ [namespace.udir]p1: 6079 // A using-directive specifies that the names in the nominated 6080 // namespace can be used in the scope in which the 6081 // using-directive appears after the using-directive. During 6082 // unqualified name lookup (3.4.1), the names appear as if they 6083 // were declared in the nearest enclosing namespace which 6084 // contains both the using-directive and the nominated 6085 // namespace. [Note: in this context, "contains" means "contains 6086 // directly or indirectly". ] 6087 6088 // Find enclosing context containing both using-directive and 6089 // nominated namespace. 6090 NamespaceDecl *NS = getNamespaceDecl(Named); 6091 DeclContext *CommonAncestor = cast<DeclContext>(NS); 6092 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 6093 CommonAncestor = CommonAncestor->getParent(); 6094 6095 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 6096 SS.getWithLocInContext(Context), 6097 IdentLoc, Named, CommonAncestor); 6098 6099 if (IsUsingDirectiveInToplevelContext(CurContext) && 6100 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 6101 Diag(IdentLoc, diag::warn_using_directive_in_header); 6102 } 6103 6104 PushUsingDirective(S, UDir); 6105 } else { 6106 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 6107 } 6108 6109 // FIXME: We ignore attributes for now. 6110 return UDir; 6111} 6112 6113void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 6114 // If scope has associated entity, then using directive is at namespace 6115 // or translation unit scope. We add UsingDirectiveDecls, into 6116 // it's lookup structure. 6117 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) 6118 Ctx->addDecl(UDir); 6119 else 6120 // Otherwise it is block-sope. using-directives will affect lookup 6121 // only to the end of scope. 6122 S->PushUsingDirective(UDir); 6123} 6124 6125 6126Decl *Sema::ActOnUsingDeclaration(Scope *S, 6127 AccessSpecifier AS, 6128 bool HasUsingKeyword, 6129 SourceLocation UsingLoc, 6130 CXXScopeSpec &SS, 6131 UnqualifiedId &Name, 6132 AttributeList *AttrList, 6133 bool IsTypeName, 6134 SourceLocation TypenameLoc) { 6135 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 6136 6137 switch (Name.getKind()) { 6138 case UnqualifiedId::IK_ImplicitSelfParam: 6139 case UnqualifiedId::IK_Identifier: 6140 case UnqualifiedId::IK_OperatorFunctionId: 6141 case UnqualifiedId::IK_LiteralOperatorId: 6142 case UnqualifiedId::IK_ConversionFunctionId: 6143 break; 6144 6145 case UnqualifiedId::IK_ConstructorName: 6146 case UnqualifiedId::IK_ConstructorTemplateId: 6147 // C++0x inherited constructors. 6148 Diag(Name.getSourceRange().getBegin(), 6149 getLangOptions().CPlusPlus0x ? 6150 diag::warn_cxx98_compat_using_decl_constructor : 6151 diag::err_using_decl_constructor) 6152 << SS.getRange(); 6153 6154 if (getLangOptions().CPlusPlus0x) break; 6155 6156 return 0; 6157 6158 case UnqualifiedId::IK_DestructorName: 6159 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor) 6160 << SS.getRange(); 6161 return 0; 6162 6163 case UnqualifiedId::IK_TemplateId: 6164 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id) 6165 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 6166 return 0; 6167 } 6168 6169 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 6170 DeclarationName TargetName = TargetNameInfo.getName(); 6171 if (!TargetName) 6172 return 0; 6173 6174 // Warn about using declarations. 6175 // TODO: store that the declaration was written without 'using' and 6176 // talk about access decls instead of using decls in the 6177 // diagnostics. 6178 if (!HasUsingKeyword) { 6179 UsingLoc = Name.getSourceRange().getBegin(); 6180 6181 Diag(UsingLoc, diag::warn_access_decl_deprecated) 6182 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 6183 } 6184 6185 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 6186 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 6187 return 0; 6188 6189 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 6190 TargetNameInfo, AttrList, 6191 /* IsInstantiation */ false, 6192 IsTypeName, TypenameLoc); 6193 if (UD) 6194 PushOnScopeChains(UD, S, /*AddToContext*/ false); 6195 6196 return UD; 6197} 6198 6199/// \brief Determine whether a using declaration considers the given 6200/// declarations as "equivalent", e.g., if they are redeclarations of 6201/// the same entity or are both typedefs of the same type. 6202static bool 6203IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2, 6204 bool &SuppressRedeclaration) { 6205 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) { 6206 SuppressRedeclaration = false; 6207 return true; 6208 } 6209 6210 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 6211 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) { 6212 SuppressRedeclaration = true; 6213 return Context.hasSameType(TD1->getUnderlyingType(), 6214 TD2->getUnderlyingType()); 6215 } 6216 6217 return false; 6218} 6219 6220 6221/// Determines whether to create a using shadow decl for a particular 6222/// decl, given the set of decls existing prior to this using lookup. 6223bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 6224 const LookupResult &Previous) { 6225 // Diagnose finding a decl which is not from a base class of the 6226 // current class. We do this now because there are cases where this 6227 // function will silently decide not to build a shadow decl, which 6228 // will pre-empt further diagnostics. 6229 // 6230 // We don't need to do this in C++0x because we do the check once on 6231 // the qualifier. 6232 // 6233 // FIXME: diagnose the following if we care enough: 6234 // struct A { int foo; }; 6235 // struct B : A { using A::foo; }; 6236 // template <class T> struct C : A {}; 6237 // template <class T> struct D : C<T> { using B::foo; } // <--- 6238 // This is invalid (during instantiation) in C++03 because B::foo 6239 // resolves to the using decl in B, which is not a base class of D<T>. 6240 // We can't diagnose it immediately because C<T> is an unknown 6241 // specialization. The UsingShadowDecl in D<T> then points directly 6242 // to A::foo, which will look well-formed when we instantiate. 6243 // The right solution is to not collapse the shadow-decl chain. 6244 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) { 6245 DeclContext *OrigDC = Orig->getDeclContext(); 6246 6247 // Handle enums and anonymous structs. 6248 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 6249 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 6250 while (OrigRec->isAnonymousStructOrUnion()) 6251 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 6252 6253 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 6254 if (OrigDC == CurContext) { 6255 Diag(Using->getLocation(), 6256 diag::err_using_decl_nested_name_specifier_is_current_class) 6257 << Using->getQualifierLoc().getSourceRange(); 6258 Diag(Orig->getLocation(), diag::note_using_decl_target); 6259 return true; 6260 } 6261 6262 Diag(Using->getQualifierLoc().getBeginLoc(), 6263 diag::err_using_decl_nested_name_specifier_is_not_base_class) 6264 << Using->getQualifier() 6265 << cast<CXXRecordDecl>(CurContext) 6266 << Using->getQualifierLoc().getSourceRange(); 6267 Diag(Orig->getLocation(), diag::note_using_decl_target); 6268 return true; 6269 } 6270 } 6271 6272 if (Previous.empty()) return false; 6273 6274 NamedDecl *Target = Orig; 6275 if (isa<UsingShadowDecl>(Target)) 6276 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 6277 6278 // If the target happens to be one of the previous declarations, we 6279 // don't have a conflict. 6280 // 6281 // FIXME: but we might be increasing its access, in which case we 6282 // should redeclare it. 6283 NamedDecl *NonTag = 0, *Tag = 0; 6284 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 6285 I != E; ++I) { 6286 NamedDecl *D = (*I)->getUnderlyingDecl(); 6287 bool Result; 6288 if (IsEquivalentForUsingDecl(Context, D, Target, Result)) 6289 return Result; 6290 6291 (isa<TagDecl>(D) ? Tag : NonTag) = D; 6292 } 6293 6294 if (Target->isFunctionOrFunctionTemplate()) { 6295 FunctionDecl *FD; 6296 if (isa<FunctionTemplateDecl>(Target)) 6297 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl(); 6298 else 6299 FD = cast<FunctionDecl>(Target); 6300 6301 NamedDecl *OldDecl = 0; 6302 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) { 6303 case Ovl_Overload: 6304 return false; 6305 6306 case Ovl_NonFunction: 6307 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6308 break; 6309 6310 // We found a decl with the exact signature. 6311 case Ovl_Match: 6312 // If we're in a record, we want to hide the target, so we 6313 // return true (without a diagnostic) to tell the caller not to 6314 // build a shadow decl. 6315 if (CurContext->isRecord()) 6316 return true; 6317 6318 // If we're not in a record, this is an error. 6319 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6320 break; 6321 } 6322 6323 Diag(Target->getLocation(), diag::note_using_decl_target); 6324 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 6325 return true; 6326 } 6327 6328 // Target is not a function. 6329 6330 if (isa<TagDecl>(Target)) { 6331 // No conflict between a tag and a non-tag. 6332 if (!Tag) return false; 6333 6334 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6335 Diag(Target->getLocation(), diag::note_using_decl_target); 6336 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 6337 return true; 6338 } 6339 6340 // No conflict between a tag and a non-tag. 6341 if (!NonTag) return false; 6342 6343 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6344 Diag(Target->getLocation(), diag::note_using_decl_target); 6345 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 6346 return true; 6347} 6348 6349/// Builds a shadow declaration corresponding to a 'using' declaration. 6350UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 6351 UsingDecl *UD, 6352 NamedDecl *Orig) { 6353 6354 // If we resolved to another shadow declaration, just coalesce them. 6355 NamedDecl *Target = Orig; 6356 if (isa<UsingShadowDecl>(Target)) { 6357 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 6358 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 6359 } 6360 6361 UsingShadowDecl *Shadow 6362 = UsingShadowDecl::Create(Context, CurContext, 6363 UD->getLocation(), UD, Target); 6364 UD->addShadowDecl(Shadow); 6365 6366 Shadow->setAccess(UD->getAccess()); 6367 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 6368 Shadow->setInvalidDecl(); 6369 6370 if (S) 6371 PushOnScopeChains(Shadow, S); 6372 else 6373 CurContext->addDecl(Shadow); 6374 6375 6376 return Shadow; 6377} 6378 6379/// Hides a using shadow declaration. This is required by the current 6380/// using-decl implementation when a resolvable using declaration in a 6381/// class is followed by a declaration which would hide or override 6382/// one or more of the using decl's targets; for example: 6383/// 6384/// struct Base { void foo(int); }; 6385/// struct Derived : Base { 6386/// using Base::foo; 6387/// void foo(int); 6388/// }; 6389/// 6390/// The governing language is C++03 [namespace.udecl]p12: 6391/// 6392/// When a using-declaration brings names from a base class into a 6393/// derived class scope, member functions in the derived class 6394/// override and/or hide member functions with the same name and 6395/// parameter types in a base class (rather than conflicting). 6396/// 6397/// There are two ways to implement this: 6398/// (1) optimistically create shadow decls when they're not hidden 6399/// by existing declarations, or 6400/// (2) don't create any shadow decls (or at least don't make them 6401/// visible) until we've fully parsed/instantiated the class. 6402/// The problem with (1) is that we might have to retroactively remove 6403/// a shadow decl, which requires several O(n) operations because the 6404/// decl structures are (very reasonably) not designed for removal. 6405/// (2) avoids this but is very fiddly and phase-dependent. 6406void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 6407 if (Shadow->getDeclName().getNameKind() == 6408 DeclarationName::CXXConversionFunctionName) 6409 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 6410 6411 // Remove it from the DeclContext... 6412 Shadow->getDeclContext()->removeDecl(Shadow); 6413 6414 // ...and the scope, if applicable... 6415 if (S) { 6416 S->RemoveDecl(Shadow); 6417 IdResolver.RemoveDecl(Shadow); 6418 } 6419 6420 // ...and the using decl. 6421 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 6422 6423 // TODO: complain somehow if Shadow was used. It shouldn't 6424 // be possible for this to happen, because...? 6425} 6426 6427/// Builds a using declaration. 6428/// 6429/// \param IsInstantiation - Whether this call arises from an 6430/// instantiation of an unresolved using declaration. We treat 6431/// the lookup differently for these declarations. 6432NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 6433 SourceLocation UsingLoc, 6434 CXXScopeSpec &SS, 6435 const DeclarationNameInfo &NameInfo, 6436 AttributeList *AttrList, 6437 bool IsInstantiation, 6438 bool IsTypeName, 6439 SourceLocation TypenameLoc) { 6440 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 6441 SourceLocation IdentLoc = NameInfo.getLoc(); 6442 assert(IdentLoc.isValid() && "Invalid TargetName location."); 6443 6444 // FIXME: We ignore attributes for now. 6445 6446 if (SS.isEmpty()) { 6447 Diag(IdentLoc, diag::err_using_requires_qualname); 6448 return 0; 6449 } 6450 6451 // Do the redeclaration lookup in the current scope. 6452 LookupResult Previous(*this, NameInfo, LookupUsingDeclName, 6453 ForRedeclaration); 6454 Previous.setHideTags(false); 6455 if (S) { 6456 LookupName(Previous, S); 6457 6458 // It is really dumb that we have to do this. 6459 LookupResult::Filter F = Previous.makeFilter(); 6460 while (F.hasNext()) { 6461 NamedDecl *D = F.next(); 6462 if (!isDeclInScope(D, CurContext, S)) 6463 F.erase(); 6464 } 6465 F.done(); 6466 } else { 6467 assert(IsInstantiation && "no scope in non-instantiation"); 6468 assert(CurContext->isRecord() && "scope not record in instantiation"); 6469 LookupQualifiedName(Previous, CurContext); 6470 } 6471 6472 // Check for invalid redeclarations. 6473 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous)) 6474 return 0; 6475 6476 // Check for bad qualifiers. 6477 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc)) 6478 return 0; 6479 6480 DeclContext *LookupContext = computeDeclContext(SS); 6481 NamedDecl *D; 6482 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 6483 if (!LookupContext) { 6484 if (IsTypeName) { 6485 // FIXME: not all declaration name kinds are legal here 6486 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 6487 UsingLoc, TypenameLoc, 6488 QualifierLoc, 6489 IdentLoc, NameInfo.getName()); 6490 } else { 6491 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 6492 QualifierLoc, NameInfo); 6493 } 6494 } else { 6495 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 6496 NameInfo, IsTypeName); 6497 } 6498 D->setAccess(AS); 6499 CurContext->addDecl(D); 6500 6501 if (!LookupContext) return D; 6502 UsingDecl *UD = cast<UsingDecl>(D); 6503 6504 if (RequireCompleteDeclContext(SS, LookupContext)) { 6505 UD->setInvalidDecl(); 6506 return UD; 6507 } 6508 6509 // Constructor inheriting using decls get special treatment. 6510 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) { 6511 if (CheckInheritedConstructorUsingDecl(UD)) 6512 UD->setInvalidDecl(); 6513 return UD; 6514 } 6515 6516 // Otherwise, look up the target name. 6517 6518 LookupResult R(*this, NameInfo, LookupOrdinaryName); 6519 6520 // Unlike most lookups, we don't always want to hide tag 6521 // declarations: tag names are visible through the using declaration 6522 // even if hidden by ordinary names, *except* in a dependent context 6523 // where it's important for the sanity of two-phase lookup. 6524 if (!IsInstantiation) 6525 R.setHideTags(false); 6526 6527 LookupQualifiedName(R, LookupContext); 6528 6529 if (R.empty()) { 6530 Diag(IdentLoc, diag::err_no_member) 6531 << NameInfo.getName() << LookupContext << SS.getRange(); 6532 UD->setInvalidDecl(); 6533 return UD; 6534 } 6535 6536 if (R.isAmbiguous()) { 6537 UD->setInvalidDecl(); 6538 return UD; 6539 } 6540 6541 if (IsTypeName) { 6542 // If we asked for a typename and got a non-type decl, error out. 6543 if (!R.getAsSingle<TypeDecl>()) { 6544 Diag(IdentLoc, diag::err_using_typename_non_type); 6545 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 6546 Diag((*I)->getUnderlyingDecl()->getLocation(), 6547 diag::note_using_decl_target); 6548 UD->setInvalidDecl(); 6549 return UD; 6550 } 6551 } else { 6552 // If we asked for a non-typename and we got a type, error out, 6553 // but only if this is an instantiation of an unresolved using 6554 // decl. Otherwise just silently find the type name. 6555 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 6556 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 6557 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 6558 UD->setInvalidDecl(); 6559 return UD; 6560 } 6561 } 6562 6563 // C++0x N2914 [namespace.udecl]p6: 6564 // A using-declaration shall not name a namespace. 6565 if (R.getAsSingle<NamespaceDecl>()) { 6566 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 6567 << SS.getRange(); 6568 UD->setInvalidDecl(); 6569 return UD; 6570 } 6571 6572 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 6573 if (!CheckUsingShadowDecl(UD, *I, Previous)) 6574 BuildUsingShadowDecl(S, UD, *I); 6575 } 6576 6577 return UD; 6578} 6579 6580/// Additional checks for a using declaration referring to a constructor name. 6581bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) { 6582 if (UD->isTypeName()) { 6583 // FIXME: Cannot specify typename when specifying constructor 6584 return true; 6585 } 6586 6587 const Type *SourceType = UD->getQualifier()->getAsType(); 6588 assert(SourceType && 6589 "Using decl naming constructor doesn't have type in scope spec."); 6590 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 6591 6592 // Check whether the named type is a direct base class. 6593 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified(); 6594 CXXRecordDecl::base_class_iterator BaseIt, BaseE; 6595 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end(); 6596 BaseIt != BaseE; ++BaseIt) { 6597 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified(); 6598 if (CanonicalSourceType == BaseType) 6599 break; 6600 } 6601 6602 if (BaseIt == BaseE) { 6603 // Did not find SourceType in the bases. 6604 Diag(UD->getUsingLocation(), 6605 diag::err_using_decl_constructor_not_in_direct_base) 6606 << UD->getNameInfo().getSourceRange() 6607 << QualType(SourceType, 0) << TargetClass; 6608 return true; 6609 } 6610 6611 BaseIt->setInheritConstructors(); 6612 6613 return false; 6614} 6615 6616/// Checks that the given using declaration is not an invalid 6617/// redeclaration. Note that this is checking only for the using decl 6618/// itself, not for any ill-formedness among the UsingShadowDecls. 6619bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 6620 bool isTypeName, 6621 const CXXScopeSpec &SS, 6622 SourceLocation NameLoc, 6623 const LookupResult &Prev) { 6624 // C++03 [namespace.udecl]p8: 6625 // C++0x [namespace.udecl]p10: 6626 // A using-declaration is a declaration and can therefore be used 6627 // repeatedly where (and only where) multiple declarations are 6628 // allowed. 6629 // 6630 // That's in non-member contexts. 6631 if (!CurContext->getRedeclContext()->isRecord()) 6632 return false; 6633 6634 NestedNameSpecifier *Qual 6635 = static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 6636 6637 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 6638 NamedDecl *D = *I; 6639 6640 bool DTypename; 6641 NestedNameSpecifier *DQual; 6642 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 6643 DTypename = UD->isTypeName(); 6644 DQual = UD->getQualifier(); 6645 } else if (UnresolvedUsingValueDecl *UD 6646 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 6647 DTypename = false; 6648 DQual = UD->getQualifier(); 6649 } else if (UnresolvedUsingTypenameDecl *UD 6650 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 6651 DTypename = true; 6652 DQual = UD->getQualifier(); 6653 } else continue; 6654 6655 // using decls differ if one says 'typename' and the other doesn't. 6656 // FIXME: non-dependent using decls? 6657 if (isTypeName != DTypename) continue; 6658 6659 // using decls differ if they name different scopes (but note that 6660 // template instantiation can cause this check to trigger when it 6661 // didn't before instantiation). 6662 if (Context.getCanonicalNestedNameSpecifier(Qual) != 6663 Context.getCanonicalNestedNameSpecifier(DQual)) 6664 continue; 6665 6666 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 6667 Diag(D->getLocation(), diag::note_using_decl) << 1; 6668 return true; 6669 } 6670 6671 return false; 6672} 6673 6674 6675/// Checks that the given nested-name qualifier used in a using decl 6676/// in the current context is appropriately related to the current 6677/// scope. If an error is found, diagnoses it and returns true. 6678bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 6679 const CXXScopeSpec &SS, 6680 SourceLocation NameLoc) { 6681 DeclContext *NamedContext = computeDeclContext(SS); 6682 6683 if (!CurContext->isRecord()) { 6684 // C++03 [namespace.udecl]p3: 6685 // C++0x [namespace.udecl]p8: 6686 // A using-declaration for a class member shall be a member-declaration. 6687 6688 // If we weren't able to compute a valid scope, it must be a 6689 // dependent class scope. 6690 if (!NamedContext || NamedContext->isRecord()) { 6691 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 6692 << SS.getRange(); 6693 return true; 6694 } 6695 6696 // Otherwise, everything is known to be fine. 6697 return false; 6698 } 6699 6700 // The current scope is a record. 6701 6702 // If the named context is dependent, we can't decide much. 6703 if (!NamedContext) { 6704 // FIXME: in C++0x, we can diagnose if we can prove that the 6705 // nested-name-specifier does not refer to a base class, which is 6706 // still possible in some cases. 6707 6708 // Otherwise we have to conservatively report that things might be 6709 // okay. 6710 return false; 6711 } 6712 6713 if (!NamedContext->isRecord()) { 6714 // Ideally this would point at the last name in the specifier, 6715 // but we don't have that level of source info. 6716 Diag(SS.getRange().getBegin(), 6717 diag::err_using_decl_nested_name_specifier_is_not_class) 6718 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange(); 6719 return true; 6720 } 6721 6722 if (!NamedContext->isDependentContext() && 6723 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 6724 return true; 6725 6726 if (getLangOptions().CPlusPlus0x) { 6727 // C++0x [namespace.udecl]p3: 6728 // In a using-declaration used as a member-declaration, the 6729 // nested-name-specifier shall name a base class of the class 6730 // being defined. 6731 6732 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 6733 cast<CXXRecordDecl>(NamedContext))) { 6734 if (CurContext == NamedContext) { 6735 Diag(NameLoc, 6736 diag::err_using_decl_nested_name_specifier_is_current_class) 6737 << SS.getRange(); 6738 return true; 6739 } 6740 6741 Diag(SS.getRange().getBegin(), 6742 diag::err_using_decl_nested_name_specifier_is_not_base_class) 6743 << (NestedNameSpecifier*) SS.getScopeRep() 6744 << cast<CXXRecordDecl>(CurContext) 6745 << SS.getRange(); 6746 return true; 6747 } 6748 6749 return false; 6750 } 6751 6752 // C++03 [namespace.udecl]p4: 6753 // A using-declaration used as a member-declaration shall refer 6754 // to a member of a base class of the class being defined [etc.]. 6755 6756 // Salient point: SS doesn't have to name a base class as long as 6757 // lookup only finds members from base classes. Therefore we can 6758 // diagnose here only if we can prove that that can't happen, 6759 // i.e. if the class hierarchies provably don't intersect. 6760 6761 // TODO: it would be nice if "definitely valid" results were cached 6762 // in the UsingDecl and UsingShadowDecl so that these checks didn't 6763 // need to be repeated. 6764 6765 struct UserData { 6766 llvm::DenseSet<const CXXRecordDecl*> Bases; 6767 6768 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) { 6769 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 6770 Data->Bases.insert(Base); 6771 return true; 6772 } 6773 6774 bool hasDependentBases(const CXXRecordDecl *Class) { 6775 return !Class->forallBases(collect, this); 6776 } 6777 6778 /// Returns true if the base is dependent or is one of the 6779 /// accumulated base classes. 6780 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) { 6781 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 6782 return !Data->Bases.count(Base); 6783 } 6784 6785 bool mightShareBases(const CXXRecordDecl *Class) { 6786 return Bases.count(Class) || !Class->forallBases(doesNotContain, this); 6787 } 6788 }; 6789 6790 UserData Data; 6791 6792 // Returns false if we find a dependent base. 6793 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext))) 6794 return false; 6795 6796 // Returns false if the class has a dependent base or if it or one 6797 // of its bases is present in the base set of the current context. 6798 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext))) 6799 return false; 6800 6801 Diag(SS.getRange().getBegin(), 6802 diag::err_using_decl_nested_name_specifier_is_not_base_class) 6803 << (NestedNameSpecifier*) SS.getScopeRep() 6804 << cast<CXXRecordDecl>(CurContext) 6805 << SS.getRange(); 6806 6807 return true; 6808} 6809 6810Decl *Sema::ActOnAliasDeclaration(Scope *S, 6811 AccessSpecifier AS, 6812 MultiTemplateParamsArg TemplateParamLists, 6813 SourceLocation UsingLoc, 6814 UnqualifiedId &Name, 6815 TypeResult Type) { 6816 // Skip up to the relevant declaration scope. 6817 while (S->getFlags() & Scope::TemplateParamScope) 6818 S = S->getParent(); 6819 assert((S->getFlags() & Scope::DeclScope) && 6820 "got alias-declaration outside of declaration scope"); 6821 6822 if (Type.isInvalid()) 6823 return 0; 6824 6825 bool Invalid = false; 6826 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 6827 TypeSourceInfo *TInfo = 0; 6828 GetTypeFromParser(Type.get(), &TInfo); 6829 6830 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 6831 return 0; 6832 6833 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 6834 UPPC_DeclarationType)) { 6835 Invalid = true; 6836 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 6837 TInfo->getTypeLoc().getBeginLoc()); 6838 } 6839 6840 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration); 6841 LookupName(Previous, S); 6842 6843 // Warn about shadowing the name of a template parameter. 6844 if (Previous.isSingleResult() && 6845 Previous.getFoundDecl()->isTemplateParameter()) { 6846 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 6847 Previous.clear(); 6848 } 6849 6850 assert(Name.Kind == UnqualifiedId::IK_Identifier && 6851 "name in alias declaration must be an identifier"); 6852 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 6853 Name.StartLocation, 6854 Name.Identifier, TInfo); 6855 6856 NewTD->setAccess(AS); 6857 6858 if (Invalid) 6859 NewTD->setInvalidDecl(); 6860 6861 CheckTypedefForVariablyModifiedType(S, NewTD); 6862 Invalid |= NewTD->isInvalidDecl(); 6863 6864 bool Redeclaration = false; 6865 6866 NamedDecl *NewND; 6867 if (TemplateParamLists.size()) { 6868 TypeAliasTemplateDecl *OldDecl = 0; 6869 TemplateParameterList *OldTemplateParams = 0; 6870 6871 if (TemplateParamLists.size() != 1) { 6872 Diag(UsingLoc, diag::err_alias_template_extra_headers) 6873 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(), 6874 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc()); 6875 } 6876 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0]; 6877 6878 // Only consider previous declarations in the same scope. 6879 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 6880 /*ExplicitInstantiationOrSpecialization*/false); 6881 if (!Previous.empty()) { 6882 Redeclaration = true; 6883 6884 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 6885 if (!OldDecl && !Invalid) { 6886 Diag(UsingLoc, diag::err_redefinition_different_kind) 6887 << Name.Identifier; 6888 6889 NamedDecl *OldD = Previous.getRepresentativeDecl(); 6890 if (OldD->getLocation().isValid()) 6891 Diag(OldD->getLocation(), diag::note_previous_definition); 6892 6893 Invalid = true; 6894 } 6895 6896 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 6897 if (TemplateParameterListsAreEqual(TemplateParams, 6898 OldDecl->getTemplateParameters(), 6899 /*Complain=*/true, 6900 TPL_TemplateMatch)) 6901 OldTemplateParams = OldDecl->getTemplateParameters(); 6902 else 6903 Invalid = true; 6904 6905 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 6906 if (!Invalid && 6907 !Context.hasSameType(OldTD->getUnderlyingType(), 6908 NewTD->getUnderlyingType())) { 6909 // FIXME: The C++0x standard does not clearly say this is ill-formed, 6910 // but we can't reasonably accept it. 6911 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 6912 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 6913 if (OldTD->getLocation().isValid()) 6914 Diag(OldTD->getLocation(), diag::note_previous_definition); 6915 Invalid = true; 6916 } 6917 } 6918 } 6919 6920 // Merge any previous default template arguments into our parameters, 6921 // and check the parameter list. 6922 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 6923 TPC_TypeAliasTemplate)) 6924 return 0; 6925 6926 TypeAliasTemplateDecl *NewDecl = 6927 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 6928 Name.Identifier, TemplateParams, 6929 NewTD); 6930 6931 NewDecl->setAccess(AS); 6932 6933 if (Invalid) 6934 NewDecl->setInvalidDecl(); 6935 else if (OldDecl) 6936 NewDecl->setPreviousDeclaration(OldDecl); 6937 6938 NewND = NewDecl; 6939 } else { 6940 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 6941 NewND = NewTD; 6942 } 6943 6944 if (!Redeclaration) 6945 PushOnScopeChains(NewND, S); 6946 6947 return NewND; 6948} 6949 6950Decl *Sema::ActOnNamespaceAliasDef(Scope *S, 6951 SourceLocation NamespaceLoc, 6952 SourceLocation AliasLoc, 6953 IdentifierInfo *Alias, 6954 CXXScopeSpec &SS, 6955 SourceLocation IdentLoc, 6956 IdentifierInfo *Ident) { 6957 6958 // Lookup the namespace name. 6959 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 6960 LookupParsedName(R, S, &SS); 6961 6962 // Check if we have a previous declaration with the same name. 6963 NamedDecl *PrevDecl 6964 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName, 6965 ForRedeclaration); 6966 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S)) 6967 PrevDecl = 0; 6968 6969 if (PrevDecl) { 6970 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 6971 // We already have an alias with the same name that points to the same 6972 // namespace, so don't create a new one. 6973 // FIXME: At some point, we'll want to create the (redundant) 6974 // declaration to maintain better source information. 6975 if (!R.isAmbiguous() && !R.empty() && 6976 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl()))) 6977 return 0; 6978 } 6979 6980 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition : 6981 diag::err_redefinition_different_kind; 6982 Diag(AliasLoc, DiagID) << Alias; 6983 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 6984 return 0; 6985 } 6986 6987 if (R.isAmbiguous()) 6988 return 0; 6989 6990 if (R.empty()) { 6991 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 6992 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange(); 6993 return 0; 6994 } 6995 } 6996 6997 NamespaceAliasDecl *AliasDecl = 6998 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 6999 Alias, SS.getWithLocInContext(Context), 7000 IdentLoc, R.getFoundDecl()); 7001 7002 PushOnScopeChains(AliasDecl, S); 7003 return AliasDecl; 7004} 7005 7006namespace { 7007 /// \brief Scoped object used to handle the state changes required in Sema 7008 /// to implicitly define the body of a C++ member function; 7009 class ImplicitlyDefinedFunctionScope { 7010 Sema &S; 7011 Sema::ContextRAII SavedContext; 7012 7013 public: 7014 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method) 7015 : S(S), SavedContext(S, Method) 7016 { 7017 S.PushFunctionScope(); 7018 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated); 7019 } 7020 7021 ~ImplicitlyDefinedFunctionScope() { 7022 S.PopExpressionEvaluationContext(); 7023 S.PopFunctionScopeInfo(); 7024 } 7025 }; 7026} 7027 7028Sema::ImplicitExceptionSpecification 7029Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) { 7030 // C++ [except.spec]p14: 7031 // An implicitly declared special member function (Clause 12) shall have an 7032 // exception-specification. [...] 7033 ImplicitExceptionSpecification ExceptSpec(Context); 7034 if (ClassDecl->isInvalidDecl()) 7035 return ExceptSpec; 7036 7037 // Direct base-class constructors. 7038 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 7039 BEnd = ClassDecl->bases_end(); 7040 B != BEnd; ++B) { 7041 if (B->isVirtual()) // Handled below. 7042 continue; 7043 7044 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 7045 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7046 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 7047 // If this is a deleted function, add it anyway. This might be conformant 7048 // with the standard. This might not. I'm not sure. It might not matter. 7049 if (Constructor) 7050 ExceptSpec.CalledDecl(Constructor); 7051 } 7052 } 7053 7054 // Virtual base-class constructors. 7055 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 7056 BEnd = ClassDecl->vbases_end(); 7057 B != BEnd; ++B) { 7058 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 7059 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7060 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 7061 // If this is a deleted function, add it anyway. This might be conformant 7062 // with the standard. This might not. I'm not sure. It might not matter. 7063 if (Constructor) 7064 ExceptSpec.CalledDecl(Constructor); 7065 } 7066 } 7067 7068 // Field constructors. 7069 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 7070 FEnd = ClassDecl->field_end(); 7071 F != FEnd; ++F) { 7072 if (F->hasInClassInitializer()) { 7073 if (Expr *E = F->getInClassInitializer()) 7074 ExceptSpec.CalledExpr(E); 7075 else if (!F->isInvalidDecl()) 7076 ExceptSpec.SetDelayed(); 7077 } else if (const RecordType *RecordTy 7078 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 7079 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 7080 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 7081 // If this is a deleted function, add it anyway. This might be conformant 7082 // with the standard. This might not. I'm not sure. It might not matter. 7083 // In particular, the problem is that this function never gets called. It 7084 // might just be ill-formed because this function attempts to refer to 7085 // a deleted function here. 7086 if (Constructor) 7087 ExceptSpec.CalledDecl(Constructor); 7088 } 7089 } 7090 7091 return ExceptSpec; 7092} 7093 7094CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 7095 CXXRecordDecl *ClassDecl) { 7096 // C++ [class.ctor]p5: 7097 // A default constructor for a class X is a constructor of class X 7098 // that can be called without an argument. If there is no 7099 // user-declared constructor for class X, a default constructor is 7100 // implicitly declared. An implicitly-declared default constructor 7101 // is an inline public member of its class. 7102 assert(!ClassDecl->hasUserDeclaredConstructor() && 7103 "Should not build implicit default constructor!"); 7104 7105 ImplicitExceptionSpecification Spec = 7106 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl); 7107 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 7108 7109 // Create the actual constructor declaration. 7110 CanQualType ClassType 7111 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 7112 SourceLocation ClassLoc = ClassDecl->getLocation(); 7113 DeclarationName Name 7114 = Context.DeclarationNames.getCXXConstructorName(ClassType); 7115 DeclarationNameInfo NameInfo(Name, ClassLoc); 7116 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 7117 Context, ClassDecl, ClassLoc, NameInfo, 7118 Context.getFunctionType(Context.VoidTy, 0, 0, EPI), /*TInfo=*/0, 7119 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 7120 /*isConstexpr=*/ClassDecl->defaultedDefaultConstructorIsConstexpr() && 7121 getLangOptions().CPlusPlus0x); 7122 DefaultCon->setAccess(AS_public); 7123 DefaultCon->setDefaulted(); 7124 DefaultCon->setImplicit(); 7125 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 7126 7127 // Note that we have declared this constructor. 7128 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 7129 7130 if (Scope *S = getScopeForContext(ClassDecl)) 7131 PushOnScopeChains(DefaultCon, S, false); 7132 ClassDecl->addDecl(DefaultCon); 7133 7134 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 7135 DefaultCon->setDeletedAsWritten(); 7136 7137 return DefaultCon; 7138} 7139 7140void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 7141 CXXConstructorDecl *Constructor) { 7142 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 7143 !Constructor->doesThisDeclarationHaveABody() && 7144 !Constructor->isDeleted()) && 7145 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 7146 7147 CXXRecordDecl *ClassDecl = Constructor->getParent(); 7148 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 7149 7150 ImplicitlyDefinedFunctionScope Scope(*this, Constructor); 7151 DiagnosticErrorTrap Trap(Diags); 7152 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) || 7153 Trap.hasErrorOccurred()) { 7154 Diag(CurrentLocation, diag::note_member_synthesized_at) 7155 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl); 7156 Constructor->setInvalidDecl(); 7157 return; 7158 } 7159 7160 SourceLocation Loc = Constructor->getLocation(); 7161 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc)); 7162 7163 Constructor->setUsed(); 7164 MarkVTableUsed(CurrentLocation, ClassDecl); 7165 7166 if (ASTMutationListener *L = getASTMutationListener()) { 7167 L->CompletedImplicitDefinition(Constructor); 7168 } 7169} 7170 7171/// Get any existing defaulted default constructor for the given class. Do not 7172/// implicitly define one if it does not exist. 7173static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self, 7174 CXXRecordDecl *D) { 7175 ASTContext &Context = Self.Context; 7176 QualType ClassType = Context.getTypeDeclType(D); 7177 DeclarationName ConstructorName 7178 = Context.DeclarationNames.getCXXConstructorName( 7179 Context.getCanonicalType(ClassType.getUnqualifiedType())); 7180 7181 DeclContext::lookup_const_iterator Con, ConEnd; 7182 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName); 7183 Con != ConEnd; ++Con) { 7184 // A function template cannot be defaulted. 7185 if (isa<FunctionTemplateDecl>(*Con)) 7186 continue; 7187 7188 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con); 7189 if (Constructor->isDefaultConstructor()) 7190 return Constructor->isDefaulted() ? Constructor : 0; 7191 } 7192 return 0; 7193} 7194 7195void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 7196 if (!D) return; 7197 AdjustDeclIfTemplate(D); 7198 7199 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D); 7200 CXXConstructorDecl *CtorDecl 7201 = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl); 7202 7203 if (!CtorDecl) return; 7204 7205 // Compute the exception specification for the default constructor. 7206 const FunctionProtoType *CtorTy = 7207 CtorDecl->getType()->castAs<FunctionProtoType>(); 7208 if (CtorTy->getExceptionSpecType() == EST_Delayed) { 7209 ImplicitExceptionSpecification Spec = 7210 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl); 7211 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 7212 assert(EPI.ExceptionSpecType != EST_Delayed); 7213 7214 CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI)); 7215 } 7216 7217 // If the default constructor is explicitly defaulted, checking the exception 7218 // specification is deferred until now. 7219 if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() && 7220 !ClassDecl->isDependentType()) 7221 CheckExplicitlyDefaultedDefaultConstructor(CtorDecl); 7222} 7223 7224void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) { 7225 // We start with an initial pass over the base classes to collect those that 7226 // inherit constructors from. If there are none, we can forgo all further 7227 // processing. 7228 typedef SmallVector<const RecordType *, 4> BasesVector; 7229 BasesVector BasesToInheritFrom; 7230 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(), 7231 BaseE = ClassDecl->bases_end(); 7232 BaseIt != BaseE; ++BaseIt) { 7233 if (BaseIt->getInheritConstructors()) { 7234 QualType Base = BaseIt->getType(); 7235 if (Base->isDependentType()) { 7236 // If we inherit constructors from anything that is dependent, just 7237 // abort processing altogether. We'll get another chance for the 7238 // instantiations. 7239 return; 7240 } 7241 BasesToInheritFrom.push_back(Base->castAs<RecordType>()); 7242 } 7243 } 7244 if (BasesToInheritFrom.empty()) 7245 return; 7246 7247 // Now collect the constructors that we already have in the current class. 7248 // Those take precedence over inherited constructors. 7249 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...] 7250 // unless there is a user-declared constructor with the same signature in 7251 // the class where the using-declaration appears. 7252 llvm::SmallSet<const Type *, 8> ExistingConstructors; 7253 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(), 7254 CtorE = ClassDecl->ctor_end(); 7255 CtorIt != CtorE; ++CtorIt) { 7256 ExistingConstructors.insert( 7257 Context.getCanonicalType(CtorIt->getType()).getTypePtr()); 7258 } 7259 7260 Scope *S = getScopeForContext(ClassDecl); 7261 DeclarationName CreatedCtorName = 7262 Context.DeclarationNames.getCXXConstructorName( 7263 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified()); 7264 7265 // Now comes the true work. 7266 // First, we keep a map from constructor types to the base that introduced 7267 // them. Needed for finding conflicting constructors. We also keep the 7268 // actually inserted declarations in there, for pretty diagnostics. 7269 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo; 7270 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap; 7271 ConstructorToSourceMap InheritedConstructors; 7272 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(), 7273 BaseE = BasesToInheritFrom.end(); 7274 BaseIt != BaseE; ++BaseIt) { 7275 const RecordType *Base = *BaseIt; 7276 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified(); 7277 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl()); 7278 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(), 7279 CtorE = BaseDecl->ctor_end(); 7280 CtorIt != CtorE; ++CtorIt) { 7281 // Find the using declaration for inheriting this base's constructors. 7282 DeclarationName Name = 7283 Context.DeclarationNames.getCXXConstructorName(CanonicalBase); 7284 UsingDecl *UD = dyn_cast_or_null<UsingDecl>( 7285 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName)); 7286 SourceLocation UsingLoc = UD ? UD->getLocation() : 7287 ClassDecl->getLocation(); 7288 7289 // C++0x [class.inhctor]p1: The candidate set of inherited constructors 7290 // from the class X named in the using-declaration consists of actual 7291 // constructors and notional constructors that result from the 7292 // transformation of defaulted parameters as follows: 7293 // - all non-template default constructors of X, and 7294 // - for each non-template constructor of X that has at least one 7295 // parameter with a default argument, the set of constructors that 7296 // results from omitting any ellipsis parameter specification and 7297 // successively omitting parameters with a default argument from the 7298 // end of the parameter-type-list. 7299 CXXConstructorDecl *BaseCtor = *CtorIt; 7300 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor(); 7301 const FunctionProtoType *BaseCtorType = 7302 BaseCtor->getType()->getAs<FunctionProtoType>(); 7303 7304 for (unsigned params = BaseCtor->getMinRequiredArguments(), 7305 maxParams = BaseCtor->getNumParams(); 7306 params <= maxParams; ++params) { 7307 // Skip default constructors. They're never inherited. 7308 if (params == 0) 7309 continue; 7310 // Skip copy and move constructors for the same reason. 7311 if (CanBeCopyOrMove && params == 1) 7312 continue; 7313 7314 // Build up a function type for this particular constructor. 7315 // FIXME: The working paper does not consider that the exception spec 7316 // for the inheriting constructor might be larger than that of the 7317 // source. This code doesn't yet, either. When it does, this code will 7318 // need to be delayed until after exception specifications and in-class 7319 // member initializers are attached. 7320 const Type *NewCtorType; 7321 if (params == maxParams) 7322 NewCtorType = BaseCtorType; 7323 else { 7324 SmallVector<QualType, 16> Args; 7325 for (unsigned i = 0; i < params; ++i) { 7326 Args.push_back(BaseCtorType->getArgType(i)); 7327 } 7328 FunctionProtoType::ExtProtoInfo ExtInfo = 7329 BaseCtorType->getExtProtoInfo(); 7330 ExtInfo.Variadic = false; 7331 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(), 7332 Args.data(), params, ExtInfo) 7333 .getTypePtr(); 7334 } 7335 const Type *CanonicalNewCtorType = 7336 Context.getCanonicalType(NewCtorType); 7337 7338 // Now that we have the type, first check if the class already has a 7339 // constructor with this signature. 7340 if (ExistingConstructors.count(CanonicalNewCtorType)) 7341 continue; 7342 7343 // Then we check if we have already declared an inherited constructor 7344 // with this signature. 7345 std::pair<ConstructorToSourceMap::iterator, bool> result = 7346 InheritedConstructors.insert(std::make_pair( 7347 CanonicalNewCtorType, 7348 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0))); 7349 if (!result.second) { 7350 // Already in the map. If it came from a different class, that's an 7351 // error. Not if it's from the same. 7352 CanQualType PreviousBase = result.first->second.first; 7353 if (CanonicalBase != PreviousBase) { 7354 const CXXConstructorDecl *PrevCtor = result.first->second.second; 7355 const CXXConstructorDecl *PrevBaseCtor = 7356 PrevCtor->getInheritedConstructor(); 7357 assert(PrevBaseCtor && "Conflicting constructor was not inherited"); 7358 7359 Diag(UsingLoc, diag::err_using_decl_constructor_conflict); 7360 Diag(BaseCtor->getLocation(), 7361 diag::note_using_decl_constructor_conflict_current_ctor); 7362 Diag(PrevBaseCtor->getLocation(), 7363 diag::note_using_decl_constructor_conflict_previous_ctor); 7364 Diag(PrevCtor->getLocation(), 7365 diag::note_using_decl_constructor_conflict_previous_using); 7366 } 7367 continue; 7368 } 7369 7370 // OK, we're there, now add the constructor. 7371 // C++0x [class.inhctor]p8: [...] that would be performed by a 7372 // user-written inline constructor [...] 7373 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc); 7374 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create( 7375 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0), 7376 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true, 7377 /*ImplicitlyDeclared=*/true, 7378 // FIXME: Due to a defect in the standard, we treat inherited 7379 // constructors as constexpr even if that makes them ill-formed. 7380 /*Constexpr=*/BaseCtor->isConstexpr()); 7381 NewCtor->setAccess(BaseCtor->getAccess()); 7382 7383 // Build up the parameter decls and add them. 7384 SmallVector<ParmVarDecl *, 16> ParamDecls; 7385 for (unsigned i = 0; i < params; ++i) { 7386 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor, 7387 UsingLoc, UsingLoc, 7388 /*IdentifierInfo=*/0, 7389 BaseCtorType->getArgType(i), 7390 /*TInfo=*/0, SC_None, 7391 SC_None, /*DefaultArg=*/0)); 7392 } 7393 NewCtor->setParams(ParamDecls); 7394 NewCtor->setInheritedConstructor(BaseCtor); 7395 7396 PushOnScopeChains(NewCtor, S, false); 7397 ClassDecl->addDecl(NewCtor); 7398 result.first->second.second = NewCtor; 7399 } 7400 } 7401 } 7402} 7403 7404Sema::ImplicitExceptionSpecification 7405Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) { 7406 // C++ [except.spec]p14: 7407 // An implicitly declared special member function (Clause 12) shall have 7408 // an exception-specification. 7409 ImplicitExceptionSpecification ExceptSpec(Context); 7410 if (ClassDecl->isInvalidDecl()) 7411 return ExceptSpec; 7412 7413 // Direct base-class destructors. 7414 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 7415 BEnd = ClassDecl->bases_end(); 7416 B != BEnd; ++B) { 7417 if (B->isVirtual()) // Handled below. 7418 continue; 7419 7420 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) 7421 ExceptSpec.CalledDecl( 7422 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 7423 } 7424 7425 // Virtual base-class destructors. 7426 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 7427 BEnd = ClassDecl->vbases_end(); 7428 B != BEnd; ++B) { 7429 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) 7430 ExceptSpec.CalledDecl( 7431 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 7432 } 7433 7434 // Field destructors. 7435 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 7436 FEnd = ClassDecl->field_end(); 7437 F != FEnd; ++F) { 7438 if (const RecordType *RecordTy 7439 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) 7440 ExceptSpec.CalledDecl( 7441 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl()))); 7442 } 7443 7444 return ExceptSpec; 7445} 7446 7447CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 7448 // C++ [class.dtor]p2: 7449 // If a class has no user-declared destructor, a destructor is 7450 // declared implicitly. An implicitly-declared destructor is an 7451 // inline public member of its class. 7452 7453 ImplicitExceptionSpecification Spec = 7454 ComputeDefaultedDtorExceptionSpec(ClassDecl); 7455 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 7456 7457 // Create the actual destructor declaration. 7458 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI); 7459 7460 CanQualType ClassType 7461 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 7462 SourceLocation ClassLoc = ClassDecl->getLocation(); 7463 DeclarationName Name 7464 = Context.DeclarationNames.getCXXDestructorName(ClassType); 7465 DeclarationNameInfo NameInfo(Name, ClassLoc); 7466 CXXDestructorDecl *Destructor 7467 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0, 7468 /*isInline=*/true, 7469 /*isImplicitlyDeclared=*/true); 7470 Destructor->setAccess(AS_public); 7471 Destructor->setDefaulted(); 7472 Destructor->setImplicit(); 7473 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 7474 7475 // Note that we have declared this destructor. 7476 ++ASTContext::NumImplicitDestructorsDeclared; 7477 7478 // Introduce this destructor into its scope. 7479 if (Scope *S = getScopeForContext(ClassDecl)) 7480 PushOnScopeChains(Destructor, S, false); 7481 ClassDecl->addDecl(Destructor); 7482 7483 // This could be uniqued if it ever proves significant. 7484 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty)); 7485 7486 if (ShouldDeleteDestructor(Destructor)) 7487 Destructor->setDeletedAsWritten(); 7488 7489 AddOverriddenMethods(ClassDecl, Destructor); 7490 7491 return Destructor; 7492} 7493 7494void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 7495 CXXDestructorDecl *Destructor) { 7496 assert((Destructor->isDefaulted() && 7497 !Destructor->doesThisDeclarationHaveABody()) && 7498 "DefineImplicitDestructor - call it for implicit default dtor"); 7499 CXXRecordDecl *ClassDecl = Destructor->getParent(); 7500 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 7501 7502 if (Destructor->isInvalidDecl()) 7503 return; 7504 7505 ImplicitlyDefinedFunctionScope Scope(*this, Destructor); 7506 7507 DiagnosticErrorTrap Trap(Diags); 7508 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 7509 Destructor->getParent()); 7510 7511 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) { 7512 Diag(CurrentLocation, diag::note_member_synthesized_at) 7513 << CXXDestructor << Context.getTagDeclType(ClassDecl); 7514 7515 Destructor->setInvalidDecl(); 7516 return; 7517 } 7518 7519 SourceLocation Loc = Destructor->getLocation(); 7520 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc)); 7521 Destructor->setImplicitlyDefined(true); 7522 Destructor->setUsed(); 7523 MarkVTableUsed(CurrentLocation, ClassDecl); 7524 7525 if (ASTMutationListener *L = getASTMutationListener()) { 7526 L->CompletedImplicitDefinition(Destructor); 7527 } 7528} 7529 7530void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl, 7531 CXXDestructorDecl *destructor) { 7532 // C++11 [class.dtor]p3: 7533 // A declaration of a destructor that does not have an exception- 7534 // specification is implicitly considered to have the same exception- 7535 // specification as an implicit declaration. 7536 const FunctionProtoType *dtorType = destructor->getType()-> 7537 getAs<FunctionProtoType>(); 7538 if (dtorType->hasExceptionSpec()) 7539 return; 7540 7541 ImplicitExceptionSpecification exceptSpec = 7542 ComputeDefaultedDtorExceptionSpec(classDecl); 7543 7544 // Replace the destructor's type, building off the existing one. Fortunately, 7545 // the only thing of interest in the destructor type is its extended info. 7546 // The return and arguments are fixed. 7547 FunctionProtoType::ExtProtoInfo epi = dtorType->getExtProtoInfo(); 7548 epi.ExceptionSpecType = exceptSpec.getExceptionSpecType(); 7549 epi.NumExceptions = exceptSpec.size(); 7550 epi.Exceptions = exceptSpec.data(); 7551 QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi); 7552 7553 destructor->setType(ty); 7554 7555 // FIXME: If the destructor has a body that could throw, and the newly created 7556 // spec doesn't allow exceptions, we should emit a warning, because this 7557 // change in behavior can break conforming C++03 programs at runtime. 7558 // However, we don't have a body yet, so it needs to be done somewhere else. 7559} 7560 7561/// \brief Builds a statement that copies/moves the given entity from \p From to 7562/// \c To. 7563/// 7564/// This routine is used to copy/move the members of a class with an 7565/// implicitly-declared copy/move assignment operator. When the entities being 7566/// copied are arrays, this routine builds for loops to copy them. 7567/// 7568/// \param S The Sema object used for type-checking. 7569/// 7570/// \param Loc The location where the implicit copy/move is being generated. 7571/// 7572/// \param T The type of the expressions being copied/moved. Both expressions 7573/// must have this type. 7574/// 7575/// \param To The expression we are copying/moving to. 7576/// 7577/// \param From The expression we are copying/moving from. 7578/// 7579/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 7580/// Otherwise, it's a non-static member subobject. 7581/// 7582/// \param Copying Whether we're copying or moving. 7583/// 7584/// \param Depth Internal parameter recording the depth of the recursion. 7585/// 7586/// \returns A statement or a loop that copies the expressions. 7587static StmtResult 7588BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 7589 Expr *To, Expr *From, 7590 bool CopyingBaseSubobject, bool Copying, 7591 unsigned Depth = 0) { 7592 // C++0x [class.copy]p28: 7593 // Each subobject is assigned in the manner appropriate to its type: 7594 // 7595 // - if the subobject is of class type, as if by a call to operator= with 7596 // the subobject as the object expression and the corresponding 7597 // subobject of x as a single function argument (as if by explicit 7598 // qualification; that is, ignoring any possible virtual overriding 7599 // functions in more derived classes); 7600 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 7601 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 7602 7603 // Look for operator=. 7604 DeclarationName Name 7605 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 7606 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 7607 S.LookupQualifiedName(OpLookup, ClassDecl, false); 7608 7609 // Filter out any result that isn't a copy/move-assignment operator. 7610 LookupResult::Filter F = OpLookup.makeFilter(); 7611 while (F.hasNext()) { 7612 NamedDecl *D = F.next(); 7613 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 7614 if (Copying ? Method->isCopyAssignmentOperator() : 7615 Method->isMoveAssignmentOperator()) 7616 continue; 7617 7618 F.erase(); 7619 } 7620 F.done(); 7621 7622 // Suppress the protected check (C++ [class.protected]) for each of the 7623 // assignment operators we found. This strange dance is required when 7624 // we're assigning via a base classes's copy-assignment operator. To 7625 // ensure that we're getting the right base class subobject (without 7626 // ambiguities), we need to cast "this" to that subobject type; to 7627 // ensure that we don't go through the virtual call mechanism, we need 7628 // to qualify the operator= name with the base class (see below). However, 7629 // this means that if the base class has a protected copy assignment 7630 // operator, the protected member access check will fail. So, we 7631 // rewrite "protected" access to "public" access in this case, since we 7632 // know by construction that we're calling from a derived class. 7633 if (CopyingBaseSubobject) { 7634 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 7635 L != LEnd; ++L) { 7636 if (L.getAccess() == AS_protected) 7637 L.setAccess(AS_public); 7638 } 7639 } 7640 7641 // Create the nested-name-specifier that will be used to qualify the 7642 // reference to operator=; this is required to suppress the virtual 7643 // call mechanism. 7644 CXXScopeSpec SS; 7645 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 7646 SS.MakeTrivial(S.Context, 7647 NestedNameSpecifier::Create(S.Context, 0, false, 7648 CanonicalT), 7649 Loc); 7650 7651 // Create the reference to operator=. 7652 ExprResult OpEqualRef 7653 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS, 7654 /*TemplateKWLoc=*/SourceLocation(), 7655 /*FirstQualifierInScope=*/0, 7656 OpLookup, 7657 /*TemplateArgs=*/0, 7658 /*SuppressQualifierCheck=*/true); 7659 if (OpEqualRef.isInvalid()) 7660 return StmtError(); 7661 7662 // Build the call to the assignment operator. 7663 7664 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0, 7665 OpEqualRef.takeAs<Expr>(), 7666 Loc, &From, 1, Loc); 7667 if (Call.isInvalid()) 7668 return StmtError(); 7669 7670 return S.Owned(Call.takeAs<Stmt>()); 7671 } 7672 7673 // - if the subobject is of scalar type, the built-in assignment 7674 // operator is used. 7675 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 7676 if (!ArrayTy) { 7677 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From); 7678 if (Assignment.isInvalid()) 7679 return StmtError(); 7680 7681 return S.Owned(Assignment.takeAs<Stmt>()); 7682 } 7683 7684 // - if the subobject is an array, each element is assigned, in the 7685 // manner appropriate to the element type; 7686 7687 // Construct a loop over the array bounds, e.g., 7688 // 7689 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 7690 // 7691 // that will copy each of the array elements. 7692 QualType SizeType = S.Context.getSizeType(); 7693 7694 // Create the iteration variable. 7695 IdentifierInfo *IterationVarName = 0; 7696 { 7697 SmallString<8> Str; 7698 llvm::raw_svector_ostream OS(Str); 7699 OS << "__i" << Depth; 7700 IterationVarName = &S.Context.Idents.get(OS.str()); 7701 } 7702 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 7703 IterationVarName, SizeType, 7704 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 7705 SC_None, SC_None); 7706 7707 // Initialize the iteration variable to zero. 7708 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 7709 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 7710 7711 // Create a reference to the iteration variable; we'll use this several 7712 // times throughout. 7713 Expr *IterationVarRef 7714 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take(); 7715 assert(IterationVarRef && "Reference to invented variable cannot fail!"); 7716 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take(); 7717 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!"); 7718 7719 // Create the DeclStmt that holds the iteration variable. 7720 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 7721 7722 // Create the comparison against the array bound. 7723 llvm::APInt Upper 7724 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 7725 Expr *Comparison 7726 = new (S.Context) BinaryOperator(IterationVarRefRVal, 7727 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 7728 BO_NE, S.Context.BoolTy, 7729 VK_RValue, OK_Ordinary, Loc); 7730 7731 // Create the pre-increment of the iteration variable. 7732 Expr *Increment 7733 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType, 7734 VK_LValue, OK_Ordinary, Loc); 7735 7736 // Subscript the "from" and "to" expressions with the iteration variable. 7737 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc, 7738 IterationVarRefRVal, 7739 Loc)); 7740 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc, 7741 IterationVarRefRVal, 7742 Loc)); 7743 if (!Copying) // Cast to rvalue 7744 From = CastForMoving(S, From); 7745 7746 // Build the copy/move for an individual element of the array. 7747 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(), 7748 To, From, CopyingBaseSubobject, 7749 Copying, Depth + 1); 7750 if (Copy.isInvalid()) 7751 return StmtError(); 7752 7753 // Construct the loop that copies all elements of this array. 7754 return S.ActOnForStmt(Loc, Loc, InitStmt, 7755 S.MakeFullExpr(Comparison), 7756 0, S.MakeFullExpr(Increment), 7757 Loc, Copy.take()); 7758} 7759 7760std::pair<Sema::ImplicitExceptionSpecification, bool> 7761Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst( 7762 CXXRecordDecl *ClassDecl) { 7763 if (ClassDecl->isInvalidDecl()) 7764 return std::make_pair(ImplicitExceptionSpecification(Context), false); 7765 7766 // C++ [class.copy]p10: 7767 // If the class definition does not explicitly declare a copy 7768 // assignment operator, one is declared implicitly. 7769 // The implicitly-defined copy assignment operator for a class X 7770 // will have the form 7771 // 7772 // X& X::operator=(const X&) 7773 // 7774 // if 7775 bool HasConstCopyAssignment = true; 7776 7777 // -- each direct base class B of X has a copy assignment operator 7778 // whose parameter is of type const B&, const volatile B& or B, 7779 // and 7780 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 7781 BaseEnd = ClassDecl->bases_end(); 7782 HasConstCopyAssignment && Base != BaseEnd; ++Base) { 7783 // We'll handle this below 7784 if (LangOpts.CPlusPlus0x && Base->isVirtual()) 7785 continue; 7786 7787 assert(!Base->getType()->isDependentType() && 7788 "Cannot generate implicit members for class with dependent bases."); 7789 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl(); 7790 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0, 7791 &HasConstCopyAssignment); 7792 } 7793 7794 // In C++11, the above citation has "or virtual" added 7795 if (LangOpts.CPlusPlus0x) { 7796 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 7797 BaseEnd = ClassDecl->vbases_end(); 7798 HasConstCopyAssignment && Base != BaseEnd; ++Base) { 7799 assert(!Base->getType()->isDependentType() && 7800 "Cannot generate implicit members for class with dependent bases."); 7801 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl(); 7802 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0, 7803 &HasConstCopyAssignment); 7804 } 7805 } 7806 7807 // -- for all the nonstatic data members of X that are of a class 7808 // type M (or array thereof), each such class type has a copy 7809 // assignment operator whose parameter is of type const M&, 7810 // const volatile M& or M. 7811 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 7812 FieldEnd = ClassDecl->field_end(); 7813 HasConstCopyAssignment && Field != FieldEnd; 7814 ++Field) { 7815 QualType FieldType = Context.getBaseElementType((*Field)->getType()); 7816 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 7817 LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const, false, 0, 7818 &HasConstCopyAssignment); 7819 } 7820 } 7821 7822 // Otherwise, the implicitly declared copy assignment operator will 7823 // have the form 7824 // 7825 // X& X::operator=(X&) 7826 7827 // C++ [except.spec]p14: 7828 // An implicitly declared special member function (Clause 12) shall have an 7829 // exception-specification. [...] 7830 7831 // It is unspecified whether or not an implicit copy assignment operator 7832 // attempts to deduplicate calls to assignment operators of virtual bases are 7833 // made. As such, this exception specification is effectively unspecified. 7834 // Based on a similar decision made for constness in C++0x, we're erring on 7835 // the side of assuming such calls to be made regardless of whether they 7836 // actually happen. 7837 ImplicitExceptionSpecification ExceptSpec(Context); 7838 unsigned ArgQuals = HasConstCopyAssignment ? Qualifiers::Const : 0; 7839 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 7840 BaseEnd = ClassDecl->bases_end(); 7841 Base != BaseEnd; ++Base) { 7842 if (Base->isVirtual()) 7843 continue; 7844 7845 CXXRecordDecl *BaseClassDecl 7846 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 7847 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 7848 ArgQuals, false, 0)) 7849 ExceptSpec.CalledDecl(CopyAssign); 7850 } 7851 7852 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 7853 BaseEnd = ClassDecl->vbases_end(); 7854 Base != BaseEnd; ++Base) { 7855 CXXRecordDecl *BaseClassDecl 7856 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 7857 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 7858 ArgQuals, false, 0)) 7859 ExceptSpec.CalledDecl(CopyAssign); 7860 } 7861 7862 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 7863 FieldEnd = ClassDecl->field_end(); 7864 Field != FieldEnd; 7865 ++Field) { 7866 QualType FieldType = Context.getBaseElementType((*Field)->getType()); 7867 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 7868 if (CXXMethodDecl *CopyAssign = 7869 LookupCopyingAssignment(FieldClassDecl, ArgQuals, false, 0)) 7870 ExceptSpec.CalledDecl(CopyAssign); 7871 } 7872 } 7873 7874 return std::make_pair(ExceptSpec, HasConstCopyAssignment); 7875} 7876 7877CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 7878 // Note: The following rules are largely analoguous to the copy 7879 // constructor rules. Note that virtual bases are not taken into account 7880 // for determining the argument type of the operator. Note also that 7881 // operators taking an object instead of a reference are allowed. 7882 7883 ImplicitExceptionSpecification Spec(Context); 7884 bool Const; 7885 llvm::tie(Spec, Const) = 7886 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl); 7887 7888 QualType ArgType = Context.getTypeDeclType(ClassDecl); 7889 QualType RetType = Context.getLValueReferenceType(ArgType); 7890 if (Const) 7891 ArgType = ArgType.withConst(); 7892 ArgType = Context.getLValueReferenceType(ArgType); 7893 7894 // An implicitly-declared copy assignment operator is an inline public 7895 // member of its class. 7896 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 7897 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 7898 SourceLocation ClassLoc = ClassDecl->getLocation(); 7899 DeclarationNameInfo NameInfo(Name, ClassLoc); 7900 CXXMethodDecl *CopyAssignment 7901 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 7902 Context.getFunctionType(RetType, &ArgType, 1, EPI), 7903 /*TInfo=*/0, /*isStatic=*/false, 7904 /*StorageClassAsWritten=*/SC_None, 7905 /*isInline=*/true, /*isConstexpr=*/false, 7906 SourceLocation()); 7907 CopyAssignment->setAccess(AS_public); 7908 CopyAssignment->setDefaulted(); 7909 CopyAssignment->setImplicit(); 7910 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment()); 7911 7912 // Add the parameter to the operator. 7913 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 7914 ClassLoc, ClassLoc, /*Id=*/0, 7915 ArgType, /*TInfo=*/0, 7916 SC_None, 7917 SC_None, 0); 7918 CopyAssignment->setParams(FromParam); 7919 7920 // Note that we have added this copy-assignment operator. 7921 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 7922 7923 if (Scope *S = getScopeForContext(ClassDecl)) 7924 PushOnScopeChains(CopyAssignment, S, false); 7925 ClassDecl->addDecl(CopyAssignment); 7926 7927 // C++0x [class.copy]p19: 7928 // .... If the class definition does not explicitly declare a copy 7929 // assignment operator, there is no user-declared move constructor, and 7930 // there is no user-declared move assignment operator, a copy assignment 7931 // operator is implicitly declared as defaulted. 7932 if ((ClassDecl->hasUserDeclaredMoveConstructor() && 7933 !getLangOptions().MicrosoftMode) || 7934 ClassDecl->hasUserDeclaredMoveAssignment() || 7935 ShouldDeleteCopyAssignmentOperator(CopyAssignment)) 7936 CopyAssignment->setDeletedAsWritten(); 7937 7938 AddOverriddenMethods(ClassDecl, CopyAssignment); 7939 return CopyAssignment; 7940} 7941 7942void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 7943 CXXMethodDecl *CopyAssignOperator) { 7944 assert((CopyAssignOperator->isDefaulted() && 7945 CopyAssignOperator->isOverloadedOperator() && 7946 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 7947 !CopyAssignOperator->doesThisDeclarationHaveABody()) && 7948 "DefineImplicitCopyAssignment called for wrong function"); 7949 7950 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 7951 7952 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) { 7953 CopyAssignOperator->setInvalidDecl(); 7954 return; 7955 } 7956 7957 CopyAssignOperator->setUsed(); 7958 7959 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator); 7960 DiagnosticErrorTrap Trap(Diags); 7961 7962 // C++0x [class.copy]p30: 7963 // The implicitly-defined or explicitly-defaulted copy assignment operator 7964 // for a non-union class X performs memberwise copy assignment of its 7965 // subobjects. The direct base classes of X are assigned first, in the 7966 // order of their declaration in the base-specifier-list, and then the 7967 // immediate non-static data members of X are assigned, in the order in 7968 // which they were declared in the class definition. 7969 7970 // The statements that form the synthesized function body. 7971 ASTOwningVector<Stmt*> Statements(*this); 7972 7973 // The parameter for the "other" object, which we are copying from. 7974 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 7975 Qualifiers OtherQuals = Other->getType().getQualifiers(); 7976 QualType OtherRefType = Other->getType(); 7977 if (const LValueReferenceType *OtherRef 7978 = OtherRefType->getAs<LValueReferenceType>()) { 7979 OtherRefType = OtherRef->getPointeeType(); 7980 OtherQuals = OtherRefType.getQualifiers(); 7981 } 7982 7983 // Our location for everything implicitly-generated. 7984 SourceLocation Loc = CopyAssignOperator->getLocation(); 7985 7986 // Construct a reference to the "other" object. We'll be using this 7987 // throughout the generated ASTs. 7988 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take(); 7989 assert(OtherRef && "Reference to parameter cannot fail!"); 7990 7991 // Construct the "this" pointer. We'll be using this throughout the generated 7992 // ASTs. 7993 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>(); 7994 assert(This && "Reference to this cannot fail!"); 7995 7996 // Assign base classes. 7997 bool Invalid = false; 7998 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 7999 E = ClassDecl->bases_end(); Base != E; ++Base) { 8000 // Form the assignment: 8001 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 8002 QualType BaseType = Base->getType().getUnqualifiedType(); 8003 if (!BaseType->isRecordType()) { 8004 Invalid = true; 8005 continue; 8006 } 8007 8008 CXXCastPath BasePath; 8009 BasePath.push_back(Base); 8010 8011 // Construct the "from" expression, which is an implicit cast to the 8012 // appropriately-qualified base type. 8013 Expr *From = OtherRef; 8014 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals), 8015 CK_UncheckedDerivedToBase, 8016 VK_LValue, &BasePath).take(); 8017 8018 // Dereference "this". 8019 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 8020 8021 // Implicitly cast "this" to the appropriately-qualified base type. 8022 To = ImpCastExprToType(To.take(), 8023 Context.getCVRQualifiedType(BaseType, 8024 CopyAssignOperator->getTypeQualifiers()), 8025 CK_UncheckedDerivedToBase, 8026 VK_LValue, &BasePath); 8027 8028 // Build the copy. 8029 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType, 8030 To.get(), From, 8031 /*CopyingBaseSubobject=*/true, 8032 /*Copying=*/true); 8033 if (Copy.isInvalid()) { 8034 Diag(CurrentLocation, diag::note_member_synthesized_at) 8035 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 8036 CopyAssignOperator->setInvalidDecl(); 8037 return; 8038 } 8039 8040 // Success! Record the copy. 8041 Statements.push_back(Copy.takeAs<Expr>()); 8042 } 8043 8044 // \brief Reference to the __builtin_memcpy function. 8045 Expr *BuiltinMemCpyRef = 0; 8046 // \brief Reference to the __builtin_objc_memmove_collectable function. 8047 Expr *CollectableMemCpyRef = 0; 8048 8049 // Assign non-static members. 8050 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8051 FieldEnd = ClassDecl->field_end(); 8052 Field != FieldEnd; ++Field) { 8053 if (Field->isUnnamedBitfield()) 8054 continue; 8055 8056 // Check for members of reference type; we can't copy those. 8057 if (Field->getType()->isReferenceType()) { 8058 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 8059 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 8060 Diag(Field->getLocation(), diag::note_declared_at); 8061 Diag(CurrentLocation, diag::note_member_synthesized_at) 8062 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 8063 Invalid = true; 8064 continue; 8065 } 8066 8067 // Check for members of const-qualified, non-class type. 8068 QualType BaseType = Context.getBaseElementType(Field->getType()); 8069 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 8070 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 8071 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 8072 Diag(Field->getLocation(), diag::note_declared_at); 8073 Diag(CurrentLocation, diag::note_member_synthesized_at) 8074 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 8075 Invalid = true; 8076 continue; 8077 } 8078 8079 // Suppress assigning zero-width bitfields. 8080 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 8081 continue; 8082 8083 QualType FieldType = Field->getType().getNonReferenceType(); 8084 if (FieldType->isIncompleteArrayType()) { 8085 assert(ClassDecl->hasFlexibleArrayMember() && 8086 "Incomplete array type is not valid"); 8087 continue; 8088 } 8089 8090 // Build references to the field in the object we're copying from and to. 8091 CXXScopeSpec SS; // Intentionally empty 8092 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 8093 LookupMemberName); 8094 MemberLookup.addDecl(*Field); 8095 MemberLookup.resolveKind(); 8096 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType, 8097 Loc, /*IsArrow=*/false, 8098 SS, SourceLocation(), 0, 8099 MemberLookup, 0); 8100 ExprResult To = BuildMemberReferenceExpr(This, This->getType(), 8101 Loc, /*IsArrow=*/true, 8102 SS, SourceLocation(), 0, 8103 MemberLookup, 0); 8104 assert(!From.isInvalid() && "Implicit field reference cannot fail"); 8105 assert(!To.isInvalid() && "Implicit field reference cannot fail"); 8106 8107 // If the field should be copied with __builtin_memcpy rather than via 8108 // explicit assignments, do so. This optimization only applies for arrays 8109 // of scalars and arrays of class type with trivial copy-assignment 8110 // operators. 8111 if (FieldType->isArrayType() && !FieldType.isVolatileQualified() 8112 && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) { 8113 // Compute the size of the memory buffer to be copied. 8114 QualType SizeType = Context.getSizeType(); 8115 llvm::APInt Size(Context.getTypeSize(SizeType), 8116 Context.getTypeSizeInChars(BaseType).getQuantity()); 8117 for (const ConstantArrayType *Array 8118 = Context.getAsConstantArrayType(FieldType); 8119 Array; 8120 Array = Context.getAsConstantArrayType(Array->getElementType())) { 8121 llvm::APInt ArraySize 8122 = Array->getSize().zextOrTrunc(Size.getBitWidth()); 8123 Size *= ArraySize; 8124 } 8125 8126 // Take the address of the field references for "from" and "to". 8127 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get()); 8128 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get()); 8129 8130 bool NeedsCollectableMemCpy = 8131 (BaseType->isRecordType() && 8132 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()); 8133 8134 if (NeedsCollectableMemCpy) { 8135 if (!CollectableMemCpyRef) { 8136 // Create a reference to the __builtin_objc_memmove_collectable function. 8137 LookupResult R(*this, 8138 &Context.Idents.get("__builtin_objc_memmove_collectable"), 8139 Loc, LookupOrdinaryName); 8140 LookupName(R, TUScope, true); 8141 8142 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>(); 8143 if (!CollectableMemCpy) { 8144 // Something went horribly wrong earlier, and we will have 8145 // complained about it. 8146 Invalid = true; 8147 continue; 8148 } 8149 8150 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy, 8151 CollectableMemCpy->getType(), 8152 VK_LValue, Loc, 0).take(); 8153 assert(CollectableMemCpyRef && "Builtin reference cannot fail"); 8154 } 8155 } 8156 // Create a reference to the __builtin_memcpy builtin function. 8157 else if (!BuiltinMemCpyRef) { 8158 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc, 8159 LookupOrdinaryName); 8160 LookupName(R, TUScope, true); 8161 8162 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>(); 8163 if (!BuiltinMemCpy) { 8164 // Something went horribly wrong earlier, and we will have complained 8165 // about it. 8166 Invalid = true; 8167 continue; 8168 } 8169 8170 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy, 8171 BuiltinMemCpy->getType(), 8172 VK_LValue, Loc, 0).take(); 8173 assert(BuiltinMemCpyRef && "Builtin reference cannot fail"); 8174 } 8175 8176 ASTOwningVector<Expr*> CallArgs(*this); 8177 CallArgs.push_back(To.takeAs<Expr>()); 8178 CallArgs.push_back(From.takeAs<Expr>()); 8179 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc)); 8180 ExprResult Call = ExprError(); 8181 if (NeedsCollectableMemCpy) 8182 Call = ActOnCallExpr(/*Scope=*/0, 8183 CollectableMemCpyRef, 8184 Loc, move_arg(CallArgs), 8185 Loc); 8186 else 8187 Call = ActOnCallExpr(/*Scope=*/0, 8188 BuiltinMemCpyRef, 8189 Loc, move_arg(CallArgs), 8190 Loc); 8191 8192 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 8193 Statements.push_back(Call.takeAs<Expr>()); 8194 continue; 8195 } 8196 8197 // Build the copy of this field. 8198 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType, 8199 To.get(), From.get(), 8200 /*CopyingBaseSubobject=*/false, 8201 /*Copying=*/true); 8202 if (Copy.isInvalid()) { 8203 Diag(CurrentLocation, diag::note_member_synthesized_at) 8204 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 8205 CopyAssignOperator->setInvalidDecl(); 8206 return; 8207 } 8208 8209 // Success! Record the copy. 8210 Statements.push_back(Copy.takeAs<Stmt>()); 8211 } 8212 8213 if (!Invalid) { 8214 // Add a "return *this;" 8215 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 8216 8217 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get()); 8218 if (Return.isInvalid()) 8219 Invalid = true; 8220 else { 8221 Statements.push_back(Return.takeAs<Stmt>()); 8222 8223 if (Trap.hasErrorOccurred()) { 8224 Diag(CurrentLocation, diag::note_member_synthesized_at) 8225 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 8226 Invalid = true; 8227 } 8228 } 8229 } 8230 8231 if (Invalid) { 8232 CopyAssignOperator->setInvalidDecl(); 8233 return; 8234 } 8235 8236 StmtResult Body; 8237 { 8238 CompoundScopeRAII CompoundScope(*this); 8239 Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements), 8240 /*isStmtExpr=*/false); 8241 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 8242 } 8243 CopyAssignOperator->setBody(Body.takeAs<Stmt>()); 8244 8245 if (ASTMutationListener *L = getASTMutationListener()) { 8246 L->CompletedImplicitDefinition(CopyAssignOperator); 8247 } 8248} 8249 8250Sema::ImplicitExceptionSpecification 8251Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXRecordDecl *ClassDecl) { 8252 ImplicitExceptionSpecification ExceptSpec(Context); 8253 8254 if (ClassDecl->isInvalidDecl()) 8255 return ExceptSpec; 8256 8257 // C++0x [except.spec]p14: 8258 // An implicitly declared special member function (Clause 12) shall have an 8259 // exception-specification. [...] 8260 8261 // It is unspecified whether or not an implicit move assignment operator 8262 // attempts to deduplicate calls to assignment operators of virtual bases are 8263 // made. As such, this exception specification is effectively unspecified. 8264 // Based on a similar decision made for constness in C++0x, we're erring on 8265 // the side of assuming such calls to be made regardless of whether they 8266 // actually happen. 8267 // Note that a move constructor is not implicitly declared when there are 8268 // virtual bases, but it can still be user-declared and explicitly defaulted. 8269 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 8270 BaseEnd = ClassDecl->bases_end(); 8271 Base != BaseEnd; ++Base) { 8272 if (Base->isVirtual()) 8273 continue; 8274 8275 CXXRecordDecl *BaseClassDecl 8276 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8277 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 8278 false, 0)) 8279 ExceptSpec.CalledDecl(MoveAssign); 8280 } 8281 8282 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 8283 BaseEnd = ClassDecl->vbases_end(); 8284 Base != BaseEnd; ++Base) { 8285 CXXRecordDecl *BaseClassDecl 8286 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8287 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 8288 false, 0)) 8289 ExceptSpec.CalledDecl(MoveAssign); 8290 } 8291 8292 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8293 FieldEnd = ClassDecl->field_end(); 8294 Field != FieldEnd; 8295 ++Field) { 8296 QualType FieldType = Context.getBaseElementType((*Field)->getType()); 8297 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 8298 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(FieldClassDecl, 8299 false, 0)) 8300 ExceptSpec.CalledDecl(MoveAssign); 8301 } 8302 } 8303 8304 return ExceptSpec; 8305} 8306 8307CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 8308 // Note: The following rules are largely analoguous to the move 8309 // constructor rules. 8310 8311 ImplicitExceptionSpecification Spec( 8312 ComputeDefaultedMoveAssignmentExceptionSpec(ClassDecl)); 8313 8314 QualType ArgType = Context.getTypeDeclType(ClassDecl); 8315 QualType RetType = Context.getLValueReferenceType(ArgType); 8316 ArgType = Context.getRValueReferenceType(ArgType); 8317 8318 // An implicitly-declared move assignment operator is an inline public 8319 // member of its class. 8320 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 8321 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 8322 SourceLocation ClassLoc = ClassDecl->getLocation(); 8323 DeclarationNameInfo NameInfo(Name, ClassLoc); 8324 CXXMethodDecl *MoveAssignment 8325 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 8326 Context.getFunctionType(RetType, &ArgType, 1, EPI), 8327 /*TInfo=*/0, /*isStatic=*/false, 8328 /*StorageClassAsWritten=*/SC_None, 8329 /*isInline=*/true, 8330 /*isConstexpr=*/false, 8331 SourceLocation()); 8332 MoveAssignment->setAccess(AS_public); 8333 MoveAssignment->setDefaulted(); 8334 MoveAssignment->setImplicit(); 8335 MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment()); 8336 8337 // Add the parameter to the operator. 8338 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 8339 ClassLoc, ClassLoc, /*Id=*/0, 8340 ArgType, /*TInfo=*/0, 8341 SC_None, 8342 SC_None, 0); 8343 MoveAssignment->setParams(FromParam); 8344 8345 // Note that we have added this copy-assignment operator. 8346 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 8347 8348 // C++0x [class.copy]p9: 8349 // If the definition of a class X does not explicitly declare a move 8350 // assignment operator, one will be implicitly declared as defaulted if and 8351 // only if: 8352 // [...] 8353 // - the move assignment operator would not be implicitly defined as 8354 // deleted. 8355 if (ShouldDeleteMoveAssignmentOperator(MoveAssignment)) { 8356 // Cache this result so that we don't try to generate this over and over 8357 // on every lookup, leaking memory and wasting time. 8358 ClassDecl->setFailedImplicitMoveAssignment(); 8359 return 0; 8360 } 8361 8362 if (Scope *S = getScopeForContext(ClassDecl)) 8363 PushOnScopeChains(MoveAssignment, S, false); 8364 ClassDecl->addDecl(MoveAssignment); 8365 8366 AddOverriddenMethods(ClassDecl, MoveAssignment); 8367 return MoveAssignment; 8368} 8369 8370void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 8371 CXXMethodDecl *MoveAssignOperator) { 8372 assert((MoveAssignOperator->isDefaulted() && 8373 MoveAssignOperator->isOverloadedOperator() && 8374 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 8375 !MoveAssignOperator->doesThisDeclarationHaveABody()) && 8376 "DefineImplicitMoveAssignment called for wrong function"); 8377 8378 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 8379 8380 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) { 8381 MoveAssignOperator->setInvalidDecl(); 8382 return; 8383 } 8384 8385 MoveAssignOperator->setUsed(); 8386 8387 ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator); 8388 DiagnosticErrorTrap Trap(Diags); 8389 8390 // C++0x [class.copy]p28: 8391 // The implicitly-defined or move assignment operator for a non-union class 8392 // X performs memberwise move assignment of its subobjects. The direct base 8393 // classes of X are assigned first, in the order of their declaration in the 8394 // base-specifier-list, and then the immediate non-static data members of X 8395 // are assigned, in the order in which they were declared in the class 8396 // definition. 8397 8398 // The statements that form the synthesized function body. 8399 ASTOwningVector<Stmt*> Statements(*this); 8400 8401 // The parameter for the "other" object, which we are move from. 8402 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 8403 QualType OtherRefType = Other->getType()-> 8404 getAs<RValueReferenceType>()->getPointeeType(); 8405 assert(OtherRefType.getQualifiers() == 0 && 8406 "Bad argument type of defaulted move assignment"); 8407 8408 // Our location for everything implicitly-generated. 8409 SourceLocation Loc = MoveAssignOperator->getLocation(); 8410 8411 // Construct a reference to the "other" object. We'll be using this 8412 // throughout the generated ASTs. 8413 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take(); 8414 assert(OtherRef && "Reference to parameter cannot fail!"); 8415 // Cast to rvalue. 8416 OtherRef = CastForMoving(*this, OtherRef); 8417 8418 // Construct the "this" pointer. We'll be using this throughout the generated 8419 // ASTs. 8420 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>(); 8421 assert(This && "Reference to this cannot fail!"); 8422 8423 // Assign base classes. 8424 bool Invalid = false; 8425 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 8426 E = ClassDecl->bases_end(); Base != E; ++Base) { 8427 // Form the assignment: 8428 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 8429 QualType BaseType = Base->getType().getUnqualifiedType(); 8430 if (!BaseType->isRecordType()) { 8431 Invalid = true; 8432 continue; 8433 } 8434 8435 CXXCastPath BasePath; 8436 BasePath.push_back(Base); 8437 8438 // Construct the "from" expression, which is an implicit cast to the 8439 // appropriately-qualified base type. 8440 Expr *From = OtherRef; 8441 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase, 8442 VK_XValue, &BasePath).take(); 8443 8444 // Dereference "this". 8445 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 8446 8447 // Implicitly cast "this" to the appropriately-qualified base type. 8448 To = ImpCastExprToType(To.take(), 8449 Context.getCVRQualifiedType(BaseType, 8450 MoveAssignOperator->getTypeQualifiers()), 8451 CK_UncheckedDerivedToBase, 8452 VK_LValue, &BasePath); 8453 8454 // Build the move. 8455 StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType, 8456 To.get(), From, 8457 /*CopyingBaseSubobject=*/true, 8458 /*Copying=*/false); 8459 if (Move.isInvalid()) { 8460 Diag(CurrentLocation, diag::note_member_synthesized_at) 8461 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 8462 MoveAssignOperator->setInvalidDecl(); 8463 return; 8464 } 8465 8466 // Success! Record the move. 8467 Statements.push_back(Move.takeAs<Expr>()); 8468 } 8469 8470 // \brief Reference to the __builtin_memcpy function. 8471 Expr *BuiltinMemCpyRef = 0; 8472 // \brief Reference to the __builtin_objc_memmove_collectable function. 8473 Expr *CollectableMemCpyRef = 0; 8474 8475 // Assign non-static members. 8476 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8477 FieldEnd = ClassDecl->field_end(); 8478 Field != FieldEnd; ++Field) { 8479 if (Field->isUnnamedBitfield()) 8480 continue; 8481 8482 // Check for members of reference type; we can't move those. 8483 if (Field->getType()->isReferenceType()) { 8484 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 8485 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 8486 Diag(Field->getLocation(), diag::note_declared_at); 8487 Diag(CurrentLocation, diag::note_member_synthesized_at) 8488 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 8489 Invalid = true; 8490 continue; 8491 } 8492 8493 // Check for members of const-qualified, non-class type. 8494 QualType BaseType = Context.getBaseElementType(Field->getType()); 8495 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 8496 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 8497 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 8498 Diag(Field->getLocation(), diag::note_declared_at); 8499 Diag(CurrentLocation, diag::note_member_synthesized_at) 8500 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 8501 Invalid = true; 8502 continue; 8503 } 8504 8505 // Suppress assigning zero-width bitfields. 8506 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 8507 continue; 8508 8509 QualType FieldType = Field->getType().getNonReferenceType(); 8510 if (FieldType->isIncompleteArrayType()) { 8511 assert(ClassDecl->hasFlexibleArrayMember() && 8512 "Incomplete array type is not valid"); 8513 continue; 8514 } 8515 8516 // Build references to the field in the object we're copying from and to. 8517 CXXScopeSpec SS; // Intentionally empty 8518 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 8519 LookupMemberName); 8520 MemberLookup.addDecl(*Field); 8521 MemberLookup.resolveKind(); 8522 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType, 8523 Loc, /*IsArrow=*/false, 8524 SS, SourceLocation(), 0, 8525 MemberLookup, 0); 8526 ExprResult To = BuildMemberReferenceExpr(This, This->getType(), 8527 Loc, /*IsArrow=*/true, 8528 SS, SourceLocation(), 0, 8529 MemberLookup, 0); 8530 assert(!From.isInvalid() && "Implicit field reference cannot fail"); 8531 assert(!To.isInvalid() && "Implicit field reference cannot fail"); 8532 8533 assert(!From.get()->isLValue() && // could be xvalue or prvalue 8534 "Member reference with rvalue base must be rvalue except for reference " 8535 "members, which aren't allowed for move assignment."); 8536 8537 // If the field should be copied with __builtin_memcpy rather than via 8538 // explicit assignments, do so. This optimization only applies for arrays 8539 // of scalars and arrays of class type with trivial move-assignment 8540 // operators. 8541 if (FieldType->isArrayType() && !FieldType.isVolatileQualified() 8542 && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) { 8543 // Compute the size of the memory buffer to be copied. 8544 QualType SizeType = Context.getSizeType(); 8545 llvm::APInt Size(Context.getTypeSize(SizeType), 8546 Context.getTypeSizeInChars(BaseType).getQuantity()); 8547 for (const ConstantArrayType *Array 8548 = Context.getAsConstantArrayType(FieldType); 8549 Array; 8550 Array = Context.getAsConstantArrayType(Array->getElementType())) { 8551 llvm::APInt ArraySize 8552 = Array->getSize().zextOrTrunc(Size.getBitWidth()); 8553 Size *= ArraySize; 8554 } 8555 8556 // Take the address of the field references for "from" and "to". We 8557 // directly construct UnaryOperators here because semantic analysis 8558 // does not permit us to take the address of an xvalue. 8559 From = new (Context) UnaryOperator(From.get(), UO_AddrOf, 8560 Context.getPointerType(From.get()->getType()), 8561 VK_RValue, OK_Ordinary, Loc); 8562 To = new (Context) UnaryOperator(To.get(), UO_AddrOf, 8563 Context.getPointerType(To.get()->getType()), 8564 VK_RValue, OK_Ordinary, Loc); 8565 8566 bool NeedsCollectableMemCpy = 8567 (BaseType->isRecordType() && 8568 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()); 8569 8570 if (NeedsCollectableMemCpy) { 8571 if (!CollectableMemCpyRef) { 8572 // Create a reference to the __builtin_objc_memmove_collectable function. 8573 LookupResult R(*this, 8574 &Context.Idents.get("__builtin_objc_memmove_collectable"), 8575 Loc, LookupOrdinaryName); 8576 LookupName(R, TUScope, true); 8577 8578 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>(); 8579 if (!CollectableMemCpy) { 8580 // Something went horribly wrong earlier, and we will have 8581 // complained about it. 8582 Invalid = true; 8583 continue; 8584 } 8585 8586 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy, 8587 CollectableMemCpy->getType(), 8588 VK_LValue, Loc, 0).take(); 8589 assert(CollectableMemCpyRef && "Builtin reference cannot fail"); 8590 } 8591 } 8592 // Create a reference to the __builtin_memcpy builtin function. 8593 else if (!BuiltinMemCpyRef) { 8594 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc, 8595 LookupOrdinaryName); 8596 LookupName(R, TUScope, true); 8597 8598 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>(); 8599 if (!BuiltinMemCpy) { 8600 // Something went horribly wrong earlier, and we will have complained 8601 // about it. 8602 Invalid = true; 8603 continue; 8604 } 8605 8606 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy, 8607 BuiltinMemCpy->getType(), 8608 VK_LValue, Loc, 0).take(); 8609 assert(BuiltinMemCpyRef && "Builtin reference cannot fail"); 8610 } 8611 8612 ASTOwningVector<Expr*> CallArgs(*this); 8613 CallArgs.push_back(To.takeAs<Expr>()); 8614 CallArgs.push_back(From.takeAs<Expr>()); 8615 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc)); 8616 ExprResult Call = ExprError(); 8617 if (NeedsCollectableMemCpy) 8618 Call = ActOnCallExpr(/*Scope=*/0, 8619 CollectableMemCpyRef, 8620 Loc, move_arg(CallArgs), 8621 Loc); 8622 else 8623 Call = ActOnCallExpr(/*Scope=*/0, 8624 BuiltinMemCpyRef, 8625 Loc, move_arg(CallArgs), 8626 Loc); 8627 8628 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 8629 Statements.push_back(Call.takeAs<Expr>()); 8630 continue; 8631 } 8632 8633 // Build the move of this field. 8634 StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType, 8635 To.get(), From.get(), 8636 /*CopyingBaseSubobject=*/false, 8637 /*Copying=*/false); 8638 if (Move.isInvalid()) { 8639 Diag(CurrentLocation, diag::note_member_synthesized_at) 8640 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 8641 MoveAssignOperator->setInvalidDecl(); 8642 return; 8643 } 8644 8645 // Success! Record the copy. 8646 Statements.push_back(Move.takeAs<Stmt>()); 8647 } 8648 8649 if (!Invalid) { 8650 // Add a "return *this;" 8651 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 8652 8653 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get()); 8654 if (Return.isInvalid()) 8655 Invalid = true; 8656 else { 8657 Statements.push_back(Return.takeAs<Stmt>()); 8658 8659 if (Trap.hasErrorOccurred()) { 8660 Diag(CurrentLocation, diag::note_member_synthesized_at) 8661 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 8662 Invalid = true; 8663 } 8664 } 8665 } 8666 8667 if (Invalid) { 8668 MoveAssignOperator->setInvalidDecl(); 8669 return; 8670 } 8671 8672 StmtResult Body; 8673 { 8674 CompoundScopeRAII CompoundScope(*this); 8675 Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements), 8676 /*isStmtExpr=*/false); 8677 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 8678 } 8679 MoveAssignOperator->setBody(Body.takeAs<Stmt>()); 8680 8681 if (ASTMutationListener *L = getASTMutationListener()) { 8682 L->CompletedImplicitDefinition(MoveAssignOperator); 8683 } 8684} 8685 8686std::pair<Sema::ImplicitExceptionSpecification, bool> 8687Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) { 8688 if (ClassDecl->isInvalidDecl()) 8689 return std::make_pair(ImplicitExceptionSpecification(Context), false); 8690 8691 // C++ [class.copy]p5: 8692 // The implicitly-declared copy constructor for a class X will 8693 // have the form 8694 // 8695 // X::X(const X&) 8696 // 8697 // if 8698 // FIXME: It ought to be possible to store this on the record. 8699 bool HasConstCopyConstructor = true; 8700 8701 // -- each direct or virtual base class B of X has a copy 8702 // constructor whose first parameter is of type const B& or 8703 // const volatile B&, and 8704 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 8705 BaseEnd = ClassDecl->bases_end(); 8706 HasConstCopyConstructor && Base != BaseEnd; 8707 ++Base) { 8708 // Virtual bases are handled below. 8709 if (Base->isVirtual()) 8710 continue; 8711 8712 CXXRecordDecl *BaseClassDecl 8713 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8714 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const, 8715 &HasConstCopyConstructor); 8716 } 8717 8718 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 8719 BaseEnd = ClassDecl->vbases_end(); 8720 HasConstCopyConstructor && Base != BaseEnd; 8721 ++Base) { 8722 CXXRecordDecl *BaseClassDecl 8723 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8724 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const, 8725 &HasConstCopyConstructor); 8726 } 8727 8728 // -- for all the nonstatic data members of X that are of a 8729 // class type M (or array thereof), each such class type 8730 // has a copy constructor whose first parameter is of type 8731 // const M& or const volatile M&. 8732 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8733 FieldEnd = ClassDecl->field_end(); 8734 HasConstCopyConstructor && Field != FieldEnd; 8735 ++Field) { 8736 QualType FieldType = Context.getBaseElementType((*Field)->getType()); 8737 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 8738 LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const, 8739 &HasConstCopyConstructor); 8740 } 8741 } 8742 // Otherwise, the implicitly declared copy constructor will have 8743 // the form 8744 // 8745 // X::X(X&) 8746 8747 // C++ [except.spec]p14: 8748 // An implicitly declared special member function (Clause 12) shall have an 8749 // exception-specification. [...] 8750 ImplicitExceptionSpecification ExceptSpec(Context); 8751 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0; 8752 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 8753 BaseEnd = ClassDecl->bases_end(); 8754 Base != BaseEnd; 8755 ++Base) { 8756 // Virtual bases are handled below. 8757 if (Base->isVirtual()) 8758 continue; 8759 8760 CXXRecordDecl *BaseClassDecl 8761 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8762 if (CXXConstructorDecl *CopyConstructor = 8763 LookupCopyingConstructor(BaseClassDecl, Quals)) 8764 ExceptSpec.CalledDecl(CopyConstructor); 8765 } 8766 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 8767 BaseEnd = ClassDecl->vbases_end(); 8768 Base != BaseEnd; 8769 ++Base) { 8770 CXXRecordDecl *BaseClassDecl 8771 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8772 if (CXXConstructorDecl *CopyConstructor = 8773 LookupCopyingConstructor(BaseClassDecl, Quals)) 8774 ExceptSpec.CalledDecl(CopyConstructor); 8775 } 8776 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8777 FieldEnd = ClassDecl->field_end(); 8778 Field != FieldEnd; 8779 ++Field) { 8780 QualType FieldType = Context.getBaseElementType((*Field)->getType()); 8781 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 8782 if (CXXConstructorDecl *CopyConstructor = 8783 LookupCopyingConstructor(FieldClassDecl, Quals)) 8784 ExceptSpec.CalledDecl(CopyConstructor); 8785 } 8786 } 8787 8788 return std::make_pair(ExceptSpec, HasConstCopyConstructor); 8789} 8790 8791CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 8792 CXXRecordDecl *ClassDecl) { 8793 // C++ [class.copy]p4: 8794 // If the class definition does not explicitly declare a copy 8795 // constructor, one is declared implicitly. 8796 8797 ImplicitExceptionSpecification Spec(Context); 8798 bool Const; 8799 llvm::tie(Spec, Const) = 8800 ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl); 8801 8802 QualType ClassType = Context.getTypeDeclType(ClassDecl); 8803 QualType ArgType = ClassType; 8804 if (Const) 8805 ArgType = ArgType.withConst(); 8806 ArgType = Context.getLValueReferenceType(ArgType); 8807 8808 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 8809 8810 DeclarationName Name 8811 = Context.DeclarationNames.getCXXConstructorName( 8812 Context.getCanonicalType(ClassType)); 8813 SourceLocation ClassLoc = ClassDecl->getLocation(); 8814 DeclarationNameInfo NameInfo(Name, ClassLoc); 8815 8816 // An implicitly-declared copy constructor is an inline public 8817 // member of its class. 8818 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 8819 Context, ClassDecl, ClassLoc, NameInfo, 8820 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0, 8821 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 8822 /*isConstexpr=*/ClassDecl->defaultedCopyConstructorIsConstexpr() && 8823 getLangOptions().CPlusPlus0x); 8824 CopyConstructor->setAccess(AS_public); 8825 CopyConstructor->setDefaulted(); 8826 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor()); 8827 8828 // Note that we have declared this constructor. 8829 ++ASTContext::NumImplicitCopyConstructorsDeclared; 8830 8831 // Add the parameter to the constructor. 8832 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 8833 ClassLoc, ClassLoc, 8834 /*IdentifierInfo=*/0, 8835 ArgType, /*TInfo=*/0, 8836 SC_None, 8837 SC_None, 0); 8838 CopyConstructor->setParams(FromParam); 8839 8840 if (Scope *S = getScopeForContext(ClassDecl)) 8841 PushOnScopeChains(CopyConstructor, S, false); 8842 ClassDecl->addDecl(CopyConstructor); 8843 8844 // C++11 [class.copy]p8: 8845 // ... If the class definition does not explicitly declare a copy 8846 // constructor, there is no user-declared move constructor, and there is no 8847 // user-declared move assignment operator, a copy constructor is implicitly 8848 // declared as defaulted. 8849 if (ClassDecl->hasUserDeclaredMoveConstructor() || 8850 (ClassDecl->hasUserDeclaredMoveAssignment() && 8851 !getLangOptions().MicrosoftMode) || 8852 ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) 8853 CopyConstructor->setDeletedAsWritten(); 8854 8855 return CopyConstructor; 8856} 8857 8858void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 8859 CXXConstructorDecl *CopyConstructor) { 8860 assert((CopyConstructor->isDefaulted() && 8861 CopyConstructor->isCopyConstructor() && 8862 !CopyConstructor->doesThisDeclarationHaveABody()) && 8863 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 8864 8865 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 8866 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 8867 8868 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor); 8869 DiagnosticErrorTrap Trap(Diags); 8870 8871 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) || 8872 Trap.hasErrorOccurred()) { 8873 Diag(CurrentLocation, diag::note_member_synthesized_at) 8874 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl); 8875 CopyConstructor->setInvalidDecl(); 8876 } else { 8877 Sema::CompoundScopeRAII CompoundScope(*this); 8878 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(), 8879 CopyConstructor->getLocation(), 8880 MultiStmtArg(*this, 0, 0), 8881 /*isStmtExpr=*/false) 8882 .takeAs<Stmt>()); 8883 CopyConstructor->setImplicitlyDefined(true); 8884 } 8885 8886 CopyConstructor->setUsed(); 8887 if (ASTMutationListener *L = getASTMutationListener()) { 8888 L->CompletedImplicitDefinition(CopyConstructor); 8889 } 8890} 8891 8892Sema::ImplicitExceptionSpecification 8893Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXRecordDecl *ClassDecl) { 8894 // C++ [except.spec]p14: 8895 // An implicitly declared special member function (Clause 12) shall have an 8896 // exception-specification. [...] 8897 ImplicitExceptionSpecification ExceptSpec(Context); 8898 if (ClassDecl->isInvalidDecl()) 8899 return ExceptSpec; 8900 8901 // Direct base-class constructors. 8902 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 8903 BEnd = ClassDecl->bases_end(); 8904 B != BEnd; ++B) { 8905 if (B->isVirtual()) // Handled below. 8906 continue; 8907 8908 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 8909 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8910 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl); 8911 // If this is a deleted function, add it anyway. This might be conformant 8912 // with the standard. This might not. I'm not sure. It might not matter. 8913 if (Constructor) 8914 ExceptSpec.CalledDecl(Constructor); 8915 } 8916 } 8917 8918 // Virtual base-class constructors. 8919 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 8920 BEnd = ClassDecl->vbases_end(); 8921 B != BEnd; ++B) { 8922 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 8923 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8924 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl); 8925 // If this is a deleted function, add it anyway. This might be conformant 8926 // with the standard. This might not. I'm not sure. It might not matter. 8927 if (Constructor) 8928 ExceptSpec.CalledDecl(Constructor); 8929 } 8930 } 8931 8932 // Field constructors. 8933 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 8934 FEnd = ClassDecl->field_end(); 8935 F != FEnd; ++F) { 8936 if (const RecordType *RecordTy 8937 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 8938 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8939 CXXConstructorDecl *Constructor = LookupMovingConstructor(FieldRecDecl); 8940 // If this is a deleted function, add it anyway. This might be conformant 8941 // with the standard. This might not. I'm not sure. It might not matter. 8942 // In particular, the problem is that this function never gets called. It 8943 // might just be ill-formed because this function attempts to refer to 8944 // a deleted function here. 8945 if (Constructor) 8946 ExceptSpec.CalledDecl(Constructor); 8947 } 8948 } 8949 8950 return ExceptSpec; 8951} 8952 8953CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 8954 CXXRecordDecl *ClassDecl) { 8955 ImplicitExceptionSpecification Spec( 8956 ComputeDefaultedMoveCtorExceptionSpec(ClassDecl)); 8957 8958 QualType ClassType = Context.getTypeDeclType(ClassDecl); 8959 QualType ArgType = Context.getRValueReferenceType(ClassType); 8960 8961 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 8962 8963 DeclarationName Name 8964 = Context.DeclarationNames.getCXXConstructorName( 8965 Context.getCanonicalType(ClassType)); 8966 SourceLocation ClassLoc = ClassDecl->getLocation(); 8967 DeclarationNameInfo NameInfo(Name, ClassLoc); 8968 8969 // C++0x [class.copy]p11: 8970 // An implicitly-declared copy/move constructor is an inline public 8971 // member of its class. 8972 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 8973 Context, ClassDecl, ClassLoc, NameInfo, 8974 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0, 8975 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 8976 /*isConstexpr=*/ClassDecl->defaultedMoveConstructorIsConstexpr() && 8977 getLangOptions().CPlusPlus0x); 8978 MoveConstructor->setAccess(AS_public); 8979 MoveConstructor->setDefaulted(); 8980 MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor()); 8981 8982 // Add the parameter to the constructor. 8983 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 8984 ClassLoc, ClassLoc, 8985 /*IdentifierInfo=*/0, 8986 ArgType, /*TInfo=*/0, 8987 SC_None, 8988 SC_None, 0); 8989 MoveConstructor->setParams(FromParam); 8990 8991 // C++0x [class.copy]p9: 8992 // If the definition of a class X does not explicitly declare a move 8993 // constructor, one will be implicitly declared as defaulted if and only if: 8994 // [...] 8995 // - the move constructor would not be implicitly defined as deleted. 8996 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 8997 // Cache this result so that we don't try to generate this over and over 8998 // on every lookup, leaking memory and wasting time. 8999 ClassDecl->setFailedImplicitMoveConstructor(); 9000 return 0; 9001 } 9002 9003 // Note that we have declared this constructor. 9004 ++ASTContext::NumImplicitMoveConstructorsDeclared; 9005 9006 if (Scope *S = getScopeForContext(ClassDecl)) 9007 PushOnScopeChains(MoveConstructor, S, false); 9008 ClassDecl->addDecl(MoveConstructor); 9009 9010 return MoveConstructor; 9011} 9012 9013void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 9014 CXXConstructorDecl *MoveConstructor) { 9015 assert((MoveConstructor->isDefaulted() && 9016 MoveConstructor->isMoveConstructor() && 9017 !MoveConstructor->doesThisDeclarationHaveABody()) && 9018 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 9019 9020 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 9021 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 9022 9023 ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor); 9024 DiagnosticErrorTrap Trap(Diags); 9025 9026 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) || 9027 Trap.hasErrorOccurred()) { 9028 Diag(CurrentLocation, diag::note_member_synthesized_at) 9029 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl); 9030 MoveConstructor->setInvalidDecl(); 9031 } else { 9032 Sema::CompoundScopeRAII CompoundScope(*this); 9033 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(), 9034 MoveConstructor->getLocation(), 9035 MultiStmtArg(*this, 0, 0), 9036 /*isStmtExpr=*/false) 9037 .takeAs<Stmt>()); 9038 MoveConstructor->setImplicitlyDefined(true); 9039 } 9040 9041 MoveConstructor->setUsed(); 9042 9043 if (ASTMutationListener *L = getASTMutationListener()) { 9044 L->CompletedImplicitDefinition(MoveConstructor); 9045 } 9046} 9047 9048bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 9049 return FD->isDeleted() && 9050 (FD->isDefaulted() || FD->isImplicit()) && 9051 isa<CXXMethodDecl>(FD); 9052} 9053 9054void Sema::DefineImplicitLambdaToFunctionPointerConversion( 9055 SourceLocation CurrentLocation, 9056 CXXConversionDecl *Conv) 9057{ 9058 Conv->setUsed(); 9059 9060 ImplicitlyDefinedFunctionScope Scope(*this, Conv); 9061 DiagnosticErrorTrap Trap(Diags); 9062 9063 // Introduce a bogus body, which IR generation will override anyway. 9064 Conv->setBody(new (Context) CompoundStmt(Context, 0, 0, Conv->getLocation(), 9065 Conv->getLocation())); 9066 9067 if (ASTMutationListener *L = getASTMutationListener()) { 9068 L->CompletedImplicitDefinition(Conv); 9069 } 9070} 9071 9072void Sema::DefineImplicitLambdaToBlockPointerConversion( 9073 SourceLocation CurrentLocation, 9074 CXXConversionDecl *Conv) 9075{ 9076 Conv->setUsed(); 9077 9078 ImplicitlyDefinedFunctionScope Scope(*this, Conv); 9079 DiagnosticErrorTrap Trap(Diags); 9080 9081 // Copy-initialize the lambda object as needed to capture 9082 Expr *This = ActOnCXXThis(CurrentLocation).take(); 9083 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take(); 9084 ExprResult Init = PerformCopyInitialization( 9085 InitializedEntity::InitializeBlock(CurrentLocation, 9086 DerefThis->getType(), 9087 /*NRVO=*/false), 9088 CurrentLocation, DerefThis); 9089 if (!Init.isInvalid()) 9090 Init = ActOnFinishFullExpr(Init.take()); 9091 9092 if (!Init.isInvalid()) 9093 Conv->setLambdaToBlockPointerCopyInit(Init.take()); 9094 else { 9095 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 9096 } 9097 9098 // Introduce a bogus body, which IR generation will override anyway. 9099 Conv->setBody(new (Context) CompoundStmt(Context, 0, 0, Conv->getLocation(), 9100 Conv->getLocation())); 9101 9102 if (ASTMutationListener *L = getASTMutationListener()) { 9103 L->CompletedImplicitDefinition(Conv); 9104 } 9105} 9106 9107ExprResult 9108Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 9109 CXXConstructorDecl *Constructor, 9110 MultiExprArg ExprArgs, 9111 bool HadMultipleCandidates, 9112 bool RequiresZeroInit, 9113 unsigned ConstructKind, 9114 SourceRange ParenRange) { 9115 bool Elidable = false; 9116 9117 // C++0x [class.copy]p34: 9118 // When certain criteria are met, an implementation is allowed to 9119 // omit the copy/move construction of a class object, even if the 9120 // copy/move constructor and/or destructor for the object have 9121 // side effects. [...] 9122 // - when a temporary class object that has not been bound to a 9123 // reference (12.2) would be copied/moved to a class object 9124 // with the same cv-unqualified type, the copy/move operation 9125 // can be omitted by constructing the temporary object 9126 // directly into the target of the omitted copy/move 9127 if (ConstructKind == CXXConstructExpr::CK_Complete && 9128 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) { 9129 Expr *SubExpr = ((Expr **)ExprArgs.get())[0]; 9130 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent()); 9131 } 9132 9133 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 9134 Elidable, move(ExprArgs), HadMultipleCandidates, 9135 RequiresZeroInit, ConstructKind, ParenRange); 9136} 9137 9138/// BuildCXXConstructExpr - Creates a complete call to a constructor, 9139/// including handling of its default argument expressions. 9140ExprResult 9141Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 9142 CXXConstructorDecl *Constructor, bool Elidable, 9143 MultiExprArg ExprArgs, 9144 bool HadMultipleCandidates, 9145 bool RequiresZeroInit, 9146 unsigned ConstructKind, 9147 SourceRange ParenRange) { 9148 unsigned NumExprs = ExprArgs.size(); 9149 Expr **Exprs = (Expr **)ExprArgs.release(); 9150 9151 for (specific_attr_iterator<NonNullAttr> 9152 i = Constructor->specific_attr_begin<NonNullAttr>(), 9153 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) { 9154 const NonNullAttr *NonNull = *i; 9155 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc); 9156 } 9157 9158 MarkFunctionReferenced(ConstructLoc, Constructor); 9159 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc, 9160 Constructor, Elidable, Exprs, NumExprs, 9161 HadMultipleCandidates, /*FIXME*/false, 9162 RequiresZeroInit, 9163 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 9164 ParenRange)); 9165} 9166 9167bool Sema::InitializeVarWithConstructor(VarDecl *VD, 9168 CXXConstructorDecl *Constructor, 9169 MultiExprArg Exprs, 9170 bool HadMultipleCandidates) { 9171 // FIXME: Provide the correct paren SourceRange when available. 9172 ExprResult TempResult = 9173 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor, 9174 move(Exprs), HadMultipleCandidates, false, 9175 CXXConstructExpr::CK_Complete, SourceRange()); 9176 if (TempResult.isInvalid()) 9177 return true; 9178 9179 Expr *Temp = TempResult.takeAs<Expr>(); 9180 CheckImplicitConversions(Temp, VD->getLocation()); 9181 MarkFunctionReferenced(VD->getLocation(), Constructor); 9182 Temp = MaybeCreateExprWithCleanups(Temp); 9183 VD->setInit(Temp); 9184 9185 return false; 9186} 9187 9188void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 9189 if (VD->isInvalidDecl()) return; 9190 9191 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 9192 if (ClassDecl->isInvalidDecl()) return; 9193 if (ClassDecl->hasTrivialDestructor()) return; 9194 if (ClassDecl->isDependentContext()) return; 9195 9196 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 9197 MarkFunctionReferenced(VD->getLocation(), Destructor); 9198 CheckDestructorAccess(VD->getLocation(), Destructor, 9199 PDiag(diag::err_access_dtor_var) 9200 << VD->getDeclName() 9201 << VD->getType()); 9202 9203 if (!VD->hasGlobalStorage()) return; 9204 9205 // Emit warning for non-trivial dtor in global scope (a real global, 9206 // class-static, function-static). 9207 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 9208 9209 // TODO: this should be re-enabled for static locals by !CXAAtExit 9210 if (!VD->isStaticLocal()) 9211 Diag(VD->getLocation(), diag::warn_global_destructor); 9212} 9213 9214/// \brief Given a constructor and the set of arguments provided for the 9215/// constructor, convert the arguments and add any required default arguments 9216/// to form a proper call to this constructor. 9217/// 9218/// \returns true if an error occurred, false otherwise. 9219bool 9220Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 9221 MultiExprArg ArgsPtr, 9222 SourceLocation Loc, 9223 ASTOwningVector<Expr*> &ConvertedArgs) { 9224 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 9225 unsigned NumArgs = ArgsPtr.size(); 9226 Expr **Args = (Expr **)ArgsPtr.get(); 9227 9228 const FunctionProtoType *Proto 9229 = Constructor->getType()->getAs<FunctionProtoType>(); 9230 assert(Proto && "Constructor without a prototype?"); 9231 unsigned NumArgsInProto = Proto->getNumArgs(); 9232 9233 // If too few arguments are available, we'll fill in the rest with defaults. 9234 if (NumArgs < NumArgsInProto) 9235 ConvertedArgs.reserve(NumArgsInProto); 9236 else 9237 ConvertedArgs.reserve(NumArgs); 9238 9239 VariadicCallType CallType = 9240 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 9241 SmallVector<Expr *, 8> AllArgs; 9242 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 9243 Proto, 0, Args, NumArgs, AllArgs, 9244 CallType); 9245 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 9246 return Invalid; 9247} 9248 9249static inline bool 9250CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 9251 const FunctionDecl *FnDecl) { 9252 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 9253 if (isa<NamespaceDecl>(DC)) { 9254 return SemaRef.Diag(FnDecl->getLocation(), 9255 diag::err_operator_new_delete_declared_in_namespace) 9256 << FnDecl->getDeclName(); 9257 } 9258 9259 if (isa<TranslationUnitDecl>(DC) && 9260 FnDecl->getStorageClass() == SC_Static) { 9261 return SemaRef.Diag(FnDecl->getLocation(), 9262 diag::err_operator_new_delete_declared_static) 9263 << FnDecl->getDeclName(); 9264 } 9265 9266 return false; 9267} 9268 9269static inline bool 9270CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 9271 CanQualType ExpectedResultType, 9272 CanQualType ExpectedFirstParamType, 9273 unsigned DependentParamTypeDiag, 9274 unsigned InvalidParamTypeDiag) { 9275 QualType ResultType = 9276 FnDecl->getType()->getAs<FunctionType>()->getResultType(); 9277 9278 // Check that the result type is not dependent. 9279 if (ResultType->isDependentType()) 9280 return SemaRef.Diag(FnDecl->getLocation(), 9281 diag::err_operator_new_delete_dependent_result_type) 9282 << FnDecl->getDeclName() << ExpectedResultType; 9283 9284 // Check that the result type is what we expect. 9285 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 9286 return SemaRef.Diag(FnDecl->getLocation(), 9287 diag::err_operator_new_delete_invalid_result_type) 9288 << FnDecl->getDeclName() << ExpectedResultType; 9289 9290 // A function template must have at least 2 parameters. 9291 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 9292 return SemaRef.Diag(FnDecl->getLocation(), 9293 diag::err_operator_new_delete_template_too_few_parameters) 9294 << FnDecl->getDeclName(); 9295 9296 // The function decl must have at least 1 parameter. 9297 if (FnDecl->getNumParams() == 0) 9298 return SemaRef.Diag(FnDecl->getLocation(), 9299 diag::err_operator_new_delete_too_few_parameters) 9300 << FnDecl->getDeclName(); 9301 9302 // Check the the first parameter type is not dependent. 9303 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 9304 if (FirstParamType->isDependentType()) 9305 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 9306 << FnDecl->getDeclName() << ExpectedFirstParamType; 9307 9308 // Check that the first parameter type is what we expect. 9309 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 9310 ExpectedFirstParamType) 9311 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 9312 << FnDecl->getDeclName() << ExpectedFirstParamType; 9313 9314 return false; 9315} 9316 9317static bool 9318CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 9319 // C++ [basic.stc.dynamic.allocation]p1: 9320 // A program is ill-formed if an allocation function is declared in a 9321 // namespace scope other than global scope or declared static in global 9322 // scope. 9323 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 9324 return true; 9325 9326 CanQualType SizeTy = 9327 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 9328 9329 // C++ [basic.stc.dynamic.allocation]p1: 9330 // The return type shall be void*. The first parameter shall have type 9331 // std::size_t. 9332 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 9333 SizeTy, 9334 diag::err_operator_new_dependent_param_type, 9335 diag::err_operator_new_param_type)) 9336 return true; 9337 9338 // C++ [basic.stc.dynamic.allocation]p1: 9339 // The first parameter shall not have an associated default argument. 9340 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 9341 return SemaRef.Diag(FnDecl->getLocation(), 9342 diag::err_operator_new_default_arg) 9343 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 9344 9345 return false; 9346} 9347 9348static bool 9349CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 9350 // C++ [basic.stc.dynamic.deallocation]p1: 9351 // A program is ill-formed if deallocation functions are declared in a 9352 // namespace scope other than global scope or declared static in global 9353 // scope. 9354 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 9355 return true; 9356 9357 // C++ [basic.stc.dynamic.deallocation]p2: 9358 // Each deallocation function shall return void and its first parameter 9359 // shall be void*. 9360 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 9361 SemaRef.Context.VoidPtrTy, 9362 diag::err_operator_delete_dependent_param_type, 9363 diag::err_operator_delete_param_type)) 9364 return true; 9365 9366 return false; 9367} 9368 9369/// CheckOverloadedOperatorDeclaration - Check whether the declaration 9370/// of this overloaded operator is well-formed. If so, returns false; 9371/// otherwise, emits appropriate diagnostics and returns true. 9372bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 9373 assert(FnDecl && FnDecl->isOverloadedOperator() && 9374 "Expected an overloaded operator declaration"); 9375 9376 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 9377 9378 // C++ [over.oper]p5: 9379 // The allocation and deallocation functions, operator new, 9380 // operator new[], operator delete and operator delete[], are 9381 // described completely in 3.7.3. The attributes and restrictions 9382 // found in the rest of this subclause do not apply to them unless 9383 // explicitly stated in 3.7.3. 9384 if (Op == OO_Delete || Op == OO_Array_Delete) 9385 return CheckOperatorDeleteDeclaration(*this, FnDecl); 9386 9387 if (Op == OO_New || Op == OO_Array_New) 9388 return CheckOperatorNewDeclaration(*this, FnDecl); 9389 9390 // C++ [over.oper]p6: 9391 // An operator function shall either be a non-static member 9392 // function or be a non-member function and have at least one 9393 // parameter whose type is a class, a reference to a class, an 9394 // enumeration, or a reference to an enumeration. 9395 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 9396 if (MethodDecl->isStatic()) 9397 return Diag(FnDecl->getLocation(), 9398 diag::err_operator_overload_static) << FnDecl->getDeclName(); 9399 } else { 9400 bool ClassOrEnumParam = false; 9401 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 9402 ParamEnd = FnDecl->param_end(); 9403 Param != ParamEnd; ++Param) { 9404 QualType ParamType = (*Param)->getType().getNonReferenceType(); 9405 if (ParamType->isDependentType() || ParamType->isRecordType() || 9406 ParamType->isEnumeralType()) { 9407 ClassOrEnumParam = true; 9408 break; 9409 } 9410 } 9411 9412 if (!ClassOrEnumParam) 9413 return Diag(FnDecl->getLocation(), 9414 diag::err_operator_overload_needs_class_or_enum) 9415 << FnDecl->getDeclName(); 9416 } 9417 9418 // C++ [over.oper]p8: 9419 // An operator function cannot have default arguments (8.3.6), 9420 // except where explicitly stated below. 9421 // 9422 // Only the function-call operator allows default arguments 9423 // (C++ [over.call]p1). 9424 if (Op != OO_Call) { 9425 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(); 9426 Param != FnDecl->param_end(); ++Param) { 9427 if ((*Param)->hasDefaultArg()) 9428 return Diag((*Param)->getLocation(), 9429 diag::err_operator_overload_default_arg) 9430 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange(); 9431 } 9432 } 9433 9434 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 9435 { false, false, false } 9436#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 9437 , { Unary, Binary, MemberOnly } 9438#include "clang/Basic/OperatorKinds.def" 9439 }; 9440 9441 bool CanBeUnaryOperator = OperatorUses[Op][0]; 9442 bool CanBeBinaryOperator = OperatorUses[Op][1]; 9443 bool MustBeMemberOperator = OperatorUses[Op][2]; 9444 9445 // C++ [over.oper]p8: 9446 // [...] Operator functions cannot have more or fewer parameters 9447 // than the number required for the corresponding operator, as 9448 // described in the rest of this subclause. 9449 unsigned NumParams = FnDecl->getNumParams() 9450 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 9451 if (Op != OO_Call && 9452 ((NumParams == 1 && !CanBeUnaryOperator) || 9453 (NumParams == 2 && !CanBeBinaryOperator) || 9454 (NumParams < 1) || (NumParams > 2))) { 9455 // We have the wrong number of parameters. 9456 unsigned ErrorKind; 9457 if (CanBeUnaryOperator && CanBeBinaryOperator) { 9458 ErrorKind = 2; // 2 -> unary or binary. 9459 } else if (CanBeUnaryOperator) { 9460 ErrorKind = 0; // 0 -> unary 9461 } else { 9462 assert(CanBeBinaryOperator && 9463 "All non-call overloaded operators are unary or binary!"); 9464 ErrorKind = 1; // 1 -> binary 9465 } 9466 9467 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 9468 << FnDecl->getDeclName() << NumParams << ErrorKind; 9469 } 9470 9471 // Overloaded operators other than operator() cannot be variadic. 9472 if (Op != OO_Call && 9473 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 9474 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 9475 << FnDecl->getDeclName(); 9476 } 9477 9478 // Some operators must be non-static member functions. 9479 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 9480 return Diag(FnDecl->getLocation(), 9481 diag::err_operator_overload_must_be_member) 9482 << FnDecl->getDeclName(); 9483 } 9484 9485 // C++ [over.inc]p1: 9486 // The user-defined function called operator++ implements the 9487 // prefix and postfix ++ operator. If this function is a member 9488 // function with no parameters, or a non-member function with one 9489 // parameter of class or enumeration type, it defines the prefix 9490 // increment operator ++ for objects of that type. If the function 9491 // is a member function with one parameter (which shall be of type 9492 // int) or a non-member function with two parameters (the second 9493 // of which shall be of type int), it defines the postfix 9494 // increment operator ++ for objects of that type. 9495 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 9496 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 9497 bool ParamIsInt = false; 9498 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>()) 9499 ParamIsInt = BT->getKind() == BuiltinType::Int; 9500 9501 if (!ParamIsInt) 9502 return Diag(LastParam->getLocation(), 9503 diag::err_operator_overload_post_incdec_must_be_int) 9504 << LastParam->getType() << (Op == OO_MinusMinus); 9505 } 9506 9507 return false; 9508} 9509 9510/// CheckLiteralOperatorDeclaration - Check whether the declaration 9511/// of this literal operator function is well-formed. If so, returns 9512/// false; otherwise, emits appropriate diagnostics and returns true. 9513bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 9514 DeclContext *DC = FnDecl->getDeclContext(); 9515 Decl::Kind Kind = DC->getDeclKind(); 9516 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace && 9517 Kind != Decl::LinkageSpec) { 9518 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 9519 << FnDecl->getDeclName(); 9520 return true; 9521 } 9522 9523 bool Valid = false; 9524 9525 // template <char...> type operator "" name() is the only valid template 9526 // signature, and the only valid signature with no parameters. 9527 if (FnDecl->param_size() == 0) { 9528 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) { 9529 // Must have only one template parameter 9530 TemplateParameterList *Params = TpDecl->getTemplateParameters(); 9531 if (Params->size() == 1) { 9532 NonTypeTemplateParmDecl *PmDecl = 9533 cast<NonTypeTemplateParmDecl>(Params->getParam(0)); 9534 9535 // The template parameter must be a char parameter pack. 9536 if (PmDecl && PmDecl->isTemplateParameterPack() && 9537 Context.hasSameType(PmDecl->getType(), Context.CharTy)) 9538 Valid = true; 9539 } 9540 } 9541 } else { 9542 // Check the first parameter 9543 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 9544 9545 QualType T = (*Param)->getType(); 9546 9547 // unsigned long long int, long double, and any character type are allowed 9548 // as the only parameters. 9549 if (Context.hasSameType(T, Context.UnsignedLongLongTy) || 9550 Context.hasSameType(T, Context.LongDoubleTy) || 9551 Context.hasSameType(T, Context.CharTy) || 9552 Context.hasSameType(T, Context.WCharTy) || 9553 Context.hasSameType(T, Context.Char16Ty) || 9554 Context.hasSameType(T, Context.Char32Ty)) { 9555 if (++Param == FnDecl->param_end()) 9556 Valid = true; 9557 goto FinishedParams; 9558 } 9559 9560 // Otherwise it must be a pointer to const; let's strip those qualifiers. 9561 const PointerType *PT = T->getAs<PointerType>(); 9562 if (!PT) 9563 goto FinishedParams; 9564 T = PT->getPointeeType(); 9565 if (!T.isConstQualified()) 9566 goto FinishedParams; 9567 T = T.getUnqualifiedType(); 9568 9569 // Move on to the second parameter; 9570 ++Param; 9571 9572 // If there is no second parameter, the first must be a const char * 9573 if (Param == FnDecl->param_end()) { 9574 if (Context.hasSameType(T, Context.CharTy)) 9575 Valid = true; 9576 goto FinishedParams; 9577 } 9578 9579 // const char *, const wchar_t*, const char16_t*, and const char32_t* 9580 // are allowed as the first parameter to a two-parameter function 9581 if (!(Context.hasSameType(T, Context.CharTy) || 9582 Context.hasSameType(T, Context.WCharTy) || 9583 Context.hasSameType(T, Context.Char16Ty) || 9584 Context.hasSameType(T, Context.Char32Ty))) 9585 goto FinishedParams; 9586 9587 // The second and final parameter must be an std::size_t 9588 T = (*Param)->getType().getUnqualifiedType(); 9589 if (Context.hasSameType(T, Context.getSizeType()) && 9590 ++Param == FnDecl->param_end()) 9591 Valid = true; 9592 } 9593 9594 // FIXME: This diagnostic is absolutely terrible. 9595FinishedParams: 9596 if (!Valid) { 9597 Diag(FnDecl->getLocation(), diag::err_literal_operator_params) 9598 << FnDecl->getDeclName(); 9599 return true; 9600 } 9601 9602 StringRef LiteralName 9603 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 9604 if (LiteralName[0] != '_') { 9605 // C++0x [usrlit.suffix]p1: 9606 // Literal suffix identifiers that do not start with an underscore are 9607 // reserved for future standardization. 9608 bool IsHexFloat = true; 9609 if (LiteralName.size() > 1 && 9610 (LiteralName[0] == 'P' || LiteralName[0] == 'p')) { 9611 for (unsigned I = 1, N = LiteralName.size(); I < N; ++I) { 9612 if (!isdigit(LiteralName[I])) { 9613 IsHexFloat = false; 9614 break; 9615 } 9616 } 9617 } 9618 9619 if (IsHexFloat) 9620 Diag(FnDecl->getLocation(), diag::warn_user_literal_hexfloat) 9621 << LiteralName; 9622 else 9623 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved); 9624 } 9625 9626 return false; 9627} 9628 9629/// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 9630/// linkage specification, including the language and (if present) 9631/// the '{'. ExternLoc is the location of the 'extern', LangLoc is 9632/// the location of the language string literal, which is provided 9633/// by Lang/StrSize. LBraceLoc, if valid, provides the location of 9634/// the '{' brace. Otherwise, this linkage specification does not 9635/// have any braces. 9636Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 9637 SourceLocation LangLoc, 9638 StringRef Lang, 9639 SourceLocation LBraceLoc) { 9640 LinkageSpecDecl::LanguageIDs Language; 9641 if (Lang == "\"C\"") 9642 Language = LinkageSpecDecl::lang_c; 9643 else if (Lang == "\"C++\"") 9644 Language = LinkageSpecDecl::lang_cxx; 9645 else { 9646 Diag(LangLoc, diag::err_bad_language); 9647 return 0; 9648 } 9649 9650 // FIXME: Add all the various semantics of linkage specifications 9651 9652 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, 9653 ExternLoc, LangLoc, Language); 9654 CurContext->addDecl(D); 9655 PushDeclContext(S, D); 9656 return D; 9657} 9658 9659/// ActOnFinishLinkageSpecification - Complete the definition of 9660/// the C++ linkage specification LinkageSpec. If RBraceLoc is 9661/// valid, it's the position of the closing '}' brace in a linkage 9662/// specification that uses braces. 9663Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 9664 Decl *LinkageSpec, 9665 SourceLocation RBraceLoc) { 9666 if (LinkageSpec) { 9667 if (RBraceLoc.isValid()) { 9668 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 9669 LSDecl->setRBraceLoc(RBraceLoc); 9670 } 9671 PopDeclContext(); 9672 } 9673 return LinkageSpec; 9674} 9675 9676/// \brief Perform semantic analysis for the variable declaration that 9677/// occurs within a C++ catch clause, returning the newly-created 9678/// variable. 9679VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 9680 TypeSourceInfo *TInfo, 9681 SourceLocation StartLoc, 9682 SourceLocation Loc, 9683 IdentifierInfo *Name) { 9684 bool Invalid = false; 9685 QualType ExDeclType = TInfo->getType(); 9686 9687 // Arrays and functions decay. 9688 if (ExDeclType->isArrayType()) 9689 ExDeclType = Context.getArrayDecayedType(ExDeclType); 9690 else if (ExDeclType->isFunctionType()) 9691 ExDeclType = Context.getPointerType(ExDeclType); 9692 9693 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 9694 // The exception-declaration shall not denote a pointer or reference to an 9695 // incomplete type, other than [cv] void*. 9696 // N2844 forbids rvalue references. 9697 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 9698 Diag(Loc, diag::err_catch_rvalue_ref); 9699 Invalid = true; 9700 } 9701 9702 QualType BaseType = ExDeclType; 9703 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 9704 unsigned DK = diag::err_catch_incomplete; 9705 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 9706 BaseType = Ptr->getPointeeType(); 9707 Mode = 1; 9708 DK = diag::err_catch_incomplete_ptr; 9709 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 9710 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 9711 BaseType = Ref->getPointeeType(); 9712 Mode = 2; 9713 DK = diag::err_catch_incomplete_ref; 9714 } 9715 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 9716 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 9717 Invalid = true; 9718 9719 if (!Invalid && !ExDeclType->isDependentType() && 9720 RequireNonAbstractType(Loc, ExDeclType, 9721 diag::err_abstract_type_in_decl, 9722 AbstractVariableType)) 9723 Invalid = true; 9724 9725 // Only the non-fragile NeXT runtime currently supports C++ catches 9726 // of ObjC types, and no runtime supports catching ObjC types by value. 9727 if (!Invalid && getLangOptions().ObjC1) { 9728 QualType T = ExDeclType; 9729 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 9730 T = RT->getPointeeType(); 9731 9732 if (T->isObjCObjectType()) { 9733 Diag(Loc, diag::err_objc_object_catch); 9734 Invalid = true; 9735 } else if (T->isObjCObjectPointerType()) { 9736 if (!getLangOptions().ObjCNonFragileABI) 9737 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 9738 } 9739 } 9740 9741 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 9742 ExDeclType, TInfo, SC_None, SC_None); 9743 ExDecl->setExceptionVariable(true); 9744 9745 // In ARC, infer 'retaining' for variables of retainable type. 9746 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 9747 Invalid = true; 9748 9749 if (!Invalid && !ExDeclType->isDependentType()) { 9750 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 9751 // C++ [except.handle]p16: 9752 // The object declared in an exception-declaration or, if the 9753 // exception-declaration does not specify a name, a temporary (12.2) is 9754 // copy-initialized (8.5) from the exception object. [...] 9755 // The object is destroyed when the handler exits, after the destruction 9756 // of any automatic objects initialized within the handler. 9757 // 9758 // We just pretend to initialize the object with itself, then make sure 9759 // it can be destroyed later. 9760 QualType initType = ExDeclType; 9761 9762 InitializedEntity entity = 9763 InitializedEntity::InitializeVariable(ExDecl); 9764 InitializationKind initKind = 9765 InitializationKind::CreateCopy(Loc, SourceLocation()); 9766 9767 Expr *opaqueValue = 9768 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 9769 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1); 9770 ExprResult result = sequence.Perform(*this, entity, initKind, 9771 MultiExprArg(&opaqueValue, 1)); 9772 if (result.isInvalid()) 9773 Invalid = true; 9774 else { 9775 // If the constructor used was non-trivial, set this as the 9776 // "initializer". 9777 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take()); 9778 if (!construct->getConstructor()->isTrivial()) { 9779 Expr *init = MaybeCreateExprWithCleanups(construct); 9780 ExDecl->setInit(init); 9781 } 9782 9783 // And make sure it's destructable. 9784 FinalizeVarWithDestructor(ExDecl, recordType); 9785 } 9786 } 9787 } 9788 9789 if (Invalid) 9790 ExDecl->setInvalidDecl(); 9791 9792 return ExDecl; 9793} 9794 9795/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 9796/// handler. 9797Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 9798 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 9799 bool Invalid = D.isInvalidType(); 9800 9801 // Check for unexpanded parameter packs. 9802 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 9803 UPPC_ExceptionType)) { 9804 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 9805 D.getIdentifierLoc()); 9806 Invalid = true; 9807 } 9808 9809 IdentifierInfo *II = D.getIdentifier(); 9810 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 9811 LookupOrdinaryName, 9812 ForRedeclaration)) { 9813 // The scope should be freshly made just for us. There is just no way 9814 // it contains any previous declaration. 9815 assert(!S->isDeclScope(PrevDecl)); 9816 if (PrevDecl->isTemplateParameter()) { 9817 // Maybe we will complain about the shadowed template parameter. 9818 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 9819 PrevDecl = 0; 9820 } 9821 } 9822 9823 if (D.getCXXScopeSpec().isSet() && !Invalid) { 9824 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 9825 << D.getCXXScopeSpec().getRange(); 9826 Invalid = true; 9827 } 9828 9829 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 9830 D.getSourceRange().getBegin(), 9831 D.getIdentifierLoc(), 9832 D.getIdentifier()); 9833 if (Invalid) 9834 ExDecl->setInvalidDecl(); 9835 9836 // Add the exception declaration into this scope. 9837 if (II) 9838 PushOnScopeChains(ExDecl, S); 9839 else 9840 CurContext->addDecl(ExDecl); 9841 9842 ProcessDeclAttributes(S, ExDecl, D); 9843 return ExDecl; 9844} 9845 9846Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 9847 Expr *AssertExpr, 9848 Expr *AssertMessageExpr_, 9849 SourceLocation RParenLoc) { 9850 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_); 9851 9852 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) { 9853 // In a static_assert-declaration, the constant-expression shall be a 9854 // constant expression that can be contextually converted to bool. 9855 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 9856 if (Converted.isInvalid()) 9857 return 0; 9858 9859 llvm::APSInt Cond; 9860 if (VerifyIntegerConstantExpression(Converted.get(), &Cond, 9861 PDiag(diag::err_static_assert_expression_is_not_constant), 9862 /*AllowFold=*/false).isInvalid()) 9863 return 0; 9864 9865 if (!Cond) 9866 Diag(StaticAssertLoc, diag::err_static_assert_failed) 9867 << AssertMessage->getString() << AssertExpr->getSourceRange(); 9868 } 9869 9870 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 9871 return 0; 9872 9873 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 9874 AssertExpr, AssertMessage, RParenLoc); 9875 9876 CurContext->addDecl(Decl); 9877 return Decl; 9878} 9879 9880/// \brief Perform semantic analysis of the given friend type declaration. 9881/// 9882/// \returns A friend declaration that. 9883FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation Loc, 9884 SourceLocation FriendLoc, 9885 TypeSourceInfo *TSInfo) { 9886 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 9887 9888 QualType T = TSInfo->getType(); 9889 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 9890 9891 // C++03 [class.friend]p2: 9892 // An elaborated-type-specifier shall be used in a friend declaration 9893 // for a class.* 9894 // 9895 // * The class-key of the elaborated-type-specifier is required. 9896 if (!ActiveTemplateInstantiations.empty()) { 9897 // Do not complain about the form of friend template types during 9898 // template instantiation; we will already have complained when the 9899 // template was declared. 9900 } else if (!T->isElaboratedTypeSpecifier()) { 9901 // If we evaluated the type to a record type, suggest putting 9902 // a tag in front. 9903 if (const RecordType *RT = T->getAs<RecordType>()) { 9904 RecordDecl *RD = RT->getDecl(); 9905 9906 std::string InsertionText = std::string(" ") + RD->getKindName(); 9907 9908 Diag(TypeRange.getBegin(), 9909 getLangOptions().CPlusPlus0x ? 9910 diag::warn_cxx98_compat_unelaborated_friend_type : 9911 diag::ext_unelaborated_friend_type) 9912 << (unsigned) RD->getTagKind() 9913 << T 9914 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc), 9915 InsertionText); 9916 } else { 9917 Diag(FriendLoc, 9918 getLangOptions().CPlusPlus0x ? 9919 diag::warn_cxx98_compat_nonclass_type_friend : 9920 diag::ext_nonclass_type_friend) 9921 << T 9922 << SourceRange(FriendLoc, TypeRange.getEnd()); 9923 } 9924 } else if (T->getAs<EnumType>()) { 9925 Diag(FriendLoc, 9926 getLangOptions().CPlusPlus0x ? 9927 diag::warn_cxx98_compat_enum_friend : 9928 diag::ext_enum_friend) 9929 << T 9930 << SourceRange(FriendLoc, TypeRange.getEnd()); 9931 } 9932 9933 // C++0x [class.friend]p3: 9934 // If the type specifier in a friend declaration designates a (possibly 9935 // cv-qualified) class type, that class is declared as a friend; otherwise, 9936 // the friend declaration is ignored. 9937 9938 // FIXME: C++0x has some syntactic restrictions on friend type declarations 9939 // in [class.friend]p3 that we do not implement. 9940 9941 return FriendDecl::Create(Context, CurContext, Loc, TSInfo, FriendLoc); 9942} 9943 9944/// Handle a friend tag declaration where the scope specifier was 9945/// templated. 9946Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 9947 unsigned TagSpec, SourceLocation TagLoc, 9948 CXXScopeSpec &SS, 9949 IdentifierInfo *Name, SourceLocation NameLoc, 9950 AttributeList *Attr, 9951 MultiTemplateParamsArg TempParamLists) { 9952 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 9953 9954 bool isExplicitSpecialization = false; 9955 bool Invalid = false; 9956 9957 if (TemplateParameterList *TemplateParams 9958 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS, 9959 TempParamLists.get(), 9960 TempParamLists.size(), 9961 /*friend*/ true, 9962 isExplicitSpecialization, 9963 Invalid)) { 9964 if (TemplateParams->size() > 0) { 9965 // This is a declaration of a class template. 9966 if (Invalid) 9967 return 0; 9968 9969 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, 9970 SS, Name, NameLoc, Attr, 9971 TemplateParams, AS_public, 9972 /*ModulePrivateLoc=*/SourceLocation(), 9973 TempParamLists.size() - 1, 9974 (TemplateParameterList**) TempParamLists.release()).take(); 9975 } else { 9976 // The "template<>" header is extraneous. 9977 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 9978 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 9979 isExplicitSpecialization = true; 9980 } 9981 } 9982 9983 if (Invalid) return 0; 9984 9985 bool isAllExplicitSpecializations = true; 9986 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 9987 if (TempParamLists.get()[I]->size()) { 9988 isAllExplicitSpecializations = false; 9989 break; 9990 } 9991 } 9992 9993 // FIXME: don't ignore attributes. 9994 9995 // If it's explicit specializations all the way down, just forget 9996 // about the template header and build an appropriate non-templated 9997 // friend. TODO: for source fidelity, remember the headers. 9998 if (isAllExplicitSpecializations) { 9999 if (SS.isEmpty()) { 10000 bool Owned = false; 10001 bool IsDependent = false; 10002 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 10003 Attr, AS_public, 10004 /*ModulePrivateLoc=*/SourceLocation(), 10005 MultiTemplateParamsArg(), Owned, IsDependent, 10006 /*ScopedEnumKWLoc=*/SourceLocation(), 10007 /*ScopedEnumUsesClassTag=*/false, 10008 /*UnderlyingType=*/TypeResult()); 10009 } 10010 10011 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 10012 ElaboratedTypeKeyword Keyword 10013 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 10014 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 10015 *Name, NameLoc); 10016 if (T.isNull()) 10017 return 0; 10018 10019 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 10020 if (isa<DependentNameType>(T)) { 10021 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc()); 10022 TL.setElaboratedKeywordLoc(TagLoc); 10023 TL.setQualifierLoc(QualifierLoc); 10024 TL.setNameLoc(NameLoc); 10025 } else { 10026 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc()); 10027 TL.setElaboratedKeywordLoc(TagLoc); 10028 TL.setQualifierLoc(QualifierLoc); 10029 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc); 10030 } 10031 10032 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 10033 TSI, FriendLoc); 10034 Friend->setAccess(AS_public); 10035 CurContext->addDecl(Friend); 10036 return Friend; 10037 } 10038 10039 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 10040 10041 10042 10043 // Handle the case of a templated-scope friend class. e.g. 10044 // template <class T> class A<T>::B; 10045 // FIXME: we don't support these right now. 10046 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 10047 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 10048 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 10049 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc()); 10050 TL.setElaboratedKeywordLoc(TagLoc); 10051 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 10052 TL.setNameLoc(NameLoc); 10053 10054 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 10055 TSI, FriendLoc); 10056 Friend->setAccess(AS_public); 10057 Friend->setUnsupportedFriend(true); 10058 CurContext->addDecl(Friend); 10059 return Friend; 10060} 10061 10062 10063/// Handle a friend type declaration. This works in tandem with 10064/// ActOnTag. 10065/// 10066/// Notes on friend class templates: 10067/// 10068/// We generally treat friend class declarations as if they were 10069/// declaring a class. So, for example, the elaborated type specifier 10070/// in a friend declaration is required to obey the restrictions of a 10071/// class-head (i.e. no typedefs in the scope chain), template 10072/// parameters are required to match up with simple template-ids, &c. 10073/// However, unlike when declaring a template specialization, it's 10074/// okay to refer to a template specialization without an empty 10075/// template parameter declaration, e.g. 10076/// friend class A<T>::B<unsigned>; 10077/// We permit this as a special case; if there are any template 10078/// parameters present at all, require proper matching, i.e. 10079/// template <> template <class T> friend class A<int>::B; 10080Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 10081 MultiTemplateParamsArg TempParams) { 10082 SourceLocation Loc = DS.getSourceRange().getBegin(); 10083 10084 assert(DS.isFriendSpecified()); 10085 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 10086 10087 // Try to convert the decl specifier to a type. This works for 10088 // friend templates because ActOnTag never produces a ClassTemplateDecl 10089 // for a TUK_Friend. 10090 Declarator TheDeclarator(DS, Declarator::MemberContext); 10091 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 10092 QualType T = TSI->getType(); 10093 if (TheDeclarator.isInvalidType()) 10094 return 0; 10095 10096 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 10097 return 0; 10098 10099 // This is definitely an error in C++98. It's probably meant to 10100 // be forbidden in C++0x, too, but the specification is just 10101 // poorly written. 10102 // 10103 // The problem is with declarations like the following: 10104 // template <T> friend A<T>::foo; 10105 // where deciding whether a class C is a friend or not now hinges 10106 // on whether there exists an instantiation of A that causes 10107 // 'foo' to equal C. There are restrictions on class-heads 10108 // (which we declare (by fiat) elaborated friend declarations to 10109 // be) that makes this tractable. 10110 // 10111 // FIXME: handle "template <> friend class A<T>;", which 10112 // is possibly well-formed? Who even knows? 10113 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 10114 Diag(Loc, diag::err_tagless_friend_type_template) 10115 << DS.getSourceRange(); 10116 return 0; 10117 } 10118 10119 // C++98 [class.friend]p1: A friend of a class is a function 10120 // or class that is not a member of the class . . . 10121 // This is fixed in DR77, which just barely didn't make the C++03 10122 // deadline. It's also a very silly restriction that seriously 10123 // affects inner classes and which nobody else seems to implement; 10124 // thus we never diagnose it, not even in -pedantic. 10125 // 10126 // But note that we could warn about it: it's always useless to 10127 // friend one of your own members (it's not, however, worthless to 10128 // friend a member of an arbitrary specialization of your template). 10129 10130 Decl *D; 10131 if (unsigned NumTempParamLists = TempParams.size()) 10132 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 10133 NumTempParamLists, 10134 TempParams.release(), 10135 TSI, 10136 DS.getFriendSpecLoc()); 10137 else 10138 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 10139 10140 if (!D) 10141 return 0; 10142 10143 D->setAccess(AS_public); 10144 CurContext->addDecl(D); 10145 10146 return D; 10147} 10148 10149Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 10150 MultiTemplateParamsArg TemplateParams) { 10151 const DeclSpec &DS = D.getDeclSpec(); 10152 10153 assert(DS.isFriendSpecified()); 10154 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 10155 10156 SourceLocation Loc = D.getIdentifierLoc(); 10157 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 10158 10159 // C++ [class.friend]p1 10160 // A friend of a class is a function or class.... 10161 // Note that this sees through typedefs, which is intended. 10162 // It *doesn't* see through dependent types, which is correct 10163 // according to [temp.arg.type]p3: 10164 // If a declaration acquires a function type through a 10165 // type dependent on a template-parameter and this causes 10166 // a declaration that does not use the syntactic form of a 10167 // function declarator to have a function type, the program 10168 // is ill-formed. 10169 if (!TInfo->getType()->isFunctionType()) { 10170 Diag(Loc, diag::err_unexpected_friend); 10171 10172 // It might be worthwhile to try to recover by creating an 10173 // appropriate declaration. 10174 return 0; 10175 } 10176 10177 // C++ [namespace.memdef]p3 10178 // - If a friend declaration in a non-local class first declares a 10179 // class or function, the friend class or function is a member 10180 // of the innermost enclosing namespace. 10181 // - The name of the friend is not found by simple name lookup 10182 // until a matching declaration is provided in that namespace 10183 // scope (either before or after the class declaration granting 10184 // friendship). 10185 // - If a friend function is called, its name may be found by the 10186 // name lookup that considers functions from namespaces and 10187 // classes associated with the types of the function arguments. 10188 // - When looking for a prior declaration of a class or a function 10189 // declared as a friend, scopes outside the innermost enclosing 10190 // namespace scope are not considered. 10191 10192 CXXScopeSpec &SS = D.getCXXScopeSpec(); 10193 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 10194 DeclarationName Name = NameInfo.getName(); 10195 assert(Name); 10196 10197 // Check for unexpanded parameter packs. 10198 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 10199 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 10200 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 10201 return 0; 10202 10203 // The context we found the declaration in, or in which we should 10204 // create the declaration. 10205 DeclContext *DC; 10206 Scope *DCScope = S; 10207 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 10208 ForRedeclaration); 10209 10210 // FIXME: there are different rules in local classes 10211 10212 // There are four cases here. 10213 // - There's no scope specifier, in which case we just go to the 10214 // appropriate scope and look for a function or function template 10215 // there as appropriate. 10216 // Recover from invalid scope qualifiers as if they just weren't there. 10217 if (SS.isInvalid() || !SS.isSet()) { 10218 // C++0x [namespace.memdef]p3: 10219 // If the name in a friend declaration is neither qualified nor 10220 // a template-id and the declaration is a function or an 10221 // elaborated-type-specifier, the lookup to determine whether 10222 // the entity has been previously declared shall not consider 10223 // any scopes outside the innermost enclosing namespace. 10224 // C++0x [class.friend]p11: 10225 // If a friend declaration appears in a local class and the name 10226 // specified is an unqualified name, a prior declaration is 10227 // looked up without considering scopes that are outside the 10228 // innermost enclosing non-class scope. For a friend function 10229 // declaration, if there is no prior declaration, the program is 10230 // ill-formed. 10231 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass(); 10232 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 10233 10234 // Find the appropriate context according to the above. 10235 DC = CurContext; 10236 while (true) { 10237 // Skip class contexts. If someone can cite chapter and verse 10238 // for this behavior, that would be nice --- it's what GCC and 10239 // EDG do, and it seems like a reasonable intent, but the spec 10240 // really only says that checks for unqualified existing 10241 // declarations should stop at the nearest enclosing namespace, 10242 // not that they should only consider the nearest enclosing 10243 // namespace. 10244 while (DC->isRecord()) 10245 DC = DC->getParent(); 10246 10247 LookupQualifiedName(Previous, DC); 10248 10249 // TODO: decide what we think about using declarations. 10250 if (isLocal || !Previous.empty()) 10251 break; 10252 10253 if (isTemplateId) { 10254 if (isa<TranslationUnitDecl>(DC)) break; 10255 } else { 10256 if (DC->isFileContext()) break; 10257 } 10258 DC = DC->getParent(); 10259 } 10260 10261 // C++ [class.friend]p1: A friend of a class is a function or 10262 // class that is not a member of the class . . . 10263 // C++11 changes this for both friend types and functions. 10264 // Most C++ 98 compilers do seem to give an error here, so 10265 // we do, too. 10266 if (!Previous.empty() && DC->Equals(CurContext)) 10267 Diag(DS.getFriendSpecLoc(), 10268 getLangOptions().CPlusPlus0x ? 10269 diag::warn_cxx98_compat_friend_is_member : 10270 diag::err_friend_is_member); 10271 10272 DCScope = getScopeForDeclContext(S, DC); 10273 10274 // C++ [class.friend]p6: 10275 // A function can be defined in a friend declaration of a class if and 10276 // only if the class is a non-local class (9.8), the function name is 10277 // unqualified, and the function has namespace scope. 10278 if (isLocal && D.isFunctionDefinition()) { 10279 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 10280 } 10281 10282 // - There's a non-dependent scope specifier, in which case we 10283 // compute it and do a previous lookup there for a function 10284 // or function template. 10285 } else if (!SS.getScopeRep()->isDependent()) { 10286 DC = computeDeclContext(SS); 10287 if (!DC) return 0; 10288 10289 if (RequireCompleteDeclContext(SS, DC)) return 0; 10290 10291 LookupQualifiedName(Previous, DC); 10292 10293 // Ignore things found implicitly in the wrong scope. 10294 // TODO: better diagnostics for this case. Suggesting the right 10295 // qualified scope would be nice... 10296 LookupResult::Filter F = Previous.makeFilter(); 10297 while (F.hasNext()) { 10298 NamedDecl *D = F.next(); 10299 if (!DC->InEnclosingNamespaceSetOf( 10300 D->getDeclContext()->getRedeclContext())) 10301 F.erase(); 10302 } 10303 F.done(); 10304 10305 if (Previous.empty()) { 10306 D.setInvalidType(); 10307 Diag(Loc, diag::err_qualified_friend_not_found) 10308 << Name << TInfo->getType(); 10309 return 0; 10310 } 10311 10312 // C++ [class.friend]p1: A friend of a class is a function or 10313 // class that is not a member of the class . . . 10314 if (DC->Equals(CurContext)) 10315 Diag(DS.getFriendSpecLoc(), 10316 getLangOptions().CPlusPlus0x ? 10317 diag::warn_cxx98_compat_friend_is_member : 10318 diag::err_friend_is_member); 10319 10320 if (D.isFunctionDefinition()) { 10321 // C++ [class.friend]p6: 10322 // A function can be defined in a friend declaration of a class if and 10323 // only if the class is a non-local class (9.8), the function name is 10324 // unqualified, and the function has namespace scope. 10325 SemaDiagnosticBuilder DB 10326 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 10327 10328 DB << SS.getScopeRep(); 10329 if (DC->isFileContext()) 10330 DB << FixItHint::CreateRemoval(SS.getRange()); 10331 SS.clear(); 10332 } 10333 10334 // - There's a scope specifier that does not match any template 10335 // parameter lists, in which case we use some arbitrary context, 10336 // create a method or method template, and wait for instantiation. 10337 // - There's a scope specifier that does match some template 10338 // parameter lists, which we don't handle right now. 10339 } else { 10340 if (D.isFunctionDefinition()) { 10341 // C++ [class.friend]p6: 10342 // A function can be defined in a friend declaration of a class if and 10343 // only if the class is a non-local class (9.8), the function name is 10344 // unqualified, and the function has namespace scope. 10345 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 10346 << SS.getScopeRep(); 10347 } 10348 10349 DC = CurContext; 10350 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 10351 } 10352 10353 if (!DC->isRecord()) { 10354 // This implies that it has to be an operator or function. 10355 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName || 10356 D.getName().getKind() == UnqualifiedId::IK_DestructorName || 10357 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) { 10358 Diag(Loc, diag::err_introducing_special_friend) << 10359 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 : 10360 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2); 10361 return 0; 10362 } 10363 } 10364 10365 // FIXME: This is an egregious hack to cope with cases where the scope stack 10366 // does not contain the declaration context, i.e., in an out-of-line 10367 // definition of a class. 10368 Scope FakeDCScope(S, Scope::DeclScope, Diags); 10369 if (!DCScope) { 10370 FakeDCScope.setEntity(DC); 10371 DCScope = &FakeDCScope; 10372 } 10373 10374 bool AddToScope = true; 10375 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 10376 move(TemplateParams), AddToScope); 10377 if (!ND) return 0; 10378 10379 assert(ND->getDeclContext() == DC); 10380 assert(ND->getLexicalDeclContext() == CurContext); 10381 10382 // Add the function declaration to the appropriate lookup tables, 10383 // adjusting the redeclarations list as necessary. We don't 10384 // want to do this yet if the friending class is dependent. 10385 // 10386 // Also update the scope-based lookup if the target context's 10387 // lookup context is in lexical scope. 10388 if (!CurContext->isDependentContext()) { 10389 DC = DC->getRedeclContext(); 10390 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false); 10391 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 10392 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 10393 } 10394 10395 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 10396 D.getIdentifierLoc(), ND, 10397 DS.getFriendSpecLoc()); 10398 FrD->setAccess(AS_public); 10399 CurContext->addDecl(FrD); 10400 10401 if (ND->isInvalidDecl()) 10402 FrD->setInvalidDecl(); 10403 else { 10404 FunctionDecl *FD; 10405 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 10406 FD = FTD->getTemplatedDecl(); 10407 else 10408 FD = cast<FunctionDecl>(ND); 10409 10410 // Mark templated-scope function declarations as unsupported. 10411 if (FD->getNumTemplateParameterLists()) 10412 FrD->setUnsupportedFriend(true); 10413 } 10414 10415 return ND; 10416} 10417 10418void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 10419 AdjustDeclIfTemplate(Dcl); 10420 10421 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl); 10422 if (!Fn) { 10423 Diag(DelLoc, diag::err_deleted_non_function); 10424 return; 10425 } 10426 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 10427 Diag(DelLoc, diag::err_deleted_decl_not_first); 10428 Diag(Prev->getLocation(), diag::note_previous_declaration); 10429 // If the declaration wasn't the first, we delete the function anyway for 10430 // recovery. 10431 } 10432 Fn->setDeletedAsWritten(); 10433} 10434 10435void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 10436 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl); 10437 10438 if (MD) { 10439 if (MD->getParent()->isDependentType()) { 10440 MD->setDefaulted(); 10441 MD->setExplicitlyDefaulted(); 10442 return; 10443 } 10444 10445 CXXSpecialMember Member = getSpecialMember(MD); 10446 if (Member == CXXInvalid) { 10447 Diag(DefaultLoc, diag::err_default_special_members); 10448 return; 10449 } 10450 10451 MD->setDefaulted(); 10452 MD->setExplicitlyDefaulted(); 10453 10454 // If this definition appears within the record, do the checking when 10455 // the record is complete. 10456 const FunctionDecl *Primary = MD; 10457 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate) 10458 // Find the uninstantiated declaration that actually had the '= default' 10459 // on it. 10460 MD->getTemplateInstantiationPattern()->isDefined(Primary); 10461 10462 if (Primary == Primary->getCanonicalDecl()) 10463 return; 10464 10465 switch (Member) { 10466 case CXXDefaultConstructor: { 10467 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD); 10468 CheckExplicitlyDefaultedDefaultConstructor(CD); 10469 if (!CD->isInvalidDecl()) 10470 DefineImplicitDefaultConstructor(DefaultLoc, CD); 10471 break; 10472 } 10473 10474 case CXXCopyConstructor: { 10475 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD); 10476 CheckExplicitlyDefaultedCopyConstructor(CD); 10477 if (!CD->isInvalidDecl()) 10478 DefineImplicitCopyConstructor(DefaultLoc, CD); 10479 break; 10480 } 10481 10482 case CXXCopyAssignment: { 10483 CheckExplicitlyDefaultedCopyAssignment(MD); 10484 if (!MD->isInvalidDecl()) 10485 DefineImplicitCopyAssignment(DefaultLoc, MD); 10486 break; 10487 } 10488 10489 case CXXDestructor: { 10490 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD); 10491 CheckExplicitlyDefaultedDestructor(DD); 10492 if (!DD->isInvalidDecl()) 10493 DefineImplicitDestructor(DefaultLoc, DD); 10494 break; 10495 } 10496 10497 case CXXMoveConstructor: { 10498 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD); 10499 CheckExplicitlyDefaultedMoveConstructor(CD); 10500 if (!CD->isInvalidDecl()) 10501 DefineImplicitMoveConstructor(DefaultLoc, CD); 10502 break; 10503 } 10504 10505 case CXXMoveAssignment: { 10506 CheckExplicitlyDefaultedMoveAssignment(MD); 10507 if (!MD->isInvalidDecl()) 10508 DefineImplicitMoveAssignment(DefaultLoc, MD); 10509 break; 10510 } 10511 10512 case CXXInvalid: 10513 llvm_unreachable("Invalid special member."); 10514 } 10515 } else { 10516 Diag(DefaultLoc, diag::err_default_special_members); 10517 } 10518} 10519 10520static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 10521 for (Stmt::child_range CI = S->children(); CI; ++CI) { 10522 Stmt *SubStmt = *CI; 10523 if (!SubStmt) 10524 continue; 10525 if (isa<ReturnStmt>(SubStmt)) 10526 Self.Diag(SubStmt->getSourceRange().getBegin(), 10527 diag::err_return_in_constructor_handler); 10528 if (!isa<Expr>(SubStmt)) 10529 SearchForReturnInStmt(Self, SubStmt); 10530 } 10531} 10532 10533void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 10534 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 10535 CXXCatchStmt *Handler = TryBlock->getHandler(I); 10536 SearchForReturnInStmt(*this, Handler); 10537 } 10538} 10539 10540bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 10541 const CXXMethodDecl *Old) { 10542 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType(); 10543 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType(); 10544 10545 if (Context.hasSameType(NewTy, OldTy) || 10546 NewTy->isDependentType() || OldTy->isDependentType()) 10547 return false; 10548 10549 // Check if the return types are covariant 10550 QualType NewClassTy, OldClassTy; 10551 10552 /// Both types must be pointers or references to classes. 10553 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 10554 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 10555 NewClassTy = NewPT->getPointeeType(); 10556 OldClassTy = OldPT->getPointeeType(); 10557 } 10558 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 10559 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 10560 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 10561 NewClassTy = NewRT->getPointeeType(); 10562 OldClassTy = OldRT->getPointeeType(); 10563 } 10564 } 10565 } 10566 10567 // The return types aren't either both pointers or references to a class type. 10568 if (NewClassTy.isNull()) { 10569 Diag(New->getLocation(), 10570 diag::err_different_return_type_for_overriding_virtual_function) 10571 << New->getDeclName() << NewTy << OldTy; 10572 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 10573 10574 return true; 10575 } 10576 10577 // C++ [class.virtual]p6: 10578 // If the return type of D::f differs from the return type of B::f, the 10579 // class type in the return type of D::f shall be complete at the point of 10580 // declaration of D::f or shall be the class type D. 10581 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 10582 if (!RT->isBeingDefined() && 10583 RequireCompleteType(New->getLocation(), NewClassTy, 10584 PDiag(diag::err_covariant_return_incomplete) 10585 << New->getDeclName())) 10586 return true; 10587 } 10588 10589 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 10590 // Check if the new class derives from the old class. 10591 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 10592 Diag(New->getLocation(), 10593 diag::err_covariant_return_not_derived) 10594 << New->getDeclName() << NewTy << OldTy; 10595 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 10596 return true; 10597 } 10598 10599 // Check if we the conversion from derived to base is valid. 10600 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy, 10601 diag::err_covariant_return_inaccessible_base, 10602 diag::err_covariant_return_ambiguous_derived_to_base_conv, 10603 // FIXME: Should this point to the return type? 10604 New->getLocation(), SourceRange(), New->getDeclName(), 0)) { 10605 // FIXME: this note won't trigger for delayed access control 10606 // diagnostics, and it's impossible to get an undelayed error 10607 // here from access control during the original parse because 10608 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 10609 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 10610 return true; 10611 } 10612 } 10613 10614 // The qualifiers of the return types must be the same. 10615 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 10616 Diag(New->getLocation(), 10617 diag::err_covariant_return_type_different_qualifications) 10618 << New->getDeclName() << NewTy << OldTy; 10619 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 10620 return true; 10621 }; 10622 10623 10624 // The new class type must have the same or less qualifiers as the old type. 10625 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 10626 Diag(New->getLocation(), 10627 diag::err_covariant_return_type_class_type_more_qualified) 10628 << New->getDeclName() << NewTy << OldTy; 10629 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 10630 return true; 10631 }; 10632 10633 return false; 10634} 10635 10636/// \brief Mark the given method pure. 10637/// 10638/// \param Method the method to be marked pure. 10639/// 10640/// \param InitRange the source range that covers the "0" initializer. 10641bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 10642 SourceLocation EndLoc = InitRange.getEnd(); 10643 if (EndLoc.isValid()) 10644 Method->setRangeEnd(EndLoc); 10645 10646 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 10647 Method->setPure(); 10648 return false; 10649 } 10650 10651 if (!Method->isInvalidDecl()) 10652 Diag(Method->getLocation(), diag::err_non_virtual_pure) 10653 << Method->getDeclName() << InitRange; 10654 return true; 10655} 10656 10657/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 10658/// an initializer for the out-of-line declaration 'Dcl'. The scope 10659/// is a fresh scope pushed for just this purpose. 10660/// 10661/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 10662/// static data member of class X, names should be looked up in the scope of 10663/// class X. 10664void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 10665 // If there is no declaration, there was an error parsing it. 10666 if (D == 0 || D->isInvalidDecl()) return; 10667 10668 // We should only get called for declarations with scope specifiers, like: 10669 // int foo::bar; 10670 assert(D->isOutOfLine()); 10671 EnterDeclaratorContext(S, D->getDeclContext()); 10672} 10673 10674/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 10675/// initializer for the out-of-line declaration 'D'. 10676void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 10677 // If there is no declaration, there was an error parsing it. 10678 if (D == 0 || D->isInvalidDecl()) return; 10679 10680 assert(D->isOutOfLine()); 10681 ExitDeclaratorContext(S); 10682} 10683 10684/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 10685/// C++ if/switch/while/for statement. 10686/// e.g: "if (int x = f()) {...}" 10687DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 10688 // C++ 6.4p2: 10689 // The declarator shall not specify a function or an array. 10690 // The type-specifier-seq shall not contain typedef and shall not declare a 10691 // new class or enumeration. 10692 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 10693 "Parser allowed 'typedef' as storage class of condition decl."); 10694 10695 Decl *Dcl = ActOnDeclarator(S, D); 10696 if (!Dcl) 10697 return true; 10698 10699 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 10700 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 10701 << D.getSourceRange(); 10702 return true; 10703 } 10704 10705 return Dcl; 10706} 10707 10708void Sema::LoadExternalVTableUses() { 10709 if (!ExternalSource) 10710 return; 10711 10712 SmallVector<ExternalVTableUse, 4> VTables; 10713 ExternalSource->ReadUsedVTables(VTables); 10714 SmallVector<VTableUse, 4> NewUses; 10715 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 10716 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 10717 = VTablesUsed.find(VTables[I].Record); 10718 // Even if a definition wasn't required before, it may be required now. 10719 if (Pos != VTablesUsed.end()) { 10720 if (!Pos->second && VTables[I].DefinitionRequired) 10721 Pos->second = true; 10722 continue; 10723 } 10724 10725 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 10726 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 10727 } 10728 10729 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 10730} 10731 10732void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 10733 bool DefinitionRequired) { 10734 // Ignore any vtable uses in unevaluated operands or for classes that do 10735 // not have a vtable. 10736 if (!Class->isDynamicClass() || Class->isDependentContext() || 10737 CurContext->isDependentContext() || 10738 ExprEvalContexts.back().Context == Unevaluated) 10739 return; 10740 10741 // Try to insert this class into the map. 10742 LoadExternalVTableUses(); 10743 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 10744 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 10745 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 10746 if (!Pos.second) { 10747 // If we already had an entry, check to see if we are promoting this vtable 10748 // to required a definition. If so, we need to reappend to the VTableUses 10749 // list, since we may have already processed the first entry. 10750 if (DefinitionRequired && !Pos.first->second) { 10751 Pos.first->second = true; 10752 } else { 10753 // Otherwise, we can early exit. 10754 return; 10755 } 10756 } 10757 10758 // Local classes need to have their virtual members marked 10759 // immediately. For all other classes, we mark their virtual members 10760 // at the end of the translation unit. 10761 if (Class->isLocalClass()) 10762 MarkVirtualMembersReferenced(Loc, Class); 10763 else 10764 VTableUses.push_back(std::make_pair(Class, Loc)); 10765} 10766 10767bool Sema::DefineUsedVTables() { 10768 LoadExternalVTableUses(); 10769 if (VTableUses.empty()) 10770 return false; 10771 10772 // Note: The VTableUses vector could grow as a result of marking 10773 // the members of a class as "used", so we check the size each 10774 // time through the loop and prefer indices (with are stable) to 10775 // iterators (which are not). 10776 bool DefinedAnything = false; 10777 for (unsigned I = 0; I != VTableUses.size(); ++I) { 10778 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 10779 if (!Class) 10780 continue; 10781 10782 SourceLocation Loc = VTableUses[I].second; 10783 10784 // If this class has a key function, but that key function is 10785 // defined in another translation unit, we don't need to emit the 10786 // vtable even though we're using it. 10787 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class); 10788 if (KeyFunction && !KeyFunction->hasBody()) { 10789 switch (KeyFunction->getTemplateSpecializationKind()) { 10790 case TSK_Undeclared: 10791 case TSK_ExplicitSpecialization: 10792 case TSK_ExplicitInstantiationDeclaration: 10793 // The key function is in another translation unit. 10794 continue; 10795 10796 case TSK_ExplicitInstantiationDefinition: 10797 case TSK_ImplicitInstantiation: 10798 // We will be instantiating the key function. 10799 break; 10800 } 10801 } else if (!KeyFunction) { 10802 // If we have a class with no key function that is the subject 10803 // of an explicit instantiation declaration, suppress the 10804 // vtable; it will live with the explicit instantiation 10805 // definition. 10806 bool IsExplicitInstantiationDeclaration 10807 = Class->getTemplateSpecializationKind() 10808 == TSK_ExplicitInstantiationDeclaration; 10809 for (TagDecl::redecl_iterator R = Class->redecls_begin(), 10810 REnd = Class->redecls_end(); 10811 R != REnd; ++R) { 10812 TemplateSpecializationKind TSK 10813 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind(); 10814 if (TSK == TSK_ExplicitInstantiationDeclaration) 10815 IsExplicitInstantiationDeclaration = true; 10816 else if (TSK == TSK_ExplicitInstantiationDefinition) { 10817 IsExplicitInstantiationDeclaration = false; 10818 break; 10819 } 10820 } 10821 10822 if (IsExplicitInstantiationDeclaration) 10823 continue; 10824 } 10825 10826 // Mark all of the virtual members of this class as referenced, so 10827 // that we can build a vtable. Then, tell the AST consumer that a 10828 // vtable for this class is required. 10829 DefinedAnything = true; 10830 MarkVirtualMembersReferenced(Loc, Class); 10831 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 10832 Consumer.HandleVTable(Class, VTablesUsed[Canonical]); 10833 10834 // Optionally warn if we're emitting a weak vtable. 10835 if (Class->getLinkage() == ExternalLinkage && 10836 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) { 10837 const FunctionDecl *KeyFunctionDef = 0; 10838 if (!KeyFunction || 10839 (KeyFunction->hasBody(KeyFunctionDef) && 10840 KeyFunctionDef->isInlined())) 10841 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() == 10842 TSK_ExplicitInstantiationDefinition 10843 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable) 10844 << Class; 10845 } 10846 } 10847 VTableUses.clear(); 10848 10849 return DefinedAnything; 10850} 10851 10852void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 10853 const CXXRecordDecl *RD) { 10854 for (CXXRecordDecl::method_iterator i = RD->method_begin(), 10855 e = RD->method_end(); i != e; ++i) { 10856 CXXMethodDecl *MD = *i; 10857 10858 // C++ [basic.def.odr]p2: 10859 // [...] A virtual member function is used if it is not pure. [...] 10860 if (MD->isVirtual() && !MD->isPure()) 10861 MarkFunctionReferenced(Loc, MD); 10862 } 10863 10864 // Only classes that have virtual bases need a VTT. 10865 if (RD->getNumVBases() == 0) 10866 return; 10867 10868 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(), 10869 e = RD->bases_end(); i != e; ++i) { 10870 const CXXRecordDecl *Base = 10871 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl()); 10872 if (Base->getNumVBases() == 0) 10873 continue; 10874 MarkVirtualMembersReferenced(Loc, Base); 10875 } 10876} 10877 10878/// SetIvarInitializers - This routine builds initialization ASTs for the 10879/// Objective-C implementation whose ivars need be initialized. 10880void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 10881 if (!getLangOptions().CPlusPlus) 10882 return; 10883 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 10884 SmallVector<ObjCIvarDecl*, 8> ivars; 10885 CollectIvarsToConstructOrDestruct(OID, ivars); 10886 if (ivars.empty()) 10887 return; 10888 SmallVector<CXXCtorInitializer*, 32> AllToInit; 10889 for (unsigned i = 0; i < ivars.size(); i++) { 10890 FieldDecl *Field = ivars[i]; 10891 if (Field->isInvalidDecl()) 10892 continue; 10893 10894 CXXCtorInitializer *Member; 10895 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 10896 InitializationKind InitKind = 10897 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 10898 10899 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0); 10900 ExprResult MemberInit = 10901 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg()); 10902 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 10903 // Note, MemberInit could actually come back empty if no initialization 10904 // is required (e.g., because it would call a trivial default constructor) 10905 if (!MemberInit.get() || MemberInit.isInvalid()) 10906 continue; 10907 10908 Member = 10909 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 10910 SourceLocation(), 10911 MemberInit.takeAs<Expr>(), 10912 SourceLocation()); 10913 AllToInit.push_back(Member); 10914 10915 // Be sure that the destructor is accessible and is marked as referenced. 10916 if (const RecordType *RecordTy 10917 = Context.getBaseElementType(Field->getType()) 10918 ->getAs<RecordType>()) { 10919 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 10920 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 10921 MarkFunctionReferenced(Field->getLocation(), Destructor); 10922 CheckDestructorAccess(Field->getLocation(), Destructor, 10923 PDiag(diag::err_access_dtor_ivar) 10924 << Context.getBaseElementType(Field->getType())); 10925 } 10926 } 10927 } 10928 ObjCImplementation->setIvarInitializers(Context, 10929 AllToInit.data(), AllToInit.size()); 10930 } 10931} 10932 10933static 10934void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 10935 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid, 10936 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid, 10937 llvm::SmallSet<CXXConstructorDecl*, 4> &Current, 10938 Sema &S) { 10939 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(), 10940 CE = Current.end(); 10941 if (Ctor->isInvalidDecl()) 10942 return; 10943 10944 const FunctionDecl *FNTarget = 0; 10945 CXXConstructorDecl *Target; 10946 10947 // We ignore the result here since if we don't have a body, Target will be 10948 // null below. 10949 (void)Ctor->getTargetConstructor()->hasBody(FNTarget); 10950 Target 10951= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget)); 10952 10953 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 10954 // Avoid dereferencing a null pointer here. 10955 *TCanonical = Target ? Target->getCanonicalDecl() : 0; 10956 10957 if (!Current.insert(Canonical)) 10958 return; 10959 10960 // We know that beyond here, we aren't chaining into a cycle. 10961 if (!Target || !Target->isDelegatingConstructor() || 10962 Target->isInvalidDecl() || Valid.count(TCanonical)) { 10963 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI) 10964 Valid.insert(*CI); 10965 Current.clear(); 10966 // We've hit a cycle. 10967 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 10968 Current.count(TCanonical)) { 10969 // If we haven't diagnosed this cycle yet, do so now. 10970 if (!Invalid.count(TCanonical)) { 10971 S.Diag((*Ctor->init_begin())->getSourceLocation(), 10972 diag::warn_delegating_ctor_cycle) 10973 << Ctor; 10974 10975 // Don't add a note for a function delegating directo to itself. 10976 if (TCanonical != Canonical) 10977 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 10978 10979 CXXConstructorDecl *C = Target; 10980 while (C->getCanonicalDecl() != Canonical) { 10981 (void)C->getTargetConstructor()->hasBody(FNTarget); 10982 assert(FNTarget && "Ctor cycle through bodiless function"); 10983 10984 C 10985 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget)); 10986 S.Diag(C->getLocation(), diag::note_which_delegates_to); 10987 } 10988 } 10989 10990 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI) 10991 Invalid.insert(*CI); 10992 Current.clear(); 10993 } else { 10994 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 10995 } 10996} 10997 10998 10999void Sema::CheckDelegatingCtorCycles() { 11000 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 11001 11002 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(), 11003 CE = Current.end(); 11004 11005 for (DelegatingCtorDeclsType::iterator 11006 I = DelegatingCtorDecls.begin(ExternalSource), 11007 E = DelegatingCtorDecls.end(); 11008 I != E; ++I) { 11009 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 11010 } 11011 11012 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI) 11013 (*CI)->setInvalidDecl(); 11014} 11015 11016/// IdentifyCUDATarget - Determine the CUDA compilation target for this function 11017Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) { 11018 // Implicitly declared functions (e.g. copy constructors) are 11019 // __host__ __device__ 11020 if (D->isImplicit()) 11021 return CFT_HostDevice; 11022 11023 if (D->hasAttr<CUDAGlobalAttr>()) 11024 return CFT_Global; 11025 11026 if (D->hasAttr<CUDADeviceAttr>()) { 11027 if (D->hasAttr<CUDAHostAttr>()) 11028 return CFT_HostDevice; 11029 else 11030 return CFT_Device; 11031 } 11032 11033 return CFT_Host; 11034} 11035 11036bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget, 11037 CUDAFunctionTarget CalleeTarget) { 11038 // CUDA B.1.1 "The __device__ qualifier declares a function that is... 11039 // Callable from the device only." 11040 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device) 11041 return true; 11042 11043 // CUDA B.1.2 "The __global__ qualifier declares a function that is... 11044 // Callable from the host only." 11045 // CUDA B.1.3 "The __host__ qualifier declares a function that is... 11046 // Callable from the host only." 11047 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) && 11048 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global)) 11049 return true; 11050 11051 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice) 11052 return true; 11053 11054 return false; 11055} 11056