SemaDeclCXX.cpp revision 1d87fbaeea4a9fbbd73b3a53641f59f1673098e5
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 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 356 DeclaratorChunk &chunk = D.getTypeObject(i); 357 if (chunk.Kind == DeclaratorChunk::Function) { 358 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) { 359 ParmVarDecl *Param = 360 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param); 361 if (Param->hasUnparsedDefaultArg()) { 362 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens; 363 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 364 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation()); 365 delete Toks; 366 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0; 367 } else if (Param->getDefaultArg()) { 368 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 369 << Param->getDefaultArg()->getSourceRange(); 370 Param->setDefaultArg(0); 371 } 372 } 373 } 374 } 375} 376 377/// MergeCXXFunctionDecl - Merge two declarations of the same C++ 378/// function, once we already know that they have the same 379/// type. Subroutine of MergeFunctionDecl. Returns true if there was an 380/// error, false otherwise. 381bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 382 Scope *S) { 383 bool Invalid = false; 384 385 // C++ [dcl.fct.default]p4: 386 // For non-template functions, default arguments can be added in 387 // later declarations of a function in the same 388 // scope. Declarations in different scopes have completely 389 // distinct sets of default arguments. That is, declarations in 390 // inner scopes do not acquire default arguments from 391 // declarations in outer scopes, and vice versa. In a given 392 // function declaration, all parameters subsequent to a 393 // parameter with a default argument shall have default 394 // arguments supplied in this or previous declarations. A 395 // default argument shall not be redefined by a later 396 // declaration (not even to the same value). 397 // 398 // C++ [dcl.fct.default]p6: 399 // Except for member functions of class templates, the default arguments 400 // in a member function definition that appears outside of the class 401 // definition are added to the set of default arguments provided by the 402 // member function declaration in the class definition. 403 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 404 ParmVarDecl *OldParam = Old->getParamDecl(p); 405 ParmVarDecl *NewParam = New->getParamDecl(p); 406 407 bool OldParamHasDfl = OldParam->hasDefaultArg(); 408 bool NewParamHasDfl = NewParam->hasDefaultArg(); 409 410 NamedDecl *ND = Old; 411 if (S && !isDeclInScope(ND, New->getDeclContext(), S)) 412 // Ignore default parameters of old decl if they are not in 413 // the same scope. 414 OldParamHasDfl = false; 415 416 if (OldParamHasDfl && NewParamHasDfl) { 417 418 unsigned DiagDefaultParamID = 419 diag::err_param_default_argument_redefinition; 420 421 // MSVC accepts that default parameters be redefined for member functions 422 // of template class. The new default parameter's value is ignored. 423 Invalid = true; 424 if (getLangOpts().MicrosoftExt) { 425 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New); 426 if (MD && MD->getParent()->getDescribedClassTemplate()) { 427 // Merge the old default argument into the new parameter. 428 NewParam->setHasInheritedDefaultArg(); 429 if (OldParam->hasUninstantiatedDefaultArg()) 430 NewParam->setUninstantiatedDefaultArg( 431 OldParam->getUninstantiatedDefaultArg()); 432 else 433 NewParam->setDefaultArg(OldParam->getInit()); 434 DiagDefaultParamID = diag::warn_param_default_argument_redefinition; 435 Invalid = false; 436 } 437 } 438 439 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 440 // hint here. Alternatively, we could walk the type-source information 441 // for NewParam to find the last source location in the type... but it 442 // isn't worth the effort right now. This is the kind of test case that 443 // is hard to get right: 444 // int f(int); 445 // void g(int (*fp)(int) = f); 446 // void g(int (*fp)(int) = &f); 447 Diag(NewParam->getLocation(), DiagDefaultParamID) 448 << NewParam->getDefaultArgRange(); 449 450 // Look for the function declaration where the default argument was 451 // actually written, which may be a declaration prior to Old. 452 for (FunctionDecl *Older = Old->getPreviousDecl(); 453 Older; Older = Older->getPreviousDecl()) { 454 if (!Older->getParamDecl(p)->hasDefaultArg()) 455 break; 456 457 OldParam = Older->getParamDecl(p); 458 } 459 460 Diag(OldParam->getLocation(), diag::note_previous_definition) 461 << OldParam->getDefaultArgRange(); 462 } else if (OldParamHasDfl) { 463 // Merge the old default argument into the new parameter. 464 // It's important to use getInit() here; getDefaultArg() 465 // strips off any top-level ExprWithCleanups. 466 NewParam->setHasInheritedDefaultArg(); 467 if (OldParam->hasUninstantiatedDefaultArg()) 468 NewParam->setUninstantiatedDefaultArg( 469 OldParam->getUninstantiatedDefaultArg()); 470 else 471 NewParam->setDefaultArg(OldParam->getInit()); 472 } else if (NewParamHasDfl) { 473 if (New->getDescribedFunctionTemplate()) { 474 // Paragraph 4, quoted above, only applies to non-template functions. 475 Diag(NewParam->getLocation(), 476 diag::err_param_default_argument_template_redecl) 477 << NewParam->getDefaultArgRange(); 478 Diag(Old->getLocation(), diag::note_template_prev_declaration) 479 << false; 480 } else if (New->getTemplateSpecializationKind() 481 != TSK_ImplicitInstantiation && 482 New->getTemplateSpecializationKind() != TSK_Undeclared) { 483 // C++ [temp.expr.spec]p21: 484 // Default function arguments shall not be specified in a declaration 485 // or a definition for one of the following explicit specializations: 486 // - the explicit specialization of a function template; 487 // - the explicit specialization of a member function template; 488 // - the explicit specialization of a member function of a class 489 // template where the class template specialization to which the 490 // member function specialization belongs is implicitly 491 // instantiated. 492 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 493 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 494 << New->getDeclName() 495 << NewParam->getDefaultArgRange(); 496 } else if (New->getDeclContext()->isDependentContext()) { 497 // C++ [dcl.fct.default]p6 (DR217): 498 // Default arguments for a member function of a class template shall 499 // be specified on the initial declaration of the member function 500 // within the class template. 501 // 502 // Reading the tea leaves a bit in DR217 and its reference to DR205 503 // leads me to the conclusion that one cannot add default function 504 // arguments for an out-of-line definition of a member function of a 505 // dependent type. 506 int WhichKind = 2; 507 if (CXXRecordDecl *Record 508 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 509 if (Record->getDescribedClassTemplate()) 510 WhichKind = 0; 511 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 512 WhichKind = 1; 513 else 514 WhichKind = 2; 515 } 516 517 Diag(NewParam->getLocation(), 518 diag::err_param_default_argument_member_template_redecl) 519 << WhichKind 520 << NewParam->getDefaultArgRange(); 521 } 522 } 523 } 524 525 // DR1344: If a default argument is added outside a class definition and that 526 // default argument makes the function a special member function, the program 527 // is ill-formed. This can only happen for constructors. 528 if (isa<CXXConstructorDecl>(New) && 529 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 530 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 531 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 532 if (NewSM != OldSM) { 533 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 534 assert(NewParam->hasDefaultArg()); 535 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 536 << NewParam->getDefaultArgRange() << NewSM; 537 Diag(Old->getLocation(), diag::note_previous_declaration); 538 } 539 } 540 541 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 542 // template has a constexpr specifier then all its declarations shall 543 // contain the constexpr specifier. 544 if (New->isConstexpr() != Old->isConstexpr()) { 545 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 546 << New << New->isConstexpr(); 547 Diag(Old->getLocation(), diag::note_previous_declaration); 548 Invalid = true; 549 } 550 551 if (CheckEquivalentExceptionSpec(Old, New)) 552 Invalid = true; 553 554 return Invalid; 555} 556 557/// \brief Merge the exception specifications of two variable declarations. 558/// 559/// This is called when there's a redeclaration of a VarDecl. The function 560/// checks if the redeclaration might have an exception specification and 561/// validates compatibility and merges the specs if necessary. 562void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 563 // Shortcut if exceptions are disabled. 564 if (!getLangOpts().CXXExceptions) 565 return; 566 567 assert(Context.hasSameType(New->getType(), Old->getType()) && 568 "Should only be called if types are otherwise the same."); 569 570 QualType NewType = New->getType(); 571 QualType OldType = Old->getType(); 572 573 // We're only interested in pointers and references to functions, as well 574 // as pointers to member functions. 575 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 576 NewType = R->getPointeeType(); 577 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 578 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 579 NewType = P->getPointeeType(); 580 OldType = OldType->getAs<PointerType>()->getPointeeType(); 581 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 582 NewType = M->getPointeeType(); 583 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 584 } 585 586 if (!NewType->isFunctionProtoType()) 587 return; 588 589 // There's lots of special cases for functions. For function pointers, system 590 // libraries are hopefully not as broken so that we don't need these 591 // workarounds. 592 if (CheckEquivalentExceptionSpec( 593 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 594 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 595 New->setInvalidDecl(); 596 } 597} 598 599/// CheckCXXDefaultArguments - Verify that the default arguments for a 600/// function declaration are well-formed according to C++ 601/// [dcl.fct.default]. 602void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 603 unsigned NumParams = FD->getNumParams(); 604 unsigned p; 605 606 bool IsLambda = FD->getOverloadedOperator() == OO_Call && 607 isa<CXXMethodDecl>(FD) && 608 cast<CXXMethodDecl>(FD)->getParent()->isLambda(); 609 610 // Find first parameter with a default argument 611 for (p = 0; p < NumParams; ++p) { 612 ParmVarDecl *Param = FD->getParamDecl(p); 613 if (Param->hasDefaultArg()) { 614 // C++11 [expr.prim.lambda]p5: 615 // [...] Default arguments (8.3.6) shall not be specified in the 616 // parameter-declaration-clause of a lambda-declarator. 617 // 618 // FIXME: Core issue 974 strikes this sentence, we only provide an 619 // extension warning. 620 if (IsLambda) 621 Diag(Param->getLocation(), diag::ext_lambda_default_arguments) 622 << Param->getDefaultArgRange(); 623 break; 624 } 625 } 626 627 // C++ [dcl.fct.default]p4: 628 // In a given function declaration, all parameters 629 // subsequent to a parameter with a default argument shall 630 // have default arguments supplied in this or previous 631 // declarations. A default argument shall not be redefined 632 // by a later declaration (not even to the same value). 633 unsigned LastMissingDefaultArg = 0; 634 for (; p < NumParams; ++p) { 635 ParmVarDecl *Param = FD->getParamDecl(p); 636 if (!Param->hasDefaultArg()) { 637 if (Param->isInvalidDecl()) 638 /* We already complained about this parameter. */; 639 else if (Param->getIdentifier()) 640 Diag(Param->getLocation(), 641 diag::err_param_default_argument_missing_name) 642 << Param->getIdentifier(); 643 else 644 Diag(Param->getLocation(), 645 diag::err_param_default_argument_missing); 646 647 LastMissingDefaultArg = p; 648 } 649 } 650 651 if (LastMissingDefaultArg > 0) { 652 // Some default arguments were missing. Clear out all of the 653 // default arguments up to (and including) the last missing 654 // default argument, so that we leave the function parameters 655 // in a semantically valid state. 656 for (p = 0; p <= LastMissingDefaultArg; ++p) { 657 ParmVarDecl *Param = FD->getParamDecl(p); 658 if (Param->hasDefaultArg()) { 659 Param->setDefaultArg(0); 660 } 661 } 662 } 663} 664 665// CheckConstexprParameterTypes - Check whether a function's parameter types 666// are all literal types. If so, return true. If not, produce a suitable 667// diagnostic and return false. 668static bool CheckConstexprParameterTypes(Sema &SemaRef, 669 const FunctionDecl *FD) { 670 unsigned ArgIndex = 0; 671 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 672 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(), 673 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) { 674 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 675 SourceLocation ParamLoc = PD->getLocation(); 676 if (!(*i)->isDependentType() && 677 SemaRef.RequireLiteralType(ParamLoc, *i, 678 diag::err_constexpr_non_literal_param, 679 ArgIndex+1, PD->getSourceRange(), 680 isa<CXXConstructorDecl>(FD))) 681 return false; 682 } 683 return true; 684} 685 686/// \brief Get diagnostic %select index for tag kind for 687/// record diagnostic message. 688/// WARNING: Indexes apply to particular diagnostics only! 689/// 690/// \returns diagnostic %select index. 691static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 692 switch (Tag) { 693 case TTK_Struct: return 0; 694 case TTK_Interface: return 1; 695 case TTK_Class: return 2; 696 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 697 } 698} 699 700// CheckConstexprFunctionDecl - Check whether a function declaration satisfies 701// the requirements of a constexpr function definition or a constexpr 702// constructor definition. If so, return true. If not, produce appropriate 703// diagnostics and return false. 704// 705// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 706bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) { 707 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 708 if (MD && MD->isInstance()) { 709 // C++11 [dcl.constexpr]p4: 710 // The definition of a constexpr constructor shall satisfy the following 711 // constraints: 712 // - the class shall not have any virtual base classes; 713 const CXXRecordDecl *RD = MD->getParent(); 714 if (RD->getNumVBases()) { 715 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 716 << isa<CXXConstructorDecl>(NewFD) 717 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 718 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(), 719 E = RD->vbases_end(); I != E; ++I) 720 Diag(I->getLocStart(), 721 diag::note_constexpr_virtual_base_here) << I->getSourceRange(); 722 return false; 723 } 724 } 725 726 if (!isa<CXXConstructorDecl>(NewFD)) { 727 // C++11 [dcl.constexpr]p3: 728 // The definition of a constexpr function shall satisfy the following 729 // constraints: 730 // - it shall not be virtual; 731 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 732 if (Method && Method->isVirtual()) { 733 Diag(NewFD->getLocation(), diag::err_constexpr_virtual); 734 735 // If it's not obvious why this function is virtual, find an overridden 736 // function which uses the 'virtual' keyword. 737 const CXXMethodDecl *WrittenVirtual = Method; 738 while (!WrittenVirtual->isVirtualAsWritten()) 739 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 740 if (WrittenVirtual != Method) 741 Diag(WrittenVirtual->getLocation(), 742 diag::note_overridden_virtual_function); 743 return false; 744 } 745 746 // - its return type shall be a literal type; 747 QualType RT = NewFD->getResultType(); 748 if (!RT->isDependentType() && 749 RequireLiteralType(NewFD->getLocation(), RT, 750 diag::err_constexpr_non_literal_return)) 751 return false; 752 } 753 754 // - each of its parameter types shall be a literal type; 755 if (!CheckConstexprParameterTypes(*this, NewFD)) 756 return false; 757 758 return true; 759} 760 761/// Check the given declaration statement is legal within a constexpr function 762/// body. C++0x [dcl.constexpr]p3,p4. 763/// 764/// \return true if the body is OK, false if we have diagnosed a problem. 765static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 766 DeclStmt *DS) { 767 // C++0x [dcl.constexpr]p3 and p4: 768 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 769 // contain only 770 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(), 771 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) { 772 switch ((*DclIt)->getKind()) { 773 case Decl::StaticAssert: 774 case Decl::Using: 775 case Decl::UsingShadow: 776 case Decl::UsingDirective: 777 case Decl::UnresolvedUsingTypename: 778 // - static_assert-declarations 779 // - using-declarations, 780 // - using-directives, 781 continue; 782 783 case Decl::Typedef: 784 case Decl::TypeAlias: { 785 // - typedef declarations and alias-declarations that do not define 786 // classes or enumerations, 787 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt); 788 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 789 // Don't allow variably-modified types in constexpr functions. 790 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 791 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 792 << TL.getSourceRange() << TL.getType() 793 << isa<CXXConstructorDecl>(Dcl); 794 return false; 795 } 796 continue; 797 } 798 799 case Decl::Enum: 800 case Decl::CXXRecord: 801 // As an extension, we allow the declaration (but not the definition) of 802 // classes and enumerations in all declarations, not just in typedef and 803 // alias declarations. 804 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) { 805 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition) 806 << isa<CXXConstructorDecl>(Dcl); 807 return false; 808 } 809 continue; 810 811 case Decl::Var: 812 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration) 813 << isa<CXXConstructorDecl>(Dcl); 814 return false; 815 816 default: 817 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt) 818 << isa<CXXConstructorDecl>(Dcl); 819 return false; 820 } 821 } 822 823 return true; 824} 825 826/// Check that the given field is initialized within a constexpr constructor. 827/// 828/// \param Dcl The constexpr constructor being checked. 829/// \param Field The field being checked. This may be a member of an anonymous 830/// struct or union nested within the class being checked. 831/// \param Inits All declarations, including anonymous struct/union members and 832/// indirect members, for which any initialization was provided. 833/// \param Diagnosed Set to true if an error is produced. 834static void CheckConstexprCtorInitializer(Sema &SemaRef, 835 const FunctionDecl *Dcl, 836 FieldDecl *Field, 837 llvm::SmallSet<Decl*, 16> &Inits, 838 bool &Diagnosed) { 839 if (Field->isUnnamedBitfield()) 840 return; 841 842 if (Field->isAnonymousStructOrUnion() && 843 Field->getType()->getAsCXXRecordDecl()->isEmpty()) 844 return; 845 846 if (!Inits.count(Field)) { 847 if (!Diagnosed) { 848 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init); 849 Diagnosed = true; 850 } 851 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init); 852 } else if (Field->isAnonymousStructOrUnion()) { 853 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 854 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end(); 855 I != E; ++I) 856 // If an anonymous union contains an anonymous struct of which any member 857 // is initialized, all members must be initialized. 858 if (!RD->isUnion() || Inits.count(*I)) 859 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed); 860 } 861} 862 863/// Check the body for the given constexpr function declaration only contains 864/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 865/// 866/// \return true if the body is OK, false if we have diagnosed a problem. 867bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) { 868 if (isa<CXXTryStmt>(Body)) { 869 // C++11 [dcl.constexpr]p3: 870 // The definition of a constexpr function shall satisfy the following 871 // constraints: [...] 872 // - its function-body shall be = delete, = default, or a 873 // compound-statement 874 // 875 // C++11 [dcl.constexpr]p4: 876 // In the definition of a constexpr constructor, [...] 877 // - its function-body shall not be a function-try-block; 878 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block) 879 << isa<CXXConstructorDecl>(Dcl); 880 return false; 881 } 882 883 // - its function-body shall be [...] a compound-statement that contains only 884 CompoundStmt *CompBody = cast<CompoundStmt>(Body); 885 886 SmallVector<SourceLocation, 4> ReturnStmts; 887 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(), 888 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) { 889 switch ((*BodyIt)->getStmtClass()) { 890 case Stmt::NullStmtClass: 891 // - null statements, 892 continue; 893 894 case Stmt::DeclStmtClass: 895 // - static_assert-declarations 896 // - using-declarations, 897 // - using-directives, 898 // - typedef declarations and alias-declarations that do not define 899 // classes or enumerations, 900 if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt))) 901 return false; 902 continue; 903 904 case Stmt::ReturnStmtClass: 905 // - and exactly one return statement; 906 if (isa<CXXConstructorDecl>(Dcl)) 907 break; 908 909 ReturnStmts.push_back((*BodyIt)->getLocStart()); 910 continue; 911 912 default: 913 break; 914 } 915 916 Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt) 917 << isa<CXXConstructorDecl>(Dcl); 918 return false; 919 } 920 921 if (const CXXConstructorDecl *Constructor 922 = dyn_cast<CXXConstructorDecl>(Dcl)) { 923 const CXXRecordDecl *RD = Constructor->getParent(); 924 // DR1359: 925 // - every non-variant non-static data member and base class sub-object 926 // shall be initialized; 927 // - if the class is a non-empty union, or for each non-empty anonymous 928 // union member of a non-union class, exactly one non-static data member 929 // shall be initialized; 930 if (RD->isUnion()) { 931 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) { 932 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init); 933 return false; 934 } 935 } else if (!Constructor->isDependentContext() && 936 !Constructor->isDelegatingConstructor()) { 937 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 938 939 // Skip detailed checking if we have enough initializers, and we would 940 // allow at most one initializer per member. 941 bool AnyAnonStructUnionMembers = false; 942 unsigned Fields = 0; 943 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 944 E = RD->field_end(); I != E; ++I, ++Fields) { 945 if (I->isAnonymousStructOrUnion()) { 946 AnyAnonStructUnionMembers = true; 947 break; 948 } 949 } 950 if (AnyAnonStructUnionMembers || 951 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 952 // Check initialization of non-static data members. Base classes are 953 // always initialized so do not need to be checked. Dependent bases 954 // might not have initializers in the member initializer list. 955 llvm::SmallSet<Decl*, 16> Inits; 956 for (CXXConstructorDecl::init_const_iterator 957 I = Constructor->init_begin(), E = Constructor->init_end(); 958 I != E; ++I) { 959 if (FieldDecl *FD = (*I)->getMember()) 960 Inits.insert(FD); 961 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember()) 962 Inits.insert(ID->chain_begin(), ID->chain_end()); 963 } 964 965 bool Diagnosed = false; 966 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 967 E = RD->field_end(); I != E; ++I) 968 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed); 969 if (Diagnosed) 970 return false; 971 } 972 } 973 } else { 974 if (ReturnStmts.empty()) { 975 Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return); 976 return false; 977 } 978 if (ReturnStmts.size() > 1) { 979 Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return); 980 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 981 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return); 982 return false; 983 } 984 } 985 986 // C++11 [dcl.constexpr]p5: 987 // if no function argument values exist such that the function invocation 988 // substitution would produce a constant expression, the program is 989 // ill-formed; no diagnostic required. 990 // C++11 [dcl.constexpr]p3: 991 // - every constructor call and implicit conversion used in initializing the 992 // return value shall be one of those allowed in a constant expression. 993 // C++11 [dcl.constexpr]p4: 994 // - every constructor involved in initializing non-static data members and 995 // base class sub-objects shall be a constexpr constructor. 996 SmallVector<PartialDiagnosticAt, 8> Diags; 997 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) { 998 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr) 999 << isa<CXXConstructorDecl>(Dcl); 1000 for (size_t I = 0, N = Diags.size(); I != N; ++I) 1001 Diag(Diags[I].first, Diags[I].second); 1002 // Don't return false here: we allow this for compatibility in 1003 // system headers. 1004 } 1005 1006 return true; 1007} 1008 1009/// isCurrentClassName - Determine whether the identifier II is the 1010/// name of the class type currently being defined. In the case of 1011/// nested classes, this will only return true if II is the name of 1012/// the innermost class. 1013bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 1014 const CXXScopeSpec *SS) { 1015 assert(getLangOpts().CPlusPlus && "No class names in C!"); 1016 1017 CXXRecordDecl *CurDecl; 1018 if (SS && SS->isSet() && !SS->isInvalid()) { 1019 DeclContext *DC = computeDeclContext(*SS, true); 1020 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 1021 } else 1022 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1023 1024 if (CurDecl && CurDecl->getIdentifier()) 1025 return &II == CurDecl->getIdentifier(); 1026 else 1027 return false; 1028} 1029 1030/// \brief Determine whether the given class is a base class of the given 1031/// class, including looking at dependent bases. 1032static bool findCircularInheritance(const CXXRecordDecl *Class, 1033 const CXXRecordDecl *Current) { 1034 SmallVector<const CXXRecordDecl*, 8> Queue; 1035 1036 Class = Class->getCanonicalDecl(); 1037 while (true) { 1038 for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(), 1039 E = Current->bases_end(); 1040 I != E; ++I) { 1041 CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 1042 if (!Base) 1043 continue; 1044 1045 Base = Base->getDefinition(); 1046 if (!Base) 1047 continue; 1048 1049 if (Base->getCanonicalDecl() == Class) 1050 return true; 1051 1052 Queue.push_back(Base); 1053 } 1054 1055 if (Queue.empty()) 1056 return false; 1057 1058 Current = Queue.back(); 1059 Queue.pop_back(); 1060 } 1061 1062 return false; 1063} 1064 1065/// \brief Check the validity of a C++ base class specifier. 1066/// 1067/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 1068/// and returns NULL otherwise. 1069CXXBaseSpecifier * 1070Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 1071 SourceRange SpecifierRange, 1072 bool Virtual, AccessSpecifier Access, 1073 TypeSourceInfo *TInfo, 1074 SourceLocation EllipsisLoc) { 1075 QualType BaseType = TInfo->getType(); 1076 1077 // C++ [class.union]p1: 1078 // A union shall not have base classes. 1079 if (Class->isUnion()) { 1080 Diag(Class->getLocation(), diag::err_base_clause_on_union) 1081 << SpecifierRange; 1082 return 0; 1083 } 1084 1085 if (EllipsisLoc.isValid() && 1086 !TInfo->getType()->containsUnexpandedParameterPack()) { 1087 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 1088 << TInfo->getTypeLoc().getSourceRange(); 1089 EllipsisLoc = SourceLocation(); 1090 } 1091 1092 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 1093 1094 if (BaseType->isDependentType()) { 1095 // Make sure that we don't have circular inheritance among our dependent 1096 // bases. For non-dependent bases, the check for completeness below handles 1097 // this. 1098 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 1099 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 1100 ((BaseDecl = BaseDecl->getDefinition()) && 1101 findCircularInheritance(Class, BaseDecl))) { 1102 Diag(BaseLoc, diag::err_circular_inheritance) 1103 << BaseType << Context.getTypeDeclType(Class); 1104 1105 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 1106 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 1107 << BaseType; 1108 1109 return 0; 1110 } 1111 } 1112 1113 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1114 Class->getTagKind() == TTK_Class, 1115 Access, TInfo, EllipsisLoc); 1116 } 1117 1118 // Base specifiers must be record types. 1119 if (!BaseType->isRecordType()) { 1120 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 1121 return 0; 1122 } 1123 1124 // C++ [class.union]p1: 1125 // A union shall not be used as a base class. 1126 if (BaseType->isUnionType()) { 1127 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 1128 return 0; 1129 } 1130 1131 // C++ [class.derived]p2: 1132 // The class-name in a base-specifier shall not be an incompletely 1133 // defined class. 1134 if (RequireCompleteType(BaseLoc, BaseType, 1135 diag::err_incomplete_base_class, SpecifierRange)) { 1136 Class->setInvalidDecl(); 1137 return 0; 1138 } 1139 1140 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 1141 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 1142 assert(BaseDecl && "Record type has no declaration"); 1143 BaseDecl = BaseDecl->getDefinition(); 1144 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 1145 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 1146 assert(CXXBaseDecl && "Base type is not a C++ type"); 1147 1148 // C++ [class]p3: 1149 // If a class is marked final and it appears as a base-type-specifier in 1150 // base-clause, the program is ill-formed. 1151 if (CXXBaseDecl->hasAttr<FinalAttr>()) { 1152 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 1153 << CXXBaseDecl->getDeclName(); 1154 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl) 1155 << CXXBaseDecl->getDeclName(); 1156 return 0; 1157 } 1158 1159 if (BaseDecl->isInvalidDecl()) 1160 Class->setInvalidDecl(); 1161 1162 // Create the base specifier. 1163 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1164 Class->getTagKind() == TTK_Class, 1165 Access, TInfo, EllipsisLoc); 1166} 1167 1168/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 1169/// one entry in the base class list of a class specifier, for 1170/// example: 1171/// class foo : public bar, virtual private baz { 1172/// 'public bar' and 'virtual private baz' are each base-specifiers. 1173BaseResult 1174Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 1175 bool Virtual, AccessSpecifier Access, 1176 ParsedType basetype, SourceLocation BaseLoc, 1177 SourceLocation EllipsisLoc) { 1178 if (!classdecl) 1179 return true; 1180 1181 AdjustDeclIfTemplate(classdecl); 1182 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 1183 if (!Class) 1184 return true; 1185 1186 TypeSourceInfo *TInfo = 0; 1187 GetTypeFromParser(basetype, &TInfo); 1188 1189 if (EllipsisLoc.isInvalid() && 1190 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 1191 UPPC_BaseType)) 1192 return true; 1193 1194 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 1195 Virtual, Access, TInfo, 1196 EllipsisLoc)) 1197 return BaseSpec; 1198 else 1199 Class->setInvalidDecl(); 1200 1201 return true; 1202} 1203 1204/// \brief Performs the actual work of attaching the given base class 1205/// specifiers to a C++ class. 1206bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 1207 unsigned NumBases) { 1208 if (NumBases == 0) 1209 return false; 1210 1211 // Used to keep track of which base types we have already seen, so 1212 // that we can properly diagnose redundant direct base types. Note 1213 // that the key is always the unqualified canonical type of the base 1214 // class. 1215 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 1216 1217 // Copy non-redundant base specifiers into permanent storage. 1218 unsigned NumGoodBases = 0; 1219 bool Invalid = false; 1220 for (unsigned idx = 0; idx < NumBases; ++idx) { 1221 QualType NewBaseType 1222 = Context.getCanonicalType(Bases[idx]->getType()); 1223 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 1224 1225 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 1226 if (KnownBase) { 1227 // C++ [class.mi]p3: 1228 // A class shall not be specified as a direct base class of a 1229 // derived class more than once. 1230 Diag(Bases[idx]->getLocStart(), 1231 diag::err_duplicate_base_class) 1232 << KnownBase->getType() 1233 << Bases[idx]->getSourceRange(); 1234 1235 // Delete the duplicate base class specifier; we're going to 1236 // overwrite its pointer later. 1237 Context.Deallocate(Bases[idx]); 1238 1239 Invalid = true; 1240 } else { 1241 // Okay, add this new base class. 1242 KnownBase = Bases[idx]; 1243 Bases[NumGoodBases++] = Bases[idx]; 1244 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 1245 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 1246 if (Class->isInterface() && 1247 (!RD->isInterface() || 1248 KnownBase->getAccessSpecifier() != AS_public)) { 1249 // The Microsoft extension __interface does not permit bases that 1250 // are not themselves public interfaces. 1251 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface) 1252 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName() 1253 << RD->getSourceRange(); 1254 Invalid = true; 1255 } 1256 if (RD->hasAttr<WeakAttr>()) 1257 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context)); 1258 } 1259 } 1260 } 1261 1262 // Attach the remaining base class specifiers to the derived class. 1263 Class->setBases(Bases, NumGoodBases); 1264 1265 // Delete the remaining (good) base class specifiers, since their 1266 // data has been copied into the CXXRecordDecl. 1267 for (unsigned idx = 0; idx < NumGoodBases; ++idx) 1268 Context.Deallocate(Bases[idx]); 1269 1270 return Invalid; 1271} 1272 1273/// ActOnBaseSpecifiers - Attach the given base specifiers to the 1274/// class, after checking whether there are any duplicate base 1275/// classes. 1276void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases, 1277 unsigned NumBases) { 1278 if (!ClassDecl || !Bases || !NumBases) 1279 return; 1280 1281 AdjustDeclIfTemplate(ClassDecl); 1282 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), 1283 (CXXBaseSpecifier**)(Bases), NumBases); 1284} 1285 1286static CXXRecordDecl *GetClassForType(QualType T) { 1287 if (const RecordType *RT = T->getAs<RecordType>()) 1288 return cast<CXXRecordDecl>(RT->getDecl()); 1289 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>()) 1290 return ICT->getDecl(); 1291 else 1292 return 0; 1293} 1294 1295/// \brief Determine whether the type \p Derived is a C++ class that is 1296/// derived from the type \p Base. 1297bool Sema::IsDerivedFrom(QualType Derived, QualType Base) { 1298 if (!getLangOpts().CPlusPlus) 1299 return false; 1300 1301 CXXRecordDecl *DerivedRD = GetClassForType(Derived); 1302 if (!DerivedRD) 1303 return false; 1304 1305 CXXRecordDecl *BaseRD = GetClassForType(Base); 1306 if (!BaseRD) 1307 return false; 1308 1309 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this. 1310 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD); 1311} 1312 1313/// \brief Determine whether the type \p Derived is a C++ class that is 1314/// derived from the type \p Base. 1315bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) { 1316 if (!getLangOpts().CPlusPlus) 1317 return false; 1318 1319 CXXRecordDecl *DerivedRD = GetClassForType(Derived); 1320 if (!DerivedRD) 1321 return false; 1322 1323 CXXRecordDecl *BaseRD = GetClassForType(Base); 1324 if (!BaseRD) 1325 return false; 1326 1327 return DerivedRD->isDerivedFrom(BaseRD, Paths); 1328} 1329 1330void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 1331 CXXCastPath &BasePathArray) { 1332 assert(BasePathArray.empty() && "Base path array must be empty!"); 1333 assert(Paths.isRecordingPaths() && "Must record paths!"); 1334 1335 const CXXBasePath &Path = Paths.front(); 1336 1337 // We first go backward and check if we have a virtual base. 1338 // FIXME: It would be better if CXXBasePath had the base specifier for 1339 // the nearest virtual base. 1340 unsigned Start = 0; 1341 for (unsigned I = Path.size(); I != 0; --I) { 1342 if (Path[I - 1].Base->isVirtual()) { 1343 Start = I - 1; 1344 break; 1345 } 1346 } 1347 1348 // Now add all bases. 1349 for (unsigned I = Start, E = Path.size(); I != E; ++I) 1350 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 1351} 1352 1353/// \brief Determine whether the given base path includes a virtual 1354/// base class. 1355bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) { 1356 for (CXXCastPath::const_iterator B = BasePath.begin(), 1357 BEnd = BasePath.end(); 1358 B != BEnd; ++B) 1359 if ((*B)->isVirtual()) 1360 return true; 1361 1362 return false; 1363} 1364 1365/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 1366/// conversion (where Derived and Base are class types) is 1367/// well-formed, meaning that the conversion is unambiguous (and 1368/// that all of the base classes are accessible). Returns true 1369/// and emits a diagnostic if the code is ill-formed, returns false 1370/// otherwise. Loc is the location where this routine should point to 1371/// if there is an error, and Range is the source range to highlight 1372/// if there is an error. 1373bool 1374Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1375 unsigned InaccessibleBaseID, 1376 unsigned AmbigiousBaseConvID, 1377 SourceLocation Loc, SourceRange Range, 1378 DeclarationName Name, 1379 CXXCastPath *BasePath) { 1380 // First, determine whether the path from Derived to Base is 1381 // ambiguous. This is slightly more expensive than checking whether 1382 // the Derived to Base conversion exists, because here we need to 1383 // explore multiple paths to determine if there is an ambiguity. 1384 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1385 /*DetectVirtual=*/false); 1386 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths); 1387 assert(DerivationOkay && 1388 "Can only be used with a derived-to-base conversion"); 1389 (void)DerivationOkay; 1390 1391 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 1392 if (InaccessibleBaseID) { 1393 // Check that the base class can be accessed. 1394 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(), 1395 InaccessibleBaseID)) { 1396 case AR_inaccessible: 1397 return true; 1398 case AR_accessible: 1399 case AR_dependent: 1400 case AR_delayed: 1401 break; 1402 } 1403 } 1404 1405 // Build a base path if necessary. 1406 if (BasePath) 1407 BuildBasePathArray(Paths, *BasePath); 1408 return false; 1409 } 1410 1411 // We know that the derived-to-base conversion is ambiguous, and 1412 // we're going to produce a diagnostic. Perform the derived-to-base 1413 // search just one more time to compute all of the possible paths so 1414 // that we can print them out. This is more expensive than any of 1415 // the previous derived-to-base checks we've done, but at this point 1416 // performance isn't as much of an issue. 1417 Paths.clear(); 1418 Paths.setRecordingPaths(true); 1419 bool StillOkay = IsDerivedFrom(Derived, Base, Paths); 1420 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 1421 (void)StillOkay; 1422 1423 // Build up a textual representation of the ambiguous paths, e.g., 1424 // D -> B -> A, that will be used to illustrate the ambiguous 1425 // conversions in the diagnostic. We only print one of the paths 1426 // to each base class subobject. 1427 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 1428 1429 Diag(Loc, AmbigiousBaseConvID) 1430 << Derived << Base << PathDisplayStr << Range << Name; 1431 return true; 1432} 1433 1434bool 1435Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1436 SourceLocation Loc, SourceRange Range, 1437 CXXCastPath *BasePath, 1438 bool IgnoreAccess) { 1439 return CheckDerivedToBaseConversion(Derived, Base, 1440 IgnoreAccess ? 0 1441 : diag::err_upcast_to_inaccessible_base, 1442 diag::err_ambiguous_derived_to_base_conv, 1443 Loc, Range, DeclarationName(), 1444 BasePath); 1445} 1446 1447 1448/// @brief Builds a string representing ambiguous paths from a 1449/// specific derived class to different subobjects of the same base 1450/// class. 1451/// 1452/// This function builds a string that can be used in error messages 1453/// to show the different paths that one can take through the 1454/// inheritance hierarchy to go from the derived class to different 1455/// subobjects of a base class. The result looks something like this: 1456/// @code 1457/// struct D -> struct B -> struct A 1458/// struct D -> struct C -> struct A 1459/// @endcode 1460std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 1461 std::string PathDisplayStr; 1462 std::set<unsigned> DisplayedPaths; 1463 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 1464 Path != Paths.end(); ++Path) { 1465 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 1466 // We haven't displayed a path to this particular base 1467 // class subobject yet. 1468 PathDisplayStr += "\n "; 1469 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 1470 for (CXXBasePath::const_iterator Element = Path->begin(); 1471 Element != Path->end(); ++Element) 1472 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 1473 } 1474 } 1475 1476 return PathDisplayStr; 1477} 1478 1479//===----------------------------------------------------------------------===// 1480// C++ class member Handling 1481//===----------------------------------------------------------------------===// 1482 1483/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 1484bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, 1485 SourceLocation ASLoc, 1486 SourceLocation ColonLoc, 1487 AttributeList *Attrs) { 1488 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 1489 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 1490 ASLoc, ColonLoc); 1491 CurContext->addHiddenDecl(ASDecl); 1492 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 1493} 1494 1495/// CheckOverrideControl - Check C++11 override control semantics. 1496void Sema::CheckOverrideControl(Decl *D) { 1497 if (D->isInvalidDecl()) 1498 return; 1499 1500 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 1501 1502 // Do we know which functions this declaration might be overriding? 1503 bool OverridesAreKnown = !MD || 1504 (!MD->getParent()->hasAnyDependentBases() && 1505 !MD->getType()->isDependentType()); 1506 1507 if (!MD || !MD->isVirtual()) { 1508 if (OverridesAreKnown) { 1509 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1510 Diag(OA->getLocation(), 1511 diag::override_keyword_only_allowed_on_virtual_member_functions) 1512 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 1513 D->dropAttr<OverrideAttr>(); 1514 } 1515 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1516 Diag(FA->getLocation(), 1517 diag::override_keyword_only_allowed_on_virtual_member_functions) 1518 << "final" << FixItHint::CreateRemoval(FA->getLocation()); 1519 D->dropAttr<FinalAttr>(); 1520 } 1521 } 1522 return; 1523 } 1524 1525 if (!OverridesAreKnown) 1526 return; 1527 1528 // C++11 [class.virtual]p5: 1529 // If a virtual function is marked with the virt-specifier override and 1530 // does not override a member function of a base class, the program is 1531 // ill-formed. 1532 bool HasOverriddenMethods = 1533 MD->begin_overridden_methods() != MD->end_overridden_methods(); 1534 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 1535 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 1536 << MD->getDeclName(); 1537} 1538 1539/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 1540/// function overrides a virtual member function marked 'final', according to 1541/// C++11 [class.virtual]p4. 1542bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 1543 const CXXMethodDecl *Old) { 1544 if (!Old->hasAttr<FinalAttr>()) 1545 return false; 1546 1547 Diag(New->getLocation(), diag::err_final_function_overridden) 1548 << New->getDeclName(); 1549 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 1550 return true; 1551} 1552 1553static bool InitializationHasSideEffects(const FieldDecl &FD) { 1554 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 1555 // FIXME: Destruction of ObjC lifetime types has side-effects. 1556 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 1557 return !RD->isCompleteDefinition() || 1558 !RD->hasTrivialDefaultConstructor() || 1559 !RD->hasTrivialDestructor(); 1560 return false; 1561} 1562 1563/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 1564/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 1565/// bitfield width if there is one, 'InitExpr' specifies the initializer if 1566/// one has been parsed, and 'InitStyle' is set if an in-class initializer is 1567/// present (but parsing it has been deferred). 1568NamedDecl * 1569Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 1570 MultiTemplateParamsArg TemplateParameterLists, 1571 Expr *BW, const VirtSpecifiers &VS, 1572 InClassInitStyle InitStyle) { 1573 const DeclSpec &DS = D.getDeclSpec(); 1574 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 1575 DeclarationName Name = NameInfo.getName(); 1576 SourceLocation Loc = NameInfo.getLoc(); 1577 1578 // For anonymous bitfields, the location should point to the type. 1579 if (Loc.isInvalid()) 1580 Loc = D.getLocStart(); 1581 1582 Expr *BitWidth = static_cast<Expr*>(BW); 1583 1584 assert(isa<CXXRecordDecl>(CurContext)); 1585 assert(!DS.isFriendSpecified()); 1586 1587 bool isFunc = D.isDeclarationOfFunction(); 1588 1589 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 1590 // The Microsoft extension __interface only permits public member functions 1591 // and prohibits constructors, destructors, operators, non-public member 1592 // functions, static methods and data members. 1593 unsigned InvalidDecl; 1594 bool ShowDeclName = true; 1595 if (!isFunc) 1596 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1; 1597 else if (AS != AS_public) 1598 InvalidDecl = 2; 1599 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 1600 InvalidDecl = 3; 1601 else switch (Name.getNameKind()) { 1602 case DeclarationName::CXXConstructorName: 1603 InvalidDecl = 4; 1604 ShowDeclName = false; 1605 break; 1606 1607 case DeclarationName::CXXDestructorName: 1608 InvalidDecl = 5; 1609 ShowDeclName = false; 1610 break; 1611 1612 case DeclarationName::CXXOperatorName: 1613 case DeclarationName::CXXConversionFunctionName: 1614 InvalidDecl = 6; 1615 break; 1616 1617 default: 1618 InvalidDecl = 0; 1619 break; 1620 } 1621 1622 if (InvalidDecl) { 1623 if (ShowDeclName) 1624 Diag(Loc, diag::err_invalid_member_in_interface) 1625 << (InvalidDecl-1) << Name; 1626 else 1627 Diag(Loc, diag::err_invalid_member_in_interface) 1628 << (InvalidDecl-1) << ""; 1629 return 0; 1630 } 1631 } 1632 1633 // C++ 9.2p6: A member shall not be declared to have automatic storage 1634 // duration (auto, register) or with the extern storage-class-specifier. 1635 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 1636 // data members and cannot be applied to names declared const or static, 1637 // and cannot be applied to reference members. 1638 switch (DS.getStorageClassSpec()) { 1639 case DeclSpec::SCS_unspecified: 1640 case DeclSpec::SCS_typedef: 1641 case DeclSpec::SCS_static: 1642 // FALL THROUGH. 1643 break; 1644 case DeclSpec::SCS_mutable: 1645 if (isFunc) { 1646 if (DS.getStorageClassSpecLoc().isValid()) 1647 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 1648 else 1649 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function); 1650 1651 // FIXME: It would be nicer if the keyword was ignored only for this 1652 // declarator. Otherwise we could get follow-up errors. 1653 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1654 } 1655 break; 1656 default: 1657 if (DS.getStorageClassSpecLoc().isValid()) 1658 Diag(DS.getStorageClassSpecLoc(), 1659 diag::err_storageclass_invalid_for_member); 1660 else 1661 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member); 1662 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1663 } 1664 1665 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 1666 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 1667 !isFunc); 1668 1669 if (DS.isConstexprSpecified() && isInstField) { 1670 SemaDiagnosticBuilder B = 1671 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 1672 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 1673 if (InitStyle == ICIS_NoInit) { 1674 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const"); 1675 D.getMutableDeclSpec().ClearConstexprSpec(); 1676 const char *PrevSpec; 1677 unsigned DiagID; 1678 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc, 1679 PrevSpec, DiagID, getLangOpts()); 1680 assert(!Failed && "Making a constexpr member const shouldn't fail"); 1681 } else { 1682 B << 1; 1683 const char *PrevSpec; 1684 unsigned DiagID; 1685 DeclSpec::SCS PrevSCS = DS.getStorageClassSpec(); 1686 if (D.getMutableDeclSpec().SetStorageClassSpec( 1687 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) { 1688 assert(PrevSCS == DeclSpec::SCS_mutable && 1689 "This is the only DeclSpec that should fail to be applied"); 1690 B << 1; 1691 } else { 1692 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 1693 isInstField = false; 1694 } 1695 } 1696 } 1697 1698 NamedDecl *Member; 1699 if (isInstField) { 1700 CXXScopeSpec &SS = D.getCXXScopeSpec(); 1701 1702 // Data members must have identifiers for names. 1703 if (!Name.isIdentifier()) { 1704 Diag(Loc, diag::err_bad_variable_name) 1705 << Name; 1706 return 0; 1707 } 1708 1709 IdentifierInfo *II = Name.getAsIdentifierInfo(); 1710 1711 // Member field could not be with "template" keyword. 1712 // So TemplateParameterLists should be empty in this case. 1713 if (TemplateParameterLists.size()) { 1714 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 1715 if (TemplateParams->size()) { 1716 // There is no such thing as a member field template. 1717 Diag(D.getIdentifierLoc(), diag::err_template_member) 1718 << II 1719 << SourceRange(TemplateParams->getTemplateLoc(), 1720 TemplateParams->getRAngleLoc()); 1721 } else { 1722 // There is an extraneous 'template<>' for this member. 1723 Diag(TemplateParams->getTemplateLoc(), 1724 diag::err_template_member_noparams) 1725 << II 1726 << SourceRange(TemplateParams->getTemplateLoc(), 1727 TemplateParams->getRAngleLoc()); 1728 } 1729 return 0; 1730 } 1731 1732 if (SS.isSet() && !SS.isInvalid()) { 1733 // The user provided a superfluous scope specifier inside a class 1734 // definition: 1735 // 1736 // class X { 1737 // int X::member; 1738 // }; 1739 if (DeclContext *DC = computeDeclContext(SS, false)) 1740 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc()); 1741 else 1742 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 1743 << Name << SS.getRange(); 1744 1745 SS.clear(); 1746 } 1747 1748 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth, 1749 InitStyle, AS); 1750 assert(Member && "HandleField never returns null"); 1751 } else { 1752 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static); 1753 1754 Member = HandleDeclarator(S, D, TemplateParameterLists); 1755 if (!Member) { 1756 return 0; 1757 } 1758 1759 // Non-instance-fields can't have a bitfield. 1760 if (BitWidth) { 1761 if (Member->isInvalidDecl()) { 1762 // don't emit another diagnostic. 1763 } else if (isa<VarDecl>(Member)) { 1764 // C++ 9.6p3: A bit-field shall not be a static member. 1765 // "static member 'A' cannot be a bit-field" 1766 Diag(Loc, diag::err_static_not_bitfield) 1767 << Name << BitWidth->getSourceRange(); 1768 } else if (isa<TypedefDecl>(Member)) { 1769 // "typedef member 'x' cannot be a bit-field" 1770 Diag(Loc, diag::err_typedef_not_bitfield) 1771 << Name << BitWidth->getSourceRange(); 1772 } else { 1773 // A function typedef ("typedef int f(); f a;"). 1774 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 1775 Diag(Loc, diag::err_not_integral_type_bitfield) 1776 << Name << cast<ValueDecl>(Member)->getType() 1777 << BitWidth->getSourceRange(); 1778 } 1779 1780 BitWidth = 0; 1781 Member->setInvalidDecl(); 1782 } 1783 1784 Member->setAccess(AS); 1785 1786 // If we have declared a member function template, set the access of the 1787 // templated declaration as well. 1788 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 1789 FunTmpl->getTemplatedDecl()->setAccess(AS); 1790 } 1791 1792 if (VS.isOverrideSpecified()) 1793 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context)); 1794 if (VS.isFinalSpecified()) 1795 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context)); 1796 1797 if (VS.getLastLocation().isValid()) { 1798 // Update the end location of a method that has a virt-specifiers. 1799 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 1800 MD->setRangeEnd(VS.getLastLocation()); 1801 } 1802 1803 CheckOverrideControl(Member); 1804 1805 assert((Name || isInstField) && "No identifier for non-field ?"); 1806 1807 if (isInstField) { 1808 FieldDecl *FD = cast<FieldDecl>(Member); 1809 FieldCollector->Add(FD); 1810 1811 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field, 1812 FD->getLocation()) 1813 != DiagnosticsEngine::Ignored) { 1814 // Remember all explicit private FieldDecls that have a name, no side 1815 // effects and are not part of a dependent type declaration. 1816 if (!FD->isImplicit() && FD->getDeclName() && 1817 FD->getAccess() == AS_private && 1818 !FD->hasAttr<UnusedAttr>() && 1819 !FD->getParent()->isDependentContext() && 1820 !InitializationHasSideEffects(*FD)) 1821 UnusedPrivateFields.insert(FD); 1822 } 1823 } 1824 1825 return Member; 1826} 1827 1828namespace { 1829 class UninitializedFieldVisitor 1830 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 1831 Sema &S; 1832 ValueDecl *VD; 1833 public: 1834 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 1835 UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context), 1836 S(S) { 1837 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD)) 1838 this->VD = IFD->getAnonField(); 1839 else 1840 this->VD = VD; 1841 } 1842 1843 void HandleExpr(Expr *E) { 1844 if (!E) return; 1845 1846 // Expressions like x(x) sometimes lack the surrounding expressions 1847 // but need to be checked anyways. 1848 HandleValue(E); 1849 Visit(E); 1850 } 1851 1852 void HandleValue(Expr *E) { 1853 E = E->IgnoreParens(); 1854 1855 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 1856 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 1857 return; 1858 1859 // FieldME is the inner-most MemberExpr that is not an anonymous struct 1860 // or union. 1861 MemberExpr *FieldME = ME; 1862 1863 Expr *Base = E; 1864 while (isa<MemberExpr>(Base)) { 1865 ME = cast<MemberExpr>(Base); 1866 1867 if (isa<VarDecl>(ME->getMemberDecl())) 1868 return; 1869 1870 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 1871 if (!FD->isAnonymousStructOrUnion()) 1872 FieldME = ME; 1873 1874 Base = ME->getBase(); 1875 } 1876 1877 if (VD == FieldME->getMemberDecl() && isa<CXXThisExpr>(Base)) { 1878 unsigned diag = VD->getType()->isReferenceType() 1879 ? diag::warn_reference_field_is_uninit 1880 : diag::warn_field_is_uninit; 1881 S.Diag(FieldME->getExprLoc(), diag) << VD; 1882 } 1883 return; 1884 } 1885 1886 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 1887 HandleValue(CO->getTrueExpr()); 1888 HandleValue(CO->getFalseExpr()); 1889 return; 1890 } 1891 1892 if (BinaryConditionalOperator *BCO = 1893 dyn_cast<BinaryConditionalOperator>(E)) { 1894 HandleValue(BCO->getCommon()); 1895 HandleValue(BCO->getFalseExpr()); 1896 return; 1897 } 1898 1899 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 1900 switch (BO->getOpcode()) { 1901 default: 1902 return; 1903 case(BO_PtrMemD): 1904 case(BO_PtrMemI): 1905 HandleValue(BO->getLHS()); 1906 return; 1907 case(BO_Comma): 1908 HandleValue(BO->getRHS()); 1909 return; 1910 } 1911 } 1912 } 1913 1914 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 1915 if (E->getCastKind() == CK_LValueToRValue) 1916 HandleValue(E->getSubExpr()); 1917 1918 Inherited::VisitImplicitCastExpr(E); 1919 } 1920 1921 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 1922 Expr *Callee = E->getCallee(); 1923 if (isa<MemberExpr>(Callee)) 1924 HandleValue(Callee); 1925 1926 Inherited::VisitCXXMemberCallExpr(E); 1927 } 1928 }; 1929 static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E, 1930 ValueDecl *VD) { 1931 UninitializedFieldVisitor(S, VD).HandleExpr(E); 1932 } 1933} // namespace 1934 1935/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an 1936/// in-class initializer for a non-static C++ class member, and after 1937/// instantiating an in-class initializer in a class template. Such actions 1938/// are deferred until the class is complete. 1939void 1940Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc, 1941 Expr *InitExpr) { 1942 FieldDecl *FD = cast<FieldDecl>(D); 1943 assert(FD->getInClassInitStyle() != ICIS_NoInit && 1944 "must set init style when field is created"); 1945 1946 if (!InitExpr) { 1947 FD->setInvalidDecl(); 1948 FD->removeInClassInitializer(); 1949 return; 1950 } 1951 1952 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 1953 FD->setInvalidDecl(); 1954 FD->removeInClassInitializer(); 1955 return; 1956 } 1957 1958 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, InitLoc) 1959 != DiagnosticsEngine::Ignored) { 1960 CheckInitExprContainsUninitializedFields(*this, InitExpr, FD); 1961 } 1962 1963 ExprResult Init = InitExpr; 1964 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 1965 if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) { 1966 Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list) 1967 << /*at end of ctor*/1 << InitExpr->getSourceRange(); 1968 } 1969 Expr **Inits = &InitExpr; 1970 unsigned NumInits = 1; 1971 InitializedEntity Entity = InitializedEntity::InitializeMember(FD); 1972 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit 1973 ? InitializationKind::CreateDirectList(InitExpr->getLocStart()) 1974 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc); 1975 InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits); 1976 Init = Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits)); 1977 if (Init.isInvalid()) { 1978 FD->setInvalidDecl(); 1979 return; 1980 } 1981 } 1982 1983 // C++11 [class.base.init]p7: 1984 // The initialization of each base and member constitutes a 1985 // full-expression. 1986 Init = ActOnFinishFullExpr(Init.take(), InitLoc); 1987 if (Init.isInvalid()) { 1988 FD->setInvalidDecl(); 1989 return; 1990 } 1991 1992 InitExpr = Init.release(); 1993 1994 FD->setInClassInitializer(InitExpr); 1995} 1996 1997/// \brief Find the direct and/or virtual base specifiers that 1998/// correspond to the given base type, for use in base initialization 1999/// within a constructor. 2000static bool FindBaseInitializer(Sema &SemaRef, 2001 CXXRecordDecl *ClassDecl, 2002 QualType BaseType, 2003 const CXXBaseSpecifier *&DirectBaseSpec, 2004 const CXXBaseSpecifier *&VirtualBaseSpec) { 2005 // First, check for a direct base class. 2006 DirectBaseSpec = 0; 2007 for (CXXRecordDecl::base_class_const_iterator Base 2008 = ClassDecl->bases_begin(); 2009 Base != ClassDecl->bases_end(); ++Base) { 2010 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) { 2011 // We found a direct base of this type. That's what we're 2012 // initializing. 2013 DirectBaseSpec = &*Base; 2014 break; 2015 } 2016 } 2017 2018 // Check for a virtual base class. 2019 // FIXME: We might be able to short-circuit this if we know in advance that 2020 // there are no virtual bases. 2021 VirtualBaseSpec = 0; 2022 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 2023 // We haven't found a base yet; search the class hierarchy for a 2024 // virtual base class. 2025 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2026 /*DetectVirtual=*/false); 2027 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl), 2028 BaseType, Paths)) { 2029 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2030 Path != Paths.end(); ++Path) { 2031 if (Path->back().Base->isVirtual()) { 2032 VirtualBaseSpec = Path->back().Base; 2033 break; 2034 } 2035 } 2036 } 2037 } 2038 2039 return DirectBaseSpec || VirtualBaseSpec; 2040} 2041 2042/// \brief Handle a C++ member initializer using braced-init-list syntax. 2043MemInitResult 2044Sema::ActOnMemInitializer(Decl *ConstructorD, 2045 Scope *S, 2046 CXXScopeSpec &SS, 2047 IdentifierInfo *MemberOrBase, 2048 ParsedType TemplateTypeTy, 2049 const DeclSpec &DS, 2050 SourceLocation IdLoc, 2051 Expr *InitList, 2052 SourceLocation EllipsisLoc) { 2053 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2054 DS, IdLoc, InitList, 2055 EllipsisLoc); 2056} 2057 2058/// \brief Handle a C++ member initializer using parentheses syntax. 2059MemInitResult 2060Sema::ActOnMemInitializer(Decl *ConstructorD, 2061 Scope *S, 2062 CXXScopeSpec &SS, 2063 IdentifierInfo *MemberOrBase, 2064 ParsedType TemplateTypeTy, 2065 const DeclSpec &DS, 2066 SourceLocation IdLoc, 2067 SourceLocation LParenLoc, 2068 Expr **Args, unsigned NumArgs, 2069 SourceLocation RParenLoc, 2070 SourceLocation EllipsisLoc) { 2071 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, 2072 llvm::makeArrayRef(Args, NumArgs), 2073 RParenLoc); 2074 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2075 DS, IdLoc, List, EllipsisLoc); 2076} 2077 2078namespace { 2079 2080// Callback to only accept typo corrections that can be a valid C++ member 2081// intializer: either a non-static field member or a base class. 2082class MemInitializerValidatorCCC : public CorrectionCandidateCallback { 2083 public: 2084 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 2085 : ClassDecl(ClassDecl) {} 2086 2087 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 2088 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 2089 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 2090 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 2091 else 2092 return isa<TypeDecl>(ND); 2093 } 2094 return false; 2095 } 2096 2097 private: 2098 CXXRecordDecl *ClassDecl; 2099}; 2100 2101} 2102 2103/// \brief Handle a C++ member initializer. 2104MemInitResult 2105Sema::BuildMemInitializer(Decl *ConstructorD, 2106 Scope *S, 2107 CXXScopeSpec &SS, 2108 IdentifierInfo *MemberOrBase, 2109 ParsedType TemplateTypeTy, 2110 const DeclSpec &DS, 2111 SourceLocation IdLoc, 2112 Expr *Init, 2113 SourceLocation EllipsisLoc) { 2114 if (!ConstructorD) 2115 return true; 2116 2117 AdjustDeclIfTemplate(ConstructorD); 2118 2119 CXXConstructorDecl *Constructor 2120 = dyn_cast<CXXConstructorDecl>(ConstructorD); 2121 if (!Constructor) { 2122 // The user wrote a constructor initializer on a function that is 2123 // not a C++ constructor. Ignore the error for now, because we may 2124 // have more member initializers coming; we'll diagnose it just 2125 // once in ActOnMemInitializers. 2126 return true; 2127 } 2128 2129 CXXRecordDecl *ClassDecl = Constructor->getParent(); 2130 2131 // C++ [class.base.init]p2: 2132 // Names in a mem-initializer-id are looked up in the scope of the 2133 // constructor's class and, if not found in that scope, are looked 2134 // up in the scope containing the constructor's definition. 2135 // [Note: if the constructor's class contains a member with the 2136 // same name as a direct or virtual base class of the class, a 2137 // mem-initializer-id naming the member or base class and composed 2138 // of a single identifier refers to the class member. A 2139 // mem-initializer-id for the hidden base class may be specified 2140 // using a qualified name. ] 2141 if (!SS.getScopeRep() && !TemplateTypeTy) { 2142 // Look for a member, first. 2143 DeclContext::lookup_result Result 2144 = ClassDecl->lookup(MemberOrBase); 2145 if (!Result.empty()) { 2146 ValueDecl *Member; 2147 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 2148 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) { 2149 if (EllipsisLoc.isValid()) 2150 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 2151 << MemberOrBase 2152 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 2153 2154 return BuildMemberInitializer(Member, Init, IdLoc); 2155 } 2156 } 2157 } 2158 // It didn't name a member, so see if it names a class. 2159 QualType BaseType; 2160 TypeSourceInfo *TInfo = 0; 2161 2162 if (TemplateTypeTy) { 2163 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 2164 } else if (DS.getTypeSpecType() == TST_decltype) { 2165 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 2166 } else { 2167 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 2168 LookupParsedName(R, S, &SS); 2169 2170 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 2171 if (!TyD) { 2172 if (R.isAmbiguous()) return true; 2173 2174 // We don't want access-control diagnostics here. 2175 R.suppressDiagnostics(); 2176 2177 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 2178 bool NotUnknownSpecialization = false; 2179 DeclContext *DC = computeDeclContext(SS, false); 2180 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 2181 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 2182 2183 if (!NotUnknownSpecialization) { 2184 // When the scope specifier can refer to a member of an unknown 2185 // specialization, we take it as a type name. 2186 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 2187 SS.getWithLocInContext(Context), 2188 *MemberOrBase, IdLoc); 2189 if (BaseType.isNull()) 2190 return true; 2191 2192 R.clear(); 2193 R.setLookupName(MemberOrBase); 2194 } 2195 } 2196 2197 // If no results were found, try to correct typos. 2198 TypoCorrection Corr; 2199 MemInitializerValidatorCCC Validator(ClassDecl); 2200 if (R.empty() && BaseType.isNull() && 2201 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 2202 Validator, ClassDecl))) { 2203 std::string CorrectedStr(Corr.getAsString(getLangOpts())); 2204 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts())); 2205 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 2206 // We have found a non-static data member with a similar 2207 // name to what was typed; complain and initialize that 2208 // member. 2209 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest) 2210 << MemberOrBase << true << CorrectedQuotedStr 2211 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr); 2212 Diag(Member->getLocation(), diag::note_previous_decl) 2213 << CorrectedQuotedStr; 2214 2215 return BuildMemberInitializer(Member, Init, IdLoc); 2216 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 2217 const CXXBaseSpecifier *DirectBaseSpec; 2218 const CXXBaseSpecifier *VirtualBaseSpec; 2219 if (FindBaseInitializer(*this, ClassDecl, 2220 Context.getTypeDeclType(Type), 2221 DirectBaseSpec, VirtualBaseSpec)) { 2222 // We have found a direct or virtual base class with a 2223 // similar name to what was typed; complain and initialize 2224 // that base class. 2225 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest) 2226 << MemberOrBase << false << CorrectedQuotedStr 2227 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr); 2228 2229 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec 2230 : VirtualBaseSpec; 2231 Diag(BaseSpec->getLocStart(), 2232 diag::note_base_class_specified_here) 2233 << BaseSpec->getType() 2234 << BaseSpec->getSourceRange(); 2235 2236 TyD = Type; 2237 } 2238 } 2239 } 2240 2241 if (!TyD && BaseType.isNull()) { 2242 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 2243 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 2244 return true; 2245 } 2246 } 2247 2248 if (BaseType.isNull()) { 2249 BaseType = Context.getTypeDeclType(TyD); 2250 if (SS.isSet()) { 2251 NestedNameSpecifier *Qualifier = 2252 static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 2253 2254 // FIXME: preserve source range information 2255 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType); 2256 } 2257 } 2258 } 2259 2260 if (!TInfo) 2261 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 2262 2263 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 2264} 2265 2266/// Checks a member initializer expression for cases where reference (or 2267/// pointer) members are bound to by-value parameters (or their addresses). 2268static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member, 2269 Expr *Init, 2270 SourceLocation IdLoc) { 2271 QualType MemberTy = Member->getType(); 2272 2273 // We only handle pointers and references currently. 2274 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers? 2275 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType()) 2276 return; 2277 2278 const bool IsPointer = MemberTy->isPointerType(); 2279 if (IsPointer) { 2280 if (const UnaryOperator *Op 2281 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) { 2282 // The only case we're worried about with pointers requires taking the 2283 // address. 2284 if (Op->getOpcode() != UO_AddrOf) 2285 return; 2286 2287 Init = Op->getSubExpr(); 2288 } else { 2289 // We only handle address-of expression initializers for pointers. 2290 return; 2291 } 2292 } 2293 2294 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) { 2295 // Taking the address of a temporary will be diagnosed as a hard error. 2296 if (IsPointer) 2297 return; 2298 2299 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary) 2300 << Member << Init->getSourceRange(); 2301 } else if (const DeclRefExpr *DRE 2302 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) { 2303 // We only warn when referring to a non-reference parameter declaration. 2304 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl()); 2305 if (!Parameter || Parameter->getType()->isReferenceType()) 2306 return; 2307 2308 S.Diag(Init->getExprLoc(), 2309 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr 2310 : diag::warn_bind_ref_member_to_parameter) 2311 << Member << Parameter << Init->getSourceRange(); 2312 } else { 2313 // Other initializers are fine. 2314 return; 2315 } 2316 2317 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here) 2318 << (unsigned)IsPointer; 2319} 2320 2321MemInitResult 2322Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 2323 SourceLocation IdLoc) { 2324 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 2325 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 2326 assert((DirectMember || IndirectMember) && 2327 "Member must be a FieldDecl or IndirectFieldDecl"); 2328 2329 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 2330 return true; 2331 2332 if (Member->isInvalidDecl()) 2333 return true; 2334 2335 // Diagnose value-uses of fields to initialize themselves, e.g. 2336 // foo(foo) 2337 // where foo is not also a parameter to the constructor. 2338 // TODO: implement -Wuninitialized and fold this into that framework. 2339 Expr **Args; 2340 unsigned NumArgs; 2341 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2342 Args = ParenList->getExprs(); 2343 NumArgs = ParenList->getNumExprs(); 2344 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 2345 Args = InitList->getInits(); 2346 NumArgs = InitList->getNumInits(); 2347 } else { 2348 // Template instantiation doesn't reconstruct ParenListExprs for us. 2349 Args = &Init; 2350 NumArgs = 1; 2351 } 2352 2353 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc) 2354 != DiagnosticsEngine::Ignored) 2355 for (unsigned i = 0; i < NumArgs; ++i) 2356 // FIXME: Warn about the case when other fields are used before being 2357 // initialized. For example, let this field be the i'th field. When 2358 // initializing the i'th field, throw a warning if any of the >= i'th 2359 // fields are used, as they are not yet initialized. 2360 // Right now we are only handling the case where the i'th field uses 2361 // itself in its initializer. 2362 // Also need to take into account that some fields may be initialized by 2363 // in-class initializers, see C++11 [class.base.init]p9. 2364 CheckInitExprContainsUninitializedFields(*this, Args[i], Member); 2365 2366 SourceRange InitRange = Init->getSourceRange(); 2367 2368 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 2369 // Can't check initialization for a member of dependent type or when 2370 // any of the arguments are type-dependent expressions. 2371 DiscardCleanupsInEvaluationContext(); 2372 } else { 2373 bool InitList = false; 2374 if (isa<InitListExpr>(Init)) { 2375 InitList = true; 2376 Args = &Init; 2377 NumArgs = 1; 2378 2379 if (isStdInitializerList(Member->getType(), 0)) { 2380 Diag(IdLoc, diag::warn_dangling_std_initializer_list) 2381 << /*at end of ctor*/1 << InitRange; 2382 } 2383 } 2384 2385 // Initialize the member. 2386 InitializedEntity MemberEntity = 2387 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0) 2388 : InitializedEntity::InitializeMember(IndirectMember, 0); 2389 InitializationKind Kind = 2390 InitList ? InitializationKind::CreateDirectList(IdLoc) 2391 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 2392 InitRange.getEnd()); 2393 2394 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs); 2395 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, 2396 MultiExprArg(Args, NumArgs), 2397 0); 2398 if (MemberInit.isInvalid()) 2399 return true; 2400 2401 // C++11 [class.base.init]p7: 2402 // The initialization of each base and member constitutes a 2403 // full-expression. 2404 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin()); 2405 if (MemberInit.isInvalid()) 2406 return true; 2407 2408 Init = MemberInit.get(); 2409 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc); 2410 } 2411 2412 if (DirectMember) { 2413 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 2414 InitRange.getBegin(), Init, 2415 InitRange.getEnd()); 2416 } else { 2417 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 2418 InitRange.getBegin(), Init, 2419 InitRange.getEnd()); 2420 } 2421} 2422 2423MemInitResult 2424Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 2425 CXXRecordDecl *ClassDecl) { 2426 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 2427 if (!LangOpts.CPlusPlus11) 2428 return Diag(NameLoc, diag::err_delegating_ctor) 2429 << TInfo->getTypeLoc().getLocalSourceRange(); 2430 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 2431 2432 bool InitList = true; 2433 Expr **Args = &Init; 2434 unsigned NumArgs = 1; 2435 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2436 InitList = false; 2437 Args = ParenList->getExprs(); 2438 NumArgs = ParenList->getNumExprs(); 2439 } 2440 2441 SourceRange InitRange = Init->getSourceRange(); 2442 // Initialize the object. 2443 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 2444 QualType(ClassDecl->getTypeForDecl(), 0)); 2445 InitializationKind Kind = 2446 InitList ? InitializationKind::CreateDirectList(NameLoc) 2447 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 2448 InitRange.getEnd()); 2449 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs); 2450 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 2451 MultiExprArg(Args, NumArgs), 2452 0); 2453 if (DelegationInit.isInvalid()) 2454 return true; 2455 2456 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 2457 "Delegating constructor with no target?"); 2458 2459 // C++11 [class.base.init]p7: 2460 // The initialization of each base and member constitutes a 2461 // full-expression. 2462 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(), 2463 InitRange.getBegin()); 2464 if (DelegationInit.isInvalid()) 2465 return true; 2466 2467 // If we are in a dependent context, template instantiation will 2468 // perform this type-checking again. Just save the arguments that we 2469 // received in a ParenListExpr. 2470 // FIXME: This isn't quite ideal, since our ASTs don't capture all 2471 // of the information that we have about the base 2472 // initializer. However, deconstructing the ASTs is a dicey process, 2473 // and this approach is far more likely to get the corner cases right. 2474 if (CurContext->isDependentContext()) 2475 DelegationInit = Owned(Init); 2476 2477 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 2478 DelegationInit.takeAs<Expr>(), 2479 InitRange.getEnd()); 2480} 2481 2482MemInitResult 2483Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 2484 Expr *Init, CXXRecordDecl *ClassDecl, 2485 SourceLocation EllipsisLoc) { 2486 SourceLocation BaseLoc 2487 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 2488 2489 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 2490 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 2491 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2492 2493 // C++ [class.base.init]p2: 2494 // [...] Unless the mem-initializer-id names a nonstatic data 2495 // member of the constructor's class or a direct or virtual base 2496 // of that class, the mem-initializer is ill-formed. A 2497 // mem-initializer-list can initialize a base class using any 2498 // name that denotes that base class type. 2499 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 2500 2501 SourceRange InitRange = Init->getSourceRange(); 2502 if (EllipsisLoc.isValid()) { 2503 // This is a pack expansion. 2504 if (!BaseType->containsUnexpandedParameterPack()) { 2505 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2506 << SourceRange(BaseLoc, InitRange.getEnd()); 2507 2508 EllipsisLoc = SourceLocation(); 2509 } 2510 } else { 2511 // Check for any unexpanded parameter packs. 2512 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 2513 return true; 2514 2515 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 2516 return true; 2517 } 2518 2519 // Check for direct and virtual base classes. 2520 const CXXBaseSpecifier *DirectBaseSpec = 0; 2521 const CXXBaseSpecifier *VirtualBaseSpec = 0; 2522 if (!Dependent) { 2523 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 2524 BaseType)) 2525 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 2526 2527 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 2528 VirtualBaseSpec); 2529 2530 // C++ [base.class.init]p2: 2531 // Unless the mem-initializer-id names a nonstatic data member of the 2532 // constructor's class or a direct or virtual base of that class, the 2533 // mem-initializer is ill-formed. 2534 if (!DirectBaseSpec && !VirtualBaseSpec) { 2535 // If the class has any dependent bases, then it's possible that 2536 // one of those types will resolve to the same type as 2537 // BaseType. Therefore, just treat this as a dependent base 2538 // class initialization. FIXME: Should we try to check the 2539 // initialization anyway? It seems odd. 2540 if (ClassDecl->hasAnyDependentBases()) 2541 Dependent = true; 2542 else 2543 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 2544 << BaseType << Context.getTypeDeclType(ClassDecl) 2545 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2546 } 2547 } 2548 2549 if (Dependent) { 2550 DiscardCleanupsInEvaluationContext(); 2551 2552 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 2553 /*IsVirtual=*/false, 2554 InitRange.getBegin(), Init, 2555 InitRange.getEnd(), EllipsisLoc); 2556 } 2557 2558 // C++ [base.class.init]p2: 2559 // If a mem-initializer-id is ambiguous because it designates both 2560 // a direct non-virtual base class and an inherited virtual base 2561 // class, the mem-initializer is ill-formed. 2562 if (DirectBaseSpec && VirtualBaseSpec) 2563 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 2564 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2565 2566 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec); 2567 if (!BaseSpec) 2568 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec); 2569 2570 // Initialize the base. 2571 bool InitList = true; 2572 Expr **Args = &Init; 2573 unsigned NumArgs = 1; 2574 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2575 InitList = false; 2576 Args = ParenList->getExprs(); 2577 NumArgs = ParenList->getNumExprs(); 2578 } 2579 2580 InitializedEntity BaseEntity = 2581 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 2582 InitializationKind Kind = 2583 InitList ? InitializationKind::CreateDirectList(BaseLoc) 2584 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 2585 InitRange.getEnd()); 2586 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs); 2587 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, 2588 MultiExprArg(Args, NumArgs), 0); 2589 if (BaseInit.isInvalid()) 2590 return true; 2591 2592 // C++11 [class.base.init]p7: 2593 // The initialization of each base and member constitutes a 2594 // full-expression. 2595 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin()); 2596 if (BaseInit.isInvalid()) 2597 return true; 2598 2599 // If we are in a dependent context, template instantiation will 2600 // perform this type-checking again. Just save the arguments that we 2601 // received in a ParenListExpr. 2602 // FIXME: This isn't quite ideal, since our ASTs don't capture all 2603 // of the information that we have about the base 2604 // initializer. However, deconstructing the ASTs is a dicey process, 2605 // and this approach is far more likely to get the corner cases right. 2606 if (CurContext->isDependentContext()) 2607 BaseInit = Owned(Init); 2608 2609 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 2610 BaseSpec->isVirtual(), 2611 InitRange.getBegin(), 2612 BaseInit.takeAs<Expr>(), 2613 InitRange.getEnd(), EllipsisLoc); 2614} 2615 2616// Create a static_cast\<T&&>(expr). 2617static Expr *CastForMoving(Sema &SemaRef, Expr *E) { 2618 QualType ExprType = E->getType(); 2619 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType); 2620 SourceLocation ExprLoc = E->getLocStart(); 2621 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 2622 TargetType, ExprLoc); 2623 2624 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 2625 SourceRange(ExprLoc, ExprLoc), 2626 E->getSourceRange()).take(); 2627} 2628 2629/// ImplicitInitializerKind - How an implicit base or member initializer should 2630/// initialize its base or member. 2631enum ImplicitInitializerKind { 2632 IIK_Default, 2633 IIK_Copy, 2634 IIK_Move 2635}; 2636 2637static bool 2638BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 2639 ImplicitInitializerKind ImplicitInitKind, 2640 CXXBaseSpecifier *BaseSpec, 2641 bool IsInheritedVirtualBase, 2642 CXXCtorInitializer *&CXXBaseInit) { 2643 InitializedEntity InitEntity 2644 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 2645 IsInheritedVirtualBase); 2646 2647 ExprResult BaseInit; 2648 2649 switch (ImplicitInitKind) { 2650 case IIK_Default: { 2651 InitializationKind InitKind 2652 = InitializationKind::CreateDefault(Constructor->getLocation()); 2653 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0); 2654 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg()); 2655 break; 2656 } 2657 2658 case IIK_Move: 2659 case IIK_Copy: { 2660 bool Moving = ImplicitInitKind == IIK_Move; 2661 ParmVarDecl *Param = Constructor->getParamDecl(0); 2662 QualType ParamType = Param->getType().getNonReferenceType(); 2663 2664 Expr *CopyCtorArg = 2665 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 2666 SourceLocation(), Param, false, 2667 Constructor->getLocation(), ParamType, 2668 VK_LValue, 0); 2669 2670 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 2671 2672 // Cast to the base class to avoid ambiguities. 2673 QualType ArgTy = 2674 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 2675 ParamType.getQualifiers()); 2676 2677 if (Moving) { 2678 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 2679 } 2680 2681 CXXCastPath BasePath; 2682 BasePath.push_back(BaseSpec); 2683 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 2684 CK_UncheckedDerivedToBase, 2685 Moving ? VK_XValue : VK_LValue, 2686 &BasePath).take(); 2687 2688 InitializationKind InitKind 2689 = InitializationKind::CreateDirect(Constructor->getLocation(), 2690 SourceLocation(), SourceLocation()); 2691 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 2692 &CopyCtorArg, 1); 2693 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, 2694 MultiExprArg(&CopyCtorArg, 1)); 2695 break; 2696 } 2697 } 2698 2699 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 2700 if (BaseInit.isInvalid()) 2701 return true; 2702 2703 CXXBaseInit = 2704 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 2705 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 2706 SourceLocation()), 2707 BaseSpec->isVirtual(), 2708 SourceLocation(), 2709 BaseInit.takeAs<Expr>(), 2710 SourceLocation(), 2711 SourceLocation()); 2712 2713 return false; 2714} 2715 2716static bool RefersToRValueRef(Expr *MemRef) { 2717 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 2718 return Referenced->getType()->isRValueReferenceType(); 2719} 2720 2721static bool 2722BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 2723 ImplicitInitializerKind ImplicitInitKind, 2724 FieldDecl *Field, IndirectFieldDecl *Indirect, 2725 CXXCtorInitializer *&CXXMemberInit) { 2726 if (Field->isInvalidDecl()) 2727 return true; 2728 2729 SourceLocation Loc = Constructor->getLocation(); 2730 2731 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 2732 bool Moving = ImplicitInitKind == IIK_Move; 2733 ParmVarDecl *Param = Constructor->getParamDecl(0); 2734 QualType ParamType = Param->getType().getNonReferenceType(); 2735 2736 // Suppress copying zero-width bitfields. 2737 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0) 2738 return false; 2739 2740 Expr *MemberExprBase = 2741 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 2742 SourceLocation(), Param, false, 2743 Loc, ParamType, VK_LValue, 0); 2744 2745 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 2746 2747 if (Moving) { 2748 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 2749 } 2750 2751 // Build a reference to this field within the parameter. 2752 CXXScopeSpec SS; 2753 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 2754 Sema::LookupMemberName); 2755 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 2756 : cast<ValueDecl>(Field), AS_public); 2757 MemberLookup.resolveKind(); 2758 ExprResult CtorArg 2759 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 2760 ParamType, Loc, 2761 /*IsArrow=*/false, 2762 SS, 2763 /*TemplateKWLoc=*/SourceLocation(), 2764 /*FirstQualifierInScope=*/0, 2765 MemberLookup, 2766 /*TemplateArgs=*/0); 2767 if (CtorArg.isInvalid()) 2768 return true; 2769 2770 // C++11 [class.copy]p15: 2771 // - if a member m has rvalue reference type T&&, it is direct-initialized 2772 // with static_cast<T&&>(x.m); 2773 if (RefersToRValueRef(CtorArg.get())) { 2774 CtorArg = CastForMoving(SemaRef, CtorArg.take()); 2775 } 2776 2777 // When the field we are copying is an array, create index variables for 2778 // each dimension of the array. We use these index variables to subscript 2779 // the source array, and other clients (e.g., CodeGen) will perform the 2780 // necessary iteration with these index variables. 2781 SmallVector<VarDecl *, 4> IndexVariables; 2782 QualType BaseType = Field->getType(); 2783 QualType SizeType = SemaRef.Context.getSizeType(); 2784 bool InitializingArray = false; 2785 while (const ConstantArrayType *Array 2786 = SemaRef.Context.getAsConstantArrayType(BaseType)) { 2787 InitializingArray = true; 2788 // Create the iteration variable for this array index. 2789 IdentifierInfo *IterationVarName = 0; 2790 { 2791 SmallString<8> Str; 2792 llvm::raw_svector_ostream OS(Str); 2793 OS << "__i" << IndexVariables.size(); 2794 IterationVarName = &SemaRef.Context.Idents.get(OS.str()); 2795 } 2796 VarDecl *IterationVar 2797 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc, 2798 IterationVarName, SizeType, 2799 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc), 2800 SC_None, SC_None); 2801 IndexVariables.push_back(IterationVar); 2802 2803 // Create a reference to the iteration variable. 2804 ExprResult IterationVarRef 2805 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 2806 assert(!IterationVarRef.isInvalid() && 2807 "Reference to invented variable cannot fail!"); 2808 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take()); 2809 assert(!IterationVarRef.isInvalid() && 2810 "Conversion of invented variable cannot fail!"); 2811 2812 // Subscript the array with this iteration variable. 2813 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc, 2814 IterationVarRef.take(), 2815 Loc); 2816 if (CtorArg.isInvalid()) 2817 return true; 2818 2819 BaseType = Array->getElementType(); 2820 } 2821 2822 // The array subscript expression is an lvalue, which is wrong for moving. 2823 if (Moving && InitializingArray) 2824 CtorArg = CastForMoving(SemaRef, CtorArg.take()); 2825 2826 // Construct the entity that we will be initializing. For an array, this 2827 // will be first element in the array, which may require several levels 2828 // of array-subscript entities. 2829 SmallVector<InitializedEntity, 4> Entities; 2830 Entities.reserve(1 + IndexVariables.size()); 2831 if (Indirect) 2832 Entities.push_back(InitializedEntity::InitializeMember(Indirect)); 2833 else 2834 Entities.push_back(InitializedEntity::InitializeMember(Field)); 2835 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 2836 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context, 2837 0, 2838 Entities.back())); 2839 2840 // Direct-initialize to use the copy constructor. 2841 InitializationKind InitKind = 2842 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 2843 2844 Expr *CtorArgE = CtorArg.takeAs<Expr>(); 2845 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, 2846 &CtorArgE, 1); 2847 2848 ExprResult MemberInit 2849 = InitSeq.Perform(SemaRef, Entities.back(), InitKind, 2850 MultiExprArg(&CtorArgE, 1)); 2851 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 2852 if (MemberInit.isInvalid()) 2853 return true; 2854 2855 if (Indirect) { 2856 assert(IndexVariables.size() == 0 && 2857 "Indirect field improperly initialized"); 2858 CXXMemberInit 2859 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 2860 Loc, Loc, 2861 MemberInit.takeAs<Expr>(), 2862 Loc); 2863 } else 2864 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, 2865 Loc, MemberInit.takeAs<Expr>(), 2866 Loc, 2867 IndexVariables.data(), 2868 IndexVariables.size()); 2869 return false; 2870 } 2871 2872 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!"); 2873 2874 QualType FieldBaseElementType = 2875 SemaRef.Context.getBaseElementType(Field->getType()); 2876 2877 if (FieldBaseElementType->isRecordType()) { 2878 InitializedEntity InitEntity 2879 = Indirect? InitializedEntity::InitializeMember(Indirect) 2880 : InitializedEntity::InitializeMember(Field); 2881 InitializationKind InitKind = 2882 InitializationKind::CreateDefault(Loc); 2883 2884 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0); 2885 ExprResult MemberInit = 2886 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg()); 2887 2888 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 2889 if (MemberInit.isInvalid()) 2890 return true; 2891 2892 if (Indirect) 2893 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 2894 Indirect, Loc, 2895 Loc, 2896 MemberInit.get(), 2897 Loc); 2898 else 2899 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 2900 Field, Loc, Loc, 2901 MemberInit.get(), 2902 Loc); 2903 return false; 2904 } 2905 2906 if (!Field->getParent()->isUnion()) { 2907 if (FieldBaseElementType->isReferenceType()) { 2908 SemaRef.Diag(Constructor->getLocation(), 2909 diag::err_uninitialized_member_in_ctor) 2910 << (int)Constructor->isImplicit() 2911 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 2912 << 0 << Field->getDeclName(); 2913 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 2914 return true; 2915 } 2916 2917 if (FieldBaseElementType.isConstQualified()) { 2918 SemaRef.Diag(Constructor->getLocation(), 2919 diag::err_uninitialized_member_in_ctor) 2920 << (int)Constructor->isImplicit() 2921 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 2922 << 1 << Field->getDeclName(); 2923 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 2924 return true; 2925 } 2926 } 2927 2928 if (SemaRef.getLangOpts().ObjCAutoRefCount && 2929 FieldBaseElementType->isObjCRetainableType() && 2930 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None && 2931 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) { 2932 // ARC: 2933 // Default-initialize Objective-C pointers to NULL. 2934 CXXMemberInit 2935 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 2936 Loc, Loc, 2937 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 2938 Loc); 2939 return false; 2940 } 2941 2942 // Nothing to initialize. 2943 CXXMemberInit = 0; 2944 return false; 2945} 2946 2947namespace { 2948struct BaseAndFieldInfo { 2949 Sema &S; 2950 CXXConstructorDecl *Ctor; 2951 bool AnyErrorsInInits; 2952 ImplicitInitializerKind IIK; 2953 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 2954 SmallVector<CXXCtorInitializer*, 8> AllToInit; 2955 2956 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 2957 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 2958 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 2959 if (Generated && Ctor->isCopyConstructor()) 2960 IIK = IIK_Copy; 2961 else if (Generated && Ctor->isMoveConstructor()) 2962 IIK = IIK_Move; 2963 else 2964 IIK = IIK_Default; 2965 } 2966 2967 bool isImplicitCopyOrMove() const { 2968 switch (IIK) { 2969 case IIK_Copy: 2970 case IIK_Move: 2971 return true; 2972 2973 case IIK_Default: 2974 return false; 2975 } 2976 2977 llvm_unreachable("Invalid ImplicitInitializerKind!"); 2978 } 2979 2980 bool addFieldInitializer(CXXCtorInitializer *Init) { 2981 AllToInit.push_back(Init); 2982 2983 // Check whether this initializer makes the field "used". 2984 if (Init->getInit() && Init->getInit()->HasSideEffects(S.Context)) 2985 S.UnusedPrivateFields.remove(Init->getAnyMember()); 2986 2987 return false; 2988 } 2989}; 2990} 2991 2992/// \brief Determine whether the given indirect field declaration is somewhere 2993/// within an anonymous union. 2994static bool isWithinAnonymousUnion(IndirectFieldDecl *F) { 2995 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(), 2996 CEnd = F->chain_end(); 2997 C != CEnd; ++C) 2998 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext())) 2999 if (Record->isUnion()) 3000 return true; 3001 3002 return false; 3003} 3004 3005/// \brief Determine whether the given type is an incomplete or zero-lenfgth 3006/// array type. 3007static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 3008 if (T->isIncompleteArrayType()) 3009 return true; 3010 3011 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 3012 if (!ArrayT->getSize()) 3013 return true; 3014 3015 T = ArrayT->getElementType(); 3016 } 3017 3018 return false; 3019} 3020 3021static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 3022 FieldDecl *Field, 3023 IndirectFieldDecl *Indirect = 0) { 3024 3025 // Overwhelmingly common case: we have a direct initializer for this field. 3026 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) 3027 return Info.addFieldInitializer(Init); 3028 3029 // C++11 [class.base.init]p8: if the entity is a non-static data member that 3030 // has a brace-or-equal-initializer, the entity is initialized as specified 3031 // in [dcl.init]. 3032 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 3033 CXXCtorInitializer *Init; 3034 if (Indirect) 3035 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 3036 SourceLocation(), 3037 SourceLocation(), 0, 3038 SourceLocation()); 3039 else 3040 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 3041 SourceLocation(), 3042 SourceLocation(), 0, 3043 SourceLocation()); 3044 return Info.addFieldInitializer(Init); 3045 } 3046 3047 // Don't build an implicit initializer for union members if none was 3048 // explicitly specified. 3049 if (Field->getParent()->isUnion() || 3050 (Indirect && isWithinAnonymousUnion(Indirect))) 3051 return false; 3052 3053 // Don't initialize incomplete or zero-length arrays. 3054 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 3055 return false; 3056 3057 // Don't try to build an implicit initializer if there were semantic 3058 // errors in any of the initializers (and therefore we might be 3059 // missing some that the user actually wrote). 3060 if (Info.AnyErrorsInInits || Field->isInvalidDecl()) 3061 return false; 3062 3063 CXXCtorInitializer *Init = 0; 3064 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 3065 Indirect, Init)) 3066 return true; 3067 3068 if (!Init) 3069 return false; 3070 3071 return Info.addFieldInitializer(Init); 3072} 3073 3074bool 3075Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 3076 CXXCtorInitializer *Initializer) { 3077 assert(Initializer->isDelegatingInitializer()); 3078 Constructor->setNumCtorInitializers(1); 3079 CXXCtorInitializer **initializer = 3080 new (Context) CXXCtorInitializer*[1]; 3081 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 3082 Constructor->setCtorInitializers(initializer); 3083 3084 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 3085 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 3086 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 3087 } 3088 3089 DelegatingCtorDecls.push_back(Constructor); 3090 3091 return false; 3092} 3093 3094bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 3095 ArrayRef<CXXCtorInitializer *> Initializers) { 3096 if (Constructor->isDependentContext()) { 3097 // Just store the initializers as written, they will be checked during 3098 // instantiation. 3099 if (!Initializers.empty()) { 3100 Constructor->setNumCtorInitializers(Initializers.size()); 3101 CXXCtorInitializer **baseOrMemberInitializers = 3102 new (Context) CXXCtorInitializer*[Initializers.size()]; 3103 memcpy(baseOrMemberInitializers, Initializers.data(), 3104 Initializers.size() * sizeof(CXXCtorInitializer*)); 3105 Constructor->setCtorInitializers(baseOrMemberInitializers); 3106 } 3107 3108 // Let template instantiation know whether we had errors. 3109 if (AnyErrors) 3110 Constructor->setInvalidDecl(); 3111 3112 return false; 3113 } 3114 3115 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 3116 3117 // We need to build the initializer AST according to order of construction 3118 // and not what user specified in the Initializers list. 3119 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 3120 if (!ClassDecl) 3121 return true; 3122 3123 bool HadError = false; 3124 3125 for (unsigned i = 0; i < Initializers.size(); i++) { 3126 CXXCtorInitializer *Member = Initializers[i]; 3127 3128 if (Member->isBaseInitializer()) 3129 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 3130 else 3131 Info.AllBaseFields[Member->getAnyMember()] = Member; 3132 } 3133 3134 // Keep track of the direct virtual bases. 3135 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 3136 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(), 3137 E = ClassDecl->bases_end(); I != E; ++I) { 3138 if (I->isVirtual()) 3139 DirectVBases.insert(I); 3140 } 3141 3142 // Push virtual bases before others. 3143 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 3144 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 3145 3146 if (CXXCtorInitializer *Value 3147 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) { 3148 Info.AllToInit.push_back(Value); 3149 } else if (!AnyErrors) { 3150 bool IsInheritedVirtualBase = !DirectVBases.count(VBase); 3151 CXXCtorInitializer *CXXBaseInit; 3152 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3153 VBase, IsInheritedVirtualBase, 3154 CXXBaseInit)) { 3155 HadError = true; 3156 continue; 3157 } 3158 3159 Info.AllToInit.push_back(CXXBaseInit); 3160 } 3161 } 3162 3163 // Non-virtual bases. 3164 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 3165 E = ClassDecl->bases_end(); Base != E; ++Base) { 3166 // Virtuals are in the virtual base list and already constructed. 3167 if (Base->isVirtual()) 3168 continue; 3169 3170 if (CXXCtorInitializer *Value 3171 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) { 3172 Info.AllToInit.push_back(Value); 3173 } else if (!AnyErrors) { 3174 CXXCtorInitializer *CXXBaseInit; 3175 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3176 Base, /*IsInheritedVirtualBase=*/false, 3177 CXXBaseInit)) { 3178 HadError = true; 3179 continue; 3180 } 3181 3182 Info.AllToInit.push_back(CXXBaseInit); 3183 } 3184 } 3185 3186 // Fields. 3187 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(), 3188 MemEnd = ClassDecl->decls_end(); 3189 Mem != MemEnd; ++Mem) { 3190 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) { 3191 // C++ [class.bit]p2: 3192 // A declaration for a bit-field that omits the identifier declares an 3193 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 3194 // initialized. 3195 if (F->isUnnamedBitfield()) 3196 continue; 3197 3198 // If we're not generating the implicit copy/move constructor, then we'll 3199 // handle anonymous struct/union fields based on their individual 3200 // indirect fields. 3201 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default) 3202 continue; 3203 3204 if (CollectFieldInitializer(*this, Info, F)) 3205 HadError = true; 3206 continue; 3207 } 3208 3209 // Beyond this point, we only consider default initialization. 3210 if (Info.IIK != IIK_Default) 3211 continue; 3212 3213 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) { 3214 if (F->getType()->isIncompleteArrayType()) { 3215 assert(ClassDecl->hasFlexibleArrayMember() && 3216 "Incomplete array type is not valid"); 3217 continue; 3218 } 3219 3220 // Initialize each field of an anonymous struct individually. 3221 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 3222 HadError = true; 3223 3224 continue; 3225 } 3226 } 3227 3228 unsigned NumInitializers = Info.AllToInit.size(); 3229 if (NumInitializers > 0) { 3230 Constructor->setNumCtorInitializers(NumInitializers); 3231 CXXCtorInitializer **baseOrMemberInitializers = 3232 new (Context) CXXCtorInitializer*[NumInitializers]; 3233 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 3234 NumInitializers * sizeof(CXXCtorInitializer*)); 3235 Constructor->setCtorInitializers(baseOrMemberInitializers); 3236 3237 // Constructors implicitly reference the base and member 3238 // destructors. 3239 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 3240 Constructor->getParent()); 3241 } 3242 3243 return HadError; 3244} 3245 3246static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 3247 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 3248 const RecordDecl *RD = RT->getDecl(); 3249 if (RD->isAnonymousStructOrUnion()) { 3250 for (RecordDecl::field_iterator Field = RD->field_begin(), 3251 E = RD->field_end(); Field != E; ++Field) 3252 PopulateKeysForFields(*Field, IdealInits); 3253 return; 3254 } 3255 } 3256 IdealInits.push_back(Field); 3257} 3258 3259static void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 3260 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr()); 3261} 3262 3263static void *GetKeyForMember(ASTContext &Context, 3264 CXXCtorInitializer *Member) { 3265 if (!Member->isAnyMemberInitializer()) 3266 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 3267 3268 return Member->getAnyMember(); 3269} 3270 3271static void DiagnoseBaseOrMemInitializerOrder( 3272 Sema &SemaRef, const CXXConstructorDecl *Constructor, 3273 ArrayRef<CXXCtorInitializer *> Inits) { 3274 if (Constructor->getDeclContext()->isDependentContext()) 3275 return; 3276 3277 // Don't check initializers order unless the warning is enabled at the 3278 // location of at least one initializer. 3279 bool ShouldCheckOrder = false; 3280 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 3281 CXXCtorInitializer *Init = Inits[InitIndex]; 3282 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order, 3283 Init->getSourceLocation()) 3284 != DiagnosticsEngine::Ignored) { 3285 ShouldCheckOrder = true; 3286 break; 3287 } 3288 } 3289 if (!ShouldCheckOrder) 3290 return; 3291 3292 // Build the list of bases and members in the order that they'll 3293 // actually be initialized. The explicit initializers should be in 3294 // this same order but may be missing things. 3295 SmallVector<const void*, 32> IdealInitKeys; 3296 3297 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 3298 3299 // 1. Virtual bases. 3300 for (CXXRecordDecl::base_class_const_iterator VBase = 3301 ClassDecl->vbases_begin(), 3302 E = ClassDecl->vbases_end(); VBase != E; ++VBase) 3303 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType())); 3304 3305 // 2. Non-virtual bases. 3306 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(), 3307 E = ClassDecl->bases_end(); Base != E; ++Base) { 3308 if (Base->isVirtual()) 3309 continue; 3310 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType())); 3311 } 3312 3313 // 3. Direct fields. 3314 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 3315 E = ClassDecl->field_end(); Field != E; ++Field) { 3316 if (Field->isUnnamedBitfield()) 3317 continue; 3318 3319 PopulateKeysForFields(*Field, IdealInitKeys); 3320 } 3321 3322 unsigned NumIdealInits = IdealInitKeys.size(); 3323 unsigned IdealIndex = 0; 3324 3325 CXXCtorInitializer *PrevInit = 0; 3326 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 3327 CXXCtorInitializer *Init = Inits[InitIndex]; 3328 void *InitKey = GetKeyForMember(SemaRef.Context, Init); 3329 3330 // Scan forward to try to find this initializer in the idealized 3331 // initializers list. 3332 for (; IdealIndex != NumIdealInits; ++IdealIndex) 3333 if (InitKey == IdealInitKeys[IdealIndex]) 3334 break; 3335 3336 // If we didn't find this initializer, it must be because we 3337 // scanned past it on a previous iteration. That can only 3338 // happen if we're out of order; emit a warning. 3339 if (IdealIndex == NumIdealInits && PrevInit) { 3340 Sema::SemaDiagnosticBuilder D = 3341 SemaRef.Diag(PrevInit->getSourceLocation(), 3342 diag::warn_initializer_out_of_order); 3343 3344 if (PrevInit->isAnyMemberInitializer()) 3345 D << 0 << PrevInit->getAnyMember()->getDeclName(); 3346 else 3347 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 3348 3349 if (Init->isAnyMemberInitializer()) 3350 D << 0 << Init->getAnyMember()->getDeclName(); 3351 else 3352 D << 1 << Init->getTypeSourceInfo()->getType(); 3353 3354 // Move back to the initializer's location in the ideal list. 3355 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 3356 if (InitKey == IdealInitKeys[IdealIndex]) 3357 break; 3358 3359 assert(IdealIndex != NumIdealInits && 3360 "initializer not found in initializer list"); 3361 } 3362 3363 PrevInit = Init; 3364 } 3365} 3366 3367namespace { 3368bool CheckRedundantInit(Sema &S, 3369 CXXCtorInitializer *Init, 3370 CXXCtorInitializer *&PrevInit) { 3371 if (!PrevInit) { 3372 PrevInit = Init; 3373 return false; 3374 } 3375 3376 if (FieldDecl *Field = Init->getMember()) 3377 S.Diag(Init->getSourceLocation(), 3378 diag::err_multiple_mem_initialization) 3379 << Field->getDeclName() 3380 << Init->getSourceRange(); 3381 else { 3382 const Type *BaseClass = Init->getBaseClass(); 3383 assert(BaseClass && "neither field nor base"); 3384 S.Diag(Init->getSourceLocation(), 3385 diag::err_multiple_base_initialization) 3386 << QualType(BaseClass, 0) 3387 << Init->getSourceRange(); 3388 } 3389 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 3390 << 0 << PrevInit->getSourceRange(); 3391 3392 return true; 3393} 3394 3395typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 3396typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 3397 3398bool CheckRedundantUnionInit(Sema &S, 3399 CXXCtorInitializer *Init, 3400 RedundantUnionMap &Unions) { 3401 FieldDecl *Field = Init->getAnyMember(); 3402 RecordDecl *Parent = Field->getParent(); 3403 NamedDecl *Child = Field; 3404 3405 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 3406 if (Parent->isUnion()) { 3407 UnionEntry &En = Unions[Parent]; 3408 if (En.first && En.first != Child) { 3409 S.Diag(Init->getSourceLocation(), 3410 diag::err_multiple_mem_union_initialization) 3411 << Field->getDeclName() 3412 << Init->getSourceRange(); 3413 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 3414 << 0 << En.second->getSourceRange(); 3415 return true; 3416 } 3417 if (!En.first) { 3418 En.first = Child; 3419 En.second = Init; 3420 } 3421 if (!Parent->isAnonymousStructOrUnion()) 3422 return false; 3423 } 3424 3425 Child = Parent; 3426 Parent = cast<RecordDecl>(Parent->getDeclContext()); 3427 } 3428 3429 return false; 3430} 3431} 3432 3433/// ActOnMemInitializers - Handle the member initializers for a constructor. 3434void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 3435 SourceLocation ColonLoc, 3436 ArrayRef<CXXCtorInitializer*> MemInits, 3437 bool AnyErrors) { 3438 if (!ConstructorDecl) 3439 return; 3440 3441 AdjustDeclIfTemplate(ConstructorDecl); 3442 3443 CXXConstructorDecl *Constructor 3444 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 3445 3446 if (!Constructor) { 3447 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 3448 return; 3449 } 3450 3451 // Mapping for the duplicate initializers check. 3452 // For member initializers, this is keyed with a FieldDecl*. 3453 // For base initializers, this is keyed with a Type*. 3454 llvm::DenseMap<void*, CXXCtorInitializer *> Members; 3455 3456 // Mapping for the inconsistent anonymous-union initializers check. 3457 RedundantUnionMap MemberUnions; 3458 3459 bool HadError = false; 3460 for (unsigned i = 0; i < MemInits.size(); i++) { 3461 CXXCtorInitializer *Init = MemInits[i]; 3462 3463 // Set the source order index. 3464 Init->setSourceOrder(i); 3465 3466 if (Init->isAnyMemberInitializer()) { 3467 FieldDecl *Field = Init->getAnyMember(); 3468 if (CheckRedundantInit(*this, Init, Members[Field]) || 3469 CheckRedundantUnionInit(*this, Init, MemberUnions)) 3470 HadError = true; 3471 } else if (Init->isBaseInitializer()) { 3472 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0)); 3473 if (CheckRedundantInit(*this, Init, Members[Key])) 3474 HadError = true; 3475 } else { 3476 assert(Init->isDelegatingInitializer()); 3477 // This must be the only initializer 3478 if (MemInits.size() != 1) { 3479 Diag(Init->getSourceLocation(), 3480 diag::err_delegating_initializer_alone) 3481 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 3482 // We will treat this as being the only initializer. 3483 } 3484 SetDelegatingInitializer(Constructor, MemInits[i]); 3485 // Return immediately as the initializer is set. 3486 return; 3487 } 3488 } 3489 3490 if (HadError) 3491 return; 3492 3493 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 3494 3495 SetCtorInitializers(Constructor, AnyErrors, MemInits); 3496} 3497 3498void 3499Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 3500 CXXRecordDecl *ClassDecl) { 3501 // Ignore dependent contexts. Also ignore unions, since their members never 3502 // have destructors implicitly called. 3503 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 3504 return; 3505 3506 // FIXME: all the access-control diagnostics are positioned on the 3507 // field/base declaration. That's probably good; that said, the 3508 // user might reasonably want to know why the destructor is being 3509 // emitted, and we currently don't say. 3510 3511 // Non-static data members. 3512 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(), 3513 E = ClassDecl->field_end(); I != E; ++I) { 3514 FieldDecl *Field = *I; 3515 if (Field->isInvalidDecl()) 3516 continue; 3517 3518 // Don't destroy incomplete or zero-length arrays. 3519 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 3520 continue; 3521 3522 QualType FieldType = Context.getBaseElementType(Field->getType()); 3523 3524 const RecordType* RT = FieldType->getAs<RecordType>(); 3525 if (!RT) 3526 continue; 3527 3528 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3529 if (FieldClassDecl->isInvalidDecl()) 3530 continue; 3531 if (FieldClassDecl->hasIrrelevantDestructor()) 3532 continue; 3533 // The destructor for an implicit anonymous union member is never invoked. 3534 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 3535 continue; 3536 3537 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 3538 assert(Dtor && "No dtor found for FieldClassDecl!"); 3539 CheckDestructorAccess(Field->getLocation(), Dtor, 3540 PDiag(diag::err_access_dtor_field) 3541 << Field->getDeclName() 3542 << FieldType); 3543 3544 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 3545 DiagnoseUseOfDecl(Dtor, Location); 3546 } 3547 3548 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 3549 3550 // Bases. 3551 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 3552 E = ClassDecl->bases_end(); Base != E; ++Base) { 3553 // Bases are always records in a well-formed non-dependent class. 3554 const RecordType *RT = Base->getType()->getAs<RecordType>(); 3555 3556 // Remember direct virtual bases. 3557 if (Base->isVirtual()) 3558 DirectVirtualBases.insert(RT); 3559 3560 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3561 // If our base class is invalid, we probably can't get its dtor anyway. 3562 if (BaseClassDecl->isInvalidDecl()) 3563 continue; 3564 if (BaseClassDecl->hasIrrelevantDestructor()) 3565 continue; 3566 3567 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 3568 assert(Dtor && "No dtor found for BaseClassDecl!"); 3569 3570 // FIXME: caret should be on the start of the class name 3571 CheckDestructorAccess(Base->getLocStart(), Dtor, 3572 PDiag(diag::err_access_dtor_base) 3573 << Base->getType() 3574 << Base->getSourceRange(), 3575 Context.getTypeDeclType(ClassDecl)); 3576 3577 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 3578 DiagnoseUseOfDecl(Dtor, Location); 3579 } 3580 3581 // Virtual bases. 3582 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 3583 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 3584 3585 // Bases are always records in a well-formed non-dependent class. 3586 const RecordType *RT = VBase->getType()->castAs<RecordType>(); 3587 3588 // Ignore direct virtual bases. 3589 if (DirectVirtualBases.count(RT)) 3590 continue; 3591 3592 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3593 // If our base class is invalid, we probably can't get its dtor anyway. 3594 if (BaseClassDecl->isInvalidDecl()) 3595 continue; 3596 if (BaseClassDecl->hasIrrelevantDestructor()) 3597 continue; 3598 3599 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 3600 assert(Dtor && "No dtor found for BaseClassDecl!"); 3601 CheckDestructorAccess(ClassDecl->getLocation(), Dtor, 3602 PDiag(diag::err_access_dtor_vbase) 3603 << VBase->getType(), 3604 Context.getTypeDeclType(ClassDecl)); 3605 3606 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 3607 DiagnoseUseOfDecl(Dtor, Location); 3608 } 3609} 3610 3611void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 3612 if (!CDtorDecl) 3613 return; 3614 3615 if (CXXConstructorDecl *Constructor 3616 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) 3617 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 3618} 3619 3620bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 3621 unsigned DiagID, AbstractDiagSelID SelID) { 3622 class NonAbstractTypeDiagnoser : public TypeDiagnoser { 3623 unsigned DiagID; 3624 AbstractDiagSelID SelID; 3625 3626 public: 3627 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID) 3628 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { } 3629 3630 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 3631 if (Suppressed) return; 3632 if (SelID == -1) 3633 S.Diag(Loc, DiagID) << T; 3634 else 3635 S.Diag(Loc, DiagID) << SelID << T; 3636 } 3637 } Diagnoser(DiagID, SelID); 3638 3639 return RequireNonAbstractType(Loc, T, Diagnoser); 3640} 3641 3642bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 3643 TypeDiagnoser &Diagnoser) { 3644 if (!getLangOpts().CPlusPlus) 3645 return false; 3646 3647 if (const ArrayType *AT = Context.getAsArrayType(T)) 3648 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 3649 3650 if (const PointerType *PT = T->getAs<PointerType>()) { 3651 // Find the innermost pointer type. 3652 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 3653 PT = T; 3654 3655 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 3656 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 3657 } 3658 3659 const RecordType *RT = T->getAs<RecordType>(); 3660 if (!RT) 3661 return false; 3662 3663 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 3664 3665 // We can't answer whether something is abstract until it has a 3666 // definition. If it's currently being defined, we'll walk back 3667 // over all the declarations when we have a full definition. 3668 const CXXRecordDecl *Def = RD->getDefinition(); 3669 if (!Def || Def->isBeingDefined()) 3670 return false; 3671 3672 if (!RD->isAbstract()) 3673 return false; 3674 3675 Diagnoser.diagnose(*this, Loc, T); 3676 DiagnoseAbstractType(RD); 3677 3678 return true; 3679} 3680 3681void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 3682 // Check if we've already emitted the list of pure virtual functions 3683 // for this class. 3684 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 3685 return; 3686 3687 CXXFinalOverriderMap FinalOverriders; 3688 RD->getFinalOverriders(FinalOverriders); 3689 3690 // Keep a set of seen pure methods so we won't diagnose the same method 3691 // more than once. 3692 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 3693 3694 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 3695 MEnd = FinalOverriders.end(); 3696 M != MEnd; 3697 ++M) { 3698 for (OverridingMethods::iterator SO = M->second.begin(), 3699 SOEnd = M->second.end(); 3700 SO != SOEnd; ++SO) { 3701 // C++ [class.abstract]p4: 3702 // A class is abstract if it contains or inherits at least one 3703 // pure virtual function for which the final overrider is pure 3704 // virtual. 3705 3706 // 3707 if (SO->second.size() != 1) 3708 continue; 3709 3710 if (!SO->second.front().Method->isPure()) 3711 continue; 3712 3713 if (!SeenPureMethods.insert(SO->second.front().Method)) 3714 continue; 3715 3716 Diag(SO->second.front().Method->getLocation(), 3717 diag::note_pure_virtual_function) 3718 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 3719 } 3720 } 3721 3722 if (!PureVirtualClassDiagSet) 3723 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 3724 PureVirtualClassDiagSet->insert(RD); 3725} 3726 3727namespace { 3728struct AbstractUsageInfo { 3729 Sema &S; 3730 CXXRecordDecl *Record; 3731 CanQualType AbstractType; 3732 bool Invalid; 3733 3734 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 3735 : S(S), Record(Record), 3736 AbstractType(S.Context.getCanonicalType( 3737 S.Context.getTypeDeclType(Record))), 3738 Invalid(false) {} 3739 3740 void DiagnoseAbstractType() { 3741 if (Invalid) return; 3742 S.DiagnoseAbstractType(Record); 3743 Invalid = true; 3744 } 3745 3746 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 3747}; 3748 3749struct CheckAbstractUsage { 3750 AbstractUsageInfo &Info; 3751 const NamedDecl *Ctx; 3752 3753 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 3754 : Info(Info), Ctx(Ctx) {} 3755 3756 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 3757 switch (TL.getTypeLocClass()) { 3758#define ABSTRACT_TYPELOC(CLASS, PARENT) 3759#define TYPELOC(CLASS, PARENT) \ 3760 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break; 3761#include "clang/AST/TypeLocNodes.def" 3762 } 3763 } 3764 3765 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 3766 Visit(TL.getResultLoc(), Sema::AbstractReturnType); 3767 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 3768 if (!TL.getArg(I)) 3769 continue; 3770 3771 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo(); 3772 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 3773 } 3774 } 3775 3776 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 3777 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 3778 } 3779 3780 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 3781 // Visit the type parameters from a permissive context. 3782 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 3783 TemplateArgumentLoc TAL = TL.getArgLoc(I); 3784 if (TAL.getArgument().getKind() == TemplateArgument::Type) 3785 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 3786 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 3787 // TODO: other template argument types? 3788 } 3789 } 3790 3791 // Visit pointee types from a permissive context. 3792#define CheckPolymorphic(Type) \ 3793 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 3794 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 3795 } 3796 CheckPolymorphic(PointerTypeLoc) 3797 CheckPolymorphic(ReferenceTypeLoc) 3798 CheckPolymorphic(MemberPointerTypeLoc) 3799 CheckPolymorphic(BlockPointerTypeLoc) 3800 CheckPolymorphic(AtomicTypeLoc) 3801 3802 /// Handle all the types we haven't given a more specific 3803 /// implementation for above. 3804 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 3805 // Every other kind of type that we haven't called out already 3806 // that has an inner type is either (1) sugar or (2) contains that 3807 // inner type in some way as a subobject. 3808 if (TypeLoc Next = TL.getNextTypeLoc()) 3809 return Visit(Next, Sel); 3810 3811 // If there's no inner type and we're in a permissive context, 3812 // don't diagnose. 3813 if (Sel == Sema::AbstractNone) return; 3814 3815 // Check whether the type matches the abstract type. 3816 QualType T = TL.getType(); 3817 if (T->isArrayType()) { 3818 Sel = Sema::AbstractArrayType; 3819 T = Info.S.Context.getBaseElementType(T); 3820 } 3821 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 3822 if (CT != Info.AbstractType) return; 3823 3824 // It matched; do some magic. 3825 if (Sel == Sema::AbstractArrayType) { 3826 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 3827 << T << TL.getSourceRange(); 3828 } else { 3829 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 3830 << Sel << T << TL.getSourceRange(); 3831 } 3832 Info.DiagnoseAbstractType(); 3833 } 3834}; 3835 3836void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 3837 Sema::AbstractDiagSelID Sel) { 3838 CheckAbstractUsage(*this, D).Visit(TL, Sel); 3839} 3840 3841} 3842 3843/// Check for invalid uses of an abstract type in a method declaration. 3844static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 3845 CXXMethodDecl *MD) { 3846 // No need to do the check on definitions, which require that 3847 // the return/param types be complete. 3848 if (MD->doesThisDeclarationHaveABody()) 3849 return; 3850 3851 // For safety's sake, just ignore it if we don't have type source 3852 // information. This should never happen for non-implicit methods, 3853 // but... 3854 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 3855 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 3856} 3857 3858/// Check for invalid uses of an abstract type within a class definition. 3859static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 3860 CXXRecordDecl *RD) { 3861 for (CXXRecordDecl::decl_iterator 3862 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) { 3863 Decl *D = *I; 3864 if (D->isImplicit()) continue; 3865 3866 // Methods and method templates. 3867 if (isa<CXXMethodDecl>(D)) { 3868 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 3869 } else if (isa<FunctionTemplateDecl>(D)) { 3870 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 3871 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 3872 3873 // Fields and static variables. 3874 } else if (isa<FieldDecl>(D)) { 3875 FieldDecl *FD = cast<FieldDecl>(D); 3876 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 3877 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 3878 } else if (isa<VarDecl>(D)) { 3879 VarDecl *VD = cast<VarDecl>(D); 3880 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 3881 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 3882 3883 // Nested classes and class templates. 3884 } else if (isa<CXXRecordDecl>(D)) { 3885 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 3886 } else if (isa<ClassTemplateDecl>(D)) { 3887 CheckAbstractClassUsage(Info, 3888 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 3889 } 3890 } 3891} 3892 3893/// \brief Perform semantic checks on a class definition that has been 3894/// completing, introducing implicitly-declared members, checking for 3895/// abstract types, etc. 3896void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 3897 if (!Record) 3898 return; 3899 3900 if (Record->isAbstract() && !Record->isInvalidDecl()) { 3901 AbstractUsageInfo Info(*this, Record); 3902 CheckAbstractClassUsage(Info, Record); 3903 } 3904 3905 // If this is not an aggregate type and has no user-declared constructor, 3906 // complain about any non-static data members of reference or const scalar 3907 // type, since they will never get initializers. 3908 if (!Record->isInvalidDecl() && !Record->isDependentType() && 3909 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 3910 !Record->isLambda()) { 3911 bool Complained = false; 3912 for (RecordDecl::field_iterator F = Record->field_begin(), 3913 FEnd = Record->field_end(); 3914 F != FEnd; ++F) { 3915 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 3916 continue; 3917 3918 if (F->getType()->isReferenceType() || 3919 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 3920 if (!Complained) { 3921 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 3922 << Record->getTagKind() << Record; 3923 Complained = true; 3924 } 3925 3926 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 3927 << F->getType()->isReferenceType() 3928 << F->getDeclName(); 3929 } 3930 } 3931 } 3932 3933 if (Record->isDynamicClass() && !Record->isDependentType()) 3934 DynamicClasses.push_back(Record); 3935 3936 if (Record->getIdentifier()) { 3937 // C++ [class.mem]p13: 3938 // If T is the name of a class, then each of the following shall have a 3939 // name different from T: 3940 // - every member of every anonymous union that is a member of class T. 3941 // 3942 // C++ [class.mem]p14: 3943 // In addition, if class T has a user-declared constructor (12.1), every 3944 // non-static data member of class T shall have a name different from T. 3945 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 3946 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 3947 ++I) { 3948 NamedDecl *D = *I; 3949 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 3950 isa<IndirectFieldDecl>(D)) { 3951 Diag(D->getLocation(), diag::err_member_name_of_class) 3952 << D->getDeclName(); 3953 break; 3954 } 3955 } 3956 } 3957 3958 // Warn if the class has virtual methods but non-virtual public destructor. 3959 if (Record->isPolymorphic() && !Record->isDependentType()) { 3960 CXXDestructorDecl *dtor = Record->getDestructor(); 3961 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) 3962 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 3963 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 3964 } 3965 3966 if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) { 3967 Diag(Record->getLocation(), diag::warn_abstract_final_class); 3968 DiagnoseAbstractType(Record); 3969 } 3970 3971 if (!Record->isDependentType()) { 3972 for (CXXRecordDecl::method_iterator M = Record->method_begin(), 3973 MEnd = Record->method_end(); 3974 M != MEnd; ++M) { 3975 // See if a method overloads virtual methods in a base 3976 // class without overriding any. 3977 if (!M->isStatic()) 3978 DiagnoseHiddenVirtualMethods(Record, *M); 3979 3980 // Check whether the explicitly-defaulted special members are valid. 3981 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) 3982 CheckExplicitlyDefaultedSpecialMember(*M); 3983 3984 // For an explicitly defaulted or deleted special member, we defer 3985 // determining triviality until the class is complete. That time is now! 3986 if (!M->isImplicit() && !M->isUserProvided()) { 3987 CXXSpecialMember CSM = getSpecialMember(*M); 3988 if (CSM != CXXInvalid) { 3989 M->setTrivial(SpecialMemberIsTrivial(*M, CSM)); 3990 3991 // Inform the class that we've finished declaring this member. 3992 Record->finishedDefaultedOrDeletedMember(*M); 3993 } 3994 } 3995 } 3996 } 3997 3998 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member 3999 // function that is not a constructor declares that member function to be 4000 // const. [...] The class of which that function is a member shall be 4001 // a literal type. 4002 // 4003 // If the class has virtual bases, any constexpr members will already have 4004 // been diagnosed by the checks performed on the member declaration, so 4005 // suppress this (less useful) diagnostic. 4006 // 4007 // We delay this until we know whether an explicitly-defaulted (or deleted) 4008 // destructor for the class is trivial. 4009 if (LangOpts.CPlusPlus11 && !Record->isDependentType() && 4010 !Record->isLiteral() && !Record->getNumVBases()) { 4011 for (CXXRecordDecl::method_iterator M = Record->method_begin(), 4012 MEnd = Record->method_end(); 4013 M != MEnd; ++M) { 4014 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) { 4015 switch (Record->getTemplateSpecializationKind()) { 4016 case TSK_ImplicitInstantiation: 4017 case TSK_ExplicitInstantiationDeclaration: 4018 case TSK_ExplicitInstantiationDefinition: 4019 // If a template instantiates to a non-literal type, but its members 4020 // instantiate to constexpr functions, the template is technically 4021 // ill-formed, but we allow it for sanity. 4022 continue; 4023 4024 case TSK_Undeclared: 4025 case TSK_ExplicitSpecialization: 4026 RequireLiteralType(M->getLocation(), Context.getRecordType(Record), 4027 diag::err_constexpr_method_non_literal); 4028 break; 4029 } 4030 4031 // Only produce one error per class. 4032 break; 4033 } 4034 } 4035 } 4036 4037 // Declare inherited constructors. We do this eagerly here because: 4038 // - The standard requires an eager diagnostic for conflicting inherited 4039 // constructors from different classes. 4040 // - The lazy declaration of the other implicit constructors is so as to not 4041 // waste space and performance on classes that are not meant to be 4042 // instantiated (e.g. meta-functions). This doesn't apply to classes that 4043 // have inherited constructors. 4044 DeclareInheritedConstructors(Record); 4045} 4046 4047/// Is the special member function which would be selected to perform the 4048/// specified operation on the specified class type a constexpr constructor? 4049static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 4050 Sema::CXXSpecialMember CSM, 4051 bool ConstArg) { 4052 Sema::SpecialMemberOverloadResult *SMOR = 4053 S.LookupSpecialMember(ClassDecl, CSM, ConstArg, 4054 false, false, false, false); 4055 if (!SMOR || !SMOR->getMethod()) 4056 // A constructor we wouldn't select can't be "involved in initializing" 4057 // anything. 4058 return true; 4059 return SMOR->getMethod()->isConstexpr(); 4060} 4061 4062/// Determine whether the specified special member function would be constexpr 4063/// if it were implicitly defined. 4064static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 4065 Sema::CXXSpecialMember CSM, 4066 bool ConstArg) { 4067 if (!S.getLangOpts().CPlusPlus11) 4068 return false; 4069 4070 // C++11 [dcl.constexpr]p4: 4071 // In the definition of a constexpr constructor [...] 4072 switch (CSM) { 4073 case Sema::CXXDefaultConstructor: 4074 // Since default constructor lookup is essentially trivial (and cannot 4075 // involve, for instance, template instantiation), we compute whether a 4076 // defaulted default constructor is constexpr directly within CXXRecordDecl. 4077 // 4078 // This is important for performance; we need to know whether the default 4079 // constructor is constexpr to determine whether the type is a literal type. 4080 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 4081 4082 case Sema::CXXCopyConstructor: 4083 case Sema::CXXMoveConstructor: 4084 // For copy or move constructors, we need to perform overload resolution. 4085 break; 4086 4087 case Sema::CXXCopyAssignment: 4088 case Sema::CXXMoveAssignment: 4089 case Sema::CXXDestructor: 4090 case Sema::CXXInvalid: 4091 return false; 4092 } 4093 4094 // -- if the class is a non-empty union, or for each non-empty anonymous 4095 // union member of a non-union class, exactly one non-static data member 4096 // shall be initialized; [DR1359] 4097 // 4098 // If we squint, this is guaranteed, since exactly one non-static data member 4099 // will be initialized (if the constructor isn't deleted), we just don't know 4100 // which one. 4101 if (ClassDecl->isUnion()) 4102 return true; 4103 4104 // -- the class shall not have any virtual base classes; 4105 if (ClassDecl->getNumVBases()) 4106 return false; 4107 4108 // -- every constructor involved in initializing [...] base class 4109 // sub-objects shall be a constexpr constructor; 4110 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 4111 BEnd = ClassDecl->bases_end(); 4112 B != BEnd; ++B) { 4113 const RecordType *BaseType = B->getType()->getAs<RecordType>(); 4114 if (!BaseType) continue; 4115 4116 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 4117 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg)) 4118 return false; 4119 } 4120 4121 // -- every constructor involved in initializing non-static data members 4122 // [...] shall be a constexpr constructor; 4123 // -- every non-static data member and base class sub-object shall be 4124 // initialized 4125 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 4126 FEnd = ClassDecl->field_end(); 4127 F != FEnd; ++F) { 4128 if (F->isInvalidDecl()) 4129 continue; 4130 if (const RecordType *RecordTy = 4131 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 4132 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 4133 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg)) 4134 return false; 4135 } 4136 } 4137 4138 // All OK, it's constexpr! 4139 return true; 4140} 4141 4142static Sema::ImplicitExceptionSpecification 4143computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 4144 switch (S.getSpecialMember(MD)) { 4145 case Sema::CXXDefaultConstructor: 4146 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD); 4147 case Sema::CXXCopyConstructor: 4148 return S.ComputeDefaultedCopyCtorExceptionSpec(MD); 4149 case Sema::CXXCopyAssignment: 4150 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD); 4151 case Sema::CXXMoveConstructor: 4152 return S.ComputeDefaultedMoveCtorExceptionSpec(MD); 4153 case Sema::CXXMoveAssignment: 4154 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD); 4155 case Sema::CXXDestructor: 4156 return S.ComputeDefaultedDtorExceptionSpec(MD); 4157 case Sema::CXXInvalid: 4158 break; 4159 } 4160 llvm_unreachable("only special members have implicit exception specs"); 4161} 4162 4163static void 4164updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT, 4165 const Sema::ImplicitExceptionSpecification &ExceptSpec) { 4166 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 4167 ExceptSpec.getEPI(EPI); 4168 const FunctionProtoType *NewFPT = cast<FunctionProtoType>( 4169 S.Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(), 4170 FPT->getNumArgs(), EPI)); 4171 FD->setType(QualType(NewFPT, 0)); 4172} 4173 4174void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 4175 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 4176 if (FPT->getExceptionSpecType() != EST_Unevaluated) 4177 return; 4178 4179 // Evaluate the exception specification. 4180 ImplicitExceptionSpecification ExceptSpec = 4181 computeImplicitExceptionSpec(*this, Loc, MD); 4182 4183 // Update the type of the special member to use it. 4184 updateExceptionSpec(*this, MD, FPT, ExceptSpec); 4185 4186 // A user-provided destructor can be defined outside the class. When that 4187 // happens, be sure to update the exception specification on both 4188 // declarations. 4189 const FunctionProtoType *CanonicalFPT = 4190 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 4191 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 4192 updateExceptionSpec(*this, MD->getCanonicalDecl(), 4193 CanonicalFPT, ExceptSpec); 4194} 4195 4196void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 4197 CXXRecordDecl *RD = MD->getParent(); 4198 CXXSpecialMember CSM = getSpecialMember(MD); 4199 4200 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 4201 "not an explicitly-defaulted special member"); 4202 4203 // Whether this was the first-declared instance of the constructor. 4204 // This affects whether we implicitly add an exception spec and constexpr. 4205 bool First = MD == MD->getCanonicalDecl(); 4206 4207 bool HadError = false; 4208 4209 // C++11 [dcl.fct.def.default]p1: 4210 // A function that is explicitly defaulted shall 4211 // -- be a special member function (checked elsewhere), 4212 // -- have the same type (except for ref-qualifiers, and except that a 4213 // copy operation can take a non-const reference) as an implicit 4214 // declaration, and 4215 // -- not have default arguments. 4216 unsigned ExpectedParams = 1; 4217 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 4218 ExpectedParams = 0; 4219 if (MD->getNumParams() != ExpectedParams) { 4220 // This also checks for default arguments: a copy or move constructor with a 4221 // default argument is classified as a default constructor, and assignment 4222 // operations and destructors can't have default arguments. 4223 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 4224 << CSM << MD->getSourceRange(); 4225 HadError = true; 4226 } else if (MD->isVariadic()) { 4227 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 4228 << CSM << MD->getSourceRange(); 4229 HadError = true; 4230 } 4231 4232 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 4233 4234 bool CanHaveConstParam = false; 4235 if (CSM == CXXCopyConstructor) 4236 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 4237 else if (CSM == CXXCopyAssignment) 4238 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 4239 4240 QualType ReturnType = Context.VoidTy; 4241 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 4242 // Check for return type matching. 4243 ReturnType = Type->getResultType(); 4244 QualType ExpectedReturnType = 4245 Context.getLValueReferenceType(Context.getTypeDeclType(RD)); 4246 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 4247 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 4248 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 4249 HadError = true; 4250 } 4251 4252 // A defaulted special member cannot have cv-qualifiers. 4253 if (Type->getTypeQuals()) { 4254 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 4255 << (CSM == CXXMoveAssignment); 4256 HadError = true; 4257 } 4258 } 4259 4260 // Check for parameter type matching. 4261 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType(); 4262 bool HasConstParam = false; 4263 if (ExpectedParams && ArgType->isReferenceType()) { 4264 // Argument must be reference to possibly-const T. 4265 QualType ReferentType = ArgType->getPointeeType(); 4266 HasConstParam = ReferentType.isConstQualified(); 4267 4268 if (ReferentType.isVolatileQualified()) { 4269 Diag(MD->getLocation(), 4270 diag::err_defaulted_special_member_volatile_param) << CSM; 4271 HadError = true; 4272 } 4273 4274 if (HasConstParam && !CanHaveConstParam) { 4275 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 4276 Diag(MD->getLocation(), 4277 diag::err_defaulted_special_member_copy_const_param) 4278 << (CSM == CXXCopyAssignment); 4279 // FIXME: Explain why this special member can't be const. 4280 } else { 4281 Diag(MD->getLocation(), 4282 diag::err_defaulted_special_member_move_const_param) 4283 << (CSM == CXXMoveAssignment); 4284 } 4285 HadError = true; 4286 } 4287 } else if (ExpectedParams) { 4288 // A copy assignment operator can take its argument by value, but a 4289 // defaulted one cannot. 4290 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 4291 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 4292 HadError = true; 4293 } 4294 4295 // C++11 [dcl.fct.def.default]p2: 4296 // An explicitly-defaulted function may be declared constexpr only if it 4297 // would have been implicitly declared as constexpr, 4298 // Do not apply this rule to members of class templates, since core issue 1358 4299 // makes such functions always instantiate to constexpr functions. For 4300 // non-constructors, this is checked elsewhere. 4301 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 4302 HasConstParam); 4303 if (isa<CXXConstructorDecl>(MD) && MD->isConstexpr() && !Constexpr && 4304 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 4305 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM; 4306 // FIXME: Explain why the constructor can't be constexpr. 4307 HadError = true; 4308 } 4309 4310 // and may have an explicit exception-specification only if it is compatible 4311 // with the exception-specification on the implicit declaration. 4312 if (Type->hasExceptionSpec()) { 4313 // Delay the check if this is the first declaration of the special member, 4314 // since we may not have parsed some necessary in-class initializers yet. 4315 if (First) 4316 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type)); 4317 else 4318 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type); 4319 } 4320 4321 // If a function is explicitly defaulted on its first declaration, 4322 if (First) { 4323 // -- it is implicitly considered to be constexpr if the implicit 4324 // definition would be, 4325 MD->setConstexpr(Constexpr); 4326 4327 // -- it is implicitly considered to have the same exception-specification 4328 // as if it had been implicitly declared, 4329 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 4330 EPI.ExceptionSpecType = EST_Unevaluated; 4331 EPI.ExceptionSpecDecl = MD; 4332 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 4333 ExpectedParams, EPI)); 4334 } 4335 4336 if (ShouldDeleteSpecialMember(MD, CSM)) { 4337 if (First) { 4338 MD->setDeletedAsWritten(); 4339 } else { 4340 // C++11 [dcl.fct.def.default]p4: 4341 // [For a] user-provided explicitly-defaulted function [...] if such a 4342 // function is implicitly defined as deleted, the program is ill-formed. 4343 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 4344 HadError = true; 4345 } 4346 } 4347 4348 if (HadError) 4349 MD->setInvalidDecl(); 4350} 4351 4352/// Check whether the exception specification provided for an 4353/// explicitly-defaulted special member matches the exception specification 4354/// that would have been generated for an implicit special member, per 4355/// C++11 [dcl.fct.def.default]p2. 4356void Sema::CheckExplicitlyDefaultedMemberExceptionSpec( 4357 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) { 4358 // Compute the implicit exception specification. 4359 FunctionProtoType::ExtProtoInfo EPI; 4360 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI); 4361 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>( 4362 Context.getFunctionType(Context.VoidTy, 0, 0, EPI)); 4363 4364 // Ensure that it matches. 4365 CheckEquivalentExceptionSpec( 4366 PDiag(diag::err_incorrect_defaulted_exception_spec) 4367 << getSpecialMember(MD), PDiag(), 4368 ImplicitType, SourceLocation(), 4369 SpecifiedType, MD->getLocation()); 4370} 4371 4372void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() { 4373 for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size(); 4374 I != N; ++I) 4375 CheckExplicitlyDefaultedMemberExceptionSpec( 4376 DelayedDefaultedMemberExceptionSpecs[I].first, 4377 DelayedDefaultedMemberExceptionSpecs[I].second); 4378 4379 DelayedDefaultedMemberExceptionSpecs.clear(); 4380} 4381 4382namespace { 4383struct SpecialMemberDeletionInfo { 4384 Sema &S; 4385 CXXMethodDecl *MD; 4386 Sema::CXXSpecialMember CSM; 4387 bool Diagnose; 4388 4389 // Properties of the special member, computed for convenience. 4390 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg; 4391 SourceLocation Loc; 4392 4393 bool AllFieldsAreConst; 4394 4395 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 4396 Sema::CXXSpecialMember CSM, bool Diagnose) 4397 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose), 4398 IsConstructor(false), IsAssignment(false), IsMove(false), 4399 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()), 4400 AllFieldsAreConst(true) { 4401 switch (CSM) { 4402 case Sema::CXXDefaultConstructor: 4403 case Sema::CXXCopyConstructor: 4404 IsConstructor = true; 4405 break; 4406 case Sema::CXXMoveConstructor: 4407 IsConstructor = true; 4408 IsMove = true; 4409 break; 4410 case Sema::CXXCopyAssignment: 4411 IsAssignment = true; 4412 break; 4413 case Sema::CXXMoveAssignment: 4414 IsAssignment = true; 4415 IsMove = true; 4416 break; 4417 case Sema::CXXDestructor: 4418 break; 4419 case Sema::CXXInvalid: 4420 llvm_unreachable("invalid special member kind"); 4421 } 4422 4423 if (MD->getNumParams()) { 4424 ConstArg = MD->getParamDecl(0)->getType().isConstQualified(); 4425 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified(); 4426 } 4427 } 4428 4429 bool inUnion() const { return MD->getParent()->isUnion(); } 4430 4431 /// Look up the corresponding special member in the given class. 4432 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class, 4433 unsigned Quals) { 4434 unsigned TQ = MD->getTypeQualifiers(); 4435 // cv-qualifiers on class members don't affect default ctor / dtor calls. 4436 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 4437 Quals = 0; 4438 return S.LookupSpecialMember(Class, CSM, 4439 ConstArg || (Quals & Qualifiers::Const), 4440 VolatileArg || (Quals & Qualifiers::Volatile), 4441 MD->getRefQualifier() == RQ_RValue, 4442 TQ & Qualifiers::Const, 4443 TQ & Qualifiers::Volatile); 4444 } 4445 4446 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 4447 4448 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 4449 bool shouldDeleteForField(FieldDecl *FD); 4450 bool shouldDeleteForAllConstMembers(); 4451 4452 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 4453 unsigned Quals); 4454 bool shouldDeleteForSubobjectCall(Subobject Subobj, 4455 Sema::SpecialMemberOverloadResult *SMOR, 4456 bool IsDtorCallInCtor); 4457 4458 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 4459}; 4460} 4461 4462/// Is the given special member inaccessible when used on the given 4463/// sub-object. 4464bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 4465 CXXMethodDecl *target) { 4466 /// If we're operating on a base class, the object type is the 4467 /// type of this special member. 4468 QualType objectTy; 4469 AccessSpecifier access = target->getAccess(); 4470 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 4471 objectTy = S.Context.getTypeDeclType(MD->getParent()); 4472 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 4473 4474 // If we're operating on a field, the object type is the type of the field. 4475 } else { 4476 objectTy = S.Context.getTypeDeclType(target->getParent()); 4477 } 4478 4479 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 4480} 4481 4482/// Check whether we should delete a special member due to the implicit 4483/// definition containing a call to a special member of a subobject. 4484bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 4485 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR, 4486 bool IsDtorCallInCtor) { 4487 CXXMethodDecl *Decl = SMOR->getMethod(); 4488 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 4489 4490 int DiagKind = -1; 4491 4492 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 4493 DiagKind = !Decl ? 0 : 1; 4494 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 4495 DiagKind = 2; 4496 else if (!isAccessible(Subobj, Decl)) 4497 DiagKind = 3; 4498 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 4499 !Decl->isTrivial()) { 4500 // A member of a union must have a trivial corresponding special member. 4501 // As a weird special case, a destructor call from a union's constructor 4502 // must be accessible and non-deleted, but need not be trivial. Such a 4503 // destructor is never actually called, but is semantically checked as 4504 // if it were. 4505 DiagKind = 4; 4506 } 4507 4508 if (DiagKind == -1) 4509 return false; 4510 4511 if (Diagnose) { 4512 if (Field) { 4513 S.Diag(Field->getLocation(), 4514 diag::note_deleted_special_member_class_subobject) 4515 << CSM << MD->getParent() << /*IsField*/true 4516 << Field << DiagKind << IsDtorCallInCtor; 4517 } else { 4518 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 4519 S.Diag(Base->getLocStart(), 4520 diag::note_deleted_special_member_class_subobject) 4521 << CSM << MD->getParent() << /*IsField*/false 4522 << Base->getType() << DiagKind << IsDtorCallInCtor; 4523 } 4524 4525 if (DiagKind == 1) 4526 S.NoteDeletedFunction(Decl); 4527 // FIXME: Explain inaccessibility if DiagKind == 3. 4528 } 4529 4530 return true; 4531} 4532 4533/// Check whether we should delete a special member function due to having a 4534/// direct or virtual base class or non-static data member of class type M. 4535bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 4536 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 4537 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 4538 4539 // C++11 [class.ctor]p5: 4540 // -- any direct or virtual base class, or non-static data member with no 4541 // brace-or-equal-initializer, has class type M (or array thereof) and 4542 // either M has no default constructor or overload resolution as applied 4543 // to M's default constructor results in an ambiguity or in a function 4544 // that is deleted or inaccessible 4545 // C++11 [class.copy]p11, C++11 [class.copy]p23: 4546 // -- a direct or virtual base class B that cannot be copied/moved because 4547 // overload resolution, as applied to B's corresponding special member, 4548 // results in an ambiguity or a function that is deleted or inaccessible 4549 // from the defaulted special member 4550 // C++11 [class.dtor]p5: 4551 // -- any direct or virtual base class [...] has a type with a destructor 4552 // that is deleted or inaccessible 4553 if (!(CSM == Sema::CXXDefaultConstructor && 4554 Field && Field->hasInClassInitializer()) && 4555 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false)) 4556 return true; 4557 4558 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 4559 // -- any direct or virtual base class or non-static data member has a 4560 // type with a destructor that is deleted or inaccessible 4561 if (IsConstructor) { 4562 Sema::SpecialMemberOverloadResult *SMOR = 4563 S.LookupSpecialMember(Class, Sema::CXXDestructor, 4564 false, false, false, false, false); 4565 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 4566 return true; 4567 } 4568 4569 return false; 4570} 4571 4572/// Check whether we should delete a special member function due to the class 4573/// having a particular direct or virtual base class. 4574bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 4575 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 4576 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 4577} 4578 4579/// Check whether we should delete a special member function due to the class 4580/// having a particular non-static data member. 4581bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 4582 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 4583 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 4584 4585 if (CSM == Sema::CXXDefaultConstructor) { 4586 // For a default constructor, all references must be initialized in-class 4587 // and, if a union, it must have a non-const member. 4588 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 4589 if (Diagnose) 4590 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 4591 << MD->getParent() << FD << FieldType << /*Reference*/0; 4592 return true; 4593 } 4594 // C++11 [class.ctor]p5: any non-variant non-static data member of 4595 // const-qualified type (or array thereof) with no 4596 // brace-or-equal-initializer does not have a user-provided default 4597 // constructor. 4598 if (!inUnion() && FieldType.isConstQualified() && 4599 !FD->hasInClassInitializer() && 4600 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 4601 if (Diagnose) 4602 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 4603 << MD->getParent() << FD << FD->getType() << /*Const*/1; 4604 return true; 4605 } 4606 4607 if (inUnion() && !FieldType.isConstQualified()) 4608 AllFieldsAreConst = false; 4609 } else if (CSM == Sema::CXXCopyConstructor) { 4610 // For a copy constructor, data members must not be of rvalue reference 4611 // type. 4612 if (FieldType->isRValueReferenceType()) { 4613 if (Diagnose) 4614 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 4615 << MD->getParent() << FD << FieldType; 4616 return true; 4617 } 4618 } else if (IsAssignment) { 4619 // For an assignment operator, data members must not be of reference type. 4620 if (FieldType->isReferenceType()) { 4621 if (Diagnose) 4622 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 4623 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0; 4624 return true; 4625 } 4626 if (!FieldRecord && FieldType.isConstQualified()) { 4627 // C++11 [class.copy]p23: 4628 // -- a non-static data member of const non-class type (or array thereof) 4629 if (Diagnose) 4630 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 4631 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1; 4632 return true; 4633 } 4634 } 4635 4636 if (FieldRecord) { 4637 // Some additional restrictions exist on the variant members. 4638 if (!inUnion() && FieldRecord->isUnion() && 4639 FieldRecord->isAnonymousStructOrUnion()) { 4640 bool AllVariantFieldsAreConst = true; 4641 4642 // FIXME: Handle anonymous unions declared within anonymous unions. 4643 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(), 4644 UE = FieldRecord->field_end(); 4645 UI != UE; ++UI) { 4646 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 4647 4648 if (!UnionFieldType.isConstQualified()) 4649 AllVariantFieldsAreConst = false; 4650 4651 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 4652 if (UnionFieldRecord && 4653 shouldDeleteForClassSubobject(UnionFieldRecord, *UI, 4654 UnionFieldType.getCVRQualifiers())) 4655 return true; 4656 } 4657 4658 // At least one member in each anonymous union must be non-const 4659 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 4660 FieldRecord->field_begin() != FieldRecord->field_end()) { 4661 if (Diagnose) 4662 S.Diag(FieldRecord->getLocation(), 4663 diag::note_deleted_default_ctor_all_const) 4664 << MD->getParent() << /*anonymous union*/1; 4665 return true; 4666 } 4667 4668 // Don't check the implicit member of the anonymous union type. 4669 // This is technically non-conformant, but sanity demands it. 4670 return false; 4671 } 4672 4673 if (shouldDeleteForClassSubobject(FieldRecord, FD, 4674 FieldType.getCVRQualifiers())) 4675 return true; 4676 } 4677 4678 return false; 4679} 4680 4681/// C++11 [class.ctor] p5: 4682/// A defaulted default constructor for a class X is defined as deleted if 4683/// X is a union and all of its variant members are of const-qualified type. 4684bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 4685 // This is a silly definition, because it gives an empty union a deleted 4686 // default constructor. Don't do that. 4687 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst && 4688 (MD->getParent()->field_begin() != MD->getParent()->field_end())) { 4689 if (Diagnose) 4690 S.Diag(MD->getParent()->getLocation(), 4691 diag::note_deleted_default_ctor_all_const) 4692 << MD->getParent() << /*not anonymous union*/0; 4693 return true; 4694 } 4695 return false; 4696} 4697 4698/// Determine whether a defaulted special member function should be defined as 4699/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 4700/// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 4701bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 4702 bool Diagnose) { 4703 if (MD->isInvalidDecl()) 4704 return false; 4705 CXXRecordDecl *RD = MD->getParent(); 4706 assert(!RD->isDependentType() && "do deletion after instantiation"); 4707 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 4708 return false; 4709 4710 // C++11 [expr.lambda.prim]p19: 4711 // The closure type associated with a lambda-expression has a 4712 // deleted (8.4.3) default constructor and a deleted copy 4713 // assignment operator. 4714 if (RD->isLambda() && 4715 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 4716 if (Diagnose) 4717 Diag(RD->getLocation(), diag::note_lambda_decl); 4718 return true; 4719 } 4720 4721 // For an anonymous struct or union, the copy and assignment special members 4722 // will never be used, so skip the check. For an anonymous union declared at 4723 // namespace scope, the constructor and destructor are used. 4724 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 4725 RD->isAnonymousStructOrUnion()) 4726 return false; 4727 4728 // C++11 [class.copy]p7, p18: 4729 // If the class definition declares a move constructor or move assignment 4730 // operator, an implicitly declared copy constructor or copy assignment 4731 // operator is defined as deleted. 4732 if (MD->isImplicit() && 4733 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 4734 CXXMethodDecl *UserDeclaredMove = 0; 4735 4736 // In Microsoft mode, a user-declared move only causes the deletion of the 4737 // corresponding copy operation, not both copy operations. 4738 if (RD->hasUserDeclaredMoveConstructor() && 4739 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) { 4740 if (!Diagnose) return true; 4741 4742 // Find any user-declared move constructor. 4743 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(), 4744 E = RD->ctor_end(); I != E; ++I) { 4745 if (I->isMoveConstructor()) { 4746 UserDeclaredMove = *I; 4747 break; 4748 } 4749 } 4750 assert(UserDeclaredMove); 4751 } else if (RD->hasUserDeclaredMoveAssignment() && 4752 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) { 4753 if (!Diagnose) return true; 4754 4755 // Find any user-declared move assignment operator. 4756 for (CXXRecordDecl::method_iterator I = RD->method_begin(), 4757 E = RD->method_end(); I != E; ++I) { 4758 if (I->isMoveAssignmentOperator()) { 4759 UserDeclaredMove = *I; 4760 break; 4761 } 4762 } 4763 assert(UserDeclaredMove); 4764 } 4765 4766 if (UserDeclaredMove) { 4767 Diag(UserDeclaredMove->getLocation(), 4768 diag::note_deleted_copy_user_declared_move) 4769 << (CSM == CXXCopyAssignment) << RD 4770 << UserDeclaredMove->isMoveAssignmentOperator(); 4771 return true; 4772 } 4773 } 4774 4775 // Do access control from the special member function 4776 ContextRAII MethodContext(*this, MD); 4777 4778 // C++11 [class.dtor]p5: 4779 // -- for a virtual destructor, lookup of the non-array deallocation function 4780 // results in an ambiguity or in a function that is deleted or inaccessible 4781 if (CSM == CXXDestructor && MD->isVirtual()) { 4782 FunctionDecl *OperatorDelete = 0; 4783 DeclarationName Name = 4784 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 4785 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 4786 OperatorDelete, false)) { 4787 if (Diagnose) 4788 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 4789 return true; 4790 } 4791 } 4792 4793 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose); 4794 4795 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 4796 BE = RD->bases_end(); BI != BE; ++BI) 4797 if (!BI->isVirtual() && 4798 SMI.shouldDeleteForBase(BI)) 4799 return true; 4800 4801 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(), 4802 BE = RD->vbases_end(); BI != BE; ++BI) 4803 if (SMI.shouldDeleteForBase(BI)) 4804 return true; 4805 4806 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 4807 FE = RD->field_end(); FI != FE; ++FI) 4808 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() && 4809 SMI.shouldDeleteForField(*FI)) 4810 return true; 4811 4812 if (SMI.shouldDeleteForAllConstMembers()) 4813 return true; 4814 4815 return false; 4816} 4817 4818/// Perform lookup for a special member of the specified kind, and determine 4819/// whether it is trivial. If the triviality can be determined without the 4820/// lookup, skip it. This is intended for use when determining whether a 4821/// special member of a containing object is trivial, and thus does not ever 4822/// perform overload resolution for default constructors. 4823/// 4824/// If \p Selected is not \c NULL, \c *Selected will be filled in with the 4825/// member that was most likely to be intended to be trivial, if any. 4826static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 4827 Sema::CXXSpecialMember CSM, unsigned Quals, 4828 CXXMethodDecl **Selected) { 4829 if (Selected) 4830 *Selected = 0; 4831 4832 switch (CSM) { 4833 case Sema::CXXInvalid: 4834 llvm_unreachable("not a special member"); 4835 4836 case Sema::CXXDefaultConstructor: 4837 // C++11 [class.ctor]p5: 4838 // A default constructor is trivial if: 4839 // - all the [direct subobjects] have trivial default constructors 4840 // 4841 // Note, no overload resolution is performed in this case. 4842 if (RD->hasTrivialDefaultConstructor()) 4843 return true; 4844 4845 if (Selected) { 4846 // If there's a default constructor which could have been trivial, dig it 4847 // out. Otherwise, if there's any user-provided default constructor, point 4848 // to that as an example of why there's not a trivial one. 4849 CXXConstructorDecl *DefCtor = 0; 4850 if (RD->needsImplicitDefaultConstructor()) 4851 S.DeclareImplicitDefaultConstructor(RD); 4852 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), 4853 CE = RD->ctor_end(); CI != CE; ++CI) { 4854 if (!CI->isDefaultConstructor()) 4855 continue; 4856 DefCtor = *CI; 4857 if (!DefCtor->isUserProvided()) 4858 break; 4859 } 4860 4861 *Selected = DefCtor; 4862 } 4863 4864 return false; 4865 4866 case Sema::CXXDestructor: 4867 // C++11 [class.dtor]p5: 4868 // A destructor is trivial if: 4869 // - all the direct [subobjects] have trivial destructors 4870 if (RD->hasTrivialDestructor()) 4871 return true; 4872 4873 if (Selected) { 4874 if (RD->needsImplicitDestructor()) 4875 S.DeclareImplicitDestructor(RD); 4876 *Selected = RD->getDestructor(); 4877 } 4878 4879 return false; 4880 4881 case Sema::CXXCopyConstructor: 4882 // C++11 [class.copy]p12: 4883 // A copy constructor is trivial if: 4884 // - the constructor selected to copy each direct [subobject] is trivial 4885 if (RD->hasTrivialCopyConstructor()) { 4886 if (Quals == Qualifiers::Const) 4887 // We must either select the trivial copy constructor or reach an 4888 // ambiguity; no need to actually perform overload resolution. 4889 return true; 4890 } else if (!Selected) { 4891 return false; 4892 } 4893 // In C++98, we are not supposed to perform overload resolution here, but we 4894 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 4895 // cases like B as having a non-trivial copy constructor: 4896 // struct A { template<typename T> A(T&); }; 4897 // struct B { mutable A a; }; 4898 goto NeedOverloadResolution; 4899 4900 case Sema::CXXCopyAssignment: 4901 // C++11 [class.copy]p25: 4902 // A copy assignment operator is trivial if: 4903 // - the assignment operator selected to copy each direct [subobject] is 4904 // trivial 4905 if (RD->hasTrivialCopyAssignment()) { 4906 if (Quals == Qualifiers::Const) 4907 return true; 4908 } else if (!Selected) { 4909 return false; 4910 } 4911 // In C++98, we are not supposed to perform overload resolution here, but we 4912 // treat that as a language defect. 4913 goto NeedOverloadResolution; 4914 4915 case Sema::CXXMoveConstructor: 4916 case Sema::CXXMoveAssignment: 4917 NeedOverloadResolution: 4918 Sema::SpecialMemberOverloadResult *SMOR = 4919 S.LookupSpecialMember(RD, CSM, 4920 Quals & Qualifiers::Const, 4921 Quals & Qualifiers::Volatile, 4922 /*RValueThis*/false, /*ConstThis*/false, 4923 /*VolatileThis*/false); 4924 4925 // The standard doesn't describe how to behave if the lookup is ambiguous. 4926 // We treat it as not making the member non-trivial, just like the standard 4927 // mandates for the default constructor. This should rarely matter, because 4928 // the member will also be deleted. 4929 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 4930 return true; 4931 4932 if (!SMOR->getMethod()) { 4933 assert(SMOR->getKind() == 4934 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 4935 return false; 4936 } 4937 4938 // We deliberately don't check if we found a deleted special member. We're 4939 // not supposed to! 4940 if (Selected) 4941 *Selected = SMOR->getMethod(); 4942 return SMOR->getMethod()->isTrivial(); 4943 } 4944 4945 llvm_unreachable("unknown special method kind"); 4946} 4947 4948CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 4949 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end(); 4950 CI != CE; ++CI) 4951 if (!CI->isImplicit()) 4952 return *CI; 4953 4954 // Look for constructor templates. 4955 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 4956 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 4957 if (CXXConstructorDecl *CD = 4958 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 4959 return CD; 4960 } 4961 4962 return 0; 4963} 4964 4965/// The kind of subobject we are checking for triviality. The values of this 4966/// enumeration are used in diagnostics. 4967enum TrivialSubobjectKind { 4968 /// The subobject is a base class. 4969 TSK_BaseClass, 4970 /// The subobject is a non-static data member. 4971 TSK_Field, 4972 /// The object is actually the complete object. 4973 TSK_CompleteObject 4974}; 4975 4976/// Check whether the special member selected for a given type would be trivial. 4977static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 4978 QualType SubType, 4979 Sema::CXXSpecialMember CSM, 4980 TrivialSubobjectKind Kind, 4981 bool Diagnose) { 4982 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 4983 if (!SubRD) 4984 return true; 4985 4986 CXXMethodDecl *Selected; 4987 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 4988 Diagnose ? &Selected : 0)) 4989 return true; 4990 4991 if (Diagnose) { 4992 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 4993 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 4994 << Kind << SubType.getUnqualifiedType(); 4995 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 4996 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 4997 } else if (!Selected) 4998 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 4999 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 5000 else if (Selected->isUserProvided()) { 5001 if (Kind == TSK_CompleteObject) 5002 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 5003 << Kind << SubType.getUnqualifiedType() << CSM; 5004 else { 5005 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 5006 << Kind << SubType.getUnqualifiedType() << CSM; 5007 S.Diag(Selected->getLocation(), diag::note_declared_at); 5008 } 5009 } else { 5010 if (Kind != TSK_CompleteObject) 5011 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 5012 << Kind << SubType.getUnqualifiedType() << CSM; 5013 5014 // Explain why the defaulted or deleted special member isn't trivial. 5015 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose); 5016 } 5017 } 5018 5019 return false; 5020} 5021 5022/// Check whether the members of a class type allow a special member to be 5023/// trivial. 5024static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 5025 Sema::CXXSpecialMember CSM, 5026 bool ConstArg, bool Diagnose) { 5027 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 5028 FE = RD->field_end(); FI != FE; ++FI) { 5029 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 5030 continue; 5031 5032 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 5033 5034 // Pretend anonymous struct or union members are members of this class. 5035 if (FI->isAnonymousStructOrUnion()) { 5036 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 5037 CSM, ConstArg, Diagnose)) 5038 return false; 5039 continue; 5040 } 5041 5042 // C++11 [class.ctor]p5: 5043 // A default constructor is trivial if [...] 5044 // -- no non-static data member of its class has a 5045 // brace-or-equal-initializer 5046 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 5047 if (Diagnose) 5048 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI; 5049 return false; 5050 } 5051 5052 // Objective C ARC 4.3.5: 5053 // [...] nontrivally ownership-qualified types are [...] not trivially 5054 // default constructible, copy constructible, move constructible, copy 5055 // assignable, move assignable, or destructible [...] 5056 if (S.getLangOpts().ObjCAutoRefCount && 5057 FieldType.hasNonTrivialObjCLifetime()) { 5058 if (Diagnose) 5059 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 5060 << RD << FieldType.getObjCLifetime(); 5061 return false; 5062 } 5063 5064 if (ConstArg && !FI->isMutable()) 5065 FieldType.addConst(); 5066 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM, 5067 TSK_Field, Diagnose)) 5068 return false; 5069 } 5070 5071 return true; 5072} 5073 5074/// Diagnose why the specified class does not have a trivial special member of 5075/// the given kind. 5076void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 5077 QualType Ty = Context.getRecordType(RD); 5078 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) 5079 Ty.addConst(); 5080 5081 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM, 5082 TSK_CompleteObject, /*Diagnose*/true); 5083} 5084 5085/// Determine whether a defaulted or deleted special member function is trivial, 5086/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 5087/// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 5088bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 5089 bool Diagnose) { 5090 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 5091 5092 CXXRecordDecl *RD = MD->getParent(); 5093 5094 bool ConstArg = false; 5095 ParmVarDecl *Param0 = MD->getNumParams() ? MD->getParamDecl(0) : 0; 5096 5097 // C++11 [class.copy]p12, p25: 5098 // A [special member] is trivial if its declared parameter type is the same 5099 // as if it had been implicitly declared [...] 5100 switch (CSM) { 5101 case CXXDefaultConstructor: 5102 case CXXDestructor: 5103 // Trivial default constructors and destructors cannot have parameters. 5104 break; 5105 5106 case CXXCopyConstructor: 5107 case CXXCopyAssignment: { 5108 // Trivial copy operations always have const, non-volatile parameter types. 5109 ConstArg = true; 5110 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 5111 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 5112 if (Diagnose) 5113 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 5114 << Param0->getSourceRange() << Param0->getType() 5115 << Context.getLValueReferenceType( 5116 Context.getRecordType(RD).withConst()); 5117 return false; 5118 } 5119 break; 5120 } 5121 5122 case CXXMoveConstructor: 5123 case CXXMoveAssignment: { 5124 // Trivial move operations always have non-cv-qualified parameters. 5125 const RValueReferenceType *RT = 5126 Param0->getType()->getAs<RValueReferenceType>(); 5127 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 5128 if (Diagnose) 5129 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 5130 << Param0->getSourceRange() << Param0->getType() 5131 << Context.getRValueReferenceType(Context.getRecordType(RD)); 5132 return false; 5133 } 5134 break; 5135 } 5136 5137 case CXXInvalid: 5138 llvm_unreachable("not a special member"); 5139 } 5140 5141 // FIXME: We require that the parameter-declaration-clause is equivalent to 5142 // that of an implicit declaration, not just that the declared parameter type 5143 // matches, in order to prevent absuridities like a function simultaneously 5144 // being a trivial copy constructor and a non-trivial default constructor. 5145 // This issue has not yet been assigned a core issue number. 5146 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 5147 if (Diagnose) 5148 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 5149 diag::note_nontrivial_default_arg) 5150 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 5151 return false; 5152 } 5153 if (MD->isVariadic()) { 5154 if (Diagnose) 5155 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 5156 return false; 5157 } 5158 5159 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 5160 // A copy/move [constructor or assignment operator] is trivial if 5161 // -- the [member] selected to copy/move each direct base class subobject 5162 // is trivial 5163 // 5164 // C++11 [class.copy]p12, C++11 [class.copy]p25: 5165 // A [default constructor or destructor] is trivial if 5166 // -- all the direct base classes have trivial [default constructors or 5167 // destructors] 5168 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 5169 BE = RD->bases_end(); BI != BE; ++BI) 5170 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(), 5171 ConstArg ? BI->getType().withConst() 5172 : BI->getType(), 5173 CSM, TSK_BaseClass, Diagnose)) 5174 return false; 5175 5176 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 5177 // A copy/move [constructor or assignment operator] for a class X is 5178 // trivial if 5179 // -- for each non-static data member of X that is of class type (or array 5180 // thereof), the constructor selected to copy/move that member is 5181 // trivial 5182 // 5183 // C++11 [class.copy]p12, C++11 [class.copy]p25: 5184 // A [default constructor or destructor] is trivial if 5185 // -- for all of the non-static data members of its class that are of class 5186 // type (or array thereof), each such class has a trivial [default 5187 // constructor or destructor] 5188 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose)) 5189 return false; 5190 5191 // C++11 [class.dtor]p5: 5192 // A destructor is trivial if [...] 5193 // -- the destructor is not virtual 5194 if (CSM == CXXDestructor && MD->isVirtual()) { 5195 if (Diagnose) 5196 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 5197 return false; 5198 } 5199 5200 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 5201 // A [special member] for class X is trivial if [...] 5202 // -- class X has no virtual functions and no virtual base classes 5203 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 5204 if (!Diagnose) 5205 return false; 5206 5207 if (RD->getNumVBases()) { 5208 // Check for virtual bases. We already know that the corresponding 5209 // member in all bases is trivial, so vbases must all be direct. 5210 CXXBaseSpecifier &BS = *RD->vbases_begin(); 5211 assert(BS.isVirtual()); 5212 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1; 5213 return false; 5214 } 5215 5216 // Must have a virtual method. 5217 for (CXXRecordDecl::method_iterator MI = RD->method_begin(), 5218 ME = RD->method_end(); MI != ME; ++MI) { 5219 if (MI->isVirtual()) { 5220 SourceLocation MLoc = MI->getLocStart(); 5221 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 5222 return false; 5223 } 5224 } 5225 5226 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 5227 } 5228 5229 // Looks like it's trivial! 5230 return true; 5231} 5232 5233/// \brief Data used with FindHiddenVirtualMethod 5234namespace { 5235 struct FindHiddenVirtualMethodData { 5236 Sema *S; 5237 CXXMethodDecl *Method; 5238 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 5239 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 5240 }; 5241} 5242 5243/// \brief Check whether any most overriden method from MD in Methods 5244static bool CheckMostOverridenMethods(const CXXMethodDecl *MD, 5245 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) { 5246 if (MD->size_overridden_methods() == 0) 5247 return Methods.count(MD->getCanonicalDecl()); 5248 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 5249 E = MD->end_overridden_methods(); 5250 I != E; ++I) 5251 if (CheckMostOverridenMethods(*I, Methods)) 5252 return true; 5253 return false; 5254} 5255 5256/// \brief Member lookup function that determines whether a given C++ 5257/// method overloads virtual methods in a base class without overriding any, 5258/// to be used with CXXRecordDecl::lookupInBases(). 5259static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier, 5260 CXXBasePath &Path, 5261 void *UserData) { 5262 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 5263 5264 FindHiddenVirtualMethodData &Data 5265 = *static_cast<FindHiddenVirtualMethodData*>(UserData); 5266 5267 DeclarationName Name = Data.Method->getDeclName(); 5268 assert(Name.getNameKind() == DeclarationName::Identifier); 5269 5270 bool foundSameNameMethod = false; 5271 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 5272 for (Path.Decls = BaseRecord->lookup(Name); 5273 !Path.Decls.empty(); 5274 Path.Decls = Path.Decls.slice(1)) { 5275 NamedDecl *D = Path.Decls.front(); 5276 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 5277 MD = MD->getCanonicalDecl(); 5278 foundSameNameMethod = true; 5279 // Interested only in hidden virtual methods. 5280 if (!MD->isVirtual()) 5281 continue; 5282 // If the method we are checking overrides a method from its base 5283 // don't warn about the other overloaded methods. 5284 if (!Data.S->IsOverload(Data.Method, MD, false)) 5285 return true; 5286 // Collect the overload only if its hidden. 5287 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods)) 5288 overloadedMethods.push_back(MD); 5289 } 5290 } 5291 5292 if (foundSameNameMethod) 5293 Data.OverloadedMethods.append(overloadedMethods.begin(), 5294 overloadedMethods.end()); 5295 return foundSameNameMethod; 5296} 5297 5298/// \brief Add the most overriden methods from MD to Methods 5299static void AddMostOverridenMethods(const CXXMethodDecl *MD, 5300 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) { 5301 if (MD->size_overridden_methods() == 0) 5302 Methods.insert(MD->getCanonicalDecl()); 5303 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 5304 E = MD->end_overridden_methods(); 5305 I != E; ++I) 5306 AddMostOverridenMethods(*I, Methods); 5307} 5308 5309/// \brief See if a method overloads virtual methods in a base class without 5310/// overriding any. 5311void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 5312 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual, 5313 MD->getLocation()) == DiagnosticsEngine::Ignored) 5314 return; 5315 if (!MD->getDeclName().isIdentifier()) 5316 return; 5317 5318 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 5319 /*bool RecordPaths=*/false, 5320 /*bool DetectVirtual=*/false); 5321 FindHiddenVirtualMethodData Data; 5322 Data.Method = MD; 5323 Data.S = this; 5324 5325 // Keep the base methods that were overriden or introduced in the subclass 5326 // by 'using' in a set. A base method not in this set is hidden. 5327 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 5328 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 5329 NamedDecl *ND = *I; 5330 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 5331 ND = shad->getTargetDecl(); 5332 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 5333 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods); 5334 } 5335 5336 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) && 5337 !Data.OverloadedMethods.empty()) { 5338 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 5339 << MD << (Data.OverloadedMethods.size() > 1); 5340 5341 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) { 5342 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i]; 5343 Diag(overloadedMD->getLocation(), 5344 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 5345 } 5346 } 5347} 5348 5349void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 5350 Decl *TagDecl, 5351 SourceLocation LBrac, 5352 SourceLocation RBrac, 5353 AttributeList *AttrList) { 5354 if (!TagDecl) 5355 return; 5356 5357 AdjustDeclIfTemplate(TagDecl); 5358 5359 for (const AttributeList* l = AttrList; l; l = l->getNext()) { 5360 if (l->getKind() != AttributeList::AT_Visibility) 5361 continue; 5362 l->setInvalid(); 5363 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) << 5364 l->getName(); 5365 } 5366 5367 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 5368 // strict aliasing violation! 5369 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 5370 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 5371 5372 CheckCompletedCXXClass( 5373 dyn_cast_or_null<CXXRecordDecl>(TagDecl)); 5374} 5375 5376/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 5377/// special functions, such as the default constructor, copy 5378/// constructor, or destructor, to the given C++ class (C++ 5379/// [special]p1). This routine can only be executed just before the 5380/// definition of the class is complete. 5381void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 5382 if (!ClassDecl->hasUserDeclaredConstructor()) 5383 ++ASTContext::NumImplicitDefaultConstructors; 5384 5385 if (!ClassDecl->hasUserDeclaredCopyConstructor()) { 5386 ++ASTContext::NumImplicitCopyConstructors; 5387 5388 // If the properties or semantics of the copy constructor couldn't be 5389 // determined while the class was being declared, force a declaration 5390 // of it now. 5391 if (ClassDecl->needsOverloadResolutionForCopyConstructor()) 5392 DeclareImplicitCopyConstructor(ClassDecl); 5393 } 5394 5395 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 5396 ++ASTContext::NumImplicitMoveConstructors; 5397 5398 if (ClassDecl->needsOverloadResolutionForMoveConstructor()) 5399 DeclareImplicitMoveConstructor(ClassDecl); 5400 } 5401 5402 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 5403 ++ASTContext::NumImplicitCopyAssignmentOperators; 5404 5405 // If we have a dynamic class, then the copy assignment operator may be 5406 // virtual, so we have to declare it immediately. This ensures that, e.g., 5407 // it shows up in the right place in the vtable and that we diagnose 5408 // problems with the implicit exception specification. 5409 if (ClassDecl->isDynamicClass() || 5410 ClassDecl->needsOverloadResolutionForCopyAssignment()) 5411 DeclareImplicitCopyAssignment(ClassDecl); 5412 } 5413 5414 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 5415 ++ASTContext::NumImplicitMoveAssignmentOperators; 5416 5417 // Likewise for the move assignment operator. 5418 if (ClassDecl->isDynamicClass() || 5419 ClassDecl->needsOverloadResolutionForMoveAssignment()) 5420 DeclareImplicitMoveAssignment(ClassDecl); 5421 } 5422 5423 if (!ClassDecl->hasUserDeclaredDestructor()) { 5424 ++ASTContext::NumImplicitDestructors; 5425 5426 // If we have a dynamic class, then the destructor may be virtual, so we 5427 // have to declare the destructor immediately. This ensures that, e.g., it 5428 // shows up in the right place in the vtable and that we diagnose problems 5429 // with the implicit exception specification. 5430 if (ClassDecl->isDynamicClass() || 5431 ClassDecl->needsOverloadResolutionForDestructor()) 5432 DeclareImplicitDestructor(ClassDecl); 5433 } 5434} 5435 5436void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) { 5437 if (!D) 5438 return; 5439 5440 int NumParamList = D->getNumTemplateParameterLists(); 5441 for (int i = 0; i < NumParamList; i++) { 5442 TemplateParameterList* Params = D->getTemplateParameterList(i); 5443 for (TemplateParameterList::iterator Param = Params->begin(), 5444 ParamEnd = Params->end(); 5445 Param != ParamEnd; ++Param) { 5446 NamedDecl *Named = cast<NamedDecl>(*Param); 5447 if (Named->getDeclName()) { 5448 S->AddDecl(Named); 5449 IdResolver.AddDecl(Named); 5450 } 5451 } 5452 } 5453} 5454 5455void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 5456 if (!D) 5457 return; 5458 5459 TemplateParameterList *Params = 0; 5460 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) 5461 Params = Template->getTemplateParameters(); 5462 else if (ClassTemplatePartialSpecializationDecl *PartialSpec 5463 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 5464 Params = PartialSpec->getTemplateParameters(); 5465 else 5466 return; 5467 5468 for (TemplateParameterList::iterator Param = Params->begin(), 5469 ParamEnd = Params->end(); 5470 Param != ParamEnd; ++Param) { 5471 NamedDecl *Named = cast<NamedDecl>(*Param); 5472 if (Named->getDeclName()) { 5473 S->AddDecl(Named); 5474 IdResolver.AddDecl(Named); 5475 } 5476 } 5477} 5478 5479void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 5480 if (!RecordD) return; 5481 AdjustDeclIfTemplate(RecordD); 5482 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 5483 PushDeclContext(S, Record); 5484} 5485 5486void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 5487 if (!RecordD) return; 5488 PopDeclContext(); 5489} 5490 5491/// ActOnStartDelayedCXXMethodDeclaration - We have completed 5492/// parsing a top-level (non-nested) C++ class, and we are now 5493/// parsing those parts of the given Method declaration that could 5494/// not be parsed earlier (C++ [class.mem]p2), such as default 5495/// arguments. This action should enter the scope of the given 5496/// Method declaration as if we had just parsed the qualified method 5497/// name. However, it should not bring the parameters into scope; 5498/// that will be performed by ActOnDelayedCXXMethodParameter. 5499void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 5500} 5501 5502/// ActOnDelayedCXXMethodParameter - We've already started a delayed 5503/// C++ method declaration. We're (re-)introducing the given 5504/// function parameter into scope for use in parsing later parts of 5505/// the method declaration. For example, we could see an 5506/// ActOnParamDefaultArgument event for this parameter. 5507void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 5508 if (!ParamD) 5509 return; 5510 5511 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 5512 5513 // If this parameter has an unparsed default argument, clear it out 5514 // to make way for the parsed default argument. 5515 if (Param->hasUnparsedDefaultArg()) 5516 Param->setDefaultArg(0); 5517 5518 S->AddDecl(Param); 5519 if (Param->getDeclName()) 5520 IdResolver.AddDecl(Param); 5521} 5522 5523/// ActOnFinishDelayedCXXMethodDeclaration - We have finished 5524/// processing the delayed method declaration for Method. The method 5525/// declaration is now considered finished. There may be a separate 5526/// ActOnStartOfFunctionDef action later (not necessarily 5527/// immediately!) for this method, if it was also defined inside the 5528/// class body. 5529void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 5530 if (!MethodD) 5531 return; 5532 5533 AdjustDeclIfTemplate(MethodD); 5534 5535 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 5536 5537 // Now that we have our default arguments, check the constructor 5538 // again. It could produce additional diagnostics or affect whether 5539 // the class has implicitly-declared destructors, among other 5540 // things. 5541 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 5542 CheckConstructor(Constructor); 5543 5544 // Check the default arguments, which we may have added. 5545 if (!Method->isInvalidDecl()) 5546 CheckCXXDefaultArguments(Method); 5547} 5548 5549/// CheckConstructorDeclarator - Called by ActOnDeclarator to check 5550/// the well-formedness of the constructor declarator @p D with type @p 5551/// R. If there are any errors in the declarator, this routine will 5552/// emit diagnostics and set the invalid bit to true. In any case, the type 5553/// will be updated to reflect a well-formed type for the constructor and 5554/// returned. 5555QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 5556 StorageClass &SC) { 5557 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 5558 5559 // C++ [class.ctor]p3: 5560 // A constructor shall not be virtual (10.3) or static (9.4). A 5561 // constructor can be invoked for a const, volatile or const 5562 // volatile object. A constructor shall not be declared const, 5563 // volatile, or const volatile (9.3.2). 5564 if (isVirtual) { 5565 if (!D.isInvalidType()) 5566 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 5567 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 5568 << SourceRange(D.getIdentifierLoc()); 5569 D.setInvalidType(); 5570 } 5571 if (SC == SC_Static) { 5572 if (!D.isInvalidType()) 5573 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 5574 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 5575 << SourceRange(D.getIdentifierLoc()); 5576 D.setInvalidType(); 5577 SC = SC_None; 5578 } 5579 5580 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 5581 if (FTI.TypeQuals != 0) { 5582 if (FTI.TypeQuals & Qualifiers::Const) 5583 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 5584 << "const" << SourceRange(D.getIdentifierLoc()); 5585 if (FTI.TypeQuals & Qualifiers::Volatile) 5586 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 5587 << "volatile" << SourceRange(D.getIdentifierLoc()); 5588 if (FTI.TypeQuals & Qualifiers::Restrict) 5589 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 5590 << "restrict" << SourceRange(D.getIdentifierLoc()); 5591 D.setInvalidType(); 5592 } 5593 5594 // C++0x [class.ctor]p4: 5595 // A constructor shall not be declared with a ref-qualifier. 5596 if (FTI.hasRefQualifier()) { 5597 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 5598 << FTI.RefQualifierIsLValueRef 5599 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 5600 D.setInvalidType(); 5601 } 5602 5603 // Rebuild the function type "R" without any type qualifiers (in 5604 // case any of the errors above fired) and with "void" as the 5605 // return type, since constructors don't have return types. 5606 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 5607 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType()) 5608 return R; 5609 5610 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 5611 EPI.TypeQuals = 0; 5612 EPI.RefQualifier = RQ_None; 5613 5614 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(), 5615 Proto->getNumArgs(), EPI); 5616} 5617 5618/// CheckConstructor - Checks a fully-formed constructor for 5619/// well-formedness, issuing any diagnostics required. Returns true if 5620/// the constructor declarator is invalid. 5621void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 5622 CXXRecordDecl *ClassDecl 5623 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 5624 if (!ClassDecl) 5625 return Constructor->setInvalidDecl(); 5626 5627 // C++ [class.copy]p3: 5628 // A declaration of a constructor for a class X is ill-formed if 5629 // its first parameter is of type (optionally cv-qualified) X and 5630 // either there are no other parameters or else all other 5631 // parameters have default arguments. 5632 if (!Constructor->isInvalidDecl() && 5633 ((Constructor->getNumParams() == 1) || 5634 (Constructor->getNumParams() > 1 && 5635 Constructor->getParamDecl(1)->hasDefaultArg())) && 5636 Constructor->getTemplateSpecializationKind() 5637 != TSK_ImplicitInstantiation) { 5638 QualType ParamType = Constructor->getParamDecl(0)->getType(); 5639 QualType ClassTy = Context.getTagDeclType(ClassDecl); 5640 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 5641 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 5642 const char *ConstRef 5643 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 5644 : " const &"; 5645 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 5646 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 5647 5648 // FIXME: Rather that making the constructor invalid, we should endeavor 5649 // to fix the type. 5650 Constructor->setInvalidDecl(); 5651 } 5652 } 5653} 5654 5655/// CheckDestructor - Checks a fully-formed destructor definition for 5656/// well-formedness, issuing any diagnostics required. Returns true 5657/// on error. 5658bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 5659 CXXRecordDecl *RD = Destructor->getParent(); 5660 5661 if (Destructor->isVirtual()) { 5662 SourceLocation Loc; 5663 5664 if (!Destructor->isImplicit()) 5665 Loc = Destructor->getLocation(); 5666 else 5667 Loc = RD->getLocation(); 5668 5669 // If we have a virtual destructor, look up the deallocation function 5670 FunctionDecl *OperatorDelete = 0; 5671 DeclarationName Name = 5672 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 5673 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 5674 return true; 5675 5676 MarkFunctionReferenced(Loc, OperatorDelete); 5677 5678 Destructor->setOperatorDelete(OperatorDelete); 5679 } 5680 5681 return false; 5682} 5683 5684static inline bool 5685FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) { 5686 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 5687 FTI.ArgInfo[0].Param && 5688 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()); 5689} 5690 5691/// CheckDestructorDeclarator - Called by ActOnDeclarator to check 5692/// the well-formednes of the destructor declarator @p D with type @p 5693/// R. If there are any errors in the declarator, this routine will 5694/// emit diagnostics and set the declarator to invalid. Even if this happens, 5695/// will be updated to reflect a well-formed type for the destructor and 5696/// returned. 5697QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 5698 StorageClass& SC) { 5699 // C++ [class.dtor]p1: 5700 // [...] A typedef-name that names a class is a class-name 5701 // (7.1.3); however, a typedef-name that names a class shall not 5702 // be used as the identifier in the declarator for a destructor 5703 // declaration. 5704 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 5705 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 5706 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 5707 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 5708 else if (const TemplateSpecializationType *TST = 5709 DeclaratorType->getAs<TemplateSpecializationType>()) 5710 if (TST->isTypeAlias()) 5711 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 5712 << DeclaratorType << 1; 5713 5714 // C++ [class.dtor]p2: 5715 // A destructor is used to destroy objects of its class type. A 5716 // destructor takes no parameters, and no return type can be 5717 // specified for it (not even void). The address of a destructor 5718 // shall not be taken. A destructor shall not be static. A 5719 // destructor can be invoked for a const, volatile or const 5720 // volatile object. A destructor shall not be declared const, 5721 // volatile or const volatile (9.3.2). 5722 if (SC == SC_Static) { 5723 if (!D.isInvalidType()) 5724 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 5725 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 5726 << SourceRange(D.getIdentifierLoc()) 5727 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5728 5729 SC = SC_None; 5730 } 5731 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 5732 // Destructors don't have return types, but the parser will 5733 // happily parse something like: 5734 // 5735 // class X { 5736 // float ~X(); 5737 // }; 5738 // 5739 // The return type will be eliminated later. 5740 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 5741 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 5742 << SourceRange(D.getIdentifierLoc()); 5743 } 5744 5745 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 5746 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 5747 if (FTI.TypeQuals & Qualifiers::Const) 5748 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 5749 << "const" << SourceRange(D.getIdentifierLoc()); 5750 if (FTI.TypeQuals & Qualifiers::Volatile) 5751 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 5752 << "volatile" << SourceRange(D.getIdentifierLoc()); 5753 if (FTI.TypeQuals & Qualifiers::Restrict) 5754 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 5755 << "restrict" << SourceRange(D.getIdentifierLoc()); 5756 D.setInvalidType(); 5757 } 5758 5759 // C++0x [class.dtor]p2: 5760 // A destructor shall not be declared with a ref-qualifier. 5761 if (FTI.hasRefQualifier()) { 5762 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 5763 << FTI.RefQualifierIsLValueRef 5764 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 5765 D.setInvalidType(); 5766 } 5767 5768 // Make sure we don't have any parameters. 5769 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) { 5770 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 5771 5772 // Delete the parameters. 5773 FTI.freeArgs(); 5774 D.setInvalidType(); 5775 } 5776 5777 // Make sure the destructor isn't variadic. 5778 if (FTI.isVariadic) { 5779 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 5780 D.setInvalidType(); 5781 } 5782 5783 // Rebuild the function type "R" without any type qualifiers or 5784 // parameters (in case any of the errors above fired) and with 5785 // "void" as the return type, since destructors don't have return 5786 // types. 5787 if (!D.isInvalidType()) 5788 return R; 5789 5790 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 5791 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 5792 EPI.Variadic = false; 5793 EPI.TypeQuals = 0; 5794 EPI.RefQualifier = RQ_None; 5795 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI); 5796} 5797 5798/// CheckConversionDeclarator - Called by ActOnDeclarator to check the 5799/// well-formednes of the conversion function declarator @p D with 5800/// type @p R. If there are any errors in the declarator, this routine 5801/// will emit diagnostics and return true. Otherwise, it will return 5802/// false. Either way, the type @p R will be updated to reflect a 5803/// well-formed type for the conversion operator. 5804void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 5805 StorageClass& SC) { 5806 // C++ [class.conv.fct]p1: 5807 // Neither parameter types nor return type can be specified. The 5808 // type of a conversion function (8.3.5) is "function taking no 5809 // parameter returning conversion-type-id." 5810 if (SC == SC_Static) { 5811 if (!D.isInvalidType()) 5812 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 5813 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 5814 << SourceRange(D.getIdentifierLoc()); 5815 D.setInvalidType(); 5816 SC = SC_None; 5817 } 5818 5819 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId); 5820 5821 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 5822 // Conversion functions don't have return types, but the parser will 5823 // happily parse something like: 5824 // 5825 // class X { 5826 // float operator bool(); 5827 // }; 5828 // 5829 // The return type will be changed later anyway. 5830 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 5831 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 5832 << SourceRange(D.getIdentifierLoc()); 5833 D.setInvalidType(); 5834 } 5835 5836 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 5837 5838 // Make sure we don't have any parameters. 5839 if (Proto->getNumArgs() > 0) { 5840 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 5841 5842 // Delete the parameters. 5843 D.getFunctionTypeInfo().freeArgs(); 5844 D.setInvalidType(); 5845 } else if (Proto->isVariadic()) { 5846 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 5847 D.setInvalidType(); 5848 } 5849 5850 // Diagnose "&operator bool()" and other such nonsense. This 5851 // is actually a gcc extension which we don't support. 5852 if (Proto->getResultType() != ConvType) { 5853 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 5854 << Proto->getResultType(); 5855 D.setInvalidType(); 5856 ConvType = Proto->getResultType(); 5857 } 5858 5859 // C++ [class.conv.fct]p4: 5860 // The conversion-type-id shall not represent a function type nor 5861 // an array type. 5862 if (ConvType->isArrayType()) { 5863 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 5864 ConvType = Context.getPointerType(ConvType); 5865 D.setInvalidType(); 5866 } else if (ConvType->isFunctionType()) { 5867 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 5868 ConvType = Context.getPointerType(ConvType); 5869 D.setInvalidType(); 5870 } 5871 5872 // Rebuild the function type "R" without any parameters (in case any 5873 // of the errors above fired) and with the conversion type as the 5874 // return type. 5875 if (D.isInvalidType()) 5876 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo()); 5877 5878 // C++0x explicit conversion operators. 5879 if (D.getDeclSpec().isExplicitSpecified()) 5880 Diag(D.getDeclSpec().getExplicitSpecLoc(), 5881 getLangOpts().CPlusPlus11 ? 5882 diag::warn_cxx98_compat_explicit_conversion_functions : 5883 diag::ext_explicit_conversion_functions) 5884 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 5885} 5886 5887/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 5888/// the declaration of the given C++ conversion function. This routine 5889/// is responsible for recording the conversion function in the C++ 5890/// class, if possible. 5891Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 5892 assert(Conversion && "Expected to receive a conversion function declaration"); 5893 5894 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 5895 5896 // Make sure we aren't redeclaring the conversion function. 5897 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 5898 5899 // C++ [class.conv.fct]p1: 5900 // [...] A conversion function is never used to convert a 5901 // (possibly cv-qualified) object to the (possibly cv-qualified) 5902 // same object type (or a reference to it), to a (possibly 5903 // cv-qualified) base class of that type (or a reference to it), 5904 // or to (possibly cv-qualified) void. 5905 // FIXME: Suppress this warning if the conversion function ends up being a 5906 // virtual function that overrides a virtual function in a base class. 5907 QualType ClassType 5908 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 5909 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 5910 ConvType = ConvTypeRef->getPointeeType(); 5911 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 5912 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 5913 /* Suppress diagnostics for instantiations. */; 5914 else if (ConvType->isRecordType()) { 5915 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 5916 if (ConvType == ClassType) 5917 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 5918 << ClassType; 5919 else if (IsDerivedFrom(ClassType, ConvType)) 5920 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 5921 << ClassType << ConvType; 5922 } else if (ConvType->isVoidType()) { 5923 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 5924 << ClassType << ConvType; 5925 } 5926 5927 if (FunctionTemplateDecl *ConversionTemplate 5928 = Conversion->getDescribedFunctionTemplate()) 5929 return ConversionTemplate; 5930 5931 return Conversion; 5932} 5933 5934//===----------------------------------------------------------------------===// 5935// Namespace Handling 5936//===----------------------------------------------------------------------===// 5937 5938/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is 5939/// reopened. 5940static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 5941 SourceLocation Loc, 5942 IdentifierInfo *II, bool *IsInline, 5943 NamespaceDecl *PrevNS) { 5944 assert(*IsInline != PrevNS->isInline()); 5945 5946 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 5947 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 5948 // inline namespaces, with the intention of bringing names into namespace std. 5949 // 5950 // We support this just well enough to get that case working; this is not 5951 // sufficient to support reopening namespaces as inline in general. 5952 if (*IsInline && II && II->getName().startswith("__atomic") && 5953 S.getSourceManager().isInSystemHeader(Loc)) { 5954 // Mark all prior declarations of the namespace as inline. 5955 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 5956 NS = NS->getPreviousDecl()) 5957 NS->setInline(*IsInline); 5958 // Patch up the lookup table for the containing namespace. This isn't really 5959 // correct, but it's good enough for this particular case. 5960 for (DeclContext::decl_iterator I = PrevNS->decls_begin(), 5961 E = PrevNS->decls_end(); I != E; ++I) 5962 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I)) 5963 PrevNS->getParent()->makeDeclVisibleInContext(ND); 5964 return; 5965 } 5966 5967 if (PrevNS->isInline()) 5968 // The user probably just forgot the 'inline', so suggest that it 5969 // be added back. 5970 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 5971 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 5972 else 5973 S.Diag(Loc, diag::err_inline_namespace_mismatch) 5974 << IsInline; 5975 5976 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 5977 *IsInline = PrevNS->isInline(); 5978} 5979 5980/// ActOnStartNamespaceDef - This is called at the start of a namespace 5981/// definition. 5982Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 5983 SourceLocation InlineLoc, 5984 SourceLocation NamespaceLoc, 5985 SourceLocation IdentLoc, 5986 IdentifierInfo *II, 5987 SourceLocation LBrace, 5988 AttributeList *AttrList) { 5989 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 5990 // For anonymous namespace, take the location of the left brace. 5991 SourceLocation Loc = II ? IdentLoc : LBrace; 5992 bool IsInline = InlineLoc.isValid(); 5993 bool IsInvalid = false; 5994 bool IsStd = false; 5995 bool AddToKnown = false; 5996 Scope *DeclRegionScope = NamespcScope->getParent(); 5997 5998 NamespaceDecl *PrevNS = 0; 5999 if (II) { 6000 // C++ [namespace.def]p2: 6001 // The identifier in an original-namespace-definition shall not 6002 // have been previously defined in the declarative region in 6003 // which the original-namespace-definition appears. The 6004 // identifier in an original-namespace-definition is the name of 6005 // the namespace. Subsequently in that declarative region, it is 6006 // treated as an original-namespace-name. 6007 // 6008 // Since namespace names are unique in their scope, and we don't 6009 // look through using directives, just look for any ordinary names. 6010 6011 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member | 6012 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag | 6013 Decl::IDNS_Namespace; 6014 NamedDecl *PrevDecl = 0; 6015 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II); 6016 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 6017 ++I) { 6018 if ((*I)->getIdentifierNamespace() & IDNS) { 6019 PrevDecl = *I; 6020 break; 6021 } 6022 } 6023 6024 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 6025 6026 if (PrevNS) { 6027 // This is an extended namespace definition. 6028 if (IsInline != PrevNS->isInline()) 6029 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 6030 &IsInline, PrevNS); 6031 } else if (PrevDecl) { 6032 // This is an invalid name redefinition. 6033 Diag(Loc, diag::err_redefinition_different_kind) 6034 << II; 6035 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 6036 IsInvalid = true; 6037 // Continue on to push Namespc as current DeclContext and return it. 6038 } else if (II->isStr("std") && 6039 CurContext->getRedeclContext()->isTranslationUnit()) { 6040 // This is the first "real" definition of the namespace "std", so update 6041 // our cache of the "std" namespace to point at this definition. 6042 PrevNS = getStdNamespace(); 6043 IsStd = true; 6044 AddToKnown = !IsInline; 6045 } else { 6046 // We've seen this namespace for the first time. 6047 AddToKnown = !IsInline; 6048 } 6049 } else { 6050 // Anonymous namespaces. 6051 6052 // Determine whether the parent already has an anonymous namespace. 6053 DeclContext *Parent = CurContext->getRedeclContext(); 6054 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 6055 PrevNS = TU->getAnonymousNamespace(); 6056 } else { 6057 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 6058 PrevNS = ND->getAnonymousNamespace(); 6059 } 6060 6061 if (PrevNS && IsInline != PrevNS->isInline()) 6062 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 6063 &IsInline, PrevNS); 6064 } 6065 6066 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 6067 StartLoc, Loc, II, PrevNS); 6068 if (IsInvalid) 6069 Namespc->setInvalidDecl(); 6070 6071 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 6072 6073 // FIXME: Should we be merging attributes? 6074 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 6075 PushNamespaceVisibilityAttr(Attr, Loc); 6076 6077 if (IsStd) 6078 StdNamespace = Namespc; 6079 if (AddToKnown) 6080 KnownNamespaces[Namespc] = false; 6081 6082 if (II) { 6083 PushOnScopeChains(Namespc, DeclRegionScope); 6084 } else { 6085 // Link the anonymous namespace into its parent. 6086 DeclContext *Parent = CurContext->getRedeclContext(); 6087 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 6088 TU->setAnonymousNamespace(Namespc); 6089 } else { 6090 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 6091 } 6092 6093 CurContext->addDecl(Namespc); 6094 6095 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 6096 // behaves as if it were replaced by 6097 // namespace unique { /* empty body */ } 6098 // using namespace unique; 6099 // namespace unique { namespace-body } 6100 // where all occurrences of 'unique' in a translation unit are 6101 // replaced by the same identifier and this identifier differs 6102 // from all other identifiers in the entire program. 6103 6104 // We just create the namespace with an empty name and then add an 6105 // implicit using declaration, just like the standard suggests. 6106 // 6107 // CodeGen enforces the "universally unique" aspect by giving all 6108 // declarations semantically contained within an anonymous 6109 // namespace internal linkage. 6110 6111 if (!PrevNS) { 6112 UsingDirectiveDecl* UD 6113 = UsingDirectiveDecl::Create(Context, Parent, 6114 /* 'using' */ LBrace, 6115 /* 'namespace' */ SourceLocation(), 6116 /* qualifier */ NestedNameSpecifierLoc(), 6117 /* identifier */ SourceLocation(), 6118 Namespc, 6119 /* Ancestor */ Parent); 6120 UD->setImplicit(); 6121 Parent->addDecl(UD); 6122 } 6123 } 6124 6125 ActOnDocumentableDecl(Namespc); 6126 6127 // Although we could have an invalid decl (i.e. the namespace name is a 6128 // redefinition), push it as current DeclContext and try to continue parsing. 6129 // FIXME: We should be able to push Namespc here, so that the each DeclContext 6130 // for the namespace has the declarations that showed up in that particular 6131 // namespace definition. 6132 PushDeclContext(NamespcScope, Namespc); 6133 return Namespc; 6134} 6135 6136/// getNamespaceDecl - Returns the namespace a decl represents. If the decl 6137/// is a namespace alias, returns the namespace it points to. 6138static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 6139 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 6140 return AD->getNamespace(); 6141 return dyn_cast_or_null<NamespaceDecl>(D); 6142} 6143 6144/// ActOnFinishNamespaceDef - This callback is called after a namespace is 6145/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 6146void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 6147 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 6148 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 6149 Namespc->setRBraceLoc(RBrace); 6150 PopDeclContext(); 6151 if (Namespc->hasAttr<VisibilityAttr>()) 6152 PopPragmaVisibility(true, RBrace); 6153} 6154 6155CXXRecordDecl *Sema::getStdBadAlloc() const { 6156 return cast_or_null<CXXRecordDecl>( 6157 StdBadAlloc.get(Context.getExternalSource())); 6158} 6159 6160NamespaceDecl *Sema::getStdNamespace() const { 6161 return cast_or_null<NamespaceDecl>( 6162 StdNamespace.get(Context.getExternalSource())); 6163} 6164 6165/// \brief Retrieve the special "std" namespace, which may require us to 6166/// implicitly define the namespace. 6167NamespaceDecl *Sema::getOrCreateStdNamespace() { 6168 if (!StdNamespace) { 6169 // The "std" namespace has not yet been defined, so build one implicitly. 6170 StdNamespace = NamespaceDecl::Create(Context, 6171 Context.getTranslationUnitDecl(), 6172 /*Inline=*/false, 6173 SourceLocation(), SourceLocation(), 6174 &PP.getIdentifierTable().get("std"), 6175 /*PrevDecl=*/0); 6176 getStdNamespace()->setImplicit(true); 6177 } 6178 6179 return getStdNamespace(); 6180} 6181 6182bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 6183 assert(getLangOpts().CPlusPlus && 6184 "Looking for std::initializer_list outside of C++."); 6185 6186 // We're looking for implicit instantiations of 6187 // template <typename E> class std::initializer_list. 6188 6189 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 6190 return false; 6191 6192 ClassTemplateDecl *Template = 0; 6193 const TemplateArgument *Arguments = 0; 6194 6195 if (const RecordType *RT = Ty->getAs<RecordType>()) { 6196 6197 ClassTemplateSpecializationDecl *Specialization = 6198 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 6199 if (!Specialization) 6200 return false; 6201 6202 Template = Specialization->getSpecializedTemplate(); 6203 Arguments = Specialization->getTemplateArgs().data(); 6204 } else if (const TemplateSpecializationType *TST = 6205 Ty->getAs<TemplateSpecializationType>()) { 6206 Template = dyn_cast_or_null<ClassTemplateDecl>( 6207 TST->getTemplateName().getAsTemplateDecl()); 6208 Arguments = TST->getArgs(); 6209 } 6210 if (!Template) 6211 return false; 6212 6213 if (!StdInitializerList) { 6214 // Haven't recognized std::initializer_list yet, maybe this is it. 6215 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 6216 if (TemplateClass->getIdentifier() != 6217 &PP.getIdentifierTable().get("initializer_list") || 6218 !getStdNamespace()->InEnclosingNamespaceSetOf( 6219 TemplateClass->getDeclContext())) 6220 return false; 6221 // This is a template called std::initializer_list, but is it the right 6222 // template? 6223 TemplateParameterList *Params = Template->getTemplateParameters(); 6224 if (Params->getMinRequiredArguments() != 1) 6225 return false; 6226 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 6227 return false; 6228 6229 // It's the right template. 6230 StdInitializerList = Template; 6231 } 6232 6233 if (Template != StdInitializerList) 6234 return false; 6235 6236 // This is an instance of std::initializer_list. Find the argument type. 6237 if (Element) 6238 *Element = Arguments[0].getAsType(); 6239 return true; 6240} 6241 6242static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 6243 NamespaceDecl *Std = S.getStdNamespace(); 6244 if (!Std) { 6245 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 6246 return 0; 6247 } 6248 6249 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 6250 Loc, Sema::LookupOrdinaryName); 6251 if (!S.LookupQualifiedName(Result, Std)) { 6252 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 6253 return 0; 6254 } 6255 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 6256 if (!Template) { 6257 Result.suppressDiagnostics(); 6258 // We found something weird. Complain about the first thing we found. 6259 NamedDecl *Found = *Result.begin(); 6260 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 6261 return 0; 6262 } 6263 6264 // We found some template called std::initializer_list. Now verify that it's 6265 // correct. 6266 TemplateParameterList *Params = Template->getTemplateParameters(); 6267 if (Params->getMinRequiredArguments() != 1 || 6268 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 6269 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 6270 return 0; 6271 } 6272 6273 return Template; 6274} 6275 6276QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 6277 if (!StdInitializerList) { 6278 StdInitializerList = LookupStdInitializerList(*this, Loc); 6279 if (!StdInitializerList) 6280 return QualType(); 6281 } 6282 6283 TemplateArgumentListInfo Args(Loc, Loc); 6284 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 6285 Context.getTrivialTypeSourceInfo(Element, 6286 Loc))); 6287 return Context.getCanonicalType( 6288 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 6289} 6290 6291bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) { 6292 // C++ [dcl.init.list]p2: 6293 // A constructor is an initializer-list constructor if its first parameter 6294 // is of type std::initializer_list<E> or reference to possibly cv-qualified 6295 // std::initializer_list<E> for some type E, and either there are no other 6296 // parameters or else all other parameters have default arguments. 6297 if (Ctor->getNumParams() < 1 || 6298 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 6299 return false; 6300 6301 QualType ArgType = Ctor->getParamDecl(0)->getType(); 6302 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 6303 ArgType = RT->getPointeeType().getUnqualifiedType(); 6304 6305 return isStdInitializerList(ArgType, 0); 6306} 6307 6308/// \brief Determine whether a using statement is in a context where it will be 6309/// apply in all contexts. 6310static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 6311 switch (CurContext->getDeclKind()) { 6312 case Decl::TranslationUnit: 6313 return true; 6314 case Decl::LinkageSpec: 6315 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 6316 default: 6317 return false; 6318 } 6319} 6320 6321namespace { 6322 6323// Callback to only accept typo corrections that are namespaces. 6324class NamespaceValidatorCCC : public CorrectionCandidateCallback { 6325 public: 6326 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 6327 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 6328 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 6329 } 6330 return false; 6331 } 6332}; 6333 6334} 6335 6336static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 6337 CXXScopeSpec &SS, 6338 SourceLocation IdentLoc, 6339 IdentifierInfo *Ident) { 6340 NamespaceValidatorCCC Validator; 6341 R.clear(); 6342 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(), 6343 R.getLookupKind(), Sc, &SS, 6344 Validator)) { 6345 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 6346 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts())); 6347 if (DeclContext *DC = S.computeDeclContext(SS, false)) 6348 S.Diag(IdentLoc, diag::err_using_directive_member_suggest) 6349 << Ident << DC << CorrectedQuotedStr << SS.getRange() 6350 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(), 6351 CorrectedStr); 6352 else 6353 S.Diag(IdentLoc, diag::err_using_directive_suggest) 6354 << Ident << CorrectedQuotedStr 6355 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr); 6356 6357 S.Diag(Corrected.getCorrectionDecl()->getLocation(), 6358 diag::note_namespace_defined_here) << CorrectedQuotedStr; 6359 6360 R.addDecl(Corrected.getCorrectionDecl()); 6361 return true; 6362 } 6363 return false; 6364} 6365 6366Decl *Sema::ActOnUsingDirective(Scope *S, 6367 SourceLocation UsingLoc, 6368 SourceLocation NamespcLoc, 6369 CXXScopeSpec &SS, 6370 SourceLocation IdentLoc, 6371 IdentifierInfo *NamespcName, 6372 AttributeList *AttrList) { 6373 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 6374 assert(NamespcName && "Invalid NamespcName."); 6375 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 6376 6377 // This can only happen along a recovery path. 6378 while (S->getFlags() & Scope::TemplateParamScope) 6379 S = S->getParent(); 6380 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 6381 6382 UsingDirectiveDecl *UDir = 0; 6383 NestedNameSpecifier *Qualifier = 0; 6384 if (SS.isSet()) 6385 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 6386 6387 // Lookup namespace name. 6388 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 6389 LookupParsedName(R, S, &SS); 6390 if (R.isAmbiguous()) 6391 return 0; 6392 6393 if (R.empty()) { 6394 R.clear(); 6395 // Allow "using namespace std;" or "using namespace ::std;" even if 6396 // "std" hasn't been defined yet, for GCC compatibility. 6397 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 6398 NamespcName->isStr("std")) { 6399 Diag(IdentLoc, diag::ext_using_undefined_std); 6400 R.addDecl(getOrCreateStdNamespace()); 6401 R.resolveKind(); 6402 } 6403 // Otherwise, attempt typo correction. 6404 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 6405 } 6406 6407 if (!R.empty()) { 6408 NamedDecl *Named = R.getFoundDecl(); 6409 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named)) 6410 && "expected namespace decl"); 6411 // C++ [namespace.udir]p1: 6412 // A using-directive specifies that the names in the nominated 6413 // namespace can be used in the scope in which the 6414 // using-directive appears after the using-directive. During 6415 // unqualified name lookup (3.4.1), the names appear as if they 6416 // were declared in the nearest enclosing namespace which 6417 // contains both the using-directive and the nominated 6418 // namespace. [Note: in this context, "contains" means "contains 6419 // directly or indirectly". ] 6420 6421 // Find enclosing context containing both using-directive and 6422 // nominated namespace. 6423 NamespaceDecl *NS = getNamespaceDecl(Named); 6424 DeclContext *CommonAncestor = cast<DeclContext>(NS); 6425 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 6426 CommonAncestor = CommonAncestor->getParent(); 6427 6428 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 6429 SS.getWithLocInContext(Context), 6430 IdentLoc, Named, CommonAncestor); 6431 6432 if (IsUsingDirectiveInToplevelContext(CurContext) && 6433 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 6434 Diag(IdentLoc, diag::warn_using_directive_in_header); 6435 } 6436 6437 PushUsingDirective(S, UDir); 6438 } else { 6439 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 6440 } 6441 6442 // FIXME: We ignore attributes for now. 6443 return UDir; 6444} 6445 6446void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 6447 // If the scope has an associated entity and the using directive is at 6448 // namespace or translation unit scope, add the UsingDirectiveDecl into 6449 // its lookup structure so qualified name lookup can find it. 6450 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()); 6451 if (Ctx && !Ctx->isFunctionOrMethod()) 6452 Ctx->addDecl(UDir); 6453 else 6454 // Otherwise, it is at block sope. The using-directives will affect lookup 6455 // only to the end of the scope. 6456 S->PushUsingDirective(UDir); 6457} 6458 6459 6460Decl *Sema::ActOnUsingDeclaration(Scope *S, 6461 AccessSpecifier AS, 6462 bool HasUsingKeyword, 6463 SourceLocation UsingLoc, 6464 CXXScopeSpec &SS, 6465 UnqualifiedId &Name, 6466 AttributeList *AttrList, 6467 bool IsTypeName, 6468 SourceLocation TypenameLoc) { 6469 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 6470 6471 switch (Name.getKind()) { 6472 case UnqualifiedId::IK_ImplicitSelfParam: 6473 case UnqualifiedId::IK_Identifier: 6474 case UnqualifiedId::IK_OperatorFunctionId: 6475 case UnqualifiedId::IK_LiteralOperatorId: 6476 case UnqualifiedId::IK_ConversionFunctionId: 6477 break; 6478 6479 case UnqualifiedId::IK_ConstructorName: 6480 case UnqualifiedId::IK_ConstructorTemplateId: 6481 // C++11 inheriting constructors. 6482 Diag(Name.getLocStart(), 6483 getLangOpts().CPlusPlus11 ? 6484 // FIXME: Produce warn_cxx98_compat_using_decl_constructor 6485 // instead once inheriting constructors work. 6486 diag::err_using_decl_constructor_unsupported : 6487 diag::err_using_decl_constructor) 6488 << SS.getRange(); 6489 6490 if (getLangOpts().CPlusPlus11) break; 6491 6492 return 0; 6493 6494 case UnqualifiedId::IK_DestructorName: 6495 Diag(Name.getLocStart(), diag::err_using_decl_destructor) 6496 << SS.getRange(); 6497 return 0; 6498 6499 case UnqualifiedId::IK_TemplateId: 6500 Diag(Name.getLocStart(), diag::err_using_decl_template_id) 6501 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 6502 return 0; 6503 } 6504 6505 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 6506 DeclarationName TargetName = TargetNameInfo.getName(); 6507 if (!TargetName) 6508 return 0; 6509 6510 // Warn about using declarations. 6511 // TODO: store that the declaration was written without 'using' and 6512 // talk about access decls instead of using decls in the 6513 // diagnostics. 6514 if (!HasUsingKeyword) { 6515 UsingLoc = Name.getLocStart(); 6516 6517 Diag(UsingLoc, diag::warn_access_decl_deprecated) 6518 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 6519 } 6520 6521 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 6522 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 6523 return 0; 6524 6525 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 6526 TargetNameInfo, AttrList, 6527 /* IsInstantiation */ false, 6528 IsTypeName, TypenameLoc); 6529 if (UD) 6530 PushOnScopeChains(UD, S, /*AddToContext*/ false); 6531 6532 return UD; 6533} 6534 6535/// \brief Determine whether a using declaration considers the given 6536/// declarations as "equivalent", e.g., if they are redeclarations of 6537/// the same entity or are both typedefs of the same type. 6538static bool 6539IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2, 6540 bool &SuppressRedeclaration) { 6541 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) { 6542 SuppressRedeclaration = false; 6543 return true; 6544 } 6545 6546 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 6547 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) { 6548 SuppressRedeclaration = true; 6549 return Context.hasSameType(TD1->getUnderlyingType(), 6550 TD2->getUnderlyingType()); 6551 } 6552 6553 return false; 6554} 6555 6556 6557/// Determines whether to create a using shadow decl for a particular 6558/// decl, given the set of decls existing prior to this using lookup. 6559bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 6560 const LookupResult &Previous) { 6561 // Diagnose finding a decl which is not from a base class of the 6562 // current class. We do this now because there are cases where this 6563 // function will silently decide not to build a shadow decl, which 6564 // will pre-empt further diagnostics. 6565 // 6566 // We don't need to do this in C++0x because we do the check once on 6567 // the qualifier. 6568 // 6569 // FIXME: diagnose the following if we care enough: 6570 // struct A { int foo; }; 6571 // struct B : A { using A::foo; }; 6572 // template <class T> struct C : A {}; 6573 // template <class T> struct D : C<T> { using B::foo; } // <--- 6574 // This is invalid (during instantiation) in C++03 because B::foo 6575 // resolves to the using decl in B, which is not a base class of D<T>. 6576 // We can't diagnose it immediately because C<T> is an unknown 6577 // specialization. The UsingShadowDecl in D<T> then points directly 6578 // to A::foo, which will look well-formed when we instantiate. 6579 // The right solution is to not collapse the shadow-decl chain. 6580 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 6581 DeclContext *OrigDC = Orig->getDeclContext(); 6582 6583 // Handle enums and anonymous structs. 6584 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 6585 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 6586 while (OrigRec->isAnonymousStructOrUnion()) 6587 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 6588 6589 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 6590 if (OrigDC == CurContext) { 6591 Diag(Using->getLocation(), 6592 diag::err_using_decl_nested_name_specifier_is_current_class) 6593 << Using->getQualifierLoc().getSourceRange(); 6594 Diag(Orig->getLocation(), diag::note_using_decl_target); 6595 return true; 6596 } 6597 6598 Diag(Using->getQualifierLoc().getBeginLoc(), 6599 diag::err_using_decl_nested_name_specifier_is_not_base_class) 6600 << Using->getQualifier() 6601 << cast<CXXRecordDecl>(CurContext) 6602 << Using->getQualifierLoc().getSourceRange(); 6603 Diag(Orig->getLocation(), diag::note_using_decl_target); 6604 return true; 6605 } 6606 } 6607 6608 if (Previous.empty()) return false; 6609 6610 NamedDecl *Target = Orig; 6611 if (isa<UsingShadowDecl>(Target)) 6612 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 6613 6614 // If the target happens to be one of the previous declarations, we 6615 // don't have a conflict. 6616 // 6617 // FIXME: but we might be increasing its access, in which case we 6618 // should redeclare it. 6619 NamedDecl *NonTag = 0, *Tag = 0; 6620 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 6621 I != E; ++I) { 6622 NamedDecl *D = (*I)->getUnderlyingDecl(); 6623 bool Result; 6624 if (IsEquivalentForUsingDecl(Context, D, Target, Result)) 6625 return Result; 6626 6627 (isa<TagDecl>(D) ? Tag : NonTag) = D; 6628 } 6629 6630 if (Target->isFunctionOrFunctionTemplate()) { 6631 FunctionDecl *FD; 6632 if (isa<FunctionTemplateDecl>(Target)) 6633 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl(); 6634 else 6635 FD = cast<FunctionDecl>(Target); 6636 6637 NamedDecl *OldDecl = 0; 6638 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) { 6639 case Ovl_Overload: 6640 return false; 6641 6642 case Ovl_NonFunction: 6643 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6644 break; 6645 6646 // We found a decl with the exact signature. 6647 case Ovl_Match: 6648 // If we're in a record, we want to hide the target, so we 6649 // return true (without a diagnostic) to tell the caller not to 6650 // build a shadow decl. 6651 if (CurContext->isRecord()) 6652 return true; 6653 6654 // If we're not in a record, this is an error. 6655 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6656 break; 6657 } 6658 6659 Diag(Target->getLocation(), diag::note_using_decl_target); 6660 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 6661 return true; 6662 } 6663 6664 // Target is not a function. 6665 6666 if (isa<TagDecl>(Target)) { 6667 // No conflict between a tag and a non-tag. 6668 if (!Tag) return false; 6669 6670 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6671 Diag(Target->getLocation(), diag::note_using_decl_target); 6672 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 6673 return true; 6674 } 6675 6676 // No conflict between a tag and a non-tag. 6677 if (!NonTag) return false; 6678 6679 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6680 Diag(Target->getLocation(), diag::note_using_decl_target); 6681 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 6682 return true; 6683} 6684 6685/// Builds a shadow declaration corresponding to a 'using' declaration. 6686UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 6687 UsingDecl *UD, 6688 NamedDecl *Orig) { 6689 6690 // If we resolved to another shadow declaration, just coalesce them. 6691 NamedDecl *Target = Orig; 6692 if (isa<UsingShadowDecl>(Target)) { 6693 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 6694 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 6695 } 6696 6697 UsingShadowDecl *Shadow 6698 = UsingShadowDecl::Create(Context, CurContext, 6699 UD->getLocation(), UD, Target); 6700 UD->addShadowDecl(Shadow); 6701 6702 Shadow->setAccess(UD->getAccess()); 6703 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 6704 Shadow->setInvalidDecl(); 6705 6706 if (S) 6707 PushOnScopeChains(Shadow, S); 6708 else 6709 CurContext->addDecl(Shadow); 6710 6711 6712 return Shadow; 6713} 6714 6715/// Hides a using shadow declaration. This is required by the current 6716/// using-decl implementation when a resolvable using declaration in a 6717/// class is followed by a declaration which would hide or override 6718/// one or more of the using decl's targets; for example: 6719/// 6720/// struct Base { void foo(int); }; 6721/// struct Derived : Base { 6722/// using Base::foo; 6723/// void foo(int); 6724/// }; 6725/// 6726/// The governing language is C++03 [namespace.udecl]p12: 6727/// 6728/// When a using-declaration brings names from a base class into a 6729/// derived class scope, member functions in the derived class 6730/// override and/or hide member functions with the same name and 6731/// parameter types in a base class (rather than conflicting). 6732/// 6733/// There are two ways to implement this: 6734/// (1) optimistically create shadow decls when they're not hidden 6735/// by existing declarations, or 6736/// (2) don't create any shadow decls (or at least don't make them 6737/// visible) until we've fully parsed/instantiated the class. 6738/// The problem with (1) is that we might have to retroactively remove 6739/// a shadow decl, which requires several O(n) operations because the 6740/// decl structures are (very reasonably) not designed for removal. 6741/// (2) avoids this but is very fiddly and phase-dependent. 6742void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 6743 if (Shadow->getDeclName().getNameKind() == 6744 DeclarationName::CXXConversionFunctionName) 6745 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 6746 6747 // Remove it from the DeclContext... 6748 Shadow->getDeclContext()->removeDecl(Shadow); 6749 6750 // ...and the scope, if applicable... 6751 if (S) { 6752 S->RemoveDecl(Shadow); 6753 IdResolver.RemoveDecl(Shadow); 6754 } 6755 6756 // ...and the using decl. 6757 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 6758 6759 // TODO: complain somehow if Shadow was used. It shouldn't 6760 // be possible for this to happen, because...? 6761} 6762 6763/// Builds a using declaration. 6764/// 6765/// \param IsInstantiation - Whether this call arises from an 6766/// instantiation of an unresolved using declaration. We treat 6767/// the lookup differently for these declarations. 6768NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 6769 SourceLocation UsingLoc, 6770 CXXScopeSpec &SS, 6771 const DeclarationNameInfo &NameInfo, 6772 AttributeList *AttrList, 6773 bool IsInstantiation, 6774 bool IsTypeName, 6775 SourceLocation TypenameLoc) { 6776 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 6777 SourceLocation IdentLoc = NameInfo.getLoc(); 6778 assert(IdentLoc.isValid() && "Invalid TargetName location."); 6779 6780 // FIXME: We ignore attributes for now. 6781 6782 if (SS.isEmpty()) { 6783 Diag(IdentLoc, diag::err_using_requires_qualname); 6784 return 0; 6785 } 6786 6787 // Do the redeclaration lookup in the current scope. 6788 LookupResult Previous(*this, NameInfo, LookupUsingDeclName, 6789 ForRedeclaration); 6790 Previous.setHideTags(false); 6791 if (S) { 6792 LookupName(Previous, S); 6793 6794 // It is really dumb that we have to do this. 6795 LookupResult::Filter F = Previous.makeFilter(); 6796 while (F.hasNext()) { 6797 NamedDecl *D = F.next(); 6798 if (!isDeclInScope(D, CurContext, S)) 6799 F.erase(); 6800 } 6801 F.done(); 6802 } else { 6803 assert(IsInstantiation && "no scope in non-instantiation"); 6804 assert(CurContext->isRecord() && "scope not record in instantiation"); 6805 LookupQualifiedName(Previous, CurContext); 6806 } 6807 6808 // Check for invalid redeclarations. 6809 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous)) 6810 return 0; 6811 6812 // Check for bad qualifiers. 6813 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc)) 6814 return 0; 6815 6816 DeclContext *LookupContext = computeDeclContext(SS); 6817 NamedDecl *D; 6818 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 6819 if (!LookupContext) { 6820 if (IsTypeName) { 6821 // FIXME: not all declaration name kinds are legal here 6822 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 6823 UsingLoc, TypenameLoc, 6824 QualifierLoc, 6825 IdentLoc, NameInfo.getName()); 6826 } else { 6827 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 6828 QualifierLoc, NameInfo); 6829 } 6830 } else { 6831 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 6832 NameInfo, IsTypeName); 6833 } 6834 D->setAccess(AS); 6835 CurContext->addDecl(D); 6836 6837 if (!LookupContext) return D; 6838 UsingDecl *UD = cast<UsingDecl>(D); 6839 6840 if (RequireCompleteDeclContext(SS, LookupContext)) { 6841 UD->setInvalidDecl(); 6842 return UD; 6843 } 6844 6845 // The normal rules do not apply to inheriting constructor declarations. 6846 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) { 6847 if (CheckInheritingConstructorUsingDecl(UD)) 6848 UD->setInvalidDecl(); 6849 return UD; 6850 } 6851 6852 // Otherwise, look up the target name. 6853 6854 LookupResult R(*this, NameInfo, LookupOrdinaryName); 6855 6856 // Unlike most lookups, we don't always want to hide tag 6857 // declarations: tag names are visible through the using declaration 6858 // even if hidden by ordinary names, *except* in a dependent context 6859 // where it's important for the sanity of two-phase lookup. 6860 if (!IsInstantiation) 6861 R.setHideTags(false); 6862 6863 // For the purposes of this lookup, we have a base object type 6864 // equal to that of the current context. 6865 if (CurContext->isRecord()) { 6866 R.setBaseObjectType( 6867 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 6868 } 6869 6870 LookupQualifiedName(R, LookupContext); 6871 6872 if (R.empty()) { 6873 Diag(IdentLoc, diag::err_no_member) 6874 << NameInfo.getName() << LookupContext << SS.getRange(); 6875 UD->setInvalidDecl(); 6876 return UD; 6877 } 6878 6879 if (R.isAmbiguous()) { 6880 UD->setInvalidDecl(); 6881 return UD; 6882 } 6883 6884 if (IsTypeName) { 6885 // If we asked for a typename and got a non-type decl, error out. 6886 if (!R.getAsSingle<TypeDecl>()) { 6887 Diag(IdentLoc, diag::err_using_typename_non_type); 6888 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 6889 Diag((*I)->getUnderlyingDecl()->getLocation(), 6890 diag::note_using_decl_target); 6891 UD->setInvalidDecl(); 6892 return UD; 6893 } 6894 } else { 6895 // If we asked for a non-typename and we got a type, error out, 6896 // but only if this is an instantiation of an unresolved using 6897 // decl. Otherwise just silently find the type name. 6898 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 6899 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 6900 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 6901 UD->setInvalidDecl(); 6902 return UD; 6903 } 6904 } 6905 6906 // C++0x N2914 [namespace.udecl]p6: 6907 // A using-declaration shall not name a namespace. 6908 if (R.getAsSingle<NamespaceDecl>()) { 6909 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 6910 << SS.getRange(); 6911 UD->setInvalidDecl(); 6912 return UD; 6913 } 6914 6915 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 6916 if (!CheckUsingShadowDecl(UD, *I, Previous)) 6917 BuildUsingShadowDecl(S, UD, *I); 6918 } 6919 6920 return UD; 6921} 6922 6923/// Additional checks for a using declaration referring to a constructor name. 6924bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 6925 assert(!UD->isTypeName() && "expecting a constructor name"); 6926 6927 const Type *SourceType = UD->getQualifier()->getAsType(); 6928 assert(SourceType && 6929 "Using decl naming constructor doesn't have type in scope spec."); 6930 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 6931 6932 // Check whether the named type is a direct base class. 6933 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified(); 6934 CXXRecordDecl::base_class_iterator BaseIt, BaseE; 6935 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end(); 6936 BaseIt != BaseE; ++BaseIt) { 6937 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified(); 6938 if (CanonicalSourceType == BaseType) 6939 break; 6940 if (BaseIt->getType()->isDependentType()) 6941 break; 6942 } 6943 6944 if (BaseIt == BaseE) { 6945 // Did not find SourceType in the bases. 6946 Diag(UD->getUsingLocation(), 6947 diag::err_using_decl_constructor_not_in_direct_base) 6948 << UD->getNameInfo().getSourceRange() 6949 << QualType(SourceType, 0) << TargetClass; 6950 return true; 6951 } 6952 6953 if (!CurContext->isDependentContext()) 6954 BaseIt->setInheritConstructors(); 6955 6956 return false; 6957} 6958 6959/// Checks that the given using declaration is not an invalid 6960/// redeclaration. Note that this is checking only for the using decl 6961/// itself, not for any ill-formedness among the UsingShadowDecls. 6962bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 6963 bool isTypeName, 6964 const CXXScopeSpec &SS, 6965 SourceLocation NameLoc, 6966 const LookupResult &Prev) { 6967 // C++03 [namespace.udecl]p8: 6968 // C++0x [namespace.udecl]p10: 6969 // A using-declaration is a declaration and can therefore be used 6970 // repeatedly where (and only where) multiple declarations are 6971 // allowed. 6972 // 6973 // That's in non-member contexts. 6974 if (!CurContext->getRedeclContext()->isRecord()) 6975 return false; 6976 6977 NestedNameSpecifier *Qual 6978 = static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 6979 6980 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 6981 NamedDecl *D = *I; 6982 6983 bool DTypename; 6984 NestedNameSpecifier *DQual; 6985 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 6986 DTypename = UD->isTypeName(); 6987 DQual = UD->getQualifier(); 6988 } else if (UnresolvedUsingValueDecl *UD 6989 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 6990 DTypename = false; 6991 DQual = UD->getQualifier(); 6992 } else if (UnresolvedUsingTypenameDecl *UD 6993 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 6994 DTypename = true; 6995 DQual = UD->getQualifier(); 6996 } else continue; 6997 6998 // using decls differ if one says 'typename' and the other doesn't. 6999 // FIXME: non-dependent using decls? 7000 if (isTypeName != DTypename) continue; 7001 7002 // using decls differ if they name different scopes (but note that 7003 // template instantiation can cause this check to trigger when it 7004 // didn't before instantiation). 7005 if (Context.getCanonicalNestedNameSpecifier(Qual) != 7006 Context.getCanonicalNestedNameSpecifier(DQual)) 7007 continue; 7008 7009 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 7010 Diag(D->getLocation(), diag::note_using_decl) << 1; 7011 return true; 7012 } 7013 7014 return false; 7015} 7016 7017 7018/// Checks that the given nested-name qualifier used in a using decl 7019/// in the current context is appropriately related to the current 7020/// scope. If an error is found, diagnoses it and returns true. 7021bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 7022 const CXXScopeSpec &SS, 7023 SourceLocation NameLoc) { 7024 DeclContext *NamedContext = computeDeclContext(SS); 7025 7026 if (!CurContext->isRecord()) { 7027 // C++03 [namespace.udecl]p3: 7028 // C++0x [namespace.udecl]p8: 7029 // A using-declaration for a class member shall be a member-declaration. 7030 7031 // If we weren't able to compute a valid scope, it must be a 7032 // dependent class scope. 7033 if (!NamedContext || NamedContext->isRecord()) { 7034 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 7035 << SS.getRange(); 7036 return true; 7037 } 7038 7039 // Otherwise, everything is known to be fine. 7040 return false; 7041 } 7042 7043 // The current scope is a record. 7044 7045 // If the named context is dependent, we can't decide much. 7046 if (!NamedContext) { 7047 // FIXME: in C++0x, we can diagnose if we can prove that the 7048 // nested-name-specifier does not refer to a base class, which is 7049 // still possible in some cases. 7050 7051 // Otherwise we have to conservatively report that things might be 7052 // okay. 7053 return false; 7054 } 7055 7056 if (!NamedContext->isRecord()) { 7057 // Ideally this would point at the last name in the specifier, 7058 // but we don't have that level of source info. 7059 Diag(SS.getRange().getBegin(), 7060 diag::err_using_decl_nested_name_specifier_is_not_class) 7061 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange(); 7062 return true; 7063 } 7064 7065 if (!NamedContext->isDependentContext() && 7066 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 7067 return true; 7068 7069 if (getLangOpts().CPlusPlus11) { 7070 // C++0x [namespace.udecl]p3: 7071 // In a using-declaration used as a member-declaration, the 7072 // nested-name-specifier shall name a base class of the class 7073 // being defined. 7074 7075 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 7076 cast<CXXRecordDecl>(NamedContext))) { 7077 if (CurContext == NamedContext) { 7078 Diag(NameLoc, 7079 diag::err_using_decl_nested_name_specifier_is_current_class) 7080 << SS.getRange(); 7081 return true; 7082 } 7083 7084 Diag(SS.getRange().getBegin(), 7085 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7086 << (NestedNameSpecifier*) SS.getScopeRep() 7087 << cast<CXXRecordDecl>(CurContext) 7088 << SS.getRange(); 7089 return true; 7090 } 7091 7092 return false; 7093 } 7094 7095 // C++03 [namespace.udecl]p4: 7096 // A using-declaration used as a member-declaration shall refer 7097 // to a member of a base class of the class being defined [etc.]. 7098 7099 // Salient point: SS doesn't have to name a base class as long as 7100 // lookup only finds members from base classes. Therefore we can 7101 // diagnose here only if we can prove that that can't happen, 7102 // i.e. if the class hierarchies provably don't intersect. 7103 7104 // TODO: it would be nice if "definitely valid" results were cached 7105 // in the UsingDecl and UsingShadowDecl so that these checks didn't 7106 // need to be repeated. 7107 7108 struct UserData { 7109 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases; 7110 7111 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) { 7112 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 7113 Data->Bases.insert(Base); 7114 return true; 7115 } 7116 7117 bool hasDependentBases(const CXXRecordDecl *Class) { 7118 return !Class->forallBases(collect, this); 7119 } 7120 7121 /// Returns true if the base is dependent or is one of the 7122 /// accumulated base classes. 7123 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) { 7124 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 7125 return !Data->Bases.count(Base); 7126 } 7127 7128 bool mightShareBases(const CXXRecordDecl *Class) { 7129 return Bases.count(Class) || !Class->forallBases(doesNotContain, this); 7130 } 7131 }; 7132 7133 UserData Data; 7134 7135 // Returns false if we find a dependent base. 7136 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext))) 7137 return false; 7138 7139 // Returns false if the class has a dependent base or if it or one 7140 // of its bases is present in the base set of the current context. 7141 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext))) 7142 return false; 7143 7144 Diag(SS.getRange().getBegin(), 7145 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7146 << (NestedNameSpecifier*) SS.getScopeRep() 7147 << cast<CXXRecordDecl>(CurContext) 7148 << SS.getRange(); 7149 7150 return true; 7151} 7152 7153Decl *Sema::ActOnAliasDeclaration(Scope *S, 7154 AccessSpecifier AS, 7155 MultiTemplateParamsArg TemplateParamLists, 7156 SourceLocation UsingLoc, 7157 UnqualifiedId &Name, 7158 TypeResult Type) { 7159 // Skip up to the relevant declaration scope. 7160 while (S->getFlags() & Scope::TemplateParamScope) 7161 S = S->getParent(); 7162 assert((S->getFlags() & Scope::DeclScope) && 7163 "got alias-declaration outside of declaration scope"); 7164 7165 if (Type.isInvalid()) 7166 return 0; 7167 7168 bool Invalid = false; 7169 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 7170 TypeSourceInfo *TInfo = 0; 7171 GetTypeFromParser(Type.get(), &TInfo); 7172 7173 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 7174 return 0; 7175 7176 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 7177 UPPC_DeclarationType)) { 7178 Invalid = true; 7179 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 7180 TInfo->getTypeLoc().getBeginLoc()); 7181 } 7182 7183 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration); 7184 LookupName(Previous, S); 7185 7186 // Warn about shadowing the name of a template parameter. 7187 if (Previous.isSingleResult() && 7188 Previous.getFoundDecl()->isTemplateParameter()) { 7189 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 7190 Previous.clear(); 7191 } 7192 7193 assert(Name.Kind == UnqualifiedId::IK_Identifier && 7194 "name in alias declaration must be an identifier"); 7195 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 7196 Name.StartLocation, 7197 Name.Identifier, TInfo); 7198 7199 NewTD->setAccess(AS); 7200 7201 if (Invalid) 7202 NewTD->setInvalidDecl(); 7203 7204 CheckTypedefForVariablyModifiedType(S, NewTD); 7205 Invalid |= NewTD->isInvalidDecl(); 7206 7207 bool Redeclaration = false; 7208 7209 NamedDecl *NewND; 7210 if (TemplateParamLists.size()) { 7211 TypeAliasTemplateDecl *OldDecl = 0; 7212 TemplateParameterList *OldTemplateParams = 0; 7213 7214 if (TemplateParamLists.size() != 1) { 7215 Diag(UsingLoc, diag::err_alias_template_extra_headers) 7216 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 7217 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 7218 } 7219 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 7220 7221 // Only consider previous declarations in the same scope. 7222 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 7223 /*ExplicitInstantiationOrSpecialization*/false); 7224 if (!Previous.empty()) { 7225 Redeclaration = true; 7226 7227 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 7228 if (!OldDecl && !Invalid) { 7229 Diag(UsingLoc, diag::err_redefinition_different_kind) 7230 << Name.Identifier; 7231 7232 NamedDecl *OldD = Previous.getRepresentativeDecl(); 7233 if (OldD->getLocation().isValid()) 7234 Diag(OldD->getLocation(), diag::note_previous_definition); 7235 7236 Invalid = true; 7237 } 7238 7239 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 7240 if (TemplateParameterListsAreEqual(TemplateParams, 7241 OldDecl->getTemplateParameters(), 7242 /*Complain=*/true, 7243 TPL_TemplateMatch)) 7244 OldTemplateParams = OldDecl->getTemplateParameters(); 7245 else 7246 Invalid = true; 7247 7248 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 7249 if (!Invalid && 7250 !Context.hasSameType(OldTD->getUnderlyingType(), 7251 NewTD->getUnderlyingType())) { 7252 // FIXME: The C++0x standard does not clearly say this is ill-formed, 7253 // but we can't reasonably accept it. 7254 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 7255 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 7256 if (OldTD->getLocation().isValid()) 7257 Diag(OldTD->getLocation(), diag::note_previous_definition); 7258 Invalid = true; 7259 } 7260 } 7261 } 7262 7263 // Merge any previous default template arguments into our parameters, 7264 // and check the parameter list. 7265 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 7266 TPC_TypeAliasTemplate)) 7267 return 0; 7268 7269 TypeAliasTemplateDecl *NewDecl = 7270 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 7271 Name.Identifier, TemplateParams, 7272 NewTD); 7273 7274 NewDecl->setAccess(AS); 7275 7276 if (Invalid) 7277 NewDecl->setInvalidDecl(); 7278 else if (OldDecl) 7279 NewDecl->setPreviousDeclaration(OldDecl); 7280 7281 NewND = NewDecl; 7282 } else { 7283 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 7284 NewND = NewTD; 7285 } 7286 7287 if (!Redeclaration) 7288 PushOnScopeChains(NewND, S); 7289 7290 ActOnDocumentableDecl(NewND); 7291 return NewND; 7292} 7293 7294Decl *Sema::ActOnNamespaceAliasDef(Scope *S, 7295 SourceLocation NamespaceLoc, 7296 SourceLocation AliasLoc, 7297 IdentifierInfo *Alias, 7298 CXXScopeSpec &SS, 7299 SourceLocation IdentLoc, 7300 IdentifierInfo *Ident) { 7301 7302 // Lookup the namespace name. 7303 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 7304 LookupParsedName(R, S, &SS); 7305 7306 // Check if we have a previous declaration with the same name. 7307 NamedDecl *PrevDecl 7308 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName, 7309 ForRedeclaration); 7310 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S)) 7311 PrevDecl = 0; 7312 7313 if (PrevDecl) { 7314 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 7315 // We already have an alias with the same name that points to the same 7316 // namespace, so don't create a new one. 7317 // FIXME: At some point, we'll want to create the (redundant) 7318 // declaration to maintain better source information. 7319 if (!R.isAmbiguous() && !R.empty() && 7320 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl()))) 7321 return 0; 7322 } 7323 7324 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition : 7325 diag::err_redefinition_different_kind; 7326 Diag(AliasLoc, DiagID) << Alias; 7327 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 7328 return 0; 7329 } 7330 7331 if (R.isAmbiguous()) 7332 return 0; 7333 7334 if (R.empty()) { 7335 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 7336 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 7337 return 0; 7338 } 7339 } 7340 7341 NamespaceAliasDecl *AliasDecl = 7342 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 7343 Alias, SS.getWithLocInContext(Context), 7344 IdentLoc, R.getFoundDecl()); 7345 7346 PushOnScopeChains(AliasDecl, S); 7347 return AliasDecl; 7348} 7349 7350Sema::ImplicitExceptionSpecification 7351Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, 7352 CXXMethodDecl *MD) { 7353 CXXRecordDecl *ClassDecl = MD->getParent(); 7354 7355 // C++ [except.spec]p14: 7356 // An implicitly declared special member function (Clause 12) shall have an 7357 // exception-specification. [...] 7358 ImplicitExceptionSpecification ExceptSpec(*this); 7359 if (ClassDecl->isInvalidDecl()) 7360 return ExceptSpec; 7361 7362 // Direct base-class constructors. 7363 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 7364 BEnd = ClassDecl->bases_end(); 7365 B != BEnd; ++B) { 7366 if (B->isVirtual()) // Handled below. 7367 continue; 7368 7369 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 7370 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7371 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 7372 // If this is a deleted function, add it anyway. This might be conformant 7373 // with the standard. This might not. I'm not sure. It might not matter. 7374 if (Constructor) 7375 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 7376 } 7377 } 7378 7379 // Virtual base-class constructors. 7380 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 7381 BEnd = ClassDecl->vbases_end(); 7382 B != BEnd; ++B) { 7383 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 7384 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7385 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 7386 // If this is a deleted function, add it anyway. This might be conformant 7387 // with the standard. This might not. I'm not sure. It might not matter. 7388 if (Constructor) 7389 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 7390 } 7391 } 7392 7393 // Field constructors. 7394 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 7395 FEnd = ClassDecl->field_end(); 7396 F != FEnd; ++F) { 7397 if (F->hasInClassInitializer()) { 7398 if (Expr *E = F->getInClassInitializer()) 7399 ExceptSpec.CalledExpr(E); 7400 else if (!F->isInvalidDecl()) 7401 // DR1351: 7402 // If the brace-or-equal-initializer of a non-static data member 7403 // invokes a defaulted default constructor of its class or of an 7404 // enclosing class in a potentially evaluated subexpression, the 7405 // program is ill-formed. 7406 // 7407 // This resolution is unworkable: the exception specification of the 7408 // default constructor can be needed in an unevaluated context, in 7409 // particular, in the operand of a noexcept-expression, and we can be 7410 // unable to compute an exception specification for an enclosed class. 7411 // 7412 // We do not allow an in-class initializer to require the evaluation 7413 // of the exception specification for any in-class initializer whose 7414 // definition is not lexically complete. 7415 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD; 7416 } else if (const RecordType *RecordTy 7417 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 7418 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 7419 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 7420 // If this is a deleted function, add it anyway. This might be conformant 7421 // with the standard. This might not. I'm not sure. It might not matter. 7422 // In particular, the problem is that this function never gets called. It 7423 // might just be ill-formed because this function attempts to refer to 7424 // a deleted function here. 7425 if (Constructor) 7426 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 7427 } 7428 } 7429 7430 return ExceptSpec; 7431} 7432 7433namespace { 7434/// RAII object to register a special member as being currently declared. 7435struct DeclaringSpecialMember { 7436 Sema &S; 7437 Sema::SpecialMemberDecl D; 7438 bool WasAlreadyBeingDeclared; 7439 7440 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 7441 : S(S), D(RD, CSM) { 7442 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D); 7443 if (WasAlreadyBeingDeclared) 7444 // This almost never happens, but if it does, ensure that our cache 7445 // doesn't contain a stale result. 7446 S.SpecialMemberCache.clear(); 7447 7448 // FIXME: Register a note to be produced if we encounter an error while 7449 // declaring the special member. 7450 } 7451 ~DeclaringSpecialMember() { 7452 if (!WasAlreadyBeingDeclared) 7453 S.SpecialMembersBeingDeclared.erase(D); 7454 } 7455 7456 /// \brief Are we already trying to declare this special member? 7457 bool isAlreadyBeingDeclared() const { 7458 return WasAlreadyBeingDeclared; 7459 } 7460}; 7461} 7462 7463CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 7464 CXXRecordDecl *ClassDecl) { 7465 // C++ [class.ctor]p5: 7466 // A default constructor for a class X is a constructor of class X 7467 // that can be called without an argument. If there is no 7468 // user-declared constructor for class X, a default constructor is 7469 // implicitly declared. An implicitly-declared default constructor 7470 // is an inline public member of its class. 7471 assert(ClassDecl->needsImplicitDefaultConstructor() && 7472 "Should not build implicit default constructor!"); 7473 7474 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 7475 if (DSM.isAlreadyBeingDeclared()) 7476 return 0; 7477 7478 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 7479 CXXDefaultConstructor, 7480 false); 7481 7482 // Create the actual constructor declaration. 7483 CanQualType ClassType 7484 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 7485 SourceLocation ClassLoc = ClassDecl->getLocation(); 7486 DeclarationName Name 7487 = Context.DeclarationNames.getCXXConstructorName(ClassType); 7488 DeclarationNameInfo NameInfo(Name, ClassLoc); 7489 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 7490 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0, 7491 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 7492 Constexpr); 7493 DefaultCon->setAccess(AS_public); 7494 DefaultCon->setDefaulted(); 7495 DefaultCon->setImplicit(); 7496 7497 // Build an exception specification pointing back at this constructor. 7498 FunctionProtoType::ExtProtoInfo EPI; 7499 EPI.ExceptionSpecType = EST_Unevaluated; 7500 EPI.ExceptionSpecDecl = DefaultCon; 7501 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI)); 7502 7503 // We don't need to use SpecialMemberIsTrivial here; triviality for default 7504 // constructors is easy to compute. 7505 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 7506 7507 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 7508 DefaultCon->setDeletedAsWritten(); 7509 7510 // Note that we have declared this constructor. 7511 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 7512 7513 if (Scope *S = getScopeForContext(ClassDecl)) 7514 PushOnScopeChains(DefaultCon, S, false); 7515 ClassDecl->addDecl(DefaultCon); 7516 7517 return DefaultCon; 7518} 7519 7520void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 7521 CXXConstructorDecl *Constructor) { 7522 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 7523 !Constructor->doesThisDeclarationHaveABody() && 7524 !Constructor->isDeleted()) && 7525 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 7526 7527 CXXRecordDecl *ClassDecl = Constructor->getParent(); 7528 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 7529 7530 SynthesizedFunctionScope Scope(*this, Constructor); 7531 DiagnosticErrorTrap Trap(Diags); 7532 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 7533 Trap.hasErrorOccurred()) { 7534 Diag(CurrentLocation, diag::note_member_synthesized_at) 7535 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl); 7536 Constructor->setInvalidDecl(); 7537 return; 7538 } 7539 7540 SourceLocation Loc = Constructor->getLocation(); 7541 Constructor->setBody(new (Context) CompoundStmt(Loc)); 7542 7543 Constructor->setUsed(); 7544 MarkVTableUsed(CurrentLocation, ClassDecl); 7545 7546 if (ASTMutationListener *L = getASTMutationListener()) { 7547 L->CompletedImplicitDefinition(Constructor); 7548 } 7549} 7550 7551void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 7552 // Check that any explicitly-defaulted methods have exception specifications 7553 // compatible with their implicit exception specifications. 7554 CheckDelayedExplicitlyDefaultedMemberExceptionSpecs(); 7555} 7556 7557void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) { 7558 // We start with an initial pass over the base classes to collect those that 7559 // inherit constructors from. If there are none, we can forgo all further 7560 // processing. 7561 typedef SmallVector<const RecordType *, 4> BasesVector; 7562 BasesVector BasesToInheritFrom; 7563 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(), 7564 BaseE = ClassDecl->bases_end(); 7565 BaseIt != BaseE; ++BaseIt) { 7566 if (BaseIt->getInheritConstructors()) { 7567 QualType Base = BaseIt->getType(); 7568 if (Base->isDependentType()) { 7569 // If we inherit constructors from anything that is dependent, just 7570 // abort processing altogether. We'll get another chance for the 7571 // instantiations. 7572 return; 7573 } 7574 BasesToInheritFrom.push_back(Base->castAs<RecordType>()); 7575 } 7576 } 7577 if (BasesToInheritFrom.empty()) 7578 return; 7579 7580 // Now collect the constructors that we already have in the current class. 7581 // Those take precedence over inherited constructors. 7582 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...] 7583 // unless there is a user-declared constructor with the same signature in 7584 // the class where the using-declaration appears. 7585 llvm::SmallSet<const Type *, 8> ExistingConstructors; 7586 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(), 7587 CtorE = ClassDecl->ctor_end(); 7588 CtorIt != CtorE; ++CtorIt) { 7589 ExistingConstructors.insert( 7590 Context.getCanonicalType(CtorIt->getType()).getTypePtr()); 7591 } 7592 7593 DeclarationName CreatedCtorName = 7594 Context.DeclarationNames.getCXXConstructorName( 7595 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified()); 7596 7597 // Now comes the true work. 7598 // First, we keep a map from constructor types to the base that introduced 7599 // them. Needed for finding conflicting constructors. We also keep the 7600 // actually inserted declarations in there, for pretty diagnostics. 7601 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo; 7602 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap; 7603 ConstructorToSourceMap InheritedConstructors; 7604 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(), 7605 BaseE = BasesToInheritFrom.end(); 7606 BaseIt != BaseE; ++BaseIt) { 7607 const RecordType *Base = *BaseIt; 7608 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified(); 7609 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl()); 7610 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(), 7611 CtorE = BaseDecl->ctor_end(); 7612 CtorIt != CtorE; ++CtorIt) { 7613 // Find the using declaration for inheriting this base's constructors. 7614 // FIXME: Don't perform name lookup just to obtain a source location! 7615 DeclarationName Name = 7616 Context.DeclarationNames.getCXXConstructorName(CanonicalBase); 7617 LookupResult Result(*this, Name, SourceLocation(), LookupUsingDeclName); 7618 LookupQualifiedName(Result, CurContext); 7619 UsingDecl *UD = Result.getAsSingle<UsingDecl>(); 7620 SourceLocation UsingLoc = UD ? UD->getLocation() : 7621 ClassDecl->getLocation(); 7622 7623 // C++0x [class.inhctor]p1: The candidate set of inherited constructors 7624 // from the class X named in the using-declaration consists of actual 7625 // constructors and notional constructors that result from the 7626 // transformation of defaulted parameters as follows: 7627 // - all non-template default constructors of X, and 7628 // - for each non-template constructor of X that has at least one 7629 // parameter with a default argument, the set of constructors that 7630 // results from omitting any ellipsis parameter specification and 7631 // successively omitting parameters with a default argument from the 7632 // end of the parameter-type-list. 7633 CXXConstructorDecl *BaseCtor = *CtorIt; 7634 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor(); 7635 const FunctionProtoType *BaseCtorType = 7636 BaseCtor->getType()->getAs<FunctionProtoType>(); 7637 7638 for (unsigned params = BaseCtor->getMinRequiredArguments(), 7639 maxParams = BaseCtor->getNumParams(); 7640 params <= maxParams; ++params) { 7641 // Skip default constructors. They're never inherited. 7642 if (params == 0) 7643 continue; 7644 // Skip copy and move constructors for the same reason. 7645 if (CanBeCopyOrMove && params == 1) 7646 continue; 7647 7648 // Build up a function type for this particular constructor. 7649 // FIXME: The working paper does not consider that the exception spec 7650 // for the inheriting constructor might be larger than that of the 7651 // source. This code doesn't yet, either. When it does, this code will 7652 // need to be delayed until after exception specifications and in-class 7653 // member initializers are attached. 7654 const Type *NewCtorType; 7655 if (params == maxParams) 7656 NewCtorType = BaseCtorType; 7657 else { 7658 SmallVector<QualType, 16> Args; 7659 for (unsigned i = 0; i < params; ++i) { 7660 Args.push_back(BaseCtorType->getArgType(i)); 7661 } 7662 FunctionProtoType::ExtProtoInfo ExtInfo = 7663 BaseCtorType->getExtProtoInfo(); 7664 ExtInfo.Variadic = false; 7665 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(), 7666 Args.data(), params, ExtInfo) 7667 .getTypePtr(); 7668 } 7669 const Type *CanonicalNewCtorType = 7670 Context.getCanonicalType(NewCtorType); 7671 7672 // Now that we have the type, first check if the class already has a 7673 // constructor with this signature. 7674 if (ExistingConstructors.count(CanonicalNewCtorType)) 7675 continue; 7676 7677 // Then we check if we have already declared an inherited constructor 7678 // with this signature. 7679 std::pair<ConstructorToSourceMap::iterator, bool> result = 7680 InheritedConstructors.insert(std::make_pair( 7681 CanonicalNewCtorType, 7682 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0))); 7683 if (!result.second) { 7684 // Already in the map. If it came from a different class, that's an 7685 // error. Not if it's from the same. 7686 CanQualType PreviousBase = result.first->second.first; 7687 if (CanonicalBase != PreviousBase) { 7688 const CXXConstructorDecl *PrevCtor = result.first->second.second; 7689 const CXXConstructorDecl *PrevBaseCtor = 7690 PrevCtor->getInheritedConstructor(); 7691 assert(PrevBaseCtor && "Conflicting constructor was not inherited"); 7692 7693 Diag(UsingLoc, diag::err_using_decl_constructor_conflict); 7694 Diag(BaseCtor->getLocation(), 7695 diag::note_using_decl_constructor_conflict_current_ctor); 7696 Diag(PrevBaseCtor->getLocation(), 7697 diag::note_using_decl_constructor_conflict_previous_ctor); 7698 Diag(PrevCtor->getLocation(), 7699 diag::note_using_decl_constructor_conflict_previous_using); 7700 } 7701 continue; 7702 } 7703 7704 // OK, we're there, now add the constructor. 7705 // C++0x [class.inhctor]p8: [...] that would be performed by a 7706 // user-written inline constructor [...] 7707 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc); 7708 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create( 7709 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0), 7710 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true, 7711 /*ImplicitlyDeclared=*/true, 7712 // FIXME: Due to a defect in the standard, we treat inherited 7713 // constructors as constexpr even if that makes them ill-formed. 7714 /*Constexpr=*/BaseCtor->isConstexpr()); 7715 NewCtor->setAccess(BaseCtor->getAccess()); 7716 7717 // Build up the parameter decls and add them. 7718 SmallVector<ParmVarDecl *, 16> ParamDecls; 7719 for (unsigned i = 0; i < params; ++i) { 7720 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor, 7721 UsingLoc, UsingLoc, 7722 /*IdentifierInfo=*/0, 7723 BaseCtorType->getArgType(i), 7724 /*TInfo=*/0, SC_None, 7725 SC_None, /*DefaultArg=*/0)); 7726 } 7727 NewCtor->setParams(ParamDecls); 7728 NewCtor->setInheritedConstructor(BaseCtor); 7729 7730 ClassDecl->addDecl(NewCtor); 7731 result.first->second.second = NewCtor; 7732 } 7733 } 7734 } 7735} 7736 7737Sema::ImplicitExceptionSpecification 7738Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) { 7739 CXXRecordDecl *ClassDecl = MD->getParent(); 7740 7741 // C++ [except.spec]p14: 7742 // An implicitly declared special member function (Clause 12) shall have 7743 // an exception-specification. 7744 ImplicitExceptionSpecification ExceptSpec(*this); 7745 if (ClassDecl->isInvalidDecl()) 7746 return ExceptSpec; 7747 7748 // Direct base-class destructors. 7749 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 7750 BEnd = ClassDecl->bases_end(); 7751 B != BEnd; ++B) { 7752 if (B->isVirtual()) // Handled below. 7753 continue; 7754 7755 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) 7756 ExceptSpec.CalledDecl(B->getLocStart(), 7757 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 7758 } 7759 7760 // Virtual base-class destructors. 7761 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 7762 BEnd = ClassDecl->vbases_end(); 7763 B != BEnd; ++B) { 7764 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) 7765 ExceptSpec.CalledDecl(B->getLocStart(), 7766 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 7767 } 7768 7769 // Field destructors. 7770 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 7771 FEnd = ClassDecl->field_end(); 7772 F != FEnd; ++F) { 7773 if (const RecordType *RecordTy 7774 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) 7775 ExceptSpec.CalledDecl(F->getLocation(), 7776 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl()))); 7777 } 7778 7779 return ExceptSpec; 7780} 7781 7782CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 7783 // C++ [class.dtor]p2: 7784 // If a class has no user-declared destructor, a destructor is 7785 // declared implicitly. An implicitly-declared destructor is an 7786 // inline public member of its class. 7787 assert(ClassDecl->needsImplicitDestructor()); 7788 7789 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 7790 if (DSM.isAlreadyBeingDeclared()) 7791 return 0; 7792 7793 // Create the actual destructor declaration. 7794 CanQualType ClassType 7795 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 7796 SourceLocation ClassLoc = ClassDecl->getLocation(); 7797 DeclarationName Name 7798 = Context.DeclarationNames.getCXXDestructorName(ClassType); 7799 DeclarationNameInfo NameInfo(Name, ClassLoc); 7800 CXXDestructorDecl *Destructor 7801 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 7802 QualType(), 0, /*isInline=*/true, 7803 /*isImplicitlyDeclared=*/true); 7804 Destructor->setAccess(AS_public); 7805 Destructor->setDefaulted(); 7806 Destructor->setImplicit(); 7807 7808 // Build an exception specification pointing back at this destructor. 7809 FunctionProtoType::ExtProtoInfo EPI; 7810 EPI.ExceptionSpecType = EST_Unevaluated; 7811 EPI.ExceptionSpecDecl = Destructor; 7812 Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI)); 7813 7814 AddOverriddenMethods(ClassDecl, Destructor); 7815 7816 // We don't need to use SpecialMemberIsTrivial here; triviality for 7817 // destructors is easy to compute. 7818 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 7819 7820 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 7821 Destructor->setDeletedAsWritten(); 7822 7823 // Note that we have declared this destructor. 7824 ++ASTContext::NumImplicitDestructorsDeclared; 7825 7826 // Introduce this destructor into its scope. 7827 if (Scope *S = getScopeForContext(ClassDecl)) 7828 PushOnScopeChains(Destructor, S, false); 7829 ClassDecl->addDecl(Destructor); 7830 7831 return Destructor; 7832} 7833 7834void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 7835 CXXDestructorDecl *Destructor) { 7836 assert((Destructor->isDefaulted() && 7837 !Destructor->doesThisDeclarationHaveABody() && 7838 !Destructor->isDeleted()) && 7839 "DefineImplicitDestructor - call it for implicit default dtor"); 7840 CXXRecordDecl *ClassDecl = Destructor->getParent(); 7841 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 7842 7843 if (Destructor->isInvalidDecl()) 7844 return; 7845 7846 SynthesizedFunctionScope Scope(*this, Destructor); 7847 7848 DiagnosticErrorTrap Trap(Diags); 7849 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 7850 Destructor->getParent()); 7851 7852 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) { 7853 Diag(CurrentLocation, diag::note_member_synthesized_at) 7854 << CXXDestructor << Context.getTagDeclType(ClassDecl); 7855 7856 Destructor->setInvalidDecl(); 7857 return; 7858 } 7859 7860 SourceLocation Loc = Destructor->getLocation(); 7861 Destructor->setBody(new (Context) CompoundStmt(Loc)); 7862 Destructor->setImplicitlyDefined(true); 7863 Destructor->setUsed(); 7864 MarkVTableUsed(CurrentLocation, ClassDecl); 7865 7866 if (ASTMutationListener *L = getASTMutationListener()) { 7867 L->CompletedImplicitDefinition(Destructor); 7868 } 7869} 7870 7871/// \brief Perform any semantic analysis which needs to be delayed until all 7872/// pending class member declarations have been parsed. 7873void Sema::ActOnFinishCXXMemberDecls() { 7874 // Perform any deferred checking of exception specifications for virtual 7875 // destructors. 7876 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size(); 7877 i != e; ++i) { 7878 const CXXDestructorDecl *Dtor = 7879 DelayedDestructorExceptionSpecChecks[i].first; 7880 assert(!Dtor->getParent()->isDependentType() && 7881 "Should not ever add destructors of templates into the list."); 7882 CheckOverridingFunctionExceptionSpec(Dtor, 7883 DelayedDestructorExceptionSpecChecks[i].second); 7884 } 7885 DelayedDestructorExceptionSpecChecks.clear(); 7886} 7887 7888void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 7889 CXXDestructorDecl *Destructor) { 7890 assert(getLangOpts().CPlusPlus11 && 7891 "adjusting dtor exception specs was introduced in c++11"); 7892 7893 // C++11 [class.dtor]p3: 7894 // A declaration of a destructor that does not have an exception- 7895 // specification is implicitly considered to have the same exception- 7896 // specification as an implicit declaration. 7897 const FunctionProtoType *DtorType = Destructor->getType()-> 7898 getAs<FunctionProtoType>(); 7899 if (DtorType->hasExceptionSpec()) 7900 return; 7901 7902 // Replace the destructor's type, building off the existing one. Fortunately, 7903 // the only thing of interest in the destructor type is its extended info. 7904 // The return and arguments are fixed. 7905 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 7906 EPI.ExceptionSpecType = EST_Unevaluated; 7907 EPI.ExceptionSpecDecl = Destructor; 7908 Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI)); 7909 7910 // FIXME: If the destructor has a body that could throw, and the newly created 7911 // spec doesn't allow exceptions, we should emit a warning, because this 7912 // change in behavior can break conforming C++03 programs at runtime. 7913 // However, we don't have a body or an exception specification yet, so it 7914 // needs to be done somewhere else. 7915} 7916 7917/// When generating a defaulted copy or move assignment operator, if a field 7918/// should be copied with __builtin_memcpy rather than via explicit assignments, 7919/// do so. This optimization only applies for arrays of scalars, and for arrays 7920/// of class type where the selected copy/move-assignment operator is trivial. 7921static StmtResult 7922buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 7923 Expr *To, Expr *From) { 7924 // Compute the size of the memory buffer to be copied. 7925 QualType SizeType = S.Context.getSizeType(); 7926 llvm::APInt Size(S.Context.getTypeSize(SizeType), 7927 S.Context.getTypeSizeInChars(T).getQuantity()); 7928 7929 // Take the address of the field references for "from" and "to". We 7930 // directly construct UnaryOperators here because semantic analysis 7931 // does not permit us to take the address of an xvalue. 7932 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 7933 S.Context.getPointerType(From->getType()), 7934 VK_RValue, OK_Ordinary, Loc); 7935 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 7936 S.Context.getPointerType(To->getType()), 7937 VK_RValue, OK_Ordinary, Loc); 7938 7939 const Type *E = T->getBaseElementTypeUnsafe(); 7940 bool NeedsCollectableMemCpy = 7941 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 7942 7943 // Create a reference to the __builtin_objc_memmove_collectable function 7944 StringRef MemCpyName = NeedsCollectableMemCpy ? 7945 "__builtin_objc_memmove_collectable" : 7946 "__builtin_memcpy"; 7947 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 7948 Sema::LookupOrdinaryName); 7949 S.LookupName(R, S.TUScope, true); 7950 7951 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 7952 if (!MemCpy) 7953 // Something went horribly wrong earlier, and we will have complained 7954 // about it. 7955 return StmtError(); 7956 7957 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 7958 VK_RValue, Loc, 0); 7959 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 7960 7961 Expr *CallArgs[] = { 7962 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 7963 }; 7964 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(), 7965 Loc, CallArgs, Loc); 7966 7967 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 7968 return S.Owned(Call.takeAs<Stmt>()); 7969} 7970 7971/// \brief Builds a statement that copies/moves the given entity from \p From to 7972/// \c To. 7973/// 7974/// This routine is used to copy/move the members of a class with an 7975/// implicitly-declared copy/move assignment operator. When the entities being 7976/// copied are arrays, this routine builds for loops to copy them. 7977/// 7978/// \param S The Sema object used for type-checking. 7979/// 7980/// \param Loc The location where the implicit copy/move is being generated. 7981/// 7982/// \param T The type of the expressions being copied/moved. Both expressions 7983/// must have this type. 7984/// 7985/// \param To The expression we are copying/moving to. 7986/// 7987/// \param From The expression we are copying/moving from. 7988/// 7989/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 7990/// Otherwise, it's a non-static member subobject. 7991/// 7992/// \param Copying Whether we're copying or moving. 7993/// 7994/// \param Depth Internal parameter recording the depth of the recursion. 7995/// 7996/// \returns A statement or a loop that copies the expressions, or StmtResult(0) 7997/// if a memcpy should be used instead. 7998static StmtResult 7999buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 8000 Expr *To, Expr *From, 8001 bool CopyingBaseSubobject, bool Copying, 8002 unsigned Depth = 0) { 8003 // C++11 [class.copy]p28: 8004 // Each subobject is assigned in the manner appropriate to its type: 8005 // 8006 // - if the subobject is of class type, as if by a call to operator= with 8007 // the subobject as the object expression and the corresponding 8008 // subobject of x as a single function argument (as if by explicit 8009 // qualification; that is, ignoring any possible virtual overriding 8010 // functions in more derived classes); 8011 // 8012 // C++03 [class.copy]p13: 8013 // - if the subobject is of class type, the copy assignment operator for 8014 // the class is used (as if by explicit qualification; that is, 8015 // ignoring any possible virtual overriding functions in more derived 8016 // classes); 8017 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 8018 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8019 8020 // Look for operator=. 8021 DeclarationName Name 8022 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 8023 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 8024 S.LookupQualifiedName(OpLookup, ClassDecl, false); 8025 8026 // Prior to C++11, filter out any result that isn't a copy/move-assignment 8027 // operator. 8028 if (!S.getLangOpts().CPlusPlus11) { 8029 LookupResult::Filter F = OpLookup.makeFilter(); 8030 while (F.hasNext()) { 8031 NamedDecl *D = F.next(); 8032 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 8033 if (Method->isCopyAssignmentOperator() || 8034 (!Copying && Method->isMoveAssignmentOperator())) 8035 continue; 8036 8037 F.erase(); 8038 } 8039 F.done(); 8040 } 8041 8042 // Suppress the protected check (C++ [class.protected]) for each of the 8043 // assignment operators we found. This strange dance is required when 8044 // we're assigning via a base classes's copy-assignment operator. To 8045 // ensure that we're getting the right base class subobject (without 8046 // ambiguities), we need to cast "this" to that subobject type; to 8047 // ensure that we don't go through the virtual call mechanism, we need 8048 // to qualify the operator= name with the base class (see below). However, 8049 // this means that if the base class has a protected copy assignment 8050 // operator, the protected member access check will fail. So, we 8051 // rewrite "protected" access to "public" access in this case, since we 8052 // know by construction that we're calling from a derived class. 8053 if (CopyingBaseSubobject) { 8054 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 8055 L != LEnd; ++L) { 8056 if (L.getAccess() == AS_protected) 8057 L.setAccess(AS_public); 8058 } 8059 } 8060 8061 // Create the nested-name-specifier that will be used to qualify the 8062 // reference to operator=; this is required to suppress the virtual 8063 // call mechanism. 8064 CXXScopeSpec SS; 8065 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 8066 SS.MakeTrivial(S.Context, 8067 NestedNameSpecifier::Create(S.Context, 0, false, 8068 CanonicalT), 8069 Loc); 8070 8071 // Create the reference to operator=. 8072 ExprResult OpEqualRef 8073 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS, 8074 /*TemplateKWLoc=*/SourceLocation(), 8075 /*FirstQualifierInScope=*/0, 8076 OpLookup, 8077 /*TemplateArgs=*/0, 8078 /*SuppressQualifierCheck=*/true); 8079 if (OpEqualRef.isInvalid()) 8080 return StmtError(); 8081 8082 // Build the call to the assignment operator. 8083 8084 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0, 8085 OpEqualRef.takeAs<Expr>(), 8086 Loc, &From, 1, Loc); 8087 if (Call.isInvalid()) 8088 return StmtError(); 8089 8090 // If we built a call to a trivial 'operator=' while copying an array, 8091 // bail out. We'll replace the whole shebang with a memcpy. 8092 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 8093 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 8094 return StmtResult((Stmt*)0); 8095 8096 // Convert to an expression-statement, and clean up any produced 8097 // temporaries. 8098 return S.ActOnExprStmt(Call); 8099 } 8100 8101 // - if the subobject is of scalar type, the built-in assignment 8102 // operator is used. 8103 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 8104 if (!ArrayTy) { 8105 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From); 8106 if (Assignment.isInvalid()) 8107 return StmtError(); 8108 return S.ActOnExprStmt(Assignment); 8109 } 8110 8111 // - if the subobject is an array, each element is assigned, in the 8112 // manner appropriate to the element type; 8113 8114 // Construct a loop over the array bounds, e.g., 8115 // 8116 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 8117 // 8118 // that will copy each of the array elements. 8119 QualType SizeType = S.Context.getSizeType(); 8120 8121 // Create the iteration variable. 8122 IdentifierInfo *IterationVarName = 0; 8123 { 8124 SmallString<8> Str; 8125 llvm::raw_svector_ostream OS(Str); 8126 OS << "__i" << Depth; 8127 IterationVarName = &S.Context.Idents.get(OS.str()); 8128 } 8129 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 8130 IterationVarName, SizeType, 8131 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 8132 SC_None, SC_None); 8133 8134 // Initialize the iteration variable to zero. 8135 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 8136 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 8137 8138 // Create a reference to the iteration variable; we'll use this several 8139 // times throughout. 8140 Expr *IterationVarRef 8141 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take(); 8142 assert(IterationVarRef && "Reference to invented variable cannot fail!"); 8143 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take(); 8144 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!"); 8145 8146 // Create the DeclStmt that holds the iteration variable. 8147 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 8148 8149 // Subscript the "from" and "to" expressions with the iteration variable. 8150 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc, 8151 IterationVarRefRVal, 8152 Loc)); 8153 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc, 8154 IterationVarRefRVal, 8155 Loc)); 8156 if (!Copying) // Cast to rvalue 8157 From = CastForMoving(S, From); 8158 8159 // Build the copy/move for an individual element of the array. 8160 StmtResult Copy = 8161 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 8162 To, From, CopyingBaseSubobject, 8163 Copying, Depth + 1); 8164 // Bail out if copying fails or if we determined that we should use memcpy. 8165 if (Copy.isInvalid() || !Copy.get()) 8166 return Copy; 8167 8168 // Create the comparison against the array bound. 8169 llvm::APInt Upper 8170 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 8171 Expr *Comparison 8172 = new (S.Context) BinaryOperator(IterationVarRefRVal, 8173 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 8174 BO_NE, S.Context.BoolTy, 8175 VK_RValue, OK_Ordinary, Loc, false); 8176 8177 // Create the pre-increment of the iteration variable. 8178 Expr *Increment 8179 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType, 8180 VK_LValue, OK_Ordinary, Loc); 8181 8182 // Construct the loop that copies all elements of this array. 8183 return S.ActOnForStmt(Loc, Loc, InitStmt, 8184 S.MakeFullExpr(Comparison), 8185 0, S.MakeFullDiscardedValueExpr(Increment), 8186 Loc, Copy.take()); 8187} 8188 8189static StmtResult 8190buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 8191 Expr *To, Expr *From, 8192 bool CopyingBaseSubobject, bool Copying) { 8193 // Maybe we should use a memcpy? 8194 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 8195 T.isTriviallyCopyableType(S.Context)) 8196 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 8197 8198 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 8199 CopyingBaseSubobject, 8200 Copying, 0)); 8201 8202 // If we ended up picking a trivial assignment operator for an array of a 8203 // non-trivially-copyable class type, just emit a memcpy. 8204 if (!Result.isInvalid() && !Result.get()) 8205 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 8206 8207 return Result; 8208} 8209 8210Sema::ImplicitExceptionSpecification 8211Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) { 8212 CXXRecordDecl *ClassDecl = MD->getParent(); 8213 8214 ImplicitExceptionSpecification ExceptSpec(*this); 8215 if (ClassDecl->isInvalidDecl()) 8216 return ExceptSpec; 8217 8218 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 8219 assert(T->getNumArgs() == 1 && "not a copy assignment op"); 8220 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers(); 8221 8222 // C++ [except.spec]p14: 8223 // An implicitly declared special member function (Clause 12) shall have an 8224 // exception-specification. [...] 8225 8226 // It is unspecified whether or not an implicit copy assignment operator 8227 // attempts to deduplicate calls to assignment operators of virtual bases are 8228 // made. As such, this exception specification is effectively unspecified. 8229 // Based on a similar decision made for constness in C++0x, we're erring on 8230 // the side of assuming such calls to be made regardless of whether they 8231 // actually happen. 8232 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 8233 BaseEnd = ClassDecl->bases_end(); 8234 Base != BaseEnd; ++Base) { 8235 if (Base->isVirtual()) 8236 continue; 8237 8238 CXXRecordDecl *BaseClassDecl 8239 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8240 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 8241 ArgQuals, false, 0)) 8242 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign); 8243 } 8244 8245 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 8246 BaseEnd = ClassDecl->vbases_end(); 8247 Base != BaseEnd; ++Base) { 8248 CXXRecordDecl *BaseClassDecl 8249 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8250 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 8251 ArgQuals, false, 0)) 8252 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign); 8253 } 8254 8255 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8256 FieldEnd = ClassDecl->field_end(); 8257 Field != FieldEnd; 8258 ++Field) { 8259 QualType FieldType = Context.getBaseElementType(Field->getType()); 8260 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 8261 if (CXXMethodDecl *CopyAssign = 8262 LookupCopyingAssignment(FieldClassDecl, 8263 ArgQuals | FieldType.getCVRQualifiers(), 8264 false, 0)) 8265 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign); 8266 } 8267 } 8268 8269 return ExceptSpec; 8270} 8271 8272CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 8273 // Note: The following rules are largely analoguous to the copy 8274 // constructor rules. Note that virtual bases are not taken into account 8275 // for determining the argument type of the operator. Note also that 8276 // operators taking an object instead of a reference are allowed. 8277 assert(ClassDecl->needsImplicitCopyAssignment()); 8278 8279 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 8280 if (DSM.isAlreadyBeingDeclared()) 8281 return 0; 8282 8283 QualType ArgType = Context.getTypeDeclType(ClassDecl); 8284 QualType RetType = Context.getLValueReferenceType(ArgType); 8285 if (ClassDecl->implicitCopyAssignmentHasConstParam()) 8286 ArgType = ArgType.withConst(); 8287 ArgType = Context.getLValueReferenceType(ArgType); 8288 8289 // An implicitly-declared copy assignment operator is an inline public 8290 // member of its class. 8291 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 8292 SourceLocation ClassLoc = ClassDecl->getLocation(); 8293 DeclarationNameInfo NameInfo(Name, ClassLoc); 8294 CXXMethodDecl *CopyAssignment 8295 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 8296 /*TInfo=*/0, /*isStatic=*/false, 8297 /*StorageClassAsWritten=*/SC_None, 8298 /*isInline=*/true, /*isConstexpr=*/false, 8299 SourceLocation()); 8300 CopyAssignment->setAccess(AS_public); 8301 CopyAssignment->setDefaulted(); 8302 CopyAssignment->setImplicit(); 8303 8304 // Build an exception specification pointing back at this member. 8305 FunctionProtoType::ExtProtoInfo EPI; 8306 EPI.ExceptionSpecType = EST_Unevaluated; 8307 EPI.ExceptionSpecDecl = CopyAssignment; 8308 CopyAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI)); 8309 8310 // Add the parameter to the operator. 8311 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 8312 ClassLoc, ClassLoc, /*Id=*/0, 8313 ArgType, /*TInfo=*/0, 8314 SC_None, 8315 SC_None, 0); 8316 CopyAssignment->setParams(FromParam); 8317 8318 AddOverriddenMethods(ClassDecl, CopyAssignment); 8319 8320 CopyAssignment->setTrivial( 8321 ClassDecl->needsOverloadResolutionForCopyAssignment() 8322 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 8323 : ClassDecl->hasTrivialCopyAssignment()); 8324 8325 // C++0x [class.copy]p19: 8326 // .... If the class definition does not explicitly declare a copy 8327 // assignment operator, there is no user-declared move constructor, and 8328 // there is no user-declared move assignment operator, a copy assignment 8329 // operator is implicitly declared as defaulted. 8330 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 8331 CopyAssignment->setDeletedAsWritten(); 8332 8333 // Note that we have added this copy-assignment operator. 8334 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 8335 8336 if (Scope *S = getScopeForContext(ClassDecl)) 8337 PushOnScopeChains(CopyAssignment, S, false); 8338 ClassDecl->addDecl(CopyAssignment); 8339 8340 return CopyAssignment; 8341} 8342 8343void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 8344 CXXMethodDecl *CopyAssignOperator) { 8345 assert((CopyAssignOperator->isDefaulted() && 8346 CopyAssignOperator->isOverloadedOperator() && 8347 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 8348 !CopyAssignOperator->doesThisDeclarationHaveABody() && 8349 !CopyAssignOperator->isDeleted()) && 8350 "DefineImplicitCopyAssignment called for wrong function"); 8351 8352 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 8353 8354 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) { 8355 CopyAssignOperator->setInvalidDecl(); 8356 return; 8357 } 8358 8359 CopyAssignOperator->setUsed(); 8360 8361 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 8362 DiagnosticErrorTrap Trap(Diags); 8363 8364 // C++0x [class.copy]p30: 8365 // The implicitly-defined or explicitly-defaulted copy assignment operator 8366 // for a non-union class X performs memberwise copy assignment of its 8367 // subobjects. The direct base classes of X are assigned first, in the 8368 // order of their declaration in the base-specifier-list, and then the 8369 // immediate non-static data members of X are assigned, in the order in 8370 // which they were declared in the class definition. 8371 8372 // The statements that form the synthesized function body. 8373 SmallVector<Stmt*, 8> Statements; 8374 8375 // The parameter for the "other" object, which we are copying from. 8376 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 8377 Qualifiers OtherQuals = Other->getType().getQualifiers(); 8378 QualType OtherRefType = Other->getType(); 8379 if (const LValueReferenceType *OtherRef 8380 = OtherRefType->getAs<LValueReferenceType>()) { 8381 OtherRefType = OtherRef->getPointeeType(); 8382 OtherQuals = OtherRefType.getQualifiers(); 8383 } 8384 8385 // Our location for everything implicitly-generated. 8386 SourceLocation Loc = CopyAssignOperator->getLocation(); 8387 8388 // Construct a reference to the "other" object. We'll be using this 8389 // throughout the generated ASTs. 8390 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take(); 8391 assert(OtherRef && "Reference to parameter cannot fail!"); 8392 8393 // Construct the "this" pointer. We'll be using this throughout the generated 8394 // ASTs. 8395 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>(); 8396 assert(This && "Reference to this cannot fail!"); 8397 8398 // Assign base classes. 8399 bool Invalid = false; 8400 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 8401 E = ClassDecl->bases_end(); Base != E; ++Base) { 8402 // Form the assignment: 8403 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 8404 QualType BaseType = Base->getType().getUnqualifiedType(); 8405 if (!BaseType->isRecordType()) { 8406 Invalid = true; 8407 continue; 8408 } 8409 8410 CXXCastPath BasePath; 8411 BasePath.push_back(Base); 8412 8413 // Construct the "from" expression, which is an implicit cast to the 8414 // appropriately-qualified base type. 8415 Expr *From = OtherRef; 8416 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals), 8417 CK_UncheckedDerivedToBase, 8418 VK_LValue, &BasePath).take(); 8419 8420 // Dereference "this". 8421 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 8422 8423 // Implicitly cast "this" to the appropriately-qualified base type. 8424 To = ImpCastExprToType(To.take(), 8425 Context.getCVRQualifiedType(BaseType, 8426 CopyAssignOperator->getTypeQualifiers()), 8427 CK_UncheckedDerivedToBase, 8428 VK_LValue, &BasePath); 8429 8430 // Build the copy. 8431 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 8432 To.get(), From, 8433 /*CopyingBaseSubobject=*/true, 8434 /*Copying=*/true); 8435 if (Copy.isInvalid()) { 8436 Diag(CurrentLocation, diag::note_member_synthesized_at) 8437 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 8438 CopyAssignOperator->setInvalidDecl(); 8439 return; 8440 } 8441 8442 // Success! Record the copy. 8443 Statements.push_back(Copy.takeAs<Expr>()); 8444 } 8445 8446 // Assign non-static members. 8447 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8448 FieldEnd = ClassDecl->field_end(); 8449 Field != FieldEnd; ++Field) { 8450 if (Field->isUnnamedBitfield()) 8451 continue; 8452 8453 // Check for members of reference type; we can't copy those. 8454 if (Field->getType()->isReferenceType()) { 8455 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 8456 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 8457 Diag(Field->getLocation(), diag::note_declared_at); 8458 Diag(CurrentLocation, diag::note_member_synthesized_at) 8459 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 8460 Invalid = true; 8461 continue; 8462 } 8463 8464 // Check for members of const-qualified, non-class type. 8465 QualType BaseType = Context.getBaseElementType(Field->getType()); 8466 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 8467 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 8468 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 8469 Diag(Field->getLocation(), diag::note_declared_at); 8470 Diag(CurrentLocation, diag::note_member_synthesized_at) 8471 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 8472 Invalid = true; 8473 continue; 8474 } 8475 8476 // Suppress assigning zero-width bitfields. 8477 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 8478 continue; 8479 8480 QualType FieldType = Field->getType().getNonReferenceType(); 8481 if (FieldType->isIncompleteArrayType()) { 8482 assert(ClassDecl->hasFlexibleArrayMember() && 8483 "Incomplete array type is not valid"); 8484 continue; 8485 } 8486 8487 // Build references to the field in the object we're copying from and to. 8488 CXXScopeSpec SS; // Intentionally empty 8489 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 8490 LookupMemberName); 8491 MemberLookup.addDecl(*Field); 8492 MemberLookup.resolveKind(); 8493 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType, 8494 Loc, /*IsArrow=*/false, 8495 SS, SourceLocation(), 0, 8496 MemberLookup, 0); 8497 ExprResult To = BuildMemberReferenceExpr(This, This->getType(), 8498 Loc, /*IsArrow=*/true, 8499 SS, SourceLocation(), 0, 8500 MemberLookup, 0); 8501 assert(!From.isInvalid() && "Implicit field reference cannot fail"); 8502 assert(!To.isInvalid() && "Implicit field reference cannot fail"); 8503 8504 // Build the copy of this field. 8505 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 8506 To.get(), From.get(), 8507 /*CopyingBaseSubobject=*/false, 8508 /*Copying=*/true); 8509 if (Copy.isInvalid()) { 8510 Diag(CurrentLocation, diag::note_member_synthesized_at) 8511 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 8512 CopyAssignOperator->setInvalidDecl(); 8513 return; 8514 } 8515 8516 // Success! Record the copy. 8517 Statements.push_back(Copy.takeAs<Stmt>()); 8518 } 8519 8520 if (!Invalid) { 8521 // Add a "return *this;" 8522 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 8523 8524 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get()); 8525 if (Return.isInvalid()) 8526 Invalid = true; 8527 else { 8528 Statements.push_back(Return.takeAs<Stmt>()); 8529 8530 if (Trap.hasErrorOccurred()) { 8531 Diag(CurrentLocation, diag::note_member_synthesized_at) 8532 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 8533 Invalid = true; 8534 } 8535 } 8536 } 8537 8538 if (Invalid) { 8539 CopyAssignOperator->setInvalidDecl(); 8540 return; 8541 } 8542 8543 StmtResult Body; 8544 { 8545 CompoundScopeRAII CompoundScope(*this); 8546 Body = ActOnCompoundStmt(Loc, Loc, Statements, 8547 /*isStmtExpr=*/false); 8548 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 8549 } 8550 CopyAssignOperator->setBody(Body.takeAs<Stmt>()); 8551 8552 if (ASTMutationListener *L = getASTMutationListener()) { 8553 L->CompletedImplicitDefinition(CopyAssignOperator); 8554 } 8555} 8556 8557Sema::ImplicitExceptionSpecification 8558Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) { 8559 CXXRecordDecl *ClassDecl = MD->getParent(); 8560 8561 ImplicitExceptionSpecification ExceptSpec(*this); 8562 if (ClassDecl->isInvalidDecl()) 8563 return ExceptSpec; 8564 8565 // C++0x [except.spec]p14: 8566 // An implicitly declared special member function (Clause 12) shall have an 8567 // exception-specification. [...] 8568 8569 // It is unspecified whether or not an implicit move assignment operator 8570 // attempts to deduplicate calls to assignment operators of virtual bases are 8571 // made. As such, this exception specification is effectively unspecified. 8572 // Based on a similar decision made for constness in C++0x, we're erring on 8573 // the side of assuming such calls to be made regardless of whether they 8574 // actually happen. 8575 // Note that a move constructor is not implicitly declared when there are 8576 // virtual bases, but it can still be user-declared and explicitly defaulted. 8577 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 8578 BaseEnd = ClassDecl->bases_end(); 8579 Base != BaseEnd; ++Base) { 8580 if (Base->isVirtual()) 8581 continue; 8582 8583 CXXRecordDecl *BaseClassDecl 8584 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8585 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 8586 0, false, 0)) 8587 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign); 8588 } 8589 8590 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 8591 BaseEnd = ClassDecl->vbases_end(); 8592 Base != BaseEnd; ++Base) { 8593 CXXRecordDecl *BaseClassDecl 8594 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8595 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 8596 0, false, 0)) 8597 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign); 8598 } 8599 8600 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8601 FieldEnd = ClassDecl->field_end(); 8602 Field != FieldEnd; 8603 ++Field) { 8604 QualType FieldType = Context.getBaseElementType(Field->getType()); 8605 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 8606 if (CXXMethodDecl *MoveAssign = 8607 LookupMovingAssignment(FieldClassDecl, 8608 FieldType.getCVRQualifiers(), 8609 false, 0)) 8610 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign); 8611 } 8612 } 8613 8614 return ExceptSpec; 8615} 8616 8617/// Determine whether the class type has any direct or indirect virtual base 8618/// classes which have a non-trivial move assignment operator. 8619static bool 8620hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) { 8621 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 8622 BaseEnd = ClassDecl->vbases_end(); 8623 Base != BaseEnd; ++Base) { 8624 CXXRecordDecl *BaseClass = 8625 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8626 8627 // Try to declare the move assignment. If it would be deleted, then the 8628 // class does not have a non-trivial move assignment. 8629 if (BaseClass->needsImplicitMoveAssignment()) 8630 S.DeclareImplicitMoveAssignment(BaseClass); 8631 8632 if (BaseClass->hasNonTrivialMoveAssignment()) 8633 return true; 8634 } 8635 8636 return false; 8637} 8638 8639/// Determine whether the given type either has a move constructor or is 8640/// trivially copyable. 8641static bool 8642hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) { 8643 Type = S.Context.getBaseElementType(Type); 8644 8645 // FIXME: Technically, non-trivially-copyable non-class types, such as 8646 // reference types, are supposed to return false here, but that appears 8647 // to be a standard defect. 8648 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl(); 8649 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl()) 8650 return true; 8651 8652 if (Type.isTriviallyCopyableType(S.Context)) 8653 return true; 8654 8655 if (IsConstructor) { 8656 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to 8657 // give the right answer. 8658 if (ClassDecl->needsImplicitMoveConstructor()) 8659 S.DeclareImplicitMoveConstructor(ClassDecl); 8660 return ClassDecl->hasMoveConstructor(); 8661 } 8662 8663 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to 8664 // give the right answer. 8665 if (ClassDecl->needsImplicitMoveAssignment()) 8666 S.DeclareImplicitMoveAssignment(ClassDecl); 8667 return ClassDecl->hasMoveAssignment(); 8668} 8669 8670/// Determine whether all non-static data members and direct or virtual bases 8671/// of class \p ClassDecl have either a move operation, or are trivially 8672/// copyable. 8673static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl, 8674 bool IsConstructor) { 8675 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 8676 BaseEnd = ClassDecl->bases_end(); 8677 Base != BaseEnd; ++Base) { 8678 if (Base->isVirtual()) 8679 continue; 8680 8681 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor)) 8682 return false; 8683 } 8684 8685 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 8686 BaseEnd = ClassDecl->vbases_end(); 8687 Base != BaseEnd; ++Base) { 8688 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor)) 8689 return false; 8690 } 8691 8692 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8693 FieldEnd = ClassDecl->field_end(); 8694 Field != FieldEnd; ++Field) { 8695 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor)) 8696 return false; 8697 } 8698 8699 return true; 8700} 8701 8702CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 8703 // C++11 [class.copy]p20: 8704 // If the definition of a class X does not explicitly declare a move 8705 // assignment operator, one will be implicitly declared as defaulted 8706 // if and only if: 8707 // 8708 // - [first 4 bullets] 8709 assert(ClassDecl->needsImplicitMoveAssignment()); 8710 8711 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 8712 if (DSM.isAlreadyBeingDeclared()) 8713 return 0; 8714 8715 // [Checked after we build the declaration] 8716 // - the move assignment operator would not be implicitly defined as 8717 // deleted, 8718 8719 // [DR1402]: 8720 // - X has no direct or indirect virtual base class with a non-trivial 8721 // move assignment operator, and 8722 // - each of X's non-static data members and direct or virtual base classes 8723 // has a type that either has a move assignment operator or is trivially 8724 // copyable. 8725 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) || 8726 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) { 8727 ClassDecl->setFailedImplicitMoveAssignment(); 8728 return 0; 8729 } 8730 8731 // Note: The following rules are largely analoguous to the move 8732 // constructor rules. 8733 8734 QualType ArgType = Context.getTypeDeclType(ClassDecl); 8735 QualType RetType = Context.getLValueReferenceType(ArgType); 8736 ArgType = Context.getRValueReferenceType(ArgType); 8737 8738 // An implicitly-declared move assignment operator is an inline public 8739 // member of its class. 8740 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 8741 SourceLocation ClassLoc = ClassDecl->getLocation(); 8742 DeclarationNameInfo NameInfo(Name, ClassLoc); 8743 CXXMethodDecl *MoveAssignment 8744 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 8745 /*TInfo=*/0, /*isStatic=*/false, 8746 /*StorageClassAsWritten=*/SC_None, 8747 /*isInline=*/true, 8748 /*isConstexpr=*/false, 8749 SourceLocation()); 8750 MoveAssignment->setAccess(AS_public); 8751 MoveAssignment->setDefaulted(); 8752 MoveAssignment->setImplicit(); 8753 8754 // Build an exception specification pointing back at this member. 8755 FunctionProtoType::ExtProtoInfo EPI; 8756 EPI.ExceptionSpecType = EST_Unevaluated; 8757 EPI.ExceptionSpecDecl = MoveAssignment; 8758 MoveAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI)); 8759 8760 // Add the parameter to the operator. 8761 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 8762 ClassLoc, ClassLoc, /*Id=*/0, 8763 ArgType, /*TInfo=*/0, 8764 SC_None, 8765 SC_None, 0); 8766 MoveAssignment->setParams(FromParam); 8767 8768 AddOverriddenMethods(ClassDecl, MoveAssignment); 8769 8770 MoveAssignment->setTrivial( 8771 ClassDecl->needsOverloadResolutionForMoveAssignment() 8772 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 8773 : ClassDecl->hasTrivialMoveAssignment()); 8774 8775 // C++0x [class.copy]p9: 8776 // If the definition of a class X does not explicitly declare a move 8777 // assignment operator, one will be implicitly declared as defaulted if and 8778 // only if: 8779 // [...] 8780 // - the move assignment operator would not be implicitly defined as 8781 // deleted. 8782 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 8783 // Cache this result so that we don't try to generate this over and over 8784 // on every lookup, leaking memory and wasting time. 8785 ClassDecl->setFailedImplicitMoveAssignment(); 8786 return 0; 8787 } 8788 8789 // Note that we have added this copy-assignment operator. 8790 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 8791 8792 if (Scope *S = getScopeForContext(ClassDecl)) 8793 PushOnScopeChains(MoveAssignment, S, false); 8794 ClassDecl->addDecl(MoveAssignment); 8795 8796 return MoveAssignment; 8797} 8798 8799void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 8800 CXXMethodDecl *MoveAssignOperator) { 8801 assert((MoveAssignOperator->isDefaulted() && 8802 MoveAssignOperator->isOverloadedOperator() && 8803 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 8804 !MoveAssignOperator->doesThisDeclarationHaveABody() && 8805 !MoveAssignOperator->isDeleted()) && 8806 "DefineImplicitMoveAssignment called for wrong function"); 8807 8808 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 8809 8810 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) { 8811 MoveAssignOperator->setInvalidDecl(); 8812 return; 8813 } 8814 8815 MoveAssignOperator->setUsed(); 8816 8817 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 8818 DiagnosticErrorTrap Trap(Diags); 8819 8820 // C++0x [class.copy]p28: 8821 // The implicitly-defined or move assignment operator for a non-union class 8822 // X performs memberwise move assignment of its subobjects. The direct base 8823 // classes of X are assigned first, in the order of their declaration in the 8824 // base-specifier-list, and then the immediate non-static data members of X 8825 // are assigned, in the order in which they were declared in the class 8826 // definition. 8827 8828 // The statements that form the synthesized function body. 8829 SmallVector<Stmt*, 8> Statements; 8830 8831 // The parameter for the "other" object, which we are move from. 8832 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 8833 QualType OtherRefType = Other->getType()-> 8834 getAs<RValueReferenceType>()->getPointeeType(); 8835 assert(OtherRefType.getQualifiers() == 0 && 8836 "Bad argument type of defaulted move assignment"); 8837 8838 // Our location for everything implicitly-generated. 8839 SourceLocation Loc = MoveAssignOperator->getLocation(); 8840 8841 // Construct a reference to the "other" object. We'll be using this 8842 // throughout the generated ASTs. 8843 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take(); 8844 assert(OtherRef && "Reference to parameter cannot fail!"); 8845 // Cast to rvalue. 8846 OtherRef = CastForMoving(*this, OtherRef); 8847 8848 // Construct the "this" pointer. We'll be using this throughout the generated 8849 // ASTs. 8850 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>(); 8851 assert(This && "Reference to this cannot fail!"); 8852 8853 // Assign base classes. 8854 bool Invalid = false; 8855 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 8856 E = ClassDecl->bases_end(); Base != E; ++Base) { 8857 // Form the assignment: 8858 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 8859 QualType BaseType = Base->getType().getUnqualifiedType(); 8860 if (!BaseType->isRecordType()) { 8861 Invalid = true; 8862 continue; 8863 } 8864 8865 CXXCastPath BasePath; 8866 BasePath.push_back(Base); 8867 8868 // Construct the "from" expression, which is an implicit cast to the 8869 // appropriately-qualified base type. 8870 Expr *From = OtherRef; 8871 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase, 8872 VK_XValue, &BasePath).take(); 8873 8874 // Dereference "this". 8875 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 8876 8877 // Implicitly cast "this" to the appropriately-qualified base type. 8878 To = ImpCastExprToType(To.take(), 8879 Context.getCVRQualifiedType(BaseType, 8880 MoveAssignOperator->getTypeQualifiers()), 8881 CK_UncheckedDerivedToBase, 8882 VK_LValue, &BasePath); 8883 8884 // Build the move. 8885 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 8886 To.get(), From, 8887 /*CopyingBaseSubobject=*/true, 8888 /*Copying=*/false); 8889 if (Move.isInvalid()) { 8890 Diag(CurrentLocation, diag::note_member_synthesized_at) 8891 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 8892 MoveAssignOperator->setInvalidDecl(); 8893 return; 8894 } 8895 8896 // Success! Record the move. 8897 Statements.push_back(Move.takeAs<Expr>()); 8898 } 8899 8900 // Assign non-static members. 8901 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8902 FieldEnd = ClassDecl->field_end(); 8903 Field != FieldEnd; ++Field) { 8904 if (Field->isUnnamedBitfield()) 8905 continue; 8906 8907 // Check for members of reference type; we can't move those. 8908 if (Field->getType()->isReferenceType()) { 8909 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 8910 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 8911 Diag(Field->getLocation(), diag::note_declared_at); 8912 Diag(CurrentLocation, diag::note_member_synthesized_at) 8913 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 8914 Invalid = true; 8915 continue; 8916 } 8917 8918 // Check for members of const-qualified, non-class type. 8919 QualType BaseType = Context.getBaseElementType(Field->getType()); 8920 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 8921 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 8922 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 8923 Diag(Field->getLocation(), diag::note_declared_at); 8924 Diag(CurrentLocation, diag::note_member_synthesized_at) 8925 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 8926 Invalid = true; 8927 continue; 8928 } 8929 8930 // Suppress assigning zero-width bitfields. 8931 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 8932 continue; 8933 8934 QualType FieldType = Field->getType().getNonReferenceType(); 8935 if (FieldType->isIncompleteArrayType()) { 8936 assert(ClassDecl->hasFlexibleArrayMember() && 8937 "Incomplete array type is not valid"); 8938 continue; 8939 } 8940 8941 // Build references to the field in the object we're copying from and to. 8942 CXXScopeSpec SS; // Intentionally empty 8943 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 8944 LookupMemberName); 8945 MemberLookup.addDecl(*Field); 8946 MemberLookup.resolveKind(); 8947 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType, 8948 Loc, /*IsArrow=*/false, 8949 SS, SourceLocation(), 0, 8950 MemberLookup, 0); 8951 ExprResult To = BuildMemberReferenceExpr(This, This->getType(), 8952 Loc, /*IsArrow=*/true, 8953 SS, SourceLocation(), 0, 8954 MemberLookup, 0); 8955 assert(!From.isInvalid() && "Implicit field reference cannot fail"); 8956 assert(!To.isInvalid() && "Implicit field reference cannot fail"); 8957 8958 assert(!From.get()->isLValue() && // could be xvalue or prvalue 8959 "Member reference with rvalue base must be rvalue except for reference " 8960 "members, which aren't allowed for move assignment."); 8961 8962 // Build the move of this field. 8963 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 8964 To.get(), From.get(), 8965 /*CopyingBaseSubobject=*/false, 8966 /*Copying=*/false); 8967 if (Move.isInvalid()) { 8968 Diag(CurrentLocation, diag::note_member_synthesized_at) 8969 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 8970 MoveAssignOperator->setInvalidDecl(); 8971 return; 8972 } 8973 8974 // Success! Record the copy. 8975 Statements.push_back(Move.takeAs<Stmt>()); 8976 } 8977 8978 if (!Invalid) { 8979 // Add a "return *this;" 8980 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 8981 8982 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get()); 8983 if (Return.isInvalid()) 8984 Invalid = true; 8985 else { 8986 Statements.push_back(Return.takeAs<Stmt>()); 8987 8988 if (Trap.hasErrorOccurred()) { 8989 Diag(CurrentLocation, diag::note_member_synthesized_at) 8990 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 8991 Invalid = true; 8992 } 8993 } 8994 } 8995 8996 if (Invalid) { 8997 MoveAssignOperator->setInvalidDecl(); 8998 return; 8999 } 9000 9001 StmtResult Body; 9002 { 9003 CompoundScopeRAII CompoundScope(*this); 9004 Body = ActOnCompoundStmt(Loc, Loc, Statements, 9005 /*isStmtExpr=*/false); 9006 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 9007 } 9008 MoveAssignOperator->setBody(Body.takeAs<Stmt>()); 9009 9010 if (ASTMutationListener *L = getASTMutationListener()) { 9011 L->CompletedImplicitDefinition(MoveAssignOperator); 9012 } 9013} 9014 9015Sema::ImplicitExceptionSpecification 9016Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) { 9017 CXXRecordDecl *ClassDecl = MD->getParent(); 9018 9019 ImplicitExceptionSpecification ExceptSpec(*this); 9020 if (ClassDecl->isInvalidDecl()) 9021 return ExceptSpec; 9022 9023 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 9024 assert(T->getNumArgs() >= 1 && "not a copy ctor"); 9025 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers(); 9026 9027 // C++ [except.spec]p14: 9028 // An implicitly declared special member function (Clause 12) shall have an 9029 // exception-specification. [...] 9030 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 9031 BaseEnd = ClassDecl->bases_end(); 9032 Base != BaseEnd; 9033 ++Base) { 9034 // Virtual bases are handled below. 9035 if (Base->isVirtual()) 9036 continue; 9037 9038 CXXRecordDecl *BaseClassDecl 9039 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9040 if (CXXConstructorDecl *CopyConstructor = 9041 LookupCopyingConstructor(BaseClassDecl, Quals)) 9042 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor); 9043 } 9044 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 9045 BaseEnd = ClassDecl->vbases_end(); 9046 Base != BaseEnd; 9047 ++Base) { 9048 CXXRecordDecl *BaseClassDecl 9049 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9050 if (CXXConstructorDecl *CopyConstructor = 9051 LookupCopyingConstructor(BaseClassDecl, Quals)) 9052 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor); 9053 } 9054 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 9055 FieldEnd = ClassDecl->field_end(); 9056 Field != FieldEnd; 9057 ++Field) { 9058 QualType FieldType = Context.getBaseElementType(Field->getType()); 9059 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 9060 if (CXXConstructorDecl *CopyConstructor = 9061 LookupCopyingConstructor(FieldClassDecl, 9062 Quals | FieldType.getCVRQualifiers())) 9063 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor); 9064 } 9065 } 9066 9067 return ExceptSpec; 9068} 9069 9070CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 9071 CXXRecordDecl *ClassDecl) { 9072 // C++ [class.copy]p4: 9073 // If the class definition does not explicitly declare a copy 9074 // constructor, one is declared implicitly. 9075 assert(ClassDecl->needsImplicitCopyConstructor()); 9076 9077 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 9078 if (DSM.isAlreadyBeingDeclared()) 9079 return 0; 9080 9081 QualType ClassType = Context.getTypeDeclType(ClassDecl); 9082 QualType ArgType = ClassType; 9083 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 9084 if (Const) 9085 ArgType = ArgType.withConst(); 9086 ArgType = Context.getLValueReferenceType(ArgType); 9087 9088 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9089 CXXCopyConstructor, 9090 Const); 9091 9092 DeclarationName Name 9093 = Context.DeclarationNames.getCXXConstructorName( 9094 Context.getCanonicalType(ClassType)); 9095 SourceLocation ClassLoc = ClassDecl->getLocation(); 9096 DeclarationNameInfo NameInfo(Name, ClassLoc); 9097 9098 // An implicitly-declared copy constructor is an inline public 9099 // member of its class. 9100 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 9101 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0, 9102 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 9103 Constexpr); 9104 CopyConstructor->setAccess(AS_public); 9105 CopyConstructor->setDefaulted(); 9106 9107 // Build an exception specification pointing back at this member. 9108 FunctionProtoType::ExtProtoInfo EPI; 9109 EPI.ExceptionSpecType = EST_Unevaluated; 9110 EPI.ExceptionSpecDecl = CopyConstructor; 9111 CopyConstructor->setType( 9112 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI)); 9113 9114 // Add the parameter to the constructor. 9115 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 9116 ClassLoc, ClassLoc, 9117 /*IdentifierInfo=*/0, 9118 ArgType, /*TInfo=*/0, 9119 SC_None, 9120 SC_None, 0); 9121 CopyConstructor->setParams(FromParam); 9122 9123 CopyConstructor->setTrivial( 9124 ClassDecl->needsOverloadResolutionForCopyConstructor() 9125 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 9126 : ClassDecl->hasTrivialCopyConstructor()); 9127 9128 // C++11 [class.copy]p8: 9129 // ... If the class definition does not explicitly declare a copy 9130 // constructor, there is no user-declared move constructor, and there is no 9131 // user-declared move assignment operator, a copy constructor is implicitly 9132 // declared as defaulted. 9133 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) 9134 CopyConstructor->setDeletedAsWritten(); 9135 9136 // Note that we have declared this constructor. 9137 ++ASTContext::NumImplicitCopyConstructorsDeclared; 9138 9139 if (Scope *S = getScopeForContext(ClassDecl)) 9140 PushOnScopeChains(CopyConstructor, S, false); 9141 ClassDecl->addDecl(CopyConstructor); 9142 9143 return CopyConstructor; 9144} 9145 9146void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 9147 CXXConstructorDecl *CopyConstructor) { 9148 assert((CopyConstructor->isDefaulted() && 9149 CopyConstructor->isCopyConstructor() && 9150 !CopyConstructor->doesThisDeclarationHaveABody() && 9151 !CopyConstructor->isDeleted()) && 9152 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 9153 9154 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 9155 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 9156 9157 SynthesizedFunctionScope Scope(*this, CopyConstructor); 9158 DiagnosticErrorTrap Trap(Diags); 9159 9160 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) || 9161 Trap.hasErrorOccurred()) { 9162 Diag(CurrentLocation, diag::note_member_synthesized_at) 9163 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl); 9164 CopyConstructor->setInvalidDecl(); 9165 } else { 9166 Sema::CompoundScopeRAII CompoundScope(*this); 9167 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(), 9168 CopyConstructor->getLocation(), 9169 MultiStmtArg(), 9170 /*isStmtExpr=*/false) 9171 .takeAs<Stmt>()); 9172 CopyConstructor->setImplicitlyDefined(true); 9173 } 9174 9175 CopyConstructor->setUsed(); 9176 if (ASTMutationListener *L = getASTMutationListener()) { 9177 L->CompletedImplicitDefinition(CopyConstructor); 9178 } 9179} 9180 9181Sema::ImplicitExceptionSpecification 9182Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) { 9183 CXXRecordDecl *ClassDecl = MD->getParent(); 9184 9185 // C++ [except.spec]p14: 9186 // An implicitly declared special member function (Clause 12) shall have an 9187 // exception-specification. [...] 9188 ImplicitExceptionSpecification ExceptSpec(*this); 9189 if (ClassDecl->isInvalidDecl()) 9190 return ExceptSpec; 9191 9192 // Direct base-class constructors. 9193 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 9194 BEnd = ClassDecl->bases_end(); 9195 B != BEnd; ++B) { 9196 if (B->isVirtual()) // Handled below. 9197 continue; 9198 9199 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 9200 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 9201 CXXConstructorDecl *Constructor = 9202 LookupMovingConstructor(BaseClassDecl, 0); 9203 // If this is a deleted function, add it anyway. This might be conformant 9204 // with the standard. This might not. I'm not sure. It might not matter. 9205 if (Constructor) 9206 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 9207 } 9208 } 9209 9210 // Virtual base-class constructors. 9211 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 9212 BEnd = ClassDecl->vbases_end(); 9213 B != BEnd; ++B) { 9214 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 9215 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 9216 CXXConstructorDecl *Constructor = 9217 LookupMovingConstructor(BaseClassDecl, 0); 9218 // If this is a deleted function, add it anyway. This might be conformant 9219 // with the standard. This might not. I'm not sure. It might not matter. 9220 if (Constructor) 9221 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 9222 } 9223 } 9224 9225 // Field constructors. 9226 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 9227 FEnd = ClassDecl->field_end(); 9228 F != FEnd; ++F) { 9229 QualType FieldType = Context.getBaseElementType(F->getType()); 9230 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) { 9231 CXXConstructorDecl *Constructor = 9232 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers()); 9233 // If this is a deleted function, add it anyway. This might be conformant 9234 // with the standard. This might not. I'm not sure. It might not matter. 9235 // In particular, the problem is that this function never gets called. It 9236 // might just be ill-formed because this function attempts to refer to 9237 // a deleted function here. 9238 if (Constructor) 9239 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 9240 } 9241 } 9242 9243 return ExceptSpec; 9244} 9245 9246CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 9247 CXXRecordDecl *ClassDecl) { 9248 // C++11 [class.copy]p9: 9249 // If the definition of a class X does not explicitly declare a move 9250 // constructor, one will be implicitly declared as defaulted if and only if: 9251 // 9252 // - [first 4 bullets] 9253 assert(ClassDecl->needsImplicitMoveConstructor()); 9254 9255 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 9256 if (DSM.isAlreadyBeingDeclared()) 9257 return 0; 9258 9259 // [Checked after we build the declaration] 9260 // - the move assignment operator would not be implicitly defined as 9261 // deleted, 9262 9263 // [DR1402]: 9264 // - each of X's non-static data members and direct or virtual base classes 9265 // has a type that either has a move constructor or is trivially copyable. 9266 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) { 9267 ClassDecl->setFailedImplicitMoveConstructor(); 9268 return 0; 9269 } 9270 9271 QualType ClassType = Context.getTypeDeclType(ClassDecl); 9272 QualType ArgType = Context.getRValueReferenceType(ClassType); 9273 9274 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9275 CXXMoveConstructor, 9276 false); 9277 9278 DeclarationName Name 9279 = Context.DeclarationNames.getCXXConstructorName( 9280 Context.getCanonicalType(ClassType)); 9281 SourceLocation ClassLoc = ClassDecl->getLocation(); 9282 DeclarationNameInfo NameInfo(Name, ClassLoc); 9283 9284 // C++0x [class.copy]p11: 9285 // An implicitly-declared copy/move constructor is an inline public 9286 // member of its class. 9287 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 9288 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0, 9289 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 9290 Constexpr); 9291 MoveConstructor->setAccess(AS_public); 9292 MoveConstructor->setDefaulted(); 9293 9294 // Build an exception specification pointing back at this member. 9295 FunctionProtoType::ExtProtoInfo EPI; 9296 EPI.ExceptionSpecType = EST_Unevaluated; 9297 EPI.ExceptionSpecDecl = MoveConstructor; 9298 MoveConstructor->setType( 9299 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI)); 9300 9301 // Add the parameter to the constructor. 9302 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 9303 ClassLoc, ClassLoc, 9304 /*IdentifierInfo=*/0, 9305 ArgType, /*TInfo=*/0, 9306 SC_None, 9307 SC_None, 0); 9308 MoveConstructor->setParams(FromParam); 9309 9310 MoveConstructor->setTrivial( 9311 ClassDecl->needsOverloadResolutionForMoveConstructor() 9312 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 9313 : ClassDecl->hasTrivialMoveConstructor()); 9314 9315 // C++0x [class.copy]p9: 9316 // If the definition of a class X does not explicitly declare a move 9317 // constructor, one will be implicitly declared as defaulted if and only if: 9318 // [...] 9319 // - the move constructor would not be implicitly defined as deleted. 9320 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 9321 // Cache this result so that we don't try to generate this over and over 9322 // on every lookup, leaking memory and wasting time. 9323 ClassDecl->setFailedImplicitMoveConstructor(); 9324 return 0; 9325 } 9326 9327 // Note that we have declared this constructor. 9328 ++ASTContext::NumImplicitMoveConstructorsDeclared; 9329 9330 if (Scope *S = getScopeForContext(ClassDecl)) 9331 PushOnScopeChains(MoveConstructor, S, false); 9332 ClassDecl->addDecl(MoveConstructor); 9333 9334 return MoveConstructor; 9335} 9336 9337void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 9338 CXXConstructorDecl *MoveConstructor) { 9339 assert((MoveConstructor->isDefaulted() && 9340 MoveConstructor->isMoveConstructor() && 9341 !MoveConstructor->doesThisDeclarationHaveABody() && 9342 !MoveConstructor->isDeleted()) && 9343 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 9344 9345 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 9346 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 9347 9348 SynthesizedFunctionScope Scope(*this, MoveConstructor); 9349 DiagnosticErrorTrap Trap(Diags); 9350 9351 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) || 9352 Trap.hasErrorOccurred()) { 9353 Diag(CurrentLocation, diag::note_member_synthesized_at) 9354 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl); 9355 MoveConstructor->setInvalidDecl(); 9356 } else { 9357 Sema::CompoundScopeRAII CompoundScope(*this); 9358 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(), 9359 MoveConstructor->getLocation(), 9360 MultiStmtArg(), 9361 /*isStmtExpr=*/false) 9362 .takeAs<Stmt>()); 9363 MoveConstructor->setImplicitlyDefined(true); 9364 } 9365 9366 MoveConstructor->setUsed(); 9367 9368 if (ASTMutationListener *L = getASTMutationListener()) { 9369 L->CompletedImplicitDefinition(MoveConstructor); 9370 } 9371} 9372 9373bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 9374 return FD->isDeleted() && 9375 (FD->isDefaulted() || FD->isImplicit()) && 9376 isa<CXXMethodDecl>(FD); 9377} 9378 9379/// \brief Mark the call operator of the given lambda closure type as "used". 9380static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) { 9381 CXXMethodDecl *CallOperator 9382 = cast<CXXMethodDecl>( 9383 Lambda->lookup( 9384 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front()); 9385 CallOperator->setReferenced(); 9386 CallOperator->setUsed(); 9387} 9388 9389void Sema::DefineImplicitLambdaToFunctionPointerConversion( 9390 SourceLocation CurrentLocation, 9391 CXXConversionDecl *Conv) 9392{ 9393 CXXRecordDecl *Lambda = Conv->getParent(); 9394 9395 // Make sure that the lambda call operator is marked used. 9396 markLambdaCallOperatorUsed(*this, Lambda); 9397 9398 Conv->setUsed(); 9399 9400 SynthesizedFunctionScope Scope(*this, Conv); 9401 DiagnosticErrorTrap Trap(Diags); 9402 9403 // Return the address of the __invoke function. 9404 DeclarationName InvokeName = &Context.Idents.get("__invoke"); 9405 CXXMethodDecl *Invoke 9406 = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front()); 9407 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(), 9408 VK_LValue, Conv->getLocation()).take(); 9409 assert(FunctionRef && "Can't refer to __invoke function?"); 9410 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take(); 9411 Conv->setBody(new (Context) CompoundStmt(Context, Return, 9412 Conv->getLocation(), 9413 Conv->getLocation())); 9414 9415 // Fill in the __invoke function with a dummy implementation. IR generation 9416 // will fill in the actual details. 9417 Invoke->setUsed(); 9418 Invoke->setReferenced(); 9419 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation())); 9420 9421 if (ASTMutationListener *L = getASTMutationListener()) { 9422 L->CompletedImplicitDefinition(Conv); 9423 L->CompletedImplicitDefinition(Invoke); 9424 } 9425} 9426 9427void Sema::DefineImplicitLambdaToBlockPointerConversion( 9428 SourceLocation CurrentLocation, 9429 CXXConversionDecl *Conv) 9430{ 9431 Conv->setUsed(); 9432 9433 SynthesizedFunctionScope Scope(*this, Conv); 9434 DiagnosticErrorTrap Trap(Diags); 9435 9436 // Copy-initialize the lambda object as needed to capture it. 9437 Expr *This = ActOnCXXThis(CurrentLocation).take(); 9438 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take(); 9439 9440 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 9441 Conv->getLocation(), 9442 Conv, DerefThis); 9443 9444 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 9445 // behavior. Note that only the general conversion function does this 9446 // (since it's unusable otherwise); in the case where we inline the 9447 // block literal, it has block literal lifetime semantics. 9448 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 9449 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 9450 CK_CopyAndAutoreleaseBlockObject, 9451 BuildBlock.get(), 0, VK_RValue); 9452 9453 if (BuildBlock.isInvalid()) { 9454 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 9455 Conv->setInvalidDecl(); 9456 return; 9457 } 9458 9459 // Create the return statement that returns the block from the conversion 9460 // function. 9461 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get()); 9462 if (Return.isInvalid()) { 9463 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 9464 Conv->setInvalidDecl(); 9465 return; 9466 } 9467 9468 // Set the body of the conversion function. 9469 Stmt *ReturnS = Return.take(); 9470 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS, 9471 Conv->getLocation(), 9472 Conv->getLocation())); 9473 9474 // We're done; notify the mutation listener, if any. 9475 if (ASTMutationListener *L = getASTMutationListener()) { 9476 L->CompletedImplicitDefinition(Conv); 9477 } 9478} 9479 9480/// \brief Determine whether the given list arguments contains exactly one 9481/// "real" (non-default) argument. 9482static bool hasOneRealArgument(MultiExprArg Args) { 9483 switch (Args.size()) { 9484 case 0: 9485 return false; 9486 9487 default: 9488 if (!Args[1]->isDefaultArgument()) 9489 return false; 9490 9491 // fall through 9492 case 1: 9493 return !Args[0]->isDefaultArgument(); 9494 } 9495 9496 return false; 9497} 9498 9499ExprResult 9500Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 9501 CXXConstructorDecl *Constructor, 9502 MultiExprArg ExprArgs, 9503 bool HadMultipleCandidates, 9504 bool IsListInitialization, 9505 bool RequiresZeroInit, 9506 unsigned ConstructKind, 9507 SourceRange ParenRange) { 9508 bool Elidable = false; 9509 9510 // C++0x [class.copy]p34: 9511 // When certain criteria are met, an implementation is allowed to 9512 // omit the copy/move construction of a class object, even if the 9513 // copy/move constructor and/or destructor for the object have 9514 // side effects. [...] 9515 // - when a temporary class object that has not been bound to a 9516 // reference (12.2) would be copied/moved to a class object 9517 // with the same cv-unqualified type, the copy/move operation 9518 // can be omitted by constructing the temporary object 9519 // directly into the target of the omitted copy/move 9520 if (ConstructKind == CXXConstructExpr::CK_Complete && 9521 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 9522 Expr *SubExpr = ExprArgs[0]; 9523 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent()); 9524 } 9525 9526 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 9527 Elidable, ExprArgs, HadMultipleCandidates, 9528 IsListInitialization, RequiresZeroInit, 9529 ConstructKind, ParenRange); 9530} 9531 9532/// BuildCXXConstructExpr - Creates a complete call to a constructor, 9533/// including handling of its default argument expressions. 9534ExprResult 9535Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 9536 CXXConstructorDecl *Constructor, bool Elidable, 9537 MultiExprArg ExprArgs, 9538 bool HadMultipleCandidates, 9539 bool IsListInitialization, 9540 bool RequiresZeroInit, 9541 unsigned ConstructKind, 9542 SourceRange ParenRange) { 9543 MarkFunctionReferenced(ConstructLoc, Constructor); 9544 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc, 9545 Constructor, Elidable, ExprArgs, 9546 HadMultipleCandidates, 9547 IsListInitialization, RequiresZeroInit, 9548 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 9549 ParenRange)); 9550} 9551 9552void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 9553 if (VD->isInvalidDecl()) return; 9554 9555 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 9556 if (ClassDecl->isInvalidDecl()) return; 9557 if (ClassDecl->hasIrrelevantDestructor()) return; 9558 if (ClassDecl->isDependentContext()) return; 9559 9560 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 9561 MarkFunctionReferenced(VD->getLocation(), Destructor); 9562 CheckDestructorAccess(VD->getLocation(), Destructor, 9563 PDiag(diag::err_access_dtor_var) 9564 << VD->getDeclName() 9565 << VD->getType()); 9566 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 9567 9568 if (!VD->hasGlobalStorage()) return; 9569 9570 // Emit warning for non-trivial dtor in global scope (a real global, 9571 // class-static, function-static). 9572 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 9573 9574 // TODO: this should be re-enabled for static locals by !CXAAtExit 9575 if (!VD->isStaticLocal()) 9576 Diag(VD->getLocation(), diag::warn_global_destructor); 9577} 9578 9579/// \brief Given a constructor and the set of arguments provided for the 9580/// constructor, convert the arguments and add any required default arguments 9581/// to form a proper call to this constructor. 9582/// 9583/// \returns true if an error occurred, false otherwise. 9584bool 9585Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 9586 MultiExprArg ArgsPtr, 9587 SourceLocation Loc, 9588 SmallVectorImpl<Expr*> &ConvertedArgs, 9589 bool AllowExplicit) { 9590 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 9591 unsigned NumArgs = ArgsPtr.size(); 9592 Expr **Args = ArgsPtr.data(); 9593 9594 const FunctionProtoType *Proto 9595 = Constructor->getType()->getAs<FunctionProtoType>(); 9596 assert(Proto && "Constructor without a prototype?"); 9597 unsigned NumArgsInProto = Proto->getNumArgs(); 9598 9599 // If too few arguments are available, we'll fill in the rest with defaults. 9600 if (NumArgs < NumArgsInProto) 9601 ConvertedArgs.reserve(NumArgsInProto); 9602 else 9603 ConvertedArgs.reserve(NumArgs); 9604 9605 VariadicCallType CallType = 9606 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 9607 SmallVector<Expr *, 8> AllArgs; 9608 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 9609 Proto, 0, Args, NumArgs, AllArgs, 9610 CallType, AllowExplicit); 9611 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 9612 9613 DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size()); 9614 9615 CheckConstructorCall(Constructor, 9616 llvm::makeArrayRef<const Expr *>(AllArgs.data(), 9617 AllArgs.size()), 9618 Proto, Loc); 9619 9620 return Invalid; 9621} 9622 9623static inline bool 9624CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 9625 const FunctionDecl *FnDecl) { 9626 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 9627 if (isa<NamespaceDecl>(DC)) { 9628 return SemaRef.Diag(FnDecl->getLocation(), 9629 diag::err_operator_new_delete_declared_in_namespace) 9630 << FnDecl->getDeclName(); 9631 } 9632 9633 if (isa<TranslationUnitDecl>(DC) && 9634 FnDecl->getStorageClass() == SC_Static) { 9635 return SemaRef.Diag(FnDecl->getLocation(), 9636 diag::err_operator_new_delete_declared_static) 9637 << FnDecl->getDeclName(); 9638 } 9639 9640 return false; 9641} 9642 9643static inline bool 9644CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 9645 CanQualType ExpectedResultType, 9646 CanQualType ExpectedFirstParamType, 9647 unsigned DependentParamTypeDiag, 9648 unsigned InvalidParamTypeDiag) { 9649 QualType ResultType = 9650 FnDecl->getType()->getAs<FunctionType>()->getResultType(); 9651 9652 // Check that the result type is not dependent. 9653 if (ResultType->isDependentType()) 9654 return SemaRef.Diag(FnDecl->getLocation(), 9655 diag::err_operator_new_delete_dependent_result_type) 9656 << FnDecl->getDeclName() << ExpectedResultType; 9657 9658 // Check that the result type is what we expect. 9659 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 9660 return SemaRef.Diag(FnDecl->getLocation(), 9661 diag::err_operator_new_delete_invalid_result_type) 9662 << FnDecl->getDeclName() << ExpectedResultType; 9663 9664 // A function template must have at least 2 parameters. 9665 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 9666 return SemaRef.Diag(FnDecl->getLocation(), 9667 diag::err_operator_new_delete_template_too_few_parameters) 9668 << FnDecl->getDeclName(); 9669 9670 // The function decl must have at least 1 parameter. 9671 if (FnDecl->getNumParams() == 0) 9672 return SemaRef.Diag(FnDecl->getLocation(), 9673 diag::err_operator_new_delete_too_few_parameters) 9674 << FnDecl->getDeclName(); 9675 9676 // Check the first parameter type is not dependent. 9677 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 9678 if (FirstParamType->isDependentType()) 9679 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 9680 << FnDecl->getDeclName() << ExpectedFirstParamType; 9681 9682 // Check that the first parameter type is what we expect. 9683 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 9684 ExpectedFirstParamType) 9685 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 9686 << FnDecl->getDeclName() << ExpectedFirstParamType; 9687 9688 return false; 9689} 9690 9691static bool 9692CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 9693 // C++ [basic.stc.dynamic.allocation]p1: 9694 // A program is ill-formed if an allocation function is declared in a 9695 // namespace scope other than global scope or declared static in global 9696 // scope. 9697 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 9698 return true; 9699 9700 CanQualType SizeTy = 9701 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 9702 9703 // C++ [basic.stc.dynamic.allocation]p1: 9704 // The return type shall be void*. The first parameter shall have type 9705 // std::size_t. 9706 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 9707 SizeTy, 9708 diag::err_operator_new_dependent_param_type, 9709 diag::err_operator_new_param_type)) 9710 return true; 9711 9712 // C++ [basic.stc.dynamic.allocation]p1: 9713 // The first parameter shall not have an associated default argument. 9714 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 9715 return SemaRef.Diag(FnDecl->getLocation(), 9716 diag::err_operator_new_default_arg) 9717 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 9718 9719 return false; 9720} 9721 9722static bool 9723CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 9724 // C++ [basic.stc.dynamic.deallocation]p1: 9725 // A program is ill-formed if deallocation functions are declared in a 9726 // namespace scope other than global scope or declared static in global 9727 // scope. 9728 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 9729 return true; 9730 9731 // C++ [basic.stc.dynamic.deallocation]p2: 9732 // Each deallocation function shall return void and its first parameter 9733 // shall be void*. 9734 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 9735 SemaRef.Context.VoidPtrTy, 9736 diag::err_operator_delete_dependent_param_type, 9737 diag::err_operator_delete_param_type)) 9738 return true; 9739 9740 return false; 9741} 9742 9743/// CheckOverloadedOperatorDeclaration - Check whether the declaration 9744/// of this overloaded operator is well-formed. If so, returns false; 9745/// otherwise, emits appropriate diagnostics and returns true. 9746bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 9747 assert(FnDecl && FnDecl->isOverloadedOperator() && 9748 "Expected an overloaded operator declaration"); 9749 9750 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 9751 9752 // C++ [over.oper]p5: 9753 // The allocation and deallocation functions, operator new, 9754 // operator new[], operator delete and operator delete[], are 9755 // described completely in 3.7.3. The attributes and restrictions 9756 // found in the rest of this subclause do not apply to them unless 9757 // explicitly stated in 3.7.3. 9758 if (Op == OO_Delete || Op == OO_Array_Delete) 9759 return CheckOperatorDeleteDeclaration(*this, FnDecl); 9760 9761 if (Op == OO_New || Op == OO_Array_New) 9762 return CheckOperatorNewDeclaration(*this, FnDecl); 9763 9764 // C++ [over.oper]p6: 9765 // An operator function shall either be a non-static member 9766 // function or be a non-member function and have at least one 9767 // parameter whose type is a class, a reference to a class, an 9768 // enumeration, or a reference to an enumeration. 9769 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 9770 if (MethodDecl->isStatic()) 9771 return Diag(FnDecl->getLocation(), 9772 diag::err_operator_overload_static) << FnDecl->getDeclName(); 9773 } else { 9774 bool ClassOrEnumParam = false; 9775 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 9776 ParamEnd = FnDecl->param_end(); 9777 Param != ParamEnd; ++Param) { 9778 QualType ParamType = (*Param)->getType().getNonReferenceType(); 9779 if (ParamType->isDependentType() || ParamType->isRecordType() || 9780 ParamType->isEnumeralType()) { 9781 ClassOrEnumParam = true; 9782 break; 9783 } 9784 } 9785 9786 if (!ClassOrEnumParam) 9787 return Diag(FnDecl->getLocation(), 9788 diag::err_operator_overload_needs_class_or_enum) 9789 << FnDecl->getDeclName(); 9790 } 9791 9792 // C++ [over.oper]p8: 9793 // An operator function cannot have default arguments (8.3.6), 9794 // except where explicitly stated below. 9795 // 9796 // Only the function-call operator allows default arguments 9797 // (C++ [over.call]p1). 9798 if (Op != OO_Call) { 9799 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(); 9800 Param != FnDecl->param_end(); ++Param) { 9801 if ((*Param)->hasDefaultArg()) 9802 return Diag((*Param)->getLocation(), 9803 diag::err_operator_overload_default_arg) 9804 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange(); 9805 } 9806 } 9807 9808 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 9809 { false, false, false } 9810#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 9811 , { Unary, Binary, MemberOnly } 9812#include "clang/Basic/OperatorKinds.def" 9813 }; 9814 9815 bool CanBeUnaryOperator = OperatorUses[Op][0]; 9816 bool CanBeBinaryOperator = OperatorUses[Op][1]; 9817 bool MustBeMemberOperator = OperatorUses[Op][2]; 9818 9819 // C++ [over.oper]p8: 9820 // [...] Operator functions cannot have more or fewer parameters 9821 // than the number required for the corresponding operator, as 9822 // described in the rest of this subclause. 9823 unsigned NumParams = FnDecl->getNumParams() 9824 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 9825 if (Op != OO_Call && 9826 ((NumParams == 1 && !CanBeUnaryOperator) || 9827 (NumParams == 2 && !CanBeBinaryOperator) || 9828 (NumParams < 1) || (NumParams > 2))) { 9829 // We have the wrong number of parameters. 9830 unsigned ErrorKind; 9831 if (CanBeUnaryOperator && CanBeBinaryOperator) { 9832 ErrorKind = 2; // 2 -> unary or binary. 9833 } else if (CanBeUnaryOperator) { 9834 ErrorKind = 0; // 0 -> unary 9835 } else { 9836 assert(CanBeBinaryOperator && 9837 "All non-call overloaded operators are unary or binary!"); 9838 ErrorKind = 1; // 1 -> binary 9839 } 9840 9841 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 9842 << FnDecl->getDeclName() << NumParams << ErrorKind; 9843 } 9844 9845 // Overloaded operators other than operator() cannot be variadic. 9846 if (Op != OO_Call && 9847 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 9848 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 9849 << FnDecl->getDeclName(); 9850 } 9851 9852 // Some operators must be non-static member functions. 9853 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 9854 return Diag(FnDecl->getLocation(), 9855 diag::err_operator_overload_must_be_member) 9856 << FnDecl->getDeclName(); 9857 } 9858 9859 // C++ [over.inc]p1: 9860 // The user-defined function called operator++ implements the 9861 // prefix and postfix ++ operator. If this function is a member 9862 // function with no parameters, or a non-member function with one 9863 // parameter of class or enumeration type, it defines the prefix 9864 // increment operator ++ for objects of that type. If the function 9865 // is a member function with one parameter (which shall be of type 9866 // int) or a non-member function with two parameters (the second 9867 // of which shall be of type int), it defines the postfix 9868 // increment operator ++ for objects of that type. 9869 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 9870 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 9871 bool ParamIsInt = false; 9872 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>()) 9873 ParamIsInt = BT->getKind() == BuiltinType::Int; 9874 9875 if (!ParamIsInt) 9876 return Diag(LastParam->getLocation(), 9877 diag::err_operator_overload_post_incdec_must_be_int) 9878 << LastParam->getType() << (Op == OO_MinusMinus); 9879 } 9880 9881 return false; 9882} 9883 9884/// CheckLiteralOperatorDeclaration - Check whether the declaration 9885/// of this literal operator function is well-formed. If so, returns 9886/// false; otherwise, emits appropriate diagnostics and returns true. 9887bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 9888 if (isa<CXXMethodDecl>(FnDecl)) { 9889 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 9890 << FnDecl->getDeclName(); 9891 return true; 9892 } 9893 9894 if (FnDecl->isExternC()) { 9895 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 9896 return true; 9897 } 9898 9899 bool Valid = false; 9900 9901 // This might be the definition of a literal operator template. 9902 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 9903 // This might be a specialization of a literal operator template. 9904 if (!TpDecl) 9905 TpDecl = FnDecl->getPrimaryTemplate(); 9906 9907 // template <char...> type operator "" name() is the only valid template 9908 // signature, and the only valid signature with no parameters. 9909 if (TpDecl) { 9910 if (FnDecl->param_size() == 0) { 9911 // Must have only one template parameter 9912 TemplateParameterList *Params = TpDecl->getTemplateParameters(); 9913 if (Params->size() == 1) { 9914 NonTypeTemplateParmDecl *PmDecl = 9915 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0)); 9916 9917 // The template parameter must be a char parameter pack. 9918 if (PmDecl && PmDecl->isTemplateParameterPack() && 9919 Context.hasSameType(PmDecl->getType(), Context.CharTy)) 9920 Valid = true; 9921 } 9922 } 9923 } else if (FnDecl->param_size()) { 9924 // Check the first parameter 9925 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 9926 9927 QualType T = (*Param)->getType().getUnqualifiedType(); 9928 9929 // unsigned long long int, long double, and any character type are allowed 9930 // as the only parameters. 9931 if (Context.hasSameType(T, Context.UnsignedLongLongTy) || 9932 Context.hasSameType(T, Context.LongDoubleTy) || 9933 Context.hasSameType(T, Context.CharTy) || 9934 Context.hasSameType(T, Context.WCharTy) || 9935 Context.hasSameType(T, Context.Char16Ty) || 9936 Context.hasSameType(T, Context.Char32Ty)) { 9937 if (++Param == FnDecl->param_end()) 9938 Valid = true; 9939 goto FinishedParams; 9940 } 9941 9942 // Otherwise it must be a pointer to const; let's strip those qualifiers. 9943 const PointerType *PT = T->getAs<PointerType>(); 9944 if (!PT) 9945 goto FinishedParams; 9946 T = PT->getPointeeType(); 9947 if (!T.isConstQualified() || T.isVolatileQualified()) 9948 goto FinishedParams; 9949 T = T.getUnqualifiedType(); 9950 9951 // Move on to the second parameter; 9952 ++Param; 9953 9954 // If there is no second parameter, the first must be a const char * 9955 if (Param == FnDecl->param_end()) { 9956 if (Context.hasSameType(T, Context.CharTy)) 9957 Valid = true; 9958 goto FinishedParams; 9959 } 9960 9961 // const char *, const wchar_t*, const char16_t*, and const char32_t* 9962 // are allowed as the first parameter to a two-parameter function 9963 if (!(Context.hasSameType(T, Context.CharTy) || 9964 Context.hasSameType(T, Context.WCharTy) || 9965 Context.hasSameType(T, Context.Char16Ty) || 9966 Context.hasSameType(T, Context.Char32Ty))) 9967 goto FinishedParams; 9968 9969 // The second and final parameter must be an std::size_t 9970 T = (*Param)->getType().getUnqualifiedType(); 9971 if (Context.hasSameType(T, Context.getSizeType()) && 9972 ++Param == FnDecl->param_end()) 9973 Valid = true; 9974 } 9975 9976 // FIXME: This diagnostic is absolutely terrible. 9977FinishedParams: 9978 if (!Valid) { 9979 Diag(FnDecl->getLocation(), diag::err_literal_operator_params) 9980 << FnDecl->getDeclName(); 9981 return true; 9982 } 9983 9984 // A parameter-declaration-clause containing a default argument is not 9985 // equivalent to any of the permitted forms. 9986 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 9987 ParamEnd = FnDecl->param_end(); 9988 Param != ParamEnd; ++Param) { 9989 if ((*Param)->hasDefaultArg()) { 9990 Diag((*Param)->getDefaultArgRange().getBegin(), 9991 diag::err_literal_operator_default_argument) 9992 << (*Param)->getDefaultArgRange(); 9993 break; 9994 } 9995 } 9996 9997 StringRef LiteralName 9998 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 9999 if (LiteralName[0] != '_') { 10000 // C++11 [usrlit.suffix]p1: 10001 // Literal suffix identifiers that do not start with an underscore 10002 // are reserved for future standardization. 10003 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved); 10004 } 10005 10006 return false; 10007} 10008 10009/// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 10010/// linkage specification, including the language and (if present) 10011/// the '{'. ExternLoc is the location of the 'extern', LangLoc is 10012/// the location of the language string literal, which is provided 10013/// by Lang/StrSize. LBraceLoc, if valid, provides the location of 10014/// the '{' brace. Otherwise, this linkage specification does not 10015/// have any braces. 10016Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 10017 SourceLocation LangLoc, 10018 StringRef Lang, 10019 SourceLocation LBraceLoc) { 10020 LinkageSpecDecl::LanguageIDs Language; 10021 if (Lang == "\"C\"") 10022 Language = LinkageSpecDecl::lang_c; 10023 else if (Lang == "\"C++\"") 10024 Language = LinkageSpecDecl::lang_cxx; 10025 else { 10026 Diag(LangLoc, diag::err_bad_language); 10027 return 0; 10028 } 10029 10030 // FIXME: Add all the various semantics of linkage specifications 10031 10032 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, 10033 ExternLoc, LangLoc, Language); 10034 CurContext->addDecl(D); 10035 PushDeclContext(S, D); 10036 return D; 10037} 10038 10039/// ActOnFinishLinkageSpecification - Complete the definition of 10040/// the C++ linkage specification LinkageSpec. If RBraceLoc is 10041/// valid, it's the position of the closing '}' brace in a linkage 10042/// specification that uses braces. 10043Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 10044 Decl *LinkageSpec, 10045 SourceLocation RBraceLoc) { 10046 if (LinkageSpec) { 10047 if (RBraceLoc.isValid()) { 10048 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 10049 LSDecl->setRBraceLoc(RBraceLoc); 10050 } 10051 PopDeclContext(); 10052 } 10053 return LinkageSpec; 10054} 10055 10056/// \brief Perform semantic analysis for the variable declaration that 10057/// occurs within a C++ catch clause, returning the newly-created 10058/// variable. 10059VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 10060 TypeSourceInfo *TInfo, 10061 SourceLocation StartLoc, 10062 SourceLocation Loc, 10063 IdentifierInfo *Name) { 10064 bool Invalid = false; 10065 QualType ExDeclType = TInfo->getType(); 10066 10067 // Arrays and functions decay. 10068 if (ExDeclType->isArrayType()) 10069 ExDeclType = Context.getArrayDecayedType(ExDeclType); 10070 else if (ExDeclType->isFunctionType()) 10071 ExDeclType = Context.getPointerType(ExDeclType); 10072 10073 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 10074 // The exception-declaration shall not denote a pointer or reference to an 10075 // incomplete type, other than [cv] void*. 10076 // N2844 forbids rvalue references. 10077 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 10078 Diag(Loc, diag::err_catch_rvalue_ref); 10079 Invalid = true; 10080 } 10081 10082 QualType BaseType = ExDeclType; 10083 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 10084 unsigned DK = diag::err_catch_incomplete; 10085 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 10086 BaseType = Ptr->getPointeeType(); 10087 Mode = 1; 10088 DK = diag::err_catch_incomplete_ptr; 10089 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 10090 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 10091 BaseType = Ref->getPointeeType(); 10092 Mode = 2; 10093 DK = diag::err_catch_incomplete_ref; 10094 } 10095 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 10096 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 10097 Invalid = true; 10098 10099 if (!Invalid && !ExDeclType->isDependentType() && 10100 RequireNonAbstractType(Loc, ExDeclType, 10101 diag::err_abstract_type_in_decl, 10102 AbstractVariableType)) 10103 Invalid = true; 10104 10105 // Only the non-fragile NeXT runtime currently supports C++ catches 10106 // of ObjC types, and no runtime supports catching ObjC types by value. 10107 if (!Invalid && getLangOpts().ObjC1) { 10108 QualType T = ExDeclType; 10109 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 10110 T = RT->getPointeeType(); 10111 10112 if (T->isObjCObjectType()) { 10113 Diag(Loc, diag::err_objc_object_catch); 10114 Invalid = true; 10115 } else if (T->isObjCObjectPointerType()) { 10116 // FIXME: should this be a test for macosx-fragile specifically? 10117 if (getLangOpts().ObjCRuntime.isFragile()) 10118 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 10119 } 10120 } 10121 10122 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 10123 ExDeclType, TInfo, SC_None, SC_None); 10124 ExDecl->setExceptionVariable(true); 10125 10126 // In ARC, infer 'retaining' for variables of retainable type. 10127 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 10128 Invalid = true; 10129 10130 if (!Invalid && !ExDeclType->isDependentType()) { 10131 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 10132 // C++ [except.handle]p16: 10133 // The object declared in an exception-declaration or, if the 10134 // exception-declaration does not specify a name, a temporary (12.2) is 10135 // copy-initialized (8.5) from the exception object. [...] 10136 // The object is destroyed when the handler exits, after the destruction 10137 // of any automatic objects initialized within the handler. 10138 // 10139 // We just pretend to initialize the object with itself, then make sure 10140 // it can be destroyed later. 10141 QualType initType = ExDeclType; 10142 10143 InitializedEntity entity = 10144 InitializedEntity::InitializeVariable(ExDecl); 10145 InitializationKind initKind = 10146 InitializationKind::CreateCopy(Loc, SourceLocation()); 10147 10148 Expr *opaqueValue = 10149 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 10150 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1); 10151 ExprResult result = sequence.Perform(*this, entity, initKind, 10152 MultiExprArg(&opaqueValue, 1)); 10153 if (result.isInvalid()) 10154 Invalid = true; 10155 else { 10156 // If the constructor used was non-trivial, set this as the 10157 // "initializer". 10158 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take()); 10159 if (!construct->getConstructor()->isTrivial()) { 10160 Expr *init = MaybeCreateExprWithCleanups(construct); 10161 ExDecl->setInit(init); 10162 } 10163 10164 // And make sure it's destructable. 10165 FinalizeVarWithDestructor(ExDecl, recordType); 10166 } 10167 } 10168 } 10169 10170 if (Invalid) 10171 ExDecl->setInvalidDecl(); 10172 10173 return ExDecl; 10174} 10175 10176/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 10177/// handler. 10178Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 10179 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 10180 bool Invalid = D.isInvalidType(); 10181 10182 // Check for unexpanded parameter packs. 10183 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 10184 UPPC_ExceptionType)) { 10185 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 10186 D.getIdentifierLoc()); 10187 Invalid = true; 10188 } 10189 10190 IdentifierInfo *II = D.getIdentifier(); 10191 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 10192 LookupOrdinaryName, 10193 ForRedeclaration)) { 10194 // The scope should be freshly made just for us. There is just no way 10195 // it contains any previous declaration. 10196 assert(!S->isDeclScope(PrevDecl)); 10197 if (PrevDecl->isTemplateParameter()) { 10198 // Maybe we will complain about the shadowed template parameter. 10199 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 10200 PrevDecl = 0; 10201 } 10202 } 10203 10204 if (D.getCXXScopeSpec().isSet() && !Invalid) { 10205 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 10206 << D.getCXXScopeSpec().getRange(); 10207 Invalid = true; 10208 } 10209 10210 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 10211 D.getLocStart(), 10212 D.getIdentifierLoc(), 10213 D.getIdentifier()); 10214 if (Invalid) 10215 ExDecl->setInvalidDecl(); 10216 10217 // Add the exception declaration into this scope. 10218 if (II) 10219 PushOnScopeChains(ExDecl, S); 10220 else 10221 CurContext->addDecl(ExDecl); 10222 10223 ProcessDeclAttributes(S, ExDecl, D); 10224 return ExDecl; 10225} 10226 10227Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 10228 Expr *AssertExpr, 10229 Expr *AssertMessageExpr, 10230 SourceLocation RParenLoc) { 10231 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr); 10232 10233 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 10234 return 0; 10235 10236 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 10237 AssertMessage, RParenLoc, false); 10238} 10239 10240Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 10241 Expr *AssertExpr, 10242 StringLiteral *AssertMessage, 10243 SourceLocation RParenLoc, 10244 bool Failed) { 10245 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 10246 !Failed) { 10247 // In a static_assert-declaration, the constant-expression shall be a 10248 // constant expression that can be contextually converted to bool. 10249 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 10250 if (Converted.isInvalid()) 10251 Failed = true; 10252 10253 llvm::APSInt Cond; 10254 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 10255 diag::err_static_assert_expression_is_not_constant, 10256 /*AllowFold=*/false).isInvalid()) 10257 Failed = true; 10258 10259 if (!Failed && !Cond) { 10260 SmallString<256> MsgBuffer; 10261 llvm::raw_svector_ostream Msg(MsgBuffer); 10262 AssertMessage->printPretty(Msg, 0, getPrintingPolicy()); 10263 Diag(StaticAssertLoc, diag::err_static_assert_failed) 10264 << Msg.str() << AssertExpr->getSourceRange(); 10265 Failed = true; 10266 } 10267 } 10268 10269 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 10270 AssertExpr, AssertMessage, RParenLoc, 10271 Failed); 10272 10273 CurContext->addDecl(Decl); 10274 return Decl; 10275} 10276 10277/// \brief Perform semantic analysis of the given friend type declaration. 10278/// 10279/// \returns A friend declaration that. 10280FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 10281 SourceLocation FriendLoc, 10282 TypeSourceInfo *TSInfo) { 10283 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 10284 10285 QualType T = TSInfo->getType(); 10286 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 10287 10288 // C++03 [class.friend]p2: 10289 // An elaborated-type-specifier shall be used in a friend declaration 10290 // for a class.* 10291 // 10292 // * The class-key of the elaborated-type-specifier is required. 10293 if (!ActiveTemplateInstantiations.empty()) { 10294 // Do not complain about the form of friend template types during 10295 // template instantiation; we will already have complained when the 10296 // template was declared. 10297 } else if (!T->isElaboratedTypeSpecifier()) { 10298 // If we evaluated the type to a record type, suggest putting 10299 // a tag in front. 10300 if (const RecordType *RT = T->getAs<RecordType>()) { 10301 RecordDecl *RD = RT->getDecl(); 10302 10303 std::string InsertionText = std::string(" ") + RD->getKindName(); 10304 10305 Diag(TypeRange.getBegin(), 10306 getLangOpts().CPlusPlus11 ? 10307 diag::warn_cxx98_compat_unelaborated_friend_type : 10308 diag::ext_unelaborated_friend_type) 10309 << (unsigned) RD->getTagKind() 10310 << T 10311 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc), 10312 InsertionText); 10313 } else { 10314 Diag(FriendLoc, 10315 getLangOpts().CPlusPlus11 ? 10316 diag::warn_cxx98_compat_nonclass_type_friend : 10317 diag::ext_nonclass_type_friend) 10318 << T 10319 << TypeRange; 10320 } 10321 } else if (T->getAs<EnumType>()) { 10322 Diag(FriendLoc, 10323 getLangOpts().CPlusPlus11 ? 10324 diag::warn_cxx98_compat_enum_friend : 10325 diag::ext_enum_friend) 10326 << T 10327 << TypeRange; 10328 } 10329 10330 // C++11 [class.friend]p3: 10331 // A friend declaration that does not declare a function shall have one 10332 // of the following forms: 10333 // friend elaborated-type-specifier ; 10334 // friend simple-type-specifier ; 10335 // friend typename-specifier ; 10336 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 10337 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 10338 10339 // If the type specifier in a friend declaration designates a (possibly 10340 // cv-qualified) class type, that class is declared as a friend; otherwise, 10341 // the friend declaration is ignored. 10342 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc); 10343} 10344 10345/// Handle a friend tag declaration where the scope specifier was 10346/// templated. 10347Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 10348 unsigned TagSpec, SourceLocation TagLoc, 10349 CXXScopeSpec &SS, 10350 IdentifierInfo *Name, SourceLocation NameLoc, 10351 AttributeList *Attr, 10352 MultiTemplateParamsArg TempParamLists) { 10353 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 10354 10355 bool isExplicitSpecialization = false; 10356 bool Invalid = false; 10357 10358 if (TemplateParameterList *TemplateParams 10359 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS, 10360 TempParamLists.data(), 10361 TempParamLists.size(), 10362 /*friend*/ true, 10363 isExplicitSpecialization, 10364 Invalid)) { 10365 if (TemplateParams->size() > 0) { 10366 // This is a declaration of a class template. 10367 if (Invalid) 10368 return 0; 10369 10370 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, 10371 SS, Name, NameLoc, Attr, 10372 TemplateParams, AS_public, 10373 /*ModulePrivateLoc=*/SourceLocation(), 10374 TempParamLists.size() - 1, 10375 TempParamLists.data()).take(); 10376 } else { 10377 // The "template<>" header is extraneous. 10378 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 10379 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 10380 isExplicitSpecialization = true; 10381 } 10382 } 10383 10384 if (Invalid) return 0; 10385 10386 bool isAllExplicitSpecializations = true; 10387 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 10388 if (TempParamLists[I]->size()) { 10389 isAllExplicitSpecializations = false; 10390 break; 10391 } 10392 } 10393 10394 // FIXME: don't ignore attributes. 10395 10396 // If it's explicit specializations all the way down, just forget 10397 // about the template header and build an appropriate non-templated 10398 // friend. TODO: for source fidelity, remember the headers. 10399 if (isAllExplicitSpecializations) { 10400 if (SS.isEmpty()) { 10401 bool Owned = false; 10402 bool IsDependent = false; 10403 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 10404 Attr, AS_public, 10405 /*ModulePrivateLoc=*/SourceLocation(), 10406 MultiTemplateParamsArg(), Owned, IsDependent, 10407 /*ScopedEnumKWLoc=*/SourceLocation(), 10408 /*ScopedEnumUsesClassTag=*/false, 10409 /*UnderlyingType=*/TypeResult()); 10410 } 10411 10412 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 10413 ElaboratedTypeKeyword Keyword 10414 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 10415 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 10416 *Name, NameLoc); 10417 if (T.isNull()) 10418 return 0; 10419 10420 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 10421 if (isa<DependentNameType>(T)) { 10422 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc()); 10423 TL.setElaboratedKeywordLoc(TagLoc); 10424 TL.setQualifierLoc(QualifierLoc); 10425 TL.setNameLoc(NameLoc); 10426 } else { 10427 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc()); 10428 TL.setElaboratedKeywordLoc(TagLoc); 10429 TL.setQualifierLoc(QualifierLoc); 10430 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc); 10431 } 10432 10433 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 10434 TSI, FriendLoc); 10435 Friend->setAccess(AS_public); 10436 CurContext->addDecl(Friend); 10437 return Friend; 10438 } 10439 10440 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 10441 10442 10443 10444 // Handle the case of a templated-scope friend class. e.g. 10445 // template <class T> class A<T>::B; 10446 // FIXME: we don't support these right now. 10447 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 10448 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 10449 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 10450 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc()); 10451 TL.setElaboratedKeywordLoc(TagLoc); 10452 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 10453 TL.setNameLoc(NameLoc); 10454 10455 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 10456 TSI, FriendLoc); 10457 Friend->setAccess(AS_public); 10458 Friend->setUnsupportedFriend(true); 10459 CurContext->addDecl(Friend); 10460 return Friend; 10461} 10462 10463 10464/// Handle a friend type declaration. This works in tandem with 10465/// ActOnTag. 10466/// 10467/// Notes on friend class templates: 10468/// 10469/// We generally treat friend class declarations as if they were 10470/// declaring a class. So, for example, the elaborated type specifier 10471/// in a friend declaration is required to obey the restrictions of a 10472/// class-head (i.e. no typedefs in the scope chain), template 10473/// parameters are required to match up with simple template-ids, &c. 10474/// However, unlike when declaring a template specialization, it's 10475/// okay to refer to a template specialization without an empty 10476/// template parameter declaration, e.g. 10477/// friend class A<T>::B<unsigned>; 10478/// We permit this as a special case; if there are any template 10479/// parameters present at all, require proper matching, i.e. 10480/// template <> template \<class T> friend class A<int>::B; 10481Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 10482 MultiTemplateParamsArg TempParams) { 10483 SourceLocation Loc = DS.getLocStart(); 10484 10485 assert(DS.isFriendSpecified()); 10486 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 10487 10488 // Try to convert the decl specifier to a type. This works for 10489 // friend templates because ActOnTag never produces a ClassTemplateDecl 10490 // for a TUK_Friend. 10491 Declarator TheDeclarator(DS, Declarator::MemberContext); 10492 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 10493 QualType T = TSI->getType(); 10494 if (TheDeclarator.isInvalidType()) 10495 return 0; 10496 10497 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 10498 return 0; 10499 10500 // This is definitely an error in C++98. It's probably meant to 10501 // be forbidden in C++0x, too, but the specification is just 10502 // poorly written. 10503 // 10504 // The problem is with declarations like the following: 10505 // template <T> friend A<T>::foo; 10506 // where deciding whether a class C is a friend or not now hinges 10507 // on whether there exists an instantiation of A that causes 10508 // 'foo' to equal C. There are restrictions on class-heads 10509 // (which we declare (by fiat) elaborated friend declarations to 10510 // be) that makes this tractable. 10511 // 10512 // FIXME: handle "template <> friend class A<T>;", which 10513 // is possibly well-formed? Who even knows? 10514 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 10515 Diag(Loc, diag::err_tagless_friend_type_template) 10516 << DS.getSourceRange(); 10517 return 0; 10518 } 10519 10520 // C++98 [class.friend]p1: A friend of a class is a function 10521 // or class that is not a member of the class . . . 10522 // This is fixed in DR77, which just barely didn't make the C++03 10523 // deadline. It's also a very silly restriction that seriously 10524 // affects inner classes and which nobody else seems to implement; 10525 // thus we never diagnose it, not even in -pedantic. 10526 // 10527 // But note that we could warn about it: it's always useless to 10528 // friend one of your own members (it's not, however, worthless to 10529 // friend a member of an arbitrary specialization of your template). 10530 10531 Decl *D; 10532 if (unsigned NumTempParamLists = TempParams.size()) 10533 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 10534 NumTempParamLists, 10535 TempParams.data(), 10536 TSI, 10537 DS.getFriendSpecLoc()); 10538 else 10539 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 10540 10541 if (!D) 10542 return 0; 10543 10544 D->setAccess(AS_public); 10545 CurContext->addDecl(D); 10546 10547 return D; 10548} 10549 10550NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 10551 MultiTemplateParamsArg TemplateParams) { 10552 const DeclSpec &DS = D.getDeclSpec(); 10553 10554 assert(DS.isFriendSpecified()); 10555 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 10556 10557 SourceLocation Loc = D.getIdentifierLoc(); 10558 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 10559 10560 // C++ [class.friend]p1 10561 // A friend of a class is a function or class.... 10562 // Note that this sees through typedefs, which is intended. 10563 // It *doesn't* see through dependent types, which is correct 10564 // according to [temp.arg.type]p3: 10565 // If a declaration acquires a function type through a 10566 // type dependent on a template-parameter and this causes 10567 // a declaration that does not use the syntactic form of a 10568 // function declarator to have a function type, the program 10569 // is ill-formed. 10570 if (!TInfo->getType()->isFunctionType()) { 10571 Diag(Loc, diag::err_unexpected_friend); 10572 10573 // It might be worthwhile to try to recover by creating an 10574 // appropriate declaration. 10575 return 0; 10576 } 10577 10578 // C++ [namespace.memdef]p3 10579 // - If a friend declaration in a non-local class first declares a 10580 // class or function, the friend class or function is a member 10581 // of the innermost enclosing namespace. 10582 // - The name of the friend is not found by simple name lookup 10583 // until a matching declaration is provided in that namespace 10584 // scope (either before or after the class declaration granting 10585 // friendship). 10586 // - If a friend function is called, its name may be found by the 10587 // name lookup that considers functions from namespaces and 10588 // classes associated with the types of the function arguments. 10589 // - When looking for a prior declaration of a class or a function 10590 // declared as a friend, scopes outside the innermost enclosing 10591 // namespace scope are not considered. 10592 10593 CXXScopeSpec &SS = D.getCXXScopeSpec(); 10594 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 10595 DeclarationName Name = NameInfo.getName(); 10596 assert(Name); 10597 10598 // Check for unexpanded parameter packs. 10599 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 10600 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 10601 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 10602 return 0; 10603 10604 // The context we found the declaration in, or in which we should 10605 // create the declaration. 10606 DeclContext *DC; 10607 Scope *DCScope = S; 10608 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 10609 ForRedeclaration); 10610 10611 // FIXME: there are different rules in local classes 10612 10613 // There are four cases here. 10614 // - There's no scope specifier, in which case we just go to the 10615 // appropriate scope and look for a function or function template 10616 // there as appropriate. 10617 // Recover from invalid scope qualifiers as if they just weren't there. 10618 if (SS.isInvalid() || !SS.isSet()) { 10619 // C++0x [namespace.memdef]p3: 10620 // If the name in a friend declaration is neither qualified nor 10621 // a template-id and the declaration is a function or an 10622 // elaborated-type-specifier, the lookup to determine whether 10623 // the entity has been previously declared shall not consider 10624 // any scopes outside the innermost enclosing namespace. 10625 // C++0x [class.friend]p11: 10626 // If a friend declaration appears in a local class and the name 10627 // specified is an unqualified name, a prior declaration is 10628 // looked up without considering scopes that are outside the 10629 // innermost enclosing non-class scope. For a friend function 10630 // declaration, if there is no prior declaration, the program is 10631 // ill-formed. 10632 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass(); 10633 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 10634 10635 // Find the appropriate context according to the above. 10636 DC = CurContext; 10637 while (true) { 10638 // Skip class contexts. If someone can cite chapter and verse 10639 // for this behavior, that would be nice --- it's what GCC and 10640 // EDG do, and it seems like a reasonable intent, but the spec 10641 // really only says that checks for unqualified existing 10642 // declarations should stop at the nearest enclosing namespace, 10643 // not that they should only consider the nearest enclosing 10644 // namespace. 10645 while (DC->isRecord() || DC->isTransparentContext()) 10646 DC = DC->getParent(); 10647 10648 LookupQualifiedName(Previous, DC); 10649 10650 // TODO: decide what we think about using declarations. 10651 if (isLocal || !Previous.empty()) 10652 break; 10653 10654 if (isTemplateId) { 10655 if (isa<TranslationUnitDecl>(DC)) break; 10656 } else { 10657 if (DC->isFileContext()) break; 10658 } 10659 DC = DC->getParent(); 10660 } 10661 10662 // C++ [class.friend]p1: A friend of a class is a function or 10663 // class that is not a member of the class . . . 10664 // C++11 changes this for both friend types and functions. 10665 // Most C++ 98 compilers do seem to give an error here, so 10666 // we do, too. 10667 if (!Previous.empty() && DC->Equals(CurContext)) 10668 Diag(DS.getFriendSpecLoc(), 10669 getLangOpts().CPlusPlus11 ? 10670 diag::warn_cxx98_compat_friend_is_member : 10671 diag::err_friend_is_member); 10672 10673 DCScope = getScopeForDeclContext(S, DC); 10674 10675 // C++ [class.friend]p6: 10676 // A function can be defined in a friend declaration of a class if and 10677 // only if the class is a non-local class (9.8), the function name is 10678 // unqualified, and the function has namespace scope. 10679 if (isLocal && D.isFunctionDefinition()) { 10680 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 10681 } 10682 10683 // - There's a non-dependent scope specifier, in which case we 10684 // compute it and do a previous lookup there for a function 10685 // or function template. 10686 } else if (!SS.getScopeRep()->isDependent()) { 10687 DC = computeDeclContext(SS); 10688 if (!DC) return 0; 10689 10690 if (RequireCompleteDeclContext(SS, DC)) return 0; 10691 10692 LookupQualifiedName(Previous, DC); 10693 10694 // Ignore things found implicitly in the wrong scope. 10695 // TODO: better diagnostics for this case. Suggesting the right 10696 // qualified scope would be nice... 10697 LookupResult::Filter F = Previous.makeFilter(); 10698 while (F.hasNext()) { 10699 NamedDecl *D = F.next(); 10700 if (!DC->InEnclosingNamespaceSetOf( 10701 D->getDeclContext()->getRedeclContext())) 10702 F.erase(); 10703 } 10704 F.done(); 10705 10706 if (Previous.empty()) { 10707 D.setInvalidType(); 10708 Diag(Loc, diag::err_qualified_friend_not_found) 10709 << Name << TInfo->getType(); 10710 return 0; 10711 } 10712 10713 // C++ [class.friend]p1: A friend of a class is a function or 10714 // class that is not a member of the class . . . 10715 if (DC->Equals(CurContext)) 10716 Diag(DS.getFriendSpecLoc(), 10717 getLangOpts().CPlusPlus11 ? 10718 diag::warn_cxx98_compat_friend_is_member : 10719 diag::err_friend_is_member); 10720 10721 if (D.isFunctionDefinition()) { 10722 // C++ [class.friend]p6: 10723 // A function can be defined in a friend declaration of a class if and 10724 // only if the class is a non-local class (9.8), the function name is 10725 // unqualified, and the function has namespace scope. 10726 SemaDiagnosticBuilder DB 10727 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 10728 10729 DB << SS.getScopeRep(); 10730 if (DC->isFileContext()) 10731 DB << FixItHint::CreateRemoval(SS.getRange()); 10732 SS.clear(); 10733 } 10734 10735 // - There's a scope specifier that does not match any template 10736 // parameter lists, in which case we use some arbitrary context, 10737 // create a method or method template, and wait for instantiation. 10738 // - There's a scope specifier that does match some template 10739 // parameter lists, which we don't handle right now. 10740 } else { 10741 if (D.isFunctionDefinition()) { 10742 // C++ [class.friend]p6: 10743 // A function can be defined in a friend declaration of a class if and 10744 // only if the class is a non-local class (9.8), the function name is 10745 // unqualified, and the function has namespace scope. 10746 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 10747 << SS.getScopeRep(); 10748 } 10749 10750 DC = CurContext; 10751 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 10752 } 10753 10754 if (!DC->isRecord()) { 10755 // This implies that it has to be an operator or function. 10756 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName || 10757 D.getName().getKind() == UnqualifiedId::IK_DestructorName || 10758 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) { 10759 Diag(Loc, diag::err_introducing_special_friend) << 10760 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 : 10761 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2); 10762 return 0; 10763 } 10764 } 10765 10766 // FIXME: This is an egregious hack to cope with cases where the scope stack 10767 // does not contain the declaration context, i.e., in an out-of-line 10768 // definition of a class. 10769 Scope FakeDCScope(S, Scope::DeclScope, Diags); 10770 if (!DCScope) { 10771 FakeDCScope.setEntity(DC); 10772 DCScope = &FakeDCScope; 10773 } 10774 10775 bool AddToScope = true; 10776 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 10777 TemplateParams, AddToScope); 10778 if (!ND) return 0; 10779 10780 assert(ND->getDeclContext() == DC); 10781 assert(ND->getLexicalDeclContext() == CurContext); 10782 10783 // Add the function declaration to the appropriate lookup tables, 10784 // adjusting the redeclarations list as necessary. We don't 10785 // want to do this yet if the friending class is dependent. 10786 // 10787 // Also update the scope-based lookup if the target context's 10788 // lookup context is in lexical scope. 10789 if (!CurContext->isDependentContext()) { 10790 DC = DC->getRedeclContext(); 10791 DC->makeDeclVisibleInContext(ND); 10792 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 10793 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 10794 } 10795 10796 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 10797 D.getIdentifierLoc(), ND, 10798 DS.getFriendSpecLoc()); 10799 FrD->setAccess(AS_public); 10800 CurContext->addDecl(FrD); 10801 10802 if (ND->isInvalidDecl()) { 10803 FrD->setInvalidDecl(); 10804 } else { 10805 if (DC->isRecord()) CheckFriendAccess(ND); 10806 10807 FunctionDecl *FD; 10808 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 10809 FD = FTD->getTemplatedDecl(); 10810 else 10811 FD = cast<FunctionDecl>(ND); 10812 10813 // Mark templated-scope function declarations as unsupported. 10814 if (FD->getNumTemplateParameterLists()) 10815 FrD->setUnsupportedFriend(true); 10816 } 10817 10818 return ND; 10819} 10820 10821void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 10822 AdjustDeclIfTemplate(Dcl); 10823 10824 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 10825 if (!Fn) { 10826 Diag(DelLoc, diag::err_deleted_non_function); 10827 return; 10828 } 10829 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 10830 // Don't consider the implicit declaration we generate for explicit 10831 // specializations. FIXME: Do not generate these implicit declarations. 10832 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization 10833 || Prev->getPreviousDecl()) && !Prev->isDefined()) { 10834 Diag(DelLoc, diag::err_deleted_decl_not_first); 10835 Diag(Prev->getLocation(), diag::note_previous_declaration); 10836 } 10837 // If the declaration wasn't the first, we delete the function anyway for 10838 // recovery. 10839 } 10840 Fn->setDeletedAsWritten(); 10841} 10842 10843void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 10844 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 10845 10846 if (MD) { 10847 if (MD->getParent()->isDependentType()) { 10848 MD->setDefaulted(); 10849 MD->setExplicitlyDefaulted(); 10850 return; 10851 } 10852 10853 CXXSpecialMember Member = getSpecialMember(MD); 10854 if (Member == CXXInvalid) { 10855 Diag(DefaultLoc, diag::err_default_special_members); 10856 return; 10857 } 10858 10859 MD->setDefaulted(); 10860 MD->setExplicitlyDefaulted(); 10861 10862 // If this definition appears within the record, do the checking when 10863 // the record is complete. 10864 const FunctionDecl *Primary = MD; 10865 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 10866 // Find the uninstantiated declaration that actually had the '= default' 10867 // on it. 10868 Pattern->isDefined(Primary); 10869 10870 if (Primary == Primary->getCanonicalDecl()) 10871 return; 10872 10873 CheckExplicitlyDefaultedSpecialMember(MD); 10874 10875 // The exception specification is needed because we are defining the 10876 // function. 10877 ResolveExceptionSpec(DefaultLoc, 10878 MD->getType()->castAs<FunctionProtoType>()); 10879 10880 switch (Member) { 10881 case CXXDefaultConstructor: { 10882 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD); 10883 if (!CD->isInvalidDecl()) 10884 DefineImplicitDefaultConstructor(DefaultLoc, CD); 10885 break; 10886 } 10887 10888 case CXXCopyConstructor: { 10889 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD); 10890 if (!CD->isInvalidDecl()) 10891 DefineImplicitCopyConstructor(DefaultLoc, CD); 10892 break; 10893 } 10894 10895 case CXXCopyAssignment: { 10896 if (!MD->isInvalidDecl()) 10897 DefineImplicitCopyAssignment(DefaultLoc, MD); 10898 break; 10899 } 10900 10901 case CXXDestructor: { 10902 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD); 10903 if (!DD->isInvalidDecl()) 10904 DefineImplicitDestructor(DefaultLoc, DD); 10905 break; 10906 } 10907 10908 case CXXMoveConstructor: { 10909 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD); 10910 if (!CD->isInvalidDecl()) 10911 DefineImplicitMoveConstructor(DefaultLoc, CD); 10912 break; 10913 } 10914 10915 case CXXMoveAssignment: { 10916 if (!MD->isInvalidDecl()) 10917 DefineImplicitMoveAssignment(DefaultLoc, MD); 10918 break; 10919 } 10920 10921 case CXXInvalid: 10922 llvm_unreachable("Invalid special member."); 10923 } 10924 } else { 10925 Diag(DefaultLoc, diag::err_default_special_members); 10926 } 10927} 10928 10929static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 10930 for (Stmt::child_range CI = S->children(); CI; ++CI) { 10931 Stmt *SubStmt = *CI; 10932 if (!SubStmt) 10933 continue; 10934 if (isa<ReturnStmt>(SubStmt)) 10935 Self.Diag(SubStmt->getLocStart(), 10936 diag::err_return_in_constructor_handler); 10937 if (!isa<Expr>(SubStmt)) 10938 SearchForReturnInStmt(Self, SubStmt); 10939 } 10940} 10941 10942void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 10943 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 10944 CXXCatchStmt *Handler = TryBlock->getHandler(I); 10945 SearchForReturnInStmt(*this, Handler); 10946 } 10947} 10948 10949bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 10950 const CXXMethodDecl *Old) { 10951 const FunctionType *NewFT = New->getType()->getAs<FunctionType>(); 10952 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>(); 10953 10954 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 10955 10956 // If the calling conventions match, everything is fine 10957 if (NewCC == OldCC) 10958 return false; 10959 10960 // If either of the calling conventions are set to "default", we need to pick 10961 // something more sensible based on the target. This supports code where the 10962 // one method explicitly sets thiscall, and another has no explicit calling 10963 // convention. 10964 CallingConv Default = 10965 Context.getTargetInfo().getDefaultCallingConv(TargetInfo::CCMT_Member); 10966 if (NewCC == CC_Default) 10967 NewCC = Default; 10968 if (OldCC == CC_Default) 10969 OldCC = Default; 10970 10971 // If the calling conventions still don't match, then report the error 10972 if (NewCC != OldCC) { 10973 Diag(New->getLocation(), 10974 diag::err_conflicting_overriding_cc_attributes) 10975 << New->getDeclName() << New->getType() << Old->getType(); 10976 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 10977 return true; 10978 } 10979 10980 return false; 10981} 10982 10983bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 10984 const CXXMethodDecl *Old) { 10985 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType(); 10986 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType(); 10987 10988 if (Context.hasSameType(NewTy, OldTy) || 10989 NewTy->isDependentType() || OldTy->isDependentType()) 10990 return false; 10991 10992 // Check if the return types are covariant 10993 QualType NewClassTy, OldClassTy; 10994 10995 /// Both types must be pointers or references to classes. 10996 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 10997 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 10998 NewClassTy = NewPT->getPointeeType(); 10999 OldClassTy = OldPT->getPointeeType(); 11000 } 11001 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 11002 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 11003 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 11004 NewClassTy = NewRT->getPointeeType(); 11005 OldClassTy = OldRT->getPointeeType(); 11006 } 11007 } 11008 } 11009 11010 // The return types aren't either both pointers or references to a class type. 11011 if (NewClassTy.isNull()) { 11012 Diag(New->getLocation(), 11013 diag::err_different_return_type_for_overriding_virtual_function) 11014 << New->getDeclName() << NewTy << OldTy; 11015 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 11016 11017 return true; 11018 } 11019 11020 // C++ [class.virtual]p6: 11021 // If the return type of D::f differs from the return type of B::f, the 11022 // class type in the return type of D::f shall be complete at the point of 11023 // declaration of D::f or shall be the class type D. 11024 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 11025 if (!RT->isBeingDefined() && 11026 RequireCompleteType(New->getLocation(), NewClassTy, 11027 diag::err_covariant_return_incomplete, 11028 New->getDeclName())) 11029 return true; 11030 } 11031 11032 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 11033 // Check if the new class derives from the old class. 11034 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 11035 Diag(New->getLocation(), 11036 diag::err_covariant_return_not_derived) 11037 << New->getDeclName() << NewTy << OldTy; 11038 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 11039 return true; 11040 } 11041 11042 // Check if we the conversion from derived to base is valid. 11043 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy, 11044 diag::err_covariant_return_inaccessible_base, 11045 diag::err_covariant_return_ambiguous_derived_to_base_conv, 11046 // FIXME: Should this point to the return type? 11047 New->getLocation(), SourceRange(), New->getDeclName(), 0)) { 11048 // FIXME: this note won't trigger for delayed access control 11049 // diagnostics, and it's impossible to get an undelayed error 11050 // here from access control during the original parse because 11051 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 11052 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 11053 return true; 11054 } 11055 } 11056 11057 // The qualifiers of the return types must be the same. 11058 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 11059 Diag(New->getLocation(), 11060 diag::err_covariant_return_type_different_qualifications) 11061 << New->getDeclName() << NewTy << OldTy; 11062 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 11063 return true; 11064 }; 11065 11066 11067 // The new class type must have the same or less qualifiers as the old type. 11068 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 11069 Diag(New->getLocation(), 11070 diag::err_covariant_return_type_class_type_more_qualified) 11071 << New->getDeclName() << NewTy << OldTy; 11072 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 11073 return true; 11074 }; 11075 11076 return false; 11077} 11078 11079/// \brief Mark the given method pure. 11080/// 11081/// \param Method the method to be marked pure. 11082/// 11083/// \param InitRange the source range that covers the "0" initializer. 11084bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 11085 SourceLocation EndLoc = InitRange.getEnd(); 11086 if (EndLoc.isValid()) 11087 Method->setRangeEnd(EndLoc); 11088 11089 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 11090 Method->setPure(); 11091 return false; 11092 } 11093 11094 if (!Method->isInvalidDecl()) 11095 Diag(Method->getLocation(), diag::err_non_virtual_pure) 11096 << Method->getDeclName() << InitRange; 11097 return true; 11098} 11099 11100/// \brief Determine whether the given declaration is a static data member. 11101static bool isStaticDataMember(Decl *D) { 11102 VarDecl *Var = dyn_cast_or_null<VarDecl>(D); 11103 if (!Var) 11104 return false; 11105 11106 return Var->isStaticDataMember(); 11107} 11108/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 11109/// an initializer for the out-of-line declaration 'Dcl'. The scope 11110/// is a fresh scope pushed for just this purpose. 11111/// 11112/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 11113/// static data member of class X, names should be looked up in the scope of 11114/// class X. 11115void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 11116 // If there is no declaration, there was an error parsing it. 11117 if (D == 0 || D->isInvalidDecl()) return; 11118 11119 // We should only get called for declarations with scope specifiers, like: 11120 // int foo::bar; 11121 assert(D->isOutOfLine()); 11122 EnterDeclaratorContext(S, D->getDeclContext()); 11123 11124 // If we are parsing the initializer for a static data member, push a 11125 // new expression evaluation context that is associated with this static 11126 // data member. 11127 if (isStaticDataMember(D)) 11128 PushExpressionEvaluationContext(PotentiallyEvaluated, D); 11129} 11130 11131/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 11132/// initializer for the out-of-line declaration 'D'. 11133void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 11134 // If there is no declaration, there was an error parsing it. 11135 if (D == 0 || D->isInvalidDecl()) return; 11136 11137 if (isStaticDataMember(D)) 11138 PopExpressionEvaluationContext(); 11139 11140 assert(D->isOutOfLine()); 11141 ExitDeclaratorContext(S); 11142} 11143 11144/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 11145/// C++ if/switch/while/for statement. 11146/// e.g: "if (int x = f()) {...}" 11147DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 11148 // C++ 6.4p2: 11149 // The declarator shall not specify a function or an array. 11150 // The type-specifier-seq shall not contain typedef and shall not declare a 11151 // new class or enumeration. 11152 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 11153 "Parser allowed 'typedef' as storage class of condition decl."); 11154 11155 Decl *Dcl = ActOnDeclarator(S, D); 11156 if (!Dcl) 11157 return true; 11158 11159 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 11160 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 11161 << D.getSourceRange(); 11162 return true; 11163 } 11164 11165 return Dcl; 11166} 11167 11168void Sema::LoadExternalVTableUses() { 11169 if (!ExternalSource) 11170 return; 11171 11172 SmallVector<ExternalVTableUse, 4> VTables; 11173 ExternalSource->ReadUsedVTables(VTables); 11174 SmallVector<VTableUse, 4> NewUses; 11175 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 11176 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 11177 = VTablesUsed.find(VTables[I].Record); 11178 // Even if a definition wasn't required before, it may be required now. 11179 if (Pos != VTablesUsed.end()) { 11180 if (!Pos->second && VTables[I].DefinitionRequired) 11181 Pos->second = true; 11182 continue; 11183 } 11184 11185 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 11186 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 11187 } 11188 11189 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 11190} 11191 11192void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 11193 bool DefinitionRequired) { 11194 // Ignore any vtable uses in unevaluated operands or for classes that do 11195 // not have a vtable. 11196 if (!Class->isDynamicClass() || Class->isDependentContext() || 11197 CurContext->isDependentContext() || 11198 ExprEvalContexts.back().Context == Unevaluated) 11199 return; 11200 11201 // Try to insert this class into the map. 11202 LoadExternalVTableUses(); 11203 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 11204 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 11205 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 11206 if (!Pos.second) { 11207 // If we already had an entry, check to see if we are promoting this vtable 11208 // to required a definition. If so, we need to reappend to the VTableUses 11209 // list, since we may have already processed the first entry. 11210 if (DefinitionRequired && !Pos.first->second) { 11211 Pos.first->second = true; 11212 } else { 11213 // Otherwise, we can early exit. 11214 return; 11215 } 11216 } 11217 11218 // Local classes need to have their virtual members marked 11219 // immediately. For all other classes, we mark their virtual members 11220 // at the end of the translation unit. 11221 if (Class->isLocalClass()) 11222 MarkVirtualMembersReferenced(Loc, Class); 11223 else 11224 VTableUses.push_back(std::make_pair(Class, Loc)); 11225} 11226 11227bool Sema::DefineUsedVTables() { 11228 LoadExternalVTableUses(); 11229 if (VTableUses.empty()) 11230 return false; 11231 11232 // Note: The VTableUses vector could grow as a result of marking 11233 // the members of a class as "used", so we check the size each 11234 // time through the loop and prefer indices (which are stable) to 11235 // iterators (which are not). 11236 bool DefinedAnything = false; 11237 for (unsigned I = 0; I != VTableUses.size(); ++I) { 11238 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 11239 if (!Class) 11240 continue; 11241 11242 SourceLocation Loc = VTableUses[I].second; 11243 11244 bool DefineVTable = true; 11245 11246 // If this class has a key function, but that key function is 11247 // defined in another translation unit, we don't need to emit the 11248 // vtable even though we're using it. 11249 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 11250 if (KeyFunction && !KeyFunction->hasBody()) { 11251 switch (KeyFunction->getTemplateSpecializationKind()) { 11252 case TSK_Undeclared: 11253 case TSK_ExplicitSpecialization: 11254 case TSK_ExplicitInstantiationDeclaration: 11255 // The key function is in another translation unit. 11256 DefineVTable = false; 11257 break; 11258 11259 case TSK_ExplicitInstantiationDefinition: 11260 case TSK_ImplicitInstantiation: 11261 // We will be instantiating the key function. 11262 break; 11263 } 11264 } else if (!KeyFunction) { 11265 // If we have a class with no key function that is the subject 11266 // of an explicit instantiation declaration, suppress the 11267 // vtable; it will live with the explicit instantiation 11268 // definition. 11269 bool IsExplicitInstantiationDeclaration 11270 = Class->getTemplateSpecializationKind() 11271 == TSK_ExplicitInstantiationDeclaration; 11272 for (TagDecl::redecl_iterator R = Class->redecls_begin(), 11273 REnd = Class->redecls_end(); 11274 R != REnd; ++R) { 11275 TemplateSpecializationKind TSK 11276 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind(); 11277 if (TSK == TSK_ExplicitInstantiationDeclaration) 11278 IsExplicitInstantiationDeclaration = true; 11279 else if (TSK == TSK_ExplicitInstantiationDefinition) { 11280 IsExplicitInstantiationDeclaration = false; 11281 break; 11282 } 11283 } 11284 11285 if (IsExplicitInstantiationDeclaration) 11286 DefineVTable = false; 11287 } 11288 11289 // The exception specifications for all virtual members may be needed even 11290 // if we are not providing an authoritative form of the vtable in this TU. 11291 // We may choose to emit it available_externally anyway. 11292 if (!DefineVTable) { 11293 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 11294 continue; 11295 } 11296 11297 // Mark all of the virtual members of this class as referenced, so 11298 // that we can build a vtable. Then, tell the AST consumer that a 11299 // vtable for this class is required. 11300 DefinedAnything = true; 11301 MarkVirtualMembersReferenced(Loc, Class); 11302 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 11303 Consumer.HandleVTable(Class, VTablesUsed[Canonical]); 11304 11305 // Optionally warn if we're emitting a weak vtable. 11306 if (Class->getLinkage() == ExternalLinkage && 11307 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) { 11308 const FunctionDecl *KeyFunctionDef = 0; 11309 if (!KeyFunction || 11310 (KeyFunction->hasBody(KeyFunctionDef) && 11311 KeyFunctionDef->isInlined())) 11312 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() == 11313 TSK_ExplicitInstantiationDefinition 11314 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable) 11315 << Class; 11316 } 11317 } 11318 VTableUses.clear(); 11319 11320 return DefinedAnything; 11321} 11322 11323void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 11324 const CXXRecordDecl *RD) { 11325 for (CXXRecordDecl::method_iterator I = RD->method_begin(), 11326 E = RD->method_end(); I != E; ++I) 11327 if ((*I)->isVirtual() && !(*I)->isPure()) 11328 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>()); 11329} 11330 11331void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 11332 const CXXRecordDecl *RD) { 11333 // Mark all functions which will appear in RD's vtable as used. 11334 CXXFinalOverriderMap FinalOverriders; 11335 RD->getFinalOverriders(FinalOverriders); 11336 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 11337 E = FinalOverriders.end(); 11338 I != E; ++I) { 11339 for (OverridingMethods::const_iterator OI = I->second.begin(), 11340 OE = I->second.end(); 11341 OI != OE; ++OI) { 11342 assert(OI->second.size() > 0 && "no final overrider"); 11343 CXXMethodDecl *Overrider = OI->second.front().Method; 11344 11345 // C++ [basic.def.odr]p2: 11346 // [...] A virtual member function is used if it is not pure. [...] 11347 if (!Overrider->isPure()) 11348 MarkFunctionReferenced(Loc, Overrider); 11349 } 11350 } 11351 11352 // Only classes that have virtual bases need a VTT. 11353 if (RD->getNumVBases() == 0) 11354 return; 11355 11356 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(), 11357 e = RD->bases_end(); i != e; ++i) { 11358 const CXXRecordDecl *Base = 11359 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl()); 11360 if (Base->getNumVBases() == 0) 11361 continue; 11362 MarkVirtualMembersReferenced(Loc, Base); 11363 } 11364} 11365 11366/// SetIvarInitializers - This routine builds initialization ASTs for the 11367/// Objective-C implementation whose ivars need be initialized. 11368void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 11369 if (!getLangOpts().CPlusPlus) 11370 return; 11371 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 11372 SmallVector<ObjCIvarDecl*, 8> ivars; 11373 CollectIvarsToConstructOrDestruct(OID, ivars); 11374 if (ivars.empty()) 11375 return; 11376 SmallVector<CXXCtorInitializer*, 32> AllToInit; 11377 for (unsigned i = 0; i < ivars.size(); i++) { 11378 FieldDecl *Field = ivars[i]; 11379 if (Field->isInvalidDecl()) 11380 continue; 11381 11382 CXXCtorInitializer *Member; 11383 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 11384 InitializationKind InitKind = 11385 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 11386 11387 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0); 11388 ExprResult MemberInit = 11389 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg()); 11390 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 11391 // Note, MemberInit could actually come back empty if no initialization 11392 // is required (e.g., because it would call a trivial default constructor) 11393 if (!MemberInit.get() || MemberInit.isInvalid()) 11394 continue; 11395 11396 Member = 11397 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 11398 SourceLocation(), 11399 MemberInit.takeAs<Expr>(), 11400 SourceLocation()); 11401 AllToInit.push_back(Member); 11402 11403 // Be sure that the destructor is accessible and is marked as referenced. 11404 if (const RecordType *RecordTy 11405 = Context.getBaseElementType(Field->getType()) 11406 ->getAs<RecordType>()) { 11407 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 11408 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 11409 MarkFunctionReferenced(Field->getLocation(), Destructor); 11410 CheckDestructorAccess(Field->getLocation(), Destructor, 11411 PDiag(diag::err_access_dtor_ivar) 11412 << Context.getBaseElementType(Field->getType())); 11413 } 11414 } 11415 } 11416 ObjCImplementation->setIvarInitializers(Context, 11417 AllToInit.data(), AllToInit.size()); 11418 } 11419} 11420 11421static 11422void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 11423 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid, 11424 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid, 11425 llvm::SmallSet<CXXConstructorDecl*, 4> &Current, 11426 Sema &S) { 11427 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(), 11428 CE = Current.end(); 11429 if (Ctor->isInvalidDecl()) 11430 return; 11431 11432 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 11433 11434 // Target may not be determinable yet, for instance if this is a dependent 11435 // call in an uninstantiated template. 11436 if (Target) { 11437 const FunctionDecl *FNTarget = 0; 11438 (void)Target->hasBody(FNTarget); 11439 Target = const_cast<CXXConstructorDecl*>( 11440 cast_or_null<CXXConstructorDecl>(FNTarget)); 11441 } 11442 11443 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 11444 // Avoid dereferencing a null pointer here. 11445 *TCanonical = Target ? Target->getCanonicalDecl() : 0; 11446 11447 if (!Current.insert(Canonical)) 11448 return; 11449 11450 // We know that beyond here, we aren't chaining into a cycle. 11451 if (!Target || !Target->isDelegatingConstructor() || 11452 Target->isInvalidDecl() || Valid.count(TCanonical)) { 11453 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI) 11454 Valid.insert(*CI); 11455 Current.clear(); 11456 // We've hit a cycle. 11457 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 11458 Current.count(TCanonical)) { 11459 // If we haven't diagnosed this cycle yet, do so now. 11460 if (!Invalid.count(TCanonical)) { 11461 S.Diag((*Ctor->init_begin())->getSourceLocation(), 11462 diag::warn_delegating_ctor_cycle) 11463 << Ctor; 11464 11465 // Don't add a note for a function delegating directly to itself. 11466 if (TCanonical != Canonical) 11467 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 11468 11469 CXXConstructorDecl *C = Target; 11470 while (C->getCanonicalDecl() != Canonical) { 11471 const FunctionDecl *FNTarget = 0; 11472 (void)C->getTargetConstructor()->hasBody(FNTarget); 11473 assert(FNTarget && "Ctor cycle through bodiless function"); 11474 11475 C = const_cast<CXXConstructorDecl*>( 11476 cast<CXXConstructorDecl>(FNTarget)); 11477 S.Diag(C->getLocation(), diag::note_which_delegates_to); 11478 } 11479 } 11480 11481 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI) 11482 Invalid.insert(*CI); 11483 Current.clear(); 11484 } else { 11485 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 11486 } 11487} 11488 11489 11490void Sema::CheckDelegatingCtorCycles() { 11491 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 11492 11493 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(), 11494 CE = Current.end(); 11495 11496 for (DelegatingCtorDeclsType::iterator 11497 I = DelegatingCtorDecls.begin(ExternalSource), 11498 E = DelegatingCtorDecls.end(); 11499 I != E; ++I) 11500 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 11501 11502 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI) 11503 (*CI)->setInvalidDecl(); 11504} 11505 11506namespace { 11507 /// \brief AST visitor that finds references to the 'this' expression. 11508 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 11509 Sema &S; 11510 11511 public: 11512 explicit FindCXXThisExpr(Sema &S) : S(S) { } 11513 11514 bool VisitCXXThisExpr(CXXThisExpr *E) { 11515 S.Diag(E->getLocation(), diag::err_this_static_member_func) 11516 << E->isImplicit(); 11517 return false; 11518 } 11519 }; 11520} 11521 11522bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 11523 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 11524 if (!TSInfo) 11525 return false; 11526 11527 TypeLoc TL = TSInfo->getTypeLoc(); 11528 FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL); 11529 if (!ProtoTL) 11530 return false; 11531 11532 // C++11 [expr.prim.general]p3: 11533 // [The expression this] shall not appear before the optional 11534 // cv-qualifier-seq and it shall not appear within the declaration of a 11535 // static member function (although its type and value category are defined 11536 // within a static member function as they are within a non-static member 11537 // function). [ Note: this is because declaration matching does not occur 11538 // until the complete declarator is known. - end note ] 11539 const FunctionProtoType *Proto = ProtoTL->getTypePtr(); 11540 FindCXXThisExpr Finder(*this); 11541 11542 // If the return type came after the cv-qualifier-seq, check it now. 11543 if (Proto->hasTrailingReturn() && 11544 !Finder.TraverseTypeLoc(ProtoTL->getResultLoc())) 11545 return true; 11546 11547 // Check the exception specification. 11548 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 11549 return true; 11550 11551 return checkThisInStaticMemberFunctionAttributes(Method); 11552} 11553 11554bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 11555 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 11556 if (!TSInfo) 11557 return false; 11558 11559 TypeLoc TL = TSInfo->getTypeLoc(); 11560 FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL); 11561 if (!ProtoTL) 11562 return false; 11563 11564 const FunctionProtoType *Proto = ProtoTL->getTypePtr(); 11565 FindCXXThisExpr Finder(*this); 11566 11567 switch (Proto->getExceptionSpecType()) { 11568 case EST_Uninstantiated: 11569 case EST_Unevaluated: 11570 case EST_BasicNoexcept: 11571 case EST_DynamicNone: 11572 case EST_MSAny: 11573 case EST_None: 11574 break; 11575 11576 case EST_ComputedNoexcept: 11577 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 11578 return true; 11579 11580 case EST_Dynamic: 11581 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(), 11582 EEnd = Proto->exception_end(); 11583 E != EEnd; ++E) { 11584 if (!Finder.TraverseType(*E)) 11585 return true; 11586 } 11587 break; 11588 } 11589 11590 return false; 11591} 11592 11593bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 11594 FindCXXThisExpr Finder(*this); 11595 11596 // Check attributes. 11597 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end(); 11598 A != AEnd; ++A) { 11599 // FIXME: This should be emitted by tblgen. 11600 Expr *Arg = 0; 11601 ArrayRef<Expr *> Args; 11602 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A)) 11603 Arg = G->getArg(); 11604 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A)) 11605 Arg = G->getArg(); 11606 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A)) 11607 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size()); 11608 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A)) 11609 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size()); 11610 else if (ExclusiveLockFunctionAttr *ELF 11611 = dyn_cast<ExclusiveLockFunctionAttr>(*A)) 11612 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size()); 11613 else if (SharedLockFunctionAttr *SLF 11614 = dyn_cast<SharedLockFunctionAttr>(*A)) 11615 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size()); 11616 else if (ExclusiveTrylockFunctionAttr *ETLF 11617 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) { 11618 Arg = ETLF->getSuccessValue(); 11619 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size()); 11620 } else if (SharedTrylockFunctionAttr *STLF 11621 = dyn_cast<SharedTrylockFunctionAttr>(*A)) { 11622 Arg = STLF->getSuccessValue(); 11623 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size()); 11624 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A)) 11625 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size()); 11626 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A)) 11627 Arg = LR->getArg(); 11628 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A)) 11629 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size()); 11630 else if (ExclusiveLocksRequiredAttr *ELR 11631 = dyn_cast<ExclusiveLocksRequiredAttr>(*A)) 11632 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size()); 11633 else if (SharedLocksRequiredAttr *SLR 11634 = dyn_cast<SharedLocksRequiredAttr>(*A)) 11635 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size()); 11636 11637 if (Arg && !Finder.TraverseStmt(Arg)) 11638 return true; 11639 11640 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 11641 if (!Finder.TraverseStmt(Args[I])) 11642 return true; 11643 } 11644 } 11645 11646 return false; 11647} 11648 11649void 11650Sema::checkExceptionSpecification(ExceptionSpecificationType EST, 11651 ArrayRef<ParsedType> DynamicExceptions, 11652 ArrayRef<SourceRange> DynamicExceptionRanges, 11653 Expr *NoexceptExpr, 11654 SmallVectorImpl<QualType> &Exceptions, 11655 FunctionProtoType::ExtProtoInfo &EPI) { 11656 Exceptions.clear(); 11657 EPI.ExceptionSpecType = EST; 11658 if (EST == EST_Dynamic) { 11659 Exceptions.reserve(DynamicExceptions.size()); 11660 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 11661 // FIXME: Preserve type source info. 11662 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 11663 11664 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 11665 collectUnexpandedParameterPacks(ET, Unexpanded); 11666 if (!Unexpanded.empty()) { 11667 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(), 11668 UPPC_ExceptionType, 11669 Unexpanded); 11670 continue; 11671 } 11672 11673 // Check that the type is valid for an exception spec, and 11674 // drop it if not. 11675 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 11676 Exceptions.push_back(ET); 11677 } 11678 EPI.NumExceptions = Exceptions.size(); 11679 EPI.Exceptions = Exceptions.data(); 11680 return; 11681 } 11682 11683 if (EST == EST_ComputedNoexcept) { 11684 // If an error occurred, there's no expression here. 11685 if (NoexceptExpr) { 11686 assert((NoexceptExpr->isTypeDependent() || 11687 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 11688 Context.BoolTy) && 11689 "Parser should have made sure that the expression is boolean"); 11690 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 11691 EPI.ExceptionSpecType = EST_BasicNoexcept; 11692 return; 11693 } 11694 11695 if (!NoexceptExpr->isValueDependent()) 11696 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0, 11697 diag::err_noexcept_needs_constant_expression, 11698 /*AllowFold*/ false).take(); 11699 EPI.NoexceptExpr = NoexceptExpr; 11700 } 11701 return; 11702 } 11703} 11704 11705/// IdentifyCUDATarget - Determine the CUDA compilation target for this function 11706Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) { 11707 // Implicitly declared functions (e.g. copy constructors) are 11708 // __host__ __device__ 11709 if (D->isImplicit()) 11710 return CFT_HostDevice; 11711 11712 if (D->hasAttr<CUDAGlobalAttr>()) 11713 return CFT_Global; 11714 11715 if (D->hasAttr<CUDADeviceAttr>()) { 11716 if (D->hasAttr<CUDAHostAttr>()) 11717 return CFT_HostDevice; 11718 else 11719 return CFT_Device; 11720 } 11721 11722 return CFT_Host; 11723} 11724 11725bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget, 11726 CUDAFunctionTarget CalleeTarget) { 11727 // CUDA B.1.1 "The __device__ qualifier declares a function that is... 11728 // Callable from the device only." 11729 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device) 11730 return true; 11731 11732 // CUDA B.1.2 "The __global__ qualifier declares a function that is... 11733 // Callable from the host only." 11734 // CUDA B.1.3 "The __host__ qualifier declares a function that is... 11735 // Callable from the host only." 11736 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) && 11737 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global)) 11738 return true; 11739 11740 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice) 11741 return true; 11742 11743 return false; 11744} 11745