SemaDeclCXX.cpp revision 7974c60375b2b9dfc20defc77c9ed8c3d6d241a1
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/AST/ASTConsumer.h" 16#include "clang/AST/ASTContext.h" 17#include "clang/AST/ASTMutationListener.h" 18#include "clang/AST/CXXInheritance.h" 19#include "clang/AST/CharUnits.h" 20#include "clang/AST/DeclVisitor.h" 21#include "clang/AST/EvaluatedExprVisitor.h" 22#include "clang/AST/ExprCXX.h" 23#include "clang/AST/RecordLayout.h" 24#include "clang/AST/RecursiveASTVisitor.h" 25#include "clang/AST/StmtVisitor.h" 26#include "clang/AST/TypeLoc.h" 27#include "clang/AST/TypeOrdering.h" 28#include "clang/Basic/PartialDiagnostic.h" 29#include "clang/Basic/TargetInfo.h" 30#include "clang/Lex/Preprocessor.h" 31#include "clang/Sema/CXXFieldCollector.h" 32#include "clang/Sema/DeclSpec.h" 33#include "clang/Sema/Initialization.h" 34#include "clang/Sema/Lookup.h" 35#include "clang/Sema/ParsedTemplate.h" 36#include "clang/Sema/Scope.h" 37#include "clang/Sema/ScopeInfo.h" 38#include "llvm/ADT/STLExtras.h" 39#include "llvm/ADT/SmallString.h" 40#include <map> 41#include <set> 42 43using namespace clang; 44 45//===----------------------------------------------------------------------===// 46// CheckDefaultArgumentVisitor 47//===----------------------------------------------------------------------===// 48 49namespace { 50 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 51 /// the default argument of a parameter to determine whether it 52 /// contains any ill-formed subexpressions. For example, this will 53 /// diagnose the use of local variables or parameters within the 54 /// default argument expression. 55 class CheckDefaultArgumentVisitor 56 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 57 Expr *DefaultArg; 58 Sema *S; 59 60 public: 61 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 62 : DefaultArg(defarg), S(s) {} 63 64 bool VisitExpr(Expr *Node); 65 bool VisitDeclRefExpr(DeclRefExpr *DRE); 66 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 67 bool VisitLambdaExpr(LambdaExpr *Lambda); 68 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE); 69 }; 70 71 /// VisitExpr - Visit all of the children of this expression. 72 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 73 bool IsInvalid = false; 74 for (Stmt::child_range I = Node->children(); I; ++I) 75 IsInvalid |= Visit(*I); 76 return IsInvalid; 77 } 78 79 /// VisitDeclRefExpr - Visit a reference to a declaration, to 80 /// determine whether this declaration can be used in the default 81 /// argument expression. 82 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 83 NamedDecl *Decl = DRE->getDecl(); 84 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 85 // C++ [dcl.fct.default]p9 86 // Default arguments are evaluated each time the function is 87 // called. The order of evaluation of function arguments is 88 // unspecified. Consequently, parameters of a function shall not 89 // be used in default argument expressions, even if they are not 90 // evaluated. Parameters of a function declared before a default 91 // argument expression are in scope and can hide namespace and 92 // class member names. 93 return S->Diag(DRE->getLocStart(), 94 diag::err_param_default_argument_references_param) 95 << Param->getDeclName() << DefaultArg->getSourceRange(); 96 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 97 // C++ [dcl.fct.default]p7 98 // Local variables shall not be used in default argument 99 // expressions. 100 if (VDecl->isLocalVarDecl()) 101 return S->Diag(DRE->getLocStart(), 102 diag::err_param_default_argument_references_local) 103 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 104 } 105 106 return false; 107 } 108 109 /// VisitCXXThisExpr - Visit a C++ "this" expression. 110 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 111 // C++ [dcl.fct.default]p8: 112 // The keyword this shall not be used in a default argument of a 113 // member function. 114 return S->Diag(ThisE->getLocStart(), 115 diag::err_param_default_argument_references_this) 116 << ThisE->getSourceRange(); 117 } 118 119 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) { 120 bool Invalid = false; 121 for (PseudoObjectExpr::semantics_iterator 122 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) { 123 Expr *E = *i; 124 125 // Look through bindings. 126 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 127 E = OVE->getSourceExpr(); 128 assert(E && "pseudo-object binding without source expression?"); 129 } 130 131 Invalid |= Visit(E); 132 } 133 return Invalid; 134 } 135 136 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) { 137 // C++11 [expr.lambda.prim]p13: 138 // A lambda-expression appearing in a default argument shall not 139 // implicitly or explicitly capture any entity. 140 if (Lambda->capture_begin() == Lambda->capture_end()) 141 return false; 142 143 return S->Diag(Lambda->getLocStart(), 144 diag::err_lambda_capture_default_arg); 145 } 146} 147 148void 149Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc, 150 const CXXMethodDecl *Method) { 151 // If we have an MSAny spec already, don't bother. 152 if (!Method || ComputedEST == EST_MSAny) 153 return; 154 155 const FunctionProtoType *Proto 156 = Method->getType()->getAs<FunctionProtoType>(); 157 Proto = Self->ResolveExceptionSpec(CallLoc, Proto); 158 if (!Proto) 159 return; 160 161 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 162 163 // If this function can throw any exceptions, make a note of that. 164 if (EST == EST_MSAny || EST == EST_None) { 165 ClearExceptions(); 166 ComputedEST = EST; 167 return; 168 } 169 170 // FIXME: If the call to this decl is using any of its default arguments, we 171 // need to search them for potentially-throwing calls. 172 173 // If this function has a basic noexcept, it doesn't affect the outcome. 174 if (EST == EST_BasicNoexcept) 175 return; 176 177 // If we have a throw-all spec at this point, ignore the function. 178 if (ComputedEST == EST_None) 179 return; 180 181 // If we're still at noexcept(true) and there's a nothrow() callee, 182 // change to that specification. 183 if (EST == EST_DynamicNone) { 184 if (ComputedEST == EST_BasicNoexcept) 185 ComputedEST = EST_DynamicNone; 186 return; 187 } 188 189 // Check out noexcept specs. 190 if (EST == EST_ComputedNoexcept) { 191 FunctionProtoType::NoexceptResult NR = 192 Proto->getNoexceptSpec(Self->Context); 193 assert(NR != FunctionProtoType::NR_NoNoexcept && 194 "Must have noexcept result for EST_ComputedNoexcept."); 195 assert(NR != FunctionProtoType::NR_Dependent && 196 "Should not generate implicit declarations for dependent cases, " 197 "and don't know how to handle them anyway."); 198 199 // noexcept(false) -> no spec on the new function 200 if (NR == FunctionProtoType::NR_Throw) { 201 ClearExceptions(); 202 ComputedEST = EST_None; 203 } 204 // noexcept(true) won't change anything either. 205 return; 206 } 207 208 assert(EST == EST_Dynamic && "EST case not considered earlier."); 209 assert(ComputedEST != EST_None && 210 "Shouldn't collect exceptions when throw-all is guaranteed."); 211 ComputedEST = EST_Dynamic; 212 // Record the exceptions in this function's exception specification. 213 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(), 214 EEnd = Proto->exception_end(); 215 E != EEnd; ++E) 216 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E))) 217 Exceptions.push_back(*E); 218} 219 220void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) { 221 if (!E || ComputedEST == EST_MSAny) 222 return; 223 224 // FIXME: 225 // 226 // C++0x [except.spec]p14: 227 // [An] implicit exception-specification specifies the type-id T if and 228 // only if T is allowed by the exception-specification of a function directly 229 // invoked by f's implicit definition; f shall allow all exceptions if any 230 // function it directly invokes allows all exceptions, and f shall allow no 231 // exceptions if every function it directly invokes allows no exceptions. 232 // 233 // Note in particular that if an implicit exception-specification is generated 234 // for a function containing a throw-expression, that specification can still 235 // be noexcept(true). 236 // 237 // Note also that 'directly invoked' is not defined in the standard, and there 238 // is no indication that we should only consider potentially-evaluated calls. 239 // 240 // Ultimately we should implement the intent of the standard: the exception 241 // specification should be the set of exceptions which can be thrown by the 242 // implicit definition. For now, we assume that any non-nothrow expression can 243 // throw any exception. 244 245 if (Self->canThrow(E)) 246 ComputedEST = EST_None; 247} 248 249bool 250Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 251 SourceLocation EqualLoc) { 252 if (RequireCompleteType(Param->getLocation(), Param->getType(), 253 diag::err_typecheck_decl_incomplete_type)) { 254 Param->setInvalidDecl(); 255 return true; 256 } 257 258 // C++ [dcl.fct.default]p5 259 // A default argument expression is implicitly converted (clause 260 // 4) to the parameter type. The default argument expression has 261 // the same semantic constraints as the initializer expression in 262 // a declaration of a variable of the parameter type, using the 263 // copy-initialization semantics (8.5). 264 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 265 Param); 266 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 267 EqualLoc); 268 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1); 269 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); 270 if (Result.isInvalid()) 271 return true; 272 Arg = Result.takeAs<Expr>(); 273 274 CheckCompletedExpr(Arg, EqualLoc); 275 Arg = MaybeCreateExprWithCleanups(Arg); 276 277 // Okay: add the default argument to the parameter 278 Param->setDefaultArg(Arg); 279 280 // We have already instantiated this parameter; provide each of the 281 // instantiations with the uninstantiated default argument. 282 UnparsedDefaultArgInstantiationsMap::iterator InstPos 283 = UnparsedDefaultArgInstantiations.find(Param); 284 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 285 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 286 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 287 288 // We're done tracking this parameter's instantiations. 289 UnparsedDefaultArgInstantiations.erase(InstPos); 290 } 291 292 return false; 293} 294 295/// ActOnParamDefaultArgument - Check whether the default argument 296/// provided for a function parameter is well-formed. If so, attach it 297/// to the parameter declaration. 298void 299Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 300 Expr *DefaultArg) { 301 if (!param || !DefaultArg) 302 return; 303 304 ParmVarDecl *Param = cast<ParmVarDecl>(param); 305 UnparsedDefaultArgLocs.erase(Param); 306 307 // Default arguments are only permitted in C++ 308 if (!getLangOpts().CPlusPlus) { 309 Diag(EqualLoc, diag::err_param_default_argument) 310 << DefaultArg->getSourceRange(); 311 Param->setInvalidDecl(); 312 return; 313 } 314 315 // Check for unexpanded parameter packs. 316 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 317 Param->setInvalidDecl(); 318 return; 319 } 320 321 // Check that the default argument is well-formed 322 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this); 323 if (DefaultArgChecker.Visit(DefaultArg)) { 324 Param->setInvalidDecl(); 325 return; 326 } 327 328 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 329} 330 331/// ActOnParamUnparsedDefaultArgument - We've seen a default 332/// argument for a function parameter, but we can't parse it yet 333/// because we're inside a class definition. Note that this default 334/// argument will be parsed later. 335void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 336 SourceLocation EqualLoc, 337 SourceLocation ArgLoc) { 338 if (!param) 339 return; 340 341 ParmVarDecl *Param = cast<ParmVarDecl>(param); 342 if (Param) 343 Param->setUnparsedDefaultArg(); 344 345 UnparsedDefaultArgLocs[Param] = ArgLoc; 346} 347 348/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 349/// the default argument for the parameter param failed. 350void Sema::ActOnParamDefaultArgumentError(Decl *param) { 351 if (!param) 352 return; 353 354 ParmVarDecl *Param = cast<ParmVarDecl>(param); 355 356 Param->setInvalidDecl(); 357 358 UnparsedDefaultArgLocs.erase(Param); 359} 360 361/// CheckExtraCXXDefaultArguments - Check for any extra default 362/// arguments in the declarator, which is not a function declaration 363/// or definition and therefore is not permitted to have default 364/// arguments. This routine should be invoked for every declarator 365/// that is not a function declaration or definition. 366void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 367 // C++ [dcl.fct.default]p3 368 // A default argument expression shall be specified only in the 369 // parameter-declaration-clause of a function declaration or in a 370 // template-parameter (14.1). It shall not be specified for a 371 // parameter pack. If it is specified in a 372 // parameter-declaration-clause, it shall not occur within a 373 // declarator or abstract-declarator of a parameter-declaration. 374 bool MightBeFunction = D.isFunctionDeclarationContext(); 375 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 376 DeclaratorChunk &chunk = D.getTypeObject(i); 377 if (chunk.Kind == DeclaratorChunk::Function) { 378 if (MightBeFunction) { 379 // This is a function declaration. It can have default arguments, but 380 // keep looking in case its return type is a function type with default 381 // arguments. 382 MightBeFunction = false; 383 continue; 384 } 385 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) { 386 ParmVarDecl *Param = 387 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param); 388 if (Param->hasUnparsedDefaultArg()) { 389 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens; 390 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 391 << SourceRange((*Toks)[1].getLocation(), 392 Toks->back().getLocation()); 393 delete Toks; 394 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0; 395 } else if (Param->getDefaultArg()) { 396 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 397 << Param->getDefaultArg()->getSourceRange(); 398 Param->setDefaultArg(0); 399 } 400 } 401 } else if (chunk.Kind != DeclaratorChunk::Paren) { 402 MightBeFunction = false; 403 } 404 } 405} 406 407/// MergeCXXFunctionDecl - Merge two declarations of the same C++ 408/// function, once we already know that they have the same 409/// type. Subroutine of MergeFunctionDecl. Returns true if there was an 410/// error, false otherwise. 411bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 412 Scope *S) { 413 bool Invalid = false; 414 415 // C++ [dcl.fct.default]p4: 416 // For non-template functions, default arguments can be added in 417 // later declarations of a function in the same 418 // scope. Declarations in different scopes have completely 419 // distinct sets of default arguments. That is, declarations in 420 // inner scopes do not acquire default arguments from 421 // declarations in outer scopes, and vice versa. In a given 422 // function declaration, all parameters subsequent to a 423 // parameter with a default argument shall have default 424 // arguments supplied in this or previous declarations. A 425 // default argument shall not be redefined by a later 426 // declaration (not even to the same value). 427 // 428 // C++ [dcl.fct.default]p6: 429 // Except for member functions of class templates, the default arguments 430 // in a member function definition that appears outside of the class 431 // definition are added to the set of default arguments provided by the 432 // member function declaration in the class definition. 433 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 434 ParmVarDecl *OldParam = Old->getParamDecl(p); 435 ParmVarDecl *NewParam = New->getParamDecl(p); 436 437 bool OldParamHasDfl = OldParam->hasDefaultArg(); 438 bool NewParamHasDfl = NewParam->hasDefaultArg(); 439 440 NamedDecl *ND = Old; 441 if (S && !isDeclInScope(ND, New->getDeclContext(), S)) 442 // Ignore default parameters of old decl if they are not in 443 // the same scope. 444 OldParamHasDfl = false; 445 446 if (OldParamHasDfl && NewParamHasDfl) { 447 448 unsigned DiagDefaultParamID = 449 diag::err_param_default_argument_redefinition; 450 451 // MSVC accepts that default parameters be redefined for member functions 452 // of template class. The new default parameter's value is ignored. 453 Invalid = true; 454 if (getLangOpts().MicrosoftExt) { 455 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New); 456 if (MD && MD->getParent()->getDescribedClassTemplate()) { 457 // Merge the old default argument into the new parameter. 458 NewParam->setHasInheritedDefaultArg(); 459 if (OldParam->hasUninstantiatedDefaultArg()) 460 NewParam->setUninstantiatedDefaultArg( 461 OldParam->getUninstantiatedDefaultArg()); 462 else 463 NewParam->setDefaultArg(OldParam->getInit()); 464 DiagDefaultParamID = diag::warn_param_default_argument_redefinition; 465 Invalid = false; 466 } 467 } 468 469 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 470 // hint here. Alternatively, we could walk the type-source information 471 // for NewParam to find the last source location in the type... but it 472 // isn't worth the effort right now. This is the kind of test case that 473 // is hard to get right: 474 // int f(int); 475 // void g(int (*fp)(int) = f); 476 // void g(int (*fp)(int) = &f); 477 Diag(NewParam->getLocation(), DiagDefaultParamID) 478 << NewParam->getDefaultArgRange(); 479 480 // Look for the function declaration where the default argument was 481 // actually written, which may be a declaration prior to Old. 482 for (FunctionDecl *Older = Old->getPreviousDecl(); 483 Older; Older = Older->getPreviousDecl()) { 484 if (!Older->getParamDecl(p)->hasDefaultArg()) 485 break; 486 487 OldParam = Older->getParamDecl(p); 488 } 489 490 Diag(OldParam->getLocation(), diag::note_previous_definition) 491 << OldParam->getDefaultArgRange(); 492 } else if (OldParamHasDfl) { 493 // Merge the old default argument into the new parameter. 494 // It's important to use getInit() here; getDefaultArg() 495 // strips off any top-level ExprWithCleanups. 496 NewParam->setHasInheritedDefaultArg(); 497 if (OldParam->hasUninstantiatedDefaultArg()) 498 NewParam->setUninstantiatedDefaultArg( 499 OldParam->getUninstantiatedDefaultArg()); 500 else 501 NewParam->setDefaultArg(OldParam->getInit()); 502 } else if (NewParamHasDfl) { 503 if (New->getDescribedFunctionTemplate()) { 504 // Paragraph 4, quoted above, only applies to non-template functions. 505 Diag(NewParam->getLocation(), 506 diag::err_param_default_argument_template_redecl) 507 << NewParam->getDefaultArgRange(); 508 Diag(Old->getLocation(), diag::note_template_prev_declaration) 509 << false; 510 } else if (New->getTemplateSpecializationKind() 511 != TSK_ImplicitInstantiation && 512 New->getTemplateSpecializationKind() != TSK_Undeclared) { 513 // C++ [temp.expr.spec]p21: 514 // Default function arguments shall not be specified in a declaration 515 // or a definition for one of the following explicit specializations: 516 // - the explicit specialization of a function template; 517 // - the explicit specialization of a member function template; 518 // - the explicit specialization of a member function of a class 519 // template where the class template specialization to which the 520 // member function specialization belongs is implicitly 521 // instantiated. 522 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 523 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 524 << New->getDeclName() 525 << NewParam->getDefaultArgRange(); 526 } else if (New->getDeclContext()->isDependentContext()) { 527 // C++ [dcl.fct.default]p6 (DR217): 528 // Default arguments for a member function of a class template shall 529 // be specified on the initial declaration of the member function 530 // within the class template. 531 // 532 // Reading the tea leaves a bit in DR217 and its reference to DR205 533 // leads me to the conclusion that one cannot add default function 534 // arguments for an out-of-line definition of a member function of a 535 // dependent type. 536 int WhichKind = 2; 537 if (CXXRecordDecl *Record 538 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 539 if (Record->getDescribedClassTemplate()) 540 WhichKind = 0; 541 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 542 WhichKind = 1; 543 else 544 WhichKind = 2; 545 } 546 547 Diag(NewParam->getLocation(), 548 diag::err_param_default_argument_member_template_redecl) 549 << WhichKind 550 << NewParam->getDefaultArgRange(); 551 } 552 } 553 } 554 555 // DR1344: If a default argument is added outside a class definition and that 556 // default argument makes the function a special member function, the program 557 // is ill-formed. This can only happen for constructors. 558 if (isa<CXXConstructorDecl>(New) && 559 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 560 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 561 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 562 if (NewSM != OldSM) { 563 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 564 assert(NewParam->hasDefaultArg()); 565 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 566 << NewParam->getDefaultArgRange() << NewSM; 567 Diag(Old->getLocation(), diag::note_previous_declaration); 568 } 569 } 570 571 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 572 // template has a constexpr specifier then all its declarations shall 573 // contain the constexpr specifier. 574 if (New->isConstexpr() != Old->isConstexpr()) { 575 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 576 << New << New->isConstexpr(); 577 Diag(Old->getLocation(), diag::note_previous_declaration); 578 Invalid = true; 579 } 580 581 if (CheckEquivalentExceptionSpec(Old, New)) 582 Invalid = true; 583 584 return Invalid; 585} 586 587/// \brief Merge the exception specifications of two variable declarations. 588/// 589/// This is called when there's a redeclaration of a VarDecl. The function 590/// checks if the redeclaration might have an exception specification and 591/// validates compatibility and merges the specs if necessary. 592void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 593 // Shortcut if exceptions are disabled. 594 if (!getLangOpts().CXXExceptions) 595 return; 596 597 assert(Context.hasSameType(New->getType(), Old->getType()) && 598 "Should only be called if types are otherwise the same."); 599 600 QualType NewType = New->getType(); 601 QualType OldType = Old->getType(); 602 603 // We're only interested in pointers and references to functions, as well 604 // as pointers to member functions. 605 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 606 NewType = R->getPointeeType(); 607 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 608 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 609 NewType = P->getPointeeType(); 610 OldType = OldType->getAs<PointerType>()->getPointeeType(); 611 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 612 NewType = M->getPointeeType(); 613 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 614 } 615 616 if (!NewType->isFunctionProtoType()) 617 return; 618 619 // There's lots of special cases for functions. For function pointers, system 620 // libraries are hopefully not as broken so that we don't need these 621 // workarounds. 622 if (CheckEquivalentExceptionSpec( 623 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 624 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 625 New->setInvalidDecl(); 626 } 627} 628 629/// CheckCXXDefaultArguments - Verify that the default arguments for a 630/// function declaration are well-formed according to C++ 631/// [dcl.fct.default]. 632void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 633 unsigned NumParams = FD->getNumParams(); 634 unsigned p; 635 636 bool IsLambda = FD->getOverloadedOperator() == OO_Call && 637 isa<CXXMethodDecl>(FD) && 638 cast<CXXMethodDecl>(FD)->getParent()->isLambda(); 639 640 // Find first parameter with a default argument 641 for (p = 0; p < NumParams; ++p) { 642 ParmVarDecl *Param = FD->getParamDecl(p); 643 if (Param->hasDefaultArg()) 644 break; 645 } 646 647 // C++ [dcl.fct.default]p4: 648 // In a given function declaration, all parameters 649 // subsequent to a parameter with a default argument shall 650 // have default arguments supplied in this or previous 651 // declarations. A default argument shall not be redefined 652 // by a later declaration (not even to the same value). 653 unsigned LastMissingDefaultArg = 0; 654 for (; p < NumParams; ++p) { 655 ParmVarDecl *Param = FD->getParamDecl(p); 656 if (!Param->hasDefaultArg()) { 657 if (Param->isInvalidDecl()) 658 /* We already complained about this parameter. */; 659 else if (Param->getIdentifier()) 660 Diag(Param->getLocation(), 661 diag::err_param_default_argument_missing_name) 662 << Param->getIdentifier(); 663 else 664 Diag(Param->getLocation(), 665 diag::err_param_default_argument_missing); 666 667 LastMissingDefaultArg = p; 668 } 669 } 670 671 if (LastMissingDefaultArg > 0) { 672 // Some default arguments were missing. Clear out all of the 673 // default arguments up to (and including) the last missing 674 // default argument, so that we leave the function parameters 675 // in a semantically valid state. 676 for (p = 0; p <= LastMissingDefaultArg; ++p) { 677 ParmVarDecl *Param = FD->getParamDecl(p); 678 if (Param->hasDefaultArg()) { 679 Param->setDefaultArg(0); 680 } 681 } 682 } 683} 684 685// CheckConstexprParameterTypes - Check whether a function's parameter types 686// are all literal types. If so, return true. If not, produce a suitable 687// diagnostic and return false. 688static bool CheckConstexprParameterTypes(Sema &SemaRef, 689 const FunctionDecl *FD) { 690 unsigned ArgIndex = 0; 691 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 692 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(), 693 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) { 694 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 695 SourceLocation ParamLoc = PD->getLocation(); 696 if (!(*i)->isDependentType() && 697 SemaRef.RequireLiteralType(ParamLoc, *i, 698 diag::err_constexpr_non_literal_param, 699 ArgIndex+1, PD->getSourceRange(), 700 isa<CXXConstructorDecl>(FD))) 701 return false; 702 } 703 return true; 704} 705 706/// \brief Get diagnostic %select index for tag kind for 707/// record diagnostic message. 708/// WARNING: Indexes apply to particular diagnostics only! 709/// 710/// \returns diagnostic %select index. 711static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 712 switch (Tag) { 713 case TTK_Struct: return 0; 714 case TTK_Interface: return 1; 715 case TTK_Class: return 2; 716 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 717 } 718} 719 720// CheckConstexprFunctionDecl - Check whether a function declaration satisfies 721// the requirements of a constexpr function definition or a constexpr 722// constructor definition. If so, return true. If not, produce appropriate 723// diagnostics and return false. 724// 725// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 726bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) { 727 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 728 if (MD && MD->isInstance()) { 729 // C++11 [dcl.constexpr]p4: 730 // The definition of a constexpr constructor shall satisfy the following 731 // constraints: 732 // - the class shall not have any virtual base classes; 733 const CXXRecordDecl *RD = MD->getParent(); 734 if (RD->getNumVBases()) { 735 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 736 << isa<CXXConstructorDecl>(NewFD) 737 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 738 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(), 739 E = RD->vbases_end(); I != E; ++I) 740 Diag(I->getLocStart(), 741 diag::note_constexpr_virtual_base_here) << I->getSourceRange(); 742 return false; 743 } 744 } 745 746 if (!isa<CXXConstructorDecl>(NewFD)) { 747 // C++11 [dcl.constexpr]p3: 748 // The definition of a constexpr function shall satisfy the following 749 // constraints: 750 // - it shall not be virtual; 751 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 752 if (Method && Method->isVirtual()) { 753 Diag(NewFD->getLocation(), diag::err_constexpr_virtual); 754 755 // If it's not obvious why this function is virtual, find an overridden 756 // function which uses the 'virtual' keyword. 757 const CXXMethodDecl *WrittenVirtual = Method; 758 while (!WrittenVirtual->isVirtualAsWritten()) 759 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 760 if (WrittenVirtual != Method) 761 Diag(WrittenVirtual->getLocation(), 762 diag::note_overridden_virtual_function); 763 return false; 764 } 765 766 // - its return type shall be a literal type; 767 QualType RT = NewFD->getResultType(); 768 if (!RT->isDependentType() && 769 RequireLiteralType(NewFD->getLocation(), RT, 770 diag::err_constexpr_non_literal_return)) 771 return false; 772 } 773 774 // - each of its parameter types shall be a literal type; 775 if (!CheckConstexprParameterTypes(*this, NewFD)) 776 return false; 777 778 return true; 779} 780 781/// Check the given declaration statement is legal within a constexpr function 782/// body. C++0x [dcl.constexpr]p3,p4. 783/// 784/// \return true if the body is OK, false if we have diagnosed a problem. 785static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 786 DeclStmt *DS) { 787 // C++0x [dcl.constexpr]p3 and p4: 788 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 789 // contain only 790 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(), 791 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) { 792 switch ((*DclIt)->getKind()) { 793 case Decl::StaticAssert: 794 case Decl::Using: 795 case Decl::UsingShadow: 796 case Decl::UsingDirective: 797 case Decl::UnresolvedUsingTypename: 798 // - static_assert-declarations 799 // - using-declarations, 800 // - using-directives, 801 continue; 802 803 case Decl::Typedef: 804 case Decl::TypeAlias: { 805 // - typedef declarations and alias-declarations that do not define 806 // classes or enumerations, 807 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt); 808 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 809 // Don't allow variably-modified types in constexpr functions. 810 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 811 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 812 << TL.getSourceRange() << TL.getType() 813 << isa<CXXConstructorDecl>(Dcl); 814 return false; 815 } 816 continue; 817 } 818 819 case Decl::Enum: 820 case Decl::CXXRecord: 821 // As an extension, we allow the declaration (but not the definition) of 822 // classes and enumerations in all declarations, not just in typedef and 823 // alias declarations. 824 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) { 825 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition) 826 << isa<CXXConstructorDecl>(Dcl); 827 return false; 828 } 829 continue; 830 831 case Decl::Var: 832 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration) 833 << isa<CXXConstructorDecl>(Dcl); 834 return false; 835 836 default: 837 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt) 838 << isa<CXXConstructorDecl>(Dcl); 839 return false; 840 } 841 } 842 843 return true; 844} 845 846/// Check that the given field is initialized within a constexpr constructor. 847/// 848/// \param Dcl The constexpr constructor being checked. 849/// \param Field The field being checked. This may be a member of an anonymous 850/// struct or union nested within the class being checked. 851/// \param Inits All declarations, including anonymous struct/union members and 852/// indirect members, for which any initialization was provided. 853/// \param Diagnosed Set to true if an error is produced. 854static void CheckConstexprCtorInitializer(Sema &SemaRef, 855 const FunctionDecl *Dcl, 856 FieldDecl *Field, 857 llvm::SmallSet<Decl*, 16> &Inits, 858 bool &Diagnosed) { 859 if (Field->isUnnamedBitfield()) 860 return; 861 862 if (Field->isAnonymousStructOrUnion() && 863 Field->getType()->getAsCXXRecordDecl()->isEmpty()) 864 return; 865 866 if (!Inits.count(Field)) { 867 if (!Diagnosed) { 868 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init); 869 Diagnosed = true; 870 } 871 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init); 872 } else if (Field->isAnonymousStructOrUnion()) { 873 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 874 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end(); 875 I != E; ++I) 876 // If an anonymous union contains an anonymous struct of which any member 877 // is initialized, all members must be initialized. 878 if (!RD->isUnion() || Inits.count(*I)) 879 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed); 880 } 881} 882 883/// Check the body for the given constexpr function declaration only contains 884/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 885/// 886/// \return true if the body is OK, false if we have diagnosed a problem. 887bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) { 888 if (isa<CXXTryStmt>(Body)) { 889 // C++11 [dcl.constexpr]p3: 890 // The definition of a constexpr function shall satisfy the following 891 // constraints: [...] 892 // - its function-body shall be = delete, = default, or a 893 // compound-statement 894 // 895 // C++11 [dcl.constexpr]p4: 896 // In the definition of a constexpr constructor, [...] 897 // - its function-body shall not be a function-try-block; 898 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block) 899 << isa<CXXConstructorDecl>(Dcl); 900 return false; 901 } 902 903 // - its function-body shall be [...] a compound-statement that contains only 904 CompoundStmt *CompBody = cast<CompoundStmt>(Body); 905 906 SmallVector<SourceLocation, 4> ReturnStmts; 907 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(), 908 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) { 909 switch ((*BodyIt)->getStmtClass()) { 910 case Stmt::NullStmtClass: 911 // - null statements, 912 continue; 913 914 case Stmt::DeclStmtClass: 915 // - static_assert-declarations 916 // - using-declarations, 917 // - using-directives, 918 // - typedef declarations and alias-declarations that do not define 919 // classes or enumerations, 920 if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt))) 921 return false; 922 continue; 923 924 case Stmt::ReturnStmtClass: 925 // - and exactly one return statement; 926 if (isa<CXXConstructorDecl>(Dcl)) 927 break; 928 929 ReturnStmts.push_back((*BodyIt)->getLocStart()); 930 continue; 931 932 default: 933 break; 934 } 935 936 Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt) 937 << isa<CXXConstructorDecl>(Dcl); 938 return false; 939 } 940 941 if (const CXXConstructorDecl *Constructor 942 = dyn_cast<CXXConstructorDecl>(Dcl)) { 943 const CXXRecordDecl *RD = Constructor->getParent(); 944 // DR1359: 945 // - every non-variant non-static data member and base class sub-object 946 // shall be initialized; 947 // - if the class is a non-empty union, or for each non-empty anonymous 948 // union member of a non-union class, exactly one non-static data member 949 // shall be initialized; 950 if (RD->isUnion()) { 951 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) { 952 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init); 953 return false; 954 } 955 } else if (!Constructor->isDependentContext() && 956 !Constructor->isDelegatingConstructor()) { 957 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 958 959 // Skip detailed checking if we have enough initializers, and we would 960 // allow at most one initializer per member. 961 bool AnyAnonStructUnionMembers = false; 962 unsigned Fields = 0; 963 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 964 E = RD->field_end(); I != E; ++I, ++Fields) { 965 if (I->isAnonymousStructOrUnion()) { 966 AnyAnonStructUnionMembers = true; 967 break; 968 } 969 } 970 if (AnyAnonStructUnionMembers || 971 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 972 // Check initialization of non-static data members. Base classes are 973 // always initialized so do not need to be checked. Dependent bases 974 // might not have initializers in the member initializer list. 975 llvm::SmallSet<Decl*, 16> Inits; 976 for (CXXConstructorDecl::init_const_iterator 977 I = Constructor->init_begin(), E = Constructor->init_end(); 978 I != E; ++I) { 979 if (FieldDecl *FD = (*I)->getMember()) 980 Inits.insert(FD); 981 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember()) 982 Inits.insert(ID->chain_begin(), ID->chain_end()); 983 } 984 985 bool Diagnosed = false; 986 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 987 E = RD->field_end(); I != E; ++I) 988 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed); 989 if (Diagnosed) 990 return false; 991 } 992 } 993 } else { 994 if (ReturnStmts.empty()) { 995 Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return); 996 return false; 997 } 998 if (ReturnStmts.size() > 1) { 999 Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return); 1000 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 1001 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return); 1002 return false; 1003 } 1004 } 1005 1006 // C++11 [dcl.constexpr]p5: 1007 // if no function argument values exist such that the function invocation 1008 // substitution would produce a constant expression, the program is 1009 // ill-formed; no diagnostic required. 1010 // C++11 [dcl.constexpr]p3: 1011 // - every constructor call and implicit conversion used in initializing the 1012 // return value shall be one of those allowed in a constant expression. 1013 // C++11 [dcl.constexpr]p4: 1014 // - every constructor involved in initializing non-static data members and 1015 // base class sub-objects shall be a constexpr constructor. 1016 SmallVector<PartialDiagnosticAt, 8> Diags; 1017 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) { 1018 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr) 1019 << isa<CXXConstructorDecl>(Dcl); 1020 for (size_t I = 0, N = Diags.size(); I != N; ++I) 1021 Diag(Diags[I].first, Diags[I].second); 1022 // Don't return false here: we allow this for compatibility in 1023 // system headers. 1024 } 1025 1026 return true; 1027} 1028 1029/// isCurrentClassName - Determine whether the identifier II is the 1030/// name of the class type currently being defined. In the case of 1031/// nested classes, this will only return true if II is the name of 1032/// the innermost class. 1033bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 1034 const CXXScopeSpec *SS) { 1035 assert(getLangOpts().CPlusPlus && "No class names in C!"); 1036 1037 CXXRecordDecl *CurDecl; 1038 if (SS && SS->isSet() && !SS->isInvalid()) { 1039 DeclContext *DC = computeDeclContext(*SS, true); 1040 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 1041 } else 1042 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1043 1044 if (CurDecl && CurDecl->getIdentifier()) 1045 return &II == CurDecl->getIdentifier(); 1046 else 1047 return false; 1048} 1049 1050/// \brief Determine whether the given class is a base class of the given 1051/// class, including looking at dependent bases. 1052static bool findCircularInheritance(const CXXRecordDecl *Class, 1053 const CXXRecordDecl *Current) { 1054 SmallVector<const CXXRecordDecl*, 8> Queue; 1055 1056 Class = Class->getCanonicalDecl(); 1057 while (true) { 1058 for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(), 1059 E = Current->bases_end(); 1060 I != E; ++I) { 1061 CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 1062 if (!Base) 1063 continue; 1064 1065 Base = Base->getDefinition(); 1066 if (!Base) 1067 continue; 1068 1069 if (Base->getCanonicalDecl() == Class) 1070 return true; 1071 1072 Queue.push_back(Base); 1073 } 1074 1075 if (Queue.empty()) 1076 return false; 1077 1078 Current = Queue.back(); 1079 Queue.pop_back(); 1080 } 1081 1082 return false; 1083} 1084 1085/// \brief Check the validity of a C++ base class specifier. 1086/// 1087/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 1088/// and returns NULL otherwise. 1089CXXBaseSpecifier * 1090Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 1091 SourceRange SpecifierRange, 1092 bool Virtual, AccessSpecifier Access, 1093 TypeSourceInfo *TInfo, 1094 SourceLocation EllipsisLoc) { 1095 QualType BaseType = TInfo->getType(); 1096 1097 // C++ [class.union]p1: 1098 // A union shall not have base classes. 1099 if (Class->isUnion()) { 1100 Diag(Class->getLocation(), diag::err_base_clause_on_union) 1101 << SpecifierRange; 1102 return 0; 1103 } 1104 1105 if (EllipsisLoc.isValid() && 1106 !TInfo->getType()->containsUnexpandedParameterPack()) { 1107 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 1108 << TInfo->getTypeLoc().getSourceRange(); 1109 EllipsisLoc = SourceLocation(); 1110 } 1111 1112 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 1113 1114 if (BaseType->isDependentType()) { 1115 // Make sure that we don't have circular inheritance among our dependent 1116 // bases. For non-dependent bases, the check for completeness below handles 1117 // this. 1118 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 1119 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 1120 ((BaseDecl = BaseDecl->getDefinition()) && 1121 findCircularInheritance(Class, BaseDecl))) { 1122 Diag(BaseLoc, diag::err_circular_inheritance) 1123 << BaseType << Context.getTypeDeclType(Class); 1124 1125 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 1126 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 1127 << BaseType; 1128 1129 return 0; 1130 } 1131 } 1132 1133 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1134 Class->getTagKind() == TTK_Class, 1135 Access, TInfo, EllipsisLoc); 1136 } 1137 1138 // Base specifiers must be record types. 1139 if (!BaseType->isRecordType()) { 1140 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 1141 return 0; 1142 } 1143 1144 // C++ [class.union]p1: 1145 // A union shall not be used as a base class. 1146 if (BaseType->isUnionType()) { 1147 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 1148 return 0; 1149 } 1150 1151 // C++ [class.derived]p2: 1152 // The class-name in a base-specifier shall not be an incompletely 1153 // defined class. 1154 if (RequireCompleteType(BaseLoc, BaseType, 1155 diag::err_incomplete_base_class, SpecifierRange)) { 1156 Class->setInvalidDecl(); 1157 return 0; 1158 } 1159 1160 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 1161 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 1162 assert(BaseDecl && "Record type has no declaration"); 1163 BaseDecl = BaseDecl->getDefinition(); 1164 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 1165 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 1166 assert(CXXBaseDecl && "Base type is not a C++ type"); 1167 1168 // C++ [class]p3: 1169 // If a class is marked final and it appears as a base-type-specifier in 1170 // base-clause, the program is ill-formed. 1171 if (CXXBaseDecl->hasAttr<FinalAttr>()) { 1172 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 1173 << CXXBaseDecl->getDeclName(); 1174 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl) 1175 << CXXBaseDecl->getDeclName(); 1176 return 0; 1177 } 1178 1179 if (BaseDecl->isInvalidDecl()) 1180 Class->setInvalidDecl(); 1181 1182 // Create the base specifier. 1183 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1184 Class->getTagKind() == TTK_Class, 1185 Access, TInfo, EllipsisLoc); 1186} 1187 1188/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 1189/// one entry in the base class list of a class specifier, for 1190/// example: 1191/// class foo : public bar, virtual private baz { 1192/// 'public bar' and 'virtual private baz' are each base-specifiers. 1193BaseResult 1194Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 1195 ParsedAttributes &Attributes, 1196 bool Virtual, AccessSpecifier Access, 1197 ParsedType basetype, SourceLocation BaseLoc, 1198 SourceLocation EllipsisLoc) { 1199 if (!classdecl) 1200 return true; 1201 1202 AdjustDeclIfTemplate(classdecl); 1203 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 1204 if (!Class) 1205 return true; 1206 1207 // We do not support any C++11 attributes on base-specifiers yet. 1208 // Diagnose any attributes we see. 1209 if (!Attributes.empty()) { 1210 for (AttributeList *Attr = Attributes.getList(); Attr; 1211 Attr = Attr->getNext()) { 1212 if (Attr->isInvalid() || 1213 Attr->getKind() == AttributeList::IgnoredAttribute) 1214 continue; 1215 Diag(Attr->getLoc(), 1216 Attr->getKind() == AttributeList::UnknownAttribute 1217 ? diag::warn_unknown_attribute_ignored 1218 : diag::err_base_specifier_attribute) 1219 << Attr->getName(); 1220 } 1221 } 1222 1223 TypeSourceInfo *TInfo = 0; 1224 GetTypeFromParser(basetype, &TInfo); 1225 1226 if (EllipsisLoc.isInvalid() && 1227 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 1228 UPPC_BaseType)) 1229 return true; 1230 1231 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 1232 Virtual, Access, TInfo, 1233 EllipsisLoc)) 1234 return BaseSpec; 1235 else 1236 Class->setInvalidDecl(); 1237 1238 return true; 1239} 1240 1241/// \brief Performs the actual work of attaching the given base class 1242/// specifiers to a C++ class. 1243bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 1244 unsigned NumBases) { 1245 if (NumBases == 0) 1246 return false; 1247 1248 // Used to keep track of which base types we have already seen, so 1249 // that we can properly diagnose redundant direct base types. Note 1250 // that the key is always the unqualified canonical type of the base 1251 // class. 1252 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 1253 1254 // Copy non-redundant base specifiers into permanent storage. 1255 unsigned NumGoodBases = 0; 1256 bool Invalid = false; 1257 for (unsigned idx = 0; idx < NumBases; ++idx) { 1258 QualType NewBaseType 1259 = Context.getCanonicalType(Bases[idx]->getType()); 1260 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 1261 1262 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 1263 if (KnownBase) { 1264 // C++ [class.mi]p3: 1265 // A class shall not be specified as a direct base class of a 1266 // derived class more than once. 1267 Diag(Bases[idx]->getLocStart(), 1268 diag::err_duplicate_base_class) 1269 << KnownBase->getType() 1270 << Bases[idx]->getSourceRange(); 1271 1272 // Delete the duplicate base class specifier; we're going to 1273 // overwrite its pointer later. 1274 Context.Deallocate(Bases[idx]); 1275 1276 Invalid = true; 1277 } else { 1278 // Okay, add this new base class. 1279 KnownBase = Bases[idx]; 1280 Bases[NumGoodBases++] = Bases[idx]; 1281 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 1282 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 1283 if (Class->isInterface() && 1284 (!RD->isInterface() || 1285 KnownBase->getAccessSpecifier() != AS_public)) { 1286 // The Microsoft extension __interface does not permit bases that 1287 // are not themselves public interfaces. 1288 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface) 1289 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName() 1290 << RD->getSourceRange(); 1291 Invalid = true; 1292 } 1293 if (RD->hasAttr<WeakAttr>()) 1294 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context)); 1295 } 1296 } 1297 } 1298 1299 // Attach the remaining base class specifiers to the derived class. 1300 Class->setBases(Bases, NumGoodBases); 1301 1302 // Delete the remaining (good) base class specifiers, since their 1303 // data has been copied into the CXXRecordDecl. 1304 for (unsigned idx = 0; idx < NumGoodBases; ++idx) 1305 Context.Deallocate(Bases[idx]); 1306 1307 return Invalid; 1308} 1309 1310/// ActOnBaseSpecifiers - Attach the given base specifiers to the 1311/// class, after checking whether there are any duplicate base 1312/// classes. 1313void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases, 1314 unsigned NumBases) { 1315 if (!ClassDecl || !Bases || !NumBases) 1316 return; 1317 1318 AdjustDeclIfTemplate(ClassDecl); 1319 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), 1320 (CXXBaseSpecifier**)(Bases), NumBases); 1321} 1322 1323/// \brief Determine whether the type \p Derived is a C++ class that is 1324/// derived from the type \p Base. 1325bool Sema::IsDerivedFrom(QualType Derived, QualType Base) { 1326 if (!getLangOpts().CPlusPlus) 1327 return false; 1328 1329 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1330 if (!DerivedRD) 1331 return false; 1332 1333 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1334 if (!BaseRD) 1335 return false; 1336 1337 // If either the base or the derived type is invalid, don't try to 1338 // check whether one is derived from the other. 1339 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 1340 return false; 1341 1342 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this. 1343 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD); 1344} 1345 1346/// \brief Determine whether the type \p Derived is a C++ class that is 1347/// derived from the type \p Base. 1348bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) { 1349 if (!getLangOpts().CPlusPlus) 1350 return false; 1351 1352 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1353 if (!DerivedRD) 1354 return false; 1355 1356 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1357 if (!BaseRD) 1358 return false; 1359 1360 return DerivedRD->isDerivedFrom(BaseRD, Paths); 1361} 1362 1363void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 1364 CXXCastPath &BasePathArray) { 1365 assert(BasePathArray.empty() && "Base path array must be empty!"); 1366 assert(Paths.isRecordingPaths() && "Must record paths!"); 1367 1368 const CXXBasePath &Path = Paths.front(); 1369 1370 // We first go backward and check if we have a virtual base. 1371 // FIXME: It would be better if CXXBasePath had the base specifier for 1372 // the nearest virtual base. 1373 unsigned Start = 0; 1374 for (unsigned I = Path.size(); I != 0; --I) { 1375 if (Path[I - 1].Base->isVirtual()) { 1376 Start = I - 1; 1377 break; 1378 } 1379 } 1380 1381 // Now add all bases. 1382 for (unsigned I = Start, E = Path.size(); I != E; ++I) 1383 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 1384} 1385 1386/// \brief Determine whether the given base path includes a virtual 1387/// base class. 1388bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) { 1389 for (CXXCastPath::const_iterator B = BasePath.begin(), 1390 BEnd = BasePath.end(); 1391 B != BEnd; ++B) 1392 if ((*B)->isVirtual()) 1393 return true; 1394 1395 return false; 1396} 1397 1398/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 1399/// conversion (where Derived and Base are class types) is 1400/// well-formed, meaning that the conversion is unambiguous (and 1401/// that all of the base classes are accessible). Returns true 1402/// and emits a diagnostic if the code is ill-formed, returns false 1403/// otherwise. Loc is the location where this routine should point to 1404/// if there is an error, and Range is the source range to highlight 1405/// if there is an error. 1406bool 1407Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1408 unsigned InaccessibleBaseID, 1409 unsigned AmbigiousBaseConvID, 1410 SourceLocation Loc, SourceRange Range, 1411 DeclarationName Name, 1412 CXXCastPath *BasePath) { 1413 // First, determine whether the path from Derived to Base is 1414 // ambiguous. This is slightly more expensive than checking whether 1415 // the Derived to Base conversion exists, because here we need to 1416 // explore multiple paths to determine if there is an ambiguity. 1417 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1418 /*DetectVirtual=*/false); 1419 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths); 1420 assert(DerivationOkay && 1421 "Can only be used with a derived-to-base conversion"); 1422 (void)DerivationOkay; 1423 1424 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 1425 if (InaccessibleBaseID) { 1426 // Check that the base class can be accessed. 1427 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(), 1428 InaccessibleBaseID)) { 1429 case AR_inaccessible: 1430 return true; 1431 case AR_accessible: 1432 case AR_dependent: 1433 case AR_delayed: 1434 break; 1435 } 1436 } 1437 1438 // Build a base path if necessary. 1439 if (BasePath) 1440 BuildBasePathArray(Paths, *BasePath); 1441 return false; 1442 } 1443 1444 // We know that the derived-to-base conversion is ambiguous, and 1445 // we're going to produce a diagnostic. Perform the derived-to-base 1446 // search just one more time to compute all of the possible paths so 1447 // that we can print them out. This is more expensive than any of 1448 // the previous derived-to-base checks we've done, but at this point 1449 // performance isn't as much of an issue. 1450 Paths.clear(); 1451 Paths.setRecordingPaths(true); 1452 bool StillOkay = IsDerivedFrom(Derived, Base, Paths); 1453 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 1454 (void)StillOkay; 1455 1456 // Build up a textual representation of the ambiguous paths, e.g., 1457 // D -> B -> A, that will be used to illustrate the ambiguous 1458 // conversions in the diagnostic. We only print one of the paths 1459 // to each base class subobject. 1460 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 1461 1462 Diag(Loc, AmbigiousBaseConvID) 1463 << Derived << Base << PathDisplayStr << Range << Name; 1464 return true; 1465} 1466 1467bool 1468Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1469 SourceLocation Loc, SourceRange Range, 1470 CXXCastPath *BasePath, 1471 bool IgnoreAccess) { 1472 return CheckDerivedToBaseConversion(Derived, Base, 1473 IgnoreAccess ? 0 1474 : diag::err_upcast_to_inaccessible_base, 1475 diag::err_ambiguous_derived_to_base_conv, 1476 Loc, Range, DeclarationName(), 1477 BasePath); 1478} 1479 1480 1481/// @brief Builds a string representing ambiguous paths from a 1482/// specific derived class to different subobjects of the same base 1483/// class. 1484/// 1485/// This function builds a string that can be used in error messages 1486/// to show the different paths that one can take through the 1487/// inheritance hierarchy to go from the derived class to different 1488/// subobjects of a base class. The result looks something like this: 1489/// @code 1490/// struct D -> struct B -> struct A 1491/// struct D -> struct C -> struct A 1492/// @endcode 1493std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 1494 std::string PathDisplayStr; 1495 std::set<unsigned> DisplayedPaths; 1496 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 1497 Path != Paths.end(); ++Path) { 1498 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 1499 // We haven't displayed a path to this particular base 1500 // class subobject yet. 1501 PathDisplayStr += "\n "; 1502 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 1503 for (CXXBasePath::const_iterator Element = Path->begin(); 1504 Element != Path->end(); ++Element) 1505 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 1506 } 1507 } 1508 1509 return PathDisplayStr; 1510} 1511 1512//===----------------------------------------------------------------------===// 1513// C++ class member Handling 1514//===----------------------------------------------------------------------===// 1515 1516/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 1517bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, 1518 SourceLocation ASLoc, 1519 SourceLocation ColonLoc, 1520 AttributeList *Attrs) { 1521 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 1522 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 1523 ASLoc, ColonLoc); 1524 CurContext->addHiddenDecl(ASDecl); 1525 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 1526} 1527 1528/// CheckOverrideControl - Check C++11 override control semantics. 1529void Sema::CheckOverrideControl(Decl *D) { 1530 if (D->isInvalidDecl()) 1531 return; 1532 1533 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 1534 1535 // Do we know which functions this declaration might be overriding? 1536 bool OverridesAreKnown = !MD || 1537 (!MD->getParent()->hasAnyDependentBases() && 1538 !MD->getType()->isDependentType()); 1539 1540 if (!MD || !MD->isVirtual()) { 1541 if (OverridesAreKnown) { 1542 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1543 Diag(OA->getLocation(), 1544 diag::override_keyword_only_allowed_on_virtual_member_functions) 1545 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 1546 D->dropAttr<OverrideAttr>(); 1547 } 1548 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1549 Diag(FA->getLocation(), 1550 diag::override_keyword_only_allowed_on_virtual_member_functions) 1551 << "final" << FixItHint::CreateRemoval(FA->getLocation()); 1552 D->dropAttr<FinalAttr>(); 1553 } 1554 } 1555 return; 1556 } 1557 1558 if (!OverridesAreKnown) 1559 return; 1560 1561 // C++11 [class.virtual]p5: 1562 // If a virtual function is marked with the virt-specifier override and 1563 // does not override a member function of a base class, the program is 1564 // ill-formed. 1565 bool HasOverriddenMethods = 1566 MD->begin_overridden_methods() != MD->end_overridden_methods(); 1567 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 1568 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 1569 << MD->getDeclName(); 1570} 1571 1572/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 1573/// function overrides a virtual member function marked 'final', according to 1574/// C++11 [class.virtual]p4. 1575bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 1576 const CXXMethodDecl *Old) { 1577 if (!Old->hasAttr<FinalAttr>()) 1578 return false; 1579 1580 Diag(New->getLocation(), diag::err_final_function_overridden) 1581 << New->getDeclName(); 1582 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 1583 return true; 1584} 1585 1586static bool InitializationHasSideEffects(const FieldDecl &FD) { 1587 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 1588 // FIXME: Destruction of ObjC lifetime types has side-effects. 1589 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 1590 return !RD->isCompleteDefinition() || 1591 !RD->hasTrivialDefaultConstructor() || 1592 !RD->hasTrivialDestructor(); 1593 return false; 1594} 1595 1596static AttributeList *getMSPropertyAttr(AttributeList *list) { 1597 for (AttributeList* it = list; it != 0; it = it->getNext()) 1598 if (it->isDeclspecPropertyAttribute()) 1599 return it; 1600 return 0; 1601} 1602 1603/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 1604/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 1605/// bitfield width if there is one, 'InitExpr' specifies the initializer if 1606/// one has been parsed, and 'InitStyle' is set if an in-class initializer is 1607/// present (but parsing it has been deferred). 1608NamedDecl * 1609Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 1610 MultiTemplateParamsArg TemplateParameterLists, 1611 Expr *BW, const VirtSpecifiers &VS, 1612 InClassInitStyle InitStyle) { 1613 const DeclSpec &DS = D.getDeclSpec(); 1614 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 1615 DeclarationName Name = NameInfo.getName(); 1616 SourceLocation Loc = NameInfo.getLoc(); 1617 1618 // For anonymous bitfields, the location should point to the type. 1619 if (Loc.isInvalid()) 1620 Loc = D.getLocStart(); 1621 1622 Expr *BitWidth = static_cast<Expr*>(BW); 1623 1624 assert(isa<CXXRecordDecl>(CurContext)); 1625 assert(!DS.isFriendSpecified()); 1626 1627 bool isFunc = D.isDeclarationOfFunction(); 1628 1629 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 1630 // The Microsoft extension __interface only permits public member functions 1631 // and prohibits constructors, destructors, operators, non-public member 1632 // functions, static methods and data members. 1633 unsigned InvalidDecl; 1634 bool ShowDeclName = true; 1635 if (!isFunc) 1636 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1; 1637 else if (AS != AS_public) 1638 InvalidDecl = 2; 1639 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 1640 InvalidDecl = 3; 1641 else switch (Name.getNameKind()) { 1642 case DeclarationName::CXXConstructorName: 1643 InvalidDecl = 4; 1644 ShowDeclName = false; 1645 break; 1646 1647 case DeclarationName::CXXDestructorName: 1648 InvalidDecl = 5; 1649 ShowDeclName = false; 1650 break; 1651 1652 case DeclarationName::CXXOperatorName: 1653 case DeclarationName::CXXConversionFunctionName: 1654 InvalidDecl = 6; 1655 break; 1656 1657 default: 1658 InvalidDecl = 0; 1659 break; 1660 } 1661 1662 if (InvalidDecl) { 1663 if (ShowDeclName) 1664 Diag(Loc, diag::err_invalid_member_in_interface) 1665 << (InvalidDecl-1) << Name; 1666 else 1667 Diag(Loc, diag::err_invalid_member_in_interface) 1668 << (InvalidDecl-1) << ""; 1669 return 0; 1670 } 1671 } 1672 1673 // C++ 9.2p6: A member shall not be declared to have automatic storage 1674 // duration (auto, register) or with the extern storage-class-specifier. 1675 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 1676 // data members and cannot be applied to names declared const or static, 1677 // and cannot be applied to reference members. 1678 switch (DS.getStorageClassSpec()) { 1679 case DeclSpec::SCS_unspecified: 1680 case DeclSpec::SCS_typedef: 1681 case DeclSpec::SCS_static: 1682 break; 1683 case DeclSpec::SCS_mutable: 1684 if (isFunc) { 1685 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 1686 1687 // FIXME: It would be nicer if the keyword was ignored only for this 1688 // declarator. Otherwise we could get follow-up errors. 1689 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1690 } 1691 break; 1692 default: 1693 Diag(DS.getStorageClassSpecLoc(), 1694 diag::err_storageclass_invalid_for_member); 1695 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1696 break; 1697 } 1698 1699 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 1700 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 1701 !isFunc); 1702 1703 if (DS.isConstexprSpecified() && isInstField) { 1704 SemaDiagnosticBuilder B = 1705 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 1706 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 1707 if (InitStyle == ICIS_NoInit) { 1708 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const"); 1709 D.getMutableDeclSpec().ClearConstexprSpec(); 1710 const char *PrevSpec; 1711 unsigned DiagID; 1712 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc, 1713 PrevSpec, DiagID, getLangOpts()); 1714 (void)Failed; 1715 assert(!Failed && "Making a constexpr member const shouldn't fail"); 1716 } else { 1717 B << 1; 1718 const char *PrevSpec; 1719 unsigned DiagID; 1720 if (D.getMutableDeclSpec().SetStorageClassSpec( 1721 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) { 1722 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 1723 "This is the only DeclSpec that should fail to be applied"); 1724 B << 1; 1725 } else { 1726 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 1727 isInstField = false; 1728 } 1729 } 1730 } 1731 1732 NamedDecl *Member; 1733 if (isInstField) { 1734 CXXScopeSpec &SS = D.getCXXScopeSpec(); 1735 1736 // Data members must have identifiers for names. 1737 if (!Name.isIdentifier()) { 1738 Diag(Loc, diag::err_bad_variable_name) 1739 << Name; 1740 return 0; 1741 } 1742 1743 IdentifierInfo *II = Name.getAsIdentifierInfo(); 1744 1745 // Member field could not be with "template" keyword. 1746 // So TemplateParameterLists should be empty in this case. 1747 if (TemplateParameterLists.size()) { 1748 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 1749 if (TemplateParams->size()) { 1750 // There is no such thing as a member field template. 1751 Diag(D.getIdentifierLoc(), diag::err_template_member) 1752 << II 1753 << SourceRange(TemplateParams->getTemplateLoc(), 1754 TemplateParams->getRAngleLoc()); 1755 } else { 1756 // There is an extraneous 'template<>' for this member. 1757 Diag(TemplateParams->getTemplateLoc(), 1758 diag::err_template_member_noparams) 1759 << II 1760 << SourceRange(TemplateParams->getTemplateLoc(), 1761 TemplateParams->getRAngleLoc()); 1762 } 1763 return 0; 1764 } 1765 1766 if (SS.isSet() && !SS.isInvalid()) { 1767 // The user provided a superfluous scope specifier inside a class 1768 // definition: 1769 // 1770 // class X { 1771 // int X::member; 1772 // }; 1773 if (DeclContext *DC = computeDeclContext(SS, false)) 1774 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc()); 1775 else 1776 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 1777 << Name << SS.getRange(); 1778 1779 SS.clear(); 1780 } 1781 1782 AttributeList *MSPropertyAttr = 1783 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList()); 1784 if (MSPropertyAttr) { 1785 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 1786 BitWidth, InitStyle, AS, MSPropertyAttr); 1787 isInstField = false; 1788 } else { 1789 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 1790 BitWidth, InitStyle, AS); 1791 } 1792 assert(Member && "HandleField never returns null"); 1793 } else { 1794 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static); 1795 1796 Member = HandleDeclarator(S, D, TemplateParameterLists); 1797 if (!Member) { 1798 return 0; 1799 } 1800 1801 // Non-instance-fields can't have a bitfield. 1802 if (BitWidth) { 1803 if (Member->isInvalidDecl()) { 1804 // don't emit another diagnostic. 1805 } else if (isa<VarDecl>(Member)) { 1806 // C++ 9.6p3: A bit-field shall not be a static member. 1807 // "static member 'A' cannot be a bit-field" 1808 Diag(Loc, diag::err_static_not_bitfield) 1809 << Name << BitWidth->getSourceRange(); 1810 } else if (isa<TypedefDecl>(Member)) { 1811 // "typedef member 'x' cannot be a bit-field" 1812 Diag(Loc, diag::err_typedef_not_bitfield) 1813 << Name << BitWidth->getSourceRange(); 1814 } else { 1815 // A function typedef ("typedef int f(); f a;"). 1816 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 1817 Diag(Loc, diag::err_not_integral_type_bitfield) 1818 << Name << cast<ValueDecl>(Member)->getType() 1819 << BitWidth->getSourceRange(); 1820 } 1821 1822 BitWidth = 0; 1823 Member->setInvalidDecl(); 1824 } 1825 1826 Member->setAccess(AS); 1827 1828 // If we have declared a member function template, set the access of the 1829 // templated declaration as well. 1830 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 1831 FunTmpl->getTemplatedDecl()->setAccess(AS); 1832 } 1833 1834 if (VS.isOverrideSpecified()) 1835 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context)); 1836 if (VS.isFinalSpecified()) 1837 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context)); 1838 1839 if (VS.getLastLocation().isValid()) { 1840 // Update the end location of a method that has a virt-specifiers. 1841 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 1842 MD->setRangeEnd(VS.getLastLocation()); 1843 } 1844 1845 CheckOverrideControl(Member); 1846 1847 assert((Name || isInstField) && "No identifier for non-field ?"); 1848 1849 if (isInstField) { 1850 FieldDecl *FD = cast<FieldDecl>(Member); 1851 FieldCollector->Add(FD); 1852 1853 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field, 1854 FD->getLocation()) 1855 != DiagnosticsEngine::Ignored) { 1856 // Remember all explicit private FieldDecls that have a name, no side 1857 // effects and are not part of a dependent type declaration. 1858 if (!FD->isImplicit() && FD->getDeclName() && 1859 FD->getAccess() == AS_private && 1860 !FD->hasAttr<UnusedAttr>() && 1861 !FD->getParent()->isDependentContext() && 1862 !InitializationHasSideEffects(*FD)) 1863 UnusedPrivateFields.insert(FD); 1864 } 1865 } 1866 1867 return Member; 1868} 1869 1870namespace { 1871 class UninitializedFieldVisitor 1872 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 1873 Sema &S; 1874 ValueDecl *VD; 1875 public: 1876 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 1877 UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context), 1878 S(S) { 1879 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD)) 1880 this->VD = IFD->getAnonField(); 1881 else 1882 this->VD = VD; 1883 } 1884 1885 void HandleExpr(Expr *E) { 1886 if (!E) return; 1887 1888 // Expressions like x(x) sometimes lack the surrounding expressions 1889 // but need to be checked anyways. 1890 HandleValue(E); 1891 Visit(E); 1892 } 1893 1894 void HandleValue(Expr *E) { 1895 E = E->IgnoreParens(); 1896 1897 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 1898 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 1899 return; 1900 1901 // FieldME is the inner-most MemberExpr that is not an anonymous struct 1902 // or union. 1903 MemberExpr *FieldME = ME; 1904 1905 Expr *Base = E; 1906 while (isa<MemberExpr>(Base)) { 1907 ME = cast<MemberExpr>(Base); 1908 1909 if (isa<VarDecl>(ME->getMemberDecl())) 1910 return; 1911 1912 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 1913 if (!FD->isAnonymousStructOrUnion()) 1914 FieldME = ME; 1915 1916 Base = ME->getBase(); 1917 } 1918 1919 if (VD == FieldME->getMemberDecl() && isa<CXXThisExpr>(Base)) { 1920 unsigned diag = VD->getType()->isReferenceType() 1921 ? diag::warn_reference_field_is_uninit 1922 : diag::warn_field_is_uninit; 1923 S.Diag(FieldME->getExprLoc(), diag) << VD; 1924 } 1925 return; 1926 } 1927 1928 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 1929 HandleValue(CO->getTrueExpr()); 1930 HandleValue(CO->getFalseExpr()); 1931 return; 1932 } 1933 1934 if (BinaryConditionalOperator *BCO = 1935 dyn_cast<BinaryConditionalOperator>(E)) { 1936 HandleValue(BCO->getCommon()); 1937 HandleValue(BCO->getFalseExpr()); 1938 return; 1939 } 1940 1941 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 1942 switch (BO->getOpcode()) { 1943 default: 1944 return; 1945 case(BO_PtrMemD): 1946 case(BO_PtrMemI): 1947 HandleValue(BO->getLHS()); 1948 return; 1949 case(BO_Comma): 1950 HandleValue(BO->getRHS()); 1951 return; 1952 } 1953 } 1954 } 1955 1956 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 1957 if (E->getCastKind() == CK_LValueToRValue) 1958 HandleValue(E->getSubExpr()); 1959 1960 Inherited::VisitImplicitCastExpr(E); 1961 } 1962 1963 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 1964 Expr *Callee = E->getCallee(); 1965 if (isa<MemberExpr>(Callee)) 1966 HandleValue(Callee); 1967 1968 Inherited::VisitCXXMemberCallExpr(E); 1969 } 1970 }; 1971 static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E, 1972 ValueDecl *VD) { 1973 UninitializedFieldVisitor(S, VD).HandleExpr(E); 1974 } 1975} // namespace 1976 1977/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an 1978/// in-class initializer for a non-static C++ class member, and after 1979/// instantiating an in-class initializer in a class template. Such actions 1980/// are deferred until the class is complete. 1981void 1982Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc, 1983 Expr *InitExpr) { 1984 FieldDecl *FD = cast<FieldDecl>(D); 1985 assert(FD->getInClassInitStyle() != ICIS_NoInit && 1986 "must set init style when field is created"); 1987 1988 if (!InitExpr) { 1989 FD->setInvalidDecl(); 1990 FD->removeInClassInitializer(); 1991 return; 1992 } 1993 1994 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 1995 FD->setInvalidDecl(); 1996 FD->removeInClassInitializer(); 1997 return; 1998 } 1999 2000 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, InitLoc) 2001 != DiagnosticsEngine::Ignored) { 2002 CheckInitExprContainsUninitializedFields(*this, InitExpr, FD); 2003 } 2004 2005 ExprResult Init = InitExpr; 2006 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 2007 if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) { 2008 Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list) 2009 << /*at end of ctor*/1 << InitExpr->getSourceRange(); 2010 } 2011 Expr **Inits = &InitExpr; 2012 unsigned NumInits = 1; 2013 InitializedEntity Entity = InitializedEntity::InitializeMember(FD); 2014 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit 2015 ? InitializationKind::CreateDirectList(InitExpr->getLocStart()) 2016 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc); 2017 InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits); 2018 Init = Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits)); 2019 if (Init.isInvalid()) { 2020 FD->setInvalidDecl(); 2021 return; 2022 } 2023 } 2024 2025 // C++11 [class.base.init]p7: 2026 // The initialization of each base and member constitutes a 2027 // full-expression. 2028 Init = ActOnFinishFullExpr(Init.take(), InitLoc); 2029 if (Init.isInvalid()) { 2030 FD->setInvalidDecl(); 2031 return; 2032 } 2033 2034 InitExpr = Init.release(); 2035 2036 FD->setInClassInitializer(InitExpr); 2037} 2038 2039/// \brief Find the direct and/or virtual base specifiers that 2040/// correspond to the given base type, for use in base initialization 2041/// within a constructor. 2042static bool FindBaseInitializer(Sema &SemaRef, 2043 CXXRecordDecl *ClassDecl, 2044 QualType BaseType, 2045 const CXXBaseSpecifier *&DirectBaseSpec, 2046 const CXXBaseSpecifier *&VirtualBaseSpec) { 2047 // First, check for a direct base class. 2048 DirectBaseSpec = 0; 2049 for (CXXRecordDecl::base_class_const_iterator Base 2050 = ClassDecl->bases_begin(); 2051 Base != ClassDecl->bases_end(); ++Base) { 2052 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) { 2053 // We found a direct base of this type. That's what we're 2054 // initializing. 2055 DirectBaseSpec = &*Base; 2056 break; 2057 } 2058 } 2059 2060 // Check for a virtual base class. 2061 // FIXME: We might be able to short-circuit this if we know in advance that 2062 // there are no virtual bases. 2063 VirtualBaseSpec = 0; 2064 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 2065 // We haven't found a base yet; search the class hierarchy for a 2066 // virtual base class. 2067 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2068 /*DetectVirtual=*/false); 2069 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl), 2070 BaseType, Paths)) { 2071 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2072 Path != Paths.end(); ++Path) { 2073 if (Path->back().Base->isVirtual()) { 2074 VirtualBaseSpec = Path->back().Base; 2075 break; 2076 } 2077 } 2078 } 2079 } 2080 2081 return DirectBaseSpec || VirtualBaseSpec; 2082} 2083 2084/// \brief Handle a C++ member initializer using braced-init-list syntax. 2085MemInitResult 2086Sema::ActOnMemInitializer(Decl *ConstructorD, 2087 Scope *S, 2088 CXXScopeSpec &SS, 2089 IdentifierInfo *MemberOrBase, 2090 ParsedType TemplateTypeTy, 2091 const DeclSpec &DS, 2092 SourceLocation IdLoc, 2093 Expr *InitList, 2094 SourceLocation EllipsisLoc) { 2095 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2096 DS, IdLoc, InitList, 2097 EllipsisLoc); 2098} 2099 2100/// \brief Handle a C++ member initializer using parentheses syntax. 2101MemInitResult 2102Sema::ActOnMemInitializer(Decl *ConstructorD, 2103 Scope *S, 2104 CXXScopeSpec &SS, 2105 IdentifierInfo *MemberOrBase, 2106 ParsedType TemplateTypeTy, 2107 const DeclSpec &DS, 2108 SourceLocation IdLoc, 2109 SourceLocation LParenLoc, 2110 Expr **Args, unsigned NumArgs, 2111 SourceLocation RParenLoc, 2112 SourceLocation EllipsisLoc) { 2113 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, 2114 llvm::makeArrayRef(Args, NumArgs), 2115 RParenLoc); 2116 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2117 DS, IdLoc, List, EllipsisLoc); 2118} 2119 2120namespace { 2121 2122// Callback to only accept typo corrections that can be a valid C++ member 2123// intializer: either a non-static field member or a base class. 2124class MemInitializerValidatorCCC : public CorrectionCandidateCallback { 2125 public: 2126 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 2127 : ClassDecl(ClassDecl) {} 2128 2129 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 2130 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 2131 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 2132 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 2133 else 2134 return isa<TypeDecl>(ND); 2135 } 2136 return false; 2137 } 2138 2139 private: 2140 CXXRecordDecl *ClassDecl; 2141}; 2142 2143} 2144 2145/// \brief Handle a C++ member initializer. 2146MemInitResult 2147Sema::BuildMemInitializer(Decl *ConstructorD, 2148 Scope *S, 2149 CXXScopeSpec &SS, 2150 IdentifierInfo *MemberOrBase, 2151 ParsedType TemplateTypeTy, 2152 const DeclSpec &DS, 2153 SourceLocation IdLoc, 2154 Expr *Init, 2155 SourceLocation EllipsisLoc) { 2156 if (!ConstructorD) 2157 return true; 2158 2159 AdjustDeclIfTemplate(ConstructorD); 2160 2161 CXXConstructorDecl *Constructor 2162 = dyn_cast<CXXConstructorDecl>(ConstructorD); 2163 if (!Constructor) { 2164 // The user wrote a constructor initializer on a function that is 2165 // not a C++ constructor. Ignore the error for now, because we may 2166 // have more member initializers coming; we'll diagnose it just 2167 // once in ActOnMemInitializers. 2168 return true; 2169 } 2170 2171 CXXRecordDecl *ClassDecl = Constructor->getParent(); 2172 2173 // C++ [class.base.init]p2: 2174 // Names in a mem-initializer-id are looked up in the scope of the 2175 // constructor's class and, if not found in that scope, are looked 2176 // up in the scope containing the constructor's definition. 2177 // [Note: if the constructor's class contains a member with the 2178 // same name as a direct or virtual base class of the class, a 2179 // mem-initializer-id naming the member or base class and composed 2180 // of a single identifier refers to the class member. A 2181 // mem-initializer-id for the hidden base class may be specified 2182 // using a qualified name. ] 2183 if (!SS.getScopeRep() && !TemplateTypeTy) { 2184 // Look for a member, first. 2185 DeclContext::lookup_result Result 2186 = ClassDecl->lookup(MemberOrBase); 2187 if (!Result.empty()) { 2188 ValueDecl *Member; 2189 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 2190 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) { 2191 if (EllipsisLoc.isValid()) 2192 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 2193 << MemberOrBase 2194 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 2195 2196 return BuildMemberInitializer(Member, Init, IdLoc); 2197 } 2198 } 2199 } 2200 // It didn't name a member, so see if it names a class. 2201 QualType BaseType; 2202 TypeSourceInfo *TInfo = 0; 2203 2204 if (TemplateTypeTy) { 2205 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 2206 } else if (DS.getTypeSpecType() == TST_decltype) { 2207 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 2208 } else { 2209 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 2210 LookupParsedName(R, S, &SS); 2211 2212 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 2213 if (!TyD) { 2214 if (R.isAmbiguous()) return true; 2215 2216 // We don't want access-control diagnostics here. 2217 R.suppressDiagnostics(); 2218 2219 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 2220 bool NotUnknownSpecialization = false; 2221 DeclContext *DC = computeDeclContext(SS, false); 2222 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 2223 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 2224 2225 if (!NotUnknownSpecialization) { 2226 // When the scope specifier can refer to a member of an unknown 2227 // specialization, we take it as a type name. 2228 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 2229 SS.getWithLocInContext(Context), 2230 *MemberOrBase, IdLoc); 2231 if (BaseType.isNull()) 2232 return true; 2233 2234 R.clear(); 2235 R.setLookupName(MemberOrBase); 2236 } 2237 } 2238 2239 // If no results were found, try to correct typos. 2240 TypoCorrection Corr; 2241 MemInitializerValidatorCCC Validator(ClassDecl); 2242 if (R.empty() && BaseType.isNull() && 2243 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 2244 Validator, ClassDecl))) { 2245 std::string CorrectedStr(Corr.getAsString(getLangOpts())); 2246 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts())); 2247 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 2248 // We have found a non-static data member with a similar 2249 // name to what was typed; complain and initialize that 2250 // member. 2251 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest) 2252 << MemberOrBase << true << CorrectedQuotedStr 2253 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr); 2254 Diag(Member->getLocation(), diag::note_previous_decl) 2255 << CorrectedQuotedStr; 2256 2257 return BuildMemberInitializer(Member, Init, IdLoc); 2258 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 2259 const CXXBaseSpecifier *DirectBaseSpec; 2260 const CXXBaseSpecifier *VirtualBaseSpec; 2261 if (FindBaseInitializer(*this, ClassDecl, 2262 Context.getTypeDeclType(Type), 2263 DirectBaseSpec, VirtualBaseSpec)) { 2264 // We have found a direct or virtual base class with a 2265 // similar name to what was typed; complain and initialize 2266 // that base class. 2267 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest) 2268 << MemberOrBase << false << CorrectedQuotedStr 2269 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr); 2270 2271 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec 2272 : VirtualBaseSpec; 2273 Diag(BaseSpec->getLocStart(), 2274 diag::note_base_class_specified_here) 2275 << BaseSpec->getType() 2276 << BaseSpec->getSourceRange(); 2277 2278 TyD = Type; 2279 } 2280 } 2281 } 2282 2283 if (!TyD && BaseType.isNull()) { 2284 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 2285 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 2286 return true; 2287 } 2288 } 2289 2290 if (BaseType.isNull()) { 2291 BaseType = Context.getTypeDeclType(TyD); 2292 if (SS.isSet()) { 2293 NestedNameSpecifier *Qualifier = 2294 static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 2295 2296 // FIXME: preserve source range information 2297 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType); 2298 } 2299 } 2300 } 2301 2302 if (!TInfo) 2303 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 2304 2305 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 2306} 2307 2308/// Checks a member initializer expression for cases where reference (or 2309/// pointer) members are bound to by-value parameters (or their addresses). 2310static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member, 2311 Expr *Init, 2312 SourceLocation IdLoc) { 2313 QualType MemberTy = Member->getType(); 2314 2315 // We only handle pointers and references currently. 2316 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers? 2317 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType()) 2318 return; 2319 2320 const bool IsPointer = MemberTy->isPointerType(); 2321 if (IsPointer) { 2322 if (const UnaryOperator *Op 2323 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) { 2324 // The only case we're worried about with pointers requires taking the 2325 // address. 2326 if (Op->getOpcode() != UO_AddrOf) 2327 return; 2328 2329 Init = Op->getSubExpr(); 2330 } else { 2331 // We only handle address-of expression initializers for pointers. 2332 return; 2333 } 2334 } 2335 2336 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) { 2337 // Taking the address of a temporary will be diagnosed as a hard error. 2338 if (IsPointer) 2339 return; 2340 2341 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary) 2342 << Member << Init->getSourceRange(); 2343 } else if (const DeclRefExpr *DRE 2344 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) { 2345 // We only warn when referring to a non-reference parameter declaration. 2346 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl()); 2347 if (!Parameter || Parameter->getType()->isReferenceType()) 2348 return; 2349 2350 S.Diag(Init->getExprLoc(), 2351 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr 2352 : diag::warn_bind_ref_member_to_parameter) 2353 << Member << Parameter << Init->getSourceRange(); 2354 } else { 2355 // Other initializers are fine. 2356 return; 2357 } 2358 2359 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here) 2360 << (unsigned)IsPointer; 2361} 2362 2363MemInitResult 2364Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 2365 SourceLocation IdLoc) { 2366 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 2367 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 2368 assert((DirectMember || IndirectMember) && 2369 "Member must be a FieldDecl or IndirectFieldDecl"); 2370 2371 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 2372 return true; 2373 2374 if (Member->isInvalidDecl()) 2375 return true; 2376 2377 // Diagnose value-uses of fields to initialize themselves, e.g. 2378 // foo(foo) 2379 // where foo is not also a parameter to the constructor. 2380 // TODO: implement -Wuninitialized and fold this into that framework. 2381 Expr **Args; 2382 unsigned NumArgs; 2383 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2384 Args = ParenList->getExprs(); 2385 NumArgs = ParenList->getNumExprs(); 2386 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 2387 Args = InitList->getInits(); 2388 NumArgs = InitList->getNumInits(); 2389 } else { 2390 // Template instantiation doesn't reconstruct ParenListExprs for us. 2391 Args = &Init; 2392 NumArgs = 1; 2393 } 2394 2395 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc) 2396 != DiagnosticsEngine::Ignored) 2397 for (unsigned i = 0; i < NumArgs; ++i) 2398 // FIXME: Warn about the case when other fields are used before being 2399 // initialized. For example, let this field be the i'th field. When 2400 // initializing the i'th field, throw a warning if any of the >= i'th 2401 // fields are used, as they are not yet initialized. 2402 // Right now we are only handling the case where the i'th field uses 2403 // itself in its initializer. 2404 // Also need to take into account that some fields may be initialized by 2405 // in-class initializers, see C++11 [class.base.init]p9. 2406 CheckInitExprContainsUninitializedFields(*this, Args[i], Member); 2407 2408 SourceRange InitRange = Init->getSourceRange(); 2409 2410 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 2411 // Can't check initialization for a member of dependent type or when 2412 // any of the arguments are type-dependent expressions. 2413 DiscardCleanupsInEvaluationContext(); 2414 } else { 2415 bool InitList = false; 2416 if (isa<InitListExpr>(Init)) { 2417 InitList = true; 2418 Args = &Init; 2419 NumArgs = 1; 2420 2421 if (isStdInitializerList(Member->getType(), 0)) { 2422 Diag(IdLoc, diag::warn_dangling_std_initializer_list) 2423 << /*at end of ctor*/1 << InitRange; 2424 } 2425 } 2426 2427 // Initialize the member. 2428 InitializedEntity MemberEntity = 2429 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0) 2430 : InitializedEntity::InitializeMember(IndirectMember, 0); 2431 InitializationKind Kind = 2432 InitList ? InitializationKind::CreateDirectList(IdLoc) 2433 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 2434 InitRange.getEnd()); 2435 2436 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs); 2437 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, 2438 MultiExprArg(Args, NumArgs), 2439 0); 2440 if (MemberInit.isInvalid()) 2441 return true; 2442 2443 // C++11 [class.base.init]p7: 2444 // The initialization of each base and member constitutes a 2445 // full-expression. 2446 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin()); 2447 if (MemberInit.isInvalid()) 2448 return true; 2449 2450 Init = MemberInit.get(); 2451 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc); 2452 } 2453 2454 if (DirectMember) { 2455 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 2456 InitRange.getBegin(), Init, 2457 InitRange.getEnd()); 2458 } else { 2459 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 2460 InitRange.getBegin(), Init, 2461 InitRange.getEnd()); 2462 } 2463} 2464 2465MemInitResult 2466Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 2467 CXXRecordDecl *ClassDecl) { 2468 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 2469 if (!LangOpts.CPlusPlus11) 2470 return Diag(NameLoc, diag::err_delegating_ctor) 2471 << TInfo->getTypeLoc().getLocalSourceRange(); 2472 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 2473 2474 bool InitList = true; 2475 Expr **Args = &Init; 2476 unsigned NumArgs = 1; 2477 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2478 InitList = false; 2479 Args = ParenList->getExprs(); 2480 NumArgs = ParenList->getNumExprs(); 2481 } 2482 2483 SourceRange InitRange = Init->getSourceRange(); 2484 // Initialize the object. 2485 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 2486 QualType(ClassDecl->getTypeForDecl(), 0)); 2487 InitializationKind Kind = 2488 InitList ? InitializationKind::CreateDirectList(NameLoc) 2489 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 2490 InitRange.getEnd()); 2491 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs); 2492 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 2493 MultiExprArg(Args, NumArgs), 2494 0); 2495 if (DelegationInit.isInvalid()) 2496 return true; 2497 2498 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 2499 "Delegating constructor with no target?"); 2500 2501 // C++11 [class.base.init]p7: 2502 // The initialization of each base and member constitutes a 2503 // full-expression. 2504 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(), 2505 InitRange.getBegin()); 2506 if (DelegationInit.isInvalid()) 2507 return true; 2508 2509 // If we are in a dependent context, template instantiation will 2510 // perform this type-checking again. Just save the arguments that we 2511 // received in a ParenListExpr. 2512 // FIXME: This isn't quite ideal, since our ASTs don't capture all 2513 // of the information that we have about the base 2514 // initializer. However, deconstructing the ASTs is a dicey process, 2515 // and this approach is far more likely to get the corner cases right. 2516 if (CurContext->isDependentContext()) 2517 DelegationInit = Owned(Init); 2518 2519 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 2520 DelegationInit.takeAs<Expr>(), 2521 InitRange.getEnd()); 2522} 2523 2524MemInitResult 2525Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 2526 Expr *Init, CXXRecordDecl *ClassDecl, 2527 SourceLocation EllipsisLoc) { 2528 SourceLocation BaseLoc 2529 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 2530 2531 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 2532 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 2533 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2534 2535 // C++ [class.base.init]p2: 2536 // [...] Unless the mem-initializer-id names a nonstatic data 2537 // member of the constructor's class or a direct or virtual base 2538 // of that class, the mem-initializer is ill-formed. A 2539 // mem-initializer-list can initialize a base class using any 2540 // name that denotes that base class type. 2541 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 2542 2543 SourceRange InitRange = Init->getSourceRange(); 2544 if (EllipsisLoc.isValid()) { 2545 // This is a pack expansion. 2546 if (!BaseType->containsUnexpandedParameterPack()) { 2547 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2548 << SourceRange(BaseLoc, InitRange.getEnd()); 2549 2550 EllipsisLoc = SourceLocation(); 2551 } 2552 } else { 2553 // Check for any unexpanded parameter packs. 2554 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 2555 return true; 2556 2557 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 2558 return true; 2559 } 2560 2561 // Check for direct and virtual base classes. 2562 const CXXBaseSpecifier *DirectBaseSpec = 0; 2563 const CXXBaseSpecifier *VirtualBaseSpec = 0; 2564 if (!Dependent) { 2565 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 2566 BaseType)) 2567 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 2568 2569 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 2570 VirtualBaseSpec); 2571 2572 // C++ [base.class.init]p2: 2573 // Unless the mem-initializer-id names a nonstatic data member of the 2574 // constructor's class or a direct or virtual base of that class, the 2575 // mem-initializer is ill-formed. 2576 if (!DirectBaseSpec && !VirtualBaseSpec) { 2577 // If the class has any dependent bases, then it's possible that 2578 // one of those types will resolve to the same type as 2579 // BaseType. Therefore, just treat this as a dependent base 2580 // class initialization. FIXME: Should we try to check the 2581 // initialization anyway? It seems odd. 2582 if (ClassDecl->hasAnyDependentBases()) 2583 Dependent = true; 2584 else 2585 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 2586 << BaseType << Context.getTypeDeclType(ClassDecl) 2587 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2588 } 2589 } 2590 2591 if (Dependent) { 2592 DiscardCleanupsInEvaluationContext(); 2593 2594 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 2595 /*IsVirtual=*/false, 2596 InitRange.getBegin(), Init, 2597 InitRange.getEnd(), EllipsisLoc); 2598 } 2599 2600 // C++ [base.class.init]p2: 2601 // If a mem-initializer-id is ambiguous because it designates both 2602 // a direct non-virtual base class and an inherited virtual base 2603 // class, the mem-initializer is ill-formed. 2604 if (DirectBaseSpec && VirtualBaseSpec) 2605 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 2606 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2607 2608 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec); 2609 if (!BaseSpec) 2610 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec); 2611 2612 // Initialize the base. 2613 bool InitList = true; 2614 Expr **Args = &Init; 2615 unsigned NumArgs = 1; 2616 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2617 InitList = false; 2618 Args = ParenList->getExprs(); 2619 NumArgs = ParenList->getNumExprs(); 2620 } 2621 2622 InitializedEntity BaseEntity = 2623 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 2624 InitializationKind Kind = 2625 InitList ? InitializationKind::CreateDirectList(BaseLoc) 2626 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 2627 InitRange.getEnd()); 2628 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs); 2629 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, 2630 MultiExprArg(Args, NumArgs), 0); 2631 if (BaseInit.isInvalid()) 2632 return true; 2633 2634 // C++11 [class.base.init]p7: 2635 // The initialization of each base and member constitutes a 2636 // full-expression. 2637 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin()); 2638 if (BaseInit.isInvalid()) 2639 return true; 2640 2641 // If we are in a dependent context, template instantiation will 2642 // perform this type-checking again. Just save the arguments that we 2643 // received in a ParenListExpr. 2644 // FIXME: This isn't quite ideal, since our ASTs don't capture all 2645 // of the information that we have about the base 2646 // initializer. However, deconstructing the ASTs is a dicey process, 2647 // and this approach is far more likely to get the corner cases right. 2648 if (CurContext->isDependentContext()) 2649 BaseInit = Owned(Init); 2650 2651 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 2652 BaseSpec->isVirtual(), 2653 InitRange.getBegin(), 2654 BaseInit.takeAs<Expr>(), 2655 InitRange.getEnd(), EllipsisLoc); 2656} 2657 2658// Create a static_cast\<T&&>(expr). 2659static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 2660 if (T.isNull()) T = E->getType(); 2661 QualType TargetType = SemaRef.BuildReferenceType( 2662 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 2663 SourceLocation ExprLoc = E->getLocStart(); 2664 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 2665 TargetType, ExprLoc); 2666 2667 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 2668 SourceRange(ExprLoc, ExprLoc), 2669 E->getSourceRange()).take(); 2670} 2671 2672/// ImplicitInitializerKind - How an implicit base or member initializer should 2673/// initialize its base or member. 2674enum ImplicitInitializerKind { 2675 IIK_Default, 2676 IIK_Copy, 2677 IIK_Move, 2678 IIK_Inherit 2679}; 2680 2681static bool 2682BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 2683 ImplicitInitializerKind ImplicitInitKind, 2684 CXXBaseSpecifier *BaseSpec, 2685 bool IsInheritedVirtualBase, 2686 CXXCtorInitializer *&CXXBaseInit) { 2687 InitializedEntity InitEntity 2688 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 2689 IsInheritedVirtualBase); 2690 2691 ExprResult BaseInit; 2692 2693 switch (ImplicitInitKind) { 2694 case IIK_Inherit: { 2695 const CXXRecordDecl *Inherited = 2696 Constructor->getInheritedConstructor()->getParent(); 2697 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 2698 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) { 2699 // C++11 [class.inhctor]p8: 2700 // Each expression in the expression-list is of the form 2701 // static_cast<T&&>(p), where p is the name of the corresponding 2702 // constructor parameter and T is the declared type of p. 2703 SmallVector<Expr*, 16> Args; 2704 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) { 2705 ParmVarDecl *PD = Constructor->getParamDecl(I); 2706 ExprResult ArgExpr = 2707 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(), 2708 VK_LValue, SourceLocation()); 2709 if (ArgExpr.isInvalid()) 2710 return true; 2711 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType())); 2712 } 2713 2714 InitializationKind InitKind = InitializationKind::CreateDirect( 2715 Constructor->getLocation(), SourceLocation(), SourceLocation()); 2716 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 2717 Args.data(), Args.size()); 2718 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args); 2719 break; 2720 } 2721 } 2722 // Fall through. 2723 case IIK_Default: { 2724 InitializationKind InitKind 2725 = InitializationKind::CreateDefault(Constructor->getLocation()); 2726 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0); 2727 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg()); 2728 break; 2729 } 2730 2731 case IIK_Move: 2732 case IIK_Copy: { 2733 bool Moving = ImplicitInitKind == IIK_Move; 2734 ParmVarDecl *Param = Constructor->getParamDecl(0); 2735 QualType ParamType = Param->getType().getNonReferenceType(); 2736 2737 Expr *CopyCtorArg = 2738 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 2739 SourceLocation(), Param, false, 2740 Constructor->getLocation(), ParamType, 2741 VK_LValue, 0); 2742 2743 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 2744 2745 // Cast to the base class to avoid ambiguities. 2746 QualType ArgTy = 2747 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 2748 ParamType.getQualifiers()); 2749 2750 if (Moving) { 2751 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 2752 } 2753 2754 CXXCastPath BasePath; 2755 BasePath.push_back(BaseSpec); 2756 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 2757 CK_UncheckedDerivedToBase, 2758 Moving ? VK_XValue : VK_LValue, 2759 &BasePath).take(); 2760 2761 InitializationKind InitKind 2762 = InitializationKind::CreateDirect(Constructor->getLocation(), 2763 SourceLocation(), SourceLocation()); 2764 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 2765 &CopyCtorArg, 1); 2766 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, 2767 MultiExprArg(&CopyCtorArg, 1)); 2768 break; 2769 } 2770 } 2771 2772 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 2773 if (BaseInit.isInvalid()) 2774 return true; 2775 2776 CXXBaseInit = 2777 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 2778 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 2779 SourceLocation()), 2780 BaseSpec->isVirtual(), 2781 SourceLocation(), 2782 BaseInit.takeAs<Expr>(), 2783 SourceLocation(), 2784 SourceLocation()); 2785 2786 return false; 2787} 2788 2789static bool RefersToRValueRef(Expr *MemRef) { 2790 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 2791 return Referenced->getType()->isRValueReferenceType(); 2792} 2793 2794static bool 2795BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 2796 ImplicitInitializerKind ImplicitInitKind, 2797 FieldDecl *Field, IndirectFieldDecl *Indirect, 2798 CXXCtorInitializer *&CXXMemberInit) { 2799 if (Field->isInvalidDecl()) 2800 return true; 2801 2802 SourceLocation Loc = Constructor->getLocation(); 2803 2804 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 2805 bool Moving = ImplicitInitKind == IIK_Move; 2806 ParmVarDecl *Param = Constructor->getParamDecl(0); 2807 QualType ParamType = Param->getType().getNonReferenceType(); 2808 2809 // Suppress copying zero-width bitfields. 2810 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0) 2811 return false; 2812 2813 Expr *MemberExprBase = 2814 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 2815 SourceLocation(), Param, false, 2816 Loc, ParamType, VK_LValue, 0); 2817 2818 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 2819 2820 if (Moving) { 2821 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 2822 } 2823 2824 // Build a reference to this field within the parameter. 2825 CXXScopeSpec SS; 2826 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 2827 Sema::LookupMemberName); 2828 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 2829 : cast<ValueDecl>(Field), AS_public); 2830 MemberLookup.resolveKind(); 2831 ExprResult CtorArg 2832 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 2833 ParamType, Loc, 2834 /*IsArrow=*/false, 2835 SS, 2836 /*TemplateKWLoc=*/SourceLocation(), 2837 /*FirstQualifierInScope=*/0, 2838 MemberLookup, 2839 /*TemplateArgs=*/0); 2840 if (CtorArg.isInvalid()) 2841 return true; 2842 2843 // C++11 [class.copy]p15: 2844 // - if a member m has rvalue reference type T&&, it is direct-initialized 2845 // with static_cast<T&&>(x.m); 2846 if (RefersToRValueRef(CtorArg.get())) { 2847 CtorArg = CastForMoving(SemaRef, CtorArg.take()); 2848 } 2849 2850 // When the field we are copying is an array, create index variables for 2851 // each dimension of the array. We use these index variables to subscript 2852 // the source array, and other clients (e.g., CodeGen) will perform the 2853 // necessary iteration with these index variables. 2854 SmallVector<VarDecl *, 4> IndexVariables; 2855 QualType BaseType = Field->getType(); 2856 QualType SizeType = SemaRef.Context.getSizeType(); 2857 bool InitializingArray = false; 2858 while (const ConstantArrayType *Array 2859 = SemaRef.Context.getAsConstantArrayType(BaseType)) { 2860 InitializingArray = true; 2861 // Create the iteration variable for this array index. 2862 IdentifierInfo *IterationVarName = 0; 2863 { 2864 SmallString<8> Str; 2865 llvm::raw_svector_ostream OS(Str); 2866 OS << "__i" << IndexVariables.size(); 2867 IterationVarName = &SemaRef.Context.Idents.get(OS.str()); 2868 } 2869 VarDecl *IterationVar 2870 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc, 2871 IterationVarName, SizeType, 2872 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc), 2873 SC_None); 2874 IndexVariables.push_back(IterationVar); 2875 2876 // Create a reference to the iteration variable. 2877 ExprResult IterationVarRef 2878 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 2879 assert(!IterationVarRef.isInvalid() && 2880 "Reference to invented variable cannot fail!"); 2881 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take()); 2882 assert(!IterationVarRef.isInvalid() && 2883 "Conversion of invented variable cannot fail!"); 2884 2885 // Subscript the array with this iteration variable. 2886 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc, 2887 IterationVarRef.take(), 2888 Loc); 2889 if (CtorArg.isInvalid()) 2890 return true; 2891 2892 BaseType = Array->getElementType(); 2893 } 2894 2895 // The array subscript expression is an lvalue, which is wrong for moving. 2896 if (Moving && InitializingArray) 2897 CtorArg = CastForMoving(SemaRef, CtorArg.take()); 2898 2899 // Construct the entity that we will be initializing. For an array, this 2900 // will be first element in the array, which may require several levels 2901 // of array-subscript entities. 2902 SmallVector<InitializedEntity, 4> Entities; 2903 Entities.reserve(1 + IndexVariables.size()); 2904 if (Indirect) 2905 Entities.push_back(InitializedEntity::InitializeMember(Indirect)); 2906 else 2907 Entities.push_back(InitializedEntity::InitializeMember(Field)); 2908 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 2909 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context, 2910 0, 2911 Entities.back())); 2912 2913 // Direct-initialize to use the copy constructor. 2914 InitializationKind InitKind = 2915 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 2916 2917 Expr *CtorArgE = CtorArg.takeAs<Expr>(); 2918 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, 2919 &CtorArgE, 1); 2920 2921 ExprResult MemberInit 2922 = InitSeq.Perform(SemaRef, Entities.back(), InitKind, 2923 MultiExprArg(&CtorArgE, 1)); 2924 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 2925 if (MemberInit.isInvalid()) 2926 return true; 2927 2928 if (Indirect) { 2929 assert(IndexVariables.size() == 0 && 2930 "Indirect field improperly initialized"); 2931 CXXMemberInit 2932 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 2933 Loc, Loc, 2934 MemberInit.takeAs<Expr>(), 2935 Loc); 2936 } else 2937 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, 2938 Loc, MemberInit.takeAs<Expr>(), 2939 Loc, 2940 IndexVariables.data(), 2941 IndexVariables.size()); 2942 return false; 2943 } 2944 2945 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 2946 "Unhandled implicit init kind!"); 2947 2948 QualType FieldBaseElementType = 2949 SemaRef.Context.getBaseElementType(Field->getType()); 2950 2951 if (FieldBaseElementType->isRecordType()) { 2952 InitializedEntity InitEntity 2953 = Indirect? InitializedEntity::InitializeMember(Indirect) 2954 : InitializedEntity::InitializeMember(Field); 2955 InitializationKind InitKind = 2956 InitializationKind::CreateDefault(Loc); 2957 2958 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0); 2959 ExprResult MemberInit = 2960 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg()); 2961 2962 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 2963 if (MemberInit.isInvalid()) 2964 return true; 2965 2966 if (Indirect) 2967 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 2968 Indirect, Loc, 2969 Loc, 2970 MemberInit.get(), 2971 Loc); 2972 else 2973 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 2974 Field, Loc, Loc, 2975 MemberInit.get(), 2976 Loc); 2977 return false; 2978 } 2979 2980 if (!Field->getParent()->isUnion()) { 2981 if (FieldBaseElementType->isReferenceType()) { 2982 SemaRef.Diag(Constructor->getLocation(), 2983 diag::err_uninitialized_member_in_ctor) 2984 << (int)Constructor->isImplicit() 2985 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 2986 << 0 << Field->getDeclName(); 2987 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 2988 return true; 2989 } 2990 2991 if (FieldBaseElementType.isConstQualified()) { 2992 SemaRef.Diag(Constructor->getLocation(), 2993 diag::err_uninitialized_member_in_ctor) 2994 << (int)Constructor->isImplicit() 2995 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 2996 << 1 << Field->getDeclName(); 2997 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 2998 return true; 2999 } 3000 } 3001 3002 if (SemaRef.getLangOpts().ObjCAutoRefCount && 3003 FieldBaseElementType->isObjCRetainableType() && 3004 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None && 3005 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) { 3006 // ARC: 3007 // Default-initialize Objective-C pointers to NULL. 3008 CXXMemberInit 3009 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 3010 Loc, Loc, 3011 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 3012 Loc); 3013 return false; 3014 } 3015 3016 // Nothing to initialize. 3017 CXXMemberInit = 0; 3018 return false; 3019} 3020 3021namespace { 3022struct BaseAndFieldInfo { 3023 Sema &S; 3024 CXXConstructorDecl *Ctor; 3025 bool AnyErrorsInInits; 3026 ImplicitInitializerKind IIK; 3027 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 3028 SmallVector<CXXCtorInitializer*, 8> AllToInit; 3029 3030 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 3031 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 3032 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 3033 if (Generated && Ctor->isCopyConstructor()) 3034 IIK = IIK_Copy; 3035 else if (Generated && Ctor->isMoveConstructor()) 3036 IIK = IIK_Move; 3037 else if (Ctor->getInheritedConstructor()) 3038 IIK = IIK_Inherit; 3039 else 3040 IIK = IIK_Default; 3041 } 3042 3043 bool isImplicitCopyOrMove() const { 3044 switch (IIK) { 3045 case IIK_Copy: 3046 case IIK_Move: 3047 return true; 3048 3049 case IIK_Default: 3050 case IIK_Inherit: 3051 return false; 3052 } 3053 3054 llvm_unreachable("Invalid ImplicitInitializerKind!"); 3055 } 3056 3057 bool addFieldInitializer(CXXCtorInitializer *Init) { 3058 AllToInit.push_back(Init); 3059 3060 // Check whether this initializer makes the field "used". 3061 if (Init->getInit() && Init->getInit()->HasSideEffects(S.Context)) 3062 S.UnusedPrivateFields.remove(Init->getAnyMember()); 3063 3064 return false; 3065 } 3066}; 3067} 3068 3069/// \brief Determine whether the given indirect field declaration is somewhere 3070/// within an anonymous union. 3071static bool isWithinAnonymousUnion(IndirectFieldDecl *F) { 3072 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(), 3073 CEnd = F->chain_end(); 3074 C != CEnd; ++C) 3075 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext())) 3076 if (Record->isUnion()) 3077 return true; 3078 3079 return false; 3080} 3081 3082/// \brief Determine whether the given type is an incomplete or zero-lenfgth 3083/// array type. 3084static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 3085 if (T->isIncompleteArrayType()) 3086 return true; 3087 3088 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 3089 if (!ArrayT->getSize()) 3090 return true; 3091 3092 T = ArrayT->getElementType(); 3093 } 3094 3095 return false; 3096} 3097 3098static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 3099 FieldDecl *Field, 3100 IndirectFieldDecl *Indirect = 0) { 3101 3102 // Overwhelmingly common case: we have a direct initializer for this field. 3103 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) 3104 return Info.addFieldInitializer(Init); 3105 3106 // C++11 [class.base.init]p8: if the entity is a non-static data member that 3107 // has a brace-or-equal-initializer, the entity is initialized as specified 3108 // in [dcl.init]. 3109 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 3110 CXXCtorInitializer *Init; 3111 if (Indirect) 3112 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 3113 SourceLocation(), 3114 SourceLocation(), 0, 3115 SourceLocation()); 3116 else 3117 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 3118 SourceLocation(), 3119 SourceLocation(), 0, 3120 SourceLocation()); 3121 return Info.addFieldInitializer(Init); 3122 } 3123 3124 // Don't build an implicit initializer for union members if none was 3125 // explicitly specified. 3126 if (Field->getParent()->isUnion() || 3127 (Indirect && isWithinAnonymousUnion(Indirect))) 3128 return false; 3129 3130 // Don't initialize incomplete or zero-length arrays. 3131 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 3132 return false; 3133 3134 // Don't try to build an implicit initializer if there were semantic 3135 // errors in any of the initializers (and therefore we might be 3136 // missing some that the user actually wrote). 3137 if (Info.AnyErrorsInInits || Field->isInvalidDecl()) 3138 return false; 3139 3140 CXXCtorInitializer *Init = 0; 3141 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 3142 Indirect, Init)) 3143 return true; 3144 3145 if (!Init) 3146 return false; 3147 3148 return Info.addFieldInitializer(Init); 3149} 3150 3151bool 3152Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 3153 CXXCtorInitializer *Initializer) { 3154 assert(Initializer->isDelegatingInitializer()); 3155 Constructor->setNumCtorInitializers(1); 3156 CXXCtorInitializer **initializer = 3157 new (Context) CXXCtorInitializer*[1]; 3158 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 3159 Constructor->setCtorInitializers(initializer); 3160 3161 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 3162 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 3163 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 3164 } 3165 3166 DelegatingCtorDecls.push_back(Constructor); 3167 3168 return false; 3169} 3170 3171bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 3172 ArrayRef<CXXCtorInitializer *> Initializers) { 3173 if (Constructor->isDependentContext()) { 3174 // Just store the initializers as written, they will be checked during 3175 // instantiation. 3176 if (!Initializers.empty()) { 3177 Constructor->setNumCtorInitializers(Initializers.size()); 3178 CXXCtorInitializer **baseOrMemberInitializers = 3179 new (Context) CXXCtorInitializer*[Initializers.size()]; 3180 memcpy(baseOrMemberInitializers, Initializers.data(), 3181 Initializers.size() * sizeof(CXXCtorInitializer*)); 3182 Constructor->setCtorInitializers(baseOrMemberInitializers); 3183 } 3184 3185 // Let template instantiation know whether we had errors. 3186 if (AnyErrors) 3187 Constructor->setInvalidDecl(); 3188 3189 return false; 3190 } 3191 3192 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 3193 3194 // We need to build the initializer AST according to order of construction 3195 // and not what user specified in the Initializers list. 3196 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 3197 if (!ClassDecl) 3198 return true; 3199 3200 bool HadError = false; 3201 3202 for (unsigned i = 0; i < Initializers.size(); i++) { 3203 CXXCtorInitializer *Member = Initializers[i]; 3204 3205 if (Member->isBaseInitializer()) 3206 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 3207 else 3208 Info.AllBaseFields[Member->getAnyMember()] = Member; 3209 } 3210 3211 // Keep track of the direct virtual bases. 3212 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 3213 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(), 3214 E = ClassDecl->bases_end(); I != E; ++I) { 3215 if (I->isVirtual()) 3216 DirectVBases.insert(I); 3217 } 3218 3219 // Push virtual bases before others. 3220 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 3221 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 3222 3223 if (CXXCtorInitializer *Value 3224 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) { 3225 Info.AllToInit.push_back(Value); 3226 } else if (!AnyErrors) { 3227 bool IsInheritedVirtualBase = !DirectVBases.count(VBase); 3228 CXXCtorInitializer *CXXBaseInit; 3229 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3230 VBase, IsInheritedVirtualBase, 3231 CXXBaseInit)) { 3232 HadError = true; 3233 continue; 3234 } 3235 3236 Info.AllToInit.push_back(CXXBaseInit); 3237 } 3238 } 3239 3240 // Non-virtual bases. 3241 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 3242 E = ClassDecl->bases_end(); Base != E; ++Base) { 3243 // Virtuals are in the virtual base list and already constructed. 3244 if (Base->isVirtual()) 3245 continue; 3246 3247 if (CXXCtorInitializer *Value 3248 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) { 3249 Info.AllToInit.push_back(Value); 3250 } else if (!AnyErrors) { 3251 CXXCtorInitializer *CXXBaseInit; 3252 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3253 Base, /*IsInheritedVirtualBase=*/false, 3254 CXXBaseInit)) { 3255 HadError = true; 3256 continue; 3257 } 3258 3259 Info.AllToInit.push_back(CXXBaseInit); 3260 } 3261 } 3262 3263 // Fields. 3264 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(), 3265 MemEnd = ClassDecl->decls_end(); 3266 Mem != MemEnd; ++Mem) { 3267 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) { 3268 // C++ [class.bit]p2: 3269 // A declaration for a bit-field that omits the identifier declares an 3270 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 3271 // initialized. 3272 if (F->isUnnamedBitfield()) 3273 continue; 3274 3275 // If we're not generating the implicit copy/move constructor, then we'll 3276 // handle anonymous struct/union fields based on their individual 3277 // indirect fields. 3278 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 3279 continue; 3280 3281 if (CollectFieldInitializer(*this, Info, F)) 3282 HadError = true; 3283 continue; 3284 } 3285 3286 // Beyond this point, we only consider default initialization. 3287 if (Info.isImplicitCopyOrMove()) 3288 continue; 3289 3290 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) { 3291 if (F->getType()->isIncompleteArrayType()) { 3292 assert(ClassDecl->hasFlexibleArrayMember() && 3293 "Incomplete array type is not valid"); 3294 continue; 3295 } 3296 3297 // Initialize each field of an anonymous struct individually. 3298 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 3299 HadError = true; 3300 3301 continue; 3302 } 3303 } 3304 3305 unsigned NumInitializers = Info.AllToInit.size(); 3306 if (NumInitializers > 0) { 3307 Constructor->setNumCtorInitializers(NumInitializers); 3308 CXXCtorInitializer **baseOrMemberInitializers = 3309 new (Context) CXXCtorInitializer*[NumInitializers]; 3310 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 3311 NumInitializers * sizeof(CXXCtorInitializer*)); 3312 Constructor->setCtorInitializers(baseOrMemberInitializers); 3313 3314 // Constructors implicitly reference the base and member 3315 // destructors. 3316 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 3317 Constructor->getParent()); 3318 } 3319 3320 return HadError; 3321} 3322 3323static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 3324 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 3325 const RecordDecl *RD = RT->getDecl(); 3326 if (RD->isAnonymousStructOrUnion()) { 3327 for (RecordDecl::field_iterator Field = RD->field_begin(), 3328 E = RD->field_end(); Field != E; ++Field) 3329 PopulateKeysForFields(*Field, IdealInits); 3330 return; 3331 } 3332 } 3333 IdealInits.push_back(Field); 3334} 3335 3336static void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 3337 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr()); 3338} 3339 3340static void *GetKeyForMember(ASTContext &Context, 3341 CXXCtorInitializer *Member) { 3342 if (!Member->isAnyMemberInitializer()) 3343 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 3344 3345 return Member->getAnyMember(); 3346} 3347 3348static void DiagnoseBaseOrMemInitializerOrder( 3349 Sema &SemaRef, const CXXConstructorDecl *Constructor, 3350 ArrayRef<CXXCtorInitializer *> Inits) { 3351 if (Constructor->getDeclContext()->isDependentContext()) 3352 return; 3353 3354 // Don't check initializers order unless the warning is enabled at the 3355 // location of at least one initializer. 3356 bool ShouldCheckOrder = false; 3357 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 3358 CXXCtorInitializer *Init = Inits[InitIndex]; 3359 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order, 3360 Init->getSourceLocation()) 3361 != DiagnosticsEngine::Ignored) { 3362 ShouldCheckOrder = true; 3363 break; 3364 } 3365 } 3366 if (!ShouldCheckOrder) 3367 return; 3368 3369 // Build the list of bases and members in the order that they'll 3370 // actually be initialized. The explicit initializers should be in 3371 // this same order but may be missing things. 3372 SmallVector<const void*, 32> IdealInitKeys; 3373 3374 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 3375 3376 // 1. Virtual bases. 3377 for (CXXRecordDecl::base_class_const_iterator VBase = 3378 ClassDecl->vbases_begin(), 3379 E = ClassDecl->vbases_end(); VBase != E; ++VBase) 3380 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType())); 3381 3382 // 2. Non-virtual bases. 3383 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(), 3384 E = ClassDecl->bases_end(); Base != E; ++Base) { 3385 if (Base->isVirtual()) 3386 continue; 3387 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType())); 3388 } 3389 3390 // 3. Direct fields. 3391 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 3392 E = ClassDecl->field_end(); Field != E; ++Field) { 3393 if (Field->isUnnamedBitfield()) 3394 continue; 3395 3396 PopulateKeysForFields(*Field, IdealInitKeys); 3397 } 3398 3399 unsigned NumIdealInits = IdealInitKeys.size(); 3400 unsigned IdealIndex = 0; 3401 3402 CXXCtorInitializer *PrevInit = 0; 3403 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 3404 CXXCtorInitializer *Init = Inits[InitIndex]; 3405 void *InitKey = GetKeyForMember(SemaRef.Context, Init); 3406 3407 // Scan forward to try to find this initializer in the idealized 3408 // initializers list. 3409 for (; IdealIndex != NumIdealInits; ++IdealIndex) 3410 if (InitKey == IdealInitKeys[IdealIndex]) 3411 break; 3412 3413 // If we didn't find this initializer, it must be because we 3414 // scanned past it on a previous iteration. That can only 3415 // happen if we're out of order; emit a warning. 3416 if (IdealIndex == NumIdealInits && PrevInit) { 3417 Sema::SemaDiagnosticBuilder D = 3418 SemaRef.Diag(PrevInit->getSourceLocation(), 3419 diag::warn_initializer_out_of_order); 3420 3421 if (PrevInit->isAnyMemberInitializer()) 3422 D << 0 << PrevInit->getAnyMember()->getDeclName(); 3423 else 3424 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 3425 3426 if (Init->isAnyMemberInitializer()) 3427 D << 0 << Init->getAnyMember()->getDeclName(); 3428 else 3429 D << 1 << Init->getTypeSourceInfo()->getType(); 3430 3431 // Move back to the initializer's location in the ideal list. 3432 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 3433 if (InitKey == IdealInitKeys[IdealIndex]) 3434 break; 3435 3436 assert(IdealIndex != NumIdealInits && 3437 "initializer not found in initializer list"); 3438 } 3439 3440 PrevInit = Init; 3441 } 3442} 3443 3444namespace { 3445bool CheckRedundantInit(Sema &S, 3446 CXXCtorInitializer *Init, 3447 CXXCtorInitializer *&PrevInit) { 3448 if (!PrevInit) { 3449 PrevInit = Init; 3450 return false; 3451 } 3452 3453 if (FieldDecl *Field = Init->getAnyMember()) 3454 S.Diag(Init->getSourceLocation(), 3455 diag::err_multiple_mem_initialization) 3456 << Field->getDeclName() 3457 << Init->getSourceRange(); 3458 else { 3459 const Type *BaseClass = Init->getBaseClass(); 3460 assert(BaseClass && "neither field nor base"); 3461 S.Diag(Init->getSourceLocation(), 3462 diag::err_multiple_base_initialization) 3463 << QualType(BaseClass, 0) 3464 << Init->getSourceRange(); 3465 } 3466 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 3467 << 0 << PrevInit->getSourceRange(); 3468 3469 return true; 3470} 3471 3472typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 3473typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 3474 3475bool CheckRedundantUnionInit(Sema &S, 3476 CXXCtorInitializer *Init, 3477 RedundantUnionMap &Unions) { 3478 FieldDecl *Field = Init->getAnyMember(); 3479 RecordDecl *Parent = Field->getParent(); 3480 NamedDecl *Child = Field; 3481 3482 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 3483 if (Parent->isUnion()) { 3484 UnionEntry &En = Unions[Parent]; 3485 if (En.first && En.first != Child) { 3486 S.Diag(Init->getSourceLocation(), 3487 diag::err_multiple_mem_union_initialization) 3488 << Field->getDeclName() 3489 << Init->getSourceRange(); 3490 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 3491 << 0 << En.second->getSourceRange(); 3492 return true; 3493 } 3494 if (!En.first) { 3495 En.first = Child; 3496 En.second = Init; 3497 } 3498 if (!Parent->isAnonymousStructOrUnion()) 3499 return false; 3500 } 3501 3502 Child = Parent; 3503 Parent = cast<RecordDecl>(Parent->getDeclContext()); 3504 } 3505 3506 return false; 3507} 3508} 3509 3510/// ActOnMemInitializers - Handle the member initializers for a constructor. 3511void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 3512 SourceLocation ColonLoc, 3513 ArrayRef<CXXCtorInitializer*> MemInits, 3514 bool AnyErrors) { 3515 if (!ConstructorDecl) 3516 return; 3517 3518 AdjustDeclIfTemplate(ConstructorDecl); 3519 3520 CXXConstructorDecl *Constructor 3521 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 3522 3523 if (!Constructor) { 3524 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 3525 return; 3526 } 3527 3528 // Mapping for the duplicate initializers check. 3529 // For member initializers, this is keyed with a FieldDecl*. 3530 // For base initializers, this is keyed with a Type*. 3531 llvm::DenseMap<void*, CXXCtorInitializer *> Members; 3532 3533 // Mapping for the inconsistent anonymous-union initializers check. 3534 RedundantUnionMap MemberUnions; 3535 3536 bool HadError = false; 3537 for (unsigned i = 0; i < MemInits.size(); i++) { 3538 CXXCtorInitializer *Init = MemInits[i]; 3539 3540 // Set the source order index. 3541 Init->setSourceOrder(i); 3542 3543 if (Init->isAnyMemberInitializer()) { 3544 FieldDecl *Field = Init->getAnyMember(); 3545 if (CheckRedundantInit(*this, Init, Members[Field]) || 3546 CheckRedundantUnionInit(*this, Init, MemberUnions)) 3547 HadError = true; 3548 } else if (Init->isBaseInitializer()) { 3549 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0)); 3550 if (CheckRedundantInit(*this, Init, Members[Key])) 3551 HadError = true; 3552 } else { 3553 assert(Init->isDelegatingInitializer()); 3554 // This must be the only initializer 3555 if (MemInits.size() != 1) { 3556 Diag(Init->getSourceLocation(), 3557 diag::err_delegating_initializer_alone) 3558 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 3559 // We will treat this as being the only initializer. 3560 } 3561 SetDelegatingInitializer(Constructor, MemInits[i]); 3562 // Return immediately as the initializer is set. 3563 return; 3564 } 3565 } 3566 3567 if (HadError) 3568 return; 3569 3570 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 3571 3572 SetCtorInitializers(Constructor, AnyErrors, MemInits); 3573} 3574 3575void 3576Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 3577 CXXRecordDecl *ClassDecl) { 3578 // Ignore dependent contexts. Also ignore unions, since their members never 3579 // have destructors implicitly called. 3580 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 3581 return; 3582 3583 // FIXME: all the access-control diagnostics are positioned on the 3584 // field/base declaration. That's probably good; that said, the 3585 // user might reasonably want to know why the destructor is being 3586 // emitted, and we currently don't say. 3587 3588 // Non-static data members. 3589 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(), 3590 E = ClassDecl->field_end(); I != E; ++I) { 3591 FieldDecl *Field = *I; 3592 if (Field->isInvalidDecl()) 3593 continue; 3594 3595 // Don't destroy incomplete or zero-length arrays. 3596 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 3597 continue; 3598 3599 QualType FieldType = Context.getBaseElementType(Field->getType()); 3600 3601 const RecordType* RT = FieldType->getAs<RecordType>(); 3602 if (!RT) 3603 continue; 3604 3605 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3606 if (FieldClassDecl->isInvalidDecl()) 3607 continue; 3608 if (FieldClassDecl->hasIrrelevantDestructor()) 3609 continue; 3610 // The destructor for an implicit anonymous union member is never invoked. 3611 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 3612 continue; 3613 3614 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 3615 assert(Dtor && "No dtor found for FieldClassDecl!"); 3616 CheckDestructorAccess(Field->getLocation(), Dtor, 3617 PDiag(diag::err_access_dtor_field) 3618 << Field->getDeclName() 3619 << FieldType); 3620 3621 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 3622 DiagnoseUseOfDecl(Dtor, Location); 3623 } 3624 3625 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 3626 3627 // Bases. 3628 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 3629 E = ClassDecl->bases_end(); Base != E; ++Base) { 3630 // Bases are always records in a well-formed non-dependent class. 3631 const RecordType *RT = Base->getType()->getAs<RecordType>(); 3632 3633 // Remember direct virtual bases. 3634 if (Base->isVirtual()) 3635 DirectVirtualBases.insert(RT); 3636 3637 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3638 // If our base class is invalid, we probably can't get its dtor anyway. 3639 if (BaseClassDecl->isInvalidDecl()) 3640 continue; 3641 if (BaseClassDecl->hasIrrelevantDestructor()) 3642 continue; 3643 3644 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 3645 assert(Dtor && "No dtor found for BaseClassDecl!"); 3646 3647 // FIXME: caret should be on the start of the class name 3648 CheckDestructorAccess(Base->getLocStart(), Dtor, 3649 PDiag(diag::err_access_dtor_base) 3650 << Base->getType() 3651 << Base->getSourceRange(), 3652 Context.getTypeDeclType(ClassDecl)); 3653 3654 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 3655 DiagnoseUseOfDecl(Dtor, Location); 3656 } 3657 3658 // Virtual bases. 3659 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 3660 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 3661 3662 // Bases are always records in a well-formed non-dependent class. 3663 const RecordType *RT = VBase->getType()->castAs<RecordType>(); 3664 3665 // Ignore direct virtual bases. 3666 if (DirectVirtualBases.count(RT)) 3667 continue; 3668 3669 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3670 // If our base class is invalid, we probably can't get its dtor anyway. 3671 if (BaseClassDecl->isInvalidDecl()) 3672 continue; 3673 if (BaseClassDecl->hasIrrelevantDestructor()) 3674 continue; 3675 3676 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 3677 assert(Dtor && "No dtor found for BaseClassDecl!"); 3678 CheckDestructorAccess(ClassDecl->getLocation(), Dtor, 3679 PDiag(diag::err_access_dtor_vbase) 3680 << VBase->getType(), 3681 Context.getTypeDeclType(ClassDecl)); 3682 3683 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 3684 DiagnoseUseOfDecl(Dtor, Location); 3685 } 3686} 3687 3688void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 3689 if (!CDtorDecl) 3690 return; 3691 3692 if (CXXConstructorDecl *Constructor 3693 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) 3694 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 3695} 3696 3697bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 3698 unsigned DiagID, AbstractDiagSelID SelID) { 3699 class NonAbstractTypeDiagnoser : public TypeDiagnoser { 3700 unsigned DiagID; 3701 AbstractDiagSelID SelID; 3702 3703 public: 3704 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID) 3705 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { } 3706 3707 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 3708 if (Suppressed) return; 3709 if (SelID == -1) 3710 S.Diag(Loc, DiagID) << T; 3711 else 3712 S.Diag(Loc, DiagID) << SelID << T; 3713 } 3714 } Diagnoser(DiagID, SelID); 3715 3716 return RequireNonAbstractType(Loc, T, Diagnoser); 3717} 3718 3719bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 3720 TypeDiagnoser &Diagnoser) { 3721 if (!getLangOpts().CPlusPlus) 3722 return false; 3723 3724 if (const ArrayType *AT = Context.getAsArrayType(T)) 3725 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 3726 3727 if (const PointerType *PT = T->getAs<PointerType>()) { 3728 // Find the innermost pointer type. 3729 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 3730 PT = T; 3731 3732 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 3733 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 3734 } 3735 3736 const RecordType *RT = T->getAs<RecordType>(); 3737 if (!RT) 3738 return false; 3739 3740 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 3741 3742 // We can't answer whether something is abstract until it has a 3743 // definition. If it's currently being defined, we'll walk back 3744 // over all the declarations when we have a full definition. 3745 const CXXRecordDecl *Def = RD->getDefinition(); 3746 if (!Def || Def->isBeingDefined()) 3747 return false; 3748 3749 if (!RD->isAbstract()) 3750 return false; 3751 3752 Diagnoser.diagnose(*this, Loc, T); 3753 DiagnoseAbstractType(RD); 3754 3755 return true; 3756} 3757 3758void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 3759 // Check if we've already emitted the list of pure virtual functions 3760 // for this class. 3761 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 3762 return; 3763 3764 CXXFinalOverriderMap FinalOverriders; 3765 RD->getFinalOverriders(FinalOverriders); 3766 3767 // Keep a set of seen pure methods so we won't diagnose the same method 3768 // more than once. 3769 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 3770 3771 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 3772 MEnd = FinalOverriders.end(); 3773 M != MEnd; 3774 ++M) { 3775 for (OverridingMethods::iterator SO = M->second.begin(), 3776 SOEnd = M->second.end(); 3777 SO != SOEnd; ++SO) { 3778 // C++ [class.abstract]p4: 3779 // A class is abstract if it contains or inherits at least one 3780 // pure virtual function for which the final overrider is pure 3781 // virtual. 3782 3783 // 3784 if (SO->second.size() != 1) 3785 continue; 3786 3787 if (!SO->second.front().Method->isPure()) 3788 continue; 3789 3790 if (!SeenPureMethods.insert(SO->second.front().Method)) 3791 continue; 3792 3793 Diag(SO->second.front().Method->getLocation(), 3794 diag::note_pure_virtual_function) 3795 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 3796 } 3797 } 3798 3799 if (!PureVirtualClassDiagSet) 3800 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 3801 PureVirtualClassDiagSet->insert(RD); 3802} 3803 3804namespace { 3805struct AbstractUsageInfo { 3806 Sema &S; 3807 CXXRecordDecl *Record; 3808 CanQualType AbstractType; 3809 bool Invalid; 3810 3811 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 3812 : S(S), Record(Record), 3813 AbstractType(S.Context.getCanonicalType( 3814 S.Context.getTypeDeclType(Record))), 3815 Invalid(false) {} 3816 3817 void DiagnoseAbstractType() { 3818 if (Invalid) return; 3819 S.DiagnoseAbstractType(Record); 3820 Invalid = true; 3821 } 3822 3823 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 3824}; 3825 3826struct CheckAbstractUsage { 3827 AbstractUsageInfo &Info; 3828 const NamedDecl *Ctx; 3829 3830 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 3831 : Info(Info), Ctx(Ctx) {} 3832 3833 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 3834 switch (TL.getTypeLocClass()) { 3835#define ABSTRACT_TYPELOC(CLASS, PARENT) 3836#define TYPELOC(CLASS, PARENT) \ 3837 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 3838#include "clang/AST/TypeLocNodes.def" 3839 } 3840 } 3841 3842 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 3843 Visit(TL.getResultLoc(), Sema::AbstractReturnType); 3844 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 3845 if (!TL.getArg(I)) 3846 continue; 3847 3848 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo(); 3849 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 3850 } 3851 } 3852 3853 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 3854 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 3855 } 3856 3857 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 3858 // Visit the type parameters from a permissive context. 3859 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 3860 TemplateArgumentLoc TAL = TL.getArgLoc(I); 3861 if (TAL.getArgument().getKind() == TemplateArgument::Type) 3862 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 3863 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 3864 // TODO: other template argument types? 3865 } 3866 } 3867 3868 // Visit pointee types from a permissive context. 3869#define CheckPolymorphic(Type) \ 3870 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 3871 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 3872 } 3873 CheckPolymorphic(PointerTypeLoc) 3874 CheckPolymorphic(ReferenceTypeLoc) 3875 CheckPolymorphic(MemberPointerTypeLoc) 3876 CheckPolymorphic(BlockPointerTypeLoc) 3877 CheckPolymorphic(AtomicTypeLoc) 3878 3879 /// Handle all the types we haven't given a more specific 3880 /// implementation for above. 3881 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 3882 // Every other kind of type that we haven't called out already 3883 // that has an inner type is either (1) sugar or (2) contains that 3884 // inner type in some way as a subobject. 3885 if (TypeLoc Next = TL.getNextTypeLoc()) 3886 return Visit(Next, Sel); 3887 3888 // If there's no inner type and we're in a permissive context, 3889 // don't diagnose. 3890 if (Sel == Sema::AbstractNone) return; 3891 3892 // Check whether the type matches the abstract type. 3893 QualType T = TL.getType(); 3894 if (T->isArrayType()) { 3895 Sel = Sema::AbstractArrayType; 3896 T = Info.S.Context.getBaseElementType(T); 3897 } 3898 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 3899 if (CT != Info.AbstractType) return; 3900 3901 // It matched; do some magic. 3902 if (Sel == Sema::AbstractArrayType) { 3903 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 3904 << T << TL.getSourceRange(); 3905 } else { 3906 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 3907 << Sel << T << TL.getSourceRange(); 3908 } 3909 Info.DiagnoseAbstractType(); 3910 } 3911}; 3912 3913void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 3914 Sema::AbstractDiagSelID Sel) { 3915 CheckAbstractUsage(*this, D).Visit(TL, Sel); 3916} 3917 3918} 3919 3920/// Check for invalid uses of an abstract type in a method declaration. 3921static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 3922 CXXMethodDecl *MD) { 3923 // No need to do the check on definitions, which require that 3924 // the return/param types be complete. 3925 if (MD->doesThisDeclarationHaveABody()) 3926 return; 3927 3928 // For safety's sake, just ignore it if we don't have type source 3929 // information. This should never happen for non-implicit methods, 3930 // but... 3931 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 3932 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 3933} 3934 3935/// Check for invalid uses of an abstract type within a class definition. 3936static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 3937 CXXRecordDecl *RD) { 3938 for (CXXRecordDecl::decl_iterator 3939 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) { 3940 Decl *D = *I; 3941 if (D->isImplicit()) continue; 3942 3943 // Methods and method templates. 3944 if (isa<CXXMethodDecl>(D)) { 3945 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 3946 } else if (isa<FunctionTemplateDecl>(D)) { 3947 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 3948 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 3949 3950 // Fields and static variables. 3951 } else if (isa<FieldDecl>(D)) { 3952 FieldDecl *FD = cast<FieldDecl>(D); 3953 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 3954 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 3955 } else if (isa<VarDecl>(D)) { 3956 VarDecl *VD = cast<VarDecl>(D); 3957 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 3958 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 3959 3960 // Nested classes and class templates. 3961 } else if (isa<CXXRecordDecl>(D)) { 3962 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 3963 } else if (isa<ClassTemplateDecl>(D)) { 3964 CheckAbstractClassUsage(Info, 3965 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 3966 } 3967 } 3968} 3969 3970/// \brief Perform semantic checks on a class definition that has been 3971/// completing, introducing implicitly-declared members, checking for 3972/// abstract types, etc. 3973void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 3974 if (!Record) 3975 return; 3976 3977 if (Record->isAbstract() && !Record->isInvalidDecl()) { 3978 AbstractUsageInfo Info(*this, Record); 3979 CheckAbstractClassUsage(Info, Record); 3980 } 3981 3982 // If this is not an aggregate type and has no user-declared constructor, 3983 // complain about any non-static data members of reference or const scalar 3984 // type, since they will never get initializers. 3985 if (!Record->isInvalidDecl() && !Record->isDependentType() && 3986 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 3987 !Record->isLambda()) { 3988 bool Complained = false; 3989 for (RecordDecl::field_iterator F = Record->field_begin(), 3990 FEnd = Record->field_end(); 3991 F != FEnd; ++F) { 3992 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 3993 continue; 3994 3995 if (F->getType()->isReferenceType() || 3996 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 3997 if (!Complained) { 3998 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 3999 << Record->getTagKind() << Record; 4000 Complained = true; 4001 } 4002 4003 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 4004 << F->getType()->isReferenceType() 4005 << F->getDeclName(); 4006 } 4007 } 4008 } 4009 4010 if (Record->isDynamicClass() && !Record->isDependentType()) 4011 DynamicClasses.push_back(Record); 4012 4013 if (Record->getIdentifier()) { 4014 // C++ [class.mem]p13: 4015 // If T is the name of a class, then each of the following shall have a 4016 // name different from T: 4017 // - every member of every anonymous union that is a member of class T. 4018 // 4019 // C++ [class.mem]p14: 4020 // In addition, if class T has a user-declared constructor (12.1), every 4021 // non-static data member of class T shall have a name different from T. 4022 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 4023 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 4024 ++I) { 4025 NamedDecl *D = *I; 4026 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 4027 isa<IndirectFieldDecl>(D)) { 4028 Diag(D->getLocation(), diag::err_member_name_of_class) 4029 << D->getDeclName(); 4030 break; 4031 } 4032 } 4033 } 4034 4035 // Warn if the class has virtual methods but non-virtual public destructor. 4036 if (Record->isPolymorphic() && !Record->isDependentType()) { 4037 CXXDestructorDecl *dtor = Record->getDestructor(); 4038 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) 4039 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 4040 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 4041 } 4042 4043 if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) { 4044 Diag(Record->getLocation(), diag::warn_abstract_final_class); 4045 DiagnoseAbstractType(Record); 4046 } 4047 4048 if (!Record->isDependentType()) { 4049 for (CXXRecordDecl::method_iterator M = Record->method_begin(), 4050 MEnd = Record->method_end(); 4051 M != MEnd; ++M) { 4052 // See if a method overloads virtual methods in a base 4053 // class without overriding any. 4054 if (!M->isStatic()) 4055 DiagnoseHiddenVirtualMethods(Record, *M); 4056 4057 // Check whether the explicitly-defaulted special members are valid. 4058 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) 4059 CheckExplicitlyDefaultedSpecialMember(*M); 4060 4061 // For an explicitly defaulted or deleted special member, we defer 4062 // determining triviality until the class is complete. That time is now! 4063 if (!M->isImplicit() && !M->isUserProvided()) { 4064 CXXSpecialMember CSM = getSpecialMember(*M); 4065 if (CSM != CXXInvalid) { 4066 M->setTrivial(SpecialMemberIsTrivial(*M, CSM)); 4067 4068 // Inform the class that we've finished declaring this member. 4069 Record->finishedDefaultedOrDeletedMember(*M); 4070 } 4071 } 4072 } 4073 } 4074 4075 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member 4076 // function that is not a constructor declares that member function to be 4077 // const. [...] The class of which that function is a member shall be 4078 // a literal type. 4079 // 4080 // If the class has virtual bases, any constexpr members will already have 4081 // been diagnosed by the checks performed on the member declaration, so 4082 // suppress this (less useful) diagnostic. 4083 // 4084 // We delay this until we know whether an explicitly-defaulted (or deleted) 4085 // destructor for the class is trivial. 4086 if (LangOpts.CPlusPlus11 && !Record->isDependentType() && 4087 !Record->isLiteral() && !Record->getNumVBases()) { 4088 for (CXXRecordDecl::method_iterator M = Record->method_begin(), 4089 MEnd = Record->method_end(); 4090 M != MEnd; ++M) { 4091 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) { 4092 switch (Record->getTemplateSpecializationKind()) { 4093 case TSK_ImplicitInstantiation: 4094 case TSK_ExplicitInstantiationDeclaration: 4095 case TSK_ExplicitInstantiationDefinition: 4096 // If a template instantiates to a non-literal type, but its members 4097 // instantiate to constexpr functions, the template is technically 4098 // ill-formed, but we allow it for sanity. 4099 continue; 4100 4101 case TSK_Undeclared: 4102 case TSK_ExplicitSpecialization: 4103 RequireLiteralType(M->getLocation(), Context.getRecordType(Record), 4104 diag::err_constexpr_method_non_literal); 4105 break; 4106 } 4107 4108 // Only produce one error per class. 4109 break; 4110 } 4111 } 4112 } 4113 4114 // Declare inheriting constructors. We do this eagerly here because: 4115 // - The standard requires an eager diagnostic for conflicting inheriting 4116 // constructors from different classes. 4117 // - The lazy declaration of the other implicit constructors is so as to not 4118 // waste space and performance on classes that are not meant to be 4119 // instantiated (e.g. meta-functions). This doesn't apply to classes that 4120 // have inheriting constructors. 4121 DeclareInheritingConstructors(Record); 4122} 4123 4124/// Is the special member function which would be selected to perform the 4125/// specified operation on the specified class type a constexpr constructor? 4126static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 4127 Sema::CXXSpecialMember CSM, 4128 bool ConstArg) { 4129 Sema::SpecialMemberOverloadResult *SMOR = 4130 S.LookupSpecialMember(ClassDecl, CSM, ConstArg, 4131 false, false, false, false); 4132 if (!SMOR || !SMOR->getMethod()) 4133 // A constructor we wouldn't select can't be "involved in initializing" 4134 // anything. 4135 return true; 4136 return SMOR->getMethod()->isConstexpr(); 4137} 4138 4139/// Determine whether the specified special member function would be constexpr 4140/// if it were implicitly defined. 4141static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 4142 Sema::CXXSpecialMember CSM, 4143 bool ConstArg) { 4144 if (!S.getLangOpts().CPlusPlus11) 4145 return false; 4146 4147 // C++11 [dcl.constexpr]p4: 4148 // In the definition of a constexpr constructor [...] 4149 switch (CSM) { 4150 case Sema::CXXDefaultConstructor: 4151 // Since default constructor lookup is essentially trivial (and cannot 4152 // involve, for instance, template instantiation), we compute whether a 4153 // defaulted default constructor is constexpr directly within CXXRecordDecl. 4154 // 4155 // This is important for performance; we need to know whether the default 4156 // constructor is constexpr to determine whether the type is a literal type. 4157 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 4158 4159 case Sema::CXXCopyConstructor: 4160 case Sema::CXXMoveConstructor: 4161 // For copy or move constructors, we need to perform overload resolution. 4162 break; 4163 4164 case Sema::CXXCopyAssignment: 4165 case Sema::CXXMoveAssignment: 4166 case Sema::CXXDestructor: 4167 case Sema::CXXInvalid: 4168 return false; 4169 } 4170 4171 // -- if the class is a non-empty union, or for each non-empty anonymous 4172 // union member of a non-union class, exactly one non-static data member 4173 // shall be initialized; [DR1359] 4174 // 4175 // If we squint, this is guaranteed, since exactly one non-static data member 4176 // will be initialized (if the constructor isn't deleted), we just don't know 4177 // which one. 4178 if (ClassDecl->isUnion()) 4179 return true; 4180 4181 // -- the class shall not have any virtual base classes; 4182 if (ClassDecl->getNumVBases()) 4183 return false; 4184 4185 // -- every constructor involved in initializing [...] base class 4186 // sub-objects shall be a constexpr constructor; 4187 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 4188 BEnd = ClassDecl->bases_end(); 4189 B != BEnd; ++B) { 4190 const RecordType *BaseType = B->getType()->getAs<RecordType>(); 4191 if (!BaseType) continue; 4192 4193 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 4194 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg)) 4195 return false; 4196 } 4197 4198 // -- every constructor involved in initializing non-static data members 4199 // [...] shall be a constexpr constructor; 4200 // -- every non-static data member and base class sub-object shall be 4201 // initialized 4202 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 4203 FEnd = ClassDecl->field_end(); 4204 F != FEnd; ++F) { 4205 if (F->isInvalidDecl()) 4206 continue; 4207 if (const RecordType *RecordTy = 4208 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 4209 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 4210 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg)) 4211 return false; 4212 } 4213 } 4214 4215 // All OK, it's constexpr! 4216 return true; 4217} 4218 4219static Sema::ImplicitExceptionSpecification 4220computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 4221 switch (S.getSpecialMember(MD)) { 4222 case Sema::CXXDefaultConstructor: 4223 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD); 4224 case Sema::CXXCopyConstructor: 4225 return S.ComputeDefaultedCopyCtorExceptionSpec(MD); 4226 case Sema::CXXCopyAssignment: 4227 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD); 4228 case Sema::CXXMoveConstructor: 4229 return S.ComputeDefaultedMoveCtorExceptionSpec(MD); 4230 case Sema::CXXMoveAssignment: 4231 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD); 4232 case Sema::CXXDestructor: 4233 return S.ComputeDefaultedDtorExceptionSpec(MD); 4234 case Sema::CXXInvalid: 4235 break; 4236 } 4237 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() && 4238 "only special members have implicit exception specs"); 4239 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD)); 4240} 4241 4242static void 4243updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT, 4244 const Sema::ImplicitExceptionSpecification &ExceptSpec) { 4245 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 4246 ExceptSpec.getEPI(EPI); 4247 FD->setType(S.Context.getFunctionType(FPT->getResultType(), 4248 FPT->getArgTypes(), EPI)); 4249} 4250 4251void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 4252 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 4253 if (FPT->getExceptionSpecType() != EST_Unevaluated) 4254 return; 4255 4256 // Evaluate the exception specification. 4257 ImplicitExceptionSpecification ExceptSpec = 4258 computeImplicitExceptionSpec(*this, Loc, MD); 4259 4260 // Update the type of the special member to use it. 4261 updateExceptionSpec(*this, MD, FPT, ExceptSpec); 4262 4263 // A user-provided destructor can be defined outside the class. When that 4264 // happens, be sure to update the exception specification on both 4265 // declarations. 4266 const FunctionProtoType *CanonicalFPT = 4267 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 4268 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 4269 updateExceptionSpec(*this, MD->getCanonicalDecl(), 4270 CanonicalFPT, ExceptSpec); 4271} 4272 4273void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 4274 CXXRecordDecl *RD = MD->getParent(); 4275 CXXSpecialMember CSM = getSpecialMember(MD); 4276 4277 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 4278 "not an explicitly-defaulted special member"); 4279 4280 // Whether this was the first-declared instance of the constructor. 4281 // This affects whether we implicitly add an exception spec and constexpr. 4282 bool First = MD == MD->getCanonicalDecl(); 4283 4284 bool HadError = false; 4285 4286 // C++11 [dcl.fct.def.default]p1: 4287 // A function that is explicitly defaulted shall 4288 // -- be a special member function (checked elsewhere), 4289 // -- have the same type (except for ref-qualifiers, and except that a 4290 // copy operation can take a non-const reference) as an implicit 4291 // declaration, and 4292 // -- not have default arguments. 4293 unsigned ExpectedParams = 1; 4294 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 4295 ExpectedParams = 0; 4296 if (MD->getNumParams() != ExpectedParams) { 4297 // This also checks for default arguments: a copy or move constructor with a 4298 // default argument is classified as a default constructor, and assignment 4299 // operations and destructors can't have default arguments. 4300 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 4301 << CSM << MD->getSourceRange(); 4302 HadError = true; 4303 } else if (MD->isVariadic()) { 4304 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 4305 << CSM << MD->getSourceRange(); 4306 HadError = true; 4307 } 4308 4309 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 4310 4311 bool CanHaveConstParam = false; 4312 if (CSM == CXXCopyConstructor) 4313 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 4314 else if (CSM == CXXCopyAssignment) 4315 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 4316 4317 QualType ReturnType = Context.VoidTy; 4318 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 4319 // Check for return type matching. 4320 ReturnType = Type->getResultType(); 4321 QualType ExpectedReturnType = 4322 Context.getLValueReferenceType(Context.getTypeDeclType(RD)); 4323 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 4324 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 4325 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 4326 HadError = true; 4327 } 4328 4329 // A defaulted special member cannot have cv-qualifiers. 4330 if (Type->getTypeQuals()) { 4331 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 4332 << (CSM == CXXMoveAssignment); 4333 HadError = true; 4334 } 4335 } 4336 4337 // Check for parameter type matching. 4338 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType(); 4339 bool HasConstParam = false; 4340 if (ExpectedParams && ArgType->isReferenceType()) { 4341 // Argument must be reference to possibly-const T. 4342 QualType ReferentType = ArgType->getPointeeType(); 4343 HasConstParam = ReferentType.isConstQualified(); 4344 4345 if (ReferentType.isVolatileQualified()) { 4346 Diag(MD->getLocation(), 4347 diag::err_defaulted_special_member_volatile_param) << CSM; 4348 HadError = true; 4349 } 4350 4351 if (HasConstParam && !CanHaveConstParam) { 4352 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 4353 Diag(MD->getLocation(), 4354 diag::err_defaulted_special_member_copy_const_param) 4355 << (CSM == CXXCopyAssignment); 4356 // FIXME: Explain why this special member can't be const. 4357 } else { 4358 Diag(MD->getLocation(), 4359 diag::err_defaulted_special_member_move_const_param) 4360 << (CSM == CXXMoveAssignment); 4361 } 4362 HadError = true; 4363 } 4364 } else if (ExpectedParams) { 4365 // A copy assignment operator can take its argument by value, but a 4366 // defaulted one cannot. 4367 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 4368 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 4369 HadError = true; 4370 } 4371 4372 // C++11 [dcl.fct.def.default]p2: 4373 // An explicitly-defaulted function may be declared constexpr only if it 4374 // would have been implicitly declared as constexpr, 4375 // Do not apply this rule to members of class templates, since core issue 1358 4376 // makes such functions always instantiate to constexpr functions. For 4377 // non-constructors, this is checked elsewhere. 4378 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 4379 HasConstParam); 4380 if (isa<CXXConstructorDecl>(MD) && MD->isConstexpr() && !Constexpr && 4381 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 4382 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM; 4383 // FIXME: Explain why the constructor can't be constexpr. 4384 HadError = true; 4385 } 4386 4387 // and may have an explicit exception-specification only if it is compatible 4388 // with the exception-specification on the implicit declaration. 4389 if (Type->hasExceptionSpec()) { 4390 // Delay the check if this is the first declaration of the special member, 4391 // since we may not have parsed some necessary in-class initializers yet. 4392 if (First) { 4393 // If the exception specification needs to be instantiated, do so now, 4394 // before we clobber it with an EST_Unevaluated specification below. 4395 if (Type->getExceptionSpecType() == EST_Uninstantiated) { 4396 InstantiateExceptionSpec(MD->getLocStart(), MD); 4397 Type = MD->getType()->getAs<FunctionProtoType>(); 4398 } 4399 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type)); 4400 } else 4401 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type); 4402 } 4403 4404 // If a function is explicitly defaulted on its first declaration, 4405 if (First) { 4406 // -- it is implicitly considered to be constexpr if the implicit 4407 // definition would be, 4408 MD->setConstexpr(Constexpr); 4409 4410 // -- it is implicitly considered to have the same exception-specification 4411 // as if it had been implicitly declared, 4412 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 4413 EPI.ExceptionSpecType = EST_Unevaluated; 4414 EPI.ExceptionSpecDecl = MD; 4415 MD->setType(Context.getFunctionType(ReturnType, 4416 ArrayRef<QualType>(&ArgType, 4417 ExpectedParams), 4418 EPI)); 4419 } 4420 4421 if (ShouldDeleteSpecialMember(MD, CSM)) { 4422 if (First) { 4423 SetDeclDeleted(MD, MD->getLocation()); 4424 } else { 4425 // C++11 [dcl.fct.def.default]p4: 4426 // [For a] user-provided explicitly-defaulted function [...] if such a 4427 // function is implicitly defined as deleted, the program is ill-formed. 4428 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 4429 HadError = true; 4430 } 4431 } 4432 4433 if (HadError) 4434 MD->setInvalidDecl(); 4435} 4436 4437/// Check whether the exception specification provided for an 4438/// explicitly-defaulted special member matches the exception specification 4439/// that would have been generated for an implicit special member, per 4440/// C++11 [dcl.fct.def.default]p2. 4441void Sema::CheckExplicitlyDefaultedMemberExceptionSpec( 4442 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) { 4443 // Compute the implicit exception specification. 4444 FunctionProtoType::ExtProtoInfo EPI; 4445 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI); 4446 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>( 4447 Context.getFunctionType(Context.VoidTy, ArrayRef<QualType>(), EPI)); 4448 4449 // Ensure that it matches. 4450 CheckEquivalentExceptionSpec( 4451 PDiag(diag::err_incorrect_defaulted_exception_spec) 4452 << getSpecialMember(MD), PDiag(), 4453 ImplicitType, SourceLocation(), 4454 SpecifiedType, MD->getLocation()); 4455} 4456 4457void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() { 4458 for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size(); 4459 I != N; ++I) 4460 CheckExplicitlyDefaultedMemberExceptionSpec( 4461 DelayedDefaultedMemberExceptionSpecs[I].first, 4462 DelayedDefaultedMemberExceptionSpecs[I].second); 4463 4464 DelayedDefaultedMemberExceptionSpecs.clear(); 4465} 4466 4467namespace { 4468struct SpecialMemberDeletionInfo { 4469 Sema &S; 4470 CXXMethodDecl *MD; 4471 Sema::CXXSpecialMember CSM; 4472 bool Diagnose; 4473 4474 // Properties of the special member, computed for convenience. 4475 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg; 4476 SourceLocation Loc; 4477 4478 bool AllFieldsAreConst; 4479 4480 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 4481 Sema::CXXSpecialMember CSM, bool Diagnose) 4482 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose), 4483 IsConstructor(false), IsAssignment(false), IsMove(false), 4484 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()), 4485 AllFieldsAreConst(true) { 4486 switch (CSM) { 4487 case Sema::CXXDefaultConstructor: 4488 case Sema::CXXCopyConstructor: 4489 IsConstructor = true; 4490 break; 4491 case Sema::CXXMoveConstructor: 4492 IsConstructor = true; 4493 IsMove = true; 4494 break; 4495 case Sema::CXXCopyAssignment: 4496 IsAssignment = true; 4497 break; 4498 case Sema::CXXMoveAssignment: 4499 IsAssignment = true; 4500 IsMove = true; 4501 break; 4502 case Sema::CXXDestructor: 4503 break; 4504 case Sema::CXXInvalid: 4505 llvm_unreachable("invalid special member kind"); 4506 } 4507 4508 if (MD->getNumParams()) { 4509 ConstArg = MD->getParamDecl(0)->getType().isConstQualified(); 4510 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified(); 4511 } 4512 } 4513 4514 bool inUnion() const { return MD->getParent()->isUnion(); } 4515 4516 /// Look up the corresponding special member in the given class. 4517 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class, 4518 unsigned Quals) { 4519 unsigned TQ = MD->getTypeQualifiers(); 4520 // cv-qualifiers on class members don't affect default ctor / dtor calls. 4521 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 4522 Quals = 0; 4523 return S.LookupSpecialMember(Class, CSM, 4524 ConstArg || (Quals & Qualifiers::Const), 4525 VolatileArg || (Quals & Qualifiers::Volatile), 4526 MD->getRefQualifier() == RQ_RValue, 4527 TQ & Qualifiers::Const, 4528 TQ & Qualifiers::Volatile); 4529 } 4530 4531 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 4532 4533 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 4534 bool shouldDeleteForField(FieldDecl *FD); 4535 bool shouldDeleteForAllConstMembers(); 4536 4537 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 4538 unsigned Quals); 4539 bool shouldDeleteForSubobjectCall(Subobject Subobj, 4540 Sema::SpecialMemberOverloadResult *SMOR, 4541 bool IsDtorCallInCtor); 4542 4543 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 4544}; 4545} 4546 4547/// Is the given special member inaccessible when used on the given 4548/// sub-object. 4549bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 4550 CXXMethodDecl *target) { 4551 /// If we're operating on a base class, the object type is the 4552 /// type of this special member. 4553 QualType objectTy; 4554 AccessSpecifier access = target->getAccess(); 4555 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 4556 objectTy = S.Context.getTypeDeclType(MD->getParent()); 4557 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 4558 4559 // If we're operating on a field, the object type is the type of the field. 4560 } else { 4561 objectTy = S.Context.getTypeDeclType(target->getParent()); 4562 } 4563 4564 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 4565} 4566 4567/// Check whether we should delete a special member due to the implicit 4568/// definition containing a call to a special member of a subobject. 4569bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 4570 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR, 4571 bool IsDtorCallInCtor) { 4572 CXXMethodDecl *Decl = SMOR->getMethod(); 4573 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 4574 4575 int DiagKind = -1; 4576 4577 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 4578 DiagKind = !Decl ? 0 : 1; 4579 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 4580 DiagKind = 2; 4581 else if (!isAccessible(Subobj, Decl)) 4582 DiagKind = 3; 4583 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 4584 !Decl->isTrivial()) { 4585 // A member of a union must have a trivial corresponding special member. 4586 // As a weird special case, a destructor call from a union's constructor 4587 // must be accessible and non-deleted, but need not be trivial. Such a 4588 // destructor is never actually called, but is semantically checked as 4589 // if it were. 4590 DiagKind = 4; 4591 } 4592 4593 if (DiagKind == -1) 4594 return false; 4595 4596 if (Diagnose) { 4597 if (Field) { 4598 S.Diag(Field->getLocation(), 4599 diag::note_deleted_special_member_class_subobject) 4600 << CSM << MD->getParent() << /*IsField*/true 4601 << Field << DiagKind << IsDtorCallInCtor; 4602 } else { 4603 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 4604 S.Diag(Base->getLocStart(), 4605 diag::note_deleted_special_member_class_subobject) 4606 << CSM << MD->getParent() << /*IsField*/false 4607 << Base->getType() << DiagKind << IsDtorCallInCtor; 4608 } 4609 4610 if (DiagKind == 1) 4611 S.NoteDeletedFunction(Decl); 4612 // FIXME: Explain inaccessibility if DiagKind == 3. 4613 } 4614 4615 return true; 4616} 4617 4618/// Check whether we should delete a special member function due to having a 4619/// direct or virtual base class or non-static data member of class type M. 4620bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 4621 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 4622 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 4623 4624 // C++11 [class.ctor]p5: 4625 // -- any direct or virtual base class, or non-static data member with no 4626 // brace-or-equal-initializer, has class type M (or array thereof) and 4627 // either M has no default constructor or overload resolution as applied 4628 // to M's default constructor results in an ambiguity or in a function 4629 // that is deleted or inaccessible 4630 // C++11 [class.copy]p11, C++11 [class.copy]p23: 4631 // -- a direct or virtual base class B that cannot be copied/moved because 4632 // overload resolution, as applied to B's corresponding special member, 4633 // results in an ambiguity or a function that is deleted or inaccessible 4634 // from the defaulted special member 4635 // C++11 [class.dtor]p5: 4636 // -- any direct or virtual base class [...] has a type with a destructor 4637 // that is deleted or inaccessible 4638 if (!(CSM == Sema::CXXDefaultConstructor && 4639 Field && Field->hasInClassInitializer()) && 4640 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false)) 4641 return true; 4642 4643 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 4644 // -- any direct or virtual base class or non-static data member has a 4645 // type with a destructor that is deleted or inaccessible 4646 if (IsConstructor) { 4647 Sema::SpecialMemberOverloadResult *SMOR = 4648 S.LookupSpecialMember(Class, Sema::CXXDestructor, 4649 false, false, false, false, false); 4650 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 4651 return true; 4652 } 4653 4654 return false; 4655} 4656 4657/// Check whether we should delete a special member function due to the class 4658/// having a particular direct or virtual base class. 4659bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 4660 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 4661 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 4662} 4663 4664/// Check whether we should delete a special member function due to the class 4665/// having a particular non-static data member. 4666bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 4667 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 4668 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 4669 4670 if (CSM == Sema::CXXDefaultConstructor) { 4671 // For a default constructor, all references must be initialized in-class 4672 // and, if a union, it must have a non-const member. 4673 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 4674 if (Diagnose) 4675 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 4676 << MD->getParent() << FD << FieldType << /*Reference*/0; 4677 return true; 4678 } 4679 // C++11 [class.ctor]p5: any non-variant non-static data member of 4680 // const-qualified type (or array thereof) with no 4681 // brace-or-equal-initializer does not have a user-provided default 4682 // constructor. 4683 if (!inUnion() && FieldType.isConstQualified() && 4684 !FD->hasInClassInitializer() && 4685 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 4686 if (Diagnose) 4687 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 4688 << MD->getParent() << FD << FD->getType() << /*Const*/1; 4689 return true; 4690 } 4691 4692 if (inUnion() && !FieldType.isConstQualified()) 4693 AllFieldsAreConst = false; 4694 } else if (CSM == Sema::CXXCopyConstructor) { 4695 // For a copy constructor, data members must not be of rvalue reference 4696 // type. 4697 if (FieldType->isRValueReferenceType()) { 4698 if (Diagnose) 4699 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 4700 << MD->getParent() << FD << FieldType; 4701 return true; 4702 } 4703 } else if (IsAssignment) { 4704 // For an assignment operator, data members must not be of reference type. 4705 if (FieldType->isReferenceType()) { 4706 if (Diagnose) 4707 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 4708 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0; 4709 return true; 4710 } 4711 if (!FieldRecord && FieldType.isConstQualified()) { 4712 // C++11 [class.copy]p23: 4713 // -- a non-static data member of const non-class type (or array thereof) 4714 if (Diagnose) 4715 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 4716 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1; 4717 return true; 4718 } 4719 } 4720 4721 if (FieldRecord) { 4722 // Some additional restrictions exist on the variant members. 4723 if (!inUnion() && FieldRecord->isUnion() && 4724 FieldRecord->isAnonymousStructOrUnion()) { 4725 bool AllVariantFieldsAreConst = true; 4726 4727 // FIXME: Handle anonymous unions declared within anonymous unions. 4728 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(), 4729 UE = FieldRecord->field_end(); 4730 UI != UE; ++UI) { 4731 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 4732 4733 if (!UnionFieldType.isConstQualified()) 4734 AllVariantFieldsAreConst = false; 4735 4736 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 4737 if (UnionFieldRecord && 4738 shouldDeleteForClassSubobject(UnionFieldRecord, *UI, 4739 UnionFieldType.getCVRQualifiers())) 4740 return true; 4741 } 4742 4743 // At least one member in each anonymous union must be non-const 4744 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 4745 FieldRecord->field_begin() != FieldRecord->field_end()) { 4746 if (Diagnose) 4747 S.Diag(FieldRecord->getLocation(), 4748 diag::note_deleted_default_ctor_all_const) 4749 << MD->getParent() << /*anonymous union*/1; 4750 return true; 4751 } 4752 4753 // Don't check the implicit member of the anonymous union type. 4754 // This is technically non-conformant, but sanity demands it. 4755 return false; 4756 } 4757 4758 if (shouldDeleteForClassSubobject(FieldRecord, FD, 4759 FieldType.getCVRQualifiers())) 4760 return true; 4761 } 4762 4763 return false; 4764} 4765 4766/// C++11 [class.ctor] p5: 4767/// A defaulted default constructor for a class X is defined as deleted if 4768/// X is a union and all of its variant members are of const-qualified type. 4769bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 4770 // This is a silly definition, because it gives an empty union a deleted 4771 // default constructor. Don't do that. 4772 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst && 4773 (MD->getParent()->field_begin() != MD->getParent()->field_end())) { 4774 if (Diagnose) 4775 S.Diag(MD->getParent()->getLocation(), 4776 diag::note_deleted_default_ctor_all_const) 4777 << MD->getParent() << /*not anonymous union*/0; 4778 return true; 4779 } 4780 return false; 4781} 4782 4783/// Determine whether a defaulted special member function should be defined as 4784/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 4785/// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 4786bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 4787 bool Diagnose) { 4788 if (MD->isInvalidDecl()) 4789 return false; 4790 CXXRecordDecl *RD = MD->getParent(); 4791 assert(!RD->isDependentType() && "do deletion after instantiation"); 4792 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 4793 return false; 4794 4795 // C++11 [expr.lambda.prim]p19: 4796 // The closure type associated with a lambda-expression has a 4797 // deleted (8.4.3) default constructor and a deleted copy 4798 // assignment operator. 4799 if (RD->isLambda() && 4800 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 4801 if (Diagnose) 4802 Diag(RD->getLocation(), diag::note_lambda_decl); 4803 return true; 4804 } 4805 4806 // For an anonymous struct or union, the copy and assignment special members 4807 // will never be used, so skip the check. For an anonymous union declared at 4808 // namespace scope, the constructor and destructor are used. 4809 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 4810 RD->isAnonymousStructOrUnion()) 4811 return false; 4812 4813 // C++11 [class.copy]p7, p18: 4814 // If the class definition declares a move constructor or move assignment 4815 // operator, an implicitly declared copy constructor or copy assignment 4816 // operator is defined as deleted. 4817 if (MD->isImplicit() && 4818 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 4819 CXXMethodDecl *UserDeclaredMove = 0; 4820 4821 // In Microsoft mode, a user-declared move only causes the deletion of the 4822 // corresponding copy operation, not both copy operations. 4823 if (RD->hasUserDeclaredMoveConstructor() && 4824 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) { 4825 if (!Diagnose) return true; 4826 4827 // Find any user-declared move constructor. 4828 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(), 4829 E = RD->ctor_end(); I != E; ++I) { 4830 if (I->isMoveConstructor()) { 4831 UserDeclaredMove = *I; 4832 break; 4833 } 4834 } 4835 assert(UserDeclaredMove); 4836 } else if (RD->hasUserDeclaredMoveAssignment() && 4837 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) { 4838 if (!Diagnose) return true; 4839 4840 // Find any user-declared move assignment operator. 4841 for (CXXRecordDecl::method_iterator I = RD->method_begin(), 4842 E = RD->method_end(); I != E; ++I) { 4843 if (I->isMoveAssignmentOperator()) { 4844 UserDeclaredMove = *I; 4845 break; 4846 } 4847 } 4848 assert(UserDeclaredMove); 4849 } 4850 4851 if (UserDeclaredMove) { 4852 Diag(UserDeclaredMove->getLocation(), 4853 diag::note_deleted_copy_user_declared_move) 4854 << (CSM == CXXCopyAssignment) << RD 4855 << UserDeclaredMove->isMoveAssignmentOperator(); 4856 return true; 4857 } 4858 } 4859 4860 // Do access control from the special member function 4861 ContextRAII MethodContext(*this, MD); 4862 4863 // C++11 [class.dtor]p5: 4864 // -- for a virtual destructor, lookup of the non-array deallocation function 4865 // results in an ambiguity or in a function that is deleted or inaccessible 4866 if (CSM == CXXDestructor && MD->isVirtual()) { 4867 FunctionDecl *OperatorDelete = 0; 4868 DeclarationName Name = 4869 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 4870 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 4871 OperatorDelete, false)) { 4872 if (Diagnose) 4873 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 4874 return true; 4875 } 4876 } 4877 4878 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose); 4879 4880 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 4881 BE = RD->bases_end(); BI != BE; ++BI) 4882 if (!BI->isVirtual() && 4883 SMI.shouldDeleteForBase(BI)) 4884 return true; 4885 4886 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(), 4887 BE = RD->vbases_end(); BI != BE; ++BI) 4888 if (SMI.shouldDeleteForBase(BI)) 4889 return true; 4890 4891 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 4892 FE = RD->field_end(); FI != FE; ++FI) 4893 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() && 4894 SMI.shouldDeleteForField(*FI)) 4895 return true; 4896 4897 if (SMI.shouldDeleteForAllConstMembers()) 4898 return true; 4899 4900 return false; 4901} 4902 4903/// Perform lookup for a special member of the specified kind, and determine 4904/// whether it is trivial. If the triviality can be determined without the 4905/// lookup, skip it. This is intended for use when determining whether a 4906/// special member of a containing object is trivial, and thus does not ever 4907/// perform overload resolution for default constructors. 4908/// 4909/// If \p Selected is not \c NULL, \c *Selected will be filled in with the 4910/// member that was most likely to be intended to be trivial, if any. 4911static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 4912 Sema::CXXSpecialMember CSM, unsigned Quals, 4913 CXXMethodDecl **Selected) { 4914 if (Selected) 4915 *Selected = 0; 4916 4917 switch (CSM) { 4918 case Sema::CXXInvalid: 4919 llvm_unreachable("not a special member"); 4920 4921 case Sema::CXXDefaultConstructor: 4922 // C++11 [class.ctor]p5: 4923 // A default constructor is trivial if: 4924 // - all the [direct subobjects] have trivial default constructors 4925 // 4926 // Note, no overload resolution is performed in this case. 4927 if (RD->hasTrivialDefaultConstructor()) 4928 return true; 4929 4930 if (Selected) { 4931 // If there's a default constructor which could have been trivial, dig it 4932 // out. Otherwise, if there's any user-provided default constructor, point 4933 // to that as an example of why there's not a trivial one. 4934 CXXConstructorDecl *DefCtor = 0; 4935 if (RD->needsImplicitDefaultConstructor()) 4936 S.DeclareImplicitDefaultConstructor(RD); 4937 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), 4938 CE = RD->ctor_end(); CI != CE; ++CI) { 4939 if (!CI->isDefaultConstructor()) 4940 continue; 4941 DefCtor = *CI; 4942 if (!DefCtor->isUserProvided()) 4943 break; 4944 } 4945 4946 *Selected = DefCtor; 4947 } 4948 4949 return false; 4950 4951 case Sema::CXXDestructor: 4952 // C++11 [class.dtor]p5: 4953 // A destructor is trivial if: 4954 // - all the direct [subobjects] have trivial destructors 4955 if (RD->hasTrivialDestructor()) 4956 return true; 4957 4958 if (Selected) { 4959 if (RD->needsImplicitDestructor()) 4960 S.DeclareImplicitDestructor(RD); 4961 *Selected = RD->getDestructor(); 4962 } 4963 4964 return false; 4965 4966 case Sema::CXXCopyConstructor: 4967 // C++11 [class.copy]p12: 4968 // A copy constructor is trivial if: 4969 // - the constructor selected to copy each direct [subobject] is trivial 4970 if (RD->hasTrivialCopyConstructor()) { 4971 if (Quals == Qualifiers::Const) 4972 // We must either select the trivial copy constructor or reach an 4973 // ambiguity; no need to actually perform overload resolution. 4974 return true; 4975 } else if (!Selected) { 4976 return false; 4977 } 4978 // In C++98, we are not supposed to perform overload resolution here, but we 4979 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 4980 // cases like B as having a non-trivial copy constructor: 4981 // struct A { template<typename T> A(T&); }; 4982 // struct B { mutable A a; }; 4983 goto NeedOverloadResolution; 4984 4985 case Sema::CXXCopyAssignment: 4986 // C++11 [class.copy]p25: 4987 // A copy assignment operator is trivial if: 4988 // - the assignment operator selected to copy each direct [subobject] is 4989 // trivial 4990 if (RD->hasTrivialCopyAssignment()) { 4991 if (Quals == Qualifiers::Const) 4992 return true; 4993 } else if (!Selected) { 4994 return false; 4995 } 4996 // In C++98, we are not supposed to perform overload resolution here, but we 4997 // treat that as a language defect. 4998 goto NeedOverloadResolution; 4999 5000 case Sema::CXXMoveConstructor: 5001 case Sema::CXXMoveAssignment: 5002 NeedOverloadResolution: 5003 Sema::SpecialMemberOverloadResult *SMOR = 5004 S.LookupSpecialMember(RD, CSM, 5005 Quals & Qualifiers::Const, 5006 Quals & Qualifiers::Volatile, 5007 /*RValueThis*/false, /*ConstThis*/false, 5008 /*VolatileThis*/false); 5009 5010 // The standard doesn't describe how to behave if the lookup is ambiguous. 5011 // We treat it as not making the member non-trivial, just like the standard 5012 // mandates for the default constructor. This should rarely matter, because 5013 // the member will also be deleted. 5014 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 5015 return true; 5016 5017 if (!SMOR->getMethod()) { 5018 assert(SMOR->getKind() == 5019 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 5020 return false; 5021 } 5022 5023 // We deliberately don't check if we found a deleted special member. We're 5024 // not supposed to! 5025 if (Selected) 5026 *Selected = SMOR->getMethod(); 5027 return SMOR->getMethod()->isTrivial(); 5028 } 5029 5030 llvm_unreachable("unknown special method kind"); 5031} 5032 5033static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 5034 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end(); 5035 CI != CE; ++CI) 5036 if (!CI->isImplicit()) 5037 return *CI; 5038 5039 // Look for constructor templates. 5040 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 5041 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 5042 if (CXXConstructorDecl *CD = 5043 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 5044 return CD; 5045 } 5046 5047 return 0; 5048} 5049 5050/// The kind of subobject we are checking for triviality. The values of this 5051/// enumeration are used in diagnostics. 5052enum TrivialSubobjectKind { 5053 /// The subobject is a base class. 5054 TSK_BaseClass, 5055 /// The subobject is a non-static data member. 5056 TSK_Field, 5057 /// The object is actually the complete object. 5058 TSK_CompleteObject 5059}; 5060 5061/// Check whether the special member selected for a given type would be trivial. 5062static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 5063 QualType SubType, 5064 Sema::CXXSpecialMember CSM, 5065 TrivialSubobjectKind Kind, 5066 bool Diagnose) { 5067 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 5068 if (!SubRD) 5069 return true; 5070 5071 CXXMethodDecl *Selected; 5072 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 5073 Diagnose ? &Selected : 0)) 5074 return true; 5075 5076 if (Diagnose) { 5077 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 5078 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 5079 << Kind << SubType.getUnqualifiedType(); 5080 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 5081 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 5082 } else if (!Selected) 5083 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 5084 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 5085 else if (Selected->isUserProvided()) { 5086 if (Kind == TSK_CompleteObject) 5087 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 5088 << Kind << SubType.getUnqualifiedType() << CSM; 5089 else { 5090 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 5091 << Kind << SubType.getUnqualifiedType() << CSM; 5092 S.Diag(Selected->getLocation(), diag::note_declared_at); 5093 } 5094 } else { 5095 if (Kind != TSK_CompleteObject) 5096 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 5097 << Kind << SubType.getUnqualifiedType() << CSM; 5098 5099 // Explain why the defaulted or deleted special member isn't trivial. 5100 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose); 5101 } 5102 } 5103 5104 return false; 5105} 5106 5107/// Check whether the members of a class type allow a special member to be 5108/// trivial. 5109static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 5110 Sema::CXXSpecialMember CSM, 5111 bool ConstArg, bool Diagnose) { 5112 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 5113 FE = RD->field_end(); FI != FE; ++FI) { 5114 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 5115 continue; 5116 5117 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 5118 5119 // Pretend anonymous struct or union members are members of this class. 5120 if (FI->isAnonymousStructOrUnion()) { 5121 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 5122 CSM, ConstArg, Diagnose)) 5123 return false; 5124 continue; 5125 } 5126 5127 // C++11 [class.ctor]p5: 5128 // A default constructor is trivial if [...] 5129 // -- no non-static data member of its class has a 5130 // brace-or-equal-initializer 5131 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 5132 if (Diagnose) 5133 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI; 5134 return false; 5135 } 5136 5137 // Objective C ARC 4.3.5: 5138 // [...] nontrivally ownership-qualified types are [...] not trivially 5139 // default constructible, copy constructible, move constructible, copy 5140 // assignable, move assignable, or destructible [...] 5141 if (S.getLangOpts().ObjCAutoRefCount && 5142 FieldType.hasNonTrivialObjCLifetime()) { 5143 if (Diagnose) 5144 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 5145 << RD << FieldType.getObjCLifetime(); 5146 return false; 5147 } 5148 5149 if (ConstArg && !FI->isMutable()) 5150 FieldType.addConst(); 5151 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM, 5152 TSK_Field, Diagnose)) 5153 return false; 5154 } 5155 5156 return true; 5157} 5158 5159/// Diagnose why the specified class does not have a trivial special member of 5160/// the given kind. 5161void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 5162 QualType Ty = Context.getRecordType(RD); 5163 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) 5164 Ty.addConst(); 5165 5166 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM, 5167 TSK_CompleteObject, /*Diagnose*/true); 5168} 5169 5170/// Determine whether a defaulted or deleted special member function is trivial, 5171/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 5172/// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 5173bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 5174 bool Diagnose) { 5175 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 5176 5177 CXXRecordDecl *RD = MD->getParent(); 5178 5179 bool ConstArg = false; 5180 5181 // C++11 [class.copy]p12, p25: 5182 // A [special member] is trivial if its declared parameter type is the same 5183 // as if it had been implicitly declared [...] 5184 switch (CSM) { 5185 case CXXDefaultConstructor: 5186 case CXXDestructor: 5187 // Trivial default constructors and destructors cannot have parameters. 5188 break; 5189 5190 case CXXCopyConstructor: 5191 case CXXCopyAssignment: { 5192 // Trivial copy operations always have const, non-volatile parameter types. 5193 ConstArg = true; 5194 const ParmVarDecl *Param0 = MD->getParamDecl(0); 5195 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 5196 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 5197 if (Diagnose) 5198 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 5199 << Param0->getSourceRange() << Param0->getType() 5200 << Context.getLValueReferenceType( 5201 Context.getRecordType(RD).withConst()); 5202 return false; 5203 } 5204 break; 5205 } 5206 5207 case CXXMoveConstructor: 5208 case CXXMoveAssignment: { 5209 // Trivial move operations always have non-cv-qualified parameters. 5210 const ParmVarDecl *Param0 = MD->getParamDecl(0); 5211 const RValueReferenceType *RT = 5212 Param0->getType()->getAs<RValueReferenceType>(); 5213 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 5214 if (Diagnose) 5215 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 5216 << Param0->getSourceRange() << Param0->getType() 5217 << Context.getRValueReferenceType(Context.getRecordType(RD)); 5218 return false; 5219 } 5220 break; 5221 } 5222 5223 case CXXInvalid: 5224 llvm_unreachable("not a special member"); 5225 } 5226 5227 // FIXME: We require that the parameter-declaration-clause is equivalent to 5228 // that of an implicit declaration, not just that the declared parameter type 5229 // matches, in order to prevent absuridities like a function simultaneously 5230 // being a trivial copy constructor and a non-trivial default constructor. 5231 // This issue has not yet been assigned a core issue number. 5232 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 5233 if (Diagnose) 5234 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 5235 diag::note_nontrivial_default_arg) 5236 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 5237 return false; 5238 } 5239 if (MD->isVariadic()) { 5240 if (Diagnose) 5241 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 5242 return false; 5243 } 5244 5245 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 5246 // A copy/move [constructor or assignment operator] is trivial if 5247 // -- the [member] selected to copy/move each direct base class subobject 5248 // is trivial 5249 // 5250 // C++11 [class.copy]p12, C++11 [class.copy]p25: 5251 // A [default constructor or destructor] is trivial if 5252 // -- all the direct base classes have trivial [default constructors or 5253 // destructors] 5254 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 5255 BE = RD->bases_end(); BI != BE; ++BI) 5256 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(), 5257 ConstArg ? BI->getType().withConst() 5258 : BI->getType(), 5259 CSM, TSK_BaseClass, Diagnose)) 5260 return false; 5261 5262 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 5263 // A copy/move [constructor or assignment operator] for a class X is 5264 // trivial if 5265 // -- for each non-static data member of X that is of class type (or array 5266 // thereof), the constructor selected to copy/move that member is 5267 // trivial 5268 // 5269 // C++11 [class.copy]p12, C++11 [class.copy]p25: 5270 // A [default constructor or destructor] is trivial if 5271 // -- for all of the non-static data members of its class that are of class 5272 // type (or array thereof), each such class has a trivial [default 5273 // constructor or destructor] 5274 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose)) 5275 return false; 5276 5277 // C++11 [class.dtor]p5: 5278 // A destructor is trivial if [...] 5279 // -- the destructor is not virtual 5280 if (CSM == CXXDestructor && MD->isVirtual()) { 5281 if (Diagnose) 5282 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 5283 return false; 5284 } 5285 5286 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 5287 // A [special member] for class X is trivial if [...] 5288 // -- class X has no virtual functions and no virtual base classes 5289 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 5290 if (!Diagnose) 5291 return false; 5292 5293 if (RD->getNumVBases()) { 5294 // Check for virtual bases. We already know that the corresponding 5295 // member in all bases is trivial, so vbases must all be direct. 5296 CXXBaseSpecifier &BS = *RD->vbases_begin(); 5297 assert(BS.isVirtual()); 5298 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1; 5299 return false; 5300 } 5301 5302 // Must have a virtual method. 5303 for (CXXRecordDecl::method_iterator MI = RD->method_begin(), 5304 ME = RD->method_end(); MI != ME; ++MI) { 5305 if (MI->isVirtual()) { 5306 SourceLocation MLoc = MI->getLocStart(); 5307 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 5308 return false; 5309 } 5310 } 5311 5312 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 5313 } 5314 5315 // Looks like it's trivial! 5316 return true; 5317} 5318 5319/// \brief Data used with FindHiddenVirtualMethod 5320namespace { 5321 struct FindHiddenVirtualMethodData { 5322 Sema *S; 5323 CXXMethodDecl *Method; 5324 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 5325 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 5326 }; 5327} 5328 5329/// \brief Check whether any most overriden method from MD in Methods 5330static bool CheckMostOverridenMethods(const CXXMethodDecl *MD, 5331 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) { 5332 if (MD->size_overridden_methods() == 0) 5333 return Methods.count(MD->getCanonicalDecl()); 5334 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 5335 E = MD->end_overridden_methods(); 5336 I != E; ++I) 5337 if (CheckMostOverridenMethods(*I, Methods)) 5338 return true; 5339 return false; 5340} 5341 5342/// \brief Member lookup function that determines whether a given C++ 5343/// method overloads virtual methods in a base class without overriding any, 5344/// to be used with CXXRecordDecl::lookupInBases(). 5345static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier, 5346 CXXBasePath &Path, 5347 void *UserData) { 5348 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 5349 5350 FindHiddenVirtualMethodData &Data 5351 = *static_cast<FindHiddenVirtualMethodData*>(UserData); 5352 5353 DeclarationName Name = Data.Method->getDeclName(); 5354 assert(Name.getNameKind() == DeclarationName::Identifier); 5355 5356 bool foundSameNameMethod = false; 5357 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 5358 for (Path.Decls = BaseRecord->lookup(Name); 5359 !Path.Decls.empty(); 5360 Path.Decls = Path.Decls.slice(1)) { 5361 NamedDecl *D = Path.Decls.front(); 5362 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 5363 MD = MD->getCanonicalDecl(); 5364 foundSameNameMethod = true; 5365 // Interested only in hidden virtual methods. 5366 if (!MD->isVirtual()) 5367 continue; 5368 // If the method we are checking overrides a method from its base 5369 // don't warn about the other overloaded methods. 5370 if (!Data.S->IsOverload(Data.Method, MD, false)) 5371 return true; 5372 // Collect the overload only if its hidden. 5373 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods)) 5374 overloadedMethods.push_back(MD); 5375 } 5376 } 5377 5378 if (foundSameNameMethod) 5379 Data.OverloadedMethods.append(overloadedMethods.begin(), 5380 overloadedMethods.end()); 5381 return foundSameNameMethod; 5382} 5383 5384/// \brief Add the most overriden methods from MD to Methods 5385static void AddMostOverridenMethods(const CXXMethodDecl *MD, 5386 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) { 5387 if (MD->size_overridden_methods() == 0) 5388 Methods.insert(MD->getCanonicalDecl()); 5389 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 5390 E = MD->end_overridden_methods(); 5391 I != E; ++I) 5392 AddMostOverridenMethods(*I, Methods); 5393} 5394 5395/// \brief See if a method overloads virtual methods in a base class without 5396/// overriding any. 5397void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 5398 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual, 5399 MD->getLocation()) == DiagnosticsEngine::Ignored) 5400 return; 5401 if (!MD->getDeclName().isIdentifier()) 5402 return; 5403 5404 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 5405 /*bool RecordPaths=*/false, 5406 /*bool DetectVirtual=*/false); 5407 FindHiddenVirtualMethodData Data; 5408 Data.Method = MD; 5409 Data.S = this; 5410 5411 // Keep the base methods that were overriden or introduced in the subclass 5412 // by 'using' in a set. A base method not in this set is hidden. 5413 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 5414 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 5415 NamedDecl *ND = *I; 5416 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 5417 ND = shad->getTargetDecl(); 5418 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 5419 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods); 5420 } 5421 5422 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) && 5423 !Data.OverloadedMethods.empty()) { 5424 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 5425 << MD << (Data.OverloadedMethods.size() > 1); 5426 5427 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) { 5428 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i]; 5429 PartialDiagnostic PD = PDiag( 5430 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 5431 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 5432 Diag(overloadedMD->getLocation(), PD); 5433 } 5434 } 5435} 5436 5437void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 5438 Decl *TagDecl, 5439 SourceLocation LBrac, 5440 SourceLocation RBrac, 5441 AttributeList *AttrList) { 5442 if (!TagDecl) 5443 return; 5444 5445 AdjustDeclIfTemplate(TagDecl); 5446 5447 for (const AttributeList* l = AttrList; l; l = l->getNext()) { 5448 if (l->getKind() != AttributeList::AT_Visibility) 5449 continue; 5450 l->setInvalid(); 5451 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) << 5452 l->getName(); 5453 } 5454 5455 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 5456 // strict aliasing violation! 5457 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 5458 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 5459 5460 CheckCompletedCXXClass( 5461 dyn_cast_or_null<CXXRecordDecl>(TagDecl)); 5462} 5463 5464/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 5465/// special functions, such as the default constructor, copy 5466/// constructor, or destructor, to the given C++ class (C++ 5467/// [special]p1). This routine can only be executed just before the 5468/// definition of the class is complete. 5469void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 5470 if (!ClassDecl->hasUserDeclaredConstructor()) 5471 ++ASTContext::NumImplicitDefaultConstructors; 5472 5473 if (!ClassDecl->hasUserDeclaredCopyConstructor()) { 5474 ++ASTContext::NumImplicitCopyConstructors; 5475 5476 // If the properties or semantics of the copy constructor couldn't be 5477 // determined while the class was being declared, force a declaration 5478 // of it now. 5479 if (ClassDecl->needsOverloadResolutionForCopyConstructor()) 5480 DeclareImplicitCopyConstructor(ClassDecl); 5481 } 5482 5483 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 5484 ++ASTContext::NumImplicitMoveConstructors; 5485 5486 if (ClassDecl->needsOverloadResolutionForMoveConstructor()) 5487 DeclareImplicitMoveConstructor(ClassDecl); 5488 } 5489 5490 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 5491 ++ASTContext::NumImplicitCopyAssignmentOperators; 5492 5493 // If we have a dynamic class, then the copy assignment operator may be 5494 // virtual, so we have to declare it immediately. This ensures that, e.g., 5495 // it shows up in the right place in the vtable and that we diagnose 5496 // problems with the implicit exception specification. 5497 if (ClassDecl->isDynamicClass() || 5498 ClassDecl->needsOverloadResolutionForCopyAssignment()) 5499 DeclareImplicitCopyAssignment(ClassDecl); 5500 } 5501 5502 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 5503 ++ASTContext::NumImplicitMoveAssignmentOperators; 5504 5505 // Likewise for the move assignment operator. 5506 if (ClassDecl->isDynamicClass() || 5507 ClassDecl->needsOverloadResolutionForMoveAssignment()) 5508 DeclareImplicitMoveAssignment(ClassDecl); 5509 } 5510 5511 if (!ClassDecl->hasUserDeclaredDestructor()) { 5512 ++ASTContext::NumImplicitDestructors; 5513 5514 // If we have a dynamic class, then the destructor may be virtual, so we 5515 // have to declare the destructor immediately. This ensures that, e.g., it 5516 // shows up in the right place in the vtable and that we diagnose problems 5517 // with the implicit exception specification. 5518 if (ClassDecl->isDynamicClass() || 5519 ClassDecl->needsOverloadResolutionForDestructor()) 5520 DeclareImplicitDestructor(ClassDecl); 5521 } 5522} 5523 5524void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) { 5525 if (!D) 5526 return; 5527 5528 int NumParamList = D->getNumTemplateParameterLists(); 5529 for (int i = 0; i < NumParamList; i++) { 5530 TemplateParameterList* Params = D->getTemplateParameterList(i); 5531 for (TemplateParameterList::iterator Param = Params->begin(), 5532 ParamEnd = Params->end(); 5533 Param != ParamEnd; ++Param) { 5534 NamedDecl *Named = cast<NamedDecl>(*Param); 5535 if (Named->getDeclName()) { 5536 S->AddDecl(Named); 5537 IdResolver.AddDecl(Named); 5538 } 5539 } 5540 } 5541} 5542 5543void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 5544 if (!D) 5545 return; 5546 5547 TemplateParameterList *Params = 0; 5548 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) 5549 Params = Template->getTemplateParameters(); 5550 else if (ClassTemplatePartialSpecializationDecl *PartialSpec 5551 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 5552 Params = PartialSpec->getTemplateParameters(); 5553 else 5554 return; 5555 5556 for (TemplateParameterList::iterator Param = Params->begin(), 5557 ParamEnd = Params->end(); 5558 Param != ParamEnd; ++Param) { 5559 NamedDecl *Named = cast<NamedDecl>(*Param); 5560 if (Named->getDeclName()) { 5561 S->AddDecl(Named); 5562 IdResolver.AddDecl(Named); 5563 } 5564 } 5565} 5566 5567void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 5568 if (!RecordD) return; 5569 AdjustDeclIfTemplate(RecordD); 5570 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 5571 PushDeclContext(S, Record); 5572} 5573 5574void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 5575 if (!RecordD) return; 5576 PopDeclContext(); 5577} 5578 5579/// ActOnStartDelayedCXXMethodDeclaration - We have completed 5580/// parsing a top-level (non-nested) C++ class, and we are now 5581/// parsing those parts of the given Method declaration that could 5582/// not be parsed earlier (C++ [class.mem]p2), such as default 5583/// arguments. This action should enter the scope of the given 5584/// Method declaration as if we had just parsed the qualified method 5585/// name. However, it should not bring the parameters into scope; 5586/// that will be performed by ActOnDelayedCXXMethodParameter. 5587void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 5588} 5589 5590/// ActOnDelayedCXXMethodParameter - We've already started a delayed 5591/// C++ method declaration. We're (re-)introducing the given 5592/// function parameter into scope for use in parsing later parts of 5593/// the method declaration. For example, we could see an 5594/// ActOnParamDefaultArgument event for this parameter. 5595void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 5596 if (!ParamD) 5597 return; 5598 5599 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 5600 5601 // If this parameter has an unparsed default argument, clear it out 5602 // to make way for the parsed default argument. 5603 if (Param->hasUnparsedDefaultArg()) 5604 Param->setDefaultArg(0); 5605 5606 S->AddDecl(Param); 5607 if (Param->getDeclName()) 5608 IdResolver.AddDecl(Param); 5609} 5610 5611/// ActOnFinishDelayedCXXMethodDeclaration - We have finished 5612/// processing the delayed method declaration for Method. The method 5613/// declaration is now considered finished. There may be a separate 5614/// ActOnStartOfFunctionDef action later (not necessarily 5615/// immediately!) for this method, if it was also defined inside the 5616/// class body. 5617void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 5618 if (!MethodD) 5619 return; 5620 5621 AdjustDeclIfTemplate(MethodD); 5622 5623 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 5624 5625 // Now that we have our default arguments, check the constructor 5626 // again. It could produce additional diagnostics or affect whether 5627 // the class has implicitly-declared destructors, among other 5628 // things. 5629 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 5630 CheckConstructor(Constructor); 5631 5632 // Check the default arguments, which we may have added. 5633 if (!Method->isInvalidDecl()) 5634 CheckCXXDefaultArguments(Method); 5635} 5636 5637/// CheckConstructorDeclarator - Called by ActOnDeclarator to check 5638/// the well-formedness of the constructor declarator @p D with type @p 5639/// R. If there are any errors in the declarator, this routine will 5640/// emit diagnostics and set the invalid bit to true. In any case, the type 5641/// will be updated to reflect a well-formed type for the constructor and 5642/// returned. 5643QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 5644 StorageClass &SC) { 5645 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 5646 5647 // C++ [class.ctor]p3: 5648 // A constructor shall not be virtual (10.3) or static (9.4). A 5649 // constructor can be invoked for a const, volatile or const 5650 // volatile object. A constructor shall not be declared const, 5651 // volatile, or const volatile (9.3.2). 5652 if (isVirtual) { 5653 if (!D.isInvalidType()) 5654 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 5655 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 5656 << SourceRange(D.getIdentifierLoc()); 5657 D.setInvalidType(); 5658 } 5659 if (SC == SC_Static) { 5660 if (!D.isInvalidType()) 5661 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 5662 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 5663 << SourceRange(D.getIdentifierLoc()); 5664 D.setInvalidType(); 5665 SC = SC_None; 5666 } 5667 5668 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 5669 if (FTI.TypeQuals != 0) { 5670 if (FTI.TypeQuals & Qualifiers::Const) 5671 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 5672 << "const" << SourceRange(D.getIdentifierLoc()); 5673 if (FTI.TypeQuals & Qualifiers::Volatile) 5674 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 5675 << "volatile" << SourceRange(D.getIdentifierLoc()); 5676 if (FTI.TypeQuals & Qualifiers::Restrict) 5677 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 5678 << "restrict" << SourceRange(D.getIdentifierLoc()); 5679 D.setInvalidType(); 5680 } 5681 5682 // C++0x [class.ctor]p4: 5683 // A constructor shall not be declared with a ref-qualifier. 5684 if (FTI.hasRefQualifier()) { 5685 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 5686 << FTI.RefQualifierIsLValueRef 5687 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 5688 D.setInvalidType(); 5689 } 5690 5691 // Rebuild the function type "R" without any type qualifiers (in 5692 // case any of the errors above fired) and with "void" as the 5693 // return type, since constructors don't have return types. 5694 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 5695 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType()) 5696 return R; 5697 5698 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 5699 EPI.TypeQuals = 0; 5700 EPI.RefQualifier = RQ_None; 5701 5702 return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI); 5703} 5704 5705/// CheckConstructor - Checks a fully-formed constructor for 5706/// well-formedness, issuing any diagnostics required. Returns true if 5707/// the constructor declarator is invalid. 5708void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 5709 CXXRecordDecl *ClassDecl 5710 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 5711 if (!ClassDecl) 5712 return Constructor->setInvalidDecl(); 5713 5714 // C++ [class.copy]p3: 5715 // A declaration of a constructor for a class X is ill-formed if 5716 // its first parameter is of type (optionally cv-qualified) X and 5717 // either there are no other parameters or else all other 5718 // parameters have default arguments. 5719 if (!Constructor->isInvalidDecl() && 5720 ((Constructor->getNumParams() == 1) || 5721 (Constructor->getNumParams() > 1 && 5722 Constructor->getParamDecl(1)->hasDefaultArg())) && 5723 Constructor->getTemplateSpecializationKind() 5724 != TSK_ImplicitInstantiation) { 5725 QualType ParamType = Constructor->getParamDecl(0)->getType(); 5726 QualType ClassTy = Context.getTagDeclType(ClassDecl); 5727 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 5728 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 5729 const char *ConstRef 5730 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 5731 : " const &"; 5732 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 5733 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 5734 5735 // FIXME: Rather that making the constructor invalid, we should endeavor 5736 // to fix the type. 5737 Constructor->setInvalidDecl(); 5738 } 5739 } 5740} 5741 5742/// CheckDestructor - Checks a fully-formed destructor definition for 5743/// well-formedness, issuing any diagnostics required. Returns true 5744/// on error. 5745bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 5746 CXXRecordDecl *RD = Destructor->getParent(); 5747 5748 if (Destructor->isVirtual()) { 5749 SourceLocation Loc; 5750 5751 if (!Destructor->isImplicit()) 5752 Loc = Destructor->getLocation(); 5753 else 5754 Loc = RD->getLocation(); 5755 5756 // If we have a virtual destructor, look up the deallocation function 5757 FunctionDecl *OperatorDelete = 0; 5758 DeclarationName Name = 5759 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 5760 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 5761 return true; 5762 5763 MarkFunctionReferenced(Loc, OperatorDelete); 5764 5765 Destructor->setOperatorDelete(OperatorDelete); 5766 } 5767 5768 return false; 5769} 5770 5771static inline bool 5772FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) { 5773 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 5774 FTI.ArgInfo[0].Param && 5775 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()); 5776} 5777 5778/// CheckDestructorDeclarator - Called by ActOnDeclarator to check 5779/// the well-formednes of the destructor declarator @p D with type @p 5780/// R. If there are any errors in the declarator, this routine will 5781/// emit diagnostics and set the declarator to invalid. Even if this happens, 5782/// will be updated to reflect a well-formed type for the destructor and 5783/// returned. 5784QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 5785 StorageClass& SC) { 5786 // C++ [class.dtor]p1: 5787 // [...] A typedef-name that names a class is a class-name 5788 // (7.1.3); however, a typedef-name that names a class shall not 5789 // be used as the identifier in the declarator for a destructor 5790 // declaration. 5791 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 5792 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 5793 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 5794 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 5795 else if (const TemplateSpecializationType *TST = 5796 DeclaratorType->getAs<TemplateSpecializationType>()) 5797 if (TST->isTypeAlias()) 5798 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 5799 << DeclaratorType << 1; 5800 5801 // C++ [class.dtor]p2: 5802 // A destructor is used to destroy objects of its class type. A 5803 // destructor takes no parameters, and no return type can be 5804 // specified for it (not even void). The address of a destructor 5805 // shall not be taken. A destructor shall not be static. A 5806 // destructor can be invoked for a const, volatile or const 5807 // volatile object. A destructor shall not be declared const, 5808 // volatile or const volatile (9.3.2). 5809 if (SC == SC_Static) { 5810 if (!D.isInvalidType()) 5811 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 5812 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 5813 << SourceRange(D.getIdentifierLoc()) 5814 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5815 5816 SC = SC_None; 5817 } 5818 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 5819 // Destructors don't have return types, but the parser will 5820 // happily parse something like: 5821 // 5822 // class X { 5823 // float ~X(); 5824 // }; 5825 // 5826 // The return type will be eliminated later. 5827 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 5828 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 5829 << SourceRange(D.getIdentifierLoc()); 5830 } 5831 5832 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 5833 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 5834 if (FTI.TypeQuals & Qualifiers::Const) 5835 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 5836 << "const" << SourceRange(D.getIdentifierLoc()); 5837 if (FTI.TypeQuals & Qualifiers::Volatile) 5838 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 5839 << "volatile" << SourceRange(D.getIdentifierLoc()); 5840 if (FTI.TypeQuals & Qualifiers::Restrict) 5841 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 5842 << "restrict" << SourceRange(D.getIdentifierLoc()); 5843 D.setInvalidType(); 5844 } 5845 5846 // C++0x [class.dtor]p2: 5847 // A destructor shall not be declared with a ref-qualifier. 5848 if (FTI.hasRefQualifier()) { 5849 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 5850 << FTI.RefQualifierIsLValueRef 5851 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 5852 D.setInvalidType(); 5853 } 5854 5855 // Make sure we don't have any parameters. 5856 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) { 5857 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 5858 5859 // Delete the parameters. 5860 FTI.freeArgs(); 5861 D.setInvalidType(); 5862 } 5863 5864 // Make sure the destructor isn't variadic. 5865 if (FTI.isVariadic) { 5866 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 5867 D.setInvalidType(); 5868 } 5869 5870 // Rebuild the function type "R" without any type qualifiers or 5871 // parameters (in case any of the errors above fired) and with 5872 // "void" as the return type, since destructors don't have return 5873 // types. 5874 if (!D.isInvalidType()) 5875 return R; 5876 5877 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 5878 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 5879 EPI.Variadic = false; 5880 EPI.TypeQuals = 0; 5881 EPI.RefQualifier = RQ_None; 5882 return Context.getFunctionType(Context.VoidTy, ArrayRef<QualType>(), EPI); 5883} 5884 5885/// CheckConversionDeclarator - Called by ActOnDeclarator to check the 5886/// well-formednes of the conversion function declarator @p D with 5887/// type @p R. If there are any errors in the declarator, this routine 5888/// will emit diagnostics and return true. Otherwise, it will return 5889/// false. Either way, the type @p R will be updated to reflect a 5890/// well-formed type for the conversion operator. 5891void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 5892 StorageClass& SC) { 5893 // C++ [class.conv.fct]p1: 5894 // Neither parameter types nor return type can be specified. The 5895 // type of a conversion function (8.3.5) is "function taking no 5896 // parameter returning conversion-type-id." 5897 if (SC == SC_Static) { 5898 if (!D.isInvalidType()) 5899 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 5900 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 5901 << SourceRange(D.getIdentifierLoc()); 5902 D.setInvalidType(); 5903 SC = SC_None; 5904 } 5905 5906 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId); 5907 5908 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 5909 // Conversion functions don't have return types, but the parser will 5910 // happily parse something like: 5911 // 5912 // class X { 5913 // float operator bool(); 5914 // }; 5915 // 5916 // The return type will be changed later anyway. 5917 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 5918 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 5919 << SourceRange(D.getIdentifierLoc()); 5920 D.setInvalidType(); 5921 } 5922 5923 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 5924 5925 // Make sure we don't have any parameters. 5926 if (Proto->getNumArgs() > 0) { 5927 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 5928 5929 // Delete the parameters. 5930 D.getFunctionTypeInfo().freeArgs(); 5931 D.setInvalidType(); 5932 } else if (Proto->isVariadic()) { 5933 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 5934 D.setInvalidType(); 5935 } 5936 5937 // Diagnose "&operator bool()" and other such nonsense. This 5938 // is actually a gcc extension which we don't support. 5939 if (Proto->getResultType() != ConvType) { 5940 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 5941 << Proto->getResultType(); 5942 D.setInvalidType(); 5943 ConvType = Proto->getResultType(); 5944 } 5945 5946 // C++ [class.conv.fct]p4: 5947 // The conversion-type-id shall not represent a function type nor 5948 // an array type. 5949 if (ConvType->isArrayType()) { 5950 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 5951 ConvType = Context.getPointerType(ConvType); 5952 D.setInvalidType(); 5953 } else if (ConvType->isFunctionType()) { 5954 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 5955 ConvType = Context.getPointerType(ConvType); 5956 D.setInvalidType(); 5957 } 5958 5959 // Rebuild the function type "R" without any parameters (in case any 5960 // of the errors above fired) and with the conversion type as the 5961 // return type. 5962 if (D.isInvalidType()) 5963 R = Context.getFunctionType(ConvType, ArrayRef<QualType>(), 5964 Proto->getExtProtoInfo()); 5965 5966 // C++0x explicit conversion operators. 5967 if (D.getDeclSpec().isExplicitSpecified()) 5968 Diag(D.getDeclSpec().getExplicitSpecLoc(), 5969 getLangOpts().CPlusPlus11 ? 5970 diag::warn_cxx98_compat_explicit_conversion_functions : 5971 diag::ext_explicit_conversion_functions) 5972 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 5973} 5974 5975/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 5976/// the declaration of the given C++ conversion function. This routine 5977/// is responsible for recording the conversion function in the C++ 5978/// class, if possible. 5979Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 5980 assert(Conversion && "Expected to receive a conversion function declaration"); 5981 5982 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 5983 5984 // Make sure we aren't redeclaring the conversion function. 5985 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 5986 5987 // C++ [class.conv.fct]p1: 5988 // [...] A conversion function is never used to convert a 5989 // (possibly cv-qualified) object to the (possibly cv-qualified) 5990 // same object type (or a reference to it), to a (possibly 5991 // cv-qualified) base class of that type (or a reference to it), 5992 // or to (possibly cv-qualified) void. 5993 // FIXME: Suppress this warning if the conversion function ends up being a 5994 // virtual function that overrides a virtual function in a base class. 5995 QualType ClassType 5996 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 5997 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 5998 ConvType = ConvTypeRef->getPointeeType(); 5999 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 6000 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 6001 /* Suppress diagnostics for instantiations. */; 6002 else if (ConvType->isRecordType()) { 6003 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 6004 if (ConvType == ClassType) 6005 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 6006 << ClassType; 6007 else if (IsDerivedFrom(ClassType, ConvType)) 6008 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 6009 << ClassType << ConvType; 6010 } else if (ConvType->isVoidType()) { 6011 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 6012 << ClassType << ConvType; 6013 } 6014 6015 if (FunctionTemplateDecl *ConversionTemplate 6016 = Conversion->getDescribedFunctionTemplate()) 6017 return ConversionTemplate; 6018 6019 return Conversion; 6020} 6021 6022//===----------------------------------------------------------------------===// 6023// Namespace Handling 6024//===----------------------------------------------------------------------===// 6025 6026/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is 6027/// reopened. 6028static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 6029 SourceLocation Loc, 6030 IdentifierInfo *II, bool *IsInline, 6031 NamespaceDecl *PrevNS) { 6032 assert(*IsInline != PrevNS->isInline()); 6033 6034 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 6035 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 6036 // inline namespaces, with the intention of bringing names into namespace std. 6037 // 6038 // We support this just well enough to get that case working; this is not 6039 // sufficient to support reopening namespaces as inline in general. 6040 if (*IsInline && II && II->getName().startswith("__atomic") && 6041 S.getSourceManager().isInSystemHeader(Loc)) { 6042 // Mark all prior declarations of the namespace as inline. 6043 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 6044 NS = NS->getPreviousDecl()) 6045 NS->setInline(*IsInline); 6046 // Patch up the lookup table for the containing namespace. This isn't really 6047 // correct, but it's good enough for this particular case. 6048 for (DeclContext::decl_iterator I = PrevNS->decls_begin(), 6049 E = PrevNS->decls_end(); I != E; ++I) 6050 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I)) 6051 PrevNS->getParent()->makeDeclVisibleInContext(ND); 6052 return; 6053 } 6054 6055 if (PrevNS->isInline()) 6056 // The user probably just forgot the 'inline', so suggest that it 6057 // be added back. 6058 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 6059 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 6060 else 6061 S.Diag(Loc, diag::err_inline_namespace_mismatch) 6062 << IsInline; 6063 6064 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 6065 *IsInline = PrevNS->isInline(); 6066} 6067 6068/// ActOnStartNamespaceDef - This is called at the start of a namespace 6069/// definition. 6070Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 6071 SourceLocation InlineLoc, 6072 SourceLocation NamespaceLoc, 6073 SourceLocation IdentLoc, 6074 IdentifierInfo *II, 6075 SourceLocation LBrace, 6076 AttributeList *AttrList) { 6077 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 6078 // For anonymous namespace, take the location of the left brace. 6079 SourceLocation Loc = II ? IdentLoc : LBrace; 6080 bool IsInline = InlineLoc.isValid(); 6081 bool IsInvalid = false; 6082 bool IsStd = false; 6083 bool AddToKnown = false; 6084 Scope *DeclRegionScope = NamespcScope->getParent(); 6085 6086 NamespaceDecl *PrevNS = 0; 6087 if (II) { 6088 // C++ [namespace.def]p2: 6089 // The identifier in an original-namespace-definition shall not 6090 // have been previously defined in the declarative region in 6091 // which the original-namespace-definition appears. The 6092 // identifier in an original-namespace-definition is the name of 6093 // the namespace. Subsequently in that declarative region, it is 6094 // treated as an original-namespace-name. 6095 // 6096 // Since namespace names are unique in their scope, and we don't 6097 // look through using directives, just look for any ordinary names. 6098 6099 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member | 6100 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag | 6101 Decl::IDNS_Namespace; 6102 NamedDecl *PrevDecl = 0; 6103 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II); 6104 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 6105 ++I) { 6106 if ((*I)->getIdentifierNamespace() & IDNS) { 6107 PrevDecl = *I; 6108 break; 6109 } 6110 } 6111 6112 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 6113 6114 if (PrevNS) { 6115 // This is an extended namespace definition. 6116 if (IsInline != PrevNS->isInline()) 6117 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 6118 &IsInline, PrevNS); 6119 } else if (PrevDecl) { 6120 // This is an invalid name redefinition. 6121 Diag(Loc, diag::err_redefinition_different_kind) 6122 << II; 6123 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 6124 IsInvalid = true; 6125 // Continue on to push Namespc as current DeclContext and return it. 6126 } else if (II->isStr("std") && 6127 CurContext->getRedeclContext()->isTranslationUnit()) { 6128 // This is the first "real" definition of the namespace "std", so update 6129 // our cache of the "std" namespace to point at this definition. 6130 PrevNS = getStdNamespace(); 6131 IsStd = true; 6132 AddToKnown = !IsInline; 6133 } else { 6134 // We've seen this namespace for the first time. 6135 AddToKnown = !IsInline; 6136 } 6137 } else { 6138 // Anonymous namespaces. 6139 6140 // Determine whether the parent already has an anonymous namespace. 6141 DeclContext *Parent = CurContext->getRedeclContext(); 6142 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 6143 PrevNS = TU->getAnonymousNamespace(); 6144 } else { 6145 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 6146 PrevNS = ND->getAnonymousNamespace(); 6147 } 6148 6149 if (PrevNS && IsInline != PrevNS->isInline()) 6150 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 6151 &IsInline, PrevNS); 6152 } 6153 6154 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 6155 StartLoc, Loc, II, PrevNS); 6156 if (IsInvalid) 6157 Namespc->setInvalidDecl(); 6158 6159 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 6160 6161 // FIXME: Should we be merging attributes? 6162 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 6163 PushNamespaceVisibilityAttr(Attr, Loc); 6164 6165 if (IsStd) 6166 StdNamespace = Namespc; 6167 if (AddToKnown) 6168 KnownNamespaces[Namespc] = false; 6169 6170 if (II) { 6171 PushOnScopeChains(Namespc, DeclRegionScope); 6172 } else { 6173 // Link the anonymous namespace into its parent. 6174 DeclContext *Parent = CurContext->getRedeclContext(); 6175 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 6176 TU->setAnonymousNamespace(Namespc); 6177 } else { 6178 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 6179 } 6180 6181 CurContext->addDecl(Namespc); 6182 6183 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 6184 // behaves as if it were replaced by 6185 // namespace unique { /* empty body */ } 6186 // using namespace unique; 6187 // namespace unique { namespace-body } 6188 // where all occurrences of 'unique' in a translation unit are 6189 // replaced by the same identifier and this identifier differs 6190 // from all other identifiers in the entire program. 6191 6192 // We just create the namespace with an empty name and then add an 6193 // implicit using declaration, just like the standard suggests. 6194 // 6195 // CodeGen enforces the "universally unique" aspect by giving all 6196 // declarations semantically contained within an anonymous 6197 // namespace internal linkage. 6198 6199 if (!PrevNS) { 6200 UsingDirectiveDecl* UD 6201 = UsingDirectiveDecl::Create(Context, Parent, 6202 /* 'using' */ LBrace, 6203 /* 'namespace' */ SourceLocation(), 6204 /* qualifier */ NestedNameSpecifierLoc(), 6205 /* identifier */ SourceLocation(), 6206 Namespc, 6207 /* Ancestor */ Parent); 6208 UD->setImplicit(); 6209 Parent->addDecl(UD); 6210 } 6211 } 6212 6213 ActOnDocumentableDecl(Namespc); 6214 6215 // Although we could have an invalid decl (i.e. the namespace name is a 6216 // redefinition), push it as current DeclContext and try to continue parsing. 6217 // FIXME: We should be able to push Namespc here, so that the each DeclContext 6218 // for the namespace has the declarations that showed up in that particular 6219 // namespace definition. 6220 PushDeclContext(NamespcScope, Namespc); 6221 return Namespc; 6222} 6223 6224/// getNamespaceDecl - Returns the namespace a decl represents. If the decl 6225/// is a namespace alias, returns the namespace it points to. 6226static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 6227 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 6228 return AD->getNamespace(); 6229 return dyn_cast_or_null<NamespaceDecl>(D); 6230} 6231 6232/// ActOnFinishNamespaceDef - This callback is called after a namespace is 6233/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 6234void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 6235 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 6236 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 6237 Namespc->setRBraceLoc(RBrace); 6238 PopDeclContext(); 6239 if (Namespc->hasAttr<VisibilityAttr>()) 6240 PopPragmaVisibility(true, RBrace); 6241} 6242 6243CXXRecordDecl *Sema::getStdBadAlloc() const { 6244 return cast_or_null<CXXRecordDecl>( 6245 StdBadAlloc.get(Context.getExternalSource())); 6246} 6247 6248NamespaceDecl *Sema::getStdNamespace() const { 6249 return cast_or_null<NamespaceDecl>( 6250 StdNamespace.get(Context.getExternalSource())); 6251} 6252 6253/// \brief Retrieve the special "std" namespace, which may require us to 6254/// implicitly define the namespace. 6255NamespaceDecl *Sema::getOrCreateStdNamespace() { 6256 if (!StdNamespace) { 6257 // The "std" namespace has not yet been defined, so build one implicitly. 6258 StdNamespace = NamespaceDecl::Create(Context, 6259 Context.getTranslationUnitDecl(), 6260 /*Inline=*/false, 6261 SourceLocation(), SourceLocation(), 6262 &PP.getIdentifierTable().get("std"), 6263 /*PrevDecl=*/0); 6264 getStdNamespace()->setImplicit(true); 6265 } 6266 6267 return getStdNamespace(); 6268} 6269 6270bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 6271 assert(getLangOpts().CPlusPlus && 6272 "Looking for std::initializer_list outside of C++."); 6273 6274 // We're looking for implicit instantiations of 6275 // template <typename E> class std::initializer_list. 6276 6277 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 6278 return false; 6279 6280 ClassTemplateDecl *Template = 0; 6281 const TemplateArgument *Arguments = 0; 6282 6283 if (const RecordType *RT = Ty->getAs<RecordType>()) { 6284 6285 ClassTemplateSpecializationDecl *Specialization = 6286 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 6287 if (!Specialization) 6288 return false; 6289 6290 Template = Specialization->getSpecializedTemplate(); 6291 Arguments = Specialization->getTemplateArgs().data(); 6292 } else if (const TemplateSpecializationType *TST = 6293 Ty->getAs<TemplateSpecializationType>()) { 6294 Template = dyn_cast_or_null<ClassTemplateDecl>( 6295 TST->getTemplateName().getAsTemplateDecl()); 6296 Arguments = TST->getArgs(); 6297 } 6298 if (!Template) 6299 return false; 6300 6301 if (!StdInitializerList) { 6302 // Haven't recognized std::initializer_list yet, maybe this is it. 6303 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 6304 if (TemplateClass->getIdentifier() != 6305 &PP.getIdentifierTable().get("initializer_list") || 6306 !getStdNamespace()->InEnclosingNamespaceSetOf( 6307 TemplateClass->getDeclContext())) 6308 return false; 6309 // This is a template called std::initializer_list, but is it the right 6310 // template? 6311 TemplateParameterList *Params = Template->getTemplateParameters(); 6312 if (Params->getMinRequiredArguments() != 1) 6313 return false; 6314 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 6315 return false; 6316 6317 // It's the right template. 6318 StdInitializerList = Template; 6319 } 6320 6321 if (Template != StdInitializerList) 6322 return false; 6323 6324 // This is an instance of std::initializer_list. Find the argument type. 6325 if (Element) 6326 *Element = Arguments[0].getAsType(); 6327 return true; 6328} 6329 6330static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 6331 NamespaceDecl *Std = S.getStdNamespace(); 6332 if (!Std) { 6333 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 6334 return 0; 6335 } 6336 6337 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 6338 Loc, Sema::LookupOrdinaryName); 6339 if (!S.LookupQualifiedName(Result, Std)) { 6340 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 6341 return 0; 6342 } 6343 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 6344 if (!Template) { 6345 Result.suppressDiagnostics(); 6346 // We found something weird. Complain about the first thing we found. 6347 NamedDecl *Found = *Result.begin(); 6348 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 6349 return 0; 6350 } 6351 6352 // We found some template called std::initializer_list. Now verify that it's 6353 // correct. 6354 TemplateParameterList *Params = Template->getTemplateParameters(); 6355 if (Params->getMinRequiredArguments() != 1 || 6356 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 6357 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 6358 return 0; 6359 } 6360 6361 return Template; 6362} 6363 6364QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 6365 if (!StdInitializerList) { 6366 StdInitializerList = LookupStdInitializerList(*this, Loc); 6367 if (!StdInitializerList) 6368 return QualType(); 6369 } 6370 6371 TemplateArgumentListInfo Args(Loc, Loc); 6372 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 6373 Context.getTrivialTypeSourceInfo(Element, 6374 Loc))); 6375 return Context.getCanonicalType( 6376 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 6377} 6378 6379bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) { 6380 // C++ [dcl.init.list]p2: 6381 // A constructor is an initializer-list constructor if its first parameter 6382 // is of type std::initializer_list<E> or reference to possibly cv-qualified 6383 // std::initializer_list<E> for some type E, and either there are no other 6384 // parameters or else all other parameters have default arguments. 6385 if (Ctor->getNumParams() < 1 || 6386 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 6387 return false; 6388 6389 QualType ArgType = Ctor->getParamDecl(0)->getType(); 6390 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 6391 ArgType = RT->getPointeeType().getUnqualifiedType(); 6392 6393 return isStdInitializerList(ArgType, 0); 6394} 6395 6396/// \brief Determine whether a using statement is in a context where it will be 6397/// apply in all contexts. 6398static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 6399 switch (CurContext->getDeclKind()) { 6400 case Decl::TranslationUnit: 6401 return true; 6402 case Decl::LinkageSpec: 6403 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 6404 default: 6405 return false; 6406 } 6407} 6408 6409namespace { 6410 6411// Callback to only accept typo corrections that are namespaces. 6412class NamespaceValidatorCCC : public CorrectionCandidateCallback { 6413 public: 6414 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 6415 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 6416 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 6417 } 6418 return false; 6419 } 6420}; 6421 6422} 6423 6424static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 6425 CXXScopeSpec &SS, 6426 SourceLocation IdentLoc, 6427 IdentifierInfo *Ident) { 6428 NamespaceValidatorCCC Validator; 6429 R.clear(); 6430 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(), 6431 R.getLookupKind(), Sc, &SS, 6432 Validator)) { 6433 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 6434 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts())); 6435 if (DeclContext *DC = S.computeDeclContext(SS, false)) 6436 S.Diag(IdentLoc, diag::err_using_directive_member_suggest) 6437 << Ident << DC << CorrectedQuotedStr << SS.getRange() 6438 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(), 6439 CorrectedStr); 6440 else 6441 S.Diag(IdentLoc, diag::err_using_directive_suggest) 6442 << Ident << CorrectedQuotedStr 6443 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr); 6444 6445 S.Diag(Corrected.getCorrectionDecl()->getLocation(), 6446 diag::note_namespace_defined_here) << CorrectedQuotedStr; 6447 6448 R.addDecl(Corrected.getCorrectionDecl()); 6449 return true; 6450 } 6451 return false; 6452} 6453 6454Decl *Sema::ActOnUsingDirective(Scope *S, 6455 SourceLocation UsingLoc, 6456 SourceLocation NamespcLoc, 6457 CXXScopeSpec &SS, 6458 SourceLocation IdentLoc, 6459 IdentifierInfo *NamespcName, 6460 AttributeList *AttrList) { 6461 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 6462 assert(NamespcName && "Invalid NamespcName."); 6463 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 6464 6465 // This can only happen along a recovery path. 6466 while (S->getFlags() & Scope::TemplateParamScope) 6467 S = S->getParent(); 6468 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 6469 6470 UsingDirectiveDecl *UDir = 0; 6471 NestedNameSpecifier *Qualifier = 0; 6472 if (SS.isSet()) 6473 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 6474 6475 // Lookup namespace name. 6476 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 6477 LookupParsedName(R, S, &SS); 6478 if (R.isAmbiguous()) 6479 return 0; 6480 6481 if (R.empty()) { 6482 R.clear(); 6483 // Allow "using namespace std;" or "using namespace ::std;" even if 6484 // "std" hasn't been defined yet, for GCC compatibility. 6485 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 6486 NamespcName->isStr("std")) { 6487 Diag(IdentLoc, diag::ext_using_undefined_std); 6488 R.addDecl(getOrCreateStdNamespace()); 6489 R.resolveKind(); 6490 } 6491 // Otherwise, attempt typo correction. 6492 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 6493 } 6494 6495 if (!R.empty()) { 6496 NamedDecl *Named = R.getFoundDecl(); 6497 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named)) 6498 && "expected namespace decl"); 6499 // C++ [namespace.udir]p1: 6500 // A using-directive specifies that the names in the nominated 6501 // namespace can be used in the scope in which the 6502 // using-directive appears after the using-directive. During 6503 // unqualified name lookup (3.4.1), the names appear as if they 6504 // were declared in the nearest enclosing namespace which 6505 // contains both the using-directive and the nominated 6506 // namespace. [Note: in this context, "contains" means "contains 6507 // directly or indirectly". ] 6508 6509 // Find enclosing context containing both using-directive and 6510 // nominated namespace. 6511 NamespaceDecl *NS = getNamespaceDecl(Named); 6512 DeclContext *CommonAncestor = cast<DeclContext>(NS); 6513 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 6514 CommonAncestor = CommonAncestor->getParent(); 6515 6516 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 6517 SS.getWithLocInContext(Context), 6518 IdentLoc, Named, CommonAncestor); 6519 6520 if (IsUsingDirectiveInToplevelContext(CurContext) && 6521 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 6522 Diag(IdentLoc, diag::warn_using_directive_in_header); 6523 } 6524 6525 PushUsingDirective(S, UDir); 6526 } else { 6527 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 6528 } 6529 6530 if (UDir) 6531 ProcessDeclAttributeList(S, UDir, AttrList); 6532 6533 return UDir; 6534} 6535 6536void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 6537 // If the scope has an associated entity and the using directive is at 6538 // namespace or translation unit scope, add the UsingDirectiveDecl into 6539 // its lookup structure so qualified name lookup can find it. 6540 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()); 6541 if (Ctx && !Ctx->isFunctionOrMethod()) 6542 Ctx->addDecl(UDir); 6543 else 6544 // Otherwise, it is at block sope. The using-directives will affect lookup 6545 // only to the end of the scope. 6546 S->PushUsingDirective(UDir); 6547} 6548 6549 6550Decl *Sema::ActOnUsingDeclaration(Scope *S, 6551 AccessSpecifier AS, 6552 bool HasUsingKeyword, 6553 SourceLocation UsingLoc, 6554 CXXScopeSpec &SS, 6555 UnqualifiedId &Name, 6556 AttributeList *AttrList, 6557 bool IsTypeName, 6558 SourceLocation TypenameLoc) { 6559 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 6560 6561 switch (Name.getKind()) { 6562 case UnqualifiedId::IK_ImplicitSelfParam: 6563 case UnqualifiedId::IK_Identifier: 6564 case UnqualifiedId::IK_OperatorFunctionId: 6565 case UnqualifiedId::IK_LiteralOperatorId: 6566 case UnqualifiedId::IK_ConversionFunctionId: 6567 break; 6568 6569 case UnqualifiedId::IK_ConstructorName: 6570 case UnqualifiedId::IK_ConstructorTemplateId: 6571 // C++11 inheriting constructors. 6572 Diag(Name.getLocStart(), 6573 getLangOpts().CPlusPlus11 ? 6574 diag::warn_cxx98_compat_using_decl_constructor : 6575 diag::err_using_decl_constructor) 6576 << SS.getRange(); 6577 6578 if (getLangOpts().CPlusPlus11) break; 6579 6580 return 0; 6581 6582 case UnqualifiedId::IK_DestructorName: 6583 Diag(Name.getLocStart(), diag::err_using_decl_destructor) 6584 << SS.getRange(); 6585 return 0; 6586 6587 case UnqualifiedId::IK_TemplateId: 6588 Diag(Name.getLocStart(), diag::err_using_decl_template_id) 6589 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 6590 return 0; 6591 } 6592 6593 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 6594 DeclarationName TargetName = TargetNameInfo.getName(); 6595 if (!TargetName) 6596 return 0; 6597 6598 // Warn about access declarations. 6599 // TODO: store that the declaration was written without 'using' and 6600 // talk about access decls instead of using decls in the 6601 // diagnostics. 6602 if (!HasUsingKeyword) { 6603 UsingLoc = Name.getLocStart(); 6604 6605 Diag(UsingLoc, diag::warn_access_decl_deprecated) 6606 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 6607 } 6608 6609 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 6610 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 6611 return 0; 6612 6613 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 6614 TargetNameInfo, AttrList, 6615 /* IsInstantiation */ false, 6616 IsTypeName, TypenameLoc); 6617 if (UD) 6618 PushOnScopeChains(UD, S, /*AddToContext*/ false); 6619 6620 return UD; 6621} 6622 6623/// \brief Determine whether a using declaration considers the given 6624/// declarations as "equivalent", e.g., if they are redeclarations of 6625/// the same entity or are both typedefs of the same type. 6626static bool 6627IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2, 6628 bool &SuppressRedeclaration) { 6629 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) { 6630 SuppressRedeclaration = false; 6631 return true; 6632 } 6633 6634 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 6635 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) { 6636 SuppressRedeclaration = true; 6637 return Context.hasSameType(TD1->getUnderlyingType(), 6638 TD2->getUnderlyingType()); 6639 } 6640 6641 return false; 6642} 6643 6644 6645/// Determines whether to create a using shadow decl for a particular 6646/// decl, given the set of decls existing prior to this using lookup. 6647bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 6648 const LookupResult &Previous) { 6649 // Diagnose finding a decl which is not from a base class of the 6650 // current class. We do this now because there are cases where this 6651 // function will silently decide not to build a shadow decl, which 6652 // will pre-empt further diagnostics. 6653 // 6654 // We don't need to do this in C++0x because we do the check once on 6655 // the qualifier. 6656 // 6657 // FIXME: diagnose the following if we care enough: 6658 // struct A { int foo; }; 6659 // struct B : A { using A::foo; }; 6660 // template <class T> struct C : A {}; 6661 // template <class T> struct D : C<T> { using B::foo; } // <--- 6662 // This is invalid (during instantiation) in C++03 because B::foo 6663 // resolves to the using decl in B, which is not a base class of D<T>. 6664 // We can't diagnose it immediately because C<T> is an unknown 6665 // specialization. The UsingShadowDecl in D<T> then points directly 6666 // to A::foo, which will look well-formed when we instantiate. 6667 // The right solution is to not collapse the shadow-decl chain. 6668 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 6669 DeclContext *OrigDC = Orig->getDeclContext(); 6670 6671 // Handle enums and anonymous structs. 6672 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 6673 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 6674 while (OrigRec->isAnonymousStructOrUnion()) 6675 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 6676 6677 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 6678 if (OrigDC == CurContext) { 6679 Diag(Using->getLocation(), 6680 diag::err_using_decl_nested_name_specifier_is_current_class) 6681 << Using->getQualifierLoc().getSourceRange(); 6682 Diag(Orig->getLocation(), diag::note_using_decl_target); 6683 return true; 6684 } 6685 6686 Diag(Using->getQualifierLoc().getBeginLoc(), 6687 diag::err_using_decl_nested_name_specifier_is_not_base_class) 6688 << Using->getQualifier() 6689 << cast<CXXRecordDecl>(CurContext) 6690 << Using->getQualifierLoc().getSourceRange(); 6691 Diag(Orig->getLocation(), diag::note_using_decl_target); 6692 return true; 6693 } 6694 } 6695 6696 if (Previous.empty()) return false; 6697 6698 NamedDecl *Target = Orig; 6699 if (isa<UsingShadowDecl>(Target)) 6700 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 6701 6702 // If the target happens to be one of the previous declarations, we 6703 // don't have a conflict. 6704 // 6705 // FIXME: but we might be increasing its access, in which case we 6706 // should redeclare it. 6707 NamedDecl *NonTag = 0, *Tag = 0; 6708 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 6709 I != E; ++I) { 6710 NamedDecl *D = (*I)->getUnderlyingDecl(); 6711 bool Result; 6712 if (IsEquivalentForUsingDecl(Context, D, Target, Result)) 6713 return Result; 6714 6715 (isa<TagDecl>(D) ? Tag : NonTag) = D; 6716 } 6717 6718 if (Target->isFunctionOrFunctionTemplate()) { 6719 FunctionDecl *FD; 6720 if (isa<FunctionTemplateDecl>(Target)) 6721 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl(); 6722 else 6723 FD = cast<FunctionDecl>(Target); 6724 6725 NamedDecl *OldDecl = 0; 6726 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) { 6727 case Ovl_Overload: 6728 return false; 6729 6730 case Ovl_NonFunction: 6731 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6732 break; 6733 6734 // We found a decl with the exact signature. 6735 case Ovl_Match: 6736 // If we're in a record, we want to hide the target, so we 6737 // return true (without a diagnostic) to tell the caller not to 6738 // build a shadow decl. 6739 if (CurContext->isRecord()) 6740 return true; 6741 6742 // If we're not in a record, this is an error. 6743 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6744 break; 6745 } 6746 6747 Diag(Target->getLocation(), diag::note_using_decl_target); 6748 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 6749 return true; 6750 } 6751 6752 // Target is not a function. 6753 6754 if (isa<TagDecl>(Target)) { 6755 // No conflict between a tag and a non-tag. 6756 if (!Tag) return false; 6757 6758 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6759 Diag(Target->getLocation(), diag::note_using_decl_target); 6760 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 6761 return true; 6762 } 6763 6764 // No conflict between a tag and a non-tag. 6765 if (!NonTag) return false; 6766 6767 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6768 Diag(Target->getLocation(), diag::note_using_decl_target); 6769 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 6770 return true; 6771} 6772 6773/// Builds a shadow declaration corresponding to a 'using' declaration. 6774UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 6775 UsingDecl *UD, 6776 NamedDecl *Orig) { 6777 6778 // If we resolved to another shadow declaration, just coalesce them. 6779 NamedDecl *Target = Orig; 6780 if (isa<UsingShadowDecl>(Target)) { 6781 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 6782 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 6783 } 6784 6785 UsingShadowDecl *Shadow 6786 = UsingShadowDecl::Create(Context, CurContext, 6787 UD->getLocation(), UD, Target); 6788 UD->addShadowDecl(Shadow); 6789 6790 Shadow->setAccess(UD->getAccess()); 6791 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 6792 Shadow->setInvalidDecl(); 6793 6794 if (S) 6795 PushOnScopeChains(Shadow, S); 6796 else 6797 CurContext->addDecl(Shadow); 6798 6799 6800 return Shadow; 6801} 6802 6803/// Hides a using shadow declaration. This is required by the current 6804/// using-decl implementation when a resolvable using declaration in a 6805/// class is followed by a declaration which would hide or override 6806/// one or more of the using decl's targets; for example: 6807/// 6808/// struct Base { void foo(int); }; 6809/// struct Derived : Base { 6810/// using Base::foo; 6811/// void foo(int); 6812/// }; 6813/// 6814/// The governing language is C++03 [namespace.udecl]p12: 6815/// 6816/// When a using-declaration brings names from a base class into a 6817/// derived class scope, member functions in the derived class 6818/// override and/or hide member functions with the same name and 6819/// parameter types in a base class (rather than conflicting). 6820/// 6821/// There are two ways to implement this: 6822/// (1) optimistically create shadow decls when they're not hidden 6823/// by existing declarations, or 6824/// (2) don't create any shadow decls (or at least don't make them 6825/// visible) until we've fully parsed/instantiated the class. 6826/// The problem with (1) is that we might have to retroactively remove 6827/// a shadow decl, which requires several O(n) operations because the 6828/// decl structures are (very reasonably) not designed for removal. 6829/// (2) avoids this but is very fiddly and phase-dependent. 6830void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 6831 if (Shadow->getDeclName().getNameKind() == 6832 DeclarationName::CXXConversionFunctionName) 6833 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 6834 6835 // Remove it from the DeclContext... 6836 Shadow->getDeclContext()->removeDecl(Shadow); 6837 6838 // ...and the scope, if applicable... 6839 if (S) { 6840 S->RemoveDecl(Shadow); 6841 IdResolver.RemoveDecl(Shadow); 6842 } 6843 6844 // ...and the using decl. 6845 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 6846 6847 // TODO: complain somehow if Shadow was used. It shouldn't 6848 // be possible for this to happen, because...? 6849} 6850 6851/// Builds a using declaration. 6852/// 6853/// \param IsInstantiation - Whether this call arises from an 6854/// instantiation of an unresolved using declaration. We treat 6855/// the lookup differently for these declarations. 6856NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 6857 SourceLocation UsingLoc, 6858 CXXScopeSpec &SS, 6859 const DeclarationNameInfo &NameInfo, 6860 AttributeList *AttrList, 6861 bool IsInstantiation, 6862 bool IsTypeName, 6863 SourceLocation TypenameLoc) { 6864 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 6865 SourceLocation IdentLoc = NameInfo.getLoc(); 6866 assert(IdentLoc.isValid() && "Invalid TargetName location."); 6867 6868 // FIXME: We ignore attributes for now. 6869 6870 if (SS.isEmpty()) { 6871 Diag(IdentLoc, diag::err_using_requires_qualname); 6872 return 0; 6873 } 6874 6875 // Do the redeclaration lookup in the current scope. 6876 LookupResult Previous(*this, NameInfo, LookupUsingDeclName, 6877 ForRedeclaration); 6878 Previous.setHideTags(false); 6879 if (S) { 6880 LookupName(Previous, S); 6881 6882 // It is really dumb that we have to do this. 6883 LookupResult::Filter F = Previous.makeFilter(); 6884 while (F.hasNext()) { 6885 NamedDecl *D = F.next(); 6886 if (!isDeclInScope(D, CurContext, S)) 6887 F.erase(); 6888 } 6889 F.done(); 6890 } else { 6891 assert(IsInstantiation && "no scope in non-instantiation"); 6892 assert(CurContext->isRecord() && "scope not record in instantiation"); 6893 LookupQualifiedName(Previous, CurContext); 6894 } 6895 6896 // Check for invalid redeclarations. 6897 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous)) 6898 return 0; 6899 6900 // Check for bad qualifiers. 6901 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc)) 6902 return 0; 6903 6904 DeclContext *LookupContext = computeDeclContext(SS); 6905 NamedDecl *D; 6906 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 6907 if (!LookupContext) { 6908 if (IsTypeName) { 6909 // FIXME: not all declaration name kinds are legal here 6910 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 6911 UsingLoc, TypenameLoc, 6912 QualifierLoc, 6913 IdentLoc, NameInfo.getName()); 6914 } else { 6915 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 6916 QualifierLoc, NameInfo); 6917 } 6918 } else { 6919 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 6920 NameInfo, IsTypeName); 6921 } 6922 D->setAccess(AS); 6923 CurContext->addDecl(D); 6924 6925 if (!LookupContext) return D; 6926 UsingDecl *UD = cast<UsingDecl>(D); 6927 6928 if (RequireCompleteDeclContext(SS, LookupContext)) { 6929 UD->setInvalidDecl(); 6930 return UD; 6931 } 6932 6933 // The normal rules do not apply to inheriting constructor declarations. 6934 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) { 6935 if (CheckInheritingConstructorUsingDecl(UD)) 6936 UD->setInvalidDecl(); 6937 return UD; 6938 } 6939 6940 // Otherwise, look up the target name. 6941 6942 LookupResult R(*this, NameInfo, LookupOrdinaryName); 6943 6944 // Unlike most lookups, we don't always want to hide tag 6945 // declarations: tag names are visible through the using declaration 6946 // even if hidden by ordinary names, *except* in a dependent context 6947 // where it's important for the sanity of two-phase lookup. 6948 if (!IsInstantiation) 6949 R.setHideTags(false); 6950 6951 // For the purposes of this lookup, we have a base object type 6952 // equal to that of the current context. 6953 if (CurContext->isRecord()) { 6954 R.setBaseObjectType( 6955 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 6956 } 6957 6958 LookupQualifiedName(R, LookupContext); 6959 6960 if (R.empty()) { 6961 Diag(IdentLoc, diag::err_no_member) 6962 << NameInfo.getName() << LookupContext << SS.getRange(); 6963 UD->setInvalidDecl(); 6964 return UD; 6965 } 6966 6967 if (R.isAmbiguous()) { 6968 UD->setInvalidDecl(); 6969 return UD; 6970 } 6971 6972 if (IsTypeName) { 6973 // If we asked for a typename and got a non-type decl, error out. 6974 if (!R.getAsSingle<TypeDecl>()) { 6975 Diag(IdentLoc, diag::err_using_typename_non_type); 6976 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 6977 Diag((*I)->getUnderlyingDecl()->getLocation(), 6978 diag::note_using_decl_target); 6979 UD->setInvalidDecl(); 6980 return UD; 6981 } 6982 } else { 6983 // If we asked for a non-typename and we got a type, error out, 6984 // but only if this is an instantiation of an unresolved using 6985 // decl. Otherwise just silently find the type name. 6986 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 6987 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 6988 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 6989 UD->setInvalidDecl(); 6990 return UD; 6991 } 6992 } 6993 6994 // C++0x N2914 [namespace.udecl]p6: 6995 // A using-declaration shall not name a namespace. 6996 if (R.getAsSingle<NamespaceDecl>()) { 6997 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 6998 << SS.getRange(); 6999 UD->setInvalidDecl(); 7000 return UD; 7001 } 7002 7003 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 7004 if (!CheckUsingShadowDecl(UD, *I, Previous)) 7005 BuildUsingShadowDecl(S, UD, *I); 7006 } 7007 7008 return UD; 7009} 7010 7011/// Additional checks for a using declaration referring to a constructor name. 7012bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 7013 assert(!UD->isTypeName() && "expecting a constructor name"); 7014 7015 const Type *SourceType = UD->getQualifier()->getAsType(); 7016 assert(SourceType && 7017 "Using decl naming constructor doesn't have type in scope spec."); 7018 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 7019 7020 // Check whether the named type is a direct base class. 7021 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified(); 7022 CXXRecordDecl::base_class_iterator BaseIt, BaseE; 7023 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end(); 7024 BaseIt != BaseE; ++BaseIt) { 7025 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified(); 7026 if (CanonicalSourceType == BaseType) 7027 break; 7028 if (BaseIt->getType()->isDependentType()) 7029 break; 7030 } 7031 7032 if (BaseIt == BaseE) { 7033 // Did not find SourceType in the bases. 7034 Diag(UD->getUsingLocation(), 7035 diag::err_using_decl_constructor_not_in_direct_base) 7036 << UD->getNameInfo().getSourceRange() 7037 << QualType(SourceType, 0) << TargetClass; 7038 return true; 7039 } 7040 7041 if (!CurContext->isDependentContext()) 7042 BaseIt->setInheritConstructors(); 7043 7044 return false; 7045} 7046 7047/// Checks that the given using declaration is not an invalid 7048/// redeclaration. Note that this is checking only for the using decl 7049/// itself, not for any ill-formedness among the UsingShadowDecls. 7050bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 7051 bool isTypeName, 7052 const CXXScopeSpec &SS, 7053 SourceLocation NameLoc, 7054 const LookupResult &Prev) { 7055 // C++03 [namespace.udecl]p8: 7056 // C++0x [namespace.udecl]p10: 7057 // A using-declaration is a declaration and can therefore be used 7058 // repeatedly where (and only where) multiple declarations are 7059 // allowed. 7060 // 7061 // That's in non-member contexts. 7062 if (!CurContext->getRedeclContext()->isRecord()) 7063 return false; 7064 7065 NestedNameSpecifier *Qual 7066 = static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 7067 7068 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 7069 NamedDecl *D = *I; 7070 7071 bool DTypename; 7072 NestedNameSpecifier *DQual; 7073 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 7074 DTypename = UD->isTypeName(); 7075 DQual = UD->getQualifier(); 7076 } else if (UnresolvedUsingValueDecl *UD 7077 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 7078 DTypename = false; 7079 DQual = UD->getQualifier(); 7080 } else if (UnresolvedUsingTypenameDecl *UD 7081 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 7082 DTypename = true; 7083 DQual = UD->getQualifier(); 7084 } else continue; 7085 7086 // using decls differ if one says 'typename' and the other doesn't. 7087 // FIXME: non-dependent using decls? 7088 if (isTypeName != DTypename) continue; 7089 7090 // using decls differ if they name different scopes (but note that 7091 // template instantiation can cause this check to trigger when it 7092 // didn't before instantiation). 7093 if (Context.getCanonicalNestedNameSpecifier(Qual) != 7094 Context.getCanonicalNestedNameSpecifier(DQual)) 7095 continue; 7096 7097 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 7098 Diag(D->getLocation(), diag::note_using_decl) << 1; 7099 return true; 7100 } 7101 7102 return false; 7103} 7104 7105 7106/// Checks that the given nested-name qualifier used in a using decl 7107/// in the current context is appropriately related to the current 7108/// scope. If an error is found, diagnoses it and returns true. 7109bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 7110 const CXXScopeSpec &SS, 7111 SourceLocation NameLoc) { 7112 DeclContext *NamedContext = computeDeclContext(SS); 7113 7114 if (!CurContext->isRecord()) { 7115 // C++03 [namespace.udecl]p3: 7116 // C++0x [namespace.udecl]p8: 7117 // A using-declaration for a class member shall be a member-declaration. 7118 7119 // If we weren't able to compute a valid scope, it must be a 7120 // dependent class scope. 7121 if (!NamedContext || NamedContext->isRecord()) { 7122 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 7123 << SS.getRange(); 7124 return true; 7125 } 7126 7127 // Otherwise, everything is known to be fine. 7128 return false; 7129 } 7130 7131 // The current scope is a record. 7132 7133 // If the named context is dependent, we can't decide much. 7134 if (!NamedContext) { 7135 // FIXME: in C++0x, we can diagnose if we can prove that the 7136 // nested-name-specifier does not refer to a base class, which is 7137 // still possible in some cases. 7138 7139 // Otherwise we have to conservatively report that things might be 7140 // okay. 7141 return false; 7142 } 7143 7144 if (!NamedContext->isRecord()) { 7145 // Ideally this would point at the last name in the specifier, 7146 // but we don't have that level of source info. 7147 Diag(SS.getRange().getBegin(), 7148 diag::err_using_decl_nested_name_specifier_is_not_class) 7149 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange(); 7150 return true; 7151 } 7152 7153 if (!NamedContext->isDependentContext() && 7154 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 7155 return true; 7156 7157 if (getLangOpts().CPlusPlus11) { 7158 // C++0x [namespace.udecl]p3: 7159 // In a using-declaration used as a member-declaration, the 7160 // nested-name-specifier shall name a base class of the class 7161 // being defined. 7162 7163 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 7164 cast<CXXRecordDecl>(NamedContext))) { 7165 if (CurContext == NamedContext) { 7166 Diag(NameLoc, 7167 diag::err_using_decl_nested_name_specifier_is_current_class) 7168 << SS.getRange(); 7169 return true; 7170 } 7171 7172 Diag(SS.getRange().getBegin(), 7173 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7174 << (NestedNameSpecifier*) SS.getScopeRep() 7175 << cast<CXXRecordDecl>(CurContext) 7176 << SS.getRange(); 7177 return true; 7178 } 7179 7180 return false; 7181 } 7182 7183 // C++03 [namespace.udecl]p4: 7184 // A using-declaration used as a member-declaration shall refer 7185 // to a member of a base class of the class being defined [etc.]. 7186 7187 // Salient point: SS doesn't have to name a base class as long as 7188 // lookup only finds members from base classes. Therefore we can 7189 // diagnose here only if we can prove that that can't happen, 7190 // i.e. if the class hierarchies provably don't intersect. 7191 7192 // TODO: it would be nice if "definitely valid" results were cached 7193 // in the UsingDecl and UsingShadowDecl so that these checks didn't 7194 // need to be repeated. 7195 7196 struct UserData { 7197 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases; 7198 7199 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) { 7200 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 7201 Data->Bases.insert(Base); 7202 return true; 7203 } 7204 7205 bool hasDependentBases(const CXXRecordDecl *Class) { 7206 return !Class->forallBases(collect, this); 7207 } 7208 7209 /// Returns true if the base is dependent or is one of the 7210 /// accumulated base classes. 7211 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) { 7212 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 7213 return !Data->Bases.count(Base); 7214 } 7215 7216 bool mightShareBases(const CXXRecordDecl *Class) { 7217 return Bases.count(Class) || !Class->forallBases(doesNotContain, this); 7218 } 7219 }; 7220 7221 UserData Data; 7222 7223 // Returns false if we find a dependent base. 7224 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext))) 7225 return false; 7226 7227 // Returns false if the class has a dependent base or if it or one 7228 // of its bases is present in the base set of the current context. 7229 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext))) 7230 return false; 7231 7232 Diag(SS.getRange().getBegin(), 7233 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7234 << (NestedNameSpecifier*) SS.getScopeRep() 7235 << cast<CXXRecordDecl>(CurContext) 7236 << SS.getRange(); 7237 7238 return true; 7239} 7240 7241Decl *Sema::ActOnAliasDeclaration(Scope *S, 7242 AccessSpecifier AS, 7243 MultiTemplateParamsArg TemplateParamLists, 7244 SourceLocation UsingLoc, 7245 UnqualifiedId &Name, 7246 AttributeList *AttrList, 7247 TypeResult Type) { 7248 // Skip up to the relevant declaration scope. 7249 while (S->getFlags() & Scope::TemplateParamScope) 7250 S = S->getParent(); 7251 assert((S->getFlags() & Scope::DeclScope) && 7252 "got alias-declaration outside of declaration scope"); 7253 7254 if (Type.isInvalid()) 7255 return 0; 7256 7257 bool Invalid = false; 7258 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 7259 TypeSourceInfo *TInfo = 0; 7260 GetTypeFromParser(Type.get(), &TInfo); 7261 7262 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 7263 return 0; 7264 7265 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 7266 UPPC_DeclarationType)) { 7267 Invalid = true; 7268 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 7269 TInfo->getTypeLoc().getBeginLoc()); 7270 } 7271 7272 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration); 7273 LookupName(Previous, S); 7274 7275 // Warn about shadowing the name of a template parameter. 7276 if (Previous.isSingleResult() && 7277 Previous.getFoundDecl()->isTemplateParameter()) { 7278 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 7279 Previous.clear(); 7280 } 7281 7282 assert(Name.Kind == UnqualifiedId::IK_Identifier && 7283 "name in alias declaration must be an identifier"); 7284 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 7285 Name.StartLocation, 7286 Name.Identifier, TInfo); 7287 7288 NewTD->setAccess(AS); 7289 7290 if (Invalid) 7291 NewTD->setInvalidDecl(); 7292 7293 ProcessDeclAttributeList(S, NewTD, AttrList); 7294 7295 CheckTypedefForVariablyModifiedType(S, NewTD); 7296 Invalid |= NewTD->isInvalidDecl(); 7297 7298 bool Redeclaration = false; 7299 7300 NamedDecl *NewND; 7301 if (TemplateParamLists.size()) { 7302 TypeAliasTemplateDecl *OldDecl = 0; 7303 TemplateParameterList *OldTemplateParams = 0; 7304 7305 if (TemplateParamLists.size() != 1) { 7306 Diag(UsingLoc, diag::err_alias_template_extra_headers) 7307 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 7308 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 7309 } 7310 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 7311 7312 // Only consider previous declarations in the same scope. 7313 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 7314 /*ExplicitInstantiationOrSpecialization*/false); 7315 if (!Previous.empty()) { 7316 Redeclaration = true; 7317 7318 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 7319 if (!OldDecl && !Invalid) { 7320 Diag(UsingLoc, diag::err_redefinition_different_kind) 7321 << Name.Identifier; 7322 7323 NamedDecl *OldD = Previous.getRepresentativeDecl(); 7324 if (OldD->getLocation().isValid()) 7325 Diag(OldD->getLocation(), diag::note_previous_definition); 7326 7327 Invalid = true; 7328 } 7329 7330 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 7331 if (TemplateParameterListsAreEqual(TemplateParams, 7332 OldDecl->getTemplateParameters(), 7333 /*Complain=*/true, 7334 TPL_TemplateMatch)) 7335 OldTemplateParams = OldDecl->getTemplateParameters(); 7336 else 7337 Invalid = true; 7338 7339 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 7340 if (!Invalid && 7341 !Context.hasSameType(OldTD->getUnderlyingType(), 7342 NewTD->getUnderlyingType())) { 7343 // FIXME: The C++0x standard does not clearly say this is ill-formed, 7344 // but we can't reasonably accept it. 7345 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 7346 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 7347 if (OldTD->getLocation().isValid()) 7348 Diag(OldTD->getLocation(), diag::note_previous_definition); 7349 Invalid = true; 7350 } 7351 } 7352 } 7353 7354 // Merge any previous default template arguments into our parameters, 7355 // and check the parameter list. 7356 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 7357 TPC_TypeAliasTemplate)) 7358 return 0; 7359 7360 TypeAliasTemplateDecl *NewDecl = 7361 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 7362 Name.Identifier, TemplateParams, 7363 NewTD); 7364 7365 NewDecl->setAccess(AS); 7366 7367 if (Invalid) 7368 NewDecl->setInvalidDecl(); 7369 else if (OldDecl) 7370 NewDecl->setPreviousDeclaration(OldDecl); 7371 7372 NewND = NewDecl; 7373 } else { 7374 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 7375 NewND = NewTD; 7376 } 7377 7378 if (!Redeclaration) 7379 PushOnScopeChains(NewND, S); 7380 7381 ActOnDocumentableDecl(NewND); 7382 return NewND; 7383} 7384 7385Decl *Sema::ActOnNamespaceAliasDef(Scope *S, 7386 SourceLocation NamespaceLoc, 7387 SourceLocation AliasLoc, 7388 IdentifierInfo *Alias, 7389 CXXScopeSpec &SS, 7390 SourceLocation IdentLoc, 7391 IdentifierInfo *Ident) { 7392 7393 // Lookup the namespace name. 7394 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 7395 LookupParsedName(R, S, &SS); 7396 7397 // Check if we have a previous declaration with the same name. 7398 NamedDecl *PrevDecl 7399 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName, 7400 ForRedeclaration); 7401 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S)) 7402 PrevDecl = 0; 7403 7404 if (PrevDecl) { 7405 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 7406 // We already have an alias with the same name that points to the same 7407 // namespace, so don't create a new one. 7408 // FIXME: At some point, we'll want to create the (redundant) 7409 // declaration to maintain better source information. 7410 if (!R.isAmbiguous() && !R.empty() && 7411 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl()))) 7412 return 0; 7413 } 7414 7415 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition : 7416 diag::err_redefinition_different_kind; 7417 Diag(AliasLoc, DiagID) << Alias; 7418 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 7419 return 0; 7420 } 7421 7422 if (R.isAmbiguous()) 7423 return 0; 7424 7425 if (R.empty()) { 7426 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 7427 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 7428 return 0; 7429 } 7430 } 7431 7432 NamespaceAliasDecl *AliasDecl = 7433 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 7434 Alias, SS.getWithLocInContext(Context), 7435 IdentLoc, R.getFoundDecl()); 7436 7437 PushOnScopeChains(AliasDecl, S); 7438 return AliasDecl; 7439} 7440 7441Sema::ImplicitExceptionSpecification 7442Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, 7443 CXXMethodDecl *MD) { 7444 CXXRecordDecl *ClassDecl = MD->getParent(); 7445 7446 // C++ [except.spec]p14: 7447 // An implicitly declared special member function (Clause 12) shall have an 7448 // exception-specification. [...] 7449 ImplicitExceptionSpecification ExceptSpec(*this); 7450 if (ClassDecl->isInvalidDecl()) 7451 return ExceptSpec; 7452 7453 // Direct base-class constructors. 7454 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 7455 BEnd = ClassDecl->bases_end(); 7456 B != BEnd; ++B) { 7457 if (B->isVirtual()) // Handled below. 7458 continue; 7459 7460 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 7461 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7462 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 7463 // If this is a deleted function, add it anyway. This might be conformant 7464 // with the standard. This might not. I'm not sure. It might not matter. 7465 if (Constructor) 7466 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 7467 } 7468 } 7469 7470 // Virtual base-class constructors. 7471 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 7472 BEnd = ClassDecl->vbases_end(); 7473 B != BEnd; ++B) { 7474 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 7475 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7476 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 7477 // If this is a deleted function, add it anyway. This might be conformant 7478 // with the standard. This might not. I'm not sure. It might not matter. 7479 if (Constructor) 7480 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 7481 } 7482 } 7483 7484 // Field constructors. 7485 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 7486 FEnd = ClassDecl->field_end(); 7487 F != FEnd; ++F) { 7488 if (F->hasInClassInitializer()) { 7489 if (Expr *E = F->getInClassInitializer()) 7490 ExceptSpec.CalledExpr(E); 7491 else if (!F->isInvalidDecl()) 7492 // DR1351: 7493 // If the brace-or-equal-initializer of a non-static data member 7494 // invokes a defaulted default constructor of its class or of an 7495 // enclosing class in a potentially evaluated subexpression, the 7496 // program is ill-formed. 7497 // 7498 // This resolution is unworkable: the exception specification of the 7499 // default constructor can be needed in an unevaluated context, in 7500 // particular, in the operand of a noexcept-expression, and we can be 7501 // unable to compute an exception specification for an enclosed class. 7502 // 7503 // We do not allow an in-class initializer to require the evaluation 7504 // of the exception specification for any in-class initializer whose 7505 // definition is not lexically complete. 7506 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD; 7507 } else if (const RecordType *RecordTy 7508 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 7509 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 7510 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 7511 // If this is a deleted function, add it anyway. This might be conformant 7512 // with the standard. This might not. I'm not sure. It might not matter. 7513 // In particular, the problem is that this function never gets called. It 7514 // might just be ill-formed because this function attempts to refer to 7515 // a deleted function here. 7516 if (Constructor) 7517 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 7518 } 7519 } 7520 7521 return ExceptSpec; 7522} 7523 7524Sema::ImplicitExceptionSpecification 7525Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) { 7526 CXXRecordDecl *ClassDecl = CD->getParent(); 7527 7528 // C++ [except.spec]p14: 7529 // An inheriting constructor [...] shall have an exception-specification. [...] 7530 ImplicitExceptionSpecification ExceptSpec(*this); 7531 if (ClassDecl->isInvalidDecl()) 7532 return ExceptSpec; 7533 7534 // Inherited constructor. 7535 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor(); 7536 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent(); 7537 // FIXME: Copying or moving the parameters could add extra exceptions to the 7538 // set, as could the default arguments for the inherited constructor. This 7539 // will be addressed when we implement the resolution of core issue 1351. 7540 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD); 7541 7542 // Direct base-class constructors. 7543 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 7544 BEnd = ClassDecl->bases_end(); 7545 B != BEnd; ++B) { 7546 if (B->isVirtual()) // Handled below. 7547 continue; 7548 7549 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 7550 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7551 if (BaseClassDecl == InheritedDecl) 7552 continue; 7553 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 7554 if (Constructor) 7555 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 7556 } 7557 } 7558 7559 // Virtual base-class constructors. 7560 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 7561 BEnd = ClassDecl->vbases_end(); 7562 B != BEnd; ++B) { 7563 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 7564 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7565 if (BaseClassDecl == InheritedDecl) 7566 continue; 7567 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 7568 if (Constructor) 7569 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 7570 } 7571 } 7572 7573 // Field constructors. 7574 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 7575 FEnd = ClassDecl->field_end(); 7576 F != FEnd; ++F) { 7577 if (F->hasInClassInitializer()) { 7578 if (Expr *E = F->getInClassInitializer()) 7579 ExceptSpec.CalledExpr(E); 7580 else if (!F->isInvalidDecl()) 7581 Diag(CD->getLocation(), 7582 diag::err_in_class_initializer_references_def_ctor) << CD; 7583 } else if (const RecordType *RecordTy 7584 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 7585 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 7586 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 7587 if (Constructor) 7588 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 7589 } 7590 } 7591 7592 return ExceptSpec; 7593} 7594 7595namespace { 7596/// RAII object to register a special member as being currently declared. 7597struct DeclaringSpecialMember { 7598 Sema &S; 7599 Sema::SpecialMemberDecl D; 7600 bool WasAlreadyBeingDeclared; 7601 7602 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 7603 : S(S), D(RD, CSM) { 7604 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D); 7605 if (WasAlreadyBeingDeclared) 7606 // This almost never happens, but if it does, ensure that our cache 7607 // doesn't contain a stale result. 7608 S.SpecialMemberCache.clear(); 7609 7610 // FIXME: Register a note to be produced if we encounter an error while 7611 // declaring the special member. 7612 } 7613 ~DeclaringSpecialMember() { 7614 if (!WasAlreadyBeingDeclared) 7615 S.SpecialMembersBeingDeclared.erase(D); 7616 } 7617 7618 /// \brief Are we already trying to declare this special member? 7619 bool isAlreadyBeingDeclared() const { 7620 return WasAlreadyBeingDeclared; 7621 } 7622}; 7623} 7624 7625CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 7626 CXXRecordDecl *ClassDecl) { 7627 // C++ [class.ctor]p5: 7628 // A default constructor for a class X is a constructor of class X 7629 // that can be called without an argument. If there is no 7630 // user-declared constructor for class X, a default constructor is 7631 // implicitly declared. An implicitly-declared default constructor 7632 // is an inline public member of its class. 7633 assert(ClassDecl->needsImplicitDefaultConstructor() && 7634 "Should not build implicit default constructor!"); 7635 7636 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 7637 if (DSM.isAlreadyBeingDeclared()) 7638 return 0; 7639 7640 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 7641 CXXDefaultConstructor, 7642 false); 7643 7644 // Create the actual constructor declaration. 7645 CanQualType ClassType 7646 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 7647 SourceLocation ClassLoc = ClassDecl->getLocation(); 7648 DeclarationName Name 7649 = Context.DeclarationNames.getCXXConstructorName(ClassType); 7650 DeclarationNameInfo NameInfo(Name, ClassLoc); 7651 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 7652 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0, 7653 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 7654 Constexpr); 7655 DefaultCon->setAccess(AS_public); 7656 DefaultCon->setDefaulted(); 7657 DefaultCon->setImplicit(); 7658 7659 // Build an exception specification pointing back at this constructor. 7660 FunctionProtoType::ExtProtoInfo EPI; 7661 EPI.ExceptionSpecType = EST_Unevaluated; 7662 EPI.ExceptionSpecDecl = DefaultCon; 7663 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, 7664 ArrayRef<QualType>(), 7665 EPI)); 7666 7667 // We don't need to use SpecialMemberIsTrivial here; triviality for default 7668 // constructors is easy to compute. 7669 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 7670 7671 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 7672 SetDeclDeleted(DefaultCon, ClassLoc); 7673 7674 // Note that we have declared this constructor. 7675 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 7676 7677 if (Scope *S = getScopeForContext(ClassDecl)) 7678 PushOnScopeChains(DefaultCon, S, false); 7679 ClassDecl->addDecl(DefaultCon); 7680 7681 return DefaultCon; 7682} 7683 7684void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 7685 CXXConstructorDecl *Constructor) { 7686 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 7687 !Constructor->doesThisDeclarationHaveABody() && 7688 !Constructor->isDeleted()) && 7689 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 7690 7691 CXXRecordDecl *ClassDecl = Constructor->getParent(); 7692 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 7693 7694 SynthesizedFunctionScope Scope(*this, Constructor); 7695 DiagnosticErrorTrap Trap(Diags); 7696 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 7697 Trap.hasErrorOccurred()) { 7698 Diag(CurrentLocation, diag::note_member_synthesized_at) 7699 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl); 7700 Constructor->setInvalidDecl(); 7701 return; 7702 } 7703 7704 SourceLocation Loc = Constructor->getLocation(); 7705 Constructor->setBody(new (Context) CompoundStmt(Loc)); 7706 7707 Constructor->setUsed(); 7708 MarkVTableUsed(CurrentLocation, ClassDecl); 7709 7710 if (ASTMutationListener *L = getASTMutationListener()) { 7711 L->CompletedImplicitDefinition(Constructor); 7712 } 7713} 7714 7715void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 7716 // Check that any explicitly-defaulted methods have exception specifications 7717 // compatible with their implicit exception specifications. 7718 CheckDelayedExplicitlyDefaultedMemberExceptionSpecs(); 7719} 7720 7721namespace { 7722/// Information on inheriting constructors to declare. 7723class InheritingConstructorInfo { 7724public: 7725 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived) 7726 : SemaRef(SemaRef), Derived(Derived) { 7727 // Mark the constructors that we already have in the derived class. 7728 // 7729 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...] 7730 // unless there is a user-declared constructor with the same signature in 7731 // the class where the using-declaration appears. 7732 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived); 7733 } 7734 7735 void inheritAll(CXXRecordDecl *RD) { 7736 visitAll(RD, &InheritingConstructorInfo::inherit); 7737 } 7738 7739private: 7740 /// Information about an inheriting constructor. 7741 struct InheritingConstructor { 7742 InheritingConstructor() 7743 : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {} 7744 7745 /// If \c true, a constructor with this signature is already declared 7746 /// in the derived class. 7747 bool DeclaredInDerived; 7748 7749 /// The constructor which is inherited. 7750 const CXXConstructorDecl *BaseCtor; 7751 7752 /// The derived constructor we declared. 7753 CXXConstructorDecl *DerivedCtor; 7754 }; 7755 7756 /// Inheriting constructors with a given canonical type. There can be at 7757 /// most one such non-template constructor, and any number of templated 7758 /// constructors. 7759 struct InheritingConstructorsForType { 7760 InheritingConstructor NonTemplate; 7761 llvm::SmallVector< 7762 std::pair<TemplateParameterList*, InheritingConstructor>, 4> Templates; 7763 7764 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) { 7765 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) { 7766 TemplateParameterList *ParamList = FTD->getTemplateParameters(); 7767 for (unsigned I = 0, N = Templates.size(); I != N; ++I) 7768 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first, 7769 false, S.TPL_TemplateMatch)) 7770 return Templates[I].second; 7771 Templates.push_back(std::make_pair(ParamList, InheritingConstructor())); 7772 return Templates.back().second; 7773 } 7774 7775 return NonTemplate; 7776 } 7777 }; 7778 7779 /// Get or create the inheriting constructor record for a constructor. 7780 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor, 7781 QualType CtorType) { 7782 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()] 7783 .getEntry(SemaRef, Ctor); 7784 } 7785 7786 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*); 7787 7788 /// Process all constructors for a class. 7789 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) { 7790 for (CXXRecordDecl::ctor_iterator CtorIt = RD->ctor_begin(), 7791 CtorE = RD->ctor_end(); 7792 CtorIt != CtorE; ++CtorIt) 7793 (this->*Callback)(*CtorIt); 7794 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> 7795 I(RD->decls_begin()), E(RD->decls_end()); 7796 I != E; ++I) { 7797 const FunctionDecl *FD = (*I)->getTemplatedDecl(); 7798 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) 7799 (this->*Callback)(CD); 7800 } 7801 } 7802 7803 /// Note that a constructor (or constructor template) was declared in Derived. 7804 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) { 7805 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true; 7806 } 7807 7808 /// Inherit a single constructor. 7809 void inherit(const CXXConstructorDecl *Ctor) { 7810 const FunctionProtoType *CtorType = 7811 Ctor->getType()->castAs<FunctionProtoType>(); 7812 ArrayRef<QualType> ArgTypes(CtorType->getArgTypes()); 7813 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo(); 7814 7815 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent()); 7816 7817 // Core issue (no number yet): the ellipsis is always discarded. 7818 if (EPI.Variadic) { 7819 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis); 7820 SemaRef.Diag(Ctor->getLocation(), 7821 diag::note_using_decl_constructor_ellipsis); 7822 EPI.Variadic = false; 7823 } 7824 7825 // Declare a constructor for each number of parameters. 7826 // 7827 // C++11 [class.inhctor]p1: 7828 // The candidate set of inherited constructors from the class X named in 7829 // the using-declaration consists of [... modulo defects ...] for each 7830 // constructor or constructor template of X, the set of constructors or 7831 // constructor templates that results from omitting any ellipsis parameter 7832 // specification and successively omitting parameters with a default 7833 // argument from the end of the parameter-type-list 7834 for (unsigned Params = std::max(minParamsToInherit(Ctor), 7835 Ctor->getMinRequiredArguments()), 7836 MaxParams = Ctor->getNumParams(); 7837 Params <= MaxParams; ++Params) 7838 declareCtor(UsingLoc, Ctor, 7839 SemaRef.Context.getFunctionType( 7840 Ctor->getResultType(), ArgTypes.slice(0, Params), EPI)); 7841 } 7842 7843 /// Find the using-declaration which specified that we should inherit the 7844 /// constructors of \p Base. 7845 SourceLocation getUsingLoc(const CXXRecordDecl *Base) { 7846 // No fancy lookup required; just look for the base constructor name 7847 // directly within the derived class. 7848 ASTContext &Context = SemaRef.Context; 7849 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 7850 Context.getCanonicalType(Context.getRecordType(Base))); 7851 DeclContext::lookup_const_result Decls = Derived->lookup(Name); 7852 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation(); 7853 } 7854 7855 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) { 7856 // C++11 [class.inhctor]p3: 7857 // [F]or each constructor template in the candidate set of inherited 7858 // constructors, a constructor template is implicitly declared 7859 if (Ctor->getDescribedFunctionTemplate()) 7860 return 0; 7861 7862 // For each non-template constructor in the candidate set of inherited 7863 // constructors other than a constructor having no parameters or a 7864 // copy/move constructor having a single parameter, a constructor is 7865 // implicitly declared [...] 7866 if (Ctor->getNumParams() == 0) 7867 return 1; 7868 if (Ctor->isCopyOrMoveConstructor()) 7869 return 2; 7870 7871 // Per discussion on core reflector, never inherit a constructor which 7872 // would become a default, copy, or move constructor of Derived either. 7873 const ParmVarDecl *PD = Ctor->getParamDecl(0); 7874 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>(); 7875 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1; 7876 } 7877 7878 /// Declare a single inheriting constructor, inheriting the specified 7879 /// constructor, with the given type. 7880 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor, 7881 QualType DerivedType) { 7882 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType); 7883 7884 // C++11 [class.inhctor]p3: 7885 // ... a constructor is implicitly declared with the same constructor 7886 // characteristics unless there is a user-declared constructor with 7887 // the same signature in the class where the using-declaration appears 7888 if (Entry.DeclaredInDerived) 7889 return; 7890 7891 // C++11 [class.inhctor]p7: 7892 // If two using-declarations declare inheriting constructors with the 7893 // same signature, the program is ill-formed 7894 if (Entry.DerivedCtor) { 7895 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) { 7896 // Only diagnose this once per constructor. 7897 if (Entry.DerivedCtor->isInvalidDecl()) 7898 return; 7899 Entry.DerivedCtor->setInvalidDecl(); 7900 7901 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict); 7902 SemaRef.Diag(BaseCtor->getLocation(), 7903 diag::note_using_decl_constructor_conflict_current_ctor); 7904 SemaRef.Diag(Entry.BaseCtor->getLocation(), 7905 diag::note_using_decl_constructor_conflict_previous_ctor); 7906 SemaRef.Diag(Entry.DerivedCtor->getLocation(), 7907 diag::note_using_decl_constructor_conflict_previous_using); 7908 } else { 7909 // Core issue (no number): if the same inheriting constructor is 7910 // produced by multiple base class constructors from the same base 7911 // class, the inheriting constructor is defined as deleted. 7912 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc); 7913 } 7914 7915 return; 7916 } 7917 7918 ASTContext &Context = SemaRef.Context; 7919 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 7920 Context.getCanonicalType(Context.getRecordType(Derived))); 7921 DeclarationNameInfo NameInfo(Name, UsingLoc); 7922 7923 TemplateParameterList *TemplateParams = 0; 7924 if (const FunctionTemplateDecl *FTD = 7925 BaseCtor->getDescribedFunctionTemplate()) { 7926 TemplateParams = FTD->getTemplateParameters(); 7927 // We're reusing template parameters from a different DeclContext. This 7928 // is questionable at best, but works out because the template depth in 7929 // both places is guaranteed to be 0. 7930 // FIXME: Rebuild the template parameters in the new context, and 7931 // transform the function type to refer to them. 7932 } 7933 7934 // Build type source info pointing at the using-declaration. This is 7935 // required by template instantiation. 7936 TypeSourceInfo *TInfo = 7937 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc); 7938 FunctionProtoTypeLoc ProtoLoc = 7939 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 7940 7941 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 7942 Context, Derived, UsingLoc, NameInfo, DerivedType, 7943 TInfo, BaseCtor->isExplicit(), /*Inline=*/true, 7944 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr()); 7945 7946 // Build an unevaluated exception specification for this constructor. 7947 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>(); 7948 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 7949 EPI.ExceptionSpecType = EST_Unevaluated; 7950 EPI.ExceptionSpecDecl = DerivedCtor; 7951 DerivedCtor->setType(Context.getFunctionType(FPT->getResultType(), 7952 FPT->getArgTypes(), EPI)); 7953 7954 // Build the parameter declarations. 7955 SmallVector<ParmVarDecl *, 16> ParamDecls; 7956 for (unsigned I = 0, N = FPT->getNumArgs(); I != N; ++I) { 7957 TypeSourceInfo *TInfo = 7958 Context.getTrivialTypeSourceInfo(FPT->getArgType(I), UsingLoc); 7959 ParmVarDecl *PD = ParmVarDecl::Create( 7960 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0, 7961 FPT->getArgType(I), TInfo, SC_None, /*DefaultArg=*/0); 7962 PD->setScopeInfo(0, I); 7963 PD->setImplicit(); 7964 ParamDecls.push_back(PD); 7965 ProtoLoc.setArg(I, PD); 7966 } 7967 7968 // Set up the new constructor. 7969 DerivedCtor->setAccess(BaseCtor->getAccess()); 7970 DerivedCtor->setParams(ParamDecls); 7971 DerivedCtor->setInheritedConstructor(BaseCtor); 7972 if (BaseCtor->isDeleted()) 7973 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc); 7974 7975 // If this is a constructor template, build the template declaration. 7976 if (TemplateParams) { 7977 FunctionTemplateDecl *DerivedTemplate = 7978 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name, 7979 TemplateParams, DerivedCtor); 7980 DerivedTemplate->setAccess(BaseCtor->getAccess()); 7981 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate); 7982 Derived->addDecl(DerivedTemplate); 7983 } else { 7984 Derived->addDecl(DerivedCtor); 7985 } 7986 7987 Entry.BaseCtor = BaseCtor; 7988 Entry.DerivedCtor = DerivedCtor; 7989 } 7990 7991 Sema &SemaRef; 7992 CXXRecordDecl *Derived; 7993 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType; 7994 MapType Map; 7995}; 7996} 7997 7998void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) { 7999 // Defer declaring the inheriting constructors until the class is 8000 // instantiated. 8001 if (ClassDecl->isDependentContext()) 8002 return; 8003 8004 // Find base classes from which we might inherit constructors. 8005 SmallVector<CXXRecordDecl*, 4> InheritedBases; 8006 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(), 8007 BaseE = ClassDecl->bases_end(); 8008 BaseIt != BaseE; ++BaseIt) 8009 if (BaseIt->getInheritConstructors()) 8010 InheritedBases.push_back(BaseIt->getType()->getAsCXXRecordDecl()); 8011 8012 // Go no further if we're not inheriting any constructors. 8013 if (InheritedBases.empty()) 8014 return; 8015 8016 // Declare the inherited constructors. 8017 InheritingConstructorInfo ICI(*this, ClassDecl); 8018 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I) 8019 ICI.inheritAll(InheritedBases[I]); 8020} 8021 8022void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 8023 CXXConstructorDecl *Constructor) { 8024 CXXRecordDecl *ClassDecl = Constructor->getParent(); 8025 assert(Constructor->getInheritedConstructor() && 8026 !Constructor->doesThisDeclarationHaveABody() && 8027 !Constructor->isDeleted()); 8028 8029 SynthesizedFunctionScope Scope(*this, Constructor); 8030 DiagnosticErrorTrap Trap(Diags); 8031 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 8032 Trap.hasErrorOccurred()) { 8033 Diag(CurrentLocation, diag::note_inhctor_synthesized_at) 8034 << Context.getTagDeclType(ClassDecl); 8035 Constructor->setInvalidDecl(); 8036 return; 8037 } 8038 8039 SourceLocation Loc = Constructor->getLocation(); 8040 Constructor->setBody(new (Context) CompoundStmt(Loc)); 8041 8042 Constructor->setUsed(); 8043 MarkVTableUsed(CurrentLocation, ClassDecl); 8044 8045 if (ASTMutationListener *L = getASTMutationListener()) { 8046 L->CompletedImplicitDefinition(Constructor); 8047 } 8048} 8049 8050 8051Sema::ImplicitExceptionSpecification 8052Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) { 8053 CXXRecordDecl *ClassDecl = MD->getParent(); 8054 8055 // C++ [except.spec]p14: 8056 // An implicitly declared special member function (Clause 12) shall have 8057 // an exception-specification. 8058 ImplicitExceptionSpecification ExceptSpec(*this); 8059 if (ClassDecl->isInvalidDecl()) 8060 return ExceptSpec; 8061 8062 // Direct base-class destructors. 8063 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 8064 BEnd = ClassDecl->bases_end(); 8065 B != BEnd; ++B) { 8066 if (B->isVirtual()) // Handled below. 8067 continue; 8068 8069 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) 8070 ExceptSpec.CalledDecl(B->getLocStart(), 8071 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 8072 } 8073 8074 // Virtual base-class destructors. 8075 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 8076 BEnd = ClassDecl->vbases_end(); 8077 B != BEnd; ++B) { 8078 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) 8079 ExceptSpec.CalledDecl(B->getLocStart(), 8080 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 8081 } 8082 8083 // Field destructors. 8084 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 8085 FEnd = ClassDecl->field_end(); 8086 F != FEnd; ++F) { 8087 if (const RecordType *RecordTy 8088 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) 8089 ExceptSpec.CalledDecl(F->getLocation(), 8090 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl()))); 8091 } 8092 8093 return ExceptSpec; 8094} 8095 8096CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 8097 // C++ [class.dtor]p2: 8098 // If a class has no user-declared destructor, a destructor is 8099 // declared implicitly. An implicitly-declared destructor is an 8100 // inline public member of its class. 8101 assert(ClassDecl->needsImplicitDestructor()); 8102 8103 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 8104 if (DSM.isAlreadyBeingDeclared()) 8105 return 0; 8106 8107 // Create the actual destructor declaration. 8108 CanQualType ClassType 8109 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8110 SourceLocation ClassLoc = ClassDecl->getLocation(); 8111 DeclarationName Name 8112 = Context.DeclarationNames.getCXXDestructorName(ClassType); 8113 DeclarationNameInfo NameInfo(Name, ClassLoc); 8114 CXXDestructorDecl *Destructor 8115 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 8116 QualType(), 0, /*isInline=*/true, 8117 /*isImplicitlyDeclared=*/true); 8118 Destructor->setAccess(AS_public); 8119 Destructor->setDefaulted(); 8120 Destructor->setImplicit(); 8121 8122 // Build an exception specification pointing back at this destructor. 8123 FunctionProtoType::ExtProtoInfo EPI; 8124 EPI.ExceptionSpecType = EST_Unevaluated; 8125 EPI.ExceptionSpecDecl = Destructor; 8126 Destructor->setType(Context.getFunctionType(Context.VoidTy, 8127 ArrayRef<QualType>(), 8128 EPI)); 8129 8130 AddOverriddenMethods(ClassDecl, Destructor); 8131 8132 // We don't need to use SpecialMemberIsTrivial here; triviality for 8133 // destructors is easy to compute. 8134 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 8135 8136 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 8137 SetDeclDeleted(Destructor, ClassLoc); 8138 8139 // Note that we have declared this destructor. 8140 ++ASTContext::NumImplicitDestructorsDeclared; 8141 8142 // Introduce this destructor into its scope. 8143 if (Scope *S = getScopeForContext(ClassDecl)) 8144 PushOnScopeChains(Destructor, S, false); 8145 ClassDecl->addDecl(Destructor); 8146 8147 return Destructor; 8148} 8149 8150void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 8151 CXXDestructorDecl *Destructor) { 8152 assert((Destructor->isDefaulted() && 8153 !Destructor->doesThisDeclarationHaveABody() && 8154 !Destructor->isDeleted()) && 8155 "DefineImplicitDestructor - call it for implicit default dtor"); 8156 CXXRecordDecl *ClassDecl = Destructor->getParent(); 8157 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 8158 8159 if (Destructor->isInvalidDecl()) 8160 return; 8161 8162 SynthesizedFunctionScope Scope(*this, Destructor); 8163 8164 DiagnosticErrorTrap Trap(Diags); 8165 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 8166 Destructor->getParent()); 8167 8168 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) { 8169 Diag(CurrentLocation, diag::note_member_synthesized_at) 8170 << CXXDestructor << Context.getTagDeclType(ClassDecl); 8171 8172 Destructor->setInvalidDecl(); 8173 return; 8174 } 8175 8176 SourceLocation Loc = Destructor->getLocation(); 8177 Destructor->setBody(new (Context) CompoundStmt(Loc)); 8178 Destructor->setImplicitlyDefined(true); 8179 Destructor->setUsed(); 8180 MarkVTableUsed(CurrentLocation, ClassDecl); 8181 8182 if (ASTMutationListener *L = getASTMutationListener()) { 8183 L->CompletedImplicitDefinition(Destructor); 8184 } 8185} 8186 8187/// \brief Perform any semantic analysis which needs to be delayed until all 8188/// pending class member declarations have been parsed. 8189void Sema::ActOnFinishCXXMemberDecls() { 8190 // If the context is an invalid C++ class, just suppress these checks. 8191 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 8192 if (Record->isInvalidDecl()) { 8193 DelayedDestructorExceptionSpecChecks.clear(); 8194 return; 8195 } 8196 } 8197 8198 // Perform any deferred checking of exception specifications for virtual 8199 // destructors. 8200 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size(); 8201 i != e; ++i) { 8202 const CXXDestructorDecl *Dtor = 8203 DelayedDestructorExceptionSpecChecks[i].first; 8204 assert(!Dtor->getParent()->isDependentType() && 8205 "Should not ever add destructors of templates into the list."); 8206 CheckOverridingFunctionExceptionSpec(Dtor, 8207 DelayedDestructorExceptionSpecChecks[i].second); 8208 } 8209 DelayedDestructorExceptionSpecChecks.clear(); 8210} 8211 8212void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 8213 CXXDestructorDecl *Destructor) { 8214 assert(getLangOpts().CPlusPlus11 && 8215 "adjusting dtor exception specs was introduced in c++11"); 8216 8217 // C++11 [class.dtor]p3: 8218 // A declaration of a destructor that does not have an exception- 8219 // specification is implicitly considered to have the same exception- 8220 // specification as an implicit declaration. 8221 const FunctionProtoType *DtorType = Destructor->getType()-> 8222 getAs<FunctionProtoType>(); 8223 if (DtorType->hasExceptionSpec()) 8224 return; 8225 8226 // Replace the destructor's type, building off the existing one. Fortunately, 8227 // the only thing of interest in the destructor type is its extended info. 8228 // The return and arguments are fixed. 8229 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 8230 EPI.ExceptionSpecType = EST_Unevaluated; 8231 EPI.ExceptionSpecDecl = Destructor; 8232 Destructor->setType(Context.getFunctionType(Context.VoidTy, 8233 ArrayRef<QualType>(), 8234 EPI)); 8235 8236 // FIXME: If the destructor has a body that could throw, and the newly created 8237 // spec doesn't allow exceptions, we should emit a warning, because this 8238 // change in behavior can break conforming C++03 programs at runtime. 8239 // However, we don't have a body or an exception specification yet, so it 8240 // needs to be done somewhere else. 8241} 8242 8243/// When generating a defaulted copy or move assignment operator, if a field 8244/// should be copied with __builtin_memcpy rather than via explicit assignments, 8245/// do so. This optimization only applies for arrays of scalars, and for arrays 8246/// of class type where the selected copy/move-assignment operator is trivial. 8247static StmtResult 8248buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 8249 Expr *To, Expr *From) { 8250 // Compute the size of the memory buffer to be copied. 8251 QualType SizeType = S.Context.getSizeType(); 8252 llvm::APInt Size(S.Context.getTypeSize(SizeType), 8253 S.Context.getTypeSizeInChars(T).getQuantity()); 8254 8255 // Take the address of the field references for "from" and "to". We 8256 // directly construct UnaryOperators here because semantic analysis 8257 // does not permit us to take the address of an xvalue. 8258 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 8259 S.Context.getPointerType(From->getType()), 8260 VK_RValue, OK_Ordinary, Loc); 8261 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 8262 S.Context.getPointerType(To->getType()), 8263 VK_RValue, OK_Ordinary, Loc); 8264 8265 const Type *E = T->getBaseElementTypeUnsafe(); 8266 bool NeedsCollectableMemCpy = 8267 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 8268 8269 // Create a reference to the __builtin_objc_memmove_collectable function 8270 StringRef MemCpyName = NeedsCollectableMemCpy ? 8271 "__builtin_objc_memmove_collectable" : 8272 "__builtin_memcpy"; 8273 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 8274 Sema::LookupOrdinaryName); 8275 S.LookupName(R, S.TUScope, true); 8276 8277 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 8278 if (!MemCpy) 8279 // Something went horribly wrong earlier, and we will have complained 8280 // about it. 8281 return StmtError(); 8282 8283 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 8284 VK_RValue, Loc, 0); 8285 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 8286 8287 Expr *CallArgs[] = { 8288 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 8289 }; 8290 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(), 8291 Loc, CallArgs, Loc); 8292 8293 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 8294 return S.Owned(Call.takeAs<Stmt>()); 8295} 8296 8297/// \brief Builds a statement that copies/moves the given entity from \p From to 8298/// \c To. 8299/// 8300/// This routine is used to copy/move the members of a class with an 8301/// implicitly-declared copy/move assignment operator. When the entities being 8302/// copied are arrays, this routine builds for loops to copy them. 8303/// 8304/// \param S The Sema object used for type-checking. 8305/// 8306/// \param Loc The location where the implicit copy/move is being generated. 8307/// 8308/// \param T The type of the expressions being copied/moved. Both expressions 8309/// must have this type. 8310/// 8311/// \param To The expression we are copying/moving to. 8312/// 8313/// \param From The expression we are copying/moving from. 8314/// 8315/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 8316/// Otherwise, it's a non-static member subobject. 8317/// 8318/// \param Copying Whether we're copying or moving. 8319/// 8320/// \param Depth Internal parameter recording the depth of the recursion. 8321/// 8322/// \returns A statement or a loop that copies the expressions, or StmtResult(0) 8323/// if a memcpy should be used instead. 8324static StmtResult 8325buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 8326 Expr *To, Expr *From, 8327 bool CopyingBaseSubobject, bool Copying, 8328 unsigned Depth = 0) { 8329 // C++11 [class.copy]p28: 8330 // Each subobject is assigned in the manner appropriate to its type: 8331 // 8332 // - if the subobject is of class type, as if by a call to operator= with 8333 // the subobject as the object expression and the corresponding 8334 // subobject of x as a single function argument (as if by explicit 8335 // qualification; that is, ignoring any possible virtual overriding 8336 // functions in more derived classes); 8337 // 8338 // C++03 [class.copy]p13: 8339 // - if the subobject is of class type, the copy assignment operator for 8340 // the class is used (as if by explicit qualification; that is, 8341 // ignoring any possible virtual overriding functions in more derived 8342 // classes); 8343 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 8344 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8345 8346 // Look for operator=. 8347 DeclarationName Name 8348 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 8349 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 8350 S.LookupQualifiedName(OpLookup, ClassDecl, false); 8351 8352 // Prior to C++11, filter out any result that isn't a copy/move-assignment 8353 // operator. 8354 if (!S.getLangOpts().CPlusPlus11) { 8355 LookupResult::Filter F = OpLookup.makeFilter(); 8356 while (F.hasNext()) { 8357 NamedDecl *D = F.next(); 8358 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 8359 if (Method->isCopyAssignmentOperator() || 8360 (!Copying && Method->isMoveAssignmentOperator())) 8361 continue; 8362 8363 F.erase(); 8364 } 8365 F.done(); 8366 } 8367 8368 // Suppress the protected check (C++ [class.protected]) for each of the 8369 // assignment operators we found. This strange dance is required when 8370 // we're assigning via a base classes's copy-assignment operator. To 8371 // ensure that we're getting the right base class subobject (without 8372 // ambiguities), we need to cast "this" to that subobject type; to 8373 // ensure that we don't go through the virtual call mechanism, we need 8374 // to qualify the operator= name with the base class (see below). However, 8375 // this means that if the base class has a protected copy assignment 8376 // operator, the protected member access check will fail. So, we 8377 // rewrite "protected" access to "public" access in this case, since we 8378 // know by construction that we're calling from a derived class. 8379 if (CopyingBaseSubobject) { 8380 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 8381 L != LEnd; ++L) { 8382 if (L.getAccess() == AS_protected) 8383 L.setAccess(AS_public); 8384 } 8385 } 8386 8387 // Create the nested-name-specifier that will be used to qualify the 8388 // reference to operator=; this is required to suppress the virtual 8389 // call mechanism. 8390 CXXScopeSpec SS; 8391 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 8392 SS.MakeTrivial(S.Context, 8393 NestedNameSpecifier::Create(S.Context, 0, false, 8394 CanonicalT), 8395 Loc); 8396 8397 // Create the reference to operator=. 8398 ExprResult OpEqualRef 8399 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS, 8400 /*TemplateKWLoc=*/SourceLocation(), 8401 /*FirstQualifierInScope=*/0, 8402 OpLookup, 8403 /*TemplateArgs=*/0, 8404 /*SuppressQualifierCheck=*/true); 8405 if (OpEqualRef.isInvalid()) 8406 return StmtError(); 8407 8408 // Build the call to the assignment operator. 8409 8410 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0, 8411 OpEqualRef.takeAs<Expr>(), 8412 Loc, &From, 1, Loc); 8413 if (Call.isInvalid()) 8414 return StmtError(); 8415 8416 // If we built a call to a trivial 'operator=' while copying an array, 8417 // bail out. We'll replace the whole shebang with a memcpy. 8418 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 8419 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 8420 return StmtResult((Stmt*)0); 8421 8422 // Convert to an expression-statement, and clean up any produced 8423 // temporaries. 8424 return S.ActOnExprStmt(Call); 8425 } 8426 8427 // - if the subobject is of scalar type, the built-in assignment 8428 // operator is used. 8429 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 8430 if (!ArrayTy) { 8431 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From); 8432 if (Assignment.isInvalid()) 8433 return StmtError(); 8434 return S.ActOnExprStmt(Assignment); 8435 } 8436 8437 // - if the subobject is an array, each element is assigned, in the 8438 // manner appropriate to the element type; 8439 8440 // Construct a loop over the array bounds, e.g., 8441 // 8442 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 8443 // 8444 // that will copy each of the array elements. 8445 QualType SizeType = S.Context.getSizeType(); 8446 8447 // Create the iteration variable. 8448 IdentifierInfo *IterationVarName = 0; 8449 { 8450 SmallString<8> Str; 8451 llvm::raw_svector_ostream OS(Str); 8452 OS << "__i" << Depth; 8453 IterationVarName = &S.Context.Idents.get(OS.str()); 8454 } 8455 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 8456 IterationVarName, SizeType, 8457 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 8458 SC_None); 8459 8460 // Initialize the iteration variable to zero. 8461 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 8462 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 8463 8464 // Create a reference to the iteration variable; we'll use this several 8465 // times throughout. 8466 Expr *IterationVarRef 8467 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take(); 8468 assert(IterationVarRef && "Reference to invented variable cannot fail!"); 8469 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take(); 8470 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!"); 8471 8472 // Create the DeclStmt that holds the iteration variable. 8473 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 8474 8475 // Subscript the "from" and "to" expressions with the iteration variable. 8476 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc, 8477 IterationVarRefRVal, 8478 Loc)); 8479 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc, 8480 IterationVarRefRVal, 8481 Loc)); 8482 if (!Copying) // Cast to rvalue 8483 From = CastForMoving(S, From); 8484 8485 // Build the copy/move for an individual element of the array. 8486 StmtResult Copy = 8487 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 8488 To, From, CopyingBaseSubobject, 8489 Copying, Depth + 1); 8490 // Bail out if copying fails or if we determined that we should use memcpy. 8491 if (Copy.isInvalid() || !Copy.get()) 8492 return Copy; 8493 8494 // Create the comparison against the array bound. 8495 llvm::APInt Upper 8496 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 8497 Expr *Comparison 8498 = new (S.Context) BinaryOperator(IterationVarRefRVal, 8499 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 8500 BO_NE, S.Context.BoolTy, 8501 VK_RValue, OK_Ordinary, Loc, false); 8502 8503 // Create the pre-increment of the iteration variable. 8504 Expr *Increment 8505 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType, 8506 VK_LValue, OK_Ordinary, Loc); 8507 8508 // Construct the loop that copies all elements of this array. 8509 return S.ActOnForStmt(Loc, Loc, InitStmt, 8510 S.MakeFullExpr(Comparison), 8511 0, S.MakeFullDiscardedValueExpr(Increment), 8512 Loc, Copy.take()); 8513} 8514 8515static StmtResult 8516buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 8517 Expr *To, Expr *From, 8518 bool CopyingBaseSubobject, bool Copying) { 8519 // Maybe we should use a memcpy? 8520 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 8521 T.isTriviallyCopyableType(S.Context)) 8522 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 8523 8524 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 8525 CopyingBaseSubobject, 8526 Copying, 0)); 8527 8528 // If we ended up picking a trivial assignment operator for an array of a 8529 // non-trivially-copyable class type, just emit a memcpy. 8530 if (!Result.isInvalid() && !Result.get()) 8531 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 8532 8533 return Result; 8534} 8535 8536Sema::ImplicitExceptionSpecification 8537Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) { 8538 CXXRecordDecl *ClassDecl = MD->getParent(); 8539 8540 ImplicitExceptionSpecification ExceptSpec(*this); 8541 if (ClassDecl->isInvalidDecl()) 8542 return ExceptSpec; 8543 8544 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 8545 assert(T->getNumArgs() == 1 && "not a copy assignment op"); 8546 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers(); 8547 8548 // C++ [except.spec]p14: 8549 // An implicitly declared special member function (Clause 12) shall have an 8550 // exception-specification. [...] 8551 8552 // It is unspecified whether or not an implicit copy assignment operator 8553 // attempts to deduplicate calls to assignment operators of virtual bases are 8554 // made. As such, this exception specification is effectively unspecified. 8555 // Based on a similar decision made for constness in C++0x, we're erring on 8556 // the side of assuming such calls to be made regardless of whether they 8557 // actually happen. 8558 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 8559 BaseEnd = ClassDecl->bases_end(); 8560 Base != BaseEnd; ++Base) { 8561 if (Base->isVirtual()) 8562 continue; 8563 8564 CXXRecordDecl *BaseClassDecl 8565 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8566 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 8567 ArgQuals, false, 0)) 8568 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign); 8569 } 8570 8571 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 8572 BaseEnd = ClassDecl->vbases_end(); 8573 Base != BaseEnd; ++Base) { 8574 CXXRecordDecl *BaseClassDecl 8575 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8576 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 8577 ArgQuals, false, 0)) 8578 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign); 8579 } 8580 8581 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8582 FieldEnd = ClassDecl->field_end(); 8583 Field != FieldEnd; 8584 ++Field) { 8585 QualType FieldType = Context.getBaseElementType(Field->getType()); 8586 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 8587 if (CXXMethodDecl *CopyAssign = 8588 LookupCopyingAssignment(FieldClassDecl, 8589 ArgQuals | FieldType.getCVRQualifiers(), 8590 false, 0)) 8591 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign); 8592 } 8593 } 8594 8595 return ExceptSpec; 8596} 8597 8598CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 8599 // Note: The following rules are largely analoguous to the copy 8600 // constructor rules. Note that virtual bases are not taken into account 8601 // for determining the argument type of the operator. Note also that 8602 // operators taking an object instead of a reference are allowed. 8603 assert(ClassDecl->needsImplicitCopyAssignment()); 8604 8605 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 8606 if (DSM.isAlreadyBeingDeclared()) 8607 return 0; 8608 8609 QualType ArgType = Context.getTypeDeclType(ClassDecl); 8610 QualType RetType = Context.getLValueReferenceType(ArgType); 8611 if (ClassDecl->implicitCopyAssignmentHasConstParam()) 8612 ArgType = ArgType.withConst(); 8613 ArgType = Context.getLValueReferenceType(ArgType); 8614 8615 // An implicitly-declared copy assignment operator is an inline public 8616 // member of its class. 8617 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 8618 SourceLocation ClassLoc = ClassDecl->getLocation(); 8619 DeclarationNameInfo NameInfo(Name, ClassLoc); 8620 CXXMethodDecl *CopyAssignment 8621 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 8622 /*TInfo=*/0, 8623 /*StorageClass=*/SC_None, 8624 /*isInline=*/true, /*isConstexpr=*/false, 8625 SourceLocation()); 8626 CopyAssignment->setAccess(AS_public); 8627 CopyAssignment->setDefaulted(); 8628 CopyAssignment->setImplicit(); 8629 8630 // Build an exception specification pointing back at this member. 8631 FunctionProtoType::ExtProtoInfo EPI; 8632 EPI.ExceptionSpecType = EST_Unevaluated; 8633 EPI.ExceptionSpecDecl = CopyAssignment; 8634 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 8635 8636 // Add the parameter to the operator. 8637 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 8638 ClassLoc, ClassLoc, /*Id=*/0, 8639 ArgType, /*TInfo=*/0, 8640 SC_None, 0); 8641 CopyAssignment->setParams(FromParam); 8642 8643 AddOverriddenMethods(ClassDecl, CopyAssignment); 8644 8645 CopyAssignment->setTrivial( 8646 ClassDecl->needsOverloadResolutionForCopyAssignment() 8647 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 8648 : ClassDecl->hasTrivialCopyAssignment()); 8649 8650 // C++0x [class.copy]p19: 8651 // .... If the class definition does not explicitly declare a copy 8652 // assignment operator, there is no user-declared move constructor, and 8653 // there is no user-declared move assignment operator, a copy assignment 8654 // operator is implicitly declared as defaulted. 8655 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 8656 SetDeclDeleted(CopyAssignment, ClassLoc); 8657 8658 // Note that we have added this copy-assignment operator. 8659 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 8660 8661 if (Scope *S = getScopeForContext(ClassDecl)) 8662 PushOnScopeChains(CopyAssignment, S, false); 8663 ClassDecl->addDecl(CopyAssignment); 8664 8665 return CopyAssignment; 8666} 8667 8668void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 8669 CXXMethodDecl *CopyAssignOperator) { 8670 assert((CopyAssignOperator->isDefaulted() && 8671 CopyAssignOperator->isOverloadedOperator() && 8672 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 8673 !CopyAssignOperator->doesThisDeclarationHaveABody() && 8674 !CopyAssignOperator->isDeleted()) && 8675 "DefineImplicitCopyAssignment called for wrong function"); 8676 8677 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 8678 8679 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) { 8680 CopyAssignOperator->setInvalidDecl(); 8681 return; 8682 } 8683 8684 CopyAssignOperator->setUsed(); 8685 8686 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 8687 DiagnosticErrorTrap Trap(Diags); 8688 8689 // C++0x [class.copy]p30: 8690 // The implicitly-defined or explicitly-defaulted copy assignment operator 8691 // for a non-union class X performs memberwise copy assignment of its 8692 // subobjects. The direct base classes of X are assigned first, in the 8693 // order of their declaration in the base-specifier-list, and then the 8694 // immediate non-static data members of X are assigned, in the order in 8695 // which they were declared in the class definition. 8696 8697 // The statements that form the synthesized function body. 8698 SmallVector<Stmt*, 8> Statements; 8699 8700 // The parameter for the "other" object, which we are copying from. 8701 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 8702 Qualifiers OtherQuals = Other->getType().getQualifiers(); 8703 QualType OtherRefType = Other->getType(); 8704 if (const LValueReferenceType *OtherRef 8705 = OtherRefType->getAs<LValueReferenceType>()) { 8706 OtherRefType = OtherRef->getPointeeType(); 8707 OtherQuals = OtherRefType.getQualifiers(); 8708 } 8709 8710 // Our location for everything implicitly-generated. 8711 SourceLocation Loc = CopyAssignOperator->getLocation(); 8712 8713 // Construct a reference to the "other" object. We'll be using this 8714 // throughout the generated ASTs. 8715 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take(); 8716 assert(OtherRef && "Reference to parameter cannot fail!"); 8717 8718 // Construct the "this" pointer. We'll be using this throughout the generated 8719 // ASTs. 8720 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>(); 8721 assert(This && "Reference to this cannot fail!"); 8722 8723 // Assign base classes. 8724 bool Invalid = false; 8725 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 8726 E = ClassDecl->bases_end(); Base != E; ++Base) { 8727 // Form the assignment: 8728 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 8729 QualType BaseType = Base->getType().getUnqualifiedType(); 8730 if (!BaseType->isRecordType()) { 8731 Invalid = true; 8732 continue; 8733 } 8734 8735 CXXCastPath BasePath; 8736 BasePath.push_back(Base); 8737 8738 // Construct the "from" expression, which is an implicit cast to the 8739 // appropriately-qualified base type. 8740 Expr *From = OtherRef; 8741 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals), 8742 CK_UncheckedDerivedToBase, 8743 VK_LValue, &BasePath).take(); 8744 8745 // Dereference "this". 8746 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 8747 8748 // Implicitly cast "this" to the appropriately-qualified base type. 8749 To = ImpCastExprToType(To.take(), 8750 Context.getCVRQualifiedType(BaseType, 8751 CopyAssignOperator->getTypeQualifiers()), 8752 CK_UncheckedDerivedToBase, 8753 VK_LValue, &BasePath); 8754 8755 // Build the copy. 8756 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 8757 To.get(), From, 8758 /*CopyingBaseSubobject=*/true, 8759 /*Copying=*/true); 8760 if (Copy.isInvalid()) { 8761 Diag(CurrentLocation, diag::note_member_synthesized_at) 8762 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 8763 CopyAssignOperator->setInvalidDecl(); 8764 return; 8765 } 8766 8767 // Success! Record the copy. 8768 Statements.push_back(Copy.takeAs<Expr>()); 8769 } 8770 8771 // Assign non-static members. 8772 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8773 FieldEnd = ClassDecl->field_end(); 8774 Field != FieldEnd; ++Field) { 8775 if (Field->isUnnamedBitfield()) 8776 continue; 8777 8778 // Check for members of reference type; we can't copy those. 8779 if (Field->getType()->isReferenceType()) { 8780 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 8781 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 8782 Diag(Field->getLocation(), diag::note_declared_at); 8783 Diag(CurrentLocation, diag::note_member_synthesized_at) 8784 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 8785 Invalid = true; 8786 continue; 8787 } 8788 8789 // Check for members of const-qualified, non-class type. 8790 QualType BaseType = Context.getBaseElementType(Field->getType()); 8791 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 8792 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 8793 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 8794 Diag(Field->getLocation(), diag::note_declared_at); 8795 Diag(CurrentLocation, diag::note_member_synthesized_at) 8796 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 8797 Invalid = true; 8798 continue; 8799 } 8800 8801 // Suppress assigning zero-width bitfields. 8802 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 8803 continue; 8804 8805 QualType FieldType = Field->getType().getNonReferenceType(); 8806 if (FieldType->isIncompleteArrayType()) { 8807 assert(ClassDecl->hasFlexibleArrayMember() && 8808 "Incomplete array type is not valid"); 8809 continue; 8810 } 8811 8812 // Build references to the field in the object we're copying from and to. 8813 CXXScopeSpec SS; // Intentionally empty 8814 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 8815 LookupMemberName); 8816 MemberLookup.addDecl(*Field); 8817 MemberLookup.resolveKind(); 8818 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType, 8819 Loc, /*IsArrow=*/false, 8820 SS, SourceLocation(), 0, 8821 MemberLookup, 0); 8822 ExprResult To = BuildMemberReferenceExpr(This, This->getType(), 8823 Loc, /*IsArrow=*/true, 8824 SS, SourceLocation(), 0, 8825 MemberLookup, 0); 8826 assert(!From.isInvalid() && "Implicit field reference cannot fail"); 8827 assert(!To.isInvalid() && "Implicit field reference cannot fail"); 8828 8829 // Build the copy of this field. 8830 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 8831 To.get(), From.get(), 8832 /*CopyingBaseSubobject=*/false, 8833 /*Copying=*/true); 8834 if (Copy.isInvalid()) { 8835 Diag(CurrentLocation, diag::note_member_synthesized_at) 8836 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 8837 CopyAssignOperator->setInvalidDecl(); 8838 return; 8839 } 8840 8841 // Success! Record the copy. 8842 Statements.push_back(Copy.takeAs<Stmt>()); 8843 } 8844 8845 if (!Invalid) { 8846 // Add a "return *this;" 8847 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 8848 8849 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get()); 8850 if (Return.isInvalid()) 8851 Invalid = true; 8852 else { 8853 Statements.push_back(Return.takeAs<Stmt>()); 8854 8855 if (Trap.hasErrorOccurred()) { 8856 Diag(CurrentLocation, diag::note_member_synthesized_at) 8857 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 8858 Invalid = true; 8859 } 8860 } 8861 } 8862 8863 if (Invalid) { 8864 CopyAssignOperator->setInvalidDecl(); 8865 return; 8866 } 8867 8868 StmtResult Body; 8869 { 8870 CompoundScopeRAII CompoundScope(*this); 8871 Body = ActOnCompoundStmt(Loc, Loc, Statements, 8872 /*isStmtExpr=*/false); 8873 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 8874 } 8875 CopyAssignOperator->setBody(Body.takeAs<Stmt>()); 8876 8877 if (ASTMutationListener *L = getASTMutationListener()) { 8878 L->CompletedImplicitDefinition(CopyAssignOperator); 8879 } 8880} 8881 8882Sema::ImplicitExceptionSpecification 8883Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) { 8884 CXXRecordDecl *ClassDecl = MD->getParent(); 8885 8886 ImplicitExceptionSpecification ExceptSpec(*this); 8887 if (ClassDecl->isInvalidDecl()) 8888 return ExceptSpec; 8889 8890 // C++0x [except.spec]p14: 8891 // An implicitly declared special member function (Clause 12) shall have an 8892 // exception-specification. [...] 8893 8894 // It is unspecified whether or not an implicit move assignment operator 8895 // attempts to deduplicate calls to assignment operators of virtual bases are 8896 // made. As such, this exception specification is effectively unspecified. 8897 // Based on a similar decision made for constness in C++0x, we're erring on 8898 // the side of assuming such calls to be made regardless of whether they 8899 // actually happen. 8900 // Note that a move constructor is not implicitly declared when there are 8901 // virtual bases, but it can still be user-declared and explicitly defaulted. 8902 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 8903 BaseEnd = ClassDecl->bases_end(); 8904 Base != BaseEnd; ++Base) { 8905 if (Base->isVirtual()) 8906 continue; 8907 8908 CXXRecordDecl *BaseClassDecl 8909 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8910 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 8911 0, false, 0)) 8912 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign); 8913 } 8914 8915 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 8916 BaseEnd = ClassDecl->vbases_end(); 8917 Base != BaseEnd; ++Base) { 8918 CXXRecordDecl *BaseClassDecl 8919 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8920 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 8921 0, false, 0)) 8922 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign); 8923 } 8924 8925 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8926 FieldEnd = ClassDecl->field_end(); 8927 Field != FieldEnd; 8928 ++Field) { 8929 QualType FieldType = Context.getBaseElementType(Field->getType()); 8930 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 8931 if (CXXMethodDecl *MoveAssign = 8932 LookupMovingAssignment(FieldClassDecl, 8933 FieldType.getCVRQualifiers(), 8934 false, 0)) 8935 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign); 8936 } 8937 } 8938 8939 return ExceptSpec; 8940} 8941 8942/// Determine whether the class type has any direct or indirect virtual base 8943/// classes which have a non-trivial move assignment operator. 8944static bool 8945hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) { 8946 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 8947 BaseEnd = ClassDecl->vbases_end(); 8948 Base != BaseEnd; ++Base) { 8949 CXXRecordDecl *BaseClass = 8950 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8951 8952 // Try to declare the move assignment. If it would be deleted, then the 8953 // class does not have a non-trivial move assignment. 8954 if (BaseClass->needsImplicitMoveAssignment()) 8955 S.DeclareImplicitMoveAssignment(BaseClass); 8956 8957 if (BaseClass->hasNonTrivialMoveAssignment()) 8958 return true; 8959 } 8960 8961 return false; 8962} 8963 8964/// Determine whether the given type either has a move constructor or is 8965/// trivially copyable. 8966static bool 8967hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) { 8968 Type = S.Context.getBaseElementType(Type); 8969 8970 // FIXME: Technically, non-trivially-copyable non-class types, such as 8971 // reference types, are supposed to return false here, but that appears 8972 // to be a standard defect. 8973 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl(); 8974 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl()) 8975 return true; 8976 8977 if (Type.isTriviallyCopyableType(S.Context)) 8978 return true; 8979 8980 if (IsConstructor) { 8981 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to 8982 // give the right answer. 8983 if (ClassDecl->needsImplicitMoveConstructor()) 8984 S.DeclareImplicitMoveConstructor(ClassDecl); 8985 return ClassDecl->hasMoveConstructor(); 8986 } 8987 8988 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to 8989 // give the right answer. 8990 if (ClassDecl->needsImplicitMoveAssignment()) 8991 S.DeclareImplicitMoveAssignment(ClassDecl); 8992 return ClassDecl->hasMoveAssignment(); 8993} 8994 8995/// Determine whether all non-static data members and direct or virtual bases 8996/// of class \p ClassDecl have either a move operation, or are trivially 8997/// copyable. 8998static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl, 8999 bool IsConstructor) { 9000 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 9001 BaseEnd = ClassDecl->bases_end(); 9002 Base != BaseEnd; ++Base) { 9003 if (Base->isVirtual()) 9004 continue; 9005 9006 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor)) 9007 return false; 9008 } 9009 9010 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 9011 BaseEnd = ClassDecl->vbases_end(); 9012 Base != BaseEnd; ++Base) { 9013 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor)) 9014 return false; 9015 } 9016 9017 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 9018 FieldEnd = ClassDecl->field_end(); 9019 Field != FieldEnd; ++Field) { 9020 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor)) 9021 return false; 9022 } 9023 9024 return true; 9025} 9026 9027CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 9028 // C++11 [class.copy]p20: 9029 // If the definition of a class X does not explicitly declare a move 9030 // assignment operator, one will be implicitly declared as defaulted 9031 // if and only if: 9032 // 9033 // - [first 4 bullets] 9034 assert(ClassDecl->needsImplicitMoveAssignment()); 9035 9036 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 9037 if (DSM.isAlreadyBeingDeclared()) 9038 return 0; 9039 9040 // [Checked after we build the declaration] 9041 // - the move assignment operator would not be implicitly defined as 9042 // deleted, 9043 9044 // [DR1402]: 9045 // - X has no direct or indirect virtual base class with a non-trivial 9046 // move assignment operator, and 9047 // - each of X's non-static data members and direct or virtual base classes 9048 // has a type that either has a move assignment operator or is trivially 9049 // copyable. 9050 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) || 9051 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) { 9052 ClassDecl->setFailedImplicitMoveAssignment(); 9053 return 0; 9054 } 9055 9056 // Note: The following rules are largely analoguous to the move 9057 // constructor rules. 9058 9059 QualType ArgType = Context.getTypeDeclType(ClassDecl); 9060 QualType RetType = Context.getLValueReferenceType(ArgType); 9061 ArgType = Context.getRValueReferenceType(ArgType); 9062 9063 // An implicitly-declared move assignment operator is an inline public 9064 // member of its class. 9065 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9066 SourceLocation ClassLoc = ClassDecl->getLocation(); 9067 DeclarationNameInfo NameInfo(Name, ClassLoc); 9068 CXXMethodDecl *MoveAssignment 9069 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 9070 /*TInfo=*/0, 9071 /*StorageClass=*/SC_None, 9072 /*isInline=*/true, 9073 /*isConstexpr=*/false, 9074 SourceLocation()); 9075 MoveAssignment->setAccess(AS_public); 9076 MoveAssignment->setDefaulted(); 9077 MoveAssignment->setImplicit(); 9078 9079 // Build an exception specification pointing back at this member. 9080 FunctionProtoType::ExtProtoInfo EPI; 9081 EPI.ExceptionSpecType = EST_Unevaluated; 9082 EPI.ExceptionSpecDecl = MoveAssignment; 9083 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 9084 9085 // Add the parameter to the operator. 9086 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 9087 ClassLoc, ClassLoc, /*Id=*/0, 9088 ArgType, /*TInfo=*/0, 9089 SC_None, 0); 9090 MoveAssignment->setParams(FromParam); 9091 9092 AddOverriddenMethods(ClassDecl, MoveAssignment); 9093 9094 MoveAssignment->setTrivial( 9095 ClassDecl->needsOverloadResolutionForMoveAssignment() 9096 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 9097 : ClassDecl->hasTrivialMoveAssignment()); 9098 9099 // C++0x [class.copy]p9: 9100 // If the definition of a class X does not explicitly declare a move 9101 // assignment operator, one will be implicitly declared as defaulted if and 9102 // only if: 9103 // [...] 9104 // - the move assignment operator would not be implicitly defined as 9105 // deleted. 9106 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 9107 // Cache this result so that we don't try to generate this over and over 9108 // on every lookup, leaking memory and wasting time. 9109 ClassDecl->setFailedImplicitMoveAssignment(); 9110 return 0; 9111 } 9112 9113 // Note that we have added this copy-assignment operator. 9114 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 9115 9116 if (Scope *S = getScopeForContext(ClassDecl)) 9117 PushOnScopeChains(MoveAssignment, S, false); 9118 ClassDecl->addDecl(MoveAssignment); 9119 9120 return MoveAssignment; 9121} 9122 9123void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 9124 CXXMethodDecl *MoveAssignOperator) { 9125 assert((MoveAssignOperator->isDefaulted() && 9126 MoveAssignOperator->isOverloadedOperator() && 9127 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 9128 !MoveAssignOperator->doesThisDeclarationHaveABody() && 9129 !MoveAssignOperator->isDeleted()) && 9130 "DefineImplicitMoveAssignment called for wrong function"); 9131 9132 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 9133 9134 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) { 9135 MoveAssignOperator->setInvalidDecl(); 9136 return; 9137 } 9138 9139 MoveAssignOperator->setUsed(); 9140 9141 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 9142 DiagnosticErrorTrap Trap(Diags); 9143 9144 // C++0x [class.copy]p28: 9145 // The implicitly-defined or move assignment operator for a non-union class 9146 // X performs memberwise move assignment of its subobjects. The direct base 9147 // classes of X are assigned first, in the order of their declaration in the 9148 // base-specifier-list, and then the immediate non-static data members of X 9149 // are assigned, in the order in which they were declared in the class 9150 // definition. 9151 9152 // The statements that form the synthesized function body. 9153 SmallVector<Stmt*, 8> Statements; 9154 9155 // The parameter for the "other" object, which we are move from. 9156 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 9157 QualType OtherRefType = Other->getType()-> 9158 getAs<RValueReferenceType>()->getPointeeType(); 9159 assert(OtherRefType.getQualifiers() == 0 && 9160 "Bad argument type of defaulted move assignment"); 9161 9162 // Our location for everything implicitly-generated. 9163 SourceLocation Loc = MoveAssignOperator->getLocation(); 9164 9165 // Construct a reference to the "other" object. We'll be using this 9166 // throughout the generated ASTs. 9167 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take(); 9168 assert(OtherRef && "Reference to parameter cannot fail!"); 9169 // Cast to rvalue. 9170 OtherRef = CastForMoving(*this, OtherRef); 9171 9172 // Construct the "this" pointer. We'll be using this throughout the generated 9173 // ASTs. 9174 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>(); 9175 assert(This && "Reference to this cannot fail!"); 9176 9177 // Assign base classes. 9178 bool Invalid = false; 9179 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 9180 E = ClassDecl->bases_end(); Base != E; ++Base) { 9181 // Form the assignment: 9182 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 9183 QualType BaseType = Base->getType().getUnqualifiedType(); 9184 if (!BaseType->isRecordType()) { 9185 Invalid = true; 9186 continue; 9187 } 9188 9189 CXXCastPath BasePath; 9190 BasePath.push_back(Base); 9191 9192 // Construct the "from" expression, which is an implicit cast to the 9193 // appropriately-qualified base type. 9194 Expr *From = OtherRef; 9195 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase, 9196 VK_XValue, &BasePath).take(); 9197 9198 // Dereference "this". 9199 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 9200 9201 // Implicitly cast "this" to the appropriately-qualified base type. 9202 To = ImpCastExprToType(To.take(), 9203 Context.getCVRQualifiedType(BaseType, 9204 MoveAssignOperator->getTypeQualifiers()), 9205 CK_UncheckedDerivedToBase, 9206 VK_LValue, &BasePath); 9207 9208 // Build the move. 9209 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 9210 To.get(), From, 9211 /*CopyingBaseSubobject=*/true, 9212 /*Copying=*/false); 9213 if (Move.isInvalid()) { 9214 Diag(CurrentLocation, diag::note_member_synthesized_at) 9215 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9216 MoveAssignOperator->setInvalidDecl(); 9217 return; 9218 } 9219 9220 // Success! Record the move. 9221 Statements.push_back(Move.takeAs<Expr>()); 9222 } 9223 9224 // Assign non-static members. 9225 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 9226 FieldEnd = ClassDecl->field_end(); 9227 Field != FieldEnd; ++Field) { 9228 if (Field->isUnnamedBitfield()) 9229 continue; 9230 9231 // Check for members of reference type; we can't move those. 9232 if (Field->getType()->isReferenceType()) { 9233 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9234 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 9235 Diag(Field->getLocation(), diag::note_declared_at); 9236 Diag(CurrentLocation, diag::note_member_synthesized_at) 9237 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9238 Invalid = true; 9239 continue; 9240 } 9241 9242 // Check for members of const-qualified, non-class type. 9243 QualType BaseType = Context.getBaseElementType(Field->getType()); 9244 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 9245 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9246 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 9247 Diag(Field->getLocation(), diag::note_declared_at); 9248 Diag(CurrentLocation, diag::note_member_synthesized_at) 9249 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9250 Invalid = true; 9251 continue; 9252 } 9253 9254 // Suppress assigning zero-width bitfields. 9255 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 9256 continue; 9257 9258 QualType FieldType = Field->getType().getNonReferenceType(); 9259 if (FieldType->isIncompleteArrayType()) { 9260 assert(ClassDecl->hasFlexibleArrayMember() && 9261 "Incomplete array type is not valid"); 9262 continue; 9263 } 9264 9265 // Build references to the field in the object we're copying from and to. 9266 CXXScopeSpec SS; // Intentionally empty 9267 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 9268 LookupMemberName); 9269 MemberLookup.addDecl(*Field); 9270 MemberLookup.resolveKind(); 9271 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType, 9272 Loc, /*IsArrow=*/false, 9273 SS, SourceLocation(), 0, 9274 MemberLookup, 0); 9275 ExprResult To = BuildMemberReferenceExpr(This, This->getType(), 9276 Loc, /*IsArrow=*/true, 9277 SS, SourceLocation(), 0, 9278 MemberLookup, 0); 9279 assert(!From.isInvalid() && "Implicit field reference cannot fail"); 9280 assert(!To.isInvalid() && "Implicit field reference cannot fail"); 9281 9282 assert(!From.get()->isLValue() && // could be xvalue or prvalue 9283 "Member reference with rvalue base must be rvalue except for reference " 9284 "members, which aren't allowed for move assignment."); 9285 9286 // Build the move of this field. 9287 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 9288 To.get(), From.get(), 9289 /*CopyingBaseSubobject=*/false, 9290 /*Copying=*/false); 9291 if (Move.isInvalid()) { 9292 Diag(CurrentLocation, diag::note_member_synthesized_at) 9293 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9294 MoveAssignOperator->setInvalidDecl(); 9295 return; 9296 } 9297 9298 // Success! Record the copy. 9299 Statements.push_back(Move.takeAs<Stmt>()); 9300 } 9301 9302 if (!Invalid) { 9303 // Add a "return *this;" 9304 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 9305 9306 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get()); 9307 if (Return.isInvalid()) 9308 Invalid = true; 9309 else { 9310 Statements.push_back(Return.takeAs<Stmt>()); 9311 9312 if (Trap.hasErrorOccurred()) { 9313 Diag(CurrentLocation, diag::note_member_synthesized_at) 9314 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9315 Invalid = true; 9316 } 9317 } 9318 } 9319 9320 if (Invalid) { 9321 MoveAssignOperator->setInvalidDecl(); 9322 return; 9323 } 9324 9325 StmtResult Body; 9326 { 9327 CompoundScopeRAII CompoundScope(*this); 9328 Body = ActOnCompoundStmt(Loc, Loc, Statements, 9329 /*isStmtExpr=*/false); 9330 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 9331 } 9332 MoveAssignOperator->setBody(Body.takeAs<Stmt>()); 9333 9334 if (ASTMutationListener *L = getASTMutationListener()) { 9335 L->CompletedImplicitDefinition(MoveAssignOperator); 9336 } 9337} 9338 9339Sema::ImplicitExceptionSpecification 9340Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) { 9341 CXXRecordDecl *ClassDecl = MD->getParent(); 9342 9343 ImplicitExceptionSpecification ExceptSpec(*this); 9344 if (ClassDecl->isInvalidDecl()) 9345 return ExceptSpec; 9346 9347 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 9348 assert(T->getNumArgs() >= 1 && "not a copy ctor"); 9349 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers(); 9350 9351 // C++ [except.spec]p14: 9352 // An implicitly declared special member function (Clause 12) shall have an 9353 // exception-specification. [...] 9354 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 9355 BaseEnd = ClassDecl->bases_end(); 9356 Base != BaseEnd; 9357 ++Base) { 9358 // Virtual bases are handled below. 9359 if (Base->isVirtual()) 9360 continue; 9361 9362 CXXRecordDecl *BaseClassDecl 9363 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9364 if (CXXConstructorDecl *CopyConstructor = 9365 LookupCopyingConstructor(BaseClassDecl, Quals)) 9366 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor); 9367 } 9368 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 9369 BaseEnd = ClassDecl->vbases_end(); 9370 Base != BaseEnd; 9371 ++Base) { 9372 CXXRecordDecl *BaseClassDecl 9373 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9374 if (CXXConstructorDecl *CopyConstructor = 9375 LookupCopyingConstructor(BaseClassDecl, Quals)) 9376 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor); 9377 } 9378 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 9379 FieldEnd = ClassDecl->field_end(); 9380 Field != FieldEnd; 9381 ++Field) { 9382 QualType FieldType = Context.getBaseElementType(Field->getType()); 9383 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 9384 if (CXXConstructorDecl *CopyConstructor = 9385 LookupCopyingConstructor(FieldClassDecl, 9386 Quals | FieldType.getCVRQualifiers())) 9387 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor); 9388 } 9389 } 9390 9391 return ExceptSpec; 9392} 9393 9394CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 9395 CXXRecordDecl *ClassDecl) { 9396 // C++ [class.copy]p4: 9397 // If the class definition does not explicitly declare a copy 9398 // constructor, one is declared implicitly. 9399 assert(ClassDecl->needsImplicitCopyConstructor()); 9400 9401 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 9402 if (DSM.isAlreadyBeingDeclared()) 9403 return 0; 9404 9405 QualType ClassType = Context.getTypeDeclType(ClassDecl); 9406 QualType ArgType = ClassType; 9407 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 9408 if (Const) 9409 ArgType = ArgType.withConst(); 9410 ArgType = Context.getLValueReferenceType(ArgType); 9411 9412 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9413 CXXCopyConstructor, 9414 Const); 9415 9416 DeclarationName Name 9417 = Context.DeclarationNames.getCXXConstructorName( 9418 Context.getCanonicalType(ClassType)); 9419 SourceLocation ClassLoc = ClassDecl->getLocation(); 9420 DeclarationNameInfo NameInfo(Name, ClassLoc); 9421 9422 // An implicitly-declared copy constructor is an inline public 9423 // member of its class. 9424 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 9425 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0, 9426 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 9427 Constexpr); 9428 CopyConstructor->setAccess(AS_public); 9429 CopyConstructor->setDefaulted(); 9430 9431 // Build an exception specification pointing back at this member. 9432 FunctionProtoType::ExtProtoInfo EPI; 9433 EPI.ExceptionSpecType = EST_Unevaluated; 9434 EPI.ExceptionSpecDecl = CopyConstructor; 9435 CopyConstructor->setType( 9436 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 9437 9438 // Add the parameter to the constructor. 9439 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 9440 ClassLoc, ClassLoc, 9441 /*IdentifierInfo=*/0, 9442 ArgType, /*TInfo=*/0, 9443 SC_None, 0); 9444 CopyConstructor->setParams(FromParam); 9445 9446 CopyConstructor->setTrivial( 9447 ClassDecl->needsOverloadResolutionForCopyConstructor() 9448 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 9449 : ClassDecl->hasTrivialCopyConstructor()); 9450 9451 // C++11 [class.copy]p8: 9452 // ... If the class definition does not explicitly declare a copy 9453 // constructor, there is no user-declared move constructor, and there is no 9454 // user-declared move assignment operator, a copy constructor is implicitly 9455 // declared as defaulted. 9456 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) 9457 SetDeclDeleted(CopyConstructor, ClassLoc); 9458 9459 // Note that we have declared this constructor. 9460 ++ASTContext::NumImplicitCopyConstructorsDeclared; 9461 9462 if (Scope *S = getScopeForContext(ClassDecl)) 9463 PushOnScopeChains(CopyConstructor, S, false); 9464 ClassDecl->addDecl(CopyConstructor); 9465 9466 return CopyConstructor; 9467} 9468 9469void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 9470 CXXConstructorDecl *CopyConstructor) { 9471 assert((CopyConstructor->isDefaulted() && 9472 CopyConstructor->isCopyConstructor() && 9473 !CopyConstructor->doesThisDeclarationHaveABody() && 9474 !CopyConstructor->isDeleted()) && 9475 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 9476 9477 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 9478 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 9479 9480 SynthesizedFunctionScope Scope(*this, CopyConstructor); 9481 DiagnosticErrorTrap Trap(Diags); 9482 9483 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) || 9484 Trap.hasErrorOccurred()) { 9485 Diag(CurrentLocation, diag::note_member_synthesized_at) 9486 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl); 9487 CopyConstructor->setInvalidDecl(); 9488 } else { 9489 Sema::CompoundScopeRAII CompoundScope(*this); 9490 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(), 9491 CopyConstructor->getLocation(), 9492 MultiStmtArg(), 9493 /*isStmtExpr=*/false) 9494 .takeAs<Stmt>()); 9495 CopyConstructor->setImplicitlyDefined(true); 9496 } 9497 9498 CopyConstructor->setUsed(); 9499 if (ASTMutationListener *L = getASTMutationListener()) { 9500 L->CompletedImplicitDefinition(CopyConstructor); 9501 } 9502} 9503 9504Sema::ImplicitExceptionSpecification 9505Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) { 9506 CXXRecordDecl *ClassDecl = MD->getParent(); 9507 9508 // C++ [except.spec]p14: 9509 // An implicitly declared special member function (Clause 12) shall have an 9510 // exception-specification. [...] 9511 ImplicitExceptionSpecification ExceptSpec(*this); 9512 if (ClassDecl->isInvalidDecl()) 9513 return ExceptSpec; 9514 9515 // Direct base-class constructors. 9516 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 9517 BEnd = ClassDecl->bases_end(); 9518 B != BEnd; ++B) { 9519 if (B->isVirtual()) // Handled below. 9520 continue; 9521 9522 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 9523 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 9524 CXXConstructorDecl *Constructor = 9525 LookupMovingConstructor(BaseClassDecl, 0); 9526 // If this is a deleted function, add it anyway. This might be conformant 9527 // with the standard. This might not. I'm not sure. It might not matter. 9528 if (Constructor) 9529 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 9530 } 9531 } 9532 9533 // Virtual base-class constructors. 9534 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 9535 BEnd = ClassDecl->vbases_end(); 9536 B != BEnd; ++B) { 9537 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 9538 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 9539 CXXConstructorDecl *Constructor = 9540 LookupMovingConstructor(BaseClassDecl, 0); 9541 // If this is a deleted function, add it anyway. This might be conformant 9542 // with the standard. This might not. I'm not sure. It might not matter. 9543 if (Constructor) 9544 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 9545 } 9546 } 9547 9548 // Field constructors. 9549 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 9550 FEnd = ClassDecl->field_end(); 9551 F != FEnd; ++F) { 9552 QualType FieldType = Context.getBaseElementType(F->getType()); 9553 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) { 9554 CXXConstructorDecl *Constructor = 9555 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers()); 9556 // If this is a deleted function, add it anyway. This might be conformant 9557 // with the standard. This might not. I'm not sure. It might not matter. 9558 // In particular, the problem is that this function never gets called. It 9559 // might just be ill-formed because this function attempts to refer to 9560 // a deleted function here. 9561 if (Constructor) 9562 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 9563 } 9564 } 9565 9566 return ExceptSpec; 9567} 9568 9569CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 9570 CXXRecordDecl *ClassDecl) { 9571 // C++11 [class.copy]p9: 9572 // If the definition of a class X does not explicitly declare a move 9573 // constructor, one will be implicitly declared as defaulted if and only if: 9574 // 9575 // - [first 4 bullets] 9576 assert(ClassDecl->needsImplicitMoveConstructor()); 9577 9578 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 9579 if (DSM.isAlreadyBeingDeclared()) 9580 return 0; 9581 9582 // [Checked after we build the declaration] 9583 // - the move assignment operator would not be implicitly defined as 9584 // deleted, 9585 9586 // [DR1402]: 9587 // - each of X's non-static data members and direct or virtual base classes 9588 // has a type that either has a move constructor or is trivially copyable. 9589 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) { 9590 ClassDecl->setFailedImplicitMoveConstructor(); 9591 return 0; 9592 } 9593 9594 QualType ClassType = Context.getTypeDeclType(ClassDecl); 9595 QualType ArgType = Context.getRValueReferenceType(ClassType); 9596 9597 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9598 CXXMoveConstructor, 9599 false); 9600 9601 DeclarationName Name 9602 = Context.DeclarationNames.getCXXConstructorName( 9603 Context.getCanonicalType(ClassType)); 9604 SourceLocation ClassLoc = ClassDecl->getLocation(); 9605 DeclarationNameInfo NameInfo(Name, ClassLoc); 9606 9607 // C++0x [class.copy]p11: 9608 // An implicitly-declared copy/move constructor is an inline public 9609 // member of its class. 9610 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 9611 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0, 9612 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 9613 Constexpr); 9614 MoveConstructor->setAccess(AS_public); 9615 MoveConstructor->setDefaulted(); 9616 9617 // Build an exception specification pointing back at this member. 9618 FunctionProtoType::ExtProtoInfo EPI; 9619 EPI.ExceptionSpecType = EST_Unevaluated; 9620 EPI.ExceptionSpecDecl = MoveConstructor; 9621 MoveConstructor->setType( 9622 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 9623 9624 // Add the parameter to the constructor. 9625 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 9626 ClassLoc, ClassLoc, 9627 /*IdentifierInfo=*/0, 9628 ArgType, /*TInfo=*/0, 9629 SC_None, 0); 9630 MoveConstructor->setParams(FromParam); 9631 9632 MoveConstructor->setTrivial( 9633 ClassDecl->needsOverloadResolutionForMoveConstructor() 9634 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 9635 : ClassDecl->hasTrivialMoveConstructor()); 9636 9637 // C++0x [class.copy]p9: 9638 // If the definition of a class X does not explicitly declare a move 9639 // constructor, one will be implicitly declared as defaulted if and only if: 9640 // [...] 9641 // - the move constructor would not be implicitly defined as deleted. 9642 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 9643 // Cache this result so that we don't try to generate this over and over 9644 // on every lookup, leaking memory and wasting time. 9645 ClassDecl->setFailedImplicitMoveConstructor(); 9646 return 0; 9647 } 9648 9649 // Note that we have declared this constructor. 9650 ++ASTContext::NumImplicitMoveConstructorsDeclared; 9651 9652 if (Scope *S = getScopeForContext(ClassDecl)) 9653 PushOnScopeChains(MoveConstructor, S, false); 9654 ClassDecl->addDecl(MoveConstructor); 9655 9656 return MoveConstructor; 9657} 9658 9659void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 9660 CXXConstructorDecl *MoveConstructor) { 9661 assert((MoveConstructor->isDefaulted() && 9662 MoveConstructor->isMoveConstructor() && 9663 !MoveConstructor->doesThisDeclarationHaveABody() && 9664 !MoveConstructor->isDeleted()) && 9665 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 9666 9667 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 9668 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 9669 9670 SynthesizedFunctionScope Scope(*this, MoveConstructor); 9671 DiagnosticErrorTrap Trap(Diags); 9672 9673 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) || 9674 Trap.hasErrorOccurred()) { 9675 Diag(CurrentLocation, diag::note_member_synthesized_at) 9676 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl); 9677 MoveConstructor->setInvalidDecl(); 9678 } else { 9679 Sema::CompoundScopeRAII CompoundScope(*this); 9680 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(), 9681 MoveConstructor->getLocation(), 9682 MultiStmtArg(), 9683 /*isStmtExpr=*/false) 9684 .takeAs<Stmt>()); 9685 MoveConstructor->setImplicitlyDefined(true); 9686 } 9687 9688 MoveConstructor->setUsed(); 9689 9690 if (ASTMutationListener *L = getASTMutationListener()) { 9691 L->CompletedImplicitDefinition(MoveConstructor); 9692 } 9693} 9694 9695bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 9696 return FD->isDeleted() && 9697 (FD->isDefaulted() || FD->isImplicit()) && 9698 isa<CXXMethodDecl>(FD); 9699} 9700 9701/// \brief Mark the call operator of the given lambda closure type as "used". 9702static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) { 9703 CXXMethodDecl *CallOperator 9704 = cast<CXXMethodDecl>( 9705 Lambda->lookup( 9706 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front()); 9707 CallOperator->setReferenced(); 9708 CallOperator->setUsed(); 9709} 9710 9711void Sema::DefineImplicitLambdaToFunctionPointerConversion( 9712 SourceLocation CurrentLocation, 9713 CXXConversionDecl *Conv) 9714{ 9715 CXXRecordDecl *Lambda = Conv->getParent(); 9716 9717 // Make sure that the lambda call operator is marked used. 9718 markLambdaCallOperatorUsed(*this, Lambda); 9719 9720 Conv->setUsed(); 9721 9722 SynthesizedFunctionScope Scope(*this, Conv); 9723 DiagnosticErrorTrap Trap(Diags); 9724 9725 // Return the address of the __invoke function. 9726 DeclarationName InvokeName = &Context.Idents.get("__invoke"); 9727 CXXMethodDecl *Invoke 9728 = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front()); 9729 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(), 9730 VK_LValue, Conv->getLocation()).take(); 9731 assert(FunctionRef && "Can't refer to __invoke function?"); 9732 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take(); 9733 Conv->setBody(new (Context) CompoundStmt(Context, Return, 9734 Conv->getLocation(), 9735 Conv->getLocation())); 9736 9737 // Fill in the __invoke function with a dummy implementation. IR generation 9738 // will fill in the actual details. 9739 Invoke->setUsed(); 9740 Invoke->setReferenced(); 9741 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation())); 9742 9743 if (ASTMutationListener *L = getASTMutationListener()) { 9744 L->CompletedImplicitDefinition(Conv); 9745 L->CompletedImplicitDefinition(Invoke); 9746 } 9747} 9748 9749void Sema::DefineImplicitLambdaToBlockPointerConversion( 9750 SourceLocation CurrentLocation, 9751 CXXConversionDecl *Conv) 9752{ 9753 Conv->setUsed(); 9754 9755 SynthesizedFunctionScope Scope(*this, Conv); 9756 DiagnosticErrorTrap Trap(Diags); 9757 9758 // Copy-initialize the lambda object as needed to capture it. 9759 Expr *This = ActOnCXXThis(CurrentLocation).take(); 9760 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take(); 9761 9762 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 9763 Conv->getLocation(), 9764 Conv, DerefThis); 9765 9766 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 9767 // behavior. Note that only the general conversion function does this 9768 // (since it's unusable otherwise); in the case where we inline the 9769 // block literal, it has block literal lifetime semantics. 9770 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 9771 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 9772 CK_CopyAndAutoreleaseBlockObject, 9773 BuildBlock.get(), 0, VK_RValue); 9774 9775 if (BuildBlock.isInvalid()) { 9776 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 9777 Conv->setInvalidDecl(); 9778 return; 9779 } 9780 9781 // Create the return statement that returns the block from the conversion 9782 // function. 9783 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get()); 9784 if (Return.isInvalid()) { 9785 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 9786 Conv->setInvalidDecl(); 9787 return; 9788 } 9789 9790 // Set the body of the conversion function. 9791 Stmt *ReturnS = Return.take(); 9792 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS, 9793 Conv->getLocation(), 9794 Conv->getLocation())); 9795 9796 // We're done; notify the mutation listener, if any. 9797 if (ASTMutationListener *L = getASTMutationListener()) { 9798 L->CompletedImplicitDefinition(Conv); 9799 } 9800} 9801 9802/// \brief Determine whether the given list arguments contains exactly one 9803/// "real" (non-default) argument. 9804static bool hasOneRealArgument(MultiExprArg Args) { 9805 switch (Args.size()) { 9806 case 0: 9807 return false; 9808 9809 default: 9810 if (!Args[1]->isDefaultArgument()) 9811 return false; 9812 9813 // fall through 9814 case 1: 9815 return !Args[0]->isDefaultArgument(); 9816 } 9817 9818 return false; 9819} 9820 9821ExprResult 9822Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 9823 CXXConstructorDecl *Constructor, 9824 MultiExprArg ExprArgs, 9825 bool HadMultipleCandidates, 9826 bool IsListInitialization, 9827 bool RequiresZeroInit, 9828 unsigned ConstructKind, 9829 SourceRange ParenRange) { 9830 bool Elidable = false; 9831 9832 // C++0x [class.copy]p34: 9833 // When certain criteria are met, an implementation is allowed to 9834 // omit the copy/move construction of a class object, even if the 9835 // copy/move constructor and/or destructor for the object have 9836 // side effects. [...] 9837 // - when a temporary class object that has not been bound to a 9838 // reference (12.2) would be copied/moved to a class object 9839 // with the same cv-unqualified type, the copy/move operation 9840 // can be omitted by constructing the temporary object 9841 // directly into the target of the omitted copy/move 9842 if (ConstructKind == CXXConstructExpr::CK_Complete && 9843 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 9844 Expr *SubExpr = ExprArgs[0]; 9845 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent()); 9846 } 9847 9848 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 9849 Elidable, ExprArgs, HadMultipleCandidates, 9850 IsListInitialization, RequiresZeroInit, 9851 ConstructKind, ParenRange); 9852} 9853 9854/// BuildCXXConstructExpr - Creates a complete call to a constructor, 9855/// including handling of its default argument expressions. 9856ExprResult 9857Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 9858 CXXConstructorDecl *Constructor, bool Elidable, 9859 MultiExprArg ExprArgs, 9860 bool HadMultipleCandidates, 9861 bool IsListInitialization, 9862 bool RequiresZeroInit, 9863 unsigned ConstructKind, 9864 SourceRange ParenRange) { 9865 MarkFunctionReferenced(ConstructLoc, Constructor); 9866 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc, 9867 Constructor, Elidable, ExprArgs, 9868 HadMultipleCandidates, 9869 IsListInitialization, RequiresZeroInit, 9870 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 9871 ParenRange)); 9872} 9873 9874void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 9875 if (VD->isInvalidDecl()) return; 9876 9877 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 9878 if (ClassDecl->isInvalidDecl()) return; 9879 if (ClassDecl->hasIrrelevantDestructor()) return; 9880 if (ClassDecl->isDependentContext()) return; 9881 9882 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 9883 MarkFunctionReferenced(VD->getLocation(), Destructor); 9884 CheckDestructorAccess(VD->getLocation(), Destructor, 9885 PDiag(diag::err_access_dtor_var) 9886 << VD->getDeclName() 9887 << VD->getType()); 9888 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 9889 9890 if (!VD->hasGlobalStorage()) return; 9891 9892 // Emit warning for non-trivial dtor in global scope (a real global, 9893 // class-static, function-static). 9894 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 9895 9896 // TODO: this should be re-enabled for static locals by !CXAAtExit 9897 if (!VD->isStaticLocal()) 9898 Diag(VD->getLocation(), diag::warn_global_destructor); 9899} 9900 9901/// \brief Given a constructor and the set of arguments provided for the 9902/// constructor, convert the arguments and add any required default arguments 9903/// to form a proper call to this constructor. 9904/// 9905/// \returns true if an error occurred, false otherwise. 9906bool 9907Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 9908 MultiExprArg ArgsPtr, 9909 SourceLocation Loc, 9910 SmallVectorImpl<Expr*> &ConvertedArgs, 9911 bool AllowExplicit, 9912 bool IsListInitialization) { 9913 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 9914 unsigned NumArgs = ArgsPtr.size(); 9915 Expr **Args = ArgsPtr.data(); 9916 9917 const FunctionProtoType *Proto 9918 = Constructor->getType()->getAs<FunctionProtoType>(); 9919 assert(Proto && "Constructor without a prototype?"); 9920 unsigned NumArgsInProto = Proto->getNumArgs(); 9921 9922 // If too few arguments are available, we'll fill in the rest with defaults. 9923 if (NumArgs < NumArgsInProto) 9924 ConvertedArgs.reserve(NumArgsInProto); 9925 else 9926 ConvertedArgs.reserve(NumArgs); 9927 9928 VariadicCallType CallType = 9929 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 9930 SmallVector<Expr *, 8> AllArgs; 9931 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 9932 Proto, 0, Args, NumArgs, AllArgs, 9933 CallType, AllowExplicit, 9934 IsListInitialization); 9935 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 9936 9937 DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size()); 9938 9939 CheckConstructorCall(Constructor, 9940 llvm::makeArrayRef<const Expr *>(AllArgs.data(), 9941 AllArgs.size()), 9942 Proto, Loc); 9943 9944 return Invalid; 9945} 9946 9947static inline bool 9948CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 9949 const FunctionDecl *FnDecl) { 9950 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 9951 if (isa<NamespaceDecl>(DC)) { 9952 return SemaRef.Diag(FnDecl->getLocation(), 9953 diag::err_operator_new_delete_declared_in_namespace) 9954 << FnDecl->getDeclName(); 9955 } 9956 9957 if (isa<TranslationUnitDecl>(DC) && 9958 FnDecl->getStorageClass() == SC_Static) { 9959 return SemaRef.Diag(FnDecl->getLocation(), 9960 diag::err_operator_new_delete_declared_static) 9961 << FnDecl->getDeclName(); 9962 } 9963 9964 return false; 9965} 9966 9967static inline bool 9968CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 9969 CanQualType ExpectedResultType, 9970 CanQualType ExpectedFirstParamType, 9971 unsigned DependentParamTypeDiag, 9972 unsigned InvalidParamTypeDiag) { 9973 QualType ResultType = 9974 FnDecl->getType()->getAs<FunctionType>()->getResultType(); 9975 9976 // Check that the result type is not dependent. 9977 if (ResultType->isDependentType()) 9978 return SemaRef.Diag(FnDecl->getLocation(), 9979 diag::err_operator_new_delete_dependent_result_type) 9980 << FnDecl->getDeclName() << ExpectedResultType; 9981 9982 // Check that the result type is what we expect. 9983 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 9984 return SemaRef.Diag(FnDecl->getLocation(), 9985 diag::err_operator_new_delete_invalid_result_type) 9986 << FnDecl->getDeclName() << ExpectedResultType; 9987 9988 // A function template must have at least 2 parameters. 9989 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 9990 return SemaRef.Diag(FnDecl->getLocation(), 9991 diag::err_operator_new_delete_template_too_few_parameters) 9992 << FnDecl->getDeclName(); 9993 9994 // The function decl must have at least 1 parameter. 9995 if (FnDecl->getNumParams() == 0) 9996 return SemaRef.Diag(FnDecl->getLocation(), 9997 diag::err_operator_new_delete_too_few_parameters) 9998 << FnDecl->getDeclName(); 9999 10000 // Check the first parameter type is not dependent. 10001 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 10002 if (FirstParamType->isDependentType()) 10003 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 10004 << FnDecl->getDeclName() << ExpectedFirstParamType; 10005 10006 // Check that the first parameter type is what we expect. 10007 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 10008 ExpectedFirstParamType) 10009 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 10010 << FnDecl->getDeclName() << ExpectedFirstParamType; 10011 10012 return false; 10013} 10014 10015static bool 10016CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 10017 // C++ [basic.stc.dynamic.allocation]p1: 10018 // A program is ill-formed if an allocation function is declared in a 10019 // namespace scope other than global scope or declared static in global 10020 // scope. 10021 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 10022 return true; 10023 10024 CanQualType SizeTy = 10025 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 10026 10027 // C++ [basic.stc.dynamic.allocation]p1: 10028 // The return type shall be void*. The first parameter shall have type 10029 // std::size_t. 10030 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 10031 SizeTy, 10032 diag::err_operator_new_dependent_param_type, 10033 diag::err_operator_new_param_type)) 10034 return true; 10035 10036 // C++ [basic.stc.dynamic.allocation]p1: 10037 // The first parameter shall not have an associated default argument. 10038 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 10039 return SemaRef.Diag(FnDecl->getLocation(), 10040 diag::err_operator_new_default_arg) 10041 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 10042 10043 return false; 10044} 10045 10046static bool 10047CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 10048 // C++ [basic.stc.dynamic.deallocation]p1: 10049 // A program is ill-formed if deallocation functions are declared in a 10050 // namespace scope other than global scope or declared static in global 10051 // scope. 10052 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 10053 return true; 10054 10055 // C++ [basic.stc.dynamic.deallocation]p2: 10056 // Each deallocation function shall return void and its first parameter 10057 // shall be void*. 10058 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 10059 SemaRef.Context.VoidPtrTy, 10060 diag::err_operator_delete_dependent_param_type, 10061 diag::err_operator_delete_param_type)) 10062 return true; 10063 10064 return false; 10065} 10066 10067/// CheckOverloadedOperatorDeclaration - Check whether the declaration 10068/// of this overloaded operator is well-formed. If so, returns false; 10069/// otherwise, emits appropriate diagnostics and returns true. 10070bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 10071 assert(FnDecl && FnDecl->isOverloadedOperator() && 10072 "Expected an overloaded operator declaration"); 10073 10074 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 10075 10076 // C++ [over.oper]p5: 10077 // The allocation and deallocation functions, operator new, 10078 // operator new[], operator delete and operator delete[], are 10079 // described completely in 3.7.3. The attributes and restrictions 10080 // found in the rest of this subclause do not apply to them unless 10081 // explicitly stated in 3.7.3. 10082 if (Op == OO_Delete || Op == OO_Array_Delete) 10083 return CheckOperatorDeleteDeclaration(*this, FnDecl); 10084 10085 if (Op == OO_New || Op == OO_Array_New) 10086 return CheckOperatorNewDeclaration(*this, FnDecl); 10087 10088 // C++ [over.oper]p6: 10089 // An operator function shall either be a non-static member 10090 // function or be a non-member function and have at least one 10091 // parameter whose type is a class, a reference to a class, an 10092 // enumeration, or a reference to an enumeration. 10093 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 10094 if (MethodDecl->isStatic()) 10095 return Diag(FnDecl->getLocation(), 10096 diag::err_operator_overload_static) << FnDecl->getDeclName(); 10097 } else { 10098 bool ClassOrEnumParam = false; 10099 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 10100 ParamEnd = FnDecl->param_end(); 10101 Param != ParamEnd; ++Param) { 10102 QualType ParamType = (*Param)->getType().getNonReferenceType(); 10103 if (ParamType->isDependentType() || ParamType->isRecordType() || 10104 ParamType->isEnumeralType()) { 10105 ClassOrEnumParam = true; 10106 break; 10107 } 10108 } 10109 10110 if (!ClassOrEnumParam) 10111 return Diag(FnDecl->getLocation(), 10112 diag::err_operator_overload_needs_class_or_enum) 10113 << FnDecl->getDeclName(); 10114 } 10115 10116 // C++ [over.oper]p8: 10117 // An operator function cannot have default arguments (8.3.6), 10118 // except where explicitly stated below. 10119 // 10120 // Only the function-call operator allows default arguments 10121 // (C++ [over.call]p1). 10122 if (Op != OO_Call) { 10123 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(); 10124 Param != FnDecl->param_end(); ++Param) { 10125 if ((*Param)->hasDefaultArg()) 10126 return Diag((*Param)->getLocation(), 10127 diag::err_operator_overload_default_arg) 10128 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange(); 10129 } 10130 } 10131 10132 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 10133 { false, false, false } 10134#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 10135 , { Unary, Binary, MemberOnly } 10136#include "clang/Basic/OperatorKinds.def" 10137 }; 10138 10139 bool CanBeUnaryOperator = OperatorUses[Op][0]; 10140 bool CanBeBinaryOperator = OperatorUses[Op][1]; 10141 bool MustBeMemberOperator = OperatorUses[Op][2]; 10142 10143 // C++ [over.oper]p8: 10144 // [...] Operator functions cannot have more or fewer parameters 10145 // than the number required for the corresponding operator, as 10146 // described in the rest of this subclause. 10147 unsigned NumParams = FnDecl->getNumParams() 10148 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 10149 if (Op != OO_Call && 10150 ((NumParams == 1 && !CanBeUnaryOperator) || 10151 (NumParams == 2 && !CanBeBinaryOperator) || 10152 (NumParams < 1) || (NumParams > 2))) { 10153 // We have the wrong number of parameters. 10154 unsigned ErrorKind; 10155 if (CanBeUnaryOperator && CanBeBinaryOperator) { 10156 ErrorKind = 2; // 2 -> unary or binary. 10157 } else if (CanBeUnaryOperator) { 10158 ErrorKind = 0; // 0 -> unary 10159 } else { 10160 assert(CanBeBinaryOperator && 10161 "All non-call overloaded operators are unary or binary!"); 10162 ErrorKind = 1; // 1 -> binary 10163 } 10164 10165 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 10166 << FnDecl->getDeclName() << NumParams << ErrorKind; 10167 } 10168 10169 // Overloaded operators other than operator() cannot be variadic. 10170 if (Op != OO_Call && 10171 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 10172 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 10173 << FnDecl->getDeclName(); 10174 } 10175 10176 // Some operators must be non-static member functions. 10177 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 10178 return Diag(FnDecl->getLocation(), 10179 diag::err_operator_overload_must_be_member) 10180 << FnDecl->getDeclName(); 10181 } 10182 10183 // C++ [over.inc]p1: 10184 // The user-defined function called operator++ implements the 10185 // prefix and postfix ++ operator. If this function is a member 10186 // function with no parameters, or a non-member function with one 10187 // parameter of class or enumeration type, it defines the prefix 10188 // increment operator ++ for objects of that type. If the function 10189 // is a member function with one parameter (which shall be of type 10190 // int) or a non-member function with two parameters (the second 10191 // of which shall be of type int), it defines the postfix 10192 // increment operator ++ for objects of that type. 10193 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 10194 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 10195 bool ParamIsInt = false; 10196 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>()) 10197 ParamIsInt = BT->getKind() == BuiltinType::Int; 10198 10199 if (!ParamIsInt) 10200 return Diag(LastParam->getLocation(), 10201 diag::err_operator_overload_post_incdec_must_be_int) 10202 << LastParam->getType() << (Op == OO_MinusMinus); 10203 } 10204 10205 return false; 10206} 10207 10208/// CheckLiteralOperatorDeclaration - Check whether the declaration 10209/// of this literal operator function is well-formed. If so, returns 10210/// false; otherwise, emits appropriate diagnostics and returns true. 10211bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 10212 if (isa<CXXMethodDecl>(FnDecl)) { 10213 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 10214 << FnDecl->getDeclName(); 10215 return true; 10216 } 10217 10218 if (FnDecl->isExternC()) { 10219 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 10220 return true; 10221 } 10222 10223 bool Valid = false; 10224 10225 // This might be the definition of a literal operator template. 10226 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 10227 // This might be a specialization of a literal operator template. 10228 if (!TpDecl) 10229 TpDecl = FnDecl->getPrimaryTemplate(); 10230 10231 // template <char...> type operator "" name() is the only valid template 10232 // signature, and the only valid signature with no parameters. 10233 if (TpDecl) { 10234 if (FnDecl->param_size() == 0) { 10235 // Must have only one template parameter 10236 TemplateParameterList *Params = TpDecl->getTemplateParameters(); 10237 if (Params->size() == 1) { 10238 NonTypeTemplateParmDecl *PmDecl = 10239 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0)); 10240 10241 // The template parameter must be a char parameter pack. 10242 if (PmDecl && PmDecl->isTemplateParameterPack() && 10243 Context.hasSameType(PmDecl->getType(), Context.CharTy)) 10244 Valid = true; 10245 } 10246 } 10247 } else if (FnDecl->param_size()) { 10248 // Check the first parameter 10249 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 10250 10251 QualType T = (*Param)->getType().getUnqualifiedType(); 10252 10253 // unsigned long long int, long double, and any character type are allowed 10254 // as the only parameters. 10255 if (Context.hasSameType(T, Context.UnsignedLongLongTy) || 10256 Context.hasSameType(T, Context.LongDoubleTy) || 10257 Context.hasSameType(T, Context.CharTy) || 10258 Context.hasSameType(T, Context.WCharTy) || 10259 Context.hasSameType(T, Context.Char16Ty) || 10260 Context.hasSameType(T, Context.Char32Ty)) { 10261 if (++Param == FnDecl->param_end()) 10262 Valid = true; 10263 goto FinishedParams; 10264 } 10265 10266 // Otherwise it must be a pointer to const; let's strip those qualifiers. 10267 const PointerType *PT = T->getAs<PointerType>(); 10268 if (!PT) 10269 goto FinishedParams; 10270 T = PT->getPointeeType(); 10271 if (!T.isConstQualified() || T.isVolatileQualified()) 10272 goto FinishedParams; 10273 T = T.getUnqualifiedType(); 10274 10275 // Move on to the second parameter; 10276 ++Param; 10277 10278 // If there is no second parameter, the first must be a const char * 10279 if (Param == FnDecl->param_end()) { 10280 if (Context.hasSameType(T, Context.CharTy)) 10281 Valid = true; 10282 goto FinishedParams; 10283 } 10284 10285 // const char *, const wchar_t*, const char16_t*, and const char32_t* 10286 // are allowed as the first parameter to a two-parameter function 10287 if (!(Context.hasSameType(T, Context.CharTy) || 10288 Context.hasSameType(T, Context.WCharTy) || 10289 Context.hasSameType(T, Context.Char16Ty) || 10290 Context.hasSameType(T, Context.Char32Ty))) 10291 goto FinishedParams; 10292 10293 // The second and final parameter must be an std::size_t 10294 T = (*Param)->getType().getUnqualifiedType(); 10295 if (Context.hasSameType(T, Context.getSizeType()) && 10296 ++Param == FnDecl->param_end()) 10297 Valid = true; 10298 } 10299 10300 // FIXME: This diagnostic is absolutely terrible. 10301FinishedParams: 10302 if (!Valid) { 10303 Diag(FnDecl->getLocation(), diag::err_literal_operator_params) 10304 << FnDecl->getDeclName(); 10305 return true; 10306 } 10307 10308 // A parameter-declaration-clause containing a default argument is not 10309 // equivalent to any of the permitted forms. 10310 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 10311 ParamEnd = FnDecl->param_end(); 10312 Param != ParamEnd; ++Param) { 10313 if ((*Param)->hasDefaultArg()) { 10314 Diag((*Param)->getDefaultArgRange().getBegin(), 10315 diag::err_literal_operator_default_argument) 10316 << (*Param)->getDefaultArgRange(); 10317 break; 10318 } 10319 } 10320 10321 StringRef LiteralName 10322 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 10323 if (LiteralName[0] != '_') { 10324 // C++11 [usrlit.suffix]p1: 10325 // Literal suffix identifiers that do not start with an underscore 10326 // are reserved for future standardization. 10327 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved); 10328 } 10329 10330 return false; 10331} 10332 10333/// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 10334/// linkage specification, including the language and (if present) 10335/// the '{'. ExternLoc is the location of the 'extern', LangLoc is 10336/// the location of the language string literal, which is provided 10337/// by Lang/StrSize. LBraceLoc, if valid, provides the location of 10338/// the '{' brace. Otherwise, this linkage specification does not 10339/// have any braces. 10340Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 10341 SourceLocation LangLoc, 10342 StringRef Lang, 10343 SourceLocation LBraceLoc) { 10344 LinkageSpecDecl::LanguageIDs Language; 10345 if (Lang == "\"C\"") 10346 Language = LinkageSpecDecl::lang_c; 10347 else if (Lang == "\"C++\"") 10348 Language = LinkageSpecDecl::lang_cxx; 10349 else { 10350 Diag(LangLoc, diag::err_bad_language); 10351 return 0; 10352 } 10353 10354 // FIXME: Add all the various semantics of linkage specifications 10355 10356 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, 10357 ExternLoc, LangLoc, Language); 10358 CurContext->addDecl(D); 10359 PushDeclContext(S, D); 10360 return D; 10361} 10362 10363/// ActOnFinishLinkageSpecification - Complete the definition of 10364/// the C++ linkage specification LinkageSpec. If RBraceLoc is 10365/// valid, it's the position of the closing '}' brace in a linkage 10366/// specification that uses braces. 10367Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 10368 Decl *LinkageSpec, 10369 SourceLocation RBraceLoc) { 10370 if (LinkageSpec) { 10371 if (RBraceLoc.isValid()) { 10372 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 10373 LSDecl->setRBraceLoc(RBraceLoc); 10374 } 10375 PopDeclContext(); 10376 } 10377 return LinkageSpec; 10378} 10379 10380Decl *Sema::ActOnEmptyDeclaration(Scope *S, 10381 AttributeList *AttrList, 10382 SourceLocation SemiLoc) { 10383 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 10384 // Attribute declarations appertain to empty declaration so we handle 10385 // them here. 10386 if (AttrList) 10387 ProcessDeclAttributeList(S, ED, AttrList); 10388 10389 CurContext->addDecl(ED); 10390 return ED; 10391} 10392 10393/// \brief Perform semantic analysis for the variable declaration that 10394/// occurs within a C++ catch clause, returning the newly-created 10395/// variable. 10396VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 10397 TypeSourceInfo *TInfo, 10398 SourceLocation StartLoc, 10399 SourceLocation Loc, 10400 IdentifierInfo *Name) { 10401 bool Invalid = false; 10402 QualType ExDeclType = TInfo->getType(); 10403 10404 // Arrays and functions decay. 10405 if (ExDeclType->isArrayType()) 10406 ExDeclType = Context.getArrayDecayedType(ExDeclType); 10407 else if (ExDeclType->isFunctionType()) 10408 ExDeclType = Context.getPointerType(ExDeclType); 10409 10410 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 10411 // The exception-declaration shall not denote a pointer or reference to an 10412 // incomplete type, other than [cv] void*. 10413 // N2844 forbids rvalue references. 10414 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 10415 Diag(Loc, diag::err_catch_rvalue_ref); 10416 Invalid = true; 10417 } 10418 10419 QualType BaseType = ExDeclType; 10420 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 10421 unsigned DK = diag::err_catch_incomplete; 10422 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 10423 BaseType = Ptr->getPointeeType(); 10424 Mode = 1; 10425 DK = diag::err_catch_incomplete_ptr; 10426 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 10427 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 10428 BaseType = Ref->getPointeeType(); 10429 Mode = 2; 10430 DK = diag::err_catch_incomplete_ref; 10431 } 10432 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 10433 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 10434 Invalid = true; 10435 10436 if (!Invalid && !ExDeclType->isDependentType() && 10437 RequireNonAbstractType(Loc, ExDeclType, 10438 diag::err_abstract_type_in_decl, 10439 AbstractVariableType)) 10440 Invalid = true; 10441 10442 // Only the non-fragile NeXT runtime currently supports C++ catches 10443 // of ObjC types, and no runtime supports catching ObjC types by value. 10444 if (!Invalid && getLangOpts().ObjC1) { 10445 QualType T = ExDeclType; 10446 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 10447 T = RT->getPointeeType(); 10448 10449 if (T->isObjCObjectType()) { 10450 Diag(Loc, diag::err_objc_object_catch); 10451 Invalid = true; 10452 } else if (T->isObjCObjectPointerType()) { 10453 // FIXME: should this be a test for macosx-fragile specifically? 10454 if (getLangOpts().ObjCRuntime.isFragile()) 10455 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 10456 } 10457 } 10458 10459 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 10460 ExDeclType, TInfo, SC_None); 10461 ExDecl->setExceptionVariable(true); 10462 10463 // In ARC, infer 'retaining' for variables of retainable type. 10464 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 10465 Invalid = true; 10466 10467 if (!Invalid && !ExDeclType->isDependentType()) { 10468 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 10469 // Insulate this from anything else we might currently be parsing. 10470 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 10471 10472 // C++ [except.handle]p16: 10473 // The object declared in an exception-declaration or, if the 10474 // exception-declaration does not specify a name, a temporary (12.2) is 10475 // copy-initialized (8.5) from the exception object. [...] 10476 // The object is destroyed when the handler exits, after the destruction 10477 // of any automatic objects initialized within the handler. 10478 // 10479 // We just pretend to initialize the object with itself, then make sure 10480 // it can be destroyed later. 10481 QualType initType = ExDeclType; 10482 10483 InitializedEntity entity = 10484 InitializedEntity::InitializeVariable(ExDecl); 10485 InitializationKind initKind = 10486 InitializationKind::CreateCopy(Loc, SourceLocation()); 10487 10488 Expr *opaqueValue = 10489 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 10490 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1); 10491 ExprResult result = sequence.Perform(*this, entity, initKind, 10492 MultiExprArg(&opaqueValue, 1)); 10493 if (result.isInvalid()) 10494 Invalid = true; 10495 else { 10496 // If the constructor used was non-trivial, set this as the 10497 // "initializer". 10498 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take()); 10499 if (!construct->getConstructor()->isTrivial()) { 10500 Expr *init = MaybeCreateExprWithCleanups(construct); 10501 ExDecl->setInit(init); 10502 } 10503 10504 // And make sure it's destructable. 10505 FinalizeVarWithDestructor(ExDecl, recordType); 10506 } 10507 } 10508 } 10509 10510 if (Invalid) 10511 ExDecl->setInvalidDecl(); 10512 10513 return ExDecl; 10514} 10515 10516/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 10517/// handler. 10518Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 10519 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 10520 bool Invalid = D.isInvalidType(); 10521 10522 // Check for unexpanded parameter packs. 10523 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 10524 UPPC_ExceptionType)) { 10525 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 10526 D.getIdentifierLoc()); 10527 Invalid = true; 10528 } 10529 10530 IdentifierInfo *II = D.getIdentifier(); 10531 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 10532 LookupOrdinaryName, 10533 ForRedeclaration)) { 10534 // The scope should be freshly made just for us. There is just no way 10535 // it contains any previous declaration. 10536 assert(!S->isDeclScope(PrevDecl)); 10537 if (PrevDecl->isTemplateParameter()) { 10538 // Maybe we will complain about the shadowed template parameter. 10539 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 10540 PrevDecl = 0; 10541 } 10542 } 10543 10544 if (D.getCXXScopeSpec().isSet() && !Invalid) { 10545 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 10546 << D.getCXXScopeSpec().getRange(); 10547 Invalid = true; 10548 } 10549 10550 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 10551 D.getLocStart(), 10552 D.getIdentifierLoc(), 10553 D.getIdentifier()); 10554 if (Invalid) 10555 ExDecl->setInvalidDecl(); 10556 10557 // Add the exception declaration into this scope. 10558 if (II) 10559 PushOnScopeChains(ExDecl, S); 10560 else 10561 CurContext->addDecl(ExDecl); 10562 10563 ProcessDeclAttributes(S, ExDecl, D); 10564 return ExDecl; 10565} 10566 10567Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 10568 Expr *AssertExpr, 10569 Expr *AssertMessageExpr, 10570 SourceLocation RParenLoc) { 10571 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr); 10572 10573 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 10574 return 0; 10575 10576 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 10577 AssertMessage, RParenLoc, false); 10578} 10579 10580Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 10581 Expr *AssertExpr, 10582 StringLiteral *AssertMessage, 10583 SourceLocation RParenLoc, 10584 bool Failed) { 10585 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 10586 !Failed) { 10587 // In a static_assert-declaration, the constant-expression shall be a 10588 // constant expression that can be contextually converted to bool. 10589 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 10590 if (Converted.isInvalid()) 10591 Failed = true; 10592 10593 llvm::APSInt Cond; 10594 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 10595 diag::err_static_assert_expression_is_not_constant, 10596 /*AllowFold=*/false).isInvalid()) 10597 Failed = true; 10598 10599 if (!Failed && !Cond) { 10600 SmallString<256> MsgBuffer; 10601 llvm::raw_svector_ostream Msg(MsgBuffer); 10602 AssertMessage->printPretty(Msg, 0, getPrintingPolicy()); 10603 Diag(StaticAssertLoc, diag::err_static_assert_failed) 10604 << Msg.str() << AssertExpr->getSourceRange(); 10605 Failed = true; 10606 } 10607 } 10608 10609 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 10610 AssertExpr, AssertMessage, RParenLoc, 10611 Failed); 10612 10613 CurContext->addDecl(Decl); 10614 return Decl; 10615} 10616 10617/// \brief Perform semantic analysis of the given friend type declaration. 10618/// 10619/// \returns A friend declaration that. 10620FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 10621 SourceLocation FriendLoc, 10622 TypeSourceInfo *TSInfo) { 10623 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 10624 10625 QualType T = TSInfo->getType(); 10626 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 10627 10628 // C++03 [class.friend]p2: 10629 // An elaborated-type-specifier shall be used in a friend declaration 10630 // for a class.* 10631 // 10632 // * The class-key of the elaborated-type-specifier is required. 10633 if (!ActiveTemplateInstantiations.empty()) { 10634 // Do not complain about the form of friend template types during 10635 // template instantiation; we will already have complained when the 10636 // template was declared. 10637 } else { 10638 if (!T->isElaboratedTypeSpecifier()) { 10639 // If we evaluated the type to a record type, suggest putting 10640 // a tag in front. 10641 if (const RecordType *RT = T->getAs<RecordType>()) { 10642 RecordDecl *RD = RT->getDecl(); 10643 10644 std::string InsertionText = std::string(" ") + RD->getKindName(); 10645 10646 Diag(TypeRange.getBegin(), 10647 getLangOpts().CPlusPlus11 ? 10648 diag::warn_cxx98_compat_unelaborated_friend_type : 10649 diag::ext_unelaborated_friend_type) 10650 << (unsigned) RD->getTagKind() 10651 << T 10652 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc), 10653 InsertionText); 10654 } else { 10655 Diag(FriendLoc, 10656 getLangOpts().CPlusPlus11 ? 10657 diag::warn_cxx98_compat_nonclass_type_friend : 10658 diag::ext_nonclass_type_friend) 10659 << T 10660 << TypeRange; 10661 } 10662 } else if (T->getAs<EnumType>()) { 10663 Diag(FriendLoc, 10664 getLangOpts().CPlusPlus11 ? 10665 diag::warn_cxx98_compat_enum_friend : 10666 diag::ext_enum_friend) 10667 << T 10668 << TypeRange; 10669 } 10670 10671 // C++11 [class.friend]p3: 10672 // A friend declaration that does not declare a function shall have one 10673 // of the following forms: 10674 // friend elaborated-type-specifier ; 10675 // friend simple-type-specifier ; 10676 // friend typename-specifier ; 10677 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 10678 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 10679 } 10680 10681 // If the type specifier in a friend declaration designates a (possibly 10682 // cv-qualified) class type, that class is declared as a friend; otherwise, 10683 // the friend declaration is ignored. 10684 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc); 10685} 10686 10687/// Handle a friend tag declaration where the scope specifier was 10688/// templated. 10689Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 10690 unsigned TagSpec, SourceLocation TagLoc, 10691 CXXScopeSpec &SS, 10692 IdentifierInfo *Name, 10693 SourceLocation NameLoc, 10694 AttributeList *Attr, 10695 MultiTemplateParamsArg TempParamLists) { 10696 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 10697 10698 bool isExplicitSpecialization = false; 10699 bool Invalid = false; 10700 10701 if (TemplateParameterList *TemplateParams 10702 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS, 10703 TempParamLists.data(), 10704 TempParamLists.size(), 10705 /*friend*/ true, 10706 isExplicitSpecialization, 10707 Invalid)) { 10708 if (TemplateParams->size() > 0) { 10709 // This is a declaration of a class template. 10710 if (Invalid) 10711 return 0; 10712 10713 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, 10714 SS, Name, NameLoc, Attr, 10715 TemplateParams, AS_public, 10716 /*ModulePrivateLoc=*/SourceLocation(), 10717 TempParamLists.size() - 1, 10718 TempParamLists.data()).take(); 10719 } else { 10720 // The "template<>" header is extraneous. 10721 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 10722 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 10723 isExplicitSpecialization = true; 10724 } 10725 } 10726 10727 if (Invalid) return 0; 10728 10729 bool isAllExplicitSpecializations = true; 10730 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 10731 if (TempParamLists[I]->size()) { 10732 isAllExplicitSpecializations = false; 10733 break; 10734 } 10735 } 10736 10737 // FIXME: don't ignore attributes. 10738 10739 // If it's explicit specializations all the way down, just forget 10740 // about the template header and build an appropriate non-templated 10741 // friend. TODO: for source fidelity, remember the headers. 10742 if (isAllExplicitSpecializations) { 10743 if (SS.isEmpty()) { 10744 bool Owned = false; 10745 bool IsDependent = false; 10746 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 10747 Attr, AS_public, 10748 /*ModulePrivateLoc=*/SourceLocation(), 10749 MultiTemplateParamsArg(), Owned, IsDependent, 10750 /*ScopedEnumKWLoc=*/SourceLocation(), 10751 /*ScopedEnumUsesClassTag=*/false, 10752 /*UnderlyingType=*/TypeResult()); 10753 } 10754 10755 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 10756 ElaboratedTypeKeyword Keyword 10757 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 10758 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 10759 *Name, NameLoc); 10760 if (T.isNull()) 10761 return 0; 10762 10763 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 10764 if (isa<DependentNameType>(T)) { 10765 DependentNameTypeLoc TL = 10766 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 10767 TL.setElaboratedKeywordLoc(TagLoc); 10768 TL.setQualifierLoc(QualifierLoc); 10769 TL.setNameLoc(NameLoc); 10770 } else { 10771 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 10772 TL.setElaboratedKeywordLoc(TagLoc); 10773 TL.setQualifierLoc(QualifierLoc); 10774 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 10775 } 10776 10777 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 10778 TSI, FriendLoc, TempParamLists); 10779 Friend->setAccess(AS_public); 10780 CurContext->addDecl(Friend); 10781 return Friend; 10782 } 10783 10784 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 10785 10786 10787 10788 // Handle the case of a templated-scope friend class. e.g. 10789 // template <class T> class A<T>::B; 10790 // FIXME: we don't support these right now. 10791 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 10792 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 10793 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 10794 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 10795 TL.setElaboratedKeywordLoc(TagLoc); 10796 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 10797 TL.setNameLoc(NameLoc); 10798 10799 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 10800 TSI, FriendLoc, TempParamLists); 10801 Friend->setAccess(AS_public); 10802 Friend->setUnsupportedFriend(true); 10803 CurContext->addDecl(Friend); 10804 return Friend; 10805} 10806 10807 10808/// Handle a friend type declaration. This works in tandem with 10809/// ActOnTag. 10810/// 10811/// Notes on friend class templates: 10812/// 10813/// We generally treat friend class declarations as if they were 10814/// declaring a class. So, for example, the elaborated type specifier 10815/// in a friend declaration is required to obey the restrictions of a 10816/// class-head (i.e. no typedefs in the scope chain), template 10817/// parameters are required to match up with simple template-ids, &c. 10818/// However, unlike when declaring a template specialization, it's 10819/// okay to refer to a template specialization without an empty 10820/// template parameter declaration, e.g. 10821/// friend class A<T>::B<unsigned>; 10822/// We permit this as a special case; if there are any template 10823/// parameters present at all, require proper matching, i.e. 10824/// template <> template \<class T> friend class A<int>::B; 10825Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 10826 MultiTemplateParamsArg TempParams) { 10827 SourceLocation Loc = DS.getLocStart(); 10828 10829 assert(DS.isFriendSpecified()); 10830 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 10831 10832 // Try to convert the decl specifier to a type. This works for 10833 // friend templates because ActOnTag never produces a ClassTemplateDecl 10834 // for a TUK_Friend. 10835 Declarator TheDeclarator(DS, Declarator::MemberContext); 10836 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 10837 QualType T = TSI->getType(); 10838 if (TheDeclarator.isInvalidType()) 10839 return 0; 10840 10841 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 10842 return 0; 10843 10844 // This is definitely an error in C++98. It's probably meant to 10845 // be forbidden in C++0x, too, but the specification is just 10846 // poorly written. 10847 // 10848 // The problem is with declarations like the following: 10849 // template <T> friend A<T>::foo; 10850 // where deciding whether a class C is a friend or not now hinges 10851 // on whether there exists an instantiation of A that causes 10852 // 'foo' to equal C. There are restrictions on class-heads 10853 // (which we declare (by fiat) elaborated friend declarations to 10854 // be) that makes this tractable. 10855 // 10856 // FIXME: handle "template <> friend class A<T>;", which 10857 // is possibly well-formed? Who even knows? 10858 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 10859 Diag(Loc, diag::err_tagless_friend_type_template) 10860 << DS.getSourceRange(); 10861 return 0; 10862 } 10863 10864 // C++98 [class.friend]p1: A friend of a class is a function 10865 // or class that is not a member of the class . . . 10866 // This is fixed in DR77, which just barely didn't make the C++03 10867 // deadline. It's also a very silly restriction that seriously 10868 // affects inner classes and which nobody else seems to implement; 10869 // thus we never diagnose it, not even in -pedantic. 10870 // 10871 // But note that we could warn about it: it's always useless to 10872 // friend one of your own members (it's not, however, worthless to 10873 // friend a member of an arbitrary specialization of your template). 10874 10875 Decl *D; 10876 if (unsigned NumTempParamLists = TempParams.size()) 10877 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 10878 NumTempParamLists, 10879 TempParams.data(), 10880 TSI, 10881 DS.getFriendSpecLoc()); 10882 else 10883 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 10884 10885 if (!D) 10886 return 0; 10887 10888 D->setAccess(AS_public); 10889 CurContext->addDecl(D); 10890 10891 return D; 10892} 10893 10894NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 10895 MultiTemplateParamsArg TemplateParams) { 10896 const DeclSpec &DS = D.getDeclSpec(); 10897 10898 assert(DS.isFriendSpecified()); 10899 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 10900 10901 SourceLocation Loc = D.getIdentifierLoc(); 10902 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 10903 10904 // C++ [class.friend]p1 10905 // A friend of a class is a function or class.... 10906 // Note that this sees through typedefs, which is intended. 10907 // It *doesn't* see through dependent types, which is correct 10908 // according to [temp.arg.type]p3: 10909 // If a declaration acquires a function type through a 10910 // type dependent on a template-parameter and this causes 10911 // a declaration that does not use the syntactic form of a 10912 // function declarator to have a function type, the program 10913 // is ill-formed. 10914 if (!TInfo->getType()->isFunctionType()) { 10915 Diag(Loc, diag::err_unexpected_friend); 10916 10917 // It might be worthwhile to try to recover by creating an 10918 // appropriate declaration. 10919 return 0; 10920 } 10921 10922 // C++ [namespace.memdef]p3 10923 // - If a friend declaration in a non-local class first declares a 10924 // class or function, the friend class or function is a member 10925 // of the innermost enclosing namespace. 10926 // - The name of the friend is not found by simple name lookup 10927 // until a matching declaration is provided in that namespace 10928 // scope (either before or after the class declaration granting 10929 // friendship). 10930 // - If a friend function is called, its name may be found by the 10931 // name lookup that considers functions from namespaces and 10932 // classes associated with the types of the function arguments. 10933 // - When looking for a prior declaration of a class or a function 10934 // declared as a friend, scopes outside the innermost enclosing 10935 // namespace scope are not considered. 10936 10937 CXXScopeSpec &SS = D.getCXXScopeSpec(); 10938 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 10939 DeclarationName Name = NameInfo.getName(); 10940 assert(Name); 10941 10942 // Check for unexpanded parameter packs. 10943 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 10944 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 10945 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 10946 return 0; 10947 10948 // The context we found the declaration in, or in which we should 10949 // create the declaration. 10950 DeclContext *DC; 10951 Scope *DCScope = S; 10952 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 10953 ForRedeclaration); 10954 10955 // FIXME: there are different rules in local classes 10956 10957 // There are four cases here. 10958 // - There's no scope specifier, in which case we just go to the 10959 // appropriate scope and look for a function or function template 10960 // there as appropriate. 10961 // Recover from invalid scope qualifiers as if they just weren't there. 10962 if (SS.isInvalid() || !SS.isSet()) { 10963 // C++0x [namespace.memdef]p3: 10964 // If the name in a friend declaration is neither qualified nor 10965 // a template-id and the declaration is a function or an 10966 // elaborated-type-specifier, the lookup to determine whether 10967 // the entity has been previously declared shall not consider 10968 // any scopes outside the innermost enclosing namespace. 10969 // C++0x [class.friend]p11: 10970 // If a friend declaration appears in a local class and the name 10971 // specified is an unqualified name, a prior declaration is 10972 // looked up without considering scopes that are outside the 10973 // innermost enclosing non-class scope. For a friend function 10974 // declaration, if there is no prior declaration, the program is 10975 // ill-formed. 10976 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass(); 10977 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 10978 10979 // Find the appropriate context according to the above. 10980 DC = CurContext; 10981 while (true) { 10982 // Skip class contexts. If someone can cite chapter and verse 10983 // for this behavior, that would be nice --- it's what GCC and 10984 // EDG do, and it seems like a reasonable intent, but the spec 10985 // really only says that checks for unqualified existing 10986 // declarations should stop at the nearest enclosing namespace, 10987 // not that they should only consider the nearest enclosing 10988 // namespace. 10989 while (DC->isRecord() || DC->isTransparentContext()) 10990 DC = DC->getParent(); 10991 10992 LookupQualifiedName(Previous, DC); 10993 10994 // TODO: decide what we think about using declarations. 10995 if (isLocal || !Previous.empty()) 10996 break; 10997 10998 if (isTemplateId) { 10999 if (isa<TranslationUnitDecl>(DC)) break; 11000 } else { 11001 if (DC->isFileContext()) break; 11002 } 11003 DC = DC->getParent(); 11004 } 11005 11006 DCScope = getScopeForDeclContext(S, DC); 11007 11008 // C++ [class.friend]p6: 11009 // A function can be defined in a friend declaration of a class if and 11010 // only if the class is a non-local class (9.8), the function name is 11011 // unqualified, and the function has namespace scope. 11012 if (isLocal && D.isFunctionDefinition()) { 11013 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 11014 } 11015 11016 // - There's a non-dependent scope specifier, in which case we 11017 // compute it and do a previous lookup there for a function 11018 // or function template. 11019 } else if (!SS.getScopeRep()->isDependent()) { 11020 DC = computeDeclContext(SS); 11021 if (!DC) return 0; 11022 11023 if (RequireCompleteDeclContext(SS, DC)) return 0; 11024 11025 LookupQualifiedName(Previous, DC); 11026 11027 // Ignore things found implicitly in the wrong scope. 11028 // TODO: better diagnostics for this case. Suggesting the right 11029 // qualified scope would be nice... 11030 LookupResult::Filter F = Previous.makeFilter(); 11031 while (F.hasNext()) { 11032 NamedDecl *D = F.next(); 11033 if (!DC->InEnclosingNamespaceSetOf( 11034 D->getDeclContext()->getRedeclContext())) 11035 F.erase(); 11036 } 11037 F.done(); 11038 11039 if (Previous.empty()) { 11040 D.setInvalidType(); 11041 Diag(Loc, diag::err_qualified_friend_not_found) 11042 << Name << TInfo->getType(); 11043 return 0; 11044 } 11045 11046 // C++ [class.friend]p1: A friend of a class is a function or 11047 // class that is not a member of the class . . . 11048 if (DC->Equals(CurContext)) 11049 Diag(DS.getFriendSpecLoc(), 11050 getLangOpts().CPlusPlus11 ? 11051 diag::warn_cxx98_compat_friend_is_member : 11052 diag::err_friend_is_member); 11053 11054 if (D.isFunctionDefinition()) { 11055 // C++ [class.friend]p6: 11056 // A function can be defined in a friend declaration of a class if and 11057 // only if the class is a non-local class (9.8), the function name is 11058 // unqualified, and the function has namespace scope. 11059 SemaDiagnosticBuilder DB 11060 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 11061 11062 DB << SS.getScopeRep(); 11063 if (DC->isFileContext()) 11064 DB << FixItHint::CreateRemoval(SS.getRange()); 11065 SS.clear(); 11066 } 11067 11068 // - There's a scope specifier that does not match any template 11069 // parameter lists, in which case we use some arbitrary context, 11070 // create a method or method template, and wait for instantiation. 11071 // - There's a scope specifier that does match some template 11072 // parameter lists, which we don't handle right now. 11073 } else { 11074 if (D.isFunctionDefinition()) { 11075 // C++ [class.friend]p6: 11076 // A function can be defined in a friend declaration of a class if and 11077 // only if the class is a non-local class (9.8), the function name is 11078 // unqualified, and the function has namespace scope. 11079 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 11080 << SS.getScopeRep(); 11081 } 11082 11083 DC = CurContext; 11084 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 11085 } 11086 11087 if (!DC->isRecord()) { 11088 // This implies that it has to be an operator or function. 11089 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName || 11090 D.getName().getKind() == UnqualifiedId::IK_DestructorName || 11091 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) { 11092 Diag(Loc, diag::err_introducing_special_friend) << 11093 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 : 11094 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2); 11095 return 0; 11096 } 11097 } 11098 11099 // FIXME: This is an egregious hack to cope with cases where the scope stack 11100 // does not contain the declaration context, i.e., in an out-of-line 11101 // definition of a class. 11102 Scope FakeDCScope(S, Scope::DeclScope, Diags); 11103 if (!DCScope) { 11104 FakeDCScope.setEntity(DC); 11105 DCScope = &FakeDCScope; 11106 } 11107 11108 bool AddToScope = true; 11109 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 11110 TemplateParams, AddToScope); 11111 if (!ND) return 0; 11112 11113 assert(ND->getDeclContext() == DC); 11114 assert(ND->getLexicalDeclContext() == CurContext); 11115 11116 // Add the function declaration to the appropriate lookup tables, 11117 // adjusting the redeclarations list as necessary. We don't 11118 // want to do this yet if the friending class is dependent. 11119 // 11120 // Also update the scope-based lookup if the target context's 11121 // lookup context is in lexical scope. 11122 if (!CurContext->isDependentContext()) { 11123 DC = DC->getRedeclContext(); 11124 DC->makeDeclVisibleInContext(ND); 11125 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 11126 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 11127 } 11128 11129 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 11130 D.getIdentifierLoc(), ND, 11131 DS.getFriendSpecLoc()); 11132 FrD->setAccess(AS_public); 11133 CurContext->addDecl(FrD); 11134 11135 if (ND->isInvalidDecl()) { 11136 FrD->setInvalidDecl(); 11137 } else { 11138 if (DC->isRecord()) CheckFriendAccess(ND); 11139 11140 FunctionDecl *FD; 11141 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 11142 FD = FTD->getTemplatedDecl(); 11143 else 11144 FD = cast<FunctionDecl>(ND); 11145 11146 // Mark templated-scope function declarations as unsupported. 11147 if (FD->getNumTemplateParameterLists()) 11148 FrD->setUnsupportedFriend(true); 11149 } 11150 11151 return ND; 11152} 11153 11154void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 11155 AdjustDeclIfTemplate(Dcl); 11156 11157 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 11158 if (!Fn) { 11159 Diag(DelLoc, diag::err_deleted_non_function); 11160 return; 11161 } 11162 11163 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 11164 // Don't consider the implicit declaration we generate for explicit 11165 // specializations. FIXME: Do not generate these implicit declarations. 11166 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization 11167 || Prev->getPreviousDecl()) && !Prev->isDefined()) { 11168 Diag(DelLoc, diag::err_deleted_decl_not_first); 11169 Diag(Prev->getLocation(), diag::note_previous_declaration); 11170 } 11171 // If the declaration wasn't the first, we delete the function anyway for 11172 // recovery. 11173 Fn = Fn->getCanonicalDecl(); 11174 } 11175 11176 if (Fn->isDeleted()) 11177 return; 11178 11179 // See if we're deleting a function which is already known to override a 11180 // non-deleted virtual function. 11181 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 11182 bool IssuedDiagnostic = false; 11183 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 11184 E = MD->end_overridden_methods(); 11185 I != E; ++I) { 11186 if (!(*MD->begin_overridden_methods())->isDeleted()) { 11187 if (!IssuedDiagnostic) { 11188 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 11189 IssuedDiagnostic = true; 11190 } 11191 Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 11192 } 11193 } 11194 } 11195 11196 Fn->setDeletedAsWritten(); 11197} 11198 11199void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 11200 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 11201 11202 if (MD) { 11203 if (MD->getParent()->isDependentType()) { 11204 MD->setDefaulted(); 11205 MD->setExplicitlyDefaulted(); 11206 return; 11207 } 11208 11209 CXXSpecialMember Member = getSpecialMember(MD); 11210 if (Member == CXXInvalid) { 11211 Diag(DefaultLoc, diag::err_default_special_members); 11212 return; 11213 } 11214 11215 MD->setDefaulted(); 11216 MD->setExplicitlyDefaulted(); 11217 11218 // If this definition appears within the record, do the checking when 11219 // the record is complete. 11220 const FunctionDecl *Primary = MD; 11221 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 11222 // Find the uninstantiated declaration that actually had the '= default' 11223 // on it. 11224 Pattern->isDefined(Primary); 11225 11226 // If the method was defaulted on its first declaration, we will have 11227 // already performed the checking in CheckCompletedCXXClass. Such a 11228 // declaration doesn't trigger an implicit definition. 11229 if (Primary == Primary->getCanonicalDecl()) 11230 return; 11231 11232 CheckExplicitlyDefaultedSpecialMember(MD); 11233 11234 // The exception specification is needed because we are defining the 11235 // function. 11236 ResolveExceptionSpec(DefaultLoc, 11237 MD->getType()->castAs<FunctionProtoType>()); 11238 11239 switch (Member) { 11240 case CXXDefaultConstructor: { 11241 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD); 11242 if (!CD->isInvalidDecl()) 11243 DefineImplicitDefaultConstructor(DefaultLoc, CD); 11244 break; 11245 } 11246 11247 case CXXCopyConstructor: { 11248 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD); 11249 if (!CD->isInvalidDecl()) 11250 DefineImplicitCopyConstructor(DefaultLoc, CD); 11251 break; 11252 } 11253 11254 case CXXCopyAssignment: { 11255 if (!MD->isInvalidDecl()) 11256 DefineImplicitCopyAssignment(DefaultLoc, MD); 11257 break; 11258 } 11259 11260 case CXXDestructor: { 11261 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD); 11262 if (!DD->isInvalidDecl()) 11263 DefineImplicitDestructor(DefaultLoc, DD); 11264 break; 11265 } 11266 11267 case CXXMoveConstructor: { 11268 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD); 11269 if (!CD->isInvalidDecl()) 11270 DefineImplicitMoveConstructor(DefaultLoc, CD); 11271 break; 11272 } 11273 11274 case CXXMoveAssignment: { 11275 if (!MD->isInvalidDecl()) 11276 DefineImplicitMoveAssignment(DefaultLoc, MD); 11277 break; 11278 } 11279 11280 case CXXInvalid: 11281 llvm_unreachable("Invalid special member."); 11282 } 11283 } else { 11284 Diag(DefaultLoc, diag::err_default_special_members); 11285 } 11286} 11287 11288static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 11289 for (Stmt::child_range CI = S->children(); CI; ++CI) { 11290 Stmt *SubStmt = *CI; 11291 if (!SubStmt) 11292 continue; 11293 if (isa<ReturnStmt>(SubStmt)) 11294 Self.Diag(SubStmt->getLocStart(), 11295 diag::err_return_in_constructor_handler); 11296 if (!isa<Expr>(SubStmt)) 11297 SearchForReturnInStmt(Self, SubStmt); 11298 } 11299} 11300 11301void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 11302 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 11303 CXXCatchStmt *Handler = TryBlock->getHandler(I); 11304 SearchForReturnInStmt(*this, Handler); 11305 } 11306} 11307 11308bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 11309 const CXXMethodDecl *Old) { 11310 const FunctionType *NewFT = New->getType()->getAs<FunctionType>(); 11311 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>(); 11312 11313 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 11314 11315 // If the calling conventions match, everything is fine 11316 if (NewCC == OldCC) 11317 return false; 11318 11319 // If either of the calling conventions are set to "default", we need to pick 11320 // something more sensible based on the target. This supports code where the 11321 // one method explicitly sets thiscall, and another has no explicit calling 11322 // convention. 11323 CallingConv Default = 11324 Context.getTargetInfo().getDefaultCallingConv(TargetInfo::CCMT_Member); 11325 if (NewCC == CC_Default) 11326 NewCC = Default; 11327 if (OldCC == CC_Default) 11328 OldCC = Default; 11329 11330 // If the calling conventions still don't match, then report the error 11331 if (NewCC != OldCC) { 11332 Diag(New->getLocation(), 11333 diag::err_conflicting_overriding_cc_attributes) 11334 << New->getDeclName() << New->getType() << Old->getType(); 11335 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 11336 return true; 11337 } 11338 11339 return false; 11340} 11341 11342bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 11343 const CXXMethodDecl *Old) { 11344 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType(); 11345 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType(); 11346 11347 if (Context.hasSameType(NewTy, OldTy) || 11348 NewTy->isDependentType() || OldTy->isDependentType()) 11349 return false; 11350 11351 // Check if the return types are covariant 11352 QualType NewClassTy, OldClassTy; 11353 11354 /// Both types must be pointers or references to classes. 11355 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 11356 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 11357 NewClassTy = NewPT->getPointeeType(); 11358 OldClassTy = OldPT->getPointeeType(); 11359 } 11360 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 11361 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 11362 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 11363 NewClassTy = NewRT->getPointeeType(); 11364 OldClassTy = OldRT->getPointeeType(); 11365 } 11366 } 11367 } 11368 11369 // The return types aren't either both pointers or references to a class type. 11370 if (NewClassTy.isNull()) { 11371 Diag(New->getLocation(), 11372 diag::err_different_return_type_for_overriding_virtual_function) 11373 << New->getDeclName() << NewTy << OldTy; 11374 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 11375 11376 return true; 11377 } 11378 11379 // C++ [class.virtual]p6: 11380 // If the return type of D::f differs from the return type of B::f, the 11381 // class type in the return type of D::f shall be complete at the point of 11382 // declaration of D::f or shall be the class type D. 11383 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 11384 if (!RT->isBeingDefined() && 11385 RequireCompleteType(New->getLocation(), NewClassTy, 11386 diag::err_covariant_return_incomplete, 11387 New->getDeclName())) 11388 return true; 11389 } 11390 11391 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 11392 // Check if the new class derives from the old class. 11393 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 11394 Diag(New->getLocation(), 11395 diag::err_covariant_return_not_derived) 11396 << New->getDeclName() << NewTy << OldTy; 11397 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 11398 return true; 11399 } 11400 11401 // Check if we the conversion from derived to base is valid. 11402 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy, 11403 diag::err_covariant_return_inaccessible_base, 11404 diag::err_covariant_return_ambiguous_derived_to_base_conv, 11405 // FIXME: Should this point to the return type? 11406 New->getLocation(), SourceRange(), New->getDeclName(), 0)) { 11407 // FIXME: this note won't trigger for delayed access control 11408 // diagnostics, and it's impossible to get an undelayed error 11409 // here from access control during the original parse because 11410 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 11411 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 11412 return true; 11413 } 11414 } 11415 11416 // The qualifiers of the return types must be the same. 11417 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 11418 Diag(New->getLocation(), 11419 diag::err_covariant_return_type_different_qualifications) 11420 << New->getDeclName() << NewTy << OldTy; 11421 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 11422 return true; 11423 }; 11424 11425 11426 // The new class type must have the same or less qualifiers as the old type. 11427 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 11428 Diag(New->getLocation(), 11429 diag::err_covariant_return_type_class_type_more_qualified) 11430 << New->getDeclName() << NewTy << OldTy; 11431 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 11432 return true; 11433 }; 11434 11435 return false; 11436} 11437 11438/// \brief Mark the given method pure. 11439/// 11440/// \param Method the method to be marked pure. 11441/// 11442/// \param InitRange the source range that covers the "0" initializer. 11443bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 11444 SourceLocation EndLoc = InitRange.getEnd(); 11445 if (EndLoc.isValid()) 11446 Method->setRangeEnd(EndLoc); 11447 11448 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 11449 Method->setPure(); 11450 return false; 11451 } 11452 11453 if (!Method->isInvalidDecl()) 11454 Diag(Method->getLocation(), diag::err_non_virtual_pure) 11455 << Method->getDeclName() << InitRange; 11456 return true; 11457} 11458 11459/// \brief Determine whether the given declaration is a static data member. 11460static bool isStaticDataMember(Decl *D) { 11461 VarDecl *Var = dyn_cast_or_null<VarDecl>(D); 11462 if (!Var) 11463 return false; 11464 11465 return Var->isStaticDataMember(); 11466} 11467/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 11468/// an initializer for the out-of-line declaration 'Dcl'. The scope 11469/// is a fresh scope pushed for just this purpose. 11470/// 11471/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 11472/// static data member of class X, names should be looked up in the scope of 11473/// class X. 11474void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 11475 // If there is no declaration, there was an error parsing it. 11476 if (D == 0 || D->isInvalidDecl()) return; 11477 11478 // We should only get called for declarations with scope specifiers, like: 11479 // int foo::bar; 11480 assert(D->isOutOfLine()); 11481 EnterDeclaratorContext(S, D->getDeclContext()); 11482 11483 // If we are parsing the initializer for a static data member, push a 11484 // new expression evaluation context that is associated with this static 11485 // data member. 11486 if (isStaticDataMember(D)) 11487 PushExpressionEvaluationContext(PotentiallyEvaluated, D); 11488} 11489 11490/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 11491/// initializer for the out-of-line declaration 'D'. 11492void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 11493 // If there is no declaration, there was an error parsing it. 11494 if (D == 0 || D->isInvalidDecl()) return; 11495 11496 if (isStaticDataMember(D)) 11497 PopExpressionEvaluationContext(); 11498 11499 assert(D->isOutOfLine()); 11500 ExitDeclaratorContext(S); 11501} 11502 11503/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 11504/// C++ if/switch/while/for statement. 11505/// e.g: "if (int x = f()) {...}" 11506DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 11507 // C++ 6.4p2: 11508 // The declarator shall not specify a function or an array. 11509 // The type-specifier-seq shall not contain typedef and shall not declare a 11510 // new class or enumeration. 11511 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 11512 "Parser allowed 'typedef' as storage class of condition decl."); 11513 11514 Decl *Dcl = ActOnDeclarator(S, D); 11515 if (!Dcl) 11516 return true; 11517 11518 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 11519 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 11520 << D.getSourceRange(); 11521 return true; 11522 } 11523 11524 return Dcl; 11525} 11526 11527void Sema::LoadExternalVTableUses() { 11528 if (!ExternalSource) 11529 return; 11530 11531 SmallVector<ExternalVTableUse, 4> VTables; 11532 ExternalSource->ReadUsedVTables(VTables); 11533 SmallVector<VTableUse, 4> NewUses; 11534 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 11535 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 11536 = VTablesUsed.find(VTables[I].Record); 11537 // Even if a definition wasn't required before, it may be required now. 11538 if (Pos != VTablesUsed.end()) { 11539 if (!Pos->second && VTables[I].DefinitionRequired) 11540 Pos->second = true; 11541 continue; 11542 } 11543 11544 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 11545 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 11546 } 11547 11548 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 11549} 11550 11551void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 11552 bool DefinitionRequired) { 11553 // Ignore any vtable uses in unevaluated operands or for classes that do 11554 // not have a vtable. 11555 if (!Class->isDynamicClass() || Class->isDependentContext() || 11556 CurContext->isDependentContext() || 11557 ExprEvalContexts.back().Context == Unevaluated) 11558 return; 11559 11560 // Try to insert this class into the map. 11561 LoadExternalVTableUses(); 11562 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 11563 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 11564 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 11565 if (!Pos.second) { 11566 // If we already had an entry, check to see if we are promoting this vtable 11567 // to required a definition. If so, we need to reappend to the VTableUses 11568 // list, since we may have already processed the first entry. 11569 if (DefinitionRequired && !Pos.first->second) { 11570 Pos.first->second = true; 11571 } else { 11572 // Otherwise, we can early exit. 11573 return; 11574 } 11575 } 11576 11577 // Local classes need to have their virtual members marked 11578 // immediately. For all other classes, we mark their virtual members 11579 // at the end of the translation unit. 11580 if (Class->isLocalClass()) 11581 MarkVirtualMembersReferenced(Loc, Class); 11582 else 11583 VTableUses.push_back(std::make_pair(Class, Loc)); 11584} 11585 11586bool Sema::DefineUsedVTables() { 11587 LoadExternalVTableUses(); 11588 if (VTableUses.empty()) 11589 return false; 11590 11591 // Note: The VTableUses vector could grow as a result of marking 11592 // the members of a class as "used", so we check the size each 11593 // time through the loop and prefer indices (which are stable) to 11594 // iterators (which are not). 11595 bool DefinedAnything = false; 11596 for (unsigned I = 0; I != VTableUses.size(); ++I) { 11597 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 11598 if (!Class) 11599 continue; 11600 11601 SourceLocation Loc = VTableUses[I].second; 11602 11603 bool DefineVTable = true; 11604 11605 // If this class has a key function, but that key function is 11606 // defined in another translation unit, we don't need to emit the 11607 // vtable even though we're using it. 11608 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 11609 if (KeyFunction && !KeyFunction->hasBody()) { 11610 switch (KeyFunction->getTemplateSpecializationKind()) { 11611 case TSK_Undeclared: 11612 case TSK_ExplicitSpecialization: 11613 case TSK_ExplicitInstantiationDeclaration: 11614 // The key function is in another translation unit. 11615 DefineVTable = false; 11616 break; 11617 11618 case TSK_ExplicitInstantiationDefinition: 11619 case TSK_ImplicitInstantiation: 11620 // We will be instantiating the key function. 11621 break; 11622 } 11623 } else if (!KeyFunction) { 11624 // If we have a class with no key function that is the subject 11625 // of an explicit instantiation declaration, suppress the 11626 // vtable; it will live with the explicit instantiation 11627 // definition. 11628 bool IsExplicitInstantiationDeclaration 11629 = Class->getTemplateSpecializationKind() 11630 == TSK_ExplicitInstantiationDeclaration; 11631 for (TagDecl::redecl_iterator R = Class->redecls_begin(), 11632 REnd = Class->redecls_end(); 11633 R != REnd; ++R) { 11634 TemplateSpecializationKind TSK 11635 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind(); 11636 if (TSK == TSK_ExplicitInstantiationDeclaration) 11637 IsExplicitInstantiationDeclaration = true; 11638 else if (TSK == TSK_ExplicitInstantiationDefinition) { 11639 IsExplicitInstantiationDeclaration = false; 11640 break; 11641 } 11642 } 11643 11644 if (IsExplicitInstantiationDeclaration) 11645 DefineVTable = false; 11646 } 11647 11648 // The exception specifications for all virtual members may be needed even 11649 // if we are not providing an authoritative form of the vtable in this TU. 11650 // We may choose to emit it available_externally anyway. 11651 if (!DefineVTable) { 11652 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 11653 continue; 11654 } 11655 11656 // Mark all of the virtual members of this class as referenced, so 11657 // that we can build a vtable. Then, tell the AST consumer that a 11658 // vtable for this class is required. 11659 DefinedAnything = true; 11660 MarkVirtualMembersReferenced(Loc, Class); 11661 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 11662 Consumer.HandleVTable(Class, VTablesUsed[Canonical]); 11663 11664 // Optionally warn if we're emitting a weak vtable. 11665 if (Class->hasExternalLinkage() && 11666 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) { 11667 const FunctionDecl *KeyFunctionDef = 0; 11668 if (!KeyFunction || 11669 (KeyFunction->hasBody(KeyFunctionDef) && 11670 KeyFunctionDef->isInlined())) 11671 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() == 11672 TSK_ExplicitInstantiationDefinition 11673 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable) 11674 << Class; 11675 } 11676 } 11677 VTableUses.clear(); 11678 11679 return DefinedAnything; 11680} 11681 11682void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 11683 const CXXRecordDecl *RD) { 11684 for (CXXRecordDecl::method_iterator I = RD->method_begin(), 11685 E = RD->method_end(); I != E; ++I) 11686 if ((*I)->isVirtual() && !(*I)->isPure()) 11687 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>()); 11688} 11689 11690void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 11691 const CXXRecordDecl *RD) { 11692 // Mark all functions which will appear in RD's vtable as used. 11693 CXXFinalOverriderMap FinalOverriders; 11694 RD->getFinalOverriders(FinalOverriders); 11695 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 11696 E = FinalOverriders.end(); 11697 I != E; ++I) { 11698 for (OverridingMethods::const_iterator OI = I->second.begin(), 11699 OE = I->second.end(); 11700 OI != OE; ++OI) { 11701 assert(OI->second.size() > 0 && "no final overrider"); 11702 CXXMethodDecl *Overrider = OI->second.front().Method; 11703 11704 // C++ [basic.def.odr]p2: 11705 // [...] A virtual member function is used if it is not pure. [...] 11706 if (!Overrider->isPure()) 11707 MarkFunctionReferenced(Loc, Overrider); 11708 } 11709 } 11710 11711 // Only classes that have virtual bases need a VTT. 11712 if (RD->getNumVBases() == 0) 11713 return; 11714 11715 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(), 11716 e = RD->bases_end(); i != e; ++i) { 11717 const CXXRecordDecl *Base = 11718 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl()); 11719 if (Base->getNumVBases() == 0) 11720 continue; 11721 MarkVirtualMembersReferenced(Loc, Base); 11722 } 11723} 11724 11725/// SetIvarInitializers - This routine builds initialization ASTs for the 11726/// Objective-C implementation whose ivars need be initialized. 11727void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 11728 if (!getLangOpts().CPlusPlus) 11729 return; 11730 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 11731 SmallVector<ObjCIvarDecl*, 8> ivars; 11732 CollectIvarsToConstructOrDestruct(OID, ivars); 11733 if (ivars.empty()) 11734 return; 11735 SmallVector<CXXCtorInitializer*, 32> AllToInit; 11736 for (unsigned i = 0; i < ivars.size(); i++) { 11737 FieldDecl *Field = ivars[i]; 11738 if (Field->isInvalidDecl()) 11739 continue; 11740 11741 CXXCtorInitializer *Member; 11742 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 11743 InitializationKind InitKind = 11744 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 11745 11746 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0); 11747 ExprResult MemberInit = 11748 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg()); 11749 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 11750 // Note, MemberInit could actually come back empty if no initialization 11751 // is required (e.g., because it would call a trivial default constructor) 11752 if (!MemberInit.get() || MemberInit.isInvalid()) 11753 continue; 11754 11755 Member = 11756 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 11757 SourceLocation(), 11758 MemberInit.takeAs<Expr>(), 11759 SourceLocation()); 11760 AllToInit.push_back(Member); 11761 11762 // Be sure that the destructor is accessible and is marked as referenced. 11763 if (const RecordType *RecordTy 11764 = Context.getBaseElementType(Field->getType()) 11765 ->getAs<RecordType>()) { 11766 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 11767 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 11768 MarkFunctionReferenced(Field->getLocation(), Destructor); 11769 CheckDestructorAccess(Field->getLocation(), Destructor, 11770 PDiag(diag::err_access_dtor_ivar) 11771 << Context.getBaseElementType(Field->getType())); 11772 } 11773 } 11774 } 11775 ObjCImplementation->setIvarInitializers(Context, 11776 AllToInit.data(), AllToInit.size()); 11777 } 11778} 11779 11780static 11781void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 11782 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid, 11783 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid, 11784 llvm::SmallSet<CXXConstructorDecl*, 4> &Current, 11785 Sema &S) { 11786 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(), 11787 CE = Current.end(); 11788 if (Ctor->isInvalidDecl()) 11789 return; 11790 11791 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 11792 11793 // Target may not be determinable yet, for instance if this is a dependent 11794 // call in an uninstantiated template. 11795 if (Target) { 11796 const FunctionDecl *FNTarget = 0; 11797 (void)Target->hasBody(FNTarget); 11798 Target = const_cast<CXXConstructorDecl*>( 11799 cast_or_null<CXXConstructorDecl>(FNTarget)); 11800 } 11801 11802 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 11803 // Avoid dereferencing a null pointer here. 11804 *TCanonical = Target ? Target->getCanonicalDecl() : 0; 11805 11806 if (!Current.insert(Canonical)) 11807 return; 11808 11809 // We know that beyond here, we aren't chaining into a cycle. 11810 if (!Target || !Target->isDelegatingConstructor() || 11811 Target->isInvalidDecl() || Valid.count(TCanonical)) { 11812 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI) 11813 Valid.insert(*CI); 11814 Current.clear(); 11815 // We've hit a cycle. 11816 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 11817 Current.count(TCanonical)) { 11818 // If we haven't diagnosed this cycle yet, do so now. 11819 if (!Invalid.count(TCanonical)) { 11820 S.Diag((*Ctor->init_begin())->getSourceLocation(), 11821 diag::warn_delegating_ctor_cycle) 11822 << Ctor; 11823 11824 // Don't add a note for a function delegating directly to itself. 11825 if (TCanonical != Canonical) 11826 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 11827 11828 CXXConstructorDecl *C = Target; 11829 while (C->getCanonicalDecl() != Canonical) { 11830 const FunctionDecl *FNTarget = 0; 11831 (void)C->getTargetConstructor()->hasBody(FNTarget); 11832 assert(FNTarget && "Ctor cycle through bodiless function"); 11833 11834 C = const_cast<CXXConstructorDecl*>( 11835 cast<CXXConstructorDecl>(FNTarget)); 11836 S.Diag(C->getLocation(), diag::note_which_delegates_to); 11837 } 11838 } 11839 11840 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI) 11841 Invalid.insert(*CI); 11842 Current.clear(); 11843 } else { 11844 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 11845 } 11846} 11847 11848 11849void Sema::CheckDelegatingCtorCycles() { 11850 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 11851 11852 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(), 11853 CE = Current.end(); 11854 11855 for (DelegatingCtorDeclsType::iterator 11856 I = DelegatingCtorDecls.begin(ExternalSource), 11857 E = DelegatingCtorDecls.end(); 11858 I != E; ++I) 11859 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 11860 11861 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI) 11862 (*CI)->setInvalidDecl(); 11863} 11864 11865namespace { 11866 /// \brief AST visitor that finds references to the 'this' expression. 11867 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 11868 Sema &S; 11869 11870 public: 11871 explicit FindCXXThisExpr(Sema &S) : S(S) { } 11872 11873 bool VisitCXXThisExpr(CXXThisExpr *E) { 11874 S.Diag(E->getLocation(), diag::err_this_static_member_func) 11875 << E->isImplicit(); 11876 return false; 11877 } 11878 }; 11879} 11880 11881bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 11882 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 11883 if (!TSInfo) 11884 return false; 11885 11886 TypeLoc TL = TSInfo->getTypeLoc(); 11887 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 11888 if (!ProtoTL) 11889 return false; 11890 11891 // C++11 [expr.prim.general]p3: 11892 // [The expression this] shall not appear before the optional 11893 // cv-qualifier-seq and it shall not appear within the declaration of a 11894 // static member function (although its type and value category are defined 11895 // within a static member function as they are within a non-static member 11896 // function). [ Note: this is because declaration matching does not occur 11897 // until the complete declarator is known. - end note ] 11898 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 11899 FindCXXThisExpr Finder(*this); 11900 11901 // If the return type came after the cv-qualifier-seq, check it now. 11902 if (Proto->hasTrailingReturn() && 11903 !Finder.TraverseTypeLoc(ProtoTL.getResultLoc())) 11904 return true; 11905 11906 // Check the exception specification. 11907 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 11908 return true; 11909 11910 return checkThisInStaticMemberFunctionAttributes(Method); 11911} 11912 11913bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 11914 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 11915 if (!TSInfo) 11916 return false; 11917 11918 TypeLoc TL = TSInfo->getTypeLoc(); 11919 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 11920 if (!ProtoTL) 11921 return false; 11922 11923 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 11924 FindCXXThisExpr Finder(*this); 11925 11926 switch (Proto->getExceptionSpecType()) { 11927 case EST_Uninstantiated: 11928 case EST_Unevaluated: 11929 case EST_BasicNoexcept: 11930 case EST_DynamicNone: 11931 case EST_MSAny: 11932 case EST_None: 11933 break; 11934 11935 case EST_ComputedNoexcept: 11936 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 11937 return true; 11938 11939 case EST_Dynamic: 11940 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(), 11941 EEnd = Proto->exception_end(); 11942 E != EEnd; ++E) { 11943 if (!Finder.TraverseType(*E)) 11944 return true; 11945 } 11946 break; 11947 } 11948 11949 return false; 11950} 11951 11952bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 11953 FindCXXThisExpr Finder(*this); 11954 11955 // Check attributes. 11956 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end(); 11957 A != AEnd; ++A) { 11958 // FIXME: This should be emitted by tblgen. 11959 Expr *Arg = 0; 11960 ArrayRef<Expr *> Args; 11961 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A)) 11962 Arg = G->getArg(); 11963 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A)) 11964 Arg = G->getArg(); 11965 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A)) 11966 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size()); 11967 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A)) 11968 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size()); 11969 else if (ExclusiveLockFunctionAttr *ELF 11970 = dyn_cast<ExclusiveLockFunctionAttr>(*A)) 11971 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size()); 11972 else if (SharedLockFunctionAttr *SLF 11973 = dyn_cast<SharedLockFunctionAttr>(*A)) 11974 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size()); 11975 else if (ExclusiveTrylockFunctionAttr *ETLF 11976 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) { 11977 Arg = ETLF->getSuccessValue(); 11978 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size()); 11979 } else if (SharedTrylockFunctionAttr *STLF 11980 = dyn_cast<SharedTrylockFunctionAttr>(*A)) { 11981 Arg = STLF->getSuccessValue(); 11982 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size()); 11983 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A)) 11984 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size()); 11985 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A)) 11986 Arg = LR->getArg(); 11987 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A)) 11988 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size()); 11989 else if (ExclusiveLocksRequiredAttr *ELR 11990 = dyn_cast<ExclusiveLocksRequiredAttr>(*A)) 11991 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size()); 11992 else if (SharedLocksRequiredAttr *SLR 11993 = dyn_cast<SharedLocksRequiredAttr>(*A)) 11994 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size()); 11995 11996 if (Arg && !Finder.TraverseStmt(Arg)) 11997 return true; 11998 11999 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 12000 if (!Finder.TraverseStmt(Args[I])) 12001 return true; 12002 } 12003 } 12004 12005 return false; 12006} 12007 12008void 12009Sema::checkExceptionSpecification(ExceptionSpecificationType EST, 12010 ArrayRef<ParsedType> DynamicExceptions, 12011 ArrayRef<SourceRange> DynamicExceptionRanges, 12012 Expr *NoexceptExpr, 12013 SmallVectorImpl<QualType> &Exceptions, 12014 FunctionProtoType::ExtProtoInfo &EPI) { 12015 Exceptions.clear(); 12016 EPI.ExceptionSpecType = EST; 12017 if (EST == EST_Dynamic) { 12018 Exceptions.reserve(DynamicExceptions.size()); 12019 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 12020 // FIXME: Preserve type source info. 12021 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 12022 12023 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 12024 collectUnexpandedParameterPacks(ET, Unexpanded); 12025 if (!Unexpanded.empty()) { 12026 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(), 12027 UPPC_ExceptionType, 12028 Unexpanded); 12029 continue; 12030 } 12031 12032 // Check that the type is valid for an exception spec, and 12033 // drop it if not. 12034 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 12035 Exceptions.push_back(ET); 12036 } 12037 EPI.NumExceptions = Exceptions.size(); 12038 EPI.Exceptions = Exceptions.data(); 12039 return; 12040 } 12041 12042 if (EST == EST_ComputedNoexcept) { 12043 // If an error occurred, there's no expression here. 12044 if (NoexceptExpr) { 12045 assert((NoexceptExpr->isTypeDependent() || 12046 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 12047 Context.BoolTy) && 12048 "Parser should have made sure that the expression is boolean"); 12049 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 12050 EPI.ExceptionSpecType = EST_BasicNoexcept; 12051 return; 12052 } 12053 12054 if (!NoexceptExpr->isValueDependent()) 12055 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0, 12056 diag::err_noexcept_needs_constant_expression, 12057 /*AllowFold*/ false).take(); 12058 EPI.NoexceptExpr = NoexceptExpr; 12059 } 12060 return; 12061 } 12062} 12063 12064/// IdentifyCUDATarget - Determine the CUDA compilation target for this function 12065Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) { 12066 // Implicitly declared functions (e.g. copy constructors) are 12067 // __host__ __device__ 12068 if (D->isImplicit()) 12069 return CFT_HostDevice; 12070 12071 if (D->hasAttr<CUDAGlobalAttr>()) 12072 return CFT_Global; 12073 12074 if (D->hasAttr<CUDADeviceAttr>()) { 12075 if (D->hasAttr<CUDAHostAttr>()) 12076 return CFT_HostDevice; 12077 else 12078 return CFT_Device; 12079 } 12080 12081 return CFT_Host; 12082} 12083 12084bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget, 12085 CUDAFunctionTarget CalleeTarget) { 12086 // CUDA B.1.1 "The __device__ qualifier declares a function that is... 12087 // Callable from the device only." 12088 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device) 12089 return true; 12090 12091 // CUDA B.1.2 "The __global__ qualifier declares a function that is... 12092 // Callable from the host only." 12093 // CUDA B.1.3 "The __host__ qualifier declares a function that is... 12094 // Callable from the host only." 12095 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) && 12096 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global)) 12097 return true; 12098 12099 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice) 12100 return true; 12101 12102 return false; 12103} 12104 12105/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 12106/// 12107MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 12108 SourceLocation DeclStart, 12109 Declarator &D, Expr *BitWidth, 12110 InClassInitStyle InitStyle, 12111 AccessSpecifier AS, 12112 AttributeList *MSPropertyAttr) { 12113 IdentifierInfo *II = D.getIdentifier(); 12114 if (!II) { 12115 Diag(DeclStart, diag::err_anonymous_property); 12116 return NULL; 12117 } 12118 SourceLocation Loc = D.getIdentifierLoc(); 12119 12120 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12121 QualType T = TInfo->getType(); 12122 if (getLangOpts().CPlusPlus) { 12123 CheckExtraCXXDefaultArguments(D); 12124 12125 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 12126 UPPC_DataMemberType)) { 12127 D.setInvalidType(); 12128 T = Context.IntTy; 12129 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 12130 } 12131 } 12132 12133 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 12134 12135 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 12136 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 12137 diag::err_invalid_thread) 12138 << DeclSpec::getSpecifierName(TSCS); 12139 12140 // Check to see if this name was declared as a member previously 12141 NamedDecl *PrevDecl = 0; 12142 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 12143 LookupName(Previous, S); 12144 switch (Previous.getResultKind()) { 12145 case LookupResult::Found: 12146 case LookupResult::FoundUnresolvedValue: 12147 PrevDecl = Previous.getAsSingle<NamedDecl>(); 12148 break; 12149 12150 case LookupResult::FoundOverloaded: 12151 PrevDecl = Previous.getRepresentativeDecl(); 12152 break; 12153 12154 case LookupResult::NotFound: 12155 case LookupResult::NotFoundInCurrentInstantiation: 12156 case LookupResult::Ambiguous: 12157 break; 12158 } 12159 12160 if (PrevDecl && PrevDecl->isTemplateParameter()) { 12161 // Maybe we will complain about the shadowed template parameter. 12162 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 12163 // Just pretend that we didn't see the previous declaration. 12164 PrevDecl = 0; 12165 } 12166 12167 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 12168 PrevDecl = 0; 12169 12170 SourceLocation TSSL = D.getLocStart(); 12171 MSPropertyDecl *NewPD; 12172 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData(); 12173 NewPD = new (Context) MSPropertyDecl(Record, Loc, 12174 II, T, TInfo, TSSL, 12175 Data.GetterId, Data.SetterId); 12176 ProcessDeclAttributes(TUScope, NewPD, D); 12177 NewPD->setAccess(AS); 12178 12179 if (NewPD->isInvalidDecl()) 12180 Record->setInvalidDecl(); 12181 12182 if (D.getDeclSpec().isModulePrivateSpecified()) 12183 NewPD->setModulePrivate(); 12184 12185 if (NewPD->isInvalidDecl() && PrevDecl) { 12186 // Don't introduce NewFD into scope; there's already something 12187 // with the same name in the same scope. 12188 } else if (II) { 12189 PushOnScopeChains(NewPD, S); 12190 } else 12191 Record->addDecl(NewPD); 12192 12193 return NewPD; 12194} 12195