SemaDeclCXX.cpp revision 045d2524e136fabd10613d7ac0063df632a7c2a5
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 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc, 149 CXXMethodDecl *Method) { 150 // If we have an MSAny spec already, don't bother. 151 if (!Method || ComputedEST == EST_MSAny) 152 return; 153 154 const FunctionProtoType *Proto 155 = Method->getType()->getAs<FunctionProtoType>(); 156 Proto = Self->ResolveExceptionSpec(CallLoc, Proto); 157 if (!Proto) 158 return; 159 160 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 161 162 // If this function can throw any exceptions, make a note of that. 163 if (EST == EST_MSAny || EST == EST_None) { 164 ClearExceptions(); 165 ComputedEST = EST; 166 return; 167 } 168 169 // FIXME: If the call to this decl is using any of its default arguments, we 170 // need to search them for potentially-throwing calls. 171 172 // If this function has a basic noexcept, it doesn't affect the outcome. 173 if (EST == EST_BasicNoexcept) 174 return; 175 176 // If we have a throw-all spec at this point, ignore the function. 177 if (ComputedEST == EST_None) 178 return; 179 180 // If we're still at noexcept(true) and there's a nothrow() callee, 181 // change to that specification. 182 if (EST == EST_DynamicNone) { 183 if (ComputedEST == EST_BasicNoexcept) 184 ComputedEST = EST_DynamicNone; 185 return; 186 } 187 188 // Check out noexcept specs. 189 if (EST == EST_ComputedNoexcept) { 190 FunctionProtoType::NoexceptResult NR = 191 Proto->getNoexceptSpec(Self->Context); 192 assert(NR != FunctionProtoType::NR_NoNoexcept && 193 "Must have noexcept result for EST_ComputedNoexcept."); 194 assert(NR != FunctionProtoType::NR_Dependent && 195 "Should not generate implicit declarations for dependent cases, " 196 "and don't know how to handle them anyway."); 197 198 // noexcept(false) -> no spec on the new function 199 if (NR == FunctionProtoType::NR_Throw) { 200 ClearExceptions(); 201 ComputedEST = EST_None; 202 } 203 // noexcept(true) won't change anything either. 204 return; 205 } 206 207 assert(EST == EST_Dynamic && "EST case not considered earlier."); 208 assert(ComputedEST != EST_None && 209 "Shouldn't collect exceptions when throw-all is guaranteed."); 210 ComputedEST = EST_Dynamic; 211 // Record the exceptions in this function's exception specification. 212 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(), 213 EEnd = Proto->exception_end(); 214 E != EEnd; ++E) 215 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E))) 216 Exceptions.push_back(*E); 217} 218 219void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) { 220 if (!E || ComputedEST == EST_MSAny) 221 return; 222 223 // FIXME: 224 // 225 // C++0x [except.spec]p14: 226 // [An] implicit exception-specification specifies the type-id T if and 227 // only if T is allowed by the exception-specification of a function directly 228 // invoked by f's implicit definition; f shall allow all exceptions if any 229 // function it directly invokes allows all exceptions, and f shall allow no 230 // exceptions if every function it directly invokes allows no exceptions. 231 // 232 // Note in particular that if an implicit exception-specification is generated 233 // for a function containing a throw-expression, that specification can still 234 // be noexcept(true). 235 // 236 // Note also that 'directly invoked' is not defined in the standard, and there 237 // is no indication that we should only consider potentially-evaluated calls. 238 // 239 // Ultimately we should implement the intent of the standard: the exception 240 // specification should be the set of exceptions which can be thrown by the 241 // implicit definition. For now, we assume that any non-nothrow expression can 242 // throw any exception. 243 244 if (Self->canThrow(E)) 245 ComputedEST = EST_None; 246} 247 248bool 249Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 250 SourceLocation EqualLoc) { 251 if (RequireCompleteType(Param->getLocation(), Param->getType(), 252 diag::err_typecheck_decl_incomplete_type)) { 253 Param->setInvalidDecl(); 254 return true; 255 } 256 257 // C++ [dcl.fct.default]p5 258 // A default argument expression is implicitly converted (clause 259 // 4) to the parameter type. The default argument expression has 260 // the same semantic constraints as the initializer expression in 261 // a declaration of a variable of the parameter type, using the 262 // copy-initialization semantics (8.5). 263 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 264 Param); 265 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 266 EqualLoc); 267 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1); 268 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); 269 if (Result.isInvalid()) 270 return true; 271 Arg = Result.takeAs<Expr>(); 272 273 CheckCompletedExpr(Arg, EqualLoc); 274 Arg = MaybeCreateExprWithCleanups(Arg); 275 276 // Okay: add the default argument to the parameter 277 Param->setDefaultArg(Arg); 278 279 // We have already instantiated this parameter; provide each of the 280 // instantiations with the uninstantiated default argument. 281 UnparsedDefaultArgInstantiationsMap::iterator InstPos 282 = UnparsedDefaultArgInstantiations.find(Param); 283 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 284 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 285 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 286 287 // We're done tracking this parameter's instantiations. 288 UnparsedDefaultArgInstantiations.erase(InstPos); 289 } 290 291 return false; 292} 293 294/// ActOnParamDefaultArgument - Check whether the default argument 295/// provided for a function parameter is well-formed. If so, attach it 296/// to the parameter declaration. 297void 298Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 299 Expr *DefaultArg) { 300 if (!param || !DefaultArg) 301 return; 302 303 ParmVarDecl *Param = cast<ParmVarDecl>(param); 304 UnparsedDefaultArgLocs.erase(Param); 305 306 // Default arguments are only permitted in C++ 307 if (!getLangOpts().CPlusPlus) { 308 Diag(EqualLoc, diag::err_param_default_argument) 309 << DefaultArg->getSourceRange(); 310 Param->setInvalidDecl(); 311 return; 312 } 313 314 // Check for unexpanded parameter packs. 315 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 316 Param->setInvalidDecl(); 317 return; 318 } 319 320 // Check that the default argument is well-formed 321 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this); 322 if (DefaultArgChecker.Visit(DefaultArg)) { 323 Param->setInvalidDecl(); 324 return; 325 } 326 327 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 328} 329 330/// ActOnParamUnparsedDefaultArgument - We've seen a default 331/// argument for a function parameter, but we can't parse it yet 332/// because we're inside a class definition. Note that this default 333/// argument will be parsed later. 334void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 335 SourceLocation EqualLoc, 336 SourceLocation ArgLoc) { 337 if (!param) 338 return; 339 340 ParmVarDecl *Param = cast<ParmVarDecl>(param); 341 if (Param) 342 Param->setUnparsedDefaultArg(); 343 344 UnparsedDefaultArgLocs[Param] = ArgLoc; 345} 346 347/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 348/// the default argument for the parameter param failed. 349void Sema::ActOnParamDefaultArgumentError(Decl *param) { 350 if (!param) 351 return; 352 353 ParmVarDecl *Param = cast<ParmVarDecl>(param); 354 355 Param->setInvalidDecl(); 356 357 UnparsedDefaultArgLocs.erase(Param); 358} 359 360/// CheckExtraCXXDefaultArguments - Check for any extra default 361/// arguments in the declarator, which is not a function declaration 362/// or definition and therefore is not permitted to have default 363/// arguments. This routine should be invoked for every declarator 364/// that is not a function declaration or definition. 365void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 366 // C++ [dcl.fct.default]p3 367 // A default argument expression shall be specified only in the 368 // parameter-declaration-clause of a function declaration or in a 369 // template-parameter (14.1). It shall not be specified for a 370 // parameter pack. If it is specified in a 371 // parameter-declaration-clause, it shall not occur within a 372 // declarator or abstract-declarator of a parameter-declaration. 373 bool MightBeFunction = D.isFunctionDeclarationContext(); 374 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 375 DeclaratorChunk &chunk = D.getTypeObject(i); 376 if (chunk.Kind == DeclaratorChunk::Function) { 377 if (MightBeFunction) { 378 // This is a function declaration. It can have default arguments, but 379 // keep looking in case its return type is a function type with default 380 // arguments. 381 MightBeFunction = false; 382 continue; 383 } 384 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) { 385 ParmVarDecl *Param = 386 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param); 387 if (Param->hasUnparsedDefaultArg()) { 388 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens; 389 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 390 << SourceRange((*Toks)[1].getLocation(), 391 Toks->back().getLocation()); 392 delete Toks; 393 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0; 394 } else if (Param->getDefaultArg()) { 395 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 396 << Param->getDefaultArg()->getSourceRange(); 397 Param->setDefaultArg(0); 398 } 399 } 400 } else if (chunk.Kind != DeclaratorChunk::Paren) { 401 MightBeFunction = false; 402 } 403 } 404} 405 406/// MergeCXXFunctionDecl - Merge two declarations of the same C++ 407/// function, once we already know that they have the same 408/// type. Subroutine of MergeFunctionDecl. Returns true if there was an 409/// error, false otherwise. 410bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 411 Scope *S) { 412 bool Invalid = false; 413 414 // C++ [dcl.fct.default]p4: 415 // For non-template functions, default arguments can be added in 416 // later declarations of a function in the same 417 // scope. Declarations in different scopes have completely 418 // distinct sets of default arguments. That is, declarations in 419 // inner scopes do not acquire default arguments from 420 // declarations in outer scopes, and vice versa. In a given 421 // function declaration, all parameters subsequent to a 422 // parameter with a default argument shall have default 423 // arguments supplied in this or previous declarations. A 424 // default argument shall not be redefined by a later 425 // declaration (not even to the same value). 426 // 427 // C++ [dcl.fct.default]p6: 428 // Except for member functions of class templates, the default arguments 429 // in a member function definition that appears outside of the class 430 // definition are added to the set of default arguments provided by the 431 // member function declaration in the class definition. 432 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 433 ParmVarDecl *OldParam = Old->getParamDecl(p); 434 ParmVarDecl *NewParam = New->getParamDecl(p); 435 436 bool OldParamHasDfl = OldParam->hasDefaultArg(); 437 bool NewParamHasDfl = NewParam->hasDefaultArg(); 438 439 NamedDecl *ND = Old; 440 if (S && !isDeclInScope(ND, New->getDeclContext(), S)) 441 // Ignore default parameters of old decl if they are not in 442 // the same scope. 443 OldParamHasDfl = false; 444 445 if (OldParamHasDfl && NewParamHasDfl) { 446 447 unsigned DiagDefaultParamID = 448 diag::err_param_default_argument_redefinition; 449 450 // MSVC accepts that default parameters be redefined for member functions 451 // of template class. The new default parameter's value is ignored. 452 Invalid = true; 453 if (getLangOpts().MicrosoftExt) { 454 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New); 455 if (MD && MD->getParent()->getDescribedClassTemplate()) { 456 // Merge the old default argument into the new parameter. 457 NewParam->setHasInheritedDefaultArg(); 458 if (OldParam->hasUninstantiatedDefaultArg()) 459 NewParam->setUninstantiatedDefaultArg( 460 OldParam->getUninstantiatedDefaultArg()); 461 else 462 NewParam->setDefaultArg(OldParam->getInit()); 463 DiagDefaultParamID = diag::warn_param_default_argument_redefinition; 464 Invalid = false; 465 } 466 } 467 468 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 469 // hint here. Alternatively, we could walk the type-source information 470 // for NewParam to find the last source location in the type... but it 471 // isn't worth the effort right now. This is the kind of test case that 472 // is hard to get right: 473 // int f(int); 474 // void g(int (*fp)(int) = f); 475 // void g(int (*fp)(int) = &f); 476 Diag(NewParam->getLocation(), DiagDefaultParamID) 477 << NewParam->getDefaultArgRange(); 478 479 // Look for the function declaration where the default argument was 480 // actually written, which may be a declaration prior to Old. 481 for (FunctionDecl *Older = Old->getPreviousDecl(); 482 Older; Older = Older->getPreviousDecl()) { 483 if (!Older->getParamDecl(p)->hasDefaultArg()) 484 break; 485 486 OldParam = Older->getParamDecl(p); 487 } 488 489 Diag(OldParam->getLocation(), diag::note_previous_definition) 490 << OldParam->getDefaultArgRange(); 491 } else if (OldParamHasDfl) { 492 // Merge the old default argument into the new parameter. 493 // It's important to use getInit() here; getDefaultArg() 494 // strips off any top-level ExprWithCleanups. 495 NewParam->setHasInheritedDefaultArg(); 496 if (OldParam->hasUninstantiatedDefaultArg()) 497 NewParam->setUninstantiatedDefaultArg( 498 OldParam->getUninstantiatedDefaultArg()); 499 else 500 NewParam->setDefaultArg(OldParam->getInit()); 501 } else if (NewParamHasDfl) { 502 if (New->getDescribedFunctionTemplate()) { 503 // Paragraph 4, quoted above, only applies to non-template functions. 504 Diag(NewParam->getLocation(), 505 diag::err_param_default_argument_template_redecl) 506 << NewParam->getDefaultArgRange(); 507 Diag(Old->getLocation(), diag::note_template_prev_declaration) 508 << false; 509 } else if (New->getTemplateSpecializationKind() 510 != TSK_ImplicitInstantiation && 511 New->getTemplateSpecializationKind() != TSK_Undeclared) { 512 // C++ [temp.expr.spec]p21: 513 // Default function arguments shall not be specified in a declaration 514 // or a definition for one of the following explicit specializations: 515 // - the explicit specialization of a function template; 516 // - the explicit specialization of a member function template; 517 // - the explicit specialization of a member function of a class 518 // template where the class template specialization to which the 519 // member function specialization belongs is implicitly 520 // instantiated. 521 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 522 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 523 << New->getDeclName() 524 << NewParam->getDefaultArgRange(); 525 } else if (New->getDeclContext()->isDependentContext()) { 526 // C++ [dcl.fct.default]p6 (DR217): 527 // Default arguments for a member function of a class template shall 528 // be specified on the initial declaration of the member function 529 // within the class template. 530 // 531 // Reading the tea leaves a bit in DR217 and its reference to DR205 532 // leads me to the conclusion that one cannot add default function 533 // arguments for an out-of-line definition of a member function of a 534 // dependent type. 535 int WhichKind = 2; 536 if (CXXRecordDecl *Record 537 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 538 if (Record->getDescribedClassTemplate()) 539 WhichKind = 0; 540 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 541 WhichKind = 1; 542 else 543 WhichKind = 2; 544 } 545 546 Diag(NewParam->getLocation(), 547 diag::err_param_default_argument_member_template_redecl) 548 << WhichKind 549 << NewParam->getDefaultArgRange(); 550 } 551 } 552 } 553 554 // DR1344: If a default argument is added outside a class definition and that 555 // default argument makes the function a special member function, the program 556 // is ill-formed. This can only happen for constructors. 557 if (isa<CXXConstructorDecl>(New) && 558 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 559 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 560 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 561 if (NewSM != OldSM) { 562 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 563 assert(NewParam->hasDefaultArg()); 564 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 565 << NewParam->getDefaultArgRange() << NewSM; 566 Diag(Old->getLocation(), diag::note_previous_declaration); 567 } 568 } 569 570 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 571 // template has a constexpr specifier then all its declarations shall 572 // contain the constexpr specifier. 573 if (New->isConstexpr() != Old->isConstexpr()) { 574 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 575 << New << New->isConstexpr(); 576 Diag(Old->getLocation(), diag::note_previous_declaration); 577 Invalid = true; 578 } 579 580 if (CheckEquivalentExceptionSpec(Old, New)) 581 Invalid = true; 582 583 return Invalid; 584} 585 586/// \brief Merge the exception specifications of two variable declarations. 587/// 588/// This is called when there's a redeclaration of a VarDecl. The function 589/// checks if the redeclaration might have an exception specification and 590/// validates compatibility and merges the specs if necessary. 591void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 592 // Shortcut if exceptions are disabled. 593 if (!getLangOpts().CXXExceptions) 594 return; 595 596 assert(Context.hasSameType(New->getType(), Old->getType()) && 597 "Should only be called if types are otherwise the same."); 598 599 QualType NewType = New->getType(); 600 QualType OldType = Old->getType(); 601 602 // We're only interested in pointers and references to functions, as well 603 // as pointers to member functions. 604 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 605 NewType = R->getPointeeType(); 606 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 607 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 608 NewType = P->getPointeeType(); 609 OldType = OldType->getAs<PointerType>()->getPointeeType(); 610 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 611 NewType = M->getPointeeType(); 612 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 613 } 614 615 if (!NewType->isFunctionProtoType()) 616 return; 617 618 // There's lots of special cases for functions. For function pointers, system 619 // libraries are hopefully not as broken so that we don't need these 620 // workarounds. 621 if (CheckEquivalentExceptionSpec( 622 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 623 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 624 New->setInvalidDecl(); 625 } 626} 627 628/// CheckCXXDefaultArguments - Verify that the default arguments for a 629/// function declaration are well-formed according to C++ 630/// [dcl.fct.default]. 631void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 632 unsigned NumParams = FD->getNumParams(); 633 unsigned p; 634 635 bool IsLambda = FD->getOverloadedOperator() == OO_Call && 636 isa<CXXMethodDecl>(FD) && 637 cast<CXXMethodDecl>(FD)->getParent()->isLambda(); 638 639 // Find first parameter with a default argument 640 for (p = 0; p < NumParams; ++p) { 641 ParmVarDecl *Param = FD->getParamDecl(p); 642 if (Param->hasDefaultArg()) { 643 // C++11 [expr.prim.lambda]p5: 644 // [...] Default arguments (8.3.6) shall not be specified in the 645 // parameter-declaration-clause of a lambda-declarator. 646 // 647 // FIXME: Core issue 974 strikes this sentence, we only provide an 648 // extension warning. 649 if (IsLambda) 650 Diag(Param->getLocation(), diag::ext_lambda_default_arguments) 651 << Param->getDefaultArgRange(); 652 break; 653 } 654 } 655 656 // C++ [dcl.fct.default]p4: 657 // In a given function declaration, all parameters 658 // subsequent to a parameter with a default argument shall 659 // have default arguments supplied in this or previous 660 // declarations. A default argument shall not be redefined 661 // by a later declaration (not even to the same value). 662 unsigned LastMissingDefaultArg = 0; 663 for (; p < NumParams; ++p) { 664 ParmVarDecl *Param = FD->getParamDecl(p); 665 if (!Param->hasDefaultArg()) { 666 if (Param->isInvalidDecl()) 667 /* We already complained about this parameter. */; 668 else if (Param->getIdentifier()) 669 Diag(Param->getLocation(), 670 diag::err_param_default_argument_missing_name) 671 << Param->getIdentifier(); 672 else 673 Diag(Param->getLocation(), 674 diag::err_param_default_argument_missing); 675 676 LastMissingDefaultArg = p; 677 } 678 } 679 680 if (LastMissingDefaultArg > 0) { 681 // Some default arguments were missing. Clear out all of the 682 // default arguments up to (and including) the last missing 683 // default argument, so that we leave the function parameters 684 // in a semantically valid state. 685 for (p = 0; p <= LastMissingDefaultArg; ++p) { 686 ParmVarDecl *Param = FD->getParamDecl(p); 687 if (Param->hasDefaultArg()) { 688 Param->setDefaultArg(0); 689 } 690 } 691 } 692} 693 694// CheckConstexprParameterTypes - Check whether a function's parameter types 695// are all literal types. If so, return true. If not, produce a suitable 696// diagnostic and return false. 697static bool CheckConstexprParameterTypes(Sema &SemaRef, 698 const FunctionDecl *FD) { 699 unsigned ArgIndex = 0; 700 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 701 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(), 702 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) { 703 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 704 SourceLocation ParamLoc = PD->getLocation(); 705 if (!(*i)->isDependentType() && 706 SemaRef.RequireLiteralType(ParamLoc, *i, 707 diag::err_constexpr_non_literal_param, 708 ArgIndex+1, PD->getSourceRange(), 709 isa<CXXConstructorDecl>(FD))) 710 return false; 711 } 712 return true; 713} 714 715/// \brief Get diagnostic %select index for tag kind for 716/// record diagnostic message. 717/// WARNING: Indexes apply to particular diagnostics only! 718/// 719/// \returns diagnostic %select index. 720static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 721 switch (Tag) { 722 case TTK_Struct: return 0; 723 case TTK_Interface: return 1; 724 case TTK_Class: return 2; 725 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 726 } 727} 728 729// CheckConstexprFunctionDecl - Check whether a function declaration satisfies 730// the requirements of a constexpr function definition or a constexpr 731// constructor definition. If so, return true. If not, produce appropriate 732// diagnostics and return false. 733// 734// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 735bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) { 736 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 737 if (MD && MD->isInstance()) { 738 // C++11 [dcl.constexpr]p4: 739 // The definition of a constexpr constructor shall satisfy the following 740 // constraints: 741 // - the class shall not have any virtual base classes; 742 const CXXRecordDecl *RD = MD->getParent(); 743 if (RD->getNumVBases()) { 744 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 745 << isa<CXXConstructorDecl>(NewFD) 746 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 747 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(), 748 E = RD->vbases_end(); I != E; ++I) 749 Diag(I->getLocStart(), 750 diag::note_constexpr_virtual_base_here) << I->getSourceRange(); 751 return false; 752 } 753 } 754 755 if (!isa<CXXConstructorDecl>(NewFD)) { 756 // C++11 [dcl.constexpr]p3: 757 // The definition of a constexpr function shall satisfy the following 758 // constraints: 759 // - it shall not be virtual; 760 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 761 if (Method && Method->isVirtual()) { 762 Diag(NewFD->getLocation(), diag::err_constexpr_virtual); 763 764 // If it's not obvious why this function is virtual, find an overridden 765 // function which uses the 'virtual' keyword. 766 const CXXMethodDecl *WrittenVirtual = Method; 767 while (!WrittenVirtual->isVirtualAsWritten()) 768 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 769 if (WrittenVirtual != Method) 770 Diag(WrittenVirtual->getLocation(), 771 diag::note_overridden_virtual_function); 772 return false; 773 } 774 775 // - its return type shall be a literal type; 776 QualType RT = NewFD->getResultType(); 777 if (!RT->isDependentType() && 778 RequireLiteralType(NewFD->getLocation(), RT, 779 diag::err_constexpr_non_literal_return)) 780 return false; 781 } 782 783 // - each of its parameter types shall be a literal type; 784 if (!CheckConstexprParameterTypes(*this, NewFD)) 785 return false; 786 787 return true; 788} 789 790/// Check the given declaration statement is legal within a constexpr function 791/// body. C++0x [dcl.constexpr]p3,p4. 792/// 793/// \return true if the body is OK, false if we have diagnosed a problem. 794static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 795 DeclStmt *DS) { 796 // C++0x [dcl.constexpr]p3 and p4: 797 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 798 // contain only 799 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(), 800 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) { 801 switch ((*DclIt)->getKind()) { 802 case Decl::StaticAssert: 803 case Decl::Using: 804 case Decl::UsingShadow: 805 case Decl::UsingDirective: 806 case Decl::UnresolvedUsingTypename: 807 // - static_assert-declarations 808 // - using-declarations, 809 // - using-directives, 810 continue; 811 812 case Decl::Typedef: 813 case Decl::TypeAlias: { 814 // - typedef declarations and alias-declarations that do not define 815 // classes or enumerations, 816 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt); 817 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 818 // Don't allow variably-modified types in constexpr functions. 819 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 820 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 821 << TL.getSourceRange() << TL.getType() 822 << isa<CXXConstructorDecl>(Dcl); 823 return false; 824 } 825 continue; 826 } 827 828 case Decl::Enum: 829 case Decl::CXXRecord: 830 // As an extension, we allow the declaration (but not the definition) of 831 // classes and enumerations in all declarations, not just in typedef and 832 // alias declarations. 833 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) { 834 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition) 835 << isa<CXXConstructorDecl>(Dcl); 836 return false; 837 } 838 continue; 839 840 case Decl::Var: 841 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration) 842 << isa<CXXConstructorDecl>(Dcl); 843 return false; 844 845 default: 846 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt) 847 << isa<CXXConstructorDecl>(Dcl); 848 return false; 849 } 850 } 851 852 return true; 853} 854 855/// Check that the given field is initialized within a constexpr constructor. 856/// 857/// \param Dcl The constexpr constructor being checked. 858/// \param Field The field being checked. This may be a member of an anonymous 859/// struct or union nested within the class being checked. 860/// \param Inits All declarations, including anonymous struct/union members and 861/// indirect members, for which any initialization was provided. 862/// \param Diagnosed Set to true if an error is produced. 863static void CheckConstexprCtorInitializer(Sema &SemaRef, 864 const FunctionDecl *Dcl, 865 FieldDecl *Field, 866 llvm::SmallSet<Decl*, 16> &Inits, 867 bool &Diagnosed) { 868 if (Field->isUnnamedBitfield()) 869 return; 870 871 if (Field->isAnonymousStructOrUnion() && 872 Field->getType()->getAsCXXRecordDecl()->isEmpty()) 873 return; 874 875 if (!Inits.count(Field)) { 876 if (!Diagnosed) { 877 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init); 878 Diagnosed = true; 879 } 880 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init); 881 } else if (Field->isAnonymousStructOrUnion()) { 882 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 883 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end(); 884 I != E; ++I) 885 // If an anonymous union contains an anonymous struct of which any member 886 // is initialized, all members must be initialized. 887 if (!RD->isUnion() || Inits.count(*I)) 888 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed); 889 } 890} 891 892/// Check the body for the given constexpr function declaration only contains 893/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 894/// 895/// \return true if the body is OK, false if we have diagnosed a problem. 896bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) { 897 if (isa<CXXTryStmt>(Body)) { 898 // C++11 [dcl.constexpr]p3: 899 // The definition of a constexpr function shall satisfy the following 900 // constraints: [...] 901 // - its function-body shall be = delete, = default, or a 902 // compound-statement 903 // 904 // C++11 [dcl.constexpr]p4: 905 // In the definition of a constexpr constructor, [...] 906 // - its function-body shall not be a function-try-block; 907 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block) 908 << isa<CXXConstructorDecl>(Dcl); 909 return false; 910 } 911 912 // - its function-body shall be [...] a compound-statement that contains only 913 CompoundStmt *CompBody = cast<CompoundStmt>(Body); 914 915 SmallVector<SourceLocation, 4> ReturnStmts; 916 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(), 917 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) { 918 switch ((*BodyIt)->getStmtClass()) { 919 case Stmt::NullStmtClass: 920 // - null statements, 921 continue; 922 923 case Stmt::DeclStmtClass: 924 // - static_assert-declarations 925 // - using-declarations, 926 // - using-directives, 927 // - typedef declarations and alias-declarations that do not define 928 // classes or enumerations, 929 if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt))) 930 return false; 931 continue; 932 933 case Stmt::ReturnStmtClass: 934 // - and exactly one return statement; 935 if (isa<CXXConstructorDecl>(Dcl)) 936 break; 937 938 ReturnStmts.push_back((*BodyIt)->getLocStart()); 939 continue; 940 941 default: 942 break; 943 } 944 945 Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt) 946 << isa<CXXConstructorDecl>(Dcl); 947 return false; 948 } 949 950 if (const CXXConstructorDecl *Constructor 951 = dyn_cast<CXXConstructorDecl>(Dcl)) { 952 const CXXRecordDecl *RD = Constructor->getParent(); 953 // DR1359: 954 // - every non-variant non-static data member and base class sub-object 955 // shall be initialized; 956 // - if the class is a non-empty union, or for each non-empty anonymous 957 // union member of a non-union class, exactly one non-static data member 958 // shall be initialized; 959 if (RD->isUnion()) { 960 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) { 961 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init); 962 return false; 963 } 964 } else if (!Constructor->isDependentContext() && 965 !Constructor->isDelegatingConstructor()) { 966 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 967 968 // Skip detailed checking if we have enough initializers, and we would 969 // allow at most one initializer per member. 970 bool AnyAnonStructUnionMembers = false; 971 unsigned Fields = 0; 972 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 973 E = RD->field_end(); I != E; ++I, ++Fields) { 974 if (I->isAnonymousStructOrUnion()) { 975 AnyAnonStructUnionMembers = true; 976 break; 977 } 978 } 979 if (AnyAnonStructUnionMembers || 980 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 981 // Check initialization of non-static data members. Base classes are 982 // always initialized so do not need to be checked. Dependent bases 983 // might not have initializers in the member initializer list. 984 llvm::SmallSet<Decl*, 16> Inits; 985 for (CXXConstructorDecl::init_const_iterator 986 I = Constructor->init_begin(), E = Constructor->init_end(); 987 I != E; ++I) { 988 if (FieldDecl *FD = (*I)->getMember()) 989 Inits.insert(FD); 990 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember()) 991 Inits.insert(ID->chain_begin(), ID->chain_end()); 992 } 993 994 bool Diagnosed = false; 995 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 996 E = RD->field_end(); I != E; ++I) 997 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed); 998 if (Diagnosed) 999 return false; 1000 } 1001 } 1002 } else { 1003 if (ReturnStmts.empty()) { 1004 Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return); 1005 return false; 1006 } 1007 if (ReturnStmts.size() > 1) { 1008 Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return); 1009 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 1010 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return); 1011 return false; 1012 } 1013 } 1014 1015 // C++11 [dcl.constexpr]p5: 1016 // if no function argument values exist such that the function invocation 1017 // substitution would produce a constant expression, the program is 1018 // ill-formed; no diagnostic required. 1019 // C++11 [dcl.constexpr]p3: 1020 // - every constructor call and implicit conversion used in initializing the 1021 // return value shall be one of those allowed in a constant expression. 1022 // C++11 [dcl.constexpr]p4: 1023 // - every constructor involved in initializing non-static data members and 1024 // base class sub-objects shall be a constexpr constructor. 1025 SmallVector<PartialDiagnosticAt, 8> Diags; 1026 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) { 1027 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr) 1028 << isa<CXXConstructorDecl>(Dcl); 1029 for (size_t I = 0, N = Diags.size(); I != N; ++I) 1030 Diag(Diags[I].first, Diags[I].second); 1031 // Don't return false here: we allow this for compatibility in 1032 // system headers. 1033 } 1034 1035 return true; 1036} 1037 1038/// isCurrentClassName - Determine whether the identifier II is the 1039/// name of the class type currently being defined. In the case of 1040/// nested classes, this will only return true if II is the name of 1041/// the innermost class. 1042bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 1043 const CXXScopeSpec *SS) { 1044 assert(getLangOpts().CPlusPlus && "No class names in C!"); 1045 1046 CXXRecordDecl *CurDecl; 1047 if (SS && SS->isSet() && !SS->isInvalid()) { 1048 DeclContext *DC = computeDeclContext(*SS, true); 1049 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 1050 } else 1051 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1052 1053 if (CurDecl && CurDecl->getIdentifier()) 1054 return &II == CurDecl->getIdentifier(); 1055 else 1056 return false; 1057} 1058 1059/// \brief Determine whether the given class is a base class of the given 1060/// class, including looking at dependent bases. 1061static bool findCircularInheritance(const CXXRecordDecl *Class, 1062 const CXXRecordDecl *Current) { 1063 SmallVector<const CXXRecordDecl*, 8> Queue; 1064 1065 Class = Class->getCanonicalDecl(); 1066 while (true) { 1067 for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(), 1068 E = Current->bases_end(); 1069 I != E; ++I) { 1070 CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 1071 if (!Base) 1072 continue; 1073 1074 Base = Base->getDefinition(); 1075 if (!Base) 1076 continue; 1077 1078 if (Base->getCanonicalDecl() == Class) 1079 return true; 1080 1081 Queue.push_back(Base); 1082 } 1083 1084 if (Queue.empty()) 1085 return false; 1086 1087 Current = Queue.back(); 1088 Queue.pop_back(); 1089 } 1090 1091 return false; 1092} 1093 1094/// \brief Check the validity of a C++ base class specifier. 1095/// 1096/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 1097/// and returns NULL otherwise. 1098CXXBaseSpecifier * 1099Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 1100 SourceRange SpecifierRange, 1101 bool Virtual, AccessSpecifier Access, 1102 TypeSourceInfo *TInfo, 1103 SourceLocation EllipsisLoc) { 1104 QualType BaseType = TInfo->getType(); 1105 1106 // C++ [class.union]p1: 1107 // A union shall not have base classes. 1108 if (Class->isUnion()) { 1109 Diag(Class->getLocation(), diag::err_base_clause_on_union) 1110 << SpecifierRange; 1111 return 0; 1112 } 1113 1114 if (EllipsisLoc.isValid() && 1115 !TInfo->getType()->containsUnexpandedParameterPack()) { 1116 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 1117 << TInfo->getTypeLoc().getSourceRange(); 1118 EllipsisLoc = SourceLocation(); 1119 } 1120 1121 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 1122 1123 if (BaseType->isDependentType()) { 1124 // Make sure that we don't have circular inheritance among our dependent 1125 // bases. For non-dependent bases, the check for completeness below handles 1126 // this. 1127 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 1128 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 1129 ((BaseDecl = BaseDecl->getDefinition()) && 1130 findCircularInheritance(Class, BaseDecl))) { 1131 Diag(BaseLoc, diag::err_circular_inheritance) 1132 << BaseType << Context.getTypeDeclType(Class); 1133 1134 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 1135 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 1136 << BaseType; 1137 1138 return 0; 1139 } 1140 } 1141 1142 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1143 Class->getTagKind() == TTK_Class, 1144 Access, TInfo, EllipsisLoc); 1145 } 1146 1147 // Base specifiers must be record types. 1148 if (!BaseType->isRecordType()) { 1149 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 1150 return 0; 1151 } 1152 1153 // C++ [class.union]p1: 1154 // A union shall not be used as a base class. 1155 if (BaseType->isUnionType()) { 1156 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 1157 return 0; 1158 } 1159 1160 // C++ [class.derived]p2: 1161 // The class-name in a base-specifier shall not be an incompletely 1162 // defined class. 1163 if (RequireCompleteType(BaseLoc, BaseType, 1164 diag::err_incomplete_base_class, SpecifierRange)) { 1165 Class->setInvalidDecl(); 1166 return 0; 1167 } 1168 1169 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 1170 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 1171 assert(BaseDecl && "Record type has no declaration"); 1172 BaseDecl = BaseDecl->getDefinition(); 1173 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 1174 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 1175 assert(CXXBaseDecl && "Base type is not a C++ type"); 1176 1177 // C++ [class]p3: 1178 // If a class is marked final and it appears as a base-type-specifier in 1179 // base-clause, the program is ill-formed. 1180 if (CXXBaseDecl->hasAttr<FinalAttr>()) { 1181 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 1182 << CXXBaseDecl->getDeclName(); 1183 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl) 1184 << CXXBaseDecl->getDeclName(); 1185 return 0; 1186 } 1187 1188 if (BaseDecl->isInvalidDecl()) 1189 Class->setInvalidDecl(); 1190 1191 // Create the base specifier. 1192 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1193 Class->getTagKind() == TTK_Class, 1194 Access, TInfo, EllipsisLoc); 1195} 1196 1197/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 1198/// one entry in the base class list of a class specifier, for 1199/// example: 1200/// class foo : public bar, virtual private baz { 1201/// 'public bar' and 'virtual private baz' are each base-specifiers. 1202BaseResult 1203Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 1204 ParsedAttributes &Attributes, 1205 bool Virtual, AccessSpecifier Access, 1206 ParsedType basetype, SourceLocation BaseLoc, 1207 SourceLocation EllipsisLoc) { 1208 if (!classdecl) 1209 return true; 1210 1211 AdjustDeclIfTemplate(classdecl); 1212 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 1213 if (!Class) 1214 return true; 1215 1216 // We do not support any C++11 attributes on base-specifiers yet. 1217 // Diagnose any attributes we see. 1218 if (!Attributes.empty()) { 1219 for (AttributeList *Attr = Attributes.getList(); Attr; 1220 Attr = Attr->getNext()) { 1221 if (Attr->isInvalid() || 1222 Attr->getKind() == AttributeList::IgnoredAttribute) 1223 continue; 1224 Diag(Attr->getLoc(), 1225 Attr->getKind() == AttributeList::UnknownAttribute 1226 ? diag::warn_unknown_attribute_ignored 1227 : diag::err_base_specifier_attribute) 1228 << Attr->getName(); 1229 } 1230 } 1231 1232 TypeSourceInfo *TInfo = 0; 1233 GetTypeFromParser(basetype, &TInfo); 1234 1235 if (EllipsisLoc.isInvalid() && 1236 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 1237 UPPC_BaseType)) 1238 return true; 1239 1240 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 1241 Virtual, Access, TInfo, 1242 EllipsisLoc)) 1243 return BaseSpec; 1244 else 1245 Class->setInvalidDecl(); 1246 1247 return true; 1248} 1249 1250/// \brief Performs the actual work of attaching the given base class 1251/// specifiers to a C++ class. 1252bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 1253 unsigned NumBases) { 1254 if (NumBases == 0) 1255 return false; 1256 1257 // Used to keep track of which base types we have already seen, so 1258 // that we can properly diagnose redundant direct base types. Note 1259 // that the key is always the unqualified canonical type of the base 1260 // class. 1261 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 1262 1263 // Copy non-redundant base specifiers into permanent storage. 1264 unsigned NumGoodBases = 0; 1265 bool Invalid = false; 1266 for (unsigned idx = 0; idx < NumBases; ++idx) { 1267 QualType NewBaseType 1268 = Context.getCanonicalType(Bases[idx]->getType()); 1269 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 1270 1271 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 1272 if (KnownBase) { 1273 // C++ [class.mi]p3: 1274 // A class shall not be specified as a direct base class of a 1275 // derived class more than once. 1276 Diag(Bases[idx]->getLocStart(), 1277 diag::err_duplicate_base_class) 1278 << KnownBase->getType() 1279 << Bases[idx]->getSourceRange(); 1280 1281 // Delete the duplicate base class specifier; we're going to 1282 // overwrite its pointer later. 1283 Context.Deallocate(Bases[idx]); 1284 1285 Invalid = true; 1286 } else { 1287 // Okay, add this new base class. 1288 KnownBase = Bases[idx]; 1289 Bases[NumGoodBases++] = Bases[idx]; 1290 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 1291 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 1292 if (Class->isInterface() && 1293 (!RD->isInterface() || 1294 KnownBase->getAccessSpecifier() != AS_public)) { 1295 // The Microsoft extension __interface does not permit bases that 1296 // are not themselves public interfaces. 1297 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface) 1298 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName() 1299 << RD->getSourceRange(); 1300 Invalid = true; 1301 } 1302 if (RD->hasAttr<WeakAttr>()) 1303 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context)); 1304 } 1305 } 1306 } 1307 1308 // Attach the remaining base class specifiers to the derived class. 1309 Class->setBases(Bases, NumGoodBases); 1310 1311 // Delete the remaining (good) base class specifiers, since their 1312 // data has been copied into the CXXRecordDecl. 1313 for (unsigned idx = 0; idx < NumGoodBases; ++idx) 1314 Context.Deallocate(Bases[idx]); 1315 1316 return Invalid; 1317} 1318 1319/// ActOnBaseSpecifiers - Attach the given base specifiers to the 1320/// class, after checking whether there are any duplicate base 1321/// classes. 1322void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases, 1323 unsigned NumBases) { 1324 if (!ClassDecl || !Bases || !NumBases) 1325 return; 1326 1327 AdjustDeclIfTemplate(ClassDecl); 1328 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), 1329 (CXXBaseSpecifier**)(Bases), NumBases); 1330} 1331 1332/// \brief Determine whether the type \p Derived is a C++ class that is 1333/// derived from the type \p Base. 1334bool Sema::IsDerivedFrom(QualType Derived, QualType Base) { 1335 if (!getLangOpts().CPlusPlus) 1336 return false; 1337 1338 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1339 if (!DerivedRD) 1340 return false; 1341 1342 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1343 if (!BaseRD) 1344 return false; 1345 1346 // If either the base or the derived type is invalid, don't try to 1347 // check whether one is derived from the other. 1348 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 1349 return false; 1350 1351 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this. 1352 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD); 1353} 1354 1355/// \brief Determine whether the type \p Derived is a C++ class that is 1356/// derived from the type \p Base. 1357bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) { 1358 if (!getLangOpts().CPlusPlus) 1359 return false; 1360 1361 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1362 if (!DerivedRD) 1363 return false; 1364 1365 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1366 if (!BaseRD) 1367 return false; 1368 1369 return DerivedRD->isDerivedFrom(BaseRD, Paths); 1370} 1371 1372void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 1373 CXXCastPath &BasePathArray) { 1374 assert(BasePathArray.empty() && "Base path array must be empty!"); 1375 assert(Paths.isRecordingPaths() && "Must record paths!"); 1376 1377 const CXXBasePath &Path = Paths.front(); 1378 1379 // We first go backward and check if we have a virtual base. 1380 // FIXME: It would be better if CXXBasePath had the base specifier for 1381 // the nearest virtual base. 1382 unsigned Start = 0; 1383 for (unsigned I = Path.size(); I != 0; --I) { 1384 if (Path[I - 1].Base->isVirtual()) { 1385 Start = I - 1; 1386 break; 1387 } 1388 } 1389 1390 // Now add all bases. 1391 for (unsigned I = Start, E = Path.size(); I != E; ++I) 1392 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 1393} 1394 1395/// \brief Determine whether the given base path includes a virtual 1396/// base class. 1397bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) { 1398 for (CXXCastPath::const_iterator B = BasePath.begin(), 1399 BEnd = BasePath.end(); 1400 B != BEnd; ++B) 1401 if ((*B)->isVirtual()) 1402 return true; 1403 1404 return false; 1405} 1406 1407/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 1408/// conversion (where Derived and Base are class types) is 1409/// well-formed, meaning that the conversion is unambiguous (and 1410/// that all of the base classes are accessible). Returns true 1411/// and emits a diagnostic if the code is ill-formed, returns false 1412/// otherwise. Loc is the location where this routine should point to 1413/// if there is an error, and Range is the source range to highlight 1414/// if there is an error. 1415bool 1416Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1417 unsigned InaccessibleBaseID, 1418 unsigned AmbigiousBaseConvID, 1419 SourceLocation Loc, SourceRange Range, 1420 DeclarationName Name, 1421 CXXCastPath *BasePath) { 1422 // First, determine whether the path from Derived to Base is 1423 // ambiguous. This is slightly more expensive than checking whether 1424 // the Derived to Base conversion exists, because here we need to 1425 // explore multiple paths to determine if there is an ambiguity. 1426 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1427 /*DetectVirtual=*/false); 1428 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths); 1429 assert(DerivationOkay && 1430 "Can only be used with a derived-to-base conversion"); 1431 (void)DerivationOkay; 1432 1433 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 1434 if (InaccessibleBaseID) { 1435 // Check that the base class can be accessed. 1436 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(), 1437 InaccessibleBaseID)) { 1438 case AR_inaccessible: 1439 return true; 1440 case AR_accessible: 1441 case AR_dependent: 1442 case AR_delayed: 1443 break; 1444 } 1445 } 1446 1447 // Build a base path if necessary. 1448 if (BasePath) 1449 BuildBasePathArray(Paths, *BasePath); 1450 return false; 1451 } 1452 1453 // We know that the derived-to-base conversion is ambiguous, and 1454 // we're going to produce a diagnostic. Perform the derived-to-base 1455 // search just one more time to compute all of the possible paths so 1456 // that we can print them out. This is more expensive than any of 1457 // the previous derived-to-base checks we've done, but at this point 1458 // performance isn't as much of an issue. 1459 Paths.clear(); 1460 Paths.setRecordingPaths(true); 1461 bool StillOkay = IsDerivedFrom(Derived, Base, Paths); 1462 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 1463 (void)StillOkay; 1464 1465 // Build up a textual representation of the ambiguous paths, e.g., 1466 // D -> B -> A, that will be used to illustrate the ambiguous 1467 // conversions in the diagnostic. We only print one of the paths 1468 // to each base class subobject. 1469 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 1470 1471 Diag(Loc, AmbigiousBaseConvID) 1472 << Derived << Base << PathDisplayStr << Range << Name; 1473 return true; 1474} 1475 1476bool 1477Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1478 SourceLocation Loc, SourceRange Range, 1479 CXXCastPath *BasePath, 1480 bool IgnoreAccess) { 1481 return CheckDerivedToBaseConversion(Derived, Base, 1482 IgnoreAccess ? 0 1483 : diag::err_upcast_to_inaccessible_base, 1484 diag::err_ambiguous_derived_to_base_conv, 1485 Loc, Range, DeclarationName(), 1486 BasePath); 1487} 1488 1489 1490/// @brief Builds a string representing ambiguous paths from a 1491/// specific derived class to different subobjects of the same base 1492/// class. 1493/// 1494/// This function builds a string that can be used in error messages 1495/// to show the different paths that one can take through the 1496/// inheritance hierarchy to go from the derived class to different 1497/// subobjects of a base class. The result looks something like this: 1498/// @code 1499/// struct D -> struct B -> struct A 1500/// struct D -> struct C -> struct A 1501/// @endcode 1502std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 1503 std::string PathDisplayStr; 1504 std::set<unsigned> DisplayedPaths; 1505 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 1506 Path != Paths.end(); ++Path) { 1507 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 1508 // We haven't displayed a path to this particular base 1509 // class subobject yet. 1510 PathDisplayStr += "\n "; 1511 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 1512 for (CXXBasePath::const_iterator Element = Path->begin(); 1513 Element != Path->end(); ++Element) 1514 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 1515 } 1516 } 1517 1518 return PathDisplayStr; 1519} 1520 1521//===----------------------------------------------------------------------===// 1522// C++ class member Handling 1523//===----------------------------------------------------------------------===// 1524 1525/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 1526bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, 1527 SourceLocation ASLoc, 1528 SourceLocation ColonLoc, 1529 AttributeList *Attrs) { 1530 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 1531 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 1532 ASLoc, ColonLoc); 1533 CurContext->addHiddenDecl(ASDecl); 1534 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 1535} 1536 1537/// CheckOverrideControl - Check C++11 override control semantics. 1538void Sema::CheckOverrideControl(Decl *D) { 1539 if (D->isInvalidDecl()) 1540 return; 1541 1542 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 1543 1544 // Do we know which functions this declaration might be overriding? 1545 bool OverridesAreKnown = !MD || 1546 (!MD->getParent()->hasAnyDependentBases() && 1547 !MD->getType()->isDependentType()); 1548 1549 if (!MD || !MD->isVirtual()) { 1550 if (OverridesAreKnown) { 1551 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1552 Diag(OA->getLocation(), 1553 diag::override_keyword_only_allowed_on_virtual_member_functions) 1554 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 1555 D->dropAttr<OverrideAttr>(); 1556 } 1557 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1558 Diag(FA->getLocation(), 1559 diag::override_keyword_only_allowed_on_virtual_member_functions) 1560 << "final" << FixItHint::CreateRemoval(FA->getLocation()); 1561 D->dropAttr<FinalAttr>(); 1562 } 1563 } 1564 return; 1565 } 1566 1567 if (!OverridesAreKnown) 1568 return; 1569 1570 // C++11 [class.virtual]p5: 1571 // If a virtual function is marked with the virt-specifier override and 1572 // does not override a member function of a base class, the program is 1573 // ill-formed. 1574 bool HasOverriddenMethods = 1575 MD->begin_overridden_methods() != MD->end_overridden_methods(); 1576 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 1577 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 1578 << MD->getDeclName(); 1579} 1580 1581/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 1582/// function overrides a virtual member function marked 'final', according to 1583/// C++11 [class.virtual]p4. 1584bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 1585 const CXXMethodDecl *Old) { 1586 if (!Old->hasAttr<FinalAttr>()) 1587 return false; 1588 1589 Diag(New->getLocation(), diag::err_final_function_overridden) 1590 << New->getDeclName(); 1591 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 1592 return true; 1593} 1594 1595static bool InitializationHasSideEffects(const FieldDecl &FD) { 1596 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 1597 // FIXME: Destruction of ObjC lifetime types has side-effects. 1598 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 1599 return !RD->isCompleteDefinition() || 1600 !RD->hasTrivialDefaultConstructor() || 1601 !RD->hasTrivialDestructor(); 1602 return false; 1603} 1604 1605/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 1606/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 1607/// bitfield width if there is one, 'InitExpr' specifies the initializer if 1608/// one has been parsed, and 'InitStyle' is set if an in-class initializer is 1609/// present (but parsing it has been deferred). 1610NamedDecl * 1611Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 1612 MultiTemplateParamsArg TemplateParameterLists, 1613 Expr *BW, const VirtSpecifiers &VS, 1614 InClassInitStyle InitStyle) { 1615 const DeclSpec &DS = D.getDeclSpec(); 1616 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 1617 DeclarationName Name = NameInfo.getName(); 1618 SourceLocation Loc = NameInfo.getLoc(); 1619 1620 // For anonymous bitfields, the location should point to the type. 1621 if (Loc.isInvalid()) 1622 Loc = D.getLocStart(); 1623 1624 Expr *BitWidth = static_cast<Expr*>(BW); 1625 1626 assert(isa<CXXRecordDecl>(CurContext)); 1627 assert(!DS.isFriendSpecified()); 1628 1629 bool isFunc = D.isDeclarationOfFunction(); 1630 1631 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 1632 // The Microsoft extension __interface only permits public member functions 1633 // and prohibits constructors, destructors, operators, non-public member 1634 // functions, static methods and data members. 1635 unsigned InvalidDecl; 1636 bool ShowDeclName = true; 1637 if (!isFunc) 1638 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1; 1639 else if (AS != AS_public) 1640 InvalidDecl = 2; 1641 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 1642 InvalidDecl = 3; 1643 else switch (Name.getNameKind()) { 1644 case DeclarationName::CXXConstructorName: 1645 InvalidDecl = 4; 1646 ShowDeclName = false; 1647 break; 1648 1649 case DeclarationName::CXXDestructorName: 1650 InvalidDecl = 5; 1651 ShowDeclName = false; 1652 break; 1653 1654 case DeclarationName::CXXOperatorName: 1655 case DeclarationName::CXXConversionFunctionName: 1656 InvalidDecl = 6; 1657 break; 1658 1659 default: 1660 InvalidDecl = 0; 1661 break; 1662 } 1663 1664 if (InvalidDecl) { 1665 if (ShowDeclName) 1666 Diag(Loc, diag::err_invalid_member_in_interface) 1667 << (InvalidDecl-1) << Name; 1668 else 1669 Diag(Loc, diag::err_invalid_member_in_interface) 1670 << (InvalidDecl-1) << ""; 1671 return 0; 1672 } 1673 } 1674 1675 // C++ 9.2p6: A member shall not be declared to have automatic storage 1676 // duration (auto, register) or with the extern storage-class-specifier. 1677 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 1678 // data members and cannot be applied to names declared const or static, 1679 // and cannot be applied to reference members. 1680 switch (DS.getStorageClassSpec()) { 1681 case DeclSpec::SCS_unspecified: 1682 case DeclSpec::SCS_typedef: 1683 case DeclSpec::SCS_static: 1684 // FALL THROUGH. 1685 break; 1686 case DeclSpec::SCS_mutable: 1687 if (isFunc) { 1688 if (DS.getStorageClassSpecLoc().isValid()) 1689 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 1690 else 1691 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function); 1692 1693 // FIXME: It would be nicer if the keyword was ignored only for this 1694 // declarator. Otherwise we could get follow-up errors. 1695 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1696 } 1697 break; 1698 default: 1699 if (DS.getStorageClassSpecLoc().isValid()) 1700 Diag(DS.getStorageClassSpecLoc(), 1701 diag::err_storageclass_invalid_for_member); 1702 else 1703 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member); 1704 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1705 } 1706 1707 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 1708 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 1709 !isFunc); 1710 1711 if (DS.isConstexprSpecified() && isInstField) { 1712 SemaDiagnosticBuilder B = 1713 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 1714 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 1715 if (InitStyle == ICIS_NoInit) { 1716 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const"); 1717 D.getMutableDeclSpec().ClearConstexprSpec(); 1718 const char *PrevSpec; 1719 unsigned DiagID; 1720 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc, 1721 PrevSpec, DiagID, getLangOpts()); 1722 (void)Failed; 1723 assert(!Failed && "Making a constexpr member const shouldn't fail"); 1724 } else { 1725 B << 1; 1726 const char *PrevSpec; 1727 unsigned DiagID; 1728 if (D.getMutableDeclSpec().SetStorageClassSpec( 1729 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) { 1730 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 1731 "This is the only DeclSpec that should fail to be applied"); 1732 B << 1; 1733 } else { 1734 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 1735 isInstField = false; 1736 } 1737 } 1738 } 1739 1740 NamedDecl *Member; 1741 if (isInstField) { 1742 CXXScopeSpec &SS = D.getCXXScopeSpec(); 1743 1744 // Data members must have identifiers for names. 1745 if (!Name.isIdentifier()) { 1746 Diag(Loc, diag::err_bad_variable_name) 1747 << Name; 1748 return 0; 1749 } 1750 1751 IdentifierInfo *II = Name.getAsIdentifierInfo(); 1752 1753 // Member field could not be with "template" keyword. 1754 // So TemplateParameterLists should be empty in this case. 1755 if (TemplateParameterLists.size()) { 1756 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 1757 if (TemplateParams->size()) { 1758 // There is no such thing as a member field template. 1759 Diag(D.getIdentifierLoc(), diag::err_template_member) 1760 << II 1761 << SourceRange(TemplateParams->getTemplateLoc(), 1762 TemplateParams->getRAngleLoc()); 1763 } else { 1764 // There is an extraneous 'template<>' for this member. 1765 Diag(TemplateParams->getTemplateLoc(), 1766 diag::err_template_member_noparams) 1767 << II 1768 << SourceRange(TemplateParams->getTemplateLoc(), 1769 TemplateParams->getRAngleLoc()); 1770 } 1771 return 0; 1772 } 1773 1774 if (SS.isSet() && !SS.isInvalid()) { 1775 // The user provided a superfluous scope specifier inside a class 1776 // definition: 1777 // 1778 // class X { 1779 // int X::member; 1780 // }; 1781 if (DeclContext *DC = computeDeclContext(SS, false)) 1782 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc()); 1783 else 1784 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 1785 << Name << SS.getRange(); 1786 1787 SS.clear(); 1788 } 1789 1790 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth, 1791 InitStyle, AS); 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 const FunctionProtoType *NewFPT = cast<FunctionProtoType>( 4248 S.Context.getFunctionType(FPT->getResultType(), FPT->getArgTypes(), EPI)); 4249 FD->setType(QualType(NewFPT, 0)); 4250} 4251 4252void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 4253 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 4254 if (FPT->getExceptionSpecType() != EST_Unevaluated) 4255 return; 4256 4257 // Evaluate the exception specification. 4258 ImplicitExceptionSpecification ExceptSpec = 4259 computeImplicitExceptionSpec(*this, Loc, MD); 4260 4261 // Update the type of the special member to use it. 4262 updateExceptionSpec(*this, MD, FPT, ExceptSpec); 4263 4264 // A user-provided destructor can be defined outside the class. When that 4265 // happens, be sure to update the exception specification on both 4266 // declarations. 4267 const FunctionProtoType *CanonicalFPT = 4268 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 4269 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 4270 updateExceptionSpec(*this, MD->getCanonicalDecl(), 4271 CanonicalFPT, ExceptSpec); 4272} 4273 4274void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 4275 CXXRecordDecl *RD = MD->getParent(); 4276 CXXSpecialMember CSM = getSpecialMember(MD); 4277 4278 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 4279 "not an explicitly-defaulted special member"); 4280 4281 // Whether this was the first-declared instance of the constructor. 4282 // This affects whether we implicitly add an exception spec and constexpr. 4283 bool First = MD == MD->getCanonicalDecl(); 4284 4285 bool HadError = false; 4286 4287 // C++11 [dcl.fct.def.default]p1: 4288 // A function that is explicitly defaulted shall 4289 // -- be a special member function (checked elsewhere), 4290 // -- have the same type (except for ref-qualifiers, and except that a 4291 // copy operation can take a non-const reference) as an implicit 4292 // declaration, and 4293 // -- not have default arguments. 4294 unsigned ExpectedParams = 1; 4295 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 4296 ExpectedParams = 0; 4297 if (MD->getNumParams() != ExpectedParams) { 4298 // This also checks for default arguments: a copy or move constructor with a 4299 // default argument is classified as a default constructor, and assignment 4300 // operations and destructors can't have default arguments. 4301 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 4302 << CSM << MD->getSourceRange(); 4303 HadError = true; 4304 } else if (MD->isVariadic()) { 4305 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 4306 << CSM << MD->getSourceRange(); 4307 HadError = true; 4308 } 4309 4310 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 4311 4312 bool CanHaveConstParam = false; 4313 if (CSM == CXXCopyConstructor) 4314 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 4315 else if (CSM == CXXCopyAssignment) 4316 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 4317 4318 QualType ReturnType = Context.VoidTy; 4319 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 4320 // Check for return type matching. 4321 ReturnType = Type->getResultType(); 4322 QualType ExpectedReturnType = 4323 Context.getLValueReferenceType(Context.getTypeDeclType(RD)); 4324 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 4325 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 4326 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 4327 HadError = true; 4328 } 4329 4330 // A defaulted special member cannot have cv-qualifiers. 4331 if (Type->getTypeQuals()) { 4332 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 4333 << (CSM == CXXMoveAssignment); 4334 HadError = true; 4335 } 4336 } 4337 4338 // Check for parameter type matching. 4339 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType(); 4340 bool HasConstParam = false; 4341 if (ExpectedParams && ArgType->isReferenceType()) { 4342 // Argument must be reference to possibly-const T. 4343 QualType ReferentType = ArgType->getPointeeType(); 4344 HasConstParam = ReferentType.isConstQualified(); 4345 4346 if (ReferentType.isVolatileQualified()) { 4347 Diag(MD->getLocation(), 4348 diag::err_defaulted_special_member_volatile_param) << CSM; 4349 HadError = true; 4350 } 4351 4352 if (HasConstParam && !CanHaveConstParam) { 4353 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 4354 Diag(MD->getLocation(), 4355 diag::err_defaulted_special_member_copy_const_param) 4356 << (CSM == CXXCopyAssignment); 4357 // FIXME: Explain why this special member can't be const. 4358 } else { 4359 Diag(MD->getLocation(), 4360 diag::err_defaulted_special_member_move_const_param) 4361 << (CSM == CXXMoveAssignment); 4362 } 4363 HadError = true; 4364 } 4365 } else if (ExpectedParams) { 4366 // A copy assignment operator can take its argument by value, but a 4367 // defaulted one cannot. 4368 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 4369 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 4370 HadError = true; 4371 } 4372 4373 // C++11 [dcl.fct.def.default]p2: 4374 // An explicitly-defaulted function may be declared constexpr only if it 4375 // would have been implicitly declared as constexpr, 4376 // Do not apply this rule to members of class templates, since core issue 1358 4377 // makes such functions always instantiate to constexpr functions. For 4378 // non-constructors, this is checked elsewhere. 4379 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 4380 HasConstParam); 4381 if (isa<CXXConstructorDecl>(MD) && MD->isConstexpr() && !Constexpr && 4382 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 4383 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM; 4384 // FIXME: Explain why the constructor can't be constexpr. 4385 HadError = true; 4386 } 4387 4388 // and may have an explicit exception-specification only if it is compatible 4389 // with the exception-specification on the implicit declaration. 4390 if (Type->hasExceptionSpec()) { 4391 // Delay the check if this is the first declaration of the special member, 4392 // since we may not have parsed some necessary in-class initializers yet. 4393 if (First) { 4394 // If the exception specification needs to be instantiated, do so now, 4395 // before we clobber it with an EST_Unevaluated specification below. 4396 if (Type->getExceptionSpecType() == EST_Uninstantiated) { 4397 InstantiateExceptionSpec(MD->getLocStart(), MD); 4398 Type = MD->getType()->getAs<FunctionProtoType>(); 4399 } 4400 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type)); 4401 } else 4402 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type); 4403 } 4404 4405 // If a function is explicitly defaulted on its first declaration, 4406 if (First) { 4407 // -- it is implicitly considered to be constexpr if the implicit 4408 // definition would be, 4409 MD->setConstexpr(Constexpr); 4410 4411 // -- it is implicitly considered to have the same exception-specification 4412 // as if it had been implicitly declared, 4413 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 4414 EPI.ExceptionSpecType = EST_Unevaluated; 4415 EPI.ExceptionSpecDecl = MD; 4416 MD->setType(Context.getFunctionType(ReturnType, 4417 ArrayRef<QualType>(&ArgType, 4418 ExpectedParams), 4419 EPI)); 4420 } 4421 4422 if (ShouldDeleteSpecialMember(MD, CSM)) { 4423 if (First) { 4424 SetDeclDeleted(MD, MD->getLocation()); 4425 } else { 4426 // C++11 [dcl.fct.def.default]p4: 4427 // [For a] user-provided explicitly-defaulted function [...] if such a 4428 // function is implicitly defined as deleted, the program is ill-formed. 4429 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 4430 HadError = true; 4431 } 4432 } 4433 4434 if (HadError) 4435 MD->setInvalidDecl(); 4436} 4437 4438/// Check whether the exception specification provided for an 4439/// explicitly-defaulted special member matches the exception specification 4440/// that would have been generated for an implicit special member, per 4441/// C++11 [dcl.fct.def.default]p2. 4442void Sema::CheckExplicitlyDefaultedMemberExceptionSpec( 4443 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) { 4444 // Compute the implicit exception specification. 4445 FunctionProtoType::ExtProtoInfo EPI; 4446 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI); 4447 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>( 4448 Context.getFunctionType(Context.VoidTy, ArrayRef<QualType>(), EPI)); 4449 4450 // Ensure that it matches. 4451 CheckEquivalentExceptionSpec( 4452 PDiag(diag::err_incorrect_defaulted_exception_spec) 4453 << getSpecialMember(MD), PDiag(), 4454 ImplicitType, SourceLocation(), 4455 SpecifiedType, MD->getLocation()); 4456} 4457 4458void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() { 4459 for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size(); 4460 I != N; ++I) 4461 CheckExplicitlyDefaultedMemberExceptionSpec( 4462 DelayedDefaultedMemberExceptionSpecs[I].first, 4463 DelayedDefaultedMemberExceptionSpecs[I].second); 4464 4465 DelayedDefaultedMemberExceptionSpecs.clear(); 4466} 4467 4468namespace { 4469struct SpecialMemberDeletionInfo { 4470 Sema &S; 4471 CXXMethodDecl *MD; 4472 Sema::CXXSpecialMember CSM; 4473 bool Diagnose; 4474 4475 // Properties of the special member, computed for convenience. 4476 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg; 4477 SourceLocation Loc; 4478 4479 bool AllFieldsAreConst; 4480 4481 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 4482 Sema::CXXSpecialMember CSM, bool Diagnose) 4483 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose), 4484 IsConstructor(false), IsAssignment(false), IsMove(false), 4485 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()), 4486 AllFieldsAreConst(true) { 4487 switch (CSM) { 4488 case Sema::CXXDefaultConstructor: 4489 case Sema::CXXCopyConstructor: 4490 IsConstructor = true; 4491 break; 4492 case Sema::CXXMoveConstructor: 4493 IsConstructor = true; 4494 IsMove = true; 4495 break; 4496 case Sema::CXXCopyAssignment: 4497 IsAssignment = true; 4498 break; 4499 case Sema::CXXMoveAssignment: 4500 IsAssignment = true; 4501 IsMove = true; 4502 break; 4503 case Sema::CXXDestructor: 4504 break; 4505 case Sema::CXXInvalid: 4506 llvm_unreachable("invalid special member kind"); 4507 } 4508 4509 if (MD->getNumParams()) { 4510 ConstArg = MD->getParamDecl(0)->getType().isConstQualified(); 4511 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified(); 4512 } 4513 } 4514 4515 bool inUnion() const { return MD->getParent()->isUnion(); } 4516 4517 /// Look up the corresponding special member in the given class. 4518 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class, 4519 unsigned Quals) { 4520 unsigned TQ = MD->getTypeQualifiers(); 4521 // cv-qualifiers on class members don't affect default ctor / dtor calls. 4522 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 4523 Quals = 0; 4524 return S.LookupSpecialMember(Class, CSM, 4525 ConstArg || (Quals & Qualifiers::Const), 4526 VolatileArg || (Quals & Qualifiers::Volatile), 4527 MD->getRefQualifier() == RQ_RValue, 4528 TQ & Qualifiers::Const, 4529 TQ & Qualifiers::Volatile); 4530 } 4531 4532 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 4533 4534 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 4535 bool shouldDeleteForField(FieldDecl *FD); 4536 bool shouldDeleteForAllConstMembers(); 4537 4538 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 4539 unsigned Quals); 4540 bool shouldDeleteForSubobjectCall(Subobject Subobj, 4541 Sema::SpecialMemberOverloadResult *SMOR, 4542 bool IsDtorCallInCtor); 4543 4544 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 4545}; 4546} 4547 4548/// Is the given special member inaccessible when used on the given 4549/// sub-object. 4550bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 4551 CXXMethodDecl *target) { 4552 /// If we're operating on a base class, the object type is the 4553 /// type of this special member. 4554 QualType objectTy; 4555 AccessSpecifier access = target->getAccess(); 4556 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 4557 objectTy = S.Context.getTypeDeclType(MD->getParent()); 4558 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 4559 4560 // If we're operating on a field, the object type is the type of the field. 4561 } else { 4562 objectTy = S.Context.getTypeDeclType(target->getParent()); 4563 } 4564 4565 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 4566} 4567 4568/// Check whether we should delete a special member due to the implicit 4569/// definition containing a call to a special member of a subobject. 4570bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 4571 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR, 4572 bool IsDtorCallInCtor) { 4573 CXXMethodDecl *Decl = SMOR->getMethod(); 4574 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 4575 4576 int DiagKind = -1; 4577 4578 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 4579 DiagKind = !Decl ? 0 : 1; 4580 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 4581 DiagKind = 2; 4582 else if (!isAccessible(Subobj, Decl)) 4583 DiagKind = 3; 4584 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 4585 !Decl->isTrivial()) { 4586 // A member of a union must have a trivial corresponding special member. 4587 // As a weird special case, a destructor call from a union's constructor 4588 // must be accessible and non-deleted, but need not be trivial. Such a 4589 // destructor is never actually called, but is semantically checked as 4590 // if it were. 4591 DiagKind = 4; 4592 } 4593 4594 if (DiagKind == -1) 4595 return false; 4596 4597 if (Diagnose) { 4598 if (Field) { 4599 S.Diag(Field->getLocation(), 4600 diag::note_deleted_special_member_class_subobject) 4601 << CSM << MD->getParent() << /*IsField*/true 4602 << Field << DiagKind << IsDtorCallInCtor; 4603 } else { 4604 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 4605 S.Diag(Base->getLocStart(), 4606 diag::note_deleted_special_member_class_subobject) 4607 << CSM << MD->getParent() << /*IsField*/false 4608 << Base->getType() << DiagKind << IsDtorCallInCtor; 4609 } 4610 4611 if (DiagKind == 1) 4612 S.NoteDeletedFunction(Decl); 4613 // FIXME: Explain inaccessibility if DiagKind == 3. 4614 } 4615 4616 return true; 4617} 4618 4619/// Check whether we should delete a special member function due to having a 4620/// direct or virtual base class or non-static data member of class type M. 4621bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 4622 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 4623 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 4624 4625 // C++11 [class.ctor]p5: 4626 // -- any direct or virtual base class, or non-static data member with no 4627 // brace-or-equal-initializer, has class type M (or array thereof) and 4628 // either M has no default constructor or overload resolution as applied 4629 // to M's default constructor results in an ambiguity or in a function 4630 // that is deleted or inaccessible 4631 // C++11 [class.copy]p11, C++11 [class.copy]p23: 4632 // -- a direct or virtual base class B that cannot be copied/moved because 4633 // overload resolution, as applied to B's corresponding special member, 4634 // results in an ambiguity or a function that is deleted or inaccessible 4635 // from the defaulted special member 4636 // C++11 [class.dtor]p5: 4637 // -- any direct or virtual base class [...] has a type with a destructor 4638 // that is deleted or inaccessible 4639 if (!(CSM == Sema::CXXDefaultConstructor && 4640 Field && Field->hasInClassInitializer()) && 4641 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false)) 4642 return true; 4643 4644 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 4645 // -- any direct or virtual base class or non-static data member has a 4646 // type with a destructor that is deleted or inaccessible 4647 if (IsConstructor) { 4648 Sema::SpecialMemberOverloadResult *SMOR = 4649 S.LookupSpecialMember(Class, Sema::CXXDestructor, 4650 false, false, false, false, false); 4651 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 4652 return true; 4653 } 4654 4655 return false; 4656} 4657 4658/// Check whether we should delete a special member function due to the class 4659/// having a particular direct or virtual base class. 4660bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 4661 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 4662 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 4663} 4664 4665/// Check whether we should delete a special member function due to the class 4666/// having a particular non-static data member. 4667bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 4668 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 4669 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 4670 4671 if (CSM == Sema::CXXDefaultConstructor) { 4672 // For a default constructor, all references must be initialized in-class 4673 // and, if a union, it must have a non-const member. 4674 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 4675 if (Diagnose) 4676 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 4677 << MD->getParent() << FD << FieldType << /*Reference*/0; 4678 return true; 4679 } 4680 // C++11 [class.ctor]p5: any non-variant non-static data member of 4681 // const-qualified type (or array thereof) with no 4682 // brace-or-equal-initializer does not have a user-provided default 4683 // constructor. 4684 if (!inUnion() && FieldType.isConstQualified() && 4685 !FD->hasInClassInitializer() && 4686 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 4687 if (Diagnose) 4688 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 4689 << MD->getParent() << FD << FD->getType() << /*Const*/1; 4690 return true; 4691 } 4692 4693 if (inUnion() && !FieldType.isConstQualified()) 4694 AllFieldsAreConst = false; 4695 } else if (CSM == Sema::CXXCopyConstructor) { 4696 // For a copy constructor, data members must not be of rvalue reference 4697 // type. 4698 if (FieldType->isRValueReferenceType()) { 4699 if (Diagnose) 4700 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 4701 << MD->getParent() << FD << FieldType; 4702 return true; 4703 } 4704 } else if (IsAssignment) { 4705 // For an assignment operator, data members must not be of reference type. 4706 if (FieldType->isReferenceType()) { 4707 if (Diagnose) 4708 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 4709 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0; 4710 return true; 4711 } 4712 if (!FieldRecord && FieldType.isConstQualified()) { 4713 // C++11 [class.copy]p23: 4714 // -- a non-static data member of const non-class type (or array thereof) 4715 if (Diagnose) 4716 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 4717 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1; 4718 return true; 4719 } 4720 } 4721 4722 if (FieldRecord) { 4723 // Some additional restrictions exist on the variant members. 4724 if (!inUnion() && FieldRecord->isUnion() && 4725 FieldRecord->isAnonymousStructOrUnion()) { 4726 bool AllVariantFieldsAreConst = true; 4727 4728 // FIXME: Handle anonymous unions declared within anonymous unions. 4729 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(), 4730 UE = FieldRecord->field_end(); 4731 UI != UE; ++UI) { 4732 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 4733 4734 if (!UnionFieldType.isConstQualified()) 4735 AllVariantFieldsAreConst = false; 4736 4737 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 4738 if (UnionFieldRecord && 4739 shouldDeleteForClassSubobject(UnionFieldRecord, *UI, 4740 UnionFieldType.getCVRQualifiers())) 4741 return true; 4742 } 4743 4744 // At least one member in each anonymous union must be non-const 4745 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 4746 FieldRecord->field_begin() != FieldRecord->field_end()) { 4747 if (Diagnose) 4748 S.Diag(FieldRecord->getLocation(), 4749 diag::note_deleted_default_ctor_all_const) 4750 << MD->getParent() << /*anonymous union*/1; 4751 return true; 4752 } 4753 4754 // Don't check the implicit member of the anonymous union type. 4755 // This is technically non-conformant, but sanity demands it. 4756 return false; 4757 } 4758 4759 if (shouldDeleteForClassSubobject(FieldRecord, FD, 4760 FieldType.getCVRQualifiers())) 4761 return true; 4762 } 4763 4764 return false; 4765} 4766 4767/// C++11 [class.ctor] p5: 4768/// A defaulted default constructor for a class X is defined as deleted if 4769/// X is a union and all of its variant members are of const-qualified type. 4770bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 4771 // This is a silly definition, because it gives an empty union a deleted 4772 // default constructor. Don't do that. 4773 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst && 4774 (MD->getParent()->field_begin() != MD->getParent()->field_end())) { 4775 if (Diagnose) 4776 S.Diag(MD->getParent()->getLocation(), 4777 diag::note_deleted_default_ctor_all_const) 4778 << MD->getParent() << /*not anonymous union*/0; 4779 return true; 4780 } 4781 return false; 4782} 4783 4784/// Determine whether a defaulted special member function should be defined as 4785/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 4786/// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 4787bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 4788 bool Diagnose) { 4789 if (MD->isInvalidDecl()) 4790 return false; 4791 CXXRecordDecl *RD = MD->getParent(); 4792 assert(!RD->isDependentType() && "do deletion after instantiation"); 4793 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 4794 return false; 4795 4796 // C++11 [expr.lambda.prim]p19: 4797 // The closure type associated with a lambda-expression has a 4798 // deleted (8.4.3) default constructor and a deleted copy 4799 // assignment operator. 4800 if (RD->isLambda() && 4801 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 4802 if (Diagnose) 4803 Diag(RD->getLocation(), diag::note_lambda_decl); 4804 return true; 4805 } 4806 4807 // For an anonymous struct or union, the copy and assignment special members 4808 // will never be used, so skip the check. For an anonymous union declared at 4809 // namespace scope, the constructor and destructor are used. 4810 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 4811 RD->isAnonymousStructOrUnion()) 4812 return false; 4813 4814 // C++11 [class.copy]p7, p18: 4815 // If the class definition declares a move constructor or move assignment 4816 // operator, an implicitly declared copy constructor or copy assignment 4817 // operator is defined as deleted. 4818 if (MD->isImplicit() && 4819 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 4820 CXXMethodDecl *UserDeclaredMove = 0; 4821 4822 // In Microsoft mode, a user-declared move only causes the deletion of the 4823 // corresponding copy operation, not both copy operations. 4824 if (RD->hasUserDeclaredMoveConstructor() && 4825 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) { 4826 if (!Diagnose) return true; 4827 4828 // Find any user-declared move constructor. 4829 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(), 4830 E = RD->ctor_end(); I != E; ++I) { 4831 if (I->isMoveConstructor()) { 4832 UserDeclaredMove = *I; 4833 break; 4834 } 4835 } 4836 assert(UserDeclaredMove); 4837 } else if (RD->hasUserDeclaredMoveAssignment() && 4838 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) { 4839 if (!Diagnose) return true; 4840 4841 // Find any user-declared move assignment operator. 4842 for (CXXRecordDecl::method_iterator I = RD->method_begin(), 4843 E = RD->method_end(); I != E; ++I) { 4844 if (I->isMoveAssignmentOperator()) { 4845 UserDeclaredMove = *I; 4846 break; 4847 } 4848 } 4849 assert(UserDeclaredMove); 4850 } 4851 4852 if (UserDeclaredMove) { 4853 Diag(UserDeclaredMove->getLocation(), 4854 diag::note_deleted_copy_user_declared_move) 4855 << (CSM == CXXCopyAssignment) << RD 4856 << UserDeclaredMove->isMoveAssignmentOperator(); 4857 return true; 4858 } 4859 } 4860 4861 // Do access control from the special member function 4862 ContextRAII MethodContext(*this, MD); 4863 4864 // C++11 [class.dtor]p5: 4865 // -- for a virtual destructor, lookup of the non-array deallocation function 4866 // results in an ambiguity or in a function that is deleted or inaccessible 4867 if (CSM == CXXDestructor && MD->isVirtual()) { 4868 FunctionDecl *OperatorDelete = 0; 4869 DeclarationName Name = 4870 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 4871 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 4872 OperatorDelete, false)) { 4873 if (Diagnose) 4874 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 4875 return true; 4876 } 4877 } 4878 4879 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose); 4880 4881 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 4882 BE = RD->bases_end(); BI != BE; ++BI) 4883 if (!BI->isVirtual() && 4884 SMI.shouldDeleteForBase(BI)) 4885 return true; 4886 4887 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(), 4888 BE = RD->vbases_end(); BI != BE; ++BI) 4889 if (SMI.shouldDeleteForBase(BI)) 4890 return true; 4891 4892 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 4893 FE = RD->field_end(); FI != FE; ++FI) 4894 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() && 4895 SMI.shouldDeleteForField(*FI)) 4896 return true; 4897 4898 if (SMI.shouldDeleteForAllConstMembers()) 4899 return true; 4900 4901 return false; 4902} 4903 4904/// Perform lookup for a special member of the specified kind, and determine 4905/// whether it is trivial. If the triviality can be determined without the 4906/// lookup, skip it. This is intended for use when determining whether a 4907/// special member of a containing object is trivial, and thus does not ever 4908/// perform overload resolution for default constructors. 4909/// 4910/// If \p Selected is not \c NULL, \c *Selected will be filled in with the 4911/// member that was most likely to be intended to be trivial, if any. 4912static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 4913 Sema::CXXSpecialMember CSM, unsigned Quals, 4914 CXXMethodDecl **Selected) { 4915 if (Selected) 4916 *Selected = 0; 4917 4918 switch (CSM) { 4919 case Sema::CXXInvalid: 4920 llvm_unreachable("not a special member"); 4921 4922 case Sema::CXXDefaultConstructor: 4923 // C++11 [class.ctor]p5: 4924 // A default constructor is trivial if: 4925 // - all the [direct subobjects] have trivial default constructors 4926 // 4927 // Note, no overload resolution is performed in this case. 4928 if (RD->hasTrivialDefaultConstructor()) 4929 return true; 4930 4931 if (Selected) { 4932 // If there's a default constructor which could have been trivial, dig it 4933 // out. Otherwise, if there's any user-provided default constructor, point 4934 // to that as an example of why there's not a trivial one. 4935 CXXConstructorDecl *DefCtor = 0; 4936 if (RD->needsImplicitDefaultConstructor()) 4937 S.DeclareImplicitDefaultConstructor(RD); 4938 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), 4939 CE = RD->ctor_end(); CI != CE; ++CI) { 4940 if (!CI->isDefaultConstructor()) 4941 continue; 4942 DefCtor = *CI; 4943 if (!DefCtor->isUserProvided()) 4944 break; 4945 } 4946 4947 *Selected = DefCtor; 4948 } 4949 4950 return false; 4951 4952 case Sema::CXXDestructor: 4953 // C++11 [class.dtor]p5: 4954 // A destructor is trivial if: 4955 // - all the direct [subobjects] have trivial destructors 4956 if (RD->hasTrivialDestructor()) 4957 return true; 4958 4959 if (Selected) { 4960 if (RD->needsImplicitDestructor()) 4961 S.DeclareImplicitDestructor(RD); 4962 *Selected = RD->getDestructor(); 4963 } 4964 4965 return false; 4966 4967 case Sema::CXXCopyConstructor: 4968 // C++11 [class.copy]p12: 4969 // A copy constructor is trivial if: 4970 // - the constructor selected to copy each direct [subobject] is trivial 4971 if (RD->hasTrivialCopyConstructor()) { 4972 if (Quals == Qualifiers::Const) 4973 // We must either select the trivial copy constructor or reach an 4974 // ambiguity; no need to actually perform overload resolution. 4975 return true; 4976 } else if (!Selected) { 4977 return false; 4978 } 4979 // In C++98, we are not supposed to perform overload resolution here, but we 4980 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 4981 // cases like B as having a non-trivial copy constructor: 4982 // struct A { template<typename T> A(T&); }; 4983 // struct B { mutable A a; }; 4984 goto NeedOverloadResolution; 4985 4986 case Sema::CXXCopyAssignment: 4987 // C++11 [class.copy]p25: 4988 // A copy assignment operator is trivial if: 4989 // - the assignment operator selected to copy each direct [subobject] is 4990 // trivial 4991 if (RD->hasTrivialCopyAssignment()) { 4992 if (Quals == Qualifiers::Const) 4993 return true; 4994 } else if (!Selected) { 4995 return false; 4996 } 4997 // In C++98, we are not supposed to perform overload resolution here, but we 4998 // treat that as a language defect. 4999 goto NeedOverloadResolution; 5000 5001 case Sema::CXXMoveConstructor: 5002 case Sema::CXXMoveAssignment: 5003 NeedOverloadResolution: 5004 Sema::SpecialMemberOverloadResult *SMOR = 5005 S.LookupSpecialMember(RD, CSM, 5006 Quals & Qualifiers::Const, 5007 Quals & Qualifiers::Volatile, 5008 /*RValueThis*/false, /*ConstThis*/false, 5009 /*VolatileThis*/false); 5010 5011 // The standard doesn't describe how to behave if the lookup is ambiguous. 5012 // We treat it as not making the member non-trivial, just like the standard 5013 // mandates for the default constructor. This should rarely matter, because 5014 // the member will also be deleted. 5015 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 5016 return true; 5017 5018 if (!SMOR->getMethod()) { 5019 assert(SMOR->getKind() == 5020 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 5021 return false; 5022 } 5023 5024 // We deliberately don't check if we found a deleted special member. We're 5025 // not supposed to! 5026 if (Selected) 5027 *Selected = SMOR->getMethod(); 5028 return SMOR->getMethod()->isTrivial(); 5029 } 5030 5031 llvm_unreachable("unknown special method kind"); 5032} 5033 5034static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 5035 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end(); 5036 CI != CE; ++CI) 5037 if (!CI->isImplicit()) 5038 return *CI; 5039 5040 // Look for constructor templates. 5041 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 5042 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 5043 if (CXXConstructorDecl *CD = 5044 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 5045 return CD; 5046 } 5047 5048 return 0; 5049} 5050 5051/// The kind of subobject we are checking for triviality. The values of this 5052/// enumeration are used in diagnostics. 5053enum TrivialSubobjectKind { 5054 /// The subobject is a base class. 5055 TSK_BaseClass, 5056 /// The subobject is a non-static data member. 5057 TSK_Field, 5058 /// The object is actually the complete object. 5059 TSK_CompleteObject 5060}; 5061 5062/// Check whether the special member selected for a given type would be trivial. 5063static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 5064 QualType SubType, 5065 Sema::CXXSpecialMember CSM, 5066 TrivialSubobjectKind Kind, 5067 bool Diagnose) { 5068 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 5069 if (!SubRD) 5070 return true; 5071 5072 CXXMethodDecl *Selected; 5073 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 5074 Diagnose ? &Selected : 0)) 5075 return true; 5076 5077 if (Diagnose) { 5078 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 5079 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 5080 << Kind << SubType.getUnqualifiedType(); 5081 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 5082 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 5083 } else if (!Selected) 5084 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 5085 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 5086 else if (Selected->isUserProvided()) { 5087 if (Kind == TSK_CompleteObject) 5088 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 5089 << Kind << SubType.getUnqualifiedType() << CSM; 5090 else { 5091 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 5092 << Kind << SubType.getUnqualifiedType() << CSM; 5093 S.Diag(Selected->getLocation(), diag::note_declared_at); 5094 } 5095 } else { 5096 if (Kind != TSK_CompleteObject) 5097 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 5098 << Kind << SubType.getUnqualifiedType() << CSM; 5099 5100 // Explain why the defaulted or deleted special member isn't trivial. 5101 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose); 5102 } 5103 } 5104 5105 return false; 5106} 5107 5108/// Check whether the members of a class type allow a special member to be 5109/// trivial. 5110static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 5111 Sema::CXXSpecialMember CSM, 5112 bool ConstArg, bool Diagnose) { 5113 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 5114 FE = RD->field_end(); FI != FE; ++FI) { 5115 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 5116 continue; 5117 5118 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 5119 5120 // Pretend anonymous struct or union members are members of this class. 5121 if (FI->isAnonymousStructOrUnion()) { 5122 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 5123 CSM, ConstArg, Diagnose)) 5124 return false; 5125 continue; 5126 } 5127 5128 // C++11 [class.ctor]p5: 5129 // A default constructor is trivial if [...] 5130 // -- no non-static data member of its class has a 5131 // brace-or-equal-initializer 5132 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 5133 if (Diagnose) 5134 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI; 5135 return false; 5136 } 5137 5138 // Objective C ARC 4.3.5: 5139 // [...] nontrivally ownership-qualified types are [...] not trivially 5140 // default constructible, copy constructible, move constructible, copy 5141 // assignable, move assignable, or destructible [...] 5142 if (S.getLangOpts().ObjCAutoRefCount && 5143 FieldType.hasNonTrivialObjCLifetime()) { 5144 if (Diagnose) 5145 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 5146 << RD << FieldType.getObjCLifetime(); 5147 return false; 5148 } 5149 5150 if (ConstArg && !FI->isMutable()) 5151 FieldType.addConst(); 5152 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM, 5153 TSK_Field, Diagnose)) 5154 return false; 5155 } 5156 5157 return true; 5158} 5159 5160/// Diagnose why the specified class does not have a trivial special member of 5161/// the given kind. 5162void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 5163 QualType Ty = Context.getRecordType(RD); 5164 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) 5165 Ty.addConst(); 5166 5167 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM, 5168 TSK_CompleteObject, /*Diagnose*/true); 5169} 5170 5171/// Determine whether a defaulted or deleted special member function is trivial, 5172/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 5173/// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 5174bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 5175 bool Diagnose) { 5176 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 5177 5178 CXXRecordDecl *RD = MD->getParent(); 5179 5180 bool ConstArg = false; 5181 5182 // C++11 [class.copy]p12, p25: 5183 // A [special member] is trivial if its declared parameter type is the same 5184 // as if it had been implicitly declared [...] 5185 switch (CSM) { 5186 case CXXDefaultConstructor: 5187 case CXXDestructor: 5188 // Trivial default constructors and destructors cannot have parameters. 5189 break; 5190 5191 case CXXCopyConstructor: 5192 case CXXCopyAssignment: { 5193 // Trivial copy operations always have const, non-volatile parameter types. 5194 ConstArg = true; 5195 const ParmVarDecl *Param0 = MD->getParamDecl(0); 5196 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 5197 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 5198 if (Diagnose) 5199 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 5200 << Param0->getSourceRange() << Param0->getType() 5201 << Context.getLValueReferenceType( 5202 Context.getRecordType(RD).withConst()); 5203 return false; 5204 } 5205 break; 5206 } 5207 5208 case CXXMoveConstructor: 5209 case CXXMoveAssignment: { 5210 // Trivial move operations always have non-cv-qualified parameters. 5211 const ParmVarDecl *Param0 = MD->getParamDecl(0); 5212 const RValueReferenceType *RT = 5213 Param0->getType()->getAs<RValueReferenceType>(); 5214 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 5215 if (Diagnose) 5216 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 5217 << Param0->getSourceRange() << Param0->getType() 5218 << Context.getRValueReferenceType(Context.getRecordType(RD)); 5219 return false; 5220 } 5221 break; 5222 } 5223 5224 case CXXInvalid: 5225 llvm_unreachable("not a special member"); 5226 } 5227 5228 // FIXME: We require that the parameter-declaration-clause is equivalent to 5229 // that of an implicit declaration, not just that the declared parameter type 5230 // matches, in order to prevent absuridities like a function simultaneously 5231 // being a trivial copy constructor and a non-trivial default constructor. 5232 // This issue has not yet been assigned a core issue number. 5233 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 5234 if (Diagnose) 5235 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 5236 diag::note_nontrivial_default_arg) 5237 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 5238 return false; 5239 } 5240 if (MD->isVariadic()) { 5241 if (Diagnose) 5242 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 5243 return false; 5244 } 5245 5246 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 5247 // A copy/move [constructor or assignment operator] is trivial if 5248 // -- the [member] selected to copy/move each direct base class subobject 5249 // is trivial 5250 // 5251 // C++11 [class.copy]p12, C++11 [class.copy]p25: 5252 // A [default constructor or destructor] is trivial if 5253 // -- all the direct base classes have trivial [default constructors or 5254 // destructors] 5255 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 5256 BE = RD->bases_end(); BI != BE; ++BI) 5257 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(), 5258 ConstArg ? BI->getType().withConst() 5259 : BI->getType(), 5260 CSM, TSK_BaseClass, Diagnose)) 5261 return false; 5262 5263 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 5264 // A copy/move [constructor or assignment operator] for a class X is 5265 // trivial if 5266 // -- for each non-static data member of X that is of class type (or array 5267 // thereof), the constructor selected to copy/move that member is 5268 // trivial 5269 // 5270 // C++11 [class.copy]p12, C++11 [class.copy]p25: 5271 // A [default constructor or destructor] is trivial if 5272 // -- for all of the non-static data members of its class that are of class 5273 // type (or array thereof), each such class has a trivial [default 5274 // constructor or destructor] 5275 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose)) 5276 return false; 5277 5278 // C++11 [class.dtor]p5: 5279 // A destructor is trivial if [...] 5280 // -- the destructor is not virtual 5281 if (CSM == CXXDestructor && MD->isVirtual()) { 5282 if (Diagnose) 5283 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 5284 return false; 5285 } 5286 5287 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 5288 // A [special member] for class X is trivial if [...] 5289 // -- class X has no virtual functions and no virtual base classes 5290 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 5291 if (!Diagnose) 5292 return false; 5293 5294 if (RD->getNumVBases()) { 5295 // Check for virtual bases. We already know that the corresponding 5296 // member in all bases is trivial, so vbases must all be direct. 5297 CXXBaseSpecifier &BS = *RD->vbases_begin(); 5298 assert(BS.isVirtual()); 5299 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1; 5300 return false; 5301 } 5302 5303 // Must have a virtual method. 5304 for (CXXRecordDecl::method_iterator MI = RD->method_begin(), 5305 ME = RD->method_end(); MI != ME; ++MI) { 5306 if (MI->isVirtual()) { 5307 SourceLocation MLoc = MI->getLocStart(); 5308 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 5309 return false; 5310 } 5311 } 5312 5313 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 5314 } 5315 5316 // Looks like it's trivial! 5317 return true; 5318} 5319 5320/// \brief Data used with FindHiddenVirtualMethod 5321namespace { 5322 struct FindHiddenVirtualMethodData { 5323 Sema *S; 5324 CXXMethodDecl *Method; 5325 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 5326 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 5327 }; 5328} 5329 5330/// \brief Check whether any most overriden method from MD in Methods 5331static bool CheckMostOverridenMethods(const CXXMethodDecl *MD, 5332 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) { 5333 if (MD->size_overridden_methods() == 0) 5334 return Methods.count(MD->getCanonicalDecl()); 5335 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 5336 E = MD->end_overridden_methods(); 5337 I != E; ++I) 5338 if (CheckMostOverridenMethods(*I, Methods)) 5339 return true; 5340 return false; 5341} 5342 5343/// \brief Member lookup function that determines whether a given C++ 5344/// method overloads virtual methods in a base class without overriding any, 5345/// to be used with CXXRecordDecl::lookupInBases(). 5346static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier, 5347 CXXBasePath &Path, 5348 void *UserData) { 5349 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 5350 5351 FindHiddenVirtualMethodData &Data 5352 = *static_cast<FindHiddenVirtualMethodData*>(UserData); 5353 5354 DeclarationName Name = Data.Method->getDeclName(); 5355 assert(Name.getNameKind() == DeclarationName::Identifier); 5356 5357 bool foundSameNameMethod = false; 5358 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 5359 for (Path.Decls = BaseRecord->lookup(Name); 5360 !Path.Decls.empty(); 5361 Path.Decls = Path.Decls.slice(1)) { 5362 NamedDecl *D = Path.Decls.front(); 5363 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 5364 MD = MD->getCanonicalDecl(); 5365 foundSameNameMethod = true; 5366 // Interested only in hidden virtual methods. 5367 if (!MD->isVirtual()) 5368 continue; 5369 // If the method we are checking overrides a method from its base 5370 // don't warn about the other overloaded methods. 5371 if (!Data.S->IsOverload(Data.Method, MD, false)) 5372 return true; 5373 // Collect the overload only if its hidden. 5374 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods)) 5375 overloadedMethods.push_back(MD); 5376 } 5377 } 5378 5379 if (foundSameNameMethod) 5380 Data.OverloadedMethods.append(overloadedMethods.begin(), 5381 overloadedMethods.end()); 5382 return foundSameNameMethod; 5383} 5384 5385/// \brief Add the most overriden methods from MD to Methods 5386static void AddMostOverridenMethods(const CXXMethodDecl *MD, 5387 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) { 5388 if (MD->size_overridden_methods() == 0) 5389 Methods.insert(MD->getCanonicalDecl()); 5390 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 5391 E = MD->end_overridden_methods(); 5392 I != E; ++I) 5393 AddMostOverridenMethods(*I, Methods); 5394} 5395 5396/// \brief See if a method overloads virtual methods in a base class without 5397/// overriding any. 5398void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 5399 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual, 5400 MD->getLocation()) == DiagnosticsEngine::Ignored) 5401 return; 5402 if (!MD->getDeclName().isIdentifier()) 5403 return; 5404 5405 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 5406 /*bool RecordPaths=*/false, 5407 /*bool DetectVirtual=*/false); 5408 FindHiddenVirtualMethodData Data; 5409 Data.Method = MD; 5410 Data.S = this; 5411 5412 // Keep the base methods that were overriden or introduced in the subclass 5413 // by 'using' in a set. A base method not in this set is hidden. 5414 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 5415 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 5416 NamedDecl *ND = *I; 5417 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 5418 ND = shad->getTargetDecl(); 5419 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 5420 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods); 5421 } 5422 5423 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) && 5424 !Data.OverloadedMethods.empty()) { 5425 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 5426 << MD << (Data.OverloadedMethods.size() > 1); 5427 5428 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) { 5429 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i]; 5430 PartialDiagnostic PD = PDiag( 5431 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 5432 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 5433 Diag(overloadedMD->getLocation(), PD); 5434 } 5435 } 5436} 5437 5438void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 5439 Decl *TagDecl, 5440 SourceLocation LBrac, 5441 SourceLocation RBrac, 5442 AttributeList *AttrList) { 5443 if (!TagDecl) 5444 return; 5445 5446 AdjustDeclIfTemplate(TagDecl); 5447 5448 for (const AttributeList* l = AttrList; l; l = l->getNext()) { 5449 if (l->getKind() != AttributeList::AT_Visibility) 5450 continue; 5451 l->setInvalid(); 5452 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) << 5453 l->getName(); 5454 } 5455 5456 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 5457 // strict aliasing violation! 5458 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 5459 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 5460 5461 CheckCompletedCXXClass( 5462 dyn_cast_or_null<CXXRecordDecl>(TagDecl)); 5463} 5464 5465/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 5466/// special functions, such as the default constructor, copy 5467/// constructor, or destructor, to the given C++ class (C++ 5468/// [special]p1). This routine can only be executed just before the 5469/// definition of the class is complete. 5470void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 5471 if (!ClassDecl->hasUserDeclaredConstructor()) 5472 ++ASTContext::NumImplicitDefaultConstructors; 5473 5474 if (!ClassDecl->hasUserDeclaredCopyConstructor()) { 5475 ++ASTContext::NumImplicitCopyConstructors; 5476 5477 // If the properties or semantics of the copy constructor couldn't be 5478 // determined while the class was being declared, force a declaration 5479 // of it now. 5480 if (ClassDecl->needsOverloadResolutionForCopyConstructor()) 5481 DeclareImplicitCopyConstructor(ClassDecl); 5482 } 5483 5484 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 5485 ++ASTContext::NumImplicitMoveConstructors; 5486 5487 if (ClassDecl->needsOverloadResolutionForMoveConstructor()) 5488 DeclareImplicitMoveConstructor(ClassDecl); 5489 } 5490 5491 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 5492 ++ASTContext::NumImplicitCopyAssignmentOperators; 5493 5494 // If we have a dynamic class, then the copy assignment operator may be 5495 // virtual, so we have to declare it immediately. This ensures that, e.g., 5496 // it shows up in the right place in the vtable and that we diagnose 5497 // problems with the implicit exception specification. 5498 if (ClassDecl->isDynamicClass() || 5499 ClassDecl->needsOverloadResolutionForCopyAssignment()) 5500 DeclareImplicitCopyAssignment(ClassDecl); 5501 } 5502 5503 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 5504 ++ASTContext::NumImplicitMoveAssignmentOperators; 5505 5506 // Likewise for the move assignment operator. 5507 if (ClassDecl->isDynamicClass() || 5508 ClassDecl->needsOverloadResolutionForMoveAssignment()) 5509 DeclareImplicitMoveAssignment(ClassDecl); 5510 } 5511 5512 if (!ClassDecl->hasUserDeclaredDestructor()) { 5513 ++ASTContext::NumImplicitDestructors; 5514 5515 // If we have a dynamic class, then the destructor may be virtual, so we 5516 // have to declare the destructor immediately. This ensures that, e.g., it 5517 // shows up in the right place in the vtable and that we diagnose problems 5518 // with the implicit exception specification. 5519 if (ClassDecl->isDynamicClass() || 5520 ClassDecl->needsOverloadResolutionForDestructor()) 5521 DeclareImplicitDestructor(ClassDecl); 5522 } 5523} 5524 5525void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) { 5526 if (!D) 5527 return; 5528 5529 int NumParamList = D->getNumTemplateParameterLists(); 5530 for (int i = 0; i < NumParamList; i++) { 5531 TemplateParameterList* Params = D->getTemplateParameterList(i); 5532 for (TemplateParameterList::iterator Param = Params->begin(), 5533 ParamEnd = Params->end(); 5534 Param != ParamEnd; ++Param) { 5535 NamedDecl *Named = cast<NamedDecl>(*Param); 5536 if (Named->getDeclName()) { 5537 S->AddDecl(Named); 5538 IdResolver.AddDecl(Named); 5539 } 5540 } 5541 } 5542} 5543 5544void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 5545 if (!D) 5546 return; 5547 5548 TemplateParameterList *Params = 0; 5549 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) 5550 Params = Template->getTemplateParameters(); 5551 else if (ClassTemplatePartialSpecializationDecl *PartialSpec 5552 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 5553 Params = PartialSpec->getTemplateParameters(); 5554 else 5555 return; 5556 5557 for (TemplateParameterList::iterator Param = Params->begin(), 5558 ParamEnd = Params->end(); 5559 Param != ParamEnd; ++Param) { 5560 NamedDecl *Named = cast<NamedDecl>(*Param); 5561 if (Named->getDeclName()) { 5562 S->AddDecl(Named); 5563 IdResolver.AddDecl(Named); 5564 } 5565 } 5566} 5567 5568void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 5569 if (!RecordD) return; 5570 AdjustDeclIfTemplate(RecordD); 5571 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 5572 PushDeclContext(S, Record); 5573} 5574 5575void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 5576 if (!RecordD) return; 5577 PopDeclContext(); 5578} 5579 5580/// ActOnStartDelayedCXXMethodDeclaration - We have completed 5581/// parsing a top-level (non-nested) C++ class, and we are now 5582/// parsing those parts of the given Method declaration that could 5583/// not be parsed earlier (C++ [class.mem]p2), such as default 5584/// arguments. This action should enter the scope of the given 5585/// Method declaration as if we had just parsed the qualified method 5586/// name. However, it should not bring the parameters into scope; 5587/// that will be performed by ActOnDelayedCXXMethodParameter. 5588void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 5589} 5590 5591/// ActOnDelayedCXXMethodParameter - We've already started a delayed 5592/// C++ method declaration. We're (re-)introducing the given 5593/// function parameter into scope for use in parsing later parts of 5594/// the method declaration. For example, we could see an 5595/// ActOnParamDefaultArgument event for this parameter. 5596void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 5597 if (!ParamD) 5598 return; 5599 5600 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 5601 5602 // If this parameter has an unparsed default argument, clear it out 5603 // to make way for the parsed default argument. 5604 if (Param->hasUnparsedDefaultArg()) 5605 Param->setDefaultArg(0); 5606 5607 S->AddDecl(Param); 5608 if (Param->getDeclName()) 5609 IdResolver.AddDecl(Param); 5610} 5611 5612/// ActOnFinishDelayedCXXMethodDeclaration - We have finished 5613/// processing the delayed method declaration for Method. The method 5614/// declaration is now considered finished. There may be a separate 5615/// ActOnStartOfFunctionDef action later (not necessarily 5616/// immediately!) for this method, if it was also defined inside the 5617/// class body. 5618void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 5619 if (!MethodD) 5620 return; 5621 5622 AdjustDeclIfTemplate(MethodD); 5623 5624 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 5625 5626 // Now that we have our default arguments, check the constructor 5627 // again. It could produce additional diagnostics or affect whether 5628 // the class has implicitly-declared destructors, among other 5629 // things. 5630 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 5631 CheckConstructor(Constructor); 5632 5633 // Check the default arguments, which we may have added. 5634 if (!Method->isInvalidDecl()) 5635 CheckCXXDefaultArguments(Method); 5636} 5637 5638/// CheckConstructorDeclarator - Called by ActOnDeclarator to check 5639/// the well-formedness of the constructor declarator @p D with type @p 5640/// R. If there are any errors in the declarator, this routine will 5641/// emit diagnostics and set the invalid bit to true. In any case, the type 5642/// will be updated to reflect a well-formed type for the constructor and 5643/// returned. 5644QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 5645 StorageClass &SC) { 5646 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 5647 5648 // C++ [class.ctor]p3: 5649 // A constructor shall not be virtual (10.3) or static (9.4). A 5650 // constructor can be invoked for a const, volatile or const 5651 // volatile object. A constructor shall not be declared const, 5652 // volatile, or const volatile (9.3.2). 5653 if (isVirtual) { 5654 if (!D.isInvalidType()) 5655 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 5656 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 5657 << SourceRange(D.getIdentifierLoc()); 5658 D.setInvalidType(); 5659 } 5660 if (SC == SC_Static) { 5661 if (!D.isInvalidType()) 5662 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 5663 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 5664 << SourceRange(D.getIdentifierLoc()); 5665 D.setInvalidType(); 5666 SC = SC_None; 5667 } 5668 5669 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 5670 if (FTI.TypeQuals != 0) { 5671 if (FTI.TypeQuals & Qualifiers::Const) 5672 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 5673 << "const" << SourceRange(D.getIdentifierLoc()); 5674 if (FTI.TypeQuals & Qualifiers::Volatile) 5675 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 5676 << "volatile" << SourceRange(D.getIdentifierLoc()); 5677 if (FTI.TypeQuals & Qualifiers::Restrict) 5678 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 5679 << "restrict" << SourceRange(D.getIdentifierLoc()); 5680 D.setInvalidType(); 5681 } 5682 5683 // C++0x [class.ctor]p4: 5684 // A constructor shall not be declared with a ref-qualifier. 5685 if (FTI.hasRefQualifier()) { 5686 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 5687 << FTI.RefQualifierIsLValueRef 5688 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 5689 D.setInvalidType(); 5690 } 5691 5692 // Rebuild the function type "R" without any type qualifiers (in 5693 // case any of the errors above fired) and with "void" as the 5694 // return type, since constructors don't have return types. 5695 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 5696 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType()) 5697 return R; 5698 5699 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 5700 EPI.TypeQuals = 0; 5701 EPI.RefQualifier = RQ_None; 5702 5703 return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI); 5704} 5705 5706/// CheckConstructor - Checks a fully-formed constructor for 5707/// well-formedness, issuing any diagnostics required. Returns true if 5708/// the constructor declarator is invalid. 5709void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 5710 CXXRecordDecl *ClassDecl 5711 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 5712 if (!ClassDecl) 5713 return Constructor->setInvalidDecl(); 5714 5715 // C++ [class.copy]p3: 5716 // A declaration of a constructor for a class X is ill-formed if 5717 // its first parameter is of type (optionally cv-qualified) X and 5718 // either there are no other parameters or else all other 5719 // parameters have default arguments. 5720 if (!Constructor->isInvalidDecl() && 5721 ((Constructor->getNumParams() == 1) || 5722 (Constructor->getNumParams() > 1 && 5723 Constructor->getParamDecl(1)->hasDefaultArg())) && 5724 Constructor->getTemplateSpecializationKind() 5725 != TSK_ImplicitInstantiation) { 5726 QualType ParamType = Constructor->getParamDecl(0)->getType(); 5727 QualType ClassTy = Context.getTagDeclType(ClassDecl); 5728 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 5729 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 5730 const char *ConstRef 5731 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 5732 : " const &"; 5733 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 5734 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 5735 5736 // FIXME: Rather that making the constructor invalid, we should endeavor 5737 // to fix the type. 5738 Constructor->setInvalidDecl(); 5739 } 5740 } 5741} 5742 5743/// CheckDestructor - Checks a fully-formed destructor definition for 5744/// well-formedness, issuing any diagnostics required. Returns true 5745/// on error. 5746bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 5747 CXXRecordDecl *RD = Destructor->getParent(); 5748 5749 if (Destructor->isVirtual()) { 5750 SourceLocation Loc; 5751 5752 if (!Destructor->isImplicit()) 5753 Loc = Destructor->getLocation(); 5754 else 5755 Loc = RD->getLocation(); 5756 5757 // If we have a virtual destructor, look up the deallocation function 5758 FunctionDecl *OperatorDelete = 0; 5759 DeclarationName Name = 5760 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 5761 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 5762 return true; 5763 5764 MarkFunctionReferenced(Loc, OperatorDelete); 5765 5766 Destructor->setOperatorDelete(OperatorDelete); 5767 } 5768 5769 return false; 5770} 5771 5772static inline bool 5773FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) { 5774 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 5775 FTI.ArgInfo[0].Param && 5776 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()); 5777} 5778 5779/// CheckDestructorDeclarator - Called by ActOnDeclarator to check 5780/// the well-formednes of the destructor declarator @p D with type @p 5781/// R. If there are any errors in the declarator, this routine will 5782/// emit diagnostics and set the declarator to invalid. Even if this happens, 5783/// will be updated to reflect a well-formed type for the destructor and 5784/// returned. 5785QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 5786 StorageClass& SC) { 5787 // C++ [class.dtor]p1: 5788 // [...] A typedef-name that names a class is a class-name 5789 // (7.1.3); however, a typedef-name that names a class shall not 5790 // be used as the identifier in the declarator for a destructor 5791 // declaration. 5792 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 5793 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 5794 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 5795 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 5796 else if (const TemplateSpecializationType *TST = 5797 DeclaratorType->getAs<TemplateSpecializationType>()) 5798 if (TST->isTypeAlias()) 5799 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 5800 << DeclaratorType << 1; 5801 5802 // C++ [class.dtor]p2: 5803 // A destructor is used to destroy objects of its class type. A 5804 // destructor takes no parameters, and no return type can be 5805 // specified for it (not even void). The address of a destructor 5806 // shall not be taken. A destructor shall not be static. A 5807 // destructor can be invoked for a const, volatile or const 5808 // volatile object. A destructor shall not be declared const, 5809 // volatile or const volatile (9.3.2). 5810 if (SC == SC_Static) { 5811 if (!D.isInvalidType()) 5812 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 5813 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 5814 << SourceRange(D.getIdentifierLoc()) 5815 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5816 5817 SC = SC_None; 5818 } 5819 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 5820 // Destructors don't have return types, but the parser will 5821 // happily parse something like: 5822 // 5823 // class X { 5824 // float ~X(); 5825 // }; 5826 // 5827 // The return type will be eliminated later. 5828 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 5829 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 5830 << SourceRange(D.getIdentifierLoc()); 5831 } 5832 5833 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 5834 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 5835 if (FTI.TypeQuals & Qualifiers::Const) 5836 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 5837 << "const" << SourceRange(D.getIdentifierLoc()); 5838 if (FTI.TypeQuals & Qualifiers::Volatile) 5839 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 5840 << "volatile" << SourceRange(D.getIdentifierLoc()); 5841 if (FTI.TypeQuals & Qualifiers::Restrict) 5842 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 5843 << "restrict" << SourceRange(D.getIdentifierLoc()); 5844 D.setInvalidType(); 5845 } 5846 5847 // C++0x [class.dtor]p2: 5848 // A destructor shall not be declared with a ref-qualifier. 5849 if (FTI.hasRefQualifier()) { 5850 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 5851 << FTI.RefQualifierIsLValueRef 5852 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 5853 D.setInvalidType(); 5854 } 5855 5856 // Make sure we don't have any parameters. 5857 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) { 5858 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 5859 5860 // Delete the parameters. 5861 FTI.freeArgs(); 5862 D.setInvalidType(); 5863 } 5864 5865 // Make sure the destructor isn't variadic. 5866 if (FTI.isVariadic) { 5867 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 5868 D.setInvalidType(); 5869 } 5870 5871 // Rebuild the function type "R" without any type qualifiers or 5872 // parameters (in case any of the errors above fired) and with 5873 // "void" as the return type, since destructors don't have return 5874 // types. 5875 if (!D.isInvalidType()) 5876 return R; 5877 5878 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 5879 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 5880 EPI.Variadic = false; 5881 EPI.TypeQuals = 0; 5882 EPI.RefQualifier = RQ_None; 5883 return Context.getFunctionType(Context.VoidTy, ArrayRef<QualType>(), EPI); 5884} 5885 5886/// CheckConversionDeclarator - Called by ActOnDeclarator to check the 5887/// well-formednes of the conversion function declarator @p D with 5888/// type @p R. If there are any errors in the declarator, this routine 5889/// will emit diagnostics and return true. Otherwise, it will return 5890/// false. Either way, the type @p R will be updated to reflect a 5891/// well-formed type for the conversion operator. 5892void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 5893 StorageClass& SC) { 5894 // C++ [class.conv.fct]p1: 5895 // Neither parameter types nor return type can be specified. The 5896 // type of a conversion function (8.3.5) is "function taking no 5897 // parameter returning conversion-type-id." 5898 if (SC == SC_Static) { 5899 if (!D.isInvalidType()) 5900 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 5901 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 5902 << SourceRange(D.getIdentifierLoc()); 5903 D.setInvalidType(); 5904 SC = SC_None; 5905 } 5906 5907 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId); 5908 5909 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 5910 // Conversion functions don't have return types, but the parser will 5911 // happily parse something like: 5912 // 5913 // class X { 5914 // float operator bool(); 5915 // }; 5916 // 5917 // The return type will be changed later anyway. 5918 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 5919 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 5920 << SourceRange(D.getIdentifierLoc()); 5921 D.setInvalidType(); 5922 } 5923 5924 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 5925 5926 // Make sure we don't have any parameters. 5927 if (Proto->getNumArgs() > 0) { 5928 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 5929 5930 // Delete the parameters. 5931 D.getFunctionTypeInfo().freeArgs(); 5932 D.setInvalidType(); 5933 } else if (Proto->isVariadic()) { 5934 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 5935 D.setInvalidType(); 5936 } 5937 5938 // Diagnose "&operator bool()" and other such nonsense. This 5939 // is actually a gcc extension which we don't support. 5940 if (Proto->getResultType() != ConvType) { 5941 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 5942 << Proto->getResultType(); 5943 D.setInvalidType(); 5944 ConvType = Proto->getResultType(); 5945 } 5946 5947 // C++ [class.conv.fct]p4: 5948 // The conversion-type-id shall not represent a function type nor 5949 // an array type. 5950 if (ConvType->isArrayType()) { 5951 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 5952 ConvType = Context.getPointerType(ConvType); 5953 D.setInvalidType(); 5954 } else if (ConvType->isFunctionType()) { 5955 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 5956 ConvType = Context.getPointerType(ConvType); 5957 D.setInvalidType(); 5958 } 5959 5960 // Rebuild the function type "R" without any parameters (in case any 5961 // of the errors above fired) and with the conversion type as the 5962 // return type. 5963 if (D.isInvalidType()) 5964 R = Context.getFunctionType(ConvType, ArrayRef<QualType>(), 5965 Proto->getExtProtoInfo()); 5966 5967 // C++0x explicit conversion operators. 5968 if (D.getDeclSpec().isExplicitSpecified()) 5969 Diag(D.getDeclSpec().getExplicitSpecLoc(), 5970 getLangOpts().CPlusPlus11 ? 5971 diag::warn_cxx98_compat_explicit_conversion_functions : 5972 diag::ext_explicit_conversion_functions) 5973 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 5974} 5975 5976/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 5977/// the declaration of the given C++ conversion function. This routine 5978/// is responsible for recording the conversion function in the C++ 5979/// class, if possible. 5980Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 5981 assert(Conversion && "Expected to receive a conversion function declaration"); 5982 5983 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 5984 5985 // Make sure we aren't redeclaring the conversion function. 5986 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 5987 5988 // C++ [class.conv.fct]p1: 5989 // [...] A conversion function is never used to convert a 5990 // (possibly cv-qualified) object to the (possibly cv-qualified) 5991 // same object type (or a reference to it), to a (possibly 5992 // cv-qualified) base class of that type (or a reference to it), 5993 // or to (possibly cv-qualified) void. 5994 // FIXME: Suppress this warning if the conversion function ends up being a 5995 // virtual function that overrides a virtual function in a base class. 5996 QualType ClassType 5997 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 5998 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 5999 ConvType = ConvTypeRef->getPointeeType(); 6000 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 6001 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 6002 /* Suppress diagnostics for instantiations. */; 6003 else if (ConvType->isRecordType()) { 6004 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 6005 if (ConvType == ClassType) 6006 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 6007 << ClassType; 6008 else if (IsDerivedFrom(ClassType, ConvType)) 6009 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 6010 << ClassType << ConvType; 6011 } else if (ConvType->isVoidType()) { 6012 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 6013 << ClassType << ConvType; 6014 } 6015 6016 if (FunctionTemplateDecl *ConversionTemplate 6017 = Conversion->getDescribedFunctionTemplate()) 6018 return ConversionTemplate; 6019 6020 return Conversion; 6021} 6022 6023//===----------------------------------------------------------------------===// 6024// Namespace Handling 6025//===----------------------------------------------------------------------===// 6026 6027/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is 6028/// reopened. 6029static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 6030 SourceLocation Loc, 6031 IdentifierInfo *II, bool *IsInline, 6032 NamespaceDecl *PrevNS) { 6033 assert(*IsInline != PrevNS->isInline()); 6034 6035 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 6036 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 6037 // inline namespaces, with the intention of bringing names into namespace std. 6038 // 6039 // We support this just well enough to get that case working; this is not 6040 // sufficient to support reopening namespaces as inline in general. 6041 if (*IsInline && II && II->getName().startswith("__atomic") && 6042 S.getSourceManager().isInSystemHeader(Loc)) { 6043 // Mark all prior declarations of the namespace as inline. 6044 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 6045 NS = NS->getPreviousDecl()) 6046 NS->setInline(*IsInline); 6047 // Patch up the lookup table for the containing namespace. This isn't really 6048 // correct, but it's good enough for this particular case. 6049 for (DeclContext::decl_iterator I = PrevNS->decls_begin(), 6050 E = PrevNS->decls_end(); I != E; ++I) 6051 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I)) 6052 PrevNS->getParent()->makeDeclVisibleInContext(ND); 6053 return; 6054 } 6055 6056 if (PrevNS->isInline()) 6057 // The user probably just forgot the 'inline', so suggest that it 6058 // be added back. 6059 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 6060 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 6061 else 6062 S.Diag(Loc, diag::err_inline_namespace_mismatch) 6063 << IsInline; 6064 6065 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 6066 *IsInline = PrevNS->isInline(); 6067} 6068 6069/// ActOnStartNamespaceDef - This is called at the start of a namespace 6070/// definition. 6071Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 6072 SourceLocation InlineLoc, 6073 SourceLocation NamespaceLoc, 6074 SourceLocation IdentLoc, 6075 IdentifierInfo *II, 6076 SourceLocation LBrace, 6077 AttributeList *AttrList) { 6078 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 6079 // For anonymous namespace, take the location of the left brace. 6080 SourceLocation Loc = II ? IdentLoc : LBrace; 6081 bool IsInline = InlineLoc.isValid(); 6082 bool IsInvalid = false; 6083 bool IsStd = false; 6084 bool AddToKnown = false; 6085 Scope *DeclRegionScope = NamespcScope->getParent(); 6086 6087 NamespaceDecl *PrevNS = 0; 6088 if (II) { 6089 // C++ [namespace.def]p2: 6090 // The identifier in an original-namespace-definition shall not 6091 // have been previously defined in the declarative region in 6092 // which the original-namespace-definition appears. The 6093 // identifier in an original-namespace-definition is the name of 6094 // the namespace. Subsequently in that declarative region, it is 6095 // treated as an original-namespace-name. 6096 // 6097 // Since namespace names are unique in their scope, and we don't 6098 // look through using directives, just look for any ordinary names. 6099 6100 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member | 6101 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag | 6102 Decl::IDNS_Namespace; 6103 NamedDecl *PrevDecl = 0; 6104 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II); 6105 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 6106 ++I) { 6107 if ((*I)->getIdentifierNamespace() & IDNS) { 6108 PrevDecl = *I; 6109 break; 6110 } 6111 } 6112 6113 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 6114 6115 if (PrevNS) { 6116 // This is an extended namespace definition. 6117 if (IsInline != PrevNS->isInline()) 6118 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 6119 &IsInline, PrevNS); 6120 } else if (PrevDecl) { 6121 // This is an invalid name redefinition. 6122 Diag(Loc, diag::err_redefinition_different_kind) 6123 << II; 6124 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 6125 IsInvalid = true; 6126 // Continue on to push Namespc as current DeclContext and return it. 6127 } else if (II->isStr("std") && 6128 CurContext->getRedeclContext()->isTranslationUnit()) { 6129 // This is the first "real" definition of the namespace "std", so update 6130 // our cache of the "std" namespace to point at this definition. 6131 PrevNS = getStdNamespace(); 6132 IsStd = true; 6133 AddToKnown = !IsInline; 6134 } else { 6135 // We've seen this namespace for the first time. 6136 AddToKnown = !IsInline; 6137 } 6138 } else { 6139 // Anonymous namespaces. 6140 6141 // Determine whether the parent already has an anonymous namespace. 6142 DeclContext *Parent = CurContext->getRedeclContext(); 6143 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 6144 PrevNS = TU->getAnonymousNamespace(); 6145 } else { 6146 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 6147 PrevNS = ND->getAnonymousNamespace(); 6148 } 6149 6150 if (PrevNS && IsInline != PrevNS->isInline()) 6151 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 6152 &IsInline, PrevNS); 6153 } 6154 6155 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 6156 StartLoc, Loc, II, PrevNS); 6157 if (IsInvalid) 6158 Namespc->setInvalidDecl(); 6159 6160 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 6161 6162 // FIXME: Should we be merging attributes? 6163 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 6164 PushNamespaceVisibilityAttr(Attr, Loc); 6165 6166 if (IsStd) 6167 StdNamespace = Namespc; 6168 if (AddToKnown) 6169 KnownNamespaces[Namespc] = false; 6170 6171 if (II) { 6172 PushOnScopeChains(Namespc, DeclRegionScope); 6173 } else { 6174 // Link the anonymous namespace into its parent. 6175 DeclContext *Parent = CurContext->getRedeclContext(); 6176 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 6177 TU->setAnonymousNamespace(Namespc); 6178 } else { 6179 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 6180 } 6181 6182 CurContext->addDecl(Namespc); 6183 6184 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 6185 // behaves as if it were replaced by 6186 // namespace unique { /* empty body */ } 6187 // using namespace unique; 6188 // namespace unique { namespace-body } 6189 // where all occurrences of 'unique' in a translation unit are 6190 // replaced by the same identifier and this identifier differs 6191 // from all other identifiers in the entire program. 6192 6193 // We just create the namespace with an empty name and then add an 6194 // implicit using declaration, just like the standard suggests. 6195 // 6196 // CodeGen enforces the "universally unique" aspect by giving all 6197 // declarations semantically contained within an anonymous 6198 // namespace internal linkage. 6199 6200 if (!PrevNS) { 6201 UsingDirectiveDecl* UD 6202 = UsingDirectiveDecl::Create(Context, Parent, 6203 /* 'using' */ LBrace, 6204 /* 'namespace' */ SourceLocation(), 6205 /* qualifier */ NestedNameSpecifierLoc(), 6206 /* identifier */ SourceLocation(), 6207 Namespc, 6208 /* Ancestor */ Parent); 6209 UD->setImplicit(); 6210 Parent->addDecl(UD); 6211 } 6212 } 6213 6214 ActOnDocumentableDecl(Namespc); 6215 6216 // Although we could have an invalid decl (i.e. the namespace name is a 6217 // redefinition), push it as current DeclContext and try to continue parsing. 6218 // FIXME: We should be able to push Namespc here, so that the each DeclContext 6219 // for the namespace has the declarations that showed up in that particular 6220 // namespace definition. 6221 PushDeclContext(NamespcScope, Namespc); 6222 return Namespc; 6223} 6224 6225/// getNamespaceDecl - Returns the namespace a decl represents. If the decl 6226/// is a namespace alias, returns the namespace it points to. 6227static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 6228 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 6229 return AD->getNamespace(); 6230 return dyn_cast_or_null<NamespaceDecl>(D); 6231} 6232 6233/// ActOnFinishNamespaceDef - This callback is called after a namespace is 6234/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 6235void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 6236 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 6237 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 6238 Namespc->setRBraceLoc(RBrace); 6239 PopDeclContext(); 6240 if (Namespc->hasAttr<VisibilityAttr>()) 6241 PopPragmaVisibility(true, RBrace); 6242} 6243 6244CXXRecordDecl *Sema::getStdBadAlloc() const { 6245 return cast_or_null<CXXRecordDecl>( 6246 StdBadAlloc.get(Context.getExternalSource())); 6247} 6248 6249NamespaceDecl *Sema::getStdNamespace() const { 6250 return cast_or_null<NamespaceDecl>( 6251 StdNamespace.get(Context.getExternalSource())); 6252} 6253 6254/// \brief Retrieve the special "std" namespace, which may require us to 6255/// implicitly define the namespace. 6256NamespaceDecl *Sema::getOrCreateStdNamespace() { 6257 if (!StdNamespace) { 6258 // The "std" namespace has not yet been defined, so build one implicitly. 6259 StdNamespace = NamespaceDecl::Create(Context, 6260 Context.getTranslationUnitDecl(), 6261 /*Inline=*/false, 6262 SourceLocation(), SourceLocation(), 6263 &PP.getIdentifierTable().get("std"), 6264 /*PrevDecl=*/0); 6265 getStdNamespace()->setImplicit(true); 6266 } 6267 6268 return getStdNamespace(); 6269} 6270 6271bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 6272 assert(getLangOpts().CPlusPlus && 6273 "Looking for std::initializer_list outside of C++."); 6274 6275 // We're looking for implicit instantiations of 6276 // template <typename E> class std::initializer_list. 6277 6278 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 6279 return false; 6280 6281 ClassTemplateDecl *Template = 0; 6282 const TemplateArgument *Arguments = 0; 6283 6284 if (const RecordType *RT = Ty->getAs<RecordType>()) { 6285 6286 ClassTemplateSpecializationDecl *Specialization = 6287 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 6288 if (!Specialization) 6289 return false; 6290 6291 Template = Specialization->getSpecializedTemplate(); 6292 Arguments = Specialization->getTemplateArgs().data(); 6293 } else if (const TemplateSpecializationType *TST = 6294 Ty->getAs<TemplateSpecializationType>()) { 6295 Template = dyn_cast_or_null<ClassTemplateDecl>( 6296 TST->getTemplateName().getAsTemplateDecl()); 6297 Arguments = TST->getArgs(); 6298 } 6299 if (!Template) 6300 return false; 6301 6302 if (!StdInitializerList) { 6303 // Haven't recognized std::initializer_list yet, maybe this is it. 6304 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 6305 if (TemplateClass->getIdentifier() != 6306 &PP.getIdentifierTable().get("initializer_list") || 6307 !getStdNamespace()->InEnclosingNamespaceSetOf( 6308 TemplateClass->getDeclContext())) 6309 return false; 6310 // This is a template called std::initializer_list, but is it the right 6311 // template? 6312 TemplateParameterList *Params = Template->getTemplateParameters(); 6313 if (Params->getMinRequiredArguments() != 1) 6314 return false; 6315 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 6316 return false; 6317 6318 // It's the right template. 6319 StdInitializerList = Template; 6320 } 6321 6322 if (Template != StdInitializerList) 6323 return false; 6324 6325 // This is an instance of std::initializer_list. Find the argument type. 6326 if (Element) 6327 *Element = Arguments[0].getAsType(); 6328 return true; 6329} 6330 6331static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 6332 NamespaceDecl *Std = S.getStdNamespace(); 6333 if (!Std) { 6334 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 6335 return 0; 6336 } 6337 6338 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 6339 Loc, Sema::LookupOrdinaryName); 6340 if (!S.LookupQualifiedName(Result, Std)) { 6341 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 6342 return 0; 6343 } 6344 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 6345 if (!Template) { 6346 Result.suppressDiagnostics(); 6347 // We found something weird. Complain about the first thing we found. 6348 NamedDecl *Found = *Result.begin(); 6349 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 6350 return 0; 6351 } 6352 6353 // We found some template called std::initializer_list. Now verify that it's 6354 // correct. 6355 TemplateParameterList *Params = Template->getTemplateParameters(); 6356 if (Params->getMinRequiredArguments() != 1 || 6357 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 6358 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 6359 return 0; 6360 } 6361 6362 return Template; 6363} 6364 6365QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 6366 if (!StdInitializerList) { 6367 StdInitializerList = LookupStdInitializerList(*this, Loc); 6368 if (!StdInitializerList) 6369 return QualType(); 6370 } 6371 6372 TemplateArgumentListInfo Args(Loc, Loc); 6373 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 6374 Context.getTrivialTypeSourceInfo(Element, 6375 Loc))); 6376 return Context.getCanonicalType( 6377 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 6378} 6379 6380bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) { 6381 // C++ [dcl.init.list]p2: 6382 // A constructor is an initializer-list constructor if its first parameter 6383 // is of type std::initializer_list<E> or reference to possibly cv-qualified 6384 // std::initializer_list<E> for some type E, and either there are no other 6385 // parameters or else all other parameters have default arguments. 6386 if (Ctor->getNumParams() < 1 || 6387 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 6388 return false; 6389 6390 QualType ArgType = Ctor->getParamDecl(0)->getType(); 6391 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 6392 ArgType = RT->getPointeeType().getUnqualifiedType(); 6393 6394 return isStdInitializerList(ArgType, 0); 6395} 6396 6397/// \brief Determine whether a using statement is in a context where it will be 6398/// apply in all contexts. 6399static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 6400 switch (CurContext->getDeclKind()) { 6401 case Decl::TranslationUnit: 6402 return true; 6403 case Decl::LinkageSpec: 6404 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 6405 default: 6406 return false; 6407 } 6408} 6409 6410namespace { 6411 6412// Callback to only accept typo corrections that are namespaces. 6413class NamespaceValidatorCCC : public CorrectionCandidateCallback { 6414 public: 6415 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 6416 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 6417 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 6418 } 6419 return false; 6420 } 6421}; 6422 6423} 6424 6425static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 6426 CXXScopeSpec &SS, 6427 SourceLocation IdentLoc, 6428 IdentifierInfo *Ident) { 6429 NamespaceValidatorCCC Validator; 6430 R.clear(); 6431 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(), 6432 R.getLookupKind(), Sc, &SS, 6433 Validator)) { 6434 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 6435 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts())); 6436 if (DeclContext *DC = S.computeDeclContext(SS, false)) 6437 S.Diag(IdentLoc, diag::err_using_directive_member_suggest) 6438 << Ident << DC << CorrectedQuotedStr << SS.getRange() 6439 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(), 6440 CorrectedStr); 6441 else 6442 S.Diag(IdentLoc, diag::err_using_directive_suggest) 6443 << Ident << CorrectedQuotedStr 6444 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr); 6445 6446 S.Diag(Corrected.getCorrectionDecl()->getLocation(), 6447 diag::note_namespace_defined_here) << CorrectedQuotedStr; 6448 6449 R.addDecl(Corrected.getCorrectionDecl()); 6450 return true; 6451 } 6452 return false; 6453} 6454 6455Decl *Sema::ActOnUsingDirective(Scope *S, 6456 SourceLocation UsingLoc, 6457 SourceLocation NamespcLoc, 6458 CXXScopeSpec &SS, 6459 SourceLocation IdentLoc, 6460 IdentifierInfo *NamespcName, 6461 AttributeList *AttrList) { 6462 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 6463 assert(NamespcName && "Invalid NamespcName."); 6464 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 6465 6466 // This can only happen along a recovery path. 6467 while (S->getFlags() & Scope::TemplateParamScope) 6468 S = S->getParent(); 6469 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 6470 6471 UsingDirectiveDecl *UDir = 0; 6472 NestedNameSpecifier *Qualifier = 0; 6473 if (SS.isSet()) 6474 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 6475 6476 // Lookup namespace name. 6477 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 6478 LookupParsedName(R, S, &SS); 6479 if (R.isAmbiguous()) 6480 return 0; 6481 6482 if (R.empty()) { 6483 R.clear(); 6484 // Allow "using namespace std;" or "using namespace ::std;" even if 6485 // "std" hasn't been defined yet, for GCC compatibility. 6486 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 6487 NamespcName->isStr("std")) { 6488 Diag(IdentLoc, diag::ext_using_undefined_std); 6489 R.addDecl(getOrCreateStdNamespace()); 6490 R.resolveKind(); 6491 } 6492 // Otherwise, attempt typo correction. 6493 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 6494 } 6495 6496 if (!R.empty()) { 6497 NamedDecl *Named = R.getFoundDecl(); 6498 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named)) 6499 && "expected namespace decl"); 6500 // C++ [namespace.udir]p1: 6501 // A using-directive specifies that the names in the nominated 6502 // namespace can be used in the scope in which the 6503 // using-directive appears after the using-directive. During 6504 // unqualified name lookup (3.4.1), the names appear as if they 6505 // were declared in the nearest enclosing namespace which 6506 // contains both the using-directive and the nominated 6507 // namespace. [Note: in this context, "contains" means "contains 6508 // directly or indirectly". ] 6509 6510 // Find enclosing context containing both using-directive and 6511 // nominated namespace. 6512 NamespaceDecl *NS = getNamespaceDecl(Named); 6513 DeclContext *CommonAncestor = cast<DeclContext>(NS); 6514 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 6515 CommonAncestor = CommonAncestor->getParent(); 6516 6517 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 6518 SS.getWithLocInContext(Context), 6519 IdentLoc, Named, CommonAncestor); 6520 6521 if (IsUsingDirectiveInToplevelContext(CurContext) && 6522 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 6523 Diag(IdentLoc, diag::warn_using_directive_in_header); 6524 } 6525 6526 PushUsingDirective(S, UDir); 6527 } else { 6528 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 6529 } 6530 6531 if (UDir) 6532 ProcessDeclAttributeList(S, UDir, AttrList); 6533 6534 return UDir; 6535} 6536 6537void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 6538 // If the scope has an associated entity and the using directive is at 6539 // namespace or translation unit scope, add the UsingDirectiveDecl into 6540 // its lookup structure so qualified name lookup can find it. 6541 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()); 6542 if (Ctx && !Ctx->isFunctionOrMethod()) 6543 Ctx->addDecl(UDir); 6544 else 6545 // Otherwise, it is at block sope. The using-directives will affect lookup 6546 // only to the end of the scope. 6547 S->PushUsingDirective(UDir); 6548} 6549 6550 6551Decl *Sema::ActOnUsingDeclaration(Scope *S, 6552 AccessSpecifier AS, 6553 bool HasUsingKeyword, 6554 SourceLocation UsingLoc, 6555 CXXScopeSpec &SS, 6556 UnqualifiedId &Name, 6557 AttributeList *AttrList, 6558 bool IsTypeName, 6559 SourceLocation TypenameLoc) { 6560 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 6561 6562 switch (Name.getKind()) { 6563 case UnqualifiedId::IK_ImplicitSelfParam: 6564 case UnqualifiedId::IK_Identifier: 6565 case UnqualifiedId::IK_OperatorFunctionId: 6566 case UnqualifiedId::IK_LiteralOperatorId: 6567 case UnqualifiedId::IK_ConversionFunctionId: 6568 break; 6569 6570 case UnqualifiedId::IK_ConstructorName: 6571 case UnqualifiedId::IK_ConstructorTemplateId: 6572 // C++11 inheriting constructors. 6573 Diag(Name.getLocStart(), 6574 getLangOpts().CPlusPlus11 ? 6575 diag::warn_cxx98_compat_using_decl_constructor : 6576 diag::err_using_decl_constructor) 6577 << SS.getRange(); 6578 6579 if (getLangOpts().CPlusPlus11) break; 6580 6581 return 0; 6582 6583 case UnqualifiedId::IK_DestructorName: 6584 Diag(Name.getLocStart(), diag::err_using_decl_destructor) 6585 << SS.getRange(); 6586 return 0; 6587 6588 case UnqualifiedId::IK_TemplateId: 6589 Diag(Name.getLocStart(), diag::err_using_decl_template_id) 6590 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 6591 return 0; 6592 } 6593 6594 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 6595 DeclarationName TargetName = TargetNameInfo.getName(); 6596 if (!TargetName) 6597 return 0; 6598 6599 // Warn about access declarations. 6600 // TODO: store that the declaration was written without 'using' and 6601 // talk about access decls instead of using decls in the 6602 // diagnostics. 6603 if (!HasUsingKeyword) { 6604 UsingLoc = Name.getLocStart(); 6605 6606 Diag(UsingLoc, diag::warn_access_decl_deprecated) 6607 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 6608 } 6609 6610 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 6611 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 6612 return 0; 6613 6614 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 6615 TargetNameInfo, AttrList, 6616 /* IsInstantiation */ false, 6617 IsTypeName, TypenameLoc); 6618 if (UD) 6619 PushOnScopeChains(UD, S, /*AddToContext*/ false); 6620 6621 return UD; 6622} 6623 6624/// \brief Determine whether a using declaration considers the given 6625/// declarations as "equivalent", e.g., if they are redeclarations of 6626/// the same entity or are both typedefs of the same type. 6627static bool 6628IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2, 6629 bool &SuppressRedeclaration) { 6630 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) { 6631 SuppressRedeclaration = false; 6632 return true; 6633 } 6634 6635 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 6636 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) { 6637 SuppressRedeclaration = true; 6638 return Context.hasSameType(TD1->getUnderlyingType(), 6639 TD2->getUnderlyingType()); 6640 } 6641 6642 return false; 6643} 6644 6645 6646/// Determines whether to create a using shadow decl for a particular 6647/// decl, given the set of decls existing prior to this using lookup. 6648bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 6649 const LookupResult &Previous) { 6650 // Diagnose finding a decl which is not from a base class of the 6651 // current class. We do this now because there are cases where this 6652 // function will silently decide not to build a shadow decl, which 6653 // will pre-empt further diagnostics. 6654 // 6655 // We don't need to do this in C++0x because we do the check once on 6656 // the qualifier. 6657 // 6658 // FIXME: diagnose the following if we care enough: 6659 // struct A { int foo; }; 6660 // struct B : A { using A::foo; }; 6661 // template <class T> struct C : A {}; 6662 // template <class T> struct D : C<T> { using B::foo; } // <--- 6663 // This is invalid (during instantiation) in C++03 because B::foo 6664 // resolves to the using decl in B, which is not a base class of D<T>. 6665 // We can't diagnose it immediately because C<T> is an unknown 6666 // specialization. The UsingShadowDecl in D<T> then points directly 6667 // to A::foo, which will look well-formed when we instantiate. 6668 // The right solution is to not collapse the shadow-decl chain. 6669 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 6670 DeclContext *OrigDC = Orig->getDeclContext(); 6671 6672 // Handle enums and anonymous structs. 6673 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 6674 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 6675 while (OrigRec->isAnonymousStructOrUnion()) 6676 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 6677 6678 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 6679 if (OrigDC == CurContext) { 6680 Diag(Using->getLocation(), 6681 diag::err_using_decl_nested_name_specifier_is_current_class) 6682 << Using->getQualifierLoc().getSourceRange(); 6683 Diag(Orig->getLocation(), diag::note_using_decl_target); 6684 return true; 6685 } 6686 6687 Diag(Using->getQualifierLoc().getBeginLoc(), 6688 diag::err_using_decl_nested_name_specifier_is_not_base_class) 6689 << Using->getQualifier() 6690 << cast<CXXRecordDecl>(CurContext) 6691 << Using->getQualifierLoc().getSourceRange(); 6692 Diag(Orig->getLocation(), diag::note_using_decl_target); 6693 return true; 6694 } 6695 } 6696 6697 if (Previous.empty()) return false; 6698 6699 NamedDecl *Target = Orig; 6700 if (isa<UsingShadowDecl>(Target)) 6701 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 6702 6703 // If the target happens to be one of the previous declarations, we 6704 // don't have a conflict. 6705 // 6706 // FIXME: but we might be increasing its access, in which case we 6707 // should redeclare it. 6708 NamedDecl *NonTag = 0, *Tag = 0; 6709 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 6710 I != E; ++I) { 6711 NamedDecl *D = (*I)->getUnderlyingDecl(); 6712 bool Result; 6713 if (IsEquivalentForUsingDecl(Context, D, Target, Result)) 6714 return Result; 6715 6716 (isa<TagDecl>(D) ? Tag : NonTag) = D; 6717 } 6718 6719 if (Target->isFunctionOrFunctionTemplate()) { 6720 FunctionDecl *FD; 6721 if (isa<FunctionTemplateDecl>(Target)) 6722 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl(); 6723 else 6724 FD = cast<FunctionDecl>(Target); 6725 6726 NamedDecl *OldDecl = 0; 6727 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) { 6728 case Ovl_Overload: 6729 return false; 6730 6731 case Ovl_NonFunction: 6732 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6733 break; 6734 6735 // We found a decl with the exact signature. 6736 case Ovl_Match: 6737 // If we're in a record, we want to hide the target, so we 6738 // return true (without a diagnostic) to tell the caller not to 6739 // build a shadow decl. 6740 if (CurContext->isRecord()) 6741 return true; 6742 6743 // If we're not in a record, this is an error. 6744 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6745 break; 6746 } 6747 6748 Diag(Target->getLocation(), diag::note_using_decl_target); 6749 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 6750 return true; 6751 } 6752 6753 // Target is not a function. 6754 6755 if (isa<TagDecl>(Target)) { 6756 // No conflict between a tag and a non-tag. 6757 if (!Tag) return false; 6758 6759 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6760 Diag(Target->getLocation(), diag::note_using_decl_target); 6761 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 6762 return true; 6763 } 6764 6765 // No conflict between a tag and a non-tag. 6766 if (!NonTag) return false; 6767 6768 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6769 Diag(Target->getLocation(), diag::note_using_decl_target); 6770 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 6771 return true; 6772} 6773 6774/// Builds a shadow declaration corresponding to a 'using' declaration. 6775UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 6776 UsingDecl *UD, 6777 NamedDecl *Orig) { 6778 6779 // If we resolved to another shadow declaration, just coalesce them. 6780 NamedDecl *Target = Orig; 6781 if (isa<UsingShadowDecl>(Target)) { 6782 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 6783 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 6784 } 6785 6786 UsingShadowDecl *Shadow 6787 = UsingShadowDecl::Create(Context, CurContext, 6788 UD->getLocation(), UD, Target); 6789 UD->addShadowDecl(Shadow); 6790 6791 Shadow->setAccess(UD->getAccess()); 6792 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 6793 Shadow->setInvalidDecl(); 6794 6795 if (S) 6796 PushOnScopeChains(Shadow, S); 6797 else 6798 CurContext->addDecl(Shadow); 6799 6800 6801 return Shadow; 6802} 6803 6804/// Hides a using shadow declaration. This is required by the current 6805/// using-decl implementation when a resolvable using declaration in a 6806/// class is followed by a declaration which would hide or override 6807/// one or more of the using decl's targets; for example: 6808/// 6809/// struct Base { void foo(int); }; 6810/// struct Derived : Base { 6811/// using Base::foo; 6812/// void foo(int); 6813/// }; 6814/// 6815/// The governing language is C++03 [namespace.udecl]p12: 6816/// 6817/// When a using-declaration brings names from a base class into a 6818/// derived class scope, member functions in the derived class 6819/// override and/or hide member functions with the same name and 6820/// parameter types in a base class (rather than conflicting). 6821/// 6822/// There are two ways to implement this: 6823/// (1) optimistically create shadow decls when they're not hidden 6824/// by existing declarations, or 6825/// (2) don't create any shadow decls (or at least don't make them 6826/// visible) until we've fully parsed/instantiated the class. 6827/// The problem with (1) is that we might have to retroactively remove 6828/// a shadow decl, which requires several O(n) operations because the 6829/// decl structures are (very reasonably) not designed for removal. 6830/// (2) avoids this but is very fiddly and phase-dependent. 6831void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 6832 if (Shadow->getDeclName().getNameKind() == 6833 DeclarationName::CXXConversionFunctionName) 6834 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 6835 6836 // Remove it from the DeclContext... 6837 Shadow->getDeclContext()->removeDecl(Shadow); 6838 6839 // ...and the scope, if applicable... 6840 if (S) { 6841 S->RemoveDecl(Shadow); 6842 IdResolver.RemoveDecl(Shadow); 6843 } 6844 6845 // ...and the using decl. 6846 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 6847 6848 // TODO: complain somehow if Shadow was used. It shouldn't 6849 // be possible for this to happen, because...? 6850} 6851 6852/// Builds a using declaration. 6853/// 6854/// \param IsInstantiation - Whether this call arises from an 6855/// instantiation of an unresolved using declaration. We treat 6856/// the lookup differently for these declarations. 6857NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 6858 SourceLocation UsingLoc, 6859 CXXScopeSpec &SS, 6860 const DeclarationNameInfo &NameInfo, 6861 AttributeList *AttrList, 6862 bool IsInstantiation, 6863 bool IsTypeName, 6864 SourceLocation TypenameLoc) { 6865 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 6866 SourceLocation IdentLoc = NameInfo.getLoc(); 6867 assert(IdentLoc.isValid() && "Invalid TargetName location."); 6868 6869 // FIXME: We ignore attributes for now. 6870 6871 if (SS.isEmpty()) { 6872 Diag(IdentLoc, diag::err_using_requires_qualname); 6873 return 0; 6874 } 6875 6876 // Do the redeclaration lookup in the current scope. 6877 LookupResult Previous(*this, NameInfo, LookupUsingDeclName, 6878 ForRedeclaration); 6879 Previous.setHideTags(false); 6880 if (S) { 6881 LookupName(Previous, S); 6882 6883 // It is really dumb that we have to do this. 6884 LookupResult::Filter F = Previous.makeFilter(); 6885 while (F.hasNext()) { 6886 NamedDecl *D = F.next(); 6887 if (!isDeclInScope(D, CurContext, S)) 6888 F.erase(); 6889 } 6890 F.done(); 6891 } else { 6892 assert(IsInstantiation && "no scope in non-instantiation"); 6893 assert(CurContext->isRecord() && "scope not record in instantiation"); 6894 LookupQualifiedName(Previous, CurContext); 6895 } 6896 6897 // Check for invalid redeclarations. 6898 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous)) 6899 return 0; 6900 6901 // Check for bad qualifiers. 6902 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc)) 6903 return 0; 6904 6905 DeclContext *LookupContext = computeDeclContext(SS); 6906 NamedDecl *D; 6907 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 6908 if (!LookupContext) { 6909 if (IsTypeName) { 6910 // FIXME: not all declaration name kinds are legal here 6911 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 6912 UsingLoc, TypenameLoc, 6913 QualifierLoc, 6914 IdentLoc, NameInfo.getName()); 6915 } else { 6916 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 6917 QualifierLoc, NameInfo); 6918 } 6919 } else { 6920 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 6921 NameInfo, IsTypeName); 6922 } 6923 D->setAccess(AS); 6924 CurContext->addDecl(D); 6925 6926 if (!LookupContext) return D; 6927 UsingDecl *UD = cast<UsingDecl>(D); 6928 6929 if (RequireCompleteDeclContext(SS, LookupContext)) { 6930 UD->setInvalidDecl(); 6931 return UD; 6932 } 6933 6934 // The normal rules do not apply to inheriting constructor declarations. 6935 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) { 6936 if (CheckInheritingConstructorUsingDecl(UD)) 6937 UD->setInvalidDecl(); 6938 return UD; 6939 } 6940 6941 // Otherwise, look up the target name. 6942 6943 LookupResult R(*this, NameInfo, LookupOrdinaryName); 6944 6945 // Unlike most lookups, we don't always want to hide tag 6946 // declarations: tag names are visible through the using declaration 6947 // even if hidden by ordinary names, *except* in a dependent context 6948 // where it's important for the sanity of two-phase lookup. 6949 if (!IsInstantiation) 6950 R.setHideTags(false); 6951 6952 // For the purposes of this lookup, we have a base object type 6953 // equal to that of the current context. 6954 if (CurContext->isRecord()) { 6955 R.setBaseObjectType( 6956 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 6957 } 6958 6959 LookupQualifiedName(R, LookupContext); 6960 6961 if (R.empty()) { 6962 Diag(IdentLoc, diag::err_no_member) 6963 << NameInfo.getName() << LookupContext << SS.getRange(); 6964 UD->setInvalidDecl(); 6965 return UD; 6966 } 6967 6968 if (R.isAmbiguous()) { 6969 UD->setInvalidDecl(); 6970 return UD; 6971 } 6972 6973 if (IsTypeName) { 6974 // If we asked for a typename and got a non-type decl, error out. 6975 if (!R.getAsSingle<TypeDecl>()) { 6976 Diag(IdentLoc, diag::err_using_typename_non_type); 6977 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 6978 Diag((*I)->getUnderlyingDecl()->getLocation(), 6979 diag::note_using_decl_target); 6980 UD->setInvalidDecl(); 6981 return UD; 6982 } 6983 } else { 6984 // If we asked for a non-typename and we got a type, error out, 6985 // but only if this is an instantiation of an unresolved using 6986 // decl. Otherwise just silently find the type name. 6987 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 6988 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 6989 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 6990 UD->setInvalidDecl(); 6991 return UD; 6992 } 6993 } 6994 6995 // C++0x N2914 [namespace.udecl]p6: 6996 // A using-declaration shall not name a namespace. 6997 if (R.getAsSingle<NamespaceDecl>()) { 6998 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 6999 << SS.getRange(); 7000 UD->setInvalidDecl(); 7001 return UD; 7002 } 7003 7004 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 7005 if (!CheckUsingShadowDecl(UD, *I, Previous)) 7006 BuildUsingShadowDecl(S, UD, *I); 7007 } 7008 7009 return UD; 7010} 7011 7012/// Additional checks for a using declaration referring to a constructor name. 7013bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 7014 assert(!UD->isTypeName() && "expecting a constructor name"); 7015 7016 const Type *SourceType = UD->getQualifier()->getAsType(); 7017 assert(SourceType && 7018 "Using decl naming constructor doesn't have type in scope spec."); 7019 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 7020 7021 // Check whether the named type is a direct base class. 7022 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified(); 7023 CXXRecordDecl::base_class_iterator BaseIt, BaseE; 7024 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end(); 7025 BaseIt != BaseE; ++BaseIt) { 7026 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified(); 7027 if (CanonicalSourceType == BaseType) 7028 break; 7029 if (BaseIt->getType()->isDependentType()) 7030 break; 7031 } 7032 7033 if (BaseIt == BaseE) { 7034 // Did not find SourceType in the bases. 7035 Diag(UD->getUsingLocation(), 7036 diag::err_using_decl_constructor_not_in_direct_base) 7037 << UD->getNameInfo().getSourceRange() 7038 << QualType(SourceType, 0) << TargetClass; 7039 return true; 7040 } 7041 7042 if (!CurContext->isDependentContext()) 7043 BaseIt->setInheritConstructors(); 7044 7045 return false; 7046} 7047 7048/// Checks that the given using declaration is not an invalid 7049/// redeclaration. Note that this is checking only for the using decl 7050/// itself, not for any ill-formedness among the UsingShadowDecls. 7051bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 7052 bool isTypeName, 7053 const CXXScopeSpec &SS, 7054 SourceLocation NameLoc, 7055 const LookupResult &Prev) { 7056 // C++03 [namespace.udecl]p8: 7057 // C++0x [namespace.udecl]p10: 7058 // A using-declaration is a declaration and can therefore be used 7059 // repeatedly where (and only where) multiple declarations are 7060 // allowed. 7061 // 7062 // That's in non-member contexts. 7063 if (!CurContext->getRedeclContext()->isRecord()) 7064 return false; 7065 7066 NestedNameSpecifier *Qual 7067 = static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 7068 7069 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 7070 NamedDecl *D = *I; 7071 7072 bool DTypename; 7073 NestedNameSpecifier *DQual; 7074 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 7075 DTypename = UD->isTypeName(); 7076 DQual = UD->getQualifier(); 7077 } else if (UnresolvedUsingValueDecl *UD 7078 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 7079 DTypename = false; 7080 DQual = UD->getQualifier(); 7081 } else if (UnresolvedUsingTypenameDecl *UD 7082 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 7083 DTypename = true; 7084 DQual = UD->getQualifier(); 7085 } else continue; 7086 7087 // using decls differ if one says 'typename' and the other doesn't. 7088 // FIXME: non-dependent using decls? 7089 if (isTypeName != DTypename) continue; 7090 7091 // using decls differ if they name different scopes (but note that 7092 // template instantiation can cause this check to trigger when it 7093 // didn't before instantiation). 7094 if (Context.getCanonicalNestedNameSpecifier(Qual) != 7095 Context.getCanonicalNestedNameSpecifier(DQual)) 7096 continue; 7097 7098 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 7099 Diag(D->getLocation(), diag::note_using_decl) << 1; 7100 return true; 7101 } 7102 7103 return false; 7104} 7105 7106 7107/// Checks that the given nested-name qualifier used in a using decl 7108/// in the current context is appropriately related to the current 7109/// scope. If an error is found, diagnoses it and returns true. 7110bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 7111 const CXXScopeSpec &SS, 7112 SourceLocation NameLoc) { 7113 DeclContext *NamedContext = computeDeclContext(SS); 7114 7115 if (!CurContext->isRecord()) { 7116 // C++03 [namespace.udecl]p3: 7117 // C++0x [namespace.udecl]p8: 7118 // A using-declaration for a class member shall be a member-declaration. 7119 7120 // If we weren't able to compute a valid scope, it must be a 7121 // dependent class scope. 7122 if (!NamedContext || NamedContext->isRecord()) { 7123 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 7124 << SS.getRange(); 7125 return true; 7126 } 7127 7128 // Otherwise, everything is known to be fine. 7129 return false; 7130 } 7131 7132 // The current scope is a record. 7133 7134 // If the named context is dependent, we can't decide much. 7135 if (!NamedContext) { 7136 // FIXME: in C++0x, we can diagnose if we can prove that the 7137 // nested-name-specifier does not refer to a base class, which is 7138 // still possible in some cases. 7139 7140 // Otherwise we have to conservatively report that things might be 7141 // okay. 7142 return false; 7143 } 7144 7145 if (!NamedContext->isRecord()) { 7146 // Ideally this would point at the last name in the specifier, 7147 // but we don't have that level of source info. 7148 Diag(SS.getRange().getBegin(), 7149 diag::err_using_decl_nested_name_specifier_is_not_class) 7150 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange(); 7151 return true; 7152 } 7153 7154 if (!NamedContext->isDependentContext() && 7155 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 7156 return true; 7157 7158 if (getLangOpts().CPlusPlus11) { 7159 // C++0x [namespace.udecl]p3: 7160 // In a using-declaration used as a member-declaration, the 7161 // nested-name-specifier shall name a base class of the class 7162 // being defined. 7163 7164 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 7165 cast<CXXRecordDecl>(NamedContext))) { 7166 if (CurContext == NamedContext) { 7167 Diag(NameLoc, 7168 diag::err_using_decl_nested_name_specifier_is_current_class) 7169 << SS.getRange(); 7170 return true; 7171 } 7172 7173 Diag(SS.getRange().getBegin(), 7174 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7175 << (NestedNameSpecifier*) SS.getScopeRep() 7176 << cast<CXXRecordDecl>(CurContext) 7177 << SS.getRange(); 7178 return true; 7179 } 7180 7181 return false; 7182 } 7183 7184 // C++03 [namespace.udecl]p4: 7185 // A using-declaration used as a member-declaration shall refer 7186 // to a member of a base class of the class being defined [etc.]. 7187 7188 // Salient point: SS doesn't have to name a base class as long as 7189 // lookup only finds members from base classes. Therefore we can 7190 // diagnose here only if we can prove that that can't happen, 7191 // i.e. if the class hierarchies provably don't intersect. 7192 7193 // TODO: it would be nice if "definitely valid" results were cached 7194 // in the UsingDecl and UsingShadowDecl so that these checks didn't 7195 // need to be repeated. 7196 7197 struct UserData { 7198 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases; 7199 7200 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) { 7201 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 7202 Data->Bases.insert(Base); 7203 return true; 7204 } 7205 7206 bool hasDependentBases(const CXXRecordDecl *Class) { 7207 return !Class->forallBases(collect, this); 7208 } 7209 7210 /// Returns true if the base is dependent or is one of the 7211 /// accumulated base classes. 7212 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) { 7213 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 7214 return !Data->Bases.count(Base); 7215 } 7216 7217 bool mightShareBases(const CXXRecordDecl *Class) { 7218 return Bases.count(Class) || !Class->forallBases(doesNotContain, this); 7219 } 7220 }; 7221 7222 UserData Data; 7223 7224 // Returns false if we find a dependent base. 7225 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext))) 7226 return false; 7227 7228 // Returns false if the class has a dependent base or if it or one 7229 // of its bases is present in the base set of the current context. 7230 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext))) 7231 return false; 7232 7233 Diag(SS.getRange().getBegin(), 7234 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7235 << (NestedNameSpecifier*) SS.getScopeRep() 7236 << cast<CXXRecordDecl>(CurContext) 7237 << SS.getRange(); 7238 7239 return true; 7240} 7241 7242Decl *Sema::ActOnAliasDeclaration(Scope *S, 7243 AccessSpecifier AS, 7244 MultiTemplateParamsArg TemplateParamLists, 7245 SourceLocation UsingLoc, 7246 UnqualifiedId &Name, 7247 AttributeList *AttrList, 7248 TypeResult Type) { 7249 // Skip up to the relevant declaration scope. 7250 while (S->getFlags() & Scope::TemplateParamScope) 7251 S = S->getParent(); 7252 assert((S->getFlags() & Scope::DeclScope) && 7253 "got alias-declaration outside of declaration scope"); 7254 7255 if (Type.isInvalid()) 7256 return 0; 7257 7258 bool Invalid = false; 7259 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 7260 TypeSourceInfo *TInfo = 0; 7261 GetTypeFromParser(Type.get(), &TInfo); 7262 7263 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 7264 return 0; 7265 7266 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 7267 UPPC_DeclarationType)) { 7268 Invalid = true; 7269 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 7270 TInfo->getTypeLoc().getBeginLoc()); 7271 } 7272 7273 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration); 7274 LookupName(Previous, S); 7275 7276 // Warn about shadowing the name of a template parameter. 7277 if (Previous.isSingleResult() && 7278 Previous.getFoundDecl()->isTemplateParameter()) { 7279 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 7280 Previous.clear(); 7281 } 7282 7283 assert(Name.Kind == UnqualifiedId::IK_Identifier && 7284 "name in alias declaration must be an identifier"); 7285 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 7286 Name.StartLocation, 7287 Name.Identifier, TInfo); 7288 7289 NewTD->setAccess(AS); 7290 7291 if (Invalid) 7292 NewTD->setInvalidDecl(); 7293 7294 ProcessDeclAttributeList(S, NewTD, AttrList); 7295 7296 CheckTypedefForVariablyModifiedType(S, NewTD); 7297 Invalid |= NewTD->isInvalidDecl(); 7298 7299 bool Redeclaration = false; 7300 7301 NamedDecl *NewND; 7302 if (TemplateParamLists.size()) { 7303 TypeAliasTemplateDecl *OldDecl = 0; 7304 TemplateParameterList *OldTemplateParams = 0; 7305 7306 if (TemplateParamLists.size() != 1) { 7307 Diag(UsingLoc, diag::err_alias_template_extra_headers) 7308 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 7309 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 7310 } 7311 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 7312 7313 // Only consider previous declarations in the same scope. 7314 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 7315 /*ExplicitInstantiationOrSpecialization*/false); 7316 if (!Previous.empty()) { 7317 Redeclaration = true; 7318 7319 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 7320 if (!OldDecl && !Invalid) { 7321 Diag(UsingLoc, diag::err_redefinition_different_kind) 7322 << Name.Identifier; 7323 7324 NamedDecl *OldD = Previous.getRepresentativeDecl(); 7325 if (OldD->getLocation().isValid()) 7326 Diag(OldD->getLocation(), diag::note_previous_definition); 7327 7328 Invalid = true; 7329 } 7330 7331 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 7332 if (TemplateParameterListsAreEqual(TemplateParams, 7333 OldDecl->getTemplateParameters(), 7334 /*Complain=*/true, 7335 TPL_TemplateMatch)) 7336 OldTemplateParams = OldDecl->getTemplateParameters(); 7337 else 7338 Invalid = true; 7339 7340 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 7341 if (!Invalid && 7342 !Context.hasSameType(OldTD->getUnderlyingType(), 7343 NewTD->getUnderlyingType())) { 7344 // FIXME: The C++0x standard does not clearly say this is ill-formed, 7345 // but we can't reasonably accept it. 7346 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 7347 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 7348 if (OldTD->getLocation().isValid()) 7349 Diag(OldTD->getLocation(), diag::note_previous_definition); 7350 Invalid = true; 7351 } 7352 } 7353 } 7354 7355 // Merge any previous default template arguments into our parameters, 7356 // and check the parameter list. 7357 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 7358 TPC_TypeAliasTemplate)) 7359 return 0; 7360 7361 TypeAliasTemplateDecl *NewDecl = 7362 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 7363 Name.Identifier, TemplateParams, 7364 NewTD); 7365 7366 NewDecl->setAccess(AS); 7367 7368 if (Invalid) 7369 NewDecl->setInvalidDecl(); 7370 else if (OldDecl) 7371 NewDecl->setPreviousDeclaration(OldDecl); 7372 7373 NewND = NewDecl; 7374 } else { 7375 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 7376 NewND = NewTD; 7377 } 7378 7379 if (!Redeclaration) 7380 PushOnScopeChains(NewND, S); 7381 7382 ActOnDocumentableDecl(NewND); 7383 return NewND; 7384} 7385 7386Decl *Sema::ActOnNamespaceAliasDef(Scope *S, 7387 SourceLocation NamespaceLoc, 7388 SourceLocation AliasLoc, 7389 IdentifierInfo *Alias, 7390 CXXScopeSpec &SS, 7391 SourceLocation IdentLoc, 7392 IdentifierInfo *Ident) { 7393 7394 // Lookup the namespace name. 7395 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 7396 LookupParsedName(R, S, &SS); 7397 7398 // Check if we have a previous declaration with the same name. 7399 NamedDecl *PrevDecl 7400 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName, 7401 ForRedeclaration); 7402 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S)) 7403 PrevDecl = 0; 7404 7405 if (PrevDecl) { 7406 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 7407 // We already have an alias with the same name that points to the same 7408 // namespace, so don't create a new one. 7409 // FIXME: At some point, we'll want to create the (redundant) 7410 // declaration to maintain better source information. 7411 if (!R.isAmbiguous() && !R.empty() && 7412 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl()))) 7413 return 0; 7414 } 7415 7416 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition : 7417 diag::err_redefinition_different_kind; 7418 Diag(AliasLoc, DiagID) << Alias; 7419 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 7420 return 0; 7421 } 7422 7423 if (R.isAmbiguous()) 7424 return 0; 7425 7426 if (R.empty()) { 7427 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 7428 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 7429 return 0; 7430 } 7431 } 7432 7433 NamespaceAliasDecl *AliasDecl = 7434 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 7435 Alias, SS.getWithLocInContext(Context), 7436 IdentLoc, R.getFoundDecl()); 7437 7438 PushOnScopeChains(AliasDecl, S); 7439 return AliasDecl; 7440} 7441 7442Sema::ImplicitExceptionSpecification 7443Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, 7444 CXXMethodDecl *MD) { 7445 CXXRecordDecl *ClassDecl = MD->getParent(); 7446 7447 // C++ [except.spec]p14: 7448 // An implicitly declared special member function (Clause 12) shall have an 7449 // exception-specification. [...] 7450 ImplicitExceptionSpecification ExceptSpec(*this); 7451 if (ClassDecl->isInvalidDecl()) 7452 return ExceptSpec; 7453 7454 // Direct base-class constructors. 7455 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 7456 BEnd = ClassDecl->bases_end(); 7457 B != BEnd; ++B) { 7458 if (B->isVirtual()) // Handled below. 7459 continue; 7460 7461 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 7462 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7463 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 7464 // If this is a deleted function, add it anyway. This might be conformant 7465 // with the standard. This might not. I'm not sure. It might not matter. 7466 if (Constructor) 7467 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 7468 } 7469 } 7470 7471 // Virtual base-class constructors. 7472 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 7473 BEnd = ClassDecl->vbases_end(); 7474 B != BEnd; ++B) { 7475 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 7476 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7477 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 7478 // If this is a deleted function, add it anyway. This might be conformant 7479 // with the standard. This might not. I'm not sure. It might not matter. 7480 if (Constructor) 7481 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 7482 } 7483 } 7484 7485 // Field constructors. 7486 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 7487 FEnd = ClassDecl->field_end(); 7488 F != FEnd; ++F) { 7489 if (F->hasInClassInitializer()) { 7490 if (Expr *E = F->getInClassInitializer()) 7491 ExceptSpec.CalledExpr(E); 7492 else if (!F->isInvalidDecl()) 7493 // DR1351: 7494 // If the brace-or-equal-initializer of a non-static data member 7495 // invokes a defaulted default constructor of its class or of an 7496 // enclosing class in a potentially evaluated subexpression, the 7497 // program is ill-formed. 7498 // 7499 // This resolution is unworkable: the exception specification of the 7500 // default constructor can be needed in an unevaluated context, in 7501 // particular, in the operand of a noexcept-expression, and we can be 7502 // unable to compute an exception specification for an enclosed class. 7503 // 7504 // We do not allow an in-class initializer to require the evaluation 7505 // of the exception specification for any in-class initializer whose 7506 // definition is not lexically complete. 7507 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD; 7508 } else if (const RecordType *RecordTy 7509 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 7510 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 7511 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 7512 // If this is a deleted function, add it anyway. This might be conformant 7513 // with the standard. This might not. I'm not sure. It might not matter. 7514 // In particular, the problem is that this function never gets called. It 7515 // might just be ill-formed because this function attempts to refer to 7516 // a deleted function here. 7517 if (Constructor) 7518 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 7519 } 7520 } 7521 7522 return ExceptSpec; 7523} 7524 7525Sema::ImplicitExceptionSpecification 7526Sema::ComputeInheritingCtorExceptionSpec(CXXMethodDecl *MD) { 7527 ImplicitExceptionSpecification ExceptSpec(*this); 7528 // FIXME: Compute the exception spec. 7529 return ExceptSpec; 7530} 7531 7532namespace { 7533/// RAII object to register a special member as being currently declared. 7534struct DeclaringSpecialMember { 7535 Sema &S; 7536 Sema::SpecialMemberDecl D; 7537 bool WasAlreadyBeingDeclared; 7538 7539 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 7540 : S(S), D(RD, CSM) { 7541 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D); 7542 if (WasAlreadyBeingDeclared) 7543 // This almost never happens, but if it does, ensure that our cache 7544 // doesn't contain a stale result. 7545 S.SpecialMemberCache.clear(); 7546 7547 // FIXME: Register a note to be produced if we encounter an error while 7548 // declaring the special member. 7549 } 7550 ~DeclaringSpecialMember() { 7551 if (!WasAlreadyBeingDeclared) 7552 S.SpecialMembersBeingDeclared.erase(D); 7553 } 7554 7555 /// \brief Are we already trying to declare this special member? 7556 bool isAlreadyBeingDeclared() const { 7557 return WasAlreadyBeingDeclared; 7558 } 7559}; 7560} 7561 7562CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 7563 CXXRecordDecl *ClassDecl) { 7564 // C++ [class.ctor]p5: 7565 // A default constructor for a class X is a constructor of class X 7566 // that can be called without an argument. If there is no 7567 // user-declared constructor for class X, a default constructor is 7568 // implicitly declared. An implicitly-declared default constructor 7569 // is an inline public member of its class. 7570 assert(ClassDecl->needsImplicitDefaultConstructor() && 7571 "Should not build implicit default constructor!"); 7572 7573 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 7574 if (DSM.isAlreadyBeingDeclared()) 7575 return 0; 7576 7577 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 7578 CXXDefaultConstructor, 7579 false); 7580 7581 // Create the actual constructor declaration. 7582 CanQualType ClassType 7583 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 7584 SourceLocation ClassLoc = ClassDecl->getLocation(); 7585 DeclarationName Name 7586 = Context.DeclarationNames.getCXXConstructorName(ClassType); 7587 DeclarationNameInfo NameInfo(Name, ClassLoc); 7588 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 7589 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0, 7590 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 7591 Constexpr); 7592 DefaultCon->setAccess(AS_public); 7593 DefaultCon->setDefaulted(); 7594 DefaultCon->setImplicit(); 7595 7596 // Build an exception specification pointing back at this constructor. 7597 FunctionProtoType::ExtProtoInfo EPI; 7598 EPI.ExceptionSpecType = EST_Unevaluated; 7599 EPI.ExceptionSpecDecl = DefaultCon; 7600 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, 7601 ArrayRef<QualType>(), 7602 EPI)); 7603 7604 // We don't need to use SpecialMemberIsTrivial here; triviality for default 7605 // constructors is easy to compute. 7606 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 7607 7608 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 7609 SetDeclDeleted(DefaultCon, ClassLoc); 7610 7611 // Note that we have declared this constructor. 7612 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 7613 7614 if (Scope *S = getScopeForContext(ClassDecl)) 7615 PushOnScopeChains(DefaultCon, S, false); 7616 ClassDecl->addDecl(DefaultCon); 7617 7618 return DefaultCon; 7619} 7620 7621void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 7622 CXXConstructorDecl *Constructor) { 7623 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 7624 !Constructor->doesThisDeclarationHaveABody() && 7625 !Constructor->isDeleted()) && 7626 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 7627 7628 CXXRecordDecl *ClassDecl = Constructor->getParent(); 7629 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 7630 7631 SynthesizedFunctionScope Scope(*this, Constructor); 7632 DiagnosticErrorTrap Trap(Diags); 7633 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 7634 Trap.hasErrorOccurred()) { 7635 Diag(CurrentLocation, diag::note_member_synthesized_at) 7636 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl); 7637 Constructor->setInvalidDecl(); 7638 return; 7639 } 7640 7641 SourceLocation Loc = Constructor->getLocation(); 7642 Constructor->setBody(new (Context) CompoundStmt(Loc)); 7643 7644 Constructor->setUsed(); 7645 MarkVTableUsed(CurrentLocation, ClassDecl); 7646 7647 if (ASTMutationListener *L = getASTMutationListener()) { 7648 L->CompletedImplicitDefinition(Constructor); 7649 } 7650} 7651 7652void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 7653 // Check that any explicitly-defaulted methods have exception specifications 7654 // compatible with their implicit exception specifications. 7655 CheckDelayedExplicitlyDefaultedMemberExceptionSpecs(); 7656} 7657 7658void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) { 7659 // We start with an initial pass over the base classes to collect those that 7660 // inherit constructors from. If there are none, we can forgo all further 7661 // processing. 7662 typedef SmallVector<const RecordType *, 4> BasesVector; 7663 BasesVector BasesToInheritFrom; 7664 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(), 7665 BaseE = ClassDecl->bases_end(); 7666 BaseIt != BaseE; ++BaseIt) { 7667 if (BaseIt->getInheritConstructors()) { 7668 QualType Base = BaseIt->getType(); 7669 if (Base->isDependentType()) { 7670 // If we inherit constructors from anything that is dependent, just 7671 // abort processing altogether. We'll get another chance for the 7672 // instantiations. 7673 // FIXME: We need to ensure that any call to a constructor of this class 7674 // is considered instantiation-dependent in this case. 7675 return; 7676 } 7677 BasesToInheritFrom.push_back(Base->castAs<RecordType>()); 7678 } 7679 } 7680 if (BasesToInheritFrom.empty()) 7681 return; 7682 7683 // FIXME: Constructor templates. 7684 7685 // Now collect the constructors that we already have in the current class. 7686 // Those take precedence over inherited constructors. 7687 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...] 7688 // unless there is a user-declared constructor with the same signature in 7689 // the class where the using-declaration appears. 7690 llvm::SmallSet<const Type *, 8> ExistingConstructors; 7691 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(), 7692 CtorE = ClassDecl->ctor_end(); 7693 CtorIt != CtorE; ++CtorIt) 7694 ExistingConstructors.insert( 7695 Context.getCanonicalType(CtorIt->getType()).getTypePtr()); 7696 7697 DeclarationName CreatedCtorName = 7698 Context.DeclarationNames.getCXXConstructorName( 7699 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified()); 7700 7701 // Now comes the true work. 7702 // First, we keep a map from constructor types to the base that introduced 7703 // them. Needed for finding conflicting constructors. We also keep the 7704 // actually inserted declarations in there, for pretty diagnostics. 7705 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo; 7706 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap; 7707 ConstructorToSourceMap InheritedConstructors; 7708 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(), 7709 BaseE = BasesToInheritFrom.end(); 7710 BaseIt != BaseE; ++BaseIt) { 7711 const RecordType *Base = *BaseIt; 7712 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified(); 7713 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl()); 7714 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(), 7715 CtorE = BaseDecl->ctor_end(); 7716 CtorIt != CtorE; ++CtorIt) { 7717 // Find the using declaration for inheriting this base's constructors. 7718 // FIXME: Don't perform name lookup just to obtain a source location! 7719 DeclarationName Name = 7720 Context.DeclarationNames.getCXXConstructorName(CanonicalBase); 7721 LookupResult Result(*this, Name, SourceLocation(), LookupUsingDeclName); 7722 LookupQualifiedName(Result, CurContext); 7723 UsingDecl *UD = Result.getAsSingle<UsingDecl>(); 7724 SourceLocation UsingLoc = UD ? UD->getLocation() : 7725 ClassDecl->getLocation(); 7726 7727 // C++11 [class.inhctor]p1: 7728 // The candidate set of inherited constructors from the class X named in 7729 // the using-declaration consists of actual constructors and notional 7730 // constructors that result from the transformation of defaulted 7731 // parameters as follows: 7732 // - all non-template constructors of X, and 7733 // - for each non-template constructor of X that has at least one 7734 // parameter with a default argument, the set of constructors that 7735 // results from omitting any ellipsis parameter specification and 7736 // successively omitting parameters with a default argument from the 7737 // end of the parameter-type-list, and 7738 // FIXME: ...also constructor templates. 7739 CXXConstructorDecl *BaseCtor = *CtorIt; 7740 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor(); 7741 const FunctionProtoType *BaseCtorType = 7742 BaseCtor->getType()->getAs<FunctionProtoType>(); 7743 7744 // Determine whether this would be a copy or move constructor for the 7745 // derived class. 7746 if (BaseCtorType->getNumArgs() >= 1 && 7747 BaseCtorType->getArgType(0)->isReferenceType() && 7748 Context.hasSameUnqualifiedType( 7749 BaseCtorType->getArgType(0)->getPointeeType(), 7750 Context.getTagDeclType(ClassDecl))) 7751 CanBeCopyOrMove = true; 7752 7753 ArrayRef<QualType> ArgTypes(BaseCtorType->getArgTypes()); 7754 FunctionProtoType::ExtProtoInfo EPI = BaseCtorType->getExtProtoInfo(); 7755 // Core issue (no number yet): the ellipsis is always discarded. 7756 if (EPI.Variadic) { 7757 Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis); 7758 Diag(BaseCtor->getLocation(), 7759 diag::note_using_decl_constructor_ellipsis); 7760 EPI.Variadic = false; 7761 } 7762 7763 for (unsigned Params = BaseCtor->getMinRequiredArguments(), 7764 MaxParams = BaseCtor->getNumParams(); 7765 Params <= MaxParams; ++Params) { 7766 // Skip default constructors. They're never inherited. 7767 if (Params == 0) 7768 continue; 7769 7770 // Skip copy and move constructors for both base and derived class 7771 // for the same reason. 7772 if (CanBeCopyOrMove && Params == 1) 7773 continue; 7774 7775 // Build up a function type for this particular constructor. 7776 QualType NewCtorType = 7777 Context.getFunctionType(Context.VoidTy, ArgTypes.slice(0, Params), 7778 EPI); 7779 const Type *CanonicalNewCtorType = 7780 Context.getCanonicalType(NewCtorType).getTypePtr(); 7781 7782 // C++11 [class.inhctor]p3: 7783 // ... a constructor is implicitly declared with the same constructor 7784 // characteristics unless there is a user-declared constructor with 7785 // the same signature in the class where the using-declaration appears 7786 if (ExistingConstructors.count(CanonicalNewCtorType)) 7787 continue; 7788 7789 // C++11 [class.inhctor]p7: 7790 // If two using-declarations declare inheriting constructors with the 7791 // same signature, the program is ill-formed 7792 std::pair<ConstructorToSourceMap::iterator, bool> result = 7793 InheritedConstructors.insert(std::make_pair( 7794 CanonicalNewCtorType, 7795 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0))); 7796 if (!result.second) { 7797 // Already in the map. If it came from a different class, that's an 7798 // error. Not if it's from the same. 7799 CanQualType PreviousBase = result.first->second.first; 7800 if (CanonicalBase != PreviousBase) { 7801 const CXXConstructorDecl *PrevCtor = result.first->second.second; 7802 const CXXConstructorDecl *PrevBaseCtor = 7803 PrevCtor->getInheritedConstructor(); 7804 assert(PrevBaseCtor && "Conflicting constructor was not inherited"); 7805 7806 Diag(UsingLoc, diag::err_using_decl_constructor_conflict); 7807 Diag(BaseCtor->getLocation(), 7808 diag::note_using_decl_constructor_conflict_current_ctor); 7809 Diag(PrevBaseCtor->getLocation(), 7810 diag::note_using_decl_constructor_conflict_previous_ctor); 7811 Diag(PrevCtor->getLocation(), 7812 diag::note_using_decl_constructor_conflict_previous_using); 7813 } else { 7814 // Core issue (no number): if the same inheriting constructor is 7815 // produced by multiple base class constructors from the same base 7816 // class, the inheriting constructor is defined as deleted. 7817 SetDeclDeleted(result.first->second.second, UsingLoc); 7818 } 7819 continue; 7820 } 7821 7822 // OK, we're there, now add the constructor. 7823 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc); 7824 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create( 7825 Context, ClassDecl, UsingLoc, DNI, NewCtorType, 7826 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true, 7827 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr()); 7828 NewCtor->setAccess(BaseCtor->getAccess()); 7829 7830 // Build an unevaluated exception specification for this constructor. 7831 EPI.ExceptionSpecType = EST_Unevaluated; 7832 EPI.ExceptionSpecDecl = NewCtor; 7833 NewCtor->setType(Context.getFunctionType(Context.VoidTy, 7834 ArgTypes.slice(0, Params), 7835 EPI)); 7836 7837 // Build up the parameter decls and add them. 7838 SmallVector<ParmVarDecl *, 16> ParamDecls; 7839 for (unsigned i = 0; i < Params; ++i) { 7840 ParmVarDecl *PD = ParmVarDecl::Create(Context, NewCtor, 7841 UsingLoc, UsingLoc, 7842 /*IdentifierInfo=*/0, 7843 BaseCtorType->getArgType(i), 7844 /*TInfo=*/0, SC_None, 7845 /*DefaultArg=*/0); 7846 PD->setScopeInfo(0, i); 7847 PD->setImplicit(); 7848 ParamDecls.push_back(PD); 7849 } 7850 NewCtor->setParams(ParamDecls); 7851 NewCtor->setInheritedConstructor(BaseCtor); 7852 if (BaseCtor->isDeleted()) 7853 SetDeclDeleted(NewCtor, UsingLoc); 7854 7855 ClassDecl->addDecl(NewCtor); 7856 result.first->second.second = NewCtor; 7857 } 7858 } 7859 } 7860} 7861 7862void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 7863 CXXConstructorDecl *Constructor) { 7864 CXXRecordDecl *ClassDecl = Constructor->getParent(); 7865 assert(Constructor->getInheritedConstructor() && 7866 !Constructor->doesThisDeclarationHaveABody() && 7867 !Constructor->isDeleted()); 7868 7869 SynthesizedFunctionScope Scope(*this, Constructor); 7870 DiagnosticErrorTrap Trap(Diags); 7871 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 7872 Trap.hasErrorOccurred()) { 7873 Diag(CurrentLocation, diag::note_inhctor_synthesized_at) 7874 << Context.getTagDeclType(ClassDecl); 7875 Constructor->setInvalidDecl(); 7876 return; 7877 } 7878 7879 SourceLocation Loc = Constructor->getLocation(); 7880 Constructor->setBody(new (Context) CompoundStmt(Loc)); 7881 7882 Constructor->setUsed(); 7883 MarkVTableUsed(CurrentLocation, ClassDecl); 7884 7885 if (ASTMutationListener *L = getASTMutationListener()) { 7886 L->CompletedImplicitDefinition(Constructor); 7887 } 7888} 7889 7890 7891Sema::ImplicitExceptionSpecification 7892Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) { 7893 CXXRecordDecl *ClassDecl = MD->getParent(); 7894 7895 // C++ [except.spec]p14: 7896 // An implicitly declared special member function (Clause 12) shall have 7897 // an exception-specification. 7898 ImplicitExceptionSpecification ExceptSpec(*this); 7899 if (ClassDecl->isInvalidDecl()) 7900 return ExceptSpec; 7901 7902 // Direct base-class destructors. 7903 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 7904 BEnd = ClassDecl->bases_end(); 7905 B != BEnd; ++B) { 7906 if (B->isVirtual()) // Handled below. 7907 continue; 7908 7909 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) 7910 ExceptSpec.CalledDecl(B->getLocStart(), 7911 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 7912 } 7913 7914 // Virtual base-class destructors. 7915 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 7916 BEnd = ClassDecl->vbases_end(); 7917 B != BEnd; ++B) { 7918 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) 7919 ExceptSpec.CalledDecl(B->getLocStart(), 7920 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 7921 } 7922 7923 // Field destructors. 7924 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 7925 FEnd = ClassDecl->field_end(); 7926 F != FEnd; ++F) { 7927 if (const RecordType *RecordTy 7928 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) 7929 ExceptSpec.CalledDecl(F->getLocation(), 7930 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl()))); 7931 } 7932 7933 return ExceptSpec; 7934} 7935 7936CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 7937 // C++ [class.dtor]p2: 7938 // If a class has no user-declared destructor, a destructor is 7939 // declared implicitly. An implicitly-declared destructor is an 7940 // inline public member of its class. 7941 assert(ClassDecl->needsImplicitDestructor()); 7942 7943 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 7944 if (DSM.isAlreadyBeingDeclared()) 7945 return 0; 7946 7947 // Create the actual destructor declaration. 7948 CanQualType ClassType 7949 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 7950 SourceLocation ClassLoc = ClassDecl->getLocation(); 7951 DeclarationName Name 7952 = Context.DeclarationNames.getCXXDestructorName(ClassType); 7953 DeclarationNameInfo NameInfo(Name, ClassLoc); 7954 CXXDestructorDecl *Destructor 7955 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 7956 QualType(), 0, /*isInline=*/true, 7957 /*isImplicitlyDeclared=*/true); 7958 Destructor->setAccess(AS_public); 7959 Destructor->setDefaulted(); 7960 Destructor->setImplicit(); 7961 7962 // Build an exception specification pointing back at this destructor. 7963 FunctionProtoType::ExtProtoInfo EPI; 7964 EPI.ExceptionSpecType = EST_Unevaluated; 7965 EPI.ExceptionSpecDecl = Destructor; 7966 Destructor->setType(Context.getFunctionType(Context.VoidTy, 7967 ArrayRef<QualType>(), 7968 EPI)); 7969 7970 AddOverriddenMethods(ClassDecl, Destructor); 7971 7972 // We don't need to use SpecialMemberIsTrivial here; triviality for 7973 // destructors is easy to compute. 7974 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 7975 7976 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 7977 SetDeclDeleted(Destructor, ClassLoc); 7978 7979 // Note that we have declared this destructor. 7980 ++ASTContext::NumImplicitDestructorsDeclared; 7981 7982 // Introduce this destructor into its scope. 7983 if (Scope *S = getScopeForContext(ClassDecl)) 7984 PushOnScopeChains(Destructor, S, false); 7985 ClassDecl->addDecl(Destructor); 7986 7987 return Destructor; 7988} 7989 7990void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 7991 CXXDestructorDecl *Destructor) { 7992 assert((Destructor->isDefaulted() && 7993 !Destructor->doesThisDeclarationHaveABody() && 7994 !Destructor->isDeleted()) && 7995 "DefineImplicitDestructor - call it for implicit default dtor"); 7996 CXXRecordDecl *ClassDecl = Destructor->getParent(); 7997 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 7998 7999 if (Destructor->isInvalidDecl()) 8000 return; 8001 8002 SynthesizedFunctionScope Scope(*this, Destructor); 8003 8004 DiagnosticErrorTrap Trap(Diags); 8005 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 8006 Destructor->getParent()); 8007 8008 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) { 8009 Diag(CurrentLocation, diag::note_member_synthesized_at) 8010 << CXXDestructor << Context.getTagDeclType(ClassDecl); 8011 8012 Destructor->setInvalidDecl(); 8013 return; 8014 } 8015 8016 SourceLocation Loc = Destructor->getLocation(); 8017 Destructor->setBody(new (Context) CompoundStmt(Loc)); 8018 Destructor->setImplicitlyDefined(true); 8019 Destructor->setUsed(); 8020 MarkVTableUsed(CurrentLocation, ClassDecl); 8021 8022 if (ASTMutationListener *L = getASTMutationListener()) { 8023 L->CompletedImplicitDefinition(Destructor); 8024 } 8025} 8026 8027/// \brief Perform any semantic analysis which needs to be delayed until all 8028/// pending class member declarations have been parsed. 8029void Sema::ActOnFinishCXXMemberDecls() { 8030 // If the context is an invalid C++ class, just suppress these checks. 8031 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 8032 if (Record->isInvalidDecl()) { 8033 DelayedDestructorExceptionSpecChecks.clear(); 8034 return; 8035 } 8036 } 8037 8038 // Perform any deferred checking of exception specifications for virtual 8039 // destructors. 8040 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size(); 8041 i != e; ++i) { 8042 const CXXDestructorDecl *Dtor = 8043 DelayedDestructorExceptionSpecChecks[i].first; 8044 assert(!Dtor->getParent()->isDependentType() && 8045 "Should not ever add destructors of templates into the list."); 8046 CheckOverridingFunctionExceptionSpec(Dtor, 8047 DelayedDestructorExceptionSpecChecks[i].second); 8048 } 8049 DelayedDestructorExceptionSpecChecks.clear(); 8050} 8051 8052void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 8053 CXXDestructorDecl *Destructor) { 8054 assert(getLangOpts().CPlusPlus11 && 8055 "adjusting dtor exception specs was introduced in c++11"); 8056 8057 // C++11 [class.dtor]p3: 8058 // A declaration of a destructor that does not have an exception- 8059 // specification is implicitly considered to have the same exception- 8060 // specification as an implicit declaration. 8061 const FunctionProtoType *DtorType = Destructor->getType()-> 8062 getAs<FunctionProtoType>(); 8063 if (DtorType->hasExceptionSpec()) 8064 return; 8065 8066 // Replace the destructor's type, building off the existing one. Fortunately, 8067 // the only thing of interest in the destructor type is its extended info. 8068 // The return and arguments are fixed. 8069 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 8070 EPI.ExceptionSpecType = EST_Unevaluated; 8071 EPI.ExceptionSpecDecl = Destructor; 8072 Destructor->setType(Context.getFunctionType(Context.VoidTy, 8073 ArrayRef<QualType>(), 8074 EPI)); 8075 8076 // FIXME: If the destructor has a body that could throw, and the newly created 8077 // spec doesn't allow exceptions, we should emit a warning, because this 8078 // change in behavior can break conforming C++03 programs at runtime. 8079 // However, we don't have a body or an exception specification yet, so it 8080 // needs to be done somewhere else. 8081} 8082 8083/// When generating a defaulted copy or move assignment operator, if a field 8084/// should be copied with __builtin_memcpy rather than via explicit assignments, 8085/// do so. This optimization only applies for arrays of scalars, and for arrays 8086/// of class type where the selected copy/move-assignment operator is trivial. 8087static StmtResult 8088buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 8089 Expr *To, Expr *From) { 8090 // Compute the size of the memory buffer to be copied. 8091 QualType SizeType = S.Context.getSizeType(); 8092 llvm::APInt Size(S.Context.getTypeSize(SizeType), 8093 S.Context.getTypeSizeInChars(T).getQuantity()); 8094 8095 // Take the address of the field references for "from" and "to". We 8096 // directly construct UnaryOperators here because semantic analysis 8097 // does not permit us to take the address of an xvalue. 8098 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 8099 S.Context.getPointerType(From->getType()), 8100 VK_RValue, OK_Ordinary, Loc); 8101 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 8102 S.Context.getPointerType(To->getType()), 8103 VK_RValue, OK_Ordinary, Loc); 8104 8105 const Type *E = T->getBaseElementTypeUnsafe(); 8106 bool NeedsCollectableMemCpy = 8107 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 8108 8109 // Create a reference to the __builtin_objc_memmove_collectable function 8110 StringRef MemCpyName = NeedsCollectableMemCpy ? 8111 "__builtin_objc_memmove_collectable" : 8112 "__builtin_memcpy"; 8113 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 8114 Sema::LookupOrdinaryName); 8115 S.LookupName(R, S.TUScope, true); 8116 8117 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 8118 if (!MemCpy) 8119 // Something went horribly wrong earlier, and we will have complained 8120 // about it. 8121 return StmtError(); 8122 8123 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 8124 VK_RValue, Loc, 0); 8125 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 8126 8127 Expr *CallArgs[] = { 8128 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 8129 }; 8130 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(), 8131 Loc, CallArgs, Loc); 8132 8133 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 8134 return S.Owned(Call.takeAs<Stmt>()); 8135} 8136 8137/// \brief Builds a statement that copies/moves the given entity from \p From to 8138/// \c To. 8139/// 8140/// This routine is used to copy/move the members of a class with an 8141/// implicitly-declared copy/move assignment operator. When the entities being 8142/// copied are arrays, this routine builds for loops to copy them. 8143/// 8144/// \param S The Sema object used for type-checking. 8145/// 8146/// \param Loc The location where the implicit copy/move is being generated. 8147/// 8148/// \param T The type of the expressions being copied/moved. Both expressions 8149/// must have this type. 8150/// 8151/// \param To The expression we are copying/moving to. 8152/// 8153/// \param From The expression we are copying/moving from. 8154/// 8155/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 8156/// Otherwise, it's a non-static member subobject. 8157/// 8158/// \param Copying Whether we're copying or moving. 8159/// 8160/// \param Depth Internal parameter recording the depth of the recursion. 8161/// 8162/// \returns A statement or a loop that copies the expressions, or StmtResult(0) 8163/// if a memcpy should be used instead. 8164static StmtResult 8165buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 8166 Expr *To, Expr *From, 8167 bool CopyingBaseSubobject, bool Copying, 8168 unsigned Depth = 0) { 8169 // C++11 [class.copy]p28: 8170 // Each subobject is assigned in the manner appropriate to its type: 8171 // 8172 // - if the subobject is of class type, as if by a call to operator= with 8173 // the subobject as the object expression and the corresponding 8174 // subobject of x as a single function argument (as if by explicit 8175 // qualification; that is, ignoring any possible virtual overriding 8176 // functions in more derived classes); 8177 // 8178 // C++03 [class.copy]p13: 8179 // - if the subobject is of class type, the copy assignment operator for 8180 // the class is used (as if by explicit qualification; that is, 8181 // ignoring any possible virtual overriding functions in more derived 8182 // classes); 8183 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 8184 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8185 8186 // Look for operator=. 8187 DeclarationName Name 8188 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 8189 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 8190 S.LookupQualifiedName(OpLookup, ClassDecl, false); 8191 8192 // Prior to C++11, filter out any result that isn't a copy/move-assignment 8193 // operator. 8194 if (!S.getLangOpts().CPlusPlus11) { 8195 LookupResult::Filter F = OpLookup.makeFilter(); 8196 while (F.hasNext()) { 8197 NamedDecl *D = F.next(); 8198 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 8199 if (Method->isCopyAssignmentOperator() || 8200 (!Copying && Method->isMoveAssignmentOperator())) 8201 continue; 8202 8203 F.erase(); 8204 } 8205 F.done(); 8206 } 8207 8208 // Suppress the protected check (C++ [class.protected]) for each of the 8209 // assignment operators we found. This strange dance is required when 8210 // we're assigning via a base classes's copy-assignment operator. To 8211 // ensure that we're getting the right base class subobject (without 8212 // ambiguities), we need to cast "this" to that subobject type; to 8213 // ensure that we don't go through the virtual call mechanism, we need 8214 // to qualify the operator= name with the base class (see below). However, 8215 // this means that if the base class has a protected copy assignment 8216 // operator, the protected member access check will fail. So, we 8217 // rewrite "protected" access to "public" access in this case, since we 8218 // know by construction that we're calling from a derived class. 8219 if (CopyingBaseSubobject) { 8220 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 8221 L != LEnd; ++L) { 8222 if (L.getAccess() == AS_protected) 8223 L.setAccess(AS_public); 8224 } 8225 } 8226 8227 // Create the nested-name-specifier that will be used to qualify the 8228 // reference to operator=; this is required to suppress the virtual 8229 // call mechanism. 8230 CXXScopeSpec SS; 8231 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 8232 SS.MakeTrivial(S.Context, 8233 NestedNameSpecifier::Create(S.Context, 0, false, 8234 CanonicalT), 8235 Loc); 8236 8237 // Create the reference to operator=. 8238 ExprResult OpEqualRef 8239 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS, 8240 /*TemplateKWLoc=*/SourceLocation(), 8241 /*FirstQualifierInScope=*/0, 8242 OpLookup, 8243 /*TemplateArgs=*/0, 8244 /*SuppressQualifierCheck=*/true); 8245 if (OpEqualRef.isInvalid()) 8246 return StmtError(); 8247 8248 // Build the call to the assignment operator. 8249 8250 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0, 8251 OpEqualRef.takeAs<Expr>(), 8252 Loc, &From, 1, Loc); 8253 if (Call.isInvalid()) 8254 return StmtError(); 8255 8256 // If we built a call to a trivial 'operator=' while copying an array, 8257 // bail out. We'll replace the whole shebang with a memcpy. 8258 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 8259 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 8260 return StmtResult((Stmt*)0); 8261 8262 // Convert to an expression-statement, and clean up any produced 8263 // temporaries. 8264 return S.ActOnExprStmt(Call); 8265 } 8266 8267 // - if the subobject is of scalar type, the built-in assignment 8268 // operator is used. 8269 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 8270 if (!ArrayTy) { 8271 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From); 8272 if (Assignment.isInvalid()) 8273 return StmtError(); 8274 return S.ActOnExprStmt(Assignment); 8275 } 8276 8277 // - if the subobject is an array, each element is assigned, in the 8278 // manner appropriate to the element type; 8279 8280 // Construct a loop over the array bounds, e.g., 8281 // 8282 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 8283 // 8284 // that will copy each of the array elements. 8285 QualType SizeType = S.Context.getSizeType(); 8286 8287 // Create the iteration variable. 8288 IdentifierInfo *IterationVarName = 0; 8289 { 8290 SmallString<8> Str; 8291 llvm::raw_svector_ostream OS(Str); 8292 OS << "__i" << Depth; 8293 IterationVarName = &S.Context.Idents.get(OS.str()); 8294 } 8295 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 8296 IterationVarName, SizeType, 8297 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 8298 SC_None); 8299 8300 // Initialize the iteration variable to zero. 8301 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 8302 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 8303 8304 // Create a reference to the iteration variable; we'll use this several 8305 // times throughout. 8306 Expr *IterationVarRef 8307 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take(); 8308 assert(IterationVarRef && "Reference to invented variable cannot fail!"); 8309 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take(); 8310 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!"); 8311 8312 // Create the DeclStmt that holds the iteration variable. 8313 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 8314 8315 // Subscript the "from" and "to" expressions with the iteration variable. 8316 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc, 8317 IterationVarRefRVal, 8318 Loc)); 8319 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc, 8320 IterationVarRefRVal, 8321 Loc)); 8322 if (!Copying) // Cast to rvalue 8323 From = CastForMoving(S, From); 8324 8325 // Build the copy/move for an individual element of the array. 8326 StmtResult Copy = 8327 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 8328 To, From, CopyingBaseSubobject, 8329 Copying, Depth + 1); 8330 // Bail out if copying fails or if we determined that we should use memcpy. 8331 if (Copy.isInvalid() || !Copy.get()) 8332 return Copy; 8333 8334 // Create the comparison against the array bound. 8335 llvm::APInt Upper 8336 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 8337 Expr *Comparison 8338 = new (S.Context) BinaryOperator(IterationVarRefRVal, 8339 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 8340 BO_NE, S.Context.BoolTy, 8341 VK_RValue, OK_Ordinary, Loc, false); 8342 8343 // Create the pre-increment of the iteration variable. 8344 Expr *Increment 8345 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType, 8346 VK_LValue, OK_Ordinary, Loc); 8347 8348 // Construct the loop that copies all elements of this array. 8349 return S.ActOnForStmt(Loc, Loc, InitStmt, 8350 S.MakeFullExpr(Comparison), 8351 0, S.MakeFullDiscardedValueExpr(Increment), 8352 Loc, Copy.take()); 8353} 8354 8355static StmtResult 8356buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 8357 Expr *To, Expr *From, 8358 bool CopyingBaseSubobject, bool Copying) { 8359 // Maybe we should use a memcpy? 8360 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 8361 T.isTriviallyCopyableType(S.Context)) 8362 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 8363 8364 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 8365 CopyingBaseSubobject, 8366 Copying, 0)); 8367 8368 // If we ended up picking a trivial assignment operator for an array of a 8369 // non-trivially-copyable class type, just emit a memcpy. 8370 if (!Result.isInvalid() && !Result.get()) 8371 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 8372 8373 return Result; 8374} 8375 8376Sema::ImplicitExceptionSpecification 8377Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) { 8378 CXXRecordDecl *ClassDecl = MD->getParent(); 8379 8380 ImplicitExceptionSpecification ExceptSpec(*this); 8381 if (ClassDecl->isInvalidDecl()) 8382 return ExceptSpec; 8383 8384 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 8385 assert(T->getNumArgs() == 1 && "not a copy assignment op"); 8386 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers(); 8387 8388 // C++ [except.spec]p14: 8389 // An implicitly declared special member function (Clause 12) shall have an 8390 // exception-specification. [...] 8391 8392 // It is unspecified whether or not an implicit copy assignment operator 8393 // attempts to deduplicate calls to assignment operators of virtual bases are 8394 // made. As such, this exception specification is effectively unspecified. 8395 // Based on a similar decision made for constness in C++0x, we're erring on 8396 // the side of assuming such calls to be made regardless of whether they 8397 // actually happen. 8398 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 8399 BaseEnd = ClassDecl->bases_end(); 8400 Base != BaseEnd; ++Base) { 8401 if (Base->isVirtual()) 8402 continue; 8403 8404 CXXRecordDecl *BaseClassDecl 8405 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8406 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 8407 ArgQuals, false, 0)) 8408 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign); 8409 } 8410 8411 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 8412 BaseEnd = ClassDecl->vbases_end(); 8413 Base != BaseEnd; ++Base) { 8414 CXXRecordDecl *BaseClassDecl 8415 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8416 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 8417 ArgQuals, false, 0)) 8418 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign); 8419 } 8420 8421 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8422 FieldEnd = ClassDecl->field_end(); 8423 Field != FieldEnd; 8424 ++Field) { 8425 QualType FieldType = Context.getBaseElementType(Field->getType()); 8426 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 8427 if (CXXMethodDecl *CopyAssign = 8428 LookupCopyingAssignment(FieldClassDecl, 8429 ArgQuals | FieldType.getCVRQualifiers(), 8430 false, 0)) 8431 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign); 8432 } 8433 } 8434 8435 return ExceptSpec; 8436} 8437 8438CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 8439 // Note: The following rules are largely analoguous to the copy 8440 // constructor rules. Note that virtual bases are not taken into account 8441 // for determining the argument type of the operator. Note also that 8442 // operators taking an object instead of a reference are allowed. 8443 assert(ClassDecl->needsImplicitCopyAssignment()); 8444 8445 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 8446 if (DSM.isAlreadyBeingDeclared()) 8447 return 0; 8448 8449 QualType ArgType = Context.getTypeDeclType(ClassDecl); 8450 QualType RetType = Context.getLValueReferenceType(ArgType); 8451 if (ClassDecl->implicitCopyAssignmentHasConstParam()) 8452 ArgType = ArgType.withConst(); 8453 ArgType = Context.getLValueReferenceType(ArgType); 8454 8455 // An implicitly-declared copy assignment operator is an inline public 8456 // member of its class. 8457 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 8458 SourceLocation ClassLoc = ClassDecl->getLocation(); 8459 DeclarationNameInfo NameInfo(Name, ClassLoc); 8460 CXXMethodDecl *CopyAssignment 8461 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 8462 /*TInfo=*/0, 8463 /*StorageClass=*/SC_None, 8464 /*isInline=*/true, /*isConstexpr=*/false, 8465 SourceLocation()); 8466 CopyAssignment->setAccess(AS_public); 8467 CopyAssignment->setDefaulted(); 8468 CopyAssignment->setImplicit(); 8469 8470 // Build an exception specification pointing back at this member. 8471 FunctionProtoType::ExtProtoInfo EPI; 8472 EPI.ExceptionSpecType = EST_Unevaluated; 8473 EPI.ExceptionSpecDecl = CopyAssignment; 8474 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 8475 8476 // Add the parameter to the operator. 8477 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 8478 ClassLoc, ClassLoc, /*Id=*/0, 8479 ArgType, /*TInfo=*/0, 8480 SC_None, 0); 8481 CopyAssignment->setParams(FromParam); 8482 8483 AddOverriddenMethods(ClassDecl, CopyAssignment); 8484 8485 CopyAssignment->setTrivial( 8486 ClassDecl->needsOverloadResolutionForCopyAssignment() 8487 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 8488 : ClassDecl->hasTrivialCopyAssignment()); 8489 8490 // C++0x [class.copy]p19: 8491 // .... If the class definition does not explicitly declare a copy 8492 // assignment operator, there is no user-declared move constructor, and 8493 // there is no user-declared move assignment operator, a copy assignment 8494 // operator is implicitly declared as defaulted. 8495 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 8496 SetDeclDeleted(CopyAssignment, ClassLoc); 8497 8498 // Note that we have added this copy-assignment operator. 8499 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 8500 8501 if (Scope *S = getScopeForContext(ClassDecl)) 8502 PushOnScopeChains(CopyAssignment, S, false); 8503 ClassDecl->addDecl(CopyAssignment); 8504 8505 return CopyAssignment; 8506} 8507 8508void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 8509 CXXMethodDecl *CopyAssignOperator) { 8510 assert((CopyAssignOperator->isDefaulted() && 8511 CopyAssignOperator->isOverloadedOperator() && 8512 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 8513 !CopyAssignOperator->doesThisDeclarationHaveABody() && 8514 !CopyAssignOperator->isDeleted()) && 8515 "DefineImplicitCopyAssignment called for wrong function"); 8516 8517 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 8518 8519 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) { 8520 CopyAssignOperator->setInvalidDecl(); 8521 return; 8522 } 8523 8524 CopyAssignOperator->setUsed(); 8525 8526 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 8527 DiagnosticErrorTrap Trap(Diags); 8528 8529 // C++0x [class.copy]p30: 8530 // The implicitly-defined or explicitly-defaulted copy assignment operator 8531 // for a non-union class X performs memberwise copy assignment of its 8532 // subobjects. The direct base classes of X are assigned first, in the 8533 // order of their declaration in the base-specifier-list, and then the 8534 // immediate non-static data members of X are assigned, in the order in 8535 // which they were declared in the class definition. 8536 8537 // The statements that form the synthesized function body. 8538 SmallVector<Stmt*, 8> Statements; 8539 8540 // The parameter for the "other" object, which we are copying from. 8541 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 8542 Qualifiers OtherQuals = Other->getType().getQualifiers(); 8543 QualType OtherRefType = Other->getType(); 8544 if (const LValueReferenceType *OtherRef 8545 = OtherRefType->getAs<LValueReferenceType>()) { 8546 OtherRefType = OtherRef->getPointeeType(); 8547 OtherQuals = OtherRefType.getQualifiers(); 8548 } 8549 8550 // Our location for everything implicitly-generated. 8551 SourceLocation Loc = CopyAssignOperator->getLocation(); 8552 8553 // Construct a reference to the "other" object. We'll be using this 8554 // throughout the generated ASTs. 8555 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take(); 8556 assert(OtherRef && "Reference to parameter cannot fail!"); 8557 8558 // Construct the "this" pointer. We'll be using this throughout the generated 8559 // ASTs. 8560 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>(); 8561 assert(This && "Reference to this cannot fail!"); 8562 8563 // Assign base classes. 8564 bool Invalid = false; 8565 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 8566 E = ClassDecl->bases_end(); Base != E; ++Base) { 8567 // Form the assignment: 8568 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 8569 QualType BaseType = Base->getType().getUnqualifiedType(); 8570 if (!BaseType->isRecordType()) { 8571 Invalid = true; 8572 continue; 8573 } 8574 8575 CXXCastPath BasePath; 8576 BasePath.push_back(Base); 8577 8578 // Construct the "from" expression, which is an implicit cast to the 8579 // appropriately-qualified base type. 8580 Expr *From = OtherRef; 8581 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals), 8582 CK_UncheckedDerivedToBase, 8583 VK_LValue, &BasePath).take(); 8584 8585 // Dereference "this". 8586 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 8587 8588 // Implicitly cast "this" to the appropriately-qualified base type. 8589 To = ImpCastExprToType(To.take(), 8590 Context.getCVRQualifiedType(BaseType, 8591 CopyAssignOperator->getTypeQualifiers()), 8592 CK_UncheckedDerivedToBase, 8593 VK_LValue, &BasePath); 8594 8595 // Build the copy. 8596 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 8597 To.get(), From, 8598 /*CopyingBaseSubobject=*/true, 8599 /*Copying=*/true); 8600 if (Copy.isInvalid()) { 8601 Diag(CurrentLocation, diag::note_member_synthesized_at) 8602 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 8603 CopyAssignOperator->setInvalidDecl(); 8604 return; 8605 } 8606 8607 // Success! Record the copy. 8608 Statements.push_back(Copy.takeAs<Expr>()); 8609 } 8610 8611 // Assign non-static members. 8612 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8613 FieldEnd = ClassDecl->field_end(); 8614 Field != FieldEnd; ++Field) { 8615 if (Field->isUnnamedBitfield()) 8616 continue; 8617 8618 // Check for members of reference type; we can't copy those. 8619 if (Field->getType()->isReferenceType()) { 8620 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 8621 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 8622 Diag(Field->getLocation(), diag::note_declared_at); 8623 Diag(CurrentLocation, diag::note_member_synthesized_at) 8624 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 8625 Invalid = true; 8626 continue; 8627 } 8628 8629 // Check for members of const-qualified, non-class type. 8630 QualType BaseType = Context.getBaseElementType(Field->getType()); 8631 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 8632 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 8633 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 8634 Diag(Field->getLocation(), diag::note_declared_at); 8635 Diag(CurrentLocation, diag::note_member_synthesized_at) 8636 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 8637 Invalid = true; 8638 continue; 8639 } 8640 8641 // Suppress assigning zero-width bitfields. 8642 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 8643 continue; 8644 8645 QualType FieldType = Field->getType().getNonReferenceType(); 8646 if (FieldType->isIncompleteArrayType()) { 8647 assert(ClassDecl->hasFlexibleArrayMember() && 8648 "Incomplete array type is not valid"); 8649 continue; 8650 } 8651 8652 // Build references to the field in the object we're copying from and to. 8653 CXXScopeSpec SS; // Intentionally empty 8654 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 8655 LookupMemberName); 8656 MemberLookup.addDecl(*Field); 8657 MemberLookup.resolveKind(); 8658 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType, 8659 Loc, /*IsArrow=*/false, 8660 SS, SourceLocation(), 0, 8661 MemberLookup, 0); 8662 ExprResult To = BuildMemberReferenceExpr(This, This->getType(), 8663 Loc, /*IsArrow=*/true, 8664 SS, SourceLocation(), 0, 8665 MemberLookup, 0); 8666 assert(!From.isInvalid() && "Implicit field reference cannot fail"); 8667 assert(!To.isInvalid() && "Implicit field reference cannot fail"); 8668 8669 // Build the copy of this field. 8670 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 8671 To.get(), From.get(), 8672 /*CopyingBaseSubobject=*/false, 8673 /*Copying=*/true); 8674 if (Copy.isInvalid()) { 8675 Diag(CurrentLocation, diag::note_member_synthesized_at) 8676 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 8677 CopyAssignOperator->setInvalidDecl(); 8678 return; 8679 } 8680 8681 // Success! Record the copy. 8682 Statements.push_back(Copy.takeAs<Stmt>()); 8683 } 8684 8685 if (!Invalid) { 8686 // Add a "return *this;" 8687 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 8688 8689 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get()); 8690 if (Return.isInvalid()) 8691 Invalid = true; 8692 else { 8693 Statements.push_back(Return.takeAs<Stmt>()); 8694 8695 if (Trap.hasErrorOccurred()) { 8696 Diag(CurrentLocation, diag::note_member_synthesized_at) 8697 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 8698 Invalid = true; 8699 } 8700 } 8701 } 8702 8703 if (Invalid) { 8704 CopyAssignOperator->setInvalidDecl(); 8705 return; 8706 } 8707 8708 StmtResult Body; 8709 { 8710 CompoundScopeRAII CompoundScope(*this); 8711 Body = ActOnCompoundStmt(Loc, Loc, Statements, 8712 /*isStmtExpr=*/false); 8713 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 8714 } 8715 CopyAssignOperator->setBody(Body.takeAs<Stmt>()); 8716 8717 if (ASTMutationListener *L = getASTMutationListener()) { 8718 L->CompletedImplicitDefinition(CopyAssignOperator); 8719 } 8720} 8721 8722Sema::ImplicitExceptionSpecification 8723Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) { 8724 CXXRecordDecl *ClassDecl = MD->getParent(); 8725 8726 ImplicitExceptionSpecification ExceptSpec(*this); 8727 if (ClassDecl->isInvalidDecl()) 8728 return ExceptSpec; 8729 8730 // C++0x [except.spec]p14: 8731 // An implicitly declared special member function (Clause 12) shall have an 8732 // exception-specification. [...] 8733 8734 // It is unspecified whether or not an implicit move assignment operator 8735 // attempts to deduplicate calls to assignment operators of virtual bases are 8736 // made. As such, this exception specification is effectively unspecified. 8737 // Based on a similar decision made for constness in C++0x, we're erring on 8738 // the side of assuming such calls to be made regardless of whether they 8739 // actually happen. 8740 // Note that a move constructor is not implicitly declared when there are 8741 // virtual bases, but it can still be user-declared and explicitly defaulted. 8742 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 8743 BaseEnd = ClassDecl->bases_end(); 8744 Base != BaseEnd; ++Base) { 8745 if (Base->isVirtual()) 8746 continue; 8747 8748 CXXRecordDecl *BaseClassDecl 8749 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8750 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 8751 0, false, 0)) 8752 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign); 8753 } 8754 8755 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 8756 BaseEnd = ClassDecl->vbases_end(); 8757 Base != BaseEnd; ++Base) { 8758 CXXRecordDecl *BaseClassDecl 8759 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8760 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 8761 0, false, 0)) 8762 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign); 8763 } 8764 8765 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8766 FieldEnd = ClassDecl->field_end(); 8767 Field != FieldEnd; 8768 ++Field) { 8769 QualType FieldType = Context.getBaseElementType(Field->getType()); 8770 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 8771 if (CXXMethodDecl *MoveAssign = 8772 LookupMovingAssignment(FieldClassDecl, 8773 FieldType.getCVRQualifiers(), 8774 false, 0)) 8775 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign); 8776 } 8777 } 8778 8779 return ExceptSpec; 8780} 8781 8782/// Determine whether the class type has any direct or indirect virtual base 8783/// classes which have a non-trivial move assignment operator. 8784static bool 8785hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) { 8786 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 8787 BaseEnd = ClassDecl->vbases_end(); 8788 Base != BaseEnd; ++Base) { 8789 CXXRecordDecl *BaseClass = 8790 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8791 8792 // Try to declare the move assignment. If it would be deleted, then the 8793 // class does not have a non-trivial move assignment. 8794 if (BaseClass->needsImplicitMoveAssignment()) 8795 S.DeclareImplicitMoveAssignment(BaseClass); 8796 8797 if (BaseClass->hasNonTrivialMoveAssignment()) 8798 return true; 8799 } 8800 8801 return false; 8802} 8803 8804/// Determine whether the given type either has a move constructor or is 8805/// trivially copyable. 8806static bool 8807hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) { 8808 Type = S.Context.getBaseElementType(Type); 8809 8810 // FIXME: Technically, non-trivially-copyable non-class types, such as 8811 // reference types, are supposed to return false here, but that appears 8812 // to be a standard defect. 8813 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl(); 8814 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl()) 8815 return true; 8816 8817 if (Type.isTriviallyCopyableType(S.Context)) 8818 return true; 8819 8820 if (IsConstructor) { 8821 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to 8822 // give the right answer. 8823 if (ClassDecl->needsImplicitMoveConstructor()) 8824 S.DeclareImplicitMoveConstructor(ClassDecl); 8825 return ClassDecl->hasMoveConstructor(); 8826 } 8827 8828 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to 8829 // give the right answer. 8830 if (ClassDecl->needsImplicitMoveAssignment()) 8831 S.DeclareImplicitMoveAssignment(ClassDecl); 8832 return ClassDecl->hasMoveAssignment(); 8833} 8834 8835/// Determine whether all non-static data members and direct or virtual bases 8836/// of class \p ClassDecl have either a move operation, or are trivially 8837/// copyable. 8838static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl, 8839 bool IsConstructor) { 8840 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 8841 BaseEnd = ClassDecl->bases_end(); 8842 Base != BaseEnd; ++Base) { 8843 if (Base->isVirtual()) 8844 continue; 8845 8846 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor)) 8847 return false; 8848 } 8849 8850 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 8851 BaseEnd = ClassDecl->vbases_end(); 8852 Base != BaseEnd; ++Base) { 8853 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor)) 8854 return false; 8855 } 8856 8857 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8858 FieldEnd = ClassDecl->field_end(); 8859 Field != FieldEnd; ++Field) { 8860 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor)) 8861 return false; 8862 } 8863 8864 return true; 8865} 8866 8867CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 8868 // C++11 [class.copy]p20: 8869 // If the definition of a class X does not explicitly declare a move 8870 // assignment operator, one will be implicitly declared as defaulted 8871 // if and only if: 8872 // 8873 // - [first 4 bullets] 8874 assert(ClassDecl->needsImplicitMoveAssignment()); 8875 8876 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 8877 if (DSM.isAlreadyBeingDeclared()) 8878 return 0; 8879 8880 // [Checked after we build the declaration] 8881 // - the move assignment operator would not be implicitly defined as 8882 // deleted, 8883 8884 // [DR1402]: 8885 // - X has no direct or indirect virtual base class with a non-trivial 8886 // move assignment operator, and 8887 // - each of X's non-static data members and direct or virtual base classes 8888 // has a type that either has a move assignment operator or is trivially 8889 // copyable. 8890 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) || 8891 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) { 8892 ClassDecl->setFailedImplicitMoveAssignment(); 8893 return 0; 8894 } 8895 8896 // Note: The following rules are largely analoguous to the move 8897 // constructor rules. 8898 8899 QualType ArgType = Context.getTypeDeclType(ClassDecl); 8900 QualType RetType = Context.getLValueReferenceType(ArgType); 8901 ArgType = Context.getRValueReferenceType(ArgType); 8902 8903 // An implicitly-declared move assignment operator is an inline public 8904 // member of its class. 8905 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 8906 SourceLocation ClassLoc = ClassDecl->getLocation(); 8907 DeclarationNameInfo NameInfo(Name, ClassLoc); 8908 CXXMethodDecl *MoveAssignment 8909 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 8910 /*TInfo=*/0, 8911 /*StorageClass=*/SC_None, 8912 /*isInline=*/true, 8913 /*isConstexpr=*/false, 8914 SourceLocation()); 8915 MoveAssignment->setAccess(AS_public); 8916 MoveAssignment->setDefaulted(); 8917 MoveAssignment->setImplicit(); 8918 8919 // Build an exception specification pointing back at this member. 8920 FunctionProtoType::ExtProtoInfo EPI; 8921 EPI.ExceptionSpecType = EST_Unevaluated; 8922 EPI.ExceptionSpecDecl = MoveAssignment; 8923 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 8924 8925 // Add the parameter to the operator. 8926 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 8927 ClassLoc, ClassLoc, /*Id=*/0, 8928 ArgType, /*TInfo=*/0, 8929 SC_None, 0); 8930 MoveAssignment->setParams(FromParam); 8931 8932 AddOverriddenMethods(ClassDecl, MoveAssignment); 8933 8934 MoveAssignment->setTrivial( 8935 ClassDecl->needsOverloadResolutionForMoveAssignment() 8936 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 8937 : ClassDecl->hasTrivialMoveAssignment()); 8938 8939 // C++0x [class.copy]p9: 8940 // If the definition of a class X does not explicitly declare a move 8941 // assignment operator, one will be implicitly declared as defaulted if and 8942 // only if: 8943 // [...] 8944 // - the move assignment operator would not be implicitly defined as 8945 // deleted. 8946 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 8947 // Cache this result so that we don't try to generate this over and over 8948 // on every lookup, leaking memory and wasting time. 8949 ClassDecl->setFailedImplicitMoveAssignment(); 8950 return 0; 8951 } 8952 8953 // Note that we have added this copy-assignment operator. 8954 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 8955 8956 if (Scope *S = getScopeForContext(ClassDecl)) 8957 PushOnScopeChains(MoveAssignment, S, false); 8958 ClassDecl->addDecl(MoveAssignment); 8959 8960 return MoveAssignment; 8961} 8962 8963void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 8964 CXXMethodDecl *MoveAssignOperator) { 8965 assert((MoveAssignOperator->isDefaulted() && 8966 MoveAssignOperator->isOverloadedOperator() && 8967 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 8968 !MoveAssignOperator->doesThisDeclarationHaveABody() && 8969 !MoveAssignOperator->isDeleted()) && 8970 "DefineImplicitMoveAssignment called for wrong function"); 8971 8972 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 8973 8974 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) { 8975 MoveAssignOperator->setInvalidDecl(); 8976 return; 8977 } 8978 8979 MoveAssignOperator->setUsed(); 8980 8981 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 8982 DiagnosticErrorTrap Trap(Diags); 8983 8984 // C++0x [class.copy]p28: 8985 // The implicitly-defined or move assignment operator for a non-union class 8986 // X performs memberwise move assignment of its subobjects. The direct base 8987 // classes of X are assigned first, in the order of their declaration in the 8988 // base-specifier-list, and then the immediate non-static data members of X 8989 // are assigned, in the order in which they were declared in the class 8990 // definition. 8991 8992 // The statements that form the synthesized function body. 8993 SmallVector<Stmt*, 8> Statements; 8994 8995 // The parameter for the "other" object, which we are move from. 8996 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 8997 QualType OtherRefType = Other->getType()-> 8998 getAs<RValueReferenceType>()->getPointeeType(); 8999 assert(OtherRefType.getQualifiers() == 0 && 9000 "Bad argument type of defaulted move assignment"); 9001 9002 // Our location for everything implicitly-generated. 9003 SourceLocation Loc = MoveAssignOperator->getLocation(); 9004 9005 // Construct a reference to the "other" object. We'll be using this 9006 // throughout the generated ASTs. 9007 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take(); 9008 assert(OtherRef && "Reference to parameter cannot fail!"); 9009 // Cast to rvalue. 9010 OtherRef = CastForMoving(*this, OtherRef); 9011 9012 // Construct the "this" pointer. We'll be using this throughout the generated 9013 // ASTs. 9014 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>(); 9015 assert(This && "Reference to this cannot fail!"); 9016 9017 // Assign base classes. 9018 bool Invalid = false; 9019 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 9020 E = ClassDecl->bases_end(); Base != E; ++Base) { 9021 // Form the assignment: 9022 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 9023 QualType BaseType = Base->getType().getUnqualifiedType(); 9024 if (!BaseType->isRecordType()) { 9025 Invalid = true; 9026 continue; 9027 } 9028 9029 CXXCastPath BasePath; 9030 BasePath.push_back(Base); 9031 9032 // Construct the "from" expression, which is an implicit cast to the 9033 // appropriately-qualified base type. 9034 Expr *From = OtherRef; 9035 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase, 9036 VK_XValue, &BasePath).take(); 9037 9038 // Dereference "this". 9039 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 9040 9041 // Implicitly cast "this" to the appropriately-qualified base type. 9042 To = ImpCastExprToType(To.take(), 9043 Context.getCVRQualifiedType(BaseType, 9044 MoveAssignOperator->getTypeQualifiers()), 9045 CK_UncheckedDerivedToBase, 9046 VK_LValue, &BasePath); 9047 9048 // Build the move. 9049 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 9050 To.get(), From, 9051 /*CopyingBaseSubobject=*/true, 9052 /*Copying=*/false); 9053 if (Move.isInvalid()) { 9054 Diag(CurrentLocation, diag::note_member_synthesized_at) 9055 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9056 MoveAssignOperator->setInvalidDecl(); 9057 return; 9058 } 9059 9060 // Success! Record the move. 9061 Statements.push_back(Move.takeAs<Expr>()); 9062 } 9063 9064 // Assign non-static members. 9065 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 9066 FieldEnd = ClassDecl->field_end(); 9067 Field != FieldEnd; ++Field) { 9068 if (Field->isUnnamedBitfield()) 9069 continue; 9070 9071 // Check for members of reference type; we can't move those. 9072 if (Field->getType()->isReferenceType()) { 9073 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9074 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 9075 Diag(Field->getLocation(), diag::note_declared_at); 9076 Diag(CurrentLocation, diag::note_member_synthesized_at) 9077 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9078 Invalid = true; 9079 continue; 9080 } 9081 9082 // Check for members of const-qualified, non-class type. 9083 QualType BaseType = Context.getBaseElementType(Field->getType()); 9084 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 9085 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9086 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 9087 Diag(Field->getLocation(), diag::note_declared_at); 9088 Diag(CurrentLocation, diag::note_member_synthesized_at) 9089 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9090 Invalid = true; 9091 continue; 9092 } 9093 9094 // Suppress assigning zero-width bitfields. 9095 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 9096 continue; 9097 9098 QualType FieldType = Field->getType().getNonReferenceType(); 9099 if (FieldType->isIncompleteArrayType()) { 9100 assert(ClassDecl->hasFlexibleArrayMember() && 9101 "Incomplete array type is not valid"); 9102 continue; 9103 } 9104 9105 // Build references to the field in the object we're copying from and to. 9106 CXXScopeSpec SS; // Intentionally empty 9107 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 9108 LookupMemberName); 9109 MemberLookup.addDecl(*Field); 9110 MemberLookup.resolveKind(); 9111 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType, 9112 Loc, /*IsArrow=*/false, 9113 SS, SourceLocation(), 0, 9114 MemberLookup, 0); 9115 ExprResult To = BuildMemberReferenceExpr(This, This->getType(), 9116 Loc, /*IsArrow=*/true, 9117 SS, SourceLocation(), 0, 9118 MemberLookup, 0); 9119 assert(!From.isInvalid() && "Implicit field reference cannot fail"); 9120 assert(!To.isInvalid() && "Implicit field reference cannot fail"); 9121 9122 assert(!From.get()->isLValue() && // could be xvalue or prvalue 9123 "Member reference with rvalue base must be rvalue except for reference " 9124 "members, which aren't allowed for move assignment."); 9125 9126 // Build the move of this field. 9127 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 9128 To.get(), From.get(), 9129 /*CopyingBaseSubobject=*/false, 9130 /*Copying=*/false); 9131 if (Move.isInvalid()) { 9132 Diag(CurrentLocation, diag::note_member_synthesized_at) 9133 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9134 MoveAssignOperator->setInvalidDecl(); 9135 return; 9136 } 9137 9138 // Success! Record the copy. 9139 Statements.push_back(Move.takeAs<Stmt>()); 9140 } 9141 9142 if (!Invalid) { 9143 // Add a "return *this;" 9144 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 9145 9146 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get()); 9147 if (Return.isInvalid()) 9148 Invalid = true; 9149 else { 9150 Statements.push_back(Return.takeAs<Stmt>()); 9151 9152 if (Trap.hasErrorOccurred()) { 9153 Diag(CurrentLocation, diag::note_member_synthesized_at) 9154 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9155 Invalid = true; 9156 } 9157 } 9158 } 9159 9160 if (Invalid) { 9161 MoveAssignOperator->setInvalidDecl(); 9162 return; 9163 } 9164 9165 StmtResult Body; 9166 { 9167 CompoundScopeRAII CompoundScope(*this); 9168 Body = ActOnCompoundStmt(Loc, Loc, Statements, 9169 /*isStmtExpr=*/false); 9170 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 9171 } 9172 MoveAssignOperator->setBody(Body.takeAs<Stmt>()); 9173 9174 if (ASTMutationListener *L = getASTMutationListener()) { 9175 L->CompletedImplicitDefinition(MoveAssignOperator); 9176 } 9177} 9178 9179Sema::ImplicitExceptionSpecification 9180Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) { 9181 CXXRecordDecl *ClassDecl = MD->getParent(); 9182 9183 ImplicitExceptionSpecification ExceptSpec(*this); 9184 if (ClassDecl->isInvalidDecl()) 9185 return ExceptSpec; 9186 9187 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 9188 assert(T->getNumArgs() >= 1 && "not a copy ctor"); 9189 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers(); 9190 9191 // C++ [except.spec]p14: 9192 // An implicitly declared special member function (Clause 12) shall have an 9193 // exception-specification. [...] 9194 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 9195 BaseEnd = ClassDecl->bases_end(); 9196 Base != BaseEnd; 9197 ++Base) { 9198 // Virtual bases are handled below. 9199 if (Base->isVirtual()) 9200 continue; 9201 9202 CXXRecordDecl *BaseClassDecl 9203 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9204 if (CXXConstructorDecl *CopyConstructor = 9205 LookupCopyingConstructor(BaseClassDecl, Quals)) 9206 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor); 9207 } 9208 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 9209 BaseEnd = ClassDecl->vbases_end(); 9210 Base != BaseEnd; 9211 ++Base) { 9212 CXXRecordDecl *BaseClassDecl 9213 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9214 if (CXXConstructorDecl *CopyConstructor = 9215 LookupCopyingConstructor(BaseClassDecl, Quals)) 9216 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor); 9217 } 9218 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 9219 FieldEnd = ClassDecl->field_end(); 9220 Field != FieldEnd; 9221 ++Field) { 9222 QualType FieldType = Context.getBaseElementType(Field->getType()); 9223 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 9224 if (CXXConstructorDecl *CopyConstructor = 9225 LookupCopyingConstructor(FieldClassDecl, 9226 Quals | FieldType.getCVRQualifiers())) 9227 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor); 9228 } 9229 } 9230 9231 return ExceptSpec; 9232} 9233 9234CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 9235 CXXRecordDecl *ClassDecl) { 9236 // C++ [class.copy]p4: 9237 // If the class definition does not explicitly declare a copy 9238 // constructor, one is declared implicitly. 9239 assert(ClassDecl->needsImplicitCopyConstructor()); 9240 9241 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 9242 if (DSM.isAlreadyBeingDeclared()) 9243 return 0; 9244 9245 QualType ClassType = Context.getTypeDeclType(ClassDecl); 9246 QualType ArgType = ClassType; 9247 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 9248 if (Const) 9249 ArgType = ArgType.withConst(); 9250 ArgType = Context.getLValueReferenceType(ArgType); 9251 9252 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9253 CXXCopyConstructor, 9254 Const); 9255 9256 DeclarationName Name 9257 = Context.DeclarationNames.getCXXConstructorName( 9258 Context.getCanonicalType(ClassType)); 9259 SourceLocation ClassLoc = ClassDecl->getLocation(); 9260 DeclarationNameInfo NameInfo(Name, ClassLoc); 9261 9262 // An implicitly-declared copy constructor is an inline public 9263 // member of its class. 9264 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 9265 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0, 9266 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 9267 Constexpr); 9268 CopyConstructor->setAccess(AS_public); 9269 CopyConstructor->setDefaulted(); 9270 9271 // Build an exception specification pointing back at this member. 9272 FunctionProtoType::ExtProtoInfo EPI; 9273 EPI.ExceptionSpecType = EST_Unevaluated; 9274 EPI.ExceptionSpecDecl = CopyConstructor; 9275 CopyConstructor->setType( 9276 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 9277 9278 // Add the parameter to the constructor. 9279 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 9280 ClassLoc, ClassLoc, 9281 /*IdentifierInfo=*/0, 9282 ArgType, /*TInfo=*/0, 9283 SC_None, 0); 9284 CopyConstructor->setParams(FromParam); 9285 9286 CopyConstructor->setTrivial( 9287 ClassDecl->needsOverloadResolutionForCopyConstructor() 9288 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 9289 : ClassDecl->hasTrivialCopyConstructor()); 9290 9291 // C++11 [class.copy]p8: 9292 // ... If the class definition does not explicitly declare a copy 9293 // constructor, there is no user-declared move constructor, and there is no 9294 // user-declared move assignment operator, a copy constructor is implicitly 9295 // declared as defaulted. 9296 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) 9297 SetDeclDeleted(CopyConstructor, ClassLoc); 9298 9299 // Note that we have declared this constructor. 9300 ++ASTContext::NumImplicitCopyConstructorsDeclared; 9301 9302 if (Scope *S = getScopeForContext(ClassDecl)) 9303 PushOnScopeChains(CopyConstructor, S, false); 9304 ClassDecl->addDecl(CopyConstructor); 9305 9306 return CopyConstructor; 9307} 9308 9309void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 9310 CXXConstructorDecl *CopyConstructor) { 9311 assert((CopyConstructor->isDefaulted() && 9312 CopyConstructor->isCopyConstructor() && 9313 !CopyConstructor->doesThisDeclarationHaveABody() && 9314 !CopyConstructor->isDeleted()) && 9315 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 9316 9317 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 9318 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 9319 9320 SynthesizedFunctionScope Scope(*this, CopyConstructor); 9321 DiagnosticErrorTrap Trap(Diags); 9322 9323 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) || 9324 Trap.hasErrorOccurred()) { 9325 Diag(CurrentLocation, diag::note_member_synthesized_at) 9326 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl); 9327 CopyConstructor->setInvalidDecl(); 9328 } else { 9329 Sema::CompoundScopeRAII CompoundScope(*this); 9330 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(), 9331 CopyConstructor->getLocation(), 9332 MultiStmtArg(), 9333 /*isStmtExpr=*/false) 9334 .takeAs<Stmt>()); 9335 CopyConstructor->setImplicitlyDefined(true); 9336 } 9337 9338 CopyConstructor->setUsed(); 9339 if (ASTMutationListener *L = getASTMutationListener()) { 9340 L->CompletedImplicitDefinition(CopyConstructor); 9341 } 9342} 9343 9344Sema::ImplicitExceptionSpecification 9345Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) { 9346 CXXRecordDecl *ClassDecl = MD->getParent(); 9347 9348 // C++ [except.spec]p14: 9349 // An implicitly declared special member function (Clause 12) shall have an 9350 // exception-specification. [...] 9351 ImplicitExceptionSpecification ExceptSpec(*this); 9352 if (ClassDecl->isInvalidDecl()) 9353 return ExceptSpec; 9354 9355 // Direct base-class constructors. 9356 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 9357 BEnd = ClassDecl->bases_end(); 9358 B != BEnd; ++B) { 9359 if (B->isVirtual()) // Handled below. 9360 continue; 9361 9362 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 9363 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 9364 CXXConstructorDecl *Constructor = 9365 LookupMovingConstructor(BaseClassDecl, 0); 9366 // If this is a deleted function, add it anyway. This might be conformant 9367 // with the standard. This might not. I'm not sure. It might not matter. 9368 if (Constructor) 9369 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 9370 } 9371 } 9372 9373 // Virtual base-class constructors. 9374 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 9375 BEnd = ClassDecl->vbases_end(); 9376 B != BEnd; ++B) { 9377 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 9378 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 9379 CXXConstructorDecl *Constructor = 9380 LookupMovingConstructor(BaseClassDecl, 0); 9381 // If this is a deleted function, add it anyway. This might be conformant 9382 // with the standard. This might not. I'm not sure. It might not matter. 9383 if (Constructor) 9384 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 9385 } 9386 } 9387 9388 // Field constructors. 9389 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 9390 FEnd = ClassDecl->field_end(); 9391 F != FEnd; ++F) { 9392 QualType FieldType = Context.getBaseElementType(F->getType()); 9393 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) { 9394 CXXConstructorDecl *Constructor = 9395 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers()); 9396 // If this is a deleted function, add it anyway. This might be conformant 9397 // with the standard. This might not. I'm not sure. It might not matter. 9398 // In particular, the problem is that this function never gets called. It 9399 // might just be ill-formed because this function attempts to refer to 9400 // a deleted function here. 9401 if (Constructor) 9402 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 9403 } 9404 } 9405 9406 return ExceptSpec; 9407} 9408 9409CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 9410 CXXRecordDecl *ClassDecl) { 9411 // C++11 [class.copy]p9: 9412 // If the definition of a class X does not explicitly declare a move 9413 // constructor, one will be implicitly declared as defaulted if and only if: 9414 // 9415 // - [first 4 bullets] 9416 assert(ClassDecl->needsImplicitMoveConstructor()); 9417 9418 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 9419 if (DSM.isAlreadyBeingDeclared()) 9420 return 0; 9421 9422 // [Checked after we build the declaration] 9423 // - the move assignment operator would not be implicitly defined as 9424 // deleted, 9425 9426 // [DR1402]: 9427 // - each of X's non-static data members and direct or virtual base classes 9428 // has a type that either has a move constructor or is trivially copyable. 9429 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) { 9430 ClassDecl->setFailedImplicitMoveConstructor(); 9431 return 0; 9432 } 9433 9434 QualType ClassType = Context.getTypeDeclType(ClassDecl); 9435 QualType ArgType = Context.getRValueReferenceType(ClassType); 9436 9437 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9438 CXXMoveConstructor, 9439 false); 9440 9441 DeclarationName Name 9442 = Context.DeclarationNames.getCXXConstructorName( 9443 Context.getCanonicalType(ClassType)); 9444 SourceLocation ClassLoc = ClassDecl->getLocation(); 9445 DeclarationNameInfo NameInfo(Name, ClassLoc); 9446 9447 // C++0x [class.copy]p11: 9448 // An implicitly-declared copy/move constructor is an inline public 9449 // member of its class. 9450 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 9451 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0, 9452 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 9453 Constexpr); 9454 MoveConstructor->setAccess(AS_public); 9455 MoveConstructor->setDefaulted(); 9456 9457 // Build an exception specification pointing back at this member. 9458 FunctionProtoType::ExtProtoInfo EPI; 9459 EPI.ExceptionSpecType = EST_Unevaluated; 9460 EPI.ExceptionSpecDecl = MoveConstructor; 9461 MoveConstructor->setType( 9462 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 9463 9464 // Add the parameter to the constructor. 9465 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 9466 ClassLoc, ClassLoc, 9467 /*IdentifierInfo=*/0, 9468 ArgType, /*TInfo=*/0, 9469 SC_None, 0); 9470 MoveConstructor->setParams(FromParam); 9471 9472 MoveConstructor->setTrivial( 9473 ClassDecl->needsOverloadResolutionForMoveConstructor() 9474 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 9475 : ClassDecl->hasTrivialMoveConstructor()); 9476 9477 // C++0x [class.copy]p9: 9478 // If the definition of a class X does not explicitly declare a move 9479 // constructor, one will be implicitly declared as defaulted if and only if: 9480 // [...] 9481 // - the move constructor would not be implicitly defined as deleted. 9482 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 9483 // Cache this result so that we don't try to generate this over and over 9484 // on every lookup, leaking memory and wasting time. 9485 ClassDecl->setFailedImplicitMoveConstructor(); 9486 return 0; 9487 } 9488 9489 // Note that we have declared this constructor. 9490 ++ASTContext::NumImplicitMoveConstructorsDeclared; 9491 9492 if (Scope *S = getScopeForContext(ClassDecl)) 9493 PushOnScopeChains(MoveConstructor, S, false); 9494 ClassDecl->addDecl(MoveConstructor); 9495 9496 return MoveConstructor; 9497} 9498 9499void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 9500 CXXConstructorDecl *MoveConstructor) { 9501 assert((MoveConstructor->isDefaulted() && 9502 MoveConstructor->isMoveConstructor() && 9503 !MoveConstructor->doesThisDeclarationHaveABody() && 9504 !MoveConstructor->isDeleted()) && 9505 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 9506 9507 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 9508 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 9509 9510 SynthesizedFunctionScope Scope(*this, MoveConstructor); 9511 DiagnosticErrorTrap Trap(Diags); 9512 9513 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) || 9514 Trap.hasErrorOccurred()) { 9515 Diag(CurrentLocation, diag::note_member_synthesized_at) 9516 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl); 9517 MoveConstructor->setInvalidDecl(); 9518 } else { 9519 Sema::CompoundScopeRAII CompoundScope(*this); 9520 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(), 9521 MoveConstructor->getLocation(), 9522 MultiStmtArg(), 9523 /*isStmtExpr=*/false) 9524 .takeAs<Stmt>()); 9525 MoveConstructor->setImplicitlyDefined(true); 9526 } 9527 9528 MoveConstructor->setUsed(); 9529 9530 if (ASTMutationListener *L = getASTMutationListener()) { 9531 L->CompletedImplicitDefinition(MoveConstructor); 9532 } 9533} 9534 9535bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 9536 return FD->isDeleted() && 9537 (FD->isDefaulted() || FD->isImplicit()) && 9538 isa<CXXMethodDecl>(FD); 9539} 9540 9541/// \brief Mark the call operator of the given lambda closure type as "used". 9542static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) { 9543 CXXMethodDecl *CallOperator 9544 = cast<CXXMethodDecl>( 9545 Lambda->lookup( 9546 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front()); 9547 CallOperator->setReferenced(); 9548 CallOperator->setUsed(); 9549} 9550 9551void Sema::DefineImplicitLambdaToFunctionPointerConversion( 9552 SourceLocation CurrentLocation, 9553 CXXConversionDecl *Conv) 9554{ 9555 CXXRecordDecl *Lambda = Conv->getParent(); 9556 9557 // Make sure that the lambda call operator is marked used. 9558 markLambdaCallOperatorUsed(*this, Lambda); 9559 9560 Conv->setUsed(); 9561 9562 SynthesizedFunctionScope Scope(*this, Conv); 9563 DiagnosticErrorTrap Trap(Diags); 9564 9565 // Return the address of the __invoke function. 9566 DeclarationName InvokeName = &Context.Idents.get("__invoke"); 9567 CXXMethodDecl *Invoke 9568 = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front()); 9569 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(), 9570 VK_LValue, Conv->getLocation()).take(); 9571 assert(FunctionRef && "Can't refer to __invoke function?"); 9572 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take(); 9573 Conv->setBody(new (Context) CompoundStmt(Context, Return, 9574 Conv->getLocation(), 9575 Conv->getLocation())); 9576 9577 // Fill in the __invoke function with a dummy implementation. IR generation 9578 // will fill in the actual details. 9579 Invoke->setUsed(); 9580 Invoke->setReferenced(); 9581 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation())); 9582 9583 if (ASTMutationListener *L = getASTMutationListener()) { 9584 L->CompletedImplicitDefinition(Conv); 9585 L->CompletedImplicitDefinition(Invoke); 9586 } 9587} 9588 9589void Sema::DefineImplicitLambdaToBlockPointerConversion( 9590 SourceLocation CurrentLocation, 9591 CXXConversionDecl *Conv) 9592{ 9593 Conv->setUsed(); 9594 9595 SynthesizedFunctionScope Scope(*this, Conv); 9596 DiagnosticErrorTrap Trap(Diags); 9597 9598 // Copy-initialize the lambda object as needed to capture it. 9599 Expr *This = ActOnCXXThis(CurrentLocation).take(); 9600 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take(); 9601 9602 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 9603 Conv->getLocation(), 9604 Conv, DerefThis); 9605 9606 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 9607 // behavior. Note that only the general conversion function does this 9608 // (since it's unusable otherwise); in the case where we inline the 9609 // block literal, it has block literal lifetime semantics. 9610 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 9611 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 9612 CK_CopyAndAutoreleaseBlockObject, 9613 BuildBlock.get(), 0, VK_RValue); 9614 9615 if (BuildBlock.isInvalid()) { 9616 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 9617 Conv->setInvalidDecl(); 9618 return; 9619 } 9620 9621 // Create the return statement that returns the block from the conversion 9622 // function. 9623 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get()); 9624 if (Return.isInvalid()) { 9625 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 9626 Conv->setInvalidDecl(); 9627 return; 9628 } 9629 9630 // Set the body of the conversion function. 9631 Stmt *ReturnS = Return.take(); 9632 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS, 9633 Conv->getLocation(), 9634 Conv->getLocation())); 9635 9636 // We're done; notify the mutation listener, if any. 9637 if (ASTMutationListener *L = getASTMutationListener()) { 9638 L->CompletedImplicitDefinition(Conv); 9639 } 9640} 9641 9642/// \brief Determine whether the given list arguments contains exactly one 9643/// "real" (non-default) argument. 9644static bool hasOneRealArgument(MultiExprArg Args) { 9645 switch (Args.size()) { 9646 case 0: 9647 return false; 9648 9649 default: 9650 if (!Args[1]->isDefaultArgument()) 9651 return false; 9652 9653 // fall through 9654 case 1: 9655 return !Args[0]->isDefaultArgument(); 9656 } 9657 9658 return false; 9659} 9660 9661ExprResult 9662Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 9663 CXXConstructorDecl *Constructor, 9664 MultiExprArg ExprArgs, 9665 bool HadMultipleCandidates, 9666 bool IsListInitialization, 9667 bool RequiresZeroInit, 9668 unsigned ConstructKind, 9669 SourceRange ParenRange) { 9670 bool Elidable = false; 9671 9672 // C++0x [class.copy]p34: 9673 // When certain criteria are met, an implementation is allowed to 9674 // omit the copy/move construction of a class object, even if the 9675 // copy/move constructor and/or destructor for the object have 9676 // side effects. [...] 9677 // - when a temporary class object that has not been bound to a 9678 // reference (12.2) would be copied/moved to a class object 9679 // with the same cv-unqualified type, the copy/move operation 9680 // can be omitted by constructing the temporary object 9681 // directly into the target of the omitted copy/move 9682 if (ConstructKind == CXXConstructExpr::CK_Complete && 9683 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 9684 Expr *SubExpr = ExprArgs[0]; 9685 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent()); 9686 } 9687 9688 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 9689 Elidable, ExprArgs, HadMultipleCandidates, 9690 IsListInitialization, RequiresZeroInit, 9691 ConstructKind, ParenRange); 9692} 9693 9694/// BuildCXXConstructExpr - Creates a complete call to a constructor, 9695/// including handling of its default argument expressions. 9696ExprResult 9697Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 9698 CXXConstructorDecl *Constructor, bool Elidable, 9699 MultiExprArg ExprArgs, 9700 bool HadMultipleCandidates, 9701 bool IsListInitialization, 9702 bool RequiresZeroInit, 9703 unsigned ConstructKind, 9704 SourceRange ParenRange) { 9705 MarkFunctionReferenced(ConstructLoc, Constructor); 9706 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc, 9707 Constructor, Elidable, ExprArgs, 9708 HadMultipleCandidates, 9709 IsListInitialization, RequiresZeroInit, 9710 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 9711 ParenRange)); 9712} 9713 9714void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 9715 if (VD->isInvalidDecl()) return; 9716 9717 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 9718 if (ClassDecl->isInvalidDecl()) return; 9719 if (ClassDecl->hasIrrelevantDestructor()) return; 9720 if (ClassDecl->isDependentContext()) return; 9721 9722 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 9723 MarkFunctionReferenced(VD->getLocation(), Destructor); 9724 CheckDestructorAccess(VD->getLocation(), Destructor, 9725 PDiag(diag::err_access_dtor_var) 9726 << VD->getDeclName() 9727 << VD->getType()); 9728 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 9729 9730 if (!VD->hasGlobalStorage()) return; 9731 9732 // Emit warning for non-trivial dtor in global scope (a real global, 9733 // class-static, function-static). 9734 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 9735 9736 // TODO: this should be re-enabled for static locals by !CXAAtExit 9737 if (!VD->isStaticLocal()) 9738 Diag(VD->getLocation(), diag::warn_global_destructor); 9739} 9740 9741/// \brief Given a constructor and the set of arguments provided for the 9742/// constructor, convert the arguments and add any required default arguments 9743/// to form a proper call to this constructor. 9744/// 9745/// \returns true if an error occurred, false otherwise. 9746bool 9747Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 9748 MultiExprArg ArgsPtr, 9749 SourceLocation Loc, 9750 SmallVectorImpl<Expr*> &ConvertedArgs, 9751 bool AllowExplicit, 9752 bool IsListInitialization) { 9753 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 9754 unsigned NumArgs = ArgsPtr.size(); 9755 Expr **Args = ArgsPtr.data(); 9756 9757 const FunctionProtoType *Proto 9758 = Constructor->getType()->getAs<FunctionProtoType>(); 9759 assert(Proto && "Constructor without a prototype?"); 9760 unsigned NumArgsInProto = Proto->getNumArgs(); 9761 9762 // If too few arguments are available, we'll fill in the rest with defaults. 9763 if (NumArgs < NumArgsInProto) 9764 ConvertedArgs.reserve(NumArgsInProto); 9765 else 9766 ConvertedArgs.reserve(NumArgs); 9767 9768 VariadicCallType CallType = 9769 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 9770 SmallVector<Expr *, 8> AllArgs; 9771 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 9772 Proto, 0, Args, NumArgs, AllArgs, 9773 CallType, AllowExplicit, 9774 IsListInitialization); 9775 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 9776 9777 DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size()); 9778 9779 CheckConstructorCall(Constructor, 9780 llvm::makeArrayRef<const Expr *>(AllArgs.data(), 9781 AllArgs.size()), 9782 Proto, Loc); 9783 9784 return Invalid; 9785} 9786 9787static inline bool 9788CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 9789 const FunctionDecl *FnDecl) { 9790 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 9791 if (isa<NamespaceDecl>(DC)) { 9792 return SemaRef.Diag(FnDecl->getLocation(), 9793 diag::err_operator_new_delete_declared_in_namespace) 9794 << FnDecl->getDeclName(); 9795 } 9796 9797 if (isa<TranslationUnitDecl>(DC) && 9798 FnDecl->getStorageClass() == SC_Static) { 9799 return SemaRef.Diag(FnDecl->getLocation(), 9800 diag::err_operator_new_delete_declared_static) 9801 << FnDecl->getDeclName(); 9802 } 9803 9804 return false; 9805} 9806 9807static inline bool 9808CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 9809 CanQualType ExpectedResultType, 9810 CanQualType ExpectedFirstParamType, 9811 unsigned DependentParamTypeDiag, 9812 unsigned InvalidParamTypeDiag) { 9813 QualType ResultType = 9814 FnDecl->getType()->getAs<FunctionType>()->getResultType(); 9815 9816 // Check that the result type is not dependent. 9817 if (ResultType->isDependentType()) 9818 return SemaRef.Diag(FnDecl->getLocation(), 9819 diag::err_operator_new_delete_dependent_result_type) 9820 << FnDecl->getDeclName() << ExpectedResultType; 9821 9822 // Check that the result type is what we expect. 9823 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 9824 return SemaRef.Diag(FnDecl->getLocation(), 9825 diag::err_operator_new_delete_invalid_result_type) 9826 << FnDecl->getDeclName() << ExpectedResultType; 9827 9828 // A function template must have at least 2 parameters. 9829 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 9830 return SemaRef.Diag(FnDecl->getLocation(), 9831 diag::err_operator_new_delete_template_too_few_parameters) 9832 << FnDecl->getDeclName(); 9833 9834 // The function decl must have at least 1 parameter. 9835 if (FnDecl->getNumParams() == 0) 9836 return SemaRef.Diag(FnDecl->getLocation(), 9837 diag::err_operator_new_delete_too_few_parameters) 9838 << FnDecl->getDeclName(); 9839 9840 // Check the first parameter type is not dependent. 9841 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 9842 if (FirstParamType->isDependentType()) 9843 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 9844 << FnDecl->getDeclName() << ExpectedFirstParamType; 9845 9846 // Check that the first parameter type is what we expect. 9847 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 9848 ExpectedFirstParamType) 9849 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 9850 << FnDecl->getDeclName() << ExpectedFirstParamType; 9851 9852 return false; 9853} 9854 9855static bool 9856CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 9857 // C++ [basic.stc.dynamic.allocation]p1: 9858 // A program is ill-formed if an allocation function is declared in a 9859 // namespace scope other than global scope or declared static in global 9860 // scope. 9861 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 9862 return true; 9863 9864 CanQualType SizeTy = 9865 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 9866 9867 // C++ [basic.stc.dynamic.allocation]p1: 9868 // The return type shall be void*. The first parameter shall have type 9869 // std::size_t. 9870 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 9871 SizeTy, 9872 diag::err_operator_new_dependent_param_type, 9873 diag::err_operator_new_param_type)) 9874 return true; 9875 9876 // C++ [basic.stc.dynamic.allocation]p1: 9877 // The first parameter shall not have an associated default argument. 9878 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 9879 return SemaRef.Diag(FnDecl->getLocation(), 9880 diag::err_operator_new_default_arg) 9881 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 9882 9883 return false; 9884} 9885 9886static bool 9887CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 9888 // C++ [basic.stc.dynamic.deallocation]p1: 9889 // A program is ill-formed if deallocation functions are declared in a 9890 // namespace scope other than global scope or declared static in global 9891 // scope. 9892 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 9893 return true; 9894 9895 // C++ [basic.stc.dynamic.deallocation]p2: 9896 // Each deallocation function shall return void and its first parameter 9897 // shall be void*. 9898 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 9899 SemaRef.Context.VoidPtrTy, 9900 diag::err_operator_delete_dependent_param_type, 9901 diag::err_operator_delete_param_type)) 9902 return true; 9903 9904 return false; 9905} 9906 9907/// CheckOverloadedOperatorDeclaration - Check whether the declaration 9908/// of this overloaded operator is well-formed. If so, returns false; 9909/// otherwise, emits appropriate diagnostics and returns true. 9910bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 9911 assert(FnDecl && FnDecl->isOverloadedOperator() && 9912 "Expected an overloaded operator declaration"); 9913 9914 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 9915 9916 // C++ [over.oper]p5: 9917 // The allocation and deallocation functions, operator new, 9918 // operator new[], operator delete and operator delete[], are 9919 // described completely in 3.7.3. The attributes and restrictions 9920 // found in the rest of this subclause do not apply to them unless 9921 // explicitly stated in 3.7.3. 9922 if (Op == OO_Delete || Op == OO_Array_Delete) 9923 return CheckOperatorDeleteDeclaration(*this, FnDecl); 9924 9925 if (Op == OO_New || Op == OO_Array_New) 9926 return CheckOperatorNewDeclaration(*this, FnDecl); 9927 9928 // C++ [over.oper]p6: 9929 // An operator function shall either be a non-static member 9930 // function or be a non-member function and have at least one 9931 // parameter whose type is a class, a reference to a class, an 9932 // enumeration, or a reference to an enumeration. 9933 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 9934 if (MethodDecl->isStatic()) 9935 return Diag(FnDecl->getLocation(), 9936 diag::err_operator_overload_static) << FnDecl->getDeclName(); 9937 } else { 9938 bool ClassOrEnumParam = false; 9939 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 9940 ParamEnd = FnDecl->param_end(); 9941 Param != ParamEnd; ++Param) { 9942 QualType ParamType = (*Param)->getType().getNonReferenceType(); 9943 if (ParamType->isDependentType() || ParamType->isRecordType() || 9944 ParamType->isEnumeralType()) { 9945 ClassOrEnumParam = true; 9946 break; 9947 } 9948 } 9949 9950 if (!ClassOrEnumParam) 9951 return Diag(FnDecl->getLocation(), 9952 diag::err_operator_overload_needs_class_or_enum) 9953 << FnDecl->getDeclName(); 9954 } 9955 9956 // C++ [over.oper]p8: 9957 // An operator function cannot have default arguments (8.3.6), 9958 // except where explicitly stated below. 9959 // 9960 // Only the function-call operator allows default arguments 9961 // (C++ [over.call]p1). 9962 if (Op != OO_Call) { 9963 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(); 9964 Param != FnDecl->param_end(); ++Param) { 9965 if ((*Param)->hasDefaultArg()) 9966 return Diag((*Param)->getLocation(), 9967 diag::err_operator_overload_default_arg) 9968 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange(); 9969 } 9970 } 9971 9972 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 9973 { false, false, false } 9974#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 9975 , { Unary, Binary, MemberOnly } 9976#include "clang/Basic/OperatorKinds.def" 9977 }; 9978 9979 bool CanBeUnaryOperator = OperatorUses[Op][0]; 9980 bool CanBeBinaryOperator = OperatorUses[Op][1]; 9981 bool MustBeMemberOperator = OperatorUses[Op][2]; 9982 9983 // C++ [over.oper]p8: 9984 // [...] Operator functions cannot have more or fewer parameters 9985 // than the number required for the corresponding operator, as 9986 // described in the rest of this subclause. 9987 unsigned NumParams = FnDecl->getNumParams() 9988 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 9989 if (Op != OO_Call && 9990 ((NumParams == 1 && !CanBeUnaryOperator) || 9991 (NumParams == 2 && !CanBeBinaryOperator) || 9992 (NumParams < 1) || (NumParams > 2))) { 9993 // We have the wrong number of parameters. 9994 unsigned ErrorKind; 9995 if (CanBeUnaryOperator && CanBeBinaryOperator) { 9996 ErrorKind = 2; // 2 -> unary or binary. 9997 } else if (CanBeUnaryOperator) { 9998 ErrorKind = 0; // 0 -> unary 9999 } else { 10000 assert(CanBeBinaryOperator && 10001 "All non-call overloaded operators are unary or binary!"); 10002 ErrorKind = 1; // 1 -> binary 10003 } 10004 10005 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 10006 << FnDecl->getDeclName() << NumParams << ErrorKind; 10007 } 10008 10009 // Overloaded operators other than operator() cannot be variadic. 10010 if (Op != OO_Call && 10011 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 10012 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 10013 << FnDecl->getDeclName(); 10014 } 10015 10016 // Some operators must be non-static member functions. 10017 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 10018 return Diag(FnDecl->getLocation(), 10019 diag::err_operator_overload_must_be_member) 10020 << FnDecl->getDeclName(); 10021 } 10022 10023 // C++ [over.inc]p1: 10024 // The user-defined function called operator++ implements the 10025 // prefix and postfix ++ operator. If this function is a member 10026 // function with no parameters, or a non-member function with one 10027 // parameter of class or enumeration type, it defines the prefix 10028 // increment operator ++ for objects of that type. If the function 10029 // is a member function with one parameter (which shall be of type 10030 // int) or a non-member function with two parameters (the second 10031 // of which shall be of type int), it defines the postfix 10032 // increment operator ++ for objects of that type. 10033 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 10034 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 10035 bool ParamIsInt = false; 10036 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>()) 10037 ParamIsInt = BT->getKind() == BuiltinType::Int; 10038 10039 if (!ParamIsInt) 10040 return Diag(LastParam->getLocation(), 10041 diag::err_operator_overload_post_incdec_must_be_int) 10042 << LastParam->getType() << (Op == OO_MinusMinus); 10043 } 10044 10045 return false; 10046} 10047 10048/// CheckLiteralOperatorDeclaration - Check whether the declaration 10049/// of this literal operator function is well-formed. If so, returns 10050/// false; otherwise, emits appropriate diagnostics and returns true. 10051bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 10052 if (isa<CXXMethodDecl>(FnDecl)) { 10053 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 10054 << FnDecl->getDeclName(); 10055 return true; 10056 } 10057 10058 if (FnDecl->isExternC()) { 10059 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 10060 return true; 10061 } 10062 10063 bool Valid = false; 10064 10065 // This might be the definition of a literal operator template. 10066 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 10067 // This might be a specialization of a literal operator template. 10068 if (!TpDecl) 10069 TpDecl = FnDecl->getPrimaryTemplate(); 10070 10071 // template <char...> type operator "" name() is the only valid template 10072 // signature, and the only valid signature with no parameters. 10073 if (TpDecl) { 10074 if (FnDecl->param_size() == 0) { 10075 // Must have only one template parameter 10076 TemplateParameterList *Params = TpDecl->getTemplateParameters(); 10077 if (Params->size() == 1) { 10078 NonTypeTemplateParmDecl *PmDecl = 10079 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0)); 10080 10081 // The template parameter must be a char parameter pack. 10082 if (PmDecl && PmDecl->isTemplateParameterPack() && 10083 Context.hasSameType(PmDecl->getType(), Context.CharTy)) 10084 Valid = true; 10085 } 10086 } 10087 } else if (FnDecl->param_size()) { 10088 // Check the first parameter 10089 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 10090 10091 QualType T = (*Param)->getType().getUnqualifiedType(); 10092 10093 // unsigned long long int, long double, and any character type are allowed 10094 // as the only parameters. 10095 if (Context.hasSameType(T, Context.UnsignedLongLongTy) || 10096 Context.hasSameType(T, Context.LongDoubleTy) || 10097 Context.hasSameType(T, Context.CharTy) || 10098 Context.hasSameType(T, Context.WCharTy) || 10099 Context.hasSameType(T, Context.Char16Ty) || 10100 Context.hasSameType(T, Context.Char32Ty)) { 10101 if (++Param == FnDecl->param_end()) 10102 Valid = true; 10103 goto FinishedParams; 10104 } 10105 10106 // Otherwise it must be a pointer to const; let's strip those qualifiers. 10107 const PointerType *PT = T->getAs<PointerType>(); 10108 if (!PT) 10109 goto FinishedParams; 10110 T = PT->getPointeeType(); 10111 if (!T.isConstQualified() || T.isVolatileQualified()) 10112 goto FinishedParams; 10113 T = T.getUnqualifiedType(); 10114 10115 // Move on to the second parameter; 10116 ++Param; 10117 10118 // If there is no second parameter, the first must be a const char * 10119 if (Param == FnDecl->param_end()) { 10120 if (Context.hasSameType(T, Context.CharTy)) 10121 Valid = true; 10122 goto FinishedParams; 10123 } 10124 10125 // const char *, const wchar_t*, const char16_t*, and const char32_t* 10126 // are allowed as the first parameter to a two-parameter function 10127 if (!(Context.hasSameType(T, Context.CharTy) || 10128 Context.hasSameType(T, Context.WCharTy) || 10129 Context.hasSameType(T, Context.Char16Ty) || 10130 Context.hasSameType(T, Context.Char32Ty))) 10131 goto FinishedParams; 10132 10133 // The second and final parameter must be an std::size_t 10134 T = (*Param)->getType().getUnqualifiedType(); 10135 if (Context.hasSameType(T, Context.getSizeType()) && 10136 ++Param == FnDecl->param_end()) 10137 Valid = true; 10138 } 10139 10140 // FIXME: This diagnostic is absolutely terrible. 10141FinishedParams: 10142 if (!Valid) { 10143 Diag(FnDecl->getLocation(), diag::err_literal_operator_params) 10144 << FnDecl->getDeclName(); 10145 return true; 10146 } 10147 10148 // A parameter-declaration-clause containing a default argument is not 10149 // equivalent to any of the permitted forms. 10150 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 10151 ParamEnd = FnDecl->param_end(); 10152 Param != ParamEnd; ++Param) { 10153 if ((*Param)->hasDefaultArg()) { 10154 Diag((*Param)->getDefaultArgRange().getBegin(), 10155 diag::err_literal_operator_default_argument) 10156 << (*Param)->getDefaultArgRange(); 10157 break; 10158 } 10159 } 10160 10161 StringRef LiteralName 10162 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 10163 if (LiteralName[0] != '_') { 10164 // C++11 [usrlit.suffix]p1: 10165 // Literal suffix identifiers that do not start with an underscore 10166 // are reserved for future standardization. 10167 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved); 10168 } 10169 10170 return false; 10171} 10172 10173/// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 10174/// linkage specification, including the language and (if present) 10175/// the '{'. ExternLoc is the location of the 'extern', LangLoc is 10176/// the location of the language string literal, which is provided 10177/// by Lang/StrSize. LBraceLoc, if valid, provides the location of 10178/// the '{' brace. Otherwise, this linkage specification does not 10179/// have any braces. 10180Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 10181 SourceLocation LangLoc, 10182 StringRef Lang, 10183 SourceLocation LBraceLoc) { 10184 LinkageSpecDecl::LanguageIDs Language; 10185 if (Lang == "\"C\"") 10186 Language = LinkageSpecDecl::lang_c; 10187 else if (Lang == "\"C++\"") 10188 Language = LinkageSpecDecl::lang_cxx; 10189 else { 10190 Diag(LangLoc, diag::err_bad_language); 10191 return 0; 10192 } 10193 10194 // FIXME: Add all the various semantics of linkage specifications 10195 10196 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, 10197 ExternLoc, LangLoc, Language); 10198 CurContext->addDecl(D); 10199 PushDeclContext(S, D); 10200 return D; 10201} 10202 10203/// ActOnFinishLinkageSpecification - Complete the definition of 10204/// the C++ linkage specification LinkageSpec. If RBraceLoc is 10205/// valid, it's the position of the closing '}' brace in a linkage 10206/// specification that uses braces. 10207Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 10208 Decl *LinkageSpec, 10209 SourceLocation RBraceLoc) { 10210 if (LinkageSpec) { 10211 if (RBraceLoc.isValid()) { 10212 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 10213 LSDecl->setRBraceLoc(RBraceLoc); 10214 } 10215 PopDeclContext(); 10216 } 10217 return LinkageSpec; 10218} 10219 10220Decl *Sema::ActOnEmptyDeclaration(Scope *S, 10221 AttributeList *AttrList, 10222 SourceLocation SemiLoc) { 10223 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 10224 // Attribute declarations appertain to empty declaration so we handle 10225 // them here. 10226 if (AttrList) 10227 ProcessDeclAttributeList(S, ED, AttrList); 10228 10229 CurContext->addDecl(ED); 10230 return ED; 10231} 10232 10233/// \brief Perform semantic analysis for the variable declaration that 10234/// occurs within a C++ catch clause, returning the newly-created 10235/// variable. 10236VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 10237 TypeSourceInfo *TInfo, 10238 SourceLocation StartLoc, 10239 SourceLocation Loc, 10240 IdentifierInfo *Name) { 10241 bool Invalid = false; 10242 QualType ExDeclType = TInfo->getType(); 10243 10244 // Arrays and functions decay. 10245 if (ExDeclType->isArrayType()) 10246 ExDeclType = Context.getArrayDecayedType(ExDeclType); 10247 else if (ExDeclType->isFunctionType()) 10248 ExDeclType = Context.getPointerType(ExDeclType); 10249 10250 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 10251 // The exception-declaration shall not denote a pointer or reference to an 10252 // incomplete type, other than [cv] void*. 10253 // N2844 forbids rvalue references. 10254 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 10255 Diag(Loc, diag::err_catch_rvalue_ref); 10256 Invalid = true; 10257 } 10258 10259 QualType BaseType = ExDeclType; 10260 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 10261 unsigned DK = diag::err_catch_incomplete; 10262 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 10263 BaseType = Ptr->getPointeeType(); 10264 Mode = 1; 10265 DK = diag::err_catch_incomplete_ptr; 10266 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 10267 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 10268 BaseType = Ref->getPointeeType(); 10269 Mode = 2; 10270 DK = diag::err_catch_incomplete_ref; 10271 } 10272 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 10273 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 10274 Invalid = true; 10275 10276 if (!Invalid && !ExDeclType->isDependentType() && 10277 RequireNonAbstractType(Loc, ExDeclType, 10278 diag::err_abstract_type_in_decl, 10279 AbstractVariableType)) 10280 Invalid = true; 10281 10282 // Only the non-fragile NeXT runtime currently supports C++ catches 10283 // of ObjC types, and no runtime supports catching ObjC types by value. 10284 if (!Invalid && getLangOpts().ObjC1) { 10285 QualType T = ExDeclType; 10286 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 10287 T = RT->getPointeeType(); 10288 10289 if (T->isObjCObjectType()) { 10290 Diag(Loc, diag::err_objc_object_catch); 10291 Invalid = true; 10292 } else if (T->isObjCObjectPointerType()) { 10293 // FIXME: should this be a test for macosx-fragile specifically? 10294 if (getLangOpts().ObjCRuntime.isFragile()) 10295 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 10296 } 10297 } 10298 10299 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 10300 ExDeclType, TInfo, SC_None); 10301 ExDecl->setExceptionVariable(true); 10302 10303 // In ARC, infer 'retaining' for variables of retainable type. 10304 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 10305 Invalid = true; 10306 10307 if (!Invalid && !ExDeclType->isDependentType()) { 10308 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 10309 // Insulate this from anything else we might currently be parsing. 10310 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 10311 10312 // C++ [except.handle]p16: 10313 // The object declared in an exception-declaration or, if the 10314 // exception-declaration does not specify a name, a temporary (12.2) is 10315 // copy-initialized (8.5) from the exception object. [...] 10316 // The object is destroyed when the handler exits, after the destruction 10317 // of any automatic objects initialized within the handler. 10318 // 10319 // We just pretend to initialize the object with itself, then make sure 10320 // it can be destroyed later. 10321 QualType initType = ExDeclType; 10322 10323 InitializedEntity entity = 10324 InitializedEntity::InitializeVariable(ExDecl); 10325 InitializationKind initKind = 10326 InitializationKind::CreateCopy(Loc, SourceLocation()); 10327 10328 Expr *opaqueValue = 10329 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 10330 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1); 10331 ExprResult result = sequence.Perform(*this, entity, initKind, 10332 MultiExprArg(&opaqueValue, 1)); 10333 if (result.isInvalid()) 10334 Invalid = true; 10335 else { 10336 // If the constructor used was non-trivial, set this as the 10337 // "initializer". 10338 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take()); 10339 if (!construct->getConstructor()->isTrivial()) { 10340 Expr *init = MaybeCreateExprWithCleanups(construct); 10341 ExDecl->setInit(init); 10342 } 10343 10344 // And make sure it's destructable. 10345 FinalizeVarWithDestructor(ExDecl, recordType); 10346 } 10347 } 10348 } 10349 10350 if (Invalid) 10351 ExDecl->setInvalidDecl(); 10352 10353 return ExDecl; 10354} 10355 10356/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 10357/// handler. 10358Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 10359 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 10360 bool Invalid = D.isInvalidType(); 10361 10362 // Check for unexpanded parameter packs. 10363 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 10364 UPPC_ExceptionType)) { 10365 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 10366 D.getIdentifierLoc()); 10367 Invalid = true; 10368 } 10369 10370 IdentifierInfo *II = D.getIdentifier(); 10371 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 10372 LookupOrdinaryName, 10373 ForRedeclaration)) { 10374 // The scope should be freshly made just for us. There is just no way 10375 // it contains any previous declaration. 10376 assert(!S->isDeclScope(PrevDecl)); 10377 if (PrevDecl->isTemplateParameter()) { 10378 // Maybe we will complain about the shadowed template parameter. 10379 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 10380 PrevDecl = 0; 10381 } 10382 } 10383 10384 if (D.getCXXScopeSpec().isSet() && !Invalid) { 10385 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 10386 << D.getCXXScopeSpec().getRange(); 10387 Invalid = true; 10388 } 10389 10390 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 10391 D.getLocStart(), 10392 D.getIdentifierLoc(), 10393 D.getIdentifier()); 10394 if (Invalid) 10395 ExDecl->setInvalidDecl(); 10396 10397 // Add the exception declaration into this scope. 10398 if (II) 10399 PushOnScopeChains(ExDecl, S); 10400 else 10401 CurContext->addDecl(ExDecl); 10402 10403 ProcessDeclAttributes(S, ExDecl, D); 10404 return ExDecl; 10405} 10406 10407Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 10408 Expr *AssertExpr, 10409 Expr *AssertMessageExpr, 10410 SourceLocation RParenLoc) { 10411 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr); 10412 10413 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 10414 return 0; 10415 10416 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 10417 AssertMessage, RParenLoc, false); 10418} 10419 10420Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 10421 Expr *AssertExpr, 10422 StringLiteral *AssertMessage, 10423 SourceLocation RParenLoc, 10424 bool Failed) { 10425 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 10426 !Failed) { 10427 // In a static_assert-declaration, the constant-expression shall be a 10428 // constant expression that can be contextually converted to bool. 10429 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 10430 if (Converted.isInvalid()) 10431 Failed = true; 10432 10433 llvm::APSInt Cond; 10434 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 10435 diag::err_static_assert_expression_is_not_constant, 10436 /*AllowFold=*/false).isInvalid()) 10437 Failed = true; 10438 10439 if (!Failed && !Cond) { 10440 SmallString<256> MsgBuffer; 10441 llvm::raw_svector_ostream Msg(MsgBuffer); 10442 AssertMessage->printPretty(Msg, 0, getPrintingPolicy()); 10443 Diag(StaticAssertLoc, diag::err_static_assert_failed) 10444 << Msg.str() << AssertExpr->getSourceRange(); 10445 Failed = true; 10446 } 10447 } 10448 10449 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 10450 AssertExpr, AssertMessage, RParenLoc, 10451 Failed); 10452 10453 CurContext->addDecl(Decl); 10454 return Decl; 10455} 10456 10457/// \brief Perform semantic analysis of the given friend type declaration. 10458/// 10459/// \returns A friend declaration that. 10460FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 10461 SourceLocation FriendLoc, 10462 TypeSourceInfo *TSInfo) { 10463 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 10464 10465 QualType T = TSInfo->getType(); 10466 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 10467 10468 // C++03 [class.friend]p2: 10469 // An elaborated-type-specifier shall be used in a friend declaration 10470 // for a class.* 10471 // 10472 // * The class-key of the elaborated-type-specifier is required. 10473 if (!ActiveTemplateInstantiations.empty()) { 10474 // Do not complain about the form of friend template types during 10475 // template instantiation; we will already have complained when the 10476 // template was declared. 10477 } else { 10478 if (!T->isElaboratedTypeSpecifier()) { 10479 // If we evaluated the type to a record type, suggest putting 10480 // a tag in front. 10481 if (const RecordType *RT = T->getAs<RecordType>()) { 10482 RecordDecl *RD = RT->getDecl(); 10483 10484 std::string InsertionText = std::string(" ") + RD->getKindName(); 10485 10486 Diag(TypeRange.getBegin(), 10487 getLangOpts().CPlusPlus11 ? 10488 diag::warn_cxx98_compat_unelaborated_friend_type : 10489 diag::ext_unelaborated_friend_type) 10490 << (unsigned) RD->getTagKind() 10491 << T 10492 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc), 10493 InsertionText); 10494 } else { 10495 Diag(FriendLoc, 10496 getLangOpts().CPlusPlus11 ? 10497 diag::warn_cxx98_compat_nonclass_type_friend : 10498 diag::ext_nonclass_type_friend) 10499 << T 10500 << TypeRange; 10501 } 10502 } else if (T->getAs<EnumType>()) { 10503 Diag(FriendLoc, 10504 getLangOpts().CPlusPlus11 ? 10505 diag::warn_cxx98_compat_enum_friend : 10506 diag::ext_enum_friend) 10507 << T 10508 << TypeRange; 10509 } 10510 10511 // C++11 [class.friend]p3: 10512 // A friend declaration that does not declare a function shall have one 10513 // of the following forms: 10514 // friend elaborated-type-specifier ; 10515 // friend simple-type-specifier ; 10516 // friend typename-specifier ; 10517 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 10518 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 10519 } 10520 10521 // If the type specifier in a friend declaration designates a (possibly 10522 // cv-qualified) class type, that class is declared as a friend; otherwise, 10523 // the friend declaration is ignored. 10524 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc); 10525} 10526 10527/// Handle a friend tag declaration where the scope specifier was 10528/// templated. 10529Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 10530 unsigned TagSpec, SourceLocation TagLoc, 10531 CXXScopeSpec &SS, 10532 IdentifierInfo *Name, 10533 SourceLocation NameLoc, 10534 AttributeList *Attr, 10535 MultiTemplateParamsArg TempParamLists) { 10536 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 10537 10538 bool isExplicitSpecialization = false; 10539 bool Invalid = false; 10540 10541 if (TemplateParameterList *TemplateParams 10542 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS, 10543 TempParamLists.data(), 10544 TempParamLists.size(), 10545 /*friend*/ true, 10546 isExplicitSpecialization, 10547 Invalid)) { 10548 if (TemplateParams->size() > 0) { 10549 // This is a declaration of a class template. 10550 if (Invalid) 10551 return 0; 10552 10553 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, 10554 SS, Name, NameLoc, Attr, 10555 TemplateParams, AS_public, 10556 /*ModulePrivateLoc=*/SourceLocation(), 10557 TempParamLists.size() - 1, 10558 TempParamLists.data()).take(); 10559 } else { 10560 // The "template<>" header is extraneous. 10561 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 10562 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 10563 isExplicitSpecialization = true; 10564 } 10565 } 10566 10567 if (Invalid) return 0; 10568 10569 bool isAllExplicitSpecializations = true; 10570 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 10571 if (TempParamLists[I]->size()) { 10572 isAllExplicitSpecializations = false; 10573 break; 10574 } 10575 } 10576 10577 // FIXME: don't ignore attributes. 10578 10579 // If it's explicit specializations all the way down, just forget 10580 // about the template header and build an appropriate non-templated 10581 // friend. TODO: for source fidelity, remember the headers. 10582 if (isAllExplicitSpecializations) { 10583 if (SS.isEmpty()) { 10584 bool Owned = false; 10585 bool IsDependent = false; 10586 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 10587 Attr, AS_public, 10588 /*ModulePrivateLoc=*/SourceLocation(), 10589 MultiTemplateParamsArg(), Owned, IsDependent, 10590 /*ScopedEnumKWLoc=*/SourceLocation(), 10591 /*ScopedEnumUsesClassTag=*/false, 10592 /*UnderlyingType=*/TypeResult()); 10593 } 10594 10595 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 10596 ElaboratedTypeKeyword Keyword 10597 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 10598 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 10599 *Name, NameLoc); 10600 if (T.isNull()) 10601 return 0; 10602 10603 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 10604 if (isa<DependentNameType>(T)) { 10605 DependentNameTypeLoc TL = 10606 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 10607 TL.setElaboratedKeywordLoc(TagLoc); 10608 TL.setQualifierLoc(QualifierLoc); 10609 TL.setNameLoc(NameLoc); 10610 } else { 10611 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 10612 TL.setElaboratedKeywordLoc(TagLoc); 10613 TL.setQualifierLoc(QualifierLoc); 10614 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 10615 } 10616 10617 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 10618 TSI, FriendLoc, TempParamLists); 10619 Friend->setAccess(AS_public); 10620 CurContext->addDecl(Friend); 10621 return Friend; 10622 } 10623 10624 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 10625 10626 10627 10628 // Handle the case of a templated-scope friend class. e.g. 10629 // template <class T> class A<T>::B; 10630 // FIXME: we don't support these right now. 10631 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 10632 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 10633 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 10634 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 10635 TL.setElaboratedKeywordLoc(TagLoc); 10636 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 10637 TL.setNameLoc(NameLoc); 10638 10639 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 10640 TSI, FriendLoc, TempParamLists); 10641 Friend->setAccess(AS_public); 10642 Friend->setUnsupportedFriend(true); 10643 CurContext->addDecl(Friend); 10644 return Friend; 10645} 10646 10647 10648/// Handle a friend type declaration. This works in tandem with 10649/// ActOnTag. 10650/// 10651/// Notes on friend class templates: 10652/// 10653/// We generally treat friend class declarations as if they were 10654/// declaring a class. So, for example, the elaborated type specifier 10655/// in a friend declaration is required to obey the restrictions of a 10656/// class-head (i.e. no typedefs in the scope chain), template 10657/// parameters are required to match up with simple template-ids, &c. 10658/// However, unlike when declaring a template specialization, it's 10659/// okay to refer to a template specialization without an empty 10660/// template parameter declaration, e.g. 10661/// friend class A<T>::B<unsigned>; 10662/// We permit this as a special case; if there are any template 10663/// parameters present at all, require proper matching, i.e. 10664/// template <> template \<class T> friend class A<int>::B; 10665Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 10666 MultiTemplateParamsArg TempParams) { 10667 SourceLocation Loc = DS.getLocStart(); 10668 10669 assert(DS.isFriendSpecified()); 10670 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 10671 10672 // Try to convert the decl specifier to a type. This works for 10673 // friend templates because ActOnTag never produces a ClassTemplateDecl 10674 // for a TUK_Friend. 10675 Declarator TheDeclarator(DS, Declarator::MemberContext); 10676 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 10677 QualType T = TSI->getType(); 10678 if (TheDeclarator.isInvalidType()) 10679 return 0; 10680 10681 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 10682 return 0; 10683 10684 // This is definitely an error in C++98. It's probably meant to 10685 // be forbidden in C++0x, too, but the specification is just 10686 // poorly written. 10687 // 10688 // The problem is with declarations like the following: 10689 // template <T> friend A<T>::foo; 10690 // where deciding whether a class C is a friend or not now hinges 10691 // on whether there exists an instantiation of A that causes 10692 // 'foo' to equal C. There are restrictions on class-heads 10693 // (which we declare (by fiat) elaborated friend declarations to 10694 // be) that makes this tractable. 10695 // 10696 // FIXME: handle "template <> friend class A<T>;", which 10697 // is possibly well-formed? Who even knows? 10698 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 10699 Diag(Loc, diag::err_tagless_friend_type_template) 10700 << DS.getSourceRange(); 10701 return 0; 10702 } 10703 10704 // C++98 [class.friend]p1: A friend of a class is a function 10705 // or class that is not a member of the class . . . 10706 // This is fixed in DR77, which just barely didn't make the C++03 10707 // deadline. It's also a very silly restriction that seriously 10708 // affects inner classes and which nobody else seems to implement; 10709 // thus we never diagnose it, not even in -pedantic. 10710 // 10711 // But note that we could warn about it: it's always useless to 10712 // friend one of your own members (it's not, however, worthless to 10713 // friend a member of an arbitrary specialization of your template). 10714 10715 Decl *D; 10716 if (unsigned NumTempParamLists = TempParams.size()) 10717 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 10718 NumTempParamLists, 10719 TempParams.data(), 10720 TSI, 10721 DS.getFriendSpecLoc()); 10722 else 10723 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 10724 10725 if (!D) 10726 return 0; 10727 10728 D->setAccess(AS_public); 10729 CurContext->addDecl(D); 10730 10731 return D; 10732} 10733 10734NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 10735 MultiTemplateParamsArg TemplateParams) { 10736 const DeclSpec &DS = D.getDeclSpec(); 10737 10738 assert(DS.isFriendSpecified()); 10739 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 10740 10741 SourceLocation Loc = D.getIdentifierLoc(); 10742 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 10743 10744 // C++ [class.friend]p1 10745 // A friend of a class is a function or class.... 10746 // Note that this sees through typedefs, which is intended. 10747 // It *doesn't* see through dependent types, which is correct 10748 // according to [temp.arg.type]p3: 10749 // If a declaration acquires a function type through a 10750 // type dependent on a template-parameter and this causes 10751 // a declaration that does not use the syntactic form of a 10752 // function declarator to have a function type, the program 10753 // is ill-formed. 10754 if (!TInfo->getType()->isFunctionType()) { 10755 Diag(Loc, diag::err_unexpected_friend); 10756 10757 // It might be worthwhile to try to recover by creating an 10758 // appropriate declaration. 10759 return 0; 10760 } 10761 10762 // C++ [namespace.memdef]p3 10763 // - If a friend declaration in a non-local class first declares a 10764 // class or function, the friend class or function is a member 10765 // of the innermost enclosing namespace. 10766 // - The name of the friend is not found by simple name lookup 10767 // until a matching declaration is provided in that namespace 10768 // scope (either before or after the class declaration granting 10769 // friendship). 10770 // - If a friend function is called, its name may be found by the 10771 // name lookup that considers functions from namespaces and 10772 // classes associated with the types of the function arguments. 10773 // - When looking for a prior declaration of a class or a function 10774 // declared as a friend, scopes outside the innermost enclosing 10775 // namespace scope are not considered. 10776 10777 CXXScopeSpec &SS = D.getCXXScopeSpec(); 10778 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 10779 DeclarationName Name = NameInfo.getName(); 10780 assert(Name); 10781 10782 // Check for unexpanded parameter packs. 10783 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 10784 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 10785 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 10786 return 0; 10787 10788 // The context we found the declaration in, or in which we should 10789 // create the declaration. 10790 DeclContext *DC; 10791 Scope *DCScope = S; 10792 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 10793 ForRedeclaration); 10794 10795 // FIXME: there are different rules in local classes 10796 10797 // There are four cases here. 10798 // - There's no scope specifier, in which case we just go to the 10799 // appropriate scope and look for a function or function template 10800 // there as appropriate. 10801 // Recover from invalid scope qualifiers as if they just weren't there. 10802 if (SS.isInvalid() || !SS.isSet()) { 10803 // C++0x [namespace.memdef]p3: 10804 // If the name in a friend declaration is neither qualified nor 10805 // a template-id and the declaration is a function or an 10806 // elaborated-type-specifier, the lookup to determine whether 10807 // the entity has been previously declared shall not consider 10808 // any scopes outside the innermost enclosing namespace. 10809 // C++0x [class.friend]p11: 10810 // If a friend declaration appears in a local class and the name 10811 // specified is an unqualified name, a prior declaration is 10812 // looked up without considering scopes that are outside the 10813 // innermost enclosing non-class scope. For a friend function 10814 // declaration, if there is no prior declaration, the program is 10815 // ill-formed. 10816 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass(); 10817 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 10818 10819 // Find the appropriate context according to the above. 10820 DC = CurContext; 10821 while (true) { 10822 // Skip class contexts. If someone can cite chapter and verse 10823 // for this behavior, that would be nice --- it's what GCC and 10824 // EDG do, and it seems like a reasonable intent, but the spec 10825 // really only says that checks for unqualified existing 10826 // declarations should stop at the nearest enclosing namespace, 10827 // not that they should only consider the nearest enclosing 10828 // namespace. 10829 while (DC->isRecord() || DC->isTransparentContext()) 10830 DC = DC->getParent(); 10831 10832 LookupQualifiedName(Previous, DC); 10833 10834 // TODO: decide what we think about using declarations. 10835 if (isLocal || !Previous.empty()) 10836 break; 10837 10838 if (isTemplateId) { 10839 if (isa<TranslationUnitDecl>(DC)) break; 10840 } else { 10841 if (DC->isFileContext()) break; 10842 } 10843 DC = DC->getParent(); 10844 } 10845 10846 DCScope = getScopeForDeclContext(S, DC); 10847 10848 // C++ [class.friend]p6: 10849 // A function can be defined in a friend declaration of a class if and 10850 // only if the class is a non-local class (9.8), the function name is 10851 // unqualified, and the function has namespace scope. 10852 if (isLocal && D.isFunctionDefinition()) { 10853 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 10854 } 10855 10856 // - There's a non-dependent scope specifier, in which case we 10857 // compute it and do a previous lookup there for a function 10858 // or function template. 10859 } else if (!SS.getScopeRep()->isDependent()) { 10860 DC = computeDeclContext(SS); 10861 if (!DC) return 0; 10862 10863 if (RequireCompleteDeclContext(SS, DC)) return 0; 10864 10865 LookupQualifiedName(Previous, DC); 10866 10867 // Ignore things found implicitly in the wrong scope. 10868 // TODO: better diagnostics for this case. Suggesting the right 10869 // qualified scope would be nice... 10870 LookupResult::Filter F = Previous.makeFilter(); 10871 while (F.hasNext()) { 10872 NamedDecl *D = F.next(); 10873 if (!DC->InEnclosingNamespaceSetOf( 10874 D->getDeclContext()->getRedeclContext())) 10875 F.erase(); 10876 } 10877 F.done(); 10878 10879 if (Previous.empty()) { 10880 D.setInvalidType(); 10881 Diag(Loc, diag::err_qualified_friend_not_found) 10882 << Name << TInfo->getType(); 10883 return 0; 10884 } 10885 10886 // C++ [class.friend]p1: A friend of a class is a function or 10887 // class that is not a member of the class . . . 10888 if (DC->Equals(CurContext)) 10889 Diag(DS.getFriendSpecLoc(), 10890 getLangOpts().CPlusPlus11 ? 10891 diag::warn_cxx98_compat_friend_is_member : 10892 diag::err_friend_is_member); 10893 10894 if (D.isFunctionDefinition()) { 10895 // C++ [class.friend]p6: 10896 // A function can be defined in a friend declaration of a class if and 10897 // only if the class is a non-local class (9.8), the function name is 10898 // unqualified, and the function has namespace scope. 10899 SemaDiagnosticBuilder DB 10900 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 10901 10902 DB << SS.getScopeRep(); 10903 if (DC->isFileContext()) 10904 DB << FixItHint::CreateRemoval(SS.getRange()); 10905 SS.clear(); 10906 } 10907 10908 // - There's a scope specifier that does not match any template 10909 // parameter lists, in which case we use some arbitrary context, 10910 // create a method or method template, and wait for instantiation. 10911 // - There's a scope specifier that does match some template 10912 // parameter lists, which we don't handle right now. 10913 } else { 10914 if (D.isFunctionDefinition()) { 10915 // C++ [class.friend]p6: 10916 // A function can be defined in a friend declaration of a class if and 10917 // only if the class is a non-local class (9.8), the function name is 10918 // unqualified, and the function has namespace scope. 10919 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 10920 << SS.getScopeRep(); 10921 } 10922 10923 DC = CurContext; 10924 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 10925 } 10926 10927 if (!DC->isRecord()) { 10928 // This implies that it has to be an operator or function. 10929 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName || 10930 D.getName().getKind() == UnqualifiedId::IK_DestructorName || 10931 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) { 10932 Diag(Loc, diag::err_introducing_special_friend) << 10933 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 : 10934 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2); 10935 return 0; 10936 } 10937 } 10938 10939 // FIXME: This is an egregious hack to cope with cases where the scope stack 10940 // does not contain the declaration context, i.e., in an out-of-line 10941 // definition of a class. 10942 Scope FakeDCScope(S, Scope::DeclScope, Diags); 10943 if (!DCScope) { 10944 FakeDCScope.setEntity(DC); 10945 DCScope = &FakeDCScope; 10946 } 10947 10948 bool AddToScope = true; 10949 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 10950 TemplateParams, AddToScope); 10951 if (!ND) return 0; 10952 10953 assert(ND->getDeclContext() == DC); 10954 assert(ND->getLexicalDeclContext() == CurContext); 10955 10956 // Add the function declaration to the appropriate lookup tables, 10957 // adjusting the redeclarations list as necessary. We don't 10958 // want to do this yet if the friending class is dependent. 10959 // 10960 // Also update the scope-based lookup if the target context's 10961 // lookup context is in lexical scope. 10962 if (!CurContext->isDependentContext()) { 10963 DC = DC->getRedeclContext(); 10964 DC->makeDeclVisibleInContext(ND); 10965 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 10966 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 10967 } 10968 10969 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 10970 D.getIdentifierLoc(), ND, 10971 DS.getFriendSpecLoc()); 10972 FrD->setAccess(AS_public); 10973 CurContext->addDecl(FrD); 10974 10975 if (ND->isInvalidDecl()) { 10976 FrD->setInvalidDecl(); 10977 } else { 10978 if (DC->isRecord()) CheckFriendAccess(ND); 10979 10980 FunctionDecl *FD; 10981 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 10982 FD = FTD->getTemplatedDecl(); 10983 else 10984 FD = cast<FunctionDecl>(ND); 10985 10986 // Mark templated-scope function declarations as unsupported. 10987 if (FD->getNumTemplateParameterLists()) 10988 FrD->setUnsupportedFriend(true); 10989 } 10990 10991 return ND; 10992} 10993 10994void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 10995 AdjustDeclIfTemplate(Dcl); 10996 10997 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 10998 if (!Fn) { 10999 Diag(DelLoc, diag::err_deleted_non_function); 11000 return; 11001 } 11002 11003 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 11004 // Don't consider the implicit declaration we generate for explicit 11005 // specializations. FIXME: Do not generate these implicit declarations. 11006 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization 11007 || Prev->getPreviousDecl()) && !Prev->isDefined()) { 11008 Diag(DelLoc, diag::err_deleted_decl_not_first); 11009 Diag(Prev->getLocation(), diag::note_previous_declaration); 11010 } 11011 // If the declaration wasn't the first, we delete the function anyway for 11012 // recovery. 11013 Fn = Fn->getCanonicalDecl(); 11014 } 11015 11016 if (Fn->isDeleted()) 11017 return; 11018 11019 // See if we're deleting a function which is already known to override a 11020 // non-deleted virtual function. 11021 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 11022 bool IssuedDiagnostic = false; 11023 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 11024 E = MD->end_overridden_methods(); 11025 I != E; ++I) { 11026 if (!(*MD->begin_overridden_methods())->isDeleted()) { 11027 if (!IssuedDiagnostic) { 11028 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 11029 IssuedDiagnostic = true; 11030 } 11031 Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 11032 } 11033 } 11034 } 11035 11036 Fn->setDeletedAsWritten(); 11037} 11038 11039void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 11040 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 11041 11042 if (MD) { 11043 if (MD->getParent()->isDependentType()) { 11044 MD->setDefaulted(); 11045 MD->setExplicitlyDefaulted(); 11046 return; 11047 } 11048 11049 CXXSpecialMember Member = getSpecialMember(MD); 11050 if (Member == CXXInvalid) { 11051 Diag(DefaultLoc, diag::err_default_special_members); 11052 return; 11053 } 11054 11055 MD->setDefaulted(); 11056 MD->setExplicitlyDefaulted(); 11057 11058 // If this definition appears within the record, do the checking when 11059 // the record is complete. 11060 const FunctionDecl *Primary = MD; 11061 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 11062 // Find the uninstantiated declaration that actually had the '= default' 11063 // on it. 11064 Pattern->isDefined(Primary); 11065 11066 // If the method was defaulted on its first declaration, we will have 11067 // already performed the checking in CheckCompletedCXXClass. Such a 11068 // declaration doesn't trigger an implicit definition. 11069 if (Primary == Primary->getCanonicalDecl()) 11070 return; 11071 11072 CheckExplicitlyDefaultedSpecialMember(MD); 11073 11074 // The exception specification is needed because we are defining the 11075 // function. 11076 ResolveExceptionSpec(DefaultLoc, 11077 MD->getType()->castAs<FunctionProtoType>()); 11078 11079 switch (Member) { 11080 case CXXDefaultConstructor: { 11081 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD); 11082 if (!CD->isInvalidDecl()) 11083 DefineImplicitDefaultConstructor(DefaultLoc, CD); 11084 break; 11085 } 11086 11087 case CXXCopyConstructor: { 11088 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD); 11089 if (!CD->isInvalidDecl()) 11090 DefineImplicitCopyConstructor(DefaultLoc, CD); 11091 break; 11092 } 11093 11094 case CXXCopyAssignment: { 11095 if (!MD->isInvalidDecl()) 11096 DefineImplicitCopyAssignment(DefaultLoc, MD); 11097 break; 11098 } 11099 11100 case CXXDestructor: { 11101 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD); 11102 if (!DD->isInvalidDecl()) 11103 DefineImplicitDestructor(DefaultLoc, DD); 11104 break; 11105 } 11106 11107 case CXXMoveConstructor: { 11108 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD); 11109 if (!CD->isInvalidDecl()) 11110 DefineImplicitMoveConstructor(DefaultLoc, CD); 11111 break; 11112 } 11113 11114 case CXXMoveAssignment: { 11115 if (!MD->isInvalidDecl()) 11116 DefineImplicitMoveAssignment(DefaultLoc, MD); 11117 break; 11118 } 11119 11120 case CXXInvalid: 11121 llvm_unreachable("Invalid special member."); 11122 } 11123 } else { 11124 Diag(DefaultLoc, diag::err_default_special_members); 11125 } 11126} 11127 11128static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 11129 for (Stmt::child_range CI = S->children(); CI; ++CI) { 11130 Stmt *SubStmt = *CI; 11131 if (!SubStmt) 11132 continue; 11133 if (isa<ReturnStmt>(SubStmt)) 11134 Self.Diag(SubStmt->getLocStart(), 11135 diag::err_return_in_constructor_handler); 11136 if (!isa<Expr>(SubStmt)) 11137 SearchForReturnInStmt(Self, SubStmt); 11138 } 11139} 11140 11141void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 11142 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 11143 CXXCatchStmt *Handler = TryBlock->getHandler(I); 11144 SearchForReturnInStmt(*this, Handler); 11145 } 11146} 11147 11148bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 11149 const CXXMethodDecl *Old) { 11150 const FunctionType *NewFT = New->getType()->getAs<FunctionType>(); 11151 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>(); 11152 11153 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 11154 11155 // If the calling conventions match, everything is fine 11156 if (NewCC == OldCC) 11157 return false; 11158 11159 // If either of the calling conventions are set to "default", we need to pick 11160 // something more sensible based on the target. This supports code where the 11161 // one method explicitly sets thiscall, and another has no explicit calling 11162 // convention. 11163 CallingConv Default = 11164 Context.getTargetInfo().getDefaultCallingConv(TargetInfo::CCMT_Member); 11165 if (NewCC == CC_Default) 11166 NewCC = Default; 11167 if (OldCC == CC_Default) 11168 OldCC = Default; 11169 11170 // If the calling conventions still don't match, then report the error 11171 if (NewCC != OldCC) { 11172 Diag(New->getLocation(), 11173 diag::err_conflicting_overriding_cc_attributes) 11174 << New->getDeclName() << New->getType() << Old->getType(); 11175 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 11176 return true; 11177 } 11178 11179 return false; 11180} 11181 11182bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 11183 const CXXMethodDecl *Old) { 11184 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType(); 11185 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType(); 11186 11187 if (Context.hasSameType(NewTy, OldTy) || 11188 NewTy->isDependentType() || OldTy->isDependentType()) 11189 return false; 11190 11191 // Check if the return types are covariant 11192 QualType NewClassTy, OldClassTy; 11193 11194 /// Both types must be pointers or references to classes. 11195 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 11196 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 11197 NewClassTy = NewPT->getPointeeType(); 11198 OldClassTy = OldPT->getPointeeType(); 11199 } 11200 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 11201 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 11202 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 11203 NewClassTy = NewRT->getPointeeType(); 11204 OldClassTy = OldRT->getPointeeType(); 11205 } 11206 } 11207 } 11208 11209 // The return types aren't either both pointers or references to a class type. 11210 if (NewClassTy.isNull()) { 11211 Diag(New->getLocation(), 11212 diag::err_different_return_type_for_overriding_virtual_function) 11213 << New->getDeclName() << NewTy << OldTy; 11214 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 11215 11216 return true; 11217 } 11218 11219 // C++ [class.virtual]p6: 11220 // If the return type of D::f differs from the return type of B::f, the 11221 // class type in the return type of D::f shall be complete at the point of 11222 // declaration of D::f or shall be the class type D. 11223 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 11224 if (!RT->isBeingDefined() && 11225 RequireCompleteType(New->getLocation(), NewClassTy, 11226 diag::err_covariant_return_incomplete, 11227 New->getDeclName())) 11228 return true; 11229 } 11230 11231 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 11232 // Check if the new class derives from the old class. 11233 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 11234 Diag(New->getLocation(), 11235 diag::err_covariant_return_not_derived) 11236 << New->getDeclName() << NewTy << OldTy; 11237 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 11238 return true; 11239 } 11240 11241 // Check if we the conversion from derived to base is valid. 11242 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy, 11243 diag::err_covariant_return_inaccessible_base, 11244 diag::err_covariant_return_ambiguous_derived_to_base_conv, 11245 // FIXME: Should this point to the return type? 11246 New->getLocation(), SourceRange(), New->getDeclName(), 0)) { 11247 // FIXME: this note won't trigger for delayed access control 11248 // diagnostics, and it's impossible to get an undelayed error 11249 // here from access control during the original parse because 11250 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 11251 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 11252 return true; 11253 } 11254 } 11255 11256 // The qualifiers of the return types must be the same. 11257 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 11258 Diag(New->getLocation(), 11259 diag::err_covariant_return_type_different_qualifications) 11260 << New->getDeclName() << NewTy << OldTy; 11261 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 11262 return true; 11263 }; 11264 11265 11266 // The new class type must have the same or less qualifiers as the old type. 11267 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 11268 Diag(New->getLocation(), 11269 diag::err_covariant_return_type_class_type_more_qualified) 11270 << New->getDeclName() << NewTy << OldTy; 11271 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 11272 return true; 11273 }; 11274 11275 return false; 11276} 11277 11278/// \brief Mark the given method pure. 11279/// 11280/// \param Method the method to be marked pure. 11281/// 11282/// \param InitRange the source range that covers the "0" initializer. 11283bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 11284 SourceLocation EndLoc = InitRange.getEnd(); 11285 if (EndLoc.isValid()) 11286 Method->setRangeEnd(EndLoc); 11287 11288 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 11289 Method->setPure(); 11290 return false; 11291 } 11292 11293 if (!Method->isInvalidDecl()) 11294 Diag(Method->getLocation(), diag::err_non_virtual_pure) 11295 << Method->getDeclName() << InitRange; 11296 return true; 11297} 11298 11299/// \brief Determine whether the given declaration is a static data member. 11300static bool isStaticDataMember(Decl *D) { 11301 VarDecl *Var = dyn_cast_or_null<VarDecl>(D); 11302 if (!Var) 11303 return false; 11304 11305 return Var->isStaticDataMember(); 11306} 11307/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 11308/// an initializer for the out-of-line declaration 'Dcl'. The scope 11309/// is a fresh scope pushed for just this purpose. 11310/// 11311/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 11312/// static data member of class X, names should be looked up in the scope of 11313/// class X. 11314void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 11315 // If there is no declaration, there was an error parsing it. 11316 if (D == 0 || D->isInvalidDecl()) return; 11317 11318 // We should only get called for declarations with scope specifiers, like: 11319 // int foo::bar; 11320 assert(D->isOutOfLine()); 11321 EnterDeclaratorContext(S, D->getDeclContext()); 11322 11323 // If we are parsing the initializer for a static data member, push a 11324 // new expression evaluation context that is associated with this static 11325 // data member. 11326 if (isStaticDataMember(D)) 11327 PushExpressionEvaluationContext(PotentiallyEvaluated, D); 11328} 11329 11330/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 11331/// initializer for the out-of-line declaration 'D'. 11332void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 11333 // If there is no declaration, there was an error parsing it. 11334 if (D == 0 || D->isInvalidDecl()) return; 11335 11336 if (isStaticDataMember(D)) 11337 PopExpressionEvaluationContext(); 11338 11339 assert(D->isOutOfLine()); 11340 ExitDeclaratorContext(S); 11341} 11342 11343/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 11344/// C++ if/switch/while/for statement. 11345/// e.g: "if (int x = f()) {...}" 11346DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 11347 // C++ 6.4p2: 11348 // The declarator shall not specify a function or an array. 11349 // The type-specifier-seq shall not contain typedef and shall not declare a 11350 // new class or enumeration. 11351 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 11352 "Parser allowed 'typedef' as storage class of condition decl."); 11353 11354 Decl *Dcl = ActOnDeclarator(S, D); 11355 if (!Dcl) 11356 return true; 11357 11358 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 11359 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 11360 << D.getSourceRange(); 11361 return true; 11362 } 11363 11364 return Dcl; 11365} 11366 11367void Sema::LoadExternalVTableUses() { 11368 if (!ExternalSource) 11369 return; 11370 11371 SmallVector<ExternalVTableUse, 4> VTables; 11372 ExternalSource->ReadUsedVTables(VTables); 11373 SmallVector<VTableUse, 4> NewUses; 11374 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 11375 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 11376 = VTablesUsed.find(VTables[I].Record); 11377 // Even if a definition wasn't required before, it may be required now. 11378 if (Pos != VTablesUsed.end()) { 11379 if (!Pos->second && VTables[I].DefinitionRequired) 11380 Pos->second = true; 11381 continue; 11382 } 11383 11384 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 11385 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 11386 } 11387 11388 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 11389} 11390 11391void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 11392 bool DefinitionRequired) { 11393 // Ignore any vtable uses in unevaluated operands or for classes that do 11394 // not have a vtable. 11395 if (!Class->isDynamicClass() || Class->isDependentContext() || 11396 CurContext->isDependentContext() || 11397 ExprEvalContexts.back().Context == Unevaluated) 11398 return; 11399 11400 // Try to insert this class into the map. 11401 LoadExternalVTableUses(); 11402 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 11403 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 11404 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 11405 if (!Pos.second) { 11406 // If we already had an entry, check to see if we are promoting this vtable 11407 // to required a definition. If so, we need to reappend to the VTableUses 11408 // list, since we may have already processed the first entry. 11409 if (DefinitionRequired && !Pos.first->second) { 11410 Pos.first->second = true; 11411 } else { 11412 // Otherwise, we can early exit. 11413 return; 11414 } 11415 } 11416 11417 // Local classes need to have their virtual members marked 11418 // immediately. For all other classes, we mark their virtual members 11419 // at the end of the translation unit. 11420 if (Class->isLocalClass()) 11421 MarkVirtualMembersReferenced(Loc, Class); 11422 else 11423 VTableUses.push_back(std::make_pair(Class, Loc)); 11424} 11425 11426bool Sema::DefineUsedVTables() { 11427 LoadExternalVTableUses(); 11428 if (VTableUses.empty()) 11429 return false; 11430 11431 // Note: The VTableUses vector could grow as a result of marking 11432 // the members of a class as "used", so we check the size each 11433 // time through the loop and prefer indices (which are stable) to 11434 // iterators (which are not). 11435 bool DefinedAnything = false; 11436 for (unsigned I = 0; I != VTableUses.size(); ++I) { 11437 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 11438 if (!Class) 11439 continue; 11440 11441 SourceLocation Loc = VTableUses[I].second; 11442 11443 bool DefineVTable = true; 11444 11445 // If this class has a key function, but that key function is 11446 // defined in another translation unit, we don't need to emit the 11447 // vtable even though we're using it. 11448 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 11449 if (KeyFunction && !KeyFunction->hasBody()) { 11450 switch (KeyFunction->getTemplateSpecializationKind()) { 11451 case TSK_Undeclared: 11452 case TSK_ExplicitSpecialization: 11453 case TSK_ExplicitInstantiationDeclaration: 11454 // The key function is in another translation unit. 11455 DefineVTable = false; 11456 break; 11457 11458 case TSK_ExplicitInstantiationDefinition: 11459 case TSK_ImplicitInstantiation: 11460 // We will be instantiating the key function. 11461 break; 11462 } 11463 } else if (!KeyFunction) { 11464 // If we have a class with no key function that is the subject 11465 // of an explicit instantiation declaration, suppress the 11466 // vtable; it will live with the explicit instantiation 11467 // definition. 11468 bool IsExplicitInstantiationDeclaration 11469 = Class->getTemplateSpecializationKind() 11470 == TSK_ExplicitInstantiationDeclaration; 11471 for (TagDecl::redecl_iterator R = Class->redecls_begin(), 11472 REnd = Class->redecls_end(); 11473 R != REnd; ++R) { 11474 TemplateSpecializationKind TSK 11475 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind(); 11476 if (TSK == TSK_ExplicitInstantiationDeclaration) 11477 IsExplicitInstantiationDeclaration = true; 11478 else if (TSK == TSK_ExplicitInstantiationDefinition) { 11479 IsExplicitInstantiationDeclaration = false; 11480 break; 11481 } 11482 } 11483 11484 if (IsExplicitInstantiationDeclaration) 11485 DefineVTable = false; 11486 } 11487 11488 // The exception specifications for all virtual members may be needed even 11489 // if we are not providing an authoritative form of the vtable in this TU. 11490 // We may choose to emit it available_externally anyway. 11491 if (!DefineVTable) { 11492 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 11493 continue; 11494 } 11495 11496 // Mark all of the virtual members of this class as referenced, so 11497 // that we can build a vtable. Then, tell the AST consumer that a 11498 // vtable for this class is required. 11499 DefinedAnything = true; 11500 MarkVirtualMembersReferenced(Loc, Class); 11501 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 11502 Consumer.HandleVTable(Class, VTablesUsed[Canonical]); 11503 11504 // Optionally warn if we're emitting a weak vtable. 11505 if (Class->hasExternalLinkage() && 11506 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) { 11507 const FunctionDecl *KeyFunctionDef = 0; 11508 if (!KeyFunction || 11509 (KeyFunction->hasBody(KeyFunctionDef) && 11510 KeyFunctionDef->isInlined())) 11511 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() == 11512 TSK_ExplicitInstantiationDefinition 11513 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable) 11514 << Class; 11515 } 11516 } 11517 VTableUses.clear(); 11518 11519 return DefinedAnything; 11520} 11521 11522void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 11523 const CXXRecordDecl *RD) { 11524 for (CXXRecordDecl::method_iterator I = RD->method_begin(), 11525 E = RD->method_end(); I != E; ++I) 11526 if ((*I)->isVirtual() && !(*I)->isPure()) 11527 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>()); 11528} 11529 11530void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 11531 const CXXRecordDecl *RD) { 11532 // Mark all functions which will appear in RD's vtable as used. 11533 CXXFinalOverriderMap FinalOverriders; 11534 RD->getFinalOverriders(FinalOverriders); 11535 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 11536 E = FinalOverriders.end(); 11537 I != E; ++I) { 11538 for (OverridingMethods::const_iterator OI = I->second.begin(), 11539 OE = I->second.end(); 11540 OI != OE; ++OI) { 11541 assert(OI->second.size() > 0 && "no final overrider"); 11542 CXXMethodDecl *Overrider = OI->second.front().Method; 11543 11544 // C++ [basic.def.odr]p2: 11545 // [...] A virtual member function is used if it is not pure. [...] 11546 if (!Overrider->isPure()) 11547 MarkFunctionReferenced(Loc, Overrider); 11548 } 11549 } 11550 11551 // Only classes that have virtual bases need a VTT. 11552 if (RD->getNumVBases() == 0) 11553 return; 11554 11555 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(), 11556 e = RD->bases_end(); i != e; ++i) { 11557 const CXXRecordDecl *Base = 11558 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl()); 11559 if (Base->getNumVBases() == 0) 11560 continue; 11561 MarkVirtualMembersReferenced(Loc, Base); 11562 } 11563} 11564 11565/// SetIvarInitializers - This routine builds initialization ASTs for the 11566/// Objective-C implementation whose ivars need be initialized. 11567void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 11568 if (!getLangOpts().CPlusPlus) 11569 return; 11570 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 11571 SmallVector<ObjCIvarDecl*, 8> ivars; 11572 CollectIvarsToConstructOrDestruct(OID, ivars); 11573 if (ivars.empty()) 11574 return; 11575 SmallVector<CXXCtorInitializer*, 32> AllToInit; 11576 for (unsigned i = 0; i < ivars.size(); i++) { 11577 FieldDecl *Field = ivars[i]; 11578 if (Field->isInvalidDecl()) 11579 continue; 11580 11581 CXXCtorInitializer *Member; 11582 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 11583 InitializationKind InitKind = 11584 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 11585 11586 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0); 11587 ExprResult MemberInit = 11588 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg()); 11589 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 11590 // Note, MemberInit could actually come back empty if no initialization 11591 // is required (e.g., because it would call a trivial default constructor) 11592 if (!MemberInit.get() || MemberInit.isInvalid()) 11593 continue; 11594 11595 Member = 11596 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 11597 SourceLocation(), 11598 MemberInit.takeAs<Expr>(), 11599 SourceLocation()); 11600 AllToInit.push_back(Member); 11601 11602 // Be sure that the destructor is accessible and is marked as referenced. 11603 if (const RecordType *RecordTy 11604 = Context.getBaseElementType(Field->getType()) 11605 ->getAs<RecordType>()) { 11606 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 11607 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 11608 MarkFunctionReferenced(Field->getLocation(), Destructor); 11609 CheckDestructorAccess(Field->getLocation(), Destructor, 11610 PDiag(diag::err_access_dtor_ivar) 11611 << Context.getBaseElementType(Field->getType())); 11612 } 11613 } 11614 } 11615 ObjCImplementation->setIvarInitializers(Context, 11616 AllToInit.data(), AllToInit.size()); 11617 } 11618} 11619 11620static 11621void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 11622 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid, 11623 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid, 11624 llvm::SmallSet<CXXConstructorDecl*, 4> &Current, 11625 Sema &S) { 11626 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(), 11627 CE = Current.end(); 11628 if (Ctor->isInvalidDecl()) 11629 return; 11630 11631 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 11632 11633 // Target may not be determinable yet, for instance if this is a dependent 11634 // call in an uninstantiated template. 11635 if (Target) { 11636 const FunctionDecl *FNTarget = 0; 11637 (void)Target->hasBody(FNTarget); 11638 Target = const_cast<CXXConstructorDecl*>( 11639 cast_or_null<CXXConstructorDecl>(FNTarget)); 11640 } 11641 11642 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 11643 // Avoid dereferencing a null pointer here. 11644 *TCanonical = Target ? Target->getCanonicalDecl() : 0; 11645 11646 if (!Current.insert(Canonical)) 11647 return; 11648 11649 // We know that beyond here, we aren't chaining into a cycle. 11650 if (!Target || !Target->isDelegatingConstructor() || 11651 Target->isInvalidDecl() || Valid.count(TCanonical)) { 11652 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI) 11653 Valid.insert(*CI); 11654 Current.clear(); 11655 // We've hit a cycle. 11656 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 11657 Current.count(TCanonical)) { 11658 // If we haven't diagnosed this cycle yet, do so now. 11659 if (!Invalid.count(TCanonical)) { 11660 S.Diag((*Ctor->init_begin())->getSourceLocation(), 11661 diag::warn_delegating_ctor_cycle) 11662 << Ctor; 11663 11664 // Don't add a note for a function delegating directly to itself. 11665 if (TCanonical != Canonical) 11666 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 11667 11668 CXXConstructorDecl *C = Target; 11669 while (C->getCanonicalDecl() != Canonical) { 11670 const FunctionDecl *FNTarget = 0; 11671 (void)C->getTargetConstructor()->hasBody(FNTarget); 11672 assert(FNTarget && "Ctor cycle through bodiless function"); 11673 11674 C = const_cast<CXXConstructorDecl*>( 11675 cast<CXXConstructorDecl>(FNTarget)); 11676 S.Diag(C->getLocation(), diag::note_which_delegates_to); 11677 } 11678 } 11679 11680 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI) 11681 Invalid.insert(*CI); 11682 Current.clear(); 11683 } else { 11684 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 11685 } 11686} 11687 11688 11689void Sema::CheckDelegatingCtorCycles() { 11690 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 11691 11692 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(), 11693 CE = Current.end(); 11694 11695 for (DelegatingCtorDeclsType::iterator 11696 I = DelegatingCtorDecls.begin(ExternalSource), 11697 E = DelegatingCtorDecls.end(); 11698 I != E; ++I) 11699 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 11700 11701 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI) 11702 (*CI)->setInvalidDecl(); 11703} 11704 11705namespace { 11706 /// \brief AST visitor that finds references to the 'this' expression. 11707 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 11708 Sema &S; 11709 11710 public: 11711 explicit FindCXXThisExpr(Sema &S) : S(S) { } 11712 11713 bool VisitCXXThisExpr(CXXThisExpr *E) { 11714 S.Diag(E->getLocation(), diag::err_this_static_member_func) 11715 << E->isImplicit(); 11716 return false; 11717 } 11718 }; 11719} 11720 11721bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 11722 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 11723 if (!TSInfo) 11724 return false; 11725 11726 TypeLoc TL = TSInfo->getTypeLoc(); 11727 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 11728 if (!ProtoTL) 11729 return false; 11730 11731 // C++11 [expr.prim.general]p3: 11732 // [The expression this] shall not appear before the optional 11733 // cv-qualifier-seq and it shall not appear within the declaration of a 11734 // static member function (although its type and value category are defined 11735 // within a static member function as they are within a non-static member 11736 // function). [ Note: this is because declaration matching does not occur 11737 // until the complete declarator is known. - end note ] 11738 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 11739 FindCXXThisExpr Finder(*this); 11740 11741 // If the return type came after the cv-qualifier-seq, check it now. 11742 if (Proto->hasTrailingReturn() && 11743 !Finder.TraverseTypeLoc(ProtoTL.getResultLoc())) 11744 return true; 11745 11746 // Check the exception specification. 11747 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 11748 return true; 11749 11750 return checkThisInStaticMemberFunctionAttributes(Method); 11751} 11752 11753bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 11754 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 11755 if (!TSInfo) 11756 return false; 11757 11758 TypeLoc TL = TSInfo->getTypeLoc(); 11759 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 11760 if (!ProtoTL) 11761 return false; 11762 11763 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 11764 FindCXXThisExpr Finder(*this); 11765 11766 switch (Proto->getExceptionSpecType()) { 11767 case EST_Uninstantiated: 11768 case EST_Unevaluated: 11769 case EST_BasicNoexcept: 11770 case EST_DynamicNone: 11771 case EST_MSAny: 11772 case EST_None: 11773 break; 11774 11775 case EST_ComputedNoexcept: 11776 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 11777 return true; 11778 11779 case EST_Dynamic: 11780 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(), 11781 EEnd = Proto->exception_end(); 11782 E != EEnd; ++E) { 11783 if (!Finder.TraverseType(*E)) 11784 return true; 11785 } 11786 break; 11787 } 11788 11789 return false; 11790} 11791 11792bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 11793 FindCXXThisExpr Finder(*this); 11794 11795 // Check attributes. 11796 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end(); 11797 A != AEnd; ++A) { 11798 // FIXME: This should be emitted by tblgen. 11799 Expr *Arg = 0; 11800 ArrayRef<Expr *> Args; 11801 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A)) 11802 Arg = G->getArg(); 11803 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A)) 11804 Arg = G->getArg(); 11805 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A)) 11806 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size()); 11807 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A)) 11808 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size()); 11809 else if (ExclusiveLockFunctionAttr *ELF 11810 = dyn_cast<ExclusiveLockFunctionAttr>(*A)) 11811 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size()); 11812 else if (SharedLockFunctionAttr *SLF 11813 = dyn_cast<SharedLockFunctionAttr>(*A)) 11814 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size()); 11815 else if (ExclusiveTrylockFunctionAttr *ETLF 11816 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) { 11817 Arg = ETLF->getSuccessValue(); 11818 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size()); 11819 } else if (SharedTrylockFunctionAttr *STLF 11820 = dyn_cast<SharedTrylockFunctionAttr>(*A)) { 11821 Arg = STLF->getSuccessValue(); 11822 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size()); 11823 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A)) 11824 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size()); 11825 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A)) 11826 Arg = LR->getArg(); 11827 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A)) 11828 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size()); 11829 else if (ExclusiveLocksRequiredAttr *ELR 11830 = dyn_cast<ExclusiveLocksRequiredAttr>(*A)) 11831 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size()); 11832 else if (SharedLocksRequiredAttr *SLR 11833 = dyn_cast<SharedLocksRequiredAttr>(*A)) 11834 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size()); 11835 11836 if (Arg && !Finder.TraverseStmt(Arg)) 11837 return true; 11838 11839 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 11840 if (!Finder.TraverseStmt(Args[I])) 11841 return true; 11842 } 11843 } 11844 11845 return false; 11846} 11847 11848void 11849Sema::checkExceptionSpecification(ExceptionSpecificationType EST, 11850 ArrayRef<ParsedType> DynamicExceptions, 11851 ArrayRef<SourceRange> DynamicExceptionRanges, 11852 Expr *NoexceptExpr, 11853 SmallVectorImpl<QualType> &Exceptions, 11854 FunctionProtoType::ExtProtoInfo &EPI) { 11855 Exceptions.clear(); 11856 EPI.ExceptionSpecType = EST; 11857 if (EST == EST_Dynamic) { 11858 Exceptions.reserve(DynamicExceptions.size()); 11859 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 11860 // FIXME: Preserve type source info. 11861 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 11862 11863 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 11864 collectUnexpandedParameterPacks(ET, Unexpanded); 11865 if (!Unexpanded.empty()) { 11866 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(), 11867 UPPC_ExceptionType, 11868 Unexpanded); 11869 continue; 11870 } 11871 11872 // Check that the type is valid for an exception spec, and 11873 // drop it if not. 11874 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 11875 Exceptions.push_back(ET); 11876 } 11877 EPI.NumExceptions = Exceptions.size(); 11878 EPI.Exceptions = Exceptions.data(); 11879 return; 11880 } 11881 11882 if (EST == EST_ComputedNoexcept) { 11883 // If an error occurred, there's no expression here. 11884 if (NoexceptExpr) { 11885 assert((NoexceptExpr->isTypeDependent() || 11886 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 11887 Context.BoolTy) && 11888 "Parser should have made sure that the expression is boolean"); 11889 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 11890 EPI.ExceptionSpecType = EST_BasicNoexcept; 11891 return; 11892 } 11893 11894 if (!NoexceptExpr->isValueDependent()) 11895 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0, 11896 diag::err_noexcept_needs_constant_expression, 11897 /*AllowFold*/ false).take(); 11898 EPI.NoexceptExpr = NoexceptExpr; 11899 } 11900 return; 11901 } 11902} 11903 11904/// IdentifyCUDATarget - Determine the CUDA compilation target for this function 11905Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) { 11906 // Implicitly declared functions (e.g. copy constructors) are 11907 // __host__ __device__ 11908 if (D->isImplicit()) 11909 return CFT_HostDevice; 11910 11911 if (D->hasAttr<CUDAGlobalAttr>()) 11912 return CFT_Global; 11913 11914 if (D->hasAttr<CUDADeviceAttr>()) { 11915 if (D->hasAttr<CUDAHostAttr>()) 11916 return CFT_HostDevice; 11917 else 11918 return CFT_Device; 11919 } 11920 11921 return CFT_Host; 11922} 11923 11924bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget, 11925 CUDAFunctionTarget CalleeTarget) { 11926 // CUDA B.1.1 "The __device__ qualifier declares a function that is... 11927 // Callable from the device only." 11928 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device) 11929 return true; 11930 11931 // CUDA B.1.2 "The __global__ qualifier declares a function that is... 11932 // Callable from the host only." 11933 // CUDA B.1.3 "The __host__ qualifier declares a function that is... 11934 // Callable from the host only." 11935 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) && 11936 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global)) 11937 return true; 11938 11939 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice) 11940 return true; 11941 11942 return false; 11943} 11944