SemaDeclCXX.cpp revision 249423
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 }; 69 70 /// VisitExpr - Visit all of the children of this expression. 71 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 72 bool IsInvalid = false; 73 for (Stmt::child_range I = Node->children(); I; ++I) 74 IsInvalid |= Visit(*I); 75 return IsInvalid; 76 } 77 78 /// VisitDeclRefExpr - Visit a reference to a declaration, to 79 /// determine whether this declaration can be used in the default 80 /// argument expression. 81 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 82 NamedDecl *Decl = DRE->getDecl(); 83 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 84 // C++ [dcl.fct.default]p9 85 // Default arguments are evaluated each time the function is 86 // called. The order of evaluation of function arguments is 87 // unspecified. Consequently, parameters of a function shall not 88 // be used in default argument expressions, even if they are not 89 // evaluated. Parameters of a function declared before a default 90 // argument expression are in scope and can hide namespace and 91 // class member names. 92 return S->Diag(DRE->getLocStart(), 93 diag::err_param_default_argument_references_param) 94 << Param->getDeclName() << DefaultArg->getSourceRange(); 95 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 96 // C++ [dcl.fct.default]p7 97 // Local variables shall not be used in default argument 98 // expressions. 99 if (VDecl->isLocalVarDecl()) 100 return S->Diag(DRE->getLocStart(), 101 diag::err_param_default_argument_references_local) 102 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 103 } 104 105 return false; 106 } 107 108 /// VisitCXXThisExpr - Visit a C++ "this" expression. 109 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 110 // C++ [dcl.fct.default]p8: 111 // The keyword this shall not be used in a default argument of a 112 // member function. 113 return S->Diag(ThisE->getLocStart(), 114 diag::err_param_default_argument_references_this) 115 << ThisE->getSourceRange(); 116 } 117 118 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) { 119 // C++11 [expr.lambda.prim]p13: 120 // A lambda-expression appearing in a default argument shall not 121 // implicitly or explicitly capture any entity. 122 if (Lambda->capture_begin() == Lambda->capture_end()) 123 return false; 124 125 return S->Diag(Lambda->getLocStart(), 126 diag::err_lambda_capture_default_arg); 127 } 128} 129 130void Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc, 131 CXXMethodDecl *Method) { 132 // If we have an MSAny spec already, don't bother. 133 if (!Method || ComputedEST == EST_MSAny) 134 return; 135 136 const FunctionProtoType *Proto 137 = Method->getType()->getAs<FunctionProtoType>(); 138 Proto = Self->ResolveExceptionSpec(CallLoc, Proto); 139 if (!Proto) 140 return; 141 142 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 143 144 // If this function can throw any exceptions, make a note of that. 145 if (EST == EST_MSAny || EST == EST_None) { 146 ClearExceptions(); 147 ComputedEST = EST; 148 return; 149 } 150 151 // FIXME: If the call to this decl is using any of its default arguments, we 152 // need to search them for potentially-throwing calls. 153 154 // If this function has a basic noexcept, it doesn't affect the outcome. 155 if (EST == EST_BasicNoexcept) 156 return; 157 158 // If we have a throw-all spec at this point, ignore the function. 159 if (ComputedEST == EST_None) 160 return; 161 162 // If we're still at noexcept(true) and there's a nothrow() callee, 163 // change to that specification. 164 if (EST == EST_DynamicNone) { 165 if (ComputedEST == EST_BasicNoexcept) 166 ComputedEST = EST_DynamicNone; 167 return; 168 } 169 170 // Check out noexcept specs. 171 if (EST == EST_ComputedNoexcept) { 172 FunctionProtoType::NoexceptResult NR = 173 Proto->getNoexceptSpec(Self->Context); 174 assert(NR != FunctionProtoType::NR_NoNoexcept && 175 "Must have noexcept result for EST_ComputedNoexcept."); 176 assert(NR != FunctionProtoType::NR_Dependent && 177 "Should not generate implicit declarations for dependent cases, " 178 "and don't know how to handle them anyway."); 179 180 // noexcept(false) -> no spec on the new function 181 if (NR == FunctionProtoType::NR_Throw) { 182 ClearExceptions(); 183 ComputedEST = EST_None; 184 } 185 // noexcept(true) won't change anything either. 186 return; 187 } 188 189 assert(EST == EST_Dynamic && "EST case not considered earlier."); 190 assert(ComputedEST != EST_None && 191 "Shouldn't collect exceptions when throw-all is guaranteed."); 192 ComputedEST = EST_Dynamic; 193 // Record the exceptions in this function's exception specification. 194 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(), 195 EEnd = Proto->exception_end(); 196 E != EEnd; ++E) 197 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E))) 198 Exceptions.push_back(*E); 199} 200 201void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) { 202 if (!E || ComputedEST == EST_MSAny) 203 return; 204 205 // FIXME: 206 // 207 // C++0x [except.spec]p14: 208 // [An] implicit exception-specification specifies the type-id T if and 209 // only if T is allowed by the exception-specification of a function directly 210 // invoked by f's implicit definition; f shall allow all exceptions if any 211 // function it directly invokes allows all exceptions, and f shall allow no 212 // exceptions if every function it directly invokes allows no exceptions. 213 // 214 // Note in particular that if an implicit exception-specification is generated 215 // for a function containing a throw-expression, that specification can still 216 // be noexcept(true). 217 // 218 // Note also that 'directly invoked' is not defined in the standard, and there 219 // is no indication that we should only consider potentially-evaluated calls. 220 // 221 // Ultimately we should implement the intent of the standard: the exception 222 // specification should be the set of exceptions which can be thrown by the 223 // implicit definition. For now, we assume that any non-nothrow expression can 224 // throw any exception. 225 226 if (Self->canThrow(E)) 227 ComputedEST = EST_None; 228} 229 230bool 231Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 232 SourceLocation EqualLoc) { 233 if (RequireCompleteType(Param->getLocation(), Param->getType(), 234 diag::err_typecheck_decl_incomplete_type)) { 235 Param->setInvalidDecl(); 236 return true; 237 } 238 239 // C++ [dcl.fct.default]p5 240 // A default argument expression is implicitly converted (clause 241 // 4) to the parameter type. The default argument expression has 242 // the same semantic constraints as the initializer expression in 243 // a declaration of a variable of the parameter type, using the 244 // copy-initialization semantics (8.5). 245 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 246 Param); 247 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 248 EqualLoc); 249 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1); 250 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); 251 if (Result.isInvalid()) 252 return true; 253 Arg = Result.takeAs<Expr>(); 254 255 CheckCompletedExpr(Arg, EqualLoc); 256 Arg = MaybeCreateExprWithCleanups(Arg); 257 258 // Okay: add the default argument to the parameter 259 Param->setDefaultArg(Arg); 260 261 // We have already instantiated this parameter; provide each of the 262 // instantiations with the uninstantiated default argument. 263 UnparsedDefaultArgInstantiationsMap::iterator InstPos 264 = UnparsedDefaultArgInstantiations.find(Param); 265 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 266 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 267 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 268 269 // We're done tracking this parameter's instantiations. 270 UnparsedDefaultArgInstantiations.erase(InstPos); 271 } 272 273 return false; 274} 275 276/// ActOnParamDefaultArgument - Check whether the default argument 277/// provided for a function parameter is well-formed. If so, attach it 278/// to the parameter declaration. 279void 280Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 281 Expr *DefaultArg) { 282 if (!param || !DefaultArg) 283 return; 284 285 ParmVarDecl *Param = cast<ParmVarDecl>(param); 286 UnparsedDefaultArgLocs.erase(Param); 287 288 // Default arguments are only permitted in C++ 289 if (!getLangOpts().CPlusPlus) { 290 Diag(EqualLoc, diag::err_param_default_argument) 291 << DefaultArg->getSourceRange(); 292 Param->setInvalidDecl(); 293 return; 294 } 295 296 // Check for unexpanded parameter packs. 297 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 298 Param->setInvalidDecl(); 299 return; 300 } 301 302 // Check that the default argument is well-formed 303 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this); 304 if (DefaultArgChecker.Visit(DefaultArg)) { 305 Param->setInvalidDecl(); 306 return; 307 } 308 309 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 310} 311 312/// ActOnParamUnparsedDefaultArgument - We've seen a default 313/// argument for a function parameter, but we can't parse it yet 314/// because we're inside a class definition. Note that this default 315/// argument will be parsed later. 316void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 317 SourceLocation EqualLoc, 318 SourceLocation ArgLoc) { 319 if (!param) 320 return; 321 322 ParmVarDecl *Param = cast<ParmVarDecl>(param); 323 if (Param) 324 Param->setUnparsedDefaultArg(); 325 326 UnparsedDefaultArgLocs[Param] = ArgLoc; 327} 328 329/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 330/// the default argument for the parameter param failed. 331void Sema::ActOnParamDefaultArgumentError(Decl *param) { 332 if (!param) 333 return; 334 335 ParmVarDecl *Param = cast<ParmVarDecl>(param); 336 337 Param->setInvalidDecl(); 338 339 UnparsedDefaultArgLocs.erase(Param); 340} 341 342/// CheckExtraCXXDefaultArguments - Check for any extra default 343/// arguments in the declarator, which is not a function declaration 344/// or definition and therefore is not permitted to have default 345/// arguments. This routine should be invoked for every declarator 346/// that is not a function declaration or definition. 347void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 348 // C++ [dcl.fct.default]p3 349 // A default argument expression shall be specified only in the 350 // parameter-declaration-clause of a function declaration or in a 351 // template-parameter (14.1). It shall not be specified for a 352 // parameter pack. If it is specified in a 353 // parameter-declaration-clause, it shall not occur within a 354 // declarator or abstract-declarator of a parameter-declaration. 355 bool MightBeFunction = D.isFunctionDeclarationContext(); 356 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 357 DeclaratorChunk &chunk = D.getTypeObject(i); 358 if (chunk.Kind == DeclaratorChunk::Function) { 359 if (MightBeFunction) { 360 // This is a function declaration. It can have default arguments, but 361 // keep looking in case its return type is a function type with default 362 // arguments. 363 MightBeFunction = false; 364 continue; 365 } 366 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) { 367 ParmVarDecl *Param = 368 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param); 369 if (Param->hasUnparsedDefaultArg()) { 370 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens; 371 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 372 << SourceRange((*Toks)[1].getLocation(), 373 Toks->back().getLocation()); 374 delete Toks; 375 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0; 376 } else if (Param->getDefaultArg()) { 377 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 378 << Param->getDefaultArg()->getSourceRange(); 379 Param->setDefaultArg(0); 380 } 381 } 382 } else if (chunk.Kind != DeclaratorChunk::Paren) { 383 MightBeFunction = false; 384 } 385 } 386} 387 388/// MergeCXXFunctionDecl - Merge two declarations of the same C++ 389/// function, once we already know that they have the same 390/// type. Subroutine of MergeFunctionDecl. Returns true if there was an 391/// error, false otherwise. 392bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 393 Scope *S) { 394 bool Invalid = false; 395 396 // C++ [dcl.fct.default]p4: 397 // For non-template functions, default arguments can be added in 398 // later declarations of a function in the same 399 // scope. Declarations in different scopes have completely 400 // distinct sets of default arguments. That is, declarations in 401 // inner scopes do not acquire default arguments from 402 // declarations in outer scopes, and vice versa. In a given 403 // function declaration, all parameters subsequent to a 404 // parameter with a default argument shall have default 405 // arguments supplied in this or previous declarations. A 406 // default argument shall not be redefined by a later 407 // declaration (not even to the same value). 408 // 409 // C++ [dcl.fct.default]p6: 410 // Except for member functions of class templates, the default arguments 411 // in a member function definition that appears outside of the class 412 // definition are added to the set of default arguments provided by the 413 // member function declaration in the class definition. 414 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 415 ParmVarDecl *OldParam = Old->getParamDecl(p); 416 ParmVarDecl *NewParam = New->getParamDecl(p); 417 418 bool OldParamHasDfl = OldParam->hasDefaultArg(); 419 bool NewParamHasDfl = NewParam->hasDefaultArg(); 420 421 NamedDecl *ND = Old; 422 if (S && !isDeclInScope(ND, New->getDeclContext(), S)) 423 // Ignore default parameters of old decl if they are not in 424 // the same scope. 425 OldParamHasDfl = false; 426 427 if (OldParamHasDfl && NewParamHasDfl) { 428 429 unsigned DiagDefaultParamID = 430 diag::err_param_default_argument_redefinition; 431 432 // MSVC accepts that default parameters be redefined for member functions 433 // of template class. The new default parameter's value is ignored. 434 Invalid = true; 435 if (getLangOpts().MicrosoftExt) { 436 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New); 437 if (MD && MD->getParent()->getDescribedClassTemplate()) { 438 // Merge the old default argument into the new parameter. 439 NewParam->setHasInheritedDefaultArg(); 440 if (OldParam->hasUninstantiatedDefaultArg()) 441 NewParam->setUninstantiatedDefaultArg( 442 OldParam->getUninstantiatedDefaultArg()); 443 else 444 NewParam->setDefaultArg(OldParam->getInit()); 445 DiagDefaultParamID = diag::warn_param_default_argument_redefinition; 446 Invalid = false; 447 } 448 } 449 450 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 451 // hint here. Alternatively, we could walk the type-source information 452 // for NewParam to find the last source location in the type... but it 453 // isn't worth the effort right now. This is the kind of test case that 454 // is hard to get right: 455 // int f(int); 456 // void g(int (*fp)(int) = f); 457 // void g(int (*fp)(int) = &f); 458 Diag(NewParam->getLocation(), DiagDefaultParamID) 459 << NewParam->getDefaultArgRange(); 460 461 // Look for the function declaration where the default argument was 462 // actually written, which may be a declaration prior to Old. 463 for (FunctionDecl *Older = Old->getPreviousDecl(); 464 Older; Older = Older->getPreviousDecl()) { 465 if (!Older->getParamDecl(p)->hasDefaultArg()) 466 break; 467 468 OldParam = Older->getParamDecl(p); 469 } 470 471 Diag(OldParam->getLocation(), diag::note_previous_definition) 472 << OldParam->getDefaultArgRange(); 473 } else if (OldParamHasDfl) { 474 // Merge the old default argument into the new parameter. 475 // It's important to use getInit() here; getDefaultArg() 476 // strips off any top-level ExprWithCleanups. 477 NewParam->setHasInheritedDefaultArg(); 478 if (OldParam->hasUninstantiatedDefaultArg()) 479 NewParam->setUninstantiatedDefaultArg( 480 OldParam->getUninstantiatedDefaultArg()); 481 else 482 NewParam->setDefaultArg(OldParam->getInit()); 483 } else if (NewParamHasDfl) { 484 if (New->getDescribedFunctionTemplate()) { 485 // Paragraph 4, quoted above, only applies to non-template functions. 486 Diag(NewParam->getLocation(), 487 diag::err_param_default_argument_template_redecl) 488 << NewParam->getDefaultArgRange(); 489 Diag(Old->getLocation(), diag::note_template_prev_declaration) 490 << false; 491 } else if (New->getTemplateSpecializationKind() 492 != TSK_ImplicitInstantiation && 493 New->getTemplateSpecializationKind() != TSK_Undeclared) { 494 // C++ [temp.expr.spec]p21: 495 // Default function arguments shall not be specified in a declaration 496 // or a definition for one of the following explicit specializations: 497 // - the explicit specialization of a function template; 498 // - the explicit specialization of a member function template; 499 // - the explicit specialization of a member function of a class 500 // template where the class template specialization to which the 501 // member function specialization belongs is implicitly 502 // instantiated. 503 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 504 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 505 << New->getDeclName() 506 << NewParam->getDefaultArgRange(); 507 } else if (New->getDeclContext()->isDependentContext()) { 508 // C++ [dcl.fct.default]p6 (DR217): 509 // Default arguments for a member function of a class template shall 510 // be specified on the initial declaration of the member function 511 // within the class template. 512 // 513 // Reading the tea leaves a bit in DR217 and its reference to DR205 514 // leads me to the conclusion that one cannot add default function 515 // arguments for an out-of-line definition of a member function of a 516 // dependent type. 517 int WhichKind = 2; 518 if (CXXRecordDecl *Record 519 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 520 if (Record->getDescribedClassTemplate()) 521 WhichKind = 0; 522 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 523 WhichKind = 1; 524 else 525 WhichKind = 2; 526 } 527 528 Diag(NewParam->getLocation(), 529 diag::err_param_default_argument_member_template_redecl) 530 << WhichKind 531 << NewParam->getDefaultArgRange(); 532 } 533 } 534 } 535 536 // DR1344: If a default argument is added outside a class definition and that 537 // default argument makes the function a special member function, the program 538 // is ill-formed. This can only happen for constructors. 539 if (isa<CXXConstructorDecl>(New) && 540 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 541 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 542 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 543 if (NewSM != OldSM) { 544 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 545 assert(NewParam->hasDefaultArg()); 546 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 547 << NewParam->getDefaultArgRange() << NewSM; 548 Diag(Old->getLocation(), diag::note_previous_declaration); 549 } 550 } 551 552 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 553 // template has a constexpr specifier then all its declarations shall 554 // contain the constexpr specifier. 555 if (New->isConstexpr() != Old->isConstexpr()) { 556 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 557 << New << New->isConstexpr(); 558 Diag(Old->getLocation(), diag::note_previous_declaration); 559 Invalid = true; 560 } 561 562 if (CheckEquivalentExceptionSpec(Old, New)) 563 Invalid = true; 564 565 return Invalid; 566} 567 568/// \brief Merge the exception specifications of two variable declarations. 569/// 570/// This is called when there's a redeclaration of a VarDecl. The function 571/// checks if the redeclaration might have an exception specification and 572/// validates compatibility and merges the specs if necessary. 573void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 574 // Shortcut if exceptions are disabled. 575 if (!getLangOpts().CXXExceptions) 576 return; 577 578 assert(Context.hasSameType(New->getType(), Old->getType()) && 579 "Should only be called if types are otherwise the same."); 580 581 QualType NewType = New->getType(); 582 QualType OldType = Old->getType(); 583 584 // We're only interested in pointers and references to functions, as well 585 // as pointers to member functions. 586 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 587 NewType = R->getPointeeType(); 588 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 589 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 590 NewType = P->getPointeeType(); 591 OldType = OldType->getAs<PointerType>()->getPointeeType(); 592 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 593 NewType = M->getPointeeType(); 594 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 595 } 596 597 if (!NewType->isFunctionProtoType()) 598 return; 599 600 // There's lots of special cases for functions. For function pointers, system 601 // libraries are hopefully not as broken so that we don't need these 602 // workarounds. 603 if (CheckEquivalentExceptionSpec( 604 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 605 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 606 New->setInvalidDecl(); 607 } 608} 609 610/// CheckCXXDefaultArguments - Verify that the default arguments for a 611/// function declaration are well-formed according to C++ 612/// [dcl.fct.default]. 613void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 614 unsigned NumParams = FD->getNumParams(); 615 unsigned p; 616 617 bool IsLambda = FD->getOverloadedOperator() == OO_Call && 618 isa<CXXMethodDecl>(FD) && 619 cast<CXXMethodDecl>(FD)->getParent()->isLambda(); 620 621 // Find first parameter with a default argument 622 for (p = 0; p < NumParams; ++p) { 623 ParmVarDecl *Param = FD->getParamDecl(p); 624 if (Param->hasDefaultArg()) { 625 // C++11 [expr.prim.lambda]p5: 626 // [...] Default arguments (8.3.6) shall not be specified in the 627 // parameter-declaration-clause of a lambda-declarator. 628 // 629 // FIXME: Core issue 974 strikes this sentence, we only provide an 630 // extension warning. 631 if (IsLambda) 632 Diag(Param->getLocation(), diag::ext_lambda_default_arguments) 633 << Param->getDefaultArgRange(); 634 break; 635 } 636 } 637 638 // C++ [dcl.fct.default]p4: 639 // In a given function declaration, all parameters 640 // subsequent to a parameter with a default argument shall 641 // have default arguments supplied in this or previous 642 // declarations. A default argument shall not be redefined 643 // by a later declaration (not even to the same value). 644 unsigned LastMissingDefaultArg = 0; 645 for (; p < NumParams; ++p) { 646 ParmVarDecl *Param = FD->getParamDecl(p); 647 if (!Param->hasDefaultArg()) { 648 if (Param->isInvalidDecl()) 649 /* We already complained about this parameter. */; 650 else if (Param->getIdentifier()) 651 Diag(Param->getLocation(), 652 diag::err_param_default_argument_missing_name) 653 << Param->getIdentifier(); 654 else 655 Diag(Param->getLocation(), 656 diag::err_param_default_argument_missing); 657 658 LastMissingDefaultArg = p; 659 } 660 } 661 662 if (LastMissingDefaultArg > 0) { 663 // Some default arguments were missing. Clear out all of the 664 // default arguments up to (and including) the last missing 665 // default argument, so that we leave the function parameters 666 // in a semantically valid state. 667 for (p = 0; p <= LastMissingDefaultArg; ++p) { 668 ParmVarDecl *Param = FD->getParamDecl(p); 669 if (Param->hasDefaultArg()) { 670 Param->setDefaultArg(0); 671 } 672 } 673 } 674} 675 676// CheckConstexprParameterTypes - Check whether a function's parameter types 677// are all literal types. If so, return true. If not, produce a suitable 678// diagnostic and return false. 679static bool CheckConstexprParameterTypes(Sema &SemaRef, 680 const FunctionDecl *FD) { 681 unsigned ArgIndex = 0; 682 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 683 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(), 684 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) { 685 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 686 SourceLocation ParamLoc = PD->getLocation(); 687 if (!(*i)->isDependentType() && 688 SemaRef.RequireLiteralType(ParamLoc, *i, 689 diag::err_constexpr_non_literal_param, 690 ArgIndex+1, PD->getSourceRange(), 691 isa<CXXConstructorDecl>(FD))) 692 return false; 693 } 694 return true; 695} 696 697/// \brief Get diagnostic %select index for tag kind for 698/// record diagnostic message. 699/// WARNING: Indexes apply to particular diagnostics only! 700/// 701/// \returns diagnostic %select index. 702static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 703 switch (Tag) { 704 case TTK_Struct: return 0; 705 case TTK_Interface: return 1; 706 case TTK_Class: return 2; 707 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 708 } 709} 710 711// CheckConstexprFunctionDecl - Check whether a function declaration satisfies 712// the requirements of a constexpr function definition or a constexpr 713// constructor definition. If so, return true. If not, produce appropriate 714// diagnostics and return false. 715// 716// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 717bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) { 718 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 719 if (MD && MD->isInstance()) { 720 // C++11 [dcl.constexpr]p4: 721 // The definition of a constexpr constructor shall satisfy the following 722 // constraints: 723 // - the class shall not have any virtual base classes; 724 const CXXRecordDecl *RD = MD->getParent(); 725 if (RD->getNumVBases()) { 726 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 727 << isa<CXXConstructorDecl>(NewFD) 728 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 729 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(), 730 E = RD->vbases_end(); I != E; ++I) 731 Diag(I->getLocStart(), 732 diag::note_constexpr_virtual_base_here) << I->getSourceRange(); 733 return false; 734 } 735 } 736 737 if (!isa<CXXConstructorDecl>(NewFD)) { 738 // C++11 [dcl.constexpr]p3: 739 // The definition of a constexpr function shall satisfy the following 740 // constraints: 741 // - it shall not be virtual; 742 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 743 if (Method && Method->isVirtual()) { 744 Diag(NewFD->getLocation(), diag::err_constexpr_virtual); 745 746 // If it's not obvious why this function is virtual, find an overridden 747 // function which uses the 'virtual' keyword. 748 const CXXMethodDecl *WrittenVirtual = Method; 749 while (!WrittenVirtual->isVirtualAsWritten()) 750 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 751 if (WrittenVirtual != Method) 752 Diag(WrittenVirtual->getLocation(), 753 diag::note_overridden_virtual_function); 754 return false; 755 } 756 757 // - its return type shall be a literal type; 758 QualType RT = NewFD->getResultType(); 759 if (!RT->isDependentType() && 760 RequireLiteralType(NewFD->getLocation(), RT, 761 diag::err_constexpr_non_literal_return)) 762 return false; 763 } 764 765 // - each of its parameter types shall be a literal type; 766 if (!CheckConstexprParameterTypes(*this, NewFD)) 767 return false; 768 769 return true; 770} 771 772/// Check the given declaration statement is legal within a constexpr function 773/// body. C++0x [dcl.constexpr]p3,p4. 774/// 775/// \return true if the body is OK, false if we have diagnosed a problem. 776static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 777 DeclStmt *DS) { 778 // C++0x [dcl.constexpr]p3 and p4: 779 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 780 // contain only 781 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(), 782 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) { 783 switch ((*DclIt)->getKind()) { 784 case Decl::StaticAssert: 785 case Decl::Using: 786 case Decl::UsingShadow: 787 case Decl::UsingDirective: 788 case Decl::UnresolvedUsingTypename: 789 // - static_assert-declarations 790 // - using-declarations, 791 // - using-directives, 792 continue; 793 794 case Decl::Typedef: 795 case Decl::TypeAlias: { 796 // - typedef declarations and alias-declarations that do not define 797 // classes or enumerations, 798 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt); 799 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 800 // Don't allow variably-modified types in constexpr functions. 801 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 802 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 803 << TL.getSourceRange() << TL.getType() 804 << isa<CXXConstructorDecl>(Dcl); 805 return false; 806 } 807 continue; 808 } 809 810 case Decl::Enum: 811 case Decl::CXXRecord: 812 // As an extension, we allow the declaration (but not the definition) of 813 // classes and enumerations in all declarations, not just in typedef and 814 // alias declarations. 815 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) { 816 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition) 817 << isa<CXXConstructorDecl>(Dcl); 818 return false; 819 } 820 continue; 821 822 case Decl::Var: 823 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration) 824 << isa<CXXConstructorDecl>(Dcl); 825 return false; 826 827 default: 828 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt) 829 << isa<CXXConstructorDecl>(Dcl); 830 return false; 831 } 832 } 833 834 return true; 835} 836 837/// Check that the given field is initialized within a constexpr constructor. 838/// 839/// \param Dcl The constexpr constructor being checked. 840/// \param Field The field being checked. This may be a member of an anonymous 841/// struct or union nested within the class being checked. 842/// \param Inits All declarations, including anonymous struct/union members and 843/// indirect members, for which any initialization was provided. 844/// \param Diagnosed Set to true if an error is produced. 845static void CheckConstexprCtorInitializer(Sema &SemaRef, 846 const FunctionDecl *Dcl, 847 FieldDecl *Field, 848 llvm::SmallSet<Decl*, 16> &Inits, 849 bool &Diagnosed) { 850 if (Field->isUnnamedBitfield()) 851 return; 852 853 if (Field->isAnonymousStructOrUnion() && 854 Field->getType()->getAsCXXRecordDecl()->isEmpty()) 855 return; 856 857 if (!Inits.count(Field)) { 858 if (!Diagnosed) { 859 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init); 860 Diagnosed = true; 861 } 862 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init); 863 } else if (Field->isAnonymousStructOrUnion()) { 864 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 865 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end(); 866 I != E; ++I) 867 // If an anonymous union contains an anonymous struct of which any member 868 // is initialized, all members must be initialized. 869 if (!RD->isUnion() || Inits.count(*I)) 870 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed); 871 } 872} 873 874/// Check the body for the given constexpr function declaration only contains 875/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 876/// 877/// \return true if the body is OK, false if we have diagnosed a problem. 878bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) { 879 if (isa<CXXTryStmt>(Body)) { 880 // C++11 [dcl.constexpr]p3: 881 // The definition of a constexpr function shall satisfy the following 882 // constraints: [...] 883 // - its function-body shall be = delete, = default, or a 884 // compound-statement 885 // 886 // C++11 [dcl.constexpr]p4: 887 // In the definition of a constexpr constructor, [...] 888 // - its function-body shall not be a function-try-block; 889 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block) 890 << isa<CXXConstructorDecl>(Dcl); 891 return false; 892 } 893 894 // - its function-body shall be [...] a compound-statement that contains only 895 CompoundStmt *CompBody = cast<CompoundStmt>(Body); 896 897 SmallVector<SourceLocation, 4> ReturnStmts; 898 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(), 899 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) { 900 switch ((*BodyIt)->getStmtClass()) { 901 case Stmt::NullStmtClass: 902 // - null statements, 903 continue; 904 905 case Stmt::DeclStmtClass: 906 // - static_assert-declarations 907 // - using-declarations, 908 // - using-directives, 909 // - typedef declarations and alias-declarations that do not define 910 // classes or enumerations, 911 if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt))) 912 return false; 913 continue; 914 915 case Stmt::ReturnStmtClass: 916 // - and exactly one return statement; 917 if (isa<CXXConstructorDecl>(Dcl)) 918 break; 919 920 ReturnStmts.push_back((*BodyIt)->getLocStart()); 921 continue; 922 923 default: 924 break; 925 } 926 927 Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt) 928 << isa<CXXConstructorDecl>(Dcl); 929 return false; 930 } 931 932 if (const CXXConstructorDecl *Constructor 933 = dyn_cast<CXXConstructorDecl>(Dcl)) { 934 const CXXRecordDecl *RD = Constructor->getParent(); 935 // DR1359: 936 // - every non-variant non-static data member and base class sub-object 937 // shall be initialized; 938 // - if the class is a non-empty union, or for each non-empty anonymous 939 // union member of a non-union class, exactly one non-static data member 940 // shall be initialized; 941 if (RD->isUnion()) { 942 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) { 943 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init); 944 return false; 945 } 946 } else if (!Constructor->isDependentContext() && 947 !Constructor->isDelegatingConstructor()) { 948 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 949 950 // Skip detailed checking if we have enough initializers, and we would 951 // allow at most one initializer per member. 952 bool AnyAnonStructUnionMembers = false; 953 unsigned Fields = 0; 954 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 955 E = RD->field_end(); I != E; ++I, ++Fields) { 956 if (I->isAnonymousStructOrUnion()) { 957 AnyAnonStructUnionMembers = true; 958 break; 959 } 960 } 961 if (AnyAnonStructUnionMembers || 962 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 963 // Check initialization of non-static data members. Base classes are 964 // always initialized so do not need to be checked. Dependent bases 965 // might not have initializers in the member initializer list. 966 llvm::SmallSet<Decl*, 16> Inits; 967 for (CXXConstructorDecl::init_const_iterator 968 I = Constructor->init_begin(), E = Constructor->init_end(); 969 I != E; ++I) { 970 if (FieldDecl *FD = (*I)->getMember()) 971 Inits.insert(FD); 972 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember()) 973 Inits.insert(ID->chain_begin(), ID->chain_end()); 974 } 975 976 bool Diagnosed = false; 977 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 978 E = RD->field_end(); I != E; ++I) 979 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed); 980 if (Diagnosed) 981 return false; 982 } 983 } 984 } else { 985 if (ReturnStmts.empty()) { 986 Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return); 987 return false; 988 } 989 if (ReturnStmts.size() > 1) { 990 Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return); 991 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 992 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return); 993 return false; 994 } 995 } 996 997 // C++11 [dcl.constexpr]p5: 998 // if no function argument values exist such that the function invocation 999 // substitution would produce a constant expression, the program is 1000 // ill-formed; no diagnostic required. 1001 // C++11 [dcl.constexpr]p3: 1002 // - every constructor call and implicit conversion used in initializing the 1003 // return value shall be one of those allowed in a constant expression. 1004 // C++11 [dcl.constexpr]p4: 1005 // - every constructor involved in initializing non-static data members and 1006 // base class sub-objects shall be a constexpr constructor. 1007 SmallVector<PartialDiagnosticAt, 8> Diags; 1008 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) { 1009 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr) 1010 << isa<CXXConstructorDecl>(Dcl); 1011 for (size_t I = 0, N = Diags.size(); I != N; ++I) 1012 Diag(Diags[I].first, Diags[I].second); 1013 // Don't return false here: we allow this for compatibility in 1014 // system headers. 1015 } 1016 1017 return true; 1018} 1019 1020/// isCurrentClassName - Determine whether the identifier II is the 1021/// name of the class type currently being defined. In the case of 1022/// nested classes, this will only return true if II is the name of 1023/// the innermost class. 1024bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 1025 const CXXScopeSpec *SS) { 1026 assert(getLangOpts().CPlusPlus && "No class names in C!"); 1027 1028 CXXRecordDecl *CurDecl; 1029 if (SS && SS->isSet() && !SS->isInvalid()) { 1030 DeclContext *DC = computeDeclContext(*SS, true); 1031 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 1032 } else 1033 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1034 1035 if (CurDecl && CurDecl->getIdentifier()) 1036 return &II == CurDecl->getIdentifier(); 1037 else 1038 return false; 1039} 1040 1041/// \brief Determine whether the given class is a base class of the given 1042/// class, including looking at dependent bases. 1043static bool findCircularInheritance(const CXXRecordDecl *Class, 1044 const CXXRecordDecl *Current) { 1045 SmallVector<const CXXRecordDecl*, 8> Queue; 1046 1047 Class = Class->getCanonicalDecl(); 1048 while (true) { 1049 for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(), 1050 E = Current->bases_end(); 1051 I != E; ++I) { 1052 CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 1053 if (!Base) 1054 continue; 1055 1056 Base = Base->getDefinition(); 1057 if (!Base) 1058 continue; 1059 1060 if (Base->getCanonicalDecl() == Class) 1061 return true; 1062 1063 Queue.push_back(Base); 1064 } 1065 1066 if (Queue.empty()) 1067 return false; 1068 1069 Current = Queue.back(); 1070 Queue.pop_back(); 1071 } 1072 1073 return false; 1074} 1075 1076/// \brief Check the validity of a C++ base class specifier. 1077/// 1078/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 1079/// and returns NULL otherwise. 1080CXXBaseSpecifier * 1081Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 1082 SourceRange SpecifierRange, 1083 bool Virtual, AccessSpecifier Access, 1084 TypeSourceInfo *TInfo, 1085 SourceLocation EllipsisLoc) { 1086 QualType BaseType = TInfo->getType(); 1087 1088 // C++ [class.union]p1: 1089 // A union shall not have base classes. 1090 if (Class->isUnion()) { 1091 Diag(Class->getLocation(), diag::err_base_clause_on_union) 1092 << SpecifierRange; 1093 return 0; 1094 } 1095 1096 if (EllipsisLoc.isValid() && 1097 !TInfo->getType()->containsUnexpandedParameterPack()) { 1098 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 1099 << TInfo->getTypeLoc().getSourceRange(); 1100 EllipsisLoc = SourceLocation(); 1101 } 1102 1103 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 1104 1105 if (BaseType->isDependentType()) { 1106 // Make sure that we don't have circular inheritance among our dependent 1107 // bases. For non-dependent bases, the check for completeness below handles 1108 // this. 1109 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 1110 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 1111 ((BaseDecl = BaseDecl->getDefinition()) && 1112 findCircularInheritance(Class, BaseDecl))) { 1113 Diag(BaseLoc, diag::err_circular_inheritance) 1114 << BaseType << Context.getTypeDeclType(Class); 1115 1116 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 1117 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 1118 << BaseType; 1119 1120 return 0; 1121 } 1122 } 1123 1124 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1125 Class->getTagKind() == TTK_Class, 1126 Access, TInfo, EllipsisLoc); 1127 } 1128 1129 // Base specifiers must be record types. 1130 if (!BaseType->isRecordType()) { 1131 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 1132 return 0; 1133 } 1134 1135 // C++ [class.union]p1: 1136 // A union shall not be used as a base class. 1137 if (BaseType->isUnionType()) { 1138 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 1139 return 0; 1140 } 1141 1142 // C++ [class.derived]p2: 1143 // The class-name in a base-specifier shall not be an incompletely 1144 // defined class. 1145 if (RequireCompleteType(BaseLoc, BaseType, 1146 diag::err_incomplete_base_class, SpecifierRange)) { 1147 Class->setInvalidDecl(); 1148 return 0; 1149 } 1150 1151 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 1152 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 1153 assert(BaseDecl && "Record type has no declaration"); 1154 BaseDecl = BaseDecl->getDefinition(); 1155 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 1156 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 1157 assert(CXXBaseDecl && "Base type is not a C++ type"); 1158 1159 // C++ [class]p3: 1160 // If a class is marked final and it appears as a base-type-specifier in 1161 // base-clause, the program is ill-formed. 1162 if (CXXBaseDecl->hasAttr<FinalAttr>()) { 1163 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 1164 << CXXBaseDecl->getDeclName(); 1165 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl) 1166 << CXXBaseDecl->getDeclName(); 1167 return 0; 1168 } 1169 1170 if (BaseDecl->isInvalidDecl()) 1171 Class->setInvalidDecl(); 1172 1173 // Create the base specifier. 1174 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1175 Class->getTagKind() == TTK_Class, 1176 Access, TInfo, EllipsisLoc); 1177} 1178 1179/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 1180/// one entry in the base class list of a class specifier, for 1181/// example: 1182/// class foo : public bar, virtual private baz { 1183/// 'public bar' and 'virtual private baz' are each base-specifiers. 1184BaseResult 1185Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 1186 ParsedAttributes &Attributes, 1187 bool Virtual, AccessSpecifier Access, 1188 ParsedType basetype, SourceLocation BaseLoc, 1189 SourceLocation EllipsisLoc) { 1190 if (!classdecl) 1191 return true; 1192 1193 AdjustDeclIfTemplate(classdecl); 1194 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 1195 if (!Class) 1196 return true; 1197 1198 // We do not support any C++11 attributes on base-specifiers yet. 1199 // Diagnose any attributes we see. 1200 if (!Attributes.empty()) { 1201 for (AttributeList *Attr = Attributes.getList(); Attr; 1202 Attr = Attr->getNext()) { 1203 if (Attr->isInvalid() || 1204 Attr->getKind() == AttributeList::IgnoredAttribute) 1205 continue; 1206 Diag(Attr->getLoc(), 1207 Attr->getKind() == AttributeList::UnknownAttribute 1208 ? diag::warn_unknown_attribute_ignored 1209 : diag::err_base_specifier_attribute) 1210 << Attr->getName(); 1211 } 1212 } 1213 1214 TypeSourceInfo *TInfo = 0; 1215 GetTypeFromParser(basetype, &TInfo); 1216 1217 if (EllipsisLoc.isInvalid() && 1218 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 1219 UPPC_BaseType)) 1220 return true; 1221 1222 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 1223 Virtual, Access, TInfo, 1224 EllipsisLoc)) 1225 return BaseSpec; 1226 else 1227 Class->setInvalidDecl(); 1228 1229 return true; 1230} 1231 1232/// \brief Performs the actual work of attaching the given base class 1233/// specifiers to a C++ class. 1234bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 1235 unsigned NumBases) { 1236 if (NumBases == 0) 1237 return false; 1238 1239 // Used to keep track of which base types we have already seen, so 1240 // that we can properly diagnose redundant direct base types. Note 1241 // that the key is always the unqualified canonical type of the base 1242 // class. 1243 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 1244 1245 // Copy non-redundant base specifiers into permanent storage. 1246 unsigned NumGoodBases = 0; 1247 bool Invalid = false; 1248 for (unsigned idx = 0; idx < NumBases; ++idx) { 1249 QualType NewBaseType 1250 = Context.getCanonicalType(Bases[idx]->getType()); 1251 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 1252 1253 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 1254 if (KnownBase) { 1255 // C++ [class.mi]p3: 1256 // A class shall not be specified as a direct base class of a 1257 // derived class more than once. 1258 Diag(Bases[idx]->getLocStart(), 1259 diag::err_duplicate_base_class) 1260 << KnownBase->getType() 1261 << Bases[idx]->getSourceRange(); 1262 1263 // Delete the duplicate base class specifier; we're going to 1264 // overwrite its pointer later. 1265 Context.Deallocate(Bases[idx]); 1266 1267 Invalid = true; 1268 } else { 1269 // Okay, add this new base class. 1270 KnownBase = Bases[idx]; 1271 Bases[NumGoodBases++] = Bases[idx]; 1272 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 1273 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 1274 if (Class->isInterface() && 1275 (!RD->isInterface() || 1276 KnownBase->getAccessSpecifier() != AS_public)) { 1277 // The Microsoft extension __interface does not permit bases that 1278 // are not themselves public interfaces. 1279 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface) 1280 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName() 1281 << RD->getSourceRange(); 1282 Invalid = true; 1283 } 1284 if (RD->hasAttr<WeakAttr>()) 1285 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context)); 1286 } 1287 } 1288 } 1289 1290 // Attach the remaining base class specifiers to the derived class. 1291 Class->setBases(Bases, NumGoodBases); 1292 1293 // Delete the remaining (good) base class specifiers, since their 1294 // data has been copied into the CXXRecordDecl. 1295 for (unsigned idx = 0; idx < NumGoodBases; ++idx) 1296 Context.Deallocate(Bases[idx]); 1297 1298 return Invalid; 1299} 1300 1301/// ActOnBaseSpecifiers - Attach the given base specifiers to the 1302/// class, after checking whether there are any duplicate base 1303/// classes. 1304void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases, 1305 unsigned NumBases) { 1306 if (!ClassDecl || !Bases || !NumBases) 1307 return; 1308 1309 AdjustDeclIfTemplate(ClassDecl); 1310 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), 1311 (CXXBaseSpecifier**)(Bases), NumBases); 1312} 1313 1314/// \brief Determine whether the type \p Derived is a C++ class that is 1315/// derived from the type \p Base. 1316bool Sema::IsDerivedFrom(QualType Derived, QualType Base) { 1317 if (!getLangOpts().CPlusPlus) 1318 return false; 1319 1320 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1321 if (!DerivedRD) 1322 return false; 1323 1324 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1325 if (!BaseRD) 1326 return false; 1327 1328 // If either the base or the derived type is invalid, don't try to 1329 // check whether one is derived from the other. 1330 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 1331 return false; 1332 1333 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this. 1334 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD); 1335} 1336 1337/// \brief Determine whether the type \p Derived is a C++ class that is 1338/// derived from the type \p Base. 1339bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) { 1340 if (!getLangOpts().CPlusPlus) 1341 return false; 1342 1343 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1344 if (!DerivedRD) 1345 return false; 1346 1347 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1348 if (!BaseRD) 1349 return false; 1350 1351 return DerivedRD->isDerivedFrom(BaseRD, Paths); 1352} 1353 1354void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 1355 CXXCastPath &BasePathArray) { 1356 assert(BasePathArray.empty() && "Base path array must be empty!"); 1357 assert(Paths.isRecordingPaths() && "Must record paths!"); 1358 1359 const CXXBasePath &Path = Paths.front(); 1360 1361 // We first go backward and check if we have a virtual base. 1362 // FIXME: It would be better if CXXBasePath had the base specifier for 1363 // the nearest virtual base. 1364 unsigned Start = 0; 1365 for (unsigned I = Path.size(); I != 0; --I) { 1366 if (Path[I - 1].Base->isVirtual()) { 1367 Start = I - 1; 1368 break; 1369 } 1370 } 1371 1372 // Now add all bases. 1373 for (unsigned I = Start, E = Path.size(); I != E; ++I) 1374 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 1375} 1376 1377/// \brief Determine whether the given base path includes a virtual 1378/// base class. 1379bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) { 1380 for (CXXCastPath::const_iterator B = BasePath.begin(), 1381 BEnd = BasePath.end(); 1382 B != BEnd; ++B) 1383 if ((*B)->isVirtual()) 1384 return true; 1385 1386 return false; 1387} 1388 1389/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 1390/// conversion (where Derived and Base are class types) is 1391/// well-formed, meaning that the conversion is unambiguous (and 1392/// that all of the base classes are accessible). Returns true 1393/// and emits a diagnostic if the code is ill-formed, returns false 1394/// otherwise. Loc is the location where this routine should point to 1395/// if there is an error, and Range is the source range to highlight 1396/// if there is an error. 1397bool 1398Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1399 unsigned InaccessibleBaseID, 1400 unsigned AmbigiousBaseConvID, 1401 SourceLocation Loc, SourceRange Range, 1402 DeclarationName Name, 1403 CXXCastPath *BasePath) { 1404 // First, determine whether the path from Derived to Base is 1405 // ambiguous. This is slightly more expensive than checking whether 1406 // the Derived to Base conversion exists, because here we need to 1407 // explore multiple paths to determine if there is an ambiguity. 1408 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1409 /*DetectVirtual=*/false); 1410 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths); 1411 assert(DerivationOkay && 1412 "Can only be used with a derived-to-base conversion"); 1413 (void)DerivationOkay; 1414 1415 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 1416 if (InaccessibleBaseID) { 1417 // Check that the base class can be accessed. 1418 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(), 1419 InaccessibleBaseID)) { 1420 case AR_inaccessible: 1421 return true; 1422 case AR_accessible: 1423 case AR_dependent: 1424 case AR_delayed: 1425 break; 1426 } 1427 } 1428 1429 // Build a base path if necessary. 1430 if (BasePath) 1431 BuildBasePathArray(Paths, *BasePath); 1432 return false; 1433 } 1434 1435 // We know that the derived-to-base conversion is ambiguous, and 1436 // we're going to produce a diagnostic. Perform the derived-to-base 1437 // search just one more time to compute all of the possible paths so 1438 // that we can print them out. This is more expensive than any of 1439 // the previous derived-to-base checks we've done, but at this point 1440 // performance isn't as much of an issue. 1441 Paths.clear(); 1442 Paths.setRecordingPaths(true); 1443 bool StillOkay = IsDerivedFrom(Derived, Base, Paths); 1444 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 1445 (void)StillOkay; 1446 1447 // Build up a textual representation of the ambiguous paths, e.g., 1448 // D -> B -> A, that will be used to illustrate the ambiguous 1449 // conversions in the diagnostic. We only print one of the paths 1450 // to each base class subobject. 1451 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 1452 1453 Diag(Loc, AmbigiousBaseConvID) 1454 << Derived << Base << PathDisplayStr << Range << Name; 1455 return true; 1456} 1457 1458bool 1459Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1460 SourceLocation Loc, SourceRange Range, 1461 CXXCastPath *BasePath, 1462 bool IgnoreAccess) { 1463 return CheckDerivedToBaseConversion(Derived, Base, 1464 IgnoreAccess ? 0 1465 : diag::err_upcast_to_inaccessible_base, 1466 diag::err_ambiguous_derived_to_base_conv, 1467 Loc, Range, DeclarationName(), 1468 BasePath); 1469} 1470 1471 1472/// @brief Builds a string representing ambiguous paths from a 1473/// specific derived class to different subobjects of the same base 1474/// class. 1475/// 1476/// This function builds a string that can be used in error messages 1477/// to show the different paths that one can take through the 1478/// inheritance hierarchy to go from the derived class to different 1479/// subobjects of a base class. The result looks something like this: 1480/// @code 1481/// struct D -> struct B -> struct A 1482/// struct D -> struct C -> struct A 1483/// @endcode 1484std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 1485 std::string PathDisplayStr; 1486 std::set<unsigned> DisplayedPaths; 1487 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 1488 Path != Paths.end(); ++Path) { 1489 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 1490 // We haven't displayed a path to this particular base 1491 // class subobject yet. 1492 PathDisplayStr += "\n "; 1493 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 1494 for (CXXBasePath::const_iterator Element = Path->begin(); 1495 Element != Path->end(); ++Element) 1496 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 1497 } 1498 } 1499 1500 return PathDisplayStr; 1501} 1502 1503//===----------------------------------------------------------------------===// 1504// C++ class member Handling 1505//===----------------------------------------------------------------------===// 1506 1507/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 1508bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, 1509 SourceLocation ASLoc, 1510 SourceLocation ColonLoc, 1511 AttributeList *Attrs) { 1512 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 1513 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 1514 ASLoc, ColonLoc); 1515 CurContext->addHiddenDecl(ASDecl); 1516 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 1517} 1518 1519/// CheckOverrideControl - Check C++11 override control semantics. 1520void Sema::CheckOverrideControl(Decl *D) { 1521 if (D->isInvalidDecl()) 1522 return; 1523 1524 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 1525 1526 // Do we know which functions this declaration might be overriding? 1527 bool OverridesAreKnown = !MD || 1528 (!MD->getParent()->hasAnyDependentBases() && 1529 !MD->getType()->isDependentType()); 1530 1531 if (!MD || !MD->isVirtual()) { 1532 if (OverridesAreKnown) { 1533 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1534 Diag(OA->getLocation(), 1535 diag::override_keyword_only_allowed_on_virtual_member_functions) 1536 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 1537 D->dropAttr<OverrideAttr>(); 1538 } 1539 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1540 Diag(FA->getLocation(), 1541 diag::override_keyword_only_allowed_on_virtual_member_functions) 1542 << "final" << FixItHint::CreateRemoval(FA->getLocation()); 1543 D->dropAttr<FinalAttr>(); 1544 } 1545 } 1546 return; 1547 } 1548 1549 if (!OverridesAreKnown) 1550 return; 1551 1552 // C++11 [class.virtual]p5: 1553 // If a virtual function is marked with the virt-specifier override and 1554 // does not override a member function of a base class, the program is 1555 // ill-formed. 1556 bool HasOverriddenMethods = 1557 MD->begin_overridden_methods() != MD->end_overridden_methods(); 1558 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 1559 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 1560 << MD->getDeclName(); 1561} 1562 1563/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 1564/// function overrides a virtual member function marked 'final', according to 1565/// C++11 [class.virtual]p4. 1566bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 1567 const CXXMethodDecl *Old) { 1568 if (!Old->hasAttr<FinalAttr>()) 1569 return false; 1570 1571 Diag(New->getLocation(), diag::err_final_function_overridden) 1572 << New->getDeclName(); 1573 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 1574 return true; 1575} 1576 1577static bool InitializationHasSideEffects(const FieldDecl &FD) { 1578 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 1579 // FIXME: Destruction of ObjC lifetime types has side-effects. 1580 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 1581 return !RD->isCompleteDefinition() || 1582 !RD->hasTrivialDefaultConstructor() || 1583 !RD->hasTrivialDestructor(); 1584 return false; 1585} 1586 1587/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 1588/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 1589/// bitfield width if there is one, 'InitExpr' specifies the initializer if 1590/// one has been parsed, and 'InitStyle' is set if an in-class initializer is 1591/// present (but parsing it has been deferred). 1592NamedDecl * 1593Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 1594 MultiTemplateParamsArg TemplateParameterLists, 1595 Expr *BW, const VirtSpecifiers &VS, 1596 InClassInitStyle InitStyle) { 1597 const DeclSpec &DS = D.getDeclSpec(); 1598 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 1599 DeclarationName Name = NameInfo.getName(); 1600 SourceLocation Loc = NameInfo.getLoc(); 1601 1602 // For anonymous bitfields, the location should point to the type. 1603 if (Loc.isInvalid()) 1604 Loc = D.getLocStart(); 1605 1606 Expr *BitWidth = static_cast<Expr*>(BW); 1607 1608 assert(isa<CXXRecordDecl>(CurContext)); 1609 assert(!DS.isFriendSpecified()); 1610 1611 bool isFunc = D.isDeclarationOfFunction(); 1612 1613 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 1614 // The Microsoft extension __interface only permits public member functions 1615 // and prohibits constructors, destructors, operators, non-public member 1616 // functions, static methods and data members. 1617 unsigned InvalidDecl; 1618 bool ShowDeclName = true; 1619 if (!isFunc) 1620 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1; 1621 else if (AS != AS_public) 1622 InvalidDecl = 2; 1623 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 1624 InvalidDecl = 3; 1625 else switch (Name.getNameKind()) { 1626 case DeclarationName::CXXConstructorName: 1627 InvalidDecl = 4; 1628 ShowDeclName = false; 1629 break; 1630 1631 case DeclarationName::CXXDestructorName: 1632 InvalidDecl = 5; 1633 ShowDeclName = false; 1634 break; 1635 1636 case DeclarationName::CXXOperatorName: 1637 case DeclarationName::CXXConversionFunctionName: 1638 InvalidDecl = 6; 1639 break; 1640 1641 default: 1642 InvalidDecl = 0; 1643 break; 1644 } 1645 1646 if (InvalidDecl) { 1647 if (ShowDeclName) 1648 Diag(Loc, diag::err_invalid_member_in_interface) 1649 << (InvalidDecl-1) << Name; 1650 else 1651 Diag(Loc, diag::err_invalid_member_in_interface) 1652 << (InvalidDecl-1) << ""; 1653 return 0; 1654 } 1655 } 1656 1657 // C++ 9.2p6: A member shall not be declared to have automatic storage 1658 // duration (auto, register) or with the extern storage-class-specifier. 1659 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 1660 // data members and cannot be applied to names declared const or static, 1661 // and cannot be applied to reference members. 1662 switch (DS.getStorageClassSpec()) { 1663 case DeclSpec::SCS_unspecified: 1664 case DeclSpec::SCS_typedef: 1665 case DeclSpec::SCS_static: 1666 // FALL THROUGH. 1667 break; 1668 case DeclSpec::SCS_mutable: 1669 if (isFunc) { 1670 if (DS.getStorageClassSpecLoc().isValid()) 1671 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 1672 else 1673 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function); 1674 1675 // FIXME: It would be nicer if the keyword was ignored only for this 1676 // declarator. Otherwise we could get follow-up errors. 1677 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1678 } 1679 break; 1680 default: 1681 if (DS.getStorageClassSpecLoc().isValid()) 1682 Diag(DS.getStorageClassSpecLoc(), 1683 diag::err_storageclass_invalid_for_member); 1684 else 1685 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member); 1686 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1687 } 1688 1689 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 1690 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 1691 !isFunc); 1692 1693 if (DS.isConstexprSpecified() && isInstField) { 1694 SemaDiagnosticBuilder B = 1695 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 1696 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 1697 if (InitStyle == ICIS_NoInit) { 1698 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const"); 1699 D.getMutableDeclSpec().ClearConstexprSpec(); 1700 const char *PrevSpec; 1701 unsigned DiagID; 1702 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc, 1703 PrevSpec, DiagID, getLangOpts()); 1704 (void)Failed; 1705 assert(!Failed && "Making a constexpr member const shouldn't fail"); 1706 } else { 1707 B << 1; 1708 const char *PrevSpec; 1709 unsigned DiagID; 1710 if (D.getMutableDeclSpec().SetStorageClassSpec( 1711 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) { 1712 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 1713 "This is the only DeclSpec that should fail to be applied"); 1714 B << 1; 1715 } else { 1716 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 1717 isInstField = false; 1718 } 1719 } 1720 } 1721 1722 NamedDecl *Member; 1723 if (isInstField) { 1724 CXXScopeSpec &SS = D.getCXXScopeSpec(); 1725 1726 // Data members must have identifiers for names. 1727 if (!Name.isIdentifier()) { 1728 Diag(Loc, diag::err_bad_variable_name) 1729 << Name; 1730 return 0; 1731 } 1732 1733 IdentifierInfo *II = Name.getAsIdentifierInfo(); 1734 1735 // Member field could not be with "template" keyword. 1736 // So TemplateParameterLists should be empty in this case. 1737 if (TemplateParameterLists.size()) { 1738 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 1739 if (TemplateParams->size()) { 1740 // There is no such thing as a member field template. 1741 Diag(D.getIdentifierLoc(), diag::err_template_member) 1742 << II 1743 << SourceRange(TemplateParams->getTemplateLoc(), 1744 TemplateParams->getRAngleLoc()); 1745 } else { 1746 // There is an extraneous 'template<>' for this member. 1747 Diag(TemplateParams->getTemplateLoc(), 1748 diag::err_template_member_noparams) 1749 << II 1750 << SourceRange(TemplateParams->getTemplateLoc(), 1751 TemplateParams->getRAngleLoc()); 1752 } 1753 return 0; 1754 } 1755 1756 if (SS.isSet() && !SS.isInvalid()) { 1757 // The user provided a superfluous scope specifier inside a class 1758 // definition: 1759 // 1760 // class X { 1761 // int X::member; 1762 // }; 1763 if (DeclContext *DC = computeDeclContext(SS, false)) 1764 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc()); 1765 else 1766 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 1767 << Name << SS.getRange(); 1768 1769 SS.clear(); 1770 } 1771 1772 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth, 1773 InitStyle, AS); 1774 assert(Member && "HandleField never returns null"); 1775 } else { 1776 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static); 1777 1778 Member = HandleDeclarator(S, D, TemplateParameterLists); 1779 if (!Member) { 1780 return 0; 1781 } 1782 1783 // Non-instance-fields can't have a bitfield. 1784 if (BitWidth) { 1785 if (Member->isInvalidDecl()) { 1786 // don't emit another diagnostic. 1787 } else if (isa<VarDecl>(Member)) { 1788 // C++ 9.6p3: A bit-field shall not be a static member. 1789 // "static member 'A' cannot be a bit-field" 1790 Diag(Loc, diag::err_static_not_bitfield) 1791 << Name << BitWidth->getSourceRange(); 1792 } else if (isa<TypedefDecl>(Member)) { 1793 // "typedef member 'x' cannot be a bit-field" 1794 Diag(Loc, diag::err_typedef_not_bitfield) 1795 << Name << BitWidth->getSourceRange(); 1796 } else { 1797 // A function typedef ("typedef int f(); f a;"). 1798 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 1799 Diag(Loc, diag::err_not_integral_type_bitfield) 1800 << Name << cast<ValueDecl>(Member)->getType() 1801 << BitWidth->getSourceRange(); 1802 } 1803 1804 BitWidth = 0; 1805 Member->setInvalidDecl(); 1806 } 1807 1808 Member->setAccess(AS); 1809 1810 // If we have declared a member function template, set the access of the 1811 // templated declaration as well. 1812 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 1813 FunTmpl->getTemplatedDecl()->setAccess(AS); 1814 } 1815 1816 if (VS.isOverrideSpecified()) 1817 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context)); 1818 if (VS.isFinalSpecified()) 1819 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context)); 1820 1821 if (VS.getLastLocation().isValid()) { 1822 // Update the end location of a method that has a virt-specifiers. 1823 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 1824 MD->setRangeEnd(VS.getLastLocation()); 1825 } 1826 1827 CheckOverrideControl(Member); 1828 1829 assert((Name || isInstField) && "No identifier for non-field ?"); 1830 1831 if (isInstField) { 1832 FieldDecl *FD = cast<FieldDecl>(Member); 1833 FieldCollector->Add(FD); 1834 1835 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field, 1836 FD->getLocation()) 1837 != DiagnosticsEngine::Ignored) { 1838 // Remember all explicit private FieldDecls that have a name, no side 1839 // effects and are not part of a dependent type declaration. 1840 if (!FD->isImplicit() && FD->getDeclName() && 1841 FD->getAccess() == AS_private && 1842 !FD->hasAttr<UnusedAttr>() && 1843 !FD->getParent()->isDependentContext() && 1844 !InitializationHasSideEffects(*FD)) 1845 UnusedPrivateFields.insert(FD); 1846 } 1847 } 1848 1849 return Member; 1850} 1851 1852namespace { 1853 class UninitializedFieldVisitor 1854 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 1855 Sema &S; 1856 ValueDecl *VD; 1857 public: 1858 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 1859 UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context), 1860 S(S) { 1861 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD)) 1862 this->VD = IFD->getAnonField(); 1863 else 1864 this->VD = VD; 1865 } 1866 1867 void HandleExpr(Expr *E) { 1868 if (!E) return; 1869 1870 // Expressions like x(x) sometimes lack the surrounding expressions 1871 // but need to be checked anyways. 1872 HandleValue(E); 1873 Visit(E); 1874 } 1875 1876 void HandleValue(Expr *E) { 1877 E = E->IgnoreParens(); 1878 1879 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 1880 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 1881 return; 1882 1883 // FieldME is the inner-most MemberExpr that is not an anonymous struct 1884 // or union. 1885 MemberExpr *FieldME = ME; 1886 1887 Expr *Base = E; 1888 while (isa<MemberExpr>(Base)) { 1889 ME = cast<MemberExpr>(Base); 1890 1891 if (isa<VarDecl>(ME->getMemberDecl())) 1892 return; 1893 1894 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 1895 if (!FD->isAnonymousStructOrUnion()) 1896 FieldME = ME; 1897 1898 Base = ME->getBase(); 1899 } 1900 1901 if (VD == FieldME->getMemberDecl() && isa<CXXThisExpr>(Base)) { 1902 unsigned diag = VD->getType()->isReferenceType() 1903 ? diag::warn_reference_field_is_uninit 1904 : diag::warn_field_is_uninit; 1905 S.Diag(FieldME->getExprLoc(), diag) << VD; 1906 } 1907 return; 1908 } 1909 1910 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 1911 HandleValue(CO->getTrueExpr()); 1912 HandleValue(CO->getFalseExpr()); 1913 return; 1914 } 1915 1916 if (BinaryConditionalOperator *BCO = 1917 dyn_cast<BinaryConditionalOperator>(E)) { 1918 HandleValue(BCO->getCommon()); 1919 HandleValue(BCO->getFalseExpr()); 1920 return; 1921 } 1922 1923 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 1924 switch (BO->getOpcode()) { 1925 default: 1926 return; 1927 case(BO_PtrMemD): 1928 case(BO_PtrMemI): 1929 HandleValue(BO->getLHS()); 1930 return; 1931 case(BO_Comma): 1932 HandleValue(BO->getRHS()); 1933 return; 1934 } 1935 } 1936 } 1937 1938 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 1939 if (E->getCastKind() == CK_LValueToRValue) 1940 HandleValue(E->getSubExpr()); 1941 1942 Inherited::VisitImplicitCastExpr(E); 1943 } 1944 1945 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 1946 Expr *Callee = E->getCallee(); 1947 if (isa<MemberExpr>(Callee)) 1948 HandleValue(Callee); 1949 1950 Inherited::VisitCXXMemberCallExpr(E); 1951 } 1952 }; 1953 static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E, 1954 ValueDecl *VD) { 1955 UninitializedFieldVisitor(S, VD).HandleExpr(E); 1956 } 1957} // namespace 1958 1959/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an 1960/// in-class initializer for a non-static C++ class member, and after 1961/// instantiating an in-class initializer in a class template. Such actions 1962/// are deferred until the class is complete. 1963void 1964Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc, 1965 Expr *InitExpr) { 1966 FieldDecl *FD = cast<FieldDecl>(D); 1967 assert(FD->getInClassInitStyle() != ICIS_NoInit && 1968 "must set init style when field is created"); 1969 1970 if (!InitExpr) { 1971 FD->setInvalidDecl(); 1972 FD->removeInClassInitializer(); 1973 return; 1974 } 1975 1976 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 1977 FD->setInvalidDecl(); 1978 FD->removeInClassInitializer(); 1979 return; 1980 } 1981 1982 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, InitLoc) 1983 != DiagnosticsEngine::Ignored) { 1984 CheckInitExprContainsUninitializedFields(*this, InitExpr, FD); 1985 } 1986 1987 ExprResult Init = InitExpr; 1988 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 1989 if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) { 1990 Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list) 1991 << /*at end of ctor*/1 << InitExpr->getSourceRange(); 1992 } 1993 Expr **Inits = &InitExpr; 1994 unsigned NumInits = 1; 1995 InitializedEntity Entity = InitializedEntity::InitializeMember(FD); 1996 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit 1997 ? InitializationKind::CreateDirectList(InitExpr->getLocStart()) 1998 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc); 1999 InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits); 2000 Init = Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits)); 2001 if (Init.isInvalid()) { 2002 FD->setInvalidDecl(); 2003 return; 2004 } 2005 } 2006 2007 // C++11 [class.base.init]p7: 2008 // The initialization of each base and member constitutes a 2009 // full-expression. 2010 Init = ActOnFinishFullExpr(Init.take(), InitLoc); 2011 if (Init.isInvalid()) { 2012 FD->setInvalidDecl(); 2013 return; 2014 } 2015 2016 InitExpr = Init.release(); 2017 2018 FD->setInClassInitializer(InitExpr); 2019} 2020 2021/// \brief Find the direct and/or virtual base specifiers that 2022/// correspond to the given base type, for use in base initialization 2023/// within a constructor. 2024static bool FindBaseInitializer(Sema &SemaRef, 2025 CXXRecordDecl *ClassDecl, 2026 QualType BaseType, 2027 const CXXBaseSpecifier *&DirectBaseSpec, 2028 const CXXBaseSpecifier *&VirtualBaseSpec) { 2029 // First, check for a direct base class. 2030 DirectBaseSpec = 0; 2031 for (CXXRecordDecl::base_class_const_iterator Base 2032 = ClassDecl->bases_begin(); 2033 Base != ClassDecl->bases_end(); ++Base) { 2034 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) { 2035 // We found a direct base of this type. That's what we're 2036 // initializing. 2037 DirectBaseSpec = &*Base; 2038 break; 2039 } 2040 } 2041 2042 // Check for a virtual base class. 2043 // FIXME: We might be able to short-circuit this if we know in advance that 2044 // there are no virtual bases. 2045 VirtualBaseSpec = 0; 2046 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 2047 // We haven't found a base yet; search the class hierarchy for a 2048 // virtual base class. 2049 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2050 /*DetectVirtual=*/false); 2051 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl), 2052 BaseType, Paths)) { 2053 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2054 Path != Paths.end(); ++Path) { 2055 if (Path->back().Base->isVirtual()) { 2056 VirtualBaseSpec = Path->back().Base; 2057 break; 2058 } 2059 } 2060 } 2061 } 2062 2063 return DirectBaseSpec || VirtualBaseSpec; 2064} 2065 2066/// \brief Handle a C++ member initializer using braced-init-list syntax. 2067MemInitResult 2068Sema::ActOnMemInitializer(Decl *ConstructorD, 2069 Scope *S, 2070 CXXScopeSpec &SS, 2071 IdentifierInfo *MemberOrBase, 2072 ParsedType TemplateTypeTy, 2073 const DeclSpec &DS, 2074 SourceLocation IdLoc, 2075 Expr *InitList, 2076 SourceLocation EllipsisLoc) { 2077 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2078 DS, IdLoc, InitList, 2079 EllipsisLoc); 2080} 2081 2082/// \brief Handle a C++ member initializer using parentheses syntax. 2083MemInitResult 2084Sema::ActOnMemInitializer(Decl *ConstructorD, 2085 Scope *S, 2086 CXXScopeSpec &SS, 2087 IdentifierInfo *MemberOrBase, 2088 ParsedType TemplateTypeTy, 2089 const DeclSpec &DS, 2090 SourceLocation IdLoc, 2091 SourceLocation LParenLoc, 2092 Expr **Args, unsigned NumArgs, 2093 SourceLocation RParenLoc, 2094 SourceLocation EllipsisLoc) { 2095 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, 2096 llvm::makeArrayRef(Args, NumArgs), 2097 RParenLoc); 2098 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2099 DS, IdLoc, List, EllipsisLoc); 2100} 2101 2102namespace { 2103 2104// Callback to only accept typo corrections that can be a valid C++ member 2105// intializer: either a non-static field member or a base class. 2106class MemInitializerValidatorCCC : public CorrectionCandidateCallback { 2107 public: 2108 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 2109 : ClassDecl(ClassDecl) {} 2110 2111 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 2112 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 2113 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 2114 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 2115 else 2116 return isa<TypeDecl>(ND); 2117 } 2118 return false; 2119 } 2120 2121 private: 2122 CXXRecordDecl *ClassDecl; 2123}; 2124 2125} 2126 2127/// \brief Handle a C++ member initializer. 2128MemInitResult 2129Sema::BuildMemInitializer(Decl *ConstructorD, 2130 Scope *S, 2131 CXXScopeSpec &SS, 2132 IdentifierInfo *MemberOrBase, 2133 ParsedType TemplateTypeTy, 2134 const DeclSpec &DS, 2135 SourceLocation IdLoc, 2136 Expr *Init, 2137 SourceLocation EllipsisLoc) { 2138 if (!ConstructorD) 2139 return true; 2140 2141 AdjustDeclIfTemplate(ConstructorD); 2142 2143 CXXConstructorDecl *Constructor 2144 = dyn_cast<CXXConstructorDecl>(ConstructorD); 2145 if (!Constructor) { 2146 // The user wrote a constructor initializer on a function that is 2147 // not a C++ constructor. Ignore the error for now, because we may 2148 // have more member initializers coming; we'll diagnose it just 2149 // once in ActOnMemInitializers. 2150 return true; 2151 } 2152 2153 CXXRecordDecl *ClassDecl = Constructor->getParent(); 2154 2155 // C++ [class.base.init]p2: 2156 // Names in a mem-initializer-id are looked up in the scope of the 2157 // constructor's class and, if not found in that scope, are looked 2158 // up in the scope containing the constructor's definition. 2159 // [Note: if the constructor's class contains a member with the 2160 // same name as a direct or virtual base class of the class, a 2161 // mem-initializer-id naming the member or base class and composed 2162 // of a single identifier refers to the class member. A 2163 // mem-initializer-id for the hidden base class may be specified 2164 // using a qualified name. ] 2165 if (!SS.getScopeRep() && !TemplateTypeTy) { 2166 // Look for a member, first. 2167 DeclContext::lookup_result Result 2168 = ClassDecl->lookup(MemberOrBase); 2169 if (!Result.empty()) { 2170 ValueDecl *Member; 2171 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 2172 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) { 2173 if (EllipsisLoc.isValid()) 2174 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 2175 << MemberOrBase 2176 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 2177 2178 return BuildMemberInitializer(Member, Init, IdLoc); 2179 } 2180 } 2181 } 2182 // It didn't name a member, so see if it names a class. 2183 QualType BaseType; 2184 TypeSourceInfo *TInfo = 0; 2185 2186 if (TemplateTypeTy) { 2187 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 2188 } else if (DS.getTypeSpecType() == TST_decltype) { 2189 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 2190 } else { 2191 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 2192 LookupParsedName(R, S, &SS); 2193 2194 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 2195 if (!TyD) { 2196 if (R.isAmbiguous()) return true; 2197 2198 // We don't want access-control diagnostics here. 2199 R.suppressDiagnostics(); 2200 2201 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 2202 bool NotUnknownSpecialization = false; 2203 DeclContext *DC = computeDeclContext(SS, false); 2204 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 2205 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 2206 2207 if (!NotUnknownSpecialization) { 2208 // When the scope specifier can refer to a member of an unknown 2209 // specialization, we take it as a type name. 2210 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 2211 SS.getWithLocInContext(Context), 2212 *MemberOrBase, IdLoc); 2213 if (BaseType.isNull()) 2214 return true; 2215 2216 R.clear(); 2217 R.setLookupName(MemberOrBase); 2218 } 2219 } 2220 2221 // If no results were found, try to correct typos. 2222 TypoCorrection Corr; 2223 MemInitializerValidatorCCC Validator(ClassDecl); 2224 if (R.empty() && BaseType.isNull() && 2225 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 2226 Validator, ClassDecl))) { 2227 std::string CorrectedStr(Corr.getAsString(getLangOpts())); 2228 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts())); 2229 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 2230 // We have found a non-static data member with a similar 2231 // name to what was typed; complain and initialize that 2232 // member. 2233 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest) 2234 << MemberOrBase << true << CorrectedQuotedStr 2235 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr); 2236 Diag(Member->getLocation(), diag::note_previous_decl) 2237 << CorrectedQuotedStr; 2238 2239 return BuildMemberInitializer(Member, Init, IdLoc); 2240 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 2241 const CXXBaseSpecifier *DirectBaseSpec; 2242 const CXXBaseSpecifier *VirtualBaseSpec; 2243 if (FindBaseInitializer(*this, ClassDecl, 2244 Context.getTypeDeclType(Type), 2245 DirectBaseSpec, VirtualBaseSpec)) { 2246 // We have found a direct or virtual base class with a 2247 // similar name to what was typed; complain and initialize 2248 // that base class. 2249 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest) 2250 << MemberOrBase << false << CorrectedQuotedStr 2251 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr); 2252 2253 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec 2254 : VirtualBaseSpec; 2255 Diag(BaseSpec->getLocStart(), 2256 diag::note_base_class_specified_here) 2257 << BaseSpec->getType() 2258 << BaseSpec->getSourceRange(); 2259 2260 TyD = Type; 2261 } 2262 } 2263 } 2264 2265 if (!TyD && BaseType.isNull()) { 2266 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 2267 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 2268 return true; 2269 } 2270 } 2271 2272 if (BaseType.isNull()) { 2273 BaseType = Context.getTypeDeclType(TyD); 2274 if (SS.isSet()) { 2275 NestedNameSpecifier *Qualifier = 2276 static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 2277 2278 // FIXME: preserve source range information 2279 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType); 2280 } 2281 } 2282 } 2283 2284 if (!TInfo) 2285 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 2286 2287 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 2288} 2289 2290/// Checks a member initializer expression for cases where reference (or 2291/// pointer) members are bound to by-value parameters (or their addresses). 2292static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member, 2293 Expr *Init, 2294 SourceLocation IdLoc) { 2295 QualType MemberTy = Member->getType(); 2296 2297 // We only handle pointers and references currently. 2298 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers? 2299 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType()) 2300 return; 2301 2302 const bool IsPointer = MemberTy->isPointerType(); 2303 if (IsPointer) { 2304 if (const UnaryOperator *Op 2305 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) { 2306 // The only case we're worried about with pointers requires taking the 2307 // address. 2308 if (Op->getOpcode() != UO_AddrOf) 2309 return; 2310 2311 Init = Op->getSubExpr(); 2312 } else { 2313 // We only handle address-of expression initializers for pointers. 2314 return; 2315 } 2316 } 2317 2318 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) { 2319 // Taking the address of a temporary will be diagnosed as a hard error. 2320 if (IsPointer) 2321 return; 2322 2323 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary) 2324 << Member << Init->getSourceRange(); 2325 } else if (const DeclRefExpr *DRE 2326 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) { 2327 // We only warn when referring to a non-reference parameter declaration. 2328 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl()); 2329 if (!Parameter || Parameter->getType()->isReferenceType()) 2330 return; 2331 2332 S.Diag(Init->getExprLoc(), 2333 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr 2334 : diag::warn_bind_ref_member_to_parameter) 2335 << Member << Parameter << Init->getSourceRange(); 2336 } else { 2337 // Other initializers are fine. 2338 return; 2339 } 2340 2341 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here) 2342 << (unsigned)IsPointer; 2343} 2344 2345MemInitResult 2346Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 2347 SourceLocation IdLoc) { 2348 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 2349 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 2350 assert((DirectMember || IndirectMember) && 2351 "Member must be a FieldDecl or IndirectFieldDecl"); 2352 2353 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 2354 return true; 2355 2356 if (Member->isInvalidDecl()) 2357 return true; 2358 2359 // Diagnose value-uses of fields to initialize themselves, e.g. 2360 // foo(foo) 2361 // where foo is not also a parameter to the constructor. 2362 // TODO: implement -Wuninitialized and fold this into that framework. 2363 Expr **Args; 2364 unsigned NumArgs; 2365 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2366 Args = ParenList->getExprs(); 2367 NumArgs = ParenList->getNumExprs(); 2368 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 2369 Args = InitList->getInits(); 2370 NumArgs = InitList->getNumInits(); 2371 } else { 2372 // Template instantiation doesn't reconstruct ParenListExprs for us. 2373 Args = &Init; 2374 NumArgs = 1; 2375 } 2376 2377 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc) 2378 != DiagnosticsEngine::Ignored) 2379 for (unsigned i = 0; i < NumArgs; ++i) 2380 // FIXME: Warn about the case when other fields are used before being 2381 // initialized. For example, let this field be the i'th field. When 2382 // initializing the i'th field, throw a warning if any of the >= i'th 2383 // fields are used, as they are not yet initialized. 2384 // Right now we are only handling the case where the i'th field uses 2385 // itself in its initializer. 2386 // Also need to take into account that some fields may be initialized by 2387 // in-class initializers, see C++11 [class.base.init]p9. 2388 CheckInitExprContainsUninitializedFields(*this, Args[i], Member); 2389 2390 SourceRange InitRange = Init->getSourceRange(); 2391 2392 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 2393 // Can't check initialization for a member of dependent type or when 2394 // any of the arguments are type-dependent expressions. 2395 DiscardCleanupsInEvaluationContext(); 2396 } else { 2397 bool InitList = false; 2398 if (isa<InitListExpr>(Init)) { 2399 InitList = true; 2400 Args = &Init; 2401 NumArgs = 1; 2402 2403 if (isStdInitializerList(Member->getType(), 0)) { 2404 Diag(IdLoc, diag::warn_dangling_std_initializer_list) 2405 << /*at end of ctor*/1 << InitRange; 2406 } 2407 } 2408 2409 // Initialize the member. 2410 InitializedEntity MemberEntity = 2411 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0) 2412 : InitializedEntity::InitializeMember(IndirectMember, 0); 2413 InitializationKind Kind = 2414 InitList ? InitializationKind::CreateDirectList(IdLoc) 2415 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 2416 InitRange.getEnd()); 2417 2418 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs); 2419 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, 2420 MultiExprArg(Args, NumArgs), 2421 0); 2422 if (MemberInit.isInvalid()) 2423 return true; 2424 2425 // C++11 [class.base.init]p7: 2426 // The initialization of each base and member constitutes a 2427 // full-expression. 2428 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin()); 2429 if (MemberInit.isInvalid()) 2430 return true; 2431 2432 Init = MemberInit.get(); 2433 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc); 2434 } 2435 2436 if (DirectMember) { 2437 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 2438 InitRange.getBegin(), Init, 2439 InitRange.getEnd()); 2440 } else { 2441 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 2442 InitRange.getBegin(), Init, 2443 InitRange.getEnd()); 2444 } 2445} 2446 2447MemInitResult 2448Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 2449 CXXRecordDecl *ClassDecl) { 2450 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 2451 if (!LangOpts.CPlusPlus11) 2452 return Diag(NameLoc, diag::err_delegating_ctor) 2453 << TInfo->getTypeLoc().getLocalSourceRange(); 2454 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 2455 2456 bool InitList = true; 2457 Expr **Args = &Init; 2458 unsigned NumArgs = 1; 2459 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2460 InitList = false; 2461 Args = ParenList->getExprs(); 2462 NumArgs = ParenList->getNumExprs(); 2463 } 2464 2465 SourceRange InitRange = Init->getSourceRange(); 2466 // Initialize the object. 2467 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 2468 QualType(ClassDecl->getTypeForDecl(), 0)); 2469 InitializationKind Kind = 2470 InitList ? InitializationKind::CreateDirectList(NameLoc) 2471 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 2472 InitRange.getEnd()); 2473 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs); 2474 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 2475 MultiExprArg(Args, NumArgs), 2476 0); 2477 if (DelegationInit.isInvalid()) 2478 return true; 2479 2480 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 2481 "Delegating constructor with no target?"); 2482 2483 // C++11 [class.base.init]p7: 2484 // The initialization of each base and member constitutes a 2485 // full-expression. 2486 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(), 2487 InitRange.getBegin()); 2488 if (DelegationInit.isInvalid()) 2489 return true; 2490 2491 // If we are in a dependent context, template instantiation will 2492 // perform this type-checking again. Just save the arguments that we 2493 // received in a ParenListExpr. 2494 // FIXME: This isn't quite ideal, since our ASTs don't capture all 2495 // of the information that we have about the base 2496 // initializer. However, deconstructing the ASTs is a dicey process, 2497 // and this approach is far more likely to get the corner cases right. 2498 if (CurContext->isDependentContext()) 2499 DelegationInit = Owned(Init); 2500 2501 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 2502 DelegationInit.takeAs<Expr>(), 2503 InitRange.getEnd()); 2504} 2505 2506MemInitResult 2507Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 2508 Expr *Init, CXXRecordDecl *ClassDecl, 2509 SourceLocation EllipsisLoc) { 2510 SourceLocation BaseLoc 2511 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 2512 2513 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 2514 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 2515 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2516 2517 // C++ [class.base.init]p2: 2518 // [...] Unless the mem-initializer-id names a nonstatic data 2519 // member of the constructor's class or a direct or virtual base 2520 // of that class, the mem-initializer is ill-formed. A 2521 // mem-initializer-list can initialize a base class using any 2522 // name that denotes that base class type. 2523 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 2524 2525 SourceRange InitRange = Init->getSourceRange(); 2526 if (EllipsisLoc.isValid()) { 2527 // This is a pack expansion. 2528 if (!BaseType->containsUnexpandedParameterPack()) { 2529 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2530 << SourceRange(BaseLoc, InitRange.getEnd()); 2531 2532 EllipsisLoc = SourceLocation(); 2533 } 2534 } else { 2535 // Check for any unexpanded parameter packs. 2536 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 2537 return true; 2538 2539 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 2540 return true; 2541 } 2542 2543 // Check for direct and virtual base classes. 2544 const CXXBaseSpecifier *DirectBaseSpec = 0; 2545 const CXXBaseSpecifier *VirtualBaseSpec = 0; 2546 if (!Dependent) { 2547 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 2548 BaseType)) 2549 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 2550 2551 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 2552 VirtualBaseSpec); 2553 2554 // C++ [base.class.init]p2: 2555 // Unless the mem-initializer-id names a nonstatic data member of the 2556 // constructor's class or a direct or virtual base of that class, the 2557 // mem-initializer is ill-formed. 2558 if (!DirectBaseSpec && !VirtualBaseSpec) { 2559 // If the class has any dependent bases, then it's possible that 2560 // one of those types will resolve to the same type as 2561 // BaseType. Therefore, just treat this as a dependent base 2562 // class initialization. FIXME: Should we try to check the 2563 // initialization anyway? It seems odd. 2564 if (ClassDecl->hasAnyDependentBases()) 2565 Dependent = true; 2566 else 2567 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 2568 << BaseType << Context.getTypeDeclType(ClassDecl) 2569 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2570 } 2571 } 2572 2573 if (Dependent) { 2574 DiscardCleanupsInEvaluationContext(); 2575 2576 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 2577 /*IsVirtual=*/false, 2578 InitRange.getBegin(), Init, 2579 InitRange.getEnd(), EllipsisLoc); 2580 } 2581 2582 // C++ [base.class.init]p2: 2583 // If a mem-initializer-id is ambiguous because it designates both 2584 // a direct non-virtual base class and an inherited virtual base 2585 // class, the mem-initializer is ill-formed. 2586 if (DirectBaseSpec && VirtualBaseSpec) 2587 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 2588 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2589 2590 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec); 2591 if (!BaseSpec) 2592 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec); 2593 2594 // Initialize the base. 2595 bool InitList = true; 2596 Expr **Args = &Init; 2597 unsigned NumArgs = 1; 2598 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2599 InitList = false; 2600 Args = ParenList->getExprs(); 2601 NumArgs = ParenList->getNumExprs(); 2602 } 2603 2604 InitializedEntity BaseEntity = 2605 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 2606 InitializationKind Kind = 2607 InitList ? InitializationKind::CreateDirectList(BaseLoc) 2608 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 2609 InitRange.getEnd()); 2610 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs); 2611 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, 2612 MultiExprArg(Args, NumArgs), 0); 2613 if (BaseInit.isInvalid()) 2614 return true; 2615 2616 // C++11 [class.base.init]p7: 2617 // The initialization of each base and member constitutes a 2618 // full-expression. 2619 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin()); 2620 if (BaseInit.isInvalid()) 2621 return true; 2622 2623 // If we are in a dependent context, template instantiation will 2624 // perform this type-checking again. Just save the arguments that we 2625 // received in a ParenListExpr. 2626 // FIXME: This isn't quite ideal, since our ASTs don't capture all 2627 // of the information that we have about the base 2628 // initializer. However, deconstructing the ASTs is a dicey process, 2629 // and this approach is far more likely to get the corner cases right. 2630 if (CurContext->isDependentContext()) 2631 BaseInit = Owned(Init); 2632 2633 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 2634 BaseSpec->isVirtual(), 2635 InitRange.getBegin(), 2636 BaseInit.takeAs<Expr>(), 2637 InitRange.getEnd(), EllipsisLoc); 2638} 2639 2640// Create a static_cast\<T&&>(expr). 2641static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 2642 if (T.isNull()) T = E->getType(); 2643 QualType TargetType = SemaRef.BuildReferenceType( 2644 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 2645 SourceLocation ExprLoc = E->getLocStart(); 2646 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 2647 TargetType, ExprLoc); 2648 2649 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 2650 SourceRange(ExprLoc, ExprLoc), 2651 E->getSourceRange()).take(); 2652} 2653 2654/// ImplicitInitializerKind - How an implicit base or member initializer should 2655/// initialize its base or member. 2656enum ImplicitInitializerKind { 2657 IIK_Default, 2658 IIK_Copy, 2659 IIK_Move, 2660 IIK_Inherit 2661}; 2662 2663static bool 2664BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 2665 ImplicitInitializerKind ImplicitInitKind, 2666 CXXBaseSpecifier *BaseSpec, 2667 bool IsInheritedVirtualBase, 2668 CXXCtorInitializer *&CXXBaseInit) { 2669 InitializedEntity InitEntity 2670 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 2671 IsInheritedVirtualBase); 2672 2673 ExprResult BaseInit; 2674 2675 switch (ImplicitInitKind) { 2676 case IIK_Inherit: { 2677 const CXXRecordDecl *Inherited = 2678 Constructor->getInheritedConstructor()->getParent(); 2679 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 2680 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) { 2681 // C++11 [class.inhctor]p8: 2682 // Each expression in the expression-list is of the form 2683 // static_cast<T&&>(p), where p is the name of the corresponding 2684 // constructor parameter and T is the declared type of p. 2685 SmallVector<Expr*, 16> Args; 2686 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) { 2687 ParmVarDecl *PD = Constructor->getParamDecl(I); 2688 ExprResult ArgExpr = 2689 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(), 2690 VK_LValue, SourceLocation()); 2691 if (ArgExpr.isInvalid()) 2692 return true; 2693 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType())); 2694 } 2695 2696 InitializationKind InitKind = InitializationKind::CreateDirect( 2697 Constructor->getLocation(), SourceLocation(), SourceLocation()); 2698 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 2699 Args.data(), Args.size()); 2700 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args); 2701 break; 2702 } 2703 } 2704 // Fall through. 2705 case IIK_Default: { 2706 InitializationKind InitKind 2707 = InitializationKind::CreateDefault(Constructor->getLocation()); 2708 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0); 2709 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg()); 2710 break; 2711 } 2712 2713 case IIK_Move: 2714 case IIK_Copy: { 2715 bool Moving = ImplicitInitKind == IIK_Move; 2716 ParmVarDecl *Param = Constructor->getParamDecl(0); 2717 QualType ParamType = Param->getType().getNonReferenceType(); 2718 2719 Expr *CopyCtorArg = 2720 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 2721 SourceLocation(), Param, false, 2722 Constructor->getLocation(), ParamType, 2723 VK_LValue, 0); 2724 2725 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 2726 2727 // Cast to the base class to avoid ambiguities. 2728 QualType ArgTy = 2729 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 2730 ParamType.getQualifiers()); 2731 2732 if (Moving) { 2733 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 2734 } 2735 2736 CXXCastPath BasePath; 2737 BasePath.push_back(BaseSpec); 2738 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 2739 CK_UncheckedDerivedToBase, 2740 Moving ? VK_XValue : VK_LValue, 2741 &BasePath).take(); 2742 2743 InitializationKind InitKind 2744 = InitializationKind::CreateDirect(Constructor->getLocation(), 2745 SourceLocation(), SourceLocation()); 2746 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 2747 &CopyCtorArg, 1); 2748 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, 2749 MultiExprArg(&CopyCtorArg, 1)); 2750 break; 2751 } 2752 } 2753 2754 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 2755 if (BaseInit.isInvalid()) 2756 return true; 2757 2758 CXXBaseInit = 2759 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 2760 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 2761 SourceLocation()), 2762 BaseSpec->isVirtual(), 2763 SourceLocation(), 2764 BaseInit.takeAs<Expr>(), 2765 SourceLocation(), 2766 SourceLocation()); 2767 2768 return false; 2769} 2770 2771static bool RefersToRValueRef(Expr *MemRef) { 2772 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 2773 return Referenced->getType()->isRValueReferenceType(); 2774} 2775 2776static bool 2777BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 2778 ImplicitInitializerKind ImplicitInitKind, 2779 FieldDecl *Field, IndirectFieldDecl *Indirect, 2780 CXXCtorInitializer *&CXXMemberInit) { 2781 if (Field->isInvalidDecl()) 2782 return true; 2783 2784 SourceLocation Loc = Constructor->getLocation(); 2785 2786 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 2787 bool Moving = ImplicitInitKind == IIK_Move; 2788 ParmVarDecl *Param = Constructor->getParamDecl(0); 2789 QualType ParamType = Param->getType().getNonReferenceType(); 2790 2791 // Suppress copying zero-width bitfields. 2792 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0) 2793 return false; 2794 2795 Expr *MemberExprBase = 2796 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 2797 SourceLocation(), Param, false, 2798 Loc, ParamType, VK_LValue, 0); 2799 2800 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 2801 2802 if (Moving) { 2803 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 2804 } 2805 2806 // Build a reference to this field within the parameter. 2807 CXXScopeSpec SS; 2808 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 2809 Sema::LookupMemberName); 2810 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 2811 : cast<ValueDecl>(Field), AS_public); 2812 MemberLookup.resolveKind(); 2813 ExprResult CtorArg 2814 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 2815 ParamType, Loc, 2816 /*IsArrow=*/false, 2817 SS, 2818 /*TemplateKWLoc=*/SourceLocation(), 2819 /*FirstQualifierInScope=*/0, 2820 MemberLookup, 2821 /*TemplateArgs=*/0); 2822 if (CtorArg.isInvalid()) 2823 return true; 2824 2825 // C++11 [class.copy]p15: 2826 // - if a member m has rvalue reference type T&&, it is direct-initialized 2827 // with static_cast<T&&>(x.m); 2828 if (RefersToRValueRef(CtorArg.get())) { 2829 CtorArg = CastForMoving(SemaRef, CtorArg.take()); 2830 } 2831 2832 // When the field we are copying is an array, create index variables for 2833 // each dimension of the array. We use these index variables to subscript 2834 // the source array, and other clients (e.g., CodeGen) will perform the 2835 // necessary iteration with these index variables. 2836 SmallVector<VarDecl *, 4> IndexVariables; 2837 QualType BaseType = Field->getType(); 2838 QualType SizeType = SemaRef.Context.getSizeType(); 2839 bool InitializingArray = false; 2840 while (const ConstantArrayType *Array 2841 = SemaRef.Context.getAsConstantArrayType(BaseType)) { 2842 InitializingArray = true; 2843 // Create the iteration variable for this array index. 2844 IdentifierInfo *IterationVarName = 0; 2845 { 2846 SmallString<8> Str; 2847 llvm::raw_svector_ostream OS(Str); 2848 OS << "__i" << IndexVariables.size(); 2849 IterationVarName = &SemaRef.Context.Idents.get(OS.str()); 2850 } 2851 VarDecl *IterationVar 2852 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc, 2853 IterationVarName, SizeType, 2854 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc), 2855 SC_None); 2856 IndexVariables.push_back(IterationVar); 2857 2858 // Create a reference to the iteration variable. 2859 ExprResult IterationVarRef 2860 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 2861 assert(!IterationVarRef.isInvalid() && 2862 "Reference to invented variable cannot fail!"); 2863 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take()); 2864 assert(!IterationVarRef.isInvalid() && 2865 "Conversion of invented variable cannot fail!"); 2866 2867 // Subscript the array with this iteration variable. 2868 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc, 2869 IterationVarRef.take(), 2870 Loc); 2871 if (CtorArg.isInvalid()) 2872 return true; 2873 2874 BaseType = Array->getElementType(); 2875 } 2876 2877 // The array subscript expression is an lvalue, which is wrong for moving. 2878 if (Moving && InitializingArray) 2879 CtorArg = CastForMoving(SemaRef, CtorArg.take()); 2880 2881 // Construct the entity that we will be initializing. For an array, this 2882 // will be first element in the array, which may require several levels 2883 // of array-subscript entities. 2884 SmallVector<InitializedEntity, 4> Entities; 2885 Entities.reserve(1 + IndexVariables.size()); 2886 if (Indirect) 2887 Entities.push_back(InitializedEntity::InitializeMember(Indirect)); 2888 else 2889 Entities.push_back(InitializedEntity::InitializeMember(Field)); 2890 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 2891 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context, 2892 0, 2893 Entities.back())); 2894 2895 // Direct-initialize to use the copy constructor. 2896 InitializationKind InitKind = 2897 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 2898 2899 Expr *CtorArgE = CtorArg.takeAs<Expr>(); 2900 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, 2901 &CtorArgE, 1); 2902 2903 ExprResult MemberInit 2904 = InitSeq.Perform(SemaRef, Entities.back(), InitKind, 2905 MultiExprArg(&CtorArgE, 1)); 2906 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 2907 if (MemberInit.isInvalid()) 2908 return true; 2909 2910 if (Indirect) { 2911 assert(IndexVariables.size() == 0 && 2912 "Indirect field improperly initialized"); 2913 CXXMemberInit 2914 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 2915 Loc, Loc, 2916 MemberInit.takeAs<Expr>(), 2917 Loc); 2918 } else 2919 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, 2920 Loc, MemberInit.takeAs<Expr>(), 2921 Loc, 2922 IndexVariables.data(), 2923 IndexVariables.size()); 2924 return false; 2925 } 2926 2927 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 2928 "Unhandled implicit init kind!"); 2929 2930 QualType FieldBaseElementType = 2931 SemaRef.Context.getBaseElementType(Field->getType()); 2932 2933 if (FieldBaseElementType->isRecordType()) { 2934 InitializedEntity InitEntity 2935 = Indirect? InitializedEntity::InitializeMember(Indirect) 2936 : InitializedEntity::InitializeMember(Field); 2937 InitializationKind InitKind = 2938 InitializationKind::CreateDefault(Loc); 2939 2940 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0); 2941 ExprResult MemberInit = 2942 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg()); 2943 2944 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 2945 if (MemberInit.isInvalid()) 2946 return true; 2947 2948 if (Indirect) 2949 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 2950 Indirect, Loc, 2951 Loc, 2952 MemberInit.get(), 2953 Loc); 2954 else 2955 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 2956 Field, Loc, Loc, 2957 MemberInit.get(), 2958 Loc); 2959 return false; 2960 } 2961 2962 if (!Field->getParent()->isUnion()) { 2963 if (FieldBaseElementType->isReferenceType()) { 2964 SemaRef.Diag(Constructor->getLocation(), 2965 diag::err_uninitialized_member_in_ctor) 2966 << (int)Constructor->isImplicit() 2967 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 2968 << 0 << Field->getDeclName(); 2969 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 2970 return true; 2971 } 2972 2973 if (FieldBaseElementType.isConstQualified()) { 2974 SemaRef.Diag(Constructor->getLocation(), 2975 diag::err_uninitialized_member_in_ctor) 2976 << (int)Constructor->isImplicit() 2977 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 2978 << 1 << Field->getDeclName(); 2979 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 2980 return true; 2981 } 2982 } 2983 2984 if (SemaRef.getLangOpts().ObjCAutoRefCount && 2985 FieldBaseElementType->isObjCRetainableType() && 2986 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None && 2987 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) { 2988 // ARC: 2989 // Default-initialize Objective-C pointers to NULL. 2990 CXXMemberInit 2991 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 2992 Loc, Loc, 2993 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 2994 Loc); 2995 return false; 2996 } 2997 2998 // Nothing to initialize. 2999 CXXMemberInit = 0; 3000 return false; 3001} 3002 3003namespace { 3004struct BaseAndFieldInfo { 3005 Sema &S; 3006 CXXConstructorDecl *Ctor; 3007 bool AnyErrorsInInits; 3008 ImplicitInitializerKind IIK; 3009 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 3010 SmallVector<CXXCtorInitializer*, 8> AllToInit; 3011 3012 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 3013 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 3014 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 3015 if (Generated && Ctor->isCopyConstructor()) 3016 IIK = IIK_Copy; 3017 else if (Generated && Ctor->isMoveConstructor()) 3018 IIK = IIK_Move; 3019 else if (Ctor->getInheritedConstructor()) 3020 IIK = IIK_Inherit; 3021 else 3022 IIK = IIK_Default; 3023 } 3024 3025 bool isImplicitCopyOrMove() const { 3026 switch (IIK) { 3027 case IIK_Copy: 3028 case IIK_Move: 3029 return true; 3030 3031 case IIK_Default: 3032 case IIK_Inherit: 3033 return false; 3034 } 3035 3036 llvm_unreachable("Invalid ImplicitInitializerKind!"); 3037 } 3038 3039 bool addFieldInitializer(CXXCtorInitializer *Init) { 3040 AllToInit.push_back(Init); 3041 3042 // Check whether this initializer makes the field "used". 3043 if (Init->getInit() && Init->getInit()->HasSideEffects(S.Context)) 3044 S.UnusedPrivateFields.remove(Init->getAnyMember()); 3045 3046 return false; 3047 } 3048}; 3049} 3050 3051/// \brief Determine whether the given indirect field declaration is somewhere 3052/// within an anonymous union. 3053static bool isWithinAnonymousUnion(IndirectFieldDecl *F) { 3054 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(), 3055 CEnd = F->chain_end(); 3056 C != CEnd; ++C) 3057 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext())) 3058 if (Record->isUnion()) 3059 return true; 3060 3061 return false; 3062} 3063 3064/// \brief Determine whether the given type is an incomplete or zero-lenfgth 3065/// array type. 3066static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 3067 if (T->isIncompleteArrayType()) 3068 return true; 3069 3070 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 3071 if (!ArrayT->getSize()) 3072 return true; 3073 3074 T = ArrayT->getElementType(); 3075 } 3076 3077 return false; 3078} 3079 3080static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 3081 FieldDecl *Field, 3082 IndirectFieldDecl *Indirect = 0) { 3083 3084 // Overwhelmingly common case: we have a direct initializer for this field. 3085 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) 3086 return Info.addFieldInitializer(Init); 3087 3088 // C++11 [class.base.init]p8: if the entity is a non-static data member that 3089 // has a brace-or-equal-initializer, the entity is initialized as specified 3090 // in [dcl.init]. 3091 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 3092 CXXCtorInitializer *Init; 3093 if (Indirect) 3094 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 3095 SourceLocation(), 3096 SourceLocation(), 0, 3097 SourceLocation()); 3098 else 3099 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 3100 SourceLocation(), 3101 SourceLocation(), 0, 3102 SourceLocation()); 3103 return Info.addFieldInitializer(Init); 3104 } 3105 3106 // Don't build an implicit initializer for union members if none was 3107 // explicitly specified. 3108 if (Field->getParent()->isUnion() || 3109 (Indirect && isWithinAnonymousUnion(Indirect))) 3110 return false; 3111 3112 // Don't initialize incomplete or zero-length arrays. 3113 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 3114 return false; 3115 3116 // Don't try to build an implicit initializer if there were semantic 3117 // errors in any of the initializers (and therefore we might be 3118 // missing some that the user actually wrote). 3119 if (Info.AnyErrorsInInits || Field->isInvalidDecl()) 3120 return false; 3121 3122 CXXCtorInitializer *Init = 0; 3123 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 3124 Indirect, Init)) 3125 return true; 3126 3127 if (!Init) 3128 return false; 3129 3130 return Info.addFieldInitializer(Init); 3131} 3132 3133bool 3134Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 3135 CXXCtorInitializer *Initializer) { 3136 assert(Initializer->isDelegatingInitializer()); 3137 Constructor->setNumCtorInitializers(1); 3138 CXXCtorInitializer **initializer = 3139 new (Context) CXXCtorInitializer*[1]; 3140 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 3141 Constructor->setCtorInitializers(initializer); 3142 3143 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 3144 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 3145 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 3146 } 3147 3148 DelegatingCtorDecls.push_back(Constructor); 3149 3150 return false; 3151} 3152 3153bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 3154 ArrayRef<CXXCtorInitializer *> Initializers) { 3155 if (Constructor->isDependentContext()) { 3156 // Just store the initializers as written, they will be checked during 3157 // instantiation. 3158 if (!Initializers.empty()) { 3159 Constructor->setNumCtorInitializers(Initializers.size()); 3160 CXXCtorInitializer **baseOrMemberInitializers = 3161 new (Context) CXXCtorInitializer*[Initializers.size()]; 3162 memcpy(baseOrMemberInitializers, Initializers.data(), 3163 Initializers.size() * sizeof(CXXCtorInitializer*)); 3164 Constructor->setCtorInitializers(baseOrMemberInitializers); 3165 } 3166 3167 // Let template instantiation know whether we had errors. 3168 if (AnyErrors) 3169 Constructor->setInvalidDecl(); 3170 3171 return false; 3172 } 3173 3174 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 3175 3176 // We need to build the initializer AST according to order of construction 3177 // and not what user specified in the Initializers list. 3178 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 3179 if (!ClassDecl) 3180 return true; 3181 3182 bool HadError = false; 3183 3184 for (unsigned i = 0; i < Initializers.size(); i++) { 3185 CXXCtorInitializer *Member = Initializers[i]; 3186 3187 if (Member->isBaseInitializer()) 3188 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 3189 else 3190 Info.AllBaseFields[Member->getAnyMember()] = Member; 3191 } 3192 3193 // Keep track of the direct virtual bases. 3194 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 3195 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(), 3196 E = ClassDecl->bases_end(); I != E; ++I) { 3197 if (I->isVirtual()) 3198 DirectVBases.insert(I); 3199 } 3200 3201 // Push virtual bases before others. 3202 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 3203 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 3204 3205 if (CXXCtorInitializer *Value 3206 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) { 3207 Info.AllToInit.push_back(Value); 3208 } else if (!AnyErrors) { 3209 bool IsInheritedVirtualBase = !DirectVBases.count(VBase); 3210 CXXCtorInitializer *CXXBaseInit; 3211 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3212 VBase, IsInheritedVirtualBase, 3213 CXXBaseInit)) { 3214 HadError = true; 3215 continue; 3216 } 3217 3218 Info.AllToInit.push_back(CXXBaseInit); 3219 } 3220 } 3221 3222 // Non-virtual bases. 3223 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 3224 E = ClassDecl->bases_end(); Base != E; ++Base) { 3225 // Virtuals are in the virtual base list and already constructed. 3226 if (Base->isVirtual()) 3227 continue; 3228 3229 if (CXXCtorInitializer *Value 3230 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) { 3231 Info.AllToInit.push_back(Value); 3232 } else if (!AnyErrors) { 3233 CXXCtorInitializer *CXXBaseInit; 3234 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3235 Base, /*IsInheritedVirtualBase=*/false, 3236 CXXBaseInit)) { 3237 HadError = true; 3238 continue; 3239 } 3240 3241 Info.AllToInit.push_back(CXXBaseInit); 3242 } 3243 } 3244 3245 // Fields. 3246 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(), 3247 MemEnd = ClassDecl->decls_end(); 3248 Mem != MemEnd; ++Mem) { 3249 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) { 3250 // C++ [class.bit]p2: 3251 // A declaration for a bit-field that omits the identifier declares an 3252 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 3253 // initialized. 3254 if (F->isUnnamedBitfield()) 3255 continue; 3256 3257 // If we're not generating the implicit copy/move constructor, then we'll 3258 // handle anonymous struct/union fields based on their individual 3259 // indirect fields. 3260 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 3261 continue; 3262 3263 if (CollectFieldInitializer(*this, Info, F)) 3264 HadError = true; 3265 continue; 3266 } 3267 3268 // Beyond this point, we only consider default initialization. 3269 if (Info.isImplicitCopyOrMove()) 3270 continue; 3271 3272 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) { 3273 if (F->getType()->isIncompleteArrayType()) { 3274 assert(ClassDecl->hasFlexibleArrayMember() && 3275 "Incomplete array type is not valid"); 3276 continue; 3277 } 3278 3279 // Initialize each field of an anonymous struct individually. 3280 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 3281 HadError = true; 3282 3283 continue; 3284 } 3285 } 3286 3287 unsigned NumInitializers = Info.AllToInit.size(); 3288 if (NumInitializers > 0) { 3289 Constructor->setNumCtorInitializers(NumInitializers); 3290 CXXCtorInitializer **baseOrMemberInitializers = 3291 new (Context) CXXCtorInitializer*[NumInitializers]; 3292 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 3293 NumInitializers * sizeof(CXXCtorInitializer*)); 3294 Constructor->setCtorInitializers(baseOrMemberInitializers); 3295 3296 // Constructors implicitly reference the base and member 3297 // destructors. 3298 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 3299 Constructor->getParent()); 3300 } 3301 3302 return HadError; 3303} 3304 3305static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 3306 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 3307 const RecordDecl *RD = RT->getDecl(); 3308 if (RD->isAnonymousStructOrUnion()) { 3309 for (RecordDecl::field_iterator Field = RD->field_begin(), 3310 E = RD->field_end(); Field != E; ++Field) 3311 PopulateKeysForFields(*Field, IdealInits); 3312 return; 3313 } 3314 } 3315 IdealInits.push_back(Field); 3316} 3317 3318static void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 3319 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr()); 3320} 3321 3322static void *GetKeyForMember(ASTContext &Context, 3323 CXXCtorInitializer *Member) { 3324 if (!Member->isAnyMemberInitializer()) 3325 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 3326 3327 return Member->getAnyMember(); 3328} 3329 3330static void DiagnoseBaseOrMemInitializerOrder( 3331 Sema &SemaRef, const CXXConstructorDecl *Constructor, 3332 ArrayRef<CXXCtorInitializer *> Inits) { 3333 if (Constructor->getDeclContext()->isDependentContext()) 3334 return; 3335 3336 // Don't check initializers order unless the warning is enabled at the 3337 // location of at least one initializer. 3338 bool ShouldCheckOrder = false; 3339 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 3340 CXXCtorInitializer *Init = Inits[InitIndex]; 3341 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order, 3342 Init->getSourceLocation()) 3343 != DiagnosticsEngine::Ignored) { 3344 ShouldCheckOrder = true; 3345 break; 3346 } 3347 } 3348 if (!ShouldCheckOrder) 3349 return; 3350 3351 // Build the list of bases and members in the order that they'll 3352 // actually be initialized. The explicit initializers should be in 3353 // this same order but may be missing things. 3354 SmallVector<const void*, 32> IdealInitKeys; 3355 3356 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 3357 3358 // 1. Virtual bases. 3359 for (CXXRecordDecl::base_class_const_iterator VBase = 3360 ClassDecl->vbases_begin(), 3361 E = ClassDecl->vbases_end(); VBase != E; ++VBase) 3362 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType())); 3363 3364 // 2. Non-virtual bases. 3365 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(), 3366 E = ClassDecl->bases_end(); Base != E; ++Base) { 3367 if (Base->isVirtual()) 3368 continue; 3369 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType())); 3370 } 3371 3372 // 3. Direct fields. 3373 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 3374 E = ClassDecl->field_end(); Field != E; ++Field) { 3375 if (Field->isUnnamedBitfield()) 3376 continue; 3377 3378 PopulateKeysForFields(*Field, IdealInitKeys); 3379 } 3380 3381 unsigned NumIdealInits = IdealInitKeys.size(); 3382 unsigned IdealIndex = 0; 3383 3384 CXXCtorInitializer *PrevInit = 0; 3385 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 3386 CXXCtorInitializer *Init = Inits[InitIndex]; 3387 void *InitKey = GetKeyForMember(SemaRef.Context, Init); 3388 3389 // Scan forward to try to find this initializer in the idealized 3390 // initializers list. 3391 for (; IdealIndex != NumIdealInits; ++IdealIndex) 3392 if (InitKey == IdealInitKeys[IdealIndex]) 3393 break; 3394 3395 // If we didn't find this initializer, it must be because we 3396 // scanned past it on a previous iteration. That can only 3397 // happen if we're out of order; emit a warning. 3398 if (IdealIndex == NumIdealInits && PrevInit) { 3399 Sema::SemaDiagnosticBuilder D = 3400 SemaRef.Diag(PrevInit->getSourceLocation(), 3401 diag::warn_initializer_out_of_order); 3402 3403 if (PrevInit->isAnyMemberInitializer()) 3404 D << 0 << PrevInit->getAnyMember()->getDeclName(); 3405 else 3406 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 3407 3408 if (Init->isAnyMemberInitializer()) 3409 D << 0 << Init->getAnyMember()->getDeclName(); 3410 else 3411 D << 1 << Init->getTypeSourceInfo()->getType(); 3412 3413 // Move back to the initializer's location in the ideal list. 3414 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 3415 if (InitKey == IdealInitKeys[IdealIndex]) 3416 break; 3417 3418 assert(IdealIndex != NumIdealInits && 3419 "initializer not found in initializer list"); 3420 } 3421 3422 PrevInit = Init; 3423 } 3424} 3425 3426namespace { 3427bool CheckRedundantInit(Sema &S, 3428 CXXCtorInitializer *Init, 3429 CXXCtorInitializer *&PrevInit) { 3430 if (!PrevInit) { 3431 PrevInit = Init; 3432 return false; 3433 } 3434 3435 if (FieldDecl *Field = Init->getAnyMember()) 3436 S.Diag(Init->getSourceLocation(), 3437 diag::err_multiple_mem_initialization) 3438 << Field->getDeclName() 3439 << Init->getSourceRange(); 3440 else { 3441 const Type *BaseClass = Init->getBaseClass(); 3442 assert(BaseClass && "neither field nor base"); 3443 S.Diag(Init->getSourceLocation(), 3444 diag::err_multiple_base_initialization) 3445 << QualType(BaseClass, 0) 3446 << Init->getSourceRange(); 3447 } 3448 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 3449 << 0 << PrevInit->getSourceRange(); 3450 3451 return true; 3452} 3453 3454typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 3455typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 3456 3457bool CheckRedundantUnionInit(Sema &S, 3458 CXXCtorInitializer *Init, 3459 RedundantUnionMap &Unions) { 3460 FieldDecl *Field = Init->getAnyMember(); 3461 RecordDecl *Parent = Field->getParent(); 3462 NamedDecl *Child = Field; 3463 3464 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 3465 if (Parent->isUnion()) { 3466 UnionEntry &En = Unions[Parent]; 3467 if (En.first && En.first != Child) { 3468 S.Diag(Init->getSourceLocation(), 3469 diag::err_multiple_mem_union_initialization) 3470 << Field->getDeclName() 3471 << Init->getSourceRange(); 3472 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 3473 << 0 << En.second->getSourceRange(); 3474 return true; 3475 } 3476 if (!En.first) { 3477 En.first = Child; 3478 En.second = Init; 3479 } 3480 if (!Parent->isAnonymousStructOrUnion()) 3481 return false; 3482 } 3483 3484 Child = Parent; 3485 Parent = cast<RecordDecl>(Parent->getDeclContext()); 3486 } 3487 3488 return false; 3489} 3490} 3491 3492/// ActOnMemInitializers - Handle the member initializers for a constructor. 3493void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 3494 SourceLocation ColonLoc, 3495 ArrayRef<CXXCtorInitializer*> MemInits, 3496 bool AnyErrors) { 3497 if (!ConstructorDecl) 3498 return; 3499 3500 AdjustDeclIfTemplate(ConstructorDecl); 3501 3502 CXXConstructorDecl *Constructor 3503 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 3504 3505 if (!Constructor) { 3506 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 3507 return; 3508 } 3509 3510 // Mapping for the duplicate initializers check. 3511 // For member initializers, this is keyed with a FieldDecl*. 3512 // For base initializers, this is keyed with a Type*. 3513 llvm::DenseMap<void*, CXXCtorInitializer *> Members; 3514 3515 // Mapping for the inconsistent anonymous-union initializers check. 3516 RedundantUnionMap MemberUnions; 3517 3518 bool HadError = false; 3519 for (unsigned i = 0; i < MemInits.size(); i++) { 3520 CXXCtorInitializer *Init = MemInits[i]; 3521 3522 // Set the source order index. 3523 Init->setSourceOrder(i); 3524 3525 if (Init->isAnyMemberInitializer()) { 3526 FieldDecl *Field = Init->getAnyMember(); 3527 if (CheckRedundantInit(*this, Init, Members[Field]) || 3528 CheckRedundantUnionInit(*this, Init, MemberUnions)) 3529 HadError = true; 3530 } else if (Init->isBaseInitializer()) { 3531 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0)); 3532 if (CheckRedundantInit(*this, Init, Members[Key])) 3533 HadError = true; 3534 } else { 3535 assert(Init->isDelegatingInitializer()); 3536 // This must be the only initializer 3537 if (MemInits.size() != 1) { 3538 Diag(Init->getSourceLocation(), 3539 diag::err_delegating_initializer_alone) 3540 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 3541 // We will treat this as being the only initializer. 3542 } 3543 SetDelegatingInitializer(Constructor, MemInits[i]); 3544 // Return immediately as the initializer is set. 3545 return; 3546 } 3547 } 3548 3549 if (HadError) 3550 return; 3551 3552 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 3553 3554 SetCtorInitializers(Constructor, AnyErrors, MemInits); 3555} 3556 3557void 3558Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 3559 CXXRecordDecl *ClassDecl) { 3560 // Ignore dependent contexts. Also ignore unions, since their members never 3561 // have destructors implicitly called. 3562 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 3563 return; 3564 3565 // FIXME: all the access-control diagnostics are positioned on the 3566 // field/base declaration. That's probably good; that said, the 3567 // user might reasonably want to know why the destructor is being 3568 // emitted, and we currently don't say. 3569 3570 // Non-static data members. 3571 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(), 3572 E = ClassDecl->field_end(); I != E; ++I) { 3573 FieldDecl *Field = *I; 3574 if (Field->isInvalidDecl()) 3575 continue; 3576 3577 // Don't destroy incomplete or zero-length arrays. 3578 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 3579 continue; 3580 3581 QualType FieldType = Context.getBaseElementType(Field->getType()); 3582 3583 const RecordType* RT = FieldType->getAs<RecordType>(); 3584 if (!RT) 3585 continue; 3586 3587 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3588 if (FieldClassDecl->isInvalidDecl()) 3589 continue; 3590 if (FieldClassDecl->hasIrrelevantDestructor()) 3591 continue; 3592 // The destructor for an implicit anonymous union member is never invoked. 3593 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 3594 continue; 3595 3596 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 3597 assert(Dtor && "No dtor found for FieldClassDecl!"); 3598 CheckDestructorAccess(Field->getLocation(), Dtor, 3599 PDiag(diag::err_access_dtor_field) 3600 << Field->getDeclName() 3601 << FieldType); 3602 3603 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 3604 DiagnoseUseOfDecl(Dtor, Location); 3605 } 3606 3607 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 3608 3609 // Bases. 3610 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 3611 E = ClassDecl->bases_end(); Base != E; ++Base) { 3612 // Bases are always records in a well-formed non-dependent class. 3613 const RecordType *RT = Base->getType()->getAs<RecordType>(); 3614 3615 // Remember direct virtual bases. 3616 if (Base->isVirtual()) 3617 DirectVirtualBases.insert(RT); 3618 3619 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3620 // If our base class is invalid, we probably can't get its dtor anyway. 3621 if (BaseClassDecl->isInvalidDecl()) 3622 continue; 3623 if (BaseClassDecl->hasIrrelevantDestructor()) 3624 continue; 3625 3626 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 3627 assert(Dtor && "No dtor found for BaseClassDecl!"); 3628 3629 // FIXME: caret should be on the start of the class name 3630 CheckDestructorAccess(Base->getLocStart(), Dtor, 3631 PDiag(diag::err_access_dtor_base) 3632 << Base->getType() 3633 << Base->getSourceRange(), 3634 Context.getTypeDeclType(ClassDecl)); 3635 3636 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 3637 DiagnoseUseOfDecl(Dtor, Location); 3638 } 3639 3640 // Virtual bases. 3641 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 3642 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 3643 3644 // Bases are always records in a well-formed non-dependent class. 3645 const RecordType *RT = VBase->getType()->castAs<RecordType>(); 3646 3647 // Ignore direct virtual bases. 3648 if (DirectVirtualBases.count(RT)) 3649 continue; 3650 3651 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3652 // If our base class is invalid, we probably can't get its dtor anyway. 3653 if (BaseClassDecl->isInvalidDecl()) 3654 continue; 3655 if (BaseClassDecl->hasIrrelevantDestructor()) 3656 continue; 3657 3658 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 3659 assert(Dtor && "No dtor found for BaseClassDecl!"); 3660 CheckDestructorAccess(ClassDecl->getLocation(), Dtor, 3661 PDiag(diag::err_access_dtor_vbase) 3662 << VBase->getType(), 3663 Context.getTypeDeclType(ClassDecl)); 3664 3665 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 3666 DiagnoseUseOfDecl(Dtor, Location); 3667 } 3668} 3669 3670void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 3671 if (!CDtorDecl) 3672 return; 3673 3674 if (CXXConstructorDecl *Constructor 3675 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) 3676 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 3677} 3678 3679bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 3680 unsigned DiagID, AbstractDiagSelID SelID) { 3681 class NonAbstractTypeDiagnoser : public TypeDiagnoser { 3682 unsigned DiagID; 3683 AbstractDiagSelID SelID; 3684 3685 public: 3686 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID) 3687 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { } 3688 3689 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 3690 if (Suppressed) return; 3691 if (SelID == -1) 3692 S.Diag(Loc, DiagID) << T; 3693 else 3694 S.Diag(Loc, DiagID) << SelID << T; 3695 } 3696 } Diagnoser(DiagID, SelID); 3697 3698 return RequireNonAbstractType(Loc, T, Diagnoser); 3699} 3700 3701bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 3702 TypeDiagnoser &Diagnoser) { 3703 if (!getLangOpts().CPlusPlus) 3704 return false; 3705 3706 if (const ArrayType *AT = Context.getAsArrayType(T)) 3707 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 3708 3709 if (const PointerType *PT = T->getAs<PointerType>()) { 3710 // Find the innermost pointer type. 3711 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 3712 PT = T; 3713 3714 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 3715 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 3716 } 3717 3718 const RecordType *RT = T->getAs<RecordType>(); 3719 if (!RT) 3720 return false; 3721 3722 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 3723 3724 // We can't answer whether something is abstract until it has a 3725 // definition. If it's currently being defined, we'll walk back 3726 // over all the declarations when we have a full definition. 3727 const CXXRecordDecl *Def = RD->getDefinition(); 3728 if (!Def || Def->isBeingDefined()) 3729 return false; 3730 3731 if (!RD->isAbstract()) 3732 return false; 3733 3734 Diagnoser.diagnose(*this, Loc, T); 3735 DiagnoseAbstractType(RD); 3736 3737 return true; 3738} 3739 3740void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 3741 // Check if we've already emitted the list of pure virtual functions 3742 // for this class. 3743 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 3744 return; 3745 3746 CXXFinalOverriderMap FinalOverriders; 3747 RD->getFinalOverriders(FinalOverriders); 3748 3749 // Keep a set of seen pure methods so we won't diagnose the same method 3750 // more than once. 3751 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 3752 3753 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 3754 MEnd = FinalOverriders.end(); 3755 M != MEnd; 3756 ++M) { 3757 for (OverridingMethods::iterator SO = M->second.begin(), 3758 SOEnd = M->second.end(); 3759 SO != SOEnd; ++SO) { 3760 // C++ [class.abstract]p4: 3761 // A class is abstract if it contains or inherits at least one 3762 // pure virtual function for which the final overrider is pure 3763 // virtual. 3764 3765 // 3766 if (SO->second.size() != 1) 3767 continue; 3768 3769 if (!SO->second.front().Method->isPure()) 3770 continue; 3771 3772 if (!SeenPureMethods.insert(SO->second.front().Method)) 3773 continue; 3774 3775 Diag(SO->second.front().Method->getLocation(), 3776 diag::note_pure_virtual_function) 3777 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 3778 } 3779 } 3780 3781 if (!PureVirtualClassDiagSet) 3782 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 3783 PureVirtualClassDiagSet->insert(RD); 3784} 3785 3786namespace { 3787struct AbstractUsageInfo { 3788 Sema &S; 3789 CXXRecordDecl *Record; 3790 CanQualType AbstractType; 3791 bool Invalid; 3792 3793 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 3794 : S(S), Record(Record), 3795 AbstractType(S.Context.getCanonicalType( 3796 S.Context.getTypeDeclType(Record))), 3797 Invalid(false) {} 3798 3799 void DiagnoseAbstractType() { 3800 if (Invalid) return; 3801 S.DiagnoseAbstractType(Record); 3802 Invalid = true; 3803 } 3804 3805 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 3806}; 3807 3808struct CheckAbstractUsage { 3809 AbstractUsageInfo &Info; 3810 const NamedDecl *Ctx; 3811 3812 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 3813 : Info(Info), Ctx(Ctx) {} 3814 3815 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 3816 switch (TL.getTypeLocClass()) { 3817#define ABSTRACT_TYPELOC(CLASS, PARENT) 3818#define TYPELOC(CLASS, PARENT) \ 3819 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 3820#include "clang/AST/TypeLocNodes.def" 3821 } 3822 } 3823 3824 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 3825 Visit(TL.getResultLoc(), Sema::AbstractReturnType); 3826 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 3827 if (!TL.getArg(I)) 3828 continue; 3829 3830 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo(); 3831 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 3832 } 3833 } 3834 3835 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 3836 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 3837 } 3838 3839 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 3840 // Visit the type parameters from a permissive context. 3841 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 3842 TemplateArgumentLoc TAL = TL.getArgLoc(I); 3843 if (TAL.getArgument().getKind() == TemplateArgument::Type) 3844 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 3845 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 3846 // TODO: other template argument types? 3847 } 3848 } 3849 3850 // Visit pointee types from a permissive context. 3851#define CheckPolymorphic(Type) \ 3852 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 3853 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 3854 } 3855 CheckPolymorphic(PointerTypeLoc) 3856 CheckPolymorphic(ReferenceTypeLoc) 3857 CheckPolymorphic(MemberPointerTypeLoc) 3858 CheckPolymorphic(BlockPointerTypeLoc) 3859 CheckPolymorphic(AtomicTypeLoc) 3860 3861 /// Handle all the types we haven't given a more specific 3862 /// implementation for above. 3863 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 3864 // Every other kind of type that we haven't called out already 3865 // that has an inner type is either (1) sugar or (2) contains that 3866 // inner type in some way as a subobject. 3867 if (TypeLoc Next = TL.getNextTypeLoc()) 3868 return Visit(Next, Sel); 3869 3870 // If there's no inner type and we're in a permissive context, 3871 // don't diagnose. 3872 if (Sel == Sema::AbstractNone) return; 3873 3874 // Check whether the type matches the abstract type. 3875 QualType T = TL.getType(); 3876 if (T->isArrayType()) { 3877 Sel = Sema::AbstractArrayType; 3878 T = Info.S.Context.getBaseElementType(T); 3879 } 3880 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 3881 if (CT != Info.AbstractType) return; 3882 3883 // It matched; do some magic. 3884 if (Sel == Sema::AbstractArrayType) { 3885 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 3886 << T << TL.getSourceRange(); 3887 } else { 3888 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 3889 << Sel << T << TL.getSourceRange(); 3890 } 3891 Info.DiagnoseAbstractType(); 3892 } 3893}; 3894 3895void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 3896 Sema::AbstractDiagSelID Sel) { 3897 CheckAbstractUsage(*this, D).Visit(TL, Sel); 3898} 3899 3900} 3901 3902/// Check for invalid uses of an abstract type in a method declaration. 3903static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 3904 CXXMethodDecl *MD) { 3905 // No need to do the check on definitions, which require that 3906 // the return/param types be complete. 3907 if (MD->doesThisDeclarationHaveABody()) 3908 return; 3909 3910 // For safety's sake, just ignore it if we don't have type source 3911 // information. This should never happen for non-implicit methods, 3912 // but... 3913 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 3914 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 3915} 3916 3917/// Check for invalid uses of an abstract type within a class definition. 3918static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 3919 CXXRecordDecl *RD) { 3920 for (CXXRecordDecl::decl_iterator 3921 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) { 3922 Decl *D = *I; 3923 if (D->isImplicit()) continue; 3924 3925 // Methods and method templates. 3926 if (isa<CXXMethodDecl>(D)) { 3927 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 3928 } else if (isa<FunctionTemplateDecl>(D)) { 3929 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 3930 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 3931 3932 // Fields and static variables. 3933 } else if (isa<FieldDecl>(D)) { 3934 FieldDecl *FD = cast<FieldDecl>(D); 3935 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 3936 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 3937 } else if (isa<VarDecl>(D)) { 3938 VarDecl *VD = cast<VarDecl>(D); 3939 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 3940 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 3941 3942 // Nested classes and class templates. 3943 } else if (isa<CXXRecordDecl>(D)) { 3944 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 3945 } else if (isa<ClassTemplateDecl>(D)) { 3946 CheckAbstractClassUsage(Info, 3947 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 3948 } 3949 } 3950} 3951 3952/// \brief Perform semantic checks on a class definition that has been 3953/// completing, introducing implicitly-declared members, checking for 3954/// abstract types, etc. 3955void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 3956 if (!Record) 3957 return; 3958 3959 if (Record->isAbstract() && !Record->isInvalidDecl()) { 3960 AbstractUsageInfo Info(*this, Record); 3961 CheckAbstractClassUsage(Info, Record); 3962 } 3963 3964 // If this is not an aggregate type and has no user-declared constructor, 3965 // complain about any non-static data members of reference or const scalar 3966 // type, since they will never get initializers. 3967 if (!Record->isInvalidDecl() && !Record->isDependentType() && 3968 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 3969 !Record->isLambda()) { 3970 bool Complained = false; 3971 for (RecordDecl::field_iterator F = Record->field_begin(), 3972 FEnd = Record->field_end(); 3973 F != FEnd; ++F) { 3974 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 3975 continue; 3976 3977 if (F->getType()->isReferenceType() || 3978 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 3979 if (!Complained) { 3980 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 3981 << Record->getTagKind() << Record; 3982 Complained = true; 3983 } 3984 3985 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 3986 << F->getType()->isReferenceType() 3987 << F->getDeclName(); 3988 } 3989 } 3990 } 3991 3992 if (Record->isDynamicClass() && !Record->isDependentType()) 3993 DynamicClasses.push_back(Record); 3994 3995 if (Record->getIdentifier()) { 3996 // C++ [class.mem]p13: 3997 // If T is the name of a class, then each of the following shall have a 3998 // name different from T: 3999 // - every member of every anonymous union that is a member of class T. 4000 // 4001 // C++ [class.mem]p14: 4002 // In addition, if class T has a user-declared constructor (12.1), every 4003 // non-static data member of class T shall have a name different from T. 4004 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 4005 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 4006 ++I) { 4007 NamedDecl *D = *I; 4008 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 4009 isa<IndirectFieldDecl>(D)) { 4010 Diag(D->getLocation(), diag::err_member_name_of_class) 4011 << D->getDeclName(); 4012 break; 4013 } 4014 } 4015 } 4016 4017 // Warn if the class has virtual methods but non-virtual public destructor. 4018 if (Record->isPolymorphic() && !Record->isDependentType()) { 4019 CXXDestructorDecl *dtor = Record->getDestructor(); 4020 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) 4021 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 4022 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 4023 } 4024 4025 if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) { 4026 Diag(Record->getLocation(), diag::warn_abstract_final_class); 4027 DiagnoseAbstractType(Record); 4028 } 4029 4030 if (!Record->isDependentType()) { 4031 for (CXXRecordDecl::method_iterator M = Record->method_begin(), 4032 MEnd = Record->method_end(); 4033 M != MEnd; ++M) { 4034 // See if a method overloads virtual methods in a base 4035 // class without overriding any. 4036 if (!M->isStatic()) 4037 DiagnoseHiddenVirtualMethods(Record, *M); 4038 4039 // Check whether the explicitly-defaulted special members are valid. 4040 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) 4041 CheckExplicitlyDefaultedSpecialMember(*M); 4042 4043 // For an explicitly defaulted or deleted special member, we defer 4044 // determining triviality until the class is complete. That time is now! 4045 if (!M->isImplicit() && !M->isUserProvided()) { 4046 CXXSpecialMember CSM = getSpecialMember(*M); 4047 if (CSM != CXXInvalid) { 4048 M->setTrivial(SpecialMemberIsTrivial(*M, CSM)); 4049 4050 // Inform the class that we've finished declaring this member. 4051 Record->finishedDefaultedOrDeletedMember(*M); 4052 } 4053 } 4054 } 4055 } 4056 4057 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member 4058 // function that is not a constructor declares that member function to be 4059 // const. [...] The class of which that function is a member shall be 4060 // a literal type. 4061 // 4062 // If the class has virtual bases, any constexpr members will already have 4063 // been diagnosed by the checks performed on the member declaration, so 4064 // suppress this (less useful) diagnostic. 4065 // 4066 // We delay this until we know whether an explicitly-defaulted (or deleted) 4067 // destructor for the class is trivial. 4068 if (LangOpts.CPlusPlus11 && !Record->isDependentType() && 4069 !Record->isLiteral() && !Record->getNumVBases()) { 4070 for (CXXRecordDecl::method_iterator M = Record->method_begin(), 4071 MEnd = Record->method_end(); 4072 M != MEnd; ++M) { 4073 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) { 4074 switch (Record->getTemplateSpecializationKind()) { 4075 case TSK_ImplicitInstantiation: 4076 case TSK_ExplicitInstantiationDeclaration: 4077 case TSK_ExplicitInstantiationDefinition: 4078 // If a template instantiates to a non-literal type, but its members 4079 // instantiate to constexpr functions, the template is technically 4080 // ill-formed, but we allow it for sanity. 4081 continue; 4082 4083 case TSK_Undeclared: 4084 case TSK_ExplicitSpecialization: 4085 RequireLiteralType(M->getLocation(), Context.getRecordType(Record), 4086 diag::err_constexpr_method_non_literal); 4087 break; 4088 } 4089 4090 // Only produce one error per class. 4091 break; 4092 } 4093 } 4094 } 4095 4096 // Declare inheriting constructors. We do this eagerly here because: 4097 // - The standard requires an eager diagnostic for conflicting inheriting 4098 // constructors from different classes. 4099 // - The lazy declaration of the other implicit constructors is so as to not 4100 // waste space and performance on classes that are not meant to be 4101 // instantiated (e.g. meta-functions). This doesn't apply to classes that 4102 // have inheriting constructors. 4103 DeclareInheritingConstructors(Record); 4104} 4105 4106/// Is the special member function which would be selected to perform the 4107/// specified operation on the specified class type a constexpr constructor? 4108static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 4109 Sema::CXXSpecialMember CSM, 4110 bool ConstArg) { 4111 Sema::SpecialMemberOverloadResult *SMOR = 4112 S.LookupSpecialMember(ClassDecl, CSM, ConstArg, 4113 false, false, false, false); 4114 if (!SMOR || !SMOR->getMethod()) 4115 // A constructor we wouldn't select can't be "involved in initializing" 4116 // anything. 4117 return true; 4118 return SMOR->getMethod()->isConstexpr(); 4119} 4120 4121/// Determine whether the specified special member function would be constexpr 4122/// if it were implicitly defined. 4123static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 4124 Sema::CXXSpecialMember CSM, 4125 bool ConstArg) { 4126 if (!S.getLangOpts().CPlusPlus11) 4127 return false; 4128 4129 // C++11 [dcl.constexpr]p4: 4130 // In the definition of a constexpr constructor [...] 4131 switch (CSM) { 4132 case Sema::CXXDefaultConstructor: 4133 // Since default constructor lookup is essentially trivial (and cannot 4134 // involve, for instance, template instantiation), we compute whether a 4135 // defaulted default constructor is constexpr directly within CXXRecordDecl. 4136 // 4137 // This is important for performance; we need to know whether the default 4138 // constructor is constexpr to determine whether the type is a literal type. 4139 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 4140 4141 case Sema::CXXCopyConstructor: 4142 case Sema::CXXMoveConstructor: 4143 // For copy or move constructors, we need to perform overload resolution. 4144 break; 4145 4146 case Sema::CXXCopyAssignment: 4147 case Sema::CXXMoveAssignment: 4148 case Sema::CXXDestructor: 4149 case Sema::CXXInvalid: 4150 return false; 4151 } 4152 4153 // -- if the class is a non-empty union, or for each non-empty anonymous 4154 // union member of a non-union class, exactly one non-static data member 4155 // shall be initialized; [DR1359] 4156 // 4157 // If we squint, this is guaranteed, since exactly one non-static data member 4158 // will be initialized (if the constructor isn't deleted), we just don't know 4159 // which one. 4160 if (ClassDecl->isUnion()) 4161 return true; 4162 4163 // -- the class shall not have any virtual base classes; 4164 if (ClassDecl->getNumVBases()) 4165 return false; 4166 4167 // -- every constructor involved in initializing [...] base class 4168 // sub-objects shall be a constexpr constructor; 4169 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 4170 BEnd = ClassDecl->bases_end(); 4171 B != BEnd; ++B) { 4172 const RecordType *BaseType = B->getType()->getAs<RecordType>(); 4173 if (!BaseType) continue; 4174 4175 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 4176 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg)) 4177 return false; 4178 } 4179 4180 // -- every constructor involved in initializing non-static data members 4181 // [...] shall be a constexpr constructor; 4182 // -- every non-static data member and base class sub-object shall be 4183 // initialized 4184 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 4185 FEnd = ClassDecl->field_end(); 4186 F != FEnd; ++F) { 4187 if (F->isInvalidDecl()) 4188 continue; 4189 if (const RecordType *RecordTy = 4190 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 4191 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 4192 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg)) 4193 return false; 4194 } 4195 } 4196 4197 // All OK, it's constexpr! 4198 return true; 4199} 4200 4201static Sema::ImplicitExceptionSpecification 4202computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 4203 switch (S.getSpecialMember(MD)) { 4204 case Sema::CXXDefaultConstructor: 4205 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD); 4206 case Sema::CXXCopyConstructor: 4207 return S.ComputeDefaultedCopyCtorExceptionSpec(MD); 4208 case Sema::CXXCopyAssignment: 4209 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD); 4210 case Sema::CXXMoveConstructor: 4211 return S.ComputeDefaultedMoveCtorExceptionSpec(MD); 4212 case Sema::CXXMoveAssignment: 4213 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD); 4214 case Sema::CXXDestructor: 4215 return S.ComputeDefaultedDtorExceptionSpec(MD); 4216 case Sema::CXXInvalid: 4217 break; 4218 } 4219 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() && 4220 "only special members have implicit exception specs"); 4221 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD)); 4222} 4223 4224static void 4225updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT, 4226 const Sema::ImplicitExceptionSpecification &ExceptSpec) { 4227 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 4228 ExceptSpec.getEPI(EPI); 4229 const FunctionProtoType *NewFPT = cast<FunctionProtoType>( 4230 S.Context.getFunctionType(FPT->getResultType(), FPT->getArgTypes(), EPI)); 4231 FD->setType(QualType(NewFPT, 0)); 4232} 4233 4234void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 4235 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 4236 if (FPT->getExceptionSpecType() != EST_Unevaluated) 4237 return; 4238 4239 // Evaluate the exception specification. 4240 ImplicitExceptionSpecification ExceptSpec = 4241 computeImplicitExceptionSpec(*this, Loc, MD); 4242 4243 // Update the type of the special member to use it. 4244 updateExceptionSpec(*this, MD, FPT, ExceptSpec); 4245 4246 // A user-provided destructor can be defined outside the class. When that 4247 // happens, be sure to update the exception specification on both 4248 // declarations. 4249 const FunctionProtoType *CanonicalFPT = 4250 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 4251 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 4252 updateExceptionSpec(*this, MD->getCanonicalDecl(), 4253 CanonicalFPT, ExceptSpec); 4254} 4255 4256void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 4257 CXXRecordDecl *RD = MD->getParent(); 4258 CXXSpecialMember CSM = getSpecialMember(MD); 4259 4260 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 4261 "not an explicitly-defaulted special member"); 4262 4263 // Whether this was the first-declared instance of the constructor. 4264 // This affects whether we implicitly add an exception spec and constexpr. 4265 bool First = MD == MD->getCanonicalDecl(); 4266 4267 bool HadError = false; 4268 4269 // C++11 [dcl.fct.def.default]p1: 4270 // A function that is explicitly defaulted shall 4271 // -- be a special member function (checked elsewhere), 4272 // -- have the same type (except for ref-qualifiers, and except that a 4273 // copy operation can take a non-const reference) as an implicit 4274 // declaration, and 4275 // -- not have default arguments. 4276 unsigned ExpectedParams = 1; 4277 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 4278 ExpectedParams = 0; 4279 if (MD->getNumParams() != ExpectedParams) { 4280 // This also checks for default arguments: a copy or move constructor with a 4281 // default argument is classified as a default constructor, and assignment 4282 // operations and destructors can't have default arguments. 4283 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 4284 << CSM << MD->getSourceRange(); 4285 HadError = true; 4286 } else if (MD->isVariadic()) { 4287 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 4288 << CSM << MD->getSourceRange(); 4289 HadError = true; 4290 } 4291 4292 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 4293 4294 bool CanHaveConstParam = false; 4295 if (CSM == CXXCopyConstructor) 4296 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 4297 else if (CSM == CXXCopyAssignment) 4298 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 4299 4300 QualType ReturnType = Context.VoidTy; 4301 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 4302 // Check for return type matching. 4303 ReturnType = Type->getResultType(); 4304 QualType ExpectedReturnType = 4305 Context.getLValueReferenceType(Context.getTypeDeclType(RD)); 4306 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 4307 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 4308 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 4309 HadError = true; 4310 } 4311 4312 // A defaulted special member cannot have cv-qualifiers. 4313 if (Type->getTypeQuals()) { 4314 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 4315 << (CSM == CXXMoveAssignment); 4316 HadError = true; 4317 } 4318 } 4319 4320 // Check for parameter type matching. 4321 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType(); 4322 bool HasConstParam = false; 4323 if (ExpectedParams && ArgType->isReferenceType()) { 4324 // Argument must be reference to possibly-const T. 4325 QualType ReferentType = ArgType->getPointeeType(); 4326 HasConstParam = ReferentType.isConstQualified(); 4327 4328 if (ReferentType.isVolatileQualified()) { 4329 Diag(MD->getLocation(), 4330 diag::err_defaulted_special_member_volatile_param) << CSM; 4331 HadError = true; 4332 } 4333 4334 if (HasConstParam && !CanHaveConstParam) { 4335 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 4336 Diag(MD->getLocation(), 4337 diag::err_defaulted_special_member_copy_const_param) 4338 << (CSM == CXXCopyAssignment); 4339 // FIXME: Explain why this special member can't be const. 4340 } else { 4341 Diag(MD->getLocation(), 4342 diag::err_defaulted_special_member_move_const_param) 4343 << (CSM == CXXMoveAssignment); 4344 } 4345 HadError = true; 4346 } 4347 } else if (ExpectedParams) { 4348 // A copy assignment operator can take its argument by value, but a 4349 // defaulted one cannot. 4350 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 4351 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 4352 HadError = true; 4353 } 4354 4355 // C++11 [dcl.fct.def.default]p2: 4356 // An explicitly-defaulted function may be declared constexpr only if it 4357 // would have been implicitly declared as constexpr, 4358 // Do not apply this rule to members of class templates, since core issue 1358 4359 // makes such functions always instantiate to constexpr functions. For 4360 // non-constructors, this is checked elsewhere. 4361 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 4362 HasConstParam); 4363 if (isa<CXXConstructorDecl>(MD) && MD->isConstexpr() && !Constexpr && 4364 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 4365 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM; 4366 // FIXME: Explain why the constructor can't be constexpr. 4367 HadError = true; 4368 } 4369 4370 // and may have an explicit exception-specification only if it is compatible 4371 // with the exception-specification on the implicit declaration. 4372 if (Type->hasExceptionSpec()) { 4373 // Delay the check if this is the first declaration of the special member, 4374 // since we may not have parsed some necessary in-class initializers yet. 4375 if (First) { 4376 // If the exception specification needs to be instantiated, do so now, 4377 // before we clobber it with an EST_Unevaluated specification below. 4378 if (Type->getExceptionSpecType() == EST_Uninstantiated) { 4379 InstantiateExceptionSpec(MD->getLocStart(), MD); 4380 Type = MD->getType()->getAs<FunctionProtoType>(); 4381 } 4382 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type)); 4383 } else 4384 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type); 4385 } 4386 4387 // If a function is explicitly defaulted on its first declaration, 4388 if (First) { 4389 // -- it is implicitly considered to be constexpr if the implicit 4390 // definition would be, 4391 MD->setConstexpr(Constexpr); 4392 4393 // -- it is implicitly considered to have the same exception-specification 4394 // as if it had been implicitly declared, 4395 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 4396 EPI.ExceptionSpecType = EST_Unevaluated; 4397 EPI.ExceptionSpecDecl = MD; 4398 MD->setType(Context.getFunctionType(ReturnType, 4399 ArrayRef<QualType>(&ArgType, 4400 ExpectedParams), 4401 EPI)); 4402 } 4403 4404 if (ShouldDeleteSpecialMember(MD, CSM)) { 4405 if (First) { 4406 SetDeclDeleted(MD, MD->getLocation()); 4407 } else { 4408 // C++11 [dcl.fct.def.default]p4: 4409 // [For a] user-provided explicitly-defaulted function [...] if such a 4410 // function is implicitly defined as deleted, the program is ill-formed. 4411 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 4412 HadError = true; 4413 } 4414 } 4415 4416 if (HadError) 4417 MD->setInvalidDecl(); 4418} 4419 4420/// Check whether the exception specification provided for an 4421/// explicitly-defaulted special member matches the exception specification 4422/// that would have been generated for an implicit special member, per 4423/// C++11 [dcl.fct.def.default]p2. 4424void Sema::CheckExplicitlyDefaultedMemberExceptionSpec( 4425 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) { 4426 // Compute the implicit exception specification. 4427 FunctionProtoType::ExtProtoInfo EPI; 4428 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI); 4429 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>( 4430 Context.getFunctionType(Context.VoidTy, ArrayRef<QualType>(), EPI)); 4431 4432 // Ensure that it matches. 4433 CheckEquivalentExceptionSpec( 4434 PDiag(diag::err_incorrect_defaulted_exception_spec) 4435 << getSpecialMember(MD), PDiag(), 4436 ImplicitType, SourceLocation(), 4437 SpecifiedType, MD->getLocation()); 4438} 4439 4440void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() { 4441 for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size(); 4442 I != N; ++I) 4443 CheckExplicitlyDefaultedMemberExceptionSpec( 4444 DelayedDefaultedMemberExceptionSpecs[I].first, 4445 DelayedDefaultedMemberExceptionSpecs[I].second); 4446 4447 DelayedDefaultedMemberExceptionSpecs.clear(); 4448} 4449 4450namespace { 4451struct SpecialMemberDeletionInfo { 4452 Sema &S; 4453 CXXMethodDecl *MD; 4454 Sema::CXXSpecialMember CSM; 4455 bool Diagnose; 4456 4457 // Properties of the special member, computed for convenience. 4458 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg; 4459 SourceLocation Loc; 4460 4461 bool AllFieldsAreConst; 4462 4463 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 4464 Sema::CXXSpecialMember CSM, bool Diagnose) 4465 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose), 4466 IsConstructor(false), IsAssignment(false), IsMove(false), 4467 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()), 4468 AllFieldsAreConst(true) { 4469 switch (CSM) { 4470 case Sema::CXXDefaultConstructor: 4471 case Sema::CXXCopyConstructor: 4472 IsConstructor = true; 4473 break; 4474 case Sema::CXXMoveConstructor: 4475 IsConstructor = true; 4476 IsMove = true; 4477 break; 4478 case Sema::CXXCopyAssignment: 4479 IsAssignment = true; 4480 break; 4481 case Sema::CXXMoveAssignment: 4482 IsAssignment = true; 4483 IsMove = true; 4484 break; 4485 case Sema::CXXDestructor: 4486 break; 4487 case Sema::CXXInvalid: 4488 llvm_unreachable("invalid special member kind"); 4489 } 4490 4491 if (MD->getNumParams()) { 4492 ConstArg = MD->getParamDecl(0)->getType().isConstQualified(); 4493 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified(); 4494 } 4495 } 4496 4497 bool inUnion() const { return MD->getParent()->isUnion(); } 4498 4499 /// Look up the corresponding special member in the given class. 4500 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class, 4501 unsigned Quals) { 4502 unsigned TQ = MD->getTypeQualifiers(); 4503 // cv-qualifiers on class members don't affect default ctor / dtor calls. 4504 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 4505 Quals = 0; 4506 return S.LookupSpecialMember(Class, CSM, 4507 ConstArg || (Quals & Qualifiers::Const), 4508 VolatileArg || (Quals & Qualifiers::Volatile), 4509 MD->getRefQualifier() == RQ_RValue, 4510 TQ & Qualifiers::Const, 4511 TQ & Qualifiers::Volatile); 4512 } 4513 4514 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 4515 4516 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 4517 bool shouldDeleteForField(FieldDecl *FD); 4518 bool shouldDeleteForAllConstMembers(); 4519 4520 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 4521 unsigned Quals); 4522 bool shouldDeleteForSubobjectCall(Subobject Subobj, 4523 Sema::SpecialMemberOverloadResult *SMOR, 4524 bool IsDtorCallInCtor); 4525 4526 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 4527}; 4528} 4529 4530/// Is the given special member inaccessible when used on the given 4531/// sub-object. 4532bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 4533 CXXMethodDecl *target) { 4534 /// If we're operating on a base class, the object type is the 4535 /// type of this special member. 4536 QualType objectTy; 4537 AccessSpecifier access = target->getAccess(); 4538 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 4539 objectTy = S.Context.getTypeDeclType(MD->getParent()); 4540 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 4541 4542 // If we're operating on a field, the object type is the type of the field. 4543 } else { 4544 objectTy = S.Context.getTypeDeclType(target->getParent()); 4545 } 4546 4547 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 4548} 4549 4550/// Check whether we should delete a special member due to the implicit 4551/// definition containing a call to a special member of a subobject. 4552bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 4553 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR, 4554 bool IsDtorCallInCtor) { 4555 CXXMethodDecl *Decl = SMOR->getMethod(); 4556 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 4557 4558 int DiagKind = -1; 4559 4560 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 4561 DiagKind = !Decl ? 0 : 1; 4562 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 4563 DiagKind = 2; 4564 else if (!isAccessible(Subobj, Decl)) 4565 DiagKind = 3; 4566 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 4567 !Decl->isTrivial()) { 4568 // A member of a union must have a trivial corresponding special member. 4569 // As a weird special case, a destructor call from a union's constructor 4570 // must be accessible and non-deleted, but need not be trivial. Such a 4571 // destructor is never actually called, but is semantically checked as 4572 // if it were. 4573 DiagKind = 4; 4574 } 4575 4576 if (DiagKind == -1) 4577 return false; 4578 4579 if (Diagnose) { 4580 if (Field) { 4581 S.Diag(Field->getLocation(), 4582 diag::note_deleted_special_member_class_subobject) 4583 << CSM << MD->getParent() << /*IsField*/true 4584 << Field << DiagKind << IsDtorCallInCtor; 4585 } else { 4586 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 4587 S.Diag(Base->getLocStart(), 4588 diag::note_deleted_special_member_class_subobject) 4589 << CSM << MD->getParent() << /*IsField*/false 4590 << Base->getType() << DiagKind << IsDtorCallInCtor; 4591 } 4592 4593 if (DiagKind == 1) 4594 S.NoteDeletedFunction(Decl); 4595 // FIXME: Explain inaccessibility if DiagKind == 3. 4596 } 4597 4598 return true; 4599} 4600 4601/// Check whether we should delete a special member function due to having a 4602/// direct or virtual base class or non-static data member of class type M. 4603bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 4604 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 4605 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 4606 4607 // C++11 [class.ctor]p5: 4608 // -- any direct or virtual base class, or non-static data member with no 4609 // brace-or-equal-initializer, has class type M (or array thereof) and 4610 // either M has no default constructor or overload resolution as applied 4611 // to M's default constructor results in an ambiguity or in a function 4612 // that is deleted or inaccessible 4613 // C++11 [class.copy]p11, C++11 [class.copy]p23: 4614 // -- a direct or virtual base class B that cannot be copied/moved because 4615 // overload resolution, as applied to B's corresponding special member, 4616 // results in an ambiguity or a function that is deleted or inaccessible 4617 // from the defaulted special member 4618 // C++11 [class.dtor]p5: 4619 // -- any direct or virtual base class [...] has a type with a destructor 4620 // that is deleted or inaccessible 4621 if (!(CSM == Sema::CXXDefaultConstructor && 4622 Field && Field->hasInClassInitializer()) && 4623 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false)) 4624 return true; 4625 4626 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 4627 // -- any direct or virtual base class or non-static data member has a 4628 // type with a destructor that is deleted or inaccessible 4629 if (IsConstructor) { 4630 Sema::SpecialMemberOverloadResult *SMOR = 4631 S.LookupSpecialMember(Class, Sema::CXXDestructor, 4632 false, false, false, false, false); 4633 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 4634 return true; 4635 } 4636 4637 return false; 4638} 4639 4640/// Check whether we should delete a special member function due to the class 4641/// having a particular direct or virtual base class. 4642bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 4643 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 4644 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 4645} 4646 4647/// Check whether we should delete a special member function due to the class 4648/// having a particular non-static data member. 4649bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 4650 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 4651 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 4652 4653 if (CSM == Sema::CXXDefaultConstructor) { 4654 // For a default constructor, all references must be initialized in-class 4655 // and, if a union, it must have a non-const member. 4656 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 4657 if (Diagnose) 4658 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 4659 << MD->getParent() << FD << FieldType << /*Reference*/0; 4660 return true; 4661 } 4662 // C++11 [class.ctor]p5: any non-variant non-static data member of 4663 // const-qualified type (or array thereof) with no 4664 // brace-or-equal-initializer does not have a user-provided default 4665 // constructor. 4666 if (!inUnion() && FieldType.isConstQualified() && 4667 !FD->hasInClassInitializer() && 4668 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 4669 if (Diagnose) 4670 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 4671 << MD->getParent() << FD << FD->getType() << /*Const*/1; 4672 return true; 4673 } 4674 4675 if (inUnion() && !FieldType.isConstQualified()) 4676 AllFieldsAreConst = false; 4677 } else if (CSM == Sema::CXXCopyConstructor) { 4678 // For a copy constructor, data members must not be of rvalue reference 4679 // type. 4680 if (FieldType->isRValueReferenceType()) { 4681 if (Diagnose) 4682 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 4683 << MD->getParent() << FD << FieldType; 4684 return true; 4685 } 4686 } else if (IsAssignment) { 4687 // For an assignment operator, data members must not be of reference type. 4688 if (FieldType->isReferenceType()) { 4689 if (Diagnose) 4690 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 4691 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0; 4692 return true; 4693 } 4694 if (!FieldRecord && FieldType.isConstQualified()) { 4695 // C++11 [class.copy]p23: 4696 // -- a non-static data member of const non-class type (or array thereof) 4697 if (Diagnose) 4698 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 4699 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1; 4700 return true; 4701 } 4702 } 4703 4704 if (FieldRecord) { 4705 // Some additional restrictions exist on the variant members. 4706 if (!inUnion() && FieldRecord->isUnion() && 4707 FieldRecord->isAnonymousStructOrUnion()) { 4708 bool AllVariantFieldsAreConst = true; 4709 4710 // FIXME: Handle anonymous unions declared within anonymous unions. 4711 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(), 4712 UE = FieldRecord->field_end(); 4713 UI != UE; ++UI) { 4714 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 4715 4716 if (!UnionFieldType.isConstQualified()) 4717 AllVariantFieldsAreConst = false; 4718 4719 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 4720 if (UnionFieldRecord && 4721 shouldDeleteForClassSubobject(UnionFieldRecord, *UI, 4722 UnionFieldType.getCVRQualifiers())) 4723 return true; 4724 } 4725 4726 // At least one member in each anonymous union must be non-const 4727 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 4728 FieldRecord->field_begin() != FieldRecord->field_end()) { 4729 if (Diagnose) 4730 S.Diag(FieldRecord->getLocation(), 4731 diag::note_deleted_default_ctor_all_const) 4732 << MD->getParent() << /*anonymous union*/1; 4733 return true; 4734 } 4735 4736 // Don't check the implicit member of the anonymous union type. 4737 // This is technically non-conformant, but sanity demands it. 4738 return false; 4739 } 4740 4741 if (shouldDeleteForClassSubobject(FieldRecord, FD, 4742 FieldType.getCVRQualifiers())) 4743 return true; 4744 } 4745 4746 return false; 4747} 4748 4749/// C++11 [class.ctor] p5: 4750/// A defaulted default constructor for a class X is defined as deleted if 4751/// X is a union and all of its variant members are of const-qualified type. 4752bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 4753 // This is a silly definition, because it gives an empty union a deleted 4754 // default constructor. Don't do that. 4755 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst && 4756 (MD->getParent()->field_begin() != MD->getParent()->field_end())) { 4757 if (Diagnose) 4758 S.Diag(MD->getParent()->getLocation(), 4759 diag::note_deleted_default_ctor_all_const) 4760 << MD->getParent() << /*not anonymous union*/0; 4761 return true; 4762 } 4763 return false; 4764} 4765 4766/// Determine whether a defaulted special member function should be defined as 4767/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 4768/// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 4769bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 4770 bool Diagnose) { 4771 if (MD->isInvalidDecl()) 4772 return false; 4773 CXXRecordDecl *RD = MD->getParent(); 4774 assert(!RD->isDependentType() && "do deletion after instantiation"); 4775 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 4776 return false; 4777 4778 // C++11 [expr.lambda.prim]p19: 4779 // The closure type associated with a lambda-expression has a 4780 // deleted (8.4.3) default constructor and a deleted copy 4781 // assignment operator. 4782 if (RD->isLambda() && 4783 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 4784 if (Diagnose) 4785 Diag(RD->getLocation(), diag::note_lambda_decl); 4786 return true; 4787 } 4788 4789 // For an anonymous struct or union, the copy and assignment special members 4790 // will never be used, so skip the check. For an anonymous union declared at 4791 // namespace scope, the constructor and destructor are used. 4792 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 4793 RD->isAnonymousStructOrUnion()) 4794 return false; 4795 4796 // C++11 [class.copy]p7, p18: 4797 // If the class definition declares a move constructor or move assignment 4798 // operator, an implicitly declared copy constructor or copy assignment 4799 // operator is defined as deleted. 4800 if (MD->isImplicit() && 4801 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 4802 CXXMethodDecl *UserDeclaredMove = 0; 4803 4804 // In Microsoft mode, a user-declared move only causes the deletion of the 4805 // corresponding copy operation, not both copy operations. 4806 if (RD->hasUserDeclaredMoveConstructor() && 4807 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) { 4808 if (!Diagnose) return true; 4809 4810 // Find any user-declared move constructor. 4811 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(), 4812 E = RD->ctor_end(); I != E; ++I) { 4813 if (I->isMoveConstructor()) { 4814 UserDeclaredMove = *I; 4815 break; 4816 } 4817 } 4818 assert(UserDeclaredMove); 4819 } else if (RD->hasUserDeclaredMoveAssignment() && 4820 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) { 4821 if (!Diagnose) return true; 4822 4823 // Find any user-declared move assignment operator. 4824 for (CXXRecordDecl::method_iterator I = RD->method_begin(), 4825 E = RD->method_end(); I != E; ++I) { 4826 if (I->isMoveAssignmentOperator()) { 4827 UserDeclaredMove = *I; 4828 break; 4829 } 4830 } 4831 assert(UserDeclaredMove); 4832 } 4833 4834 if (UserDeclaredMove) { 4835 Diag(UserDeclaredMove->getLocation(), 4836 diag::note_deleted_copy_user_declared_move) 4837 << (CSM == CXXCopyAssignment) << RD 4838 << UserDeclaredMove->isMoveAssignmentOperator(); 4839 return true; 4840 } 4841 } 4842 4843 // Do access control from the special member function 4844 ContextRAII MethodContext(*this, MD); 4845 4846 // C++11 [class.dtor]p5: 4847 // -- for a virtual destructor, lookup of the non-array deallocation function 4848 // results in an ambiguity or in a function that is deleted or inaccessible 4849 if (CSM == CXXDestructor && MD->isVirtual()) { 4850 FunctionDecl *OperatorDelete = 0; 4851 DeclarationName Name = 4852 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 4853 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 4854 OperatorDelete, false)) { 4855 if (Diagnose) 4856 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 4857 return true; 4858 } 4859 } 4860 4861 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose); 4862 4863 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 4864 BE = RD->bases_end(); BI != BE; ++BI) 4865 if (!BI->isVirtual() && 4866 SMI.shouldDeleteForBase(BI)) 4867 return true; 4868 4869 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(), 4870 BE = RD->vbases_end(); BI != BE; ++BI) 4871 if (SMI.shouldDeleteForBase(BI)) 4872 return true; 4873 4874 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 4875 FE = RD->field_end(); FI != FE; ++FI) 4876 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() && 4877 SMI.shouldDeleteForField(*FI)) 4878 return true; 4879 4880 if (SMI.shouldDeleteForAllConstMembers()) 4881 return true; 4882 4883 return false; 4884} 4885 4886/// Perform lookup for a special member of the specified kind, and determine 4887/// whether it is trivial. If the triviality can be determined without the 4888/// lookup, skip it. This is intended for use when determining whether a 4889/// special member of a containing object is trivial, and thus does not ever 4890/// perform overload resolution for default constructors. 4891/// 4892/// If \p Selected is not \c NULL, \c *Selected will be filled in with the 4893/// member that was most likely to be intended to be trivial, if any. 4894static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 4895 Sema::CXXSpecialMember CSM, unsigned Quals, 4896 CXXMethodDecl **Selected) { 4897 if (Selected) 4898 *Selected = 0; 4899 4900 switch (CSM) { 4901 case Sema::CXXInvalid: 4902 llvm_unreachable("not a special member"); 4903 4904 case Sema::CXXDefaultConstructor: 4905 // C++11 [class.ctor]p5: 4906 // A default constructor is trivial if: 4907 // - all the [direct subobjects] have trivial default constructors 4908 // 4909 // Note, no overload resolution is performed in this case. 4910 if (RD->hasTrivialDefaultConstructor()) 4911 return true; 4912 4913 if (Selected) { 4914 // If there's a default constructor which could have been trivial, dig it 4915 // out. Otherwise, if there's any user-provided default constructor, point 4916 // to that as an example of why there's not a trivial one. 4917 CXXConstructorDecl *DefCtor = 0; 4918 if (RD->needsImplicitDefaultConstructor()) 4919 S.DeclareImplicitDefaultConstructor(RD); 4920 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), 4921 CE = RD->ctor_end(); CI != CE; ++CI) { 4922 if (!CI->isDefaultConstructor()) 4923 continue; 4924 DefCtor = *CI; 4925 if (!DefCtor->isUserProvided()) 4926 break; 4927 } 4928 4929 *Selected = DefCtor; 4930 } 4931 4932 return false; 4933 4934 case Sema::CXXDestructor: 4935 // C++11 [class.dtor]p5: 4936 // A destructor is trivial if: 4937 // - all the direct [subobjects] have trivial destructors 4938 if (RD->hasTrivialDestructor()) 4939 return true; 4940 4941 if (Selected) { 4942 if (RD->needsImplicitDestructor()) 4943 S.DeclareImplicitDestructor(RD); 4944 *Selected = RD->getDestructor(); 4945 } 4946 4947 return false; 4948 4949 case Sema::CXXCopyConstructor: 4950 // C++11 [class.copy]p12: 4951 // A copy constructor is trivial if: 4952 // - the constructor selected to copy each direct [subobject] is trivial 4953 if (RD->hasTrivialCopyConstructor()) { 4954 if (Quals == Qualifiers::Const) 4955 // We must either select the trivial copy constructor or reach an 4956 // ambiguity; no need to actually perform overload resolution. 4957 return true; 4958 } else if (!Selected) { 4959 return false; 4960 } 4961 // In C++98, we are not supposed to perform overload resolution here, but we 4962 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 4963 // cases like B as having a non-trivial copy constructor: 4964 // struct A { template<typename T> A(T&); }; 4965 // struct B { mutable A a; }; 4966 goto NeedOverloadResolution; 4967 4968 case Sema::CXXCopyAssignment: 4969 // C++11 [class.copy]p25: 4970 // A copy assignment operator is trivial if: 4971 // - the assignment operator selected to copy each direct [subobject] is 4972 // trivial 4973 if (RD->hasTrivialCopyAssignment()) { 4974 if (Quals == Qualifiers::Const) 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. 4981 goto NeedOverloadResolution; 4982 4983 case Sema::CXXMoveConstructor: 4984 case Sema::CXXMoveAssignment: 4985 NeedOverloadResolution: 4986 Sema::SpecialMemberOverloadResult *SMOR = 4987 S.LookupSpecialMember(RD, CSM, 4988 Quals & Qualifiers::Const, 4989 Quals & Qualifiers::Volatile, 4990 /*RValueThis*/false, /*ConstThis*/false, 4991 /*VolatileThis*/false); 4992 4993 // The standard doesn't describe how to behave if the lookup is ambiguous. 4994 // We treat it as not making the member non-trivial, just like the standard 4995 // mandates for the default constructor. This should rarely matter, because 4996 // the member will also be deleted. 4997 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 4998 return true; 4999 5000 if (!SMOR->getMethod()) { 5001 assert(SMOR->getKind() == 5002 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 5003 return false; 5004 } 5005 5006 // We deliberately don't check if we found a deleted special member. We're 5007 // not supposed to! 5008 if (Selected) 5009 *Selected = SMOR->getMethod(); 5010 return SMOR->getMethod()->isTrivial(); 5011 } 5012 5013 llvm_unreachable("unknown special method kind"); 5014} 5015 5016static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 5017 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end(); 5018 CI != CE; ++CI) 5019 if (!CI->isImplicit()) 5020 return *CI; 5021 5022 // Look for constructor templates. 5023 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 5024 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 5025 if (CXXConstructorDecl *CD = 5026 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 5027 return CD; 5028 } 5029 5030 return 0; 5031} 5032 5033/// The kind of subobject we are checking for triviality. The values of this 5034/// enumeration are used in diagnostics. 5035enum TrivialSubobjectKind { 5036 /// The subobject is a base class. 5037 TSK_BaseClass, 5038 /// The subobject is a non-static data member. 5039 TSK_Field, 5040 /// The object is actually the complete object. 5041 TSK_CompleteObject 5042}; 5043 5044/// Check whether the special member selected for a given type would be trivial. 5045static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 5046 QualType SubType, 5047 Sema::CXXSpecialMember CSM, 5048 TrivialSubobjectKind Kind, 5049 bool Diagnose) { 5050 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 5051 if (!SubRD) 5052 return true; 5053 5054 CXXMethodDecl *Selected; 5055 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 5056 Diagnose ? &Selected : 0)) 5057 return true; 5058 5059 if (Diagnose) { 5060 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 5061 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 5062 << Kind << SubType.getUnqualifiedType(); 5063 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 5064 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 5065 } else if (!Selected) 5066 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 5067 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 5068 else if (Selected->isUserProvided()) { 5069 if (Kind == TSK_CompleteObject) 5070 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 5071 << Kind << SubType.getUnqualifiedType() << CSM; 5072 else { 5073 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 5074 << Kind << SubType.getUnqualifiedType() << CSM; 5075 S.Diag(Selected->getLocation(), diag::note_declared_at); 5076 } 5077 } else { 5078 if (Kind != TSK_CompleteObject) 5079 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 5080 << Kind << SubType.getUnqualifiedType() << CSM; 5081 5082 // Explain why the defaulted or deleted special member isn't trivial. 5083 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose); 5084 } 5085 } 5086 5087 return false; 5088} 5089 5090/// Check whether the members of a class type allow a special member to be 5091/// trivial. 5092static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 5093 Sema::CXXSpecialMember CSM, 5094 bool ConstArg, bool Diagnose) { 5095 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 5096 FE = RD->field_end(); FI != FE; ++FI) { 5097 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 5098 continue; 5099 5100 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 5101 5102 // Pretend anonymous struct or union members are members of this class. 5103 if (FI->isAnonymousStructOrUnion()) { 5104 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 5105 CSM, ConstArg, Diagnose)) 5106 return false; 5107 continue; 5108 } 5109 5110 // C++11 [class.ctor]p5: 5111 // A default constructor is trivial if [...] 5112 // -- no non-static data member of its class has a 5113 // brace-or-equal-initializer 5114 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 5115 if (Diagnose) 5116 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI; 5117 return false; 5118 } 5119 5120 // Objective C ARC 4.3.5: 5121 // [...] nontrivally ownership-qualified types are [...] not trivially 5122 // default constructible, copy constructible, move constructible, copy 5123 // assignable, move assignable, or destructible [...] 5124 if (S.getLangOpts().ObjCAutoRefCount && 5125 FieldType.hasNonTrivialObjCLifetime()) { 5126 if (Diagnose) 5127 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 5128 << RD << FieldType.getObjCLifetime(); 5129 return false; 5130 } 5131 5132 if (ConstArg && !FI->isMutable()) 5133 FieldType.addConst(); 5134 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM, 5135 TSK_Field, Diagnose)) 5136 return false; 5137 } 5138 5139 return true; 5140} 5141 5142/// Diagnose why the specified class does not have a trivial special member of 5143/// the given kind. 5144void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 5145 QualType Ty = Context.getRecordType(RD); 5146 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) 5147 Ty.addConst(); 5148 5149 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM, 5150 TSK_CompleteObject, /*Diagnose*/true); 5151} 5152 5153/// Determine whether a defaulted or deleted special member function is trivial, 5154/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 5155/// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 5156bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 5157 bool Diagnose) { 5158 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 5159 5160 CXXRecordDecl *RD = MD->getParent(); 5161 5162 bool ConstArg = false; 5163 5164 // C++11 [class.copy]p12, p25: 5165 // A [special member] is trivial if its declared parameter type is the same 5166 // as if it had been implicitly declared [...] 5167 switch (CSM) { 5168 case CXXDefaultConstructor: 5169 case CXXDestructor: 5170 // Trivial default constructors and destructors cannot have parameters. 5171 break; 5172 5173 case CXXCopyConstructor: 5174 case CXXCopyAssignment: { 5175 // Trivial copy operations always have const, non-volatile parameter types. 5176 ConstArg = true; 5177 const ParmVarDecl *Param0 = MD->getParamDecl(0); 5178 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 5179 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 5180 if (Diagnose) 5181 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 5182 << Param0->getSourceRange() << Param0->getType() 5183 << Context.getLValueReferenceType( 5184 Context.getRecordType(RD).withConst()); 5185 return false; 5186 } 5187 break; 5188 } 5189 5190 case CXXMoveConstructor: 5191 case CXXMoveAssignment: { 5192 // Trivial move operations always have non-cv-qualified parameters. 5193 const ParmVarDecl *Param0 = MD->getParamDecl(0); 5194 const RValueReferenceType *RT = 5195 Param0->getType()->getAs<RValueReferenceType>(); 5196 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 5197 if (Diagnose) 5198 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 5199 << Param0->getSourceRange() << Param0->getType() 5200 << Context.getRValueReferenceType(Context.getRecordType(RD)); 5201 return false; 5202 } 5203 break; 5204 } 5205 5206 case CXXInvalid: 5207 llvm_unreachable("not a special member"); 5208 } 5209 5210 // FIXME: We require that the parameter-declaration-clause is equivalent to 5211 // that of an implicit declaration, not just that the declared parameter type 5212 // matches, in order to prevent absuridities like a function simultaneously 5213 // being a trivial copy constructor and a non-trivial default constructor. 5214 // This issue has not yet been assigned a core issue number. 5215 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 5216 if (Diagnose) 5217 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 5218 diag::note_nontrivial_default_arg) 5219 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 5220 return false; 5221 } 5222 if (MD->isVariadic()) { 5223 if (Diagnose) 5224 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 5225 return false; 5226 } 5227 5228 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 5229 // A copy/move [constructor or assignment operator] is trivial if 5230 // -- the [member] selected to copy/move each direct base class subobject 5231 // is trivial 5232 // 5233 // C++11 [class.copy]p12, C++11 [class.copy]p25: 5234 // A [default constructor or destructor] is trivial if 5235 // -- all the direct base classes have trivial [default constructors or 5236 // destructors] 5237 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 5238 BE = RD->bases_end(); BI != BE; ++BI) 5239 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(), 5240 ConstArg ? BI->getType().withConst() 5241 : BI->getType(), 5242 CSM, TSK_BaseClass, Diagnose)) 5243 return false; 5244 5245 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 5246 // A copy/move [constructor or assignment operator] for a class X is 5247 // trivial if 5248 // -- for each non-static data member of X that is of class type (or array 5249 // thereof), the constructor selected to copy/move that member is 5250 // trivial 5251 // 5252 // C++11 [class.copy]p12, C++11 [class.copy]p25: 5253 // A [default constructor or destructor] is trivial if 5254 // -- for all of the non-static data members of its class that are of class 5255 // type (or array thereof), each such class has a trivial [default 5256 // constructor or destructor] 5257 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose)) 5258 return false; 5259 5260 // C++11 [class.dtor]p5: 5261 // A destructor is trivial if [...] 5262 // -- the destructor is not virtual 5263 if (CSM == CXXDestructor && MD->isVirtual()) { 5264 if (Diagnose) 5265 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 5266 return false; 5267 } 5268 5269 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 5270 // A [special member] for class X is trivial if [...] 5271 // -- class X has no virtual functions and no virtual base classes 5272 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 5273 if (!Diagnose) 5274 return false; 5275 5276 if (RD->getNumVBases()) { 5277 // Check for virtual bases. We already know that the corresponding 5278 // member in all bases is trivial, so vbases must all be direct. 5279 CXXBaseSpecifier &BS = *RD->vbases_begin(); 5280 assert(BS.isVirtual()); 5281 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1; 5282 return false; 5283 } 5284 5285 // Must have a virtual method. 5286 for (CXXRecordDecl::method_iterator MI = RD->method_begin(), 5287 ME = RD->method_end(); MI != ME; ++MI) { 5288 if (MI->isVirtual()) { 5289 SourceLocation MLoc = MI->getLocStart(); 5290 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 5291 return false; 5292 } 5293 } 5294 5295 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 5296 } 5297 5298 // Looks like it's trivial! 5299 return true; 5300} 5301 5302/// \brief Data used with FindHiddenVirtualMethod 5303namespace { 5304 struct FindHiddenVirtualMethodData { 5305 Sema *S; 5306 CXXMethodDecl *Method; 5307 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 5308 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 5309 }; 5310} 5311 5312/// \brief Check whether any most overriden method from MD in Methods 5313static bool CheckMostOverridenMethods(const CXXMethodDecl *MD, 5314 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) { 5315 if (MD->size_overridden_methods() == 0) 5316 return Methods.count(MD->getCanonicalDecl()); 5317 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 5318 E = MD->end_overridden_methods(); 5319 I != E; ++I) 5320 if (CheckMostOverridenMethods(*I, Methods)) 5321 return true; 5322 return false; 5323} 5324 5325/// \brief Member lookup function that determines whether a given C++ 5326/// method overloads virtual methods in a base class without overriding any, 5327/// to be used with CXXRecordDecl::lookupInBases(). 5328static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier, 5329 CXXBasePath &Path, 5330 void *UserData) { 5331 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 5332 5333 FindHiddenVirtualMethodData &Data 5334 = *static_cast<FindHiddenVirtualMethodData*>(UserData); 5335 5336 DeclarationName Name = Data.Method->getDeclName(); 5337 assert(Name.getNameKind() == DeclarationName::Identifier); 5338 5339 bool foundSameNameMethod = false; 5340 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 5341 for (Path.Decls = BaseRecord->lookup(Name); 5342 !Path.Decls.empty(); 5343 Path.Decls = Path.Decls.slice(1)) { 5344 NamedDecl *D = Path.Decls.front(); 5345 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 5346 MD = MD->getCanonicalDecl(); 5347 foundSameNameMethod = true; 5348 // Interested only in hidden virtual methods. 5349 if (!MD->isVirtual()) 5350 continue; 5351 // If the method we are checking overrides a method from its base 5352 // don't warn about the other overloaded methods. 5353 if (!Data.S->IsOverload(Data.Method, MD, false)) 5354 return true; 5355 // Collect the overload only if its hidden. 5356 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods)) 5357 overloadedMethods.push_back(MD); 5358 } 5359 } 5360 5361 if (foundSameNameMethod) 5362 Data.OverloadedMethods.append(overloadedMethods.begin(), 5363 overloadedMethods.end()); 5364 return foundSameNameMethod; 5365} 5366 5367/// \brief Add the most overriden methods from MD to Methods 5368static void AddMostOverridenMethods(const CXXMethodDecl *MD, 5369 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) { 5370 if (MD->size_overridden_methods() == 0) 5371 Methods.insert(MD->getCanonicalDecl()); 5372 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 5373 E = MD->end_overridden_methods(); 5374 I != E; ++I) 5375 AddMostOverridenMethods(*I, Methods); 5376} 5377 5378/// \brief See if a method overloads virtual methods in a base class without 5379/// overriding any. 5380void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 5381 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual, 5382 MD->getLocation()) == DiagnosticsEngine::Ignored) 5383 return; 5384 if (!MD->getDeclName().isIdentifier()) 5385 return; 5386 5387 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 5388 /*bool RecordPaths=*/false, 5389 /*bool DetectVirtual=*/false); 5390 FindHiddenVirtualMethodData Data; 5391 Data.Method = MD; 5392 Data.S = this; 5393 5394 // Keep the base methods that were overriden or introduced in the subclass 5395 // by 'using' in a set. A base method not in this set is hidden. 5396 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 5397 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 5398 NamedDecl *ND = *I; 5399 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 5400 ND = shad->getTargetDecl(); 5401 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 5402 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods); 5403 } 5404 5405 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) && 5406 !Data.OverloadedMethods.empty()) { 5407 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 5408 << MD << (Data.OverloadedMethods.size() > 1); 5409 5410 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) { 5411 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i]; 5412 Diag(overloadedMD->getLocation(), 5413 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 5414 } 5415 } 5416} 5417 5418void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 5419 Decl *TagDecl, 5420 SourceLocation LBrac, 5421 SourceLocation RBrac, 5422 AttributeList *AttrList) { 5423 if (!TagDecl) 5424 return; 5425 5426 AdjustDeclIfTemplate(TagDecl); 5427 5428 for (const AttributeList* l = AttrList; l; l = l->getNext()) { 5429 if (l->getKind() != AttributeList::AT_Visibility) 5430 continue; 5431 l->setInvalid(); 5432 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) << 5433 l->getName(); 5434 } 5435 5436 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 5437 // strict aliasing violation! 5438 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 5439 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 5440 5441 CheckCompletedCXXClass( 5442 dyn_cast_or_null<CXXRecordDecl>(TagDecl)); 5443} 5444 5445/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 5446/// special functions, such as the default constructor, copy 5447/// constructor, or destructor, to the given C++ class (C++ 5448/// [special]p1). This routine can only be executed just before the 5449/// definition of the class is complete. 5450void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 5451 if (!ClassDecl->hasUserDeclaredConstructor()) 5452 ++ASTContext::NumImplicitDefaultConstructors; 5453 5454 if (!ClassDecl->hasUserDeclaredCopyConstructor()) { 5455 ++ASTContext::NumImplicitCopyConstructors; 5456 5457 // If the properties or semantics of the copy constructor couldn't be 5458 // determined while the class was being declared, force a declaration 5459 // of it now. 5460 if (ClassDecl->needsOverloadResolutionForCopyConstructor()) 5461 DeclareImplicitCopyConstructor(ClassDecl); 5462 } 5463 5464 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 5465 ++ASTContext::NumImplicitMoveConstructors; 5466 5467 if (ClassDecl->needsOverloadResolutionForMoveConstructor()) 5468 DeclareImplicitMoveConstructor(ClassDecl); 5469 } 5470 5471 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 5472 ++ASTContext::NumImplicitCopyAssignmentOperators; 5473 5474 // If we have a dynamic class, then the copy assignment operator may be 5475 // virtual, so we have to declare it immediately. This ensures that, e.g., 5476 // it shows up in the right place in the vtable and that we diagnose 5477 // problems with the implicit exception specification. 5478 if (ClassDecl->isDynamicClass() || 5479 ClassDecl->needsOverloadResolutionForCopyAssignment()) 5480 DeclareImplicitCopyAssignment(ClassDecl); 5481 } 5482 5483 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 5484 ++ASTContext::NumImplicitMoveAssignmentOperators; 5485 5486 // Likewise for the move assignment operator. 5487 if (ClassDecl->isDynamicClass() || 5488 ClassDecl->needsOverloadResolutionForMoveAssignment()) 5489 DeclareImplicitMoveAssignment(ClassDecl); 5490 } 5491 5492 if (!ClassDecl->hasUserDeclaredDestructor()) { 5493 ++ASTContext::NumImplicitDestructors; 5494 5495 // If we have a dynamic class, then the destructor may be virtual, so we 5496 // have to declare the destructor immediately. This ensures that, e.g., it 5497 // shows up in the right place in the vtable and that we diagnose problems 5498 // with the implicit exception specification. 5499 if (ClassDecl->isDynamicClass() || 5500 ClassDecl->needsOverloadResolutionForDestructor()) 5501 DeclareImplicitDestructor(ClassDecl); 5502 } 5503} 5504 5505void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) { 5506 if (!D) 5507 return; 5508 5509 int NumParamList = D->getNumTemplateParameterLists(); 5510 for (int i = 0; i < NumParamList; i++) { 5511 TemplateParameterList* Params = D->getTemplateParameterList(i); 5512 for (TemplateParameterList::iterator Param = Params->begin(), 5513 ParamEnd = Params->end(); 5514 Param != ParamEnd; ++Param) { 5515 NamedDecl *Named = cast<NamedDecl>(*Param); 5516 if (Named->getDeclName()) { 5517 S->AddDecl(Named); 5518 IdResolver.AddDecl(Named); 5519 } 5520 } 5521 } 5522} 5523 5524void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 5525 if (!D) 5526 return; 5527 5528 TemplateParameterList *Params = 0; 5529 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) 5530 Params = Template->getTemplateParameters(); 5531 else if (ClassTemplatePartialSpecializationDecl *PartialSpec 5532 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 5533 Params = PartialSpec->getTemplateParameters(); 5534 else 5535 return; 5536 5537 for (TemplateParameterList::iterator Param = Params->begin(), 5538 ParamEnd = Params->end(); 5539 Param != ParamEnd; ++Param) { 5540 NamedDecl *Named = cast<NamedDecl>(*Param); 5541 if (Named->getDeclName()) { 5542 S->AddDecl(Named); 5543 IdResolver.AddDecl(Named); 5544 } 5545 } 5546} 5547 5548void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 5549 if (!RecordD) return; 5550 AdjustDeclIfTemplate(RecordD); 5551 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 5552 PushDeclContext(S, Record); 5553} 5554 5555void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 5556 if (!RecordD) return; 5557 PopDeclContext(); 5558} 5559 5560/// ActOnStartDelayedCXXMethodDeclaration - We have completed 5561/// parsing a top-level (non-nested) C++ class, and we are now 5562/// parsing those parts of the given Method declaration that could 5563/// not be parsed earlier (C++ [class.mem]p2), such as default 5564/// arguments. This action should enter the scope of the given 5565/// Method declaration as if we had just parsed the qualified method 5566/// name. However, it should not bring the parameters into scope; 5567/// that will be performed by ActOnDelayedCXXMethodParameter. 5568void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 5569} 5570 5571/// ActOnDelayedCXXMethodParameter - We've already started a delayed 5572/// C++ method declaration. We're (re-)introducing the given 5573/// function parameter into scope for use in parsing later parts of 5574/// the method declaration. For example, we could see an 5575/// ActOnParamDefaultArgument event for this parameter. 5576void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 5577 if (!ParamD) 5578 return; 5579 5580 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 5581 5582 // If this parameter has an unparsed default argument, clear it out 5583 // to make way for the parsed default argument. 5584 if (Param->hasUnparsedDefaultArg()) 5585 Param->setDefaultArg(0); 5586 5587 S->AddDecl(Param); 5588 if (Param->getDeclName()) 5589 IdResolver.AddDecl(Param); 5590} 5591 5592/// ActOnFinishDelayedCXXMethodDeclaration - We have finished 5593/// processing the delayed method declaration for Method. The method 5594/// declaration is now considered finished. There may be a separate 5595/// ActOnStartOfFunctionDef action later (not necessarily 5596/// immediately!) for this method, if it was also defined inside the 5597/// class body. 5598void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 5599 if (!MethodD) 5600 return; 5601 5602 AdjustDeclIfTemplate(MethodD); 5603 5604 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 5605 5606 // Now that we have our default arguments, check the constructor 5607 // again. It could produce additional diagnostics or affect whether 5608 // the class has implicitly-declared destructors, among other 5609 // things. 5610 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 5611 CheckConstructor(Constructor); 5612 5613 // Check the default arguments, which we may have added. 5614 if (!Method->isInvalidDecl()) 5615 CheckCXXDefaultArguments(Method); 5616} 5617 5618/// CheckConstructorDeclarator - Called by ActOnDeclarator to check 5619/// the well-formedness of the constructor declarator @p D with type @p 5620/// R. If there are any errors in the declarator, this routine will 5621/// emit diagnostics and set the invalid bit to true. In any case, the type 5622/// will be updated to reflect a well-formed type for the constructor and 5623/// returned. 5624QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 5625 StorageClass &SC) { 5626 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 5627 5628 // C++ [class.ctor]p3: 5629 // A constructor shall not be virtual (10.3) or static (9.4). A 5630 // constructor can be invoked for a const, volatile or const 5631 // volatile object. A constructor shall not be declared const, 5632 // volatile, or const volatile (9.3.2). 5633 if (isVirtual) { 5634 if (!D.isInvalidType()) 5635 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 5636 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 5637 << SourceRange(D.getIdentifierLoc()); 5638 D.setInvalidType(); 5639 } 5640 if (SC == SC_Static) { 5641 if (!D.isInvalidType()) 5642 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 5643 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 5644 << SourceRange(D.getIdentifierLoc()); 5645 D.setInvalidType(); 5646 SC = SC_None; 5647 } 5648 5649 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 5650 if (FTI.TypeQuals != 0) { 5651 if (FTI.TypeQuals & Qualifiers::Const) 5652 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 5653 << "const" << SourceRange(D.getIdentifierLoc()); 5654 if (FTI.TypeQuals & Qualifiers::Volatile) 5655 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 5656 << "volatile" << SourceRange(D.getIdentifierLoc()); 5657 if (FTI.TypeQuals & Qualifiers::Restrict) 5658 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 5659 << "restrict" << SourceRange(D.getIdentifierLoc()); 5660 D.setInvalidType(); 5661 } 5662 5663 // C++0x [class.ctor]p4: 5664 // A constructor shall not be declared with a ref-qualifier. 5665 if (FTI.hasRefQualifier()) { 5666 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 5667 << FTI.RefQualifierIsLValueRef 5668 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 5669 D.setInvalidType(); 5670 } 5671 5672 // Rebuild the function type "R" without any type qualifiers (in 5673 // case any of the errors above fired) and with "void" as the 5674 // return type, since constructors don't have return types. 5675 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 5676 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType()) 5677 return R; 5678 5679 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 5680 EPI.TypeQuals = 0; 5681 EPI.RefQualifier = RQ_None; 5682 5683 return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI); 5684} 5685 5686/// CheckConstructor - Checks a fully-formed constructor for 5687/// well-formedness, issuing any diagnostics required. Returns true if 5688/// the constructor declarator is invalid. 5689void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 5690 CXXRecordDecl *ClassDecl 5691 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 5692 if (!ClassDecl) 5693 return Constructor->setInvalidDecl(); 5694 5695 // C++ [class.copy]p3: 5696 // A declaration of a constructor for a class X is ill-formed if 5697 // its first parameter is of type (optionally cv-qualified) X and 5698 // either there are no other parameters or else all other 5699 // parameters have default arguments. 5700 if (!Constructor->isInvalidDecl() && 5701 ((Constructor->getNumParams() == 1) || 5702 (Constructor->getNumParams() > 1 && 5703 Constructor->getParamDecl(1)->hasDefaultArg())) && 5704 Constructor->getTemplateSpecializationKind() 5705 != TSK_ImplicitInstantiation) { 5706 QualType ParamType = Constructor->getParamDecl(0)->getType(); 5707 QualType ClassTy = Context.getTagDeclType(ClassDecl); 5708 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 5709 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 5710 const char *ConstRef 5711 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 5712 : " const &"; 5713 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 5714 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 5715 5716 // FIXME: Rather that making the constructor invalid, we should endeavor 5717 // to fix the type. 5718 Constructor->setInvalidDecl(); 5719 } 5720 } 5721} 5722 5723/// CheckDestructor - Checks a fully-formed destructor definition for 5724/// well-formedness, issuing any diagnostics required. Returns true 5725/// on error. 5726bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 5727 CXXRecordDecl *RD = Destructor->getParent(); 5728 5729 if (Destructor->isVirtual()) { 5730 SourceLocation Loc; 5731 5732 if (!Destructor->isImplicit()) 5733 Loc = Destructor->getLocation(); 5734 else 5735 Loc = RD->getLocation(); 5736 5737 // If we have a virtual destructor, look up the deallocation function 5738 FunctionDecl *OperatorDelete = 0; 5739 DeclarationName Name = 5740 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 5741 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 5742 return true; 5743 5744 MarkFunctionReferenced(Loc, OperatorDelete); 5745 5746 Destructor->setOperatorDelete(OperatorDelete); 5747 } 5748 5749 return false; 5750} 5751 5752static inline bool 5753FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) { 5754 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 5755 FTI.ArgInfo[0].Param && 5756 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()); 5757} 5758 5759/// CheckDestructorDeclarator - Called by ActOnDeclarator to check 5760/// the well-formednes of the destructor declarator @p D with type @p 5761/// R. If there are any errors in the declarator, this routine will 5762/// emit diagnostics and set the declarator to invalid. Even if this happens, 5763/// will be updated to reflect a well-formed type for the destructor and 5764/// returned. 5765QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 5766 StorageClass& SC) { 5767 // C++ [class.dtor]p1: 5768 // [...] A typedef-name that names a class is a class-name 5769 // (7.1.3); however, a typedef-name that names a class shall not 5770 // be used as the identifier in the declarator for a destructor 5771 // declaration. 5772 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 5773 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 5774 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 5775 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 5776 else if (const TemplateSpecializationType *TST = 5777 DeclaratorType->getAs<TemplateSpecializationType>()) 5778 if (TST->isTypeAlias()) 5779 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 5780 << DeclaratorType << 1; 5781 5782 // C++ [class.dtor]p2: 5783 // A destructor is used to destroy objects of its class type. A 5784 // destructor takes no parameters, and no return type can be 5785 // specified for it (not even void). The address of a destructor 5786 // shall not be taken. A destructor shall not be static. A 5787 // destructor can be invoked for a const, volatile or const 5788 // volatile object. A destructor shall not be declared const, 5789 // volatile or const volatile (9.3.2). 5790 if (SC == SC_Static) { 5791 if (!D.isInvalidType()) 5792 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 5793 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 5794 << SourceRange(D.getIdentifierLoc()) 5795 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5796 5797 SC = SC_None; 5798 } 5799 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 5800 // Destructors don't have return types, but the parser will 5801 // happily parse something like: 5802 // 5803 // class X { 5804 // float ~X(); 5805 // }; 5806 // 5807 // The return type will be eliminated later. 5808 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 5809 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 5810 << SourceRange(D.getIdentifierLoc()); 5811 } 5812 5813 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 5814 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 5815 if (FTI.TypeQuals & Qualifiers::Const) 5816 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 5817 << "const" << SourceRange(D.getIdentifierLoc()); 5818 if (FTI.TypeQuals & Qualifiers::Volatile) 5819 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 5820 << "volatile" << SourceRange(D.getIdentifierLoc()); 5821 if (FTI.TypeQuals & Qualifiers::Restrict) 5822 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 5823 << "restrict" << SourceRange(D.getIdentifierLoc()); 5824 D.setInvalidType(); 5825 } 5826 5827 // C++0x [class.dtor]p2: 5828 // A destructor shall not be declared with a ref-qualifier. 5829 if (FTI.hasRefQualifier()) { 5830 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 5831 << FTI.RefQualifierIsLValueRef 5832 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 5833 D.setInvalidType(); 5834 } 5835 5836 // Make sure we don't have any parameters. 5837 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) { 5838 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 5839 5840 // Delete the parameters. 5841 FTI.freeArgs(); 5842 D.setInvalidType(); 5843 } 5844 5845 // Make sure the destructor isn't variadic. 5846 if (FTI.isVariadic) { 5847 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 5848 D.setInvalidType(); 5849 } 5850 5851 // Rebuild the function type "R" without any type qualifiers or 5852 // parameters (in case any of the errors above fired) and with 5853 // "void" as the return type, since destructors don't have return 5854 // types. 5855 if (!D.isInvalidType()) 5856 return R; 5857 5858 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 5859 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 5860 EPI.Variadic = false; 5861 EPI.TypeQuals = 0; 5862 EPI.RefQualifier = RQ_None; 5863 return Context.getFunctionType(Context.VoidTy, ArrayRef<QualType>(), EPI); 5864} 5865 5866/// CheckConversionDeclarator - Called by ActOnDeclarator to check the 5867/// well-formednes of the conversion function declarator @p D with 5868/// type @p R. If there are any errors in the declarator, this routine 5869/// will emit diagnostics and return true. Otherwise, it will return 5870/// false. Either way, the type @p R will be updated to reflect a 5871/// well-formed type for the conversion operator. 5872void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 5873 StorageClass& SC) { 5874 // C++ [class.conv.fct]p1: 5875 // Neither parameter types nor return type can be specified. The 5876 // type of a conversion function (8.3.5) is "function taking no 5877 // parameter returning conversion-type-id." 5878 if (SC == SC_Static) { 5879 if (!D.isInvalidType()) 5880 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 5881 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 5882 << SourceRange(D.getIdentifierLoc()); 5883 D.setInvalidType(); 5884 SC = SC_None; 5885 } 5886 5887 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId); 5888 5889 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 5890 // Conversion functions don't have return types, but the parser will 5891 // happily parse something like: 5892 // 5893 // class X { 5894 // float operator bool(); 5895 // }; 5896 // 5897 // The return type will be changed later anyway. 5898 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 5899 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 5900 << SourceRange(D.getIdentifierLoc()); 5901 D.setInvalidType(); 5902 } 5903 5904 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 5905 5906 // Make sure we don't have any parameters. 5907 if (Proto->getNumArgs() > 0) { 5908 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 5909 5910 // Delete the parameters. 5911 D.getFunctionTypeInfo().freeArgs(); 5912 D.setInvalidType(); 5913 } else if (Proto->isVariadic()) { 5914 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 5915 D.setInvalidType(); 5916 } 5917 5918 // Diagnose "&operator bool()" and other such nonsense. This 5919 // is actually a gcc extension which we don't support. 5920 if (Proto->getResultType() != ConvType) { 5921 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 5922 << Proto->getResultType(); 5923 D.setInvalidType(); 5924 ConvType = Proto->getResultType(); 5925 } 5926 5927 // C++ [class.conv.fct]p4: 5928 // The conversion-type-id shall not represent a function type nor 5929 // an array type. 5930 if (ConvType->isArrayType()) { 5931 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 5932 ConvType = Context.getPointerType(ConvType); 5933 D.setInvalidType(); 5934 } else if (ConvType->isFunctionType()) { 5935 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 5936 ConvType = Context.getPointerType(ConvType); 5937 D.setInvalidType(); 5938 } 5939 5940 // Rebuild the function type "R" without any parameters (in case any 5941 // of the errors above fired) and with the conversion type as the 5942 // return type. 5943 if (D.isInvalidType()) 5944 R = Context.getFunctionType(ConvType, ArrayRef<QualType>(), 5945 Proto->getExtProtoInfo()); 5946 5947 // C++0x explicit conversion operators. 5948 if (D.getDeclSpec().isExplicitSpecified()) 5949 Diag(D.getDeclSpec().getExplicitSpecLoc(), 5950 getLangOpts().CPlusPlus11 ? 5951 diag::warn_cxx98_compat_explicit_conversion_functions : 5952 diag::ext_explicit_conversion_functions) 5953 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 5954} 5955 5956/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 5957/// the declaration of the given C++ conversion function. This routine 5958/// is responsible for recording the conversion function in the C++ 5959/// class, if possible. 5960Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 5961 assert(Conversion && "Expected to receive a conversion function declaration"); 5962 5963 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 5964 5965 // Make sure we aren't redeclaring the conversion function. 5966 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 5967 5968 // C++ [class.conv.fct]p1: 5969 // [...] A conversion function is never used to convert a 5970 // (possibly cv-qualified) object to the (possibly cv-qualified) 5971 // same object type (or a reference to it), to a (possibly 5972 // cv-qualified) base class of that type (or a reference to it), 5973 // or to (possibly cv-qualified) void. 5974 // FIXME: Suppress this warning if the conversion function ends up being a 5975 // virtual function that overrides a virtual function in a base class. 5976 QualType ClassType 5977 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 5978 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 5979 ConvType = ConvTypeRef->getPointeeType(); 5980 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 5981 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 5982 /* Suppress diagnostics for instantiations. */; 5983 else if (ConvType->isRecordType()) { 5984 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 5985 if (ConvType == ClassType) 5986 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 5987 << ClassType; 5988 else if (IsDerivedFrom(ClassType, ConvType)) 5989 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 5990 << ClassType << ConvType; 5991 } else if (ConvType->isVoidType()) { 5992 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 5993 << ClassType << ConvType; 5994 } 5995 5996 if (FunctionTemplateDecl *ConversionTemplate 5997 = Conversion->getDescribedFunctionTemplate()) 5998 return ConversionTemplate; 5999 6000 return Conversion; 6001} 6002 6003//===----------------------------------------------------------------------===// 6004// Namespace Handling 6005//===----------------------------------------------------------------------===// 6006 6007/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is 6008/// reopened. 6009static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 6010 SourceLocation Loc, 6011 IdentifierInfo *II, bool *IsInline, 6012 NamespaceDecl *PrevNS) { 6013 assert(*IsInline != PrevNS->isInline()); 6014 6015 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 6016 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 6017 // inline namespaces, with the intention of bringing names into namespace std. 6018 // 6019 // We support this just well enough to get that case working; this is not 6020 // sufficient to support reopening namespaces as inline in general. 6021 if (*IsInline && II && II->getName().startswith("__atomic") && 6022 S.getSourceManager().isInSystemHeader(Loc)) { 6023 // Mark all prior declarations of the namespace as inline. 6024 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 6025 NS = NS->getPreviousDecl()) 6026 NS->setInline(*IsInline); 6027 // Patch up the lookup table for the containing namespace. This isn't really 6028 // correct, but it's good enough for this particular case. 6029 for (DeclContext::decl_iterator I = PrevNS->decls_begin(), 6030 E = PrevNS->decls_end(); I != E; ++I) 6031 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I)) 6032 PrevNS->getParent()->makeDeclVisibleInContext(ND); 6033 return; 6034 } 6035 6036 if (PrevNS->isInline()) 6037 // The user probably just forgot the 'inline', so suggest that it 6038 // be added back. 6039 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 6040 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 6041 else 6042 S.Diag(Loc, diag::err_inline_namespace_mismatch) 6043 << IsInline; 6044 6045 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 6046 *IsInline = PrevNS->isInline(); 6047} 6048 6049/// ActOnStartNamespaceDef - This is called at the start of a namespace 6050/// definition. 6051Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 6052 SourceLocation InlineLoc, 6053 SourceLocation NamespaceLoc, 6054 SourceLocation IdentLoc, 6055 IdentifierInfo *II, 6056 SourceLocation LBrace, 6057 AttributeList *AttrList) { 6058 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 6059 // For anonymous namespace, take the location of the left brace. 6060 SourceLocation Loc = II ? IdentLoc : LBrace; 6061 bool IsInline = InlineLoc.isValid(); 6062 bool IsInvalid = false; 6063 bool IsStd = false; 6064 bool AddToKnown = false; 6065 Scope *DeclRegionScope = NamespcScope->getParent(); 6066 6067 NamespaceDecl *PrevNS = 0; 6068 if (II) { 6069 // C++ [namespace.def]p2: 6070 // The identifier in an original-namespace-definition shall not 6071 // have been previously defined in the declarative region in 6072 // which the original-namespace-definition appears. The 6073 // identifier in an original-namespace-definition is the name of 6074 // the namespace. Subsequently in that declarative region, it is 6075 // treated as an original-namespace-name. 6076 // 6077 // Since namespace names are unique in their scope, and we don't 6078 // look through using directives, just look for any ordinary names. 6079 6080 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member | 6081 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag | 6082 Decl::IDNS_Namespace; 6083 NamedDecl *PrevDecl = 0; 6084 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II); 6085 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 6086 ++I) { 6087 if ((*I)->getIdentifierNamespace() & IDNS) { 6088 PrevDecl = *I; 6089 break; 6090 } 6091 } 6092 6093 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 6094 6095 if (PrevNS) { 6096 // This is an extended namespace definition. 6097 if (IsInline != PrevNS->isInline()) 6098 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 6099 &IsInline, PrevNS); 6100 } else if (PrevDecl) { 6101 // This is an invalid name redefinition. 6102 Diag(Loc, diag::err_redefinition_different_kind) 6103 << II; 6104 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 6105 IsInvalid = true; 6106 // Continue on to push Namespc as current DeclContext and return it. 6107 } else if (II->isStr("std") && 6108 CurContext->getRedeclContext()->isTranslationUnit()) { 6109 // This is the first "real" definition of the namespace "std", so update 6110 // our cache of the "std" namespace to point at this definition. 6111 PrevNS = getStdNamespace(); 6112 IsStd = true; 6113 AddToKnown = !IsInline; 6114 } else { 6115 // We've seen this namespace for the first time. 6116 AddToKnown = !IsInline; 6117 } 6118 } else { 6119 // Anonymous namespaces. 6120 6121 // Determine whether the parent already has an anonymous namespace. 6122 DeclContext *Parent = CurContext->getRedeclContext(); 6123 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 6124 PrevNS = TU->getAnonymousNamespace(); 6125 } else { 6126 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 6127 PrevNS = ND->getAnonymousNamespace(); 6128 } 6129 6130 if (PrevNS && IsInline != PrevNS->isInline()) 6131 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 6132 &IsInline, PrevNS); 6133 } 6134 6135 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 6136 StartLoc, Loc, II, PrevNS); 6137 if (IsInvalid) 6138 Namespc->setInvalidDecl(); 6139 6140 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 6141 6142 // FIXME: Should we be merging attributes? 6143 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 6144 PushNamespaceVisibilityAttr(Attr, Loc); 6145 6146 if (IsStd) 6147 StdNamespace = Namespc; 6148 if (AddToKnown) 6149 KnownNamespaces[Namespc] = false; 6150 6151 if (II) { 6152 PushOnScopeChains(Namespc, DeclRegionScope); 6153 } else { 6154 // Link the anonymous namespace into its parent. 6155 DeclContext *Parent = CurContext->getRedeclContext(); 6156 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 6157 TU->setAnonymousNamespace(Namespc); 6158 } else { 6159 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 6160 } 6161 6162 CurContext->addDecl(Namespc); 6163 6164 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 6165 // behaves as if it were replaced by 6166 // namespace unique { /* empty body */ } 6167 // using namespace unique; 6168 // namespace unique { namespace-body } 6169 // where all occurrences of 'unique' in a translation unit are 6170 // replaced by the same identifier and this identifier differs 6171 // from all other identifiers in the entire program. 6172 6173 // We just create the namespace with an empty name and then add an 6174 // implicit using declaration, just like the standard suggests. 6175 // 6176 // CodeGen enforces the "universally unique" aspect by giving all 6177 // declarations semantically contained within an anonymous 6178 // namespace internal linkage. 6179 6180 if (!PrevNS) { 6181 UsingDirectiveDecl* UD 6182 = UsingDirectiveDecl::Create(Context, Parent, 6183 /* 'using' */ LBrace, 6184 /* 'namespace' */ SourceLocation(), 6185 /* qualifier */ NestedNameSpecifierLoc(), 6186 /* identifier */ SourceLocation(), 6187 Namespc, 6188 /* Ancestor */ Parent); 6189 UD->setImplicit(); 6190 Parent->addDecl(UD); 6191 } 6192 } 6193 6194 ActOnDocumentableDecl(Namespc); 6195 6196 // Although we could have an invalid decl (i.e. the namespace name is a 6197 // redefinition), push it as current DeclContext and try to continue parsing. 6198 // FIXME: We should be able to push Namespc here, so that the each DeclContext 6199 // for the namespace has the declarations that showed up in that particular 6200 // namespace definition. 6201 PushDeclContext(NamespcScope, Namespc); 6202 return Namespc; 6203} 6204 6205/// getNamespaceDecl - Returns the namespace a decl represents. If the decl 6206/// is a namespace alias, returns the namespace it points to. 6207static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 6208 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 6209 return AD->getNamespace(); 6210 return dyn_cast_or_null<NamespaceDecl>(D); 6211} 6212 6213/// ActOnFinishNamespaceDef - This callback is called after a namespace is 6214/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 6215void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 6216 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 6217 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 6218 Namespc->setRBraceLoc(RBrace); 6219 PopDeclContext(); 6220 if (Namespc->hasAttr<VisibilityAttr>()) 6221 PopPragmaVisibility(true, RBrace); 6222} 6223 6224CXXRecordDecl *Sema::getStdBadAlloc() const { 6225 return cast_or_null<CXXRecordDecl>( 6226 StdBadAlloc.get(Context.getExternalSource())); 6227} 6228 6229NamespaceDecl *Sema::getStdNamespace() const { 6230 return cast_or_null<NamespaceDecl>( 6231 StdNamespace.get(Context.getExternalSource())); 6232} 6233 6234/// \brief Retrieve the special "std" namespace, which may require us to 6235/// implicitly define the namespace. 6236NamespaceDecl *Sema::getOrCreateStdNamespace() { 6237 if (!StdNamespace) { 6238 // The "std" namespace has not yet been defined, so build one implicitly. 6239 StdNamespace = NamespaceDecl::Create(Context, 6240 Context.getTranslationUnitDecl(), 6241 /*Inline=*/false, 6242 SourceLocation(), SourceLocation(), 6243 &PP.getIdentifierTable().get("std"), 6244 /*PrevDecl=*/0); 6245 getStdNamespace()->setImplicit(true); 6246 } 6247 6248 return getStdNamespace(); 6249} 6250 6251bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 6252 assert(getLangOpts().CPlusPlus && 6253 "Looking for std::initializer_list outside of C++."); 6254 6255 // We're looking for implicit instantiations of 6256 // template <typename E> class std::initializer_list. 6257 6258 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 6259 return false; 6260 6261 ClassTemplateDecl *Template = 0; 6262 const TemplateArgument *Arguments = 0; 6263 6264 if (const RecordType *RT = Ty->getAs<RecordType>()) { 6265 6266 ClassTemplateSpecializationDecl *Specialization = 6267 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 6268 if (!Specialization) 6269 return false; 6270 6271 Template = Specialization->getSpecializedTemplate(); 6272 Arguments = Specialization->getTemplateArgs().data(); 6273 } else if (const TemplateSpecializationType *TST = 6274 Ty->getAs<TemplateSpecializationType>()) { 6275 Template = dyn_cast_or_null<ClassTemplateDecl>( 6276 TST->getTemplateName().getAsTemplateDecl()); 6277 Arguments = TST->getArgs(); 6278 } 6279 if (!Template) 6280 return false; 6281 6282 if (!StdInitializerList) { 6283 // Haven't recognized std::initializer_list yet, maybe this is it. 6284 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 6285 if (TemplateClass->getIdentifier() != 6286 &PP.getIdentifierTable().get("initializer_list") || 6287 !getStdNamespace()->InEnclosingNamespaceSetOf( 6288 TemplateClass->getDeclContext())) 6289 return false; 6290 // This is a template called std::initializer_list, but is it the right 6291 // template? 6292 TemplateParameterList *Params = Template->getTemplateParameters(); 6293 if (Params->getMinRequiredArguments() != 1) 6294 return false; 6295 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 6296 return false; 6297 6298 // It's the right template. 6299 StdInitializerList = Template; 6300 } 6301 6302 if (Template != StdInitializerList) 6303 return false; 6304 6305 // This is an instance of std::initializer_list. Find the argument type. 6306 if (Element) 6307 *Element = Arguments[0].getAsType(); 6308 return true; 6309} 6310 6311static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 6312 NamespaceDecl *Std = S.getStdNamespace(); 6313 if (!Std) { 6314 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 6315 return 0; 6316 } 6317 6318 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 6319 Loc, Sema::LookupOrdinaryName); 6320 if (!S.LookupQualifiedName(Result, Std)) { 6321 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 6322 return 0; 6323 } 6324 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 6325 if (!Template) { 6326 Result.suppressDiagnostics(); 6327 // We found something weird. Complain about the first thing we found. 6328 NamedDecl *Found = *Result.begin(); 6329 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 6330 return 0; 6331 } 6332 6333 // We found some template called std::initializer_list. Now verify that it's 6334 // correct. 6335 TemplateParameterList *Params = Template->getTemplateParameters(); 6336 if (Params->getMinRequiredArguments() != 1 || 6337 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 6338 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 6339 return 0; 6340 } 6341 6342 return Template; 6343} 6344 6345QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 6346 if (!StdInitializerList) { 6347 StdInitializerList = LookupStdInitializerList(*this, Loc); 6348 if (!StdInitializerList) 6349 return QualType(); 6350 } 6351 6352 TemplateArgumentListInfo Args(Loc, Loc); 6353 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 6354 Context.getTrivialTypeSourceInfo(Element, 6355 Loc))); 6356 return Context.getCanonicalType( 6357 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 6358} 6359 6360bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) { 6361 // C++ [dcl.init.list]p2: 6362 // A constructor is an initializer-list constructor if its first parameter 6363 // is of type std::initializer_list<E> or reference to possibly cv-qualified 6364 // std::initializer_list<E> for some type E, and either there are no other 6365 // parameters or else all other parameters have default arguments. 6366 if (Ctor->getNumParams() < 1 || 6367 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 6368 return false; 6369 6370 QualType ArgType = Ctor->getParamDecl(0)->getType(); 6371 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 6372 ArgType = RT->getPointeeType().getUnqualifiedType(); 6373 6374 return isStdInitializerList(ArgType, 0); 6375} 6376 6377/// \brief Determine whether a using statement is in a context where it will be 6378/// apply in all contexts. 6379static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 6380 switch (CurContext->getDeclKind()) { 6381 case Decl::TranslationUnit: 6382 return true; 6383 case Decl::LinkageSpec: 6384 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 6385 default: 6386 return false; 6387 } 6388} 6389 6390namespace { 6391 6392// Callback to only accept typo corrections that are namespaces. 6393class NamespaceValidatorCCC : public CorrectionCandidateCallback { 6394 public: 6395 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 6396 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 6397 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 6398 } 6399 return false; 6400 } 6401}; 6402 6403} 6404 6405static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 6406 CXXScopeSpec &SS, 6407 SourceLocation IdentLoc, 6408 IdentifierInfo *Ident) { 6409 NamespaceValidatorCCC Validator; 6410 R.clear(); 6411 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(), 6412 R.getLookupKind(), Sc, &SS, 6413 Validator)) { 6414 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 6415 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts())); 6416 if (DeclContext *DC = S.computeDeclContext(SS, false)) 6417 S.Diag(IdentLoc, diag::err_using_directive_member_suggest) 6418 << Ident << DC << CorrectedQuotedStr << SS.getRange() 6419 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(), 6420 CorrectedStr); 6421 else 6422 S.Diag(IdentLoc, diag::err_using_directive_suggest) 6423 << Ident << CorrectedQuotedStr 6424 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr); 6425 6426 S.Diag(Corrected.getCorrectionDecl()->getLocation(), 6427 diag::note_namespace_defined_here) << CorrectedQuotedStr; 6428 6429 R.addDecl(Corrected.getCorrectionDecl()); 6430 return true; 6431 } 6432 return false; 6433} 6434 6435Decl *Sema::ActOnUsingDirective(Scope *S, 6436 SourceLocation UsingLoc, 6437 SourceLocation NamespcLoc, 6438 CXXScopeSpec &SS, 6439 SourceLocation IdentLoc, 6440 IdentifierInfo *NamespcName, 6441 AttributeList *AttrList) { 6442 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 6443 assert(NamespcName && "Invalid NamespcName."); 6444 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 6445 6446 // This can only happen along a recovery path. 6447 while (S->getFlags() & Scope::TemplateParamScope) 6448 S = S->getParent(); 6449 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 6450 6451 UsingDirectiveDecl *UDir = 0; 6452 NestedNameSpecifier *Qualifier = 0; 6453 if (SS.isSet()) 6454 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 6455 6456 // Lookup namespace name. 6457 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 6458 LookupParsedName(R, S, &SS); 6459 if (R.isAmbiguous()) 6460 return 0; 6461 6462 if (R.empty()) { 6463 R.clear(); 6464 // Allow "using namespace std;" or "using namespace ::std;" even if 6465 // "std" hasn't been defined yet, for GCC compatibility. 6466 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 6467 NamespcName->isStr("std")) { 6468 Diag(IdentLoc, diag::ext_using_undefined_std); 6469 R.addDecl(getOrCreateStdNamespace()); 6470 R.resolveKind(); 6471 } 6472 // Otherwise, attempt typo correction. 6473 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 6474 } 6475 6476 if (!R.empty()) { 6477 NamedDecl *Named = R.getFoundDecl(); 6478 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named)) 6479 && "expected namespace decl"); 6480 // C++ [namespace.udir]p1: 6481 // A using-directive specifies that the names in the nominated 6482 // namespace can be used in the scope in which the 6483 // using-directive appears after the using-directive. During 6484 // unqualified name lookup (3.4.1), the names appear as if they 6485 // were declared in the nearest enclosing namespace which 6486 // contains both the using-directive and the nominated 6487 // namespace. [Note: in this context, "contains" means "contains 6488 // directly or indirectly". ] 6489 6490 // Find enclosing context containing both using-directive and 6491 // nominated namespace. 6492 NamespaceDecl *NS = getNamespaceDecl(Named); 6493 DeclContext *CommonAncestor = cast<DeclContext>(NS); 6494 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 6495 CommonAncestor = CommonAncestor->getParent(); 6496 6497 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 6498 SS.getWithLocInContext(Context), 6499 IdentLoc, Named, CommonAncestor); 6500 6501 if (IsUsingDirectiveInToplevelContext(CurContext) && 6502 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 6503 Diag(IdentLoc, diag::warn_using_directive_in_header); 6504 } 6505 6506 PushUsingDirective(S, UDir); 6507 } else { 6508 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 6509 } 6510 6511 if (UDir) 6512 ProcessDeclAttributeList(S, UDir, AttrList); 6513 6514 return UDir; 6515} 6516 6517void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 6518 // If the scope has an associated entity and the using directive is at 6519 // namespace or translation unit scope, add the UsingDirectiveDecl into 6520 // its lookup structure so qualified name lookup can find it. 6521 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()); 6522 if (Ctx && !Ctx->isFunctionOrMethod()) 6523 Ctx->addDecl(UDir); 6524 else 6525 // Otherwise, it is at block sope. The using-directives will affect lookup 6526 // only to the end of the scope. 6527 S->PushUsingDirective(UDir); 6528} 6529 6530 6531Decl *Sema::ActOnUsingDeclaration(Scope *S, 6532 AccessSpecifier AS, 6533 bool HasUsingKeyword, 6534 SourceLocation UsingLoc, 6535 CXXScopeSpec &SS, 6536 UnqualifiedId &Name, 6537 AttributeList *AttrList, 6538 bool IsTypeName, 6539 SourceLocation TypenameLoc) { 6540 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 6541 6542 switch (Name.getKind()) { 6543 case UnqualifiedId::IK_ImplicitSelfParam: 6544 case UnqualifiedId::IK_Identifier: 6545 case UnqualifiedId::IK_OperatorFunctionId: 6546 case UnqualifiedId::IK_LiteralOperatorId: 6547 case UnqualifiedId::IK_ConversionFunctionId: 6548 break; 6549 6550 case UnqualifiedId::IK_ConstructorName: 6551 case UnqualifiedId::IK_ConstructorTemplateId: 6552 // C++11 inheriting constructors. 6553 Diag(Name.getLocStart(), 6554 getLangOpts().CPlusPlus11 ? 6555 diag::warn_cxx98_compat_using_decl_constructor : 6556 diag::err_using_decl_constructor) 6557 << SS.getRange(); 6558 6559 if (getLangOpts().CPlusPlus11) break; 6560 6561 return 0; 6562 6563 case UnqualifiedId::IK_DestructorName: 6564 Diag(Name.getLocStart(), diag::err_using_decl_destructor) 6565 << SS.getRange(); 6566 return 0; 6567 6568 case UnqualifiedId::IK_TemplateId: 6569 Diag(Name.getLocStart(), diag::err_using_decl_template_id) 6570 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 6571 return 0; 6572 } 6573 6574 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 6575 DeclarationName TargetName = TargetNameInfo.getName(); 6576 if (!TargetName) 6577 return 0; 6578 6579 // Warn about access declarations. 6580 // TODO: store that the declaration was written without 'using' and 6581 // talk about access decls instead of using decls in the 6582 // diagnostics. 6583 if (!HasUsingKeyword) { 6584 UsingLoc = Name.getLocStart(); 6585 6586 Diag(UsingLoc, diag::warn_access_decl_deprecated) 6587 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 6588 } 6589 6590 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 6591 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 6592 return 0; 6593 6594 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 6595 TargetNameInfo, AttrList, 6596 /* IsInstantiation */ false, 6597 IsTypeName, TypenameLoc); 6598 if (UD) 6599 PushOnScopeChains(UD, S, /*AddToContext*/ false); 6600 6601 return UD; 6602} 6603 6604/// \brief Determine whether a using declaration considers the given 6605/// declarations as "equivalent", e.g., if they are redeclarations of 6606/// the same entity or are both typedefs of the same type. 6607static bool 6608IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2, 6609 bool &SuppressRedeclaration) { 6610 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) { 6611 SuppressRedeclaration = false; 6612 return true; 6613 } 6614 6615 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 6616 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) { 6617 SuppressRedeclaration = true; 6618 return Context.hasSameType(TD1->getUnderlyingType(), 6619 TD2->getUnderlyingType()); 6620 } 6621 6622 return false; 6623} 6624 6625 6626/// Determines whether to create a using shadow decl for a particular 6627/// decl, given the set of decls existing prior to this using lookup. 6628bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 6629 const LookupResult &Previous) { 6630 // Diagnose finding a decl which is not from a base class of the 6631 // current class. We do this now because there are cases where this 6632 // function will silently decide not to build a shadow decl, which 6633 // will pre-empt further diagnostics. 6634 // 6635 // We don't need to do this in C++0x because we do the check once on 6636 // the qualifier. 6637 // 6638 // FIXME: diagnose the following if we care enough: 6639 // struct A { int foo; }; 6640 // struct B : A { using A::foo; }; 6641 // template <class T> struct C : A {}; 6642 // template <class T> struct D : C<T> { using B::foo; } // <--- 6643 // This is invalid (during instantiation) in C++03 because B::foo 6644 // resolves to the using decl in B, which is not a base class of D<T>. 6645 // We can't diagnose it immediately because C<T> is an unknown 6646 // specialization. The UsingShadowDecl in D<T> then points directly 6647 // to A::foo, which will look well-formed when we instantiate. 6648 // The right solution is to not collapse the shadow-decl chain. 6649 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 6650 DeclContext *OrigDC = Orig->getDeclContext(); 6651 6652 // Handle enums and anonymous structs. 6653 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 6654 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 6655 while (OrigRec->isAnonymousStructOrUnion()) 6656 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 6657 6658 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 6659 if (OrigDC == CurContext) { 6660 Diag(Using->getLocation(), 6661 diag::err_using_decl_nested_name_specifier_is_current_class) 6662 << Using->getQualifierLoc().getSourceRange(); 6663 Diag(Orig->getLocation(), diag::note_using_decl_target); 6664 return true; 6665 } 6666 6667 Diag(Using->getQualifierLoc().getBeginLoc(), 6668 diag::err_using_decl_nested_name_specifier_is_not_base_class) 6669 << Using->getQualifier() 6670 << cast<CXXRecordDecl>(CurContext) 6671 << Using->getQualifierLoc().getSourceRange(); 6672 Diag(Orig->getLocation(), diag::note_using_decl_target); 6673 return true; 6674 } 6675 } 6676 6677 if (Previous.empty()) return false; 6678 6679 NamedDecl *Target = Orig; 6680 if (isa<UsingShadowDecl>(Target)) 6681 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 6682 6683 // If the target happens to be one of the previous declarations, we 6684 // don't have a conflict. 6685 // 6686 // FIXME: but we might be increasing its access, in which case we 6687 // should redeclare it. 6688 NamedDecl *NonTag = 0, *Tag = 0; 6689 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 6690 I != E; ++I) { 6691 NamedDecl *D = (*I)->getUnderlyingDecl(); 6692 bool Result; 6693 if (IsEquivalentForUsingDecl(Context, D, Target, Result)) 6694 return Result; 6695 6696 (isa<TagDecl>(D) ? Tag : NonTag) = D; 6697 } 6698 6699 if (Target->isFunctionOrFunctionTemplate()) { 6700 FunctionDecl *FD; 6701 if (isa<FunctionTemplateDecl>(Target)) 6702 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl(); 6703 else 6704 FD = cast<FunctionDecl>(Target); 6705 6706 NamedDecl *OldDecl = 0; 6707 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) { 6708 case Ovl_Overload: 6709 return false; 6710 6711 case Ovl_NonFunction: 6712 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6713 break; 6714 6715 // We found a decl with the exact signature. 6716 case Ovl_Match: 6717 // If we're in a record, we want to hide the target, so we 6718 // return true (without a diagnostic) to tell the caller not to 6719 // build a shadow decl. 6720 if (CurContext->isRecord()) 6721 return true; 6722 6723 // If we're not in a record, this is an error. 6724 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6725 break; 6726 } 6727 6728 Diag(Target->getLocation(), diag::note_using_decl_target); 6729 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 6730 return true; 6731 } 6732 6733 // Target is not a function. 6734 6735 if (isa<TagDecl>(Target)) { 6736 // No conflict between a tag and a non-tag. 6737 if (!Tag) return false; 6738 6739 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6740 Diag(Target->getLocation(), diag::note_using_decl_target); 6741 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 6742 return true; 6743 } 6744 6745 // No conflict between a tag and a non-tag. 6746 if (!NonTag) return false; 6747 6748 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6749 Diag(Target->getLocation(), diag::note_using_decl_target); 6750 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 6751 return true; 6752} 6753 6754/// Builds a shadow declaration corresponding to a 'using' declaration. 6755UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 6756 UsingDecl *UD, 6757 NamedDecl *Orig) { 6758 6759 // If we resolved to another shadow declaration, just coalesce them. 6760 NamedDecl *Target = Orig; 6761 if (isa<UsingShadowDecl>(Target)) { 6762 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 6763 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 6764 } 6765 6766 UsingShadowDecl *Shadow 6767 = UsingShadowDecl::Create(Context, CurContext, 6768 UD->getLocation(), UD, Target); 6769 UD->addShadowDecl(Shadow); 6770 6771 Shadow->setAccess(UD->getAccess()); 6772 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 6773 Shadow->setInvalidDecl(); 6774 6775 if (S) 6776 PushOnScopeChains(Shadow, S); 6777 else 6778 CurContext->addDecl(Shadow); 6779 6780 6781 return Shadow; 6782} 6783 6784/// Hides a using shadow declaration. This is required by the current 6785/// using-decl implementation when a resolvable using declaration in a 6786/// class is followed by a declaration which would hide or override 6787/// one or more of the using decl's targets; for example: 6788/// 6789/// struct Base { void foo(int); }; 6790/// struct Derived : Base { 6791/// using Base::foo; 6792/// void foo(int); 6793/// }; 6794/// 6795/// The governing language is C++03 [namespace.udecl]p12: 6796/// 6797/// When a using-declaration brings names from a base class into a 6798/// derived class scope, member functions in the derived class 6799/// override and/or hide member functions with the same name and 6800/// parameter types in a base class (rather than conflicting). 6801/// 6802/// There are two ways to implement this: 6803/// (1) optimistically create shadow decls when they're not hidden 6804/// by existing declarations, or 6805/// (2) don't create any shadow decls (or at least don't make them 6806/// visible) until we've fully parsed/instantiated the class. 6807/// The problem with (1) is that we might have to retroactively remove 6808/// a shadow decl, which requires several O(n) operations because the 6809/// decl structures are (very reasonably) not designed for removal. 6810/// (2) avoids this but is very fiddly and phase-dependent. 6811void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 6812 if (Shadow->getDeclName().getNameKind() == 6813 DeclarationName::CXXConversionFunctionName) 6814 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 6815 6816 // Remove it from the DeclContext... 6817 Shadow->getDeclContext()->removeDecl(Shadow); 6818 6819 // ...and the scope, if applicable... 6820 if (S) { 6821 S->RemoveDecl(Shadow); 6822 IdResolver.RemoveDecl(Shadow); 6823 } 6824 6825 // ...and the using decl. 6826 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 6827 6828 // TODO: complain somehow if Shadow was used. It shouldn't 6829 // be possible for this to happen, because...? 6830} 6831 6832/// Builds a using declaration. 6833/// 6834/// \param IsInstantiation - Whether this call arises from an 6835/// instantiation of an unresolved using declaration. We treat 6836/// the lookup differently for these declarations. 6837NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 6838 SourceLocation UsingLoc, 6839 CXXScopeSpec &SS, 6840 const DeclarationNameInfo &NameInfo, 6841 AttributeList *AttrList, 6842 bool IsInstantiation, 6843 bool IsTypeName, 6844 SourceLocation TypenameLoc) { 6845 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 6846 SourceLocation IdentLoc = NameInfo.getLoc(); 6847 assert(IdentLoc.isValid() && "Invalid TargetName location."); 6848 6849 // FIXME: We ignore attributes for now. 6850 6851 if (SS.isEmpty()) { 6852 Diag(IdentLoc, diag::err_using_requires_qualname); 6853 return 0; 6854 } 6855 6856 // Do the redeclaration lookup in the current scope. 6857 LookupResult Previous(*this, NameInfo, LookupUsingDeclName, 6858 ForRedeclaration); 6859 Previous.setHideTags(false); 6860 if (S) { 6861 LookupName(Previous, S); 6862 6863 // It is really dumb that we have to do this. 6864 LookupResult::Filter F = Previous.makeFilter(); 6865 while (F.hasNext()) { 6866 NamedDecl *D = F.next(); 6867 if (!isDeclInScope(D, CurContext, S)) 6868 F.erase(); 6869 } 6870 F.done(); 6871 } else { 6872 assert(IsInstantiation && "no scope in non-instantiation"); 6873 assert(CurContext->isRecord() && "scope not record in instantiation"); 6874 LookupQualifiedName(Previous, CurContext); 6875 } 6876 6877 // Check for invalid redeclarations. 6878 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous)) 6879 return 0; 6880 6881 // Check for bad qualifiers. 6882 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc)) 6883 return 0; 6884 6885 DeclContext *LookupContext = computeDeclContext(SS); 6886 NamedDecl *D; 6887 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 6888 if (!LookupContext) { 6889 if (IsTypeName) { 6890 // FIXME: not all declaration name kinds are legal here 6891 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 6892 UsingLoc, TypenameLoc, 6893 QualifierLoc, 6894 IdentLoc, NameInfo.getName()); 6895 } else { 6896 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 6897 QualifierLoc, NameInfo); 6898 } 6899 } else { 6900 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 6901 NameInfo, IsTypeName); 6902 } 6903 D->setAccess(AS); 6904 CurContext->addDecl(D); 6905 6906 if (!LookupContext) return D; 6907 UsingDecl *UD = cast<UsingDecl>(D); 6908 6909 if (RequireCompleteDeclContext(SS, LookupContext)) { 6910 UD->setInvalidDecl(); 6911 return UD; 6912 } 6913 6914 // The normal rules do not apply to inheriting constructor declarations. 6915 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) { 6916 if (CheckInheritingConstructorUsingDecl(UD)) 6917 UD->setInvalidDecl(); 6918 return UD; 6919 } 6920 6921 // Otherwise, look up the target name. 6922 6923 LookupResult R(*this, NameInfo, LookupOrdinaryName); 6924 6925 // Unlike most lookups, we don't always want to hide tag 6926 // declarations: tag names are visible through the using declaration 6927 // even if hidden by ordinary names, *except* in a dependent context 6928 // where it's important for the sanity of two-phase lookup. 6929 if (!IsInstantiation) 6930 R.setHideTags(false); 6931 6932 // For the purposes of this lookup, we have a base object type 6933 // equal to that of the current context. 6934 if (CurContext->isRecord()) { 6935 R.setBaseObjectType( 6936 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 6937 } 6938 6939 LookupQualifiedName(R, LookupContext); 6940 6941 if (R.empty()) { 6942 Diag(IdentLoc, diag::err_no_member) 6943 << NameInfo.getName() << LookupContext << SS.getRange(); 6944 UD->setInvalidDecl(); 6945 return UD; 6946 } 6947 6948 if (R.isAmbiguous()) { 6949 UD->setInvalidDecl(); 6950 return UD; 6951 } 6952 6953 if (IsTypeName) { 6954 // If we asked for a typename and got a non-type decl, error out. 6955 if (!R.getAsSingle<TypeDecl>()) { 6956 Diag(IdentLoc, diag::err_using_typename_non_type); 6957 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 6958 Diag((*I)->getUnderlyingDecl()->getLocation(), 6959 diag::note_using_decl_target); 6960 UD->setInvalidDecl(); 6961 return UD; 6962 } 6963 } else { 6964 // If we asked for a non-typename and we got a type, error out, 6965 // but only if this is an instantiation of an unresolved using 6966 // decl. Otherwise just silently find the type name. 6967 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 6968 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 6969 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 6970 UD->setInvalidDecl(); 6971 return UD; 6972 } 6973 } 6974 6975 // C++0x N2914 [namespace.udecl]p6: 6976 // A using-declaration shall not name a namespace. 6977 if (R.getAsSingle<NamespaceDecl>()) { 6978 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 6979 << SS.getRange(); 6980 UD->setInvalidDecl(); 6981 return UD; 6982 } 6983 6984 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 6985 if (!CheckUsingShadowDecl(UD, *I, Previous)) 6986 BuildUsingShadowDecl(S, UD, *I); 6987 } 6988 6989 return UD; 6990} 6991 6992/// Additional checks for a using declaration referring to a constructor name. 6993bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 6994 assert(!UD->isTypeName() && "expecting a constructor name"); 6995 6996 const Type *SourceType = UD->getQualifier()->getAsType(); 6997 assert(SourceType && 6998 "Using decl naming constructor doesn't have type in scope spec."); 6999 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 7000 7001 // Check whether the named type is a direct base class. 7002 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified(); 7003 CXXRecordDecl::base_class_iterator BaseIt, BaseE; 7004 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end(); 7005 BaseIt != BaseE; ++BaseIt) { 7006 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified(); 7007 if (CanonicalSourceType == BaseType) 7008 break; 7009 if (BaseIt->getType()->isDependentType()) 7010 break; 7011 } 7012 7013 if (BaseIt == BaseE) { 7014 // Did not find SourceType in the bases. 7015 Diag(UD->getUsingLocation(), 7016 diag::err_using_decl_constructor_not_in_direct_base) 7017 << UD->getNameInfo().getSourceRange() 7018 << QualType(SourceType, 0) << TargetClass; 7019 return true; 7020 } 7021 7022 if (!CurContext->isDependentContext()) 7023 BaseIt->setInheritConstructors(); 7024 7025 return false; 7026} 7027 7028/// Checks that the given using declaration is not an invalid 7029/// redeclaration. Note that this is checking only for the using decl 7030/// itself, not for any ill-formedness among the UsingShadowDecls. 7031bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 7032 bool isTypeName, 7033 const CXXScopeSpec &SS, 7034 SourceLocation NameLoc, 7035 const LookupResult &Prev) { 7036 // C++03 [namespace.udecl]p8: 7037 // C++0x [namespace.udecl]p10: 7038 // A using-declaration is a declaration and can therefore be used 7039 // repeatedly where (and only where) multiple declarations are 7040 // allowed. 7041 // 7042 // That's in non-member contexts. 7043 if (!CurContext->getRedeclContext()->isRecord()) 7044 return false; 7045 7046 NestedNameSpecifier *Qual 7047 = static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 7048 7049 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 7050 NamedDecl *D = *I; 7051 7052 bool DTypename; 7053 NestedNameSpecifier *DQual; 7054 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 7055 DTypename = UD->isTypeName(); 7056 DQual = UD->getQualifier(); 7057 } else if (UnresolvedUsingValueDecl *UD 7058 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 7059 DTypename = false; 7060 DQual = UD->getQualifier(); 7061 } else if (UnresolvedUsingTypenameDecl *UD 7062 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 7063 DTypename = true; 7064 DQual = UD->getQualifier(); 7065 } else continue; 7066 7067 // using decls differ if one says 'typename' and the other doesn't. 7068 // FIXME: non-dependent using decls? 7069 if (isTypeName != DTypename) continue; 7070 7071 // using decls differ if they name different scopes (but note that 7072 // template instantiation can cause this check to trigger when it 7073 // didn't before instantiation). 7074 if (Context.getCanonicalNestedNameSpecifier(Qual) != 7075 Context.getCanonicalNestedNameSpecifier(DQual)) 7076 continue; 7077 7078 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 7079 Diag(D->getLocation(), diag::note_using_decl) << 1; 7080 return true; 7081 } 7082 7083 return false; 7084} 7085 7086 7087/// Checks that the given nested-name qualifier used in a using decl 7088/// in the current context is appropriately related to the current 7089/// scope. If an error is found, diagnoses it and returns true. 7090bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 7091 const CXXScopeSpec &SS, 7092 SourceLocation NameLoc) { 7093 DeclContext *NamedContext = computeDeclContext(SS); 7094 7095 if (!CurContext->isRecord()) { 7096 // C++03 [namespace.udecl]p3: 7097 // C++0x [namespace.udecl]p8: 7098 // A using-declaration for a class member shall be a member-declaration. 7099 7100 // If we weren't able to compute a valid scope, it must be a 7101 // dependent class scope. 7102 if (!NamedContext || NamedContext->isRecord()) { 7103 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 7104 << SS.getRange(); 7105 return true; 7106 } 7107 7108 // Otherwise, everything is known to be fine. 7109 return false; 7110 } 7111 7112 // The current scope is a record. 7113 7114 // If the named context is dependent, we can't decide much. 7115 if (!NamedContext) { 7116 // FIXME: in C++0x, we can diagnose if we can prove that the 7117 // nested-name-specifier does not refer to a base class, which is 7118 // still possible in some cases. 7119 7120 // Otherwise we have to conservatively report that things might be 7121 // okay. 7122 return false; 7123 } 7124 7125 if (!NamedContext->isRecord()) { 7126 // Ideally this would point at the last name in the specifier, 7127 // but we don't have that level of source info. 7128 Diag(SS.getRange().getBegin(), 7129 diag::err_using_decl_nested_name_specifier_is_not_class) 7130 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange(); 7131 return true; 7132 } 7133 7134 if (!NamedContext->isDependentContext() && 7135 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 7136 return true; 7137 7138 if (getLangOpts().CPlusPlus11) { 7139 // C++0x [namespace.udecl]p3: 7140 // In a using-declaration used as a member-declaration, the 7141 // nested-name-specifier shall name a base class of the class 7142 // being defined. 7143 7144 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 7145 cast<CXXRecordDecl>(NamedContext))) { 7146 if (CurContext == NamedContext) { 7147 Diag(NameLoc, 7148 diag::err_using_decl_nested_name_specifier_is_current_class) 7149 << SS.getRange(); 7150 return true; 7151 } 7152 7153 Diag(SS.getRange().getBegin(), 7154 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7155 << (NestedNameSpecifier*) SS.getScopeRep() 7156 << cast<CXXRecordDecl>(CurContext) 7157 << SS.getRange(); 7158 return true; 7159 } 7160 7161 return false; 7162 } 7163 7164 // C++03 [namespace.udecl]p4: 7165 // A using-declaration used as a member-declaration shall refer 7166 // to a member of a base class of the class being defined [etc.]. 7167 7168 // Salient point: SS doesn't have to name a base class as long as 7169 // lookup only finds members from base classes. Therefore we can 7170 // diagnose here only if we can prove that that can't happen, 7171 // i.e. if the class hierarchies provably don't intersect. 7172 7173 // TODO: it would be nice if "definitely valid" results were cached 7174 // in the UsingDecl and UsingShadowDecl so that these checks didn't 7175 // need to be repeated. 7176 7177 struct UserData { 7178 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases; 7179 7180 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) { 7181 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 7182 Data->Bases.insert(Base); 7183 return true; 7184 } 7185 7186 bool hasDependentBases(const CXXRecordDecl *Class) { 7187 return !Class->forallBases(collect, this); 7188 } 7189 7190 /// Returns true if the base is dependent or is one of the 7191 /// accumulated base classes. 7192 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) { 7193 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 7194 return !Data->Bases.count(Base); 7195 } 7196 7197 bool mightShareBases(const CXXRecordDecl *Class) { 7198 return Bases.count(Class) || !Class->forallBases(doesNotContain, this); 7199 } 7200 }; 7201 7202 UserData Data; 7203 7204 // Returns false if we find a dependent base. 7205 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext))) 7206 return false; 7207 7208 // Returns false if the class has a dependent base or if it or one 7209 // of its bases is present in the base set of the current context. 7210 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext))) 7211 return false; 7212 7213 Diag(SS.getRange().getBegin(), 7214 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7215 << (NestedNameSpecifier*) SS.getScopeRep() 7216 << cast<CXXRecordDecl>(CurContext) 7217 << SS.getRange(); 7218 7219 return true; 7220} 7221 7222Decl *Sema::ActOnAliasDeclaration(Scope *S, 7223 AccessSpecifier AS, 7224 MultiTemplateParamsArg TemplateParamLists, 7225 SourceLocation UsingLoc, 7226 UnqualifiedId &Name, 7227 AttributeList *AttrList, 7228 TypeResult Type) { 7229 // Skip up to the relevant declaration scope. 7230 while (S->getFlags() & Scope::TemplateParamScope) 7231 S = S->getParent(); 7232 assert((S->getFlags() & Scope::DeclScope) && 7233 "got alias-declaration outside of declaration scope"); 7234 7235 if (Type.isInvalid()) 7236 return 0; 7237 7238 bool Invalid = false; 7239 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 7240 TypeSourceInfo *TInfo = 0; 7241 GetTypeFromParser(Type.get(), &TInfo); 7242 7243 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 7244 return 0; 7245 7246 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 7247 UPPC_DeclarationType)) { 7248 Invalid = true; 7249 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 7250 TInfo->getTypeLoc().getBeginLoc()); 7251 } 7252 7253 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration); 7254 LookupName(Previous, S); 7255 7256 // Warn about shadowing the name of a template parameter. 7257 if (Previous.isSingleResult() && 7258 Previous.getFoundDecl()->isTemplateParameter()) { 7259 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 7260 Previous.clear(); 7261 } 7262 7263 assert(Name.Kind == UnqualifiedId::IK_Identifier && 7264 "name in alias declaration must be an identifier"); 7265 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 7266 Name.StartLocation, 7267 Name.Identifier, TInfo); 7268 7269 NewTD->setAccess(AS); 7270 7271 if (Invalid) 7272 NewTD->setInvalidDecl(); 7273 7274 ProcessDeclAttributeList(S, NewTD, AttrList); 7275 7276 CheckTypedefForVariablyModifiedType(S, NewTD); 7277 Invalid |= NewTD->isInvalidDecl(); 7278 7279 bool Redeclaration = false; 7280 7281 NamedDecl *NewND; 7282 if (TemplateParamLists.size()) { 7283 TypeAliasTemplateDecl *OldDecl = 0; 7284 TemplateParameterList *OldTemplateParams = 0; 7285 7286 if (TemplateParamLists.size() != 1) { 7287 Diag(UsingLoc, diag::err_alias_template_extra_headers) 7288 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 7289 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 7290 } 7291 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 7292 7293 // Only consider previous declarations in the same scope. 7294 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 7295 /*ExplicitInstantiationOrSpecialization*/false); 7296 if (!Previous.empty()) { 7297 Redeclaration = true; 7298 7299 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 7300 if (!OldDecl && !Invalid) { 7301 Diag(UsingLoc, diag::err_redefinition_different_kind) 7302 << Name.Identifier; 7303 7304 NamedDecl *OldD = Previous.getRepresentativeDecl(); 7305 if (OldD->getLocation().isValid()) 7306 Diag(OldD->getLocation(), diag::note_previous_definition); 7307 7308 Invalid = true; 7309 } 7310 7311 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 7312 if (TemplateParameterListsAreEqual(TemplateParams, 7313 OldDecl->getTemplateParameters(), 7314 /*Complain=*/true, 7315 TPL_TemplateMatch)) 7316 OldTemplateParams = OldDecl->getTemplateParameters(); 7317 else 7318 Invalid = true; 7319 7320 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 7321 if (!Invalid && 7322 !Context.hasSameType(OldTD->getUnderlyingType(), 7323 NewTD->getUnderlyingType())) { 7324 // FIXME: The C++0x standard does not clearly say this is ill-formed, 7325 // but we can't reasonably accept it. 7326 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 7327 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 7328 if (OldTD->getLocation().isValid()) 7329 Diag(OldTD->getLocation(), diag::note_previous_definition); 7330 Invalid = true; 7331 } 7332 } 7333 } 7334 7335 // Merge any previous default template arguments into our parameters, 7336 // and check the parameter list. 7337 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 7338 TPC_TypeAliasTemplate)) 7339 return 0; 7340 7341 TypeAliasTemplateDecl *NewDecl = 7342 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 7343 Name.Identifier, TemplateParams, 7344 NewTD); 7345 7346 NewDecl->setAccess(AS); 7347 7348 if (Invalid) 7349 NewDecl->setInvalidDecl(); 7350 else if (OldDecl) 7351 NewDecl->setPreviousDeclaration(OldDecl); 7352 7353 NewND = NewDecl; 7354 } else { 7355 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 7356 NewND = NewTD; 7357 } 7358 7359 if (!Redeclaration) 7360 PushOnScopeChains(NewND, S); 7361 7362 ActOnDocumentableDecl(NewND); 7363 return NewND; 7364} 7365 7366Decl *Sema::ActOnNamespaceAliasDef(Scope *S, 7367 SourceLocation NamespaceLoc, 7368 SourceLocation AliasLoc, 7369 IdentifierInfo *Alias, 7370 CXXScopeSpec &SS, 7371 SourceLocation IdentLoc, 7372 IdentifierInfo *Ident) { 7373 7374 // Lookup the namespace name. 7375 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 7376 LookupParsedName(R, S, &SS); 7377 7378 // Check if we have a previous declaration with the same name. 7379 NamedDecl *PrevDecl 7380 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName, 7381 ForRedeclaration); 7382 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S)) 7383 PrevDecl = 0; 7384 7385 if (PrevDecl) { 7386 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 7387 // We already have an alias with the same name that points to the same 7388 // namespace, so don't create a new one. 7389 // FIXME: At some point, we'll want to create the (redundant) 7390 // declaration to maintain better source information. 7391 if (!R.isAmbiguous() && !R.empty() && 7392 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl()))) 7393 return 0; 7394 } 7395 7396 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition : 7397 diag::err_redefinition_different_kind; 7398 Diag(AliasLoc, DiagID) << Alias; 7399 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 7400 return 0; 7401 } 7402 7403 if (R.isAmbiguous()) 7404 return 0; 7405 7406 if (R.empty()) { 7407 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 7408 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 7409 return 0; 7410 } 7411 } 7412 7413 NamespaceAliasDecl *AliasDecl = 7414 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 7415 Alias, SS.getWithLocInContext(Context), 7416 IdentLoc, R.getFoundDecl()); 7417 7418 PushOnScopeChains(AliasDecl, S); 7419 return AliasDecl; 7420} 7421 7422Sema::ImplicitExceptionSpecification 7423Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, 7424 CXXMethodDecl *MD) { 7425 CXXRecordDecl *ClassDecl = MD->getParent(); 7426 7427 // C++ [except.spec]p14: 7428 // An implicitly declared special member function (Clause 12) shall have an 7429 // exception-specification. [...] 7430 ImplicitExceptionSpecification ExceptSpec(*this); 7431 if (ClassDecl->isInvalidDecl()) 7432 return ExceptSpec; 7433 7434 // Direct base-class constructors. 7435 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 7436 BEnd = ClassDecl->bases_end(); 7437 B != BEnd; ++B) { 7438 if (B->isVirtual()) // Handled below. 7439 continue; 7440 7441 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 7442 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7443 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 7444 // If this is a deleted function, add it anyway. This might be conformant 7445 // with the standard. This might not. I'm not sure. It might not matter. 7446 if (Constructor) 7447 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 7448 } 7449 } 7450 7451 // Virtual base-class constructors. 7452 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 7453 BEnd = ClassDecl->vbases_end(); 7454 B != BEnd; ++B) { 7455 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 7456 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7457 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 7458 // If this is a deleted function, add it anyway. This might be conformant 7459 // with the standard. This might not. I'm not sure. It might not matter. 7460 if (Constructor) 7461 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 7462 } 7463 } 7464 7465 // Field constructors. 7466 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 7467 FEnd = ClassDecl->field_end(); 7468 F != FEnd; ++F) { 7469 if (F->hasInClassInitializer()) { 7470 if (Expr *E = F->getInClassInitializer()) 7471 ExceptSpec.CalledExpr(E); 7472 else if (!F->isInvalidDecl()) 7473 // DR1351: 7474 // If the brace-or-equal-initializer of a non-static data member 7475 // invokes a defaulted default constructor of its class or of an 7476 // enclosing class in a potentially evaluated subexpression, the 7477 // program is ill-formed. 7478 // 7479 // This resolution is unworkable: the exception specification of the 7480 // default constructor can be needed in an unevaluated context, in 7481 // particular, in the operand of a noexcept-expression, and we can be 7482 // unable to compute an exception specification for an enclosed class. 7483 // 7484 // We do not allow an in-class initializer to require the evaluation 7485 // of the exception specification for any in-class initializer whose 7486 // definition is not lexically complete. 7487 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD; 7488 } else if (const RecordType *RecordTy 7489 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 7490 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 7491 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 7492 // If this is a deleted function, add it anyway. This might be conformant 7493 // with the standard. This might not. I'm not sure. It might not matter. 7494 // In particular, the problem is that this function never gets called. It 7495 // might just be ill-formed because this function attempts to refer to 7496 // a deleted function here. 7497 if (Constructor) 7498 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 7499 } 7500 } 7501 7502 return ExceptSpec; 7503} 7504 7505Sema::ImplicitExceptionSpecification 7506Sema::ComputeInheritingCtorExceptionSpec(CXXMethodDecl *MD) { 7507 ImplicitExceptionSpecification ExceptSpec(*this); 7508 // FIXME: Compute the exception spec. 7509 return ExceptSpec; 7510} 7511 7512namespace { 7513/// RAII object to register a special member as being currently declared. 7514struct DeclaringSpecialMember { 7515 Sema &S; 7516 Sema::SpecialMemberDecl D; 7517 bool WasAlreadyBeingDeclared; 7518 7519 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 7520 : S(S), D(RD, CSM) { 7521 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D); 7522 if (WasAlreadyBeingDeclared) 7523 // This almost never happens, but if it does, ensure that our cache 7524 // doesn't contain a stale result. 7525 S.SpecialMemberCache.clear(); 7526 7527 // FIXME: Register a note to be produced if we encounter an error while 7528 // declaring the special member. 7529 } 7530 ~DeclaringSpecialMember() { 7531 if (!WasAlreadyBeingDeclared) 7532 S.SpecialMembersBeingDeclared.erase(D); 7533 } 7534 7535 /// \brief Are we already trying to declare this special member? 7536 bool isAlreadyBeingDeclared() const { 7537 return WasAlreadyBeingDeclared; 7538 } 7539}; 7540} 7541 7542CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 7543 CXXRecordDecl *ClassDecl) { 7544 // C++ [class.ctor]p5: 7545 // A default constructor for a class X is a constructor of class X 7546 // that can be called without an argument. If there is no 7547 // user-declared constructor for class X, a default constructor is 7548 // implicitly declared. An implicitly-declared default constructor 7549 // is an inline public member of its class. 7550 assert(ClassDecl->needsImplicitDefaultConstructor() && 7551 "Should not build implicit default constructor!"); 7552 7553 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 7554 if (DSM.isAlreadyBeingDeclared()) 7555 return 0; 7556 7557 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 7558 CXXDefaultConstructor, 7559 false); 7560 7561 // Create the actual constructor declaration. 7562 CanQualType ClassType 7563 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 7564 SourceLocation ClassLoc = ClassDecl->getLocation(); 7565 DeclarationName Name 7566 = Context.DeclarationNames.getCXXConstructorName(ClassType); 7567 DeclarationNameInfo NameInfo(Name, ClassLoc); 7568 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 7569 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0, 7570 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 7571 Constexpr); 7572 DefaultCon->setAccess(AS_public); 7573 DefaultCon->setDefaulted(); 7574 DefaultCon->setImplicit(); 7575 7576 // Build an exception specification pointing back at this constructor. 7577 FunctionProtoType::ExtProtoInfo EPI; 7578 EPI.ExceptionSpecType = EST_Unevaluated; 7579 EPI.ExceptionSpecDecl = DefaultCon; 7580 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, 7581 ArrayRef<QualType>(), 7582 EPI)); 7583 7584 // We don't need to use SpecialMemberIsTrivial here; triviality for default 7585 // constructors is easy to compute. 7586 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 7587 7588 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 7589 SetDeclDeleted(DefaultCon, ClassLoc); 7590 7591 // Note that we have declared this constructor. 7592 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 7593 7594 if (Scope *S = getScopeForContext(ClassDecl)) 7595 PushOnScopeChains(DefaultCon, S, false); 7596 ClassDecl->addDecl(DefaultCon); 7597 7598 return DefaultCon; 7599} 7600 7601void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 7602 CXXConstructorDecl *Constructor) { 7603 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 7604 !Constructor->doesThisDeclarationHaveABody() && 7605 !Constructor->isDeleted()) && 7606 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 7607 7608 CXXRecordDecl *ClassDecl = Constructor->getParent(); 7609 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 7610 7611 SynthesizedFunctionScope Scope(*this, Constructor); 7612 DiagnosticErrorTrap Trap(Diags); 7613 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 7614 Trap.hasErrorOccurred()) { 7615 Diag(CurrentLocation, diag::note_member_synthesized_at) 7616 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl); 7617 Constructor->setInvalidDecl(); 7618 return; 7619 } 7620 7621 SourceLocation Loc = Constructor->getLocation(); 7622 Constructor->setBody(new (Context) CompoundStmt(Loc)); 7623 7624 Constructor->setUsed(); 7625 MarkVTableUsed(CurrentLocation, ClassDecl); 7626 7627 if (ASTMutationListener *L = getASTMutationListener()) { 7628 L->CompletedImplicitDefinition(Constructor); 7629 } 7630} 7631 7632void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 7633 // Check that any explicitly-defaulted methods have exception specifications 7634 // compatible with their implicit exception specifications. 7635 CheckDelayedExplicitlyDefaultedMemberExceptionSpecs(); 7636} 7637 7638void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) { 7639 // We start with an initial pass over the base classes to collect those that 7640 // inherit constructors from. If there are none, we can forgo all further 7641 // processing. 7642 typedef SmallVector<const RecordType *, 4> BasesVector; 7643 BasesVector BasesToInheritFrom; 7644 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(), 7645 BaseE = ClassDecl->bases_end(); 7646 BaseIt != BaseE; ++BaseIt) { 7647 if (BaseIt->getInheritConstructors()) { 7648 QualType Base = BaseIt->getType(); 7649 if (Base->isDependentType()) { 7650 // If we inherit constructors from anything that is dependent, just 7651 // abort processing altogether. We'll get another chance for the 7652 // instantiations. 7653 // FIXME: We need to ensure that any call to a constructor of this class 7654 // is considered instantiation-dependent in this case. 7655 return; 7656 } 7657 BasesToInheritFrom.push_back(Base->castAs<RecordType>()); 7658 } 7659 } 7660 if (BasesToInheritFrom.empty()) 7661 return; 7662 7663 // FIXME: Constructor templates. 7664 7665 // Now collect the constructors that we already have in the current class. 7666 // Those take precedence over inherited constructors. 7667 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...] 7668 // unless there is a user-declared constructor with the same signature in 7669 // the class where the using-declaration appears. 7670 llvm::SmallSet<const Type *, 8> ExistingConstructors; 7671 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(), 7672 CtorE = ClassDecl->ctor_end(); 7673 CtorIt != CtorE; ++CtorIt) 7674 ExistingConstructors.insert( 7675 Context.getCanonicalType(CtorIt->getType()).getTypePtr()); 7676 7677 DeclarationName CreatedCtorName = 7678 Context.DeclarationNames.getCXXConstructorName( 7679 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified()); 7680 7681 // Now comes the true work. 7682 // First, we keep a map from constructor types to the base that introduced 7683 // them. Needed for finding conflicting constructors. We also keep the 7684 // actually inserted declarations in there, for pretty diagnostics. 7685 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo; 7686 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap; 7687 ConstructorToSourceMap InheritedConstructors; 7688 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(), 7689 BaseE = BasesToInheritFrom.end(); 7690 BaseIt != BaseE; ++BaseIt) { 7691 const RecordType *Base = *BaseIt; 7692 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified(); 7693 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl()); 7694 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(), 7695 CtorE = BaseDecl->ctor_end(); 7696 CtorIt != CtorE; ++CtorIt) { 7697 // Find the using declaration for inheriting this base's constructors. 7698 // FIXME: Don't perform name lookup just to obtain a source location! 7699 DeclarationName Name = 7700 Context.DeclarationNames.getCXXConstructorName(CanonicalBase); 7701 LookupResult Result(*this, Name, SourceLocation(), LookupUsingDeclName); 7702 LookupQualifiedName(Result, CurContext); 7703 UsingDecl *UD = Result.getAsSingle<UsingDecl>(); 7704 SourceLocation UsingLoc = UD ? UD->getLocation() : 7705 ClassDecl->getLocation(); 7706 7707 // C++11 [class.inhctor]p1: 7708 // The candidate set of inherited constructors from the class X named in 7709 // the using-declaration consists of actual constructors and notional 7710 // constructors that result from the transformation of defaulted 7711 // parameters as follows: 7712 // - all non-template constructors of X, and 7713 // - for each non-template constructor of X that has at least one 7714 // parameter with a default argument, the set of constructors that 7715 // results from omitting any ellipsis parameter specification and 7716 // successively omitting parameters with a default argument from the 7717 // end of the parameter-type-list, and 7718 // FIXME: ...also constructor templates. 7719 CXXConstructorDecl *BaseCtor = *CtorIt; 7720 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor(); 7721 const FunctionProtoType *BaseCtorType = 7722 BaseCtor->getType()->getAs<FunctionProtoType>(); 7723 7724 // Determine whether this would be a copy or move constructor for the 7725 // derived class. 7726 if (BaseCtorType->getNumArgs() >= 1 && 7727 BaseCtorType->getArgType(0)->isReferenceType() && 7728 Context.hasSameUnqualifiedType( 7729 BaseCtorType->getArgType(0)->getPointeeType(), 7730 Context.getTagDeclType(ClassDecl))) 7731 CanBeCopyOrMove = true; 7732 7733 ArrayRef<QualType> ArgTypes(BaseCtorType->getArgTypes()); 7734 FunctionProtoType::ExtProtoInfo EPI = BaseCtorType->getExtProtoInfo(); 7735 // Core issue (no number yet): the ellipsis is always discarded. 7736 if (EPI.Variadic) { 7737 Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis); 7738 Diag(BaseCtor->getLocation(), 7739 diag::note_using_decl_constructor_ellipsis); 7740 EPI.Variadic = false; 7741 } 7742 7743 for (unsigned Params = BaseCtor->getMinRequiredArguments(), 7744 MaxParams = BaseCtor->getNumParams(); 7745 Params <= MaxParams; ++Params) { 7746 // Skip default constructors. They're never inherited. 7747 if (Params == 0) 7748 continue; 7749 7750 // Skip copy and move constructors for both base and derived class 7751 // for the same reason. 7752 if (CanBeCopyOrMove && Params == 1) 7753 continue; 7754 7755 // Build up a function type for this particular constructor. 7756 QualType NewCtorType = 7757 Context.getFunctionType(Context.VoidTy, ArgTypes.slice(0, Params), 7758 EPI); 7759 const Type *CanonicalNewCtorType = 7760 Context.getCanonicalType(NewCtorType).getTypePtr(); 7761 7762 // C++11 [class.inhctor]p3: 7763 // ... a constructor is implicitly declared with the same constructor 7764 // characteristics unless there is a user-declared constructor with 7765 // the same signature in the class where the using-declaration appears 7766 if (ExistingConstructors.count(CanonicalNewCtorType)) 7767 continue; 7768 7769 // C++11 [class.inhctor]p7: 7770 // If two using-declarations declare inheriting constructors with the 7771 // same signature, the program is ill-formed 7772 std::pair<ConstructorToSourceMap::iterator, bool> result = 7773 InheritedConstructors.insert(std::make_pair( 7774 CanonicalNewCtorType, 7775 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0))); 7776 if (!result.second) { 7777 // Already in the map. If it came from a different class, that's an 7778 // error. Not if it's from the same. 7779 CanQualType PreviousBase = result.first->second.first; 7780 if (CanonicalBase != PreviousBase) { 7781 const CXXConstructorDecl *PrevCtor = result.first->second.second; 7782 const CXXConstructorDecl *PrevBaseCtor = 7783 PrevCtor->getInheritedConstructor(); 7784 assert(PrevBaseCtor && "Conflicting constructor was not inherited"); 7785 7786 Diag(UsingLoc, diag::err_using_decl_constructor_conflict); 7787 Diag(BaseCtor->getLocation(), 7788 diag::note_using_decl_constructor_conflict_current_ctor); 7789 Diag(PrevBaseCtor->getLocation(), 7790 diag::note_using_decl_constructor_conflict_previous_ctor); 7791 Diag(PrevCtor->getLocation(), 7792 diag::note_using_decl_constructor_conflict_previous_using); 7793 } else { 7794 // Core issue (no number): if the same inheriting constructor is 7795 // produced by multiple base class constructors from the same base 7796 // class, the inheriting constructor is defined as deleted. 7797 SetDeclDeleted(result.first->second.second, UsingLoc); 7798 } 7799 continue; 7800 } 7801 7802 // OK, we're there, now add the constructor. 7803 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc); 7804 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create( 7805 Context, ClassDecl, UsingLoc, DNI, NewCtorType, 7806 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true, 7807 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr()); 7808 NewCtor->setAccess(BaseCtor->getAccess()); 7809 7810 // Build an unevaluated exception specification for this constructor. 7811 EPI.ExceptionSpecType = EST_Unevaluated; 7812 EPI.ExceptionSpecDecl = NewCtor; 7813 NewCtor->setType(Context.getFunctionType(Context.VoidTy, 7814 ArgTypes.slice(0, Params), 7815 EPI)); 7816 7817 // Build up the parameter decls and add them. 7818 SmallVector<ParmVarDecl *, 16> ParamDecls; 7819 for (unsigned i = 0; i < Params; ++i) { 7820 ParmVarDecl *PD = ParmVarDecl::Create(Context, NewCtor, 7821 UsingLoc, UsingLoc, 7822 /*IdentifierInfo=*/0, 7823 BaseCtorType->getArgType(i), 7824 /*TInfo=*/0, SC_None, 7825 /*DefaultArg=*/0); 7826 PD->setScopeInfo(0, i); 7827 PD->setImplicit(); 7828 ParamDecls.push_back(PD); 7829 } 7830 NewCtor->setParams(ParamDecls); 7831 NewCtor->setInheritedConstructor(BaseCtor); 7832 if (BaseCtor->isDeleted()) 7833 SetDeclDeleted(NewCtor, UsingLoc); 7834 7835 ClassDecl->addDecl(NewCtor); 7836 result.first->second.second = NewCtor; 7837 } 7838 } 7839 } 7840} 7841 7842void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 7843 CXXConstructorDecl *Constructor) { 7844 CXXRecordDecl *ClassDecl = Constructor->getParent(); 7845 assert(Constructor->getInheritedConstructor() && 7846 !Constructor->doesThisDeclarationHaveABody() && 7847 !Constructor->isDeleted()); 7848 7849 SynthesizedFunctionScope Scope(*this, Constructor); 7850 DiagnosticErrorTrap Trap(Diags); 7851 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 7852 Trap.hasErrorOccurred()) { 7853 Diag(CurrentLocation, diag::note_inhctor_synthesized_at) 7854 << Context.getTagDeclType(ClassDecl); 7855 Constructor->setInvalidDecl(); 7856 return; 7857 } 7858 7859 SourceLocation Loc = Constructor->getLocation(); 7860 Constructor->setBody(new (Context) CompoundStmt(Loc)); 7861 7862 Constructor->setUsed(); 7863 MarkVTableUsed(CurrentLocation, ClassDecl); 7864 7865 if (ASTMutationListener *L = getASTMutationListener()) { 7866 L->CompletedImplicitDefinition(Constructor); 7867 } 7868} 7869 7870 7871Sema::ImplicitExceptionSpecification 7872Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) { 7873 CXXRecordDecl *ClassDecl = MD->getParent(); 7874 7875 // C++ [except.spec]p14: 7876 // An implicitly declared special member function (Clause 12) shall have 7877 // an exception-specification. 7878 ImplicitExceptionSpecification ExceptSpec(*this); 7879 if (ClassDecl->isInvalidDecl()) 7880 return ExceptSpec; 7881 7882 // Direct base-class destructors. 7883 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 7884 BEnd = ClassDecl->bases_end(); 7885 B != BEnd; ++B) { 7886 if (B->isVirtual()) // Handled below. 7887 continue; 7888 7889 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) 7890 ExceptSpec.CalledDecl(B->getLocStart(), 7891 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 7892 } 7893 7894 // Virtual base-class destructors. 7895 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 7896 BEnd = ClassDecl->vbases_end(); 7897 B != BEnd; ++B) { 7898 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) 7899 ExceptSpec.CalledDecl(B->getLocStart(), 7900 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 7901 } 7902 7903 // Field destructors. 7904 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 7905 FEnd = ClassDecl->field_end(); 7906 F != FEnd; ++F) { 7907 if (const RecordType *RecordTy 7908 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) 7909 ExceptSpec.CalledDecl(F->getLocation(), 7910 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl()))); 7911 } 7912 7913 return ExceptSpec; 7914} 7915 7916CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 7917 // C++ [class.dtor]p2: 7918 // If a class has no user-declared destructor, a destructor is 7919 // declared implicitly. An implicitly-declared destructor is an 7920 // inline public member of its class. 7921 assert(ClassDecl->needsImplicitDestructor()); 7922 7923 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 7924 if (DSM.isAlreadyBeingDeclared()) 7925 return 0; 7926 7927 // Create the actual destructor declaration. 7928 CanQualType ClassType 7929 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 7930 SourceLocation ClassLoc = ClassDecl->getLocation(); 7931 DeclarationName Name 7932 = Context.DeclarationNames.getCXXDestructorName(ClassType); 7933 DeclarationNameInfo NameInfo(Name, ClassLoc); 7934 CXXDestructorDecl *Destructor 7935 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 7936 QualType(), 0, /*isInline=*/true, 7937 /*isImplicitlyDeclared=*/true); 7938 Destructor->setAccess(AS_public); 7939 Destructor->setDefaulted(); 7940 Destructor->setImplicit(); 7941 7942 // Build an exception specification pointing back at this destructor. 7943 FunctionProtoType::ExtProtoInfo EPI; 7944 EPI.ExceptionSpecType = EST_Unevaluated; 7945 EPI.ExceptionSpecDecl = Destructor; 7946 Destructor->setType(Context.getFunctionType(Context.VoidTy, 7947 ArrayRef<QualType>(), 7948 EPI)); 7949 7950 AddOverriddenMethods(ClassDecl, Destructor); 7951 7952 // We don't need to use SpecialMemberIsTrivial here; triviality for 7953 // destructors is easy to compute. 7954 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 7955 7956 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 7957 SetDeclDeleted(Destructor, ClassLoc); 7958 7959 // Note that we have declared this destructor. 7960 ++ASTContext::NumImplicitDestructorsDeclared; 7961 7962 // Introduce this destructor into its scope. 7963 if (Scope *S = getScopeForContext(ClassDecl)) 7964 PushOnScopeChains(Destructor, S, false); 7965 ClassDecl->addDecl(Destructor); 7966 7967 return Destructor; 7968} 7969 7970void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 7971 CXXDestructorDecl *Destructor) { 7972 assert((Destructor->isDefaulted() && 7973 !Destructor->doesThisDeclarationHaveABody() && 7974 !Destructor->isDeleted()) && 7975 "DefineImplicitDestructor - call it for implicit default dtor"); 7976 CXXRecordDecl *ClassDecl = Destructor->getParent(); 7977 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 7978 7979 if (Destructor->isInvalidDecl()) 7980 return; 7981 7982 SynthesizedFunctionScope Scope(*this, Destructor); 7983 7984 DiagnosticErrorTrap Trap(Diags); 7985 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 7986 Destructor->getParent()); 7987 7988 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) { 7989 Diag(CurrentLocation, diag::note_member_synthesized_at) 7990 << CXXDestructor << Context.getTagDeclType(ClassDecl); 7991 7992 Destructor->setInvalidDecl(); 7993 return; 7994 } 7995 7996 SourceLocation Loc = Destructor->getLocation(); 7997 Destructor->setBody(new (Context) CompoundStmt(Loc)); 7998 Destructor->setImplicitlyDefined(true); 7999 Destructor->setUsed(); 8000 MarkVTableUsed(CurrentLocation, ClassDecl); 8001 8002 if (ASTMutationListener *L = getASTMutationListener()) { 8003 L->CompletedImplicitDefinition(Destructor); 8004 } 8005} 8006 8007/// \brief Perform any semantic analysis which needs to be delayed until all 8008/// pending class member declarations have been parsed. 8009void Sema::ActOnFinishCXXMemberDecls() { 8010 // If the context is an invalid C++ class, just suppress these checks. 8011 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 8012 if (Record->isInvalidDecl()) { 8013 DelayedDestructorExceptionSpecChecks.clear(); 8014 return; 8015 } 8016 } 8017 8018 // Perform any deferred checking of exception specifications for virtual 8019 // destructors. 8020 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size(); 8021 i != e; ++i) { 8022 const CXXDestructorDecl *Dtor = 8023 DelayedDestructorExceptionSpecChecks[i].first; 8024 assert(!Dtor->getParent()->isDependentType() && 8025 "Should not ever add destructors of templates into the list."); 8026 CheckOverridingFunctionExceptionSpec(Dtor, 8027 DelayedDestructorExceptionSpecChecks[i].second); 8028 } 8029 DelayedDestructorExceptionSpecChecks.clear(); 8030} 8031 8032void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 8033 CXXDestructorDecl *Destructor) { 8034 assert(getLangOpts().CPlusPlus11 && 8035 "adjusting dtor exception specs was introduced in c++11"); 8036 8037 // C++11 [class.dtor]p3: 8038 // A declaration of a destructor that does not have an exception- 8039 // specification is implicitly considered to have the same exception- 8040 // specification as an implicit declaration. 8041 const FunctionProtoType *DtorType = Destructor->getType()-> 8042 getAs<FunctionProtoType>(); 8043 if (DtorType->hasExceptionSpec()) 8044 return; 8045 8046 // Replace the destructor's type, building off the existing one. Fortunately, 8047 // the only thing of interest in the destructor type is its extended info. 8048 // The return and arguments are fixed. 8049 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 8050 EPI.ExceptionSpecType = EST_Unevaluated; 8051 EPI.ExceptionSpecDecl = Destructor; 8052 Destructor->setType(Context.getFunctionType(Context.VoidTy, 8053 ArrayRef<QualType>(), 8054 EPI)); 8055 8056 // FIXME: If the destructor has a body that could throw, and the newly created 8057 // spec doesn't allow exceptions, we should emit a warning, because this 8058 // change in behavior can break conforming C++03 programs at runtime. 8059 // However, we don't have a body or an exception specification yet, so it 8060 // needs to be done somewhere else. 8061} 8062 8063/// When generating a defaulted copy or move assignment operator, if a field 8064/// should be copied with __builtin_memcpy rather than via explicit assignments, 8065/// do so. This optimization only applies for arrays of scalars, and for arrays 8066/// of class type where the selected copy/move-assignment operator is trivial. 8067static StmtResult 8068buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 8069 Expr *To, Expr *From) { 8070 // Compute the size of the memory buffer to be copied. 8071 QualType SizeType = S.Context.getSizeType(); 8072 llvm::APInt Size(S.Context.getTypeSize(SizeType), 8073 S.Context.getTypeSizeInChars(T).getQuantity()); 8074 8075 // Take the address of the field references for "from" and "to". We 8076 // directly construct UnaryOperators here because semantic analysis 8077 // does not permit us to take the address of an xvalue. 8078 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 8079 S.Context.getPointerType(From->getType()), 8080 VK_RValue, OK_Ordinary, Loc); 8081 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 8082 S.Context.getPointerType(To->getType()), 8083 VK_RValue, OK_Ordinary, Loc); 8084 8085 const Type *E = T->getBaseElementTypeUnsafe(); 8086 bool NeedsCollectableMemCpy = 8087 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 8088 8089 // Create a reference to the __builtin_objc_memmove_collectable function 8090 StringRef MemCpyName = NeedsCollectableMemCpy ? 8091 "__builtin_objc_memmove_collectable" : 8092 "__builtin_memcpy"; 8093 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 8094 Sema::LookupOrdinaryName); 8095 S.LookupName(R, S.TUScope, true); 8096 8097 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 8098 if (!MemCpy) 8099 // Something went horribly wrong earlier, and we will have complained 8100 // about it. 8101 return StmtError(); 8102 8103 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 8104 VK_RValue, Loc, 0); 8105 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 8106 8107 Expr *CallArgs[] = { 8108 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 8109 }; 8110 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(), 8111 Loc, CallArgs, Loc); 8112 8113 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 8114 return S.Owned(Call.takeAs<Stmt>()); 8115} 8116 8117/// \brief Builds a statement that copies/moves the given entity from \p From to 8118/// \c To. 8119/// 8120/// This routine is used to copy/move the members of a class with an 8121/// implicitly-declared copy/move assignment operator. When the entities being 8122/// copied are arrays, this routine builds for loops to copy them. 8123/// 8124/// \param S The Sema object used for type-checking. 8125/// 8126/// \param Loc The location where the implicit copy/move is being generated. 8127/// 8128/// \param T The type of the expressions being copied/moved. Both expressions 8129/// must have this type. 8130/// 8131/// \param To The expression we are copying/moving to. 8132/// 8133/// \param From The expression we are copying/moving from. 8134/// 8135/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 8136/// Otherwise, it's a non-static member subobject. 8137/// 8138/// \param Copying Whether we're copying or moving. 8139/// 8140/// \param Depth Internal parameter recording the depth of the recursion. 8141/// 8142/// \returns A statement or a loop that copies the expressions, or StmtResult(0) 8143/// if a memcpy should be used instead. 8144static StmtResult 8145buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 8146 Expr *To, Expr *From, 8147 bool CopyingBaseSubobject, bool Copying, 8148 unsigned Depth = 0) { 8149 // C++11 [class.copy]p28: 8150 // Each subobject is assigned in the manner appropriate to its type: 8151 // 8152 // - if the subobject is of class type, as if by a call to operator= with 8153 // the subobject as the object expression and the corresponding 8154 // subobject of x as a single function argument (as if by explicit 8155 // qualification; that is, ignoring any possible virtual overriding 8156 // functions in more derived classes); 8157 // 8158 // C++03 [class.copy]p13: 8159 // - if the subobject is of class type, the copy assignment operator for 8160 // the class is used (as if by explicit qualification; that is, 8161 // ignoring any possible virtual overriding functions in more derived 8162 // classes); 8163 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 8164 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8165 8166 // Look for operator=. 8167 DeclarationName Name 8168 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 8169 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 8170 S.LookupQualifiedName(OpLookup, ClassDecl, false); 8171 8172 // Prior to C++11, filter out any result that isn't a copy/move-assignment 8173 // operator. 8174 if (!S.getLangOpts().CPlusPlus11) { 8175 LookupResult::Filter F = OpLookup.makeFilter(); 8176 while (F.hasNext()) { 8177 NamedDecl *D = F.next(); 8178 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 8179 if (Method->isCopyAssignmentOperator() || 8180 (!Copying && Method->isMoveAssignmentOperator())) 8181 continue; 8182 8183 F.erase(); 8184 } 8185 F.done(); 8186 } 8187 8188 // Suppress the protected check (C++ [class.protected]) for each of the 8189 // assignment operators we found. This strange dance is required when 8190 // we're assigning via a base classes's copy-assignment operator. To 8191 // ensure that we're getting the right base class subobject (without 8192 // ambiguities), we need to cast "this" to that subobject type; to 8193 // ensure that we don't go through the virtual call mechanism, we need 8194 // to qualify the operator= name with the base class (see below). However, 8195 // this means that if the base class has a protected copy assignment 8196 // operator, the protected member access check will fail. So, we 8197 // rewrite "protected" access to "public" access in this case, since we 8198 // know by construction that we're calling from a derived class. 8199 if (CopyingBaseSubobject) { 8200 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 8201 L != LEnd; ++L) { 8202 if (L.getAccess() == AS_protected) 8203 L.setAccess(AS_public); 8204 } 8205 } 8206 8207 // Create the nested-name-specifier that will be used to qualify the 8208 // reference to operator=; this is required to suppress the virtual 8209 // call mechanism. 8210 CXXScopeSpec SS; 8211 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 8212 SS.MakeTrivial(S.Context, 8213 NestedNameSpecifier::Create(S.Context, 0, false, 8214 CanonicalT), 8215 Loc); 8216 8217 // Create the reference to operator=. 8218 ExprResult OpEqualRef 8219 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS, 8220 /*TemplateKWLoc=*/SourceLocation(), 8221 /*FirstQualifierInScope=*/0, 8222 OpLookup, 8223 /*TemplateArgs=*/0, 8224 /*SuppressQualifierCheck=*/true); 8225 if (OpEqualRef.isInvalid()) 8226 return StmtError(); 8227 8228 // Build the call to the assignment operator. 8229 8230 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0, 8231 OpEqualRef.takeAs<Expr>(), 8232 Loc, &From, 1, Loc); 8233 if (Call.isInvalid()) 8234 return StmtError(); 8235 8236 // If we built a call to a trivial 'operator=' while copying an array, 8237 // bail out. We'll replace the whole shebang with a memcpy. 8238 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 8239 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 8240 return StmtResult((Stmt*)0); 8241 8242 // Convert to an expression-statement, and clean up any produced 8243 // temporaries. 8244 return S.ActOnExprStmt(Call); 8245 } 8246 8247 // - if the subobject is of scalar type, the built-in assignment 8248 // operator is used. 8249 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 8250 if (!ArrayTy) { 8251 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From); 8252 if (Assignment.isInvalid()) 8253 return StmtError(); 8254 return S.ActOnExprStmt(Assignment); 8255 } 8256 8257 // - if the subobject is an array, each element is assigned, in the 8258 // manner appropriate to the element type; 8259 8260 // Construct a loop over the array bounds, e.g., 8261 // 8262 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 8263 // 8264 // that will copy each of the array elements. 8265 QualType SizeType = S.Context.getSizeType(); 8266 8267 // Create the iteration variable. 8268 IdentifierInfo *IterationVarName = 0; 8269 { 8270 SmallString<8> Str; 8271 llvm::raw_svector_ostream OS(Str); 8272 OS << "__i" << Depth; 8273 IterationVarName = &S.Context.Idents.get(OS.str()); 8274 } 8275 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 8276 IterationVarName, SizeType, 8277 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 8278 SC_None); 8279 8280 // Initialize the iteration variable to zero. 8281 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 8282 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 8283 8284 // Create a reference to the iteration variable; we'll use this several 8285 // times throughout. 8286 Expr *IterationVarRef 8287 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take(); 8288 assert(IterationVarRef && "Reference to invented variable cannot fail!"); 8289 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take(); 8290 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!"); 8291 8292 // Create the DeclStmt that holds the iteration variable. 8293 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 8294 8295 // Subscript the "from" and "to" expressions with the iteration variable. 8296 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc, 8297 IterationVarRefRVal, 8298 Loc)); 8299 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc, 8300 IterationVarRefRVal, 8301 Loc)); 8302 if (!Copying) // Cast to rvalue 8303 From = CastForMoving(S, From); 8304 8305 // Build the copy/move for an individual element of the array. 8306 StmtResult Copy = 8307 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 8308 To, From, CopyingBaseSubobject, 8309 Copying, Depth + 1); 8310 // Bail out if copying fails or if we determined that we should use memcpy. 8311 if (Copy.isInvalid() || !Copy.get()) 8312 return Copy; 8313 8314 // Create the comparison against the array bound. 8315 llvm::APInt Upper 8316 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 8317 Expr *Comparison 8318 = new (S.Context) BinaryOperator(IterationVarRefRVal, 8319 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 8320 BO_NE, S.Context.BoolTy, 8321 VK_RValue, OK_Ordinary, Loc, false); 8322 8323 // Create the pre-increment of the iteration variable. 8324 Expr *Increment 8325 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType, 8326 VK_LValue, OK_Ordinary, Loc); 8327 8328 // Construct the loop that copies all elements of this array. 8329 return S.ActOnForStmt(Loc, Loc, InitStmt, 8330 S.MakeFullExpr(Comparison), 8331 0, S.MakeFullDiscardedValueExpr(Increment), 8332 Loc, Copy.take()); 8333} 8334 8335static StmtResult 8336buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 8337 Expr *To, Expr *From, 8338 bool CopyingBaseSubobject, bool Copying) { 8339 // Maybe we should use a memcpy? 8340 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 8341 T.isTriviallyCopyableType(S.Context)) 8342 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 8343 8344 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 8345 CopyingBaseSubobject, 8346 Copying, 0)); 8347 8348 // If we ended up picking a trivial assignment operator for an array of a 8349 // non-trivially-copyable class type, just emit a memcpy. 8350 if (!Result.isInvalid() && !Result.get()) 8351 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 8352 8353 return Result; 8354} 8355 8356Sema::ImplicitExceptionSpecification 8357Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) { 8358 CXXRecordDecl *ClassDecl = MD->getParent(); 8359 8360 ImplicitExceptionSpecification ExceptSpec(*this); 8361 if (ClassDecl->isInvalidDecl()) 8362 return ExceptSpec; 8363 8364 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 8365 assert(T->getNumArgs() == 1 && "not a copy assignment op"); 8366 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers(); 8367 8368 // C++ [except.spec]p14: 8369 // An implicitly declared special member function (Clause 12) shall have an 8370 // exception-specification. [...] 8371 8372 // It is unspecified whether or not an implicit copy assignment operator 8373 // attempts to deduplicate calls to assignment operators of virtual bases are 8374 // made. As such, this exception specification is effectively unspecified. 8375 // Based on a similar decision made for constness in C++0x, we're erring on 8376 // the side of assuming such calls to be made regardless of whether they 8377 // actually happen. 8378 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 8379 BaseEnd = ClassDecl->bases_end(); 8380 Base != BaseEnd; ++Base) { 8381 if (Base->isVirtual()) 8382 continue; 8383 8384 CXXRecordDecl *BaseClassDecl 8385 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8386 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 8387 ArgQuals, false, 0)) 8388 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign); 8389 } 8390 8391 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 8392 BaseEnd = ClassDecl->vbases_end(); 8393 Base != BaseEnd; ++Base) { 8394 CXXRecordDecl *BaseClassDecl 8395 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8396 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 8397 ArgQuals, false, 0)) 8398 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign); 8399 } 8400 8401 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8402 FieldEnd = ClassDecl->field_end(); 8403 Field != FieldEnd; 8404 ++Field) { 8405 QualType FieldType = Context.getBaseElementType(Field->getType()); 8406 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 8407 if (CXXMethodDecl *CopyAssign = 8408 LookupCopyingAssignment(FieldClassDecl, 8409 ArgQuals | FieldType.getCVRQualifiers(), 8410 false, 0)) 8411 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign); 8412 } 8413 } 8414 8415 return ExceptSpec; 8416} 8417 8418CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 8419 // Note: The following rules are largely analoguous to the copy 8420 // constructor rules. Note that virtual bases are not taken into account 8421 // for determining the argument type of the operator. Note also that 8422 // operators taking an object instead of a reference are allowed. 8423 assert(ClassDecl->needsImplicitCopyAssignment()); 8424 8425 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 8426 if (DSM.isAlreadyBeingDeclared()) 8427 return 0; 8428 8429 QualType ArgType = Context.getTypeDeclType(ClassDecl); 8430 QualType RetType = Context.getLValueReferenceType(ArgType); 8431 if (ClassDecl->implicitCopyAssignmentHasConstParam()) 8432 ArgType = ArgType.withConst(); 8433 ArgType = Context.getLValueReferenceType(ArgType); 8434 8435 // An implicitly-declared copy assignment operator is an inline public 8436 // member of its class. 8437 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 8438 SourceLocation ClassLoc = ClassDecl->getLocation(); 8439 DeclarationNameInfo NameInfo(Name, ClassLoc); 8440 CXXMethodDecl *CopyAssignment 8441 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 8442 /*TInfo=*/0, 8443 /*StorageClass=*/SC_None, 8444 /*isInline=*/true, /*isConstexpr=*/false, 8445 SourceLocation()); 8446 CopyAssignment->setAccess(AS_public); 8447 CopyAssignment->setDefaulted(); 8448 CopyAssignment->setImplicit(); 8449 8450 // Build an exception specification pointing back at this member. 8451 FunctionProtoType::ExtProtoInfo EPI; 8452 EPI.ExceptionSpecType = EST_Unevaluated; 8453 EPI.ExceptionSpecDecl = CopyAssignment; 8454 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 8455 8456 // Add the parameter to the operator. 8457 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 8458 ClassLoc, ClassLoc, /*Id=*/0, 8459 ArgType, /*TInfo=*/0, 8460 SC_None, 0); 8461 CopyAssignment->setParams(FromParam); 8462 8463 AddOverriddenMethods(ClassDecl, CopyAssignment); 8464 8465 CopyAssignment->setTrivial( 8466 ClassDecl->needsOverloadResolutionForCopyAssignment() 8467 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 8468 : ClassDecl->hasTrivialCopyAssignment()); 8469 8470 // C++0x [class.copy]p19: 8471 // .... If the class definition does not explicitly declare a copy 8472 // assignment operator, there is no user-declared move constructor, and 8473 // there is no user-declared move assignment operator, a copy assignment 8474 // operator is implicitly declared as defaulted. 8475 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 8476 SetDeclDeleted(CopyAssignment, ClassLoc); 8477 8478 // Note that we have added this copy-assignment operator. 8479 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 8480 8481 if (Scope *S = getScopeForContext(ClassDecl)) 8482 PushOnScopeChains(CopyAssignment, S, false); 8483 ClassDecl->addDecl(CopyAssignment); 8484 8485 return CopyAssignment; 8486} 8487 8488void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 8489 CXXMethodDecl *CopyAssignOperator) { 8490 assert((CopyAssignOperator->isDefaulted() && 8491 CopyAssignOperator->isOverloadedOperator() && 8492 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 8493 !CopyAssignOperator->doesThisDeclarationHaveABody() && 8494 !CopyAssignOperator->isDeleted()) && 8495 "DefineImplicitCopyAssignment called for wrong function"); 8496 8497 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 8498 8499 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) { 8500 CopyAssignOperator->setInvalidDecl(); 8501 return; 8502 } 8503 8504 CopyAssignOperator->setUsed(); 8505 8506 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 8507 DiagnosticErrorTrap Trap(Diags); 8508 8509 // C++0x [class.copy]p30: 8510 // The implicitly-defined or explicitly-defaulted copy assignment operator 8511 // for a non-union class X performs memberwise copy assignment of its 8512 // subobjects. The direct base classes of X are assigned first, in the 8513 // order of their declaration in the base-specifier-list, and then the 8514 // immediate non-static data members of X are assigned, in the order in 8515 // which they were declared in the class definition. 8516 8517 // The statements that form the synthesized function body. 8518 SmallVector<Stmt*, 8> Statements; 8519 8520 // The parameter for the "other" object, which we are copying from. 8521 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 8522 Qualifiers OtherQuals = Other->getType().getQualifiers(); 8523 QualType OtherRefType = Other->getType(); 8524 if (const LValueReferenceType *OtherRef 8525 = OtherRefType->getAs<LValueReferenceType>()) { 8526 OtherRefType = OtherRef->getPointeeType(); 8527 OtherQuals = OtherRefType.getQualifiers(); 8528 } 8529 8530 // Our location for everything implicitly-generated. 8531 SourceLocation Loc = CopyAssignOperator->getLocation(); 8532 8533 // Construct a reference to the "other" object. We'll be using this 8534 // throughout the generated ASTs. 8535 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take(); 8536 assert(OtherRef && "Reference to parameter cannot fail!"); 8537 8538 // Construct the "this" pointer. We'll be using this throughout the generated 8539 // ASTs. 8540 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>(); 8541 assert(This && "Reference to this cannot fail!"); 8542 8543 // Assign base classes. 8544 bool Invalid = false; 8545 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 8546 E = ClassDecl->bases_end(); Base != E; ++Base) { 8547 // Form the assignment: 8548 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 8549 QualType BaseType = Base->getType().getUnqualifiedType(); 8550 if (!BaseType->isRecordType()) { 8551 Invalid = true; 8552 continue; 8553 } 8554 8555 CXXCastPath BasePath; 8556 BasePath.push_back(Base); 8557 8558 // Construct the "from" expression, which is an implicit cast to the 8559 // appropriately-qualified base type. 8560 Expr *From = OtherRef; 8561 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals), 8562 CK_UncheckedDerivedToBase, 8563 VK_LValue, &BasePath).take(); 8564 8565 // Dereference "this". 8566 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 8567 8568 // Implicitly cast "this" to the appropriately-qualified base type. 8569 To = ImpCastExprToType(To.take(), 8570 Context.getCVRQualifiedType(BaseType, 8571 CopyAssignOperator->getTypeQualifiers()), 8572 CK_UncheckedDerivedToBase, 8573 VK_LValue, &BasePath); 8574 8575 // Build the copy. 8576 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 8577 To.get(), From, 8578 /*CopyingBaseSubobject=*/true, 8579 /*Copying=*/true); 8580 if (Copy.isInvalid()) { 8581 Diag(CurrentLocation, diag::note_member_synthesized_at) 8582 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 8583 CopyAssignOperator->setInvalidDecl(); 8584 return; 8585 } 8586 8587 // Success! Record the copy. 8588 Statements.push_back(Copy.takeAs<Expr>()); 8589 } 8590 8591 // Assign non-static members. 8592 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8593 FieldEnd = ClassDecl->field_end(); 8594 Field != FieldEnd; ++Field) { 8595 if (Field->isUnnamedBitfield()) 8596 continue; 8597 8598 // Check for members of reference type; we can't copy those. 8599 if (Field->getType()->isReferenceType()) { 8600 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 8601 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 8602 Diag(Field->getLocation(), diag::note_declared_at); 8603 Diag(CurrentLocation, diag::note_member_synthesized_at) 8604 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 8605 Invalid = true; 8606 continue; 8607 } 8608 8609 // Check for members of const-qualified, non-class type. 8610 QualType BaseType = Context.getBaseElementType(Field->getType()); 8611 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 8612 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 8613 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 8614 Diag(Field->getLocation(), diag::note_declared_at); 8615 Diag(CurrentLocation, diag::note_member_synthesized_at) 8616 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 8617 Invalid = true; 8618 continue; 8619 } 8620 8621 // Suppress assigning zero-width bitfields. 8622 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 8623 continue; 8624 8625 QualType FieldType = Field->getType().getNonReferenceType(); 8626 if (FieldType->isIncompleteArrayType()) { 8627 assert(ClassDecl->hasFlexibleArrayMember() && 8628 "Incomplete array type is not valid"); 8629 continue; 8630 } 8631 8632 // Build references to the field in the object we're copying from and to. 8633 CXXScopeSpec SS; // Intentionally empty 8634 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 8635 LookupMemberName); 8636 MemberLookup.addDecl(*Field); 8637 MemberLookup.resolveKind(); 8638 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType, 8639 Loc, /*IsArrow=*/false, 8640 SS, SourceLocation(), 0, 8641 MemberLookup, 0); 8642 ExprResult To = BuildMemberReferenceExpr(This, This->getType(), 8643 Loc, /*IsArrow=*/true, 8644 SS, SourceLocation(), 0, 8645 MemberLookup, 0); 8646 assert(!From.isInvalid() && "Implicit field reference cannot fail"); 8647 assert(!To.isInvalid() && "Implicit field reference cannot fail"); 8648 8649 // Build the copy of this field. 8650 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 8651 To.get(), From.get(), 8652 /*CopyingBaseSubobject=*/false, 8653 /*Copying=*/true); 8654 if (Copy.isInvalid()) { 8655 Diag(CurrentLocation, diag::note_member_synthesized_at) 8656 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 8657 CopyAssignOperator->setInvalidDecl(); 8658 return; 8659 } 8660 8661 // Success! Record the copy. 8662 Statements.push_back(Copy.takeAs<Stmt>()); 8663 } 8664 8665 if (!Invalid) { 8666 // Add a "return *this;" 8667 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 8668 8669 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get()); 8670 if (Return.isInvalid()) 8671 Invalid = true; 8672 else { 8673 Statements.push_back(Return.takeAs<Stmt>()); 8674 8675 if (Trap.hasErrorOccurred()) { 8676 Diag(CurrentLocation, diag::note_member_synthesized_at) 8677 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 8678 Invalid = true; 8679 } 8680 } 8681 } 8682 8683 if (Invalid) { 8684 CopyAssignOperator->setInvalidDecl(); 8685 return; 8686 } 8687 8688 StmtResult Body; 8689 { 8690 CompoundScopeRAII CompoundScope(*this); 8691 Body = ActOnCompoundStmt(Loc, Loc, Statements, 8692 /*isStmtExpr=*/false); 8693 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 8694 } 8695 CopyAssignOperator->setBody(Body.takeAs<Stmt>()); 8696 8697 if (ASTMutationListener *L = getASTMutationListener()) { 8698 L->CompletedImplicitDefinition(CopyAssignOperator); 8699 } 8700} 8701 8702Sema::ImplicitExceptionSpecification 8703Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) { 8704 CXXRecordDecl *ClassDecl = MD->getParent(); 8705 8706 ImplicitExceptionSpecification ExceptSpec(*this); 8707 if (ClassDecl->isInvalidDecl()) 8708 return ExceptSpec; 8709 8710 // C++0x [except.spec]p14: 8711 // An implicitly declared special member function (Clause 12) shall have an 8712 // exception-specification. [...] 8713 8714 // It is unspecified whether or not an implicit move assignment operator 8715 // attempts to deduplicate calls to assignment operators of virtual bases are 8716 // made. As such, this exception specification is effectively unspecified. 8717 // Based on a similar decision made for constness in C++0x, we're erring on 8718 // the side of assuming such calls to be made regardless of whether they 8719 // actually happen. 8720 // Note that a move constructor is not implicitly declared when there are 8721 // virtual bases, but it can still be user-declared and explicitly defaulted. 8722 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 8723 BaseEnd = ClassDecl->bases_end(); 8724 Base != BaseEnd; ++Base) { 8725 if (Base->isVirtual()) 8726 continue; 8727 8728 CXXRecordDecl *BaseClassDecl 8729 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8730 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 8731 0, false, 0)) 8732 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign); 8733 } 8734 8735 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 8736 BaseEnd = ClassDecl->vbases_end(); 8737 Base != BaseEnd; ++Base) { 8738 CXXRecordDecl *BaseClassDecl 8739 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8740 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 8741 0, false, 0)) 8742 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign); 8743 } 8744 8745 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8746 FieldEnd = ClassDecl->field_end(); 8747 Field != FieldEnd; 8748 ++Field) { 8749 QualType FieldType = Context.getBaseElementType(Field->getType()); 8750 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 8751 if (CXXMethodDecl *MoveAssign = 8752 LookupMovingAssignment(FieldClassDecl, 8753 FieldType.getCVRQualifiers(), 8754 false, 0)) 8755 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign); 8756 } 8757 } 8758 8759 return ExceptSpec; 8760} 8761 8762/// Determine whether the class type has any direct or indirect virtual base 8763/// classes which have a non-trivial move assignment operator. 8764static bool 8765hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) { 8766 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 8767 BaseEnd = ClassDecl->vbases_end(); 8768 Base != BaseEnd; ++Base) { 8769 CXXRecordDecl *BaseClass = 8770 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8771 8772 // Try to declare the move assignment. If it would be deleted, then the 8773 // class does not have a non-trivial move assignment. 8774 if (BaseClass->needsImplicitMoveAssignment()) 8775 S.DeclareImplicitMoveAssignment(BaseClass); 8776 8777 if (BaseClass->hasNonTrivialMoveAssignment()) 8778 return true; 8779 } 8780 8781 return false; 8782} 8783 8784/// Determine whether the given type either has a move constructor or is 8785/// trivially copyable. 8786static bool 8787hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) { 8788 Type = S.Context.getBaseElementType(Type); 8789 8790 // FIXME: Technically, non-trivially-copyable non-class types, such as 8791 // reference types, are supposed to return false here, but that appears 8792 // to be a standard defect. 8793 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl(); 8794 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl()) 8795 return true; 8796 8797 if (Type.isTriviallyCopyableType(S.Context)) 8798 return true; 8799 8800 if (IsConstructor) { 8801 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to 8802 // give the right answer. 8803 if (ClassDecl->needsImplicitMoveConstructor()) 8804 S.DeclareImplicitMoveConstructor(ClassDecl); 8805 return ClassDecl->hasMoveConstructor(); 8806 } 8807 8808 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to 8809 // give the right answer. 8810 if (ClassDecl->needsImplicitMoveAssignment()) 8811 S.DeclareImplicitMoveAssignment(ClassDecl); 8812 return ClassDecl->hasMoveAssignment(); 8813} 8814 8815/// Determine whether all non-static data members and direct or virtual bases 8816/// of class \p ClassDecl have either a move operation, or are trivially 8817/// copyable. 8818static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl, 8819 bool IsConstructor) { 8820 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 8821 BaseEnd = ClassDecl->bases_end(); 8822 Base != BaseEnd; ++Base) { 8823 if (Base->isVirtual()) 8824 continue; 8825 8826 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor)) 8827 return false; 8828 } 8829 8830 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 8831 BaseEnd = ClassDecl->vbases_end(); 8832 Base != BaseEnd; ++Base) { 8833 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor)) 8834 return false; 8835 } 8836 8837 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8838 FieldEnd = ClassDecl->field_end(); 8839 Field != FieldEnd; ++Field) { 8840 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor)) 8841 return false; 8842 } 8843 8844 return true; 8845} 8846 8847CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 8848 // C++11 [class.copy]p20: 8849 // If the definition of a class X does not explicitly declare a move 8850 // assignment operator, one will be implicitly declared as defaulted 8851 // if and only if: 8852 // 8853 // - [first 4 bullets] 8854 assert(ClassDecl->needsImplicitMoveAssignment()); 8855 8856 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 8857 if (DSM.isAlreadyBeingDeclared()) 8858 return 0; 8859 8860 // [Checked after we build the declaration] 8861 // - the move assignment operator would not be implicitly defined as 8862 // deleted, 8863 8864 // [DR1402]: 8865 // - X has no direct or indirect virtual base class with a non-trivial 8866 // move assignment operator, and 8867 // - each of X's non-static data members and direct or virtual base classes 8868 // has a type that either has a move assignment operator or is trivially 8869 // copyable. 8870 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) || 8871 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) { 8872 ClassDecl->setFailedImplicitMoveAssignment(); 8873 return 0; 8874 } 8875 8876 // Note: The following rules are largely analoguous to the move 8877 // constructor rules. 8878 8879 QualType ArgType = Context.getTypeDeclType(ClassDecl); 8880 QualType RetType = Context.getLValueReferenceType(ArgType); 8881 ArgType = Context.getRValueReferenceType(ArgType); 8882 8883 // An implicitly-declared move assignment operator is an inline public 8884 // member of its class. 8885 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 8886 SourceLocation ClassLoc = ClassDecl->getLocation(); 8887 DeclarationNameInfo NameInfo(Name, ClassLoc); 8888 CXXMethodDecl *MoveAssignment 8889 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 8890 /*TInfo=*/0, 8891 /*StorageClass=*/SC_None, 8892 /*isInline=*/true, 8893 /*isConstexpr=*/false, 8894 SourceLocation()); 8895 MoveAssignment->setAccess(AS_public); 8896 MoveAssignment->setDefaulted(); 8897 MoveAssignment->setImplicit(); 8898 8899 // Build an exception specification pointing back at this member. 8900 FunctionProtoType::ExtProtoInfo EPI; 8901 EPI.ExceptionSpecType = EST_Unevaluated; 8902 EPI.ExceptionSpecDecl = MoveAssignment; 8903 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 8904 8905 // Add the parameter to the operator. 8906 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 8907 ClassLoc, ClassLoc, /*Id=*/0, 8908 ArgType, /*TInfo=*/0, 8909 SC_None, 0); 8910 MoveAssignment->setParams(FromParam); 8911 8912 AddOverriddenMethods(ClassDecl, MoveAssignment); 8913 8914 MoveAssignment->setTrivial( 8915 ClassDecl->needsOverloadResolutionForMoveAssignment() 8916 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 8917 : ClassDecl->hasTrivialMoveAssignment()); 8918 8919 // C++0x [class.copy]p9: 8920 // If the definition of a class X does not explicitly declare a move 8921 // assignment operator, one will be implicitly declared as defaulted if and 8922 // only if: 8923 // [...] 8924 // - the move assignment operator would not be implicitly defined as 8925 // deleted. 8926 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 8927 // Cache this result so that we don't try to generate this over and over 8928 // on every lookup, leaking memory and wasting time. 8929 ClassDecl->setFailedImplicitMoveAssignment(); 8930 return 0; 8931 } 8932 8933 // Note that we have added this copy-assignment operator. 8934 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 8935 8936 if (Scope *S = getScopeForContext(ClassDecl)) 8937 PushOnScopeChains(MoveAssignment, S, false); 8938 ClassDecl->addDecl(MoveAssignment); 8939 8940 return MoveAssignment; 8941} 8942 8943void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 8944 CXXMethodDecl *MoveAssignOperator) { 8945 assert((MoveAssignOperator->isDefaulted() && 8946 MoveAssignOperator->isOverloadedOperator() && 8947 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 8948 !MoveAssignOperator->doesThisDeclarationHaveABody() && 8949 !MoveAssignOperator->isDeleted()) && 8950 "DefineImplicitMoveAssignment called for wrong function"); 8951 8952 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 8953 8954 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) { 8955 MoveAssignOperator->setInvalidDecl(); 8956 return; 8957 } 8958 8959 MoveAssignOperator->setUsed(); 8960 8961 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 8962 DiagnosticErrorTrap Trap(Diags); 8963 8964 // C++0x [class.copy]p28: 8965 // The implicitly-defined or move assignment operator for a non-union class 8966 // X performs memberwise move assignment of its subobjects. The direct base 8967 // classes of X are assigned first, in the order of their declaration in the 8968 // base-specifier-list, and then the immediate non-static data members of X 8969 // are assigned, in the order in which they were declared in the class 8970 // definition. 8971 8972 // The statements that form the synthesized function body. 8973 SmallVector<Stmt*, 8> Statements; 8974 8975 // The parameter for the "other" object, which we are move from. 8976 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 8977 QualType OtherRefType = Other->getType()-> 8978 getAs<RValueReferenceType>()->getPointeeType(); 8979 assert(OtherRefType.getQualifiers() == 0 && 8980 "Bad argument type of defaulted move assignment"); 8981 8982 // Our location for everything implicitly-generated. 8983 SourceLocation Loc = MoveAssignOperator->getLocation(); 8984 8985 // Construct a reference to the "other" object. We'll be using this 8986 // throughout the generated ASTs. 8987 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take(); 8988 assert(OtherRef && "Reference to parameter cannot fail!"); 8989 // Cast to rvalue. 8990 OtherRef = CastForMoving(*this, OtherRef); 8991 8992 // Construct the "this" pointer. We'll be using this throughout the generated 8993 // ASTs. 8994 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>(); 8995 assert(This && "Reference to this cannot fail!"); 8996 8997 // Assign base classes. 8998 bool Invalid = false; 8999 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 9000 E = ClassDecl->bases_end(); Base != E; ++Base) { 9001 // Form the assignment: 9002 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 9003 QualType BaseType = Base->getType().getUnqualifiedType(); 9004 if (!BaseType->isRecordType()) { 9005 Invalid = true; 9006 continue; 9007 } 9008 9009 CXXCastPath BasePath; 9010 BasePath.push_back(Base); 9011 9012 // Construct the "from" expression, which is an implicit cast to the 9013 // appropriately-qualified base type. 9014 Expr *From = OtherRef; 9015 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase, 9016 VK_XValue, &BasePath).take(); 9017 9018 // Dereference "this". 9019 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 9020 9021 // Implicitly cast "this" to the appropriately-qualified base type. 9022 To = ImpCastExprToType(To.take(), 9023 Context.getCVRQualifiedType(BaseType, 9024 MoveAssignOperator->getTypeQualifiers()), 9025 CK_UncheckedDerivedToBase, 9026 VK_LValue, &BasePath); 9027 9028 // Build the move. 9029 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 9030 To.get(), From, 9031 /*CopyingBaseSubobject=*/true, 9032 /*Copying=*/false); 9033 if (Move.isInvalid()) { 9034 Diag(CurrentLocation, diag::note_member_synthesized_at) 9035 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9036 MoveAssignOperator->setInvalidDecl(); 9037 return; 9038 } 9039 9040 // Success! Record the move. 9041 Statements.push_back(Move.takeAs<Expr>()); 9042 } 9043 9044 // Assign non-static members. 9045 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 9046 FieldEnd = ClassDecl->field_end(); 9047 Field != FieldEnd; ++Field) { 9048 if (Field->isUnnamedBitfield()) 9049 continue; 9050 9051 // Check for members of reference type; we can't move those. 9052 if (Field->getType()->isReferenceType()) { 9053 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9054 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 9055 Diag(Field->getLocation(), diag::note_declared_at); 9056 Diag(CurrentLocation, diag::note_member_synthesized_at) 9057 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9058 Invalid = true; 9059 continue; 9060 } 9061 9062 // Check for members of const-qualified, non-class type. 9063 QualType BaseType = Context.getBaseElementType(Field->getType()); 9064 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 9065 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9066 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 9067 Diag(Field->getLocation(), diag::note_declared_at); 9068 Diag(CurrentLocation, diag::note_member_synthesized_at) 9069 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9070 Invalid = true; 9071 continue; 9072 } 9073 9074 // Suppress assigning zero-width bitfields. 9075 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 9076 continue; 9077 9078 QualType FieldType = Field->getType().getNonReferenceType(); 9079 if (FieldType->isIncompleteArrayType()) { 9080 assert(ClassDecl->hasFlexibleArrayMember() && 9081 "Incomplete array type is not valid"); 9082 continue; 9083 } 9084 9085 // Build references to the field in the object we're copying from and to. 9086 CXXScopeSpec SS; // Intentionally empty 9087 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 9088 LookupMemberName); 9089 MemberLookup.addDecl(*Field); 9090 MemberLookup.resolveKind(); 9091 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType, 9092 Loc, /*IsArrow=*/false, 9093 SS, SourceLocation(), 0, 9094 MemberLookup, 0); 9095 ExprResult To = BuildMemberReferenceExpr(This, This->getType(), 9096 Loc, /*IsArrow=*/true, 9097 SS, SourceLocation(), 0, 9098 MemberLookup, 0); 9099 assert(!From.isInvalid() && "Implicit field reference cannot fail"); 9100 assert(!To.isInvalid() && "Implicit field reference cannot fail"); 9101 9102 assert(!From.get()->isLValue() && // could be xvalue or prvalue 9103 "Member reference with rvalue base must be rvalue except for reference " 9104 "members, which aren't allowed for move assignment."); 9105 9106 // Build the move of this field. 9107 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 9108 To.get(), From.get(), 9109 /*CopyingBaseSubobject=*/false, 9110 /*Copying=*/false); 9111 if (Move.isInvalid()) { 9112 Diag(CurrentLocation, diag::note_member_synthesized_at) 9113 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9114 MoveAssignOperator->setInvalidDecl(); 9115 return; 9116 } 9117 9118 // Success! Record the copy. 9119 Statements.push_back(Move.takeAs<Stmt>()); 9120 } 9121 9122 if (!Invalid) { 9123 // Add a "return *this;" 9124 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 9125 9126 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get()); 9127 if (Return.isInvalid()) 9128 Invalid = true; 9129 else { 9130 Statements.push_back(Return.takeAs<Stmt>()); 9131 9132 if (Trap.hasErrorOccurred()) { 9133 Diag(CurrentLocation, diag::note_member_synthesized_at) 9134 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9135 Invalid = true; 9136 } 9137 } 9138 } 9139 9140 if (Invalid) { 9141 MoveAssignOperator->setInvalidDecl(); 9142 return; 9143 } 9144 9145 StmtResult Body; 9146 { 9147 CompoundScopeRAII CompoundScope(*this); 9148 Body = ActOnCompoundStmt(Loc, Loc, Statements, 9149 /*isStmtExpr=*/false); 9150 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 9151 } 9152 MoveAssignOperator->setBody(Body.takeAs<Stmt>()); 9153 9154 if (ASTMutationListener *L = getASTMutationListener()) { 9155 L->CompletedImplicitDefinition(MoveAssignOperator); 9156 } 9157} 9158 9159Sema::ImplicitExceptionSpecification 9160Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) { 9161 CXXRecordDecl *ClassDecl = MD->getParent(); 9162 9163 ImplicitExceptionSpecification ExceptSpec(*this); 9164 if (ClassDecl->isInvalidDecl()) 9165 return ExceptSpec; 9166 9167 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 9168 assert(T->getNumArgs() >= 1 && "not a copy ctor"); 9169 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers(); 9170 9171 // C++ [except.spec]p14: 9172 // An implicitly declared special member function (Clause 12) shall have an 9173 // exception-specification. [...] 9174 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 9175 BaseEnd = ClassDecl->bases_end(); 9176 Base != BaseEnd; 9177 ++Base) { 9178 // Virtual bases are handled below. 9179 if (Base->isVirtual()) 9180 continue; 9181 9182 CXXRecordDecl *BaseClassDecl 9183 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9184 if (CXXConstructorDecl *CopyConstructor = 9185 LookupCopyingConstructor(BaseClassDecl, Quals)) 9186 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor); 9187 } 9188 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 9189 BaseEnd = ClassDecl->vbases_end(); 9190 Base != BaseEnd; 9191 ++Base) { 9192 CXXRecordDecl *BaseClassDecl 9193 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9194 if (CXXConstructorDecl *CopyConstructor = 9195 LookupCopyingConstructor(BaseClassDecl, Quals)) 9196 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor); 9197 } 9198 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 9199 FieldEnd = ClassDecl->field_end(); 9200 Field != FieldEnd; 9201 ++Field) { 9202 QualType FieldType = Context.getBaseElementType(Field->getType()); 9203 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 9204 if (CXXConstructorDecl *CopyConstructor = 9205 LookupCopyingConstructor(FieldClassDecl, 9206 Quals | FieldType.getCVRQualifiers())) 9207 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor); 9208 } 9209 } 9210 9211 return ExceptSpec; 9212} 9213 9214CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 9215 CXXRecordDecl *ClassDecl) { 9216 // C++ [class.copy]p4: 9217 // If the class definition does not explicitly declare a copy 9218 // constructor, one is declared implicitly. 9219 assert(ClassDecl->needsImplicitCopyConstructor()); 9220 9221 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 9222 if (DSM.isAlreadyBeingDeclared()) 9223 return 0; 9224 9225 QualType ClassType = Context.getTypeDeclType(ClassDecl); 9226 QualType ArgType = ClassType; 9227 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 9228 if (Const) 9229 ArgType = ArgType.withConst(); 9230 ArgType = Context.getLValueReferenceType(ArgType); 9231 9232 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9233 CXXCopyConstructor, 9234 Const); 9235 9236 DeclarationName Name 9237 = Context.DeclarationNames.getCXXConstructorName( 9238 Context.getCanonicalType(ClassType)); 9239 SourceLocation ClassLoc = ClassDecl->getLocation(); 9240 DeclarationNameInfo NameInfo(Name, ClassLoc); 9241 9242 // An implicitly-declared copy constructor is an inline public 9243 // member of its class. 9244 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 9245 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0, 9246 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 9247 Constexpr); 9248 CopyConstructor->setAccess(AS_public); 9249 CopyConstructor->setDefaulted(); 9250 9251 // Build an exception specification pointing back at this member. 9252 FunctionProtoType::ExtProtoInfo EPI; 9253 EPI.ExceptionSpecType = EST_Unevaluated; 9254 EPI.ExceptionSpecDecl = CopyConstructor; 9255 CopyConstructor->setType( 9256 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 9257 9258 // Add the parameter to the constructor. 9259 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 9260 ClassLoc, ClassLoc, 9261 /*IdentifierInfo=*/0, 9262 ArgType, /*TInfo=*/0, 9263 SC_None, 0); 9264 CopyConstructor->setParams(FromParam); 9265 9266 CopyConstructor->setTrivial( 9267 ClassDecl->needsOverloadResolutionForCopyConstructor() 9268 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 9269 : ClassDecl->hasTrivialCopyConstructor()); 9270 9271 // C++11 [class.copy]p8: 9272 // ... If the class definition does not explicitly declare a copy 9273 // constructor, there is no user-declared move constructor, and there is no 9274 // user-declared move assignment operator, a copy constructor is implicitly 9275 // declared as defaulted. 9276 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) 9277 SetDeclDeleted(CopyConstructor, ClassLoc); 9278 9279 // Note that we have declared this constructor. 9280 ++ASTContext::NumImplicitCopyConstructorsDeclared; 9281 9282 if (Scope *S = getScopeForContext(ClassDecl)) 9283 PushOnScopeChains(CopyConstructor, S, false); 9284 ClassDecl->addDecl(CopyConstructor); 9285 9286 return CopyConstructor; 9287} 9288 9289void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 9290 CXXConstructorDecl *CopyConstructor) { 9291 assert((CopyConstructor->isDefaulted() && 9292 CopyConstructor->isCopyConstructor() && 9293 !CopyConstructor->doesThisDeclarationHaveABody() && 9294 !CopyConstructor->isDeleted()) && 9295 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 9296 9297 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 9298 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 9299 9300 SynthesizedFunctionScope Scope(*this, CopyConstructor); 9301 DiagnosticErrorTrap Trap(Diags); 9302 9303 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) || 9304 Trap.hasErrorOccurred()) { 9305 Diag(CurrentLocation, diag::note_member_synthesized_at) 9306 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl); 9307 CopyConstructor->setInvalidDecl(); 9308 } else { 9309 Sema::CompoundScopeRAII CompoundScope(*this); 9310 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(), 9311 CopyConstructor->getLocation(), 9312 MultiStmtArg(), 9313 /*isStmtExpr=*/false) 9314 .takeAs<Stmt>()); 9315 CopyConstructor->setImplicitlyDefined(true); 9316 } 9317 9318 CopyConstructor->setUsed(); 9319 if (ASTMutationListener *L = getASTMutationListener()) { 9320 L->CompletedImplicitDefinition(CopyConstructor); 9321 } 9322} 9323 9324Sema::ImplicitExceptionSpecification 9325Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) { 9326 CXXRecordDecl *ClassDecl = MD->getParent(); 9327 9328 // C++ [except.spec]p14: 9329 // An implicitly declared special member function (Clause 12) shall have an 9330 // exception-specification. [...] 9331 ImplicitExceptionSpecification ExceptSpec(*this); 9332 if (ClassDecl->isInvalidDecl()) 9333 return ExceptSpec; 9334 9335 // Direct base-class constructors. 9336 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 9337 BEnd = ClassDecl->bases_end(); 9338 B != BEnd; ++B) { 9339 if (B->isVirtual()) // Handled below. 9340 continue; 9341 9342 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 9343 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 9344 CXXConstructorDecl *Constructor = 9345 LookupMovingConstructor(BaseClassDecl, 0); 9346 // If this is a deleted function, add it anyway. This might be conformant 9347 // with the standard. This might not. I'm not sure. It might not matter. 9348 if (Constructor) 9349 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 9350 } 9351 } 9352 9353 // Virtual base-class constructors. 9354 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 9355 BEnd = ClassDecl->vbases_end(); 9356 B != BEnd; ++B) { 9357 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 9358 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 9359 CXXConstructorDecl *Constructor = 9360 LookupMovingConstructor(BaseClassDecl, 0); 9361 // If this is a deleted function, add it anyway. This might be conformant 9362 // with the standard. This might not. I'm not sure. It might not matter. 9363 if (Constructor) 9364 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 9365 } 9366 } 9367 9368 // Field constructors. 9369 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 9370 FEnd = ClassDecl->field_end(); 9371 F != FEnd; ++F) { 9372 QualType FieldType = Context.getBaseElementType(F->getType()); 9373 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) { 9374 CXXConstructorDecl *Constructor = 9375 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers()); 9376 // If this is a deleted function, add it anyway. This might be conformant 9377 // with the standard. This might not. I'm not sure. It might not matter. 9378 // In particular, the problem is that this function never gets called. It 9379 // might just be ill-formed because this function attempts to refer to 9380 // a deleted function here. 9381 if (Constructor) 9382 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 9383 } 9384 } 9385 9386 return ExceptSpec; 9387} 9388 9389CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 9390 CXXRecordDecl *ClassDecl) { 9391 // C++11 [class.copy]p9: 9392 // If the definition of a class X does not explicitly declare a move 9393 // constructor, one will be implicitly declared as defaulted if and only if: 9394 // 9395 // - [first 4 bullets] 9396 assert(ClassDecl->needsImplicitMoveConstructor()); 9397 9398 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 9399 if (DSM.isAlreadyBeingDeclared()) 9400 return 0; 9401 9402 // [Checked after we build the declaration] 9403 // - the move assignment operator would not be implicitly defined as 9404 // deleted, 9405 9406 // [DR1402]: 9407 // - each of X's non-static data members and direct or virtual base classes 9408 // has a type that either has a move constructor or is trivially copyable. 9409 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) { 9410 ClassDecl->setFailedImplicitMoveConstructor(); 9411 return 0; 9412 } 9413 9414 QualType ClassType = Context.getTypeDeclType(ClassDecl); 9415 QualType ArgType = Context.getRValueReferenceType(ClassType); 9416 9417 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9418 CXXMoveConstructor, 9419 false); 9420 9421 DeclarationName Name 9422 = Context.DeclarationNames.getCXXConstructorName( 9423 Context.getCanonicalType(ClassType)); 9424 SourceLocation ClassLoc = ClassDecl->getLocation(); 9425 DeclarationNameInfo NameInfo(Name, ClassLoc); 9426 9427 // C++0x [class.copy]p11: 9428 // An implicitly-declared copy/move constructor is an inline public 9429 // member of its class. 9430 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 9431 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0, 9432 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 9433 Constexpr); 9434 MoveConstructor->setAccess(AS_public); 9435 MoveConstructor->setDefaulted(); 9436 9437 // Build an exception specification pointing back at this member. 9438 FunctionProtoType::ExtProtoInfo EPI; 9439 EPI.ExceptionSpecType = EST_Unevaluated; 9440 EPI.ExceptionSpecDecl = MoveConstructor; 9441 MoveConstructor->setType( 9442 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 9443 9444 // Add the parameter to the constructor. 9445 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 9446 ClassLoc, ClassLoc, 9447 /*IdentifierInfo=*/0, 9448 ArgType, /*TInfo=*/0, 9449 SC_None, 0); 9450 MoveConstructor->setParams(FromParam); 9451 9452 MoveConstructor->setTrivial( 9453 ClassDecl->needsOverloadResolutionForMoveConstructor() 9454 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 9455 : ClassDecl->hasTrivialMoveConstructor()); 9456 9457 // C++0x [class.copy]p9: 9458 // If the definition of a class X does not explicitly declare a move 9459 // constructor, one will be implicitly declared as defaulted if and only if: 9460 // [...] 9461 // - the move constructor would not be implicitly defined as deleted. 9462 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 9463 // Cache this result so that we don't try to generate this over and over 9464 // on every lookup, leaking memory and wasting time. 9465 ClassDecl->setFailedImplicitMoveConstructor(); 9466 return 0; 9467 } 9468 9469 // Note that we have declared this constructor. 9470 ++ASTContext::NumImplicitMoveConstructorsDeclared; 9471 9472 if (Scope *S = getScopeForContext(ClassDecl)) 9473 PushOnScopeChains(MoveConstructor, S, false); 9474 ClassDecl->addDecl(MoveConstructor); 9475 9476 return MoveConstructor; 9477} 9478 9479void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 9480 CXXConstructorDecl *MoveConstructor) { 9481 assert((MoveConstructor->isDefaulted() && 9482 MoveConstructor->isMoveConstructor() && 9483 !MoveConstructor->doesThisDeclarationHaveABody() && 9484 !MoveConstructor->isDeleted()) && 9485 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 9486 9487 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 9488 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 9489 9490 SynthesizedFunctionScope Scope(*this, MoveConstructor); 9491 DiagnosticErrorTrap Trap(Diags); 9492 9493 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) || 9494 Trap.hasErrorOccurred()) { 9495 Diag(CurrentLocation, diag::note_member_synthesized_at) 9496 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl); 9497 MoveConstructor->setInvalidDecl(); 9498 } else { 9499 Sema::CompoundScopeRAII CompoundScope(*this); 9500 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(), 9501 MoveConstructor->getLocation(), 9502 MultiStmtArg(), 9503 /*isStmtExpr=*/false) 9504 .takeAs<Stmt>()); 9505 MoveConstructor->setImplicitlyDefined(true); 9506 } 9507 9508 MoveConstructor->setUsed(); 9509 9510 if (ASTMutationListener *L = getASTMutationListener()) { 9511 L->CompletedImplicitDefinition(MoveConstructor); 9512 } 9513} 9514 9515bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 9516 return FD->isDeleted() && 9517 (FD->isDefaulted() || FD->isImplicit()) && 9518 isa<CXXMethodDecl>(FD); 9519} 9520 9521/// \brief Mark the call operator of the given lambda closure type as "used". 9522static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) { 9523 CXXMethodDecl *CallOperator 9524 = cast<CXXMethodDecl>( 9525 Lambda->lookup( 9526 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front()); 9527 CallOperator->setReferenced(); 9528 CallOperator->setUsed(); 9529} 9530 9531void Sema::DefineImplicitLambdaToFunctionPointerConversion( 9532 SourceLocation CurrentLocation, 9533 CXXConversionDecl *Conv) 9534{ 9535 CXXRecordDecl *Lambda = Conv->getParent(); 9536 9537 // Make sure that the lambda call operator is marked used. 9538 markLambdaCallOperatorUsed(*this, Lambda); 9539 9540 Conv->setUsed(); 9541 9542 SynthesizedFunctionScope Scope(*this, Conv); 9543 DiagnosticErrorTrap Trap(Diags); 9544 9545 // Return the address of the __invoke function. 9546 DeclarationName InvokeName = &Context.Idents.get("__invoke"); 9547 CXXMethodDecl *Invoke 9548 = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front()); 9549 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(), 9550 VK_LValue, Conv->getLocation()).take(); 9551 assert(FunctionRef && "Can't refer to __invoke function?"); 9552 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take(); 9553 Conv->setBody(new (Context) CompoundStmt(Context, Return, 9554 Conv->getLocation(), 9555 Conv->getLocation())); 9556 9557 // Fill in the __invoke function with a dummy implementation. IR generation 9558 // will fill in the actual details. 9559 Invoke->setUsed(); 9560 Invoke->setReferenced(); 9561 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation())); 9562 9563 if (ASTMutationListener *L = getASTMutationListener()) { 9564 L->CompletedImplicitDefinition(Conv); 9565 L->CompletedImplicitDefinition(Invoke); 9566 } 9567} 9568 9569void Sema::DefineImplicitLambdaToBlockPointerConversion( 9570 SourceLocation CurrentLocation, 9571 CXXConversionDecl *Conv) 9572{ 9573 Conv->setUsed(); 9574 9575 SynthesizedFunctionScope Scope(*this, Conv); 9576 DiagnosticErrorTrap Trap(Diags); 9577 9578 // Copy-initialize the lambda object as needed to capture it. 9579 Expr *This = ActOnCXXThis(CurrentLocation).take(); 9580 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take(); 9581 9582 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 9583 Conv->getLocation(), 9584 Conv, DerefThis); 9585 9586 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 9587 // behavior. Note that only the general conversion function does this 9588 // (since it's unusable otherwise); in the case where we inline the 9589 // block literal, it has block literal lifetime semantics. 9590 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 9591 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 9592 CK_CopyAndAutoreleaseBlockObject, 9593 BuildBlock.get(), 0, VK_RValue); 9594 9595 if (BuildBlock.isInvalid()) { 9596 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 9597 Conv->setInvalidDecl(); 9598 return; 9599 } 9600 9601 // Create the return statement that returns the block from the conversion 9602 // function. 9603 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get()); 9604 if (Return.isInvalid()) { 9605 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 9606 Conv->setInvalidDecl(); 9607 return; 9608 } 9609 9610 // Set the body of the conversion function. 9611 Stmt *ReturnS = Return.take(); 9612 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS, 9613 Conv->getLocation(), 9614 Conv->getLocation())); 9615 9616 // We're done; notify the mutation listener, if any. 9617 if (ASTMutationListener *L = getASTMutationListener()) { 9618 L->CompletedImplicitDefinition(Conv); 9619 } 9620} 9621 9622/// \brief Determine whether the given list arguments contains exactly one 9623/// "real" (non-default) argument. 9624static bool hasOneRealArgument(MultiExprArg Args) { 9625 switch (Args.size()) { 9626 case 0: 9627 return false; 9628 9629 default: 9630 if (!Args[1]->isDefaultArgument()) 9631 return false; 9632 9633 // fall through 9634 case 1: 9635 return !Args[0]->isDefaultArgument(); 9636 } 9637 9638 return false; 9639} 9640 9641ExprResult 9642Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 9643 CXXConstructorDecl *Constructor, 9644 MultiExprArg ExprArgs, 9645 bool HadMultipleCandidates, 9646 bool IsListInitialization, 9647 bool RequiresZeroInit, 9648 unsigned ConstructKind, 9649 SourceRange ParenRange) { 9650 bool Elidable = false; 9651 9652 // C++0x [class.copy]p34: 9653 // When certain criteria are met, an implementation is allowed to 9654 // omit the copy/move construction of a class object, even if the 9655 // copy/move constructor and/or destructor for the object have 9656 // side effects. [...] 9657 // - when a temporary class object that has not been bound to a 9658 // reference (12.2) would be copied/moved to a class object 9659 // with the same cv-unqualified type, the copy/move operation 9660 // can be omitted by constructing the temporary object 9661 // directly into the target of the omitted copy/move 9662 if (ConstructKind == CXXConstructExpr::CK_Complete && 9663 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 9664 Expr *SubExpr = ExprArgs[0]; 9665 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent()); 9666 } 9667 9668 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 9669 Elidable, ExprArgs, HadMultipleCandidates, 9670 IsListInitialization, RequiresZeroInit, 9671 ConstructKind, ParenRange); 9672} 9673 9674/// BuildCXXConstructExpr - Creates a complete call to a constructor, 9675/// including handling of its default argument expressions. 9676ExprResult 9677Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 9678 CXXConstructorDecl *Constructor, bool Elidable, 9679 MultiExprArg ExprArgs, 9680 bool HadMultipleCandidates, 9681 bool IsListInitialization, 9682 bool RequiresZeroInit, 9683 unsigned ConstructKind, 9684 SourceRange ParenRange) { 9685 MarkFunctionReferenced(ConstructLoc, Constructor); 9686 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc, 9687 Constructor, Elidable, ExprArgs, 9688 HadMultipleCandidates, 9689 IsListInitialization, RequiresZeroInit, 9690 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 9691 ParenRange)); 9692} 9693 9694void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 9695 if (VD->isInvalidDecl()) return; 9696 9697 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 9698 if (ClassDecl->isInvalidDecl()) return; 9699 if (ClassDecl->hasIrrelevantDestructor()) return; 9700 if (ClassDecl->isDependentContext()) return; 9701 9702 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 9703 MarkFunctionReferenced(VD->getLocation(), Destructor); 9704 CheckDestructorAccess(VD->getLocation(), Destructor, 9705 PDiag(diag::err_access_dtor_var) 9706 << VD->getDeclName() 9707 << VD->getType()); 9708 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 9709 9710 if (!VD->hasGlobalStorage()) return; 9711 9712 // Emit warning for non-trivial dtor in global scope (a real global, 9713 // class-static, function-static). 9714 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 9715 9716 // TODO: this should be re-enabled for static locals by !CXAAtExit 9717 if (!VD->isStaticLocal()) 9718 Diag(VD->getLocation(), diag::warn_global_destructor); 9719} 9720 9721/// \brief Given a constructor and the set of arguments provided for the 9722/// constructor, convert the arguments and add any required default arguments 9723/// to form a proper call to this constructor. 9724/// 9725/// \returns true if an error occurred, false otherwise. 9726bool 9727Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 9728 MultiExprArg ArgsPtr, 9729 SourceLocation Loc, 9730 SmallVectorImpl<Expr*> &ConvertedArgs, 9731 bool AllowExplicit, 9732 bool IsListInitialization) { 9733 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 9734 unsigned NumArgs = ArgsPtr.size(); 9735 Expr **Args = ArgsPtr.data(); 9736 9737 const FunctionProtoType *Proto 9738 = Constructor->getType()->getAs<FunctionProtoType>(); 9739 assert(Proto && "Constructor without a prototype?"); 9740 unsigned NumArgsInProto = Proto->getNumArgs(); 9741 9742 // If too few arguments are available, we'll fill in the rest with defaults. 9743 if (NumArgs < NumArgsInProto) 9744 ConvertedArgs.reserve(NumArgsInProto); 9745 else 9746 ConvertedArgs.reserve(NumArgs); 9747 9748 VariadicCallType CallType = 9749 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 9750 SmallVector<Expr *, 8> AllArgs; 9751 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 9752 Proto, 0, Args, NumArgs, AllArgs, 9753 CallType, AllowExplicit, 9754 IsListInitialization); 9755 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 9756 9757 DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size()); 9758 9759 CheckConstructorCall(Constructor, 9760 llvm::makeArrayRef<const Expr *>(AllArgs.data(), 9761 AllArgs.size()), 9762 Proto, Loc); 9763 9764 return Invalid; 9765} 9766 9767static inline bool 9768CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 9769 const FunctionDecl *FnDecl) { 9770 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 9771 if (isa<NamespaceDecl>(DC)) { 9772 return SemaRef.Diag(FnDecl->getLocation(), 9773 diag::err_operator_new_delete_declared_in_namespace) 9774 << FnDecl->getDeclName(); 9775 } 9776 9777 if (isa<TranslationUnitDecl>(DC) && 9778 FnDecl->getStorageClass() == SC_Static) { 9779 return SemaRef.Diag(FnDecl->getLocation(), 9780 diag::err_operator_new_delete_declared_static) 9781 << FnDecl->getDeclName(); 9782 } 9783 9784 return false; 9785} 9786 9787static inline bool 9788CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 9789 CanQualType ExpectedResultType, 9790 CanQualType ExpectedFirstParamType, 9791 unsigned DependentParamTypeDiag, 9792 unsigned InvalidParamTypeDiag) { 9793 QualType ResultType = 9794 FnDecl->getType()->getAs<FunctionType>()->getResultType(); 9795 9796 // Check that the result type is not dependent. 9797 if (ResultType->isDependentType()) 9798 return SemaRef.Diag(FnDecl->getLocation(), 9799 diag::err_operator_new_delete_dependent_result_type) 9800 << FnDecl->getDeclName() << ExpectedResultType; 9801 9802 // Check that the result type is what we expect. 9803 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 9804 return SemaRef.Diag(FnDecl->getLocation(), 9805 diag::err_operator_new_delete_invalid_result_type) 9806 << FnDecl->getDeclName() << ExpectedResultType; 9807 9808 // A function template must have at least 2 parameters. 9809 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 9810 return SemaRef.Diag(FnDecl->getLocation(), 9811 diag::err_operator_new_delete_template_too_few_parameters) 9812 << FnDecl->getDeclName(); 9813 9814 // The function decl must have at least 1 parameter. 9815 if (FnDecl->getNumParams() == 0) 9816 return SemaRef.Diag(FnDecl->getLocation(), 9817 diag::err_operator_new_delete_too_few_parameters) 9818 << FnDecl->getDeclName(); 9819 9820 // Check the first parameter type is not dependent. 9821 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 9822 if (FirstParamType->isDependentType()) 9823 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 9824 << FnDecl->getDeclName() << ExpectedFirstParamType; 9825 9826 // Check that the first parameter type is what we expect. 9827 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 9828 ExpectedFirstParamType) 9829 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 9830 << FnDecl->getDeclName() << ExpectedFirstParamType; 9831 9832 return false; 9833} 9834 9835static bool 9836CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 9837 // C++ [basic.stc.dynamic.allocation]p1: 9838 // A program is ill-formed if an allocation function is declared in a 9839 // namespace scope other than global scope or declared static in global 9840 // scope. 9841 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 9842 return true; 9843 9844 CanQualType SizeTy = 9845 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 9846 9847 // C++ [basic.stc.dynamic.allocation]p1: 9848 // The return type shall be void*. The first parameter shall have type 9849 // std::size_t. 9850 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 9851 SizeTy, 9852 diag::err_operator_new_dependent_param_type, 9853 diag::err_operator_new_param_type)) 9854 return true; 9855 9856 // C++ [basic.stc.dynamic.allocation]p1: 9857 // The first parameter shall not have an associated default argument. 9858 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 9859 return SemaRef.Diag(FnDecl->getLocation(), 9860 diag::err_operator_new_default_arg) 9861 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 9862 9863 return false; 9864} 9865 9866static bool 9867CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 9868 // C++ [basic.stc.dynamic.deallocation]p1: 9869 // A program is ill-formed if deallocation functions are declared in a 9870 // namespace scope other than global scope or declared static in global 9871 // scope. 9872 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 9873 return true; 9874 9875 // C++ [basic.stc.dynamic.deallocation]p2: 9876 // Each deallocation function shall return void and its first parameter 9877 // shall be void*. 9878 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 9879 SemaRef.Context.VoidPtrTy, 9880 diag::err_operator_delete_dependent_param_type, 9881 diag::err_operator_delete_param_type)) 9882 return true; 9883 9884 return false; 9885} 9886 9887/// CheckOverloadedOperatorDeclaration - Check whether the declaration 9888/// of this overloaded operator is well-formed. If so, returns false; 9889/// otherwise, emits appropriate diagnostics and returns true. 9890bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 9891 assert(FnDecl && FnDecl->isOverloadedOperator() && 9892 "Expected an overloaded operator declaration"); 9893 9894 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 9895 9896 // C++ [over.oper]p5: 9897 // The allocation and deallocation functions, operator new, 9898 // operator new[], operator delete and operator delete[], are 9899 // described completely in 3.7.3. The attributes and restrictions 9900 // found in the rest of this subclause do not apply to them unless 9901 // explicitly stated in 3.7.3. 9902 if (Op == OO_Delete || Op == OO_Array_Delete) 9903 return CheckOperatorDeleteDeclaration(*this, FnDecl); 9904 9905 if (Op == OO_New || Op == OO_Array_New) 9906 return CheckOperatorNewDeclaration(*this, FnDecl); 9907 9908 // C++ [over.oper]p6: 9909 // An operator function shall either be a non-static member 9910 // function or be a non-member function and have at least one 9911 // parameter whose type is a class, a reference to a class, an 9912 // enumeration, or a reference to an enumeration. 9913 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 9914 if (MethodDecl->isStatic()) 9915 return Diag(FnDecl->getLocation(), 9916 diag::err_operator_overload_static) << FnDecl->getDeclName(); 9917 } else { 9918 bool ClassOrEnumParam = false; 9919 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 9920 ParamEnd = FnDecl->param_end(); 9921 Param != ParamEnd; ++Param) { 9922 QualType ParamType = (*Param)->getType().getNonReferenceType(); 9923 if (ParamType->isDependentType() || ParamType->isRecordType() || 9924 ParamType->isEnumeralType()) { 9925 ClassOrEnumParam = true; 9926 break; 9927 } 9928 } 9929 9930 if (!ClassOrEnumParam) 9931 return Diag(FnDecl->getLocation(), 9932 diag::err_operator_overload_needs_class_or_enum) 9933 << FnDecl->getDeclName(); 9934 } 9935 9936 // C++ [over.oper]p8: 9937 // An operator function cannot have default arguments (8.3.6), 9938 // except where explicitly stated below. 9939 // 9940 // Only the function-call operator allows default arguments 9941 // (C++ [over.call]p1). 9942 if (Op != OO_Call) { 9943 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(); 9944 Param != FnDecl->param_end(); ++Param) { 9945 if ((*Param)->hasDefaultArg()) 9946 return Diag((*Param)->getLocation(), 9947 diag::err_operator_overload_default_arg) 9948 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange(); 9949 } 9950 } 9951 9952 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 9953 { false, false, false } 9954#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 9955 , { Unary, Binary, MemberOnly } 9956#include "clang/Basic/OperatorKinds.def" 9957 }; 9958 9959 bool CanBeUnaryOperator = OperatorUses[Op][0]; 9960 bool CanBeBinaryOperator = OperatorUses[Op][1]; 9961 bool MustBeMemberOperator = OperatorUses[Op][2]; 9962 9963 // C++ [over.oper]p8: 9964 // [...] Operator functions cannot have more or fewer parameters 9965 // than the number required for the corresponding operator, as 9966 // described in the rest of this subclause. 9967 unsigned NumParams = FnDecl->getNumParams() 9968 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 9969 if (Op != OO_Call && 9970 ((NumParams == 1 && !CanBeUnaryOperator) || 9971 (NumParams == 2 && !CanBeBinaryOperator) || 9972 (NumParams < 1) || (NumParams > 2))) { 9973 // We have the wrong number of parameters. 9974 unsigned ErrorKind; 9975 if (CanBeUnaryOperator && CanBeBinaryOperator) { 9976 ErrorKind = 2; // 2 -> unary or binary. 9977 } else if (CanBeUnaryOperator) { 9978 ErrorKind = 0; // 0 -> unary 9979 } else { 9980 assert(CanBeBinaryOperator && 9981 "All non-call overloaded operators are unary or binary!"); 9982 ErrorKind = 1; // 1 -> binary 9983 } 9984 9985 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 9986 << FnDecl->getDeclName() << NumParams << ErrorKind; 9987 } 9988 9989 // Overloaded operators other than operator() cannot be variadic. 9990 if (Op != OO_Call && 9991 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 9992 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 9993 << FnDecl->getDeclName(); 9994 } 9995 9996 // Some operators must be non-static member functions. 9997 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 9998 return Diag(FnDecl->getLocation(), 9999 diag::err_operator_overload_must_be_member) 10000 << FnDecl->getDeclName(); 10001 } 10002 10003 // C++ [over.inc]p1: 10004 // The user-defined function called operator++ implements the 10005 // prefix and postfix ++ operator. If this function is a member 10006 // function with no parameters, or a non-member function with one 10007 // parameter of class or enumeration type, it defines the prefix 10008 // increment operator ++ for objects of that type. If the function 10009 // is a member function with one parameter (which shall be of type 10010 // int) or a non-member function with two parameters (the second 10011 // of which shall be of type int), it defines the postfix 10012 // increment operator ++ for objects of that type. 10013 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 10014 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 10015 bool ParamIsInt = false; 10016 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>()) 10017 ParamIsInt = BT->getKind() == BuiltinType::Int; 10018 10019 if (!ParamIsInt) 10020 return Diag(LastParam->getLocation(), 10021 diag::err_operator_overload_post_incdec_must_be_int) 10022 << LastParam->getType() << (Op == OO_MinusMinus); 10023 } 10024 10025 return false; 10026} 10027 10028/// CheckLiteralOperatorDeclaration - Check whether the declaration 10029/// of this literal operator function is well-formed. If so, returns 10030/// false; otherwise, emits appropriate diagnostics and returns true. 10031bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 10032 if (isa<CXXMethodDecl>(FnDecl)) { 10033 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 10034 << FnDecl->getDeclName(); 10035 return true; 10036 } 10037 10038 if (FnDecl->isExternC()) { 10039 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 10040 return true; 10041 } 10042 10043 bool Valid = false; 10044 10045 // This might be the definition of a literal operator template. 10046 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 10047 // This might be a specialization of a literal operator template. 10048 if (!TpDecl) 10049 TpDecl = FnDecl->getPrimaryTemplate(); 10050 10051 // template <char...> type operator "" name() is the only valid template 10052 // signature, and the only valid signature with no parameters. 10053 if (TpDecl) { 10054 if (FnDecl->param_size() == 0) { 10055 // Must have only one template parameter 10056 TemplateParameterList *Params = TpDecl->getTemplateParameters(); 10057 if (Params->size() == 1) { 10058 NonTypeTemplateParmDecl *PmDecl = 10059 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0)); 10060 10061 // The template parameter must be a char parameter pack. 10062 if (PmDecl && PmDecl->isTemplateParameterPack() && 10063 Context.hasSameType(PmDecl->getType(), Context.CharTy)) 10064 Valid = true; 10065 } 10066 } 10067 } else if (FnDecl->param_size()) { 10068 // Check the first parameter 10069 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 10070 10071 QualType T = (*Param)->getType().getUnqualifiedType(); 10072 10073 // unsigned long long int, long double, and any character type are allowed 10074 // as the only parameters. 10075 if (Context.hasSameType(T, Context.UnsignedLongLongTy) || 10076 Context.hasSameType(T, Context.LongDoubleTy) || 10077 Context.hasSameType(T, Context.CharTy) || 10078 Context.hasSameType(T, Context.WCharTy) || 10079 Context.hasSameType(T, Context.Char16Ty) || 10080 Context.hasSameType(T, Context.Char32Ty)) { 10081 if (++Param == FnDecl->param_end()) 10082 Valid = true; 10083 goto FinishedParams; 10084 } 10085 10086 // Otherwise it must be a pointer to const; let's strip those qualifiers. 10087 const PointerType *PT = T->getAs<PointerType>(); 10088 if (!PT) 10089 goto FinishedParams; 10090 T = PT->getPointeeType(); 10091 if (!T.isConstQualified() || T.isVolatileQualified()) 10092 goto FinishedParams; 10093 T = T.getUnqualifiedType(); 10094 10095 // Move on to the second parameter; 10096 ++Param; 10097 10098 // If there is no second parameter, the first must be a const char * 10099 if (Param == FnDecl->param_end()) { 10100 if (Context.hasSameType(T, Context.CharTy)) 10101 Valid = true; 10102 goto FinishedParams; 10103 } 10104 10105 // const char *, const wchar_t*, const char16_t*, and const char32_t* 10106 // are allowed as the first parameter to a two-parameter function 10107 if (!(Context.hasSameType(T, Context.CharTy) || 10108 Context.hasSameType(T, Context.WCharTy) || 10109 Context.hasSameType(T, Context.Char16Ty) || 10110 Context.hasSameType(T, Context.Char32Ty))) 10111 goto FinishedParams; 10112 10113 // The second and final parameter must be an std::size_t 10114 T = (*Param)->getType().getUnqualifiedType(); 10115 if (Context.hasSameType(T, Context.getSizeType()) && 10116 ++Param == FnDecl->param_end()) 10117 Valid = true; 10118 } 10119 10120 // FIXME: This diagnostic is absolutely terrible. 10121FinishedParams: 10122 if (!Valid) { 10123 Diag(FnDecl->getLocation(), diag::err_literal_operator_params) 10124 << FnDecl->getDeclName(); 10125 return true; 10126 } 10127 10128 // A parameter-declaration-clause containing a default argument is not 10129 // equivalent to any of the permitted forms. 10130 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 10131 ParamEnd = FnDecl->param_end(); 10132 Param != ParamEnd; ++Param) { 10133 if ((*Param)->hasDefaultArg()) { 10134 Diag((*Param)->getDefaultArgRange().getBegin(), 10135 diag::err_literal_operator_default_argument) 10136 << (*Param)->getDefaultArgRange(); 10137 break; 10138 } 10139 } 10140 10141 StringRef LiteralName 10142 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 10143 if (LiteralName[0] != '_') { 10144 // C++11 [usrlit.suffix]p1: 10145 // Literal suffix identifiers that do not start with an underscore 10146 // are reserved for future standardization. 10147 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved); 10148 } 10149 10150 return false; 10151} 10152 10153/// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 10154/// linkage specification, including the language and (if present) 10155/// the '{'. ExternLoc is the location of the 'extern', LangLoc is 10156/// the location of the language string literal, which is provided 10157/// by Lang/StrSize. LBraceLoc, if valid, provides the location of 10158/// the '{' brace. Otherwise, this linkage specification does not 10159/// have any braces. 10160Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 10161 SourceLocation LangLoc, 10162 StringRef Lang, 10163 SourceLocation LBraceLoc) { 10164 LinkageSpecDecl::LanguageIDs Language; 10165 if (Lang == "\"C\"") 10166 Language = LinkageSpecDecl::lang_c; 10167 else if (Lang == "\"C++\"") 10168 Language = LinkageSpecDecl::lang_cxx; 10169 else { 10170 Diag(LangLoc, diag::err_bad_language); 10171 return 0; 10172 } 10173 10174 // FIXME: Add all the various semantics of linkage specifications 10175 10176 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, 10177 ExternLoc, LangLoc, Language); 10178 CurContext->addDecl(D); 10179 PushDeclContext(S, D); 10180 return D; 10181} 10182 10183/// ActOnFinishLinkageSpecification - Complete the definition of 10184/// the C++ linkage specification LinkageSpec. If RBraceLoc is 10185/// valid, it's the position of the closing '}' brace in a linkage 10186/// specification that uses braces. 10187Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 10188 Decl *LinkageSpec, 10189 SourceLocation RBraceLoc) { 10190 if (LinkageSpec) { 10191 if (RBraceLoc.isValid()) { 10192 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 10193 LSDecl->setRBraceLoc(RBraceLoc); 10194 } 10195 PopDeclContext(); 10196 } 10197 return LinkageSpec; 10198} 10199 10200Decl *Sema::ActOnEmptyDeclaration(Scope *S, 10201 AttributeList *AttrList, 10202 SourceLocation SemiLoc) { 10203 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 10204 // Attribute declarations appertain to empty declaration so we handle 10205 // them here. 10206 if (AttrList) 10207 ProcessDeclAttributeList(S, ED, AttrList); 10208 10209 CurContext->addDecl(ED); 10210 return ED; 10211} 10212 10213/// \brief Perform semantic analysis for the variable declaration that 10214/// occurs within a C++ catch clause, returning the newly-created 10215/// variable. 10216VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 10217 TypeSourceInfo *TInfo, 10218 SourceLocation StartLoc, 10219 SourceLocation Loc, 10220 IdentifierInfo *Name) { 10221 bool Invalid = false; 10222 QualType ExDeclType = TInfo->getType(); 10223 10224 // Arrays and functions decay. 10225 if (ExDeclType->isArrayType()) 10226 ExDeclType = Context.getArrayDecayedType(ExDeclType); 10227 else if (ExDeclType->isFunctionType()) 10228 ExDeclType = Context.getPointerType(ExDeclType); 10229 10230 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 10231 // The exception-declaration shall not denote a pointer or reference to an 10232 // incomplete type, other than [cv] void*. 10233 // N2844 forbids rvalue references. 10234 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 10235 Diag(Loc, diag::err_catch_rvalue_ref); 10236 Invalid = true; 10237 } 10238 10239 QualType BaseType = ExDeclType; 10240 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 10241 unsigned DK = diag::err_catch_incomplete; 10242 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 10243 BaseType = Ptr->getPointeeType(); 10244 Mode = 1; 10245 DK = diag::err_catch_incomplete_ptr; 10246 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 10247 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 10248 BaseType = Ref->getPointeeType(); 10249 Mode = 2; 10250 DK = diag::err_catch_incomplete_ref; 10251 } 10252 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 10253 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 10254 Invalid = true; 10255 10256 if (!Invalid && !ExDeclType->isDependentType() && 10257 RequireNonAbstractType(Loc, ExDeclType, 10258 diag::err_abstract_type_in_decl, 10259 AbstractVariableType)) 10260 Invalid = true; 10261 10262 // Only the non-fragile NeXT runtime currently supports C++ catches 10263 // of ObjC types, and no runtime supports catching ObjC types by value. 10264 if (!Invalid && getLangOpts().ObjC1) { 10265 QualType T = ExDeclType; 10266 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 10267 T = RT->getPointeeType(); 10268 10269 if (T->isObjCObjectType()) { 10270 Diag(Loc, diag::err_objc_object_catch); 10271 Invalid = true; 10272 } else if (T->isObjCObjectPointerType()) { 10273 // FIXME: should this be a test for macosx-fragile specifically? 10274 if (getLangOpts().ObjCRuntime.isFragile()) 10275 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 10276 } 10277 } 10278 10279 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 10280 ExDeclType, TInfo, SC_None); 10281 ExDecl->setExceptionVariable(true); 10282 10283 // In ARC, infer 'retaining' for variables of retainable type. 10284 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 10285 Invalid = true; 10286 10287 if (!Invalid && !ExDeclType->isDependentType()) { 10288 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 10289 // Insulate this from anything else we might currently be parsing. 10290 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 10291 10292 // C++ [except.handle]p16: 10293 // The object declared in an exception-declaration or, if the 10294 // exception-declaration does not specify a name, a temporary (12.2) is 10295 // copy-initialized (8.5) from the exception object. [...] 10296 // The object is destroyed when the handler exits, after the destruction 10297 // of any automatic objects initialized within the handler. 10298 // 10299 // We just pretend to initialize the object with itself, then make sure 10300 // it can be destroyed later. 10301 QualType initType = ExDeclType; 10302 10303 InitializedEntity entity = 10304 InitializedEntity::InitializeVariable(ExDecl); 10305 InitializationKind initKind = 10306 InitializationKind::CreateCopy(Loc, SourceLocation()); 10307 10308 Expr *opaqueValue = 10309 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 10310 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1); 10311 ExprResult result = sequence.Perform(*this, entity, initKind, 10312 MultiExprArg(&opaqueValue, 1)); 10313 if (result.isInvalid()) 10314 Invalid = true; 10315 else { 10316 // If the constructor used was non-trivial, set this as the 10317 // "initializer". 10318 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take()); 10319 if (!construct->getConstructor()->isTrivial()) { 10320 Expr *init = MaybeCreateExprWithCleanups(construct); 10321 ExDecl->setInit(init); 10322 } 10323 10324 // And make sure it's destructable. 10325 FinalizeVarWithDestructor(ExDecl, recordType); 10326 } 10327 } 10328 } 10329 10330 if (Invalid) 10331 ExDecl->setInvalidDecl(); 10332 10333 return ExDecl; 10334} 10335 10336/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 10337/// handler. 10338Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 10339 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 10340 bool Invalid = D.isInvalidType(); 10341 10342 // Check for unexpanded parameter packs. 10343 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 10344 UPPC_ExceptionType)) { 10345 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 10346 D.getIdentifierLoc()); 10347 Invalid = true; 10348 } 10349 10350 IdentifierInfo *II = D.getIdentifier(); 10351 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 10352 LookupOrdinaryName, 10353 ForRedeclaration)) { 10354 // The scope should be freshly made just for us. There is just no way 10355 // it contains any previous declaration. 10356 assert(!S->isDeclScope(PrevDecl)); 10357 if (PrevDecl->isTemplateParameter()) { 10358 // Maybe we will complain about the shadowed template parameter. 10359 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 10360 PrevDecl = 0; 10361 } 10362 } 10363 10364 if (D.getCXXScopeSpec().isSet() && !Invalid) { 10365 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 10366 << D.getCXXScopeSpec().getRange(); 10367 Invalid = true; 10368 } 10369 10370 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 10371 D.getLocStart(), 10372 D.getIdentifierLoc(), 10373 D.getIdentifier()); 10374 if (Invalid) 10375 ExDecl->setInvalidDecl(); 10376 10377 // Add the exception declaration into this scope. 10378 if (II) 10379 PushOnScopeChains(ExDecl, S); 10380 else 10381 CurContext->addDecl(ExDecl); 10382 10383 ProcessDeclAttributes(S, ExDecl, D); 10384 return ExDecl; 10385} 10386 10387Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 10388 Expr *AssertExpr, 10389 Expr *AssertMessageExpr, 10390 SourceLocation RParenLoc) { 10391 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr); 10392 10393 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 10394 return 0; 10395 10396 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 10397 AssertMessage, RParenLoc, false); 10398} 10399 10400Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 10401 Expr *AssertExpr, 10402 StringLiteral *AssertMessage, 10403 SourceLocation RParenLoc, 10404 bool Failed) { 10405 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 10406 !Failed) { 10407 // In a static_assert-declaration, the constant-expression shall be a 10408 // constant expression that can be contextually converted to bool. 10409 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 10410 if (Converted.isInvalid()) 10411 Failed = true; 10412 10413 llvm::APSInt Cond; 10414 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 10415 diag::err_static_assert_expression_is_not_constant, 10416 /*AllowFold=*/false).isInvalid()) 10417 Failed = true; 10418 10419 if (!Failed && !Cond) { 10420 SmallString<256> MsgBuffer; 10421 llvm::raw_svector_ostream Msg(MsgBuffer); 10422 AssertMessage->printPretty(Msg, 0, getPrintingPolicy()); 10423 Diag(StaticAssertLoc, diag::err_static_assert_failed) 10424 << Msg.str() << AssertExpr->getSourceRange(); 10425 Failed = true; 10426 } 10427 } 10428 10429 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 10430 AssertExpr, AssertMessage, RParenLoc, 10431 Failed); 10432 10433 CurContext->addDecl(Decl); 10434 return Decl; 10435} 10436 10437/// \brief Perform semantic analysis of the given friend type declaration. 10438/// 10439/// \returns A friend declaration that. 10440FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 10441 SourceLocation FriendLoc, 10442 TypeSourceInfo *TSInfo) { 10443 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 10444 10445 QualType T = TSInfo->getType(); 10446 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 10447 10448 // C++03 [class.friend]p2: 10449 // An elaborated-type-specifier shall be used in a friend declaration 10450 // for a class.* 10451 // 10452 // * The class-key of the elaborated-type-specifier is required. 10453 if (!ActiveTemplateInstantiations.empty()) { 10454 // Do not complain about the form of friend template types during 10455 // template instantiation; we will already have complained when the 10456 // template was declared. 10457 } else { 10458 if (!T->isElaboratedTypeSpecifier()) { 10459 // If we evaluated the type to a record type, suggest putting 10460 // a tag in front. 10461 if (const RecordType *RT = T->getAs<RecordType>()) { 10462 RecordDecl *RD = RT->getDecl(); 10463 10464 std::string InsertionText = std::string(" ") + RD->getKindName(); 10465 10466 Diag(TypeRange.getBegin(), 10467 getLangOpts().CPlusPlus11 ? 10468 diag::warn_cxx98_compat_unelaborated_friend_type : 10469 diag::ext_unelaborated_friend_type) 10470 << (unsigned) RD->getTagKind() 10471 << T 10472 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc), 10473 InsertionText); 10474 } else { 10475 Diag(FriendLoc, 10476 getLangOpts().CPlusPlus11 ? 10477 diag::warn_cxx98_compat_nonclass_type_friend : 10478 diag::ext_nonclass_type_friend) 10479 << T 10480 << TypeRange; 10481 } 10482 } else if (T->getAs<EnumType>()) { 10483 Diag(FriendLoc, 10484 getLangOpts().CPlusPlus11 ? 10485 diag::warn_cxx98_compat_enum_friend : 10486 diag::ext_enum_friend) 10487 << T 10488 << TypeRange; 10489 } 10490 10491 // C++11 [class.friend]p3: 10492 // A friend declaration that does not declare a function shall have one 10493 // of the following forms: 10494 // friend elaborated-type-specifier ; 10495 // friend simple-type-specifier ; 10496 // friend typename-specifier ; 10497 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 10498 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 10499 } 10500 10501 // If the type specifier in a friend declaration designates a (possibly 10502 // cv-qualified) class type, that class is declared as a friend; otherwise, 10503 // the friend declaration is ignored. 10504 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc); 10505} 10506 10507/// Handle a friend tag declaration where the scope specifier was 10508/// templated. 10509Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 10510 unsigned TagSpec, SourceLocation TagLoc, 10511 CXXScopeSpec &SS, 10512 IdentifierInfo *Name, 10513 SourceLocation NameLoc, 10514 AttributeList *Attr, 10515 MultiTemplateParamsArg TempParamLists) { 10516 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 10517 10518 bool isExplicitSpecialization = false; 10519 bool Invalid = false; 10520 10521 if (TemplateParameterList *TemplateParams 10522 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS, 10523 TempParamLists.data(), 10524 TempParamLists.size(), 10525 /*friend*/ true, 10526 isExplicitSpecialization, 10527 Invalid)) { 10528 if (TemplateParams->size() > 0) { 10529 // This is a declaration of a class template. 10530 if (Invalid) 10531 return 0; 10532 10533 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, 10534 SS, Name, NameLoc, Attr, 10535 TemplateParams, AS_public, 10536 /*ModulePrivateLoc=*/SourceLocation(), 10537 TempParamLists.size() - 1, 10538 TempParamLists.data()).take(); 10539 } else { 10540 // The "template<>" header is extraneous. 10541 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 10542 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 10543 isExplicitSpecialization = true; 10544 } 10545 } 10546 10547 if (Invalid) return 0; 10548 10549 bool isAllExplicitSpecializations = true; 10550 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 10551 if (TempParamLists[I]->size()) { 10552 isAllExplicitSpecializations = false; 10553 break; 10554 } 10555 } 10556 10557 // FIXME: don't ignore attributes. 10558 10559 // If it's explicit specializations all the way down, just forget 10560 // about the template header and build an appropriate non-templated 10561 // friend. TODO: for source fidelity, remember the headers. 10562 if (isAllExplicitSpecializations) { 10563 if (SS.isEmpty()) { 10564 bool Owned = false; 10565 bool IsDependent = false; 10566 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 10567 Attr, AS_public, 10568 /*ModulePrivateLoc=*/SourceLocation(), 10569 MultiTemplateParamsArg(), Owned, IsDependent, 10570 /*ScopedEnumKWLoc=*/SourceLocation(), 10571 /*ScopedEnumUsesClassTag=*/false, 10572 /*UnderlyingType=*/TypeResult()); 10573 } 10574 10575 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 10576 ElaboratedTypeKeyword Keyword 10577 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 10578 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 10579 *Name, NameLoc); 10580 if (T.isNull()) 10581 return 0; 10582 10583 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 10584 if (isa<DependentNameType>(T)) { 10585 DependentNameTypeLoc TL = 10586 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 10587 TL.setElaboratedKeywordLoc(TagLoc); 10588 TL.setQualifierLoc(QualifierLoc); 10589 TL.setNameLoc(NameLoc); 10590 } else { 10591 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 10592 TL.setElaboratedKeywordLoc(TagLoc); 10593 TL.setQualifierLoc(QualifierLoc); 10594 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 10595 } 10596 10597 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 10598 TSI, FriendLoc, TempParamLists); 10599 Friend->setAccess(AS_public); 10600 CurContext->addDecl(Friend); 10601 return Friend; 10602 } 10603 10604 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 10605 10606 10607 10608 // Handle the case of a templated-scope friend class. e.g. 10609 // template <class T> class A<T>::B; 10610 // FIXME: we don't support these right now. 10611 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 10612 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 10613 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 10614 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 10615 TL.setElaboratedKeywordLoc(TagLoc); 10616 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 10617 TL.setNameLoc(NameLoc); 10618 10619 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 10620 TSI, FriendLoc, TempParamLists); 10621 Friend->setAccess(AS_public); 10622 Friend->setUnsupportedFriend(true); 10623 CurContext->addDecl(Friend); 10624 return Friend; 10625} 10626 10627 10628/// Handle a friend type declaration. This works in tandem with 10629/// ActOnTag. 10630/// 10631/// Notes on friend class templates: 10632/// 10633/// We generally treat friend class declarations as if they were 10634/// declaring a class. So, for example, the elaborated type specifier 10635/// in a friend declaration is required to obey the restrictions of a 10636/// class-head (i.e. no typedefs in the scope chain), template 10637/// parameters are required to match up with simple template-ids, &c. 10638/// However, unlike when declaring a template specialization, it's 10639/// okay to refer to a template specialization without an empty 10640/// template parameter declaration, e.g. 10641/// friend class A<T>::B<unsigned>; 10642/// We permit this as a special case; if there are any template 10643/// parameters present at all, require proper matching, i.e. 10644/// template <> template \<class T> friend class A<int>::B; 10645Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 10646 MultiTemplateParamsArg TempParams) { 10647 SourceLocation Loc = DS.getLocStart(); 10648 10649 assert(DS.isFriendSpecified()); 10650 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 10651 10652 // Try to convert the decl specifier to a type. This works for 10653 // friend templates because ActOnTag never produces a ClassTemplateDecl 10654 // for a TUK_Friend. 10655 Declarator TheDeclarator(DS, Declarator::MemberContext); 10656 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 10657 QualType T = TSI->getType(); 10658 if (TheDeclarator.isInvalidType()) 10659 return 0; 10660 10661 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 10662 return 0; 10663 10664 // This is definitely an error in C++98. It's probably meant to 10665 // be forbidden in C++0x, too, but the specification is just 10666 // poorly written. 10667 // 10668 // The problem is with declarations like the following: 10669 // template <T> friend A<T>::foo; 10670 // where deciding whether a class C is a friend or not now hinges 10671 // on whether there exists an instantiation of A that causes 10672 // 'foo' to equal C. There are restrictions on class-heads 10673 // (which we declare (by fiat) elaborated friend declarations to 10674 // be) that makes this tractable. 10675 // 10676 // FIXME: handle "template <> friend class A<T>;", which 10677 // is possibly well-formed? Who even knows? 10678 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 10679 Diag(Loc, diag::err_tagless_friend_type_template) 10680 << DS.getSourceRange(); 10681 return 0; 10682 } 10683 10684 // C++98 [class.friend]p1: A friend of a class is a function 10685 // or class that is not a member of the class . . . 10686 // This is fixed in DR77, which just barely didn't make the C++03 10687 // deadline. It's also a very silly restriction that seriously 10688 // affects inner classes and which nobody else seems to implement; 10689 // thus we never diagnose it, not even in -pedantic. 10690 // 10691 // But note that we could warn about it: it's always useless to 10692 // friend one of your own members (it's not, however, worthless to 10693 // friend a member of an arbitrary specialization of your template). 10694 10695 Decl *D; 10696 if (unsigned NumTempParamLists = TempParams.size()) 10697 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 10698 NumTempParamLists, 10699 TempParams.data(), 10700 TSI, 10701 DS.getFriendSpecLoc()); 10702 else 10703 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 10704 10705 if (!D) 10706 return 0; 10707 10708 D->setAccess(AS_public); 10709 CurContext->addDecl(D); 10710 10711 return D; 10712} 10713 10714NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 10715 MultiTemplateParamsArg TemplateParams) { 10716 const DeclSpec &DS = D.getDeclSpec(); 10717 10718 assert(DS.isFriendSpecified()); 10719 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 10720 10721 SourceLocation Loc = D.getIdentifierLoc(); 10722 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 10723 10724 // C++ [class.friend]p1 10725 // A friend of a class is a function or class.... 10726 // Note that this sees through typedefs, which is intended. 10727 // It *doesn't* see through dependent types, which is correct 10728 // according to [temp.arg.type]p3: 10729 // If a declaration acquires a function type through a 10730 // type dependent on a template-parameter and this causes 10731 // a declaration that does not use the syntactic form of a 10732 // function declarator to have a function type, the program 10733 // is ill-formed. 10734 if (!TInfo->getType()->isFunctionType()) { 10735 Diag(Loc, diag::err_unexpected_friend); 10736 10737 // It might be worthwhile to try to recover by creating an 10738 // appropriate declaration. 10739 return 0; 10740 } 10741 10742 // C++ [namespace.memdef]p3 10743 // - If a friend declaration in a non-local class first declares a 10744 // class or function, the friend class or function is a member 10745 // of the innermost enclosing namespace. 10746 // - The name of the friend is not found by simple name lookup 10747 // until a matching declaration is provided in that namespace 10748 // scope (either before or after the class declaration granting 10749 // friendship). 10750 // - If a friend function is called, its name may be found by the 10751 // name lookup that considers functions from namespaces and 10752 // classes associated with the types of the function arguments. 10753 // - When looking for a prior declaration of a class or a function 10754 // declared as a friend, scopes outside the innermost enclosing 10755 // namespace scope are not considered. 10756 10757 CXXScopeSpec &SS = D.getCXXScopeSpec(); 10758 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 10759 DeclarationName Name = NameInfo.getName(); 10760 assert(Name); 10761 10762 // Check for unexpanded parameter packs. 10763 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 10764 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 10765 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 10766 return 0; 10767 10768 // The context we found the declaration in, or in which we should 10769 // create the declaration. 10770 DeclContext *DC; 10771 Scope *DCScope = S; 10772 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 10773 ForRedeclaration); 10774 10775 // FIXME: there are different rules in local classes 10776 10777 // There are four cases here. 10778 // - There's no scope specifier, in which case we just go to the 10779 // appropriate scope and look for a function or function template 10780 // there as appropriate. 10781 // Recover from invalid scope qualifiers as if they just weren't there. 10782 if (SS.isInvalid() || !SS.isSet()) { 10783 // C++0x [namespace.memdef]p3: 10784 // If the name in a friend declaration is neither qualified nor 10785 // a template-id and the declaration is a function or an 10786 // elaborated-type-specifier, the lookup to determine whether 10787 // the entity has been previously declared shall not consider 10788 // any scopes outside the innermost enclosing namespace. 10789 // C++0x [class.friend]p11: 10790 // If a friend declaration appears in a local class and the name 10791 // specified is an unqualified name, a prior declaration is 10792 // looked up without considering scopes that are outside the 10793 // innermost enclosing non-class scope. For a friend function 10794 // declaration, if there is no prior declaration, the program is 10795 // ill-formed. 10796 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass(); 10797 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 10798 10799 // Find the appropriate context according to the above. 10800 DC = CurContext; 10801 while (true) { 10802 // Skip class contexts. If someone can cite chapter and verse 10803 // for this behavior, that would be nice --- it's what GCC and 10804 // EDG do, and it seems like a reasonable intent, but the spec 10805 // really only says that checks for unqualified existing 10806 // declarations should stop at the nearest enclosing namespace, 10807 // not that they should only consider the nearest enclosing 10808 // namespace. 10809 while (DC->isRecord() || DC->isTransparentContext()) 10810 DC = DC->getParent(); 10811 10812 LookupQualifiedName(Previous, DC); 10813 10814 // TODO: decide what we think about using declarations. 10815 if (isLocal || !Previous.empty()) 10816 break; 10817 10818 if (isTemplateId) { 10819 if (isa<TranslationUnitDecl>(DC)) break; 10820 } else { 10821 if (DC->isFileContext()) break; 10822 } 10823 DC = DC->getParent(); 10824 } 10825 10826 DCScope = getScopeForDeclContext(S, DC); 10827 10828 // C++ [class.friend]p6: 10829 // A function can be defined in a friend declaration of a class if and 10830 // only if the class is a non-local class (9.8), the function name is 10831 // unqualified, and the function has namespace scope. 10832 if (isLocal && D.isFunctionDefinition()) { 10833 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 10834 } 10835 10836 // - There's a non-dependent scope specifier, in which case we 10837 // compute it and do a previous lookup there for a function 10838 // or function template. 10839 } else if (!SS.getScopeRep()->isDependent()) { 10840 DC = computeDeclContext(SS); 10841 if (!DC) return 0; 10842 10843 if (RequireCompleteDeclContext(SS, DC)) return 0; 10844 10845 LookupQualifiedName(Previous, DC); 10846 10847 // Ignore things found implicitly in the wrong scope. 10848 // TODO: better diagnostics for this case. Suggesting the right 10849 // qualified scope would be nice... 10850 LookupResult::Filter F = Previous.makeFilter(); 10851 while (F.hasNext()) { 10852 NamedDecl *D = F.next(); 10853 if (!DC->InEnclosingNamespaceSetOf( 10854 D->getDeclContext()->getRedeclContext())) 10855 F.erase(); 10856 } 10857 F.done(); 10858 10859 if (Previous.empty()) { 10860 D.setInvalidType(); 10861 Diag(Loc, diag::err_qualified_friend_not_found) 10862 << Name << TInfo->getType(); 10863 return 0; 10864 } 10865 10866 // C++ [class.friend]p1: A friend of a class is a function or 10867 // class that is not a member of the class . . . 10868 if (DC->Equals(CurContext)) 10869 Diag(DS.getFriendSpecLoc(), 10870 getLangOpts().CPlusPlus11 ? 10871 diag::warn_cxx98_compat_friend_is_member : 10872 diag::err_friend_is_member); 10873 10874 if (D.isFunctionDefinition()) { 10875 // C++ [class.friend]p6: 10876 // A function can be defined in a friend declaration of a class if and 10877 // only if the class is a non-local class (9.8), the function name is 10878 // unqualified, and the function has namespace scope. 10879 SemaDiagnosticBuilder DB 10880 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 10881 10882 DB << SS.getScopeRep(); 10883 if (DC->isFileContext()) 10884 DB << FixItHint::CreateRemoval(SS.getRange()); 10885 SS.clear(); 10886 } 10887 10888 // - There's a scope specifier that does not match any template 10889 // parameter lists, in which case we use some arbitrary context, 10890 // create a method or method template, and wait for instantiation. 10891 // - There's a scope specifier that does match some template 10892 // parameter lists, which we don't handle right now. 10893 } else { 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 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 10900 << SS.getScopeRep(); 10901 } 10902 10903 DC = CurContext; 10904 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 10905 } 10906 10907 if (!DC->isRecord()) { 10908 // This implies that it has to be an operator or function. 10909 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName || 10910 D.getName().getKind() == UnqualifiedId::IK_DestructorName || 10911 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) { 10912 Diag(Loc, diag::err_introducing_special_friend) << 10913 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 : 10914 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2); 10915 return 0; 10916 } 10917 } 10918 10919 // FIXME: This is an egregious hack to cope with cases where the scope stack 10920 // does not contain the declaration context, i.e., in an out-of-line 10921 // definition of a class. 10922 Scope FakeDCScope(S, Scope::DeclScope, Diags); 10923 if (!DCScope) { 10924 FakeDCScope.setEntity(DC); 10925 DCScope = &FakeDCScope; 10926 } 10927 10928 bool AddToScope = true; 10929 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 10930 TemplateParams, AddToScope); 10931 if (!ND) return 0; 10932 10933 assert(ND->getDeclContext() == DC); 10934 assert(ND->getLexicalDeclContext() == CurContext); 10935 10936 // Add the function declaration to the appropriate lookup tables, 10937 // adjusting the redeclarations list as necessary. We don't 10938 // want to do this yet if the friending class is dependent. 10939 // 10940 // Also update the scope-based lookup if the target context's 10941 // lookup context is in lexical scope. 10942 if (!CurContext->isDependentContext()) { 10943 DC = DC->getRedeclContext(); 10944 DC->makeDeclVisibleInContext(ND); 10945 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 10946 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 10947 } 10948 10949 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 10950 D.getIdentifierLoc(), ND, 10951 DS.getFriendSpecLoc()); 10952 FrD->setAccess(AS_public); 10953 CurContext->addDecl(FrD); 10954 10955 if (ND->isInvalidDecl()) { 10956 FrD->setInvalidDecl(); 10957 } else { 10958 if (DC->isRecord()) CheckFriendAccess(ND); 10959 10960 FunctionDecl *FD; 10961 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 10962 FD = FTD->getTemplatedDecl(); 10963 else 10964 FD = cast<FunctionDecl>(ND); 10965 10966 // Mark templated-scope function declarations as unsupported. 10967 if (FD->getNumTemplateParameterLists()) 10968 FrD->setUnsupportedFriend(true); 10969 } 10970 10971 return ND; 10972} 10973 10974void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 10975 AdjustDeclIfTemplate(Dcl); 10976 10977 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 10978 if (!Fn) { 10979 Diag(DelLoc, diag::err_deleted_non_function); 10980 return; 10981 } 10982 10983 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 10984 // Don't consider the implicit declaration we generate for explicit 10985 // specializations. FIXME: Do not generate these implicit declarations. 10986 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization 10987 || Prev->getPreviousDecl()) && !Prev->isDefined()) { 10988 Diag(DelLoc, diag::err_deleted_decl_not_first); 10989 Diag(Prev->getLocation(), diag::note_previous_declaration); 10990 } 10991 // If the declaration wasn't the first, we delete the function anyway for 10992 // recovery. 10993 Fn = Fn->getCanonicalDecl(); 10994 } 10995 10996 if (Fn->isDeleted()) 10997 return; 10998 10999 // See if we're deleting a function which is already known to override a 11000 // non-deleted virtual function. 11001 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 11002 bool IssuedDiagnostic = false; 11003 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 11004 E = MD->end_overridden_methods(); 11005 I != E; ++I) { 11006 if (!(*MD->begin_overridden_methods())->isDeleted()) { 11007 if (!IssuedDiagnostic) { 11008 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 11009 IssuedDiagnostic = true; 11010 } 11011 Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 11012 } 11013 } 11014 } 11015 11016 Fn->setDeletedAsWritten(); 11017} 11018 11019void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 11020 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 11021 11022 if (MD) { 11023 if (MD->getParent()->isDependentType()) { 11024 MD->setDefaulted(); 11025 MD->setExplicitlyDefaulted(); 11026 return; 11027 } 11028 11029 CXXSpecialMember Member = getSpecialMember(MD); 11030 if (Member == CXXInvalid) { 11031 Diag(DefaultLoc, diag::err_default_special_members); 11032 return; 11033 } 11034 11035 MD->setDefaulted(); 11036 MD->setExplicitlyDefaulted(); 11037 11038 // If this definition appears within the record, do the checking when 11039 // the record is complete. 11040 const FunctionDecl *Primary = MD; 11041 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 11042 // Find the uninstantiated declaration that actually had the '= default' 11043 // on it. 11044 Pattern->isDefined(Primary); 11045 11046 // If the method was defaulted on its first declaration, we will have 11047 // already performed the checking in CheckCompletedCXXClass. Such a 11048 // declaration doesn't trigger an implicit definition. 11049 if (Primary == Primary->getCanonicalDecl()) 11050 return; 11051 11052 CheckExplicitlyDefaultedSpecialMember(MD); 11053 11054 // The exception specification is needed because we are defining the 11055 // function. 11056 ResolveExceptionSpec(DefaultLoc, 11057 MD->getType()->castAs<FunctionProtoType>()); 11058 11059 switch (Member) { 11060 case CXXDefaultConstructor: { 11061 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD); 11062 if (!CD->isInvalidDecl()) 11063 DefineImplicitDefaultConstructor(DefaultLoc, CD); 11064 break; 11065 } 11066 11067 case CXXCopyConstructor: { 11068 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD); 11069 if (!CD->isInvalidDecl()) 11070 DefineImplicitCopyConstructor(DefaultLoc, CD); 11071 break; 11072 } 11073 11074 case CXXCopyAssignment: { 11075 if (!MD->isInvalidDecl()) 11076 DefineImplicitCopyAssignment(DefaultLoc, MD); 11077 break; 11078 } 11079 11080 case CXXDestructor: { 11081 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD); 11082 if (!DD->isInvalidDecl()) 11083 DefineImplicitDestructor(DefaultLoc, DD); 11084 break; 11085 } 11086 11087 case CXXMoveConstructor: { 11088 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD); 11089 if (!CD->isInvalidDecl()) 11090 DefineImplicitMoveConstructor(DefaultLoc, CD); 11091 break; 11092 } 11093 11094 case CXXMoveAssignment: { 11095 if (!MD->isInvalidDecl()) 11096 DefineImplicitMoveAssignment(DefaultLoc, MD); 11097 break; 11098 } 11099 11100 case CXXInvalid: 11101 llvm_unreachable("Invalid special member."); 11102 } 11103 } else { 11104 Diag(DefaultLoc, diag::err_default_special_members); 11105 } 11106} 11107 11108static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 11109 for (Stmt::child_range CI = S->children(); CI; ++CI) { 11110 Stmt *SubStmt = *CI; 11111 if (!SubStmt) 11112 continue; 11113 if (isa<ReturnStmt>(SubStmt)) 11114 Self.Diag(SubStmt->getLocStart(), 11115 diag::err_return_in_constructor_handler); 11116 if (!isa<Expr>(SubStmt)) 11117 SearchForReturnInStmt(Self, SubStmt); 11118 } 11119} 11120 11121void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 11122 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 11123 CXXCatchStmt *Handler = TryBlock->getHandler(I); 11124 SearchForReturnInStmt(*this, Handler); 11125 } 11126} 11127 11128bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 11129 const CXXMethodDecl *Old) { 11130 const FunctionType *NewFT = New->getType()->getAs<FunctionType>(); 11131 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>(); 11132 11133 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 11134 11135 // If the calling conventions match, everything is fine 11136 if (NewCC == OldCC) 11137 return false; 11138 11139 // If either of the calling conventions are set to "default", we need to pick 11140 // something more sensible based on the target. This supports code where the 11141 // one method explicitly sets thiscall, and another has no explicit calling 11142 // convention. 11143 CallingConv Default = 11144 Context.getTargetInfo().getDefaultCallingConv(TargetInfo::CCMT_Member); 11145 if (NewCC == CC_Default) 11146 NewCC = Default; 11147 if (OldCC == CC_Default) 11148 OldCC = Default; 11149 11150 // If the calling conventions still don't match, then report the error 11151 if (NewCC != OldCC) { 11152 Diag(New->getLocation(), 11153 diag::err_conflicting_overriding_cc_attributes) 11154 << New->getDeclName() << New->getType() << Old->getType(); 11155 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 11156 return true; 11157 } 11158 11159 return false; 11160} 11161 11162bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 11163 const CXXMethodDecl *Old) { 11164 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType(); 11165 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType(); 11166 11167 if (Context.hasSameType(NewTy, OldTy) || 11168 NewTy->isDependentType() || OldTy->isDependentType()) 11169 return false; 11170 11171 // Check if the return types are covariant 11172 QualType NewClassTy, OldClassTy; 11173 11174 /// Both types must be pointers or references to classes. 11175 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 11176 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 11177 NewClassTy = NewPT->getPointeeType(); 11178 OldClassTy = OldPT->getPointeeType(); 11179 } 11180 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 11181 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 11182 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 11183 NewClassTy = NewRT->getPointeeType(); 11184 OldClassTy = OldRT->getPointeeType(); 11185 } 11186 } 11187 } 11188 11189 // The return types aren't either both pointers or references to a class type. 11190 if (NewClassTy.isNull()) { 11191 Diag(New->getLocation(), 11192 diag::err_different_return_type_for_overriding_virtual_function) 11193 << New->getDeclName() << NewTy << OldTy; 11194 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 11195 11196 return true; 11197 } 11198 11199 // C++ [class.virtual]p6: 11200 // If the return type of D::f differs from the return type of B::f, the 11201 // class type in the return type of D::f shall be complete at the point of 11202 // declaration of D::f or shall be the class type D. 11203 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 11204 if (!RT->isBeingDefined() && 11205 RequireCompleteType(New->getLocation(), NewClassTy, 11206 diag::err_covariant_return_incomplete, 11207 New->getDeclName())) 11208 return true; 11209 } 11210 11211 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 11212 // Check if the new class derives from the old class. 11213 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 11214 Diag(New->getLocation(), 11215 diag::err_covariant_return_not_derived) 11216 << New->getDeclName() << NewTy << OldTy; 11217 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 11218 return true; 11219 } 11220 11221 // Check if we the conversion from derived to base is valid. 11222 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy, 11223 diag::err_covariant_return_inaccessible_base, 11224 diag::err_covariant_return_ambiguous_derived_to_base_conv, 11225 // FIXME: Should this point to the return type? 11226 New->getLocation(), SourceRange(), New->getDeclName(), 0)) { 11227 // FIXME: this note won't trigger for delayed access control 11228 // diagnostics, and it's impossible to get an undelayed error 11229 // here from access control during the original parse because 11230 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 11231 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 11232 return true; 11233 } 11234 } 11235 11236 // The qualifiers of the return types must be the same. 11237 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 11238 Diag(New->getLocation(), 11239 diag::err_covariant_return_type_different_qualifications) 11240 << New->getDeclName() << NewTy << OldTy; 11241 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 11242 return true; 11243 }; 11244 11245 11246 // The new class type must have the same or less qualifiers as the old type. 11247 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 11248 Diag(New->getLocation(), 11249 diag::err_covariant_return_type_class_type_more_qualified) 11250 << New->getDeclName() << NewTy << OldTy; 11251 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 11252 return true; 11253 }; 11254 11255 return false; 11256} 11257 11258/// \brief Mark the given method pure. 11259/// 11260/// \param Method the method to be marked pure. 11261/// 11262/// \param InitRange the source range that covers the "0" initializer. 11263bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 11264 SourceLocation EndLoc = InitRange.getEnd(); 11265 if (EndLoc.isValid()) 11266 Method->setRangeEnd(EndLoc); 11267 11268 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 11269 Method->setPure(); 11270 return false; 11271 } 11272 11273 if (!Method->isInvalidDecl()) 11274 Diag(Method->getLocation(), diag::err_non_virtual_pure) 11275 << Method->getDeclName() << InitRange; 11276 return true; 11277} 11278 11279/// \brief Determine whether the given declaration is a static data member. 11280static bool isStaticDataMember(Decl *D) { 11281 VarDecl *Var = dyn_cast_or_null<VarDecl>(D); 11282 if (!Var) 11283 return false; 11284 11285 return Var->isStaticDataMember(); 11286} 11287/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 11288/// an initializer for the out-of-line declaration 'Dcl'. The scope 11289/// is a fresh scope pushed for just this purpose. 11290/// 11291/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 11292/// static data member of class X, names should be looked up in the scope of 11293/// class X. 11294void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 11295 // If there is no declaration, there was an error parsing it. 11296 if (D == 0 || D->isInvalidDecl()) return; 11297 11298 // We should only get called for declarations with scope specifiers, like: 11299 // int foo::bar; 11300 assert(D->isOutOfLine()); 11301 EnterDeclaratorContext(S, D->getDeclContext()); 11302 11303 // If we are parsing the initializer for a static data member, push a 11304 // new expression evaluation context that is associated with this static 11305 // data member. 11306 if (isStaticDataMember(D)) 11307 PushExpressionEvaluationContext(PotentiallyEvaluated, D); 11308} 11309 11310/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 11311/// initializer for the out-of-line declaration 'D'. 11312void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 11313 // If there is no declaration, there was an error parsing it. 11314 if (D == 0 || D->isInvalidDecl()) return; 11315 11316 if (isStaticDataMember(D)) 11317 PopExpressionEvaluationContext(); 11318 11319 assert(D->isOutOfLine()); 11320 ExitDeclaratorContext(S); 11321} 11322 11323/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 11324/// C++ if/switch/while/for statement. 11325/// e.g: "if (int x = f()) {...}" 11326DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 11327 // C++ 6.4p2: 11328 // The declarator shall not specify a function or an array. 11329 // The type-specifier-seq shall not contain typedef and shall not declare a 11330 // new class or enumeration. 11331 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 11332 "Parser allowed 'typedef' as storage class of condition decl."); 11333 11334 Decl *Dcl = ActOnDeclarator(S, D); 11335 if (!Dcl) 11336 return true; 11337 11338 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 11339 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 11340 << D.getSourceRange(); 11341 return true; 11342 } 11343 11344 return Dcl; 11345} 11346 11347void Sema::LoadExternalVTableUses() { 11348 if (!ExternalSource) 11349 return; 11350 11351 SmallVector<ExternalVTableUse, 4> VTables; 11352 ExternalSource->ReadUsedVTables(VTables); 11353 SmallVector<VTableUse, 4> NewUses; 11354 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 11355 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 11356 = VTablesUsed.find(VTables[I].Record); 11357 // Even if a definition wasn't required before, it may be required now. 11358 if (Pos != VTablesUsed.end()) { 11359 if (!Pos->second && VTables[I].DefinitionRequired) 11360 Pos->second = true; 11361 continue; 11362 } 11363 11364 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 11365 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 11366 } 11367 11368 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 11369} 11370 11371void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 11372 bool DefinitionRequired) { 11373 // Ignore any vtable uses in unevaluated operands or for classes that do 11374 // not have a vtable. 11375 if (!Class->isDynamicClass() || Class->isDependentContext() || 11376 CurContext->isDependentContext() || 11377 ExprEvalContexts.back().Context == Unevaluated) 11378 return; 11379 11380 // Try to insert this class into the map. 11381 LoadExternalVTableUses(); 11382 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 11383 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 11384 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 11385 if (!Pos.second) { 11386 // If we already had an entry, check to see if we are promoting this vtable 11387 // to required a definition. If so, we need to reappend to the VTableUses 11388 // list, since we may have already processed the first entry. 11389 if (DefinitionRequired && !Pos.first->second) { 11390 Pos.first->second = true; 11391 } else { 11392 // Otherwise, we can early exit. 11393 return; 11394 } 11395 } 11396 11397 // Local classes need to have their virtual members marked 11398 // immediately. For all other classes, we mark their virtual members 11399 // at the end of the translation unit. 11400 if (Class->isLocalClass()) 11401 MarkVirtualMembersReferenced(Loc, Class); 11402 else 11403 VTableUses.push_back(std::make_pair(Class, Loc)); 11404} 11405 11406bool Sema::DefineUsedVTables() { 11407 LoadExternalVTableUses(); 11408 if (VTableUses.empty()) 11409 return false; 11410 11411 // Note: The VTableUses vector could grow as a result of marking 11412 // the members of a class as "used", so we check the size each 11413 // time through the loop and prefer indices (which are stable) to 11414 // iterators (which are not). 11415 bool DefinedAnything = false; 11416 for (unsigned I = 0; I != VTableUses.size(); ++I) { 11417 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 11418 if (!Class) 11419 continue; 11420 11421 SourceLocation Loc = VTableUses[I].second; 11422 11423 bool DefineVTable = true; 11424 11425 // If this class has a key function, but that key function is 11426 // defined in another translation unit, we don't need to emit the 11427 // vtable even though we're using it. 11428 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 11429 if (KeyFunction && !KeyFunction->hasBody()) { 11430 switch (KeyFunction->getTemplateSpecializationKind()) { 11431 case TSK_Undeclared: 11432 case TSK_ExplicitSpecialization: 11433 case TSK_ExplicitInstantiationDeclaration: 11434 // The key function is in another translation unit. 11435 DefineVTable = false; 11436 break; 11437 11438 case TSK_ExplicitInstantiationDefinition: 11439 case TSK_ImplicitInstantiation: 11440 // We will be instantiating the key function. 11441 break; 11442 } 11443 } else if (!KeyFunction) { 11444 // If we have a class with no key function that is the subject 11445 // of an explicit instantiation declaration, suppress the 11446 // vtable; it will live with the explicit instantiation 11447 // definition. 11448 bool IsExplicitInstantiationDeclaration 11449 = Class->getTemplateSpecializationKind() 11450 == TSK_ExplicitInstantiationDeclaration; 11451 for (TagDecl::redecl_iterator R = Class->redecls_begin(), 11452 REnd = Class->redecls_end(); 11453 R != REnd; ++R) { 11454 TemplateSpecializationKind TSK 11455 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind(); 11456 if (TSK == TSK_ExplicitInstantiationDeclaration) 11457 IsExplicitInstantiationDeclaration = true; 11458 else if (TSK == TSK_ExplicitInstantiationDefinition) { 11459 IsExplicitInstantiationDeclaration = false; 11460 break; 11461 } 11462 } 11463 11464 if (IsExplicitInstantiationDeclaration) 11465 DefineVTable = false; 11466 } 11467 11468 // The exception specifications for all virtual members may be needed even 11469 // if we are not providing an authoritative form of the vtable in this TU. 11470 // We may choose to emit it available_externally anyway. 11471 if (!DefineVTable) { 11472 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 11473 continue; 11474 } 11475 11476 // Mark all of the virtual members of this class as referenced, so 11477 // that we can build a vtable. Then, tell the AST consumer that a 11478 // vtable for this class is required. 11479 DefinedAnything = true; 11480 MarkVirtualMembersReferenced(Loc, Class); 11481 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 11482 Consumer.HandleVTable(Class, VTablesUsed[Canonical]); 11483 11484 // Optionally warn if we're emitting a weak vtable. 11485 if (Class->hasExternalLinkage() && 11486 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) { 11487 const FunctionDecl *KeyFunctionDef = 0; 11488 if (!KeyFunction || 11489 (KeyFunction->hasBody(KeyFunctionDef) && 11490 KeyFunctionDef->isInlined())) 11491 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() == 11492 TSK_ExplicitInstantiationDefinition 11493 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable) 11494 << Class; 11495 } 11496 } 11497 VTableUses.clear(); 11498 11499 return DefinedAnything; 11500} 11501 11502void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 11503 const CXXRecordDecl *RD) { 11504 for (CXXRecordDecl::method_iterator I = RD->method_begin(), 11505 E = RD->method_end(); I != E; ++I) 11506 if ((*I)->isVirtual() && !(*I)->isPure()) 11507 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>()); 11508} 11509 11510void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 11511 const CXXRecordDecl *RD) { 11512 // Mark all functions which will appear in RD's vtable as used. 11513 CXXFinalOverriderMap FinalOverriders; 11514 RD->getFinalOverriders(FinalOverriders); 11515 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 11516 E = FinalOverriders.end(); 11517 I != E; ++I) { 11518 for (OverridingMethods::const_iterator OI = I->second.begin(), 11519 OE = I->second.end(); 11520 OI != OE; ++OI) { 11521 assert(OI->second.size() > 0 && "no final overrider"); 11522 CXXMethodDecl *Overrider = OI->second.front().Method; 11523 11524 // C++ [basic.def.odr]p2: 11525 // [...] A virtual member function is used if it is not pure. [...] 11526 if (!Overrider->isPure()) 11527 MarkFunctionReferenced(Loc, Overrider); 11528 } 11529 } 11530 11531 // Only classes that have virtual bases need a VTT. 11532 if (RD->getNumVBases() == 0) 11533 return; 11534 11535 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(), 11536 e = RD->bases_end(); i != e; ++i) { 11537 const CXXRecordDecl *Base = 11538 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl()); 11539 if (Base->getNumVBases() == 0) 11540 continue; 11541 MarkVirtualMembersReferenced(Loc, Base); 11542 } 11543} 11544 11545/// SetIvarInitializers - This routine builds initialization ASTs for the 11546/// Objective-C implementation whose ivars need be initialized. 11547void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 11548 if (!getLangOpts().CPlusPlus) 11549 return; 11550 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 11551 SmallVector<ObjCIvarDecl*, 8> ivars; 11552 CollectIvarsToConstructOrDestruct(OID, ivars); 11553 if (ivars.empty()) 11554 return; 11555 SmallVector<CXXCtorInitializer*, 32> AllToInit; 11556 for (unsigned i = 0; i < ivars.size(); i++) { 11557 FieldDecl *Field = ivars[i]; 11558 if (Field->isInvalidDecl()) 11559 continue; 11560 11561 CXXCtorInitializer *Member; 11562 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 11563 InitializationKind InitKind = 11564 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 11565 11566 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0); 11567 ExprResult MemberInit = 11568 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg()); 11569 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 11570 // Note, MemberInit could actually come back empty if no initialization 11571 // is required (e.g., because it would call a trivial default constructor) 11572 if (!MemberInit.get() || MemberInit.isInvalid()) 11573 continue; 11574 11575 Member = 11576 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 11577 SourceLocation(), 11578 MemberInit.takeAs<Expr>(), 11579 SourceLocation()); 11580 AllToInit.push_back(Member); 11581 11582 // Be sure that the destructor is accessible and is marked as referenced. 11583 if (const RecordType *RecordTy 11584 = Context.getBaseElementType(Field->getType()) 11585 ->getAs<RecordType>()) { 11586 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 11587 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 11588 MarkFunctionReferenced(Field->getLocation(), Destructor); 11589 CheckDestructorAccess(Field->getLocation(), Destructor, 11590 PDiag(diag::err_access_dtor_ivar) 11591 << Context.getBaseElementType(Field->getType())); 11592 } 11593 } 11594 } 11595 ObjCImplementation->setIvarInitializers(Context, 11596 AllToInit.data(), AllToInit.size()); 11597 } 11598} 11599 11600static 11601void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 11602 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid, 11603 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid, 11604 llvm::SmallSet<CXXConstructorDecl*, 4> &Current, 11605 Sema &S) { 11606 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(), 11607 CE = Current.end(); 11608 if (Ctor->isInvalidDecl()) 11609 return; 11610 11611 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 11612 11613 // Target may not be determinable yet, for instance if this is a dependent 11614 // call in an uninstantiated template. 11615 if (Target) { 11616 const FunctionDecl *FNTarget = 0; 11617 (void)Target->hasBody(FNTarget); 11618 Target = const_cast<CXXConstructorDecl*>( 11619 cast_or_null<CXXConstructorDecl>(FNTarget)); 11620 } 11621 11622 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 11623 // Avoid dereferencing a null pointer here. 11624 *TCanonical = Target ? Target->getCanonicalDecl() : 0; 11625 11626 if (!Current.insert(Canonical)) 11627 return; 11628 11629 // We know that beyond here, we aren't chaining into a cycle. 11630 if (!Target || !Target->isDelegatingConstructor() || 11631 Target->isInvalidDecl() || Valid.count(TCanonical)) { 11632 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI) 11633 Valid.insert(*CI); 11634 Current.clear(); 11635 // We've hit a cycle. 11636 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 11637 Current.count(TCanonical)) { 11638 // If we haven't diagnosed this cycle yet, do so now. 11639 if (!Invalid.count(TCanonical)) { 11640 S.Diag((*Ctor->init_begin())->getSourceLocation(), 11641 diag::warn_delegating_ctor_cycle) 11642 << Ctor; 11643 11644 // Don't add a note for a function delegating directly to itself. 11645 if (TCanonical != Canonical) 11646 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 11647 11648 CXXConstructorDecl *C = Target; 11649 while (C->getCanonicalDecl() != Canonical) { 11650 const FunctionDecl *FNTarget = 0; 11651 (void)C->getTargetConstructor()->hasBody(FNTarget); 11652 assert(FNTarget && "Ctor cycle through bodiless function"); 11653 11654 C = const_cast<CXXConstructorDecl*>( 11655 cast<CXXConstructorDecl>(FNTarget)); 11656 S.Diag(C->getLocation(), diag::note_which_delegates_to); 11657 } 11658 } 11659 11660 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI) 11661 Invalid.insert(*CI); 11662 Current.clear(); 11663 } else { 11664 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 11665 } 11666} 11667 11668 11669void Sema::CheckDelegatingCtorCycles() { 11670 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 11671 11672 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(), 11673 CE = Current.end(); 11674 11675 for (DelegatingCtorDeclsType::iterator 11676 I = DelegatingCtorDecls.begin(ExternalSource), 11677 E = DelegatingCtorDecls.end(); 11678 I != E; ++I) 11679 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 11680 11681 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI) 11682 (*CI)->setInvalidDecl(); 11683} 11684 11685namespace { 11686 /// \brief AST visitor that finds references to the 'this' expression. 11687 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 11688 Sema &S; 11689 11690 public: 11691 explicit FindCXXThisExpr(Sema &S) : S(S) { } 11692 11693 bool VisitCXXThisExpr(CXXThisExpr *E) { 11694 S.Diag(E->getLocation(), diag::err_this_static_member_func) 11695 << E->isImplicit(); 11696 return false; 11697 } 11698 }; 11699} 11700 11701bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 11702 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 11703 if (!TSInfo) 11704 return false; 11705 11706 TypeLoc TL = TSInfo->getTypeLoc(); 11707 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 11708 if (!ProtoTL) 11709 return false; 11710 11711 // C++11 [expr.prim.general]p3: 11712 // [The expression this] shall not appear before the optional 11713 // cv-qualifier-seq and it shall not appear within the declaration of a 11714 // static member function (although its type and value category are defined 11715 // within a static member function as they are within a non-static member 11716 // function). [ Note: this is because declaration matching does not occur 11717 // until the complete declarator is known. - end note ] 11718 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 11719 FindCXXThisExpr Finder(*this); 11720 11721 // If the return type came after the cv-qualifier-seq, check it now. 11722 if (Proto->hasTrailingReturn() && 11723 !Finder.TraverseTypeLoc(ProtoTL.getResultLoc())) 11724 return true; 11725 11726 // Check the exception specification. 11727 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 11728 return true; 11729 11730 return checkThisInStaticMemberFunctionAttributes(Method); 11731} 11732 11733bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 11734 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 11735 if (!TSInfo) 11736 return false; 11737 11738 TypeLoc TL = TSInfo->getTypeLoc(); 11739 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 11740 if (!ProtoTL) 11741 return false; 11742 11743 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 11744 FindCXXThisExpr Finder(*this); 11745 11746 switch (Proto->getExceptionSpecType()) { 11747 case EST_Uninstantiated: 11748 case EST_Unevaluated: 11749 case EST_BasicNoexcept: 11750 case EST_DynamicNone: 11751 case EST_MSAny: 11752 case EST_None: 11753 break; 11754 11755 case EST_ComputedNoexcept: 11756 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 11757 return true; 11758 11759 case EST_Dynamic: 11760 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(), 11761 EEnd = Proto->exception_end(); 11762 E != EEnd; ++E) { 11763 if (!Finder.TraverseType(*E)) 11764 return true; 11765 } 11766 break; 11767 } 11768 11769 return false; 11770} 11771 11772bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 11773 FindCXXThisExpr Finder(*this); 11774 11775 // Check attributes. 11776 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end(); 11777 A != AEnd; ++A) { 11778 // FIXME: This should be emitted by tblgen. 11779 Expr *Arg = 0; 11780 ArrayRef<Expr *> Args; 11781 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A)) 11782 Arg = G->getArg(); 11783 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A)) 11784 Arg = G->getArg(); 11785 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A)) 11786 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size()); 11787 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A)) 11788 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size()); 11789 else if (ExclusiveLockFunctionAttr *ELF 11790 = dyn_cast<ExclusiveLockFunctionAttr>(*A)) 11791 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size()); 11792 else if (SharedLockFunctionAttr *SLF 11793 = dyn_cast<SharedLockFunctionAttr>(*A)) 11794 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size()); 11795 else if (ExclusiveTrylockFunctionAttr *ETLF 11796 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) { 11797 Arg = ETLF->getSuccessValue(); 11798 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size()); 11799 } else if (SharedTrylockFunctionAttr *STLF 11800 = dyn_cast<SharedTrylockFunctionAttr>(*A)) { 11801 Arg = STLF->getSuccessValue(); 11802 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size()); 11803 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A)) 11804 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size()); 11805 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A)) 11806 Arg = LR->getArg(); 11807 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A)) 11808 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size()); 11809 else if (ExclusiveLocksRequiredAttr *ELR 11810 = dyn_cast<ExclusiveLocksRequiredAttr>(*A)) 11811 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size()); 11812 else if (SharedLocksRequiredAttr *SLR 11813 = dyn_cast<SharedLocksRequiredAttr>(*A)) 11814 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size()); 11815 11816 if (Arg && !Finder.TraverseStmt(Arg)) 11817 return true; 11818 11819 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 11820 if (!Finder.TraverseStmt(Args[I])) 11821 return true; 11822 } 11823 } 11824 11825 return false; 11826} 11827 11828void 11829Sema::checkExceptionSpecification(ExceptionSpecificationType EST, 11830 ArrayRef<ParsedType> DynamicExceptions, 11831 ArrayRef<SourceRange> DynamicExceptionRanges, 11832 Expr *NoexceptExpr, 11833 SmallVectorImpl<QualType> &Exceptions, 11834 FunctionProtoType::ExtProtoInfo &EPI) { 11835 Exceptions.clear(); 11836 EPI.ExceptionSpecType = EST; 11837 if (EST == EST_Dynamic) { 11838 Exceptions.reserve(DynamicExceptions.size()); 11839 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 11840 // FIXME: Preserve type source info. 11841 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 11842 11843 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 11844 collectUnexpandedParameterPacks(ET, Unexpanded); 11845 if (!Unexpanded.empty()) { 11846 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(), 11847 UPPC_ExceptionType, 11848 Unexpanded); 11849 continue; 11850 } 11851 11852 // Check that the type is valid for an exception spec, and 11853 // drop it if not. 11854 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 11855 Exceptions.push_back(ET); 11856 } 11857 EPI.NumExceptions = Exceptions.size(); 11858 EPI.Exceptions = Exceptions.data(); 11859 return; 11860 } 11861 11862 if (EST == EST_ComputedNoexcept) { 11863 // If an error occurred, there's no expression here. 11864 if (NoexceptExpr) { 11865 assert((NoexceptExpr->isTypeDependent() || 11866 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 11867 Context.BoolTy) && 11868 "Parser should have made sure that the expression is boolean"); 11869 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 11870 EPI.ExceptionSpecType = EST_BasicNoexcept; 11871 return; 11872 } 11873 11874 if (!NoexceptExpr->isValueDependent()) 11875 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0, 11876 diag::err_noexcept_needs_constant_expression, 11877 /*AllowFold*/ false).take(); 11878 EPI.NoexceptExpr = NoexceptExpr; 11879 } 11880 return; 11881 } 11882} 11883 11884/// IdentifyCUDATarget - Determine the CUDA compilation target for this function 11885Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) { 11886 // Implicitly declared functions (e.g. copy constructors) are 11887 // __host__ __device__ 11888 if (D->isImplicit()) 11889 return CFT_HostDevice; 11890 11891 if (D->hasAttr<CUDAGlobalAttr>()) 11892 return CFT_Global; 11893 11894 if (D->hasAttr<CUDADeviceAttr>()) { 11895 if (D->hasAttr<CUDAHostAttr>()) 11896 return CFT_HostDevice; 11897 else 11898 return CFT_Device; 11899 } 11900 11901 return CFT_Host; 11902} 11903 11904bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget, 11905 CUDAFunctionTarget CalleeTarget) { 11906 // CUDA B.1.1 "The __device__ qualifier declares a function that is... 11907 // Callable from the device only." 11908 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device) 11909 return true; 11910 11911 // CUDA B.1.2 "The __global__ qualifier declares a function that is... 11912 // Callable from the host only." 11913 // CUDA B.1.3 "The __host__ qualifier declares a function that is... 11914 // Callable from the host only." 11915 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) && 11916 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global)) 11917 return true; 11918 11919 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice) 11920 return true; 11921 11922 return false; 11923} 11924