SemaDeclCXX.cpp revision 08235661cf457978ba4645ec8e22697aebabe4fa
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/ASTLambda.h" 18#include "clang/AST/ASTMutationListener.h" 19#include "clang/AST/CXXInheritance.h" 20#include "clang/AST/CharUnits.h" 21#include "clang/AST/DeclVisitor.h" 22#include "clang/AST/EvaluatedExprVisitor.h" 23#include "clang/AST/ExprCXX.h" 24#include "clang/AST/RecordLayout.h" 25#include "clang/AST/RecursiveASTVisitor.h" 26#include "clang/AST/StmtVisitor.h" 27#include "clang/AST/TypeLoc.h" 28#include "clang/AST/TypeOrdering.h" 29#include "clang/Basic/PartialDiagnostic.h" 30#include "clang/Basic/TargetInfo.h" 31#include "clang/Lex/LiteralSupport.h" 32#include "clang/Lex/Preprocessor.h" 33#include "clang/Sema/CXXFieldCollector.h" 34#include "clang/Sema/DeclSpec.h" 35#include "clang/Sema/Initialization.h" 36#include "clang/Sema/Lookup.h" 37#include "clang/Sema/ParsedTemplate.h" 38#include "clang/Sema/Scope.h" 39#include "clang/Sema/ScopeInfo.h" 40#include "llvm/ADT/STLExtras.h" 41#include "llvm/ADT/SmallString.h" 42#include <map> 43#include <set> 44 45using namespace clang; 46 47//===----------------------------------------------------------------------===// 48// CheckDefaultArgumentVisitor 49//===----------------------------------------------------------------------===// 50 51namespace { 52 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 53 /// the default argument of a parameter to determine whether it 54 /// contains any ill-formed subexpressions. For example, this will 55 /// diagnose the use of local variables or parameters within the 56 /// default argument expression. 57 class CheckDefaultArgumentVisitor 58 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 59 Expr *DefaultArg; 60 Sema *S; 61 62 public: 63 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 64 : DefaultArg(defarg), S(s) {} 65 66 bool VisitExpr(Expr *Node); 67 bool VisitDeclRefExpr(DeclRefExpr *DRE); 68 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 69 bool VisitLambdaExpr(LambdaExpr *Lambda); 70 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE); 71 }; 72 73 /// VisitExpr - Visit all of the children of this expression. 74 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 75 bool IsInvalid = false; 76 for (Stmt::child_range I = Node->children(); I; ++I) 77 IsInvalid |= Visit(*I); 78 return IsInvalid; 79 } 80 81 /// VisitDeclRefExpr - Visit a reference to a declaration, to 82 /// determine whether this declaration can be used in the default 83 /// argument expression. 84 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 85 NamedDecl *Decl = DRE->getDecl(); 86 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 87 // C++ [dcl.fct.default]p9 88 // Default arguments are evaluated each time the function is 89 // called. The order of evaluation of function arguments is 90 // unspecified. Consequently, parameters of a function shall not 91 // be used in default argument expressions, even if they are not 92 // evaluated. Parameters of a function declared before a default 93 // argument expression are in scope and can hide namespace and 94 // class member names. 95 return S->Diag(DRE->getLocStart(), 96 diag::err_param_default_argument_references_param) 97 << Param->getDeclName() << DefaultArg->getSourceRange(); 98 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 99 // C++ [dcl.fct.default]p7 100 // Local variables shall not be used in default argument 101 // expressions. 102 if (VDecl->isLocalVarDecl()) 103 return S->Diag(DRE->getLocStart(), 104 diag::err_param_default_argument_references_local) 105 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 106 } 107 108 return false; 109 } 110 111 /// VisitCXXThisExpr - Visit a C++ "this" expression. 112 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 113 // C++ [dcl.fct.default]p8: 114 // The keyword this shall not be used in a default argument of a 115 // member function. 116 return S->Diag(ThisE->getLocStart(), 117 diag::err_param_default_argument_references_this) 118 << ThisE->getSourceRange(); 119 } 120 121 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) { 122 bool Invalid = false; 123 for (PseudoObjectExpr::semantics_iterator 124 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) { 125 Expr *E = *i; 126 127 // Look through bindings. 128 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 129 E = OVE->getSourceExpr(); 130 assert(E && "pseudo-object binding without source expression?"); 131 } 132 133 Invalid |= Visit(E); 134 } 135 return Invalid; 136 } 137 138 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) { 139 // C++11 [expr.lambda.prim]p13: 140 // A lambda-expression appearing in a default argument shall not 141 // implicitly or explicitly capture any entity. 142 if (Lambda->capture_begin() == Lambda->capture_end()) 143 return false; 144 145 return S->Diag(Lambda->getLocStart(), 146 diag::err_lambda_capture_default_arg); 147 } 148} 149 150void 151Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc, 152 const CXXMethodDecl *Method) { 153 // If we have an MSAny spec already, don't bother. 154 if (!Method || ComputedEST == EST_MSAny) 155 return; 156 157 const FunctionProtoType *Proto 158 = Method->getType()->getAs<FunctionProtoType>(); 159 Proto = Self->ResolveExceptionSpec(CallLoc, Proto); 160 if (!Proto) 161 return; 162 163 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 164 165 // If this function can throw any exceptions, make a note of that. 166 if (EST == EST_MSAny || EST == EST_None) { 167 ClearExceptions(); 168 ComputedEST = EST; 169 return; 170 } 171 172 // FIXME: If the call to this decl is using any of its default arguments, we 173 // need to search them for potentially-throwing calls. 174 175 // If this function has a basic noexcept, it doesn't affect the outcome. 176 if (EST == EST_BasicNoexcept) 177 return; 178 179 // If we have a throw-all spec at this point, ignore the function. 180 if (ComputedEST == EST_None) 181 return; 182 183 // If we're still at noexcept(true) and there's a nothrow() callee, 184 // change to that specification. 185 if (EST == EST_DynamicNone) { 186 if (ComputedEST == EST_BasicNoexcept) 187 ComputedEST = EST_DynamicNone; 188 return; 189 } 190 191 // Check out noexcept specs. 192 if (EST == EST_ComputedNoexcept) { 193 FunctionProtoType::NoexceptResult NR = 194 Proto->getNoexceptSpec(Self->Context); 195 assert(NR != FunctionProtoType::NR_NoNoexcept && 196 "Must have noexcept result for EST_ComputedNoexcept."); 197 assert(NR != FunctionProtoType::NR_Dependent && 198 "Should not generate implicit declarations for dependent cases, " 199 "and don't know how to handle them anyway."); 200 201 // noexcept(false) -> no spec on the new function 202 if (NR == FunctionProtoType::NR_Throw) { 203 ClearExceptions(); 204 ComputedEST = EST_None; 205 } 206 // noexcept(true) won't change anything either. 207 return; 208 } 209 210 assert(EST == EST_Dynamic && "EST case not considered earlier."); 211 assert(ComputedEST != EST_None && 212 "Shouldn't collect exceptions when throw-all is guaranteed."); 213 ComputedEST = EST_Dynamic; 214 // Record the exceptions in this function's exception specification. 215 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(), 216 EEnd = Proto->exception_end(); 217 E != EEnd; ++E) 218 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E))) 219 Exceptions.push_back(*E); 220} 221 222void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) { 223 if (!E || ComputedEST == EST_MSAny) 224 return; 225 226 // FIXME: 227 // 228 // C++0x [except.spec]p14: 229 // [An] implicit exception-specification specifies the type-id T if and 230 // only if T is allowed by the exception-specification of a function directly 231 // invoked by f's implicit definition; f shall allow all exceptions if any 232 // function it directly invokes allows all exceptions, and f shall allow no 233 // exceptions if every function it directly invokes allows no exceptions. 234 // 235 // Note in particular that if an implicit exception-specification is generated 236 // for a function containing a throw-expression, that specification can still 237 // be noexcept(true). 238 // 239 // Note also that 'directly invoked' is not defined in the standard, and there 240 // is no indication that we should only consider potentially-evaluated calls. 241 // 242 // Ultimately we should implement the intent of the standard: the exception 243 // specification should be the set of exceptions which can be thrown by the 244 // implicit definition. For now, we assume that any non-nothrow expression can 245 // throw any exception. 246 247 if (Self->canThrow(E)) 248 ComputedEST = EST_None; 249} 250 251bool 252Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 253 SourceLocation EqualLoc) { 254 if (RequireCompleteType(Param->getLocation(), Param->getType(), 255 diag::err_typecheck_decl_incomplete_type)) { 256 Param->setInvalidDecl(); 257 return true; 258 } 259 260 // C++ [dcl.fct.default]p5 261 // A default argument expression is implicitly converted (clause 262 // 4) to the parameter type. The default argument expression has 263 // the same semantic constraints as the initializer expression in 264 // a declaration of a variable of the parameter type, using the 265 // copy-initialization semantics (8.5). 266 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 267 Param); 268 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 269 EqualLoc); 270 InitializationSequence InitSeq(*this, Entity, Kind, Arg); 271 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); 272 if (Result.isInvalid()) 273 return true; 274 Arg = Result.takeAs<Expr>(); 275 276 CheckCompletedExpr(Arg, EqualLoc); 277 Arg = MaybeCreateExprWithCleanups(Arg); 278 279 // Okay: add the default argument to the parameter 280 Param->setDefaultArg(Arg); 281 282 // We have already instantiated this parameter; provide each of the 283 // instantiations with the uninstantiated default argument. 284 UnparsedDefaultArgInstantiationsMap::iterator InstPos 285 = UnparsedDefaultArgInstantiations.find(Param); 286 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 287 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 288 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 289 290 // We're done tracking this parameter's instantiations. 291 UnparsedDefaultArgInstantiations.erase(InstPos); 292 } 293 294 return false; 295} 296 297/// ActOnParamDefaultArgument - Check whether the default argument 298/// provided for a function parameter is well-formed. If so, attach it 299/// to the parameter declaration. 300void 301Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 302 Expr *DefaultArg) { 303 if (!param || !DefaultArg) 304 return; 305 306 ParmVarDecl *Param = cast<ParmVarDecl>(param); 307 UnparsedDefaultArgLocs.erase(Param); 308 309 // Default arguments are only permitted in C++ 310 if (!getLangOpts().CPlusPlus) { 311 Diag(EqualLoc, diag::err_param_default_argument) 312 << DefaultArg->getSourceRange(); 313 Param->setInvalidDecl(); 314 return; 315 } 316 317 // Check for unexpanded parameter packs. 318 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 319 Param->setInvalidDecl(); 320 return; 321 } 322 323 // Check that the default argument is well-formed 324 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this); 325 if (DefaultArgChecker.Visit(DefaultArg)) { 326 Param->setInvalidDecl(); 327 return; 328 } 329 330 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 331} 332 333/// ActOnParamUnparsedDefaultArgument - We've seen a default 334/// argument for a function parameter, but we can't parse it yet 335/// because we're inside a class definition. Note that this default 336/// argument will be parsed later. 337void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 338 SourceLocation EqualLoc, 339 SourceLocation ArgLoc) { 340 if (!param) 341 return; 342 343 ParmVarDecl *Param = cast<ParmVarDecl>(param); 344 Param->setUnparsedDefaultArg(); 345 UnparsedDefaultArgLocs[Param] = ArgLoc; 346} 347 348/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 349/// the default argument for the parameter param failed. 350void Sema::ActOnParamDefaultArgumentError(Decl *param) { 351 if (!param) 352 return; 353 354 ParmVarDecl *Param = cast<ParmVarDecl>(param); 355 Param->setInvalidDecl(); 356 UnparsedDefaultArgLocs.erase(Param); 357} 358 359/// CheckExtraCXXDefaultArguments - Check for any extra default 360/// arguments in the declarator, which is not a function declaration 361/// or definition and therefore is not permitted to have default 362/// arguments. This routine should be invoked for every declarator 363/// that is not a function declaration or definition. 364void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 365 // C++ [dcl.fct.default]p3 366 // A default argument expression shall be specified only in the 367 // parameter-declaration-clause of a function declaration or in a 368 // template-parameter (14.1). It shall not be specified for a 369 // parameter pack. If it is specified in a 370 // parameter-declaration-clause, it shall not occur within a 371 // declarator or abstract-declarator of a parameter-declaration. 372 bool MightBeFunction = D.isFunctionDeclarationContext(); 373 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 374 DeclaratorChunk &chunk = D.getTypeObject(i); 375 if (chunk.Kind == DeclaratorChunk::Function) { 376 if (MightBeFunction) { 377 // This is a function declaration. It can have default arguments, but 378 // keep looking in case its return type is a function type with default 379 // arguments. 380 MightBeFunction = false; 381 continue; 382 } 383 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) { 384 ParmVarDecl *Param = 385 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param); 386 if (Param->hasUnparsedDefaultArg()) { 387 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens; 388 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 389 << SourceRange((*Toks)[1].getLocation(), 390 Toks->back().getLocation()); 391 delete Toks; 392 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0; 393 } else if (Param->getDefaultArg()) { 394 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 395 << Param->getDefaultArg()->getSourceRange(); 396 Param->setDefaultArg(0); 397 } 398 } 399 } else if (chunk.Kind != DeclaratorChunk::Paren) { 400 MightBeFunction = false; 401 } 402 } 403} 404 405static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { 406 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) { 407 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1); 408 if (!PVD->hasDefaultArg()) 409 return false; 410 if (!PVD->hasInheritedDefaultArg()) 411 return true; 412 } 413 return false; 414} 415 416/// MergeCXXFunctionDecl - Merge two declarations of the same C++ 417/// function, once we already know that they have the same 418/// type. Subroutine of MergeFunctionDecl. Returns true if there was an 419/// error, false otherwise. 420bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 421 Scope *S) { 422 bool Invalid = false; 423 424 // C++ [dcl.fct.default]p4: 425 // For non-template functions, default arguments can be added in 426 // later declarations of a function in the same 427 // scope. Declarations in different scopes have completely 428 // distinct sets of default arguments. That is, declarations in 429 // inner scopes do not acquire default arguments from 430 // declarations in outer scopes, and vice versa. In a given 431 // function declaration, all parameters subsequent to a 432 // parameter with a default argument shall have default 433 // arguments supplied in this or previous declarations. A 434 // default argument shall not be redefined by a later 435 // declaration (not even to the same value). 436 // 437 // C++ [dcl.fct.default]p6: 438 // Except for member functions of class templates, the default arguments 439 // in a member function definition that appears outside of the class 440 // definition are added to the set of default arguments provided by the 441 // member function declaration in the class definition. 442 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 443 ParmVarDecl *OldParam = Old->getParamDecl(p); 444 ParmVarDecl *NewParam = New->getParamDecl(p); 445 446 bool OldParamHasDfl = OldParam->hasDefaultArg(); 447 bool NewParamHasDfl = NewParam->hasDefaultArg(); 448 449 NamedDecl *ND = Old; 450 451 // The declaration context corresponding to the scope is the semantic 452 // parent, unless this is a local function declaration, in which case 453 // it is that surrounding function. 454 DeclContext *ScopeDC = New->getLexicalDeclContext(); 455 if (!ScopeDC->isFunctionOrMethod()) 456 ScopeDC = New->getDeclContext(); 457 if (S && !isDeclInScope(ND, ScopeDC, S) && 458 !New->getDeclContext()->isRecord()) 459 // Ignore default parameters of old decl if they are not in 460 // the same scope and this is not an out-of-line definition of 461 // a member function. 462 OldParamHasDfl = false; 463 464 if (OldParamHasDfl && NewParamHasDfl) { 465 466 unsigned DiagDefaultParamID = 467 diag::err_param_default_argument_redefinition; 468 469 // MSVC accepts that default parameters be redefined for member functions 470 // of template class. The new default parameter's value is ignored. 471 Invalid = true; 472 if (getLangOpts().MicrosoftExt) { 473 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New); 474 if (MD && MD->getParent()->getDescribedClassTemplate()) { 475 // Merge the old default argument into the new parameter. 476 NewParam->setHasInheritedDefaultArg(); 477 if (OldParam->hasUninstantiatedDefaultArg()) 478 NewParam->setUninstantiatedDefaultArg( 479 OldParam->getUninstantiatedDefaultArg()); 480 else 481 NewParam->setDefaultArg(OldParam->getInit()); 482 DiagDefaultParamID = diag::warn_param_default_argument_redefinition; 483 Invalid = false; 484 } 485 } 486 487 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 488 // hint here. Alternatively, we could walk the type-source information 489 // for NewParam to find the last source location in the type... but it 490 // isn't worth the effort right now. This is the kind of test case that 491 // is hard to get right: 492 // int f(int); 493 // void g(int (*fp)(int) = f); 494 // void g(int (*fp)(int) = &f); 495 Diag(NewParam->getLocation(), DiagDefaultParamID) 496 << NewParam->getDefaultArgRange(); 497 498 // Look for the function declaration where the default argument was 499 // actually written, which may be a declaration prior to Old. 500 for (FunctionDecl *Older = Old->getPreviousDecl(); 501 Older; Older = Older->getPreviousDecl()) { 502 if (!Older->getParamDecl(p)->hasDefaultArg()) 503 break; 504 505 OldParam = Older->getParamDecl(p); 506 } 507 508 Diag(OldParam->getLocation(), diag::note_previous_definition) 509 << OldParam->getDefaultArgRange(); 510 } else if (OldParamHasDfl) { 511 // Merge the old default argument into the new parameter. 512 // It's important to use getInit() here; getDefaultArg() 513 // strips off any top-level ExprWithCleanups. 514 NewParam->setHasInheritedDefaultArg(); 515 if (OldParam->hasUninstantiatedDefaultArg()) 516 NewParam->setUninstantiatedDefaultArg( 517 OldParam->getUninstantiatedDefaultArg()); 518 else 519 NewParam->setDefaultArg(OldParam->getInit()); 520 } else if (NewParamHasDfl) { 521 if (New->getDescribedFunctionTemplate()) { 522 // Paragraph 4, quoted above, only applies to non-template functions. 523 Diag(NewParam->getLocation(), 524 diag::err_param_default_argument_template_redecl) 525 << NewParam->getDefaultArgRange(); 526 Diag(Old->getLocation(), diag::note_template_prev_declaration) 527 << false; 528 } else if (New->getTemplateSpecializationKind() 529 != TSK_ImplicitInstantiation && 530 New->getTemplateSpecializationKind() != TSK_Undeclared) { 531 // C++ [temp.expr.spec]p21: 532 // Default function arguments shall not be specified in a declaration 533 // or a definition for one of the following explicit specializations: 534 // - the explicit specialization of a function template; 535 // - the explicit specialization of a member function template; 536 // - the explicit specialization of a member function of a class 537 // template where the class template specialization to which the 538 // member function specialization belongs is implicitly 539 // instantiated. 540 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 541 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 542 << New->getDeclName() 543 << NewParam->getDefaultArgRange(); 544 } else if (New->getDeclContext()->isDependentContext()) { 545 // C++ [dcl.fct.default]p6 (DR217): 546 // Default arguments for a member function of a class template shall 547 // be specified on the initial declaration of the member function 548 // within the class template. 549 // 550 // Reading the tea leaves a bit in DR217 and its reference to DR205 551 // leads me to the conclusion that one cannot add default function 552 // arguments for an out-of-line definition of a member function of a 553 // dependent type. 554 int WhichKind = 2; 555 if (CXXRecordDecl *Record 556 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 557 if (Record->getDescribedClassTemplate()) 558 WhichKind = 0; 559 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 560 WhichKind = 1; 561 else 562 WhichKind = 2; 563 } 564 565 Diag(NewParam->getLocation(), 566 diag::err_param_default_argument_member_template_redecl) 567 << WhichKind 568 << NewParam->getDefaultArgRange(); 569 } 570 } 571 } 572 573 // DR1344: If a default argument is added outside a class definition and that 574 // default argument makes the function a special member function, the program 575 // is ill-formed. This can only happen for constructors. 576 if (isa<CXXConstructorDecl>(New) && 577 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 578 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 579 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 580 if (NewSM != OldSM) { 581 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 582 assert(NewParam->hasDefaultArg()); 583 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 584 << NewParam->getDefaultArgRange() << NewSM; 585 Diag(Old->getLocation(), diag::note_previous_declaration); 586 } 587 } 588 589 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 590 // template has a constexpr specifier then all its declarations shall 591 // contain the constexpr specifier. 592 if (New->isConstexpr() != Old->isConstexpr()) { 593 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 594 << New << New->isConstexpr(); 595 Diag(Old->getLocation(), diag::note_previous_declaration); 596 Invalid = true; 597 } 598 599 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 600 // argument expression, that declaration shall be a definition and shall be 601 // the only declaration of the function or function template in the 602 // translation unit. 603 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 604 functionDeclHasDefaultArgument(Old)) { 605 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 606 Diag(Old->getLocation(), diag::note_previous_declaration); 607 Invalid = true; 608 } 609 610 if (CheckEquivalentExceptionSpec(Old, New)) 611 Invalid = true; 612 613 return Invalid; 614} 615 616/// \brief Merge the exception specifications of two variable declarations. 617/// 618/// This is called when there's a redeclaration of a VarDecl. The function 619/// checks if the redeclaration might have an exception specification and 620/// validates compatibility and merges the specs if necessary. 621void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 622 // Shortcut if exceptions are disabled. 623 if (!getLangOpts().CXXExceptions) 624 return; 625 626 assert(Context.hasSameType(New->getType(), Old->getType()) && 627 "Should only be called if types are otherwise the same."); 628 629 QualType NewType = New->getType(); 630 QualType OldType = Old->getType(); 631 632 // We're only interested in pointers and references to functions, as well 633 // as pointers to member functions. 634 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 635 NewType = R->getPointeeType(); 636 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 637 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 638 NewType = P->getPointeeType(); 639 OldType = OldType->getAs<PointerType>()->getPointeeType(); 640 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 641 NewType = M->getPointeeType(); 642 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 643 } 644 645 if (!NewType->isFunctionProtoType()) 646 return; 647 648 // There's lots of special cases for functions. For function pointers, system 649 // libraries are hopefully not as broken so that we don't need these 650 // workarounds. 651 if (CheckEquivalentExceptionSpec( 652 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 653 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 654 New->setInvalidDecl(); 655 } 656} 657 658/// CheckCXXDefaultArguments - Verify that the default arguments for a 659/// function declaration are well-formed according to C++ 660/// [dcl.fct.default]. 661void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 662 unsigned NumParams = FD->getNumParams(); 663 unsigned p; 664 665 // Find first parameter with a default argument 666 for (p = 0; p < NumParams; ++p) { 667 ParmVarDecl *Param = FD->getParamDecl(p); 668 if (Param->hasDefaultArg()) 669 break; 670 } 671 672 // C++ [dcl.fct.default]p4: 673 // In a given function declaration, all parameters 674 // subsequent to a parameter with a default argument shall 675 // have default arguments supplied in this or previous 676 // declarations. A default argument shall not be redefined 677 // by a later declaration (not even to the same value). 678 unsigned LastMissingDefaultArg = 0; 679 for (; p < NumParams; ++p) { 680 ParmVarDecl *Param = FD->getParamDecl(p); 681 if (!Param->hasDefaultArg()) { 682 if (Param->isInvalidDecl()) 683 /* We already complained about this parameter. */; 684 else if (Param->getIdentifier()) 685 Diag(Param->getLocation(), 686 diag::err_param_default_argument_missing_name) 687 << Param->getIdentifier(); 688 else 689 Diag(Param->getLocation(), 690 diag::err_param_default_argument_missing); 691 692 LastMissingDefaultArg = p; 693 } 694 } 695 696 if (LastMissingDefaultArg > 0) { 697 // Some default arguments were missing. Clear out all of the 698 // default arguments up to (and including) the last missing 699 // default argument, so that we leave the function parameters 700 // in a semantically valid state. 701 for (p = 0; p <= LastMissingDefaultArg; ++p) { 702 ParmVarDecl *Param = FD->getParamDecl(p); 703 if (Param->hasDefaultArg()) { 704 Param->setDefaultArg(0); 705 } 706 } 707 } 708} 709 710// CheckConstexprParameterTypes - Check whether a function's parameter types 711// are all literal types. If so, return true. If not, produce a suitable 712// diagnostic and return false. 713static bool CheckConstexprParameterTypes(Sema &SemaRef, 714 const FunctionDecl *FD) { 715 unsigned ArgIndex = 0; 716 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 717 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(), 718 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) { 719 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 720 SourceLocation ParamLoc = PD->getLocation(); 721 if (!(*i)->isDependentType() && 722 SemaRef.RequireLiteralType(ParamLoc, *i, 723 diag::err_constexpr_non_literal_param, 724 ArgIndex+1, PD->getSourceRange(), 725 isa<CXXConstructorDecl>(FD))) 726 return false; 727 } 728 return true; 729} 730 731/// \brief Get diagnostic %select index for tag kind for 732/// record diagnostic message. 733/// WARNING: Indexes apply to particular diagnostics only! 734/// 735/// \returns diagnostic %select index. 736static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 737 switch (Tag) { 738 case TTK_Struct: return 0; 739 case TTK_Interface: return 1; 740 case TTK_Class: return 2; 741 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 742 } 743} 744 745// CheckConstexprFunctionDecl - Check whether a function declaration satisfies 746// the requirements of a constexpr function definition or a constexpr 747// constructor definition. If so, return true. If not, produce appropriate 748// diagnostics and return false. 749// 750// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 751bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) { 752 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 753 if (MD && MD->isInstance()) { 754 // C++11 [dcl.constexpr]p4: 755 // The definition of a constexpr constructor shall satisfy the following 756 // constraints: 757 // - the class shall not have any virtual base classes; 758 const CXXRecordDecl *RD = MD->getParent(); 759 if (RD->getNumVBases()) { 760 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 761 << isa<CXXConstructorDecl>(NewFD) 762 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 763 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(), 764 E = RD->vbases_end(); I != E; ++I) 765 Diag(I->getLocStart(), 766 diag::note_constexpr_virtual_base_here) << I->getSourceRange(); 767 return false; 768 } 769 } 770 771 if (!isa<CXXConstructorDecl>(NewFD)) { 772 // C++11 [dcl.constexpr]p3: 773 // The definition of a constexpr function shall satisfy the following 774 // constraints: 775 // - it shall not be virtual; 776 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 777 if (Method && Method->isVirtual()) { 778 Diag(NewFD->getLocation(), diag::err_constexpr_virtual); 779 780 // If it's not obvious why this function is virtual, find an overridden 781 // function which uses the 'virtual' keyword. 782 const CXXMethodDecl *WrittenVirtual = Method; 783 while (!WrittenVirtual->isVirtualAsWritten()) 784 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 785 if (WrittenVirtual != Method) 786 Diag(WrittenVirtual->getLocation(), 787 diag::note_overridden_virtual_function); 788 return false; 789 } 790 791 // - its return type shall be a literal type; 792 QualType RT = NewFD->getResultType(); 793 if (!RT->isDependentType() && 794 RequireLiteralType(NewFD->getLocation(), RT, 795 diag::err_constexpr_non_literal_return)) 796 return false; 797 } 798 799 // - each of its parameter types shall be a literal type; 800 if (!CheckConstexprParameterTypes(*this, NewFD)) 801 return false; 802 803 return true; 804} 805 806/// Check the given declaration statement is legal within a constexpr function 807/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 808/// 809/// \return true if the body is OK (maybe only as an extension), false if we 810/// have diagnosed a problem. 811static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 812 DeclStmt *DS, SourceLocation &Cxx1yLoc) { 813 // C++11 [dcl.constexpr]p3 and p4: 814 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 815 // contain only 816 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(), 817 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) { 818 switch ((*DclIt)->getKind()) { 819 case Decl::StaticAssert: 820 case Decl::Using: 821 case Decl::UsingShadow: 822 case Decl::UsingDirective: 823 case Decl::UnresolvedUsingTypename: 824 case Decl::UnresolvedUsingValue: 825 // - static_assert-declarations 826 // - using-declarations, 827 // - using-directives, 828 continue; 829 830 case Decl::Typedef: 831 case Decl::TypeAlias: { 832 // - typedef declarations and alias-declarations that do not define 833 // classes or enumerations, 834 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt); 835 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 836 // Don't allow variably-modified types in constexpr functions. 837 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 838 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 839 << TL.getSourceRange() << TL.getType() 840 << isa<CXXConstructorDecl>(Dcl); 841 return false; 842 } 843 continue; 844 } 845 846 case Decl::Enum: 847 case Decl::CXXRecord: 848 // C++1y allows types to be defined, not just declared. 849 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) 850 SemaRef.Diag(DS->getLocStart(), 851 SemaRef.getLangOpts().CPlusPlus1y 852 ? diag::warn_cxx11_compat_constexpr_type_definition 853 : diag::ext_constexpr_type_definition) 854 << isa<CXXConstructorDecl>(Dcl); 855 continue; 856 857 case Decl::EnumConstant: 858 case Decl::IndirectField: 859 case Decl::ParmVar: 860 // These can only appear with other declarations which are banned in 861 // C++11 and permitted in C++1y, so ignore them. 862 continue; 863 864 case Decl::Var: { 865 // C++1y [dcl.constexpr]p3 allows anything except: 866 // a definition of a variable of non-literal type or of static or 867 // thread storage duration or for which no initialization is performed. 868 VarDecl *VD = cast<VarDecl>(*DclIt); 869 if (VD->isThisDeclarationADefinition()) { 870 if (VD->isStaticLocal()) { 871 SemaRef.Diag(VD->getLocation(), 872 diag::err_constexpr_local_var_static) 873 << isa<CXXConstructorDecl>(Dcl) 874 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 875 return false; 876 } 877 if (!VD->getType()->isDependentType() && 878 SemaRef.RequireLiteralType( 879 VD->getLocation(), VD->getType(), 880 diag::err_constexpr_local_var_non_literal_type, 881 isa<CXXConstructorDecl>(Dcl))) 882 return false; 883 if (!VD->hasInit()) { 884 SemaRef.Diag(VD->getLocation(), 885 diag::err_constexpr_local_var_no_init) 886 << isa<CXXConstructorDecl>(Dcl); 887 return false; 888 } 889 } 890 SemaRef.Diag(VD->getLocation(), 891 SemaRef.getLangOpts().CPlusPlus1y 892 ? diag::warn_cxx11_compat_constexpr_local_var 893 : diag::ext_constexpr_local_var) 894 << isa<CXXConstructorDecl>(Dcl); 895 continue; 896 } 897 898 case Decl::NamespaceAlias: 899 case Decl::Function: 900 // These are disallowed in C++11 and permitted in C++1y. Allow them 901 // everywhere as an extension. 902 if (!Cxx1yLoc.isValid()) 903 Cxx1yLoc = DS->getLocStart(); 904 continue; 905 906 default: 907 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt) 908 << isa<CXXConstructorDecl>(Dcl); 909 return false; 910 } 911 } 912 913 return true; 914} 915 916/// Check that the given field is initialized within a constexpr constructor. 917/// 918/// \param Dcl The constexpr constructor being checked. 919/// \param Field The field being checked. This may be a member of an anonymous 920/// struct or union nested within the class being checked. 921/// \param Inits All declarations, including anonymous struct/union members and 922/// indirect members, for which any initialization was provided. 923/// \param Diagnosed Set to true if an error is produced. 924static void CheckConstexprCtorInitializer(Sema &SemaRef, 925 const FunctionDecl *Dcl, 926 FieldDecl *Field, 927 llvm::SmallSet<Decl*, 16> &Inits, 928 bool &Diagnosed) { 929 if (Field->isInvalidDecl()) 930 return; 931 932 if (Field->isUnnamedBitfield()) 933 return; 934 935 if (Field->isAnonymousStructOrUnion() && 936 Field->getType()->getAsCXXRecordDecl()->isEmpty()) 937 return; 938 939 if (!Inits.count(Field)) { 940 if (!Diagnosed) { 941 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init); 942 Diagnosed = true; 943 } 944 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init); 945 } else if (Field->isAnonymousStructOrUnion()) { 946 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 947 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end(); 948 I != E; ++I) 949 // If an anonymous union contains an anonymous struct of which any member 950 // is initialized, all members must be initialized. 951 if (!RD->isUnion() || Inits.count(*I)) 952 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed); 953 } 954} 955 956/// Check the provided statement is allowed in a constexpr function 957/// definition. 958static bool 959CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 960 SmallVectorImpl<SourceLocation> &ReturnStmts, 961 SourceLocation &Cxx1yLoc) { 962 // - its function-body shall be [...] a compound-statement that contains only 963 switch (S->getStmtClass()) { 964 case Stmt::NullStmtClass: 965 // - null statements, 966 return true; 967 968 case Stmt::DeclStmtClass: 969 // - static_assert-declarations 970 // - using-declarations, 971 // - using-directives, 972 // - typedef declarations and alias-declarations that do not define 973 // classes or enumerations, 974 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc)) 975 return false; 976 return true; 977 978 case Stmt::ReturnStmtClass: 979 // - and exactly one return statement; 980 if (isa<CXXConstructorDecl>(Dcl)) { 981 // C++1y allows return statements in constexpr constructors. 982 if (!Cxx1yLoc.isValid()) 983 Cxx1yLoc = S->getLocStart(); 984 return true; 985 } 986 987 ReturnStmts.push_back(S->getLocStart()); 988 return true; 989 990 case Stmt::CompoundStmtClass: { 991 // C++1y allows compound-statements. 992 if (!Cxx1yLoc.isValid()) 993 Cxx1yLoc = S->getLocStart(); 994 995 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 996 for (CompoundStmt::body_iterator BodyIt = CompStmt->body_begin(), 997 BodyEnd = CompStmt->body_end(); BodyIt != BodyEnd; ++BodyIt) { 998 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, *BodyIt, ReturnStmts, 999 Cxx1yLoc)) 1000 return false; 1001 } 1002 return true; 1003 } 1004 1005 case Stmt::AttributedStmtClass: 1006 if (!Cxx1yLoc.isValid()) 1007 Cxx1yLoc = S->getLocStart(); 1008 return true; 1009 1010 case Stmt::IfStmtClass: { 1011 // C++1y allows if-statements. 1012 if (!Cxx1yLoc.isValid()) 1013 Cxx1yLoc = S->getLocStart(); 1014 1015 IfStmt *If = cast<IfStmt>(S); 1016 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 1017 Cxx1yLoc)) 1018 return false; 1019 if (If->getElse() && 1020 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 1021 Cxx1yLoc)) 1022 return false; 1023 return true; 1024 } 1025 1026 case Stmt::WhileStmtClass: 1027 case Stmt::DoStmtClass: 1028 case Stmt::ForStmtClass: 1029 case Stmt::CXXForRangeStmtClass: 1030 case Stmt::ContinueStmtClass: 1031 // C++1y allows all of these. We don't allow them as extensions in C++11, 1032 // because they don't make sense without variable mutation. 1033 if (!SemaRef.getLangOpts().CPlusPlus1y) 1034 break; 1035 if (!Cxx1yLoc.isValid()) 1036 Cxx1yLoc = S->getLocStart(); 1037 for (Stmt::child_range Children = S->children(); Children; ++Children) 1038 if (*Children && 1039 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts, 1040 Cxx1yLoc)) 1041 return false; 1042 return true; 1043 1044 case Stmt::SwitchStmtClass: 1045 case Stmt::CaseStmtClass: 1046 case Stmt::DefaultStmtClass: 1047 case Stmt::BreakStmtClass: 1048 // C++1y allows switch-statements, and since they don't need variable 1049 // mutation, we can reasonably allow them in C++11 as an extension. 1050 if (!Cxx1yLoc.isValid()) 1051 Cxx1yLoc = S->getLocStart(); 1052 for (Stmt::child_range Children = S->children(); Children; ++Children) 1053 if (*Children && 1054 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts, 1055 Cxx1yLoc)) 1056 return false; 1057 return true; 1058 1059 default: 1060 if (!isa<Expr>(S)) 1061 break; 1062 1063 // C++1y allows expression-statements. 1064 if (!Cxx1yLoc.isValid()) 1065 Cxx1yLoc = S->getLocStart(); 1066 return true; 1067 } 1068 1069 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt) 1070 << isa<CXXConstructorDecl>(Dcl); 1071 return false; 1072} 1073 1074/// Check the body for the given constexpr function declaration only contains 1075/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 1076/// 1077/// \return true if the body is OK, false if we have diagnosed a problem. 1078bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) { 1079 if (isa<CXXTryStmt>(Body)) { 1080 // C++11 [dcl.constexpr]p3: 1081 // The definition of a constexpr function shall satisfy the following 1082 // constraints: [...] 1083 // - its function-body shall be = delete, = default, or a 1084 // compound-statement 1085 // 1086 // C++11 [dcl.constexpr]p4: 1087 // In the definition of a constexpr constructor, [...] 1088 // - its function-body shall not be a function-try-block; 1089 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block) 1090 << isa<CXXConstructorDecl>(Dcl); 1091 return false; 1092 } 1093 1094 SmallVector<SourceLocation, 4> ReturnStmts; 1095 1096 // - its function-body shall be [...] a compound-statement that contains only 1097 // [... list of cases ...] 1098 CompoundStmt *CompBody = cast<CompoundStmt>(Body); 1099 SourceLocation Cxx1yLoc; 1100 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(), 1101 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) { 1102 if (!CheckConstexprFunctionStmt(*this, Dcl, *BodyIt, ReturnStmts, Cxx1yLoc)) 1103 return false; 1104 } 1105 1106 if (Cxx1yLoc.isValid()) 1107 Diag(Cxx1yLoc, 1108 getLangOpts().CPlusPlus1y 1109 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 1110 : diag::ext_constexpr_body_invalid_stmt) 1111 << isa<CXXConstructorDecl>(Dcl); 1112 1113 if (const CXXConstructorDecl *Constructor 1114 = dyn_cast<CXXConstructorDecl>(Dcl)) { 1115 const CXXRecordDecl *RD = Constructor->getParent(); 1116 // DR1359: 1117 // - every non-variant non-static data member and base class sub-object 1118 // shall be initialized; 1119 // - if the class is a non-empty union, or for each non-empty anonymous 1120 // union member of a non-union class, exactly one non-static data member 1121 // shall be initialized; 1122 if (RD->isUnion()) { 1123 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) { 1124 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init); 1125 return false; 1126 } 1127 } else if (!Constructor->isDependentContext() && 1128 !Constructor->isDelegatingConstructor()) { 1129 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 1130 1131 // Skip detailed checking if we have enough initializers, and we would 1132 // allow at most one initializer per member. 1133 bool AnyAnonStructUnionMembers = false; 1134 unsigned Fields = 0; 1135 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 1136 E = RD->field_end(); I != E; ++I, ++Fields) { 1137 if (I->isAnonymousStructOrUnion()) { 1138 AnyAnonStructUnionMembers = true; 1139 break; 1140 } 1141 } 1142 if (AnyAnonStructUnionMembers || 1143 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 1144 // Check initialization of non-static data members. Base classes are 1145 // always initialized so do not need to be checked. Dependent bases 1146 // might not have initializers in the member initializer list. 1147 llvm::SmallSet<Decl*, 16> Inits; 1148 for (CXXConstructorDecl::init_const_iterator 1149 I = Constructor->init_begin(), E = Constructor->init_end(); 1150 I != E; ++I) { 1151 if (FieldDecl *FD = (*I)->getMember()) 1152 Inits.insert(FD); 1153 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember()) 1154 Inits.insert(ID->chain_begin(), ID->chain_end()); 1155 } 1156 1157 bool Diagnosed = false; 1158 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 1159 E = RD->field_end(); I != E; ++I) 1160 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed); 1161 if (Diagnosed) 1162 return false; 1163 } 1164 } 1165 } else { 1166 if (ReturnStmts.empty()) { 1167 // C++1y doesn't require constexpr functions to contain a 'return' 1168 // statement. We still do, unless the return type is void, because 1169 // otherwise if there's no return statement, the function cannot 1170 // be used in a core constant expression. 1171 bool OK = getLangOpts().CPlusPlus1y && Dcl->getResultType()->isVoidType(); 1172 Diag(Dcl->getLocation(), 1173 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 1174 : diag::err_constexpr_body_no_return); 1175 return OK; 1176 } 1177 if (ReturnStmts.size() > 1) { 1178 Diag(ReturnStmts.back(), 1179 getLangOpts().CPlusPlus1y 1180 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 1181 : diag::ext_constexpr_body_multiple_return); 1182 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 1183 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return); 1184 } 1185 } 1186 1187 // C++11 [dcl.constexpr]p5: 1188 // if no function argument values exist such that the function invocation 1189 // substitution would produce a constant expression, the program is 1190 // ill-formed; no diagnostic required. 1191 // C++11 [dcl.constexpr]p3: 1192 // - every constructor call and implicit conversion used in initializing the 1193 // return value shall be one of those allowed in a constant expression. 1194 // C++11 [dcl.constexpr]p4: 1195 // - every constructor involved in initializing non-static data members and 1196 // base class sub-objects shall be a constexpr constructor. 1197 SmallVector<PartialDiagnosticAt, 8> Diags; 1198 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) { 1199 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr) 1200 << isa<CXXConstructorDecl>(Dcl); 1201 for (size_t I = 0, N = Diags.size(); I != N; ++I) 1202 Diag(Diags[I].first, Diags[I].second); 1203 // Don't return false here: we allow this for compatibility in 1204 // system headers. 1205 } 1206 1207 return true; 1208} 1209 1210/// isCurrentClassName - Determine whether the identifier II is the 1211/// name of the class type currently being defined. In the case of 1212/// nested classes, this will only return true if II is the name of 1213/// the innermost class. 1214bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 1215 const CXXScopeSpec *SS) { 1216 assert(getLangOpts().CPlusPlus && "No class names in C!"); 1217 1218 CXXRecordDecl *CurDecl; 1219 if (SS && SS->isSet() && !SS->isInvalid()) { 1220 DeclContext *DC = computeDeclContext(*SS, true); 1221 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 1222 } else 1223 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1224 1225 if (CurDecl && CurDecl->getIdentifier()) 1226 return &II == CurDecl->getIdentifier(); 1227 return false; 1228} 1229 1230/// \brief Determine whether the identifier II is a typo for the name of 1231/// the class type currently being defined. If so, update it to the identifier 1232/// that should have been used. 1233bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 1234 assert(getLangOpts().CPlusPlus && "No class names in C!"); 1235 1236 if (!getLangOpts().SpellChecking) 1237 return false; 1238 1239 CXXRecordDecl *CurDecl; 1240 if (SS && SS->isSet() && !SS->isInvalid()) { 1241 DeclContext *DC = computeDeclContext(*SS, true); 1242 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 1243 } else 1244 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1245 1246 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 1247 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 1248 < II->getLength()) { 1249 II = CurDecl->getIdentifier(); 1250 return true; 1251 } 1252 1253 return false; 1254} 1255 1256/// \brief Determine whether the given class is a base class of the given 1257/// class, including looking at dependent bases. 1258static bool findCircularInheritance(const CXXRecordDecl *Class, 1259 const CXXRecordDecl *Current) { 1260 SmallVector<const CXXRecordDecl*, 8> Queue; 1261 1262 Class = Class->getCanonicalDecl(); 1263 while (true) { 1264 for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(), 1265 E = Current->bases_end(); 1266 I != E; ++I) { 1267 CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 1268 if (!Base) 1269 continue; 1270 1271 Base = Base->getDefinition(); 1272 if (!Base) 1273 continue; 1274 1275 if (Base->getCanonicalDecl() == Class) 1276 return true; 1277 1278 Queue.push_back(Base); 1279 } 1280 1281 if (Queue.empty()) 1282 return false; 1283 1284 Current = Queue.pop_back_val(); 1285 } 1286 1287 return false; 1288} 1289 1290/// \brief Check the validity of a C++ base class specifier. 1291/// 1292/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 1293/// and returns NULL otherwise. 1294CXXBaseSpecifier * 1295Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 1296 SourceRange SpecifierRange, 1297 bool Virtual, AccessSpecifier Access, 1298 TypeSourceInfo *TInfo, 1299 SourceLocation EllipsisLoc) { 1300 QualType BaseType = TInfo->getType(); 1301 1302 // C++ [class.union]p1: 1303 // A union shall not have base classes. 1304 if (Class->isUnion()) { 1305 Diag(Class->getLocation(), diag::err_base_clause_on_union) 1306 << SpecifierRange; 1307 return 0; 1308 } 1309 1310 if (EllipsisLoc.isValid() && 1311 !TInfo->getType()->containsUnexpandedParameterPack()) { 1312 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 1313 << TInfo->getTypeLoc().getSourceRange(); 1314 EllipsisLoc = SourceLocation(); 1315 } 1316 1317 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 1318 1319 if (BaseType->isDependentType()) { 1320 // Make sure that we don't have circular inheritance among our dependent 1321 // bases. For non-dependent bases, the check for completeness below handles 1322 // this. 1323 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 1324 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 1325 ((BaseDecl = BaseDecl->getDefinition()) && 1326 findCircularInheritance(Class, BaseDecl))) { 1327 Diag(BaseLoc, diag::err_circular_inheritance) 1328 << BaseType << Context.getTypeDeclType(Class); 1329 1330 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 1331 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 1332 << BaseType; 1333 1334 return 0; 1335 } 1336 } 1337 1338 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1339 Class->getTagKind() == TTK_Class, 1340 Access, TInfo, EllipsisLoc); 1341 } 1342 1343 // Base specifiers must be record types. 1344 if (!BaseType->isRecordType()) { 1345 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 1346 return 0; 1347 } 1348 1349 // C++ [class.union]p1: 1350 // A union shall not be used as a base class. 1351 if (BaseType->isUnionType()) { 1352 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 1353 return 0; 1354 } 1355 1356 // C++ [class.derived]p2: 1357 // The class-name in a base-specifier shall not be an incompletely 1358 // defined class. 1359 if (RequireCompleteType(BaseLoc, BaseType, 1360 diag::err_incomplete_base_class, SpecifierRange)) { 1361 Class->setInvalidDecl(); 1362 return 0; 1363 } 1364 1365 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 1366 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 1367 assert(BaseDecl && "Record type has no declaration"); 1368 BaseDecl = BaseDecl->getDefinition(); 1369 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 1370 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 1371 assert(CXXBaseDecl && "Base type is not a C++ type"); 1372 1373 // C++ [class]p3: 1374 // If a class is marked final and it appears as a base-type-specifier in 1375 // base-clause, the program is ill-formed. 1376 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 1377 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 1378 << CXXBaseDecl->getDeclName() 1379 << FA->isSpelledAsSealed(); 1380 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl) 1381 << CXXBaseDecl->getDeclName(); 1382 return 0; 1383 } 1384 1385 if (BaseDecl->isInvalidDecl()) 1386 Class->setInvalidDecl(); 1387 1388 // Create the base specifier. 1389 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1390 Class->getTagKind() == TTK_Class, 1391 Access, TInfo, EllipsisLoc); 1392} 1393 1394/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 1395/// one entry in the base class list of a class specifier, for 1396/// example: 1397/// class foo : public bar, virtual private baz { 1398/// 'public bar' and 'virtual private baz' are each base-specifiers. 1399BaseResult 1400Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 1401 ParsedAttributes &Attributes, 1402 bool Virtual, AccessSpecifier Access, 1403 ParsedType basetype, SourceLocation BaseLoc, 1404 SourceLocation EllipsisLoc) { 1405 if (!classdecl) 1406 return true; 1407 1408 AdjustDeclIfTemplate(classdecl); 1409 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 1410 if (!Class) 1411 return true; 1412 1413 // We do not support any C++11 attributes on base-specifiers yet. 1414 // Diagnose any attributes we see. 1415 if (!Attributes.empty()) { 1416 for (AttributeList *Attr = Attributes.getList(); Attr; 1417 Attr = Attr->getNext()) { 1418 if (Attr->isInvalid() || 1419 Attr->getKind() == AttributeList::IgnoredAttribute) 1420 continue; 1421 Diag(Attr->getLoc(), 1422 Attr->getKind() == AttributeList::UnknownAttribute 1423 ? diag::warn_unknown_attribute_ignored 1424 : diag::err_base_specifier_attribute) 1425 << Attr->getName(); 1426 } 1427 } 1428 1429 TypeSourceInfo *TInfo = 0; 1430 GetTypeFromParser(basetype, &TInfo); 1431 1432 if (EllipsisLoc.isInvalid() && 1433 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 1434 UPPC_BaseType)) 1435 return true; 1436 1437 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 1438 Virtual, Access, TInfo, 1439 EllipsisLoc)) 1440 return BaseSpec; 1441 else 1442 Class->setInvalidDecl(); 1443 1444 return true; 1445} 1446 1447/// \brief Performs the actual work of attaching the given base class 1448/// specifiers to a C++ class. 1449bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 1450 unsigned NumBases) { 1451 if (NumBases == 0) 1452 return false; 1453 1454 // Used to keep track of which base types we have already seen, so 1455 // that we can properly diagnose redundant direct base types. Note 1456 // that the key is always the unqualified canonical type of the base 1457 // class. 1458 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 1459 1460 // Copy non-redundant base specifiers into permanent storage. 1461 unsigned NumGoodBases = 0; 1462 bool Invalid = false; 1463 for (unsigned idx = 0; idx < NumBases; ++idx) { 1464 QualType NewBaseType 1465 = Context.getCanonicalType(Bases[idx]->getType()); 1466 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 1467 1468 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 1469 if (KnownBase) { 1470 // C++ [class.mi]p3: 1471 // A class shall not be specified as a direct base class of a 1472 // derived class more than once. 1473 Diag(Bases[idx]->getLocStart(), 1474 diag::err_duplicate_base_class) 1475 << KnownBase->getType() 1476 << Bases[idx]->getSourceRange(); 1477 1478 // Delete the duplicate base class specifier; we're going to 1479 // overwrite its pointer later. 1480 Context.Deallocate(Bases[idx]); 1481 1482 Invalid = true; 1483 } else { 1484 // Okay, add this new base class. 1485 KnownBase = Bases[idx]; 1486 Bases[NumGoodBases++] = Bases[idx]; 1487 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 1488 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 1489 if (Class->isInterface() && 1490 (!RD->isInterface() || 1491 KnownBase->getAccessSpecifier() != AS_public)) { 1492 // The Microsoft extension __interface does not permit bases that 1493 // are not themselves public interfaces. 1494 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface) 1495 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName() 1496 << RD->getSourceRange(); 1497 Invalid = true; 1498 } 1499 if (RD->hasAttr<WeakAttr>()) 1500 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context)); 1501 } 1502 } 1503 } 1504 1505 // Attach the remaining base class specifiers to the derived class. 1506 Class->setBases(Bases, NumGoodBases); 1507 1508 // Delete the remaining (good) base class specifiers, since their 1509 // data has been copied into the CXXRecordDecl. 1510 for (unsigned idx = 0; idx < NumGoodBases; ++idx) 1511 Context.Deallocate(Bases[idx]); 1512 1513 return Invalid; 1514} 1515 1516/// ActOnBaseSpecifiers - Attach the given base specifiers to the 1517/// class, after checking whether there are any duplicate base 1518/// classes. 1519void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases, 1520 unsigned NumBases) { 1521 if (!ClassDecl || !Bases || !NumBases) 1522 return; 1523 1524 AdjustDeclIfTemplate(ClassDecl); 1525 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases); 1526} 1527 1528/// \brief Determine whether the type \p Derived is a C++ class that is 1529/// derived from the type \p Base. 1530bool Sema::IsDerivedFrom(QualType Derived, QualType Base) { 1531 if (!getLangOpts().CPlusPlus) 1532 return false; 1533 1534 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1535 if (!DerivedRD) 1536 return false; 1537 1538 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1539 if (!BaseRD) 1540 return false; 1541 1542 // If either the base or the derived type is invalid, don't try to 1543 // check whether one is derived from the other. 1544 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 1545 return false; 1546 1547 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this. 1548 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD); 1549} 1550 1551/// \brief Determine whether the type \p Derived is a C++ class that is 1552/// derived from the type \p Base. 1553bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) { 1554 if (!getLangOpts().CPlusPlus) 1555 return false; 1556 1557 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1558 if (!DerivedRD) 1559 return false; 1560 1561 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1562 if (!BaseRD) 1563 return false; 1564 1565 return DerivedRD->isDerivedFrom(BaseRD, Paths); 1566} 1567 1568void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 1569 CXXCastPath &BasePathArray) { 1570 assert(BasePathArray.empty() && "Base path array must be empty!"); 1571 assert(Paths.isRecordingPaths() && "Must record paths!"); 1572 1573 const CXXBasePath &Path = Paths.front(); 1574 1575 // We first go backward and check if we have a virtual base. 1576 // FIXME: It would be better if CXXBasePath had the base specifier for 1577 // the nearest virtual base. 1578 unsigned Start = 0; 1579 for (unsigned I = Path.size(); I != 0; --I) { 1580 if (Path[I - 1].Base->isVirtual()) { 1581 Start = I - 1; 1582 break; 1583 } 1584 } 1585 1586 // Now add all bases. 1587 for (unsigned I = Start, E = Path.size(); I != E; ++I) 1588 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 1589} 1590 1591/// \brief Determine whether the given base path includes a virtual 1592/// base class. 1593bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) { 1594 for (CXXCastPath::const_iterator B = BasePath.begin(), 1595 BEnd = BasePath.end(); 1596 B != BEnd; ++B) 1597 if ((*B)->isVirtual()) 1598 return true; 1599 1600 return false; 1601} 1602 1603/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 1604/// conversion (where Derived and Base are class types) is 1605/// well-formed, meaning that the conversion is unambiguous (and 1606/// that all of the base classes are accessible). Returns true 1607/// and emits a diagnostic if the code is ill-formed, returns false 1608/// otherwise. Loc is the location where this routine should point to 1609/// if there is an error, and Range is the source range to highlight 1610/// if there is an error. 1611bool 1612Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1613 unsigned InaccessibleBaseID, 1614 unsigned AmbigiousBaseConvID, 1615 SourceLocation Loc, SourceRange Range, 1616 DeclarationName Name, 1617 CXXCastPath *BasePath) { 1618 // First, determine whether the path from Derived to Base is 1619 // ambiguous. This is slightly more expensive than checking whether 1620 // the Derived to Base conversion exists, because here we need to 1621 // explore multiple paths to determine if there is an ambiguity. 1622 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1623 /*DetectVirtual=*/false); 1624 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths); 1625 assert(DerivationOkay && 1626 "Can only be used with a derived-to-base conversion"); 1627 (void)DerivationOkay; 1628 1629 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 1630 if (InaccessibleBaseID) { 1631 // Check that the base class can be accessed. 1632 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(), 1633 InaccessibleBaseID)) { 1634 case AR_inaccessible: 1635 return true; 1636 case AR_accessible: 1637 case AR_dependent: 1638 case AR_delayed: 1639 break; 1640 } 1641 } 1642 1643 // Build a base path if necessary. 1644 if (BasePath) 1645 BuildBasePathArray(Paths, *BasePath); 1646 return false; 1647 } 1648 1649 if (AmbigiousBaseConvID) { 1650 // We know that the derived-to-base conversion is ambiguous, and 1651 // we're going to produce a diagnostic. Perform the derived-to-base 1652 // search just one more time to compute all of the possible paths so 1653 // that we can print them out. This is more expensive than any of 1654 // the previous derived-to-base checks we've done, but at this point 1655 // performance isn't as much of an issue. 1656 Paths.clear(); 1657 Paths.setRecordingPaths(true); 1658 bool StillOkay = IsDerivedFrom(Derived, Base, Paths); 1659 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 1660 (void)StillOkay; 1661 1662 // Build up a textual representation of the ambiguous paths, e.g., 1663 // D -> B -> A, that will be used to illustrate the ambiguous 1664 // conversions in the diagnostic. We only print one of the paths 1665 // to each base class subobject. 1666 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 1667 1668 Diag(Loc, AmbigiousBaseConvID) 1669 << Derived << Base << PathDisplayStr << Range << Name; 1670 } 1671 return true; 1672} 1673 1674bool 1675Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1676 SourceLocation Loc, SourceRange Range, 1677 CXXCastPath *BasePath, 1678 bool IgnoreAccess) { 1679 return CheckDerivedToBaseConversion(Derived, Base, 1680 IgnoreAccess ? 0 1681 : diag::err_upcast_to_inaccessible_base, 1682 diag::err_ambiguous_derived_to_base_conv, 1683 Loc, Range, DeclarationName(), 1684 BasePath); 1685} 1686 1687 1688/// @brief Builds a string representing ambiguous paths from a 1689/// specific derived class to different subobjects of the same base 1690/// class. 1691/// 1692/// This function builds a string that can be used in error messages 1693/// to show the different paths that one can take through the 1694/// inheritance hierarchy to go from the derived class to different 1695/// subobjects of a base class. The result looks something like this: 1696/// @code 1697/// struct D -> struct B -> struct A 1698/// struct D -> struct C -> struct A 1699/// @endcode 1700std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 1701 std::string PathDisplayStr; 1702 std::set<unsigned> DisplayedPaths; 1703 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 1704 Path != Paths.end(); ++Path) { 1705 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 1706 // We haven't displayed a path to this particular base 1707 // class subobject yet. 1708 PathDisplayStr += "\n "; 1709 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 1710 for (CXXBasePath::const_iterator Element = Path->begin(); 1711 Element != Path->end(); ++Element) 1712 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 1713 } 1714 } 1715 1716 return PathDisplayStr; 1717} 1718 1719//===----------------------------------------------------------------------===// 1720// C++ class member Handling 1721//===----------------------------------------------------------------------===// 1722 1723/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 1724bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, 1725 SourceLocation ASLoc, 1726 SourceLocation ColonLoc, 1727 AttributeList *Attrs) { 1728 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 1729 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 1730 ASLoc, ColonLoc); 1731 CurContext->addHiddenDecl(ASDecl); 1732 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 1733} 1734 1735/// CheckOverrideControl - Check C++11 override control semantics. 1736void Sema::CheckOverrideControl(NamedDecl *D) { 1737 if (D->isInvalidDecl()) 1738 return; 1739 1740 // We only care about "override" and "final" declarations. 1741 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 1742 return; 1743 1744 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 1745 1746 // We can't check dependent instance methods. 1747 if (MD && MD->isInstance() && 1748 (MD->getParent()->hasAnyDependentBases() || 1749 MD->getType()->isDependentType())) 1750 return; 1751 1752 if (MD && !MD->isVirtual()) { 1753 // If we have a non-virtual method, check if if hides a virtual method. 1754 // (In that case, it's most likely the method has the wrong type.) 1755 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 1756 FindHiddenVirtualMethods(MD, OverloadedMethods); 1757 1758 if (!OverloadedMethods.empty()) { 1759 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1760 Diag(OA->getLocation(), 1761 diag::override_keyword_hides_virtual_member_function) 1762 << "override" << (OverloadedMethods.size() > 1); 1763 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1764 Diag(FA->getLocation(), 1765 diag::override_keyword_hides_virtual_member_function) 1766 << (FA->isSpelledAsSealed() ? "sealed" : "final") 1767 << (OverloadedMethods.size() > 1); 1768 } 1769 NoteHiddenVirtualMethods(MD, OverloadedMethods); 1770 MD->setInvalidDecl(); 1771 return; 1772 } 1773 // Fall through into the general case diagnostic. 1774 // FIXME: We might want to attempt typo correction here. 1775 } 1776 1777 if (!MD || !MD->isVirtual()) { 1778 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1779 Diag(OA->getLocation(), 1780 diag::override_keyword_only_allowed_on_virtual_member_functions) 1781 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 1782 D->dropAttr<OverrideAttr>(); 1783 } 1784 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1785 Diag(FA->getLocation(), 1786 diag::override_keyword_only_allowed_on_virtual_member_functions) 1787 << (FA->isSpelledAsSealed() ? "sealed" : "final") 1788 << FixItHint::CreateRemoval(FA->getLocation()); 1789 D->dropAttr<FinalAttr>(); 1790 } 1791 return; 1792 } 1793 1794 // C++11 [class.virtual]p5: 1795 // If a virtual function is marked with the virt-specifier override and 1796 // does not override a member function of a base class, the program is 1797 // ill-formed. 1798 bool HasOverriddenMethods = 1799 MD->begin_overridden_methods() != MD->end_overridden_methods(); 1800 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 1801 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 1802 << MD->getDeclName(); 1803} 1804 1805/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 1806/// function overrides a virtual member function marked 'final', according to 1807/// C++11 [class.virtual]p4. 1808bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 1809 const CXXMethodDecl *Old) { 1810 FinalAttr *FA = Old->getAttr<FinalAttr>(); 1811 if (!FA) 1812 return false; 1813 1814 Diag(New->getLocation(), diag::err_final_function_overridden) 1815 << New->getDeclName() 1816 << FA->isSpelledAsSealed(); 1817 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 1818 return true; 1819} 1820 1821static bool InitializationHasSideEffects(const FieldDecl &FD) { 1822 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 1823 // FIXME: Destruction of ObjC lifetime types has side-effects. 1824 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 1825 return !RD->isCompleteDefinition() || 1826 !RD->hasTrivialDefaultConstructor() || 1827 !RD->hasTrivialDestructor(); 1828 return false; 1829} 1830 1831static AttributeList *getMSPropertyAttr(AttributeList *list) { 1832 for (AttributeList* it = list; it != 0; it = it->getNext()) 1833 if (it->isDeclspecPropertyAttribute()) 1834 return it; 1835 return 0; 1836} 1837 1838/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 1839/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 1840/// bitfield width if there is one, 'InitExpr' specifies the initializer if 1841/// one has been parsed, and 'InitStyle' is set if an in-class initializer is 1842/// present (but parsing it has been deferred). 1843NamedDecl * 1844Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 1845 MultiTemplateParamsArg TemplateParameterLists, 1846 Expr *BW, const VirtSpecifiers &VS, 1847 InClassInitStyle InitStyle) { 1848 const DeclSpec &DS = D.getDeclSpec(); 1849 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 1850 DeclarationName Name = NameInfo.getName(); 1851 SourceLocation Loc = NameInfo.getLoc(); 1852 1853 // For anonymous bitfields, the location should point to the type. 1854 if (Loc.isInvalid()) 1855 Loc = D.getLocStart(); 1856 1857 Expr *BitWidth = static_cast<Expr*>(BW); 1858 1859 assert(isa<CXXRecordDecl>(CurContext)); 1860 assert(!DS.isFriendSpecified()); 1861 1862 bool isFunc = D.isDeclarationOfFunction(); 1863 1864 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 1865 // The Microsoft extension __interface only permits public member functions 1866 // and prohibits constructors, destructors, operators, non-public member 1867 // functions, static methods and data members. 1868 unsigned InvalidDecl; 1869 bool ShowDeclName = true; 1870 if (!isFunc) 1871 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1; 1872 else if (AS != AS_public) 1873 InvalidDecl = 2; 1874 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 1875 InvalidDecl = 3; 1876 else switch (Name.getNameKind()) { 1877 case DeclarationName::CXXConstructorName: 1878 InvalidDecl = 4; 1879 ShowDeclName = false; 1880 break; 1881 1882 case DeclarationName::CXXDestructorName: 1883 InvalidDecl = 5; 1884 ShowDeclName = false; 1885 break; 1886 1887 case DeclarationName::CXXOperatorName: 1888 case DeclarationName::CXXConversionFunctionName: 1889 InvalidDecl = 6; 1890 break; 1891 1892 default: 1893 InvalidDecl = 0; 1894 break; 1895 } 1896 1897 if (InvalidDecl) { 1898 if (ShowDeclName) 1899 Diag(Loc, diag::err_invalid_member_in_interface) 1900 << (InvalidDecl-1) << Name; 1901 else 1902 Diag(Loc, diag::err_invalid_member_in_interface) 1903 << (InvalidDecl-1) << ""; 1904 return 0; 1905 } 1906 } 1907 1908 // C++ 9.2p6: A member shall not be declared to have automatic storage 1909 // duration (auto, register) or with the extern storage-class-specifier. 1910 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 1911 // data members and cannot be applied to names declared const or static, 1912 // and cannot be applied to reference members. 1913 switch (DS.getStorageClassSpec()) { 1914 case DeclSpec::SCS_unspecified: 1915 case DeclSpec::SCS_typedef: 1916 case DeclSpec::SCS_static: 1917 break; 1918 case DeclSpec::SCS_mutable: 1919 if (isFunc) { 1920 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 1921 1922 // FIXME: It would be nicer if the keyword was ignored only for this 1923 // declarator. Otherwise we could get follow-up errors. 1924 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1925 } 1926 break; 1927 default: 1928 Diag(DS.getStorageClassSpecLoc(), 1929 diag::err_storageclass_invalid_for_member); 1930 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1931 break; 1932 } 1933 1934 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 1935 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 1936 !isFunc); 1937 1938 if (DS.isConstexprSpecified() && isInstField) { 1939 SemaDiagnosticBuilder B = 1940 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 1941 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 1942 if (InitStyle == ICIS_NoInit) { 1943 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const"); 1944 D.getMutableDeclSpec().ClearConstexprSpec(); 1945 const char *PrevSpec; 1946 unsigned DiagID; 1947 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc, 1948 PrevSpec, DiagID, getLangOpts()); 1949 (void)Failed; 1950 assert(!Failed && "Making a constexpr member const shouldn't fail"); 1951 } else { 1952 B << 1; 1953 const char *PrevSpec; 1954 unsigned DiagID; 1955 if (D.getMutableDeclSpec().SetStorageClassSpec( 1956 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) { 1957 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 1958 "This is the only DeclSpec that should fail to be applied"); 1959 B << 1; 1960 } else { 1961 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 1962 isInstField = false; 1963 } 1964 } 1965 } 1966 1967 NamedDecl *Member; 1968 if (isInstField) { 1969 CXXScopeSpec &SS = D.getCXXScopeSpec(); 1970 1971 // Data members must have identifiers for names. 1972 if (!Name.isIdentifier()) { 1973 Diag(Loc, diag::err_bad_variable_name) 1974 << Name; 1975 return 0; 1976 } 1977 1978 IdentifierInfo *II = Name.getAsIdentifierInfo(); 1979 1980 // Member field could not be with "template" keyword. 1981 // So TemplateParameterLists should be empty in this case. 1982 if (TemplateParameterLists.size()) { 1983 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 1984 if (TemplateParams->size()) { 1985 // There is no such thing as a member field template. 1986 Diag(D.getIdentifierLoc(), diag::err_template_member) 1987 << II 1988 << SourceRange(TemplateParams->getTemplateLoc(), 1989 TemplateParams->getRAngleLoc()); 1990 } else { 1991 // There is an extraneous 'template<>' for this member. 1992 Diag(TemplateParams->getTemplateLoc(), 1993 diag::err_template_member_noparams) 1994 << II 1995 << SourceRange(TemplateParams->getTemplateLoc(), 1996 TemplateParams->getRAngleLoc()); 1997 } 1998 return 0; 1999 } 2000 2001 if (SS.isSet() && !SS.isInvalid()) { 2002 // The user provided a superfluous scope specifier inside a class 2003 // definition: 2004 // 2005 // class X { 2006 // int X::member; 2007 // }; 2008 if (DeclContext *DC = computeDeclContext(SS, false)) 2009 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc()); 2010 else 2011 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 2012 << Name << SS.getRange(); 2013 2014 SS.clear(); 2015 } 2016 2017 AttributeList *MSPropertyAttr = 2018 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList()); 2019 if (MSPropertyAttr) { 2020 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 2021 BitWidth, InitStyle, AS, MSPropertyAttr); 2022 if (!Member) 2023 return 0; 2024 isInstField = false; 2025 } else { 2026 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 2027 BitWidth, InitStyle, AS); 2028 assert(Member && "HandleField never returns null"); 2029 } 2030 } else { 2031 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static); 2032 2033 Member = HandleDeclarator(S, D, TemplateParameterLists); 2034 if (!Member) 2035 return 0; 2036 2037 // Non-instance-fields can't have a bitfield. 2038 if (BitWidth) { 2039 if (Member->isInvalidDecl()) { 2040 // don't emit another diagnostic. 2041 } else if (isa<VarDecl>(Member)) { 2042 // C++ 9.6p3: A bit-field shall not be a static member. 2043 // "static member 'A' cannot be a bit-field" 2044 Diag(Loc, diag::err_static_not_bitfield) 2045 << Name << BitWidth->getSourceRange(); 2046 } else if (isa<TypedefDecl>(Member)) { 2047 // "typedef member 'x' cannot be a bit-field" 2048 Diag(Loc, diag::err_typedef_not_bitfield) 2049 << Name << BitWidth->getSourceRange(); 2050 } else { 2051 // A function typedef ("typedef int f(); f a;"). 2052 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 2053 Diag(Loc, diag::err_not_integral_type_bitfield) 2054 << Name << cast<ValueDecl>(Member)->getType() 2055 << BitWidth->getSourceRange(); 2056 } 2057 2058 BitWidth = 0; 2059 Member->setInvalidDecl(); 2060 } 2061 2062 Member->setAccess(AS); 2063 2064 // If we have declared a member function template or static data member 2065 // template, set the access of the templated declaration as well. 2066 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 2067 FunTmpl->getTemplatedDecl()->setAccess(AS); 2068 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 2069 VarTmpl->getTemplatedDecl()->setAccess(AS); 2070 } 2071 2072 if (VS.isOverrideSpecified()) 2073 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context)); 2074 if (VS.isFinalSpecified()) 2075 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context, 2076 VS.isFinalSpelledSealed())); 2077 2078 if (VS.getLastLocation().isValid()) { 2079 // Update the end location of a method that has a virt-specifiers. 2080 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 2081 MD->setRangeEnd(VS.getLastLocation()); 2082 } 2083 2084 CheckOverrideControl(Member); 2085 2086 assert((Name || isInstField) && "No identifier for non-field ?"); 2087 2088 if (isInstField) { 2089 FieldDecl *FD = cast<FieldDecl>(Member); 2090 FieldCollector->Add(FD); 2091 2092 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field, 2093 FD->getLocation()) 2094 != DiagnosticsEngine::Ignored) { 2095 // Remember all explicit private FieldDecls that have a name, no side 2096 // effects and are not part of a dependent type declaration. 2097 if (!FD->isImplicit() && FD->getDeclName() && 2098 FD->getAccess() == AS_private && 2099 !FD->hasAttr<UnusedAttr>() && 2100 !FD->getParent()->isDependentContext() && 2101 !InitializationHasSideEffects(*FD)) 2102 UnusedPrivateFields.insert(FD); 2103 } 2104 } 2105 2106 return Member; 2107} 2108 2109namespace { 2110 class UninitializedFieldVisitor 2111 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 2112 Sema &S; 2113 // If VD is null, this visitor will only update the Decls set. 2114 ValueDecl *VD; 2115 bool isReferenceType; 2116 // List of Decls to generate a warning on. 2117 llvm::SmallPtrSet<ValueDecl*, 4> &Decls; 2118 bool WarnOnSelfReference; 2119 // If non-null, add a note to the warning pointing back to the constructor. 2120 const CXXConstructorDecl *Constructor; 2121 public: 2122 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 2123 UninitializedFieldVisitor(Sema &S, ValueDecl *VD, 2124 llvm::SmallPtrSet<ValueDecl*, 4> &Decls, 2125 bool WarnOnSelfReference, 2126 const CXXConstructorDecl *Constructor) 2127 : Inherited(S.Context), S(S), VD(VD), isReferenceType(false), Decls(Decls), 2128 WarnOnSelfReference(WarnOnSelfReference), Constructor(Constructor) { 2129 // When VD is null, this visitor is used to detect initialization of other 2130 // fields. 2131 if (VD) { 2132 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD)) 2133 this->VD = IFD->getAnonField(); 2134 else 2135 this->VD = VD; 2136 isReferenceType = this->VD->getType()->isReferenceType(); 2137 } 2138 } 2139 2140 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly) { 2141 if (!VD) 2142 return; 2143 2144 if (CheckReferenceOnly && !isReferenceType) 2145 return; 2146 2147 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 2148 return; 2149 2150 // FieldME is the inner-most MemberExpr that is not an anonymous struct 2151 // or union. 2152 MemberExpr *FieldME = ME; 2153 2154 Expr *Base = ME; 2155 while (isa<MemberExpr>(Base)) { 2156 ME = cast<MemberExpr>(Base); 2157 2158 if (isa<VarDecl>(ME->getMemberDecl())) 2159 return; 2160 2161 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 2162 if (!FD->isAnonymousStructOrUnion()) 2163 FieldME = ME; 2164 2165 Base = ME->getBase(); 2166 } 2167 2168 if (!isa<CXXThisExpr>(Base)) 2169 return; 2170 2171 ValueDecl* FoundVD = FieldME->getMemberDecl(); 2172 2173 if (VD == FoundVD) { 2174 if (!WarnOnSelfReference) 2175 return; 2176 2177 unsigned diag = isReferenceType 2178 ? diag::warn_reference_field_is_uninit 2179 : diag::warn_field_is_uninit; 2180 S.Diag(FieldME->getExprLoc(), diag) << VD; 2181 if (Constructor) 2182 S.Diag(Constructor->getLocation(), 2183 diag::note_uninit_in_this_constructor); 2184 return; 2185 } 2186 2187 if (CheckReferenceOnly) 2188 return; 2189 2190 if (Decls.count(FoundVD)) { 2191 S.Diag(FieldME->getExprLoc(), diag::warn_field_is_uninit) << FoundVD; 2192 if (Constructor) 2193 S.Diag(Constructor->getLocation(), 2194 diag::note_uninit_in_this_constructor); 2195 2196 } 2197 } 2198 2199 void HandleValue(Expr *E) { 2200 if (!VD) 2201 return; 2202 2203 E = E->IgnoreParens(); 2204 2205 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 2206 HandleMemberExpr(ME, false /*CheckReferenceOnly*/); 2207 return; 2208 } 2209 2210 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 2211 HandleValue(CO->getTrueExpr()); 2212 HandleValue(CO->getFalseExpr()); 2213 return; 2214 } 2215 2216 if (BinaryConditionalOperator *BCO = 2217 dyn_cast<BinaryConditionalOperator>(E)) { 2218 HandleValue(BCO->getCommon()); 2219 HandleValue(BCO->getFalseExpr()); 2220 return; 2221 } 2222 2223 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 2224 switch (BO->getOpcode()) { 2225 default: 2226 return; 2227 case(BO_PtrMemD): 2228 case(BO_PtrMemI): 2229 HandleValue(BO->getLHS()); 2230 return; 2231 case(BO_Comma): 2232 HandleValue(BO->getRHS()); 2233 return; 2234 } 2235 } 2236 } 2237 2238 void VisitMemberExpr(MemberExpr *ME) { 2239 HandleMemberExpr(ME, true /*CheckReferenceOnly*/); 2240 2241 Inherited::VisitMemberExpr(ME); 2242 } 2243 2244 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 2245 if (E->getCastKind() == CK_LValueToRValue) 2246 HandleValue(E->getSubExpr()); 2247 2248 Inherited::VisitImplicitCastExpr(E); 2249 } 2250 2251 void VisitCXXConstructExpr(CXXConstructExpr *E) { 2252 if (E->getConstructor()->isCopyConstructor()) 2253 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(E->getArg(0))) 2254 if (ICE->getCastKind() == CK_NoOp) 2255 if (MemberExpr *ME = dyn_cast<MemberExpr>(ICE->getSubExpr())) 2256 HandleMemberExpr(ME, false /*CheckReferenceOnly*/); 2257 2258 Inherited::VisitCXXConstructExpr(E); 2259 } 2260 2261 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 2262 Expr *Callee = E->getCallee(); 2263 if (isa<MemberExpr>(Callee)) 2264 HandleValue(Callee); 2265 2266 Inherited::VisitCXXMemberCallExpr(E); 2267 } 2268 2269 void VisitBinaryOperator(BinaryOperator *E) { 2270 // If a field assignment is detected, remove the field from the 2271 // uninitiailized field set. 2272 if (E->getOpcode() == BO_Assign) 2273 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 2274 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 2275 Decls.erase(FD); 2276 2277 Inherited::VisitBinaryOperator(E); 2278 } 2279 }; 2280 static void CheckInitExprContainsUninitializedFields( 2281 Sema &S, Expr *E, ValueDecl *VD, llvm::SmallPtrSet<ValueDecl*, 4> &Decls, 2282 bool WarnOnSelfReference, const CXXConstructorDecl *Constructor = 0) { 2283 if (Decls.size() == 0 && !WarnOnSelfReference) 2284 return; 2285 2286 if (E) 2287 UninitializedFieldVisitor(S, VD, Decls, WarnOnSelfReference, Constructor) 2288 .Visit(E); 2289 } 2290} // namespace 2291 2292/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an 2293/// in-class initializer for a non-static C++ class member, and after 2294/// instantiating an in-class initializer in a class template. Such actions 2295/// are deferred until the class is complete. 2296void 2297Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc, 2298 Expr *InitExpr) { 2299 FieldDecl *FD = cast<FieldDecl>(D); 2300 assert(FD->getInClassInitStyle() != ICIS_NoInit && 2301 "must set init style when field is created"); 2302 2303 if (!InitExpr) { 2304 FD->setInvalidDecl(); 2305 FD->removeInClassInitializer(); 2306 return; 2307 } 2308 2309 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 2310 FD->setInvalidDecl(); 2311 FD->removeInClassInitializer(); 2312 return; 2313 } 2314 2315 ExprResult Init = InitExpr; 2316 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 2317 InitializedEntity Entity = InitializedEntity::InitializeMember(FD); 2318 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit 2319 ? InitializationKind::CreateDirectList(InitExpr->getLocStart()) 2320 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc); 2321 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 2322 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 2323 if (Init.isInvalid()) { 2324 FD->setInvalidDecl(); 2325 return; 2326 } 2327 } 2328 2329 // C++11 [class.base.init]p7: 2330 // The initialization of each base and member constitutes a 2331 // full-expression. 2332 Init = ActOnFinishFullExpr(Init.take(), InitLoc); 2333 if (Init.isInvalid()) { 2334 FD->setInvalidDecl(); 2335 return; 2336 } 2337 2338 InitExpr = Init.release(); 2339 2340 FD->setInClassInitializer(InitExpr); 2341} 2342 2343/// \brief Find the direct and/or virtual base specifiers that 2344/// correspond to the given base type, for use in base initialization 2345/// within a constructor. 2346static bool FindBaseInitializer(Sema &SemaRef, 2347 CXXRecordDecl *ClassDecl, 2348 QualType BaseType, 2349 const CXXBaseSpecifier *&DirectBaseSpec, 2350 const CXXBaseSpecifier *&VirtualBaseSpec) { 2351 // First, check for a direct base class. 2352 DirectBaseSpec = 0; 2353 for (CXXRecordDecl::base_class_const_iterator Base 2354 = ClassDecl->bases_begin(); 2355 Base != ClassDecl->bases_end(); ++Base) { 2356 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) { 2357 // We found a direct base of this type. That's what we're 2358 // initializing. 2359 DirectBaseSpec = &*Base; 2360 break; 2361 } 2362 } 2363 2364 // Check for a virtual base class. 2365 // FIXME: We might be able to short-circuit this if we know in advance that 2366 // there are no virtual bases. 2367 VirtualBaseSpec = 0; 2368 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 2369 // We haven't found a base yet; search the class hierarchy for a 2370 // virtual base class. 2371 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2372 /*DetectVirtual=*/false); 2373 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl), 2374 BaseType, Paths)) { 2375 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2376 Path != Paths.end(); ++Path) { 2377 if (Path->back().Base->isVirtual()) { 2378 VirtualBaseSpec = Path->back().Base; 2379 break; 2380 } 2381 } 2382 } 2383 } 2384 2385 return DirectBaseSpec || VirtualBaseSpec; 2386} 2387 2388/// \brief Handle a C++ member initializer using braced-init-list syntax. 2389MemInitResult 2390Sema::ActOnMemInitializer(Decl *ConstructorD, 2391 Scope *S, 2392 CXXScopeSpec &SS, 2393 IdentifierInfo *MemberOrBase, 2394 ParsedType TemplateTypeTy, 2395 const DeclSpec &DS, 2396 SourceLocation IdLoc, 2397 Expr *InitList, 2398 SourceLocation EllipsisLoc) { 2399 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2400 DS, IdLoc, InitList, 2401 EllipsisLoc); 2402} 2403 2404/// \brief Handle a C++ member initializer using parentheses syntax. 2405MemInitResult 2406Sema::ActOnMemInitializer(Decl *ConstructorD, 2407 Scope *S, 2408 CXXScopeSpec &SS, 2409 IdentifierInfo *MemberOrBase, 2410 ParsedType TemplateTypeTy, 2411 const DeclSpec &DS, 2412 SourceLocation IdLoc, 2413 SourceLocation LParenLoc, 2414 ArrayRef<Expr *> Args, 2415 SourceLocation RParenLoc, 2416 SourceLocation EllipsisLoc) { 2417 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, 2418 Args, RParenLoc); 2419 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2420 DS, IdLoc, List, EllipsisLoc); 2421} 2422 2423namespace { 2424 2425// Callback to only accept typo corrections that can be a valid C++ member 2426// intializer: either a non-static field member or a base class. 2427class MemInitializerValidatorCCC : public CorrectionCandidateCallback { 2428public: 2429 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 2430 : ClassDecl(ClassDecl) {} 2431 2432 bool ValidateCandidate(const TypoCorrection &candidate) LLVM_OVERRIDE { 2433 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 2434 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 2435 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 2436 return isa<TypeDecl>(ND); 2437 } 2438 return false; 2439 } 2440 2441private: 2442 CXXRecordDecl *ClassDecl; 2443}; 2444 2445} 2446 2447/// \brief Handle a C++ member initializer. 2448MemInitResult 2449Sema::BuildMemInitializer(Decl *ConstructorD, 2450 Scope *S, 2451 CXXScopeSpec &SS, 2452 IdentifierInfo *MemberOrBase, 2453 ParsedType TemplateTypeTy, 2454 const DeclSpec &DS, 2455 SourceLocation IdLoc, 2456 Expr *Init, 2457 SourceLocation EllipsisLoc) { 2458 if (!ConstructorD) 2459 return true; 2460 2461 AdjustDeclIfTemplate(ConstructorD); 2462 2463 CXXConstructorDecl *Constructor 2464 = dyn_cast<CXXConstructorDecl>(ConstructorD); 2465 if (!Constructor) { 2466 // The user wrote a constructor initializer on a function that is 2467 // not a C++ constructor. Ignore the error for now, because we may 2468 // have more member initializers coming; we'll diagnose it just 2469 // once in ActOnMemInitializers. 2470 return true; 2471 } 2472 2473 CXXRecordDecl *ClassDecl = Constructor->getParent(); 2474 2475 // C++ [class.base.init]p2: 2476 // Names in a mem-initializer-id are looked up in the scope of the 2477 // constructor's class and, if not found in that scope, are looked 2478 // up in the scope containing the constructor's definition. 2479 // [Note: if the constructor's class contains a member with the 2480 // same name as a direct or virtual base class of the class, a 2481 // mem-initializer-id naming the member or base class and composed 2482 // of a single identifier refers to the class member. A 2483 // mem-initializer-id for the hidden base class may be specified 2484 // using a qualified name. ] 2485 if (!SS.getScopeRep() && !TemplateTypeTy) { 2486 // Look for a member, first. 2487 DeclContext::lookup_result Result 2488 = ClassDecl->lookup(MemberOrBase); 2489 if (!Result.empty()) { 2490 ValueDecl *Member; 2491 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 2492 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) { 2493 if (EllipsisLoc.isValid()) 2494 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 2495 << MemberOrBase 2496 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 2497 2498 return BuildMemberInitializer(Member, Init, IdLoc); 2499 } 2500 } 2501 } 2502 // It didn't name a member, so see if it names a class. 2503 QualType BaseType; 2504 TypeSourceInfo *TInfo = 0; 2505 2506 if (TemplateTypeTy) { 2507 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 2508 } else if (DS.getTypeSpecType() == TST_decltype) { 2509 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 2510 } else { 2511 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 2512 LookupParsedName(R, S, &SS); 2513 2514 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 2515 if (!TyD) { 2516 if (R.isAmbiguous()) return true; 2517 2518 // We don't want access-control diagnostics here. 2519 R.suppressDiagnostics(); 2520 2521 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 2522 bool NotUnknownSpecialization = false; 2523 DeclContext *DC = computeDeclContext(SS, false); 2524 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 2525 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 2526 2527 if (!NotUnknownSpecialization) { 2528 // When the scope specifier can refer to a member of an unknown 2529 // specialization, we take it as a type name. 2530 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 2531 SS.getWithLocInContext(Context), 2532 *MemberOrBase, IdLoc); 2533 if (BaseType.isNull()) 2534 return true; 2535 2536 R.clear(); 2537 R.setLookupName(MemberOrBase); 2538 } 2539 } 2540 2541 // If no results were found, try to correct typos. 2542 TypoCorrection Corr; 2543 MemInitializerValidatorCCC Validator(ClassDecl); 2544 if (R.empty() && BaseType.isNull() && 2545 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 2546 Validator, ClassDecl))) { 2547 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 2548 // We have found a non-static data member with a similar 2549 // name to what was typed; complain and initialize that 2550 // member. 2551 diagnoseTypo(Corr, 2552 PDiag(diag::err_mem_init_not_member_or_class_suggest) 2553 << MemberOrBase << true); 2554 return BuildMemberInitializer(Member, Init, IdLoc); 2555 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 2556 const CXXBaseSpecifier *DirectBaseSpec; 2557 const CXXBaseSpecifier *VirtualBaseSpec; 2558 if (FindBaseInitializer(*this, ClassDecl, 2559 Context.getTypeDeclType(Type), 2560 DirectBaseSpec, VirtualBaseSpec)) { 2561 // We have found a direct or virtual base class with a 2562 // similar name to what was typed; complain and initialize 2563 // that base class. 2564 diagnoseTypo(Corr, 2565 PDiag(diag::err_mem_init_not_member_or_class_suggest) 2566 << MemberOrBase << false, 2567 PDiag() /*Suppress note, we provide our own.*/); 2568 2569 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 2570 : VirtualBaseSpec; 2571 Diag(BaseSpec->getLocStart(), 2572 diag::note_base_class_specified_here) 2573 << BaseSpec->getType() 2574 << BaseSpec->getSourceRange(); 2575 2576 TyD = Type; 2577 } 2578 } 2579 } 2580 2581 if (!TyD && BaseType.isNull()) { 2582 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 2583 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 2584 return true; 2585 } 2586 } 2587 2588 if (BaseType.isNull()) { 2589 BaseType = Context.getTypeDeclType(TyD); 2590 if (SS.isSet()) { 2591 NestedNameSpecifier *Qualifier = 2592 static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 2593 2594 // FIXME: preserve source range information 2595 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType); 2596 } 2597 } 2598 } 2599 2600 if (!TInfo) 2601 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 2602 2603 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 2604} 2605 2606/// Checks a member initializer expression for cases where reference (or 2607/// pointer) members are bound to by-value parameters (or their addresses). 2608static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member, 2609 Expr *Init, 2610 SourceLocation IdLoc) { 2611 QualType MemberTy = Member->getType(); 2612 2613 // We only handle pointers and references currently. 2614 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers? 2615 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType()) 2616 return; 2617 2618 const bool IsPointer = MemberTy->isPointerType(); 2619 if (IsPointer) { 2620 if (const UnaryOperator *Op 2621 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) { 2622 // The only case we're worried about with pointers requires taking the 2623 // address. 2624 if (Op->getOpcode() != UO_AddrOf) 2625 return; 2626 2627 Init = Op->getSubExpr(); 2628 } else { 2629 // We only handle address-of expression initializers for pointers. 2630 return; 2631 } 2632 } 2633 2634 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) { 2635 // We only warn when referring to a non-reference parameter declaration. 2636 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl()); 2637 if (!Parameter || Parameter->getType()->isReferenceType()) 2638 return; 2639 2640 S.Diag(Init->getExprLoc(), 2641 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr 2642 : diag::warn_bind_ref_member_to_parameter) 2643 << Member << Parameter << Init->getSourceRange(); 2644 } else { 2645 // Other initializers are fine. 2646 return; 2647 } 2648 2649 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here) 2650 << (unsigned)IsPointer; 2651} 2652 2653MemInitResult 2654Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 2655 SourceLocation IdLoc) { 2656 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 2657 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 2658 assert((DirectMember || IndirectMember) && 2659 "Member must be a FieldDecl or IndirectFieldDecl"); 2660 2661 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 2662 return true; 2663 2664 if (Member->isInvalidDecl()) 2665 return true; 2666 2667 MultiExprArg Args; 2668 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2669 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 2670 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 2671 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 2672 } else { 2673 // Template instantiation doesn't reconstruct ParenListExprs for us. 2674 Args = Init; 2675 } 2676 2677 SourceRange InitRange = Init->getSourceRange(); 2678 2679 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 2680 // Can't check initialization for a member of dependent type or when 2681 // any of the arguments are type-dependent expressions. 2682 DiscardCleanupsInEvaluationContext(); 2683 } else { 2684 bool InitList = false; 2685 if (isa<InitListExpr>(Init)) { 2686 InitList = true; 2687 Args = Init; 2688 } 2689 2690 // Initialize the member. 2691 InitializedEntity MemberEntity = 2692 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0) 2693 : InitializedEntity::InitializeMember(IndirectMember, 0); 2694 InitializationKind Kind = 2695 InitList ? InitializationKind::CreateDirectList(IdLoc) 2696 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 2697 InitRange.getEnd()); 2698 2699 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 2700 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 0); 2701 if (MemberInit.isInvalid()) 2702 return true; 2703 2704 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc); 2705 2706 // C++11 [class.base.init]p7: 2707 // The initialization of each base and member constitutes a 2708 // full-expression. 2709 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin()); 2710 if (MemberInit.isInvalid()) 2711 return true; 2712 2713 Init = MemberInit.get(); 2714 } 2715 2716 if (DirectMember) { 2717 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 2718 InitRange.getBegin(), Init, 2719 InitRange.getEnd()); 2720 } else { 2721 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 2722 InitRange.getBegin(), Init, 2723 InitRange.getEnd()); 2724 } 2725} 2726 2727MemInitResult 2728Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 2729 CXXRecordDecl *ClassDecl) { 2730 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 2731 if (!LangOpts.CPlusPlus11) 2732 return Diag(NameLoc, diag::err_delegating_ctor) 2733 << TInfo->getTypeLoc().getLocalSourceRange(); 2734 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 2735 2736 bool InitList = true; 2737 MultiExprArg Args = Init; 2738 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2739 InitList = false; 2740 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 2741 } 2742 2743 SourceRange InitRange = Init->getSourceRange(); 2744 // Initialize the object. 2745 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 2746 QualType(ClassDecl->getTypeForDecl(), 0)); 2747 InitializationKind Kind = 2748 InitList ? InitializationKind::CreateDirectList(NameLoc) 2749 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 2750 InitRange.getEnd()); 2751 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 2752 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 2753 Args, 0); 2754 if (DelegationInit.isInvalid()) 2755 return true; 2756 2757 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 2758 "Delegating constructor with no target?"); 2759 2760 // C++11 [class.base.init]p7: 2761 // The initialization of each base and member constitutes a 2762 // full-expression. 2763 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(), 2764 InitRange.getBegin()); 2765 if (DelegationInit.isInvalid()) 2766 return true; 2767 2768 // If we are in a dependent context, template instantiation will 2769 // perform this type-checking again. Just save the arguments that we 2770 // received in a ParenListExpr. 2771 // FIXME: This isn't quite ideal, since our ASTs don't capture all 2772 // of the information that we have about the base 2773 // initializer. However, deconstructing the ASTs is a dicey process, 2774 // and this approach is far more likely to get the corner cases right. 2775 if (CurContext->isDependentContext()) 2776 DelegationInit = Owned(Init); 2777 2778 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 2779 DelegationInit.takeAs<Expr>(), 2780 InitRange.getEnd()); 2781} 2782 2783MemInitResult 2784Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 2785 Expr *Init, CXXRecordDecl *ClassDecl, 2786 SourceLocation EllipsisLoc) { 2787 SourceLocation BaseLoc 2788 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 2789 2790 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 2791 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 2792 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2793 2794 // C++ [class.base.init]p2: 2795 // [...] Unless the mem-initializer-id names a nonstatic data 2796 // member of the constructor's class or a direct or virtual base 2797 // of that class, the mem-initializer is ill-formed. A 2798 // mem-initializer-list can initialize a base class using any 2799 // name that denotes that base class type. 2800 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 2801 2802 SourceRange InitRange = Init->getSourceRange(); 2803 if (EllipsisLoc.isValid()) { 2804 // This is a pack expansion. 2805 if (!BaseType->containsUnexpandedParameterPack()) { 2806 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2807 << SourceRange(BaseLoc, InitRange.getEnd()); 2808 2809 EllipsisLoc = SourceLocation(); 2810 } 2811 } else { 2812 // Check for any unexpanded parameter packs. 2813 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 2814 return true; 2815 2816 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 2817 return true; 2818 } 2819 2820 // Check for direct and virtual base classes. 2821 const CXXBaseSpecifier *DirectBaseSpec = 0; 2822 const CXXBaseSpecifier *VirtualBaseSpec = 0; 2823 if (!Dependent) { 2824 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 2825 BaseType)) 2826 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 2827 2828 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 2829 VirtualBaseSpec); 2830 2831 // C++ [base.class.init]p2: 2832 // Unless the mem-initializer-id names a nonstatic data member of the 2833 // constructor's class or a direct or virtual base of that class, the 2834 // mem-initializer is ill-formed. 2835 if (!DirectBaseSpec && !VirtualBaseSpec) { 2836 // If the class has any dependent bases, then it's possible that 2837 // one of those types will resolve to the same type as 2838 // BaseType. Therefore, just treat this as a dependent base 2839 // class initialization. FIXME: Should we try to check the 2840 // initialization anyway? It seems odd. 2841 if (ClassDecl->hasAnyDependentBases()) 2842 Dependent = true; 2843 else 2844 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 2845 << BaseType << Context.getTypeDeclType(ClassDecl) 2846 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2847 } 2848 } 2849 2850 if (Dependent) { 2851 DiscardCleanupsInEvaluationContext(); 2852 2853 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 2854 /*IsVirtual=*/false, 2855 InitRange.getBegin(), Init, 2856 InitRange.getEnd(), EllipsisLoc); 2857 } 2858 2859 // C++ [base.class.init]p2: 2860 // If a mem-initializer-id is ambiguous because it designates both 2861 // a direct non-virtual base class and an inherited virtual base 2862 // class, the mem-initializer is ill-formed. 2863 if (DirectBaseSpec && VirtualBaseSpec) 2864 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 2865 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2866 2867 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 2868 if (!BaseSpec) 2869 BaseSpec = VirtualBaseSpec; 2870 2871 // Initialize the base. 2872 bool InitList = true; 2873 MultiExprArg Args = Init; 2874 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2875 InitList = false; 2876 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 2877 } 2878 2879 InitializedEntity BaseEntity = 2880 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 2881 InitializationKind Kind = 2882 InitList ? InitializationKind::CreateDirectList(BaseLoc) 2883 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 2884 InitRange.getEnd()); 2885 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 2886 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 0); 2887 if (BaseInit.isInvalid()) 2888 return true; 2889 2890 // C++11 [class.base.init]p7: 2891 // The initialization of each base and member constitutes a 2892 // full-expression. 2893 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin()); 2894 if (BaseInit.isInvalid()) 2895 return true; 2896 2897 // If we are in a dependent context, template instantiation will 2898 // perform this type-checking again. Just save the arguments that we 2899 // received in a ParenListExpr. 2900 // FIXME: This isn't quite ideal, since our ASTs don't capture all 2901 // of the information that we have about the base 2902 // initializer. However, deconstructing the ASTs is a dicey process, 2903 // and this approach is far more likely to get the corner cases right. 2904 if (CurContext->isDependentContext()) 2905 BaseInit = Owned(Init); 2906 2907 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 2908 BaseSpec->isVirtual(), 2909 InitRange.getBegin(), 2910 BaseInit.takeAs<Expr>(), 2911 InitRange.getEnd(), EllipsisLoc); 2912} 2913 2914// Create a static_cast\<T&&>(expr). 2915static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 2916 if (T.isNull()) T = E->getType(); 2917 QualType TargetType = SemaRef.BuildReferenceType( 2918 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 2919 SourceLocation ExprLoc = E->getLocStart(); 2920 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 2921 TargetType, ExprLoc); 2922 2923 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 2924 SourceRange(ExprLoc, ExprLoc), 2925 E->getSourceRange()).take(); 2926} 2927 2928/// ImplicitInitializerKind - How an implicit base or member initializer should 2929/// initialize its base or member. 2930enum ImplicitInitializerKind { 2931 IIK_Default, 2932 IIK_Copy, 2933 IIK_Move, 2934 IIK_Inherit 2935}; 2936 2937static bool 2938BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 2939 ImplicitInitializerKind ImplicitInitKind, 2940 CXXBaseSpecifier *BaseSpec, 2941 bool IsInheritedVirtualBase, 2942 CXXCtorInitializer *&CXXBaseInit) { 2943 InitializedEntity InitEntity 2944 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 2945 IsInheritedVirtualBase); 2946 2947 ExprResult BaseInit; 2948 2949 switch (ImplicitInitKind) { 2950 case IIK_Inherit: { 2951 const CXXRecordDecl *Inherited = 2952 Constructor->getInheritedConstructor()->getParent(); 2953 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 2954 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) { 2955 // C++11 [class.inhctor]p8: 2956 // Each expression in the expression-list is of the form 2957 // static_cast<T&&>(p), where p is the name of the corresponding 2958 // constructor parameter and T is the declared type of p. 2959 SmallVector<Expr*, 16> Args; 2960 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) { 2961 ParmVarDecl *PD = Constructor->getParamDecl(I); 2962 ExprResult ArgExpr = 2963 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(), 2964 VK_LValue, SourceLocation()); 2965 if (ArgExpr.isInvalid()) 2966 return true; 2967 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType())); 2968 } 2969 2970 InitializationKind InitKind = InitializationKind::CreateDirect( 2971 Constructor->getLocation(), SourceLocation(), SourceLocation()); 2972 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args); 2973 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args); 2974 break; 2975 } 2976 } 2977 // Fall through. 2978 case IIK_Default: { 2979 InitializationKind InitKind 2980 = InitializationKind::CreateDefault(Constructor->getLocation()); 2981 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 2982 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 2983 break; 2984 } 2985 2986 case IIK_Move: 2987 case IIK_Copy: { 2988 bool Moving = ImplicitInitKind == IIK_Move; 2989 ParmVarDecl *Param = Constructor->getParamDecl(0); 2990 QualType ParamType = Param->getType().getNonReferenceType(); 2991 2992 Expr *CopyCtorArg = 2993 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 2994 SourceLocation(), Param, false, 2995 Constructor->getLocation(), ParamType, 2996 VK_LValue, 0); 2997 2998 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 2999 3000 // Cast to the base class to avoid ambiguities. 3001 QualType ArgTy = 3002 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 3003 ParamType.getQualifiers()); 3004 3005 if (Moving) { 3006 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 3007 } 3008 3009 CXXCastPath BasePath; 3010 BasePath.push_back(BaseSpec); 3011 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 3012 CK_UncheckedDerivedToBase, 3013 Moving ? VK_XValue : VK_LValue, 3014 &BasePath).take(); 3015 3016 InitializationKind InitKind 3017 = InitializationKind::CreateDirect(Constructor->getLocation(), 3018 SourceLocation(), SourceLocation()); 3019 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 3020 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 3021 break; 3022 } 3023 } 3024 3025 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 3026 if (BaseInit.isInvalid()) 3027 return true; 3028 3029 CXXBaseInit = 3030 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3031 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 3032 SourceLocation()), 3033 BaseSpec->isVirtual(), 3034 SourceLocation(), 3035 BaseInit.takeAs<Expr>(), 3036 SourceLocation(), 3037 SourceLocation()); 3038 3039 return false; 3040} 3041 3042static bool RefersToRValueRef(Expr *MemRef) { 3043 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 3044 return Referenced->getType()->isRValueReferenceType(); 3045} 3046 3047static bool 3048BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 3049 ImplicitInitializerKind ImplicitInitKind, 3050 FieldDecl *Field, IndirectFieldDecl *Indirect, 3051 CXXCtorInitializer *&CXXMemberInit) { 3052 if (Field->isInvalidDecl()) 3053 return true; 3054 3055 SourceLocation Loc = Constructor->getLocation(); 3056 3057 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 3058 bool Moving = ImplicitInitKind == IIK_Move; 3059 ParmVarDecl *Param = Constructor->getParamDecl(0); 3060 QualType ParamType = Param->getType().getNonReferenceType(); 3061 3062 // Suppress copying zero-width bitfields. 3063 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0) 3064 return false; 3065 3066 Expr *MemberExprBase = 3067 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 3068 SourceLocation(), Param, false, 3069 Loc, ParamType, VK_LValue, 0); 3070 3071 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 3072 3073 if (Moving) { 3074 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 3075 } 3076 3077 // Build a reference to this field within the parameter. 3078 CXXScopeSpec SS; 3079 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 3080 Sema::LookupMemberName); 3081 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 3082 : cast<ValueDecl>(Field), AS_public); 3083 MemberLookup.resolveKind(); 3084 ExprResult CtorArg 3085 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 3086 ParamType, Loc, 3087 /*IsArrow=*/false, 3088 SS, 3089 /*TemplateKWLoc=*/SourceLocation(), 3090 /*FirstQualifierInScope=*/0, 3091 MemberLookup, 3092 /*TemplateArgs=*/0); 3093 if (CtorArg.isInvalid()) 3094 return true; 3095 3096 // C++11 [class.copy]p15: 3097 // - if a member m has rvalue reference type T&&, it is direct-initialized 3098 // with static_cast<T&&>(x.m); 3099 if (RefersToRValueRef(CtorArg.get())) { 3100 CtorArg = CastForMoving(SemaRef, CtorArg.take()); 3101 } 3102 3103 // When the field we are copying is an array, create index variables for 3104 // each dimension of the array. We use these index variables to subscript 3105 // the source array, and other clients (e.g., CodeGen) will perform the 3106 // necessary iteration with these index variables. 3107 SmallVector<VarDecl *, 4> IndexVariables; 3108 QualType BaseType = Field->getType(); 3109 QualType SizeType = SemaRef.Context.getSizeType(); 3110 bool InitializingArray = false; 3111 while (const ConstantArrayType *Array 3112 = SemaRef.Context.getAsConstantArrayType(BaseType)) { 3113 InitializingArray = true; 3114 // Create the iteration variable for this array index. 3115 IdentifierInfo *IterationVarName = 0; 3116 { 3117 SmallString<8> Str; 3118 llvm::raw_svector_ostream OS(Str); 3119 OS << "__i" << IndexVariables.size(); 3120 IterationVarName = &SemaRef.Context.Idents.get(OS.str()); 3121 } 3122 VarDecl *IterationVar 3123 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc, 3124 IterationVarName, SizeType, 3125 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc), 3126 SC_None); 3127 IndexVariables.push_back(IterationVar); 3128 3129 // Create a reference to the iteration variable. 3130 ExprResult IterationVarRef 3131 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 3132 assert(!IterationVarRef.isInvalid() && 3133 "Reference to invented variable cannot fail!"); 3134 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take()); 3135 assert(!IterationVarRef.isInvalid() && 3136 "Conversion of invented variable cannot fail!"); 3137 3138 // Subscript the array with this iteration variable. 3139 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc, 3140 IterationVarRef.take(), 3141 Loc); 3142 if (CtorArg.isInvalid()) 3143 return true; 3144 3145 BaseType = Array->getElementType(); 3146 } 3147 3148 // The array subscript expression is an lvalue, which is wrong for moving. 3149 if (Moving && InitializingArray) 3150 CtorArg = CastForMoving(SemaRef, CtorArg.take()); 3151 3152 // Construct the entity that we will be initializing. For an array, this 3153 // will be first element in the array, which may require several levels 3154 // of array-subscript entities. 3155 SmallVector<InitializedEntity, 4> Entities; 3156 Entities.reserve(1 + IndexVariables.size()); 3157 if (Indirect) 3158 Entities.push_back(InitializedEntity::InitializeMember(Indirect)); 3159 else 3160 Entities.push_back(InitializedEntity::InitializeMember(Field)); 3161 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 3162 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context, 3163 0, 3164 Entities.back())); 3165 3166 // Direct-initialize to use the copy constructor. 3167 InitializationKind InitKind = 3168 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 3169 3170 Expr *CtorArgE = CtorArg.takeAs<Expr>(); 3171 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE); 3172 3173 ExprResult MemberInit 3174 = InitSeq.Perform(SemaRef, Entities.back(), InitKind, 3175 MultiExprArg(&CtorArgE, 1)); 3176 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3177 if (MemberInit.isInvalid()) 3178 return true; 3179 3180 if (Indirect) { 3181 assert(IndexVariables.size() == 0 && 3182 "Indirect field improperly initialized"); 3183 CXXMemberInit 3184 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 3185 Loc, Loc, 3186 MemberInit.takeAs<Expr>(), 3187 Loc); 3188 } else 3189 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, 3190 Loc, MemberInit.takeAs<Expr>(), 3191 Loc, 3192 IndexVariables.data(), 3193 IndexVariables.size()); 3194 return false; 3195 } 3196 3197 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 3198 "Unhandled implicit init kind!"); 3199 3200 QualType FieldBaseElementType = 3201 SemaRef.Context.getBaseElementType(Field->getType()); 3202 3203 if (FieldBaseElementType->isRecordType()) { 3204 InitializedEntity InitEntity 3205 = Indirect? InitializedEntity::InitializeMember(Indirect) 3206 : InitializedEntity::InitializeMember(Field); 3207 InitializationKind InitKind = 3208 InitializationKind::CreateDefault(Loc); 3209 3210 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 3211 ExprResult MemberInit = 3212 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 3213 3214 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3215 if (MemberInit.isInvalid()) 3216 return true; 3217 3218 if (Indirect) 3219 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3220 Indirect, Loc, 3221 Loc, 3222 MemberInit.get(), 3223 Loc); 3224 else 3225 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3226 Field, Loc, Loc, 3227 MemberInit.get(), 3228 Loc); 3229 return false; 3230 } 3231 3232 if (!Field->getParent()->isUnion()) { 3233 if (FieldBaseElementType->isReferenceType()) { 3234 SemaRef.Diag(Constructor->getLocation(), 3235 diag::err_uninitialized_member_in_ctor) 3236 << (int)Constructor->isImplicit() 3237 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3238 << 0 << Field->getDeclName(); 3239 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3240 return true; 3241 } 3242 3243 if (FieldBaseElementType.isConstQualified()) { 3244 SemaRef.Diag(Constructor->getLocation(), 3245 diag::err_uninitialized_member_in_ctor) 3246 << (int)Constructor->isImplicit() 3247 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3248 << 1 << Field->getDeclName(); 3249 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3250 return true; 3251 } 3252 } 3253 3254 if (SemaRef.getLangOpts().ObjCAutoRefCount && 3255 FieldBaseElementType->isObjCRetainableType() && 3256 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None && 3257 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) { 3258 // ARC: 3259 // Default-initialize Objective-C pointers to NULL. 3260 CXXMemberInit 3261 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 3262 Loc, Loc, 3263 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 3264 Loc); 3265 return false; 3266 } 3267 3268 // Nothing to initialize. 3269 CXXMemberInit = 0; 3270 return false; 3271} 3272 3273namespace { 3274struct BaseAndFieldInfo { 3275 Sema &S; 3276 CXXConstructorDecl *Ctor; 3277 bool AnyErrorsInInits; 3278 ImplicitInitializerKind IIK; 3279 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 3280 SmallVector<CXXCtorInitializer*, 8> AllToInit; 3281 3282 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 3283 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 3284 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 3285 if (Generated && Ctor->isCopyConstructor()) 3286 IIK = IIK_Copy; 3287 else if (Generated && Ctor->isMoveConstructor()) 3288 IIK = IIK_Move; 3289 else if (Ctor->getInheritedConstructor()) 3290 IIK = IIK_Inherit; 3291 else 3292 IIK = IIK_Default; 3293 } 3294 3295 bool isImplicitCopyOrMove() const { 3296 switch (IIK) { 3297 case IIK_Copy: 3298 case IIK_Move: 3299 return true; 3300 3301 case IIK_Default: 3302 case IIK_Inherit: 3303 return false; 3304 } 3305 3306 llvm_unreachable("Invalid ImplicitInitializerKind!"); 3307 } 3308 3309 bool addFieldInitializer(CXXCtorInitializer *Init) { 3310 AllToInit.push_back(Init); 3311 3312 // Check whether this initializer makes the field "used". 3313 if (Init->getInit()->HasSideEffects(S.Context)) 3314 S.UnusedPrivateFields.remove(Init->getAnyMember()); 3315 3316 return false; 3317 } 3318}; 3319} 3320 3321/// \brief Determine whether the given indirect field declaration is somewhere 3322/// within an anonymous union. 3323static bool isWithinAnonymousUnion(IndirectFieldDecl *F) { 3324 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(), 3325 CEnd = F->chain_end(); 3326 C != CEnd; ++C) 3327 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext())) 3328 if (Record->isUnion()) 3329 return true; 3330 3331 return false; 3332} 3333 3334/// \brief Determine whether the given type is an incomplete or zero-lenfgth 3335/// array type. 3336static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 3337 if (T->isIncompleteArrayType()) 3338 return true; 3339 3340 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 3341 if (!ArrayT->getSize()) 3342 return true; 3343 3344 T = ArrayT->getElementType(); 3345 } 3346 3347 return false; 3348} 3349 3350static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 3351 FieldDecl *Field, 3352 IndirectFieldDecl *Indirect = 0) { 3353 if (Field->isInvalidDecl()) 3354 return false; 3355 3356 // Overwhelmingly common case: we have a direct initializer for this field. 3357 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) 3358 return Info.addFieldInitializer(Init); 3359 3360 // C++11 [class.base.init]p8: if the entity is a non-static data member that 3361 // has a brace-or-equal-initializer, the entity is initialized as specified 3362 // in [dcl.init]. 3363 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 3364 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context, 3365 Info.Ctor->getLocation(), Field); 3366 CXXCtorInitializer *Init; 3367 if (Indirect) 3368 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 3369 SourceLocation(), 3370 SourceLocation(), DIE, 3371 SourceLocation()); 3372 else 3373 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 3374 SourceLocation(), 3375 SourceLocation(), DIE, 3376 SourceLocation()); 3377 return Info.addFieldInitializer(Init); 3378 } 3379 3380 // Don't build an implicit initializer for union members if none was 3381 // explicitly specified. 3382 if (Field->getParent()->isUnion() || 3383 (Indirect && isWithinAnonymousUnion(Indirect))) 3384 return false; 3385 3386 // Don't initialize incomplete or zero-length arrays. 3387 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 3388 return false; 3389 3390 // Don't try to build an implicit initializer if there were semantic 3391 // errors in any of the initializers (and therefore we might be 3392 // missing some that the user actually wrote). 3393 if (Info.AnyErrorsInInits) 3394 return false; 3395 3396 CXXCtorInitializer *Init = 0; 3397 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 3398 Indirect, Init)) 3399 return true; 3400 3401 if (!Init) 3402 return false; 3403 3404 return Info.addFieldInitializer(Init); 3405} 3406 3407bool 3408Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 3409 CXXCtorInitializer *Initializer) { 3410 assert(Initializer->isDelegatingInitializer()); 3411 Constructor->setNumCtorInitializers(1); 3412 CXXCtorInitializer **initializer = 3413 new (Context) CXXCtorInitializer*[1]; 3414 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 3415 Constructor->setCtorInitializers(initializer); 3416 3417 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 3418 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 3419 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 3420 } 3421 3422 DelegatingCtorDecls.push_back(Constructor); 3423 3424 return false; 3425} 3426 3427bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 3428 ArrayRef<CXXCtorInitializer *> Initializers) { 3429 if (Constructor->isDependentContext()) { 3430 // Just store the initializers as written, they will be checked during 3431 // instantiation. 3432 if (!Initializers.empty()) { 3433 Constructor->setNumCtorInitializers(Initializers.size()); 3434 CXXCtorInitializer **baseOrMemberInitializers = 3435 new (Context) CXXCtorInitializer*[Initializers.size()]; 3436 memcpy(baseOrMemberInitializers, Initializers.data(), 3437 Initializers.size() * sizeof(CXXCtorInitializer*)); 3438 Constructor->setCtorInitializers(baseOrMemberInitializers); 3439 } 3440 3441 // Let template instantiation know whether we had errors. 3442 if (AnyErrors) 3443 Constructor->setInvalidDecl(); 3444 3445 return false; 3446 } 3447 3448 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 3449 3450 // We need to build the initializer AST according to order of construction 3451 // and not what user specified in the Initializers list. 3452 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 3453 if (!ClassDecl) 3454 return true; 3455 3456 bool HadError = false; 3457 3458 for (unsigned i = 0; i < Initializers.size(); i++) { 3459 CXXCtorInitializer *Member = Initializers[i]; 3460 3461 if (Member->isBaseInitializer()) 3462 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 3463 else 3464 Info.AllBaseFields[Member->getAnyMember()] = Member; 3465 } 3466 3467 // Keep track of the direct virtual bases. 3468 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 3469 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(), 3470 E = ClassDecl->bases_end(); I != E; ++I) { 3471 if (I->isVirtual()) 3472 DirectVBases.insert(I); 3473 } 3474 3475 // Push virtual bases before others. 3476 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 3477 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 3478 3479 if (CXXCtorInitializer *Value 3480 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) { 3481 // [class.base.init]p7, per DR257: 3482 // A mem-initializer where the mem-initializer-id names a virtual base 3483 // class is ignored during execution of a constructor of any class that 3484 // is not the most derived class. 3485 if (ClassDecl->isAbstract()) { 3486 // FIXME: Provide a fixit to remove the base specifier. This requires 3487 // tracking the location of the associated comma for a base specifier. 3488 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 3489 << VBase->getType() << ClassDecl; 3490 DiagnoseAbstractType(ClassDecl); 3491 } 3492 3493 Info.AllToInit.push_back(Value); 3494 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 3495 // [class.base.init]p8, per DR257: 3496 // If a given [...] base class is not named by a mem-initializer-id 3497 // [...] and the entity is not a virtual base class of an abstract 3498 // class, then [...] the entity is default-initialized. 3499 bool IsInheritedVirtualBase = !DirectVBases.count(VBase); 3500 CXXCtorInitializer *CXXBaseInit; 3501 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3502 VBase, IsInheritedVirtualBase, 3503 CXXBaseInit)) { 3504 HadError = true; 3505 continue; 3506 } 3507 3508 Info.AllToInit.push_back(CXXBaseInit); 3509 } 3510 } 3511 3512 // Non-virtual bases. 3513 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 3514 E = ClassDecl->bases_end(); Base != E; ++Base) { 3515 // Virtuals are in the virtual base list and already constructed. 3516 if (Base->isVirtual()) 3517 continue; 3518 3519 if (CXXCtorInitializer *Value 3520 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) { 3521 Info.AllToInit.push_back(Value); 3522 } else if (!AnyErrors) { 3523 CXXCtorInitializer *CXXBaseInit; 3524 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3525 Base, /*IsInheritedVirtualBase=*/false, 3526 CXXBaseInit)) { 3527 HadError = true; 3528 continue; 3529 } 3530 3531 Info.AllToInit.push_back(CXXBaseInit); 3532 } 3533 } 3534 3535 // Fields. 3536 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(), 3537 MemEnd = ClassDecl->decls_end(); 3538 Mem != MemEnd; ++Mem) { 3539 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) { 3540 // C++ [class.bit]p2: 3541 // A declaration for a bit-field that omits the identifier declares an 3542 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 3543 // initialized. 3544 if (F->isUnnamedBitfield()) 3545 continue; 3546 3547 // If we're not generating the implicit copy/move constructor, then we'll 3548 // handle anonymous struct/union fields based on their individual 3549 // indirect fields. 3550 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 3551 continue; 3552 3553 if (CollectFieldInitializer(*this, Info, F)) 3554 HadError = true; 3555 continue; 3556 } 3557 3558 // Beyond this point, we only consider default initialization. 3559 if (Info.isImplicitCopyOrMove()) 3560 continue; 3561 3562 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) { 3563 if (F->getType()->isIncompleteArrayType()) { 3564 assert(ClassDecl->hasFlexibleArrayMember() && 3565 "Incomplete array type is not valid"); 3566 continue; 3567 } 3568 3569 // Initialize each field of an anonymous struct individually. 3570 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 3571 HadError = true; 3572 3573 continue; 3574 } 3575 } 3576 3577 unsigned NumInitializers = Info.AllToInit.size(); 3578 if (NumInitializers > 0) { 3579 Constructor->setNumCtorInitializers(NumInitializers); 3580 CXXCtorInitializer **baseOrMemberInitializers = 3581 new (Context) CXXCtorInitializer*[NumInitializers]; 3582 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 3583 NumInitializers * sizeof(CXXCtorInitializer*)); 3584 Constructor->setCtorInitializers(baseOrMemberInitializers); 3585 3586 // Constructors implicitly reference the base and member 3587 // destructors. 3588 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 3589 Constructor->getParent()); 3590 } 3591 3592 return HadError; 3593} 3594 3595static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 3596 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 3597 const RecordDecl *RD = RT->getDecl(); 3598 if (RD->isAnonymousStructOrUnion()) { 3599 for (RecordDecl::field_iterator Field = RD->field_begin(), 3600 E = RD->field_end(); Field != E; ++Field) 3601 PopulateKeysForFields(*Field, IdealInits); 3602 return; 3603 } 3604 } 3605 IdealInits.push_back(Field); 3606} 3607 3608static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 3609 return Context.getCanonicalType(BaseType).getTypePtr(); 3610} 3611 3612static const void *GetKeyForMember(ASTContext &Context, 3613 CXXCtorInitializer *Member) { 3614 if (!Member->isAnyMemberInitializer()) 3615 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 3616 3617 return Member->getAnyMember(); 3618} 3619 3620static void DiagnoseBaseOrMemInitializerOrder( 3621 Sema &SemaRef, const CXXConstructorDecl *Constructor, 3622 ArrayRef<CXXCtorInitializer *> Inits) { 3623 if (Constructor->getDeclContext()->isDependentContext()) 3624 return; 3625 3626 // Don't check initializers order unless the warning is enabled at the 3627 // location of at least one initializer. 3628 bool ShouldCheckOrder = false; 3629 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 3630 CXXCtorInitializer *Init = Inits[InitIndex]; 3631 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order, 3632 Init->getSourceLocation()) 3633 != DiagnosticsEngine::Ignored) { 3634 ShouldCheckOrder = true; 3635 break; 3636 } 3637 } 3638 if (!ShouldCheckOrder) 3639 return; 3640 3641 // Build the list of bases and members in the order that they'll 3642 // actually be initialized. The explicit initializers should be in 3643 // this same order but may be missing things. 3644 SmallVector<const void*, 32> IdealInitKeys; 3645 3646 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 3647 3648 // 1. Virtual bases. 3649 for (CXXRecordDecl::base_class_const_iterator VBase = 3650 ClassDecl->vbases_begin(), 3651 E = ClassDecl->vbases_end(); VBase != E; ++VBase) 3652 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType())); 3653 3654 // 2. Non-virtual bases. 3655 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(), 3656 E = ClassDecl->bases_end(); Base != E; ++Base) { 3657 if (Base->isVirtual()) 3658 continue; 3659 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType())); 3660 } 3661 3662 // 3. Direct fields. 3663 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 3664 E = ClassDecl->field_end(); Field != E; ++Field) { 3665 if (Field->isUnnamedBitfield()) 3666 continue; 3667 3668 PopulateKeysForFields(*Field, IdealInitKeys); 3669 } 3670 3671 unsigned NumIdealInits = IdealInitKeys.size(); 3672 unsigned IdealIndex = 0; 3673 3674 CXXCtorInitializer *PrevInit = 0; 3675 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 3676 CXXCtorInitializer *Init = Inits[InitIndex]; 3677 const void *InitKey = GetKeyForMember(SemaRef.Context, Init); 3678 3679 // Scan forward to try to find this initializer in the idealized 3680 // initializers list. 3681 for (; IdealIndex != NumIdealInits; ++IdealIndex) 3682 if (InitKey == IdealInitKeys[IdealIndex]) 3683 break; 3684 3685 // If we didn't find this initializer, it must be because we 3686 // scanned past it on a previous iteration. That can only 3687 // happen if we're out of order; emit a warning. 3688 if (IdealIndex == NumIdealInits && PrevInit) { 3689 Sema::SemaDiagnosticBuilder D = 3690 SemaRef.Diag(PrevInit->getSourceLocation(), 3691 diag::warn_initializer_out_of_order); 3692 3693 if (PrevInit->isAnyMemberInitializer()) 3694 D << 0 << PrevInit->getAnyMember()->getDeclName(); 3695 else 3696 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 3697 3698 if (Init->isAnyMemberInitializer()) 3699 D << 0 << Init->getAnyMember()->getDeclName(); 3700 else 3701 D << 1 << Init->getTypeSourceInfo()->getType(); 3702 3703 // Move back to the initializer's location in the ideal list. 3704 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 3705 if (InitKey == IdealInitKeys[IdealIndex]) 3706 break; 3707 3708 assert(IdealIndex != NumIdealInits && 3709 "initializer not found in initializer list"); 3710 } 3711 3712 PrevInit = Init; 3713 } 3714} 3715 3716namespace { 3717bool CheckRedundantInit(Sema &S, 3718 CXXCtorInitializer *Init, 3719 CXXCtorInitializer *&PrevInit) { 3720 if (!PrevInit) { 3721 PrevInit = Init; 3722 return false; 3723 } 3724 3725 if (FieldDecl *Field = Init->getAnyMember()) 3726 S.Diag(Init->getSourceLocation(), 3727 diag::err_multiple_mem_initialization) 3728 << Field->getDeclName() 3729 << Init->getSourceRange(); 3730 else { 3731 const Type *BaseClass = Init->getBaseClass(); 3732 assert(BaseClass && "neither field nor base"); 3733 S.Diag(Init->getSourceLocation(), 3734 diag::err_multiple_base_initialization) 3735 << QualType(BaseClass, 0) 3736 << Init->getSourceRange(); 3737 } 3738 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 3739 << 0 << PrevInit->getSourceRange(); 3740 3741 return true; 3742} 3743 3744typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 3745typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 3746 3747bool CheckRedundantUnionInit(Sema &S, 3748 CXXCtorInitializer *Init, 3749 RedundantUnionMap &Unions) { 3750 FieldDecl *Field = Init->getAnyMember(); 3751 RecordDecl *Parent = Field->getParent(); 3752 NamedDecl *Child = Field; 3753 3754 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 3755 if (Parent->isUnion()) { 3756 UnionEntry &En = Unions[Parent]; 3757 if (En.first && En.first != Child) { 3758 S.Diag(Init->getSourceLocation(), 3759 diag::err_multiple_mem_union_initialization) 3760 << Field->getDeclName() 3761 << Init->getSourceRange(); 3762 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 3763 << 0 << En.second->getSourceRange(); 3764 return true; 3765 } 3766 if (!En.first) { 3767 En.first = Child; 3768 En.second = Init; 3769 } 3770 if (!Parent->isAnonymousStructOrUnion()) 3771 return false; 3772 } 3773 3774 Child = Parent; 3775 Parent = cast<RecordDecl>(Parent->getDeclContext()); 3776 } 3777 3778 return false; 3779} 3780} 3781 3782// Diagnose value-uses of fields to initialize themselves, e.g. 3783// foo(foo) 3784// where foo is not also a parameter to the constructor. 3785// Also diagnose across field uninitialized use such as 3786// x(y), y(x) 3787// TODO: implement -Wuninitialized and fold this into that framework. 3788static void DiagnoseUnitializedFields( 3789 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 3790 3791 if (SemaRef.getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, 3792 Constructor->getLocation()) 3793 == DiagnosticsEngine::Ignored) { 3794 return; 3795 } 3796 3797 const CXXRecordDecl *RD = Constructor->getParent(); 3798 3799 // Holds fields that are uninitialized. 3800 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 3801 3802 for (DeclContext::decl_iterator I = RD->decls_begin(), E = RD->decls_end(); 3803 I != E; ++I) { 3804 if (FieldDecl *FD = dyn_cast<FieldDecl>(*I)) { 3805 UninitializedFields.insert(FD); 3806 } else if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*I)) { 3807 UninitializedFields.insert(IFD->getAnonField()); 3808 } 3809 } 3810 3811 // Fields already checked when processing the in class initializers. 3812 llvm::SmallPtrSet<ValueDecl*, 4> 3813 InClassUninitializedFields = UninitializedFields; 3814 3815 for (CXXConstructorDecl::init_const_iterator FieldInit = 3816 Constructor->init_begin(), 3817 FieldInitEnd = Constructor->init_end(); 3818 FieldInit != FieldInitEnd; ++FieldInit) { 3819 3820 FieldDecl *Field = (*FieldInit)->getAnyMember(); 3821 Expr *InitExpr = (*FieldInit)->getInit(); 3822 3823 if (!Field) { 3824 CheckInitExprContainsUninitializedFields( 3825 SemaRef, InitExpr, 0, UninitializedFields, 3826 false/*WarnOnSelfReference*/); 3827 continue; 3828 } 3829 3830 if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 3831 // This field is initialized with an in-class initailzer. Remove the 3832 // fields already checked to prevent duplicate warnings. 3833 llvm::SmallPtrSet<ValueDecl*, 4> DiffSet = UninitializedFields; 3834 for (llvm::SmallPtrSet<ValueDecl*, 4>::iterator 3835 I = InClassUninitializedFields.begin(), 3836 E = InClassUninitializedFields.end(); 3837 I != E; ++I) { 3838 DiffSet.erase(*I); 3839 } 3840 CheckInitExprContainsUninitializedFields( 3841 SemaRef, Default->getExpr(), Field, DiffSet, 3842 DiffSet.count(Field), Constructor); 3843 3844 // Update the unitialized field sets. 3845 CheckInitExprContainsUninitializedFields( 3846 SemaRef, Default->getExpr(), 0, UninitializedFields, 3847 false); 3848 CheckInitExprContainsUninitializedFields( 3849 SemaRef, Default->getExpr(), 0, InClassUninitializedFields, 3850 false); 3851 } else { 3852 CheckInitExprContainsUninitializedFields( 3853 SemaRef, InitExpr, Field, UninitializedFields, 3854 UninitializedFields.count(Field)); 3855 if (Expr* InClassInit = Field->getInClassInitializer()) { 3856 CheckInitExprContainsUninitializedFields( 3857 SemaRef, InClassInit, 0, InClassUninitializedFields, 3858 false); 3859 } 3860 } 3861 UninitializedFields.erase(Field); 3862 InClassUninitializedFields.erase(Field); 3863 } 3864} 3865 3866/// ActOnMemInitializers - Handle the member initializers for a constructor. 3867void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 3868 SourceLocation ColonLoc, 3869 ArrayRef<CXXCtorInitializer*> MemInits, 3870 bool AnyErrors) { 3871 if (!ConstructorDecl) 3872 return; 3873 3874 AdjustDeclIfTemplate(ConstructorDecl); 3875 3876 CXXConstructorDecl *Constructor 3877 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 3878 3879 if (!Constructor) { 3880 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 3881 return; 3882 } 3883 3884 // Mapping for the duplicate initializers check. 3885 // For member initializers, this is keyed with a FieldDecl*. 3886 // For base initializers, this is keyed with a Type*. 3887 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 3888 3889 // Mapping for the inconsistent anonymous-union initializers check. 3890 RedundantUnionMap MemberUnions; 3891 3892 bool HadError = false; 3893 for (unsigned i = 0; i < MemInits.size(); i++) { 3894 CXXCtorInitializer *Init = MemInits[i]; 3895 3896 // Set the source order index. 3897 Init->setSourceOrder(i); 3898 3899 if (Init->isAnyMemberInitializer()) { 3900 FieldDecl *Field = Init->getAnyMember(); 3901 if (CheckRedundantInit(*this, Init, Members[Field]) || 3902 CheckRedundantUnionInit(*this, Init, MemberUnions)) 3903 HadError = true; 3904 } else if (Init->isBaseInitializer()) { 3905 const void *Key = 3906 GetKeyForBase(Context, QualType(Init->getBaseClass(), 0)); 3907 if (CheckRedundantInit(*this, Init, Members[Key])) 3908 HadError = true; 3909 } else { 3910 assert(Init->isDelegatingInitializer()); 3911 // This must be the only initializer 3912 if (MemInits.size() != 1) { 3913 Diag(Init->getSourceLocation(), 3914 diag::err_delegating_initializer_alone) 3915 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 3916 // We will treat this as being the only initializer. 3917 } 3918 SetDelegatingInitializer(Constructor, MemInits[i]); 3919 // Return immediately as the initializer is set. 3920 return; 3921 } 3922 } 3923 3924 if (HadError) 3925 return; 3926 3927 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 3928 3929 SetCtorInitializers(Constructor, AnyErrors, MemInits); 3930 3931 DiagnoseUnitializedFields(*this, Constructor); 3932} 3933 3934void 3935Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 3936 CXXRecordDecl *ClassDecl) { 3937 // Ignore dependent contexts. Also ignore unions, since their members never 3938 // have destructors implicitly called. 3939 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 3940 return; 3941 3942 // FIXME: all the access-control diagnostics are positioned on the 3943 // field/base declaration. That's probably good; that said, the 3944 // user might reasonably want to know why the destructor is being 3945 // emitted, and we currently don't say. 3946 3947 // Non-static data members. 3948 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(), 3949 E = ClassDecl->field_end(); I != E; ++I) { 3950 FieldDecl *Field = *I; 3951 if (Field->isInvalidDecl()) 3952 continue; 3953 3954 // Don't destroy incomplete or zero-length arrays. 3955 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 3956 continue; 3957 3958 QualType FieldType = Context.getBaseElementType(Field->getType()); 3959 3960 const RecordType* RT = FieldType->getAs<RecordType>(); 3961 if (!RT) 3962 continue; 3963 3964 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3965 if (FieldClassDecl->isInvalidDecl()) 3966 continue; 3967 if (FieldClassDecl->hasIrrelevantDestructor()) 3968 continue; 3969 // The destructor for an implicit anonymous union member is never invoked. 3970 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 3971 continue; 3972 3973 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 3974 assert(Dtor && "No dtor found for FieldClassDecl!"); 3975 CheckDestructorAccess(Field->getLocation(), Dtor, 3976 PDiag(diag::err_access_dtor_field) 3977 << Field->getDeclName() 3978 << FieldType); 3979 3980 MarkFunctionReferenced(Location, Dtor); 3981 DiagnoseUseOfDecl(Dtor, Location); 3982 } 3983 3984 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 3985 3986 // Bases. 3987 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 3988 E = ClassDecl->bases_end(); Base != E; ++Base) { 3989 // Bases are always records in a well-formed non-dependent class. 3990 const RecordType *RT = Base->getType()->getAs<RecordType>(); 3991 3992 // Remember direct virtual bases. 3993 if (Base->isVirtual()) 3994 DirectVirtualBases.insert(RT); 3995 3996 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3997 // If our base class is invalid, we probably can't get its dtor anyway. 3998 if (BaseClassDecl->isInvalidDecl()) 3999 continue; 4000 if (BaseClassDecl->hasIrrelevantDestructor()) 4001 continue; 4002 4003 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 4004 assert(Dtor && "No dtor found for BaseClassDecl!"); 4005 4006 // FIXME: caret should be on the start of the class name 4007 CheckDestructorAccess(Base->getLocStart(), Dtor, 4008 PDiag(diag::err_access_dtor_base) 4009 << Base->getType() 4010 << Base->getSourceRange(), 4011 Context.getTypeDeclType(ClassDecl)); 4012 4013 MarkFunctionReferenced(Location, Dtor); 4014 DiagnoseUseOfDecl(Dtor, Location); 4015 } 4016 4017 // Virtual bases. 4018 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 4019 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 4020 4021 // Bases are always records in a well-formed non-dependent class. 4022 const RecordType *RT = VBase->getType()->castAs<RecordType>(); 4023 4024 // Ignore direct virtual bases. 4025 if (DirectVirtualBases.count(RT)) 4026 continue; 4027 4028 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4029 // If our base class is invalid, we probably can't get its dtor anyway. 4030 if (BaseClassDecl->isInvalidDecl()) 4031 continue; 4032 if (BaseClassDecl->hasIrrelevantDestructor()) 4033 continue; 4034 4035 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 4036 assert(Dtor && "No dtor found for BaseClassDecl!"); 4037 if (CheckDestructorAccess( 4038 ClassDecl->getLocation(), Dtor, 4039 PDiag(diag::err_access_dtor_vbase) 4040 << Context.getTypeDeclType(ClassDecl) << VBase->getType(), 4041 Context.getTypeDeclType(ClassDecl)) == 4042 AR_accessible) { 4043 CheckDerivedToBaseConversion( 4044 Context.getTypeDeclType(ClassDecl), VBase->getType(), 4045 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 4046 SourceRange(), DeclarationName(), 0); 4047 } 4048 4049 MarkFunctionReferenced(Location, Dtor); 4050 DiagnoseUseOfDecl(Dtor, Location); 4051 } 4052} 4053 4054void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 4055 if (!CDtorDecl) 4056 return; 4057 4058 if (CXXConstructorDecl *Constructor 4059 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) 4060 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 4061} 4062 4063bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 4064 unsigned DiagID, AbstractDiagSelID SelID) { 4065 class NonAbstractTypeDiagnoser : public TypeDiagnoser { 4066 unsigned DiagID; 4067 AbstractDiagSelID SelID; 4068 4069 public: 4070 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID) 4071 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { } 4072 4073 void diagnose(Sema &S, SourceLocation Loc, QualType T) LLVM_OVERRIDE { 4074 if (Suppressed) return; 4075 if (SelID == -1) 4076 S.Diag(Loc, DiagID) << T; 4077 else 4078 S.Diag(Loc, DiagID) << SelID << T; 4079 } 4080 } Diagnoser(DiagID, SelID); 4081 4082 return RequireNonAbstractType(Loc, T, Diagnoser); 4083} 4084 4085bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 4086 TypeDiagnoser &Diagnoser) { 4087 if (!getLangOpts().CPlusPlus) 4088 return false; 4089 4090 if (const ArrayType *AT = Context.getAsArrayType(T)) 4091 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 4092 4093 if (const PointerType *PT = T->getAs<PointerType>()) { 4094 // Find the innermost pointer type. 4095 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 4096 PT = T; 4097 4098 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 4099 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 4100 } 4101 4102 const RecordType *RT = T->getAs<RecordType>(); 4103 if (!RT) 4104 return false; 4105 4106 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 4107 4108 // We can't answer whether something is abstract until it has a 4109 // definition. If it's currently being defined, we'll walk back 4110 // over all the declarations when we have a full definition. 4111 const CXXRecordDecl *Def = RD->getDefinition(); 4112 if (!Def || Def->isBeingDefined()) 4113 return false; 4114 4115 if (!RD->isAbstract()) 4116 return false; 4117 4118 Diagnoser.diagnose(*this, Loc, T); 4119 DiagnoseAbstractType(RD); 4120 4121 return true; 4122} 4123 4124void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 4125 // Check if we've already emitted the list of pure virtual functions 4126 // for this class. 4127 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 4128 return; 4129 4130 // If the diagnostic is suppressed, don't emit the notes. We're only 4131 // going to emit them once, so try to attach them to a diagnostic we're 4132 // actually going to show. 4133 if (Diags.isLastDiagnosticIgnored()) 4134 return; 4135 4136 CXXFinalOverriderMap FinalOverriders; 4137 RD->getFinalOverriders(FinalOverriders); 4138 4139 // Keep a set of seen pure methods so we won't diagnose the same method 4140 // more than once. 4141 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 4142 4143 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 4144 MEnd = FinalOverriders.end(); 4145 M != MEnd; 4146 ++M) { 4147 for (OverridingMethods::iterator SO = M->second.begin(), 4148 SOEnd = M->second.end(); 4149 SO != SOEnd; ++SO) { 4150 // C++ [class.abstract]p4: 4151 // A class is abstract if it contains or inherits at least one 4152 // pure virtual function for which the final overrider is pure 4153 // virtual. 4154 4155 // 4156 if (SO->second.size() != 1) 4157 continue; 4158 4159 if (!SO->second.front().Method->isPure()) 4160 continue; 4161 4162 if (!SeenPureMethods.insert(SO->second.front().Method)) 4163 continue; 4164 4165 Diag(SO->second.front().Method->getLocation(), 4166 diag::note_pure_virtual_function) 4167 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 4168 } 4169 } 4170 4171 if (!PureVirtualClassDiagSet) 4172 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 4173 PureVirtualClassDiagSet->insert(RD); 4174} 4175 4176namespace { 4177struct AbstractUsageInfo { 4178 Sema &S; 4179 CXXRecordDecl *Record; 4180 CanQualType AbstractType; 4181 bool Invalid; 4182 4183 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 4184 : S(S), Record(Record), 4185 AbstractType(S.Context.getCanonicalType( 4186 S.Context.getTypeDeclType(Record))), 4187 Invalid(false) {} 4188 4189 void DiagnoseAbstractType() { 4190 if (Invalid) return; 4191 S.DiagnoseAbstractType(Record); 4192 Invalid = true; 4193 } 4194 4195 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 4196}; 4197 4198struct CheckAbstractUsage { 4199 AbstractUsageInfo &Info; 4200 const NamedDecl *Ctx; 4201 4202 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 4203 : Info(Info), Ctx(Ctx) {} 4204 4205 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 4206 switch (TL.getTypeLocClass()) { 4207#define ABSTRACT_TYPELOC(CLASS, PARENT) 4208#define TYPELOC(CLASS, PARENT) \ 4209 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 4210#include "clang/AST/TypeLocNodes.def" 4211 } 4212 } 4213 4214 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4215 Visit(TL.getResultLoc(), Sema::AbstractReturnType); 4216 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 4217 if (!TL.getArg(I)) 4218 continue; 4219 4220 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo(); 4221 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 4222 } 4223 } 4224 4225 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4226 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 4227 } 4228 4229 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4230 // Visit the type parameters from a permissive context. 4231 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 4232 TemplateArgumentLoc TAL = TL.getArgLoc(I); 4233 if (TAL.getArgument().getKind() == TemplateArgument::Type) 4234 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 4235 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 4236 // TODO: other template argument types? 4237 } 4238 } 4239 4240 // Visit pointee types from a permissive context. 4241#define CheckPolymorphic(Type) \ 4242 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 4243 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 4244 } 4245 CheckPolymorphic(PointerTypeLoc) 4246 CheckPolymorphic(ReferenceTypeLoc) 4247 CheckPolymorphic(MemberPointerTypeLoc) 4248 CheckPolymorphic(BlockPointerTypeLoc) 4249 CheckPolymorphic(AtomicTypeLoc) 4250 4251 /// Handle all the types we haven't given a more specific 4252 /// implementation for above. 4253 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 4254 // Every other kind of type that we haven't called out already 4255 // that has an inner type is either (1) sugar or (2) contains that 4256 // inner type in some way as a subobject. 4257 if (TypeLoc Next = TL.getNextTypeLoc()) 4258 return Visit(Next, Sel); 4259 4260 // If there's no inner type and we're in a permissive context, 4261 // don't diagnose. 4262 if (Sel == Sema::AbstractNone) return; 4263 4264 // Check whether the type matches the abstract type. 4265 QualType T = TL.getType(); 4266 if (T->isArrayType()) { 4267 Sel = Sema::AbstractArrayType; 4268 T = Info.S.Context.getBaseElementType(T); 4269 } 4270 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 4271 if (CT != Info.AbstractType) return; 4272 4273 // It matched; do some magic. 4274 if (Sel == Sema::AbstractArrayType) { 4275 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 4276 << T << TL.getSourceRange(); 4277 } else { 4278 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 4279 << Sel << T << TL.getSourceRange(); 4280 } 4281 Info.DiagnoseAbstractType(); 4282 } 4283}; 4284 4285void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 4286 Sema::AbstractDiagSelID Sel) { 4287 CheckAbstractUsage(*this, D).Visit(TL, Sel); 4288} 4289 4290} 4291 4292/// Check for invalid uses of an abstract type in a method declaration. 4293static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4294 CXXMethodDecl *MD) { 4295 // No need to do the check on definitions, which require that 4296 // the return/param types be complete. 4297 if (MD->doesThisDeclarationHaveABody()) 4298 return; 4299 4300 // For safety's sake, just ignore it if we don't have type source 4301 // information. This should never happen for non-implicit methods, 4302 // but... 4303 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 4304 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 4305} 4306 4307/// Check for invalid uses of an abstract type within a class definition. 4308static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4309 CXXRecordDecl *RD) { 4310 for (CXXRecordDecl::decl_iterator 4311 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) { 4312 Decl *D = *I; 4313 if (D->isImplicit()) continue; 4314 4315 // Methods and method templates. 4316 if (isa<CXXMethodDecl>(D)) { 4317 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 4318 } else if (isa<FunctionTemplateDecl>(D)) { 4319 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 4320 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 4321 4322 // Fields and static variables. 4323 } else if (isa<FieldDecl>(D)) { 4324 FieldDecl *FD = cast<FieldDecl>(D); 4325 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 4326 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 4327 } else if (isa<VarDecl>(D)) { 4328 VarDecl *VD = cast<VarDecl>(D); 4329 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 4330 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 4331 4332 // Nested classes and class templates. 4333 } else if (isa<CXXRecordDecl>(D)) { 4334 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 4335 } else if (isa<ClassTemplateDecl>(D)) { 4336 CheckAbstractClassUsage(Info, 4337 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 4338 } 4339 } 4340} 4341 4342/// \brief Perform semantic checks on a class definition that has been 4343/// completing, introducing implicitly-declared members, checking for 4344/// abstract types, etc. 4345void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 4346 if (!Record) 4347 return; 4348 4349 if (Record->isAbstract() && !Record->isInvalidDecl()) { 4350 AbstractUsageInfo Info(*this, Record); 4351 CheckAbstractClassUsage(Info, Record); 4352 } 4353 4354 // If this is not an aggregate type and has no user-declared constructor, 4355 // complain about any non-static data members of reference or const scalar 4356 // type, since they will never get initializers. 4357 if (!Record->isInvalidDecl() && !Record->isDependentType() && 4358 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 4359 !Record->isLambda()) { 4360 bool Complained = false; 4361 for (RecordDecl::field_iterator F = Record->field_begin(), 4362 FEnd = Record->field_end(); 4363 F != FEnd; ++F) { 4364 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 4365 continue; 4366 4367 if (F->getType()->isReferenceType() || 4368 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 4369 if (!Complained) { 4370 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 4371 << Record->getTagKind() << Record; 4372 Complained = true; 4373 } 4374 4375 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 4376 << F->getType()->isReferenceType() 4377 << F->getDeclName(); 4378 } 4379 } 4380 } 4381 4382 if (Record->isDynamicClass() && !Record->isDependentType()) 4383 DynamicClasses.push_back(Record); 4384 4385 if (Record->getIdentifier()) { 4386 // C++ [class.mem]p13: 4387 // If T is the name of a class, then each of the following shall have a 4388 // name different from T: 4389 // - every member of every anonymous union that is a member of class T. 4390 // 4391 // C++ [class.mem]p14: 4392 // In addition, if class T has a user-declared constructor (12.1), every 4393 // non-static data member of class T shall have a name different from T. 4394 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 4395 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 4396 ++I) { 4397 NamedDecl *D = *I; 4398 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 4399 isa<IndirectFieldDecl>(D)) { 4400 Diag(D->getLocation(), diag::err_member_name_of_class) 4401 << D->getDeclName(); 4402 break; 4403 } 4404 } 4405 } 4406 4407 // Warn if the class has virtual methods but non-virtual public destructor. 4408 if (Record->isPolymorphic() && !Record->isDependentType()) { 4409 CXXDestructorDecl *dtor = Record->getDestructor(); 4410 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) 4411 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 4412 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 4413 } 4414 4415 if (Record->isAbstract()) { 4416 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 4417 Diag(Record->getLocation(), diag::warn_abstract_final_class) 4418 << FA->isSpelledAsSealed(); 4419 DiagnoseAbstractType(Record); 4420 } 4421 } 4422 4423 if (!Record->isDependentType()) { 4424 for (CXXRecordDecl::method_iterator M = Record->method_begin(), 4425 MEnd = Record->method_end(); 4426 M != MEnd; ++M) { 4427 // See if a method overloads virtual methods in a base 4428 // class without overriding any. 4429 if (!M->isStatic()) 4430 DiagnoseHiddenVirtualMethods(*M); 4431 4432 // Check whether the explicitly-defaulted special members are valid. 4433 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) 4434 CheckExplicitlyDefaultedSpecialMember(*M); 4435 4436 // For an explicitly defaulted or deleted special member, we defer 4437 // determining triviality until the class is complete. That time is now! 4438 if (!M->isImplicit() && !M->isUserProvided()) { 4439 CXXSpecialMember CSM = getSpecialMember(*M); 4440 if (CSM != CXXInvalid) { 4441 M->setTrivial(SpecialMemberIsTrivial(*M, CSM)); 4442 4443 // Inform the class that we've finished declaring this member. 4444 Record->finishedDefaultedOrDeletedMember(*M); 4445 } 4446 } 4447 } 4448 } 4449 4450 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member 4451 // function that is not a constructor declares that member function to be 4452 // const. [...] The class of which that function is a member shall be 4453 // a literal type. 4454 // 4455 // If the class has virtual bases, any constexpr members will already have 4456 // been diagnosed by the checks performed on the member declaration, so 4457 // suppress this (less useful) diagnostic. 4458 // 4459 // We delay this until we know whether an explicitly-defaulted (or deleted) 4460 // destructor for the class is trivial. 4461 if (LangOpts.CPlusPlus11 && !Record->isDependentType() && 4462 !Record->isLiteral() && !Record->getNumVBases()) { 4463 for (CXXRecordDecl::method_iterator M = Record->method_begin(), 4464 MEnd = Record->method_end(); 4465 M != MEnd; ++M) { 4466 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) { 4467 switch (Record->getTemplateSpecializationKind()) { 4468 case TSK_ImplicitInstantiation: 4469 case TSK_ExplicitInstantiationDeclaration: 4470 case TSK_ExplicitInstantiationDefinition: 4471 // If a template instantiates to a non-literal type, but its members 4472 // instantiate to constexpr functions, the template is technically 4473 // ill-formed, but we allow it for sanity. 4474 continue; 4475 4476 case TSK_Undeclared: 4477 case TSK_ExplicitSpecialization: 4478 RequireLiteralType(M->getLocation(), Context.getRecordType(Record), 4479 diag::err_constexpr_method_non_literal); 4480 break; 4481 } 4482 4483 // Only produce one error per class. 4484 break; 4485 } 4486 } 4487 } 4488 4489 // Check to see if we're trying to lay out a struct using the ms_struct 4490 // attribute that is dynamic. 4491 if (Record->isMsStruct(Context) && Record->isDynamicClass()) { 4492 Diag(Record->getLocation(), diag::warn_pragma_ms_struct_failed); 4493 Record->dropAttr<MsStructAttr>(); 4494 } 4495 4496 // Declare inheriting constructors. We do this eagerly here because: 4497 // - The standard requires an eager diagnostic for conflicting inheriting 4498 // constructors from different classes. 4499 // - The lazy declaration of the other implicit constructors is so as to not 4500 // waste space and performance on classes that are not meant to be 4501 // instantiated (e.g. meta-functions). This doesn't apply to classes that 4502 // have inheriting constructors. 4503 DeclareInheritingConstructors(Record); 4504} 4505 4506/// Is the special member function which would be selected to perform the 4507/// specified operation on the specified class type a constexpr constructor? 4508static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 4509 Sema::CXXSpecialMember CSM, 4510 bool ConstArg) { 4511 Sema::SpecialMemberOverloadResult *SMOR = 4512 S.LookupSpecialMember(ClassDecl, CSM, ConstArg, 4513 false, false, false, false); 4514 if (!SMOR || !SMOR->getMethod()) 4515 // A constructor we wouldn't select can't be "involved in initializing" 4516 // anything. 4517 return true; 4518 return SMOR->getMethod()->isConstexpr(); 4519} 4520 4521/// Determine whether the specified special member function would be constexpr 4522/// if it were implicitly defined. 4523static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 4524 Sema::CXXSpecialMember CSM, 4525 bool ConstArg) { 4526 if (!S.getLangOpts().CPlusPlus11) 4527 return false; 4528 4529 // C++11 [dcl.constexpr]p4: 4530 // In the definition of a constexpr constructor [...] 4531 bool Ctor = true; 4532 switch (CSM) { 4533 case Sema::CXXDefaultConstructor: 4534 // Since default constructor lookup is essentially trivial (and cannot 4535 // involve, for instance, template instantiation), we compute whether a 4536 // defaulted default constructor is constexpr directly within CXXRecordDecl. 4537 // 4538 // This is important for performance; we need to know whether the default 4539 // constructor is constexpr to determine whether the type is a literal type. 4540 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 4541 4542 case Sema::CXXCopyConstructor: 4543 case Sema::CXXMoveConstructor: 4544 // For copy or move constructors, we need to perform overload resolution. 4545 break; 4546 4547 case Sema::CXXCopyAssignment: 4548 case Sema::CXXMoveAssignment: 4549 if (!S.getLangOpts().CPlusPlus1y) 4550 return false; 4551 // In C++1y, we need to perform overload resolution. 4552 Ctor = false; 4553 break; 4554 4555 case Sema::CXXDestructor: 4556 case Sema::CXXInvalid: 4557 return false; 4558 } 4559 4560 // -- if the class is a non-empty union, or for each non-empty anonymous 4561 // union member of a non-union class, exactly one non-static data member 4562 // shall be initialized; [DR1359] 4563 // 4564 // If we squint, this is guaranteed, since exactly one non-static data member 4565 // will be initialized (if the constructor isn't deleted), we just don't know 4566 // which one. 4567 if (Ctor && ClassDecl->isUnion()) 4568 return true; 4569 4570 // -- the class shall not have any virtual base classes; 4571 if (Ctor && ClassDecl->getNumVBases()) 4572 return false; 4573 4574 // C++1y [class.copy]p26: 4575 // -- [the class] is a literal type, and 4576 if (!Ctor && !ClassDecl->isLiteral()) 4577 return false; 4578 4579 // -- every constructor involved in initializing [...] base class 4580 // sub-objects shall be a constexpr constructor; 4581 // -- the assignment operator selected to copy/move each direct base 4582 // class is a constexpr function, and 4583 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 4584 BEnd = ClassDecl->bases_end(); 4585 B != BEnd; ++B) { 4586 const RecordType *BaseType = B->getType()->getAs<RecordType>(); 4587 if (!BaseType) continue; 4588 4589 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 4590 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg)) 4591 return false; 4592 } 4593 4594 // -- every constructor involved in initializing non-static data members 4595 // [...] shall be a constexpr constructor; 4596 // -- every non-static data member and base class sub-object shall be 4597 // initialized 4598 // -- for each non-stastic data member of X that is of class type (or array 4599 // thereof), the assignment operator selected to copy/move that member is 4600 // a constexpr function 4601 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 4602 FEnd = ClassDecl->field_end(); 4603 F != FEnd; ++F) { 4604 if (F->isInvalidDecl()) 4605 continue; 4606 if (const RecordType *RecordTy = 4607 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 4608 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 4609 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg)) 4610 return false; 4611 } 4612 } 4613 4614 // All OK, it's constexpr! 4615 return true; 4616} 4617 4618static Sema::ImplicitExceptionSpecification 4619computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 4620 switch (S.getSpecialMember(MD)) { 4621 case Sema::CXXDefaultConstructor: 4622 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD); 4623 case Sema::CXXCopyConstructor: 4624 return S.ComputeDefaultedCopyCtorExceptionSpec(MD); 4625 case Sema::CXXCopyAssignment: 4626 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD); 4627 case Sema::CXXMoveConstructor: 4628 return S.ComputeDefaultedMoveCtorExceptionSpec(MD); 4629 case Sema::CXXMoveAssignment: 4630 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD); 4631 case Sema::CXXDestructor: 4632 return S.ComputeDefaultedDtorExceptionSpec(MD); 4633 case Sema::CXXInvalid: 4634 break; 4635 } 4636 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() && 4637 "only special members have implicit exception specs"); 4638 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD)); 4639} 4640 4641static void 4642updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT, 4643 const Sema::ImplicitExceptionSpecification &ExceptSpec) { 4644 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 4645 ExceptSpec.getEPI(EPI); 4646 FD->setType(S.Context.getFunctionType(FPT->getResultType(), 4647 FPT->getArgTypes(), EPI)); 4648} 4649 4650static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 4651 CXXMethodDecl *MD) { 4652 FunctionProtoType::ExtProtoInfo EPI; 4653 4654 // Build an exception specification pointing back at this member. 4655 EPI.ExceptionSpecType = EST_Unevaluated; 4656 EPI.ExceptionSpecDecl = MD; 4657 4658 // Set the calling convention to the default for C++ instance methods. 4659 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 4660 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 4661 /*IsCXXMethod=*/true)); 4662 return EPI; 4663} 4664 4665void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 4666 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 4667 if (FPT->getExceptionSpecType() != EST_Unevaluated) 4668 return; 4669 4670 // Evaluate the exception specification. 4671 ImplicitExceptionSpecification ExceptSpec = 4672 computeImplicitExceptionSpec(*this, Loc, MD); 4673 4674 // Update the type of the special member to use it. 4675 updateExceptionSpec(*this, MD, FPT, ExceptSpec); 4676 4677 // A user-provided destructor can be defined outside the class. When that 4678 // happens, be sure to update the exception specification on both 4679 // declarations. 4680 const FunctionProtoType *CanonicalFPT = 4681 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 4682 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 4683 updateExceptionSpec(*this, MD->getCanonicalDecl(), 4684 CanonicalFPT, ExceptSpec); 4685} 4686 4687void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 4688 CXXRecordDecl *RD = MD->getParent(); 4689 CXXSpecialMember CSM = getSpecialMember(MD); 4690 4691 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 4692 "not an explicitly-defaulted special member"); 4693 4694 // Whether this was the first-declared instance of the constructor. 4695 // This affects whether we implicitly add an exception spec and constexpr. 4696 bool First = MD == MD->getCanonicalDecl(); 4697 4698 bool HadError = false; 4699 4700 // C++11 [dcl.fct.def.default]p1: 4701 // A function that is explicitly defaulted shall 4702 // -- be a special member function (checked elsewhere), 4703 // -- have the same type (except for ref-qualifiers, and except that a 4704 // copy operation can take a non-const reference) as an implicit 4705 // declaration, and 4706 // -- not have default arguments. 4707 unsigned ExpectedParams = 1; 4708 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 4709 ExpectedParams = 0; 4710 if (MD->getNumParams() != ExpectedParams) { 4711 // This also checks for default arguments: a copy or move constructor with a 4712 // default argument is classified as a default constructor, and assignment 4713 // operations and destructors can't have default arguments. 4714 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 4715 << CSM << MD->getSourceRange(); 4716 HadError = true; 4717 } else if (MD->isVariadic()) { 4718 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 4719 << CSM << MD->getSourceRange(); 4720 HadError = true; 4721 } 4722 4723 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 4724 4725 bool CanHaveConstParam = false; 4726 if (CSM == CXXCopyConstructor) 4727 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 4728 else if (CSM == CXXCopyAssignment) 4729 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 4730 4731 QualType ReturnType = Context.VoidTy; 4732 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 4733 // Check for return type matching. 4734 ReturnType = Type->getResultType(); 4735 QualType ExpectedReturnType = 4736 Context.getLValueReferenceType(Context.getTypeDeclType(RD)); 4737 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 4738 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 4739 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 4740 HadError = true; 4741 } 4742 4743 // A defaulted special member cannot have cv-qualifiers. 4744 if (Type->getTypeQuals()) { 4745 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 4746 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y; 4747 HadError = true; 4748 } 4749 } 4750 4751 // Check for parameter type matching. 4752 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType(); 4753 bool HasConstParam = false; 4754 if (ExpectedParams && ArgType->isReferenceType()) { 4755 // Argument must be reference to possibly-const T. 4756 QualType ReferentType = ArgType->getPointeeType(); 4757 HasConstParam = ReferentType.isConstQualified(); 4758 4759 if (ReferentType.isVolatileQualified()) { 4760 Diag(MD->getLocation(), 4761 diag::err_defaulted_special_member_volatile_param) << CSM; 4762 HadError = true; 4763 } 4764 4765 if (HasConstParam && !CanHaveConstParam) { 4766 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 4767 Diag(MD->getLocation(), 4768 diag::err_defaulted_special_member_copy_const_param) 4769 << (CSM == CXXCopyAssignment); 4770 // FIXME: Explain why this special member can't be const. 4771 } else { 4772 Diag(MD->getLocation(), 4773 diag::err_defaulted_special_member_move_const_param) 4774 << (CSM == CXXMoveAssignment); 4775 } 4776 HadError = true; 4777 } 4778 } else if (ExpectedParams) { 4779 // A copy assignment operator can take its argument by value, but a 4780 // defaulted one cannot. 4781 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 4782 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 4783 HadError = true; 4784 } 4785 4786 // C++11 [dcl.fct.def.default]p2: 4787 // An explicitly-defaulted function may be declared constexpr only if it 4788 // would have been implicitly declared as constexpr, 4789 // Do not apply this rule to members of class templates, since core issue 1358 4790 // makes such functions always instantiate to constexpr functions. For 4791 // functions which cannot be constexpr (for non-constructors in C++11 and for 4792 // destructors in C++1y), this is checked elsewhere. 4793 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 4794 HasConstParam); 4795 if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD) 4796 : isa<CXXConstructorDecl>(MD)) && 4797 MD->isConstexpr() && !Constexpr && 4798 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 4799 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM; 4800 // FIXME: Explain why the special member can't be constexpr. 4801 HadError = true; 4802 } 4803 4804 // and may have an explicit exception-specification only if it is compatible 4805 // with the exception-specification on the implicit declaration. 4806 if (Type->hasExceptionSpec()) { 4807 // Delay the check if this is the first declaration of the special member, 4808 // since we may not have parsed some necessary in-class initializers yet. 4809 if (First) { 4810 // If the exception specification needs to be instantiated, do so now, 4811 // before we clobber it with an EST_Unevaluated specification below. 4812 if (Type->getExceptionSpecType() == EST_Uninstantiated) { 4813 InstantiateExceptionSpec(MD->getLocStart(), MD); 4814 Type = MD->getType()->getAs<FunctionProtoType>(); 4815 } 4816 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type)); 4817 } else 4818 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type); 4819 } 4820 4821 // If a function is explicitly defaulted on its first declaration, 4822 if (First) { 4823 // -- it is implicitly considered to be constexpr if the implicit 4824 // definition would be, 4825 MD->setConstexpr(Constexpr); 4826 4827 // -- it is implicitly considered to have the same exception-specification 4828 // as if it had been implicitly declared, 4829 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 4830 EPI.ExceptionSpecType = EST_Unevaluated; 4831 EPI.ExceptionSpecDecl = MD; 4832 MD->setType(Context.getFunctionType(ReturnType, 4833 ArrayRef<QualType>(&ArgType, 4834 ExpectedParams), 4835 EPI)); 4836 } 4837 4838 if (ShouldDeleteSpecialMember(MD, CSM)) { 4839 if (First) { 4840 SetDeclDeleted(MD, MD->getLocation()); 4841 } else { 4842 // C++11 [dcl.fct.def.default]p4: 4843 // [For a] user-provided explicitly-defaulted function [...] if such a 4844 // function is implicitly defined as deleted, the program is ill-formed. 4845 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 4846 HadError = true; 4847 } 4848 } 4849 4850 if (HadError) 4851 MD->setInvalidDecl(); 4852} 4853 4854/// Check whether the exception specification provided for an 4855/// explicitly-defaulted special member matches the exception specification 4856/// that would have been generated for an implicit special member, per 4857/// C++11 [dcl.fct.def.default]p2. 4858void Sema::CheckExplicitlyDefaultedMemberExceptionSpec( 4859 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) { 4860 // Compute the implicit exception specification. 4861 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false, 4862 /*IsCXXMethod=*/true); 4863 FunctionProtoType::ExtProtoInfo EPI(CC); 4864 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI); 4865 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>( 4866 Context.getFunctionType(Context.VoidTy, None, EPI)); 4867 4868 // Ensure that it matches. 4869 CheckEquivalentExceptionSpec( 4870 PDiag(diag::err_incorrect_defaulted_exception_spec) 4871 << getSpecialMember(MD), PDiag(), 4872 ImplicitType, SourceLocation(), 4873 SpecifiedType, MD->getLocation()); 4874} 4875 4876void Sema::CheckDelayedMemberExceptionSpecs() { 4877 SmallVector<std::pair<const CXXDestructorDecl *, const CXXDestructorDecl *>, 4878 2> Checks; 4879 SmallVector<std::pair<CXXMethodDecl *, const FunctionProtoType *>, 2> Specs; 4880 4881 std::swap(Checks, DelayedDestructorExceptionSpecChecks); 4882 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs); 4883 4884 // Perform any deferred checking of exception specifications for virtual 4885 // destructors. 4886 for (unsigned i = 0, e = Checks.size(); i != e; ++i) { 4887 const CXXDestructorDecl *Dtor = Checks[i].first; 4888 assert(!Dtor->getParent()->isDependentType() && 4889 "Should not ever add destructors of templates into the list."); 4890 CheckOverridingFunctionExceptionSpec(Dtor, Checks[i].second); 4891 } 4892 4893 // Check that any explicitly-defaulted methods have exception specifications 4894 // compatible with their implicit exception specifications. 4895 for (unsigned I = 0, N = Specs.size(); I != N; ++I) 4896 CheckExplicitlyDefaultedMemberExceptionSpec(Specs[I].first, 4897 Specs[I].second); 4898} 4899 4900namespace { 4901struct SpecialMemberDeletionInfo { 4902 Sema &S; 4903 CXXMethodDecl *MD; 4904 Sema::CXXSpecialMember CSM; 4905 bool Diagnose; 4906 4907 // Properties of the special member, computed for convenience. 4908 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg; 4909 SourceLocation Loc; 4910 4911 bool AllFieldsAreConst; 4912 4913 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 4914 Sema::CXXSpecialMember CSM, bool Diagnose) 4915 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose), 4916 IsConstructor(false), IsAssignment(false), IsMove(false), 4917 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()), 4918 AllFieldsAreConst(true) { 4919 switch (CSM) { 4920 case Sema::CXXDefaultConstructor: 4921 case Sema::CXXCopyConstructor: 4922 IsConstructor = true; 4923 break; 4924 case Sema::CXXMoveConstructor: 4925 IsConstructor = true; 4926 IsMove = true; 4927 break; 4928 case Sema::CXXCopyAssignment: 4929 IsAssignment = true; 4930 break; 4931 case Sema::CXXMoveAssignment: 4932 IsAssignment = true; 4933 IsMove = true; 4934 break; 4935 case Sema::CXXDestructor: 4936 break; 4937 case Sema::CXXInvalid: 4938 llvm_unreachable("invalid special member kind"); 4939 } 4940 4941 if (MD->getNumParams()) { 4942 ConstArg = MD->getParamDecl(0)->getType().isConstQualified(); 4943 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified(); 4944 } 4945 } 4946 4947 bool inUnion() const { return MD->getParent()->isUnion(); } 4948 4949 /// Look up the corresponding special member in the given class. 4950 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class, 4951 unsigned Quals) { 4952 unsigned TQ = MD->getTypeQualifiers(); 4953 // cv-qualifiers on class members don't affect default ctor / dtor calls. 4954 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 4955 Quals = 0; 4956 return S.LookupSpecialMember(Class, CSM, 4957 ConstArg || (Quals & Qualifiers::Const), 4958 VolatileArg || (Quals & Qualifiers::Volatile), 4959 MD->getRefQualifier() == RQ_RValue, 4960 TQ & Qualifiers::Const, 4961 TQ & Qualifiers::Volatile); 4962 } 4963 4964 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 4965 4966 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 4967 bool shouldDeleteForField(FieldDecl *FD); 4968 bool shouldDeleteForAllConstMembers(); 4969 4970 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 4971 unsigned Quals); 4972 bool shouldDeleteForSubobjectCall(Subobject Subobj, 4973 Sema::SpecialMemberOverloadResult *SMOR, 4974 bool IsDtorCallInCtor); 4975 4976 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 4977}; 4978} 4979 4980/// Is the given special member inaccessible when used on the given 4981/// sub-object. 4982bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 4983 CXXMethodDecl *target) { 4984 /// If we're operating on a base class, the object type is the 4985 /// type of this special member. 4986 QualType objectTy; 4987 AccessSpecifier access = target->getAccess(); 4988 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 4989 objectTy = S.Context.getTypeDeclType(MD->getParent()); 4990 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 4991 4992 // If we're operating on a field, the object type is the type of the field. 4993 } else { 4994 objectTy = S.Context.getTypeDeclType(target->getParent()); 4995 } 4996 4997 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 4998} 4999 5000/// Check whether we should delete a special member due to the implicit 5001/// definition containing a call to a special member of a subobject. 5002bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 5003 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR, 5004 bool IsDtorCallInCtor) { 5005 CXXMethodDecl *Decl = SMOR->getMethod(); 5006 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 5007 5008 int DiagKind = -1; 5009 5010 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 5011 DiagKind = !Decl ? 0 : 1; 5012 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 5013 DiagKind = 2; 5014 else if (!isAccessible(Subobj, Decl)) 5015 DiagKind = 3; 5016 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 5017 !Decl->isTrivial()) { 5018 // A member of a union must have a trivial corresponding special member. 5019 // As a weird special case, a destructor call from a union's constructor 5020 // must be accessible and non-deleted, but need not be trivial. Such a 5021 // destructor is never actually called, but is semantically checked as 5022 // if it were. 5023 DiagKind = 4; 5024 } 5025 5026 if (DiagKind == -1) 5027 return false; 5028 5029 if (Diagnose) { 5030 if (Field) { 5031 S.Diag(Field->getLocation(), 5032 diag::note_deleted_special_member_class_subobject) 5033 << CSM << MD->getParent() << /*IsField*/true 5034 << Field << DiagKind << IsDtorCallInCtor; 5035 } else { 5036 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 5037 S.Diag(Base->getLocStart(), 5038 diag::note_deleted_special_member_class_subobject) 5039 << CSM << MD->getParent() << /*IsField*/false 5040 << Base->getType() << DiagKind << IsDtorCallInCtor; 5041 } 5042 5043 if (DiagKind == 1) 5044 S.NoteDeletedFunction(Decl); 5045 // FIXME: Explain inaccessibility if DiagKind == 3. 5046 } 5047 5048 return true; 5049} 5050 5051/// Check whether we should delete a special member function due to having a 5052/// direct or virtual base class or non-static data member of class type M. 5053bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 5054 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 5055 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 5056 5057 // C++11 [class.ctor]p5: 5058 // -- any direct or virtual base class, or non-static data member with no 5059 // brace-or-equal-initializer, has class type M (or array thereof) and 5060 // either M has no default constructor or overload resolution as applied 5061 // to M's default constructor results in an ambiguity or in a function 5062 // that is deleted or inaccessible 5063 // C++11 [class.copy]p11, C++11 [class.copy]p23: 5064 // -- a direct or virtual base class B that cannot be copied/moved because 5065 // overload resolution, as applied to B's corresponding special member, 5066 // results in an ambiguity or a function that is deleted or inaccessible 5067 // from the defaulted special member 5068 // C++11 [class.dtor]p5: 5069 // -- any direct or virtual base class [...] has a type with a destructor 5070 // that is deleted or inaccessible 5071 if (!(CSM == Sema::CXXDefaultConstructor && 5072 Field && Field->hasInClassInitializer()) && 5073 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false)) 5074 return true; 5075 5076 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 5077 // -- any direct or virtual base class or non-static data member has a 5078 // type with a destructor that is deleted or inaccessible 5079 if (IsConstructor) { 5080 Sema::SpecialMemberOverloadResult *SMOR = 5081 S.LookupSpecialMember(Class, Sema::CXXDestructor, 5082 false, false, false, false, false); 5083 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 5084 return true; 5085 } 5086 5087 return false; 5088} 5089 5090/// Check whether we should delete a special member function due to the class 5091/// having a particular direct or virtual base class. 5092bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 5093 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 5094 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 5095} 5096 5097/// Check whether we should delete a special member function due to the class 5098/// having a particular non-static data member. 5099bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 5100 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 5101 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 5102 5103 if (CSM == Sema::CXXDefaultConstructor) { 5104 // For a default constructor, all references must be initialized in-class 5105 // and, if a union, it must have a non-const member. 5106 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 5107 if (Diagnose) 5108 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 5109 << MD->getParent() << FD << FieldType << /*Reference*/0; 5110 return true; 5111 } 5112 // C++11 [class.ctor]p5: any non-variant non-static data member of 5113 // const-qualified type (or array thereof) with no 5114 // brace-or-equal-initializer does not have a user-provided default 5115 // constructor. 5116 if (!inUnion() && FieldType.isConstQualified() && 5117 !FD->hasInClassInitializer() && 5118 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 5119 if (Diagnose) 5120 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 5121 << MD->getParent() << FD << FD->getType() << /*Const*/1; 5122 return true; 5123 } 5124 5125 if (inUnion() && !FieldType.isConstQualified()) 5126 AllFieldsAreConst = false; 5127 } else if (CSM == Sema::CXXCopyConstructor) { 5128 // For a copy constructor, data members must not be of rvalue reference 5129 // type. 5130 if (FieldType->isRValueReferenceType()) { 5131 if (Diagnose) 5132 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 5133 << MD->getParent() << FD << FieldType; 5134 return true; 5135 } 5136 } else if (IsAssignment) { 5137 // For an assignment operator, data members must not be of reference type. 5138 if (FieldType->isReferenceType()) { 5139 if (Diagnose) 5140 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 5141 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0; 5142 return true; 5143 } 5144 if (!FieldRecord && FieldType.isConstQualified()) { 5145 // C++11 [class.copy]p23: 5146 // -- a non-static data member of const non-class type (or array thereof) 5147 if (Diagnose) 5148 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 5149 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1; 5150 return true; 5151 } 5152 } 5153 5154 if (FieldRecord) { 5155 // Some additional restrictions exist on the variant members. 5156 if (!inUnion() && FieldRecord->isUnion() && 5157 FieldRecord->isAnonymousStructOrUnion()) { 5158 bool AllVariantFieldsAreConst = true; 5159 5160 // FIXME: Handle anonymous unions declared within anonymous unions. 5161 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(), 5162 UE = FieldRecord->field_end(); 5163 UI != UE; ++UI) { 5164 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 5165 5166 if (!UnionFieldType.isConstQualified()) 5167 AllVariantFieldsAreConst = false; 5168 5169 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 5170 if (UnionFieldRecord && 5171 shouldDeleteForClassSubobject(UnionFieldRecord, *UI, 5172 UnionFieldType.getCVRQualifiers())) 5173 return true; 5174 } 5175 5176 // At least one member in each anonymous union must be non-const 5177 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 5178 FieldRecord->field_begin() != FieldRecord->field_end()) { 5179 if (Diagnose) 5180 S.Diag(FieldRecord->getLocation(), 5181 diag::note_deleted_default_ctor_all_const) 5182 << MD->getParent() << /*anonymous union*/1; 5183 return true; 5184 } 5185 5186 // Don't check the implicit member of the anonymous union type. 5187 // This is technically non-conformant, but sanity demands it. 5188 return false; 5189 } 5190 5191 if (shouldDeleteForClassSubobject(FieldRecord, FD, 5192 FieldType.getCVRQualifiers())) 5193 return true; 5194 } 5195 5196 return false; 5197} 5198 5199/// C++11 [class.ctor] p5: 5200/// A defaulted default constructor for a class X is defined as deleted if 5201/// X is a union and all of its variant members are of const-qualified type. 5202bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 5203 // This is a silly definition, because it gives an empty union a deleted 5204 // default constructor. Don't do that. 5205 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst && 5206 (MD->getParent()->field_begin() != MD->getParent()->field_end())) { 5207 if (Diagnose) 5208 S.Diag(MD->getParent()->getLocation(), 5209 diag::note_deleted_default_ctor_all_const) 5210 << MD->getParent() << /*not anonymous union*/0; 5211 return true; 5212 } 5213 return false; 5214} 5215 5216/// Determine whether a defaulted special member function should be defined as 5217/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 5218/// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 5219bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 5220 bool Diagnose) { 5221 if (MD->isInvalidDecl()) 5222 return false; 5223 CXXRecordDecl *RD = MD->getParent(); 5224 assert(!RD->isDependentType() && "do deletion after instantiation"); 5225 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 5226 return false; 5227 5228 // C++11 [expr.lambda.prim]p19: 5229 // The closure type associated with a lambda-expression has a 5230 // deleted (8.4.3) default constructor and a deleted copy 5231 // assignment operator. 5232 if (RD->isLambda() && 5233 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 5234 if (Diagnose) 5235 Diag(RD->getLocation(), diag::note_lambda_decl); 5236 return true; 5237 } 5238 5239 // For an anonymous struct or union, the copy and assignment special members 5240 // will never be used, so skip the check. For an anonymous union declared at 5241 // namespace scope, the constructor and destructor are used. 5242 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 5243 RD->isAnonymousStructOrUnion()) 5244 return false; 5245 5246 // C++11 [class.copy]p7, p18: 5247 // If the class definition declares a move constructor or move assignment 5248 // operator, an implicitly declared copy constructor or copy assignment 5249 // operator is defined as deleted. 5250 if (MD->isImplicit() && 5251 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 5252 CXXMethodDecl *UserDeclaredMove = 0; 5253 5254 // In Microsoft mode, a user-declared move only causes the deletion of the 5255 // corresponding copy operation, not both copy operations. 5256 if (RD->hasUserDeclaredMoveConstructor() && 5257 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) { 5258 if (!Diagnose) return true; 5259 5260 // Find any user-declared move constructor. 5261 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(), 5262 E = RD->ctor_end(); I != E; ++I) { 5263 if (I->isMoveConstructor()) { 5264 UserDeclaredMove = *I; 5265 break; 5266 } 5267 } 5268 assert(UserDeclaredMove); 5269 } else if (RD->hasUserDeclaredMoveAssignment() && 5270 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) { 5271 if (!Diagnose) return true; 5272 5273 // Find any user-declared move assignment operator. 5274 for (CXXRecordDecl::method_iterator I = RD->method_begin(), 5275 E = RD->method_end(); I != E; ++I) { 5276 if (I->isMoveAssignmentOperator()) { 5277 UserDeclaredMove = *I; 5278 break; 5279 } 5280 } 5281 assert(UserDeclaredMove); 5282 } 5283 5284 if (UserDeclaredMove) { 5285 Diag(UserDeclaredMove->getLocation(), 5286 diag::note_deleted_copy_user_declared_move) 5287 << (CSM == CXXCopyAssignment) << RD 5288 << UserDeclaredMove->isMoveAssignmentOperator(); 5289 return true; 5290 } 5291 } 5292 5293 // Do access control from the special member function 5294 ContextRAII MethodContext(*this, MD); 5295 5296 // C++11 [class.dtor]p5: 5297 // -- for a virtual destructor, lookup of the non-array deallocation function 5298 // results in an ambiguity or in a function that is deleted or inaccessible 5299 if (CSM == CXXDestructor && MD->isVirtual()) { 5300 FunctionDecl *OperatorDelete = 0; 5301 DeclarationName Name = 5302 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 5303 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 5304 OperatorDelete, false)) { 5305 if (Diagnose) 5306 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 5307 return true; 5308 } 5309 } 5310 5311 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose); 5312 5313 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 5314 BE = RD->bases_end(); BI != BE; ++BI) 5315 if (!BI->isVirtual() && 5316 SMI.shouldDeleteForBase(BI)) 5317 return true; 5318 5319 // Per DR1611, do not consider virtual bases of constructors of abstract 5320 // classes, since we are not going to construct them. 5321 if (!RD->isAbstract() || !SMI.IsConstructor) { 5322 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(), 5323 BE = RD->vbases_end(); 5324 BI != BE; ++BI) 5325 if (SMI.shouldDeleteForBase(BI)) 5326 return true; 5327 } 5328 5329 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 5330 FE = RD->field_end(); FI != FE; ++FI) 5331 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() && 5332 SMI.shouldDeleteForField(*FI)) 5333 return true; 5334 5335 if (SMI.shouldDeleteForAllConstMembers()) 5336 return true; 5337 5338 return false; 5339} 5340 5341/// Perform lookup for a special member of the specified kind, and determine 5342/// whether it is trivial. If the triviality can be determined without the 5343/// lookup, skip it. This is intended for use when determining whether a 5344/// special member of a containing object is trivial, and thus does not ever 5345/// perform overload resolution for default constructors. 5346/// 5347/// If \p Selected is not \c NULL, \c *Selected will be filled in with the 5348/// member that was most likely to be intended to be trivial, if any. 5349static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 5350 Sema::CXXSpecialMember CSM, unsigned Quals, 5351 CXXMethodDecl **Selected) { 5352 if (Selected) 5353 *Selected = 0; 5354 5355 switch (CSM) { 5356 case Sema::CXXInvalid: 5357 llvm_unreachable("not a special member"); 5358 5359 case Sema::CXXDefaultConstructor: 5360 // C++11 [class.ctor]p5: 5361 // A default constructor is trivial if: 5362 // - all the [direct subobjects] have trivial default constructors 5363 // 5364 // Note, no overload resolution is performed in this case. 5365 if (RD->hasTrivialDefaultConstructor()) 5366 return true; 5367 5368 if (Selected) { 5369 // If there's a default constructor which could have been trivial, dig it 5370 // out. Otherwise, if there's any user-provided default constructor, point 5371 // to that as an example of why there's not a trivial one. 5372 CXXConstructorDecl *DefCtor = 0; 5373 if (RD->needsImplicitDefaultConstructor()) 5374 S.DeclareImplicitDefaultConstructor(RD); 5375 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), 5376 CE = RD->ctor_end(); CI != CE; ++CI) { 5377 if (!CI->isDefaultConstructor()) 5378 continue; 5379 DefCtor = *CI; 5380 if (!DefCtor->isUserProvided()) 5381 break; 5382 } 5383 5384 *Selected = DefCtor; 5385 } 5386 5387 return false; 5388 5389 case Sema::CXXDestructor: 5390 // C++11 [class.dtor]p5: 5391 // A destructor is trivial if: 5392 // - all the direct [subobjects] have trivial destructors 5393 if (RD->hasTrivialDestructor()) 5394 return true; 5395 5396 if (Selected) { 5397 if (RD->needsImplicitDestructor()) 5398 S.DeclareImplicitDestructor(RD); 5399 *Selected = RD->getDestructor(); 5400 } 5401 5402 return false; 5403 5404 case Sema::CXXCopyConstructor: 5405 // C++11 [class.copy]p12: 5406 // A copy constructor is trivial if: 5407 // - the constructor selected to copy each direct [subobject] is trivial 5408 if (RD->hasTrivialCopyConstructor()) { 5409 if (Quals == Qualifiers::Const) 5410 // We must either select the trivial copy constructor or reach an 5411 // ambiguity; no need to actually perform overload resolution. 5412 return true; 5413 } else if (!Selected) { 5414 return false; 5415 } 5416 // In C++98, we are not supposed to perform overload resolution here, but we 5417 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 5418 // cases like B as having a non-trivial copy constructor: 5419 // struct A { template<typename T> A(T&); }; 5420 // struct B { mutable A a; }; 5421 goto NeedOverloadResolution; 5422 5423 case Sema::CXXCopyAssignment: 5424 // C++11 [class.copy]p25: 5425 // A copy assignment operator is trivial if: 5426 // - the assignment operator selected to copy each direct [subobject] is 5427 // trivial 5428 if (RD->hasTrivialCopyAssignment()) { 5429 if (Quals == Qualifiers::Const) 5430 return true; 5431 } else if (!Selected) { 5432 return false; 5433 } 5434 // In C++98, we are not supposed to perform overload resolution here, but we 5435 // treat that as a language defect. 5436 goto NeedOverloadResolution; 5437 5438 case Sema::CXXMoveConstructor: 5439 case Sema::CXXMoveAssignment: 5440 NeedOverloadResolution: 5441 Sema::SpecialMemberOverloadResult *SMOR = 5442 S.LookupSpecialMember(RD, CSM, 5443 Quals & Qualifiers::Const, 5444 Quals & Qualifiers::Volatile, 5445 /*RValueThis*/false, /*ConstThis*/false, 5446 /*VolatileThis*/false); 5447 5448 // The standard doesn't describe how to behave if the lookup is ambiguous. 5449 // We treat it as not making the member non-trivial, just like the standard 5450 // mandates for the default constructor. This should rarely matter, because 5451 // the member will also be deleted. 5452 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 5453 return true; 5454 5455 if (!SMOR->getMethod()) { 5456 assert(SMOR->getKind() == 5457 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 5458 return false; 5459 } 5460 5461 // We deliberately don't check if we found a deleted special member. We're 5462 // not supposed to! 5463 if (Selected) 5464 *Selected = SMOR->getMethod(); 5465 return SMOR->getMethod()->isTrivial(); 5466 } 5467 5468 llvm_unreachable("unknown special method kind"); 5469} 5470 5471static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 5472 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end(); 5473 CI != CE; ++CI) 5474 if (!CI->isImplicit()) 5475 return *CI; 5476 5477 // Look for constructor templates. 5478 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 5479 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 5480 if (CXXConstructorDecl *CD = 5481 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 5482 return CD; 5483 } 5484 5485 return 0; 5486} 5487 5488/// The kind of subobject we are checking for triviality. The values of this 5489/// enumeration are used in diagnostics. 5490enum TrivialSubobjectKind { 5491 /// The subobject is a base class. 5492 TSK_BaseClass, 5493 /// The subobject is a non-static data member. 5494 TSK_Field, 5495 /// The object is actually the complete object. 5496 TSK_CompleteObject 5497}; 5498 5499/// Check whether the special member selected for a given type would be trivial. 5500static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 5501 QualType SubType, 5502 Sema::CXXSpecialMember CSM, 5503 TrivialSubobjectKind Kind, 5504 bool Diagnose) { 5505 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 5506 if (!SubRD) 5507 return true; 5508 5509 CXXMethodDecl *Selected; 5510 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 5511 Diagnose ? &Selected : 0)) 5512 return true; 5513 5514 if (Diagnose) { 5515 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 5516 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 5517 << Kind << SubType.getUnqualifiedType(); 5518 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 5519 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 5520 } else if (!Selected) 5521 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 5522 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 5523 else if (Selected->isUserProvided()) { 5524 if (Kind == TSK_CompleteObject) 5525 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 5526 << Kind << SubType.getUnqualifiedType() << CSM; 5527 else { 5528 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 5529 << Kind << SubType.getUnqualifiedType() << CSM; 5530 S.Diag(Selected->getLocation(), diag::note_declared_at); 5531 } 5532 } else { 5533 if (Kind != TSK_CompleteObject) 5534 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 5535 << Kind << SubType.getUnqualifiedType() << CSM; 5536 5537 // Explain why the defaulted or deleted special member isn't trivial. 5538 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose); 5539 } 5540 } 5541 5542 return false; 5543} 5544 5545/// Check whether the members of a class type allow a special member to be 5546/// trivial. 5547static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 5548 Sema::CXXSpecialMember CSM, 5549 bool ConstArg, bool Diagnose) { 5550 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 5551 FE = RD->field_end(); FI != FE; ++FI) { 5552 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 5553 continue; 5554 5555 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 5556 5557 // Pretend anonymous struct or union members are members of this class. 5558 if (FI->isAnonymousStructOrUnion()) { 5559 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 5560 CSM, ConstArg, Diagnose)) 5561 return false; 5562 continue; 5563 } 5564 5565 // C++11 [class.ctor]p5: 5566 // A default constructor is trivial if [...] 5567 // -- no non-static data member of its class has a 5568 // brace-or-equal-initializer 5569 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 5570 if (Diagnose) 5571 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI; 5572 return false; 5573 } 5574 5575 // Objective C ARC 4.3.5: 5576 // [...] nontrivally ownership-qualified types are [...] not trivially 5577 // default constructible, copy constructible, move constructible, copy 5578 // assignable, move assignable, or destructible [...] 5579 if (S.getLangOpts().ObjCAutoRefCount && 5580 FieldType.hasNonTrivialObjCLifetime()) { 5581 if (Diagnose) 5582 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 5583 << RD << FieldType.getObjCLifetime(); 5584 return false; 5585 } 5586 5587 if (ConstArg && !FI->isMutable()) 5588 FieldType.addConst(); 5589 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM, 5590 TSK_Field, Diagnose)) 5591 return false; 5592 } 5593 5594 return true; 5595} 5596 5597/// Diagnose why the specified class does not have a trivial special member of 5598/// the given kind. 5599void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 5600 QualType Ty = Context.getRecordType(RD); 5601 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) 5602 Ty.addConst(); 5603 5604 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM, 5605 TSK_CompleteObject, /*Diagnose*/true); 5606} 5607 5608/// Determine whether a defaulted or deleted special member function is trivial, 5609/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 5610/// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 5611bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 5612 bool Diagnose) { 5613 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 5614 5615 CXXRecordDecl *RD = MD->getParent(); 5616 5617 bool ConstArg = false; 5618 5619 // C++11 [class.copy]p12, p25: 5620 // A [special member] is trivial if its declared parameter type is the same 5621 // as if it had been implicitly declared [...] 5622 switch (CSM) { 5623 case CXXDefaultConstructor: 5624 case CXXDestructor: 5625 // Trivial default constructors and destructors cannot have parameters. 5626 break; 5627 5628 case CXXCopyConstructor: 5629 case CXXCopyAssignment: { 5630 // Trivial copy operations always have const, non-volatile parameter types. 5631 ConstArg = true; 5632 const ParmVarDecl *Param0 = MD->getParamDecl(0); 5633 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 5634 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 5635 if (Diagnose) 5636 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 5637 << Param0->getSourceRange() << Param0->getType() 5638 << Context.getLValueReferenceType( 5639 Context.getRecordType(RD).withConst()); 5640 return false; 5641 } 5642 break; 5643 } 5644 5645 case CXXMoveConstructor: 5646 case CXXMoveAssignment: { 5647 // Trivial move operations always have non-cv-qualified parameters. 5648 const ParmVarDecl *Param0 = MD->getParamDecl(0); 5649 const RValueReferenceType *RT = 5650 Param0->getType()->getAs<RValueReferenceType>(); 5651 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 5652 if (Diagnose) 5653 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 5654 << Param0->getSourceRange() << Param0->getType() 5655 << Context.getRValueReferenceType(Context.getRecordType(RD)); 5656 return false; 5657 } 5658 break; 5659 } 5660 5661 case CXXInvalid: 5662 llvm_unreachable("not a special member"); 5663 } 5664 5665 // FIXME: We require that the parameter-declaration-clause is equivalent to 5666 // that of an implicit declaration, not just that the declared parameter type 5667 // matches, in order to prevent absuridities like a function simultaneously 5668 // being a trivial copy constructor and a non-trivial default constructor. 5669 // This issue has not yet been assigned a core issue number. 5670 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 5671 if (Diagnose) 5672 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 5673 diag::note_nontrivial_default_arg) 5674 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 5675 return false; 5676 } 5677 if (MD->isVariadic()) { 5678 if (Diagnose) 5679 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 5680 return false; 5681 } 5682 5683 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 5684 // A copy/move [constructor or assignment operator] is trivial if 5685 // -- the [member] selected to copy/move each direct base class subobject 5686 // is trivial 5687 // 5688 // C++11 [class.copy]p12, C++11 [class.copy]p25: 5689 // A [default constructor or destructor] is trivial if 5690 // -- all the direct base classes have trivial [default constructors or 5691 // destructors] 5692 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 5693 BE = RD->bases_end(); BI != BE; ++BI) 5694 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(), 5695 ConstArg ? BI->getType().withConst() 5696 : BI->getType(), 5697 CSM, TSK_BaseClass, Diagnose)) 5698 return false; 5699 5700 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 5701 // A copy/move [constructor or assignment operator] for a class X is 5702 // trivial if 5703 // -- for each non-static data member of X that is of class type (or array 5704 // thereof), the constructor selected to copy/move that member is 5705 // trivial 5706 // 5707 // C++11 [class.copy]p12, C++11 [class.copy]p25: 5708 // A [default constructor or destructor] is trivial if 5709 // -- for all of the non-static data members of its class that are of class 5710 // type (or array thereof), each such class has a trivial [default 5711 // constructor or destructor] 5712 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose)) 5713 return false; 5714 5715 // C++11 [class.dtor]p5: 5716 // A destructor is trivial if [...] 5717 // -- the destructor is not virtual 5718 if (CSM == CXXDestructor && MD->isVirtual()) { 5719 if (Diagnose) 5720 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 5721 return false; 5722 } 5723 5724 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 5725 // A [special member] for class X is trivial if [...] 5726 // -- class X has no virtual functions and no virtual base classes 5727 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 5728 if (!Diagnose) 5729 return false; 5730 5731 if (RD->getNumVBases()) { 5732 // Check for virtual bases. We already know that the corresponding 5733 // member in all bases is trivial, so vbases must all be direct. 5734 CXXBaseSpecifier &BS = *RD->vbases_begin(); 5735 assert(BS.isVirtual()); 5736 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1; 5737 return false; 5738 } 5739 5740 // Must have a virtual method. 5741 for (CXXRecordDecl::method_iterator MI = RD->method_begin(), 5742 ME = RD->method_end(); MI != ME; ++MI) { 5743 if (MI->isVirtual()) { 5744 SourceLocation MLoc = MI->getLocStart(); 5745 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 5746 return false; 5747 } 5748 } 5749 5750 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 5751 } 5752 5753 // Looks like it's trivial! 5754 return true; 5755} 5756 5757/// \brief Data used with FindHiddenVirtualMethod 5758namespace { 5759 struct FindHiddenVirtualMethodData { 5760 Sema *S; 5761 CXXMethodDecl *Method; 5762 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 5763 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 5764 }; 5765} 5766 5767/// \brief Check whether any most overriden method from MD in Methods 5768static bool CheckMostOverridenMethods(const CXXMethodDecl *MD, 5769 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) { 5770 if (MD->size_overridden_methods() == 0) 5771 return Methods.count(MD->getCanonicalDecl()); 5772 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 5773 E = MD->end_overridden_methods(); 5774 I != E; ++I) 5775 if (CheckMostOverridenMethods(*I, Methods)) 5776 return true; 5777 return false; 5778} 5779 5780/// \brief Member lookup function that determines whether a given C++ 5781/// method overloads virtual methods in a base class without overriding any, 5782/// to be used with CXXRecordDecl::lookupInBases(). 5783static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier, 5784 CXXBasePath &Path, 5785 void *UserData) { 5786 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 5787 5788 FindHiddenVirtualMethodData &Data 5789 = *static_cast<FindHiddenVirtualMethodData*>(UserData); 5790 5791 DeclarationName Name = Data.Method->getDeclName(); 5792 assert(Name.getNameKind() == DeclarationName::Identifier); 5793 5794 bool foundSameNameMethod = false; 5795 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 5796 for (Path.Decls = BaseRecord->lookup(Name); 5797 !Path.Decls.empty(); 5798 Path.Decls = Path.Decls.slice(1)) { 5799 NamedDecl *D = Path.Decls.front(); 5800 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 5801 MD = MD->getCanonicalDecl(); 5802 foundSameNameMethod = true; 5803 // Interested only in hidden virtual methods. 5804 if (!MD->isVirtual()) 5805 continue; 5806 // If the method we are checking overrides a method from its base 5807 // don't warn about the other overloaded methods. 5808 if (!Data.S->IsOverload(Data.Method, MD, false)) 5809 return true; 5810 // Collect the overload only if its hidden. 5811 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods)) 5812 overloadedMethods.push_back(MD); 5813 } 5814 } 5815 5816 if (foundSameNameMethod) 5817 Data.OverloadedMethods.append(overloadedMethods.begin(), 5818 overloadedMethods.end()); 5819 return foundSameNameMethod; 5820} 5821 5822/// \brief Add the most overriden methods from MD to Methods 5823static void AddMostOverridenMethods(const CXXMethodDecl *MD, 5824 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) { 5825 if (MD->size_overridden_methods() == 0) 5826 Methods.insert(MD->getCanonicalDecl()); 5827 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 5828 E = MD->end_overridden_methods(); 5829 I != E; ++I) 5830 AddMostOverridenMethods(*I, Methods); 5831} 5832 5833/// \brief Check if a method overloads virtual methods in a base class without 5834/// overriding any. 5835void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 5836 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 5837 if (!MD->getDeclName().isIdentifier()) 5838 return; 5839 5840 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 5841 /*bool RecordPaths=*/false, 5842 /*bool DetectVirtual=*/false); 5843 FindHiddenVirtualMethodData Data; 5844 Data.Method = MD; 5845 Data.S = this; 5846 5847 // Keep the base methods that were overriden or introduced in the subclass 5848 // by 'using' in a set. A base method not in this set is hidden. 5849 CXXRecordDecl *DC = MD->getParent(); 5850 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 5851 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 5852 NamedDecl *ND = *I; 5853 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 5854 ND = shad->getTargetDecl(); 5855 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 5856 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods); 5857 } 5858 5859 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths)) 5860 OverloadedMethods = Data.OverloadedMethods; 5861} 5862 5863void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 5864 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 5865 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 5866 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 5867 PartialDiagnostic PD = PDiag( 5868 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 5869 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 5870 Diag(overloadedMD->getLocation(), PD); 5871 } 5872} 5873 5874/// \brief Diagnose methods which overload virtual methods in a base class 5875/// without overriding any. 5876void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 5877 if (MD->isInvalidDecl()) 5878 return; 5879 5880 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual, 5881 MD->getLocation()) == DiagnosticsEngine::Ignored) 5882 return; 5883 5884 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 5885 FindHiddenVirtualMethods(MD, OverloadedMethods); 5886 if (!OverloadedMethods.empty()) { 5887 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 5888 << MD << (OverloadedMethods.size() > 1); 5889 5890 NoteHiddenVirtualMethods(MD, OverloadedMethods); 5891 } 5892} 5893 5894void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 5895 Decl *TagDecl, 5896 SourceLocation LBrac, 5897 SourceLocation RBrac, 5898 AttributeList *AttrList) { 5899 if (!TagDecl) 5900 return; 5901 5902 AdjustDeclIfTemplate(TagDecl); 5903 5904 for (const AttributeList* l = AttrList; l; l = l->getNext()) { 5905 if (l->getKind() != AttributeList::AT_Visibility) 5906 continue; 5907 l->setInvalid(); 5908 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) << 5909 l->getName(); 5910 } 5911 5912 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 5913 // strict aliasing violation! 5914 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 5915 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 5916 5917 CheckCompletedCXXClass( 5918 dyn_cast_or_null<CXXRecordDecl>(TagDecl)); 5919} 5920 5921/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 5922/// special functions, such as the default constructor, copy 5923/// constructor, or destructor, to the given C++ class (C++ 5924/// [special]p1). This routine can only be executed just before the 5925/// definition of the class is complete. 5926void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 5927 if (!ClassDecl->hasUserDeclaredConstructor()) 5928 ++ASTContext::NumImplicitDefaultConstructors; 5929 5930 if (!ClassDecl->hasUserDeclaredCopyConstructor()) { 5931 ++ASTContext::NumImplicitCopyConstructors; 5932 5933 // If the properties or semantics of the copy constructor couldn't be 5934 // determined while the class was being declared, force a declaration 5935 // of it now. 5936 if (ClassDecl->needsOverloadResolutionForCopyConstructor()) 5937 DeclareImplicitCopyConstructor(ClassDecl); 5938 } 5939 5940 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 5941 ++ASTContext::NumImplicitMoveConstructors; 5942 5943 if (ClassDecl->needsOverloadResolutionForMoveConstructor()) 5944 DeclareImplicitMoveConstructor(ClassDecl); 5945 } 5946 5947 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 5948 ++ASTContext::NumImplicitCopyAssignmentOperators; 5949 5950 // If we have a dynamic class, then the copy assignment operator may be 5951 // virtual, so we have to declare it immediately. This ensures that, e.g., 5952 // it shows up in the right place in the vtable and that we diagnose 5953 // problems with the implicit exception specification. 5954 if (ClassDecl->isDynamicClass() || 5955 ClassDecl->needsOverloadResolutionForCopyAssignment()) 5956 DeclareImplicitCopyAssignment(ClassDecl); 5957 } 5958 5959 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 5960 ++ASTContext::NumImplicitMoveAssignmentOperators; 5961 5962 // Likewise for the move assignment operator. 5963 if (ClassDecl->isDynamicClass() || 5964 ClassDecl->needsOverloadResolutionForMoveAssignment()) 5965 DeclareImplicitMoveAssignment(ClassDecl); 5966 } 5967 5968 if (!ClassDecl->hasUserDeclaredDestructor()) { 5969 ++ASTContext::NumImplicitDestructors; 5970 5971 // If we have a dynamic class, then the destructor may be virtual, so we 5972 // have to declare the destructor immediately. This ensures that, e.g., it 5973 // shows up in the right place in the vtable and that we diagnose problems 5974 // with the implicit exception specification. 5975 if (ClassDecl->isDynamicClass() || 5976 ClassDecl->needsOverloadResolutionForDestructor()) 5977 DeclareImplicitDestructor(ClassDecl); 5978 } 5979} 5980 5981void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) { 5982 if (!D) 5983 return; 5984 5985 int NumParamList = D->getNumTemplateParameterLists(); 5986 for (int i = 0; i < NumParamList; i++) { 5987 TemplateParameterList* Params = D->getTemplateParameterList(i); 5988 for (TemplateParameterList::iterator Param = Params->begin(), 5989 ParamEnd = Params->end(); 5990 Param != ParamEnd; ++Param) { 5991 NamedDecl *Named = cast<NamedDecl>(*Param); 5992 if (Named->getDeclName()) { 5993 S->AddDecl(Named); 5994 IdResolver.AddDecl(Named); 5995 } 5996 } 5997 } 5998} 5999 6000void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 6001 if (!D) 6002 return; 6003 6004 TemplateParameterList *Params = 0; 6005 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) 6006 Params = Template->getTemplateParameters(); 6007 else if (ClassTemplatePartialSpecializationDecl *PartialSpec 6008 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 6009 Params = PartialSpec->getTemplateParameters(); 6010 else 6011 return; 6012 6013 for (TemplateParameterList::iterator Param = Params->begin(), 6014 ParamEnd = Params->end(); 6015 Param != ParamEnd; ++Param) { 6016 NamedDecl *Named = cast<NamedDecl>(*Param); 6017 if (Named->getDeclName()) { 6018 S->AddDecl(Named); 6019 IdResolver.AddDecl(Named); 6020 } 6021 } 6022} 6023 6024void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 6025 if (!RecordD) return; 6026 AdjustDeclIfTemplate(RecordD); 6027 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 6028 PushDeclContext(S, Record); 6029} 6030 6031void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 6032 if (!RecordD) return; 6033 PopDeclContext(); 6034} 6035 6036/// ActOnStartDelayedCXXMethodDeclaration - We have completed 6037/// parsing a top-level (non-nested) C++ class, and we are now 6038/// parsing those parts of the given Method declaration that could 6039/// not be parsed earlier (C++ [class.mem]p2), such as default 6040/// arguments. This action should enter the scope of the given 6041/// Method declaration as if we had just parsed the qualified method 6042/// name. However, it should not bring the parameters into scope; 6043/// that will be performed by ActOnDelayedCXXMethodParameter. 6044void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 6045} 6046 6047/// ActOnDelayedCXXMethodParameter - We've already started a delayed 6048/// C++ method declaration. We're (re-)introducing the given 6049/// function parameter into scope for use in parsing later parts of 6050/// the method declaration. For example, we could see an 6051/// ActOnParamDefaultArgument event for this parameter. 6052void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 6053 if (!ParamD) 6054 return; 6055 6056 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 6057 6058 // If this parameter has an unparsed default argument, clear it out 6059 // to make way for the parsed default argument. 6060 if (Param->hasUnparsedDefaultArg()) 6061 Param->setDefaultArg(0); 6062 6063 S->AddDecl(Param); 6064 if (Param->getDeclName()) 6065 IdResolver.AddDecl(Param); 6066} 6067 6068/// ActOnFinishDelayedCXXMethodDeclaration - We have finished 6069/// processing the delayed method declaration for Method. The method 6070/// declaration is now considered finished. There may be a separate 6071/// ActOnStartOfFunctionDef action later (not necessarily 6072/// immediately!) for this method, if it was also defined inside the 6073/// class body. 6074void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 6075 if (!MethodD) 6076 return; 6077 6078 AdjustDeclIfTemplate(MethodD); 6079 6080 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 6081 6082 // Now that we have our default arguments, check the constructor 6083 // again. It could produce additional diagnostics or affect whether 6084 // the class has implicitly-declared destructors, among other 6085 // things. 6086 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 6087 CheckConstructor(Constructor); 6088 6089 // Check the default arguments, which we may have added. 6090 if (!Method->isInvalidDecl()) 6091 CheckCXXDefaultArguments(Method); 6092} 6093 6094/// CheckConstructorDeclarator - Called by ActOnDeclarator to check 6095/// the well-formedness of the constructor declarator @p D with type @p 6096/// R. If there are any errors in the declarator, this routine will 6097/// emit diagnostics and set the invalid bit to true. In any case, the type 6098/// will be updated to reflect a well-formed type for the constructor and 6099/// returned. 6100QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 6101 StorageClass &SC) { 6102 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 6103 6104 // C++ [class.ctor]p3: 6105 // A constructor shall not be virtual (10.3) or static (9.4). A 6106 // constructor can be invoked for a const, volatile or const 6107 // volatile object. A constructor shall not be declared const, 6108 // volatile, or const volatile (9.3.2). 6109 if (isVirtual) { 6110 if (!D.isInvalidType()) 6111 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 6112 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 6113 << SourceRange(D.getIdentifierLoc()); 6114 D.setInvalidType(); 6115 } 6116 if (SC == SC_Static) { 6117 if (!D.isInvalidType()) 6118 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 6119 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6120 << SourceRange(D.getIdentifierLoc()); 6121 D.setInvalidType(); 6122 SC = SC_None; 6123 } 6124 6125 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6126 if (FTI.TypeQuals != 0) { 6127 if (FTI.TypeQuals & Qualifiers::Const) 6128 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6129 << "const" << SourceRange(D.getIdentifierLoc()); 6130 if (FTI.TypeQuals & Qualifiers::Volatile) 6131 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6132 << "volatile" << SourceRange(D.getIdentifierLoc()); 6133 if (FTI.TypeQuals & Qualifiers::Restrict) 6134 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6135 << "restrict" << SourceRange(D.getIdentifierLoc()); 6136 D.setInvalidType(); 6137 } 6138 6139 // C++0x [class.ctor]p4: 6140 // A constructor shall not be declared with a ref-qualifier. 6141 if (FTI.hasRefQualifier()) { 6142 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 6143 << FTI.RefQualifierIsLValueRef 6144 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 6145 D.setInvalidType(); 6146 } 6147 6148 // Rebuild the function type "R" without any type qualifiers (in 6149 // case any of the errors above fired) and with "void" as the 6150 // return type, since constructors don't have return types. 6151 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6152 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType()) 6153 return R; 6154 6155 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 6156 EPI.TypeQuals = 0; 6157 EPI.RefQualifier = RQ_None; 6158 6159 return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI); 6160} 6161 6162/// CheckConstructor - Checks a fully-formed constructor for 6163/// well-formedness, issuing any diagnostics required. Returns true if 6164/// the constructor declarator is invalid. 6165void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 6166 CXXRecordDecl *ClassDecl 6167 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 6168 if (!ClassDecl) 6169 return Constructor->setInvalidDecl(); 6170 6171 // C++ [class.copy]p3: 6172 // A declaration of a constructor for a class X is ill-formed if 6173 // its first parameter is of type (optionally cv-qualified) X and 6174 // either there are no other parameters or else all other 6175 // parameters have default arguments. 6176 if (!Constructor->isInvalidDecl() && 6177 ((Constructor->getNumParams() == 1) || 6178 (Constructor->getNumParams() > 1 && 6179 Constructor->getParamDecl(1)->hasDefaultArg())) && 6180 Constructor->getTemplateSpecializationKind() 6181 != TSK_ImplicitInstantiation) { 6182 QualType ParamType = Constructor->getParamDecl(0)->getType(); 6183 QualType ClassTy = Context.getTagDeclType(ClassDecl); 6184 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 6185 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 6186 const char *ConstRef 6187 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 6188 : " const &"; 6189 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 6190 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 6191 6192 // FIXME: Rather that making the constructor invalid, we should endeavor 6193 // to fix the type. 6194 Constructor->setInvalidDecl(); 6195 } 6196 } 6197} 6198 6199/// CheckDestructor - Checks a fully-formed destructor definition for 6200/// well-formedness, issuing any diagnostics required. Returns true 6201/// on error. 6202bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 6203 CXXRecordDecl *RD = Destructor->getParent(); 6204 6205 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 6206 SourceLocation Loc; 6207 6208 if (!Destructor->isImplicit()) 6209 Loc = Destructor->getLocation(); 6210 else 6211 Loc = RD->getLocation(); 6212 6213 // If we have a virtual destructor, look up the deallocation function 6214 FunctionDecl *OperatorDelete = 0; 6215 DeclarationName Name = 6216 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 6217 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 6218 return true; 6219 6220 MarkFunctionReferenced(Loc, OperatorDelete); 6221 6222 Destructor->setOperatorDelete(OperatorDelete); 6223 } 6224 6225 return false; 6226} 6227 6228static inline bool 6229FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) { 6230 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 6231 FTI.ArgInfo[0].Param && 6232 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()); 6233} 6234 6235/// CheckDestructorDeclarator - Called by ActOnDeclarator to check 6236/// the well-formednes of the destructor declarator @p D with type @p 6237/// R. If there are any errors in the declarator, this routine will 6238/// emit diagnostics and set the declarator to invalid. Even if this happens, 6239/// will be updated to reflect a well-formed type for the destructor and 6240/// returned. 6241QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 6242 StorageClass& SC) { 6243 // C++ [class.dtor]p1: 6244 // [...] A typedef-name that names a class is a class-name 6245 // (7.1.3); however, a typedef-name that names a class shall not 6246 // be used as the identifier in the declarator for a destructor 6247 // declaration. 6248 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 6249 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 6250 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 6251 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 6252 else if (const TemplateSpecializationType *TST = 6253 DeclaratorType->getAs<TemplateSpecializationType>()) 6254 if (TST->isTypeAlias()) 6255 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 6256 << DeclaratorType << 1; 6257 6258 // C++ [class.dtor]p2: 6259 // A destructor is used to destroy objects of its class type. A 6260 // destructor takes no parameters, and no return type can be 6261 // specified for it (not even void). The address of a destructor 6262 // shall not be taken. A destructor shall not be static. A 6263 // destructor can be invoked for a const, volatile or const 6264 // volatile object. A destructor shall not be declared const, 6265 // volatile or const volatile (9.3.2). 6266 if (SC == SC_Static) { 6267 if (!D.isInvalidType()) 6268 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 6269 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6270 << SourceRange(D.getIdentifierLoc()) 6271 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6272 6273 SC = SC_None; 6274 } 6275 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 6276 // Destructors don't have return types, but the parser will 6277 // happily parse something like: 6278 // 6279 // class X { 6280 // float ~X(); 6281 // }; 6282 // 6283 // The return type will be eliminated later. 6284 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 6285 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6286 << SourceRange(D.getIdentifierLoc()); 6287 } 6288 6289 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6290 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 6291 if (FTI.TypeQuals & Qualifiers::Const) 6292 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6293 << "const" << SourceRange(D.getIdentifierLoc()); 6294 if (FTI.TypeQuals & Qualifiers::Volatile) 6295 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6296 << "volatile" << SourceRange(D.getIdentifierLoc()); 6297 if (FTI.TypeQuals & Qualifiers::Restrict) 6298 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6299 << "restrict" << SourceRange(D.getIdentifierLoc()); 6300 D.setInvalidType(); 6301 } 6302 6303 // C++0x [class.dtor]p2: 6304 // A destructor shall not be declared with a ref-qualifier. 6305 if (FTI.hasRefQualifier()) { 6306 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 6307 << FTI.RefQualifierIsLValueRef 6308 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 6309 D.setInvalidType(); 6310 } 6311 6312 // Make sure we don't have any parameters. 6313 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) { 6314 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 6315 6316 // Delete the parameters. 6317 FTI.freeArgs(); 6318 D.setInvalidType(); 6319 } 6320 6321 // Make sure the destructor isn't variadic. 6322 if (FTI.isVariadic) { 6323 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 6324 D.setInvalidType(); 6325 } 6326 6327 // Rebuild the function type "R" without any type qualifiers or 6328 // parameters (in case any of the errors above fired) and with 6329 // "void" as the return type, since destructors don't have return 6330 // types. 6331 if (!D.isInvalidType()) 6332 return R; 6333 6334 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6335 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 6336 EPI.Variadic = false; 6337 EPI.TypeQuals = 0; 6338 EPI.RefQualifier = RQ_None; 6339 return Context.getFunctionType(Context.VoidTy, None, EPI); 6340} 6341 6342/// CheckConversionDeclarator - Called by ActOnDeclarator to check the 6343/// well-formednes of the conversion function declarator @p D with 6344/// type @p R. If there are any errors in the declarator, this routine 6345/// will emit diagnostics and return true. Otherwise, it will return 6346/// false. Either way, the type @p R will be updated to reflect a 6347/// well-formed type for the conversion operator. 6348void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 6349 StorageClass& SC) { 6350 // C++ [class.conv.fct]p1: 6351 // Neither parameter types nor return type can be specified. The 6352 // type of a conversion function (8.3.5) is "function taking no 6353 // parameter returning conversion-type-id." 6354 if (SC == SC_Static) { 6355 if (!D.isInvalidType()) 6356 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 6357 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6358 << D.getName().getSourceRange(); 6359 D.setInvalidType(); 6360 SC = SC_None; 6361 } 6362 6363 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId); 6364 6365 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 6366 // Conversion functions don't have return types, but the parser will 6367 // happily parse something like: 6368 // 6369 // class X { 6370 // float operator bool(); 6371 // }; 6372 // 6373 // The return type will be changed later anyway. 6374 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 6375 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6376 << SourceRange(D.getIdentifierLoc()); 6377 D.setInvalidType(); 6378 } 6379 6380 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6381 6382 // Make sure we don't have any parameters. 6383 if (Proto->getNumArgs() > 0) { 6384 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 6385 6386 // Delete the parameters. 6387 D.getFunctionTypeInfo().freeArgs(); 6388 D.setInvalidType(); 6389 } else if (Proto->isVariadic()) { 6390 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 6391 D.setInvalidType(); 6392 } 6393 6394 // Diagnose "&operator bool()" and other such nonsense. This 6395 // is actually a gcc extension which we don't support. 6396 if (Proto->getResultType() != ConvType) { 6397 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 6398 << Proto->getResultType(); 6399 D.setInvalidType(); 6400 ConvType = Proto->getResultType(); 6401 } 6402 6403 // C++ [class.conv.fct]p4: 6404 // The conversion-type-id shall not represent a function type nor 6405 // an array type. 6406 if (ConvType->isArrayType()) { 6407 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 6408 ConvType = Context.getPointerType(ConvType); 6409 D.setInvalidType(); 6410 } else if (ConvType->isFunctionType()) { 6411 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 6412 ConvType = Context.getPointerType(ConvType); 6413 D.setInvalidType(); 6414 } 6415 6416 // Rebuild the function type "R" without any parameters (in case any 6417 // of the errors above fired) and with the conversion type as the 6418 // return type. 6419 if (D.isInvalidType()) 6420 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 6421 6422 // C++0x explicit conversion operators. 6423 if (D.getDeclSpec().isExplicitSpecified()) 6424 Diag(D.getDeclSpec().getExplicitSpecLoc(), 6425 getLangOpts().CPlusPlus11 ? 6426 diag::warn_cxx98_compat_explicit_conversion_functions : 6427 diag::ext_explicit_conversion_functions) 6428 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 6429} 6430 6431/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 6432/// the declaration of the given C++ conversion function. This routine 6433/// is responsible for recording the conversion function in the C++ 6434/// class, if possible. 6435Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 6436 assert(Conversion && "Expected to receive a conversion function declaration"); 6437 6438 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 6439 6440 // Make sure we aren't redeclaring the conversion function. 6441 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 6442 6443 // C++ [class.conv.fct]p1: 6444 // [...] A conversion function is never used to convert a 6445 // (possibly cv-qualified) object to the (possibly cv-qualified) 6446 // same object type (or a reference to it), to a (possibly 6447 // cv-qualified) base class of that type (or a reference to it), 6448 // or to (possibly cv-qualified) void. 6449 // FIXME: Suppress this warning if the conversion function ends up being a 6450 // virtual function that overrides a virtual function in a base class. 6451 QualType ClassType 6452 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 6453 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 6454 ConvType = ConvTypeRef->getPointeeType(); 6455 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 6456 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 6457 /* Suppress diagnostics for instantiations. */; 6458 else if (ConvType->isRecordType()) { 6459 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 6460 if (ConvType == ClassType) 6461 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 6462 << ClassType; 6463 else if (IsDerivedFrom(ClassType, ConvType)) 6464 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 6465 << ClassType << ConvType; 6466 } else if (ConvType->isVoidType()) { 6467 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 6468 << ClassType << ConvType; 6469 } 6470 6471 if (FunctionTemplateDecl *ConversionTemplate 6472 = Conversion->getDescribedFunctionTemplate()) 6473 return ConversionTemplate; 6474 6475 return Conversion; 6476} 6477 6478//===----------------------------------------------------------------------===// 6479// Namespace Handling 6480//===----------------------------------------------------------------------===// 6481 6482/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is 6483/// reopened. 6484static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 6485 SourceLocation Loc, 6486 IdentifierInfo *II, bool *IsInline, 6487 NamespaceDecl *PrevNS) { 6488 assert(*IsInline != PrevNS->isInline()); 6489 6490 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 6491 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 6492 // inline namespaces, with the intention of bringing names into namespace std. 6493 // 6494 // We support this just well enough to get that case working; this is not 6495 // sufficient to support reopening namespaces as inline in general. 6496 if (*IsInline && II && II->getName().startswith("__atomic") && 6497 S.getSourceManager().isInSystemHeader(Loc)) { 6498 // Mark all prior declarations of the namespace as inline. 6499 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 6500 NS = NS->getPreviousDecl()) 6501 NS->setInline(*IsInline); 6502 // Patch up the lookup table for the containing namespace. This isn't really 6503 // correct, but it's good enough for this particular case. 6504 for (DeclContext::decl_iterator I = PrevNS->decls_begin(), 6505 E = PrevNS->decls_end(); I != E; ++I) 6506 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I)) 6507 PrevNS->getParent()->makeDeclVisibleInContext(ND); 6508 return; 6509 } 6510 6511 if (PrevNS->isInline()) 6512 // The user probably just forgot the 'inline', so suggest that it 6513 // be added back. 6514 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 6515 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 6516 else 6517 S.Diag(Loc, diag::err_inline_namespace_mismatch) 6518 << IsInline; 6519 6520 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 6521 *IsInline = PrevNS->isInline(); 6522} 6523 6524/// ActOnStartNamespaceDef - This is called at the start of a namespace 6525/// definition. 6526Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 6527 SourceLocation InlineLoc, 6528 SourceLocation NamespaceLoc, 6529 SourceLocation IdentLoc, 6530 IdentifierInfo *II, 6531 SourceLocation LBrace, 6532 AttributeList *AttrList) { 6533 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 6534 // For anonymous namespace, take the location of the left brace. 6535 SourceLocation Loc = II ? IdentLoc : LBrace; 6536 bool IsInline = InlineLoc.isValid(); 6537 bool IsInvalid = false; 6538 bool IsStd = false; 6539 bool AddToKnown = false; 6540 Scope *DeclRegionScope = NamespcScope->getParent(); 6541 6542 NamespaceDecl *PrevNS = 0; 6543 if (II) { 6544 // C++ [namespace.def]p2: 6545 // The identifier in an original-namespace-definition shall not 6546 // have been previously defined in the declarative region in 6547 // which the original-namespace-definition appears. The 6548 // identifier in an original-namespace-definition is the name of 6549 // the namespace. Subsequently in that declarative region, it is 6550 // treated as an original-namespace-name. 6551 // 6552 // Since namespace names are unique in their scope, and we don't 6553 // look through using directives, just look for any ordinary names. 6554 6555 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member | 6556 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag | 6557 Decl::IDNS_Namespace; 6558 NamedDecl *PrevDecl = 0; 6559 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II); 6560 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 6561 ++I) { 6562 if ((*I)->getIdentifierNamespace() & IDNS) { 6563 PrevDecl = *I; 6564 break; 6565 } 6566 } 6567 6568 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 6569 6570 if (PrevNS) { 6571 // This is an extended namespace definition. 6572 if (IsInline != PrevNS->isInline()) 6573 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 6574 &IsInline, PrevNS); 6575 } else if (PrevDecl) { 6576 // This is an invalid name redefinition. 6577 Diag(Loc, diag::err_redefinition_different_kind) 6578 << II; 6579 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 6580 IsInvalid = true; 6581 // Continue on to push Namespc as current DeclContext and return it. 6582 } else if (II->isStr("std") && 6583 CurContext->getRedeclContext()->isTranslationUnit()) { 6584 // This is the first "real" definition of the namespace "std", so update 6585 // our cache of the "std" namespace to point at this definition. 6586 PrevNS = getStdNamespace(); 6587 IsStd = true; 6588 AddToKnown = !IsInline; 6589 } else { 6590 // We've seen this namespace for the first time. 6591 AddToKnown = !IsInline; 6592 } 6593 } else { 6594 // Anonymous namespaces. 6595 6596 // Determine whether the parent already has an anonymous namespace. 6597 DeclContext *Parent = CurContext->getRedeclContext(); 6598 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 6599 PrevNS = TU->getAnonymousNamespace(); 6600 } else { 6601 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 6602 PrevNS = ND->getAnonymousNamespace(); 6603 } 6604 6605 if (PrevNS && IsInline != PrevNS->isInline()) 6606 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 6607 &IsInline, PrevNS); 6608 } 6609 6610 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 6611 StartLoc, Loc, II, PrevNS); 6612 if (IsInvalid) 6613 Namespc->setInvalidDecl(); 6614 6615 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 6616 6617 // FIXME: Should we be merging attributes? 6618 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 6619 PushNamespaceVisibilityAttr(Attr, Loc); 6620 6621 if (IsStd) 6622 StdNamespace = Namespc; 6623 if (AddToKnown) 6624 KnownNamespaces[Namespc] = false; 6625 6626 if (II) { 6627 PushOnScopeChains(Namespc, DeclRegionScope); 6628 } else { 6629 // Link the anonymous namespace into its parent. 6630 DeclContext *Parent = CurContext->getRedeclContext(); 6631 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 6632 TU->setAnonymousNamespace(Namespc); 6633 } else { 6634 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 6635 } 6636 6637 CurContext->addDecl(Namespc); 6638 6639 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 6640 // behaves as if it were replaced by 6641 // namespace unique { /* empty body */ } 6642 // using namespace unique; 6643 // namespace unique { namespace-body } 6644 // where all occurrences of 'unique' in a translation unit are 6645 // replaced by the same identifier and this identifier differs 6646 // from all other identifiers in the entire program. 6647 6648 // We just create the namespace with an empty name and then add an 6649 // implicit using declaration, just like the standard suggests. 6650 // 6651 // CodeGen enforces the "universally unique" aspect by giving all 6652 // declarations semantically contained within an anonymous 6653 // namespace internal linkage. 6654 6655 if (!PrevNS) { 6656 UsingDirectiveDecl* UD 6657 = UsingDirectiveDecl::Create(Context, Parent, 6658 /* 'using' */ LBrace, 6659 /* 'namespace' */ SourceLocation(), 6660 /* qualifier */ NestedNameSpecifierLoc(), 6661 /* identifier */ SourceLocation(), 6662 Namespc, 6663 /* Ancestor */ Parent); 6664 UD->setImplicit(); 6665 Parent->addDecl(UD); 6666 } 6667 } 6668 6669 ActOnDocumentableDecl(Namespc); 6670 6671 // Although we could have an invalid decl (i.e. the namespace name is a 6672 // redefinition), push it as current DeclContext and try to continue parsing. 6673 // FIXME: We should be able to push Namespc here, so that the each DeclContext 6674 // for the namespace has the declarations that showed up in that particular 6675 // namespace definition. 6676 PushDeclContext(NamespcScope, Namespc); 6677 return Namespc; 6678} 6679 6680/// getNamespaceDecl - Returns the namespace a decl represents. If the decl 6681/// is a namespace alias, returns the namespace it points to. 6682static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 6683 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 6684 return AD->getNamespace(); 6685 return dyn_cast_or_null<NamespaceDecl>(D); 6686} 6687 6688/// ActOnFinishNamespaceDef - This callback is called after a namespace is 6689/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 6690void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 6691 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 6692 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 6693 Namespc->setRBraceLoc(RBrace); 6694 PopDeclContext(); 6695 if (Namespc->hasAttr<VisibilityAttr>()) 6696 PopPragmaVisibility(true, RBrace); 6697} 6698 6699CXXRecordDecl *Sema::getStdBadAlloc() const { 6700 return cast_or_null<CXXRecordDecl>( 6701 StdBadAlloc.get(Context.getExternalSource())); 6702} 6703 6704NamespaceDecl *Sema::getStdNamespace() const { 6705 return cast_or_null<NamespaceDecl>( 6706 StdNamespace.get(Context.getExternalSource())); 6707} 6708 6709/// \brief Retrieve the special "std" namespace, which may require us to 6710/// implicitly define the namespace. 6711NamespaceDecl *Sema::getOrCreateStdNamespace() { 6712 if (!StdNamespace) { 6713 // The "std" namespace has not yet been defined, so build one implicitly. 6714 StdNamespace = NamespaceDecl::Create(Context, 6715 Context.getTranslationUnitDecl(), 6716 /*Inline=*/false, 6717 SourceLocation(), SourceLocation(), 6718 &PP.getIdentifierTable().get("std"), 6719 /*PrevDecl=*/0); 6720 getStdNamespace()->setImplicit(true); 6721 } 6722 6723 return getStdNamespace(); 6724} 6725 6726bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 6727 assert(getLangOpts().CPlusPlus && 6728 "Looking for std::initializer_list outside of C++."); 6729 6730 // We're looking for implicit instantiations of 6731 // template <typename E> class std::initializer_list. 6732 6733 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 6734 return false; 6735 6736 ClassTemplateDecl *Template = 0; 6737 const TemplateArgument *Arguments = 0; 6738 6739 if (const RecordType *RT = Ty->getAs<RecordType>()) { 6740 6741 ClassTemplateSpecializationDecl *Specialization = 6742 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 6743 if (!Specialization) 6744 return false; 6745 6746 Template = Specialization->getSpecializedTemplate(); 6747 Arguments = Specialization->getTemplateArgs().data(); 6748 } else if (const TemplateSpecializationType *TST = 6749 Ty->getAs<TemplateSpecializationType>()) { 6750 Template = dyn_cast_or_null<ClassTemplateDecl>( 6751 TST->getTemplateName().getAsTemplateDecl()); 6752 Arguments = TST->getArgs(); 6753 } 6754 if (!Template) 6755 return false; 6756 6757 if (!StdInitializerList) { 6758 // Haven't recognized std::initializer_list yet, maybe this is it. 6759 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 6760 if (TemplateClass->getIdentifier() != 6761 &PP.getIdentifierTable().get("initializer_list") || 6762 !getStdNamespace()->InEnclosingNamespaceSetOf( 6763 TemplateClass->getDeclContext())) 6764 return false; 6765 // This is a template called std::initializer_list, but is it the right 6766 // template? 6767 TemplateParameterList *Params = Template->getTemplateParameters(); 6768 if (Params->getMinRequiredArguments() != 1) 6769 return false; 6770 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 6771 return false; 6772 6773 // It's the right template. 6774 StdInitializerList = Template; 6775 } 6776 6777 if (Template != StdInitializerList) 6778 return false; 6779 6780 // This is an instance of std::initializer_list. Find the argument type. 6781 if (Element) 6782 *Element = Arguments[0].getAsType(); 6783 return true; 6784} 6785 6786static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 6787 NamespaceDecl *Std = S.getStdNamespace(); 6788 if (!Std) { 6789 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 6790 return 0; 6791 } 6792 6793 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 6794 Loc, Sema::LookupOrdinaryName); 6795 if (!S.LookupQualifiedName(Result, Std)) { 6796 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 6797 return 0; 6798 } 6799 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 6800 if (!Template) { 6801 Result.suppressDiagnostics(); 6802 // We found something weird. Complain about the first thing we found. 6803 NamedDecl *Found = *Result.begin(); 6804 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 6805 return 0; 6806 } 6807 6808 // We found some template called std::initializer_list. Now verify that it's 6809 // correct. 6810 TemplateParameterList *Params = Template->getTemplateParameters(); 6811 if (Params->getMinRequiredArguments() != 1 || 6812 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 6813 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 6814 return 0; 6815 } 6816 6817 return Template; 6818} 6819 6820QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 6821 if (!StdInitializerList) { 6822 StdInitializerList = LookupStdInitializerList(*this, Loc); 6823 if (!StdInitializerList) 6824 return QualType(); 6825 } 6826 6827 TemplateArgumentListInfo Args(Loc, Loc); 6828 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 6829 Context.getTrivialTypeSourceInfo(Element, 6830 Loc))); 6831 return Context.getCanonicalType( 6832 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 6833} 6834 6835bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) { 6836 // C++ [dcl.init.list]p2: 6837 // A constructor is an initializer-list constructor if its first parameter 6838 // is of type std::initializer_list<E> or reference to possibly cv-qualified 6839 // std::initializer_list<E> for some type E, and either there are no other 6840 // parameters or else all other parameters have default arguments. 6841 if (Ctor->getNumParams() < 1 || 6842 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 6843 return false; 6844 6845 QualType ArgType = Ctor->getParamDecl(0)->getType(); 6846 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 6847 ArgType = RT->getPointeeType().getUnqualifiedType(); 6848 6849 return isStdInitializerList(ArgType, 0); 6850} 6851 6852/// \brief Determine whether a using statement is in a context where it will be 6853/// apply in all contexts. 6854static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 6855 switch (CurContext->getDeclKind()) { 6856 case Decl::TranslationUnit: 6857 return true; 6858 case Decl::LinkageSpec: 6859 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 6860 default: 6861 return false; 6862 } 6863} 6864 6865namespace { 6866 6867// Callback to only accept typo corrections that are namespaces. 6868class NamespaceValidatorCCC : public CorrectionCandidateCallback { 6869public: 6870 bool ValidateCandidate(const TypoCorrection &candidate) LLVM_OVERRIDE { 6871 if (NamedDecl *ND = candidate.getCorrectionDecl()) 6872 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 6873 return false; 6874 } 6875}; 6876 6877} 6878 6879static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 6880 CXXScopeSpec &SS, 6881 SourceLocation IdentLoc, 6882 IdentifierInfo *Ident) { 6883 NamespaceValidatorCCC Validator; 6884 R.clear(); 6885 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(), 6886 R.getLookupKind(), Sc, &SS, 6887 Validator)) { 6888 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 6889 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 6890 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 6891 Ident->getName().equals(CorrectedStr); 6892 S.diagnoseTypo(Corrected, 6893 S.PDiag(diag::err_using_directive_member_suggest) 6894 << Ident << DC << DroppedSpecifier << SS.getRange(), 6895 S.PDiag(diag::note_namespace_defined_here)); 6896 } else { 6897 S.diagnoseTypo(Corrected, 6898 S.PDiag(diag::err_using_directive_suggest) << Ident, 6899 S.PDiag(diag::note_namespace_defined_here)); 6900 } 6901 R.addDecl(Corrected.getCorrectionDecl()); 6902 return true; 6903 } 6904 return false; 6905} 6906 6907Decl *Sema::ActOnUsingDirective(Scope *S, 6908 SourceLocation UsingLoc, 6909 SourceLocation NamespcLoc, 6910 CXXScopeSpec &SS, 6911 SourceLocation IdentLoc, 6912 IdentifierInfo *NamespcName, 6913 AttributeList *AttrList) { 6914 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 6915 assert(NamespcName && "Invalid NamespcName."); 6916 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 6917 6918 // This can only happen along a recovery path. 6919 while (S->getFlags() & Scope::TemplateParamScope) 6920 S = S->getParent(); 6921 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 6922 6923 UsingDirectiveDecl *UDir = 0; 6924 NestedNameSpecifier *Qualifier = 0; 6925 if (SS.isSet()) 6926 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 6927 6928 // Lookup namespace name. 6929 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 6930 LookupParsedName(R, S, &SS); 6931 if (R.isAmbiguous()) 6932 return 0; 6933 6934 if (R.empty()) { 6935 R.clear(); 6936 // Allow "using namespace std;" or "using namespace ::std;" even if 6937 // "std" hasn't been defined yet, for GCC compatibility. 6938 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 6939 NamespcName->isStr("std")) { 6940 Diag(IdentLoc, diag::ext_using_undefined_std); 6941 R.addDecl(getOrCreateStdNamespace()); 6942 R.resolveKind(); 6943 } 6944 // Otherwise, attempt typo correction. 6945 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 6946 } 6947 6948 if (!R.empty()) { 6949 NamedDecl *Named = R.getFoundDecl(); 6950 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named)) 6951 && "expected namespace decl"); 6952 // C++ [namespace.udir]p1: 6953 // A using-directive specifies that the names in the nominated 6954 // namespace can be used in the scope in which the 6955 // using-directive appears after the using-directive. During 6956 // unqualified name lookup (3.4.1), the names appear as if they 6957 // were declared in the nearest enclosing namespace which 6958 // contains both the using-directive and the nominated 6959 // namespace. [Note: in this context, "contains" means "contains 6960 // directly or indirectly". ] 6961 6962 // Find enclosing context containing both using-directive and 6963 // nominated namespace. 6964 NamespaceDecl *NS = getNamespaceDecl(Named); 6965 DeclContext *CommonAncestor = cast<DeclContext>(NS); 6966 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 6967 CommonAncestor = CommonAncestor->getParent(); 6968 6969 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 6970 SS.getWithLocInContext(Context), 6971 IdentLoc, Named, CommonAncestor); 6972 6973 if (IsUsingDirectiveInToplevelContext(CurContext) && 6974 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 6975 Diag(IdentLoc, diag::warn_using_directive_in_header); 6976 } 6977 6978 PushUsingDirective(S, UDir); 6979 } else { 6980 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 6981 } 6982 6983 if (UDir) 6984 ProcessDeclAttributeList(S, UDir, AttrList); 6985 6986 return UDir; 6987} 6988 6989void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 6990 // If the scope has an associated entity and the using directive is at 6991 // namespace or translation unit scope, add the UsingDirectiveDecl into 6992 // its lookup structure so qualified name lookup can find it. 6993 DeclContext *Ctx = S->getEntity(); 6994 if (Ctx && !Ctx->isFunctionOrMethod()) 6995 Ctx->addDecl(UDir); 6996 else 6997 // Otherwise, it is at block sope. The using-directives will affect lookup 6998 // only to the end of the scope. 6999 S->PushUsingDirective(UDir); 7000} 7001 7002 7003Decl *Sema::ActOnUsingDeclaration(Scope *S, 7004 AccessSpecifier AS, 7005 bool HasUsingKeyword, 7006 SourceLocation UsingLoc, 7007 CXXScopeSpec &SS, 7008 UnqualifiedId &Name, 7009 AttributeList *AttrList, 7010 bool HasTypenameKeyword, 7011 SourceLocation TypenameLoc) { 7012 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 7013 7014 switch (Name.getKind()) { 7015 case UnqualifiedId::IK_ImplicitSelfParam: 7016 case UnqualifiedId::IK_Identifier: 7017 case UnqualifiedId::IK_OperatorFunctionId: 7018 case UnqualifiedId::IK_LiteralOperatorId: 7019 case UnqualifiedId::IK_ConversionFunctionId: 7020 break; 7021 7022 case UnqualifiedId::IK_ConstructorName: 7023 case UnqualifiedId::IK_ConstructorTemplateId: 7024 // C++11 inheriting constructors. 7025 Diag(Name.getLocStart(), 7026 getLangOpts().CPlusPlus11 ? 7027 diag::warn_cxx98_compat_using_decl_constructor : 7028 diag::err_using_decl_constructor) 7029 << SS.getRange(); 7030 7031 if (getLangOpts().CPlusPlus11) break; 7032 7033 return 0; 7034 7035 case UnqualifiedId::IK_DestructorName: 7036 Diag(Name.getLocStart(), diag::err_using_decl_destructor) 7037 << SS.getRange(); 7038 return 0; 7039 7040 case UnqualifiedId::IK_TemplateId: 7041 Diag(Name.getLocStart(), diag::err_using_decl_template_id) 7042 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 7043 return 0; 7044 } 7045 7046 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 7047 DeclarationName TargetName = TargetNameInfo.getName(); 7048 if (!TargetName) 7049 return 0; 7050 7051 // Warn about access declarations. 7052 if (!HasUsingKeyword) { 7053 Diag(Name.getLocStart(), 7054 getLangOpts().CPlusPlus11 ? diag::err_access_decl 7055 : diag::warn_access_decl_deprecated) 7056 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 7057 } 7058 7059 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 7060 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 7061 return 0; 7062 7063 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 7064 TargetNameInfo, AttrList, 7065 /* IsInstantiation */ false, 7066 HasTypenameKeyword, TypenameLoc); 7067 if (UD) 7068 PushOnScopeChains(UD, S, /*AddToContext*/ false); 7069 7070 return UD; 7071} 7072 7073/// \brief Determine whether a using declaration considers the given 7074/// declarations as "equivalent", e.g., if they are redeclarations of 7075/// the same entity or are both typedefs of the same type. 7076static bool 7077IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2, 7078 bool &SuppressRedeclaration) { 7079 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) { 7080 SuppressRedeclaration = false; 7081 return true; 7082 } 7083 7084 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 7085 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) { 7086 SuppressRedeclaration = true; 7087 return Context.hasSameType(TD1->getUnderlyingType(), 7088 TD2->getUnderlyingType()); 7089 } 7090 7091 return false; 7092} 7093 7094 7095/// Determines whether to create a using shadow decl for a particular 7096/// decl, given the set of decls existing prior to this using lookup. 7097bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 7098 const LookupResult &Previous) { 7099 // Diagnose finding a decl which is not from a base class of the 7100 // current class. We do this now because there are cases where this 7101 // function will silently decide not to build a shadow decl, which 7102 // will pre-empt further diagnostics. 7103 // 7104 // We don't need to do this in C++0x because we do the check once on 7105 // the qualifier. 7106 // 7107 // FIXME: diagnose the following if we care enough: 7108 // struct A { int foo; }; 7109 // struct B : A { using A::foo; }; 7110 // template <class T> struct C : A {}; 7111 // template <class T> struct D : C<T> { using B::foo; } // <--- 7112 // This is invalid (during instantiation) in C++03 because B::foo 7113 // resolves to the using decl in B, which is not a base class of D<T>. 7114 // We can't diagnose it immediately because C<T> is an unknown 7115 // specialization. The UsingShadowDecl in D<T> then points directly 7116 // to A::foo, which will look well-formed when we instantiate. 7117 // The right solution is to not collapse the shadow-decl chain. 7118 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 7119 DeclContext *OrigDC = Orig->getDeclContext(); 7120 7121 // Handle enums and anonymous structs. 7122 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 7123 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 7124 while (OrigRec->isAnonymousStructOrUnion()) 7125 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 7126 7127 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 7128 if (OrigDC == CurContext) { 7129 Diag(Using->getLocation(), 7130 diag::err_using_decl_nested_name_specifier_is_current_class) 7131 << Using->getQualifierLoc().getSourceRange(); 7132 Diag(Orig->getLocation(), diag::note_using_decl_target); 7133 return true; 7134 } 7135 7136 Diag(Using->getQualifierLoc().getBeginLoc(), 7137 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7138 << Using->getQualifier() 7139 << cast<CXXRecordDecl>(CurContext) 7140 << Using->getQualifierLoc().getSourceRange(); 7141 Diag(Orig->getLocation(), diag::note_using_decl_target); 7142 return true; 7143 } 7144 } 7145 7146 if (Previous.empty()) return false; 7147 7148 NamedDecl *Target = Orig; 7149 if (isa<UsingShadowDecl>(Target)) 7150 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 7151 7152 // If the target happens to be one of the previous declarations, we 7153 // don't have a conflict. 7154 // 7155 // FIXME: but we might be increasing its access, in which case we 7156 // should redeclare it. 7157 NamedDecl *NonTag = 0, *Tag = 0; 7158 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7159 I != E; ++I) { 7160 NamedDecl *D = (*I)->getUnderlyingDecl(); 7161 bool Result; 7162 if (IsEquivalentForUsingDecl(Context, D, Target, Result)) 7163 return Result; 7164 7165 (isa<TagDecl>(D) ? Tag : NonTag) = D; 7166 } 7167 7168 if (Target->isFunctionOrFunctionTemplate()) { 7169 FunctionDecl *FD; 7170 if (isa<FunctionTemplateDecl>(Target)) 7171 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl(); 7172 else 7173 FD = cast<FunctionDecl>(Target); 7174 7175 NamedDecl *OldDecl = 0; 7176 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) { 7177 case Ovl_Overload: 7178 return false; 7179 7180 case Ovl_NonFunction: 7181 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7182 break; 7183 7184 // We found a decl with the exact signature. 7185 case Ovl_Match: 7186 // If we're in a record, we want to hide the target, so we 7187 // return true (without a diagnostic) to tell the caller not to 7188 // build a shadow decl. 7189 if (CurContext->isRecord()) 7190 return true; 7191 7192 // If we're not in a record, this is an error. 7193 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7194 break; 7195 } 7196 7197 Diag(Target->getLocation(), diag::note_using_decl_target); 7198 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 7199 return true; 7200 } 7201 7202 // Target is not a function. 7203 7204 if (isa<TagDecl>(Target)) { 7205 // No conflict between a tag and a non-tag. 7206 if (!Tag) return false; 7207 7208 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7209 Diag(Target->getLocation(), diag::note_using_decl_target); 7210 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 7211 return true; 7212 } 7213 7214 // No conflict between a tag and a non-tag. 7215 if (!NonTag) return false; 7216 7217 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7218 Diag(Target->getLocation(), diag::note_using_decl_target); 7219 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 7220 return true; 7221} 7222 7223/// Builds a shadow declaration corresponding to a 'using' declaration. 7224UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 7225 UsingDecl *UD, 7226 NamedDecl *Orig) { 7227 7228 // If we resolved to another shadow declaration, just coalesce them. 7229 NamedDecl *Target = Orig; 7230 if (isa<UsingShadowDecl>(Target)) { 7231 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 7232 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 7233 } 7234 7235 UsingShadowDecl *Shadow 7236 = UsingShadowDecl::Create(Context, CurContext, 7237 UD->getLocation(), UD, Target); 7238 UD->addShadowDecl(Shadow); 7239 7240 Shadow->setAccess(UD->getAccess()); 7241 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 7242 Shadow->setInvalidDecl(); 7243 7244 if (S) 7245 PushOnScopeChains(Shadow, S); 7246 else 7247 CurContext->addDecl(Shadow); 7248 7249 7250 return Shadow; 7251} 7252 7253/// Hides a using shadow declaration. This is required by the current 7254/// using-decl implementation when a resolvable using declaration in a 7255/// class is followed by a declaration which would hide or override 7256/// one or more of the using decl's targets; for example: 7257/// 7258/// struct Base { void foo(int); }; 7259/// struct Derived : Base { 7260/// using Base::foo; 7261/// void foo(int); 7262/// }; 7263/// 7264/// The governing language is C++03 [namespace.udecl]p12: 7265/// 7266/// When a using-declaration brings names from a base class into a 7267/// derived class scope, member functions in the derived class 7268/// override and/or hide member functions with the same name and 7269/// parameter types in a base class (rather than conflicting). 7270/// 7271/// There are two ways to implement this: 7272/// (1) optimistically create shadow decls when they're not hidden 7273/// by existing declarations, or 7274/// (2) don't create any shadow decls (or at least don't make them 7275/// visible) until we've fully parsed/instantiated the class. 7276/// The problem with (1) is that we might have to retroactively remove 7277/// a shadow decl, which requires several O(n) operations because the 7278/// decl structures are (very reasonably) not designed for removal. 7279/// (2) avoids this but is very fiddly and phase-dependent. 7280void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 7281 if (Shadow->getDeclName().getNameKind() == 7282 DeclarationName::CXXConversionFunctionName) 7283 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 7284 7285 // Remove it from the DeclContext... 7286 Shadow->getDeclContext()->removeDecl(Shadow); 7287 7288 // ...and the scope, if applicable... 7289 if (S) { 7290 S->RemoveDecl(Shadow); 7291 IdResolver.RemoveDecl(Shadow); 7292 } 7293 7294 // ...and the using decl. 7295 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 7296 7297 // TODO: complain somehow if Shadow was used. It shouldn't 7298 // be possible for this to happen, because...? 7299} 7300 7301namespace { 7302class UsingValidatorCCC : public CorrectionCandidateCallback { 7303public: 7304 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation) 7305 : HasTypenameKeyword(HasTypenameKeyword), 7306 IsInstantiation(IsInstantiation) {} 7307 7308 bool ValidateCandidate(const TypoCorrection &Candidate) LLVM_OVERRIDE { 7309 NamedDecl *ND = Candidate.getCorrectionDecl(); 7310 7311 // Keywords are not valid here. 7312 if (!ND || isa<NamespaceDecl>(ND)) 7313 return false; 7314 7315 // Completely unqualified names are invalid for a 'using' declaration. 7316 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 7317 return false; 7318 7319 if (isa<TypeDecl>(ND)) 7320 return HasTypenameKeyword || !IsInstantiation; 7321 7322 return !HasTypenameKeyword; 7323 } 7324 7325private: 7326 bool HasTypenameKeyword; 7327 bool IsInstantiation; 7328}; 7329} // end anonymous namespace 7330 7331/// Builds a using declaration. 7332/// 7333/// \param IsInstantiation - Whether this call arises from an 7334/// instantiation of an unresolved using declaration. We treat 7335/// the lookup differently for these declarations. 7336NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 7337 SourceLocation UsingLoc, 7338 CXXScopeSpec &SS, 7339 const DeclarationNameInfo &NameInfo, 7340 AttributeList *AttrList, 7341 bool IsInstantiation, 7342 bool HasTypenameKeyword, 7343 SourceLocation TypenameLoc) { 7344 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 7345 SourceLocation IdentLoc = NameInfo.getLoc(); 7346 assert(IdentLoc.isValid() && "Invalid TargetName location."); 7347 7348 // FIXME: We ignore attributes for now. 7349 7350 if (SS.isEmpty()) { 7351 Diag(IdentLoc, diag::err_using_requires_qualname); 7352 return 0; 7353 } 7354 7355 // Do the redeclaration lookup in the current scope. 7356 LookupResult Previous(*this, NameInfo, LookupUsingDeclName, 7357 ForRedeclaration); 7358 Previous.setHideTags(false); 7359 if (S) { 7360 LookupName(Previous, S); 7361 7362 // It is really dumb that we have to do this. 7363 LookupResult::Filter F = Previous.makeFilter(); 7364 while (F.hasNext()) { 7365 NamedDecl *D = F.next(); 7366 if (!isDeclInScope(D, CurContext, S)) 7367 F.erase(); 7368 } 7369 F.done(); 7370 } else { 7371 assert(IsInstantiation && "no scope in non-instantiation"); 7372 assert(CurContext->isRecord() && "scope not record in instantiation"); 7373 LookupQualifiedName(Previous, CurContext); 7374 } 7375 7376 // Check for invalid redeclarations. 7377 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 7378 SS, IdentLoc, Previous)) 7379 return 0; 7380 7381 // Check for bad qualifiers. 7382 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc)) 7383 return 0; 7384 7385 DeclContext *LookupContext = computeDeclContext(SS); 7386 NamedDecl *D; 7387 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 7388 if (!LookupContext) { 7389 if (HasTypenameKeyword) { 7390 // FIXME: not all declaration name kinds are legal here 7391 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 7392 UsingLoc, TypenameLoc, 7393 QualifierLoc, 7394 IdentLoc, NameInfo.getName()); 7395 } else { 7396 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 7397 QualifierLoc, NameInfo); 7398 } 7399 } else { 7400 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 7401 NameInfo, HasTypenameKeyword); 7402 } 7403 D->setAccess(AS); 7404 CurContext->addDecl(D); 7405 7406 if (!LookupContext) return D; 7407 UsingDecl *UD = cast<UsingDecl>(D); 7408 7409 if (RequireCompleteDeclContext(SS, LookupContext)) { 7410 UD->setInvalidDecl(); 7411 return UD; 7412 } 7413 7414 // The normal rules do not apply to inheriting constructor declarations. 7415 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) { 7416 if (CheckInheritingConstructorUsingDecl(UD)) 7417 UD->setInvalidDecl(); 7418 return UD; 7419 } 7420 7421 // Otherwise, look up the target name. 7422 7423 LookupResult R(*this, NameInfo, LookupOrdinaryName); 7424 7425 // Unlike most lookups, we don't always want to hide tag 7426 // declarations: tag names are visible through the using declaration 7427 // even if hidden by ordinary names, *except* in a dependent context 7428 // where it's important for the sanity of two-phase lookup. 7429 if (!IsInstantiation) 7430 R.setHideTags(false); 7431 7432 // For the purposes of this lookup, we have a base object type 7433 // equal to that of the current context. 7434 if (CurContext->isRecord()) { 7435 R.setBaseObjectType( 7436 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 7437 } 7438 7439 LookupQualifiedName(R, LookupContext); 7440 7441 // Try to correct typos if possible. 7442 if (R.empty()) { 7443 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation); 7444 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(), 7445 R.getLookupKind(), S, &SS, CCC)){ 7446 // We reject any correction for which ND would be NULL. 7447 NamedDecl *ND = Corrected.getCorrectionDecl(); 7448 R.setLookupName(Corrected.getCorrection()); 7449 R.addDecl(ND); 7450 // We reject candidates where DroppedSpecifier == true, hence the 7451 // literal '0' below. 7452 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 7453 << NameInfo.getName() << LookupContext << 0 7454 << SS.getRange()); 7455 } else { 7456 Diag(IdentLoc, diag::err_no_member) 7457 << NameInfo.getName() << LookupContext << SS.getRange(); 7458 UD->setInvalidDecl(); 7459 return UD; 7460 } 7461 } 7462 7463 if (R.isAmbiguous()) { 7464 UD->setInvalidDecl(); 7465 return UD; 7466 } 7467 7468 if (HasTypenameKeyword) { 7469 // If we asked for a typename and got a non-type decl, error out. 7470 if (!R.getAsSingle<TypeDecl>()) { 7471 Diag(IdentLoc, diag::err_using_typename_non_type); 7472 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 7473 Diag((*I)->getUnderlyingDecl()->getLocation(), 7474 diag::note_using_decl_target); 7475 UD->setInvalidDecl(); 7476 return UD; 7477 } 7478 } else { 7479 // If we asked for a non-typename and we got a type, error out, 7480 // but only if this is an instantiation of an unresolved using 7481 // decl. Otherwise just silently find the type name. 7482 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 7483 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 7484 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 7485 UD->setInvalidDecl(); 7486 return UD; 7487 } 7488 } 7489 7490 // C++0x N2914 [namespace.udecl]p6: 7491 // A using-declaration shall not name a namespace. 7492 if (R.getAsSingle<NamespaceDecl>()) { 7493 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 7494 << SS.getRange(); 7495 UD->setInvalidDecl(); 7496 return UD; 7497 } 7498 7499 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 7500 if (!CheckUsingShadowDecl(UD, *I, Previous)) 7501 BuildUsingShadowDecl(S, UD, *I); 7502 } 7503 7504 return UD; 7505} 7506 7507/// Additional checks for a using declaration referring to a constructor name. 7508bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 7509 assert(!UD->hasTypename() && "expecting a constructor name"); 7510 7511 const Type *SourceType = UD->getQualifier()->getAsType(); 7512 assert(SourceType && 7513 "Using decl naming constructor doesn't have type in scope spec."); 7514 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 7515 7516 // Check whether the named type is a direct base class. 7517 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified(); 7518 CXXRecordDecl::base_class_iterator BaseIt, BaseE; 7519 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end(); 7520 BaseIt != BaseE; ++BaseIt) { 7521 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified(); 7522 if (CanonicalSourceType == BaseType) 7523 break; 7524 if (BaseIt->getType()->isDependentType()) 7525 break; 7526 } 7527 7528 if (BaseIt == BaseE) { 7529 // Did not find SourceType in the bases. 7530 Diag(UD->getUsingLoc(), 7531 diag::err_using_decl_constructor_not_in_direct_base) 7532 << UD->getNameInfo().getSourceRange() 7533 << QualType(SourceType, 0) << TargetClass; 7534 return true; 7535 } 7536 7537 if (!CurContext->isDependentContext()) 7538 BaseIt->setInheritConstructors(); 7539 7540 return false; 7541} 7542 7543/// Checks that the given using declaration is not an invalid 7544/// redeclaration. Note that this is checking only for the using decl 7545/// itself, not for any ill-formedness among the UsingShadowDecls. 7546bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 7547 bool HasTypenameKeyword, 7548 const CXXScopeSpec &SS, 7549 SourceLocation NameLoc, 7550 const LookupResult &Prev) { 7551 // C++03 [namespace.udecl]p8: 7552 // C++0x [namespace.udecl]p10: 7553 // A using-declaration is a declaration and can therefore be used 7554 // repeatedly where (and only where) multiple declarations are 7555 // allowed. 7556 // 7557 // That's in non-member contexts. 7558 if (!CurContext->getRedeclContext()->isRecord()) 7559 return false; 7560 7561 NestedNameSpecifier *Qual 7562 = static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 7563 7564 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 7565 NamedDecl *D = *I; 7566 7567 bool DTypename; 7568 NestedNameSpecifier *DQual; 7569 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 7570 DTypename = UD->hasTypename(); 7571 DQual = UD->getQualifier(); 7572 } else if (UnresolvedUsingValueDecl *UD 7573 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 7574 DTypename = false; 7575 DQual = UD->getQualifier(); 7576 } else if (UnresolvedUsingTypenameDecl *UD 7577 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 7578 DTypename = true; 7579 DQual = UD->getQualifier(); 7580 } else continue; 7581 7582 // using decls differ if one says 'typename' and the other doesn't. 7583 // FIXME: non-dependent using decls? 7584 if (HasTypenameKeyword != DTypename) continue; 7585 7586 // using decls differ if they name different scopes (but note that 7587 // template instantiation can cause this check to trigger when it 7588 // didn't before instantiation). 7589 if (Context.getCanonicalNestedNameSpecifier(Qual) != 7590 Context.getCanonicalNestedNameSpecifier(DQual)) 7591 continue; 7592 7593 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 7594 Diag(D->getLocation(), diag::note_using_decl) << 1; 7595 return true; 7596 } 7597 7598 return false; 7599} 7600 7601 7602/// Checks that the given nested-name qualifier used in a using decl 7603/// in the current context is appropriately related to the current 7604/// scope. If an error is found, diagnoses it and returns true. 7605bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 7606 const CXXScopeSpec &SS, 7607 SourceLocation NameLoc) { 7608 DeclContext *NamedContext = computeDeclContext(SS); 7609 7610 if (!CurContext->isRecord()) { 7611 // C++03 [namespace.udecl]p3: 7612 // C++0x [namespace.udecl]p8: 7613 // A using-declaration for a class member shall be a member-declaration. 7614 7615 // If we weren't able to compute a valid scope, it must be a 7616 // dependent class scope. 7617 if (!NamedContext || NamedContext->isRecord()) { 7618 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 7619 << SS.getRange(); 7620 return true; 7621 } 7622 7623 // Otherwise, everything is known to be fine. 7624 return false; 7625 } 7626 7627 // The current scope is a record. 7628 7629 // If the named context is dependent, we can't decide much. 7630 if (!NamedContext) { 7631 // FIXME: in C++0x, we can diagnose if we can prove that the 7632 // nested-name-specifier does not refer to a base class, which is 7633 // still possible in some cases. 7634 7635 // Otherwise we have to conservatively report that things might be 7636 // okay. 7637 return false; 7638 } 7639 7640 if (!NamedContext->isRecord()) { 7641 // Ideally this would point at the last name in the specifier, 7642 // but we don't have that level of source info. 7643 Diag(SS.getRange().getBegin(), 7644 diag::err_using_decl_nested_name_specifier_is_not_class) 7645 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange(); 7646 return true; 7647 } 7648 7649 if (!NamedContext->isDependentContext() && 7650 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 7651 return true; 7652 7653 if (getLangOpts().CPlusPlus11) { 7654 // C++0x [namespace.udecl]p3: 7655 // In a using-declaration used as a member-declaration, the 7656 // nested-name-specifier shall name a base class of the class 7657 // being defined. 7658 7659 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 7660 cast<CXXRecordDecl>(NamedContext))) { 7661 if (CurContext == NamedContext) { 7662 Diag(NameLoc, 7663 diag::err_using_decl_nested_name_specifier_is_current_class) 7664 << SS.getRange(); 7665 return true; 7666 } 7667 7668 Diag(SS.getRange().getBegin(), 7669 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7670 << (NestedNameSpecifier*) SS.getScopeRep() 7671 << cast<CXXRecordDecl>(CurContext) 7672 << SS.getRange(); 7673 return true; 7674 } 7675 7676 return false; 7677 } 7678 7679 // C++03 [namespace.udecl]p4: 7680 // A using-declaration used as a member-declaration shall refer 7681 // to a member of a base class of the class being defined [etc.]. 7682 7683 // Salient point: SS doesn't have to name a base class as long as 7684 // lookup only finds members from base classes. Therefore we can 7685 // diagnose here only if we can prove that that can't happen, 7686 // i.e. if the class hierarchies provably don't intersect. 7687 7688 // TODO: it would be nice if "definitely valid" results were cached 7689 // in the UsingDecl and UsingShadowDecl so that these checks didn't 7690 // need to be repeated. 7691 7692 struct UserData { 7693 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases; 7694 7695 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) { 7696 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 7697 Data->Bases.insert(Base); 7698 return true; 7699 } 7700 7701 bool hasDependentBases(const CXXRecordDecl *Class) { 7702 return !Class->forallBases(collect, this); 7703 } 7704 7705 /// Returns true if the base is dependent or is one of the 7706 /// accumulated base classes. 7707 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) { 7708 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 7709 return !Data->Bases.count(Base); 7710 } 7711 7712 bool mightShareBases(const CXXRecordDecl *Class) { 7713 return Bases.count(Class) || !Class->forallBases(doesNotContain, this); 7714 } 7715 }; 7716 7717 UserData Data; 7718 7719 // Returns false if we find a dependent base. 7720 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext))) 7721 return false; 7722 7723 // Returns false if the class has a dependent base or if it or one 7724 // of its bases is present in the base set of the current context. 7725 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext))) 7726 return false; 7727 7728 Diag(SS.getRange().getBegin(), 7729 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7730 << (NestedNameSpecifier*) SS.getScopeRep() 7731 << cast<CXXRecordDecl>(CurContext) 7732 << SS.getRange(); 7733 7734 return true; 7735} 7736 7737Decl *Sema::ActOnAliasDeclaration(Scope *S, 7738 AccessSpecifier AS, 7739 MultiTemplateParamsArg TemplateParamLists, 7740 SourceLocation UsingLoc, 7741 UnqualifiedId &Name, 7742 AttributeList *AttrList, 7743 TypeResult Type) { 7744 // Skip up to the relevant declaration scope. 7745 while (S->getFlags() & Scope::TemplateParamScope) 7746 S = S->getParent(); 7747 assert((S->getFlags() & Scope::DeclScope) && 7748 "got alias-declaration outside of declaration scope"); 7749 7750 if (Type.isInvalid()) 7751 return 0; 7752 7753 bool Invalid = false; 7754 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 7755 TypeSourceInfo *TInfo = 0; 7756 GetTypeFromParser(Type.get(), &TInfo); 7757 7758 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 7759 return 0; 7760 7761 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 7762 UPPC_DeclarationType)) { 7763 Invalid = true; 7764 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 7765 TInfo->getTypeLoc().getBeginLoc()); 7766 } 7767 7768 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration); 7769 LookupName(Previous, S); 7770 7771 // Warn about shadowing the name of a template parameter. 7772 if (Previous.isSingleResult() && 7773 Previous.getFoundDecl()->isTemplateParameter()) { 7774 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 7775 Previous.clear(); 7776 } 7777 7778 assert(Name.Kind == UnqualifiedId::IK_Identifier && 7779 "name in alias declaration must be an identifier"); 7780 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 7781 Name.StartLocation, 7782 Name.Identifier, TInfo); 7783 7784 NewTD->setAccess(AS); 7785 7786 if (Invalid) 7787 NewTD->setInvalidDecl(); 7788 7789 ProcessDeclAttributeList(S, NewTD, AttrList); 7790 7791 CheckTypedefForVariablyModifiedType(S, NewTD); 7792 Invalid |= NewTD->isInvalidDecl(); 7793 7794 bool Redeclaration = false; 7795 7796 NamedDecl *NewND; 7797 if (TemplateParamLists.size()) { 7798 TypeAliasTemplateDecl *OldDecl = 0; 7799 TemplateParameterList *OldTemplateParams = 0; 7800 7801 if (TemplateParamLists.size() != 1) { 7802 Diag(UsingLoc, diag::err_alias_template_extra_headers) 7803 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 7804 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 7805 } 7806 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 7807 7808 // Only consider previous declarations in the same scope. 7809 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 7810 /*ExplicitInstantiationOrSpecialization*/false); 7811 if (!Previous.empty()) { 7812 Redeclaration = true; 7813 7814 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 7815 if (!OldDecl && !Invalid) { 7816 Diag(UsingLoc, diag::err_redefinition_different_kind) 7817 << Name.Identifier; 7818 7819 NamedDecl *OldD = Previous.getRepresentativeDecl(); 7820 if (OldD->getLocation().isValid()) 7821 Diag(OldD->getLocation(), diag::note_previous_definition); 7822 7823 Invalid = true; 7824 } 7825 7826 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 7827 if (TemplateParameterListsAreEqual(TemplateParams, 7828 OldDecl->getTemplateParameters(), 7829 /*Complain=*/true, 7830 TPL_TemplateMatch)) 7831 OldTemplateParams = OldDecl->getTemplateParameters(); 7832 else 7833 Invalid = true; 7834 7835 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 7836 if (!Invalid && 7837 !Context.hasSameType(OldTD->getUnderlyingType(), 7838 NewTD->getUnderlyingType())) { 7839 // FIXME: The C++0x standard does not clearly say this is ill-formed, 7840 // but we can't reasonably accept it. 7841 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 7842 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 7843 if (OldTD->getLocation().isValid()) 7844 Diag(OldTD->getLocation(), diag::note_previous_definition); 7845 Invalid = true; 7846 } 7847 } 7848 } 7849 7850 // Merge any previous default template arguments into our parameters, 7851 // and check the parameter list. 7852 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 7853 TPC_TypeAliasTemplate)) 7854 return 0; 7855 7856 TypeAliasTemplateDecl *NewDecl = 7857 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 7858 Name.Identifier, TemplateParams, 7859 NewTD); 7860 7861 NewDecl->setAccess(AS); 7862 7863 if (Invalid) 7864 NewDecl->setInvalidDecl(); 7865 else if (OldDecl) 7866 NewDecl->setPreviousDecl(OldDecl); 7867 7868 NewND = NewDecl; 7869 } else { 7870 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 7871 NewND = NewTD; 7872 } 7873 7874 if (!Redeclaration) 7875 PushOnScopeChains(NewND, S); 7876 7877 ActOnDocumentableDecl(NewND); 7878 return NewND; 7879} 7880 7881Decl *Sema::ActOnNamespaceAliasDef(Scope *S, 7882 SourceLocation NamespaceLoc, 7883 SourceLocation AliasLoc, 7884 IdentifierInfo *Alias, 7885 CXXScopeSpec &SS, 7886 SourceLocation IdentLoc, 7887 IdentifierInfo *Ident) { 7888 7889 // Lookup the namespace name. 7890 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 7891 LookupParsedName(R, S, &SS); 7892 7893 // Check if we have a previous declaration with the same name. 7894 NamedDecl *PrevDecl 7895 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName, 7896 ForRedeclaration); 7897 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S)) 7898 PrevDecl = 0; 7899 7900 if (PrevDecl) { 7901 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 7902 // We already have an alias with the same name that points to the same 7903 // namespace, so don't create a new one. 7904 // FIXME: At some point, we'll want to create the (redundant) 7905 // declaration to maintain better source information. 7906 if (!R.isAmbiguous() && !R.empty() && 7907 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl()))) 7908 return 0; 7909 } 7910 7911 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition : 7912 diag::err_redefinition_different_kind; 7913 Diag(AliasLoc, DiagID) << Alias; 7914 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 7915 return 0; 7916 } 7917 7918 if (R.isAmbiguous()) 7919 return 0; 7920 7921 if (R.empty()) { 7922 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 7923 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 7924 return 0; 7925 } 7926 } 7927 7928 NamespaceAliasDecl *AliasDecl = 7929 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 7930 Alias, SS.getWithLocInContext(Context), 7931 IdentLoc, R.getFoundDecl()); 7932 7933 PushOnScopeChains(AliasDecl, S); 7934 return AliasDecl; 7935} 7936 7937Sema::ImplicitExceptionSpecification 7938Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, 7939 CXXMethodDecl *MD) { 7940 CXXRecordDecl *ClassDecl = MD->getParent(); 7941 7942 // C++ [except.spec]p14: 7943 // An implicitly declared special member function (Clause 12) shall have an 7944 // exception-specification. [...] 7945 ImplicitExceptionSpecification ExceptSpec(*this); 7946 if (ClassDecl->isInvalidDecl()) 7947 return ExceptSpec; 7948 7949 // Direct base-class constructors. 7950 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 7951 BEnd = ClassDecl->bases_end(); 7952 B != BEnd; ++B) { 7953 if (B->isVirtual()) // Handled below. 7954 continue; 7955 7956 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 7957 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7958 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 7959 // If this is a deleted function, add it anyway. This might be conformant 7960 // with the standard. This might not. I'm not sure. It might not matter. 7961 if (Constructor) 7962 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 7963 } 7964 } 7965 7966 // Virtual base-class constructors. 7967 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 7968 BEnd = ClassDecl->vbases_end(); 7969 B != BEnd; ++B) { 7970 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 7971 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7972 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 7973 // If this is a deleted function, add it anyway. This might be conformant 7974 // with the standard. This might not. I'm not sure. It might not matter. 7975 if (Constructor) 7976 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 7977 } 7978 } 7979 7980 // Field constructors. 7981 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 7982 FEnd = ClassDecl->field_end(); 7983 F != FEnd; ++F) { 7984 if (F->hasInClassInitializer()) { 7985 if (Expr *E = F->getInClassInitializer()) 7986 ExceptSpec.CalledExpr(E); 7987 else if (!F->isInvalidDecl()) 7988 // DR1351: 7989 // If the brace-or-equal-initializer of a non-static data member 7990 // invokes a defaulted default constructor of its class or of an 7991 // enclosing class in a potentially evaluated subexpression, the 7992 // program is ill-formed. 7993 // 7994 // This resolution is unworkable: the exception specification of the 7995 // default constructor can be needed in an unevaluated context, in 7996 // particular, in the operand of a noexcept-expression, and we can be 7997 // unable to compute an exception specification for an enclosed class. 7998 // 7999 // We do not allow an in-class initializer to require the evaluation 8000 // of the exception specification for any in-class initializer whose 8001 // definition is not lexically complete. 8002 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD; 8003 } else if (const RecordType *RecordTy 8004 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 8005 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8006 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 8007 // If this is a deleted function, add it anyway. This might be conformant 8008 // with the standard. This might not. I'm not sure. It might not matter. 8009 // In particular, the problem is that this function never gets called. It 8010 // might just be ill-formed because this function attempts to refer to 8011 // a deleted function here. 8012 if (Constructor) 8013 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 8014 } 8015 } 8016 8017 return ExceptSpec; 8018} 8019 8020Sema::ImplicitExceptionSpecification 8021Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) { 8022 CXXRecordDecl *ClassDecl = CD->getParent(); 8023 8024 // C++ [except.spec]p14: 8025 // An inheriting constructor [...] shall have an exception-specification. [...] 8026 ImplicitExceptionSpecification ExceptSpec(*this); 8027 if (ClassDecl->isInvalidDecl()) 8028 return ExceptSpec; 8029 8030 // Inherited constructor. 8031 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor(); 8032 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent(); 8033 // FIXME: Copying or moving the parameters could add extra exceptions to the 8034 // set, as could the default arguments for the inherited constructor. This 8035 // will be addressed when we implement the resolution of core issue 1351. 8036 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD); 8037 8038 // Direct base-class constructors. 8039 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 8040 BEnd = ClassDecl->bases_end(); 8041 B != BEnd; ++B) { 8042 if (B->isVirtual()) // Handled below. 8043 continue; 8044 8045 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 8046 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8047 if (BaseClassDecl == InheritedDecl) 8048 continue; 8049 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8050 if (Constructor) 8051 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 8052 } 8053 } 8054 8055 // Virtual base-class constructors. 8056 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 8057 BEnd = ClassDecl->vbases_end(); 8058 B != BEnd; ++B) { 8059 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 8060 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8061 if (BaseClassDecl == InheritedDecl) 8062 continue; 8063 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8064 if (Constructor) 8065 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 8066 } 8067 } 8068 8069 // Field constructors. 8070 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 8071 FEnd = ClassDecl->field_end(); 8072 F != FEnd; ++F) { 8073 if (F->hasInClassInitializer()) { 8074 if (Expr *E = F->getInClassInitializer()) 8075 ExceptSpec.CalledExpr(E); 8076 else if (!F->isInvalidDecl()) 8077 Diag(CD->getLocation(), 8078 diag::err_in_class_initializer_references_def_ctor) << CD; 8079 } else if (const RecordType *RecordTy 8080 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 8081 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8082 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 8083 if (Constructor) 8084 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 8085 } 8086 } 8087 8088 return ExceptSpec; 8089} 8090 8091namespace { 8092/// RAII object to register a special member as being currently declared. 8093struct DeclaringSpecialMember { 8094 Sema &S; 8095 Sema::SpecialMemberDecl D; 8096 bool WasAlreadyBeingDeclared; 8097 8098 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 8099 : S(S), D(RD, CSM) { 8100 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D); 8101 if (WasAlreadyBeingDeclared) 8102 // This almost never happens, but if it does, ensure that our cache 8103 // doesn't contain a stale result. 8104 S.SpecialMemberCache.clear(); 8105 8106 // FIXME: Register a note to be produced if we encounter an error while 8107 // declaring the special member. 8108 } 8109 ~DeclaringSpecialMember() { 8110 if (!WasAlreadyBeingDeclared) 8111 S.SpecialMembersBeingDeclared.erase(D); 8112 } 8113 8114 /// \brief Are we already trying to declare this special member? 8115 bool isAlreadyBeingDeclared() const { 8116 return WasAlreadyBeingDeclared; 8117 } 8118}; 8119} 8120 8121CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 8122 CXXRecordDecl *ClassDecl) { 8123 // C++ [class.ctor]p5: 8124 // A default constructor for a class X is a constructor of class X 8125 // that can be called without an argument. If there is no 8126 // user-declared constructor for class X, a default constructor is 8127 // implicitly declared. An implicitly-declared default constructor 8128 // is an inline public member of its class. 8129 assert(ClassDecl->needsImplicitDefaultConstructor() && 8130 "Should not build implicit default constructor!"); 8131 8132 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 8133 if (DSM.isAlreadyBeingDeclared()) 8134 return 0; 8135 8136 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 8137 CXXDefaultConstructor, 8138 false); 8139 8140 // Create the actual constructor declaration. 8141 CanQualType ClassType 8142 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8143 SourceLocation ClassLoc = ClassDecl->getLocation(); 8144 DeclarationName Name 8145 = Context.DeclarationNames.getCXXConstructorName(ClassType); 8146 DeclarationNameInfo NameInfo(Name, ClassLoc); 8147 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 8148 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0, 8149 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 8150 Constexpr); 8151 DefaultCon->setAccess(AS_public); 8152 DefaultCon->setDefaulted(); 8153 DefaultCon->setImplicit(); 8154 8155 // Build an exception specification pointing back at this constructor. 8156 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon); 8157 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 8158 8159 // We don't need to use SpecialMemberIsTrivial here; triviality for default 8160 // constructors is easy to compute. 8161 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 8162 8163 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 8164 SetDeclDeleted(DefaultCon, ClassLoc); 8165 8166 // Note that we have declared this constructor. 8167 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 8168 8169 if (Scope *S = getScopeForContext(ClassDecl)) 8170 PushOnScopeChains(DefaultCon, S, false); 8171 ClassDecl->addDecl(DefaultCon); 8172 8173 return DefaultCon; 8174} 8175 8176void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 8177 CXXConstructorDecl *Constructor) { 8178 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 8179 !Constructor->doesThisDeclarationHaveABody() && 8180 !Constructor->isDeleted()) && 8181 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 8182 8183 CXXRecordDecl *ClassDecl = Constructor->getParent(); 8184 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 8185 8186 SynthesizedFunctionScope Scope(*this, Constructor); 8187 DiagnosticErrorTrap Trap(Diags); 8188 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 8189 Trap.hasErrorOccurred()) { 8190 Diag(CurrentLocation, diag::note_member_synthesized_at) 8191 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl); 8192 Constructor->setInvalidDecl(); 8193 return; 8194 } 8195 8196 SourceLocation Loc = Constructor->getLocation(); 8197 Constructor->setBody(new (Context) CompoundStmt(Loc)); 8198 8199 Constructor->markUsed(Context); 8200 MarkVTableUsed(CurrentLocation, ClassDecl); 8201 8202 if (ASTMutationListener *L = getASTMutationListener()) { 8203 L->CompletedImplicitDefinition(Constructor); 8204 } 8205} 8206 8207void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 8208 // Perform any delayed checks on exception specifications. 8209 CheckDelayedMemberExceptionSpecs(); 8210 8211 // Once all the member initializers are processed, perform checks to see if 8212 // any unintialized use is happeneing. 8213 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, 8214 D->getLocation()) 8215 == DiagnosticsEngine::Ignored) 8216 return; 8217 8218 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D); 8219 if (!RD) return; 8220 8221 // Holds fields that are uninitialized. 8222 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 8223 8224 // In the beginning, every field is uninitialized. 8225 for (DeclContext::decl_iterator I = RD->decls_begin(), E = RD->decls_end(); 8226 I != E; ++I) { 8227 if (FieldDecl *FD = dyn_cast<FieldDecl>(*I)) { 8228 UninitializedFields.insert(FD); 8229 } else if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*I)) { 8230 UninitializedFields.insert(IFD->getAnonField()); 8231 } 8232 } 8233 8234 for (DeclContext::decl_iterator I = RD->decls_begin(), E = RD->decls_end(); 8235 I != E; ++I) { 8236 FieldDecl *FD = dyn_cast<FieldDecl>(*I); 8237 if (!FD) 8238 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*I)) 8239 FD = IFD->getAnonField(); 8240 8241 if (!FD) 8242 continue; 8243 8244 Expr *InitExpr = FD->getInClassInitializer(); 8245 if (!InitExpr) { 8246 // Uninitialized reference types will give an error. 8247 // Record types with an initializer are default initialized. 8248 QualType FieldType = FD->getType(); 8249 if (FieldType->isReferenceType() || FieldType->isRecordType()) 8250 UninitializedFields.erase(FD); 8251 continue; 8252 } 8253 8254 CheckInitExprContainsUninitializedFields( 8255 *this, InitExpr, FD, UninitializedFields, 8256 UninitializedFields.count(FD)/*WarnOnSelfReference*/); 8257 8258 UninitializedFields.erase(FD); 8259 } 8260} 8261 8262namespace { 8263/// Information on inheriting constructors to declare. 8264class InheritingConstructorInfo { 8265public: 8266 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived) 8267 : SemaRef(SemaRef), Derived(Derived) { 8268 // Mark the constructors that we already have in the derived class. 8269 // 8270 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...] 8271 // unless there is a user-declared constructor with the same signature in 8272 // the class where the using-declaration appears. 8273 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived); 8274 } 8275 8276 void inheritAll(CXXRecordDecl *RD) { 8277 visitAll(RD, &InheritingConstructorInfo::inherit); 8278 } 8279 8280private: 8281 /// Information about an inheriting constructor. 8282 struct InheritingConstructor { 8283 InheritingConstructor() 8284 : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {} 8285 8286 /// If \c true, a constructor with this signature is already declared 8287 /// in the derived class. 8288 bool DeclaredInDerived; 8289 8290 /// The constructor which is inherited. 8291 const CXXConstructorDecl *BaseCtor; 8292 8293 /// The derived constructor we declared. 8294 CXXConstructorDecl *DerivedCtor; 8295 }; 8296 8297 /// Inheriting constructors with a given canonical type. There can be at 8298 /// most one such non-template constructor, and any number of templated 8299 /// constructors. 8300 struct InheritingConstructorsForType { 8301 InheritingConstructor NonTemplate; 8302 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4> 8303 Templates; 8304 8305 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) { 8306 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) { 8307 TemplateParameterList *ParamList = FTD->getTemplateParameters(); 8308 for (unsigned I = 0, N = Templates.size(); I != N; ++I) 8309 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first, 8310 false, S.TPL_TemplateMatch)) 8311 return Templates[I].second; 8312 Templates.push_back(std::make_pair(ParamList, InheritingConstructor())); 8313 return Templates.back().second; 8314 } 8315 8316 return NonTemplate; 8317 } 8318 }; 8319 8320 /// Get or create the inheriting constructor record for a constructor. 8321 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor, 8322 QualType CtorType) { 8323 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()] 8324 .getEntry(SemaRef, Ctor); 8325 } 8326 8327 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*); 8328 8329 /// Process all constructors for a class. 8330 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) { 8331 for (CXXRecordDecl::ctor_iterator CtorIt = RD->ctor_begin(), 8332 CtorE = RD->ctor_end(); 8333 CtorIt != CtorE; ++CtorIt) 8334 (this->*Callback)(*CtorIt); 8335 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> 8336 I(RD->decls_begin()), E(RD->decls_end()); 8337 I != E; ++I) { 8338 const FunctionDecl *FD = (*I)->getTemplatedDecl(); 8339 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) 8340 (this->*Callback)(CD); 8341 } 8342 } 8343 8344 /// Note that a constructor (or constructor template) was declared in Derived. 8345 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) { 8346 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true; 8347 } 8348 8349 /// Inherit a single constructor. 8350 void inherit(const CXXConstructorDecl *Ctor) { 8351 const FunctionProtoType *CtorType = 8352 Ctor->getType()->castAs<FunctionProtoType>(); 8353 ArrayRef<QualType> ArgTypes(CtorType->getArgTypes()); 8354 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo(); 8355 8356 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent()); 8357 8358 // Core issue (no number yet): the ellipsis is always discarded. 8359 if (EPI.Variadic) { 8360 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis); 8361 SemaRef.Diag(Ctor->getLocation(), 8362 diag::note_using_decl_constructor_ellipsis); 8363 EPI.Variadic = false; 8364 } 8365 8366 // Declare a constructor for each number of parameters. 8367 // 8368 // C++11 [class.inhctor]p1: 8369 // The candidate set of inherited constructors from the class X named in 8370 // the using-declaration consists of [... modulo defects ...] for each 8371 // constructor or constructor template of X, the set of constructors or 8372 // constructor templates that results from omitting any ellipsis parameter 8373 // specification and successively omitting parameters with a default 8374 // argument from the end of the parameter-type-list 8375 unsigned MinParams = minParamsToInherit(Ctor); 8376 unsigned Params = Ctor->getNumParams(); 8377 if (Params >= MinParams) { 8378 do 8379 declareCtor(UsingLoc, Ctor, 8380 SemaRef.Context.getFunctionType( 8381 Ctor->getResultType(), ArgTypes.slice(0, Params), EPI)); 8382 while (Params > MinParams && 8383 Ctor->getParamDecl(--Params)->hasDefaultArg()); 8384 } 8385 } 8386 8387 /// Find the using-declaration which specified that we should inherit the 8388 /// constructors of \p Base. 8389 SourceLocation getUsingLoc(const CXXRecordDecl *Base) { 8390 // No fancy lookup required; just look for the base constructor name 8391 // directly within the derived class. 8392 ASTContext &Context = SemaRef.Context; 8393 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 8394 Context.getCanonicalType(Context.getRecordType(Base))); 8395 DeclContext::lookup_const_result Decls = Derived->lookup(Name); 8396 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation(); 8397 } 8398 8399 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) { 8400 // C++11 [class.inhctor]p3: 8401 // [F]or each constructor template in the candidate set of inherited 8402 // constructors, a constructor template is implicitly declared 8403 if (Ctor->getDescribedFunctionTemplate()) 8404 return 0; 8405 8406 // For each non-template constructor in the candidate set of inherited 8407 // constructors other than a constructor having no parameters or a 8408 // copy/move constructor having a single parameter, a constructor is 8409 // implicitly declared [...] 8410 if (Ctor->getNumParams() == 0) 8411 return 1; 8412 if (Ctor->isCopyOrMoveConstructor()) 8413 return 2; 8414 8415 // Per discussion on core reflector, never inherit a constructor which 8416 // would become a default, copy, or move constructor of Derived either. 8417 const ParmVarDecl *PD = Ctor->getParamDecl(0); 8418 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>(); 8419 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1; 8420 } 8421 8422 /// Declare a single inheriting constructor, inheriting the specified 8423 /// constructor, with the given type. 8424 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor, 8425 QualType DerivedType) { 8426 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType); 8427 8428 // C++11 [class.inhctor]p3: 8429 // ... a constructor is implicitly declared with the same constructor 8430 // characteristics unless there is a user-declared constructor with 8431 // the same signature in the class where the using-declaration appears 8432 if (Entry.DeclaredInDerived) 8433 return; 8434 8435 // C++11 [class.inhctor]p7: 8436 // If two using-declarations declare inheriting constructors with the 8437 // same signature, the program is ill-formed 8438 if (Entry.DerivedCtor) { 8439 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) { 8440 // Only diagnose this once per constructor. 8441 if (Entry.DerivedCtor->isInvalidDecl()) 8442 return; 8443 Entry.DerivedCtor->setInvalidDecl(); 8444 8445 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict); 8446 SemaRef.Diag(BaseCtor->getLocation(), 8447 diag::note_using_decl_constructor_conflict_current_ctor); 8448 SemaRef.Diag(Entry.BaseCtor->getLocation(), 8449 diag::note_using_decl_constructor_conflict_previous_ctor); 8450 SemaRef.Diag(Entry.DerivedCtor->getLocation(), 8451 diag::note_using_decl_constructor_conflict_previous_using); 8452 } else { 8453 // Core issue (no number): if the same inheriting constructor is 8454 // produced by multiple base class constructors from the same base 8455 // class, the inheriting constructor is defined as deleted. 8456 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc); 8457 } 8458 8459 return; 8460 } 8461 8462 ASTContext &Context = SemaRef.Context; 8463 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 8464 Context.getCanonicalType(Context.getRecordType(Derived))); 8465 DeclarationNameInfo NameInfo(Name, UsingLoc); 8466 8467 TemplateParameterList *TemplateParams = 0; 8468 if (const FunctionTemplateDecl *FTD = 8469 BaseCtor->getDescribedFunctionTemplate()) { 8470 TemplateParams = FTD->getTemplateParameters(); 8471 // We're reusing template parameters from a different DeclContext. This 8472 // is questionable at best, but works out because the template depth in 8473 // both places is guaranteed to be 0. 8474 // FIXME: Rebuild the template parameters in the new context, and 8475 // transform the function type to refer to them. 8476 } 8477 8478 // Build type source info pointing at the using-declaration. This is 8479 // required by template instantiation. 8480 TypeSourceInfo *TInfo = 8481 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc); 8482 FunctionProtoTypeLoc ProtoLoc = 8483 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 8484 8485 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 8486 Context, Derived, UsingLoc, NameInfo, DerivedType, 8487 TInfo, BaseCtor->isExplicit(), /*Inline=*/true, 8488 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr()); 8489 8490 // Build an unevaluated exception specification for this constructor. 8491 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>(); 8492 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8493 EPI.ExceptionSpecType = EST_Unevaluated; 8494 EPI.ExceptionSpecDecl = DerivedCtor; 8495 DerivedCtor->setType(Context.getFunctionType(FPT->getResultType(), 8496 FPT->getArgTypes(), EPI)); 8497 8498 // Build the parameter declarations. 8499 SmallVector<ParmVarDecl *, 16> ParamDecls; 8500 for (unsigned I = 0, N = FPT->getNumArgs(); I != N; ++I) { 8501 TypeSourceInfo *TInfo = 8502 Context.getTrivialTypeSourceInfo(FPT->getArgType(I), UsingLoc); 8503 ParmVarDecl *PD = ParmVarDecl::Create( 8504 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0, 8505 FPT->getArgType(I), TInfo, SC_None, /*DefaultArg=*/0); 8506 PD->setScopeInfo(0, I); 8507 PD->setImplicit(); 8508 ParamDecls.push_back(PD); 8509 ProtoLoc.setArg(I, PD); 8510 } 8511 8512 // Set up the new constructor. 8513 DerivedCtor->setAccess(BaseCtor->getAccess()); 8514 DerivedCtor->setParams(ParamDecls); 8515 DerivedCtor->setInheritedConstructor(BaseCtor); 8516 if (BaseCtor->isDeleted()) 8517 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc); 8518 8519 // If this is a constructor template, build the template declaration. 8520 if (TemplateParams) { 8521 FunctionTemplateDecl *DerivedTemplate = 8522 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name, 8523 TemplateParams, DerivedCtor); 8524 DerivedTemplate->setAccess(BaseCtor->getAccess()); 8525 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate); 8526 Derived->addDecl(DerivedTemplate); 8527 } else { 8528 Derived->addDecl(DerivedCtor); 8529 } 8530 8531 Entry.BaseCtor = BaseCtor; 8532 Entry.DerivedCtor = DerivedCtor; 8533 } 8534 8535 Sema &SemaRef; 8536 CXXRecordDecl *Derived; 8537 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType; 8538 MapType Map; 8539}; 8540} 8541 8542void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) { 8543 // Defer declaring the inheriting constructors until the class is 8544 // instantiated. 8545 if (ClassDecl->isDependentContext()) 8546 return; 8547 8548 // Find base classes from which we might inherit constructors. 8549 SmallVector<CXXRecordDecl*, 4> InheritedBases; 8550 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(), 8551 BaseE = ClassDecl->bases_end(); 8552 BaseIt != BaseE; ++BaseIt) 8553 if (BaseIt->getInheritConstructors()) 8554 InheritedBases.push_back(BaseIt->getType()->getAsCXXRecordDecl()); 8555 8556 // Go no further if we're not inheriting any constructors. 8557 if (InheritedBases.empty()) 8558 return; 8559 8560 // Declare the inherited constructors. 8561 InheritingConstructorInfo ICI(*this, ClassDecl); 8562 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I) 8563 ICI.inheritAll(InheritedBases[I]); 8564} 8565 8566void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 8567 CXXConstructorDecl *Constructor) { 8568 CXXRecordDecl *ClassDecl = Constructor->getParent(); 8569 assert(Constructor->getInheritedConstructor() && 8570 !Constructor->doesThisDeclarationHaveABody() && 8571 !Constructor->isDeleted()); 8572 8573 SynthesizedFunctionScope Scope(*this, Constructor); 8574 DiagnosticErrorTrap Trap(Diags); 8575 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 8576 Trap.hasErrorOccurred()) { 8577 Diag(CurrentLocation, diag::note_inhctor_synthesized_at) 8578 << Context.getTagDeclType(ClassDecl); 8579 Constructor->setInvalidDecl(); 8580 return; 8581 } 8582 8583 SourceLocation Loc = Constructor->getLocation(); 8584 Constructor->setBody(new (Context) CompoundStmt(Loc)); 8585 8586 Constructor->markUsed(Context); 8587 MarkVTableUsed(CurrentLocation, ClassDecl); 8588 8589 if (ASTMutationListener *L = getASTMutationListener()) { 8590 L->CompletedImplicitDefinition(Constructor); 8591 } 8592} 8593 8594 8595Sema::ImplicitExceptionSpecification 8596Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) { 8597 CXXRecordDecl *ClassDecl = MD->getParent(); 8598 8599 // C++ [except.spec]p14: 8600 // An implicitly declared special member function (Clause 12) shall have 8601 // an exception-specification. 8602 ImplicitExceptionSpecification ExceptSpec(*this); 8603 if (ClassDecl->isInvalidDecl()) 8604 return ExceptSpec; 8605 8606 // Direct base-class destructors. 8607 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 8608 BEnd = ClassDecl->bases_end(); 8609 B != BEnd; ++B) { 8610 if (B->isVirtual()) // Handled below. 8611 continue; 8612 8613 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) 8614 ExceptSpec.CalledDecl(B->getLocStart(), 8615 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 8616 } 8617 8618 // Virtual base-class destructors. 8619 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 8620 BEnd = ClassDecl->vbases_end(); 8621 B != BEnd; ++B) { 8622 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) 8623 ExceptSpec.CalledDecl(B->getLocStart(), 8624 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 8625 } 8626 8627 // Field destructors. 8628 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 8629 FEnd = ClassDecl->field_end(); 8630 F != FEnd; ++F) { 8631 if (const RecordType *RecordTy 8632 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) 8633 ExceptSpec.CalledDecl(F->getLocation(), 8634 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl()))); 8635 } 8636 8637 return ExceptSpec; 8638} 8639 8640CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 8641 // C++ [class.dtor]p2: 8642 // If a class has no user-declared destructor, a destructor is 8643 // declared implicitly. An implicitly-declared destructor is an 8644 // inline public member of its class. 8645 assert(ClassDecl->needsImplicitDestructor()); 8646 8647 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 8648 if (DSM.isAlreadyBeingDeclared()) 8649 return 0; 8650 8651 // Create the actual destructor declaration. 8652 CanQualType ClassType 8653 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8654 SourceLocation ClassLoc = ClassDecl->getLocation(); 8655 DeclarationName Name 8656 = Context.DeclarationNames.getCXXDestructorName(ClassType); 8657 DeclarationNameInfo NameInfo(Name, ClassLoc); 8658 CXXDestructorDecl *Destructor 8659 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 8660 QualType(), 0, /*isInline=*/true, 8661 /*isImplicitlyDeclared=*/true); 8662 Destructor->setAccess(AS_public); 8663 Destructor->setDefaulted(); 8664 Destructor->setImplicit(); 8665 8666 // Build an exception specification pointing back at this destructor. 8667 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor); 8668 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 8669 8670 AddOverriddenMethods(ClassDecl, Destructor); 8671 8672 // We don't need to use SpecialMemberIsTrivial here; triviality for 8673 // destructors is easy to compute. 8674 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 8675 8676 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 8677 SetDeclDeleted(Destructor, ClassLoc); 8678 8679 // Note that we have declared this destructor. 8680 ++ASTContext::NumImplicitDestructorsDeclared; 8681 8682 // Introduce this destructor into its scope. 8683 if (Scope *S = getScopeForContext(ClassDecl)) 8684 PushOnScopeChains(Destructor, S, false); 8685 ClassDecl->addDecl(Destructor); 8686 8687 return Destructor; 8688} 8689 8690void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 8691 CXXDestructorDecl *Destructor) { 8692 assert((Destructor->isDefaulted() && 8693 !Destructor->doesThisDeclarationHaveABody() && 8694 !Destructor->isDeleted()) && 8695 "DefineImplicitDestructor - call it for implicit default dtor"); 8696 CXXRecordDecl *ClassDecl = Destructor->getParent(); 8697 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 8698 8699 if (Destructor->isInvalidDecl()) 8700 return; 8701 8702 SynthesizedFunctionScope Scope(*this, Destructor); 8703 8704 DiagnosticErrorTrap Trap(Diags); 8705 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 8706 Destructor->getParent()); 8707 8708 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) { 8709 Diag(CurrentLocation, diag::note_member_synthesized_at) 8710 << CXXDestructor << Context.getTagDeclType(ClassDecl); 8711 8712 Destructor->setInvalidDecl(); 8713 return; 8714 } 8715 8716 SourceLocation Loc = Destructor->getLocation(); 8717 Destructor->setBody(new (Context) CompoundStmt(Loc)); 8718 Destructor->markUsed(Context); 8719 MarkVTableUsed(CurrentLocation, ClassDecl); 8720 8721 if (ASTMutationListener *L = getASTMutationListener()) { 8722 L->CompletedImplicitDefinition(Destructor); 8723 } 8724} 8725 8726/// \brief Perform any semantic analysis which needs to be delayed until all 8727/// pending class member declarations have been parsed. 8728void Sema::ActOnFinishCXXMemberDecls() { 8729 // If the context is an invalid C++ class, just suppress these checks. 8730 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 8731 if (Record->isInvalidDecl()) { 8732 DelayedDefaultedMemberExceptionSpecs.clear(); 8733 DelayedDestructorExceptionSpecChecks.clear(); 8734 return; 8735 } 8736 } 8737} 8738 8739void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 8740 CXXDestructorDecl *Destructor) { 8741 assert(getLangOpts().CPlusPlus11 && 8742 "adjusting dtor exception specs was introduced in c++11"); 8743 8744 // C++11 [class.dtor]p3: 8745 // A declaration of a destructor that does not have an exception- 8746 // specification is implicitly considered to have the same exception- 8747 // specification as an implicit declaration. 8748 const FunctionProtoType *DtorType = Destructor->getType()-> 8749 getAs<FunctionProtoType>(); 8750 if (DtorType->hasExceptionSpec()) 8751 return; 8752 8753 // Replace the destructor's type, building off the existing one. Fortunately, 8754 // the only thing of interest in the destructor type is its extended info. 8755 // The return and arguments are fixed. 8756 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 8757 EPI.ExceptionSpecType = EST_Unevaluated; 8758 EPI.ExceptionSpecDecl = Destructor; 8759 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 8760 8761 // FIXME: If the destructor has a body that could throw, and the newly created 8762 // spec doesn't allow exceptions, we should emit a warning, because this 8763 // change in behavior can break conforming C++03 programs at runtime. 8764 // However, we don't have a body or an exception specification yet, so it 8765 // needs to be done somewhere else. 8766} 8767 8768namespace { 8769/// \brief An abstract base class for all helper classes used in building the 8770// copy/move operators. These classes serve as factory functions and help us 8771// avoid using the same Expr* in the AST twice. 8772class ExprBuilder { 8773 ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION; 8774 ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION; 8775 8776protected: 8777 static Expr *assertNotNull(Expr *E) { 8778 assert(E && "Expression construction must not fail."); 8779 return E; 8780 } 8781 8782public: 8783 ExprBuilder() {} 8784 virtual ~ExprBuilder() {} 8785 8786 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 8787}; 8788 8789class RefBuilder: public ExprBuilder { 8790 VarDecl *Var; 8791 QualType VarType; 8792 8793public: 8794 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE { 8795 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).take()); 8796 } 8797 8798 RefBuilder(VarDecl *Var, QualType VarType) 8799 : Var(Var), VarType(VarType) {} 8800}; 8801 8802class ThisBuilder: public ExprBuilder { 8803public: 8804 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE { 8805 return assertNotNull(S.ActOnCXXThis(Loc).takeAs<Expr>()); 8806 } 8807}; 8808 8809class CastBuilder: public ExprBuilder { 8810 const ExprBuilder &Builder; 8811 QualType Type; 8812 ExprValueKind Kind; 8813 const CXXCastPath &Path; 8814 8815public: 8816 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE { 8817 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 8818 CK_UncheckedDerivedToBase, Kind, 8819 &Path).take()); 8820 } 8821 8822 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 8823 const CXXCastPath &Path) 8824 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 8825}; 8826 8827class DerefBuilder: public ExprBuilder { 8828 const ExprBuilder &Builder; 8829 8830public: 8831 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE { 8832 return assertNotNull( 8833 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).take()); 8834 } 8835 8836 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 8837}; 8838 8839class MemberBuilder: public ExprBuilder { 8840 const ExprBuilder &Builder; 8841 QualType Type; 8842 CXXScopeSpec SS; 8843 bool IsArrow; 8844 LookupResult &MemberLookup; 8845 8846public: 8847 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE { 8848 return assertNotNull(S.BuildMemberReferenceExpr( 8849 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 0, 8850 MemberLookup, 0).take()); 8851 } 8852 8853 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 8854 LookupResult &MemberLookup) 8855 : Builder(Builder), Type(Type), IsArrow(IsArrow), 8856 MemberLookup(MemberLookup) {} 8857}; 8858 8859class MoveCastBuilder: public ExprBuilder { 8860 const ExprBuilder &Builder; 8861 8862public: 8863 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE { 8864 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 8865 } 8866 8867 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 8868}; 8869 8870class LvalueConvBuilder: public ExprBuilder { 8871 const ExprBuilder &Builder; 8872 8873public: 8874 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE { 8875 return assertNotNull( 8876 S.DefaultLvalueConversion(Builder.build(S, Loc)).take()); 8877 } 8878 8879 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 8880}; 8881 8882class SubscriptBuilder: public ExprBuilder { 8883 const ExprBuilder &Base; 8884 const ExprBuilder &Index; 8885 8886public: 8887 virtual Expr *build(Sema &S, SourceLocation Loc) const 8888 LLVM_OVERRIDE { 8889 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 8890 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).take()); 8891 } 8892 8893 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 8894 : Base(Base), Index(Index) {} 8895}; 8896 8897} // end anonymous namespace 8898 8899/// When generating a defaulted copy or move assignment operator, if a field 8900/// should be copied with __builtin_memcpy rather than via explicit assignments, 8901/// do so. This optimization only applies for arrays of scalars, and for arrays 8902/// of class type where the selected copy/move-assignment operator is trivial. 8903static StmtResult 8904buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 8905 const ExprBuilder &ToB, const ExprBuilder &FromB) { 8906 // Compute the size of the memory buffer to be copied. 8907 QualType SizeType = S.Context.getSizeType(); 8908 llvm::APInt Size(S.Context.getTypeSize(SizeType), 8909 S.Context.getTypeSizeInChars(T).getQuantity()); 8910 8911 // Take the address of the field references for "from" and "to". We 8912 // directly construct UnaryOperators here because semantic analysis 8913 // does not permit us to take the address of an xvalue. 8914 Expr *From = FromB.build(S, Loc); 8915 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 8916 S.Context.getPointerType(From->getType()), 8917 VK_RValue, OK_Ordinary, Loc); 8918 Expr *To = ToB.build(S, Loc); 8919 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 8920 S.Context.getPointerType(To->getType()), 8921 VK_RValue, OK_Ordinary, Loc); 8922 8923 const Type *E = T->getBaseElementTypeUnsafe(); 8924 bool NeedsCollectableMemCpy = 8925 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 8926 8927 // Create a reference to the __builtin_objc_memmove_collectable function 8928 StringRef MemCpyName = NeedsCollectableMemCpy ? 8929 "__builtin_objc_memmove_collectable" : 8930 "__builtin_memcpy"; 8931 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 8932 Sema::LookupOrdinaryName); 8933 S.LookupName(R, S.TUScope, true); 8934 8935 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 8936 if (!MemCpy) 8937 // Something went horribly wrong earlier, and we will have complained 8938 // about it. 8939 return StmtError(); 8940 8941 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 8942 VK_RValue, Loc, 0); 8943 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 8944 8945 Expr *CallArgs[] = { 8946 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 8947 }; 8948 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(), 8949 Loc, CallArgs, Loc); 8950 8951 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 8952 return S.Owned(Call.takeAs<Stmt>()); 8953} 8954 8955/// \brief Builds a statement that copies/moves the given entity from \p From to 8956/// \c To. 8957/// 8958/// This routine is used to copy/move the members of a class with an 8959/// implicitly-declared copy/move assignment operator. When the entities being 8960/// copied are arrays, this routine builds for loops to copy them. 8961/// 8962/// \param S The Sema object used for type-checking. 8963/// 8964/// \param Loc The location where the implicit copy/move is being generated. 8965/// 8966/// \param T The type of the expressions being copied/moved. Both expressions 8967/// must have this type. 8968/// 8969/// \param To The expression we are copying/moving to. 8970/// 8971/// \param From The expression we are copying/moving from. 8972/// 8973/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 8974/// Otherwise, it's a non-static member subobject. 8975/// 8976/// \param Copying Whether we're copying or moving. 8977/// 8978/// \param Depth Internal parameter recording the depth of the recursion. 8979/// 8980/// \returns A statement or a loop that copies the expressions, or StmtResult(0) 8981/// if a memcpy should be used instead. 8982static StmtResult 8983buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 8984 const ExprBuilder &To, const ExprBuilder &From, 8985 bool CopyingBaseSubobject, bool Copying, 8986 unsigned Depth = 0) { 8987 // C++11 [class.copy]p28: 8988 // Each subobject is assigned in the manner appropriate to its type: 8989 // 8990 // - if the subobject is of class type, as if by a call to operator= with 8991 // the subobject as the object expression and the corresponding 8992 // subobject of x as a single function argument (as if by explicit 8993 // qualification; that is, ignoring any possible virtual overriding 8994 // functions in more derived classes); 8995 // 8996 // C++03 [class.copy]p13: 8997 // - if the subobject is of class type, the copy assignment operator for 8998 // the class is used (as if by explicit qualification; that is, 8999 // ignoring any possible virtual overriding functions in more derived 9000 // classes); 9001 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 9002 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 9003 9004 // Look for operator=. 9005 DeclarationName Name 9006 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9007 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 9008 S.LookupQualifiedName(OpLookup, ClassDecl, false); 9009 9010 // Prior to C++11, filter out any result that isn't a copy/move-assignment 9011 // operator. 9012 if (!S.getLangOpts().CPlusPlus11) { 9013 LookupResult::Filter F = OpLookup.makeFilter(); 9014 while (F.hasNext()) { 9015 NamedDecl *D = F.next(); 9016 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 9017 if (Method->isCopyAssignmentOperator() || 9018 (!Copying && Method->isMoveAssignmentOperator())) 9019 continue; 9020 9021 F.erase(); 9022 } 9023 F.done(); 9024 } 9025 9026 // Suppress the protected check (C++ [class.protected]) for each of the 9027 // assignment operators we found. This strange dance is required when 9028 // we're assigning via a base classes's copy-assignment operator. To 9029 // ensure that we're getting the right base class subobject (without 9030 // ambiguities), we need to cast "this" to that subobject type; to 9031 // ensure that we don't go through the virtual call mechanism, we need 9032 // to qualify the operator= name with the base class (see below). However, 9033 // this means that if the base class has a protected copy assignment 9034 // operator, the protected member access check will fail. So, we 9035 // rewrite "protected" access to "public" access in this case, since we 9036 // know by construction that we're calling from a derived class. 9037 if (CopyingBaseSubobject) { 9038 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 9039 L != LEnd; ++L) { 9040 if (L.getAccess() == AS_protected) 9041 L.setAccess(AS_public); 9042 } 9043 } 9044 9045 // Create the nested-name-specifier that will be used to qualify the 9046 // reference to operator=; this is required to suppress the virtual 9047 // call mechanism. 9048 CXXScopeSpec SS; 9049 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 9050 SS.MakeTrivial(S.Context, 9051 NestedNameSpecifier::Create(S.Context, 0, false, 9052 CanonicalT), 9053 Loc); 9054 9055 // Create the reference to operator=. 9056 ExprResult OpEqualRef 9057 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false, 9058 SS, /*TemplateKWLoc=*/SourceLocation(), 9059 /*FirstQualifierInScope=*/0, 9060 OpLookup, 9061 /*TemplateArgs=*/0, 9062 /*SuppressQualifierCheck=*/true); 9063 if (OpEqualRef.isInvalid()) 9064 return StmtError(); 9065 9066 // Build the call to the assignment operator. 9067 9068 Expr *FromInst = From.build(S, Loc); 9069 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0, 9070 OpEqualRef.takeAs<Expr>(), 9071 Loc, FromInst, Loc); 9072 if (Call.isInvalid()) 9073 return StmtError(); 9074 9075 // If we built a call to a trivial 'operator=' while copying an array, 9076 // bail out. We'll replace the whole shebang with a memcpy. 9077 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 9078 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 9079 return StmtResult((Stmt*)0); 9080 9081 // Convert to an expression-statement, and clean up any produced 9082 // temporaries. 9083 return S.ActOnExprStmt(Call); 9084 } 9085 9086 // - if the subobject is of scalar type, the built-in assignment 9087 // operator is used. 9088 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 9089 if (!ArrayTy) { 9090 ExprResult Assignment = S.CreateBuiltinBinOp( 9091 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 9092 if (Assignment.isInvalid()) 9093 return StmtError(); 9094 return S.ActOnExprStmt(Assignment); 9095 } 9096 9097 // - if the subobject is an array, each element is assigned, in the 9098 // manner appropriate to the element type; 9099 9100 // Construct a loop over the array bounds, e.g., 9101 // 9102 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 9103 // 9104 // that will copy each of the array elements. 9105 QualType SizeType = S.Context.getSizeType(); 9106 9107 // Create the iteration variable. 9108 IdentifierInfo *IterationVarName = 0; 9109 { 9110 SmallString<8> Str; 9111 llvm::raw_svector_ostream OS(Str); 9112 OS << "__i" << Depth; 9113 IterationVarName = &S.Context.Idents.get(OS.str()); 9114 } 9115 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 9116 IterationVarName, SizeType, 9117 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 9118 SC_None); 9119 9120 // Initialize the iteration variable to zero. 9121 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 9122 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 9123 9124 // Creates a reference to the iteration variable. 9125 RefBuilder IterationVarRef(IterationVar, SizeType); 9126 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 9127 9128 // Create the DeclStmt that holds the iteration variable. 9129 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 9130 9131 // Subscript the "from" and "to" expressions with the iteration variable. 9132 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 9133 MoveCastBuilder FromIndexMove(FromIndexCopy); 9134 const ExprBuilder *FromIndex; 9135 if (Copying) 9136 FromIndex = &FromIndexCopy; 9137 else 9138 FromIndex = &FromIndexMove; 9139 9140 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 9141 9142 // Build the copy/move for an individual element of the array. 9143 StmtResult Copy = 9144 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 9145 ToIndex, *FromIndex, CopyingBaseSubobject, 9146 Copying, Depth + 1); 9147 // Bail out if copying fails or if we determined that we should use memcpy. 9148 if (Copy.isInvalid() || !Copy.get()) 9149 return Copy; 9150 9151 // Create the comparison against the array bound. 9152 llvm::APInt Upper 9153 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 9154 Expr *Comparison 9155 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc), 9156 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 9157 BO_NE, S.Context.BoolTy, 9158 VK_RValue, OK_Ordinary, Loc, false); 9159 9160 // Create the pre-increment of the iteration variable. 9161 Expr *Increment 9162 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, 9163 SizeType, VK_LValue, OK_Ordinary, Loc); 9164 9165 // Construct the loop that copies all elements of this array. 9166 return S.ActOnForStmt(Loc, Loc, InitStmt, 9167 S.MakeFullExpr(Comparison), 9168 0, S.MakeFullDiscardedValueExpr(Increment), 9169 Loc, Copy.take()); 9170} 9171 9172static StmtResult 9173buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 9174 const ExprBuilder &To, const ExprBuilder &From, 9175 bool CopyingBaseSubobject, bool Copying) { 9176 // Maybe we should use a memcpy? 9177 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 9178 T.isTriviallyCopyableType(S.Context)) 9179 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 9180 9181 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 9182 CopyingBaseSubobject, 9183 Copying, 0)); 9184 9185 // If we ended up picking a trivial assignment operator for an array of a 9186 // non-trivially-copyable class type, just emit a memcpy. 9187 if (!Result.isInvalid() && !Result.get()) 9188 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 9189 9190 return Result; 9191} 9192 9193Sema::ImplicitExceptionSpecification 9194Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) { 9195 CXXRecordDecl *ClassDecl = MD->getParent(); 9196 9197 ImplicitExceptionSpecification ExceptSpec(*this); 9198 if (ClassDecl->isInvalidDecl()) 9199 return ExceptSpec; 9200 9201 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 9202 assert(T->getNumArgs() == 1 && "not a copy assignment op"); 9203 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers(); 9204 9205 // C++ [except.spec]p14: 9206 // An implicitly declared special member function (Clause 12) shall have an 9207 // exception-specification. [...] 9208 9209 // It is unspecified whether or not an implicit copy assignment operator 9210 // attempts to deduplicate calls to assignment operators of virtual bases are 9211 // made. As such, this exception specification is effectively unspecified. 9212 // Based on a similar decision made for constness in C++0x, we're erring on 9213 // the side of assuming such calls to be made regardless of whether they 9214 // actually happen. 9215 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 9216 BaseEnd = ClassDecl->bases_end(); 9217 Base != BaseEnd; ++Base) { 9218 if (Base->isVirtual()) 9219 continue; 9220 9221 CXXRecordDecl *BaseClassDecl 9222 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9223 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 9224 ArgQuals, false, 0)) 9225 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign); 9226 } 9227 9228 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 9229 BaseEnd = ClassDecl->vbases_end(); 9230 Base != BaseEnd; ++Base) { 9231 CXXRecordDecl *BaseClassDecl 9232 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9233 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 9234 ArgQuals, false, 0)) 9235 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign); 9236 } 9237 9238 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 9239 FieldEnd = ClassDecl->field_end(); 9240 Field != FieldEnd; 9241 ++Field) { 9242 QualType FieldType = Context.getBaseElementType(Field->getType()); 9243 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 9244 if (CXXMethodDecl *CopyAssign = 9245 LookupCopyingAssignment(FieldClassDecl, 9246 ArgQuals | FieldType.getCVRQualifiers(), 9247 false, 0)) 9248 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign); 9249 } 9250 } 9251 9252 return ExceptSpec; 9253} 9254 9255CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 9256 // Note: The following rules are largely analoguous to the copy 9257 // constructor rules. Note that virtual bases are not taken into account 9258 // for determining the argument type of the operator. Note also that 9259 // operators taking an object instead of a reference are allowed. 9260 assert(ClassDecl->needsImplicitCopyAssignment()); 9261 9262 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 9263 if (DSM.isAlreadyBeingDeclared()) 9264 return 0; 9265 9266 QualType ArgType = Context.getTypeDeclType(ClassDecl); 9267 QualType RetType = Context.getLValueReferenceType(ArgType); 9268 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 9269 if (Const) 9270 ArgType = ArgType.withConst(); 9271 ArgType = Context.getLValueReferenceType(ArgType); 9272 9273 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9274 CXXCopyAssignment, 9275 Const); 9276 9277 // An implicitly-declared copy assignment operator is an inline public 9278 // member of its class. 9279 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9280 SourceLocation ClassLoc = ClassDecl->getLocation(); 9281 DeclarationNameInfo NameInfo(Name, ClassLoc); 9282 CXXMethodDecl *CopyAssignment = 9283 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 9284 /*TInfo=*/ 0, /*StorageClass=*/ SC_None, 9285 /*isInline=*/ true, Constexpr, SourceLocation()); 9286 CopyAssignment->setAccess(AS_public); 9287 CopyAssignment->setDefaulted(); 9288 CopyAssignment->setImplicit(); 9289 9290 // Build an exception specification pointing back at this member. 9291 FunctionProtoType::ExtProtoInfo EPI = 9292 getImplicitMethodEPI(*this, CopyAssignment); 9293 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 9294 9295 // Add the parameter to the operator. 9296 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 9297 ClassLoc, ClassLoc, /*Id=*/0, 9298 ArgType, /*TInfo=*/0, 9299 SC_None, 0); 9300 CopyAssignment->setParams(FromParam); 9301 9302 AddOverriddenMethods(ClassDecl, CopyAssignment); 9303 9304 CopyAssignment->setTrivial( 9305 ClassDecl->needsOverloadResolutionForCopyAssignment() 9306 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 9307 : ClassDecl->hasTrivialCopyAssignment()); 9308 9309 // C++11 [class.copy]p19: 9310 // .... If the class definition does not explicitly declare a copy 9311 // assignment operator, there is no user-declared move constructor, and 9312 // there is no user-declared move assignment operator, a copy assignment 9313 // operator is implicitly declared as defaulted. 9314 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 9315 SetDeclDeleted(CopyAssignment, ClassLoc); 9316 9317 // Note that we have added this copy-assignment operator. 9318 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 9319 9320 if (Scope *S = getScopeForContext(ClassDecl)) 9321 PushOnScopeChains(CopyAssignment, S, false); 9322 ClassDecl->addDecl(CopyAssignment); 9323 9324 return CopyAssignment; 9325} 9326 9327/// Diagnose an implicit copy operation for a class which is odr-used, but 9328/// which is deprecated because the class has a user-declared copy constructor, 9329/// copy assignment operator, or destructor. 9330static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp, 9331 SourceLocation UseLoc) { 9332 assert(CopyOp->isImplicit()); 9333 9334 CXXRecordDecl *RD = CopyOp->getParent(); 9335 CXXMethodDecl *UserDeclaredOperation = 0; 9336 9337 // In Microsoft mode, assignment operations don't affect constructors and 9338 // vice versa. 9339 if (RD->hasUserDeclaredDestructor()) { 9340 UserDeclaredOperation = RD->getDestructor(); 9341 } else if (!isa<CXXConstructorDecl>(CopyOp) && 9342 RD->hasUserDeclaredCopyConstructor() && 9343 !S.getLangOpts().MicrosoftMode) { 9344 // Find any user-declared copy constructor. 9345 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(), 9346 E = RD->ctor_end(); I != E; ++I) { 9347 if (I->isCopyConstructor()) { 9348 UserDeclaredOperation = *I; 9349 break; 9350 } 9351 } 9352 assert(UserDeclaredOperation); 9353 } else if (isa<CXXConstructorDecl>(CopyOp) && 9354 RD->hasUserDeclaredCopyAssignment() && 9355 !S.getLangOpts().MicrosoftMode) { 9356 // Find any user-declared move assignment operator. 9357 for (CXXRecordDecl::method_iterator I = RD->method_begin(), 9358 E = RD->method_end(); I != E; ++I) { 9359 if (I->isCopyAssignmentOperator()) { 9360 UserDeclaredOperation = *I; 9361 break; 9362 } 9363 } 9364 assert(UserDeclaredOperation); 9365 } 9366 9367 if (UserDeclaredOperation) { 9368 S.Diag(UserDeclaredOperation->getLocation(), 9369 diag::warn_deprecated_copy_operation) 9370 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp) 9371 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation); 9372 S.Diag(UseLoc, diag::note_member_synthesized_at) 9373 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor 9374 : Sema::CXXCopyAssignment) 9375 << RD; 9376 } 9377} 9378 9379void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 9380 CXXMethodDecl *CopyAssignOperator) { 9381 assert((CopyAssignOperator->isDefaulted() && 9382 CopyAssignOperator->isOverloadedOperator() && 9383 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 9384 !CopyAssignOperator->doesThisDeclarationHaveABody() && 9385 !CopyAssignOperator->isDeleted()) && 9386 "DefineImplicitCopyAssignment called for wrong function"); 9387 9388 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 9389 9390 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) { 9391 CopyAssignOperator->setInvalidDecl(); 9392 return; 9393 } 9394 9395 // C++11 [class.copy]p18: 9396 // The [definition of an implicitly declared copy assignment operator] is 9397 // deprecated if the class has a user-declared copy constructor or a 9398 // user-declared destructor. 9399 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 9400 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation); 9401 9402 CopyAssignOperator->markUsed(Context); 9403 9404 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 9405 DiagnosticErrorTrap Trap(Diags); 9406 9407 // C++0x [class.copy]p30: 9408 // The implicitly-defined or explicitly-defaulted copy assignment operator 9409 // for a non-union class X performs memberwise copy assignment of its 9410 // subobjects. The direct base classes of X are assigned first, in the 9411 // order of their declaration in the base-specifier-list, and then the 9412 // immediate non-static data members of X are assigned, in the order in 9413 // which they were declared in the class definition. 9414 9415 // The statements that form the synthesized function body. 9416 SmallVector<Stmt*, 8> Statements; 9417 9418 // The parameter for the "other" object, which we are copying from. 9419 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 9420 Qualifiers OtherQuals = Other->getType().getQualifiers(); 9421 QualType OtherRefType = Other->getType(); 9422 if (const LValueReferenceType *OtherRef 9423 = OtherRefType->getAs<LValueReferenceType>()) { 9424 OtherRefType = OtherRef->getPointeeType(); 9425 OtherQuals = OtherRefType.getQualifiers(); 9426 } 9427 9428 // Our location for everything implicitly-generated. 9429 SourceLocation Loc = CopyAssignOperator->getLocation(); 9430 9431 // Builds a DeclRefExpr for the "other" object. 9432 RefBuilder OtherRef(Other, OtherRefType); 9433 9434 // Builds the "this" pointer. 9435 ThisBuilder This; 9436 9437 // Assign base classes. 9438 bool Invalid = false; 9439 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 9440 E = ClassDecl->bases_end(); Base != E; ++Base) { 9441 // Form the assignment: 9442 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 9443 QualType BaseType = Base->getType().getUnqualifiedType(); 9444 if (!BaseType->isRecordType()) { 9445 Invalid = true; 9446 continue; 9447 } 9448 9449 CXXCastPath BasePath; 9450 BasePath.push_back(Base); 9451 9452 // Construct the "from" expression, which is an implicit cast to the 9453 // appropriately-qualified base type. 9454 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 9455 VK_LValue, BasePath); 9456 9457 // Dereference "this". 9458 DerefBuilder DerefThis(This); 9459 CastBuilder To(DerefThis, 9460 Context.getCVRQualifiedType( 9461 BaseType, CopyAssignOperator->getTypeQualifiers()), 9462 VK_LValue, BasePath); 9463 9464 // Build the copy. 9465 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 9466 To, From, 9467 /*CopyingBaseSubobject=*/true, 9468 /*Copying=*/true); 9469 if (Copy.isInvalid()) { 9470 Diag(CurrentLocation, diag::note_member_synthesized_at) 9471 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9472 CopyAssignOperator->setInvalidDecl(); 9473 return; 9474 } 9475 9476 // Success! Record the copy. 9477 Statements.push_back(Copy.takeAs<Expr>()); 9478 } 9479 9480 // Assign non-static members. 9481 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 9482 FieldEnd = ClassDecl->field_end(); 9483 Field != FieldEnd; ++Field) { 9484 if (Field->isUnnamedBitfield()) 9485 continue; 9486 9487 if (Field->isInvalidDecl()) { 9488 Invalid = true; 9489 continue; 9490 } 9491 9492 // Check for members of reference type; we can't copy those. 9493 if (Field->getType()->isReferenceType()) { 9494 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9495 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 9496 Diag(Field->getLocation(), diag::note_declared_at); 9497 Diag(CurrentLocation, diag::note_member_synthesized_at) 9498 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9499 Invalid = true; 9500 continue; 9501 } 9502 9503 // Check for members of const-qualified, non-class type. 9504 QualType BaseType = Context.getBaseElementType(Field->getType()); 9505 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 9506 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9507 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 9508 Diag(Field->getLocation(), diag::note_declared_at); 9509 Diag(CurrentLocation, diag::note_member_synthesized_at) 9510 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9511 Invalid = true; 9512 continue; 9513 } 9514 9515 // Suppress assigning zero-width bitfields. 9516 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 9517 continue; 9518 9519 QualType FieldType = Field->getType().getNonReferenceType(); 9520 if (FieldType->isIncompleteArrayType()) { 9521 assert(ClassDecl->hasFlexibleArrayMember() && 9522 "Incomplete array type is not valid"); 9523 continue; 9524 } 9525 9526 // Build references to the field in the object we're copying from and to. 9527 CXXScopeSpec SS; // Intentionally empty 9528 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 9529 LookupMemberName); 9530 MemberLookup.addDecl(*Field); 9531 MemberLookup.resolveKind(); 9532 9533 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 9534 9535 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 9536 9537 // Build the copy of this field. 9538 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 9539 To, From, 9540 /*CopyingBaseSubobject=*/false, 9541 /*Copying=*/true); 9542 if (Copy.isInvalid()) { 9543 Diag(CurrentLocation, diag::note_member_synthesized_at) 9544 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9545 CopyAssignOperator->setInvalidDecl(); 9546 return; 9547 } 9548 9549 // Success! Record the copy. 9550 Statements.push_back(Copy.takeAs<Stmt>()); 9551 } 9552 9553 if (!Invalid) { 9554 // Add a "return *this;" 9555 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 9556 9557 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get()); 9558 if (Return.isInvalid()) 9559 Invalid = true; 9560 else { 9561 Statements.push_back(Return.takeAs<Stmt>()); 9562 9563 if (Trap.hasErrorOccurred()) { 9564 Diag(CurrentLocation, diag::note_member_synthesized_at) 9565 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9566 Invalid = true; 9567 } 9568 } 9569 } 9570 9571 if (Invalid) { 9572 CopyAssignOperator->setInvalidDecl(); 9573 return; 9574 } 9575 9576 StmtResult Body; 9577 { 9578 CompoundScopeRAII CompoundScope(*this); 9579 Body = ActOnCompoundStmt(Loc, Loc, Statements, 9580 /*isStmtExpr=*/false); 9581 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 9582 } 9583 CopyAssignOperator->setBody(Body.takeAs<Stmt>()); 9584 9585 if (ASTMutationListener *L = getASTMutationListener()) { 9586 L->CompletedImplicitDefinition(CopyAssignOperator); 9587 } 9588} 9589 9590Sema::ImplicitExceptionSpecification 9591Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) { 9592 CXXRecordDecl *ClassDecl = MD->getParent(); 9593 9594 ImplicitExceptionSpecification ExceptSpec(*this); 9595 if (ClassDecl->isInvalidDecl()) 9596 return ExceptSpec; 9597 9598 // C++0x [except.spec]p14: 9599 // An implicitly declared special member function (Clause 12) shall have an 9600 // exception-specification. [...] 9601 9602 // It is unspecified whether or not an implicit move assignment operator 9603 // attempts to deduplicate calls to assignment operators of virtual bases are 9604 // made. As such, this exception specification is effectively unspecified. 9605 // Based on a similar decision made for constness in C++0x, we're erring on 9606 // the side of assuming such calls to be made regardless of whether they 9607 // actually happen. 9608 // Note that a move constructor is not implicitly declared when there are 9609 // virtual bases, but it can still be user-declared and explicitly defaulted. 9610 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 9611 BaseEnd = ClassDecl->bases_end(); 9612 Base != BaseEnd; ++Base) { 9613 if (Base->isVirtual()) 9614 continue; 9615 9616 CXXRecordDecl *BaseClassDecl 9617 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9618 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 9619 0, false, 0)) 9620 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign); 9621 } 9622 9623 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 9624 BaseEnd = ClassDecl->vbases_end(); 9625 Base != BaseEnd; ++Base) { 9626 CXXRecordDecl *BaseClassDecl 9627 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9628 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 9629 0, false, 0)) 9630 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign); 9631 } 9632 9633 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 9634 FieldEnd = ClassDecl->field_end(); 9635 Field != FieldEnd; 9636 ++Field) { 9637 QualType FieldType = Context.getBaseElementType(Field->getType()); 9638 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 9639 if (CXXMethodDecl *MoveAssign = 9640 LookupMovingAssignment(FieldClassDecl, 9641 FieldType.getCVRQualifiers(), 9642 false, 0)) 9643 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign); 9644 } 9645 } 9646 9647 return ExceptSpec; 9648} 9649 9650/// Determine whether the class type has any direct or indirect virtual base 9651/// classes which have a non-trivial move assignment operator. 9652static bool 9653hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) { 9654 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 9655 BaseEnd = ClassDecl->vbases_end(); 9656 Base != BaseEnd; ++Base) { 9657 CXXRecordDecl *BaseClass = 9658 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9659 9660 // Try to declare the move assignment. If it would be deleted, then the 9661 // class does not have a non-trivial move assignment. 9662 if (BaseClass->needsImplicitMoveAssignment()) 9663 S.DeclareImplicitMoveAssignment(BaseClass); 9664 9665 if (BaseClass->hasNonTrivialMoveAssignment()) 9666 return true; 9667 } 9668 9669 return false; 9670} 9671 9672/// Determine whether the given type either has a move constructor or is 9673/// trivially copyable. 9674static bool 9675hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) { 9676 Type = S.Context.getBaseElementType(Type); 9677 9678 // FIXME: Technically, non-trivially-copyable non-class types, such as 9679 // reference types, are supposed to return false here, but that appears 9680 // to be a standard defect. 9681 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl(); 9682 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl()) 9683 return true; 9684 9685 if (Type.isTriviallyCopyableType(S.Context)) 9686 return true; 9687 9688 if (IsConstructor) { 9689 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to 9690 // give the right answer. 9691 if (ClassDecl->needsImplicitMoveConstructor()) 9692 S.DeclareImplicitMoveConstructor(ClassDecl); 9693 return ClassDecl->hasMoveConstructor(); 9694 } 9695 9696 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to 9697 // give the right answer. 9698 if (ClassDecl->needsImplicitMoveAssignment()) 9699 S.DeclareImplicitMoveAssignment(ClassDecl); 9700 return ClassDecl->hasMoveAssignment(); 9701} 9702 9703/// Determine whether all non-static data members and direct or virtual bases 9704/// of class \p ClassDecl have either a move operation, or are trivially 9705/// copyable. 9706static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl, 9707 bool IsConstructor) { 9708 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 9709 BaseEnd = ClassDecl->bases_end(); 9710 Base != BaseEnd; ++Base) { 9711 if (Base->isVirtual()) 9712 continue; 9713 9714 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor)) 9715 return false; 9716 } 9717 9718 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 9719 BaseEnd = ClassDecl->vbases_end(); 9720 Base != BaseEnd; ++Base) { 9721 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor)) 9722 return false; 9723 } 9724 9725 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 9726 FieldEnd = ClassDecl->field_end(); 9727 Field != FieldEnd; ++Field) { 9728 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor)) 9729 return false; 9730 } 9731 9732 return true; 9733} 9734 9735CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 9736 // C++11 [class.copy]p20: 9737 // If the definition of a class X does not explicitly declare a move 9738 // assignment operator, one will be implicitly declared as defaulted 9739 // if and only if: 9740 // 9741 // - [first 4 bullets] 9742 assert(ClassDecl->needsImplicitMoveAssignment()); 9743 9744 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 9745 if (DSM.isAlreadyBeingDeclared()) 9746 return 0; 9747 9748 // [Checked after we build the declaration] 9749 // - the move assignment operator would not be implicitly defined as 9750 // deleted, 9751 9752 // [DR1402]: 9753 // - X has no direct or indirect virtual base class with a non-trivial 9754 // move assignment operator, and 9755 // - each of X's non-static data members and direct or virtual base classes 9756 // has a type that either has a move assignment operator or is trivially 9757 // copyable. 9758 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) || 9759 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) { 9760 ClassDecl->setFailedImplicitMoveAssignment(); 9761 return 0; 9762 } 9763 9764 // Note: The following rules are largely analoguous to the move 9765 // constructor rules. 9766 9767 QualType ArgType = Context.getTypeDeclType(ClassDecl); 9768 QualType RetType = Context.getLValueReferenceType(ArgType); 9769 ArgType = Context.getRValueReferenceType(ArgType); 9770 9771 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9772 CXXMoveAssignment, 9773 false); 9774 9775 // An implicitly-declared move assignment operator is an inline public 9776 // member of its class. 9777 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9778 SourceLocation ClassLoc = ClassDecl->getLocation(); 9779 DeclarationNameInfo NameInfo(Name, ClassLoc); 9780 CXXMethodDecl *MoveAssignment = 9781 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 9782 /*TInfo=*/0, /*StorageClass=*/SC_None, 9783 /*isInline=*/true, Constexpr, SourceLocation()); 9784 MoveAssignment->setAccess(AS_public); 9785 MoveAssignment->setDefaulted(); 9786 MoveAssignment->setImplicit(); 9787 9788 // Build an exception specification pointing back at this member. 9789 FunctionProtoType::ExtProtoInfo EPI = 9790 getImplicitMethodEPI(*this, MoveAssignment); 9791 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 9792 9793 // Add the parameter to the operator. 9794 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 9795 ClassLoc, ClassLoc, /*Id=*/0, 9796 ArgType, /*TInfo=*/0, 9797 SC_None, 0); 9798 MoveAssignment->setParams(FromParam); 9799 9800 AddOverriddenMethods(ClassDecl, MoveAssignment); 9801 9802 MoveAssignment->setTrivial( 9803 ClassDecl->needsOverloadResolutionForMoveAssignment() 9804 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 9805 : ClassDecl->hasTrivialMoveAssignment()); 9806 9807 // C++0x [class.copy]p9: 9808 // If the definition of a class X does not explicitly declare a move 9809 // assignment operator, one will be implicitly declared as defaulted if and 9810 // only if: 9811 // [...] 9812 // - the move assignment operator would not be implicitly defined as 9813 // deleted. 9814 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 9815 // Cache this result so that we don't try to generate this over and over 9816 // on every lookup, leaking memory and wasting time. 9817 ClassDecl->setFailedImplicitMoveAssignment(); 9818 return 0; 9819 } 9820 9821 // Note that we have added this copy-assignment operator. 9822 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 9823 9824 if (Scope *S = getScopeForContext(ClassDecl)) 9825 PushOnScopeChains(MoveAssignment, S, false); 9826 ClassDecl->addDecl(MoveAssignment); 9827 9828 return MoveAssignment; 9829} 9830 9831void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 9832 CXXMethodDecl *MoveAssignOperator) { 9833 assert((MoveAssignOperator->isDefaulted() && 9834 MoveAssignOperator->isOverloadedOperator() && 9835 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 9836 !MoveAssignOperator->doesThisDeclarationHaveABody() && 9837 !MoveAssignOperator->isDeleted()) && 9838 "DefineImplicitMoveAssignment called for wrong function"); 9839 9840 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 9841 9842 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) { 9843 MoveAssignOperator->setInvalidDecl(); 9844 return; 9845 } 9846 9847 MoveAssignOperator->markUsed(Context); 9848 9849 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 9850 DiagnosticErrorTrap Trap(Diags); 9851 9852 // C++0x [class.copy]p28: 9853 // The implicitly-defined or move assignment operator for a non-union class 9854 // X performs memberwise move assignment of its subobjects. The direct base 9855 // classes of X are assigned first, in the order of their declaration in the 9856 // base-specifier-list, and then the immediate non-static data members of X 9857 // are assigned, in the order in which they were declared in the class 9858 // definition. 9859 9860 // The statements that form the synthesized function body. 9861 SmallVector<Stmt*, 8> Statements; 9862 9863 // The parameter for the "other" object, which we are move from. 9864 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 9865 QualType OtherRefType = Other->getType()-> 9866 getAs<RValueReferenceType>()->getPointeeType(); 9867 assert(!OtherRefType.getQualifiers() && 9868 "Bad argument type of defaulted move assignment"); 9869 9870 // Our location for everything implicitly-generated. 9871 SourceLocation Loc = MoveAssignOperator->getLocation(); 9872 9873 // Builds a reference to the "other" object. 9874 RefBuilder OtherRef(Other, OtherRefType); 9875 // Cast to rvalue. 9876 MoveCastBuilder MoveOther(OtherRef); 9877 9878 // Builds the "this" pointer. 9879 ThisBuilder This; 9880 9881 // Assign base classes. 9882 bool Invalid = false; 9883 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 9884 E = ClassDecl->bases_end(); Base != E; ++Base) { 9885 // Form the assignment: 9886 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 9887 QualType BaseType = Base->getType().getUnqualifiedType(); 9888 if (!BaseType->isRecordType()) { 9889 Invalid = true; 9890 continue; 9891 } 9892 9893 CXXCastPath BasePath; 9894 BasePath.push_back(Base); 9895 9896 // Construct the "from" expression, which is an implicit cast to the 9897 // appropriately-qualified base type. 9898 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 9899 9900 // Dereference "this". 9901 DerefBuilder DerefThis(This); 9902 9903 // Implicitly cast "this" to the appropriately-qualified base type. 9904 CastBuilder To(DerefThis, 9905 Context.getCVRQualifiedType( 9906 BaseType, MoveAssignOperator->getTypeQualifiers()), 9907 VK_LValue, BasePath); 9908 9909 // Build the move. 9910 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 9911 To, From, 9912 /*CopyingBaseSubobject=*/true, 9913 /*Copying=*/false); 9914 if (Move.isInvalid()) { 9915 Diag(CurrentLocation, diag::note_member_synthesized_at) 9916 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9917 MoveAssignOperator->setInvalidDecl(); 9918 return; 9919 } 9920 9921 // Success! Record the move. 9922 Statements.push_back(Move.takeAs<Expr>()); 9923 } 9924 9925 // Assign non-static members. 9926 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 9927 FieldEnd = ClassDecl->field_end(); 9928 Field != FieldEnd; ++Field) { 9929 if (Field->isUnnamedBitfield()) 9930 continue; 9931 9932 if (Field->isInvalidDecl()) { 9933 Invalid = true; 9934 continue; 9935 } 9936 9937 // Check for members of reference type; we can't move those. 9938 if (Field->getType()->isReferenceType()) { 9939 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9940 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 9941 Diag(Field->getLocation(), diag::note_declared_at); 9942 Diag(CurrentLocation, diag::note_member_synthesized_at) 9943 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9944 Invalid = true; 9945 continue; 9946 } 9947 9948 // Check for members of const-qualified, non-class type. 9949 QualType BaseType = Context.getBaseElementType(Field->getType()); 9950 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 9951 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9952 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 9953 Diag(Field->getLocation(), diag::note_declared_at); 9954 Diag(CurrentLocation, diag::note_member_synthesized_at) 9955 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9956 Invalid = true; 9957 continue; 9958 } 9959 9960 // Suppress assigning zero-width bitfields. 9961 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 9962 continue; 9963 9964 QualType FieldType = Field->getType().getNonReferenceType(); 9965 if (FieldType->isIncompleteArrayType()) { 9966 assert(ClassDecl->hasFlexibleArrayMember() && 9967 "Incomplete array type is not valid"); 9968 continue; 9969 } 9970 9971 // Build references to the field in the object we're copying from and to. 9972 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 9973 LookupMemberName); 9974 MemberLookup.addDecl(*Field); 9975 MemberLookup.resolveKind(); 9976 MemberBuilder From(MoveOther, OtherRefType, 9977 /*IsArrow=*/false, MemberLookup); 9978 MemberBuilder To(This, getCurrentThisType(), 9979 /*IsArrow=*/true, MemberLookup); 9980 9981 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 9982 "Member reference with rvalue base must be rvalue except for reference " 9983 "members, which aren't allowed for move assignment."); 9984 9985 // Build the move of this field. 9986 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 9987 To, From, 9988 /*CopyingBaseSubobject=*/false, 9989 /*Copying=*/false); 9990 if (Move.isInvalid()) { 9991 Diag(CurrentLocation, diag::note_member_synthesized_at) 9992 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9993 MoveAssignOperator->setInvalidDecl(); 9994 return; 9995 } 9996 9997 // Success! Record the copy. 9998 Statements.push_back(Move.takeAs<Stmt>()); 9999 } 10000 10001 if (!Invalid) { 10002 // Add a "return *this;" 10003 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 10004 10005 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get()); 10006 if (Return.isInvalid()) 10007 Invalid = true; 10008 else { 10009 Statements.push_back(Return.takeAs<Stmt>()); 10010 10011 if (Trap.hasErrorOccurred()) { 10012 Diag(CurrentLocation, diag::note_member_synthesized_at) 10013 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10014 Invalid = true; 10015 } 10016 } 10017 } 10018 10019 if (Invalid) { 10020 MoveAssignOperator->setInvalidDecl(); 10021 return; 10022 } 10023 10024 StmtResult Body; 10025 { 10026 CompoundScopeRAII CompoundScope(*this); 10027 Body = ActOnCompoundStmt(Loc, Loc, Statements, 10028 /*isStmtExpr=*/false); 10029 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 10030 } 10031 MoveAssignOperator->setBody(Body.takeAs<Stmt>()); 10032 10033 if (ASTMutationListener *L = getASTMutationListener()) { 10034 L->CompletedImplicitDefinition(MoveAssignOperator); 10035 } 10036} 10037 10038Sema::ImplicitExceptionSpecification 10039Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) { 10040 CXXRecordDecl *ClassDecl = MD->getParent(); 10041 10042 ImplicitExceptionSpecification ExceptSpec(*this); 10043 if (ClassDecl->isInvalidDecl()) 10044 return ExceptSpec; 10045 10046 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 10047 assert(T->getNumArgs() >= 1 && "not a copy ctor"); 10048 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers(); 10049 10050 // C++ [except.spec]p14: 10051 // An implicitly declared special member function (Clause 12) shall have an 10052 // exception-specification. [...] 10053 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 10054 BaseEnd = ClassDecl->bases_end(); 10055 Base != BaseEnd; 10056 ++Base) { 10057 // Virtual bases are handled below. 10058 if (Base->isVirtual()) 10059 continue; 10060 10061 CXXRecordDecl *BaseClassDecl 10062 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 10063 if (CXXConstructorDecl *CopyConstructor = 10064 LookupCopyingConstructor(BaseClassDecl, Quals)) 10065 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor); 10066 } 10067 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 10068 BaseEnd = ClassDecl->vbases_end(); 10069 Base != BaseEnd; 10070 ++Base) { 10071 CXXRecordDecl *BaseClassDecl 10072 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 10073 if (CXXConstructorDecl *CopyConstructor = 10074 LookupCopyingConstructor(BaseClassDecl, Quals)) 10075 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor); 10076 } 10077 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 10078 FieldEnd = ClassDecl->field_end(); 10079 Field != FieldEnd; 10080 ++Field) { 10081 QualType FieldType = Context.getBaseElementType(Field->getType()); 10082 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 10083 if (CXXConstructorDecl *CopyConstructor = 10084 LookupCopyingConstructor(FieldClassDecl, 10085 Quals | FieldType.getCVRQualifiers())) 10086 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor); 10087 } 10088 } 10089 10090 return ExceptSpec; 10091} 10092 10093CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 10094 CXXRecordDecl *ClassDecl) { 10095 // C++ [class.copy]p4: 10096 // If the class definition does not explicitly declare a copy 10097 // constructor, one is declared implicitly. 10098 assert(ClassDecl->needsImplicitCopyConstructor()); 10099 10100 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 10101 if (DSM.isAlreadyBeingDeclared()) 10102 return 0; 10103 10104 QualType ClassType = Context.getTypeDeclType(ClassDecl); 10105 QualType ArgType = ClassType; 10106 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 10107 if (Const) 10108 ArgType = ArgType.withConst(); 10109 ArgType = Context.getLValueReferenceType(ArgType); 10110 10111 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10112 CXXCopyConstructor, 10113 Const); 10114 10115 DeclarationName Name 10116 = Context.DeclarationNames.getCXXConstructorName( 10117 Context.getCanonicalType(ClassType)); 10118 SourceLocation ClassLoc = ClassDecl->getLocation(); 10119 DeclarationNameInfo NameInfo(Name, ClassLoc); 10120 10121 // An implicitly-declared copy constructor is an inline public 10122 // member of its class. 10123 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 10124 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0, 10125 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 10126 Constexpr); 10127 CopyConstructor->setAccess(AS_public); 10128 CopyConstructor->setDefaulted(); 10129 10130 // Build an exception specification pointing back at this member. 10131 FunctionProtoType::ExtProtoInfo EPI = 10132 getImplicitMethodEPI(*this, CopyConstructor); 10133 CopyConstructor->setType( 10134 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 10135 10136 // Add the parameter to the constructor. 10137 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 10138 ClassLoc, ClassLoc, 10139 /*IdentifierInfo=*/0, 10140 ArgType, /*TInfo=*/0, 10141 SC_None, 0); 10142 CopyConstructor->setParams(FromParam); 10143 10144 CopyConstructor->setTrivial( 10145 ClassDecl->needsOverloadResolutionForCopyConstructor() 10146 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 10147 : ClassDecl->hasTrivialCopyConstructor()); 10148 10149 // C++11 [class.copy]p8: 10150 // ... If the class definition does not explicitly declare a copy 10151 // constructor, there is no user-declared move constructor, and there is no 10152 // user-declared move assignment operator, a copy constructor is implicitly 10153 // declared as defaulted. 10154 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) 10155 SetDeclDeleted(CopyConstructor, ClassLoc); 10156 10157 // Note that we have declared this constructor. 10158 ++ASTContext::NumImplicitCopyConstructorsDeclared; 10159 10160 if (Scope *S = getScopeForContext(ClassDecl)) 10161 PushOnScopeChains(CopyConstructor, S, false); 10162 ClassDecl->addDecl(CopyConstructor); 10163 10164 return CopyConstructor; 10165} 10166 10167void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 10168 CXXConstructorDecl *CopyConstructor) { 10169 assert((CopyConstructor->isDefaulted() && 10170 CopyConstructor->isCopyConstructor() && 10171 !CopyConstructor->doesThisDeclarationHaveABody() && 10172 !CopyConstructor->isDeleted()) && 10173 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 10174 10175 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 10176 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 10177 10178 // C++11 [class.copy]p7: 10179 // The [definition of an implicitly declared copy constructor] is 10180 // deprecated if the class has a user-declared copy assignment operator 10181 // or a user-declared destructor. 10182 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 10183 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation); 10184 10185 SynthesizedFunctionScope Scope(*this, CopyConstructor); 10186 DiagnosticErrorTrap Trap(Diags); 10187 10188 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) || 10189 Trap.hasErrorOccurred()) { 10190 Diag(CurrentLocation, diag::note_member_synthesized_at) 10191 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl); 10192 CopyConstructor->setInvalidDecl(); 10193 } else { 10194 Sema::CompoundScopeRAII CompoundScope(*this); 10195 CopyConstructor->setBody(ActOnCompoundStmt( 10196 CopyConstructor->getLocation(), CopyConstructor->getLocation(), None, 10197 /*isStmtExpr=*/ false).takeAs<Stmt>()); 10198 } 10199 10200 CopyConstructor->markUsed(Context); 10201 if (ASTMutationListener *L = getASTMutationListener()) { 10202 L->CompletedImplicitDefinition(CopyConstructor); 10203 } 10204} 10205 10206Sema::ImplicitExceptionSpecification 10207Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) { 10208 CXXRecordDecl *ClassDecl = MD->getParent(); 10209 10210 // C++ [except.spec]p14: 10211 // An implicitly declared special member function (Clause 12) shall have an 10212 // exception-specification. [...] 10213 ImplicitExceptionSpecification ExceptSpec(*this); 10214 if (ClassDecl->isInvalidDecl()) 10215 return ExceptSpec; 10216 10217 // Direct base-class constructors. 10218 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 10219 BEnd = ClassDecl->bases_end(); 10220 B != BEnd; ++B) { 10221 if (B->isVirtual()) // Handled below. 10222 continue; 10223 10224 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 10225 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 10226 CXXConstructorDecl *Constructor = 10227 LookupMovingConstructor(BaseClassDecl, 0); 10228 // If this is a deleted function, add it anyway. This might be conformant 10229 // with the standard. This might not. I'm not sure. It might not matter. 10230 if (Constructor) 10231 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 10232 } 10233 } 10234 10235 // Virtual base-class constructors. 10236 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 10237 BEnd = ClassDecl->vbases_end(); 10238 B != BEnd; ++B) { 10239 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 10240 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 10241 CXXConstructorDecl *Constructor = 10242 LookupMovingConstructor(BaseClassDecl, 0); 10243 // If this is a deleted function, add it anyway. This might be conformant 10244 // with the standard. This might not. I'm not sure. It might not matter. 10245 if (Constructor) 10246 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 10247 } 10248 } 10249 10250 // Field constructors. 10251 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 10252 FEnd = ClassDecl->field_end(); 10253 F != FEnd; ++F) { 10254 QualType FieldType = Context.getBaseElementType(F->getType()); 10255 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) { 10256 CXXConstructorDecl *Constructor = 10257 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers()); 10258 // If this is a deleted function, add it anyway. This might be conformant 10259 // with the standard. This might not. I'm not sure. It might not matter. 10260 // In particular, the problem is that this function never gets called. It 10261 // might just be ill-formed because this function attempts to refer to 10262 // a deleted function here. 10263 if (Constructor) 10264 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 10265 } 10266 } 10267 10268 return ExceptSpec; 10269} 10270 10271CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 10272 CXXRecordDecl *ClassDecl) { 10273 // C++11 [class.copy]p9: 10274 // If the definition of a class X does not explicitly declare a move 10275 // constructor, one will be implicitly declared as defaulted if and only if: 10276 // 10277 // - [first 4 bullets] 10278 assert(ClassDecl->needsImplicitMoveConstructor()); 10279 10280 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 10281 if (DSM.isAlreadyBeingDeclared()) 10282 return 0; 10283 10284 // [Checked after we build the declaration] 10285 // - the move assignment operator would not be implicitly defined as 10286 // deleted, 10287 10288 // [DR1402]: 10289 // - each of X's non-static data members and direct or virtual base classes 10290 // has a type that either has a move constructor or is trivially copyable. 10291 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) { 10292 ClassDecl->setFailedImplicitMoveConstructor(); 10293 return 0; 10294 } 10295 10296 QualType ClassType = Context.getTypeDeclType(ClassDecl); 10297 QualType ArgType = Context.getRValueReferenceType(ClassType); 10298 10299 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10300 CXXMoveConstructor, 10301 false); 10302 10303 DeclarationName Name 10304 = Context.DeclarationNames.getCXXConstructorName( 10305 Context.getCanonicalType(ClassType)); 10306 SourceLocation ClassLoc = ClassDecl->getLocation(); 10307 DeclarationNameInfo NameInfo(Name, ClassLoc); 10308 10309 // C++11 [class.copy]p11: 10310 // An implicitly-declared copy/move constructor is an inline public 10311 // member of its class. 10312 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 10313 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0, 10314 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 10315 Constexpr); 10316 MoveConstructor->setAccess(AS_public); 10317 MoveConstructor->setDefaulted(); 10318 10319 // Build an exception specification pointing back at this member. 10320 FunctionProtoType::ExtProtoInfo EPI = 10321 getImplicitMethodEPI(*this, MoveConstructor); 10322 MoveConstructor->setType( 10323 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 10324 10325 // Add the parameter to the constructor. 10326 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 10327 ClassLoc, ClassLoc, 10328 /*IdentifierInfo=*/0, 10329 ArgType, /*TInfo=*/0, 10330 SC_None, 0); 10331 MoveConstructor->setParams(FromParam); 10332 10333 MoveConstructor->setTrivial( 10334 ClassDecl->needsOverloadResolutionForMoveConstructor() 10335 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 10336 : ClassDecl->hasTrivialMoveConstructor()); 10337 10338 // C++0x [class.copy]p9: 10339 // If the definition of a class X does not explicitly declare a move 10340 // constructor, one will be implicitly declared as defaulted if and only if: 10341 // [...] 10342 // - the move constructor would not be implicitly defined as deleted. 10343 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 10344 // Cache this result so that we don't try to generate this over and over 10345 // on every lookup, leaking memory and wasting time. 10346 ClassDecl->setFailedImplicitMoveConstructor(); 10347 return 0; 10348 } 10349 10350 // Note that we have declared this constructor. 10351 ++ASTContext::NumImplicitMoveConstructorsDeclared; 10352 10353 if (Scope *S = getScopeForContext(ClassDecl)) 10354 PushOnScopeChains(MoveConstructor, S, false); 10355 ClassDecl->addDecl(MoveConstructor); 10356 10357 return MoveConstructor; 10358} 10359 10360void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 10361 CXXConstructorDecl *MoveConstructor) { 10362 assert((MoveConstructor->isDefaulted() && 10363 MoveConstructor->isMoveConstructor() && 10364 !MoveConstructor->doesThisDeclarationHaveABody() && 10365 !MoveConstructor->isDeleted()) && 10366 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 10367 10368 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 10369 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 10370 10371 SynthesizedFunctionScope Scope(*this, MoveConstructor); 10372 DiagnosticErrorTrap Trap(Diags); 10373 10374 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) || 10375 Trap.hasErrorOccurred()) { 10376 Diag(CurrentLocation, diag::note_member_synthesized_at) 10377 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl); 10378 MoveConstructor->setInvalidDecl(); 10379 } else { 10380 Sema::CompoundScopeRAII CompoundScope(*this); 10381 MoveConstructor->setBody(ActOnCompoundStmt( 10382 MoveConstructor->getLocation(), MoveConstructor->getLocation(), None, 10383 /*isStmtExpr=*/ false).takeAs<Stmt>()); 10384 } 10385 10386 MoveConstructor->markUsed(Context); 10387 10388 if (ASTMutationListener *L = getASTMutationListener()) { 10389 L->CompletedImplicitDefinition(MoveConstructor); 10390 } 10391} 10392 10393bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 10394 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 10395} 10396 10397void Sema::DefineImplicitLambdaToFunctionPointerConversion( 10398 SourceLocation CurrentLocation, 10399 CXXConversionDecl *Conv) { 10400 CXXRecordDecl *Lambda = Conv->getParent(); 10401 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator(); 10402 // If we are defining a specialization of a conversion to function-ptr 10403 // cache the deduced template arguments for this specialization 10404 // so that we can use them to retrieve the corresponding call-operator 10405 // and static-invoker. 10406 const TemplateArgumentList *DeducedTemplateArgs = 0; 10407 10408 10409 // Retrieve the corresponding call-operator specialization. 10410 if (Lambda->isGenericLambda()) { 10411 assert(Conv->isFunctionTemplateSpecialization()); 10412 FunctionTemplateDecl *CallOpTemplate = 10413 CallOp->getDescribedFunctionTemplate(); 10414 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs(); 10415 void *InsertPos = 0; 10416 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization( 10417 DeducedTemplateArgs->data(), 10418 DeducedTemplateArgs->size(), 10419 InsertPos); 10420 assert(CallOpSpec && 10421 "Conversion operator must have a corresponding call operator"); 10422 CallOp = cast<CXXMethodDecl>(CallOpSpec); 10423 } 10424 // Mark the call operator referenced (and add to pending instantiations 10425 // if necessary). 10426 // For both the conversion and static-invoker template specializations 10427 // we construct their body's in this function, so no need to add them 10428 // to the PendingInstantiations. 10429 MarkFunctionReferenced(CurrentLocation, CallOp); 10430 10431 SynthesizedFunctionScope Scope(*this, Conv); 10432 DiagnosticErrorTrap Trap(Diags); 10433 10434 // Retreive the static invoker... 10435 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker(); 10436 // ... and get the corresponding specialization for a generic lambda. 10437 if (Lambda->isGenericLambda()) { 10438 assert(DeducedTemplateArgs && 10439 "Must have deduced template arguments from Conversion Operator"); 10440 FunctionTemplateDecl *InvokeTemplate = 10441 Invoker->getDescribedFunctionTemplate(); 10442 void *InsertPos = 0; 10443 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization( 10444 DeducedTemplateArgs->data(), 10445 DeducedTemplateArgs->size(), 10446 InsertPos); 10447 assert(InvokeSpec && 10448 "Must have a corresponding static invoker specialization"); 10449 Invoker = cast<CXXMethodDecl>(InvokeSpec); 10450 } 10451 // Construct the body of the conversion function { return __invoke; }. 10452 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 10453 VK_LValue, Conv->getLocation()).take(); 10454 assert(FunctionRef && "Can't refer to __invoke function?"); 10455 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take(); 10456 Conv->setBody(new (Context) CompoundStmt(Context, Return, 10457 Conv->getLocation(), 10458 Conv->getLocation())); 10459 10460 Conv->markUsed(Context); 10461 Conv->setReferenced(); 10462 10463 // Fill in the __invoke function with a dummy implementation. IR generation 10464 // will fill in the actual details. 10465 Invoker->markUsed(Context); 10466 Invoker->setReferenced(); 10467 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 10468 10469 if (ASTMutationListener *L = getASTMutationListener()) { 10470 L->CompletedImplicitDefinition(Conv); 10471 L->CompletedImplicitDefinition(Invoker); 10472 } 10473} 10474 10475 10476 10477void Sema::DefineImplicitLambdaToBlockPointerConversion( 10478 SourceLocation CurrentLocation, 10479 CXXConversionDecl *Conv) 10480{ 10481 assert(!Conv->getParent()->isGenericLambda()); 10482 10483 Conv->markUsed(Context); 10484 10485 SynthesizedFunctionScope Scope(*this, Conv); 10486 DiagnosticErrorTrap Trap(Diags); 10487 10488 // Copy-initialize the lambda object as needed to capture it. 10489 Expr *This = ActOnCXXThis(CurrentLocation).take(); 10490 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take(); 10491 10492 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 10493 Conv->getLocation(), 10494 Conv, DerefThis); 10495 10496 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 10497 // behavior. Note that only the general conversion function does this 10498 // (since it's unusable otherwise); in the case where we inline the 10499 // block literal, it has block literal lifetime semantics. 10500 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 10501 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 10502 CK_CopyAndAutoreleaseBlockObject, 10503 BuildBlock.get(), 0, VK_RValue); 10504 10505 if (BuildBlock.isInvalid()) { 10506 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 10507 Conv->setInvalidDecl(); 10508 return; 10509 } 10510 10511 // Create the return statement that returns the block from the conversion 10512 // function. 10513 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get()); 10514 if (Return.isInvalid()) { 10515 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 10516 Conv->setInvalidDecl(); 10517 return; 10518 } 10519 10520 // Set the body of the conversion function. 10521 Stmt *ReturnS = Return.take(); 10522 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS, 10523 Conv->getLocation(), 10524 Conv->getLocation())); 10525 10526 // We're done; notify the mutation listener, if any. 10527 if (ASTMutationListener *L = getASTMutationListener()) { 10528 L->CompletedImplicitDefinition(Conv); 10529 } 10530} 10531 10532/// \brief Determine whether the given list arguments contains exactly one 10533/// "real" (non-default) argument. 10534static bool hasOneRealArgument(MultiExprArg Args) { 10535 switch (Args.size()) { 10536 case 0: 10537 return false; 10538 10539 default: 10540 if (!Args[1]->isDefaultArgument()) 10541 return false; 10542 10543 // fall through 10544 case 1: 10545 return !Args[0]->isDefaultArgument(); 10546 } 10547 10548 return false; 10549} 10550 10551ExprResult 10552Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 10553 CXXConstructorDecl *Constructor, 10554 MultiExprArg ExprArgs, 10555 bool HadMultipleCandidates, 10556 bool IsListInitialization, 10557 bool RequiresZeroInit, 10558 unsigned ConstructKind, 10559 SourceRange ParenRange) { 10560 bool Elidable = false; 10561 10562 // C++0x [class.copy]p34: 10563 // When certain criteria are met, an implementation is allowed to 10564 // omit the copy/move construction of a class object, even if the 10565 // copy/move constructor and/or destructor for the object have 10566 // side effects. [...] 10567 // - when a temporary class object that has not been bound to a 10568 // reference (12.2) would be copied/moved to a class object 10569 // with the same cv-unqualified type, the copy/move operation 10570 // can be omitted by constructing the temporary object 10571 // directly into the target of the omitted copy/move 10572 if (ConstructKind == CXXConstructExpr::CK_Complete && 10573 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 10574 Expr *SubExpr = ExprArgs[0]; 10575 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent()); 10576 } 10577 10578 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 10579 Elidable, ExprArgs, HadMultipleCandidates, 10580 IsListInitialization, RequiresZeroInit, 10581 ConstructKind, ParenRange); 10582} 10583 10584/// BuildCXXConstructExpr - Creates a complete call to a constructor, 10585/// including handling of its default argument expressions. 10586ExprResult 10587Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 10588 CXXConstructorDecl *Constructor, bool Elidable, 10589 MultiExprArg ExprArgs, 10590 bool HadMultipleCandidates, 10591 bool IsListInitialization, 10592 bool RequiresZeroInit, 10593 unsigned ConstructKind, 10594 SourceRange ParenRange) { 10595 MarkFunctionReferenced(ConstructLoc, Constructor); 10596 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc, 10597 Constructor, Elidable, ExprArgs, 10598 HadMultipleCandidates, 10599 IsListInitialization, RequiresZeroInit, 10600 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 10601 ParenRange)); 10602} 10603 10604void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 10605 if (VD->isInvalidDecl()) return; 10606 10607 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 10608 if (ClassDecl->isInvalidDecl()) return; 10609 if (ClassDecl->hasIrrelevantDestructor()) return; 10610 if (ClassDecl->isDependentContext()) return; 10611 10612 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 10613 MarkFunctionReferenced(VD->getLocation(), Destructor); 10614 CheckDestructorAccess(VD->getLocation(), Destructor, 10615 PDiag(diag::err_access_dtor_var) 10616 << VD->getDeclName() 10617 << VD->getType()); 10618 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 10619 10620 if (!VD->hasGlobalStorage()) return; 10621 10622 // Emit warning for non-trivial dtor in global scope (a real global, 10623 // class-static, function-static). 10624 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 10625 10626 // TODO: this should be re-enabled for static locals by !CXAAtExit 10627 if (!VD->isStaticLocal()) 10628 Diag(VD->getLocation(), diag::warn_global_destructor); 10629} 10630 10631/// \brief Given a constructor and the set of arguments provided for the 10632/// constructor, convert the arguments and add any required default arguments 10633/// to form a proper call to this constructor. 10634/// 10635/// \returns true if an error occurred, false otherwise. 10636bool 10637Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 10638 MultiExprArg ArgsPtr, 10639 SourceLocation Loc, 10640 SmallVectorImpl<Expr*> &ConvertedArgs, 10641 bool AllowExplicit, 10642 bool IsListInitialization) { 10643 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 10644 unsigned NumArgs = ArgsPtr.size(); 10645 Expr **Args = ArgsPtr.data(); 10646 10647 const FunctionProtoType *Proto 10648 = Constructor->getType()->getAs<FunctionProtoType>(); 10649 assert(Proto && "Constructor without a prototype?"); 10650 unsigned NumArgsInProto = Proto->getNumArgs(); 10651 10652 // If too few arguments are available, we'll fill in the rest with defaults. 10653 if (NumArgs < NumArgsInProto) 10654 ConvertedArgs.reserve(NumArgsInProto); 10655 else 10656 ConvertedArgs.reserve(NumArgs); 10657 10658 VariadicCallType CallType = 10659 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 10660 SmallVector<Expr *, 8> AllArgs; 10661 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 10662 Proto, 0, 10663 llvm::makeArrayRef(Args, NumArgs), 10664 AllArgs, 10665 CallType, AllowExplicit, 10666 IsListInitialization); 10667 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 10668 10669 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 10670 10671 CheckConstructorCall(Constructor, 10672 llvm::makeArrayRef<const Expr *>(AllArgs.data(), 10673 AllArgs.size()), 10674 Proto, Loc); 10675 10676 return Invalid; 10677} 10678 10679static inline bool 10680CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 10681 const FunctionDecl *FnDecl) { 10682 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 10683 if (isa<NamespaceDecl>(DC)) { 10684 return SemaRef.Diag(FnDecl->getLocation(), 10685 diag::err_operator_new_delete_declared_in_namespace) 10686 << FnDecl->getDeclName(); 10687 } 10688 10689 if (isa<TranslationUnitDecl>(DC) && 10690 FnDecl->getStorageClass() == SC_Static) { 10691 return SemaRef.Diag(FnDecl->getLocation(), 10692 diag::err_operator_new_delete_declared_static) 10693 << FnDecl->getDeclName(); 10694 } 10695 10696 return false; 10697} 10698 10699static inline bool 10700CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 10701 CanQualType ExpectedResultType, 10702 CanQualType ExpectedFirstParamType, 10703 unsigned DependentParamTypeDiag, 10704 unsigned InvalidParamTypeDiag) { 10705 QualType ResultType = 10706 FnDecl->getType()->getAs<FunctionType>()->getResultType(); 10707 10708 // Check that the result type is not dependent. 10709 if (ResultType->isDependentType()) 10710 return SemaRef.Diag(FnDecl->getLocation(), 10711 diag::err_operator_new_delete_dependent_result_type) 10712 << FnDecl->getDeclName() << ExpectedResultType; 10713 10714 // Check that the result type is what we expect. 10715 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 10716 return SemaRef.Diag(FnDecl->getLocation(), 10717 diag::err_operator_new_delete_invalid_result_type) 10718 << FnDecl->getDeclName() << ExpectedResultType; 10719 10720 // A function template must have at least 2 parameters. 10721 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 10722 return SemaRef.Diag(FnDecl->getLocation(), 10723 diag::err_operator_new_delete_template_too_few_parameters) 10724 << FnDecl->getDeclName(); 10725 10726 // The function decl must have at least 1 parameter. 10727 if (FnDecl->getNumParams() == 0) 10728 return SemaRef.Diag(FnDecl->getLocation(), 10729 diag::err_operator_new_delete_too_few_parameters) 10730 << FnDecl->getDeclName(); 10731 10732 // Check the first parameter type is not dependent. 10733 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 10734 if (FirstParamType->isDependentType()) 10735 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 10736 << FnDecl->getDeclName() << ExpectedFirstParamType; 10737 10738 // Check that the first parameter type is what we expect. 10739 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 10740 ExpectedFirstParamType) 10741 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 10742 << FnDecl->getDeclName() << ExpectedFirstParamType; 10743 10744 return false; 10745} 10746 10747static bool 10748CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 10749 // C++ [basic.stc.dynamic.allocation]p1: 10750 // A program is ill-formed if an allocation function is declared in a 10751 // namespace scope other than global scope or declared static in global 10752 // scope. 10753 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 10754 return true; 10755 10756 CanQualType SizeTy = 10757 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 10758 10759 // C++ [basic.stc.dynamic.allocation]p1: 10760 // The return type shall be void*. The first parameter shall have type 10761 // std::size_t. 10762 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 10763 SizeTy, 10764 diag::err_operator_new_dependent_param_type, 10765 diag::err_operator_new_param_type)) 10766 return true; 10767 10768 // C++ [basic.stc.dynamic.allocation]p1: 10769 // The first parameter shall not have an associated default argument. 10770 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 10771 return SemaRef.Diag(FnDecl->getLocation(), 10772 diag::err_operator_new_default_arg) 10773 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 10774 10775 return false; 10776} 10777 10778static bool 10779CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 10780 // C++ [basic.stc.dynamic.deallocation]p1: 10781 // A program is ill-formed if deallocation functions are declared in a 10782 // namespace scope other than global scope or declared static in global 10783 // scope. 10784 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 10785 return true; 10786 10787 // C++ [basic.stc.dynamic.deallocation]p2: 10788 // Each deallocation function shall return void and its first parameter 10789 // shall be void*. 10790 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 10791 SemaRef.Context.VoidPtrTy, 10792 diag::err_operator_delete_dependent_param_type, 10793 diag::err_operator_delete_param_type)) 10794 return true; 10795 10796 return false; 10797} 10798 10799/// CheckOverloadedOperatorDeclaration - Check whether the declaration 10800/// of this overloaded operator is well-formed. If so, returns false; 10801/// otherwise, emits appropriate diagnostics and returns true. 10802bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 10803 assert(FnDecl && FnDecl->isOverloadedOperator() && 10804 "Expected an overloaded operator declaration"); 10805 10806 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 10807 10808 // C++ [over.oper]p5: 10809 // The allocation and deallocation functions, operator new, 10810 // operator new[], operator delete and operator delete[], are 10811 // described completely in 3.7.3. The attributes and restrictions 10812 // found in the rest of this subclause do not apply to them unless 10813 // explicitly stated in 3.7.3. 10814 if (Op == OO_Delete || Op == OO_Array_Delete) 10815 return CheckOperatorDeleteDeclaration(*this, FnDecl); 10816 10817 if (Op == OO_New || Op == OO_Array_New) 10818 return CheckOperatorNewDeclaration(*this, FnDecl); 10819 10820 // C++ [over.oper]p6: 10821 // An operator function shall either be a non-static member 10822 // function or be a non-member function and have at least one 10823 // parameter whose type is a class, a reference to a class, an 10824 // enumeration, or a reference to an enumeration. 10825 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 10826 if (MethodDecl->isStatic()) 10827 return Diag(FnDecl->getLocation(), 10828 diag::err_operator_overload_static) << FnDecl->getDeclName(); 10829 } else { 10830 bool ClassOrEnumParam = false; 10831 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 10832 ParamEnd = FnDecl->param_end(); 10833 Param != ParamEnd; ++Param) { 10834 QualType ParamType = (*Param)->getType().getNonReferenceType(); 10835 if (ParamType->isDependentType() || ParamType->isRecordType() || 10836 ParamType->isEnumeralType()) { 10837 ClassOrEnumParam = true; 10838 break; 10839 } 10840 } 10841 10842 if (!ClassOrEnumParam) 10843 return Diag(FnDecl->getLocation(), 10844 diag::err_operator_overload_needs_class_or_enum) 10845 << FnDecl->getDeclName(); 10846 } 10847 10848 // C++ [over.oper]p8: 10849 // An operator function cannot have default arguments (8.3.6), 10850 // except where explicitly stated below. 10851 // 10852 // Only the function-call operator allows default arguments 10853 // (C++ [over.call]p1). 10854 if (Op != OO_Call) { 10855 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(); 10856 Param != FnDecl->param_end(); ++Param) { 10857 if ((*Param)->hasDefaultArg()) 10858 return Diag((*Param)->getLocation(), 10859 diag::err_operator_overload_default_arg) 10860 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange(); 10861 } 10862 } 10863 10864 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 10865 { false, false, false } 10866#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 10867 , { Unary, Binary, MemberOnly } 10868#include "clang/Basic/OperatorKinds.def" 10869 }; 10870 10871 bool CanBeUnaryOperator = OperatorUses[Op][0]; 10872 bool CanBeBinaryOperator = OperatorUses[Op][1]; 10873 bool MustBeMemberOperator = OperatorUses[Op][2]; 10874 10875 // C++ [over.oper]p8: 10876 // [...] Operator functions cannot have more or fewer parameters 10877 // than the number required for the corresponding operator, as 10878 // described in the rest of this subclause. 10879 unsigned NumParams = FnDecl->getNumParams() 10880 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 10881 if (Op != OO_Call && 10882 ((NumParams == 1 && !CanBeUnaryOperator) || 10883 (NumParams == 2 && !CanBeBinaryOperator) || 10884 (NumParams < 1) || (NumParams > 2))) { 10885 // We have the wrong number of parameters. 10886 unsigned ErrorKind; 10887 if (CanBeUnaryOperator && CanBeBinaryOperator) { 10888 ErrorKind = 2; // 2 -> unary or binary. 10889 } else if (CanBeUnaryOperator) { 10890 ErrorKind = 0; // 0 -> unary 10891 } else { 10892 assert(CanBeBinaryOperator && 10893 "All non-call overloaded operators are unary or binary!"); 10894 ErrorKind = 1; // 1 -> binary 10895 } 10896 10897 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 10898 << FnDecl->getDeclName() << NumParams << ErrorKind; 10899 } 10900 10901 // Overloaded operators other than operator() cannot be variadic. 10902 if (Op != OO_Call && 10903 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 10904 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 10905 << FnDecl->getDeclName(); 10906 } 10907 10908 // Some operators must be non-static member functions. 10909 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 10910 return Diag(FnDecl->getLocation(), 10911 diag::err_operator_overload_must_be_member) 10912 << FnDecl->getDeclName(); 10913 } 10914 10915 // C++ [over.inc]p1: 10916 // The user-defined function called operator++ implements the 10917 // prefix and postfix ++ operator. If this function is a member 10918 // function with no parameters, or a non-member function with one 10919 // parameter of class or enumeration type, it defines the prefix 10920 // increment operator ++ for objects of that type. If the function 10921 // is a member function with one parameter (which shall be of type 10922 // int) or a non-member function with two parameters (the second 10923 // of which shall be of type int), it defines the postfix 10924 // increment operator ++ for objects of that type. 10925 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 10926 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 10927 bool ParamIsInt = false; 10928 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>()) 10929 ParamIsInt = BT->getKind() == BuiltinType::Int; 10930 10931 if (!ParamIsInt) 10932 return Diag(LastParam->getLocation(), 10933 diag::err_operator_overload_post_incdec_must_be_int) 10934 << LastParam->getType() << (Op == OO_MinusMinus); 10935 } 10936 10937 return false; 10938} 10939 10940/// CheckLiteralOperatorDeclaration - Check whether the declaration 10941/// of this literal operator function is well-formed. If so, returns 10942/// false; otherwise, emits appropriate diagnostics and returns true. 10943bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 10944 if (isa<CXXMethodDecl>(FnDecl)) { 10945 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 10946 << FnDecl->getDeclName(); 10947 return true; 10948 } 10949 10950 if (FnDecl->isExternC()) { 10951 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 10952 return true; 10953 } 10954 10955 bool Valid = false; 10956 10957 // This might be the definition of a literal operator template. 10958 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 10959 // This might be a specialization of a literal operator template. 10960 if (!TpDecl) 10961 TpDecl = FnDecl->getPrimaryTemplate(); 10962 10963 // template <char...> type operator "" name() and 10964 // template <class T, T...> type operator "" name() are the only valid 10965 // template signatures, and the only valid signatures with no parameters. 10966 if (TpDecl) { 10967 if (FnDecl->param_size() == 0) { 10968 // Must have one or two template parameters 10969 TemplateParameterList *Params = TpDecl->getTemplateParameters(); 10970 if (Params->size() == 1) { 10971 NonTypeTemplateParmDecl *PmDecl = 10972 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0)); 10973 10974 // The template parameter must be a char parameter pack. 10975 if (PmDecl && PmDecl->isTemplateParameterPack() && 10976 Context.hasSameType(PmDecl->getType(), Context.CharTy)) 10977 Valid = true; 10978 } else if (Params->size() == 2) { 10979 TemplateTypeParmDecl *PmType = 10980 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0)); 10981 NonTypeTemplateParmDecl *PmArgs = 10982 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 10983 10984 // The second template parameter must be a parameter pack with the 10985 // first template parameter as its type. 10986 if (PmType && PmArgs && 10987 !PmType->isTemplateParameterPack() && 10988 PmArgs->isTemplateParameterPack()) { 10989 const TemplateTypeParmType *TArgs = 10990 PmArgs->getType()->getAs<TemplateTypeParmType>(); 10991 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 10992 TArgs->getIndex() == PmType->getIndex()) { 10993 Valid = true; 10994 if (ActiveTemplateInstantiations.empty()) 10995 Diag(FnDecl->getLocation(), 10996 diag::ext_string_literal_operator_template); 10997 } 10998 } 10999 } 11000 } 11001 } else if (FnDecl->param_size()) { 11002 // Check the first parameter 11003 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 11004 11005 QualType T = (*Param)->getType().getUnqualifiedType(); 11006 11007 // unsigned long long int, long double, and any character type are allowed 11008 // as the only parameters. 11009 if (Context.hasSameType(T, Context.UnsignedLongLongTy) || 11010 Context.hasSameType(T, Context.LongDoubleTy) || 11011 Context.hasSameType(T, Context.CharTy) || 11012 Context.hasSameType(T, Context.WideCharTy) || 11013 Context.hasSameType(T, Context.Char16Ty) || 11014 Context.hasSameType(T, Context.Char32Ty)) { 11015 if (++Param == FnDecl->param_end()) 11016 Valid = true; 11017 goto FinishedParams; 11018 } 11019 11020 // Otherwise it must be a pointer to const; let's strip those qualifiers. 11021 const PointerType *PT = T->getAs<PointerType>(); 11022 if (!PT) 11023 goto FinishedParams; 11024 T = PT->getPointeeType(); 11025 if (!T.isConstQualified() || T.isVolatileQualified()) 11026 goto FinishedParams; 11027 T = T.getUnqualifiedType(); 11028 11029 // Move on to the second parameter; 11030 ++Param; 11031 11032 // If there is no second parameter, the first must be a const char * 11033 if (Param == FnDecl->param_end()) { 11034 if (Context.hasSameType(T, Context.CharTy)) 11035 Valid = true; 11036 goto FinishedParams; 11037 } 11038 11039 // const char *, const wchar_t*, const char16_t*, and const char32_t* 11040 // are allowed as the first parameter to a two-parameter function 11041 if (!(Context.hasSameType(T, Context.CharTy) || 11042 Context.hasSameType(T, Context.WideCharTy) || 11043 Context.hasSameType(T, Context.Char16Ty) || 11044 Context.hasSameType(T, Context.Char32Ty))) 11045 goto FinishedParams; 11046 11047 // The second and final parameter must be an std::size_t 11048 T = (*Param)->getType().getUnqualifiedType(); 11049 if (Context.hasSameType(T, Context.getSizeType()) && 11050 ++Param == FnDecl->param_end()) 11051 Valid = true; 11052 } 11053 11054 // FIXME: This diagnostic is absolutely terrible. 11055FinishedParams: 11056 if (!Valid) { 11057 Diag(FnDecl->getLocation(), diag::err_literal_operator_params) 11058 << FnDecl->getDeclName(); 11059 return true; 11060 } 11061 11062 // A parameter-declaration-clause containing a default argument is not 11063 // equivalent to any of the permitted forms. 11064 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 11065 ParamEnd = FnDecl->param_end(); 11066 Param != ParamEnd; ++Param) { 11067 if ((*Param)->hasDefaultArg()) { 11068 Diag((*Param)->getDefaultArgRange().getBegin(), 11069 diag::err_literal_operator_default_argument) 11070 << (*Param)->getDefaultArgRange(); 11071 break; 11072 } 11073 } 11074 11075 StringRef LiteralName 11076 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 11077 if (LiteralName[0] != '_') { 11078 // C++11 [usrlit.suffix]p1: 11079 // Literal suffix identifiers that do not start with an underscore 11080 // are reserved for future standardization. 11081 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 11082 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 11083 } 11084 11085 return false; 11086} 11087 11088/// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 11089/// linkage specification, including the language and (if present) 11090/// the '{'. ExternLoc is the location of the 'extern', LangLoc is 11091/// the location of the language string literal, which is provided 11092/// by Lang/StrSize. LBraceLoc, if valid, provides the location of 11093/// the '{' brace. Otherwise, this linkage specification does not 11094/// have any braces. 11095Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 11096 SourceLocation LangLoc, 11097 StringRef Lang, 11098 SourceLocation LBraceLoc) { 11099 LinkageSpecDecl::LanguageIDs Language; 11100 if (Lang == "\"C\"") 11101 Language = LinkageSpecDecl::lang_c; 11102 else if (Lang == "\"C++\"") 11103 Language = LinkageSpecDecl::lang_cxx; 11104 else { 11105 Diag(LangLoc, diag::err_bad_language); 11106 return 0; 11107 } 11108 11109 // FIXME: Add all the various semantics of linkage specifications 11110 11111 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, 11112 ExternLoc, LangLoc, Language, 11113 LBraceLoc.isValid()); 11114 CurContext->addDecl(D); 11115 PushDeclContext(S, D); 11116 return D; 11117} 11118 11119/// ActOnFinishLinkageSpecification - Complete the definition of 11120/// the C++ linkage specification LinkageSpec. If RBraceLoc is 11121/// valid, it's the position of the closing '}' brace in a linkage 11122/// specification that uses braces. 11123Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 11124 Decl *LinkageSpec, 11125 SourceLocation RBraceLoc) { 11126 if (LinkageSpec) { 11127 if (RBraceLoc.isValid()) { 11128 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 11129 LSDecl->setRBraceLoc(RBraceLoc); 11130 } 11131 PopDeclContext(); 11132 } 11133 return LinkageSpec; 11134} 11135 11136Decl *Sema::ActOnEmptyDeclaration(Scope *S, 11137 AttributeList *AttrList, 11138 SourceLocation SemiLoc) { 11139 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 11140 // Attribute declarations appertain to empty declaration so we handle 11141 // them here. 11142 if (AttrList) 11143 ProcessDeclAttributeList(S, ED, AttrList); 11144 11145 CurContext->addDecl(ED); 11146 return ED; 11147} 11148 11149/// \brief Perform semantic analysis for the variable declaration that 11150/// occurs within a C++ catch clause, returning the newly-created 11151/// variable. 11152VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 11153 TypeSourceInfo *TInfo, 11154 SourceLocation StartLoc, 11155 SourceLocation Loc, 11156 IdentifierInfo *Name) { 11157 bool Invalid = false; 11158 QualType ExDeclType = TInfo->getType(); 11159 11160 // Arrays and functions decay. 11161 if (ExDeclType->isArrayType()) 11162 ExDeclType = Context.getArrayDecayedType(ExDeclType); 11163 else if (ExDeclType->isFunctionType()) 11164 ExDeclType = Context.getPointerType(ExDeclType); 11165 11166 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 11167 // The exception-declaration shall not denote a pointer or reference to an 11168 // incomplete type, other than [cv] void*. 11169 // N2844 forbids rvalue references. 11170 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 11171 Diag(Loc, diag::err_catch_rvalue_ref); 11172 Invalid = true; 11173 } 11174 11175 QualType BaseType = ExDeclType; 11176 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 11177 unsigned DK = diag::err_catch_incomplete; 11178 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 11179 BaseType = Ptr->getPointeeType(); 11180 Mode = 1; 11181 DK = diag::err_catch_incomplete_ptr; 11182 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 11183 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 11184 BaseType = Ref->getPointeeType(); 11185 Mode = 2; 11186 DK = diag::err_catch_incomplete_ref; 11187 } 11188 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 11189 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 11190 Invalid = true; 11191 11192 if (!Invalid && !ExDeclType->isDependentType() && 11193 RequireNonAbstractType(Loc, ExDeclType, 11194 diag::err_abstract_type_in_decl, 11195 AbstractVariableType)) 11196 Invalid = true; 11197 11198 // Only the non-fragile NeXT runtime currently supports C++ catches 11199 // of ObjC types, and no runtime supports catching ObjC types by value. 11200 if (!Invalid && getLangOpts().ObjC1) { 11201 QualType T = ExDeclType; 11202 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 11203 T = RT->getPointeeType(); 11204 11205 if (T->isObjCObjectType()) { 11206 Diag(Loc, diag::err_objc_object_catch); 11207 Invalid = true; 11208 } else if (T->isObjCObjectPointerType()) { 11209 // FIXME: should this be a test for macosx-fragile specifically? 11210 if (getLangOpts().ObjCRuntime.isFragile()) 11211 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 11212 } 11213 } 11214 11215 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 11216 ExDeclType, TInfo, SC_None); 11217 ExDecl->setExceptionVariable(true); 11218 11219 // In ARC, infer 'retaining' for variables of retainable type. 11220 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 11221 Invalid = true; 11222 11223 if (!Invalid && !ExDeclType->isDependentType()) { 11224 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 11225 // Insulate this from anything else we might currently be parsing. 11226 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 11227 11228 // C++ [except.handle]p16: 11229 // The object declared in an exception-declaration or, if the 11230 // exception-declaration does not specify a name, a temporary (12.2) is 11231 // copy-initialized (8.5) from the exception object. [...] 11232 // The object is destroyed when the handler exits, after the destruction 11233 // of any automatic objects initialized within the handler. 11234 // 11235 // We just pretend to initialize the object with itself, then make sure 11236 // it can be destroyed later. 11237 QualType initType = ExDeclType; 11238 11239 InitializedEntity entity = 11240 InitializedEntity::InitializeVariable(ExDecl); 11241 InitializationKind initKind = 11242 InitializationKind::CreateCopy(Loc, SourceLocation()); 11243 11244 Expr *opaqueValue = 11245 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 11246 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 11247 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 11248 if (result.isInvalid()) 11249 Invalid = true; 11250 else { 11251 // If the constructor used was non-trivial, set this as the 11252 // "initializer". 11253 CXXConstructExpr *construct = result.takeAs<CXXConstructExpr>(); 11254 if (!construct->getConstructor()->isTrivial()) { 11255 Expr *init = MaybeCreateExprWithCleanups(construct); 11256 ExDecl->setInit(init); 11257 } 11258 11259 // And make sure it's destructable. 11260 FinalizeVarWithDestructor(ExDecl, recordType); 11261 } 11262 } 11263 } 11264 11265 if (Invalid) 11266 ExDecl->setInvalidDecl(); 11267 11268 return ExDecl; 11269} 11270 11271/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 11272/// handler. 11273Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 11274 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11275 bool Invalid = D.isInvalidType(); 11276 11277 // Check for unexpanded parameter packs. 11278 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 11279 UPPC_ExceptionType)) { 11280 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 11281 D.getIdentifierLoc()); 11282 Invalid = true; 11283 } 11284 11285 IdentifierInfo *II = D.getIdentifier(); 11286 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 11287 LookupOrdinaryName, 11288 ForRedeclaration)) { 11289 // The scope should be freshly made just for us. There is just no way 11290 // it contains any previous declaration. 11291 assert(!S->isDeclScope(PrevDecl)); 11292 if (PrevDecl->isTemplateParameter()) { 11293 // Maybe we will complain about the shadowed template parameter. 11294 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 11295 PrevDecl = 0; 11296 } 11297 } 11298 11299 if (D.getCXXScopeSpec().isSet() && !Invalid) { 11300 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 11301 << D.getCXXScopeSpec().getRange(); 11302 Invalid = true; 11303 } 11304 11305 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 11306 D.getLocStart(), 11307 D.getIdentifierLoc(), 11308 D.getIdentifier()); 11309 if (Invalid) 11310 ExDecl->setInvalidDecl(); 11311 11312 // Add the exception declaration into this scope. 11313 if (II) 11314 PushOnScopeChains(ExDecl, S); 11315 else 11316 CurContext->addDecl(ExDecl); 11317 11318 ProcessDeclAttributes(S, ExDecl, D); 11319 return ExDecl; 11320} 11321 11322Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 11323 Expr *AssertExpr, 11324 Expr *AssertMessageExpr, 11325 SourceLocation RParenLoc) { 11326 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr); 11327 11328 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 11329 return 0; 11330 11331 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 11332 AssertMessage, RParenLoc, false); 11333} 11334 11335Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 11336 Expr *AssertExpr, 11337 StringLiteral *AssertMessage, 11338 SourceLocation RParenLoc, 11339 bool Failed) { 11340 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 11341 !Failed) { 11342 // In a static_assert-declaration, the constant-expression shall be a 11343 // constant expression that can be contextually converted to bool. 11344 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 11345 if (Converted.isInvalid()) 11346 Failed = true; 11347 11348 llvm::APSInt Cond; 11349 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 11350 diag::err_static_assert_expression_is_not_constant, 11351 /*AllowFold=*/false).isInvalid()) 11352 Failed = true; 11353 11354 if (!Failed && !Cond) { 11355 SmallString<256> MsgBuffer; 11356 llvm::raw_svector_ostream Msg(MsgBuffer); 11357 AssertMessage->printPretty(Msg, 0, getPrintingPolicy()); 11358 Diag(StaticAssertLoc, diag::err_static_assert_failed) 11359 << Msg.str() << AssertExpr->getSourceRange(); 11360 Failed = true; 11361 } 11362 } 11363 11364 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 11365 AssertExpr, AssertMessage, RParenLoc, 11366 Failed); 11367 11368 CurContext->addDecl(Decl); 11369 return Decl; 11370} 11371 11372/// \brief Perform semantic analysis of the given friend type declaration. 11373/// 11374/// \returns A friend declaration that. 11375FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 11376 SourceLocation FriendLoc, 11377 TypeSourceInfo *TSInfo) { 11378 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 11379 11380 QualType T = TSInfo->getType(); 11381 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 11382 11383 // C++03 [class.friend]p2: 11384 // An elaborated-type-specifier shall be used in a friend declaration 11385 // for a class.* 11386 // 11387 // * The class-key of the elaborated-type-specifier is required. 11388 if (!ActiveTemplateInstantiations.empty()) { 11389 // Do not complain about the form of friend template types during 11390 // template instantiation; we will already have complained when the 11391 // template was declared. 11392 } else { 11393 if (!T->isElaboratedTypeSpecifier()) { 11394 // If we evaluated the type to a record type, suggest putting 11395 // a tag in front. 11396 if (const RecordType *RT = T->getAs<RecordType>()) { 11397 RecordDecl *RD = RT->getDecl(); 11398 11399 std::string InsertionText = std::string(" ") + RD->getKindName(); 11400 11401 Diag(TypeRange.getBegin(), 11402 getLangOpts().CPlusPlus11 ? 11403 diag::warn_cxx98_compat_unelaborated_friend_type : 11404 diag::ext_unelaborated_friend_type) 11405 << (unsigned) RD->getTagKind() 11406 << T 11407 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc), 11408 InsertionText); 11409 } else { 11410 Diag(FriendLoc, 11411 getLangOpts().CPlusPlus11 ? 11412 diag::warn_cxx98_compat_nonclass_type_friend : 11413 diag::ext_nonclass_type_friend) 11414 << T 11415 << TypeRange; 11416 } 11417 } else if (T->getAs<EnumType>()) { 11418 Diag(FriendLoc, 11419 getLangOpts().CPlusPlus11 ? 11420 diag::warn_cxx98_compat_enum_friend : 11421 diag::ext_enum_friend) 11422 << T 11423 << TypeRange; 11424 } 11425 11426 // C++11 [class.friend]p3: 11427 // A friend declaration that does not declare a function shall have one 11428 // of the following forms: 11429 // friend elaborated-type-specifier ; 11430 // friend simple-type-specifier ; 11431 // friend typename-specifier ; 11432 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 11433 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 11434 } 11435 11436 // If the type specifier in a friend declaration designates a (possibly 11437 // cv-qualified) class type, that class is declared as a friend; otherwise, 11438 // the friend declaration is ignored. 11439 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc); 11440} 11441 11442/// Handle a friend tag declaration where the scope specifier was 11443/// templated. 11444Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 11445 unsigned TagSpec, SourceLocation TagLoc, 11446 CXXScopeSpec &SS, 11447 IdentifierInfo *Name, 11448 SourceLocation NameLoc, 11449 AttributeList *Attr, 11450 MultiTemplateParamsArg TempParamLists) { 11451 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 11452 11453 bool isExplicitSpecialization = false; 11454 bool Invalid = false; 11455 11456 if (TemplateParameterList *TemplateParams = 11457 MatchTemplateParametersToScopeSpecifier( 11458 TagLoc, NameLoc, SS, TempParamLists, /*friend*/ true, 11459 isExplicitSpecialization, Invalid)) { 11460 if (TemplateParams->size() > 0) { 11461 // This is a declaration of a class template. 11462 if (Invalid) 11463 return 0; 11464 11465 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, 11466 SS, Name, NameLoc, Attr, 11467 TemplateParams, AS_public, 11468 /*ModulePrivateLoc=*/SourceLocation(), 11469 TempParamLists.size() - 1, 11470 TempParamLists.data()).take(); 11471 } else { 11472 // The "template<>" header is extraneous. 11473 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 11474 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 11475 isExplicitSpecialization = true; 11476 } 11477 } 11478 11479 if (Invalid) return 0; 11480 11481 bool isAllExplicitSpecializations = true; 11482 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 11483 if (TempParamLists[I]->size()) { 11484 isAllExplicitSpecializations = false; 11485 break; 11486 } 11487 } 11488 11489 // FIXME: don't ignore attributes. 11490 11491 // If it's explicit specializations all the way down, just forget 11492 // about the template header and build an appropriate non-templated 11493 // friend. TODO: for source fidelity, remember the headers. 11494 if (isAllExplicitSpecializations) { 11495 if (SS.isEmpty()) { 11496 bool Owned = false; 11497 bool IsDependent = false; 11498 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 11499 Attr, AS_public, 11500 /*ModulePrivateLoc=*/SourceLocation(), 11501 MultiTemplateParamsArg(), Owned, IsDependent, 11502 /*ScopedEnumKWLoc=*/SourceLocation(), 11503 /*ScopedEnumUsesClassTag=*/false, 11504 /*UnderlyingType=*/TypeResult()); 11505 } 11506 11507 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 11508 ElaboratedTypeKeyword Keyword 11509 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 11510 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 11511 *Name, NameLoc); 11512 if (T.isNull()) 11513 return 0; 11514 11515 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 11516 if (isa<DependentNameType>(T)) { 11517 DependentNameTypeLoc TL = 11518 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 11519 TL.setElaboratedKeywordLoc(TagLoc); 11520 TL.setQualifierLoc(QualifierLoc); 11521 TL.setNameLoc(NameLoc); 11522 } else { 11523 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 11524 TL.setElaboratedKeywordLoc(TagLoc); 11525 TL.setQualifierLoc(QualifierLoc); 11526 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 11527 } 11528 11529 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 11530 TSI, FriendLoc, TempParamLists); 11531 Friend->setAccess(AS_public); 11532 CurContext->addDecl(Friend); 11533 return Friend; 11534 } 11535 11536 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 11537 11538 11539 11540 // Handle the case of a templated-scope friend class. e.g. 11541 // template <class T> class A<T>::B; 11542 // FIXME: we don't support these right now. 11543 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 11544 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 11545 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 11546 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 11547 TL.setElaboratedKeywordLoc(TagLoc); 11548 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 11549 TL.setNameLoc(NameLoc); 11550 11551 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 11552 TSI, FriendLoc, TempParamLists); 11553 Friend->setAccess(AS_public); 11554 Friend->setUnsupportedFriend(true); 11555 CurContext->addDecl(Friend); 11556 return Friend; 11557} 11558 11559 11560/// Handle a friend type declaration. This works in tandem with 11561/// ActOnTag. 11562/// 11563/// Notes on friend class templates: 11564/// 11565/// We generally treat friend class declarations as if they were 11566/// declaring a class. So, for example, the elaborated type specifier 11567/// in a friend declaration is required to obey the restrictions of a 11568/// class-head (i.e. no typedefs in the scope chain), template 11569/// parameters are required to match up with simple template-ids, &c. 11570/// However, unlike when declaring a template specialization, it's 11571/// okay to refer to a template specialization without an empty 11572/// template parameter declaration, e.g. 11573/// friend class A<T>::B<unsigned>; 11574/// We permit this as a special case; if there are any template 11575/// parameters present at all, require proper matching, i.e. 11576/// template <> template \<class T> friend class A<int>::B; 11577Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 11578 MultiTemplateParamsArg TempParams) { 11579 SourceLocation Loc = DS.getLocStart(); 11580 11581 assert(DS.isFriendSpecified()); 11582 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 11583 11584 // Try to convert the decl specifier to a type. This works for 11585 // friend templates because ActOnTag never produces a ClassTemplateDecl 11586 // for a TUK_Friend. 11587 Declarator TheDeclarator(DS, Declarator::MemberContext); 11588 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 11589 QualType T = TSI->getType(); 11590 if (TheDeclarator.isInvalidType()) 11591 return 0; 11592 11593 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 11594 return 0; 11595 11596 // This is definitely an error in C++98. It's probably meant to 11597 // be forbidden in C++0x, too, but the specification is just 11598 // poorly written. 11599 // 11600 // The problem is with declarations like the following: 11601 // template <T> friend A<T>::foo; 11602 // where deciding whether a class C is a friend or not now hinges 11603 // on whether there exists an instantiation of A that causes 11604 // 'foo' to equal C. There are restrictions on class-heads 11605 // (which we declare (by fiat) elaborated friend declarations to 11606 // be) that makes this tractable. 11607 // 11608 // FIXME: handle "template <> friend class A<T>;", which 11609 // is possibly well-formed? Who even knows? 11610 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 11611 Diag(Loc, diag::err_tagless_friend_type_template) 11612 << DS.getSourceRange(); 11613 return 0; 11614 } 11615 11616 // C++98 [class.friend]p1: A friend of a class is a function 11617 // or class that is not a member of the class . . . 11618 // This is fixed in DR77, which just barely didn't make the C++03 11619 // deadline. It's also a very silly restriction that seriously 11620 // affects inner classes and which nobody else seems to implement; 11621 // thus we never diagnose it, not even in -pedantic. 11622 // 11623 // But note that we could warn about it: it's always useless to 11624 // friend one of your own members (it's not, however, worthless to 11625 // friend a member of an arbitrary specialization of your template). 11626 11627 Decl *D; 11628 if (unsigned NumTempParamLists = TempParams.size()) 11629 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 11630 NumTempParamLists, 11631 TempParams.data(), 11632 TSI, 11633 DS.getFriendSpecLoc()); 11634 else 11635 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 11636 11637 if (!D) 11638 return 0; 11639 11640 D->setAccess(AS_public); 11641 CurContext->addDecl(D); 11642 11643 return D; 11644} 11645 11646NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 11647 MultiTemplateParamsArg TemplateParams) { 11648 const DeclSpec &DS = D.getDeclSpec(); 11649 11650 assert(DS.isFriendSpecified()); 11651 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 11652 11653 SourceLocation Loc = D.getIdentifierLoc(); 11654 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11655 11656 // C++ [class.friend]p1 11657 // A friend of a class is a function or class.... 11658 // Note that this sees through typedefs, which is intended. 11659 // It *doesn't* see through dependent types, which is correct 11660 // according to [temp.arg.type]p3: 11661 // If a declaration acquires a function type through a 11662 // type dependent on a template-parameter and this causes 11663 // a declaration that does not use the syntactic form of a 11664 // function declarator to have a function type, the program 11665 // is ill-formed. 11666 if (!TInfo->getType()->isFunctionType()) { 11667 Diag(Loc, diag::err_unexpected_friend); 11668 11669 // It might be worthwhile to try to recover by creating an 11670 // appropriate declaration. 11671 return 0; 11672 } 11673 11674 // C++ [namespace.memdef]p3 11675 // - If a friend declaration in a non-local class first declares a 11676 // class or function, the friend class or function is a member 11677 // of the innermost enclosing namespace. 11678 // - The name of the friend is not found by simple name lookup 11679 // until a matching declaration is provided in that namespace 11680 // scope (either before or after the class declaration granting 11681 // friendship). 11682 // - If a friend function is called, its name may be found by the 11683 // name lookup that considers functions from namespaces and 11684 // classes associated with the types of the function arguments. 11685 // - When looking for a prior declaration of a class or a function 11686 // declared as a friend, scopes outside the innermost enclosing 11687 // namespace scope are not considered. 11688 11689 CXXScopeSpec &SS = D.getCXXScopeSpec(); 11690 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 11691 DeclarationName Name = NameInfo.getName(); 11692 assert(Name); 11693 11694 // Check for unexpanded parameter packs. 11695 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 11696 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 11697 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 11698 return 0; 11699 11700 // The context we found the declaration in, or in which we should 11701 // create the declaration. 11702 DeclContext *DC; 11703 Scope *DCScope = S; 11704 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 11705 ForRedeclaration); 11706 11707 // There are five cases here. 11708 // - There's no scope specifier and we're in a local class. Only look 11709 // for functions declared in the immediately-enclosing block scope. 11710 // We recover from invalid scope qualifiers as if they just weren't there. 11711 FunctionDecl *FunctionContainingLocalClass = 0; 11712 if ((SS.isInvalid() || !SS.isSet()) && 11713 (FunctionContainingLocalClass = 11714 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 11715 // C++11 [class.friend]p11: 11716 // If a friend declaration appears in a local class and the name 11717 // specified is an unqualified name, a prior declaration is 11718 // looked up without considering scopes that are outside the 11719 // innermost enclosing non-class scope. For a friend function 11720 // declaration, if there is no prior declaration, the program is 11721 // ill-formed. 11722 11723 // Find the innermost enclosing non-class scope. This is the block 11724 // scope containing the local class definition (or for a nested class, 11725 // the outer local class). 11726 DCScope = S->getFnParent(); 11727 11728 // Look up the function name in the scope. 11729 Previous.clear(LookupLocalFriendName); 11730 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 11731 11732 if (!Previous.empty()) { 11733 // All possible previous declarations must have the same context: 11734 // either they were declared at block scope or they are members of 11735 // one of the enclosing local classes. 11736 DC = Previous.getRepresentativeDecl()->getDeclContext(); 11737 } else { 11738 // This is ill-formed, but provide the context that we would have 11739 // declared the function in, if we were permitted to, for error recovery. 11740 DC = FunctionContainingLocalClass; 11741 } 11742 adjustContextForLocalExternDecl(DC); 11743 11744 // C++ [class.friend]p6: 11745 // A function can be defined in a friend declaration of a class if and 11746 // only if the class is a non-local class (9.8), the function name is 11747 // unqualified, and the function has namespace scope. 11748 if (D.isFunctionDefinition()) { 11749 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 11750 } 11751 11752 // - There's no scope specifier, in which case we just go to the 11753 // appropriate scope and look for a function or function template 11754 // there as appropriate. 11755 } else if (SS.isInvalid() || !SS.isSet()) { 11756 // C++11 [namespace.memdef]p3: 11757 // If the name in a friend declaration is neither qualified nor 11758 // a template-id and the declaration is a function or an 11759 // elaborated-type-specifier, the lookup to determine whether 11760 // the entity has been previously declared shall not consider 11761 // any scopes outside the innermost enclosing namespace. 11762 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 11763 11764 // Find the appropriate context according to the above. 11765 DC = CurContext; 11766 11767 // Skip class contexts. If someone can cite chapter and verse 11768 // for this behavior, that would be nice --- it's what GCC and 11769 // EDG do, and it seems like a reasonable intent, but the spec 11770 // really only says that checks for unqualified existing 11771 // declarations should stop at the nearest enclosing namespace, 11772 // not that they should only consider the nearest enclosing 11773 // namespace. 11774 while (DC->isRecord()) 11775 DC = DC->getParent(); 11776 11777 DeclContext *LookupDC = DC; 11778 while (LookupDC->isTransparentContext()) 11779 LookupDC = LookupDC->getParent(); 11780 11781 while (true) { 11782 LookupQualifiedName(Previous, LookupDC); 11783 11784 if (!Previous.empty()) { 11785 DC = LookupDC; 11786 break; 11787 } 11788 11789 if (isTemplateId) { 11790 if (isa<TranslationUnitDecl>(LookupDC)) break; 11791 } else { 11792 if (LookupDC->isFileContext()) break; 11793 } 11794 LookupDC = LookupDC->getParent(); 11795 } 11796 11797 DCScope = getScopeForDeclContext(S, DC); 11798 11799 // - There's a non-dependent scope specifier, in which case we 11800 // compute it and do a previous lookup there for a function 11801 // or function template. 11802 } else if (!SS.getScopeRep()->isDependent()) { 11803 DC = computeDeclContext(SS); 11804 if (!DC) return 0; 11805 11806 if (RequireCompleteDeclContext(SS, DC)) return 0; 11807 11808 LookupQualifiedName(Previous, DC); 11809 11810 // Ignore things found implicitly in the wrong scope. 11811 // TODO: better diagnostics for this case. Suggesting the right 11812 // qualified scope would be nice... 11813 LookupResult::Filter F = Previous.makeFilter(); 11814 while (F.hasNext()) { 11815 NamedDecl *D = F.next(); 11816 if (!DC->InEnclosingNamespaceSetOf( 11817 D->getDeclContext()->getRedeclContext())) 11818 F.erase(); 11819 } 11820 F.done(); 11821 11822 if (Previous.empty()) { 11823 D.setInvalidType(); 11824 Diag(Loc, diag::err_qualified_friend_not_found) 11825 << Name << TInfo->getType(); 11826 return 0; 11827 } 11828 11829 // C++ [class.friend]p1: A friend of a class is a function or 11830 // class that is not a member of the class . . . 11831 if (DC->Equals(CurContext)) 11832 Diag(DS.getFriendSpecLoc(), 11833 getLangOpts().CPlusPlus11 ? 11834 diag::warn_cxx98_compat_friend_is_member : 11835 diag::err_friend_is_member); 11836 11837 if (D.isFunctionDefinition()) { 11838 // C++ [class.friend]p6: 11839 // A function can be defined in a friend declaration of a class if and 11840 // only if the class is a non-local class (9.8), the function name is 11841 // unqualified, and the function has namespace scope. 11842 SemaDiagnosticBuilder DB 11843 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 11844 11845 DB << SS.getScopeRep(); 11846 if (DC->isFileContext()) 11847 DB << FixItHint::CreateRemoval(SS.getRange()); 11848 SS.clear(); 11849 } 11850 11851 // - There's a scope specifier that does not match any template 11852 // parameter lists, in which case we use some arbitrary context, 11853 // create a method or method template, and wait for instantiation. 11854 // - There's a scope specifier that does match some template 11855 // parameter lists, which we don't handle right now. 11856 } else { 11857 if (D.isFunctionDefinition()) { 11858 // C++ [class.friend]p6: 11859 // A function can be defined in a friend declaration of a class if and 11860 // only if the class is a non-local class (9.8), the function name is 11861 // unqualified, and the function has namespace scope. 11862 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 11863 << SS.getScopeRep(); 11864 } 11865 11866 DC = CurContext; 11867 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 11868 } 11869 11870 if (!DC->isRecord()) { 11871 // This implies that it has to be an operator or function. 11872 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName || 11873 D.getName().getKind() == UnqualifiedId::IK_DestructorName || 11874 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) { 11875 Diag(Loc, diag::err_introducing_special_friend) << 11876 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 : 11877 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2); 11878 return 0; 11879 } 11880 } 11881 11882 // FIXME: This is an egregious hack to cope with cases where the scope stack 11883 // does not contain the declaration context, i.e., in an out-of-line 11884 // definition of a class. 11885 Scope FakeDCScope(S, Scope::DeclScope, Diags); 11886 if (!DCScope) { 11887 FakeDCScope.setEntity(DC); 11888 DCScope = &FakeDCScope; 11889 } 11890 11891 bool AddToScope = true; 11892 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 11893 TemplateParams, AddToScope); 11894 if (!ND) return 0; 11895 11896 assert(ND->getLexicalDeclContext() == CurContext); 11897 11898 // If we performed typo correction, we might have added a scope specifier 11899 // and changed the decl context. 11900 DC = ND->getDeclContext(); 11901 11902 // Add the function declaration to the appropriate lookup tables, 11903 // adjusting the redeclarations list as necessary. We don't 11904 // want to do this yet if the friending class is dependent. 11905 // 11906 // Also update the scope-based lookup if the target context's 11907 // lookup context is in lexical scope. 11908 if (!CurContext->isDependentContext()) { 11909 DC = DC->getRedeclContext(); 11910 DC->makeDeclVisibleInContext(ND); 11911 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 11912 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 11913 } 11914 11915 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 11916 D.getIdentifierLoc(), ND, 11917 DS.getFriendSpecLoc()); 11918 FrD->setAccess(AS_public); 11919 CurContext->addDecl(FrD); 11920 11921 if (ND->isInvalidDecl()) { 11922 FrD->setInvalidDecl(); 11923 } else { 11924 if (DC->isRecord()) CheckFriendAccess(ND); 11925 11926 FunctionDecl *FD; 11927 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 11928 FD = FTD->getTemplatedDecl(); 11929 else 11930 FD = cast<FunctionDecl>(ND); 11931 11932 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 11933 // default argument expression, that declaration shall be a definition 11934 // and shall be the only declaration of the function or function 11935 // template in the translation unit. 11936 if (functionDeclHasDefaultArgument(FD)) { 11937 if (FunctionDecl *OldFD = FD->getPreviousDecl()) { 11938 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 11939 Diag(OldFD->getLocation(), diag::note_previous_declaration); 11940 } else if (!D.isFunctionDefinition()) 11941 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 11942 } 11943 11944 // Mark templated-scope function declarations as unsupported. 11945 if (FD->getNumTemplateParameterLists()) 11946 FrD->setUnsupportedFriend(true); 11947 } 11948 11949 return ND; 11950} 11951 11952void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 11953 AdjustDeclIfTemplate(Dcl); 11954 11955 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 11956 if (!Fn) { 11957 Diag(DelLoc, diag::err_deleted_non_function); 11958 return; 11959 } 11960 11961 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 11962 // Don't consider the implicit declaration we generate for explicit 11963 // specializations. FIXME: Do not generate these implicit declarations. 11964 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization 11965 || Prev->getPreviousDecl()) && !Prev->isDefined()) { 11966 Diag(DelLoc, diag::err_deleted_decl_not_first); 11967 Diag(Prev->getLocation(), diag::note_previous_declaration); 11968 } 11969 // If the declaration wasn't the first, we delete the function anyway for 11970 // recovery. 11971 Fn = Fn->getCanonicalDecl(); 11972 } 11973 11974 if (Fn->isDeleted()) 11975 return; 11976 11977 // See if we're deleting a function which is already known to override a 11978 // non-deleted virtual function. 11979 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 11980 bool IssuedDiagnostic = false; 11981 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 11982 E = MD->end_overridden_methods(); 11983 I != E; ++I) { 11984 if (!(*MD->begin_overridden_methods())->isDeleted()) { 11985 if (!IssuedDiagnostic) { 11986 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 11987 IssuedDiagnostic = true; 11988 } 11989 Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 11990 } 11991 } 11992 } 11993 11994 Fn->setDeletedAsWritten(); 11995} 11996 11997void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 11998 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 11999 12000 if (MD) { 12001 if (MD->getParent()->isDependentType()) { 12002 MD->setDefaulted(); 12003 MD->setExplicitlyDefaulted(); 12004 return; 12005 } 12006 12007 CXXSpecialMember Member = getSpecialMember(MD); 12008 if (Member == CXXInvalid) { 12009 if (!MD->isInvalidDecl()) 12010 Diag(DefaultLoc, diag::err_default_special_members); 12011 return; 12012 } 12013 12014 MD->setDefaulted(); 12015 MD->setExplicitlyDefaulted(); 12016 12017 // If this definition appears within the record, do the checking when 12018 // the record is complete. 12019 const FunctionDecl *Primary = MD; 12020 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 12021 // Find the uninstantiated declaration that actually had the '= default' 12022 // on it. 12023 Pattern->isDefined(Primary); 12024 12025 // If the method was defaulted on its first declaration, we will have 12026 // already performed the checking in CheckCompletedCXXClass. Such a 12027 // declaration doesn't trigger an implicit definition. 12028 if (Primary == Primary->getCanonicalDecl()) 12029 return; 12030 12031 CheckExplicitlyDefaultedSpecialMember(MD); 12032 12033 // The exception specification is needed because we are defining the 12034 // function. 12035 ResolveExceptionSpec(DefaultLoc, 12036 MD->getType()->castAs<FunctionProtoType>()); 12037 12038 if (MD->isInvalidDecl()) 12039 return; 12040 12041 switch (Member) { 12042 case CXXDefaultConstructor: 12043 DefineImplicitDefaultConstructor(DefaultLoc, 12044 cast<CXXConstructorDecl>(MD)); 12045 break; 12046 case CXXCopyConstructor: 12047 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 12048 break; 12049 case CXXCopyAssignment: 12050 DefineImplicitCopyAssignment(DefaultLoc, MD); 12051 break; 12052 case CXXDestructor: 12053 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD)); 12054 break; 12055 case CXXMoveConstructor: 12056 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 12057 break; 12058 case CXXMoveAssignment: 12059 DefineImplicitMoveAssignment(DefaultLoc, MD); 12060 break; 12061 case CXXInvalid: 12062 llvm_unreachable("Invalid special member."); 12063 } 12064 } else { 12065 Diag(DefaultLoc, diag::err_default_special_members); 12066 } 12067} 12068 12069static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 12070 for (Stmt::child_range CI = S->children(); CI; ++CI) { 12071 Stmt *SubStmt = *CI; 12072 if (!SubStmt) 12073 continue; 12074 if (isa<ReturnStmt>(SubStmt)) 12075 Self.Diag(SubStmt->getLocStart(), 12076 diag::err_return_in_constructor_handler); 12077 if (!isa<Expr>(SubStmt)) 12078 SearchForReturnInStmt(Self, SubStmt); 12079 } 12080} 12081 12082void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 12083 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 12084 CXXCatchStmt *Handler = TryBlock->getHandler(I); 12085 SearchForReturnInStmt(*this, Handler); 12086 } 12087} 12088 12089bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 12090 const CXXMethodDecl *Old) { 12091 const FunctionType *NewFT = New->getType()->getAs<FunctionType>(); 12092 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>(); 12093 12094 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 12095 12096 // If the calling conventions match, everything is fine 12097 if (NewCC == OldCC) 12098 return false; 12099 12100 Diag(New->getLocation(), 12101 diag::err_conflicting_overriding_cc_attributes) 12102 << New->getDeclName() << New->getType() << Old->getType(); 12103 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12104 return true; 12105} 12106 12107bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 12108 const CXXMethodDecl *Old) { 12109 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType(); 12110 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType(); 12111 12112 if (Context.hasSameType(NewTy, OldTy) || 12113 NewTy->isDependentType() || OldTy->isDependentType()) 12114 return false; 12115 12116 // Check if the return types are covariant 12117 QualType NewClassTy, OldClassTy; 12118 12119 /// Both types must be pointers or references to classes. 12120 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 12121 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 12122 NewClassTy = NewPT->getPointeeType(); 12123 OldClassTy = OldPT->getPointeeType(); 12124 } 12125 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 12126 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 12127 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 12128 NewClassTy = NewRT->getPointeeType(); 12129 OldClassTy = OldRT->getPointeeType(); 12130 } 12131 } 12132 } 12133 12134 // The return types aren't either both pointers or references to a class type. 12135 if (NewClassTy.isNull()) { 12136 Diag(New->getLocation(), 12137 diag::err_different_return_type_for_overriding_virtual_function) 12138 << New->getDeclName() << NewTy << OldTy; 12139 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12140 12141 return true; 12142 } 12143 12144 // C++ [class.virtual]p6: 12145 // If the return type of D::f differs from the return type of B::f, the 12146 // class type in the return type of D::f shall be complete at the point of 12147 // declaration of D::f or shall be the class type D. 12148 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 12149 if (!RT->isBeingDefined() && 12150 RequireCompleteType(New->getLocation(), NewClassTy, 12151 diag::err_covariant_return_incomplete, 12152 New->getDeclName())) 12153 return true; 12154 } 12155 12156 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 12157 // Check if the new class derives from the old class. 12158 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 12159 Diag(New->getLocation(), 12160 diag::err_covariant_return_not_derived) 12161 << New->getDeclName() << NewTy << OldTy; 12162 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12163 return true; 12164 } 12165 12166 // Check if we the conversion from derived to base is valid. 12167 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy, 12168 diag::err_covariant_return_inaccessible_base, 12169 diag::err_covariant_return_ambiguous_derived_to_base_conv, 12170 // FIXME: Should this point to the return type? 12171 New->getLocation(), SourceRange(), New->getDeclName(), 0)) { 12172 // FIXME: this note won't trigger for delayed access control 12173 // diagnostics, and it's impossible to get an undelayed error 12174 // here from access control during the original parse because 12175 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 12176 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12177 return true; 12178 } 12179 } 12180 12181 // The qualifiers of the return types must be the same. 12182 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 12183 Diag(New->getLocation(), 12184 diag::err_covariant_return_type_different_qualifications) 12185 << New->getDeclName() << NewTy << OldTy; 12186 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12187 return true; 12188 }; 12189 12190 12191 // The new class type must have the same or less qualifiers as the old type. 12192 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 12193 Diag(New->getLocation(), 12194 diag::err_covariant_return_type_class_type_more_qualified) 12195 << New->getDeclName() << NewTy << OldTy; 12196 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12197 return true; 12198 }; 12199 12200 return false; 12201} 12202 12203/// \brief Mark the given method pure. 12204/// 12205/// \param Method the method to be marked pure. 12206/// 12207/// \param InitRange the source range that covers the "0" initializer. 12208bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 12209 SourceLocation EndLoc = InitRange.getEnd(); 12210 if (EndLoc.isValid()) 12211 Method->setRangeEnd(EndLoc); 12212 12213 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 12214 Method->setPure(); 12215 return false; 12216 } 12217 12218 if (!Method->isInvalidDecl()) 12219 Diag(Method->getLocation(), diag::err_non_virtual_pure) 12220 << Method->getDeclName() << InitRange; 12221 return true; 12222} 12223 12224/// \brief Determine whether the given declaration is a static data member. 12225static bool isStaticDataMember(const Decl *D) { 12226 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 12227 return Var->isStaticDataMember(); 12228 12229 return false; 12230} 12231 12232/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 12233/// an initializer for the out-of-line declaration 'Dcl'. The scope 12234/// is a fresh scope pushed for just this purpose. 12235/// 12236/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 12237/// static data member of class X, names should be looked up in the scope of 12238/// class X. 12239void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 12240 // If there is no declaration, there was an error parsing it. 12241 if (D == 0 || D->isInvalidDecl()) return; 12242 12243 // We should only get called for declarations with scope specifiers, like: 12244 // int foo::bar; 12245 assert(D->isOutOfLine()); 12246 EnterDeclaratorContext(S, D->getDeclContext()); 12247 12248 // If we are parsing the initializer for a static data member, push a 12249 // new expression evaluation context that is associated with this static 12250 // data member. 12251 if (isStaticDataMember(D)) 12252 PushExpressionEvaluationContext(PotentiallyEvaluated, D); 12253} 12254 12255/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 12256/// initializer for the out-of-line declaration 'D'. 12257void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 12258 // If there is no declaration, there was an error parsing it. 12259 if (D == 0 || D->isInvalidDecl()) return; 12260 12261 if (isStaticDataMember(D)) 12262 PopExpressionEvaluationContext(); 12263 12264 assert(D->isOutOfLine()); 12265 ExitDeclaratorContext(S); 12266} 12267 12268/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 12269/// C++ if/switch/while/for statement. 12270/// e.g: "if (int x = f()) {...}" 12271DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 12272 // C++ 6.4p2: 12273 // The declarator shall not specify a function or an array. 12274 // The type-specifier-seq shall not contain typedef and shall not declare a 12275 // new class or enumeration. 12276 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 12277 "Parser allowed 'typedef' as storage class of condition decl."); 12278 12279 Decl *Dcl = ActOnDeclarator(S, D); 12280 if (!Dcl) 12281 return true; 12282 12283 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 12284 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 12285 << D.getSourceRange(); 12286 return true; 12287 } 12288 12289 return Dcl; 12290} 12291 12292void Sema::LoadExternalVTableUses() { 12293 if (!ExternalSource) 12294 return; 12295 12296 SmallVector<ExternalVTableUse, 4> VTables; 12297 ExternalSource->ReadUsedVTables(VTables); 12298 SmallVector<VTableUse, 4> NewUses; 12299 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 12300 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 12301 = VTablesUsed.find(VTables[I].Record); 12302 // Even if a definition wasn't required before, it may be required now. 12303 if (Pos != VTablesUsed.end()) { 12304 if (!Pos->second && VTables[I].DefinitionRequired) 12305 Pos->second = true; 12306 continue; 12307 } 12308 12309 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 12310 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 12311 } 12312 12313 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 12314} 12315 12316void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 12317 bool DefinitionRequired) { 12318 // Ignore any vtable uses in unevaluated operands or for classes that do 12319 // not have a vtable. 12320 if (!Class->isDynamicClass() || Class->isDependentContext() || 12321 CurContext->isDependentContext() || isUnevaluatedContext()) 12322 return; 12323 12324 // Try to insert this class into the map. 12325 LoadExternalVTableUses(); 12326 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 12327 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 12328 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 12329 if (!Pos.second) { 12330 // If we already had an entry, check to see if we are promoting this vtable 12331 // to required a definition. If so, we need to reappend to the VTableUses 12332 // list, since we may have already processed the first entry. 12333 if (DefinitionRequired && !Pos.first->second) { 12334 Pos.first->second = true; 12335 } else { 12336 // Otherwise, we can early exit. 12337 return; 12338 } 12339 } 12340 12341 // Local classes need to have their virtual members marked 12342 // immediately. For all other classes, we mark their virtual members 12343 // at the end of the translation unit. 12344 if (Class->isLocalClass()) 12345 MarkVirtualMembersReferenced(Loc, Class); 12346 else 12347 VTableUses.push_back(std::make_pair(Class, Loc)); 12348} 12349 12350bool Sema::DefineUsedVTables() { 12351 LoadExternalVTableUses(); 12352 if (VTableUses.empty()) 12353 return false; 12354 12355 // Note: The VTableUses vector could grow as a result of marking 12356 // the members of a class as "used", so we check the size each 12357 // time through the loop and prefer indices (which are stable) to 12358 // iterators (which are not). 12359 bool DefinedAnything = false; 12360 for (unsigned I = 0; I != VTableUses.size(); ++I) { 12361 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 12362 if (!Class) 12363 continue; 12364 12365 SourceLocation Loc = VTableUses[I].second; 12366 12367 bool DefineVTable = true; 12368 12369 // If this class has a key function, but that key function is 12370 // defined in another translation unit, we don't need to emit the 12371 // vtable even though we're using it. 12372 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 12373 if (KeyFunction && !KeyFunction->hasBody()) { 12374 // The key function is in another translation unit. 12375 DefineVTable = false; 12376 TemplateSpecializationKind TSK = 12377 KeyFunction->getTemplateSpecializationKind(); 12378 assert(TSK != TSK_ExplicitInstantiationDefinition && 12379 TSK != TSK_ImplicitInstantiation && 12380 "Instantiations don't have key functions"); 12381 (void)TSK; 12382 } else if (!KeyFunction) { 12383 // If we have a class with no key function that is the subject 12384 // of an explicit instantiation declaration, suppress the 12385 // vtable; it will live with the explicit instantiation 12386 // definition. 12387 bool IsExplicitInstantiationDeclaration 12388 = Class->getTemplateSpecializationKind() 12389 == TSK_ExplicitInstantiationDeclaration; 12390 for (TagDecl::redecl_iterator R = Class->redecls_begin(), 12391 REnd = Class->redecls_end(); 12392 R != REnd; ++R) { 12393 TemplateSpecializationKind TSK 12394 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind(); 12395 if (TSK == TSK_ExplicitInstantiationDeclaration) 12396 IsExplicitInstantiationDeclaration = true; 12397 else if (TSK == TSK_ExplicitInstantiationDefinition) { 12398 IsExplicitInstantiationDeclaration = false; 12399 break; 12400 } 12401 } 12402 12403 if (IsExplicitInstantiationDeclaration) 12404 DefineVTable = false; 12405 } 12406 12407 // The exception specifications for all virtual members may be needed even 12408 // if we are not providing an authoritative form of the vtable in this TU. 12409 // We may choose to emit it available_externally anyway. 12410 if (!DefineVTable) { 12411 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 12412 continue; 12413 } 12414 12415 // Mark all of the virtual members of this class as referenced, so 12416 // that we can build a vtable. Then, tell the AST consumer that a 12417 // vtable for this class is required. 12418 DefinedAnything = true; 12419 MarkVirtualMembersReferenced(Loc, Class); 12420 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 12421 Consumer.HandleVTable(Class, VTablesUsed[Canonical]); 12422 12423 // Optionally warn if we're emitting a weak vtable. 12424 if (Class->isExternallyVisible() && 12425 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) { 12426 const FunctionDecl *KeyFunctionDef = 0; 12427 if (!KeyFunction || 12428 (KeyFunction->hasBody(KeyFunctionDef) && 12429 KeyFunctionDef->isInlined())) 12430 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() == 12431 TSK_ExplicitInstantiationDefinition 12432 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable) 12433 << Class; 12434 } 12435 } 12436 VTableUses.clear(); 12437 12438 return DefinedAnything; 12439} 12440 12441void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 12442 const CXXRecordDecl *RD) { 12443 for (CXXRecordDecl::method_iterator I = RD->method_begin(), 12444 E = RD->method_end(); I != E; ++I) 12445 if ((*I)->isVirtual() && !(*I)->isPure()) 12446 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>()); 12447} 12448 12449void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 12450 const CXXRecordDecl *RD) { 12451 // Mark all functions which will appear in RD's vtable as used. 12452 CXXFinalOverriderMap FinalOverriders; 12453 RD->getFinalOverriders(FinalOverriders); 12454 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 12455 E = FinalOverriders.end(); 12456 I != E; ++I) { 12457 for (OverridingMethods::const_iterator OI = I->second.begin(), 12458 OE = I->second.end(); 12459 OI != OE; ++OI) { 12460 assert(OI->second.size() > 0 && "no final overrider"); 12461 CXXMethodDecl *Overrider = OI->second.front().Method; 12462 12463 // C++ [basic.def.odr]p2: 12464 // [...] A virtual member function is used if it is not pure. [...] 12465 if (!Overrider->isPure()) 12466 MarkFunctionReferenced(Loc, Overrider); 12467 } 12468 } 12469 12470 // Only classes that have virtual bases need a VTT. 12471 if (RD->getNumVBases() == 0) 12472 return; 12473 12474 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(), 12475 e = RD->bases_end(); i != e; ++i) { 12476 const CXXRecordDecl *Base = 12477 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl()); 12478 if (Base->getNumVBases() == 0) 12479 continue; 12480 MarkVirtualMembersReferenced(Loc, Base); 12481 } 12482} 12483 12484/// SetIvarInitializers - This routine builds initialization ASTs for the 12485/// Objective-C implementation whose ivars need be initialized. 12486void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 12487 if (!getLangOpts().CPlusPlus) 12488 return; 12489 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 12490 SmallVector<ObjCIvarDecl*, 8> ivars; 12491 CollectIvarsToConstructOrDestruct(OID, ivars); 12492 if (ivars.empty()) 12493 return; 12494 SmallVector<CXXCtorInitializer*, 32> AllToInit; 12495 for (unsigned i = 0; i < ivars.size(); i++) { 12496 FieldDecl *Field = ivars[i]; 12497 if (Field->isInvalidDecl()) 12498 continue; 12499 12500 CXXCtorInitializer *Member; 12501 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 12502 InitializationKind InitKind = 12503 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 12504 12505 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 12506 ExprResult MemberInit = 12507 InitSeq.Perform(*this, InitEntity, InitKind, None); 12508 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 12509 // Note, MemberInit could actually come back empty if no initialization 12510 // is required (e.g., because it would call a trivial default constructor) 12511 if (!MemberInit.get() || MemberInit.isInvalid()) 12512 continue; 12513 12514 Member = 12515 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 12516 SourceLocation(), 12517 MemberInit.takeAs<Expr>(), 12518 SourceLocation()); 12519 AllToInit.push_back(Member); 12520 12521 // Be sure that the destructor is accessible and is marked as referenced. 12522 if (const RecordType *RecordTy 12523 = Context.getBaseElementType(Field->getType()) 12524 ->getAs<RecordType>()) { 12525 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 12526 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 12527 MarkFunctionReferenced(Field->getLocation(), Destructor); 12528 CheckDestructorAccess(Field->getLocation(), Destructor, 12529 PDiag(diag::err_access_dtor_ivar) 12530 << Context.getBaseElementType(Field->getType())); 12531 } 12532 } 12533 } 12534 ObjCImplementation->setIvarInitializers(Context, 12535 AllToInit.data(), AllToInit.size()); 12536 } 12537} 12538 12539static 12540void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 12541 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid, 12542 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid, 12543 llvm::SmallSet<CXXConstructorDecl*, 4> &Current, 12544 Sema &S) { 12545 if (Ctor->isInvalidDecl()) 12546 return; 12547 12548 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 12549 12550 // Target may not be determinable yet, for instance if this is a dependent 12551 // call in an uninstantiated template. 12552 if (Target) { 12553 const FunctionDecl *FNTarget = 0; 12554 (void)Target->hasBody(FNTarget); 12555 Target = const_cast<CXXConstructorDecl*>( 12556 cast_or_null<CXXConstructorDecl>(FNTarget)); 12557 } 12558 12559 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 12560 // Avoid dereferencing a null pointer here. 12561 *TCanonical = Target ? Target->getCanonicalDecl() : 0; 12562 12563 if (!Current.insert(Canonical)) 12564 return; 12565 12566 // We know that beyond here, we aren't chaining into a cycle. 12567 if (!Target || !Target->isDelegatingConstructor() || 12568 Target->isInvalidDecl() || Valid.count(TCanonical)) { 12569 Valid.insert(Current.begin(), Current.end()); 12570 Current.clear(); 12571 // We've hit a cycle. 12572 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 12573 Current.count(TCanonical)) { 12574 // If we haven't diagnosed this cycle yet, do so now. 12575 if (!Invalid.count(TCanonical)) { 12576 S.Diag((*Ctor->init_begin())->getSourceLocation(), 12577 diag::warn_delegating_ctor_cycle) 12578 << Ctor; 12579 12580 // Don't add a note for a function delegating directly to itself. 12581 if (TCanonical != Canonical) 12582 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 12583 12584 CXXConstructorDecl *C = Target; 12585 while (C->getCanonicalDecl() != Canonical) { 12586 const FunctionDecl *FNTarget = 0; 12587 (void)C->getTargetConstructor()->hasBody(FNTarget); 12588 assert(FNTarget && "Ctor cycle through bodiless function"); 12589 12590 C = const_cast<CXXConstructorDecl*>( 12591 cast<CXXConstructorDecl>(FNTarget)); 12592 S.Diag(C->getLocation(), diag::note_which_delegates_to); 12593 } 12594 } 12595 12596 Invalid.insert(Current.begin(), Current.end()); 12597 Current.clear(); 12598 } else { 12599 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 12600 } 12601} 12602 12603 12604void Sema::CheckDelegatingCtorCycles() { 12605 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 12606 12607 for (DelegatingCtorDeclsType::iterator 12608 I = DelegatingCtorDecls.begin(ExternalSource), 12609 E = DelegatingCtorDecls.end(); 12610 I != E; ++I) 12611 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 12612 12613 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(), 12614 CE = Invalid.end(); 12615 CI != CE; ++CI) 12616 (*CI)->setInvalidDecl(); 12617} 12618 12619namespace { 12620 /// \brief AST visitor that finds references to the 'this' expression. 12621 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 12622 Sema &S; 12623 12624 public: 12625 explicit FindCXXThisExpr(Sema &S) : S(S) { } 12626 12627 bool VisitCXXThisExpr(CXXThisExpr *E) { 12628 S.Diag(E->getLocation(), diag::err_this_static_member_func) 12629 << E->isImplicit(); 12630 return false; 12631 } 12632 }; 12633} 12634 12635bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 12636 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 12637 if (!TSInfo) 12638 return false; 12639 12640 TypeLoc TL = TSInfo->getTypeLoc(); 12641 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 12642 if (!ProtoTL) 12643 return false; 12644 12645 // C++11 [expr.prim.general]p3: 12646 // [The expression this] shall not appear before the optional 12647 // cv-qualifier-seq and it shall not appear within the declaration of a 12648 // static member function (although its type and value category are defined 12649 // within a static member function as they are within a non-static member 12650 // function). [ Note: this is because declaration matching does not occur 12651 // until the complete declarator is known. - end note ] 12652 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 12653 FindCXXThisExpr Finder(*this); 12654 12655 // If the return type came after the cv-qualifier-seq, check it now. 12656 if (Proto->hasTrailingReturn() && 12657 !Finder.TraverseTypeLoc(ProtoTL.getResultLoc())) 12658 return true; 12659 12660 // Check the exception specification. 12661 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 12662 return true; 12663 12664 return checkThisInStaticMemberFunctionAttributes(Method); 12665} 12666 12667bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 12668 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 12669 if (!TSInfo) 12670 return false; 12671 12672 TypeLoc TL = TSInfo->getTypeLoc(); 12673 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 12674 if (!ProtoTL) 12675 return false; 12676 12677 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 12678 FindCXXThisExpr Finder(*this); 12679 12680 switch (Proto->getExceptionSpecType()) { 12681 case EST_Uninstantiated: 12682 case EST_Unevaluated: 12683 case EST_BasicNoexcept: 12684 case EST_DynamicNone: 12685 case EST_MSAny: 12686 case EST_None: 12687 break; 12688 12689 case EST_ComputedNoexcept: 12690 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 12691 return true; 12692 12693 case EST_Dynamic: 12694 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(), 12695 EEnd = Proto->exception_end(); 12696 E != EEnd; ++E) { 12697 if (!Finder.TraverseType(*E)) 12698 return true; 12699 } 12700 break; 12701 } 12702 12703 return false; 12704} 12705 12706bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 12707 FindCXXThisExpr Finder(*this); 12708 12709 // Check attributes. 12710 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end(); 12711 A != AEnd; ++A) { 12712 // FIXME: This should be emitted by tblgen. 12713 Expr *Arg = 0; 12714 ArrayRef<Expr *> Args; 12715 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A)) 12716 Arg = G->getArg(); 12717 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A)) 12718 Arg = G->getArg(); 12719 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A)) 12720 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size()); 12721 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A)) 12722 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size()); 12723 else if (ExclusiveLockFunctionAttr *ELF 12724 = dyn_cast<ExclusiveLockFunctionAttr>(*A)) 12725 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size()); 12726 else if (SharedLockFunctionAttr *SLF 12727 = dyn_cast<SharedLockFunctionAttr>(*A)) 12728 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size()); 12729 else if (ExclusiveTrylockFunctionAttr *ETLF 12730 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) { 12731 Arg = ETLF->getSuccessValue(); 12732 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size()); 12733 } else if (SharedTrylockFunctionAttr *STLF 12734 = dyn_cast<SharedTrylockFunctionAttr>(*A)) { 12735 Arg = STLF->getSuccessValue(); 12736 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size()); 12737 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A)) 12738 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size()); 12739 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A)) 12740 Arg = LR->getArg(); 12741 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A)) 12742 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size()); 12743 else if (ExclusiveLocksRequiredAttr *ELR 12744 = dyn_cast<ExclusiveLocksRequiredAttr>(*A)) 12745 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size()); 12746 else if (SharedLocksRequiredAttr *SLR 12747 = dyn_cast<SharedLocksRequiredAttr>(*A)) 12748 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size()); 12749 12750 if (Arg && !Finder.TraverseStmt(Arg)) 12751 return true; 12752 12753 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 12754 if (!Finder.TraverseStmt(Args[I])) 12755 return true; 12756 } 12757 } 12758 12759 return false; 12760} 12761 12762void 12763Sema::checkExceptionSpecification(ExceptionSpecificationType EST, 12764 ArrayRef<ParsedType> DynamicExceptions, 12765 ArrayRef<SourceRange> DynamicExceptionRanges, 12766 Expr *NoexceptExpr, 12767 SmallVectorImpl<QualType> &Exceptions, 12768 FunctionProtoType::ExtProtoInfo &EPI) { 12769 Exceptions.clear(); 12770 EPI.ExceptionSpecType = EST; 12771 if (EST == EST_Dynamic) { 12772 Exceptions.reserve(DynamicExceptions.size()); 12773 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 12774 // FIXME: Preserve type source info. 12775 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 12776 12777 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 12778 collectUnexpandedParameterPacks(ET, Unexpanded); 12779 if (!Unexpanded.empty()) { 12780 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(), 12781 UPPC_ExceptionType, 12782 Unexpanded); 12783 continue; 12784 } 12785 12786 // Check that the type is valid for an exception spec, and 12787 // drop it if not. 12788 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 12789 Exceptions.push_back(ET); 12790 } 12791 EPI.NumExceptions = Exceptions.size(); 12792 EPI.Exceptions = Exceptions.data(); 12793 return; 12794 } 12795 12796 if (EST == EST_ComputedNoexcept) { 12797 // If an error occurred, there's no expression here. 12798 if (NoexceptExpr) { 12799 assert((NoexceptExpr->isTypeDependent() || 12800 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 12801 Context.BoolTy) && 12802 "Parser should have made sure that the expression is boolean"); 12803 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 12804 EPI.ExceptionSpecType = EST_BasicNoexcept; 12805 return; 12806 } 12807 12808 if (!NoexceptExpr->isValueDependent()) 12809 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0, 12810 diag::err_noexcept_needs_constant_expression, 12811 /*AllowFold*/ false).take(); 12812 EPI.NoexceptExpr = NoexceptExpr; 12813 } 12814 return; 12815 } 12816} 12817 12818/// IdentifyCUDATarget - Determine the CUDA compilation target for this function 12819Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) { 12820 // Implicitly declared functions (e.g. copy constructors) are 12821 // __host__ __device__ 12822 if (D->isImplicit()) 12823 return CFT_HostDevice; 12824 12825 if (D->hasAttr<CUDAGlobalAttr>()) 12826 return CFT_Global; 12827 12828 if (D->hasAttr<CUDADeviceAttr>()) { 12829 if (D->hasAttr<CUDAHostAttr>()) 12830 return CFT_HostDevice; 12831 return CFT_Device; 12832 } 12833 12834 return CFT_Host; 12835} 12836 12837bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget, 12838 CUDAFunctionTarget CalleeTarget) { 12839 // CUDA B.1.1 "The __device__ qualifier declares a function that is... 12840 // Callable from the device only." 12841 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device) 12842 return true; 12843 12844 // CUDA B.1.2 "The __global__ qualifier declares a function that is... 12845 // Callable from the host only." 12846 // CUDA B.1.3 "The __host__ qualifier declares a function that is... 12847 // Callable from the host only." 12848 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) && 12849 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global)) 12850 return true; 12851 12852 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice) 12853 return true; 12854 12855 return false; 12856} 12857 12858/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 12859/// 12860MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 12861 SourceLocation DeclStart, 12862 Declarator &D, Expr *BitWidth, 12863 InClassInitStyle InitStyle, 12864 AccessSpecifier AS, 12865 AttributeList *MSPropertyAttr) { 12866 IdentifierInfo *II = D.getIdentifier(); 12867 if (!II) { 12868 Diag(DeclStart, diag::err_anonymous_property); 12869 return NULL; 12870 } 12871 SourceLocation Loc = D.getIdentifierLoc(); 12872 12873 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12874 QualType T = TInfo->getType(); 12875 if (getLangOpts().CPlusPlus) { 12876 CheckExtraCXXDefaultArguments(D); 12877 12878 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 12879 UPPC_DataMemberType)) { 12880 D.setInvalidType(); 12881 T = Context.IntTy; 12882 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 12883 } 12884 } 12885 12886 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 12887 12888 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 12889 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 12890 diag::err_invalid_thread) 12891 << DeclSpec::getSpecifierName(TSCS); 12892 12893 // Check to see if this name was declared as a member previously 12894 NamedDecl *PrevDecl = 0; 12895 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 12896 LookupName(Previous, S); 12897 switch (Previous.getResultKind()) { 12898 case LookupResult::Found: 12899 case LookupResult::FoundUnresolvedValue: 12900 PrevDecl = Previous.getAsSingle<NamedDecl>(); 12901 break; 12902 12903 case LookupResult::FoundOverloaded: 12904 PrevDecl = Previous.getRepresentativeDecl(); 12905 break; 12906 12907 case LookupResult::NotFound: 12908 case LookupResult::NotFoundInCurrentInstantiation: 12909 case LookupResult::Ambiguous: 12910 break; 12911 } 12912 12913 if (PrevDecl && PrevDecl->isTemplateParameter()) { 12914 // Maybe we will complain about the shadowed template parameter. 12915 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 12916 // Just pretend that we didn't see the previous declaration. 12917 PrevDecl = 0; 12918 } 12919 12920 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 12921 PrevDecl = 0; 12922 12923 SourceLocation TSSL = D.getLocStart(); 12924 MSPropertyDecl *NewPD; 12925 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData(); 12926 NewPD = new (Context) MSPropertyDecl(Record, Loc, 12927 II, T, TInfo, TSSL, 12928 Data.GetterId, Data.SetterId); 12929 ProcessDeclAttributes(TUScope, NewPD, D); 12930 NewPD->setAccess(AS); 12931 12932 if (NewPD->isInvalidDecl()) 12933 Record->setInvalidDecl(); 12934 12935 if (D.getDeclSpec().isModulePrivateSpecified()) 12936 NewPD->setModulePrivate(); 12937 12938 if (NewPD->isInvalidDecl() && PrevDecl) { 12939 // Don't introduce NewFD into scope; there's already something 12940 // with the same name in the same scope. 12941 } else if (II) { 12942 PushOnScopeChains(NewPD, S); 12943 } else 12944 Record->addDecl(NewPD); 12945 12946 return NewPD; 12947} 12948