SemaDeclCXX.cpp revision 3a45c0e61dfc19f27b8ebcb15dd70159a36f1f9a
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/Sema/CXXFieldCollector.h" 16#include "clang/Sema/Scope.h" 17#include "clang/Sema/Initialization.h" 18#include "clang/Sema/Lookup.h" 19#include "clang/Sema/ScopeInfo.h" 20#include "clang/AST/ASTConsumer.h" 21#include "clang/AST/ASTContext.h" 22#include "clang/AST/ASTMutationListener.h" 23#include "clang/AST/CharUnits.h" 24#include "clang/AST/CXXInheritance.h" 25#include "clang/AST/DeclVisitor.h" 26#include "clang/AST/ExprCXX.h" 27#include "clang/AST/RecordLayout.h" 28#include "clang/AST/StmtVisitor.h" 29#include "clang/AST/TypeLoc.h" 30#include "clang/AST/TypeOrdering.h" 31#include "clang/Sema/DeclSpec.h" 32#include "clang/Sema/ParsedTemplate.h" 33#include "clang/Basic/PartialDiagnostic.h" 34#include "clang/Lex/Preprocessor.h" 35#include "llvm/ADT/DenseSet.h" 36#include "llvm/ADT/SmallString.h" 37#include "llvm/ADT/STLExtras.h" 38#include <map> 39#include <set> 40 41using namespace clang; 42 43//===----------------------------------------------------------------------===// 44// CheckDefaultArgumentVisitor 45//===----------------------------------------------------------------------===// 46 47namespace { 48 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 49 /// the default argument of a parameter to determine whether it 50 /// contains any ill-formed subexpressions. For example, this will 51 /// diagnose the use of local variables or parameters within the 52 /// default argument expression. 53 class CheckDefaultArgumentVisitor 54 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 55 Expr *DefaultArg; 56 Sema *S; 57 58 public: 59 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 60 : DefaultArg(defarg), S(s) {} 61 62 bool VisitExpr(Expr *Node); 63 bool VisitDeclRefExpr(DeclRefExpr *DRE); 64 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 65 bool VisitLambdaExpr(LambdaExpr *Lambda); 66 }; 67 68 /// VisitExpr - Visit all of the children of this expression. 69 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 70 bool IsInvalid = false; 71 for (Stmt::child_range I = Node->children(); I; ++I) 72 IsInvalid |= Visit(*I); 73 return IsInvalid; 74 } 75 76 /// VisitDeclRefExpr - Visit a reference to a declaration, to 77 /// determine whether this declaration can be used in the default 78 /// argument expression. 79 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 80 NamedDecl *Decl = DRE->getDecl(); 81 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 82 // C++ [dcl.fct.default]p9 83 // Default arguments are evaluated each time the function is 84 // called. The order of evaluation of function arguments is 85 // unspecified. Consequently, parameters of a function shall not 86 // be used in default argument expressions, even if they are not 87 // evaluated. Parameters of a function declared before a default 88 // argument expression are in scope and can hide namespace and 89 // class member names. 90 return S->Diag(DRE->getSourceRange().getBegin(), 91 diag::err_param_default_argument_references_param) 92 << Param->getDeclName() << DefaultArg->getSourceRange(); 93 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 94 // C++ [dcl.fct.default]p7 95 // Local variables shall not be used in default argument 96 // expressions. 97 if (VDecl->isLocalVarDecl()) 98 return S->Diag(DRE->getSourceRange().getBegin(), 99 diag::err_param_default_argument_references_local) 100 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 101 } 102 103 return false; 104 } 105 106 /// VisitCXXThisExpr - Visit a C++ "this" expression. 107 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 108 // C++ [dcl.fct.default]p8: 109 // The keyword this shall not be used in a default argument of a 110 // member function. 111 return S->Diag(ThisE->getSourceRange().getBegin(), 112 diag::err_param_default_argument_references_this) 113 << ThisE->getSourceRange(); 114 } 115 116 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) { 117 // C++11 [expr.lambda.prim]p13: 118 // A lambda-expression appearing in a default argument shall not 119 // implicitly or explicitly capture any entity. 120 if (Lambda->capture_begin() == Lambda->capture_end()) 121 return false; 122 123 return S->Diag(Lambda->getLocStart(), 124 diag::err_lambda_capture_default_arg); 125 } 126} 127 128void Sema::ImplicitExceptionSpecification::CalledDecl(CXXMethodDecl *Method) { 129 assert(Context && "ImplicitExceptionSpecification without an ASTContext"); 130 // If we have an MSAny or unknown spec already, don't bother. 131 if (!Method || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed) 132 return; 133 134 const FunctionProtoType *Proto 135 = Method->getType()->getAs<FunctionProtoType>(); 136 137 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 138 139 // If this function can throw any exceptions, make a note of that. 140 if (EST == EST_Delayed || EST == EST_MSAny || EST == EST_None) { 141 ClearExceptions(); 142 ComputedEST = EST; 143 return; 144 } 145 146 // FIXME: If the call to this decl is using any of its default arguments, we 147 // need to search them for potentially-throwing calls. 148 149 // If this function has a basic noexcept, it doesn't affect the outcome. 150 if (EST == EST_BasicNoexcept) 151 return; 152 153 // If we have a throw-all spec at this point, ignore the function. 154 if (ComputedEST == EST_None) 155 return; 156 157 // If we're still at noexcept(true) and there's a nothrow() callee, 158 // change to that specification. 159 if (EST == EST_DynamicNone) { 160 if (ComputedEST == EST_BasicNoexcept) 161 ComputedEST = EST_DynamicNone; 162 return; 163 } 164 165 // Check out noexcept specs. 166 if (EST == EST_ComputedNoexcept) { 167 FunctionProtoType::NoexceptResult NR = Proto->getNoexceptSpec(*Context); 168 assert(NR != FunctionProtoType::NR_NoNoexcept && 169 "Must have noexcept result for EST_ComputedNoexcept."); 170 assert(NR != FunctionProtoType::NR_Dependent && 171 "Should not generate implicit declarations for dependent cases, " 172 "and don't know how to handle them anyway."); 173 174 // noexcept(false) -> no spec on the new function 175 if (NR == FunctionProtoType::NR_Throw) { 176 ClearExceptions(); 177 ComputedEST = EST_None; 178 } 179 // noexcept(true) won't change anything either. 180 return; 181 } 182 183 assert(EST == EST_Dynamic && "EST case not considered earlier."); 184 assert(ComputedEST != EST_None && 185 "Shouldn't collect exceptions when throw-all is guaranteed."); 186 ComputedEST = EST_Dynamic; 187 // Record the exceptions in this function's exception specification. 188 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(), 189 EEnd = Proto->exception_end(); 190 E != EEnd; ++E) 191 if (ExceptionsSeen.insert(Context->getCanonicalType(*E))) 192 Exceptions.push_back(*E); 193} 194 195void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) { 196 if (!E || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed) 197 return; 198 199 // FIXME: 200 // 201 // C++0x [except.spec]p14: 202 // [An] implicit exception-specification specifies the type-id T if and 203 // only if T is allowed by the exception-specification of a function directly 204 // invoked by f's implicit definition; f shall allow all exceptions if any 205 // function it directly invokes allows all exceptions, and f shall allow no 206 // exceptions if every function it directly invokes allows no exceptions. 207 // 208 // Note in particular that if an implicit exception-specification is generated 209 // for a function containing a throw-expression, that specification can still 210 // be noexcept(true). 211 // 212 // Note also that 'directly invoked' is not defined in the standard, and there 213 // is no indication that we should only consider potentially-evaluated calls. 214 // 215 // Ultimately we should implement the intent of the standard: the exception 216 // specification should be the set of exceptions which can be thrown by the 217 // implicit definition. For now, we assume that any non-nothrow expression can 218 // throw any exception. 219 220 if (E->CanThrow(*Context)) 221 ComputedEST = EST_None; 222} 223 224bool 225Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 226 SourceLocation EqualLoc) { 227 if (RequireCompleteType(Param->getLocation(), Param->getType(), 228 diag::err_typecheck_decl_incomplete_type)) { 229 Param->setInvalidDecl(); 230 return true; 231 } 232 233 // C++ [dcl.fct.default]p5 234 // A default argument expression is implicitly converted (clause 235 // 4) to the parameter type. The default argument expression has 236 // the same semantic constraints as the initializer expression in 237 // a declaration of a variable of the parameter type, using the 238 // copy-initialization semantics (8.5). 239 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 240 Param); 241 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 242 EqualLoc); 243 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1); 244 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, 245 MultiExprArg(*this, &Arg, 1)); 246 if (Result.isInvalid()) 247 return true; 248 Arg = Result.takeAs<Expr>(); 249 250 CheckImplicitConversions(Arg, EqualLoc); 251 Arg = MaybeCreateExprWithCleanups(Arg); 252 253 // Okay: add the default argument to the parameter 254 Param->setDefaultArg(Arg); 255 256 // We have already instantiated this parameter; provide each of the 257 // instantiations with the uninstantiated default argument. 258 UnparsedDefaultArgInstantiationsMap::iterator InstPos 259 = UnparsedDefaultArgInstantiations.find(Param); 260 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 261 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 262 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 263 264 // We're done tracking this parameter's instantiations. 265 UnparsedDefaultArgInstantiations.erase(InstPos); 266 } 267 268 return false; 269} 270 271/// ActOnParamDefaultArgument - Check whether the default argument 272/// provided for a function parameter is well-formed. If so, attach it 273/// to the parameter declaration. 274void 275Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 276 Expr *DefaultArg) { 277 if (!param || !DefaultArg) 278 return; 279 280 ParmVarDecl *Param = cast<ParmVarDecl>(param); 281 UnparsedDefaultArgLocs.erase(Param); 282 283 // Default arguments are only permitted in C++ 284 if (!getLangOptions().CPlusPlus) { 285 Diag(EqualLoc, diag::err_param_default_argument) 286 << DefaultArg->getSourceRange(); 287 Param->setInvalidDecl(); 288 return; 289 } 290 291 // Check for unexpanded parameter packs. 292 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 293 Param->setInvalidDecl(); 294 return; 295 } 296 297 // Check that the default argument is well-formed 298 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this); 299 if (DefaultArgChecker.Visit(DefaultArg)) { 300 Param->setInvalidDecl(); 301 return; 302 } 303 304 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 305} 306 307/// ActOnParamUnparsedDefaultArgument - We've seen a default 308/// argument for a function parameter, but we can't parse it yet 309/// because we're inside a class definition. Note that this default 310/// argument will be parsed later. 311void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 312 SourceLocation EqualLoc, 313 SourceLocation ArgLoc) { 314 if (!param) 315 return; 316 317 ParmVarDecl *Param = cast<ParmVarDecl>(param); 318 if (Param) 319 Param->setUnparsedDefaultArg(); 320 321 UnparsedDefaultArgLocs[Param] = ArgLoc; 322} 323 324/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 325/// the default argument for the parameter param failed. 326void Sema::ActOnParamDefaultArgumentError(Decl *param) { 327 if (!param) 328 return; 329 330 ParmVarDecl *Param = cast<ParmVarDecl>(param); 331 332 Param->setInvalidDecl(); 333 334 UnparsedDefaultArgLocs.erase(Param); 335} 336 337/// CheckExtraCXXDefaultArguments - Check for any extra default 338/// arguments in the declarator, which is not a function declaration 339/// or definition and therefore is not permitted to have default 340/// arguments. This routine should be invoked for every declarator 341/// that is not a function declaration or definition. 342void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 343 // C++ [dcl.fct.default]p3 344 // A default argument expression shall be specified only in the 345 // parameter-declaration-clause of a function declaration or in a 346 // template-parameter (14.1). It shall not be specified for a 347 // parameter pack. If it is specified in a 348 // parameter-declaration-clause, it shall not occur within a 349 // declarator or abstract-declarator of a parameter-declaration. 350 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 351 DeclaratorChunk &chunk = D.getTypeObject(i); 352 if (chunk.Kind == DeclaratorChunk::Function) { 353 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) { 354 ParmVarDecl *Param = 355 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param); 356 if (Param->hasUnparsedDefaultArg()) { 357 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens; 358 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 359 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation()); 360 delete Toks; 361 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0; 362 } else if (Param->getDefaultArg()) { 363 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 364 << Param->getDefaultArg()->getSourceRange(); 365 Param->setDefaultArg(0); 366 } 367 } 368 } 369 } 370} 371 372// MergeCXXFunctionDecl - Merge two declarations of the same C++ 373// function, once we already know that they have the same 374// type. Subroutine of MergeFunctionDecl. Returns true if there was an 375// error, false otherwise. 376bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) { 377 bool Invalid = false; 378 379 // C++ [dcl.fct.default]p4: 380 // For non-template functions, default arguments can be added in 381 // later declarations of a function in the same 382 // scope. Declarations in different scopes have completely 383 // distinct sets of default arguments. That is, declarations in 384 // inner scopes do not acquire default arguments from 385 // declarations in outer scopes, and vice versa. In a given 386 // function declaration, all parameters subsequent to a 387 // parameter with a default argument shall have default 388 // arguments supplied in this or previous declarations. A 389 // default argument shall not be redefined by a later 390 // declaration (not even to the same value). 391 // 392 // C++ [dcl.fct.default]p6: 393 // Except for member functions of class templates, the default arguments 394 // in a member function definition that appears outside of the class 395 // definition are added to the set of default arguments provided by the 396 // member function declaration in the class definition. 397 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 398 ParmVarDecl *OldParam = Old->getParamDecl(p); 399 ParmVarDecl *NewParam = New->getParamDecl(p); 400 401 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) { 402 403 unsigned DiagDefaultParamID = 404 diag::err_param_default_argument_redefinition; 405 406 // MSVC accepts that default parameters be redefined for member functions 407 // of template class. The new default parameter's value is ignored. 408 Invalid = true; 409 if (getLangOptions().MicrosoftExt) { 410 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New); 411 if (MD && MD->getParent()->getDescribedClassTemplate()) { 412 // Merge the old default argument into the new parameter. 413 NewParam->setHasInheritedDefaultArg(); 414 if (OldParam->hasUninstantiatedDefaultArg()) 415 NewParam->setUninstantiatedDefaultArg( 416 OldParam->getUninstantiatedDefaultArg()); 417 else 418 NewParam->setDefaultArg(OldParam->getInit()); 419 DiagDefaultParamID = diag::warn_param_default_argument_redefinition; 420 Invalid = false; 421 } 422 } 423 424 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 425 // hint here. Alternatively, we could walk the type-source information 426 // for NewParam to find the last source location in the type... but it 427 // isn't worth the effort right now. This is the kind of test case that 428 // is hard to get right: 429 // int f(int); 430 // void g(int (*fp)(int) = f); 431 // void g(int (*fp)(int) = &f); 432 Diag(NewParam->getLocation(), DiagDefaultParamID) 433 << NewParam->getDefaultArgRange(); 434 435 // Look for the function declaration where the default argument was 436 // actually written, which may be a declaration prior to Old. 437 for (FunctionDecl *Older = Old->getPreviousDecl(); 438 Older; Older = Older->getPreviousDecl()) { 439 if (!Older->getParamDecl(p)->hasDefaultArg()) 440 break; 441 442 OldParam = Older->getParamDecl(p); 443 } 444 445 Diag(OldParam->getLocation(), diag::note_previous_definition) 446 << OldParam->getDefaultArgRange(); 447 } else if (OldParam->hasDefaultArg()) { 448 // Merge the old default argument into the new parameter. 449 // It's important to use getInit() here; getDefaultArg() 450 // strips off any top-level ExprWithCleanups. 451 NewParam->setHasInheritedDefaultArg(); 452 if (OldParam->hasUninstantiatedDefaultArg()) 453 NewParam->setUninstantiatedDefaultArg( 454 OldParam->getUninstantiatedDefaultArg()); 455 else 456 NewParam->setDefaultArg(OldParam->getInit()); 457 } else if (NewParam->hasDefaultArg()) { 458 if (New->getDescribedFunctionTemplate()) { 459 // Paragraph 4, quoted above, only applies to non-template functions. 460 Diag(NewParam->getLocation(), 461 diag::err_param_default_argument_template_redecl) 462 << NewParam->getDefaultArgRange(); 463 Diag(Old->getLocation(), diag::note_template_prev_declaration) 464 << false; 465 } else if (New->getTemplateSpecializationKind() 466 != TSK_ImplicitInstantiation && 467 New->getTemplateSpecializationKind() != TSK_Undeclared) { 468 // C++ [temp.expr.spec]p21: 469 // Default function arguments shall not be specified in a declaration 470 // or a definition for one of the following explicit specializations: 471 // - the explicit specialization of a function template; 472 // - the explicit specialization of a member function template; 473 // - the explicit specialization of a member function of a class 474 // template where the class template specialization to which the 475 // member function specialization belongs is implicitly 476 // instantiated. 477 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 478 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 479 << New->getDeclName() 480 << NewParam->getDefaultArgRange(); 481 } else if (New->getDeclContext()->isDependentContext()) { 482 // C++ [dcl.fct.default]p6 (DR217): 483 // Default arguments for a member function of a class template shall 484 // be specified on the initial declaration of the member function 485 // within the class template. 486 // 487 // Reading the tea leaves a bit in DR217 and its reference to DR205 488 // leads me to the conclusion that one cannot add default function 489 // arguments for an out-of-line definition of a member function of a 490 // dependent type. 491 int WhichKind = 2; 492 if (CXXRecordDecl *Record 493 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 494 if (Record->getDescribedClassTemplate()) 495 WhichKind = 0; 496 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 497 WhichKind = 1; 498 else 499 WhichKind = 2; 500 } 501 502 Diag(NewParam->getLocation(), 503 diag::err_param_default_argument_member_template_redecl) 504 << WhichKind 505 << NewParam->getDefaultArgRange(); 506 } else if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(New)) { 507 CXXSpecialMember NewSM = getSpecialMember(Ctor), 508 OldSM = getSpecialMember(cast<CXXConstructorDecl>(Old)); 509 if (NewSM != OldSM) { 510 Diag(NewParam->getLocation(),diag::warn_default_arg_makes_ctor_special) 511 << NewParam->getDefaultArgRange() << NewSM; 512 Diag(Old->getLocation(), diag::note_previous_declaration_special) 513 << OldSM; 514 } 515 } 516 } 517 } 518 519 // C++0x [dcl.constexpr]p1: If any declaration of a function or function 520 // template has a constexpr specifier then all its declarations shall 521 // contain the constexpr specifier. [Note: An explicit specialization can 522 // differ from the template declaration with respect to the constexpr 523 // specifier. -- end note] 524 // 525 // FIXME: Don't reject changes in constexpr in explicit specializations. 526 if (New->isConstexpr() != Old->isConstexpr()) { 527 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 528 << New << New->isConstexpr(); 529 Diag(Old->getLocation(), diag::note_previous_declaration); 530 Invalid = true; 531 } 532 533 if (CheckEquivalentExceptionSpec(Old, New)) 534 Invalid = true; 535 536 return Invalid; 537} 538 539/// \brief Merge the exception specifications of two variable declarations. 540/// 541/// This is called when there's a redeclaration of a VarDecl. The function 542/// checks if the redeclaration might have an exception specification and 543/// validates compatibility and merges the specs if necessary. 544void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 545 // Shortcut if exceptions are disabled. 546 if (!getLangOptions().CXXExceptions) 547 return; 548 549 assert(Context.hasSameType(New->getType(), Old->getType()) && 550 "Should only be called if types are otherwise the same."); 551 552 QualType NewType = New->getType(); 553 QualType OldType = Old->getType(); 554 555 // We're only interested in pointers and references to functions, as well 556 // as pointers to member functions. 557 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 558 NewType = R->getPointeeType(); 559 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 560 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 561 NewType = P->getPointeeType(); 562 OldType = OldType->getAs<PointerType>()->getPointeeType(); 563 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 564 NewType = M->getPointeeType(); 565 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 566 } 567 568 if (!NewType->isFunctionProtoType()) 569 return; 570 571 // There's lots of special cases for functions. For function pointers, system 572 // libraries are hopefully not as broken so that we don't need these 573 // workarounds. 574 if (CheckEquivalentExceptionSpec( 575 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 576 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 577 New->setInvalidDecl(); 578 } 579} 580 581/// CheckCXXDefaultArguments - Verify that the default arguments for a 582/// function declaration are well-formed according to C++ 583/// [dcl.fct.default]. 584void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 585 unsigned NumParams = FD->getNumParams(); 586 unsigned p; 587 588 // Find first parameter with a default argument 589 for (p = 0; p < NumParams; ++p) { 590 ParmVarDecl *Param = FD->getParamDecl(p); 591 if (Param->hasDefaultArg()) 592 break; 593 } 594 595 // C++ [dcl.fct.default]p4: 596 // In a given function declaration, all parameters 597 // subsequent to a parameter with a default argument shall 598 // have default arguments supplied in this or previous 599 // declarations. A default argument shall not be redefined 600 // by a later declaration (not even to the same value). 601 unsigned LastMissingDefaultArg = 0; 602 for (; p < NumParams; ++p) { 603 ParmVarDecl *Param = FD->getParamDecl(p); 604 if (!Param->hasDefaultArg()) { 605 if (Param->isInvalidDecl()) 606 /* We already complained about this parameter. */; 607 else if (Param->getIdentifier()) 608 Diag(Param->getLocation(), 609 diag::err_param_default_argument_missing_name) 610 << Param->getIdentifier(); 611 else 612 Diag(Param->getLocation(), 613 diag::err_param_default_argument_missing); 614 615 LastMissingDefaultArg = p; 616 } 617 } 618 619 if (LastMissingDefaultArg > 0) { 620 // Some default arguments were missing. Clear out all of the 621 // default arguments up to (and including) the last missing 622 // default argument, so that we leave the function parameters 623 // in a semantically valid state. 624 for (p = 0; p <= LastMissingDefaultArg; ++p) { 625 ParmVarDecl *Param = FD->getParamDecl(p); 626 if (Param->hasDefaultArg()) { 627 Param->setDefaultArg(0); 628 } 629 } 630 } 631} 632 633// CheckConstexprParameterTypes - Check whether a function's parameter types 634// are all literal types. If so, return true. If not, produce a suitable 635// diagnostic depending on @p CCK and return false. 636static bool CheckConstexprParameterTypes(Sema &SemaRef, const FunctionDecl *FD, 637 Sema::CheckConstexprKind CCK) { 638 unsigned ArgIndex = 0; 639 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 640 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(), 641 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) { 642 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 643 SourceLocation ParamLoc = PD->getLocation(); 644 if (!(*i)->isDependentType() && 645 SemaRef.RequireLiteralType(ParamLoc, *i, CCK == Sema::CCK_Declaration ? 646 SemaRef.PDiag(diag::err_constexpr_non_literal_param) 647 << ArgIndex+1 << PD->getSourceRange() 648 << isa<CXXConstructorDecl>(FD) : 649 SemaRef.PDiag(), 650 /*AllowIncompleteType*/ true)) { 651 if (CCK == Sema::CCK_NoteNonConstexprInstantiation) 652 SemaRef.Diag(ParamLoc, diag::note_constexpr_tmpl_non_literal_param) 653 << ArgIndex+1 << PD->getSourceRange() 654 << isa<CXXConstructorDecl>(FD) << *i; 655 return false; 656 } 657 } 658 return true; 659} 660 661// CheckConstexprFunctionDecl - Check whether a function declaration satisfies 662// the requirements of a constexpr function declaration or a constexpr 663// constructor declaration. Return true if it does, false if not. 664// 665// This implements C++11 [dcl.constexpr]p3,4, as amended by N3308. 666// 667// \param CCK Specifies whether to produce diagnostics if the function does not 668// satisfy the requirements. 669bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD, 670 CheckConstexprKind CCK) { 671 assert((CCK != CCK_NoteNonConstexprInstantiation || 672 (NewFD->getTemplateInstantiationPattern() && 673 NewFD->getTemplateInstantiationPattern()->isConstexpr())) && 674 "only constexpr templates can be instantiated non-constexpr"); 675 676 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 677 if (MD && MD->isInstance()) { 678 // C++11 [dcl.constexpr]p4: In the definition of a constexpr constructor... 679 // In addition, either its function-body shall be = delete or = default or 680 // it shall satisfy the following constraints: 681 // - the class shall not have any virtual base classes; 682 // 683 // We apply this to constexpr member functions too: the class cannot be a 684 // literal type, so the members are not permitted to be constexpr. 685 const CXXRecordDecl *RD = MD->getParent(); 686 if (RD->getNumVBases()) { 687 // Note, this is still illegal if the body is = default, since the 688 // implicit body does not satisfy the requirements of a constexpr 689 // constructor. We also reject cases where the body is = delete, as 690 // required by N3308. 691 if (CCK != CCK_Instantiation) { 692 Diag(NewFD->getLocation(), 693 CCK == CCK_Declaration ? diag::err_constexpr_virtual_base 694 : diag::note_constexpr_tmpl_virtual_base) 695 << isa<CXXConstructorDecl>(NewFD) << RD->isStruct() 696 << RD->getNumVBases(); 697 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(), 698 E = RD->vbases_end(); I != E; ++I) 699 Diag(I->getSourceRange().getBegin(), 700 diag::note_constexpr_virtual_base_here) << I->getSourceRange(); 701 } 702 return false; 703 } 704 } 705 706 if (!isa<CXXConstructorDecl>(NewFD)) { 707 // C++11 [dcl.constexpr]p3: 708 // The definition of a constexpr function shall satisfy the following 709 // constraints: 710 // - it shall not be virtual; 711 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 712 if (Method && Method->isVirtual()) { 713 if (CCK != CCK_Instantiation) { 714 Diag(NewFD->getLocation(), 715 CCK == CCK_Declaration ? diag::err_constexpr_virtual 716 : diag::note_constexpr_tmpl_virtual); 717 718 // If it's not obvious why this function is virtual, find an overridden 719 // function which uses the 'virtual' keyword. 720 const CXXMethodDecl *WrittenVirtual = Method; 721 while (!WrittenVirtual->isVirtualAsWritten()) 722 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 723 if (WrittenVirtual != Method) 724 Diag(WrittenVirtual->getLocation(), 725 diag::note_overridden_virtual_function); 726 } 727 return false; 728 } 729 730 // - its return type shall be a literal type; 731 QualType RT = NewFD->getResultType(); 732 if (!RT->isDependentType() && 733 RequireLiteralType(NewFD->getLocation(), RT, CCK == CCK_Declaration ? 734 PDiag(diag::err_constexpr_non_literal_return) : 735 PDiag(), 736 /*AllowIncompleteType*/ true)) { 737 if (CCK == CCK_NoteNonConstexprInstantiation) 738 Diag(NewFD->getLocation(), 739 diag::note_constexpr_tmpl_non_literal_return) << RT; 740 return false; 741 } 742 } 743 744 // - each of its parameter types shall be a literal type; 745 if (!CheckConstexprParameterTypes(*this, NewFD, CCK)) 746 return false; 747 748 return true; 749} 750 751/// Check the given declaration statement is legal within a constexpr function 752/// body. C++0x [dcl.constexpr]p3,p4. 753/// 754/// \return true if the body is OK, false if we have diagnosed a problem. 755static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 756 DeclStmt *DS) { 757 // C++0x [dcl.constexpr]p3 and p4: 758 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 759 // contain only 760 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(), 761 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) { 762 switch ((*DclIt)->getKind()) { 763 case Decl::StaticAssert: 764 case Decl::Using: 765 case Decl::UsingShadow: 766 case Decl::UsingDirective: 767 case Decl::UnresolvedUsingTypename: 768 // - static_assert-declarations 769 // - using-declarations, 770 // - using-directives, 771 continue; 772 773 case Decl::Typedef: 774 case Decl::TypeAlias: { 775 // - typedef declarations and alias-declarations that do not define 776 // classes or enumerations, 777 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt); 778 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 779 // Don't allow variably-modified types in constexpr functions. 780 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 781 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 782 << TL.getSourceRange() << TL.getType() 783 << isa<CXXConstructorDecl>(Dcl); 784 return false; 785 } 786 continue; 787 } 788 789 case Decl::Enum: 790 case Decl::CXXRecord: 791 // As an extension, we allow the declaration (but not the definition) of 792 // classes and enumerations in all declarations, not just in typedef and 793 // alias declarations. 794 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) { 795 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition) 796 << isa<CXXConstructorDecl>(Dcl); 797 return false; 798 } 799 continue; 800 801 case Decl::Var: 802 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration) 803 << isa<CXXConstructorDecl>(Dcl); 804 return false; 805 806 default: 807 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt) 808 << isa<CXXConstructorDecl>(Dcl); 809 return false; 810 } 811 } 812 813 return true; 814} 815 816/// Check that the given field is initialized within a constexpr constructor. 817/// 818/// \param Dcl The constexpr constructor being checked. 819/// \param Field The field being checked. This may be a member of an anonymous 820/// struct or union nested within the class being checked. 821/// \param Inits All declarations, including anonymous struct/union members and 822/// indirect members, for which any initialization was provided. 823/// \param Diagnosed Set to true if an error is produced. 824static void CheckConstexprCtorInitializer(Sema &SemaRef, 825 const FunctionDecl *Dcl, 826 FieldDecl *Field, 827 llvm::SmallSet<Decl*, 16> &Inits, 828 bool &Diagnosed) { 829 if (Field->isUnnamedBitfield()) 830 return; 831 832 if (Field->isAnonymousStructOrUnion() && 833 Field->getType()->getAsCXXRecordDecl()->isEmpty()) 834 return; 835 836 if (!Inits.count(Field)) { 837 if (!Diagnosed) { 838 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init); 839 Diagnosed = true; 840 } 841 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init); 842 } else if (Field->isAnonymousStructOrUnion()) { 843 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 844 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end(); 845 I != E; ++I) 846 // If an anonymous union contains an anonymous struct of which any member 847 // is initialized, all members must be initialized. 848 if (!RD->isUnion() || Inits.count(*I)) 849 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed); 850 } 851} 852 853/// Check the body for the given constexpr function declaration only contains 854/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 855/// 856/// \return true if the body is OK, false if we have diagnosed a problem. 857bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body, 858 bool IsInstantiation) { 859 if (isa<CXXTryStmt>(Body)) { 860 // C++11 [dcl.constexpr]p3: 861 // The definition of a constexpr function shall satisfy the following 862 // constraints: [...] 863 // - its function-body shall be = delete, = default, or a 864 // compound-statement 865 // 866 // C++11 [dcl.constexpr]p4: 867 // In the definition of a constexpr constructor, [...] 868 // - its function-body shall not be a function-try-block; 869 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block) 870 << isa<CXXConstructorDecl>(Dcl); 871 return false; 872 } 873 874 // - its function-body shall be [...] a compound-statement that contains only 875 CompoundStmt *CompBody = cast<CompoundStmt>(Body); 876 877 llvm::SmallVector<SourceLocation, 4> ReturnStmts; 878 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(), 879 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) { 880 switch ((*BodyIt)->getStmtClass()) { 881 case Stmt::NullStmtClass: 882 // - null statements, 883 continue; 884 885 case Stmt::DeclStmtClass: 886 // - static_assert-declarations 887 // - using-declarations, 888 // - using-directives, 889 // - typedef declarations and alias-declarations that do not define 890 // classes or enumerations, 891 if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt))) 892 return false; 893 continue; 894 895 case Stmt::ReturnStmtClass: 896 // - and exactly one return statement; 897 if (isa<CXXConstructorDecl>(Dcl)) 898 break; 899 900 ReturnStmts.push_back((*BodyIt)->getLocStart()); 901 // FIXME 902 // - every constructor call and implicit conversion used in initializing 903 // the return value shall be one of those allowed in a constant 904 // expression. 905 // Deal with this as part of a general check that the function can produce 906 // a constant expression (for [dcl.constexpr]p5). 907 continue; 908 909 default: 910 break; 911 } 912 913 Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt) 914 << isa<CXXConstructorDecl>(Dcl); 915 return false; 916 } 917 918 if (const CXXConstructorDecl *Constructor 919 = dyn_cast<CXXConstructorDecl>(Dcl)) { 920 const CXXRecordDecl *RD = Constructor->getParent(); 921 // DR1359: 922 // - every non-variant non-static data member and base class sub-object 923 // shall be initialized; 924 // - if the class is a non-empty union, or for each non-empty anonymous 925 // union member of a non-union class, exactly one non-static data member 926 // shall be initialized; 927 if (RD->isUnion()) { 928 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) { 929 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init); 930 return false; 931 } 932 } else if (!Constructor->isDependentContext() && 933 !Constructor->isDelegatingConstructor()) { 934 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 935 936 // Skip detailed checking if we have enough initializers, and we would 937 // allow at most one initializer per member. 938 bool AnyAnonStructUnionMembers = false; 939 unsigned Fields = 0; 940 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 941 E = RD->field_end(); I != E; ++I, ++Fields) { 942 if ((*I)->isAnonymousStructOrUnion()) { 943 AnyAnonStructUnionMembers = true; 944 break; 945 } 946 } 947 if (AnyAnonStructUnionMembers || 948 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 949 // Check initialization of non-static data members. Base classes are 950 // always initialized so do not need to be checked. Dependent bases 951 // might not have initializers in the member initializer list. 952 llvm::SmallSet<Decl*, 16> Inits; 953 for (CXXConstructorDecl::init_const_iterator 954 I = Constructor->init_begin(), E = Constructor->init_end(); 955 I != E; ++I) { 956 if (FieldDecl *FD = (*I)->getMember()) 957 Inits.insert(FD); 958 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember()) 959 Inits.insert(ID->chain_begin(), ID->chain_end()); 960 } 961 962 bool Diagnosed = false; 963 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 964 E = RD->field_end(); I != E; ++I) 965 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed); 966 if (Diagnosed) 967 return false; 968 } 969 } 970 971 // FIXME 972 // - every constructor involved in initializing non-static data members 973 // and base class sub-objects shall be a constexpr constructor; 974 // - every assignment-expression that is an initializer-clause appearing 975 // directly or indirectly within a brace-or-equal-initializer for 976 // a non-static data member that is not named by a mem-initializer-id 977 // shall be a constant expression; and 978 // - every implicit conversion used in converting a constructor argument 979 // to the corresponding parameter type and converting 980 // a full-expression to the corresponding member type shall be one of 981 // those allowed in a constant expression. 982 // Deal with these as part of a general check that the function can produce 983 // a constant expression (for [dcl.constexpr]p5). 984 } else { 985 if (ReturnStmts.empty()) { 986 Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return); 987 return false; 988 } 989 if (ReturnStmts.size() > 1) { 990 Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return); 991 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 992 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return); 993 return false; 994 } 995 } 996 997 // C++11 [dcl.constexpr]p5: 998 // if no function argument values exist such that the function invocation 999 // substitution would produce a constant expression, the program is 1000 // ill-formed; no diagnostic required. 1001 // C++11 [dcl.constexpr]p3: 1002 // - every constructor call and implicit conversion used in initializing the 1003 // return value shall be one of those allowed in a constant expression. 1004 // C++11 [dcl.constexpr]p4: 1005 // - every constructor involved in initializing non-static data members and 1006 // base class sub-objects shall be a constexpr constructor. 1007 llvm::SmallVector<PartialDiagnosticAt, 8> Diags; 1008 if (!IsInstantiation && !Expr::isPotentialConstantExpr(Dcl, Diags)) { 1009 Diag(Dcl->getLocation(), diag::err_constexpr_function_never_constant_expr) 1010 << isa<CXXConstructorDecl>(Dcl); 1011 for (size_t I = 0, N = Diags.size(); I != N; ++I) 1012 Diag(Diags[I].first, Diags[I].second); 1013 return false; 1014 } 1015 1016 return true; 1017} 1018 1019/// isCurrentClassName - Determine whether the identifier II is the 1020/// name of the class type currently being defined. In the case of 1021/// nested classes, this will only return true if II is the name of 1022/// the innermost class. 1023bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 1024 const CXXScopeSpec *SS) { 1025 assert(getLangOptions().CPlusPlus && "No class names in C!"); 1026 1027 CXXRecordDecl *CurDecl; 1028 if (SS && SS->isSet() && !SS->isInvalid()) { 1029 DeclContext *DC = computeDeclContext(*SS, true); 1030 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 1031 } else 1032 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1033 1034 if (CurDecl && CurDecl->getIdentifier()) 1035 return &II == CurDecl->getIdentifier(); 1036 else 1037 return false; 1038} 1039 1040/// \brief Check the validity of a C++ base class specifier. 1041/// 1042/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 1043/// and returns NULL otherwise. 1044CXXBaseSpecifier * 1045Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 1046 SourceRange SpecifierRange, 1047 bool Virtual, AccessSpecifier Access, 1048 TypeSourceInfo *TInfo, 1049 SourceLocation EllipsisLoc) { 1050 QualType BaseType = TInfo->getType(); 1051 1052 // C++ [class.union]p1: 1053 // A union shall not have base classes. 1054 if (Class->isUnion()) { 1055 Diag(Class->getLocation(), diag::err_base_clause_on_union) 1056 << SpecifierRange; 1057 return 0; 1058 } 1059 1060 if (EllipsisLoc.isValid() && 1061 !TInfo->getType()->containsUnexpandedParameterPack()) { 1062 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 1063 << TInfo->getTypeLoc().getSourceRange(); 1064 EllipsisLoc = SourceLocation(); 1065 } 1066 1067 if (BaseType->isDependentType()) 1068 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1069 Class->getTagKind() == TTK_Class, 1070 Access, TInfo, EllipsisLoc); 1071 1072 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 1073 1074 // Base specifiers must be record types. 1075 if (!BaseType->isRecordType()) { 1076 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 1077 return 0; 1078 } 1079 1080 // C++ [class.union]p1: 1081 // A union shall not be used as a base class. 1082 if (BaseType->isUnionType()) { 1083 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 1084 return 0; 1085 } 1086 1087 // C++ [class.derived]p2: 1088 // The class-name in a base-specifier shall not be an incompletely 1089 // defined class. 1090 if (RequireCompleteType(BaseLoc, BaseType, 1091 PDiag(diag::err_incomplete_base_class) 1092 << SpecifierRange)) { 1093 Class->setInvalidDecl(); 1094 return 0; 1095 } 1096 1097 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 1098 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 1099 assert(BaseDecl && "Record type has no declaration"); 1100 BaseDecl = BaseDecl->getDefinition(); 1101 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 1102 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 1103 assert(CXXBaseDecl && "Base type is not a C++ type"); 1104 1105 // C++ [class]p3: 1106 // If a class is marked final and it appears as a base-type-specifier in 1107 // base-clause, the program is ill-formed. 1108 if (CXXBaseDecl->hasAttr<FinalAttr>()) { 1109 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 1110 << CXXBaseDecl->getDeclName(); 1111 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl) 1112 << CXXBaseDecl->getDeclName(); 1113 return 0; 1114 } 1115 1116 if (BaseDecl->isInvalidDecl()) 1117 Class->setInvalidDecl(); 1118 1119 // Create the base specifier. 1120 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1121 Class->getTagKind() == TTK_Class, 1122 Access, TInfo, EllipsisLoc); 1123} 1124 1125/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 1126/// one entry in the base class list of a class specifier, for 1127/// example: 1128/// class foo : public bar, virtual private baz { 1129/// 'public bar' and 'virtual private baz' are each base-specifiers. 1130BaseResult 1131Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 1132 bool Virtual, AccessSpecifier Access, 1133 ParsedType basetype, SourceLocation BaseLoc, 1134 SourceLocation EllipsisLoc) { 1135 if (!classdecl) 1136 return true; 1137 1138 AdjustDeclIfTemplate(classdecl); 1139 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 1140 if (!Class) 1141 return true; 1142 1143 TypeSourceInfo *TInfo = 0; 1144 GetTypeFromParser(basetype, &TInfo); 1145 1146 if (EllipsisLoc.isInvalid() && 1147 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 1148 UPPC_BaseType)) 1149 return true; 1150 1151 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 1152 Virtual, Access, TInfo, 1153 EllipsisLoc)) 1154 return BaseSpec; 1155 1156 return true; 1157} 1158 1159/// \brief Performs the actual work of attaching the given base class 1160/// specifiers to a C++ class. 1161bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 1162 unsigned NumBases) { 1163 if (NumBases == 0) 1164 return false; 1165 1166 // Used to keep track of which base types we have already seen, so 1167 // that we can properly diagnose redundant direct base types. Note 1168 // that the key is always the unqualified canonical type of the base 1169 // class. 1170 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 1171 1172 // Copy non-redundant base specifiers into permanent storage. 1173 unsigned NumGoodBases = 0; 1174 bool Invalid = false; 1175 for (unsigned idx = 0; idx < NumBases; ++idx) { 1176 QualType NewBaseType 1177 = Context.getCanonicalType(Bases[idx]->getType()); 1178 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 1179 if (KnownBaseTypes[NewBaseType]) { 1180 // C++ [class.mi]p3: 1181 // A class shall not be specified as a direct base class of a 1182 // derived class more than once. 1183 Diag(Bases[idx]->getSourceRange().getBegin(), 1184 diag::err_duplicate_base_class) 1185 << KnownBaseTypes[NewBaseType]->getType() 1186 << Bases[idx]->getSourceRange(); 1187 1188 // Delete the duplicate base class specifier; we're going to 1189 // overwrite its pointer later. 1190 Context.Deallocate(Bases[idx]); 1191 1192 Invalid = true; 1193 } else { 1194 // Okay, add this new base class. 1195 KnownBaseTypes[NewBaseType] = Bases[idx]; 1196 Bases[NumGoodBases++] = Bases[idx]; 1197 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) 1198 if (const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl())) 1199 if (RD->hasAttr<WeakAttr>()) 1200 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context)); 1201 } 1202 } 1203 1204 // Attach the remaining base class specifiers to the derived class. 1205 Class->setBases(Bases, NumGoodBases); 1206 1207 // Delete the remaining (good) base class specifiers, since their 1208 // data has been copied into the CXXRecordDecl. 1209 for (unsigned idx = 0; idx < NumGoodBases; ++idx) 1210 Context.Deallocate(Bases[idx]); 1211 1212 return Invalid; 1213} 1214 1215/// ActOnBaseSpecifiers - Attach the given base specifiers to the 1216/// class, after checking whether there are any duplicate base 1217/// classes. 1218void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases, 1219 unsigned NumBases) { 1220 if (!ClassDecl || !Bases || !NumBases) 1221 return; 1222 1223 AdjustDeclIfTemplate(ClassDecl); 1224 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), 1225 (CXXBaseSpecifier**)(Bases), NumBases); 1226} 1227 1228static CXXRecordDecl *GetClassForType(QualType T) { 1229 if (const RecordType *RT = T->getAs<RecordType>()) 1230 return cast<CXXRecordDecl>(RT->getDecl()); 1231 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>()) 1232 return ICT->getDecl(); 1233 else 1234 return 0; 1235} 1236 1237/// \brief Determine whether the type \p Derived is a C++ class that is 1238/// derived from the type \p Base. 1239bool Sema::IsDerivedFrom(QualType Derived, QualType Base) { 1240 if (!getLangOptions().CPlusPlus) 1241 return false; 1242 1243 CXXRecordDecl *DerivedRD = GetClassForType(Derived); 1244 if (!DerivedRD) 1245 return false; 1246 1247 CXXRecordDecl *BaseRD = GetClassForType(Base); 1248 if (!BaseRD) 1249 return false; 1250 1251 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this. 1252 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD); 1253} 1254 1255/// \brief Determine whether the type \p Derived is a C++ class that is 1256/// derived from the type \p Base. 1257bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) { 1258 if (!getLangOptions().CPlusPlus) 1259 return false; 1260 1261 CXXRecordDecl *DerivedRD = GetClassForType(Derived); 1262 if (!DerivedRD) 1263 return false; 1264 1265 CXXRecordDecl *BaseRD = GetClassForType(Base); 1266 if (!BaseRD) 1267 return false; 1268 1269 return DerivedRD->isDerivedFrom(BaseRD, Paths); 1270} 1271 1272void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 1273 CXXCastPath &BasePathArray) { 1274 assert(BasePathArray.empty() && "Base path array must be empty!"); 1275 assert(Paths.isRecordingPaths() && "Must record paths!"); 1276 1277 const CXXBasePath &Path = Paths.front(); 1278 1279 // We first go backward and check if we have a virtual base. 1280 // FIXME: It would be better if CXXBasePath had the base specifier for 1281 // the nearest virtual base. 1282 unsigned Start = 0; 1283 for (unsigned I = Path.size(); I != 0; --I) { 1284 if (Path[I - 1].Base->isVirtual()) { 1285 Start = I - 1; 1286 break; 1287 } 1288 } 1289 1290 // Now add all bases. 1291 for (unsigned I = Start, E = Path.size(); I != E; ++I) 1292 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 1293} 1294 1295/// \brief Determine whether the given base path includes a virtual 1296/// base class. 1297bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) { 1298 for (CXXCastPath::const_iterator B = BasePath.begin(), 1299 BEnd = BasePath.end(); 1300 B != BEnd; ++B) 1301 if ((*B)->isVirtual()) 1302 return true; 1303 1304 return false; 1305} 1306 1307/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 1308/// conversion (where Derived and Base are class types) is 1309/// well-formed, meaning that the conversion is unambiguous (and 1310/// that all of the base classes are accessible). Returns true 1311/// and emits a diagnostic if the code is ill-formed, returns false 1312/// otherwise. Loc is the location where this routine should point to 1313/// if there is an error, and Range is the source range to highlight 1314/// if there is an error. 1315bool 1316Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1317 unsigned InaccessibleBaseID, 1318 unsigned AmbigiousBaseConvID, 1319 SourceLocation Loc, SourceRange Range, 1320 DeclarationName Name, 1321 CXXCastPath *BasePath) { 1322 // First, determine whether the path from Derived to Base is 1323 // ambiguous. This is slightly more expensive than checking whether 1324 // the Derived to Base conversion exists, because here we need to 1325 // explore multiple paths to determine if there is an ambiguity. 1326 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1327 /*DetectVirtual=*/false); 1328 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths); 1329 assert(DerivationOkay && 1330 "Can only be used with a derived-to-base conversion"); 1331 (void)DerivationOkay; 1332 1333 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 1334 if (InaccessibleBaseID) { 1335 // Check that the base class can be accessed. 1336 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(), 1337 InaccessibleBaseID)) { 1338 case AR_inaccessible: 1339 return true; 1340 case AR_accessible: 1341 case AR_dependent: 1342 case AR_delayed: 1343 break; 1344 } 1345 } 1346 1347 // Build a base path if necessary. 1348 if (BasePath) 1349 BuildBasePathArray(Paths, *BasePath); 1350 return false; 1351 } 1352 1353 // We know that the derived-to-base conversion is ambiguous, and 1354 // we're going to produce a diagnostic. Perform the derived-to-base 1355 // search just one more time to compute all of the possible paths so 1356 // that we can print them out. This is more expensive than any of 1357 // the previous derived-to-base checks we've done, but at this point 1358 // performance isn't as much of an issue. 1359 Paths.clear(); 1360 Paths.setRecordingPaths(true); 1361 bool StillOkay = IsDerivedFrom(Derived, Base, Paths); 1362 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 1363 (void)StillOkay; 1364 1365 // Build up a textual representation of the ambiguous paths, e.g., 1366 // D -> B -> A, that will be used to illustrate the ambiguous 1367 // conversions in the diagnostic. We only print one of the paths 1368 // to each base class subobject. 1369 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 1370 1371 Diag(Loc, AmbigiousBaseConvID) 1372 << Derived << Base << PathDisplayStr << Range << Name; 1373 return true; 1374} 1375 1376bool 1377Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1378 SourceLocation Loc, SourceRange Range, 1379 CXXCastPath *BasePath, 1380 bool IgnoreAccess) { 1381 return CheckDerivedToBaseConversion(Derived, Base, 1382 IgnoreAccess ? 0 1383 : diag::err_upcast_to_inaccessible_base, 1384 diag::err_ambiguous_derived_to_base_conv, 1385 Loc, Range, DeclarationName(), 1386 BasePath); 1387} 1388 1389 1390/// @brief Builds a string representing ambiguous paths from a 1391/// specific derived class to different subobjects of the same base 1392/// class. 1393/// 1394/// This function builds a string that can be used in error messages 1395/// to show the different paths that one can take through the 1396/// inheritance hierarchy to go from the derived class to different 1397/// subobjects of a base class. The result looks something like this: 1398/// @code 1399/// struct D -> struct B -> struct A 1400/// struct D -> struct C -> struct A 1401/// @endcode 1402std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 1403 std::string PathDisplayStr; 1404 std::set<unsigned> DisplayedPaths; 1405 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 1406 Path != Paths.end(); ++Path) { 1407 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 1408 // We haven't displayed a path to this particular base 1409 // class subobject yet. 1410 PathDisplayStr += "\n "; 1411 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 1412 for (CXXBasePath::const_iterator Element = Path->begin(); 1413 Element != Path->end(); ++Element) 1414 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 1415 } 1416 } 1417 1418 return PathDisplayStr; 1419} 1420 1421//===----------------------------------------------------------------------===// 1422// C++ class member Handling 1423//===----------------------------------------------------------------------===// 1424 1425/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 1426bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, 1427 SourceLocation ASLoc, 1428 SourceLocation ColonLoc, 1429 AttributeList *Attrs) { 1430 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 1431 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 1432 ASLoc, ColonLoc); 1433 CurContext->addHiddenDecl(ASDecl); 1434 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 1435} 1436 1437/// CheckOverrideControl - Check C++0x override control semantics. 1438void Sema::CheckOverrideControl(const Decl *D) { 1439 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 1440 if (!MD || !MD->isVirtual()) 1441 return; 1442 1443 if (MD->isDependentContext()) 1444 return; 1445 1446 // C++0x [class.virtual]p3: 1447 // If a virtual function is marked with the virt-specifier override and does 1448 // not override a member function of a base class, 1449 // the program is ill-formed. 1450 bool HasOverriddenMethods = 1451 MD->begin_overridden_methods() != MD->end_overridden_methods(); 1452 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) { 1453 Diag(MD->getLocation(), 1454 diag::err_function_marked_override_not_overriding) 1455 << MD->getDeclName(); 1456 return; 1457 } 1458} 1459 1460/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 1461/// function overrides a virtual member function marked 'final', according to 1462/// C++0x [class.virtual]p3. 1463bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 1464 const CXXMethodDecl *Old) { 1465 if (!Old->hasAttr<FinalAttr>()) 1466 return false; 1467 1468 Diag(New->getLocation(), diag::err_final_function_overridden) 1469 << New->getDeclName(); 1470 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 1471 return true; 1472} 1473 1474/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 1475/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 1476/// bitfield width if there is one, 'InitExpr' specifies the initializer if 1477/// one has been parsed, and 'HasDeferredInit' is true if an initializer is 1478/// present but parsing it has been deferred. 1479Decl * 1480Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 1481 MultiTemplateParamsArg TemplateParameterLists, 1482 Expr *BW, const VirtSpecifiers &VS, 1483 bool HasDeferredInit) { 1484 const DeclSpec &DS = D.getDeclSpec(); 1485 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 1486 DeclarationName Name = NameInfo.getName(); 1487 SourceLocation Loc = NameInfo.getLoc(); 1488 1489 // For anonymous bitfields, the location should point to the type. 1490 if (Loc.isInvalid()) 1491 Loc = D.getSourceRange().getBegin(); 1492 1493 Expr *BitWidth = static_cast<Expr*>(BW); 1494 1495 assert(isa<CXXRecordDecl>(CurContext)); 1496 assert(!DS.isFriendSpecified()); 1497 1498 bool isFunc = D.isDeclarationOfFunction(); 1499 1500 // C++ 9.2p6: A member shall not be declared to have automatic storage 1501 // duration (auto, register) or with the extern storage-class-specifier. 1502 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 1503 // data members and cannot be applied to names declared const or static, 1504 // and cannot be applied to reference members. 1505 switch (DS.getStorageClassSpec()) { 1506 case DeclSpec::SCS_unspecified: 1507 case DeclSpec::SCS_typedef: 1508 case DeclSpec::SCS_static: 1509 // FALL THROUGH. 1510 break; 1511 case DeclSpec::SCS_mutable: 1512 if (isFunc) { 1513 if (DS.getStorageClassSpecLoc().isValid()) 1514 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 1515 else 1516 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function); 1517 1518 // FIXME: It would be nicer if the keyword was ignored only for this 1519 // declarator. Otherwise we could get follow-up errors. 1520 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1521 } 1522 break; 1523 default: 1524 if (DS.getStorageClassSpecLoc().isValid()) 1525 Diag(DS.getStorageClassSpecLoc(), 1526 diag::err_storageclass_invalid_for_member); 1527 else 1528 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member); 1529 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1530 } 1531 1532 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 1533 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 1534 !isFunc); 1535 1536 Decl *Member; 1537 if (isInstField) { 1538 CXXScopeSpec &SS = D.getCXXScopeSpec(); 1539 1540 // Data members must have identifiers for names. 1541 if (Name.getNameKind() != DeclarationName::Identifier) { 1542 Diag(Loc, diag::err_bad_variable_name) 1543 << Name; 1544 return 0; 1545 } 1546 1547 IdentifierInfo *II = Name.getAsIdentifierInfo(); 1548 1549 // Member field could not be with "template" keyword. 1550 // So TemplateParameterLists should be empty in this case. 1551 if (TemplateParameterLists.size()) { 1552 TemplateParameterList* TemplateParams = TemplateParameterLists.get()[0]; 1553 if (TemplateParams->size()) { 1554 // There is no such thing as a member field template. 1555 Diag(D.getIdentifierLoc(), diag::err_template_member) 1556 << II 1557 << SourceRange(TemplateParams->getTemplateLoc(), 1558 TemplateParams->getRAngleLoc()); 1559 } else { 1560 // There is an extraneous 'template<>' for this member. 1561 Diag(TemplateParams->getTemplateLoc(), 1562 diag::err_template_member_noparams) 1563 << II 1564 << SourceRange(TemplateParams->getTemplateLoc(), 1565 TemplateParams->getRAngleLoc()); 1566 } 1567 return 0; 1568 } 1569 1570 if (SS.isSet() && !SS.isInvalid()) { 1571 // The user provided a superfluous scope specifier inside a class 1572 // definition: 1573 // 1574 // class X { 1575 // int X::member; 1576 // }; 1577 DeclContext *DC = 0; 1578 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext)) 1579 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification) 1580 << Name << FixItHint::CreateRemoval(SS.getRange()); 1581 else 1582 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 1583 << Name << SS.getRange(); 1584 1585 SS.clear(); 1586 } 1587 1588 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth, 1589 HasDeferredInit, AS); 1590 assert(Member && "HandleField never returns null"); 1591 } else { 1592 assert(!HasDeferredInit); 1593 1594 Member = HandleDeclarator(S, D, move(TemplateParameterLists)); 1595 if (!Member) { 1596 return 0; 1597 } 1598 1599 // Non-instance-fields can't have a bitfield. 1600 if (BitWidth) { 1601 if (Member->isInvalidDecl()) { 1602 // don't emit another diagnostic. 1603 } else if (isa<VarDecl>(Member)) { 1604 // C++ 9.6p3: A bit-field shall not be a static member. 1605 // "static member 'A' cannot be a bit-field" 1606 Diag(Loc, diag::err_static_not_bitfield) 1607 << Name << BitWidth->getSourceRange(); 1608 } else if (isa<TypedefDecl>(Member)) { 1609 // "typedef member 'x' cannot be a bit-field" 1610 Diag(Loc, diag::err_typedef_not_bitfield) 1611 << Name << BitWidth->getSourceRange(); 1612 } else { 1613 // A function typedef ("typedef int f(); f a;"). 1614 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 1615 Diag(Loc, diag::err_not_integral_type_bitfield) 1616 << Name << cast<ValueDecl>(Member)->getType() 1617 << BitWidth->getSourceRange(); 1618 } 1619 1620 BitWidth = 0; 1621 Member->setInvalidDecl(); 1622 } 1623 1624 Member->setAccess(AS); 1625 1626 // If we have declared a member function template, set the access of the 1627 // templated declaration as well. 1628 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 1629 FunTmpl->getTemplatedDecl()->setAccess(AS); 1630 } 1631 1632 if (VS.isOverrideSpecified()) { 1633 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 1634 if (!MD || !MD->isVirtual()) { 1635 Diag(Member->getLocStart(), 1636 diag::override_keyword_only_allowed_on_virtual_member_functions) 1637 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc()); 1638 } else 1639 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context)); 1640 } 1641 if (VS.isFinalSpecified()) { 1642 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 1643 if (!MD || !MD->isVirtual()) { 1644 Diag(Member->getLocStart(), 1645 diag::override_keyword_only_allowed_on_virtual_member_functions) 1646 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc()); 1647 } else 1648 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context)); 1649 } 1650 1651 if (VS.getLastLocation().isValid()) { 1652 // Update the end location of a method that has a virt-specifiers. 1653 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 1654 MD->setRangeEnd(VS.getLastLocation()); 1655 } 1656 1657 CheckOverrideControl(Member); 1658 1659 assert((Name || isInstField) && "No identifier for non-field ?"); 1660 1661 if (isInstField) 1662 FieldCollector->Add(cast<FieldDecl>(Member)); 1663 return Member; 1664} 1665 1666/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an 1667/// in-class initializer for a non-static C++ class member, and after 1668/// instantiating an in-class initializer in a class template. Such actions 1669/// are deferred until the class is complete. 1670void 1671Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation EqualLoc, 1672 Expr *InitExpr) { 1673 FieldDecl *FD = cast<FieldDecl>(D); 1674 1675 if (!InitExpr) { 1676 FD->setInvalidDecl(); 1677 FD->removeInClassInitializer(); 1678 return; 1679 } 1680 1681 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 1682 FD->setInvalidDecl(); 1683 FD->removeInClassInitializer(); 1684 return; 1685 } 1686 1687 ExprResult Init = InitExpr; 1688 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 1689 // FIXME: if there is no EqualLoc, this is list-initialization. 1690 Init = PerformCopyInitialization( 1691 InitializedEntity::InitializeMember(FD), EqualLoc, InitExpr); 1692 if (Init.isInvalid()) { 1693 FD->setInvalidDecl(); 1694 return; 1695 } 1696 1697 CheckImplicitConversions(Init.get(), EqualLoc); 1698 } 1699 1700 // C++0x [class.base.init]p7: 1701 // The initialization of each base and member constitutes a 1702 // full-expression. 1703 Init = MaybeCreateExprWithCleanups(Init); 1704 if (Init.isInvalid()) { 1705 FD->setInvalidDecl(); 1706 return; 1707 } 1708 1709 InitExpr = Init.release(); 1710 1711 FD->setInClassInitializer(InitExpr); 1712} 1713 1714/// \brief Find the direct and/or virtual base specifiers that 1715/// correspond to the given base type, for use in base initialization 1716/// within a constructor. 1717static bool FindBaseInitializer(Sema &SemaRef, 1718 CXXRecordDecl *ClassDecl, 1719 QualType BaseType, 1720 const CXXBaseSpecifier *&DirectBaseSpec, 1721 const CXXBaseSpecifier *&VirtualBaseSpec) { 1722 // First, check for a direct base class. 1723 DirectBaseSpec = 0; 1724 for (CXXRecordDecl::base_class_const_iterator Base 1725 = ClassDecl->bases_begin(); 1726 Base != ClassDecl->bases_end(); ++Base) { 1727 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) { 1728 // We found a direct base of this type. That's what we're 1729 // initializing. 1730 DirectBaseSpec = &*Base; 1731 break; 1732 } 1733 } 1734 1735 // Check for a virtual base class. 1736 // FIXME: We might be able to short-circuit this if we know in advance that 1737 // there are no virtual bases. 1738 VirtualBaseSpec = 0; 1739 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 1740 // We haven't found a base yet; search the class hierarchy for a 1741 // virtual base class. 1742 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1743 /*DetectVirtual=*/false); 1744 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl), 1745 BaseType, Paths)) { 1746 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 1747 Path != Paths.end(); ++Path) { 1748 if (Path->back().Base->isVirtual()) { 1749 VirtualBaseSpec = Path->back().Base; 1750 break; 1751 } 1752 } 1753 } 1754 } 1755 1756 return DirectBaseSpec || VirtualBaseSpec; 1757} 1758 1759/// \brief Handle a C++ member initializer using braced-init-list syntax. 1760MemInitResult 1761Sema::ActOnMemInitializer(Decl *ConstructorD, 1762 Scope *S, 1763 CXXScopeSpec &SS, 1764 IdentifierInfo *MemberOrBase, 1765 ParsedType TemplateTypeTy, 1766 const DeclSpec &DS, 1767 SourceLocation IdLoc, 1768 Expr *InitList, 1769 SourceLocation EllipsisLoc) { 1770 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 1771 DS, IdLoc, InitList, 1772 EllipsisLoc); 1773} 1774 1775/// \brief Handle a C++ member initializer using parentheses syntax. 1776MemInitResult 1777Sema::ActOnMemInitializer(Decl *ConstructorD, 1778 Scope *S, 1779 CXXScopeSpec &SS, 1780 IdentifierInfo *MemberOrBase, 1781 ParsedType TemplateTypeTy, 1782 const DeclSpec &DS, 1783 SourceLocation IdLoc, 1784 SourceLocation LParenLoc, 1785 Expr **Args, unsigned NumArgs, 1786 SourceLocation RParenLoc, 1787 SourceLocation EllipsisLoc) { 1788 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs, 1789 RParenLoc); 1790 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 1791 DS, IdLoc, List, EllipsisLoc); 1792} 1793 1794namespace { 1795 1796// Callback to only accept typo corrections that can be a valid C++ member 1797// intializer: either a non-static field member or a base class. 1798class MemInitializerValidatorCCC : public CorrectionCandidateCallback { 1799 public: 1800 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 1801 : ClassDecl(ClassDecl) {} 1802 1803 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 1804 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 1805 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 1806 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 1807 else 1808 return isa<TypeDecl>(ND); 1809 } 1810 return false; 1811 } 1812 1813 private: 1814 CXXRecordDecl *ClassDecl; 1815}; 1816 1817} 1818 1819/// \brief Handle a C++ member initializer. 1820MemInitResult 1821Sema::BuildMemInitializer(Decl *ConstructorD, 1822 Scope *S, 1823 CXXScopeSpec &SS, 1824 IdentifierInfo *MemberOrBase, 1825 ParsedType TemplateTypeTy, 1826 const DeclSpec &DS, 1827 SourceLocation IdLoc, 1828 Expr *Init, 1829 SourceLocation EllipsisLoc) { 1830 if (!ConstructorD) 1831 return true; 1832 1833 AdjustDeclIfTemplate(ConstructorD); 1834 1835 CXXConstructorDecl *Constructor 1836 = dyn_cast<CXXConstructorDecl>(ConstructorD); 1837 if (!Constructor) { 1838 // The user wrote a constructor initializer on a function that is 1839 // not a C++ constructor. Ignore the error for now, because we may 1840 // have more member initializers coming; we'll diagnose it just 1841 // once in ActOnMemInitializers. 1842 return true; 1843 } 1844 1845 CXXRecordDecl *ClassDecl = Constructor->getParent(); 1846 1847 // C++ [class.base.init]p2: 1848 // Names in a mem-initializer-id are looked up in the scope of the 1849 // constructor's class and, if not found in that scope, are looked 1850 // up in the scope containing the constructor's definition. 1851 // [Note: if the constructor's class contains a member with the 1852 // same name as a direct or virtual base class of the class, a 1853 // mem-initializer-id naming the member or base class and composed 1854 // of a single identifier refers to the class member. A 1855 // mem-initializer-id for the hidden base class may be specified 1856 // using a qualified name. ] 1857 if (!SS.getScopeRep() && !TemplateTypeTy) { 1858 // Look for a member, first. 1859 DeclContext::lookup_result Result 1860 = ClassDecl->lookup(MemberOrBase); 1861 if (Result.first != Result.second) { 1862 ValueDecl *Member; 1863 if ((Member = dyn_cast<FieldDecl>(*Result.first)) || 1864 (Member = dyn_cast<IndirectFieldDecl>(*Result.first))) { 1865 if (EllipsisLoc.isValid()) 1866 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 1867 << MemberOrBase 1868 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 1869 1870 return BuildMemberInitializer(Member, Init, IdLoc); 1871 } 1872 } 1873 } 1874 // It didn't name a member, so see if it names a class. 1875 QualType BaseType; 1876 TypeSourceInfo *TInfo = 0; 1877 1878 if (TemplateTypeTy) { 1879 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 1880 } else if (DS.getTypeSpecType() == TST_decltype) { 1881 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 1882 } else { 1883 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 1884 LookupParsedName(R, S, &SS); 1885 1886 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 1887 if (!TyD) { 1888 if (R.isAmbiguous()) return true; 1889 1890 // We don't want access-control diagnostics here. 1891 R.suppressDiagnostics(); 1892 1893 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 1894 bool NotUnknownSpecialization = false; 1895 DeclContext *DC = computeDeclContext(SS, false); 1896 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 1897 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 1898 1899 if (!NotUnknownSpecialization) { 1900 // When the scope specifier can refer to a member of an unknown 1901 // specialization, we take it as a type name. 1902 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 1903 SS.getWithLocInContext(Context), 1904 *MemberOrBase, IdLoc); 1905 if (BaseType.isNull()) 1906 return true; 1907 1908 R.clear(); 1909 R.setLookupName(MemberOrBase); 1910 } 1911 } 1912 1913 // If no results were found, try to correct typos. 1914 TypoCorrection Corr; 1915 MemInitializerValidatorCCC Validator(ClassDecl); 1916 if (R.empty() && BaseType.isNull() && 1917 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 1918 Validator, ClassDecl))) { 1919 std::string CorrectedStr(Corr.getAsString(getLangOptions())); 1920 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOptions())); 1921 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 1922 // We have found a non-static data member with a similar 1923 // name to what was typed; complain and initialize that 1924 // member. 1925 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest) 1926 << MemberOrBase << true << CorrectedQuotedStr 1927 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr); 1928 Diag(Member->getLocation(), diag::note_previous_decl) 1929 << CorrectedQuotedStr; 1930 1931 return BuildMemberInitializer(Member, Init, IdLoc); 1932 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 1933 const CXXBaseSpecifier *DirectBaseSpec; 1934 const CXXBaseSpecifier *VirtualBaseSpec; 1935 if (FindBaseInitializer(*this, ClassDecl, 1936 Context.getTypeDeclType(Type), 1937 DirectBaseSpec, VirtualBaseSpec)) { 1938 // We have found a direct or virtual base class with a 1939 // similar name to what was typed; complain and initialize 1940 // that base class. 1941 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest) 1942 << MemberOrBase << false << CorrectedQuotedStr 1943 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr); 1944 1945 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec 1946 : VirtualBaseSpec; 1947 Diag(BaseSpec->getSourceRange().getBegin(), 1948 diag::note_base_class_specified_here) 1949 << BaseSpec->getType() 1950 << BaseSpec->getSourceRange(); 1951 1952 TyD = Type; 1953 } 1954 } 1955 } 1956 1957 if (!TyD && BaseType.isNull()) { 1958 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 1959 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 1960 return true; 1961 } 1962 } 1963 1964 if (BaseType.isNull()) { 1965 BaseType = Context.getTypeDeclType(TyD); 1966 if (SS.isSet()) { 1967 NestedNameSpecifier *Qualifier = 1968 static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 1969 1970 // FIXME: preserve source range information 1971 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType); 1972 } 1973 } 1974 } 1975 1976 if (!TInfo) 1977 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 1978 1979 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 1980} 1981 1982/// Checks a member initializer expression for cases where reference (or 1983/// pointer) members are bound to by-value parameters (or their addresses). 1984static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member, 1985 Expr *Init, 1986 SourceLocation IdLoc) { 1987 QualType MemberTy = Member->getType(); 1988 1989 // We only handle pointers and references currently. 1990 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers? 1991 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType()) 1992 return; 1993 1994 const bool IsPointer = MemberTy->isPointerType(); 1995 if (IsPointer) { 1996 if (const UnaryOperator *Op 1997 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) { 1998 // The only case we're worried about with pointers requires taking the 1999 // address. 2000 if (Op->getOpcode() != UO_AddrOf) 2001 return; 2002 2003 Init = Op->getSubExpr(); 2004 } else { 2005 // We only handle address-of expression initializers for pointers. 2006 return; 2007 } 2008 } 2009 2010 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) { 2011 // Taking the address of a temporary will be diagnosed as a hard error. 2012 if (IsPointer) 2013 return; 2014 2015 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary) 2016 << Member << Init->getSourceRange(); 2017 } else if (const DeclRefExpr *DRE 2018 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) { 2019 // We only warn when referring to a non-reference parameter declaration. 2020 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl()); 2021 if (!Parameter || Parameter->getType()->isReferenceType()) 2022 return; 2023 2024 S.Diag(Init->getExprLoc(), 2025 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr 2026 : diag::warn_bind_ref_member_to_parameter) 2027 << Member << Parameter << Init->getSourceRange(); 2028 } else { 2029 // Other initializers are fine. 2030 return; 2031 } 2032 2033 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here) 2034 << (unsigned)IsPointer; 2035} 2036 2037/// Checks an initializer expression for use of uninitialized fields, such as 2038/// containing the field that is being initialized. Returns true if there is an 2039/// uninitialized field was used an updates the SourceLocation parameter; false 2040/// otherwise. 2041static bool InitExprContainsUninitializedFields(const Stmt *S, 2042 const ValueDecl *LhsField, 2043 SourceLocation *L) { 2044 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField)); 2045 2046 if (isa<CallExpr>(S)) { 2047 // Do not descend into function calls or constructors, as the use 2048 // of an uninitialized field may be valid. One would have to inspect 2049 // the contents of the function/ctor to determine if it is safe or not. 2050 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers 2051 // may be safe, depending on what the function/ctor does. 2052 return false; 2053 } 2054 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) { 2055 const NamedDecl *RhsField = ME->getMemberDecl(); 2056 2057 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) { 2058 // The member expression points to a static data member. 2059 assert(VD->isStaticDataMember() && 2060 "Member points to non-static data member!"); 2061 (void)VD; 2062 return false; 2063 } 2064 2065 if (isa<EnumConstantDecl>(RhsField)) { 2066 // The member expression points to an enum. 2067 return false; 2068 } 2069 2070 if (RhsField == LhsField) { 2071 // Initializing a field with itself. Throw a warning. 2072 // But wait; there are exceptions! 2073 // Exception #1: The field may not belong to this record. 2074 // e.g. Foo(const Foo& rhs) : A(rhs.A) {} 2075 const Expr *base = ME->getBase(); 2076 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) { 2077 // Even though the field matches, it does not belong to this record. 2078 return false; 2079 } 2080 // None of the exceptions triggered; return true to indicate an 2081 // uninitialized field was used. 2082 *L = ME->getMemberLoc(); 2083 return true; 2084 } 2085 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) { 2086 // sizeof/alignof doesn't reference contents, do not warn. 2087 return false; 2088 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) { 2089 // address-of doesn't reference contents (the pointer may be dereferenced 2090 // in the same expression but it would be rare; and weird). 2091 if (UOE->getOpcode() == UO_AddrOf) 2092 return false; 2093 } 2094 for (Stmt::const_child_range it = S->children(); it; ++it) { 2095 if (!*it) { 2096 // An expression such as 'member(arg ?: "")' may trigger this. 2097 continue; 2098 } 2099 if (InitExprContainsUninitializedFields(*it, LhsField, L)) 2100 return true; 2101 } 2102 return false; 2103} 2104 2105MemInitResult 2106Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 2107 SourceLocation IdLoc) { 2108 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 2109 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 2110 assert((DirectMember || IndirectMember) && 2111 "Member must be a FieldDecl or IndirectFieldDecl"); 2112 2113 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 2114 return true; 2115 2116 if (Member->isInvalidDecl()) 2117 return true; 2118 2119 // Diagnose value-uses of fields to initialize themselves, e.g. 2120 // foo(foo) 2121 // where foo is not also a parameter to the constructor. 2122 // TODO: implement -Wuninitialized and fold this into that framework. 2123 Expr **Args; 2124 unsigned NumArgs; 2125 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2126 Args = ParenList->getExprs(); 2127 NumArgs = ParenList->getNumExprs(); 2128 } else { 2129 InitListExpr *InitList = cast<InitListExpr>(Init); 2130 Args = InitList->getInits(); 2131 NumArgs = InitList->getNumInits(); 2132 } 2133 for (unsigned i = 0; i < NumArgs; ++i) { 2134 SourceLocation L; 2135 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) { 2136 // FIXME: Return true in the case when other fields are used before being 2137 // uninitialized. For example, let this field be the i'th field. When 2138 // initializing the i'th field, throw a warning if any of the >= i'th 2139 // fields are used, as they are not yet initialized. 2140 // Right now we are only handling the case where the i'th field uses 2141 // itself in its initializer. 2142 Diag(L, diag::warn_field_is_uninit); 2143 } 2144 } 2145 2146 SourceRange InitRange = Init->getSourceRange(); 2147 2148 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 2149 // Can't check initialization for a member of dependent type or when 2150 // any of the arguments are type-dependent expressions. 2151 DiscardCleanupsInEvaluationContext(); 2152 } else { 2153 bool InitList = false; 2154 if (isa<InitListExpr>(Init)) { 2155 InitList = true; 2156 Args = &Init; 2157 NumArgs = 1; 2158 } 2159 2160 // Initialize the member. 2161 InitializedEntity MemberEntity = 2162 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0) 2163 : InitializedEntity::InitializeMember(IndirectMember, 0); 2164 InitializationKind Kind = 2165 InitList ? InitializationKind::CreateDirectList(IdLoc) 2166 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 2167 InitRange.getEnd()); 2168 2169 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs); 2170 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, 2171 MultiExprArg(*this, Args, NumArgs), 2172 0); 2173 if (MemberInit.isInvalid()) 2174 return true; 2175 2176 CheckImplicitConversions(MemberInit.get(), 2177 InitRange.getBegin()); 2178 2179 // C++0x [class.base.init]p7: 2180 // The initialization of each base and member constitutes a 2181 // full-expression. 2182 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 2183 if (MemberInit.isInvalid()) 2184 return true; 2185 2186 // If we are in a dependent context, template instantiation will 2187 // perform this type-checking again. Just save the arguments that we 2188 // received. 2189 // FIXME: This isn't quite ideal, since our ASTs don't capture all 2190 // of the information that we have about the member 2191 // initializer. However, deconstructing the ASTs is a dicey process, 2192 // and this approach is far more likely to get the corner cases right. 2193 if (CurContext->isDependentContext()) { 2194 // The existing Init will do fine. 2195 } else { 2196 Init = MemberInit.get(); 2197 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc); 2198 } 2199 } 2200 2201 if (DirectMember) { 2202 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 2203 InitRange.getBegin(), Init, 2204 InitRange.getEnd()); 2205 } else { 2206 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 2207 InitRange.getBegin(), Init, 2208 InitRange.getEnd()); 2209 } 2210} 2211 2212MemInitResult 2213Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 2214 CXXRecordDecl *ClassDecl) { 2215 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 2216 if (!LangOpts.CPlusPlus0x) 2217 return Diag(NameLoc, diag::err_delegating_ctor) 2218 << TInfo->getTypeLoc().getLocalSourceRange(); 2219 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 2220 2221 bool InitList = true; 2222 Expr **Args = &Init; 2223 unsigned NumArgs = 1; 2224 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2225 InitList = false; 2226 Args = ParenList->getExprs(); 2227 NumArgs = ParenList->getNumExprs(); 2228 } 2229 2230 SourceRange InitRange = Init->getSourceRange(); 2231 // Initialize the object. 2232 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 2233 QualType(ClassDecl->getTypeForDecl(), 0)); 2234 InitializationKind Kind = 2235 InitList ? InitializationKind::CreateDirectList(NameLoc) 2236 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 2237 InitRange.getEnd()); 2238 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs); 2239 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 2240 MultiExprArg(*this, Args,NumArgs), 2241 0); 2242 if (DelegationInit.isInvalid()) 2243 return true; 2244 2245 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 2246 "Delegating constructor with no target?"); 2247 2248 CheckImplicitConversions(DelegationInit.get(), InitRange.getBegin()); 2249 2250 // C++0x [class.base.init]p7: 2251 // The initialization of each base and member constitutes a 2252 // full-expression. 2253 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit); 2254 if (DelegationInit.isInvalid()) 2255 return true; 2256 2257 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 2258 DelegationInit.takeAs<Expr>(), 2259 InitRange.getEnd()); 2260} 2261 2262MemInitResult 2263Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 2264 Expr *Init, CXXRecordDecl *ClassDecl, 2265 SourceLocation EllipsisLoc) { 2266 SourceLocation BaseLoc 2267 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 2268 2269 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 2270 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 2271 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2272 2273 // C++ [class.base.init]p2: 2274 // [...] Unless the mem-initializer-id names a nonstatic data 2275 // member of the constructor's class or a direct or virtual base 2276 // of that class, the mem-initializer is ill-formed. A 2277 // mem-initializer-list can initialize a base class using any 2278 // name that denotes that base class type. 2279 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 2280 2281 SourceRange InitRange = Init->getSourceRange(); 2282 if (EllipsisLoc.isValid()) { 2283 // This is a pack expansion. 2284 if (!BaseType->containsUnexpandedParameterPack()) { 2285 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2286 << SourceRange(BaseLoc, InitRange.getEnd()); 2287 2288 EllipsisLoc = SourceLocation(); 2289 } 2290 } else { 2291 // Check for any unexpanded parameter packs. 2292 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 2293 return true; 2294 2295 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 2296 return true; 2297 } 2298 2299 // Check for direct and virtual base classes. 2300 const CXXBaseSpecifier *DirectBaseSpec = 0; 2301 const CXXBaseSpecifier *VirtualBaseSpec = 0; 2302 if (!Dependent) { 2303 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 2304 BaseType)) 2305 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 2306 2307 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 2308 VirtualBaseSpec); 2309 2310 // C++ [base.class.init]p2: 2311 // Unless the mem-initializer-id names a nonstatic data member of the 2312 // constructor's class or a direct or virtual base of that class, the 2313 // mem-initializer is ill-formed. 2314 if (!DirectBaseSpec && !VirtualBaseSpec) { 2315 // If the class has any dependent bases, then it's possible that 2316 // one of those types will resolve to the same type as 2317 // BaseType. Therefore, just treat this as a dependent base 2318 // class initialization. FIXME: Should we try to check the 2319 // initialization anyway? It seems odd. 2320 if (ClassDecl->hasAnyDependentBases()) 2321 Dependent = true; 2322 else 2323 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 2324 << BaseType << Context.getTypeDeclType(ClassDecl) 2325 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2326 } 2327 } 2328 2329 if (Dependent) { 2330 DiscardCleanupsInEvaluationContext(); 2331 2332 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 2333 /*IsVirtual=*/false, 2334 InitRange.getBegin(), Init, 2335 InitRange.getEnd(), EllipsisLoc); 2336 } 2337 2338 // C++ [base.class.init]p2: 2339 // If a mem-initializer-id is ambiguous because it designates both 2340 // a direct non-virtual base class and an inherited virtual base 2341 // class, the mem-initializer is ill-formed. 2342 if (DirectBaseSpec && VirtualBaseSpec) 2343 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 2344 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2345 2346 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec); 2347 if (!BaseSpec) 2348 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec); 2349 2350 // Initialize the base. 2351 bool InitList = true; 2352 Expr **Args = &Init; 2353 unsigned NumArgs = 1; 2354 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2355 InitList = false; 2356 Args = ParenList->getExprs(); 2357 NumArgs = ParenList->getNumExprs(); 2358 } 2359 2360 InitializedEntity BaseEntity = 2361 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 2362 InitializationKind Kind = 2363 InitList ? InitializationKind::CreateDirectList(BaseLoc) 2364 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 2365 InitRange.getEnd()); 2366 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs); 2367 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, 2368 MultiExprArg(*this, Args, NumArgs), 2369 0); 2370 if (BaseInit.isInvalid()) 2371 return true; 2372 2373 CheckImplicitConversions(BaseInit.get(), InitRange.getBegin()); 2374 2375 // C++0x [class.base.init]p7: 2376 // The initialization of each base and member constitutes a 2377 // full-expression. 2378 BaseInit = MaybeCreateExprWithCleanups(BaseInit); 2379 if (BaseInit.isInvalid()) 2380 return true; 2381 2382 // If we are in a dependent context, template instantiation will 2383 // perform this type-checking again. Just save the arguments that we 2384 // received in a ParenListExpr. 2385 // FIXME: This isn't quite ideal, since our ASTs don't capture all 2386 // of the information that we have about the base 2387 // initializer. However, deconstructing the ASTs is a dicey process, 2388 // and this approach is far more likely to get the corner cases right. 2389 if (CurContext->isDependentContext()) 2390 BaseInit = Owned(Init); 2391 2392 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 2393 BaseSpec->isVirtual(), 2394 InitRange.getBegin(), 2395 BaseInit.takeAs<Expr>(), 2396 InitRange.getEnd(), EllipsisLoc); 2397} 2398 2399// Create a static_cast\<T&&>(expr). 2400static Expr *CastForMoving(Sema &SemaRef, Expr *E) { 2401 QualType ExprType = E->getType(); 2402 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType); 2403 SourceLocation ExprLoc = E->getLocStart(); 2404 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 2405 TargetType, ExprLoc); 2406 2407 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 2408 SourceRange(ExprLoc, ExprLoc), 2409 E->getSourceRange()).take(); 2410} 2411 2412/// ImplicitInitializerKind - How an implicit base or member initializer should 2413/// initialize its base or member. 2414enum ImplicitInitializerKind { 2415 IIK_Default, 2416 IIK_Copy, 2417 IIK_Move 2418}; 2419 2420static bool 2421BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 2422 ImplicitInitializerKind ImplicitInitKind, 2423 CXXBaseSpecifier *BaseSpec, 2424 bool IsInheritedVirtualBase, 2425 CXXCtorInitializer *&CXXBaseInit) { 2426 InitializedEntity InitEntity 2427 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 2428 IsInheritedVirtualBase); 2429 2430 ExprResult BaseInit; 2431 2432 switch (ImplicitInitKind) { 2433 case IIK_Default: { 2434 InitializationKind InitKind 2435 = InitializationKind::CreateDefault(Constructor->getLocation()); 2436 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0); 2437 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, 2438 MultiExprArg(SemaRef, 0, 0)); 2439 break; 2440 } 2441 2442 case IIK_Move: 2443 case IIK_Copy: { 2444 bool Moving = ImplicitInitKind == IIK_Move; 2445 ParmVarDecl *Param = Constructor->getParamDecl(0); 2446 QualType ParamType = Param->getType().getNonReferenceType(); 2447 2448 Expr *CopyCtorArg = 2449 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 2450 SourceLocation(), Param, 2451 Constructor->getLocation(), ParamType, 2452 VK_LValue, 0); 2453 2454 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 2455 2456 // Cast to the base class to avoid ambiguities. 2457 QualType ArgTy = 2458 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 2459 ParamType.getQualifiers()); 2460 2461 if (Moving) { 2462 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 2463 } 2464 2465 CXXCastPath BasePath; 2466 BasePath.push_back(BaseSpec); 2467 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 2468 CK_UncheckedDerivedToBase, 2469 Moving ? VK_XValue : VK_LValue, 2470 &BasePath).take(); 2471 2472 InitializationKind InitKind 2473 = InitializationKind::CreateDirect(Constructor->getLocation(), 2474 SourceLocation(), SourceLocation()); 2475 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 2476 &CopyCtorArg, 1); 2477 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, 2478 MultiExprArg(&CopyCtorArg, 1)); 2479 break; 2480 } 2481 } 2482 2483 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 2484 if (BaseInit.isInvalid()) 2485 return true; 2486 2487 CXXBaseInit = 2488 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 2489 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 2490 SourceLocation()), 2491 BaseSpec->isVirtual(), 2492 SourceLocation(), 2493 BaseInit.takeAs<Expr>(), 2494 SourceLocation(), 2495 SourceLocation()); 2496 2497 return false; 2498} 2499 2500static bool RefersToRValueRef(Expr *MemRef) { 2501 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 2502 return Referenced->getType()->isRValueReferenceType(); 2503} 2504 2505static bool 2506BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 2507 ImplicitInitializerKind ImplicitInitKind, 2508 FieldDecl *Field, IndirectFieldDecl *Indirect, 2509 CXXCtorInitializer *&CXXMemberInit) { 2510 if (Field->isInvalidDecl()) 2511 return true; 2512 2513 SourceLocation Loc = Constructor->getLocation(); 2514 2515 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 2516 bool Moving = ImplicitInitKind == IIK_Move; 2517 ParmVarDecl *Param = Constructor->getParamDecl(0); 2518 QualType ParamType = Param->getType().getNonReferenceType(); 2519 2520 // Suppress copying zero-width bitfields. 2521 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0) 2522 return false; 2523 2524 Expr *MemberExprBase = 2525 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 2526 SourceLocation(), Param, 2527 Loc, ParamType, VK_LValue, 0); 2528 2529 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 2530 2531 if (Moving) { 2532 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 2533 } 2534 2535 // Build a reference to this field within the parameter. 2536 CXXScopeSpec SS; 2537 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 2538 Sema::LookupMemberName); 2539 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 2540 : cast<ValueDecl>(Field), AS_public); 2541 MemberLookup.resolveKind(); 2542 ExprResult CtorArg 2543 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 2544 ParamType, Loc, 2545 /*IsArrow=*/false, 2546 SS, 2547 /*TemplateKWLoc=*/SourceLocation(), 2548 /*FirstQualifierInScope=*/0, 2549 MemberLookup, 2550 /*TemplateArgs=*/0); 2551 if (CtorArg.isInvalid()) 2552 return true; 2553 2554 // C++11 [class.copy]p15: 2555 // - if a member m has rvalue reference type T&&, it is direct-initialized 2556 // with static_cast<T&&>(x.m); 2557 if (RefersToRValueRef(CtorArg.get())) { 2558 CtorArg = CastForMoving(SemaRef, CtorArg.take()); 2559 } 2560 2561 // When the field we are copying is an array, create index variables for 2562 // each dimension of the array. We use these index variables to subscript 2563 // the source array, and other clients (e.g., CodeGen) will perform the 2564 // necessary iteration with these index variables. 2565 SmallVector<VarDecl *, 4> IndexVariables; 2566 QualType BaseType = Field->getType(); 2567 QualType SizeType = SemaRef.Context.getSizeType(); 2568 bool InitializingArray = false; 2569 while (const ConstantArrayType *Array 2570 = SemaRef.Context.getAsConstantArrayType(BaseType)) { 2571 InitializingArray = true; 2572 // Create the iteration variable for this array index. 2573 IdentifierInfo *IterationVarName = 0; 2574 { 2575 SmallString<8> Str; 2576 llvm::raw_svector_ostream OS(Str); 2577 OS << "__i" << IndexVariables.size(); 2578 IterationVarName = &SemaRef.Context.Idents.get(OS.str()); 2579 } 2580 VarDecl *IterationVar 2581 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc, 2582 IterationVarName, SizeType, 2583 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc), 2584 SC_None, SC_None); 2585 IndexVariables.push_back(IterationVar); 2586 2587 // Create a reference to the iteration variable. 2588 ExprResult IterationVarRef 2589 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 2590 assert(!IterationVarRef.isInvalid() && 2591 "Reference to invented variable cannot fail!"); 2592 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take()); 2593 assert(!IterationVarRef.isInvalid() && 2594 "Conversion of invented variable cannot fail!"); 2595 2596 // Subscript the array with this iteration variable. 2597 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc, 2598 IterationVarRef.take(), 2599 Loc); 2600 if (CtorArg.isInvalid()) 2601 return true; 2602 2603 BaseType = Array->getElementType(); 2604 } 2605 2606 // The array subscript expression is an lvalue, which is wrong for moving. 2607 if (Moving && InitializingArray) 2608 CtorArg = CastForMoving(SemaRef, CtorArg.take()); 2609 2610 // Construct the entity that we will be initializing. For an array, this 2611 // will be first element in the array, which may require several levels 2612 // of array-subscript entities. 2613 SmallVector<InitializedEntity, 4> Entities; 2614 Entities.reserve(1 + IndexVariables.size()); 2615 if (Indirect) 2616 Entities.push_back(InitializedEntity::InitializeMember(Indirect)); 2617 else 2618 Entities.push_back(InitializedEntity::InitializeMember(Field)); 2619 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 2620 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context, 2621 0, 2622 Entities.back())); 2623 2624 // Direct-initialize to use the copy constructor. 2625 InitializationKind InitKind = 2626 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 2627 2628 Expr *CtorArgE = CtorArg.takeAs<Expr>(); 2629 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, 2630 &CtorArgE, 1); 2631 2632 ExprResult MemberInit 2633 = InitSeq.Perform(SemaRef, Entities.back(), InitKind, 2634 MultiExprArg(&CtorArgE, 1)); 2635 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 2636 if (MemberInit.isInvalid()) 2637 return true; 2638 2639 if (Indirect) { 2640 assert(IndexVariables.size() == 0 && 2641 "Indirect field improperly initialized"); 2642 CXXMemberInit 2643 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 2644 Loc, Loc, 2645 MemberInit.takeAs<Expr>(), 2646 Loc); 2647 } else 2648 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, 2649 Loc, MemberInit.takeAs<Expr>(), 2650 Loc, 2651 IndexVariables.data(), 2652 IndexVariables.size()); 2653 return false; 2654 } 2655 2656 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!"); 2657 2658 QualType FieldBaseElementType = 2659 SemaRef.Context.getBaseElementType(Field->getType()); 2660 2661 if (FieldBaseElementType->isRecordType()) { 2662 InitializedEntity InitEntity 2663 = Indirect? InitializedEntity::InitializeMember(Indirect) 2664 : InitializedEntity::InitializeMember(Field); 2665 InitializationKind InitKind = 2666 InitializationKind::CreateDefault(Loc); 2667 2668 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0); 2669 ExprResult MemberInit = 2670 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg()); 2671 2672 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 2673 if (MemberInit.isInvalid()) 2674 return true; 2675 2676 if (Indirect) 2677 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 2678 Indirect, Loc, 2679 Loc, 2680 MemberInit.get(), 2681 Loc); 2682 else 2683 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 2684 Field, Loc, Loc, 2685 MemberInit.get(), 2686 Loc); 2687 return false; 2688 } 2689 2690 if (!Field->getParent()->isUnion()) { 2691 if (FieldBaseElementType->isReferenceType()) { 2692 SemaRef.Diag(Constructor->getLocation(), 2693 diag::err_uninitialized_member_in_ctor) 2694 << (int)Constructor->isImplicit() 2695 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 2696 << 0 << Field->getDeclName(); 2697 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 2698 return true; 2699 } 2700 2701 if (FieldBaseElementType.isConstQualified()) { 2702 SemaRef.Diag(Constructor->getLocation(), 2703 diag::err_uninitialized_member_in_ctor) 2704 << (int)Constructor->isImplicit() 2705 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 2706 << 1 << Field->getDeclName(); 2707 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 2708 return true; 2709 } 2710 } 2711 2712 if (SemaRef.getLangOptions().ObjCAutoRefCount && 2713 FieldBaseElementType->isObjCRetainableType() && 2714 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None && 2715 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) { 2716 // Instant objects: 2717 // Default-initialize Objective-C pointers to NULL. 2718 CXXMemberInit 2719 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 2720 Loc, Loc, 2721 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 2722 Loc); 2723 return false; 2724 } 2725 2726 // Nothing to initialize. 2727 CXXMemberInit = 0; 2728 return false; 2729} 2730 2731namespace { 2732struct BaseAndFieldInfo { 2733 Sema &S; 2734 CXXConstructorDecl *Ctor; 2735 bool AnyErrorsInInits; 2736 ImplicitInitializerKind IIK; 2737 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 2738 SmallVector<CXXCtorInitializer*, 8> AllToInit; 2739 2740 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 2741 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 2742 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 2743 if (Generated && Ctor->isCopyConstructor()) 2744 IIK = IIK_Copy; 2745 else if (Generated && Ctor->isMoveConstructor()) 2746 IIK = IIK_Move; 2747 else 2748 IIK = IIK_Default; 2749 } 2750 2751 bool isImplicitCopyOrMove() const { 2752 switch (IIK) { 2753 case IIK_Copy: 2754 case IIK_Move: 2755 return true; 2756 2757 case IIK_Default: 2758 return false; 2759 } 2760 2761 llvm_unreachable("Invalid ImplicitInitializerKind!"); 2762 } 2763}; 2764} 2765 2766/// \brief Determine whether the given indirect field declaration is somewhere 2767/// within an anonymous union. 2768static bool isWithinAnonymousUnion(IndirectFieldDecl *F) { 2769 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(), 2770 CEnd = F->chain_end(); 2771 C != CEnd; ++C) 2772 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext())) 2773 if (Record->isUnion()) 2774 return true; 2775 2776 return false; 2777} 2778 2779/// \brief Determine whether the given type is an incomplete or zero-lenfgth 2780/// array type. 2781static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 2782 if (T->isIncompleteArrayType()) 2783 return true; 2784 2785 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 2786 if (!ArrayT->getSize()) 2787 return true; 2788 2789 T = ArrayT->getElementType(); 2790 } 2791 2792 return false; 2793} 2794 2795static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 2796 FieldDecl *Field, 2797 IndirectFieldDecl *Indirect = 0) { 2798 2799 // Overwhelmingly common case: we have a direct initializer for this field. 2800 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) { 2801 Info.AllToInit.push_back(Init); 2802 return false; 2803 } 2804 2805 // C++0x [class.base.init]p8: if the entity is a non-static data member that 2806 // has a brace-or-equal-initializer, the entity is initialized as specified 2807 // in [dcl.init]. 2808 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 2809 CXXCtorInitializer *Init; 2810 if (Indirect) 2811 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 2812 SourceLocation(), 2813 SourceLocation(), 0, 2814 SourceLocation()); 2815 else 2816 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 2817 SourceLocation(), 2818 SourceLocation(), 0, 2819 SourceLocation()); 2820 Info.AllToInit.push_back(Init); 2821 return false; 2822 } 2823 2824 // Don't build an implicit initializer for union members if none was 2825 // explicitly specified. 2826 if (Field->getParent()->isUnion() || 2827 (Indirect && isWithinAnonymousUnion(Indirect))) 2828 return false; 2829 2830 // Don't initialize incomplete or zero-length arrays. 2831 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 2832 return false; 2833 2834 // Don't try to build an implicit initializer if there were semantic 2835 // errors in any of the initializers (and therefore we might be 2836 // missing some that the user actually wrote). 2837 if (Info.AnyErrorsInInits || Field->isInvalidDecl()) 2838 return false; 2839 2840 CXXCtorInitializer *Init = 0; 2841 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 2842 Indirect, Init)) 2843 return true; 2844 2845 if (Init) 2846 Info.AllToInit.push_back(Init); 2847 2848 return false; 2849} 2850 2851bool 2852Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 2853 CXXCtorInitializer *Initializer) { 2854 assert(Initializer->isDelegatingInitializer()); 2855 Constructor->setNumCtorInitializers(1); 2856 CXXCtorInitializer **initializer = 2857 new (Context) CXXCtorInitializer*[1]; 2858 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 2859 Constructor->setCtorInitializers(initializer); 2860 2861 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 2862 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 2863 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 2864 } 2865 2866 DelegatingCtorDecls.push_back(Constructor); 2867 2868 return false; 2869} 2870 2871bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, 2872 CXXCtorInitializer **Initializers, 2873 unsigned NumInitializers, 2874 bool AnyErrors) { 2875 if (Constructor->isDependentContext()) { 2876 // Just store the initializers as written, they will be checked during 2877 // instantiation. 2878 if (NumInitializers > 0) { 2879 Constructor->setNumCtorInitializers(NumInitializers); 2880 CXXCtorInitializer **baseOrMemberInitializers = 2881 new (Context) CXXCtorInitializer*[NumInitializers]; 2882 memcpy(baseOrMemberInitializers, Initializers, 2883 NumInitializers * sizeof(CXXCtorInitializer*)); 2884 Constructor->setCtorInitializers(baseOrMemberInitializers); 2885 } 2886 2887 return false; 2888 } 2889 2890 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 2891 2892 // We need to build the initializer AST according to order of construction 2893 // and not what user specified in the Initializers list. 2894 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 2895 if (!ClassDecl) 2896 return true; 2897 2898 bool HadError = false; 2899 2900 for (unsigned i = 0; i < NumInitializers; i++) { 2901 CXXCtorInitializer *Member = Initializers[i]; 2902 2903 if (Member->isBaseInitializer()) 2904 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 2905 else 2906 Info.AllBaseFields[Member->getAnyMember()] = Member; 2907 } 2908 2909 // Keep track of the direct virtual bases. 2910 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 2911 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(), 2912 E = ClassDecl->bases_end(); I != E; ++I) { 2913 if (I->isVirtual()) 2914 DirectVBases.insert(I); 2915 } 2916 2917 // Push virtual bases before others. 2918 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 2919 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 2920 2921 if (CXXCtorInitializer *Value 2922 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) { 2923 Info.AllToInit.push_back(Value); 2924 } else if (!AnyErrors) { 2925 bool IsInheritedVirtualBase = !DirectVBases.count(VBase); 2926 CXXCtorInitializer *CXXBaseInit; 2927 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 2928 VBase, IsInheritedVirtualBase, 2929 CXXBaseInit)) { 2930 HadError = true; 2931 continue; 2932 } 2933 2934 Info.AllToInit.push_back(CXXBaseInit); 2935 } 2936 } 2937 2938 // Non-virtual bases. 2939 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 2940 E = ClassDecl->bases_end(); Base != E; ++Base) { 2941 // Virtuals are in the virtual base list and already constructed. 2942 if (Base->isVirtual()) 2943 continue; 2944 2945 if (CXXCtorInitializer *Value 2946 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) { 2947 Info.AllToInit.push_back(Value); 2948 } else if (!AnyErrors) { 2949 CXXCtorInitializer *CXXBaseInit; 2950 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 2951 Base, /*IsInheritedVirtualBase=*/false, 2952 CXXBaseInit)) { 2953 HadError = true; 2954 continue; 2955 } 2956 2957 Info.AllToInit.push_back(CXXBaseInit); 2958 } 2959 } 2960 2961 // Fields. 2962 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(), 2963 MemEnd = ClassDecl->decls_end(); 2964 Mem != MemEnd; ++Mem) { 2965 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) { 2966 // C++ [class.bit]p2: 2967 // A declaration for a bit-field that omits the identifier declares an 2968 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 2969 // initialized. 2970 if (F->isUnnamedBitfield()) 2971 continue; 2972 2973 // If we're not generating the implicit copy/move constructor, then we'll 2974 // handle anonymous struct/union fields based on their individual 2975 // indirect fields. 2976 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default) 2977 continue; 2978 2979 if (CollectFieldInitializer(*this, Info, F)) 2980 HadError = true; 2981 continue; 2982 } 2983 2984 // Beyond this point, we only consider default initialization. 2985 if (Info.IIK != IIK_Default) 2986 continue; 2987 2988 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) { 2989 if (F->getType()->isIncompleteArrayType()) { 2990 assert(ClassDecl->hasFlexibleArrayMember() && 2991 "Incomplete array type is not valid"); 2992 continue; 2993 } 2994 2995 // Initialize each field of an anonymous struct individually. 2996 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 2997 HadError = true; 2998 2999 continue; 3000 } 3001 } 3002 3003 NumInitializers = Info.AllToInit.size(); 3004 if (NumInitializers > 0) { 3005 Constructor->setNumCtorInitializers(NumInitializers); 3006 CXXCtorInitializer **baseOrMemberInitializers = 3007 new (Context) CXXCtorInitializer*[NumInitializers]; 3008 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 3009 NumInitializers * sizeof(CXXCtorInitializer*)); 3010 Constructor->setCtorInitializers(baseOrMemberInitializers); 3011 3012 // Constructors implicitly reference the base and member 3013 // destructors. 3014 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 3015 Constructor->getParent()); 3016 } 3017 3018 return HadError; 3019} 3020 3021static void *GetKeyForTopLevelField(FieldDecl *Field) { 3022 // For anonymous unions, use the class declaration as the key. 3023 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 3024 if (RT->getDecl()->isAnonymousStructOrUnion()) 3025 return static_cast<void *>(RT->getDecl()); 3026 } 3027 return static_cast<void *>(Field); 3028} 3029 3030static void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 3031 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr()); 3032} 3033 3034static void *GetKeyForMember(ASTContext &Context, 3035 CXXCtorInitializer *Member) { 3036 if (!Member->isAnyMemberInitializer()) 3037 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 3038 3039 // For fields injected into the class via declaration of an anonymous union, 3040 // use its anonymous union class declaration as the unique key. 3041 FieldDecl *Field = Member->getAnyMember(); 3042 3043 // If the field is a member of an anonymous struct or union, our key 3044 // is the anonymous record decl that's a direct child of the class. 3045 RecordDecl *RD = Field->getParent(); 3046 if (RD->isAnonymousStructOrUnion()) { 3047 while (true) { 3048 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext()); 3049 if (Parent->isAnonymousStructOrUnion()) 3050 RD = Parent; 3051 else 3052 break; 3053 } 3054 3055 return static_cast<void *>(RD); 3056 } 3057 3058 return static_cast<void *>(Field); 3059} 3060 3061static void 3062DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef, 3063 const CXXConstructorDecl *Constructor, 3064 CXXCtorInitializer **Inits, 3065 unsigned NumInits) { 3066 if (Constructor->getDeclContext()->isDependentContext()) 3067 return; 3068 3069 // Don't check initializers order unless the warning is enabled at the 3070 // location of at least one initializer. 3071 bool ShouldCheckOrder = false; 3072 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) { 3073 CXXCtorInitializer *Init = Inits[InitIndex]; 3074 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order, 3075 Init->getSourceLocation()) 3076 != DiagnosticsEngine::Ignored) { 3077 ShouldCheckOrder = true; 3078 break; 3079 } 3080 } 3081 if (!ShouldCheckOrder) 3082 return; 3083 3084 // Build the list of bases and members in the order that they'll 3085 // actually be initialized. The explicit initializers should be in 3086 // this same order but may be missing things. 3087 SmallVector<const void*, 32> IdealInitKeys; 3088 3089 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 3090 3091 // 1. Virtual bases. 3092 for (CXXRecordDecl::base_class_const_iterator VBase = 3093 ClassDecl->vbases_begin(), 3094 E = ClassDecl->vbases_end(); VBase != E; ++VBase) 3095 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType())); 3096 3097 // 2. Non-virtual bases. 3098 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(), 3099 E = ClassDecl->bases_end(); Base != E; ++Base) { 3100 if (Base->isVirtual()) 3101 continue; 3102 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType())); 3103 } 3104 3105 // 3. Direct fields. 3106 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 3107 E = ClassDecl->field_end(); Field != E; ++Field) { 3108 if (Field->isUnnamedBitfield()) 3109 continue; 3110 3111 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field)); 3112 } 3113 3114 unsigned NumIdealInits = IdealInitKeys.size(); 3115 unsigned IdealIndex = 0; 3116 3117 CXXCtorInitializer *PrevInit = 0; 3118 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) { 3119 CXXCtorInitializer *Init = Inits[InitIndex]; 3120 void *InitKey = GetKeyForMember(SemaRef.Context, Init); 3121 3122 // Scan forward to try to find this initializer in the idealized 3123 // initializers list. 3124 for (; IdealIndex != NumIdealInits; ++IdealIndex) 3125 if (InitKey == IdealInitKeys[IdealIndex]) 3126 break; 3127 3128 // If we didn't find this initializer, it must be because we 3129 // scanned past it on a previous iteration. That can only 3130 // happen if we're out of order; emit a warning. 3131 if (IdealIndex == NumIdealInits && PrevInit) { 3132 Sema::SemaDiagnosticBuilder D = 3133 SemaRef.Diag(PrevInit->getSourceLocation(), 3134 diag::warn_initializer_out_of_order); 3135 3136 if (PrevInit->isAnyMemberInitializer()) 3137 D << 0 << PrevInit->getAnyMember()->getDeclName(); 3138 else 3139 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 3140 3141 if (Init->isAnyMemberInitializer()) 3142 D << 0 << Init->getAnyMember()->getDeclName(); 3143 else 3144 D << 1 << Init->getTypeSourceInfo()->getType(); 3145 3146 // Move back to the initializer's location in the ideal list. 3147 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 3148 if (InitKey == IdealInitKeys[IdealIndex]) 3149 break; 3150 3151 assert(IdealIndex != NumIdealInits && 3152 "initializer not found in initializer list"); 3153 } 3154 3155 PrevInit = Init; 3156 } 3157} 3158 3159namespace { 3160bool CheckRedundantInit(Sema &S, 3161 CXXCtorInitializer *Init, 3162 CXXCtorInitializer *&PrevInit) { 3163 if (!PrevInit) { 3164 PrevInit = Init; 3165 return false; 3166 } 3167 3168 if (FieldDecl *Field = Init->getMember()) 3169 S.Diag(Init->getSourceLocation(), 3170 diag::err_multiple_mem_initialization) 3171 << Field->getDeclName() 3172 << Init->getSourceRange(); 3173 else { 3174 const Type *BaseClass = Init->getBaseClass(); 3175 assert(BaseClass && "neither field nor base"); 3176 S.Diag(Init->getSourceLocation(), 3177 diag::err_multiple_base_initialization) 3178 << QualType(BaseClass, 0) 3179 << Init->getSourceRange(); 3180 } 3181 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 3182 << 0 << PrevInit->getSourceRange(); 3183 3184 return true; 3185} 3186 3187typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 3188typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 3189 3190bool CheckRedundantUnionInit(Sema &S, 3191 CXXCtorInitializer *Init, 3192 RedundantUnionMap &Unions) { 3193 FieldDecl *Field = Init->getAnyMember(); 3194 RecordDecl *Parent = Field->getParent(); 3195 NamedDecl *Child = Field; 3196 3197 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 3198 if (Parent->isUnion()) { 3199 UnionEntry &En = Unions[Parent]; 3200 if (En.first && En.first != Child) { 3201 S.Diag(Init->getSourceLocation(), 3202 diag::err_multiple_mem_union_initialization) 3203 << Field->getDeclName() 3204 << Init->getSourceRange(); 3205 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 3206 << 0 << En.second->getSourceRange(); 3207 return true; 3208 } 3209 if (!En.first) { 3210 En.first = Child; 3211 En.second = Init; 3212 } 3213 if (!Parent->isAnonymousStructOrUnion()) 3214 return false; 3215 } 3216 3217 Child = Parent; 3218 Parent = cast<RecordDecl>(Parent->getDeclContext()); 3219 } 3220 3221 return false; 3222} 3223} 3224 3225/// ActOnMemInitializers - Handle the member initializers for a constructor. 3226void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 3227 SourceLocation ColonLoc, 3228 CXXCtorInitializer **meminits, 3229 unsigned NumMemInits, 3230 bool AnyErrors) { 3231 if (!ConstructorDecl) 3232 return; 3233 3234 AdjustDeclIfTemplate(ConstructorDecl); 3235 3236 CXXConstructorDecl *Constructor 3237 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 3238 3239 if (!Constructor) { 3240 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 3241 return; 3242 } 3243 3244 CXXCtorInitializer **MemInits = 3245 reinterpret_cast<CXXCtorInitializer **>(meminits); 3246 3247 // Mapping for the duplicate initializers check. 3248 // For member initializers, this is keyed with a FieldDecl*. 3249 // For base initializers, this is keyed with a Type*. 3250 llvm::DenseMap<void*, CXXCtorInitializer *> Members; 3251 3252 // Mapping for the inconsistent anonymous-union initializers check. 3253 RedundantUnionMap MemberUnions; 3254 3255 bool HadError = false; 3256 for (unsigned i = 0; i < NumMemInits; i++) { 3257 CXXCtorInitializer *Init = MemInits[i]; 3258 3259 // Set the source order index. 3260 Init->setSourceOrder(i); 3261 3262 if (Init->isAnyMemberInitializer()) { 3263 FieldDecl *Field = Init->getAnyMember(); 3264 if (CheckRedundantInit(*this, Init, Members[Field]) || 3265 CheckRedundantUnionInit(*this, Init, MemberUnions)) 3266 HadError = true; 3267 } else if (Init->isBaseInitializer()) { 3268 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0)); 3269 if (CheckRedundantInit(*this, Init, Members[Key])) 3270 HadError = true; 3271 } else { 3272 assert(Init->isDelegatingInitializer()); 3273 // This must be the only initializer 3274 if (i != 0 || NumMemInits > 1) { 3275 Diag(MemInits[0]->getSourceLocation(), 3276 diag::err_delegating_initializer_alone) 3277 << MemInits[0]->getSourceRange(); 3278 HadError = true; 3279 // We will treat this as being the only initializer. 3280 } 3281 SetDelegatingInitializer(Constructor, MemInits[i]); 3282 // Return immediately as the initializer is set. 3283 return; 3284 } 3285 } 3286 3287 if (HadError) 3288 return; 3289 3290 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits); 3291 3292 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors); 3293} 3294 3295void 3296Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 3297 CXXRecordDecl *ClassDecl) { 3298 // Ignore dependent contexts. Also ignore unions, since their members never 3299 // have destructors implicitly called. 3300 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 3301 return; 3302 3303 // FIXME: all the access-control diagnostics are positioned on the 3304 // field/base declaration. That's probably good; that said, the 3305 // user might reasonably want to know why the destructor is being 3306 // emitted, and we currently don't say. 3307 3308 // Non-static data members. 3309 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(), 3310 E = ClassDecl->field_end(); I != E; ++I) { 3311 FieldDecl *Field = *I; 3312 if (Field->isInvalidDecl()) 3313 continue; 3314 3315 // Don't destroy incomplete or zero-length arrays. 3316 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 3317 continue; 3318 3319 QualType FieldType = Context.getBaseElementType(Field->getType()); 3320 3321 const RecordType* RT = FieldType->getAs<RecordType>(); 3322 if (!RT) 3323 continue; 3324 3325 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3326 if (FieldClassDecl->isInvalidDecl()) 3327 continue; 3328 if (FieldClassDecl->hasTrivialDestructor()) 3329 continue; 3330 3331 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 3332 assert(Dtor && "No dtor found for FieldClassDecl!"); 3333 CheckDestructorAccess(Field->getLocation(), Dtor, 3334 PDiag(diag::err_access_dtor_field) 3335 << Field->getDeclName() 3336 << FieldType); 3337 3338 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 3339 } 3340 3341 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 3342 3343 // Bases. 3344 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 3345 E = ClassDecl->bases_end(); Base != E; ++Base) { 3346 // Bases are always records in a well-formed non-dependent class. 3347 const RecordType *RT = Base->getType()->getAs<RecordType>(); 3348 3349 // Remember direct virtual bases. 3350 if (Base->isVirtual()) 3351 DirectVirtualBases.insert(RT); 3352 3353 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3354 // If our base class is invalid, we probably can't get its dtor anyway. 3355 if (BaseClassDecl->isInvalidDecl()) 3356 continue; 3357 // Ignore trivial destructors. 3358 if (BaseClassDecl->hasTrivialDestructor()) 3359 continue; 3360 3361 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 3362 assert(Dtor && "No dtor found for BaseClassDecl!"); 3363 3364 // FIXME: caret should be on the start of the class name 3365 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor, 3366 PDiag(diag::err_access_dtor_base) 3367 << Base->getType() 3368 << Base->getSourceRange()); 3369 3370 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 3371 } 3372 3373 // Virtual bases. 3374 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 3375 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 3376 3377 // Bases are always records in a well-formed non-dependent class. 3378 const RecordType *RT = VBase->getType()->getAs<RecordType>(); 3379 3380 // Ignore direct virtual bases. 3381 if (DirectVirtualBases.count(RT)) 3382 continue; 3383 3384 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3385 // If our base class is invalid, we probably can't get its dtor anyway. 3386 if (BaseClassDecl->isInvalidDecl()) 3387 continue; 3388 // Ignore trivial destructors. 3389 if (BaseClassDecl->hasTrivialDestructor()) 3390 continue; 3391 3392 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 3393 assert(Dtor && "No dtor found for BaseClassDecl!"); 3394 CheckDestructorAccess(ClassDecl->getLocation(), Dtor, 3395 PDiag(diag::err_access_dtor_vbase) 3396 << VBase->getType()); 3397 3398 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 3399 } 3400} 3401 3402void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 3403 if (!CDtorDecl) 3404 return; 3405 3406 if (CXXConstructorDecl *Constructor 3407 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) 3408 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false); 3409} 3410 3411bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 3412 unsigned DiagID, AbstractDiagSelID SelID) { 3413 if (SelID == -1) 3414 return RequireNonAbstractType(Loc, T, PDiag(DiagID)); 3415 else 3416 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID); 3417} 3418 3419bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 3420 const PartialDiagnostic &PD) { 3421 if (!getLangOptions().CPlusPlus) 3422 return false; 3423 3424 if (const ArrayType *AT = Context.getAsArrayType(T)) 3425 return RequireNonAbstractType(Loc, AT->getElementType(), PD); 3426 3427 if (const PointerType *PT = T->getAs<PointerType>()) { 3428 // Find the innermost pointer type. 3429 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 3430 PT = T; 3431 3432 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 3433 return RequireNonAbstractType(Loc, AT->getElementType(), PD); 3434 } 3435 3436 const RecordType *RT = T->getAs<RecordType>(); 3437 if (!RT) 3438 return false; 3439 3440 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 3441 3442 // We can't answer whether something is abstract until it has a 3443 // definition. If it's currently being defined, we'll walk back 3444 // over all the declarations when we have a full definition. 3445 const CXXRecordDecl *Def = RD->getDefinition(); 3446 if (!Def || Def->isBeingDefined()) 3447 return false; 3448 3449 if (!RD->isAbstract()) 3450 return false; 3451 3452 Diag(Loc, PD) << RD->getDeclName(); 3453 DiagnoseAbstractType(RD); 3454 3455 return true; 3456} 3457 3458void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 3459 // Check if we've already emitted the list of pure virtual functions 3460 // for this class. 3461 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 3462 return; 3463 3464 CXXFinalOverriderMap FinalOverriders; 3465 RD->getFinalOverriders(FinalOverriders); 3466 3467 // Keep a set of seen pure methods so we won't diagnose the same method 3468 // more than once. 3469 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 3470 3471 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 3472 MEnd = FinalOverriders.end(); 3473 M != MEnd; 3474 ++M) { 3475 for (OverridingMethods::iterator SO = M->second.begin(), 3476 SOEnd = M->second.end(); 3477 SO != SOEnd; ++SO) { 3478 // C++ [class.abstract]p4: 3479 // A class is abstract if it contains or inherits at least one 3480 // pure virtual function for which the final overrider is pure 3481 // virtual. 3482 3483 // 3484 if (SO->second.size() != 1) 3485 continue; 3486 3487 if (!SO->second.front().Method->isPure()) 3488 continue; 3489 3490 if (!SeenPureMethods.insert(SO->second.front().Method)) 3491 continue; 3492 3493 Diag(SO->second.front().Method->getLocation(), 3494 diag::note_pure_virtual_function) 3495 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 3496 } 3497 } 3498 3499 if (!PureVirtualClassDiagSet) 3500 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 3501 PureVirtualClassDiagSet->insert(RD); 3502} 3503 3504namespace { 3505struct AbstractUsageInfo { 3506 Sema &S; 3507 CXXRecordDecl *Record; 3508 CanQualType AbstractType; 3509 bool Invalid; 3510 3511 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 3512 : S(S), Record(Record), 3513 AbstractType(S.Context.getCanonicalType( 3514 S.Context.getTypeDeclType(Record))), 3515 Invalid(false) {} 3516 3517 void DiagnoseAbstractType() { 3518 if (Invalid) return; 3519 S.DiagnoseAbstractType(Record); 3520 Invalid = true; 3521 } 3522 3523 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 3524}; 3525 3526struct CheckAbstractUsage { 3527 AbstractUsageInfo &Info; 3528 const NamedDecl *Ctx; 3529 3530 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 3531 : Info(Info), Ctx(Ctx) {} 3532 3533 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 3534 switch (TL.getTypeLocClass()) { 3535#define ABSTRACT_TYPELOC(CLASS, PARENT) 3536#define TYPELOC(CLASS, PARENT) \ 3537 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break; 3538#include "clang/AST/TypeLocNodes.def" 3539 } 3540 } 3541 3542 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 3543 Visit(TL.getResultLoc(), Sema::AbstractReturnType); 3544 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 3545 if (!TL.getArg(I)) 3546 continue; 3547 3548 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo(); 3549 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 3550 } 3551 } 3552 3553 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 3554 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 3555 } 3556 3557 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 3558 // Visit the type parameters from a permissive context. 3559 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 3560 TemplateArgumentLoc TAL = TL.getArgLoc(I); 3561 if (TAL.getArgument().getKind() == TemplateArgument::Type) 3562 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 3563 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 3564 // TODO: other template argument types? 3565 } 3566 } 3567 3568 // Visit pointee types from a permissive context. 3569#define CheckPolymorphic(Type) \ 3570 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 3571 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 3572 } 3573 CheckPolymorphic(PointerTypeLoc) 3574 CheckPolymorphic(ReferenceTypeLoc) 3575 CheckPolymorphic(MemberPointerTypeLoc) 3576 CheckPolymorphic(BlockPointerTypeLoc) 3577 CheckPolymorphic(AtomicTypeLoc) 3578 3579 /// Handle all the types we haven't given a more specific 3580 /// implementation for above. 3581 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 3582 // Every other kind of type that we haven't called out already 3583 // that has an inner type is either (1) sugar or (2) contains that 3584 // inner type in some way as a subobject. 3585 if (TypeLoc Next = TL.getNextTypeLoc()) 3586 return Visit(Next, Sel); 3587 3588 // If there's no inner type and we're in a permissive context, 3589 // don't diagnose. 3590 if (Sel == Sema::AbstractNone) return; 3591 3592 // Check whether the type matches the abstract type. 3593 QualType T = TL.getType(); 3594 if (T->isArrayType()) { 3595 Sel = Sema::AbstractArrayType; 3596 T = Info.S.Context.getBaseElementType(T); 3597 } 3598 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 3599 if (CT != Info.AbstractType) return; 3600 3601 // It matched; do some magic. 3602 if (Sel == Sema::AbstractArrayType) { 3603 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 3604 << T << TL.getSourceRange(); 3605 } else { 3606 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 3607 << Sel << T << TL.getSourceRange(); 3608 } 3609 Info.DiagnoseAbstractType(); 3610 } 3611}; 3612 3613void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 3614 Sema::AbstractDiagSelID Sel) { 3615 CheckAbstractUsage(*this, D).Visit(TL, Sel); 3616} 3617 3618} 3619 3620/// Check for invalid uses of an abstract type in a method declaration. 3621static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 3622 CXXMethodDecl *MD) { 3623 // No need to do the check on definitions, which require that 3624 // the return/param types be complete. 3625 if (MD->doesThisDeclarationHaveABody()) 3626 return; 3627 3628 // For safety's sake, just ignore it if we don't have type source 3629 // information. This should never happen for non-implicit methods, 3630 // but... 3631 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 3632 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 3633} 3634 3635/// Check for invalid uses of an abstract type within a class definition. 3636static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 3637 CXXRecordDecl *RD) { 3638 for (CXXRecordDecl::decl_iterator 3639 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) { 3640 Decl *D = *I; 3641 if (D->isImplicit()) continue; 3642 3643 // Methods and method templates. 3644 if (isa<CXXMethodDecl>(D)) { 3645 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 3646 } else if (isa<FunctionTemplateDecl>(D)) { 3647 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 3648 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 3649 3650 // Fields and static variables. 3651 } else if (isa<FieldDecl>(D)) { 3652 FieldDecl *FD = cast<FieldDecl>(D); 3653 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 3654 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 3655 } else if (isa<VarDecl>(D)) { 3656 VarDecl *VD = cast<VarDecl>(D); 3657 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 3658 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 3659 3660 // Nested classes and class templates. 3661 } else if (isa<CXXRecordDecl>(D)) { 3662 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 3663 } else if (isa<ClassTemplateDecl>(D)) { 3664 CheckAbstractClassUsage(Info, 3665 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 3666 } 3667 } 3668} 3669 3670/// \brief Perform semantic checks on a class definition that has been 3671/// completing, introducing implicitly-declared members, checking for 3672/// abstract types, etc. 3673void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 3674 if (!Record) 3675 return; 3676 3677 if (Record->isAbstract() && !Record->isInvalidDecl()) { 3678 AbstractUsageInfo Info(*this, Record); 3679 CheckAbstractClassUsage(Info, Record); 3680 } 3681 3682 // If this is not an aggregate type and has no user-declared constructor, 3683 // complain about any non-static data members of reference or const scalar 3684 // type, since they will never get initializers. 3685 if (!Record->isInvalidDecl() && !Record->isDependentType() && 3686 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 3687 !Record->isLambda()) { 3688 bool Complained = false; 3689 for (RecordDecl::field_iterator F = Record->field_begin(), 3690 FEnd = Record->field_end(); 3691 F != FEnd; ++F) { 3692 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 3693 continue; 3694 3695 if (F->getType()->isReferenceType() || 3696 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 3697 if (!Complained) { 3698 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 3699 << Record->getTagKind() << Record; 3700 Complained = true; 3701 } 3702 3703 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 3704 << F->getType()->isReferenceType() 3705 << F->getDeclName(); 3706 } 3707 } 3708 } 3709 3710 if (Record->isDynamicClass() && !Record->isDependentType()) 3711 DynamicClasses.push_back(Record); 3712 3713 if (Record->getIdentifier()) { 3714 // C++ [class.mem]p13: 3715 // If T is the name of a class, then each of the following shall have a 3716 // name different from T: 3717 // - every member of every anonymous union that is a member of class T. 3718 // 3719 // C++ [class.mem]p14: 3720 // In addition, if class T has a user-declared constructor (12.1), every 3721 // non-static data member of class T shall have a name different from T. 3722 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 3723 R.first != R.second; ++R.first) { 3724 NamedDecl *D = *R.first; 3725 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 3726 isa<IndirectFieldDecl>(D)) { 3727 Diag(D->getLocation(), diag::err_member_name_of_class) 3728 << D->getDeclName(); 3729 break; 3730 } 3731 } 3732 } 3733 3734 // Warn if the class has virtual methods but non-virtual public destructor. 3735 if (Record->isPolymorphic() && !Record->isDependentType()) { 3736 CXXDestructorDecl *dtor = Record->getDestructor(); 3737 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) 3738 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 3739 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 3740 } 3741 3742 // See if a method overloads virtual methods in a base 3743 /// class without overriding any. 3744 if (!Record->isDependentType()) { 3745 for (CXXRecordDecl::method_iterator M = Record->method_begin(), 3746 MEnd = Record->method_end(); 3747 M != MEnd; ++M) { 3748 if (!(*M)->isStatic()) 3749 DiagnoseHiddenVirtualMethods(Record, *M); 3750 } 3751 } 3752 3753 // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member 3754 // function that is not a constructor declares that member function to be 3755 // const. [...] The class of which that function is a member shall be 3756 // a literal type. 3757 // 3758 // It's fine to diagnose constructors here too: such constructors cannot 3759 // produce a constant expression, so are ill-formed (no diagnostic required). 3760 // 3761 // If the class has virtual bases, any constexpr members will already have 3762 // been diagnosed by the checks performed on the member declaration, so 3763 // suppress this (less useful) diagnostic. 3764 if (LangOpts.CPlusPlus0x && !Record->isDependentType() && 3765 !Record->isLiteral() && !Record->getNumVBases()) { 3766 for (CXXRecordDecl::method_iterator M = Record->method_begin(), 3767 MEnd = Record->method_end(); 3768 M != MEnd; ++M) { 3769 if (M->isConstexpr() && M->isInstance()) { 3770 switch (Record->getTemplateSpecializationKind()) { 3771 case TSK_ImplicitInstantiation: 3772 case TSK_ExplicitInstantiationDeclaration: 3773 case TSK_ExplicitInstantiationDefinition: 3774 // If a template instantiates to a non-literal type, but its members 3775 // instantiate to constexpr functions, the template is technically 3776 // ill-formed, but we allow it for sanity. Such members are treated as 3777 // non-constexpr. 3778 (*M)->setConstexpr(false); 3779 continue; 3780 3781 case TSK_Undeclared: 3782 case TSK_ExplicitSpecialization: 3783 RequireLiteralType((*M)->getLocation(), Context.getRecordType(Record), 3784 PDiag(diag::err_constexpr_method_non_literal)); 3785 break; 3786 } 3787 3788 // Only produce one error per class. 3789 break; 3790 } 3791 } 3792 } 3793 3794 // Declare inherited constructors. We do this eagerly here because: 3795 // - The standard requires an eager diagnostic for conflicting inherited 3796 // constructors from different classes. 3797 // - The lazy declaration of the other implicit constructors is so as to not 3798 // waste space and performance on classes that are not meant to be 3799 // instantiated (e.g. meta-functions). This doesn't apply to classes that 3800 // have inherited constructors. 3801 DeclareInheritedConstructors(Record); 3802 3803 if (!Record->isDependentType()) 3804 CheckExplicitlyDefaultedMethods(Record); 3805} 3806 3807void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) { 3808 for (CXXRecordDecl::method_iterator MI = Record->method_begin(), 3809 ME = Record->method_end(); 3810 MI != ME; ++MI) { 3811 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) { 3812 switch (getSpecialMember(*MI)) { 3813 case CXXDefaultConstructor: 3814 CheckExplicitlyDefaultedDefaultConstructor( 3815 cast<CXXConstructorDecl>(*MI)); 3816 break; 3817 3818 case CXXDestructor: 3819 CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI)); 3820 break; 3821 3822 case CXXCopyConstructor: 3823 CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI)); 3824 break; 3825 3826 case CXXCopyAssignment: 3827 CheckExplicitlyDefaultedCopyAssignment(*MI); 3828 break; 3829 3830 case CXXMoveConstructor: 3831 CheckExplicitlyDefaultedMoveConstructor(cast<CXXConstructorDecl>(*MI)); 3832 break; 3833 3834 case CXXMoveAssignment: 3835 CheckExplicitlyDefaultedMoveAssignment(*MI); 3836 break; 3837 3838 case CXXInvalid: 3839 llvm_unreachable("non-special member explicitly defaulted!"); 3840 } 3841 } 3842 } 3843 3844} 3845 3846void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) { 3847 assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor()); 3848 3849 // Whether this was the first-declared instance of the constructor. 3850 // This affects whether we implicitly add an exception spec (and, eventually, 3851 // constexpr). It is also ill-formed to explicitly default a constructor such 3852 // that it would be deleted. (C++0x [decl.fct.def.default]) 3853 bool First = CD == CD->getCanonicalDecl(); 3854 3855 bool HadError = false; 3856 if (CD->getNumParams() != 0) { 3857 Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params) 3858 << CD->getSourceRange(); 3859 HadError = true; 3860 } 3861 3862 ImplicitExceptionSpecification Spec 3863 = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent()); 3864 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 3865 if (EPI.ExceptionSpecType == EST_Delayed) { 3866 // Exception specification depends on some deferred part of the class. We'll 3867 // try again when the class's definition has been fully processed. 3868 return; 3869 } 3870 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(), 3871 *ExceptionType = Context.getFunctionType( 3872 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>(); 3873 3874 // C++11 [dcl.fct.def.default]p2: 3875 // An explicitly-defaulted function may be declared constexpr only if it 3876 // would have been implicitly declared as constexpr, 3877 if (CD->isConstexpr()) { 3878 if (!CD->getParent()->defaultedDefaultConstructorIsConstexpr()) { 3879 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr) 3880 << CXXDefaultConstructor; 3881 HadError = true; 3882 } 3883 } 3884 // and may have an explicit exception-specification only if it is compatible 3885 // with the exception-specification on the implicit declaration. 3886 if (CtorType->hasExceptionSpec()) { 3887 if (CheckEquivalentExceptionSpec( 3888 PDiag(diag::err_incorrect_defaulted_exception_spec) 3889 << CXXDefaultConstructor, 3890 PDiag(), 3891 ExceptionType, SourceLocation(), 3892 CtorType, CD->getLocation())) { 3893 HadError = true; 3894 } 3895 } 3896 3897 // If a function is explicitly defaulted on its first declaration, 3898 if (First) { 3899 // -- it is implicitly considered to be constexpr if the implicit 3900 // definition would be, 3901 CD->setConstexpr(CD->getParent()->defaultedDefaultConstructorIsConstexpr()); 3902 3903 // -- it is implicitly considered to have the same 3904 // exception-specification as if it had been implicitly declared 3905 // 3906 // FIXME: a compatible, but different, explicit exception specification 3907 // will be silently overridden. We should issue a warning if this happens. 3908 EPI.ExtInfo = CtorType->getExtInfo(); 3909 } 3910 3911 if (HadError) { 3912 CD->setInvalidDecl(); 3913 return; 3914 } 3915 3916 if (ShouldDeleteSpecialMember(CD, CXXDefaultConstructor)) { 3917 if (First) { 3918 CD->setDeletedAsWritten(); 3919 } else { 3920 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes) 3921 << CXXDefaultConstructor; 3922 CD->setInvalidDecl(); 3923 } 3924 } 3925} 3926 3927void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) { 3928 assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor()); 3929 3930 // Whether this was the first-declared instance of the constructor. 3931 bool First = CD == CD->getCanonicalDecl(); 3932 3933 bool HadError = false; 3934 if (CD->getNumParams() != 1) { 3935 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params) 3936 << CD->getSourceRange(); 3937 HadError = true; 3938 } 3939 3940 ImplicitExceptionSpecification Spec(Context); 3941 bool Const; 3942 llvm::tie(Spec, Const) = 3943 ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent()); 3944 3945 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 3946 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(), 3947 *ExceptionType = Context.getFunctionType( 3948 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>(); 3949 3950 // Check for parameter type matching. 3951 // This is a copy ctor so we know it's a cv-qualified reference to T. 3952 QualType ArgType = CtorType->getArgType(0); 3953 if (ArgType->getPointeeType().isVolatileQualified()) { 3954 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param); 3955 HadError = true; 3956 } 3957 if (ArgType->getPointeeType().isConstQualified() && !Const) { 3958 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param); 3959 HadError = true; 3960 } 3961 3962 // C++11 [dcl.fct.def.default]p2: 3963 // An explicitly-defaulted function may be declared constexpr only if it 3964 // would have been implicitly declared as constexpr, 3965 if (CD->isConstexpr()) { 3966 if (!CD->getParent()->defaultedCopyConstructorIsConstexpr()) { 3967 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr) 3968 << CXXCopyConstructor; 3969 HadError = true; 3970 } 3971 } 3972 // and may have an explicit exception-specification only if it is compatible 3973 // with the exception-specification on the implicit declaration. 3974 if (CtorType->hasExceptionSpec()) { 3975 if (CheckEquivalentExceptionSpec( 3976 PDiag(diag::err_incorrect_defaulted_exception_spec) 3977 << CXXCopyConstructor, 3978 PDiag(), 3979 ExceptionType, SourceLocation(), 3980 CtorType, CD->getLocation())) { 3981 HadError = true; 3982 } 3983 } 3984 3985 // If a function is explicitly defaulted on its first declaration, 3986 if (First) { 3987 // -- it is implicitly considered to be constexpr if the implicit 3988 // definition would be, 3989 CD->setConstexpr(CD->getParent()->defaultedCopyConstructorIsConstexpr()); 3990 3991 // -- it is implicitly considered to have the same 3992 // exception-specification as if it had been implicitly declared, and 3993 // 3994 // FIXME: a compatible, but different, explicit exception specification 3995 // will be silently overridden. We should issue a warning if this happens. 3996 EPI.ExtInfo = CtorType->getExtInfo(); 3997 3998 // -- [...] it shall have the same parameter type as if it had been 3999 // implicitly declared. 4000 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI)); 4001 } 4002 4003 if (HadError) { 4004 CD->setInvalidDecl(); 4005 return; 4006 } 4007 4008 if (ShouldDeleteSpecialMember(CD, CXXCopyConstructor)) { 4009 if (First) { 4010 CD->setDeletedAsWritten(); 4011 } else { 4012 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes) 4013 << CXXCopyConstructor; 4014 CD->setInvalidDecl(); 4015 } 4016 } 4017} 4018 4019void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) { 4020 assert(MD->isExplicitlyDefaulted()); 4021 4022 // Whether this was the first-declared instance of the operator 4023 bool First = MD == MD->getCanonicalDecl(); 4024 4025 bool HadError = false; 4026 if (MD->getNumParams() != 1) { 4027 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params) 4028 << MD->getSourceRange(); 4029 HadError = true; 4030 } 4031 4032 QualType ReturnType = 4033 MD->getType()->getAs<FunctionType>()->getResultType(); 4034 if (!ReturnType->isLValueReferenceType() || 4035 !Context.hasSameType( 4036 Context.getCanonicalType(ReturnType->getPointeeType()), 4037 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) { 4038 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type); 4039 HadError = true; 4040 } 4041 4042 ImplicitExceptionSpecification Spec(Context); 4043 bool Const; 4044 llvm::tie(Spec, Const) = 4045 ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent()); 4046 4047 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 4048 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(), 4049 *ExceptionType = Context.getFunctionType( 4050 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>(); 4051 4052 QualType ArgType = OperType->getArgType(0); 4053 if (!ArgType->isLValueReferenceType()) { 4054 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 4055 HadError = true; 4056 } else { 4057 if (ArgType->getPointeeType().isVolatileQualified()) { 4058 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param); 4059 HadError = true; 4060 } 4061 if (ArgType->getPointeeType().isConstQualified() && !Const) { 4062 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param); 4063 HadError = true; 4064 } 4065 } 4066 4067 if (OperType->getTypeQuals()) { 4068 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals); 4069 HadError = true; 4070 } 4071 4072 if (OperType->hasExceptionSpec()) { 4073 if (CheckEquivalentExceptionSpec( 4074 PDiag(diag::err_incorrect_defaulted_exception_spec) 4075 << CXXCopyAssignment, 4076 PDiag(), 4077 ExceptionType, SourceLocation(), 4078 OperType, MD->getLocation())) { 4079 HadError = true; 4080 } 4081 } 4082 if (First) { 4083 // We set the declaration to have the computed exception spec here. 4084 // We duplicate the one parameter type. 4085 EPI.RefQualifier = OperType->getRefQualifier(); 4086 EPI.ExtInfo = OperType->getExtInfo(); 4087 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI)); 4088 } 4089 4090 if (HadError) { 4091 MD->setInvalidDecl(); 4092 return; 4093 } 4094 4095 if (ShouldDeleteCopyAssignmentOperator(MD)) { 4096 if (First) { 4097 MD->setDeletedAsWritten(); 4098 } else { 4099 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) 4100 << CXXCopyAssignment; 4101 MD->setInvalidDecl(); 4102 } 4103 } 4104} 4105 4106void Sema::CheckExplicitlyDefaultedMoveConstructor(CXXConstructorDecl *CD) { 4107 assert(CD->isExplicitlyDefaulted() && CD->isMoveConstructor()); 4108 4109 // Whether this was the first-declared instance of the constructor. 4110 bool First = CD == CD->getCanonicalDecl(); 4111 4112 bool HadError = false; 4113 if (CD->getNumParams() != 1) { 4114 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_params) 4115 << CD->getSourceRange(); 4116 HadError = true; 4117 } 4118 4119 ImplicitExceptionSpecification Spec( 4120 ComputeDefaultedMoveCtorExceptionSpec(CD->getParent())); 4121 4122 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 4123 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(), 4124 *ExceptionType = Context.getFunctionType( 4125 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>(); 4126 4127 // Check for parameter type matching. 4128 // This is a move ctor so we know it's a cv-qualified rvalue reference to T. 4129 QualType ArgType = CtorType->getArgType(0); 4130 if (ArgType->getPointeeType().isVolatileQualified()) { 4131 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_volatile_param); 4132 HadError = true; 4133 } 4134 if (ArgType->getPointeeType().isConstQualified()) { 4135 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_const_param); 4136 HadError = true; 4137 } 4138 4139 // C++11 [dcl.fct.def.default]p2: 4140 // An explicitly-defaulted function may be declared constexpr only if it 4141 // would have been implicitly declared as constexpr, 4142 if (CD->isConstexpr()) { 4143 if (!CD->getParent()->defaultedMoveConstructorIsConstexpr()) { 4144 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr) 4145 << CXXMoveConstructor; 4146 HadError = true; 4147 } 4148 } 4149 // and may have an explicit exception-specification only if it is compatible 4150 // with the exception-specification on the implicit declaration. 4151 if (CtorType->hasExceptionSpec()) { 4152 if (CheckEquivalentExceptionSpec( 4153 PDiag(diag::err_incorrect_defaulted_exception_spec) 4154 << CXXMoveConstructor, 4155 PDiag(), 4156 ExceptionType, SourceLocation(), 4157 CtorType, CD->getLocation())) { 4158 HadError = true; 4159 } 4160 } 4161 4162 // If a function is explicitly defaulted on its first declaration, 4163 if (First) { 4164 // -- it is implicitly considered to be constexpr if the implicit 4165 // definition would be, 4166 CD->setConstexpr(CD->getParent()->defaultedMoveConstructorIsConstexpr()); 4167 4168 // -- it is implicitly considered to have the same 4169 // exception-specification as if it had been implicitly declared, and 4170 // 4171 // FIXME: a compatible, but different, explicit exception specification 4172 // will be silently overridden. We should issue a warning if this happens. 4173 EPI.ExtInfo = CtorType->getExtInfo(); 4174 4175 // -- [...] it shall have the same parameter type as if it had been 4176 // implicitly declared. 4177 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI)); 4178 } 4179 4180 if (HadError) { 4181 CD->setInvalidDecl(); 4182 return; 4183 } 4184 4185 if (ShouldDeleteSpecialMember(CD, CXXMoveConstructor)) { 4186 if (First) { 4187 CD->setDeletedAsWritten(); 4188 } else { 4189 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes) 4190 << CXXMoveConstructor; 4191 CD->setInvalidDecl(); 4192 } 4193 } 4194} 4195 4196void Sema::CheckExplicitlyDefaultedMoveAssignment(CXXMethodDecl *MD) { 4197 assert(MD->isExplicitlyDefaulted()); 4198 4199 // Whether this was the first-declared instance of the operator 4200 bool First = MD == MD->getCanonicalDecl(); 4201 4202 bool HadError = false; 4203 if (MD->getNumParams() != 1) { 4204 Diag(MD->getLocation(), diag::err_defaulted_move_assign_params) 4205 << MD->getSourceRange(); 4206 HadError = true; 4207 } 4208 4209 QualType ReturnType = 4210 MD->getType()->getAs<FunctionType>()->getResultType(); 4211 if (!ReturnType->isLValueReferenceType() || 4212 !Context.hasSameType( 4213 Context.getCanonicalType(ReturnType->getPointeeType()), 4214 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) { 4215 Diag(MD->getLocation(), diag::err_defaulted_move_assign_return_type); 4216 HadError = true; 4217 } 4218 4219 ImplicitExceptionSpecification Spec( 4220 ComputeDefaultedMoveCtorExceptionSpec(MD->getParent())); 4221 4222 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 4223 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(), 4224 *ExceptionType = Context.getFunctionType( 4225 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>(); 4226 4227 QualType ArgType = OperType->getArgType(0); 4228 if (!ArgType->isRValueReferenceType()) { 4229 Diag(MD->getLocation(), diag::err_defaulted_move_assign_not_ref); 4230 HadError = true; 4231 } else { 4232 if (ArgType->getPointeeType().isVolatileQualified()) { 4233 Diag(MD->getLocation(), diag::err_defaulted_move_assign_volatile_param); 4234 HadError = true; 4235 } 4236 if (ArgType->getPointeeType().isConstQualified()) { 4237 Diag(MD->getLocation(), diag::err_defaulted_move_assign_const_param); 4238 HadError = true; 4239 } 4240 } 4241 4242 if (OperType->getTypeQuals()) { 4243 Diag(MD->getLocation(), diag::err_defaulted_move_assign_quals); 4244 HadError = true; 4245 } 4246 4247 if (OperType->hasExceptionSpec()) { 4248 if (CheckEquivalentExceptionSpec( 4249 PDiag(diag::err_incorrect_defaulted_exception_spec) 4250 << CXXMoveAssignment, 4251 PDiag(), 4252 ExceptionType, SourceLocation(), 4253 OperType, MD->getLocation())) { 4254 HadError = true; 4255 } 4256 } 4257 if (First) { 4258 // We set the declaration to have the computed exception spec here. 4259 // We duplicate the one parameter type. 4260 EPI.RefQualifier = OperType->getRefQualifier(); 4261 EPI.ExtInfo = OperType->getExtInfo(); 4262 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI)); 4263 } 4264 4265 if (HadError) { 4266 MD->setInvalidDecl(); 4267 return; 4268 } 4269 4270 if (ShouldDeleteMoveAssignmentOperator(MD)) { 4271 if (First) { 4272 MD->setDeletedAsWritten(); 4273 } else { 4274 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) 4275 << CXXMoveAssignment; 4276 MD->setInvalidDecl(); 4277 } 4278 } 4279} 4280 4281void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) { 4282 assert(DD->isExplicitlyDefaulted()); 4283 4284 // Whether this was the first-declared instance of the destructor. 4285 bool First = DD == DD->getCanonicalDecl(); 4286 4287 ImplicitExceptionSpecification Spec 4288 = ComputeDefaultedDtorExceptionSpec(DD->getParent()); 4289 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 4290 const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(), 4291 *ExceptionType = Context.getFunctionType( 4292 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>(); 4293 4294 if (DtorType->hasExceptionSpec()) { 4295 if (CheckEquivalentExceptionSpec( 4296 PDiag(diag::err_incorrect_defaulted_exception_spec) 4297 << CXXDestructor, 4298 PDiag(), 4299 ExceptionType, SourceLocation(), 4300 DtorType, DD->getLocation())) { 4301 DD->setInvalidDecl(); 4302 return; 4303 } 4304 } 4305 if (First) { 4306 // We set the declaration to have the computed exception spec here. 4307 // There are no parameters. 4308 EPI.ExtInfo = DtorType->getExtInfo(); 4309 DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI)); 4310 } 4311 4312 if (ShouldDeleteDestructor(DD)) { 4313 if (First) { 4314 DD->setDeletedAsWritten(); 4315 } else { 4316 Diag(DD->getLocation(), diag::err_out_of_line_default_deletes) 4317 << CXXDestructor; 4318 DD->setInvalidDecl(); 4319 } 4320 } 4321} 4322 4323/// This function implements the following C++0x paragraphs: 4324/// - [class.ctor]/5 4325/// - [class.copy]/11 4326bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM) { 4327 assert(!MD->isInvalidDecl()); 4328 CXXRecordDecl *RD = MD->getParent(); 4329 assert(!RD->isDependentType() && "do deletion after instantiation"); 4330 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl()) 4331 return false; 4332 4333 bool IsUnion = RD->isUnion(); 4334 bool IsConstructor = false; 4335 bool IsAssignment = false; 4336 bool IsMove = false; 4337 4338 bool ConstArg = false; 4339 4340 switch (CSM) { 4341 case CXXDefaultConstructor: 4342 IsConstructor = true; 4343 break; 4344 case CXXCopyConstructor: 4345 IsConstructor = true; 4346 ConstArg = MD->getParamDecl(0)->getType().isConstQualified(); 4347 break; 4348 case CXXMoveConstructor: 4349 IsConstructor = true; 4350 IsMove = true; 4351 break; 4352 default: 4353 llvm_unreachable("function only currently implemented for default ctors"); 4354 } 4355 4356 SourceLocation Loc = MD->getLocation(); 4357 4358 // Do access control from the special member function 4359 ContextRAII MethodContext(*this, MD); 4360 4361 bool AllConst = true; 4362 4363 // We do this because we should never actually use an anonymous 4364 // union's constructor. 4365 if (IsUnion && RD->isAnonymousStructOrUnion()) 4366 return false; 4367 4368 // FIXME: We should put some diagnostic logic right into this function. 4369 4370 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 4371 BE = RD->bases_end(); 4372 BI != BE; ++BI) { 4373 // We'll handle this one later 4374 if (BI->isVirtual()) 4375 continue; 4376 4377 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl(); 4378 assert(BaseDecl && "base isn't a CXXRecordDecl"); 4379 4380 // Unless we have an assignment operator, the base's destructor must 4381 // be accessible and not deleted. 4382 if (!IsAssignment) { 4383 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl); 4384 if (BaseDtor->isDeleted()) 4385 return true; 4386 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) != 4387 AR_accessible) 4388 return true; 4389 } 4390 4391 // Finding the corresponding member in the base should lead to a 4392 // unique, accessible, non-deleted function. If we are doing 4393 // a destructor, we have already checked this case. 4394 if (CSM != CXXDestructor) { 4395 SpecialMemberOverloadResult *SMOR = 4396 LookupSpecialMember(BaseDecl, CSM, ConstArg, false, false, false, 4397 false); 4398 if (!SMOR->hasSuccess()) 4399 return true; 4400 CXXMethodDecl *BaseMember = SMOR->getMethod(); 4401 if (IsConstructor) { 4402 CXXConstructorDecl *BaseCtor = cast<CXXConstructorDecl>(BaseMember); 4403 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), 4404 PDiag()) != AR_accessible) 4405 return true; 4406 4407 // For a move operation, the corresponding operation must actually 4408 // be a move operation (and not a copy selected by overload 4409 // resolution) unless we are working on a trivially copyable class. 4410 if (IsMove && !BaseCtor->isMoveConstructor() && 4411 !BaseDecl->isTriviallyCopyable()) 4412 return true; 4413 } 4414 } 4415 } 4416 4417 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(), 4418 BE = RD->vbases_end(); 4419 BI != BE; ++BI) { 4420 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl(); 4421 assert(BaseDecl && "base isn't a CXXRecordDecl"); 4422 4423 // Unless we have an assignment operator, the base's destructor must 4424 // be accessible and not deleted. 4425 if (!IsAssignment) { 4426 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl); 4427 if (BaseDtor->isDeleted()) 4428 return true; 4429 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) != 4430 AR_accessible) 4431 return true; 4432 } 4433 4434 // Finding the corresponding member in the base should lead to a 4435 // unique, accessible, non-deleted function. 4436 if (CSM != CXXDestructor) { 4437 SpecialMemberOverloadResult *SMOR = 4438 LookupSpecialMember(BaseDecl, CSM, ConstArg, false, false, false, 4439 false); 4440 if (!SMOR->hasSuccess()) 4441 return true; 4442 CXXMethodDecl *BaseMember = SMOR->getMethod(); 4443 if (IsConstructor) { 4444 CXXConstructorDecl *BaseCtor = cast<CXXConstructorDecl>(BaseMember); 4445 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), 4446 PDiag()) != AR_accessible) 4447 return true; 4448 4449 // For a move operation, the corresponding operation must actually 4450 // be a move operation (and not a copy selected by overload 4451 // resolution) unless we are working on a trivially copyable class. 4452 if (IsMove && !BaseCtor->isMoveConstructor() && 4453 !BaseDecl->isTriviallyCopyable()) 4454 return true; 4455 } 4456 } 4457 } 4458 4459 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 4460 FE = RD->field_end(); 4461 FI != FE; ++FI) { 4462 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 4463 continue; 4464 4465 QualType FieldType = Context.getBaseElementType(FI->getType()); 4466 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 4467 4468 // For a default constructor, all references must be initialized in-class 4469 // and, if a union, it must have a non-const member. 4470 if (CSM == CXXDefaultConstructor) { 4471 if (FieldType->isReferenceType() && !FI->hasInClassInitializer()) 4472 return true; 4473 4474 if (IsUnion && !FieldType.isConstQualified()) 4475 AllConst = false; 4476 // For a copy constructor, data members must not be of rvalue reference 4477 // type. 4478 } else if (CSM == CXXCopyConstructor) { 4479 if (FieldType->isRValueReferenceType()) 4480 return true; 4481 } 4482 4483 if (FieldRecord) { 4484 // For a default constructor, a const member must have a user-provided 4485 // default constructor or else be explicitly initialized. 4486 if (CSM == CXXDefaultConstructor && FieldType.isConstQualified() && 4487 !FI->hasInClassInitializer() && 4488 !FieldRecord->hasUserProvidedDefaultConstructor()) 4489 return true; 4490 4491 // Some additional restrictions exist on the variant members. 4492 if (!IsUnion && FieldRecord->isUnion() && 4493 FieldRecord->isAnonymousStructOrUnion()) { 4494 // We're okay to reuse AllConst here since we only care about the 4495 // value otherwise if we're in a union. 4496 AllConst = true; 4497 4498 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(), 4499 UE = FieldRecord->field_end(); 4500 UI != UE; ++UI) { 4501 QualType UnionFieldType = Context.getBaseElementType(UI->getType()); 4502 CXXRecordDecl *UnionFieldRecord = 4503 UnionFieldType->getAsCXXRecordDecl(); 4504 4505 if (!UnionFieldType.isConstQualified()) 4506 AllConst = false; 4507 4508 if (UnionFieldRecord) { 4509 // FIXME: Checking for accessibility and validity of this 4510 // destructor is technically going beyond the 4511 // standard, but this is believed to be a defect. 4512 if (!IsAssignment) { 4513 CXXDestructorDecl *FieldDtor = LookupDestructor(UnionFieldRecord); 4514 if (FieldDtor->isDeleted()) 4515 return true; 4516 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) != 4517 AR_accessible) 4518 return true; 4519 if (!FieldDtor->isTrivial()) 4520 return true; 4521 } 4522 4523 if (CSM != CXXDestructor) { 4524 SpecialMemberOverloadResult *SMOR = 4525 LookupSpecialMember(UnionFieldRecord, CSM, ConstArg, false, 4526 false, false, false); 4527 // FIXME: Checking for accessibility and validity of this 4528 // corresponding member is technically going beyond the 4529 // standard, but this is believed to be a defect. 4530 if (!SMOR->hasSuccess()) 4531 return true; 4532 4533 CXXMethodDecl *FieldMember = SMOR->getMethod(); 4534 // A member of a union must have a trivial corresponding 4535 // constructor. 4536 if (!FieldMember->isTrivial()) 4537 return true; 4538 4539 if (IsConstructor) { 4540 CXXConstructorDecl *FieldCtor = cast<CXXConstructorDecl>(FieldMember); 4541 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(), 4542 PDiag()) != AR_accessible) 4543 return true; 4544 } 4545 } 4546 } 4547 } 4548 4549 // At least one member in each anonymous union must be non-const 4550 if (CSM == CXXDefaultConstructor && AllConst) 4551 return true; 4552 4553 // Don't try to initialize the anonymous union 4554 // This is technically non-conformant, but sanity demands it. 4555 continue; 4556 } 4557 4558 // Unless we're doing assignment, the field's destructor must be 4559 // accessible and not deleted. 4560 if (!IsAssignment) { 4561 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord); 4562 if (FieldDtor->isDeleted()) 4563 return true; 4564 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) != 4565 AR_accessible) 4566 return true; 4567 } 4568 4569 // Check that the corresponding member of the field is accessible, 4570 // unique, and non-deleted. We don't do this if it has an explicit 4571 // initialization when default-constructing. 4572 if (CSM != CXXDestructor && 4573 (CSM != CXXDefaultConstructor || !FI->hasInClassInitializer())) { 4574 SpecialMemberOverloadResult *SMOR = 4575 LookupSpecialMember(FieldRecord, CSM, ConstArg, false, false, false, 4576 false); 4577 if (!SMOR->hasSuccess()) 4578 return true; 4579 4580 CXXMethodDecl *FieldMember = SMOR->getMethod(); 4581 if (IsConstructor) { 4582 CXXConstructorDecl *FieldCtor = cast<CXXConstructorDecl>(FieldMember); 4583 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(), 4584 PDiag()) != AR_accessible) 4585 return true; 4586 4587 // For a move operation, the corresponding operation must actually 4588 // be a move operation (and not a copy selected by overload 4589 // resolution) unless we are working on a trivially copyable class. 4590 if (IsMove && !FieldCtor->isMoveConstructor() && 4591 !FieldRecord->isTriviallyCopyable()) 4592 return true; 4593 } 4594 4595 // We need the corresponding member of a union to be trivial so that 4596 // we can safely copy them all simultaneously. 4597 // FIXME: Note that performing the check here (where we rely on the lack 4598 // of an in-class initializer) is technically ill-formed. However, this 4599 // seems most obviously to be a bug in the standard. 4600 if (IsUnion && !FieldMember->isTrivial()) 4601 return true; 4602 } 4603 } else if (CSM == CXXDefaultConstructor && !IsUnion && 4604 FieldType.isConstQualified() && !FI->hasInClassInitializer()) { 4605 // We can't initialize a const member of non-class type to any value. 4606 return true; 4607 } 4608 } 4609 4610 // We can't have all const members in a union when default-constructing, 4611 // or else they're all nonsensical garbage values that can't be changed. 4612 if (CSM == CXXDefaultConstructor && IsUnion && AllConst) 4613 return true; 4614 4615 return false; 4616} 4617 4618bool Sema::ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD) { 4619 CXXRecordDecl *RD = MD->getParent(); 4620 assert(!RD->isDependentType() && "do deletion after instantiation"); 4621 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl()) 4622 return false; 4623 4624 SourceLocation Loc = MD->getLocation(); 4625 4626 // Do access control from the constructor 4627 ContextRAII MethodContext(*this, MD); 4628 4629 bool Union = RD->isUnion(); 4630 4631 unsigned ArgQuals = 4632 MD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ? 4633 Qualifiers::Const : 0; 4634 4635 // We do this because we should never actually use an anonymous 4636 // union's constructor. 4637 if (Union && RD->isAnonymousStructOrUnion()) 4638 return false; 4639 4640 // FIXME: We should put some diagnostic logic right into this function. 4641 4642 // C++0x [class.copy]/20 4643 // A defaulted [copy] assignment operator for class X is defined as deleted 4644 // if X has: 4645 4646 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 4647 BE = RD->bases_end(); 4648 BI != BE; ++BI) { 4649 // We'll handle this one later 4650 if (BI->isVirtual()) 4651 continue; 4652 4653 QualType BaseType = BI->getType(); 4654 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl(); 4655 assert(BaseDecl && "base isn't a CXXRecordDecl"); 4656 4657 // -- a [direct base class] B that cannot be [copied] because overload 4658 // resolution, as applied to B's [copy] assignment operator, results in 4659 // an ambiguity or a function that is deleted or inaccessible from the 4660 // assignment operator 4661 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false, 4662 0); 4663 if (!CopyOper || CopyOper->isDeleted()) 4664 return true; 4665 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible) 4666 return true; 4667 } 4668 4669 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(), 4670 BE = RD->vbases_end(); 4671 BI != BE; ++BI) { 4672 QualType BaseType = BI->getType(); 4673 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl(); 4674 assert(BaseDecl && "base isn't a CXXRecordDecl"); 4675 4676 // -- a [virtual base class] B that cannot be [copied] because overload 4677 // resolution, as applied to B's [copy] assignment operator, results in 4678 // an ambiguity or a function that is deleted or inaccessible from the 4679 // assignment operator 4680 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false, 4681 0); 4682 if (!CopyOper || CopyOper->isDeleted()) 4683 return true; 4684 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible) 4685 return true; 4686 } 4687 4688 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 4689 FE = RD->field_end(); 4690 FI != FE; ++FI) { 4691 if (FI->isUnnamedBitfield()) 4692 continue; 4693 4694 QualType FieldType = Context.getBaseElementType(FI->getType()); 4695 4696 // -- a non-static data member of reference type 4697 if (FieldType->isReferenceType()) 4698 return true; 4699 4700 // -- a non-static data member of const non-class type (or array thereof) 4701 if (FieldType.isConstQualified() && !FieldType->isRecordType()) 4702 return true; 4703 4704 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 4705 4706 if (FieldRecord) { 4707 // This is an anonymous union 4708 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) { 4709 // Anonymous unions inside unions do not variant members create 4710 if (!Union) { 4711 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(), 4712 UE = FieldRecord->field_end(); 4713 UI != UE; ++UI) { 4714 QualType UnionFieldType = Context.getBaseElementType(UI->getType()); 4715 CXXRecordDecl *UnionFieldRecord = 4716 UnionFieldType->getAsCXXRecordDecl(); 4717 4718 // -- a variant member with a non-trivial [copy] assignment operator 4719 // and X is a union-like class 4720 if (UnionFieldRecord && 4721 !UnionFieldRecord->hasTrivialCopyAssignment()) 4722 return true; 4723 } 4724 } 4725 4726 // Don't try to initalize an anonymous union 4727 continue; 4728 // -- a variant member with a non-trivial [copy] assignment operator 4729 // and X is a union-like class 4730 } else if (Union && !FieldRecord->hasTrivialCopyAssignment()) { 4731 return true; 4732 } 4733 4734 CXXMethodDecl *CopyOper = LookupCopyingAssignment(FieldRecord, ArgQuals, 4735 false, 0); 4736 if (!CopyOper || CopyOper->isDeleted()) 4737 return true; 4738 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible) 4739 return true; 4740 } 4741 } 4742 4743 return false; 4744} 4745 4746bool Sema::ShouldDeleteMoveAssignmentOperator(CXXMethodDecl *MD) { 4747 CXXRecordDecl *RD = MD->getParent(); 4748 assert(!RD->isDependentType() && "do deletion after instantiation"); 4749 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl()) 4750 return false; 4751 4752 SourceLocation Loc = MD->getLocation(); 4753 4754 // Do access control from the constructor 4755 ContextRAII MethodContext(*this, MD); 4756 4757 bool Union = RD->isUnion(); 4758 4759 // We do this because we should never actually use an anonymous 4760 // union's constructor. 4761 if (Union && RD->isAnonymousStructOrUnion()) 4762 return false; 4763 4764 // C++0x [class.copy]/20 4765 // A defaulted [move] assignment operator for class X is defined as deleted 4766 // if X has: 4767 4768 // -- for the move constructor, [...] any direct or indirect virtual base 4769 // class. 4770 if (RD->getNumVBases() != 0) 4771 return true; 4772 4773 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 4774 BE = RD->bases_end(); 4775 BI != BE; ++BI) { 4776 4777 QualType BaseType = BI->getType(); 4778 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl(); 4779 assert(BaseDecl && "base isn't a CXXRecordDecl"); 4780 4781 // -- a [direct base class] B that cannot be [moved] because overload 4782 // resolution, as applied to B's [move] assignment operator, results in 4783 // an ambiguity or a function that is deleted or inaccessible from the 4784 // assignment operator 4785 CXXMethodDecl *MoveOper = LookupMovingAssignment(BaseDecl, false, 0); 4786 if (!MoveOper || MoveOper->isDeleted()) 4787 return true; 4788 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible) 4789 return true; 4790 4791 // -- for the move assignment operator, a [direct base class] with a type 4792 // that does not have a move assignment operator and is not trivially 4793 // copyable. 4794 if (!MoveOper->isMoveAssignmentOperator() && 4795 !BaseDecl->isTriviallyCopyable()) 4796 return true; 4797 } 4798 4799 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 4800 FE = RD->field_end(); 4801 FI != FE; ++FI) { 4802 if (FI->isUnnamedBitfield()) 4803 continue; 4804 4805 QualType FieldType = Context.getBaseElementType(FI->getType()); 4806 4807 // -- a non-static data member of reference type 4808 if (FieldType->isReferenceType()) 4809 return true; 4810 4811 // -- a non-static data member of const non-class type (or array thereof) 4812 if (FieldType.isConstQualified() && !FieldType->isRecordType()) 4813 return true; 4814 4815 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 4816 4817 if (FieldRecord) { 4818 // This is an anonymous union 4819 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) { 4820 // Anonymous unions inside unions do not variant members create 4821 if (!Union) { 4822 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(), 4823 UE = FieldRecord->field_end(); 4824 UI != UE; ++UI) { 4825 QualType UnionFieldType = Context.getBaseElementType(UI->getType()); 4826 CXXRecordDecl *UnionFieldRecord = 4827 UnionFieldType->getAsCXXRecordDecl(); 4828 4829 // -- a variant member with a non-trivial [move] assignment operator 4830 // and X is a union-like class 4831 if (UnionFieldRecord && 4832 !UnionFieldRecord->hasTrivialMoveAssignment()) 4833 return true; 4834 } 4835 } 4836 4837 // Don't try to initalize an anonymous union 4838 continue; 4839 // -- a variant member with a non-trivial [move] assignment operator 4840 // and X is a union-like class 4841 } else if (Union && !FieldRecord->hasTrivialMoveAssignment()) { 4842 return true; 4843 } 4844 4845 CXXMethodDecl *MoveOper = LookupMovingAssignment(FieldRecord, false, 0); 4846 if (!MoveOper || MoveOper->isDeleted()) 4847 return true; 4848 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible) 4849 return true; 4850 4851 // -- for the move assignment operator, a [non-static data member] with a 4852 // type that does not have a move assignment operator and is not 4853 // trivially copyable. 4854 if (!MoveOper->isMoveAssignmentOperator() && 4855 !FieldRecord->isTriviallyCopyable()) 4856 return true; 4857 } 4858 } 4859 4860 return false; 4861} 4862 4863bool Sema::ShouldDeleteDestructor(CXXDestructorDecl *DD) { 4864 CXXRecordDecl *RD = DD->getParent(); 4865 assert(!RD->isDependentType() && "do deletion after instantiation"); 4866 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl()) 4867 return false; 4868 4869 SourceLocation Loc = DD->getLocation(); 4870 4871 // Do access control from the destructor 4872 ContextRAII CtorContext(*this, DD); 4873 4874 bool Union = RD->isUnion(); 4875 4876 // We do this because we should never actually use an anonymous 4877 // union's destructor. 4878 if (Union && RD->isAnonymousStructOrUnion()) 4879 return false; 4880 4881 // C++0x [class.dtor]p5 4882 // A defaulted destructor for a class X is defined as deleted if: 4883 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 4884 BE = RD->bases_end(); 4885 BI != BE; ++BI) { 4886 // We'll handle this one later 4887 if (BI->isVirtual()) 4888 continue; 4889 4890 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl(); 4891 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl); 4892 assert(BaseDtor && "base has no destructor"); 4893 4894 // -- any direct or virtual base class has a deleted destructor or 4895 // a destructor that is inaccessible from the defaulted destructor 4896 if (BaseDtor->isDeleted()) 4897 return true; 4898 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) != 4899 AR_accessible) 4900 return true; 4901 } 4902 4903 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(), 4904 BE = RD->vbases_end(); 4905 BI != BE; ++BI) { 4906 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl(); 4907 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl); 4908 assert(BaseDtor && "base has no destructor"); 4909 4910 // -- any direct or virtual base class has a deleted destructor or 4911 // a destructor that is inaccessible from the defaulted destructor 4912 if (BaseDtor->isDeleted()) 4913 return true; 4914 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) != 4915 AR_accessible) 4916 return true; 4917 } 4918 4919 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 4920 FE = RD->field_end(); 4921 FI != FE; ++FI) { 4922 QualType FieldType = Context.getBaseElementType(FI->getType()); 4923 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 4924 if (FieldRecord) { 4925 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) { 4926 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(), 4927 UE = FieldRecord->field_end(); 4928 UI != UE; ++UI) { 4929 QualType UnionFieldType = Context.getBaseElementType(FI->getType()); 4930 CXXRecordDecl *UnionFieldRecord = 4931 UnionFieldType->getAsCXXRecordDecl(); 4932 4933 // -- X is a union-like class that has a variant member with a non- 4934 // trivial destructor. 4935 if (UnionFieldRecord && !UnionFieldRecord->hasTrivialDestructor()) 4936 return true; 4937 } 4938 // Technically we are supposed to do this next check unconditionally. 4939 // But that makes absolutely no sense. 4940 } else { 4941 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord); 4942 4943 // -- any of the non-static data members has class type M (or array 4944 // thereof) and M has a deleted destructor or a destructor that is 4945 // inaccessible from the defaulted destructor 4946 if (FieldDtor->isDeleted()) 4947 return true; 4948 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) != 4949 AR_accessible) 4950 return true; 4951 4952 // -- X is a union-like class that has a variant member with a non- 4953 // trivial destructor. 4954 if (Union && !FieldDtor->isTrivial()) 4955 return true; 4956 } 4957 } 4958 } 4959 4960 if (DD->isVirtual()) { 4961 FunctionDecl *OperatorDelete = 0; 4962 DeclarationName Name = 4963 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 4964 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete, 4965 false)) 4966 return true; 4967 } 4968 4969 4970 return false; 4971} 4972 4973/// \brief Data used with FindHiddenVirtualMethod 4974namespace { 4975 struct FindHiddenVirtualMethodData { 4976 Sema *S; 4977 CXXMethodDecl *Method; 4978 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 4979 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 4980 }; 4981} 4982 4983/// \brief Member lookup function that determines whether a given C++ 4984/// method overloads virtual methods in a base class without overriding any, 4985/// to be used with CXXRecordDecl::lookupInBases(). 4986static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier, 4987 CXXBasePath &Path, 4988 void *UserData) { 4989 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 4990 4991 FindHiddenVirtualMethodData &Data 4992 = *static_cast<FindHiddenVirtualMethodData*>(UserData); 4993 4994 DeclarationName Name = Data.Method->getDeclName(); 4995 assert(Name.getNameKind() == DeclarationName::Identifier); 4996 4997 bool foundSameNameMethod = false; 4998 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 4999 for (Path.Decls = BaseRecord->lookup(Name); 5000 Path.Decls.first != Path.Decls.second; 5001 ++Path.Decls.first) { 5002 NamedDecl *D = *Path.Decls.first; 5003 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 5004 MD = MD->getCanonicalDecl(); 5005 foundSameNameMethod = true; 5006 // Interested only in hidden virtual methods. 5007 if (!MD->isVirtual()) 5008 continue; 5009 // If the method we are checking overrides a method from its base 5010 // don't warn about the other overloaded methods. 5011 if (!Data.S->IsOverload(Data.Method, MD, false)) 5012 return true; 5013 // Collect the overload only if its hidden. 5014 if (!Data.OverridenAndUsingBaseMethods.count(MD)) 5015 overloadedMethods.push_back(MD); 5016 } 5017 } 5018 5019 if (foundSameNameMethod) 5020 Data.OverloadedMethods.append(overloadedMethods.begin(), 5021 overloadedMethods.end()); 5022 return foundSameNameMethod; 5023} 5024 5025/// \brief See if a method overloads virtual methods in a base class without 5026/// overriding any. 5027void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 5028 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual, 5029 MD->getLocation()) == DiagnosticsEngine::Ignored) 5030 return; 5031 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier) 5032 return; 5033 5034 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 5035 /*bool RecordPaths=*/false, 5036 /*bool DetectVirtual=*/false); 5037 FindHiddenVirtualMethodData Data; 5038 Data.Method = MD; 5039 Data.S = this; 5040 5041 // Keep the base methods that were overriden or introduced in the subclass 5042 // by 'using' in a set. A base method not in this set is hidden. 5043 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName()); 5044 res.first != res.second; ++res.first) { 5045 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first)) 5046 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 5047 E = MD->end_overridden_methods(); 5048 I != E; ++I) 5049 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl()); 5050 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first)) 5051 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl())) 5052 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl()); 5053 } 5054 5055 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) && 5056 !Data.OverloadedMethods.empty()) { 5057 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 5058 << MD << (Data.OverloadedMethods.size() > 1); 5059 5060 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) { 5061 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i]; 5062 Diag(overloadedMD->getLocation(), 5063 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 5064 } 5065 } 5066} 5067 5068void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 5069 Decl *TagDecl, 5070 SourceLocation LBrac, 5071 SourceLocation RBrac, 5072 AttributeList *AttrList) { 5073 if (!TagDecl) 5074 return; 5075 5076 AdjustDeclIfTemplate(TagDecl); 5077 5078 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 5079 // strict aliasing violation! 5080 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 5081 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 5082 5083 CheckCompletedCXXClass( 5084 dyn_cast_or_null<CXXRecordDecl>(TagDecl)); 5085} 5086 5087/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 5088/// special functions, such as the default constructor, copy 5089/// constructor, or destructor, to the given C++ class (C++ 5090/// [special]p1). This routine can only be executed just before the 5091/// definition of the class is complete. 5092void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 5093 if (!ClassDecl->hasUserDeclaredConstructor()) 5094 ++ASTContext::NumImplicitDefaultConstructors; 5095 5096 if (!ClassDecl->hasUserDeclaredCopyConstructor()) 5097 ++ASTContext::NumImplicitCopyConstructors; 5098 5099 if (getLangOptions().CPlusPlus0x && ClassDecl->needsImplicitMoveConstructor()) 5100 ++ASTContext::NumImplicitMoveConstructors; 5101 5102 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 5103 ++ASTContext::NumImplicitCopyAssignmentOperators; 5104 5105 // If we have a dynamic class, then the copy assignment operator may be 5106 // virtual, so we have to declare it immediately. This ensures that, e.g., 5107 // it shows up in the right place in the vtable and that we diagnose 5108 // problems with the implicit exception specification. 5109 if (ClassDecl->isDynamicClass()) 5110 DeclareImplicitCopyAssignment(ClassDecl); 5111 } 5112 5113 if (getLangOptions().CPlusPlus0x && ClassDecl->needsImplicitMoveAssignment()){ 5114 ++ASTContext::NumImplicitMoveAssignmentOperators; 5115 5116 // Likewise for the move assignment operator. 5117 if (ClassDecl->isDynamicClass()) 5118 DeclareImplicitMoveAssignment(ClassDecl); 5119 } 5120 5121 if (!ClassDecl->hasUserDeclaredDestructor()) { 5122 ++ASTContext::NumImplicitDestructors; 5123 5124 // If we have a dynamic class, then the destructor may be virtual, so we 5125 // have to declare the destructor immediately. This ensures that, e.g., it 5126 // shows up in the right place in the vtable and that we diagnose problems 5127 // with the implicit exception specification. 5128 if (ClassDecl->isDynamicClass()) 5129 DeclareImplicitDestructor(ClassDecl); 5130 } 5131} 5132 5133void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) { 5134 if (!D) 5135 return; 5136 5137 int NumParamList = D->getNumTemplateParameterLists(); 5138 for (int i = 0; i < NumParamList; i++) { 5139 TemplateParameterList* Params = D->getTemplateParameterList(i); 5140 for (TemplateParameterList::iterator Param = Params->begin(), 5141 ParamEnd = Params->end(); 5142 Param != ParamEnd; ++Param) { 5143 NamedDecl *Named = cast<NamedDecl>(*Param); 5144 if (Named->getDeclName()) { 5145 S->AddDecl(Named); 5146 IdResolver.AddDecl(Named); 5147 } 5148 } 5149 } 5150} 5151 5152void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 5153 if (!D) 5154 return; 5155 5156 TemplateParameterList *Params = 0; 5157 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) 5158 Params = Template->getTemplateParameters(); 5159 else if (ClassTemplatePartialSpecializationDecl *PartialSpec 5160 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 5161 Params = PartialSpec->getTemplateParameters(); 5162 else 5163 return; 5164 5165 for (TemplateParameterList::iterator Param = Params->begin(), 5166 ParamEnd = Params->end(); 5167 Param != ParamEnd; ++Param) { 5168 NamedDecl *Named = cast<NamedDecl>(*Param); 5169 if (Named->getDeclName()) { 5170 S->AddDecl(Named); 5171 IdResolver.AddDecl(Named); 5172 } 5173 } 5174} 5175 5176void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 5177 if (!RecordD) return; 5178 AdjustDeclIfTemplate(RecordD); 5179 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 5180 PushDeclContext(S, Record); 5181} 5182 5183void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 5184 if (!RecordD) return; 5185 PopDeclContext(); 5186} 5187 5188/// ActOnStartDelayedCXXMethodDeclaration - We have completed 5189/// parsing a top-level (non-nested) C++ class, and we are now 5190/// parsing those parts of the given Method declaration that could 5191/// not be parsed earlier (C++ [class.mem]p2), such as default 5192/// arguments. This action should enter the scope of the given 5193/// Method declaration as if we had just parsed the qualified method 5194/// name. However, it should not bring the parameters into scope; 5195/// that will be performed by ActOnDelayedCXXMethodParameter. 5196void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 5197} 5198 5199/// ActOnDelayedCXXMethodParameter - We've already started a delayed 5200/// C++ method declaration. We're (re-)introducing the given 5201/// function parameter into scope for use in parsing later parts of 5202/// the method declaration. For example, we could see an 5203/// ActOnParamDefaultArgument event for this parameter. 5204void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 5205 if (!ParamD) 5206 return; 5207 5208 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 5209 5210 // If this parameter has an unparsed default argument, clear it out 5211 // to make way for the parsed default argument. 5212 if (Param->hasUnparsedDefaultArg()) 5213 Param->setDefaultArg(0); 5214 5215 S->AddDecl(Param); 5216 if (Param->getDeclName()) 5217 IdResolver.AddDecl(Param); 5218} 5219 5220/// ActOnFinishDelayedCXXMethodDeclaration - We have finished 5221/// processing the delayed method declaration for Method. The method 5222/// declaration is now considered finished. There may be a separate 5223/// ActOnStartOfFunctionDef action later (not necessarily 5224/// immediately!) for this method, if it was also defined inside the 5225/// class body. 5226void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 5227 if (!MethodD) 5228 return; 5229 5230 AdjustDeclIfTemplate(MethodD); 5231 5232 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 5233 5234 // Now that we have our default arguments, check the constructor 5235 // again. It could produce additional diagnostics or affect whether 5236 // the class has implicitly-declared destructors, among other 5237 // things. 5238 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 5239 CheckConstructor(Constructor); 5240 5241 // Check the default arguments, which we may have added. 5242 if (!Method->isInvalidDecl()) 5243 CheckCXXDefaultArguments(Method); 5244} 5245 5246/// CheckConstructorDeclarator - Called by ActOnDeclarator to check 5247/// the well-formedness of the constructor declarator @p D with type @p 5248/// R. If there are any errors in the declarator, this routine will 5249/// emit diagnostics and set the invalid bit to true. In any case, the type 5250/// will be updated to reflect a well-formed type for the constructor and 5251/// returned. 5252QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 5253 StorageClass &SC) { 5254 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 5255 5256 // C++ [class.ctor]p3: 5257 // A constructor shall not be virtual (10.3) or static (9.4). A 5258 // constructor can be invoked for a const, volatile or const 5259 // volatile object. A constructor shall not be declared const, 5260 // volatile, or const volatile (9.3.2). 5261 if (isVirtual) { 5262 if (!D.isInvalidType()) 5263 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 5264 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 5265 << SourceRange(D.getIdentifierLoc()); 5266 D.setInvalidType(); 5267 } 5268 if (SC == SC_Static) { 5269 if (!D.isInvalidType()) 5270 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 5271 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 5272 << SourceRange(D.getIdentifierLoc()); 5273 D.setInvalidType(); 5274 SC = SC_None; 5275 } 5276 5277 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 5278 if (FTI.TypeQuals != 0) { 5279 if (FTI.TypeQuals & Qualifiers::Const) 5280 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 5281 << "const" << SourceRange(D.getIdentifierLoc()); 5282 if (FTI.TypeQuals & Qualifiers::Volatile) 5283 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 5284 << "volatile" << SourceRange(D.getIdentifierLoc()); 5285 if (FTI.TypeQuals & Qualifiers::Restrict) 5286 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 5287 << "restrict" << SourceRange(D.getIdentifierLoc()); 5288 D.setInvalidType(); 5289 } 5290 5291 // C++0x [class.ctor]p4: 5292 // A constructor shall not be declared with a ref-qualifier. 5293 if (FTI.hasRefQualifier()) { 5294 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 5295 << FTI.RefQualifierIsLValueRef 5296 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 5297 D.setInvalidType(); 5298 } 5299 5300 // Rebuild the function type "R" without any type qualifiers (in 5301 // case any of the errors above fired) and with "void" as the 5302 // return type, since constructors don't have return types. 5303 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 5304 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType()) 5305 return R; 5306 5307 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 5308 EPI.TypeQuals = 0; 5309 EPI.RefQualifier = RQ_None; 5310 5311 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(), 5312 Proto->getNumArgs(), EPI); 5313} 5314 5315/// CheckConstructor - Checks a fully-formed constructor for 5316/// well-formedness, issuing any diagnostics required. Returns true if 5317/// the constructor declarator is invalid. 5318void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 5319 CXXRecordDecl *ClassDecl 5320 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 5321 if (!ClassDecl) 5322 return Constructor->setInvalidDecl(); 5323 5324 // C++ [class.copy]p3: 5325 // A declaration of a constructor for a class X is ill-formed if 5326 // its first parameter is of type (optionally cv-qualified) X and 5327 // either there are no other parameters or else all other 5328 // parameters have default arguments. 5329 if (!Constructor->isInvalidDecl() && 5330 ((Constructor->getNumParams() == 1) || 5331 (Constructor->getNumParams() > 1 && 5332 Constructor->getParamDecl(1)->hasDefaultArg())) && 5333 Constructor->getTemplateSpecializationKind() 5334 != TSK_ImplicitInstantiation) { 5335 QualType ParamType = Constructor->getParamDecl(0)->getType(); 5336 QualType ClassTy = Context.getTagDeclType(ClassDecl); 5337 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 5338 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 5339 const char *ConstRef 5340 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 5341 : " const &"; 5342 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 5343 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 5344 5345 // FIXME: Rather that making the constructor invalid, we should endeavor 5346 // to fix the type. 5347 Constructor->setInvalidDecl(); 5348 } 5349 } 5350} 5351 5352/// CheckDestructor - Checks a fully-formed destructor definition for 5353/// well-formedness, issuing any diagnostics required. Returns true 5354/// on error. 5355bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 5356 CXXRecordDecl *RD = Destructor->getParent(); 5357 5358 if (Destructor->isVirtual()) { 5359 SourceLocation Loc; 5360 5361 if (!Destructor->isImplicit()) 5362 Loc = Destructor->getLocation(); 5363 else 5364 Loc = RD->getLocation(); 5365 5366 // If we have a virtual destructor, look up the deallocation function 5367 FunctionDecl *OperatorDelete = 0; 5368 DeclarationName Name = 5369 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 5370 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 5371 return true; 5372 5373 MarkFunctionReferenced(Loc, OperatorDelete); 5374 5375 Destructor->setOperatorDelete(OperatorDelete); 5376 } 5377 5378 return false; 5379} 5380 5381static inline bool 5382FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) { 5383 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 5384 FTI.ArgInfo[0].Param && 5385 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()); 5386} 5387 5388/// CheckDestructorDeclarator - Called by ActOnDeclarator to check 5389/// the well-formednes of the destructor declarator @p D with type @p 5390/// R. If there are any errors in the declarator, this routine will 5391/// emit diagnostics and set the declarator to invalid. Even if this happens, 5392/// will be updated to reflect a well-formed type for the destructor and 5393/// returned. 5394QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 5395 StorageClass& SC) { 5396 // C++ [class.dtor]p1: 5397 // [...] A typedef-name that names a class is a class-name 5398 // (7.1.3); however, a typedef-name that names a class shall not 5399 // be used as the identifier in the declarator for a destructor 5400 // declaration. 5401 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 5402 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 5403 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 5404 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 5405 else if (const TemplateSpecializationType *TST = 5406 DeclaratorType->getAs<TemplateSpecializationType>()) 5407 if (TST->isTypeAlias()) 5408 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 5409 << DeclaratorType << 1; 5410 5411 // C++ [class.dtor]p2: 5412 // A destructor is used to destroy objects of its class type. A 5413 // destructor takes no parameters, and no return type can be 5414 // specified for it (not even void). The address of a destructor 5415 // shall not be taken. A destructor shall not be static. A 5416 // destructor can be invoked for a const, volatile or const 5417 // volatile object. A destructor shall not be declared const, 5418 // volatile or const volatile (9.3.2). 5419 if (SC == SC_Static) { 5420 if (!D.isInvalidType()) 5421 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 5422 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 5423 << SourceRange(D.getIdentifierLoc()) 5424 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5425 5426 SC = SC_None; 5427 } 5428 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 5429 // Destructors don't have return types, but the parser will 5430 // happily parse something like: 5431 // 5432 // class X { 5433 // float ~X(); 5434 // }; 5435 // 5436 // The return type will be eliminated later. 5437 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 5438 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 5439 << SourceRange(D.getIdentifierLoc()); 5440 } 5441 5442 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 5443 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 5444 if (FTI.TypeQuals & Qualifiers::Const) 5445 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 5446 << "const" << SourceRange(D.getIdentifierLoc()); 5447 if (FTI.TypeQuals & Qualifiers::Volatile) 5448 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 5449 << "volatile" << SourceRange(D.getIdentifierLoc()); 5450 if (FTI.TypeQuals & Qualifiers::Restrict) 5451 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 5452 << "restrict" << SourceRange(D.getIdentifierLoc()); 5453 D.setInvalidType(); 5454 } 5455 5456 // C++0x [class.dtor]p2: 5457 // A destructor shall not be declared with a ref-qualifier. 5458 if (FTI.hasRefQualifier()) { 5459 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 5460 << FTI.RefQualifierIsLValueRef 5461 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 5462 D.setInvalidType(); 5463 } 5464 5465 // Make sure we don't have any parameters. 5466 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) { 5467 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 5468 5469 // Delete the parameters. 5470 FTI.freeArgs(); 5471 D.setInvalidType(); 5472 } 5473 5474 // Make sure the destructor isn't variadic. 5475 if (FTI.isVariadic) { 5476 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 5477 D.setInvalidType(); 5478 } 5479 5480 // Rebuild the function type "R" without any type qualifiers or 5481 // parameters (in case any of the errors above fired) and with 5482 // "void" as the return type, since destructors don't have return 5483 // types. 5484 if (!D.isInvalidType()) 5485 return R; 5486 5487 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 5488 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 5489 EPI.Variadic = false; 5490 EPI.TypeQuals = 0; 5491 EPI.RefQualifier = RQ_None; 5492 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI); 5493} 5494 5495/// CheckConversionDeclarator - Called by ActOnDeclarator to check the 5496/// well-formednes of the conversion function declarator @p D with 5497/// type @p R. If there are any errors in the declarator, this routine 5498/// will emit diagnostics and return true. Otherwise, it will return 5499/// false. Either way, the type @p R will be updated to reflect a 5500/// well-formed type for the conversion operator. 5501void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 5502 StorageClass& SC) { 5503 // C++ [class.conv.fct]p1: 5504 // Neither parameter types nor return type can be specified. The 5505 // type of a conversion function (8.3.5) is "function taking no 5506 // parameter returning conversion-type-id." 5507 if (SC == SC_Static) { 5508 if (!D.isInvalidType()) 5509 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 5510 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 5511 << SourceRange(D.getIdentifierLoc()); 5512 D.setInvalidType(); 5513 SC = SC_None; 5514 } 5515 5516 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId); 5517 5518 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 5519 // Conversion functions don't have return types, but the parser will 5520 // happily parse something like: 5521 // 5522 // class X { 5523 // float operator bool(); 5524 // }; 5525 // 5526 // The return type will be changed later anyway. 5527 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 5528 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 5529 << SourceRange(D.getIdentifierLoc()); 5530 D.setInvalidType(); 5531 } 5532 5533 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 5534 5535 // Make sure we don't have any parameters. 5536 if (Proto->getNumArgs() > 0) { 5537 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 5538 5539 // Delete the parameters. 5540 D.getFunctionTypeInfo().freeArgs(); 5541 D.setInvalidType(); 5542 } else if (Proto->isVariadic()) { 5543 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 5544 D.setInvalidType(); 5545 } 5546 5547 // Diagnose "&operator bool()" and other such nonsense. This 5548 // is actually a gcc extension which we don't support. 5549 if (Proto->getResultType() != ConvType) { 5550 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 5551 << Proto->getResultType(); 5552 D.setInvalidType(); 5553 ConvType = Proto->getResultType(); 5554 } 5555 5556 // C++ [class.conv.fct]p4: 5557 // The conversion-type-id shall not represent a function type nor 5558 // an array type. 5559 if (ConvType->isArrayType()) { 5560 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 5561 ConvType = Context.getPointerType(ConvType); 5562 D.setInvalidType(); 5563 } else if (ConvType->isFunctionType()) { 5564 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 5565 ConvType = Context.getPointerType(ConvType); 5566 D.setInvalidType(); 5567 } 5568 5569 // Rebuild the function type "R" without any parameters (in case any 5570 // of the errors above fired) and with the conversion type as the 5571 // return type. 5572 if (D.isInvalidType()) 5573 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo()); 5574 5575 // C++0x explicit conversion operators. 5576 if (D.getDeclSpec().isExplicitSpecified()) 5577 Diag(D.getDeclSpec().getExplicitSpecLoc(), 5578 getLangOptions().CPlusPlus0x ? 5579 diag::warn_cxx98_compat_explicit_conversion_functions : 5580 diag::ext_explicit_conversion_functions) 5581 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 5582} 5583 5584/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 5585/// the declaration of the given C++ conversion function. This routine 5586/// is responsible for recording the conversion function in the C++ 5587/// class, if possible. 5588Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 5589 assert(Conversion && "Expected to receive a conversion function declaration"); 5590 5591 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 5592 5593 // Make sure we aren't redeclaring the conversion function. 5594 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 5595 5596 // C++ [class.conv.fct]p1: 5597 // [...] A conversion function is never used to convert a 5598 // (possibly cv-qualified) object to the (possibly cv-qualified) 5599 // same object type (or a reference to it), to a (possibly 5600 // cv-qualified) base class of that type (or a reference to it), 5601 // or to (possibly cv-qualified) void. 5602 // FIXME: Suppress this warning if the conversion function ends up being a 5603 // virtual function that overrides a virtual function in a base class. 5604 QualType ClassType 5605 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 5606 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 5607 ConvType = ConvTypeRef->getPointeeType(); 5608 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 5609 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 5610 /* Suppress diagnostics for instantiations. */; 5611 else if (ConvType->isRecordType()) { 5612 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 5613 if (ConvType == ClassType) 5614 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 5615 << ClassType; 5616 else if (IsDerivedFrom(ClassType, ConvType)) 5617 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 5618 << ClassType << ConvType; 5619 } else if (ConvType->isVoidType()) { 5620 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 5621 << ClassType << ConvType; 5622 } 5623 5624 if (FunctionTemplateDecl *ConversionTemplate 5625 = Conversion->getDescribedFunctionTemplate()) 5626 return ConversionTemplate; 5627 5628 return Conversion; 5629} 5630 5631//===----------------------------------------------------------------------===// 5632// Namespace Handling 5633//===----------------------------------------------------------------------===// 5634 5635 5636 5637/// ActOnStartNamespaceDef - This is called at the start of a namespace 5638/// definition. 5639Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 5640 SourceLocation InlineLoc, 5641 SourceLocation NamespaceLoc, 5642 SourceLocation IdentLoc, 5643 IdentifierInfo *II, 5644 SourceLocation LBrace, 5645 AttributeList *AttrList) { 5646 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 5647 // For anonymous namespace, take the location of the left brace. 5648 SourceLocation Loc = II ? IdentLoc : LBrace; 5649 bool IsInline = InlineLoc.isValid(); 5650 bool IsInvalid = false; 5651 bool IsStd = false; 5652 bool AddToKnown = false; 5653 Scope *DeclRegionScope = NamespcScope->getParent(); 5654 5655 NamespaceDecl *PrevNS = 0; 5656 if (II) { 5657 // C++ [namespace.def]p2: 5658 // The identifier in an original-namespace-definition shall not 5659 // have been previously defined in the declarative region in 5660 // which the original-namespace-definition appears. The 5661 // identifier in an original-namespace-definition is the name of 5662 // the namespace. Subsequently in that declarative region, it is 5663 // treated as an original-namespace-name. 5664 // 5665 // Since namespace names are unique in their scope, and we don't 5666 // look through using directives, just look for any ordinary names. 5667 5668 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member | 5669 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag | 5670 Decl::IDNS_Namespace; 5671 NamedDecl *PrevDecl = 0; 5672 for (DeclContext::lookup_result R 5673 = CurContext->getRedeclContext()->lookup(II); 5674 R.first != R.second; ++R.first) { 5675 if ((*R.first)->getIdentifierNamespace() & IDNS) { 5676 PrevDecl = *R.first; 5677 break; 5678 } 5679 } 5680 5681 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 5682 5683 if (PrevNS) { 5684 // This is an extended namespace definition. 5685 if (IsInline != PrevNS->isInline()) { 5686 // inline-ness must match 5687 if (PrevNS->isInline()) { 5688 // The user probably just forgot the 'inline', so suggest that it 5689 // be added back. 5690 Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 5691 << FixItHint::CreateInsertion(NamespaceLoc, "inline "); 5692 } else { 5693 Diag(Loc, diag::err_inline_namespace_mismatch) 5694 << IsInline; 5695 } 5696 Diag(PrevNS->getLocation(), diag::note_previous_definition); 5697 5698 IsInline = PrevNS->isInline(); 5699 } 5700 } else if (PrevDecl) { 5701 // This is an invalid name redefinition. 5702 Diag(Loc, diag::err_redefinition_different_kind) 5703 << II; 5704 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 5705 IsInvalid = true; 5706 // Continue on to push Namespc as current DeclContext and return it. 5707 } else if (II->isStr("std") && 5708 CurContext->getRedeclContext()->isTranslationUnit()) { 5709 // This is the first "real" definition of the namespace "std", so update 5710 // our cache of the "std" namespace to point at this definition. 5711 PrevNS = getStdNamespace(); 5712 IsStd = true; 5713 AddToKnown = !IsInline; 5714 } else { 5715 // We've seen this namespace for the first time. 5716 AddToKnown = !IsInline; 5717 } 5718 } else { 5719 // Anonymous namespaces. 5720 5721 // Determine whether the parent already has an anonymous namespace. 5722 DeclContext *Parent = CurContext->getRedeclContext(); 5723 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 5724 PrevNS = TU->getAnonymousNamespace(); 5725 } else { 5726 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 5727 PrevNS = ND->getAnonymousNamespace(); 5728 } 5729 5730 if (PrevNS && IsInline != PrevNS->isInline()) { 5731 // inline-ness must match 5732 Diag(Loc, diag::err_inline_namespace_mismatch) 5733 << IsInline; 5734 Diag(PrevNS->getLocation(), diag::note_previous_definition); 5735 5736 // Recover by ignoring the new namespace's inline status. 5737 IsInline = PrevNS->isInline(); 5738 } 5739 } 5740 5741 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 5742 StartLoc, Loc, II, PrevNS); 5743 if (IsInvalid) 5744 Namespc->setInvalidDecl(); 5745 5746 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 5747 5748 // FIXME: Should we be merging attributes? 5749 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 5750 PushNamespaceVisibilityAttr(Attr, Loc); 5751 5752 if (IsStd) 5753 StdNamespace = Namespc; 5754 if (AddToKnown) 5755 KnownNamespaces[Namespc] = false; 5756 5757 if (II) { 5758 PushOnScopeChains(Namespc, DeclRegionScope); 5759 } else { 5760 // Link the anonymous namespace into its parent. 5761 DeclContext *Parent = CurContext->getRedeclContext(); 5762 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 5763 TU->setAnonymousNamespace(Namespc); 5764 } else { 5765 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 5766 } 5767 5768 CurContext->addDecl(Namespc); 5769 5770 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 5771 // behaves as if it were replaced by 5772 // namespace unique { /* empty body */ } 5773 // using namespace unique; 5774 // namespace unique { namespace-body } 5775 // where all occurrences of 'unique' in a translation unit are 5776 // replaced by the same identifier and this identifier differs 5777 // from all other identifiers in the entire program. 5778 5779 // We just create the namespace with an empty name and then add an 5780 // implicit using declaration, just like the standard suggests. 5781 // 5782 // CodeGen enforces the "universally unique" aspect by giving all 5783 // declarations semantically contained within an anonymous 5784 // namespace internal linkage. 5785 5786 if (!PrevNS) { 5787 UsingDirectiveDecl* UD 5788 = UsingDirectiveDecl::Create(Context, CurContext, 5789 /* 'using' */ LBrace, 5790 /* 'namespace' */ SourceLocation(), 5791 /* qualifier */ NestedNameSpecifierLoc(), 5792 /* identifier */ SourceLocation(), 5793 Namespc, 5794 /* Ancestor */ CurContext); 5795 UD->setImplicit(); 5796 CurContext->addDecl(UD); 5797 } 5798 } 5799 5800 // Although we could have an invalid decl (i.e. the namespace name is a 5801 // redefinition), push it as current DeclContext and try to continue parsing. 5802 // FIXME: We should be able to push Namespc here, so that the each DeclContext 5803 // for the namespace has the declarations that showed up in that particular 5804 // namespace definition. 5805 PushDeclContext(NamespcScope, Namespc); 5806 return Namespc; 5807} 5808 5809/// getNamespaceDecl - Returns the namespace a decl represents. If the decl 5810/// is a namespace alias, returns the namespace it points to. 5811static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 5812 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 5813 return AD->getNamespace(); 5814 return dyn_cast_or_null<NamespaceDecl>(D); 5815} 5816 5817/// ActOnFinishNamespaceDef - This callback is called after a namespace is 5818/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 5819void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 5820 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 5821 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 5822 Namespc->setRBraceLoc(RBrace); 5823 PopDeclContext(); 5824 if (Namespc->hasAttr<VisibilityAttr>()) 5825 PopPragmaVisibility(true, RBrace); 5826} 5827 5828CXXRecordDecl *Sema::getStdBadAlloc() const { 5829 return cast_or_null<CXXRecordDecl>( 5830 StdBadAlloc.get(Context.getExternalSource())); 5831} 5832 5833NamespaceDecl *Sema::getStdNamespace() const { 5834 return cast_or_null<NamespaceDecl>( 5835 StdNamespace.get(Context.getExternalSource())); 5836} 5837 5838/// \brief Retrieve the special "std" namespace, which may require us to 5839/// implicitly define the namespace. 5840NamespaceDecl *Sema::getOrCreateStdNamespace() { 5841 if (!StdNamespace) { 5842 // The "std" namespace has not yet been defined, so build one implicitly. 5843 StdNamespace = NamespaceDecl::Create(Context, 5844 Context.getTranslationUnitDecl(), 5845 /*Inline=*/false, 5846 SourceLocation(), SourceLocation(), 5847 &PP.getIdentifierTable().get("std"), 5848 /*PrevDecl=*/0); 5849 getStdNamespace()->setImplicit(true); 5850 } 5851 5852 return getStdNamespace(); 5853} 5854 5855bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 5856 assert(getLangOptions().CPlusPlus && 5857 "Looking for std::initializer_list outside of C++."); 5858 5859 // We're looking for implicit instantiations of 5860 // template <typename E> class std::initializer_list. 5861 5862 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 5863 return false; 5864 5865 ClassTemplateDecl *Template = 0; 5866 const TemplateArgument *Arguments = 0; 5867 5868 if (const RecordType *RT = Ty->getAs<RecordType>()) { 5869 5870 ClassTemplateSpecializationDecl *Specialization = 5871 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 5872 if (!Specialization) 5873 return false; 5874 5875 Template = Specialization->getSpecializedTemplate(); 5876 Arguments = Specialization->getTemplateArgs().data(); 5877 } else if (const TemplateSpecializationType *TST = 5878 Ty->getAs<TemplateSpecializationType>()) { 5879 Template = dyn_cast_or_null<ClassTemplateDecl>( 5880 TST->getTemplateName().getAsTemplateDecl()); 5881 Arguments = TST->getArgs(); 5882 } 5883 if (!Template) 5884 return false; 5885 5886 if (!StdInitializerList) { 5887 // Haven't recognized std::initializer_list yet, maybe this is it. 5888 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 5889 if (TemplateClass->getIdentifier() != 5890 &PP.getIdentifierTable().get("initializer_list") || 5891 !getStdNamespace()->InEnclosingNamespaceSetOf( 5892 TemplateClass->getDeclContext())) 5893 return false; 5894 // This is a template called std::initializer_list, but is it the right 5895 // template? 5896 TemplateParameterList *Params = Template->getTemplateParameters(); 5897 if (Params->getMinRequiredArguments() != 1) 5898 return false; 5899 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 5900 return false; 5901 5902 // It's the right template. 5903 StdInitializerList = Template; 5904 } 5905 5906 if (Template != StdInitializerList) 5907 return false; 5908 5909 // This is an instance of std::initializer_list. Find the argument type. 5910 if (Element) 5911 *Element = Arguments[0].getAsType(); 5912 return true; 5913} 5914 5915static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 5916 NamespaceDecl *Std = S.getStdNamespace(); 5917 if (!Std) { 5918 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 5919 return 0; 5920 } 5921 5922 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 5923 Loc, Sema::LookupOrdinaryName); 5924 if (!S.LookupQualifiedName(Result, Std)) { 5925 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 5926 return 0; 5927 } 5928 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 5929 if (!Template) { 5930 Result.suppressDiagnostics(); 5931 // We found something weird. Complain about the first thing we found. 5932 NamedDecl *Found = *Result.begin(); 5933 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 5934 return 0; 5935 } 5936 5937 // We found some template called std::initializer_list. Now verify that it's 5938 // correct. 5939 TemplateParameterList *Params = Template->getTemplateParameters(); 5940 if (Params->getMinRequiredArguments() != 1 || 5941 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 5942 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 5943 return 0; 5944 } 5945 5946 return Template; 5947} 5948 5949QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 5950 if (!StdInitializerList) { 5951 StdInitializerList = LookupStdInitializerList(*this, Loc); 5952 if (!StdInitializerList) 5953 return QualType(); 5954 } 5955 5956 TemplateArgumentListInfo Args(Loc, Loc); 5957 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 5958 Context.getTrivialTypeSourceInfo(Element, 5959 Loc))); 5960 return Context.getCanonicalType( 5961 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 5962} 5963 5964bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) { 5965 // C++ [dcl.init.list]p2: 5966 // A constructor is an initializer-list constructor if its first parameter 5967 // is of type std::initializer_list<E> or reference to possibly cv-qualified 5968 // std::initializer_list<E> for some type E, and either there are no other 5969 // parameters or else all other parameters have default arguments. 5970 if (Ctor->getNumParams() < 1 || 5971 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 5972 return false; 5973 5974 QualType ArgType = Ctor->getParamDecl(0)->getType(); 5975 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 5976 ArgType = RT->getPointeeType().getUnqualifiedType(); 5977 5978 return isStdInitializerList(ArgType, 0); 5979} 5980 5981/// \brief Determine whether a using statement is in a context where it will be 5982/// apply in all contexts. 5983static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 5984 switch (CurContext->getDeclKind()) { 5985 case Decl::TranslationUnit: 5986 return true; 5987 case Decl::LinkageSpec: 5988 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 5989 default: 5990 return false; 5991 } 5992} 5993 5994namespace { 5995 5996// Callback to only accept typo corrections that are namespaces. 5997class NamespaceValidatorCCC : public CorrectionCandidateCallback { 5998 public: 5999 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 6000 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 6001 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 6002 } 6003 return false; 6004 } 6005}; 6006 6007} 6008 6009static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 6010 CXXScopeSpec &SS, 6011 SourceLocation IdentLoc, 6012 IdentifierInfo *Ident) { 6013 NamespaceValidatorCCC Validator; 6014 R.clear(); 6015 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(), 6016 R.getLookupKind(), Sc, &SS, 6017 Validator)) { 6018 std::string CorrectedStr(Corrected.getAsString(S.getLangOptions())); 6019 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOptions())); 6020 if (DeclContext *DC = S.computeDeclContext(SS, false)) 6021 S.Diag(IdentLoc, diag::err_using_directive_member_suggest) 6022 << Ident << DC << CorrectedQuotedStr << SS.getRange() 6023 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr); 6024 else 6025 S.Diag(IdentLoc, diag::err_using_directive_suggest) 6026 << Ident << CorrectedQuotedStr 6027 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr); 6028 6029 S.Diag(Corrected.getCorrectionDecl()->getLocation(), 6030 diag::note_namespace_defined_here) << CorrectedQuotedStr; 6031 6032 Ident = Corrected.getCorrectionAsIdentifierInfo(); 6033 R.addDecl(Corrected.getCorrectionDecl()); 6034 return true; 6035 } 6036 return false; 6037} 6038 6039Decl *Sema::ActOnUsingDirective(Scope *S, 6040 SourceLocation UsingLoc, 6041 SourceLocation NamespcLoc, 6042 CXXScopeSpec &SS, 6043 SourceLocation IdentLoc, 6044 IdentifierInfo *NamespcName, 6045 AttributeList *AttrList) { 6046 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 6047 assert(NamespcName && "Invalid NamespcName."); 6048 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 6049 6050 // This can only happen along a recovery path. 6051 while (S->getFlags() & Scope::TemplateParamScope) 6052 S = S->getParent(); 6053 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 6054 6055 UsingDirectiveDecl *UDir = 0; 6056 NestedNameSpecifier *Qualifier = 0; 6057 if (SS.isSet()) 6058 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 6059 6060 // Lookup namespace name. 6061 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 6062 LookupParsedName(R, S, &SS); 6063 if (R.isAmbiguous()) 6064 return 0; 6065 6066 if (R.empty()) { 6067 R.clear(); 6068 // Allow "using namespace std;" or "using namespace ::std;" even if 6069 // "std" hasn't been defined yet, for GCC compatibility. 6070 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 6071 NamespcName->isStr("std")) { 6072 Diag(IdentLoc, diag::ext_using_undefined_std); 6073 R.addDecl(getOrCreateStdNamespace()); 6074 R.resolveKind(); 6075 } 6076 // Otherwise, attempt typo correction. 6077 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 6078 } 6079 6080 if (!R.empty()) { 6081 NamedDecl *Named = R.getFoundDecl(); 6082 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named)) 6083 && "expected namespace decl"); 6084 // C++ [namespace.udir]p1: 6085 // A using-directive specifies that the names in the nominated 6086 // namespace can be used in the scope in which the 6087 // using-directive appears after the using-directive. During 6088 // unqualified name lookup (3.4.1), the names appear as if they 6089 // were declared in the nearest enclosing namespace which 6090 // contains both the using-directive and the nominated 6091 // namespace. [Note: in this context, "contains" means "contains 6092 // directly or indirectly". ] 6093 6094 // Find enclosing context containing both using-directive and 6095 // nominated namespace. 6096 NamespaceDecl *NS = getNamespaceDecl(Named); 6097 DeclContext *CommonAncestor = cast<DeclContext>(NS); 6098 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 6099 CommonAncestor = CommonAncestor->getParent(); 6100 6101 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 6102 SS.getWithLocInContext(Context), 6103 IdentLoc, Named, CommonAncestor); 6104 6105 if (IsUsingDirectiveInToplevelContext(CurContext) && 6106 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 6107 Diag(IdentLoc, diag::warn_using_directive_in_header); 6108 } 6109 6110 PushUsingDirective(S, UDir); 6111 } else { 6112 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 6113 } 6114 6115 // FIXME: We ignore attributes for now. 6116 return UDir; 6117} 6118 6119void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 6120 // If scope has associated entity, then using directive is at namespace 6121 // or translation unit scope. We add UsingDirectiveDecls, into 6122 // it's lookup structure. 6123 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) 6124 Ctx->addDecl(UDir); 6125 else 6126 // Otherwise it is block-sope. using-directives will affect lookup 6127 // only to the end of scope. 6128 S->PushUsingDirective(UDir); 6129} 6130 6131 6132Decl *Sema::ActOnUsingDeclaration(Scope *S, 6133 AccessSpecifier AS, 6134 bool HasUsingKeyword, 6135 SourceLocation UsingLoc, 6136 CXXScopeSpec &SS, 6137 UnqualifiedId &Name, 6138 AttributeList *AttrList, 6139 bool IsTypeName, 6140 SourceLocation TypenameLoc) { 6141 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 6142 6143 switch (Name.getKind()) { 6144 case UnqualifiedId::IK_ImplicitSelfParam: 6145 case UnqualifiedId::IK_Identifier: 6146 case UnqualifiedId::IK_OperatorFunctionId: 6147 case UnqualifiedId::IK_LiteralOperatorId: 6148 case UnqualifiedId::IK_ConversionFunctionId: 6149 break; 6150 6151 case UnqualifiedId::IK_ConstructorName: 6152 case UnqualifiedId::IK_ConstructorTemplateId: 6153 // C++0x inherited constructors. 6154 Diag(Name.getSourceRange().getBegin(), 6155 getLangOptions().CPlusPlus0x ? 6156 diag::warn_cxx98_compat_using_decl_constructor : 6157 diag::err_using_decl_constructor) 6158 << SS.getRange(); 6159 6160 if (getLangOptions().CPlusPlus0x) break; 6161 6162 return 0; 6163 6164 case UnqualifiedId::IK_DestructorName: 6165 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor) 6166 << SS.getRange(); 6167 return 0; 6168 6169 case UnqualifiedId::IK_TemplateId: 6170 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id) 6171 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 6172 return 0; 6173 } 6174 6175 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 6176 DeclarationName TargetName = TargetNameInfo.getName(); 6177 if (!TargetName) 6178 return 0; 6179 6180 // Warn about using declarations. 6181 // TODO: store that the declaration was written without 'using' and 6182 // talk about access decls instead of using decls in the 6183 // diagnostics. 6184 if (!HasUsingKeyword) { 6185 UsingLoc = Name.getSourceRange().getBegin(); 6186 6187 Diag(UsingLoc, diag::warn_access_decl_deprecated) 6188 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 6189 } 6190 6191 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 6192 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 6193 return 0; 6194 6195 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 6196 TargetNameInfo, AttrList, 6197 /* IsInstantiation */ false, 6198 IsTypeName, TypenameLoc); 6199 if (UD) 6200 PushOnScopeChains(UD, S, /*AddToContext*/ false); 6201 6202 return UD; 6203} 6204 6205/// \brief Determine whether a using declaration considers the given 6206/// declarations as "equivalent", e.g., if they are redeclarations of 6207/// the same entity or are both typedefs of the same type. 6208static bool 6209IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2, 6210 bool &SuppressRedeclaration) { 6211 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) { 6212 SuppressRedeclaration = false; 6213 return true; 6214 } 6215 6216 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 6217 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) { 6218 SuppressRedeclaration = true; 6219 return Context.hasSameType(TD1->getUnderlyingType(), 6220 TD2->getUnderlyingType()); 6221 } 6222 6223 return false; 6224} 6225 6226 6227/// Determines whether to create a using shadow decl for a particular 6228/// decl, given the set of decls existing prior to this using lookup. 6229bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 6230 const LookupResult &Previous) { 6231 // Diagnose finding a decl which is not from a base class of the 6232 // current class. We do this now because there are cases where this 6233 // function will silently decide not to build a shadow decl, which 6234 // will pre-empt further diagnostics. 6235 // 6236 // We don't need to do this in C++0x because we do the check once on 6237 // the qualifier. 6238 // 6239 // FIXME: diagnose the following if we care enough: 6240 // struct A { int foo; }; 6241 // struct B : A { using A::foo; }; 6242 // template <class T> struct C : A {}; 6243 // template <class T> struct D : C<T> { using B::foo; } // <--- 6244 // This is invalid (during instantiation) in C++03 because B::foo 6245 // resolves to the using decl in B, which is not a base class of D<T>. 6246 // We can't diagnose it immediately because C<T> is an unknown 6247 // specialization. The UsingShadowDecl in D<T> then points directly 6248 // to A::foo, which will look well-formed when we instantiate. 6249 // The right solution is to not collapse the shadow-decl chain. 6250 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) { 6251 DeclContext *OrigDC = Orig->getDeclContext(); 6252 6253 // Handle enums and anonymous structs. 6254 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 6255 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 6256 while (OrigRec->isAnonymousStructOrUnion()) 6257 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 6258 6259 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 6260 if (OrigDC == CurContext) { 6261 Diag(Using->getLocation(), 6262 diag::err_using_decl_nested_name_specifier_is_current_class) 6263 << Using->getQualifierLoc().getSourceRange(); 6264 Diag(Orig->getLocation(), diag::note_using_decl_target); 6265 return true; 6266 } 6267 6268 Diag(Using->getQualifierLoc().getBeginLoc(), 6269 diag::err_using_decl_nested_name_specifier_is_not_base_class) 6270 << Using->getQualifier() 6271 << cast<CXXRecordDecl>(CurContext) 6272 << Using->getQualifierLoc().getSourceRange(); 6273 Diag(Orig->getLocation(), diag::note_using_decl_target); 6274 return true; 6275 } 6276 } 6277 6278 if (Previous.empty()) return false; 6279 6280 NamedDecl *Target = Orig; 6281 if (isa<UsingShadowDecl>(Target)) 6282 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 6283 6284 // If the target happens to be one of the previous declarations, we 6285 // don't have a conflict. 6286 // 6287 // FIXME: but we might be increasing its access, in which case we 6288 // should redeclare it. 6289 NamedDecl *NonTag = 0, *Tag = 0; 6290 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 6291 I != E; ++I) { 6292 NamedDecl *D = (*I)->getUnderlyingDecl(); 6293 bool Result; 6294 if (IsEquivalentForUsingDecl(Context, D, Target, Result)) 6295 return Result; 6296 6297 (isa<TagDecl>(D) ? Tag : NonTag) = D; 6298 } 6299 6300 if (Target->isFunctionOrFunctionTemplate()) { 6301 FunctionDecl *FD; 6302 if (isa<FunctionTemplateDecl>(Target)) 6303 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl(); 6304 else 6305 FD = cast<FunctionDecl>(Target); 6306 6307 NamedDecl *OldDecl = 0; 6308 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) { 6309 case Ovl_Overload: 6310 return false; 6311 6312 case Ovl_NonFunction: 6313 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6314 break; 6315 6316 // We found a decl with the exact signature. 6317 case Ovl_Match: 6318 // If we're in a record, we want to hide the target, so we 6319 // return true (without a diagnostic) to tell the caller not to 6320 // build a shadow decl. 6321 if (CurContext->isRecord()) 6322 return true; 6323 6324 // If we're not in a record, this is an error. 6325 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6326 break; 6327 } 6328 6329 Diag(Target->getLocation(), diag::note_using_decl_target); 6330 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 6331 return true; 6332 } 6333 6334 // Target is not a function. 6335 6336 if (isa<TagDecl>(Target)) { 6337 // No conflict between a tag and a non-tag. 6338 if (!Tag) return false; 6339 6340 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6341 Diag(Target->getLocation(), diag::note_using_decl_target); 6342 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 6343 return true; 6344 } 6345 6346 // No conflict between a tag and a non-tag. 6347 if (!NonTag) return false; 6348 6349 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6350 Diag(Target->getLocation(), diag::note_using_decl_target); 6351 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 6352 return true; 6353} 6354 6355/// Builds a shadow declaration corresponding to a 'using' declaration. 6356UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 6357 UsingDecl *UD, 6358 NamedDecl *Orig) { 6359 6360 // If we resolved to another shadow declaration, just coalesce them. 6361 NamedDecl *Target = Orig; 6362 if (isa<UsingShadowDecl>(Target)) { 6363 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 6364 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 6365 } 6366 6367 UsingShadowDecl *Shadow 6368 = UsingShadowDecl::Create(Context, CurContext, 6369 UD->getLocation(), UD, Target); 6370 UD->addShadowDecl(Shadow); 6371 6372 Shadow->setAccess(UD->getAccess()); 6373 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 6374 Shadow->setInvalidDecl(); 6375 6376 if (S) 6377 PushOnScopeChains(Shadow, S); 6378 else 6379 CurContext->addDecl(Shadow); 6380 6381 6382 return Shadow; 6383} 6384 6385/// Hides a using shadow declaration. This is required by the current 6386/// using-decl implementation when a resolvable using declaration in a 6387/// class is followed by a declaration which would hide or override 6388/// one or more of the using decl's targets; for example: 6389/// 6390/// struct Base { void foo(int); }; 6391/// struct Derived : Base { 6392/// using Base::foo; 6393/// void foo(int); 6394/// }; 6395/// 6396/// The governing language is C++03 [namespace.udecl]p12: 6397/// 6398/// When a using-declaration brings names from a base class into a 6399/// derived class scope, member functions in the derived class 6400/// override and/or hide member functions with the same name and 6401/// parameter types in a base class (rather than conflicting). 6402/// 6403/// There are two ways to implement this: 6404/// (1) optimistically create shadow decls when they're not hidden 6405/// by existing declarations, or 6406/// (2) don't create any shadow decls (or at least don't make them 6407/// visible) until we've fully parsed/instantiated the class. 6408/// The problem with (1) is that we might have to retroactively remove 6409/// a shadow decl, which requires several O(n) operations because the 6410/// decl structures are (very reasonably) not designed for removal. 6411/// (2) avoids this but is very fiddly and phase-dependent. 6412void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 6413 if (Shadow->getDeclName().getNameKind() == 6414 DeclarationName::CXXConversionFunctionName) 6415 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 6416 6417 // Remove it from the DeclContext... 6418 Shadow->getDeclContext()->removeDecl(Shadow); 6419 6420 // ...and the scope, if applicable... 6421 if (S) { 6422 S->RemoveDecl(Shadow); 6423 IdResolver.RemoveDecl(Shadow); 6424 } 6425 6426 // ...and the using decl. 6427 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 6428 6429 // TODO: complain somehow if Shadow was used. It shouldn't 6430 // be possible for this to happen, because...? 6431} 6432 6433/// Builds a using declaration. 6434/// 6435/// \param IsInstantiation - Whether this call arises from an 6436/// instantiation of an unresolved using declaration. We treat 6437/// the lookup differently for these declarations. 6438NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 6439 SourceLocation UsingLoc, 6440 CXXScopeSpec &SS, 6441 const DeclarationNameInfo &NameInfo, 6442 AttributeList *AttrList, 6443 bool IsInstantiation, 6444 bool IsTypeName, 6445 SourceLocation TypenameLoc) { 6446 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 6447 SourceLocation IdentLoc = NameInfo.getLoc(); 6448 assert(IdentLoc.isValid() && "Invalid TargetName location."); 6449 6450 // FIXME: We ignore attributes for now. 6451 6452 if (SS.isEmpty()) { 6453 Diag(IdentLoc, diag::err_using_requires_qualname); 6454 return 0; 6455 } 6456 6457 // Do the redeclaration lookup in the current scope. 6458 LookupResult Previous(*this, NameInfo, LookupUsingDeclName, 6459 ForRedeclaration); 6460 Previous.setHideTags(false); 6461 if (S) { 6462 LookupName(Previous, S); 6463 6464 // It is really dumb that we have to do this. 6465 LookupResult::Filter F = Previous.makeFilter(); 6466 while (F.hasNext()) { 6467 NamedDecl *D = F.next(); 6468 if (!isDeclInScope(D, CurContext, S)) 6469 F.erase(); 6470 } 6471 F.done(); 6472 } else { 6473 assert(IsInstantiation && "no scope in non-instantiation"); 6474 assert(CurContext->isRecord() && "scope not record in instantiation"); 6475 LookupQualifiedName(Previous, CurContext); 6476 } 6477 6478 // Check for invalid redeclarations. 6479 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous)) 6480 return 0; 6481 6482 // Check for bad qualifiers. 6483 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc)) 6484 return 0; 6485 6486 DeclContext *LookupContext = computeDeclContext(SS); 6487 NamedDecl *D; 6488 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 6489 if (!LookupContext) { 6490 if (IsTypeName) { 6491 // FIXME: not all declaration name kinds are legal here 6492 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 6493 UsingLoc, TypenameLoc, 6494 QualifierLoc, 6495 IdentLoc, NameInfo.getName()); 6496 } else { 6497 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 6498 QualifierLoc, NameInfo); 6499 } 6500 } else { 6501 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 6502 NameInfo, IsTypeName); 6503 } 6504 D->setAccess(AS); 6505 CurContext->addDecl(D); 6506 6507 if (!LookupContext) return D; 6508 UsingDecl *UD = cast<UsingDecl>(D); 6509 6510 if (RequireCompleteDeclContext(SS, LookupContext)) { 6511 UD->setInvalidDecl(); 6512 return UD; 6513 } 6514 6515 // Constructor inheriting using decls get special treatment. 6516 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) { 6517 if (CheckInheritedConstructorUsingDecl(UD)) 6518 UD->setInvalidDecl(); 6519 return UD; 6520 } 6521 6522 // Otherwise, look up the target name. 6523 6524 LookupResult R(*this, NameInfo, LookupOrdinaryName); 6525 6526 // Unlike most lookups, we don't always want to hide tag 6527 // declarations: tag names are visible through the using declaration 6528 // even if hidden by ordinary names, *except* in a dependent context 6529 // where it's important for the sanity of two-phase lookup. 6530 if (!IsInstantiation) 6531 R.setHideTags(false); 6532 6533 LookupQualifiedName(R, LookupContext); 6534 6535 if (R.empty()) { 6536 Diag(IdentLoc, diag::err_no_member) 6537 << NameInfo.getName() << LookupContext << SS.getRange(); 6538 UD->setInvalidDecl(); 6539 return UD; 6540 } 6541 6542 if (R.isAmbiguous()) { 6543 UD->setInvalidDecl(); 6544 return UD; 6545 } 6546 6547 if (IsTypeName) { 6548 // If we asked for a typename and got a non-type decl, error out. 6549 if (!R.getAsSingle<TypeDecl>()) { 6550 Diag(IdentLoc, diag::err_using_typename_non_type); 6551 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 6552 Diag((*I)->getUnderlyingDecl()->getLocation(), 6553 diag::note_using_decl_target); 6554 UD->setInvalidDecl(); 6555 return UD; 6556 } 6557 } else { 6558 // If we asked for a non-typename and we got a type, error out, 6559 // but only if this is an instantiation of an unresolved using 6560 // decl. Otherwise just silently find the type name. 6561 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 6562 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 6563 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 6564 UD->setInvalidDecl(); 6565 return UD; 6566 } 6567 } 6568 6569 // C++0x N2914 [namespace.udecl]p6: 6570 // A using-declaration shall not name a namespace. 6571 if (R.getAsSingle<NamespaceDecl>()) { 6572 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 6573 << SS.getRange(); 6574 UD->setInvalidDecl(); 6575 return UD; 6576 } 6577 6578 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 6579 if (!CheckUsingShadowDecl(UD, *I, Previous)) 6580 BuildUsingShadowDecl(S, UD, *I); 6581 } 6582 6583 return UD; 6584} 6585 6586/// Additional checks for a using declaration referring to a constructor name. 6587bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) { 6588 if (UD->isTypeName()) { 6589 // FIXME: Cannot specify typename when specifying constructor 6590 return true; 6591 } 6592 6593 const Type *SourceType = UD->getQualifier()->getAsType(); 6594 assert(SourceType && 6595 "Using decl naming constructor doesn't have type in scope spec."); 6596 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 6597 6598 // Check whether the named type is a direct base class. 6599 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified(); 6600 CXXRecordDecl::base_class_iterator BaseIt, BaseE; 6601 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end(); 6602 BaseIt != BaseE; ++BaseIt) { 6603 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified(); 6604 if (CanonicalSourceType == BaseType) 6605 break; 6606 } 6607 6608 if (BaseIt == BaseE) { 6609 // Did not find SourceType in the bases. 6610 Diag(UD->getUsingLocation(), 6611 diag::err_using_decl_constructor_not_in_direct_base) 6612 << UD->getNameInfo().getSourceRange() 6613 << QualType(SourceType, 0) << TargetClass; 6614 return true; 6615 } 6616 6617 BaseIt->setInheritConstructors(); 6618 6619 return false; 6620} 6621 6622/// Checks that the given using declaration is not an invalid 6623/// redeclaration. Note that this is checking only for the using decl 6624/// itself, not for any ill-formedness among the UsingShadowDecls. 6625bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 6626 bool isTypeName, 6627 const CXXScopeSpec &SS, 6628 SourceLocation NameLoc, 6629 const LookupResult &Prev) { 6630 // C++03 [namespace.udecl]p8: 6631 // C++0x [namespace.udecl]p10: 6632 // A using-declaration is a declaration and can therefore be used 6633 // repeatedly where (and only where) multiple declarations are 6634 // allowed. 6635 // 6636 // That's in non-member contexts. 6637 if (!CurContext->getRedeclContext()->isRecord()) 6638 return false; 6639 6640 NestedNameSpecifier *Qual 6641 = static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 6642 6643 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 6644 NamedDecl *D = *I; 6645 6646 bool DTypename; 6647 NestedNameSpecifier *DQual; 6648 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 6649 DTypename = UD->isTypeName(); 6650 DQual = UD->getQualifier(); 6651 } else if (UnresolvedUsingValueDecl *UD 6652 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 6653 DTypename = false; 6654 DQual = UD->getQualifier(); 6655 } else if (UnresolvedUsingTypenameDecl *UD 6656 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 6657 DTypename = true; 6658 DQual = UD->getQualifier(); 6659 } else continue; 6660 6661 // using decls differ if one says 'typename' and the other doesn't. 6662 // FIXME: non-dependent using decls? 6663 if (isTypeName != DTypename) continue; 6664 6665 // using decls differ if they name different scopes (but note that 6666 // template instantiation can cause this check to trigger when it 6667 // didn't before instantiation). 6668 if (Context.getCanonicalNestedNameSpecifier(Qual) != 6669 Context.getCanonicalNestedNameSpecifier(DQual)) 6670 continue; 6671 6672 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 6673 Diag(D->getLocation(), diag::note_using_decl) << 1; 6674 return true; 6675 } 6676 6677 return false; 6678} 6679 6680 6681/// Checks that the given nested-name qualifier used in a using decl 6682/// in the current context is appropriately related to the current 6683/// scope. If an error is found, diagnoses it and returns true. 6684bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 6685 const CXXScopeSpec &SS, 6686 SourceLocation NameLoc) { 6687 DeclContext *NamedContext = computeDeclContext(SS); 6688 6689 if (!CurContext->isRecord()) { 6690 // C++03 [namespace.udecl]p3: 6691 // C++0x [namespace.udecl]p8: 6692 // A using-declaration for a class member shall be a member-declaration. 6693 6694 // If we weren't able to compute a valid scope, it must be a 6695 // dependent class scope. 6696 if (!NamedContext || NamedContext->isRecord()) { 6697 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 6698 << SS.getRange(); 6699 return true; 6700 } 6701 6702 // Otherwise, everything is known to be fine. 6703 return false; 6704 } 6705 6706 // The current scope is a record. 6707 6708 // If the named context is dependent, we can't decide much. 6709 if (!NamedContext) { 6710 // FIXME: in C++0x, we can diagnose if we can prove that the 6711 // nested-name-specifier does not refer to a base class, which is 6712 // still possible in some cases. 6713 6714 // Otherwise we have to conservatively report that things might be 6715 // okay. 6716 return false; 6717 } 6718 6719 if (!NamedContext->isRecord()) { 6720 // Ideally this would point at the last name in the specifier, 6721 // but we don't have that level of source info. 6722 Diag(SS.getRange().getBegin(), 6723 diag::err_using_decl_nested_name_specifier_is_not_class) 6724 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange(); 6725 return true; 6726 } 6727 6728 if (!NamedContext->isDependentContext() && 6729 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 6730 return true; 6731 6732 if (getLangOptions().CPlusPlus0x) { 6733 // C++0x [namespace.udecl]p3: 6734 // In a using-declaration used as a member-declaration, the 6735 // nested-name-specifier shall name a base class of the class 6736 // being defined. 6737 6738 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 6739 cast<CXXRecordDecl>(NamedContext))) { 6740 if (CurContext == NamedContext) { 6741 Diag(NameLoc, 6742 diag::err_using_decl_nested_name_specifier_is_current_class) 6743 << SS.getRange(); 6744 return true; 6745 } 6746 6747 Diag(SS.getRange().getBegin(), 6748 diag::err_using_decl_nested_name_specifier_is_not_base_class) 6749 << (NestedNameSpecifier*) SS.getScopeRep() 6750 << cast<CXXRecordDecl>(CurContext) 6751 << SS.getRange(); 6752 return true; 6753 } 6754 6755 return false; 6756 } 6757 6758 // C++03 [namespace.udecl]p4: 6759 // A using-declaration used as a member-declaration shall refer 6760 // to a member of a base class of the class being defined [etc.]. 6761 6762 // Salient point: SS doesn't have to name a base class as long as 6763 // lookup only finds members from base classes. Therefore we can 6764 // diagnose here only if we can prove that that can't happen, 6765 // i.e. if the class hierarchies provably don't intersect. 6766 6767 // TODO: it would be nice if "definitely valid" results were cached 6768 // in the UsingDecl and UsingShadowDecl so that these checks didn't 6769 // need to be repeated. 6770 6771 struct UserData { 6772 llvm::DenseSet<const CXXRecordDecl*> Bases; 6773 6774 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) { 6775 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 6776 Data->Bases.insert(Base); 6777 return true; 6778 } 6779 6780 bool hasDependentBases(const CXXRecordDecl *Class) { 6781 return !Class->forallBases(collect, this); 6782 } 6783 6784 /// Returns true if the base is dependent or is one of the 6785 /// accumulated base classes. 6786 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) { 6787 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 6788 return !Data->Bases.count(Base); 6789 } 6790 6791 bool mightShareBases(const CXXRecordDecl *Class) { 6792 return Bases.count(Class) || !Class->forallBases(doesNotContain, this); 6793 } 6794 }; 6795 6796 UserData Data; 6797 6798 // Returns false if we find a dependent base. 6799 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext))) 6800 return false; 6801 6802 // Returns false if the class has a dependent base or if it or one 6803 // of its bases is present in the base set of the current context. 6804 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext))) 6805 return false; 6806 6807 Diag(SS.getRange().getBegin(), 6808 diag::err_using_decl_nested_name_specifier_is_not_base_class) 6809 << (NestedNameSpecifier*) SS.getScopeRep() 6810 << cast<CXXRecordDecl>(CurContext) 6811 << SS.getRange(); 6812 6813 return true; 6814} 6815 6816Decl *Sema::ActOnAliasDeclaration(Scope *S, 6817 AccessSpecifier AS, 6818 MultiTemplateParamsArg TemplateParamLists, 6819 SourceLocation UsingLoc, 6820 UnqualifiedId &Name, 6821 TypeResult Type) { 6822 // Skip up to the relevant declaration scope. 6823 while (S->getFlags() & Scope::TemplateParamScope) 6824 S = S->getParent(); 6825 assert((S->getFlags() & Scope::DeclScope) && 6826 "got alias-declaration outside of declaration scope"); 6827 6828 if (Type.isInvalid()) 6829 return 0; 6830 6831 bool Invalid = false; 6832 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 6833 TypeSourceInfo *TInfo = 0; 6834 GetTypeFromParser(Type.get(), &TInfo); 6835 6836 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 6837 return 0; 6838 6839 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 6840 UPPC_DeclarationType)) { 6841 Invalid = true; 6842 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 6843 TInfo->getTypeLoc().getBeginLoc()); 6844 } 6845 6846 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration); 6847 LookupName(Previous, S); 6848 6849 // Warn about shadowing the name of a template parameter. 6850 if (Previous.isSingleResult() && 6851 Previous.getFoundDecl()->isTemplateParameter()) { 6852 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 6853 Previous.clear(); 6854 } 6855 6856 assert(Name.Kind == UnqualifiedId::IK_Identifier && 6857 "name in alias declaration must be an identifier"); 6858 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 6859 Name.StartLocation, 6860 Name.Identifier, TInfo); 6861 6862 NewTD->setAccess(AS); 6863 6864 if (Invalid) 6865 NewTD->setInvalidDecl(); 6866 6867 CheckTypedefForVariablyModifiedType(S, NewTD); 6868 Invalid |= NewTD->isInvalidDecl(); 6869 6870 bool Redeclaration = false; 6871 6872 NamedDecl *NewND; 6873 if (TemplateParamLists.size()) { 6874 TypeAliasTemplateDecl *OldDecl = 0; 6875 TemplateParameterList *OldTemplateParams = 0; 6876 6877 if (TemplateParamLists.size() != 1) { 6878 Diag(UsingLoc, diag::err_alias_template_extra_headers) 6879 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(), 6880 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc()); 6881 } 6882 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0]; 6883 6884 // Only consider previous declarations in the same scope. 6885 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 6886 /*ExplicitInstantiationOrSpecialization*/false); 6887 if (!Previous.empty()) { 6888 Redeclaration = true; 6889 6890 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 6891 if (!OldDecl && !Invalid) { 6892 Diag(UsingLoc, diag::err_redefinition_different_kind) 6893 << Name.Identifier; 6894 6895 NamedDecl *OldD = Previous.getRepresentativeDecl(); 6896 if (OldD->getLocation().isValid()) 6897 Diag(OldD->getLocation(), diag::note_previous_definition); 6898 6899 Invalid = true; 6900 } 6901 6902 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 6903 if (TemplateParameterListsAreEqual(TemplateParams, 6904 OldDecl->getTemplateParameters(), 6905 /*Complain=*/true, 6906 TPL_TemplateMatch)) 6907 OldTemplateParams = OldDecl->getTemplateParameters(); 6908 else 6909 Invalid = true; 6910 6911 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 6912 if (!Invalid && 6913 !Context.hasSameType(OldTD->getUnderlyingType(), 6914 NewTD->getUnderlyingType())) { 6915 // FIXME: The C++0x standard does not clearly say this is ill-formed, 6916 // but we can't reasonably accept it. 6917 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 6918 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 6919 if (OldTD->getLocation().isValid()) 6920 Diag(OldTD->getLocation(), diag::note_previous_definition); 6921 Invalid = true; 6922 } 6923 } 6924 } 6925 6926 // Merge any previous default template arguments into our parameters, 6927 // and check the parameter list. 6928 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 6929 TPC_TypeAliasTemplate)) 6930 return 0; 6931 6932 TypeAliasTemplateDecl *NewDecl = 6933 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 6934 Name.Identifier, TemplateParams, 6935 NewTD); 6936 6937 NewDecl->setAccess(AS); 6938 6939 if (Invalid) 6940 NewDecl->setInvalidDecl(); 6941 else if (OldDecl) 6942 NewDecl->setPreviousDeclaration(OldDecl); 6943 6944 NewND = NewDecl; 6945 } else { 6946 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 6947 NewND = NewTD; 6948 } 6949 6950 if (!Redeclaration) 6951 PushOnScopeChains(NewND, S); 6952 6953 return NewND; 6954} 6955 6956Decl *Sema::ActOnNamespaceAliasDef(Scope *S, 6957 SourceLocation NamespaceLoc, 6958 SourceLocation AliasLoc, 6959 IdentifierInfo *Alias, 6960 CXXScopeSpec &SS, 6961 SourceLocation IdentLoc, 6962 IdentifierInfo *Ident) { 6963 6964 // Lookup the namespace name. 6965 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 6966 LookupParsedName(R, S, &SS); 6967 6968 // Check if we have a previous declaration with the same name. 6969 NamedDecl *PrevDecl 6970 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName, 6971 ForRedeclaration); 6972 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S)) 6973 PrevDecl = 0; 6974 6975 if (PrevDecl) { 6976 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 6977 // We already have an alias with the same name that points to the same 6978 // namespace, so don't create a new one. 6979 // FIXME: At some point, we'll want to create the (redundant) 6980 // declaration to maintain better source information. 6981 if (!R.isAmbiguous() && !R.empty() && 6982 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl()))) 6983 return 0; 6984 } 6985 6986 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition : 6987 diag::err_redefinition_different_kind; 6988 Diag(AliasLoc, DiagID) << Alias; 6989 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 6990 return 0; 6991 } 6992 6993 if (R.isAmbiguous()) 6994 return 0; 6995 6996 if (R.empty()) { 6997 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 6998 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange(); 6999 return 0; 7000 } 7001 } 7002 7003 NamespaceAliasDecl *AliasDecl = 7004 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 7005 Alias, SS.getWithLocInContext(Context), 7006 IdentLoc, R.getFoundDecl()); 7007 7008 PushOnScopeChains(AliasDecl, S); 7009 return AliasDecl; 7010} 7011 7012namespace { 7013 /// \brief Scoped object used to handle the state changes required in Sema 7014 /// to implicitly define the body of a C++ member function; 7015 class ImplicitlyDefinedFunctionScope { 7016 Sema &S; 7017 Sema::ContextRAII SavedContext; 7018 7019 public: 7020 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method) 7021 : S(S), SavedContext(S, Method) 7022 { 7023 S.PushFunctionScope(); 7024 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated); 7025 } 7026 7027 ~ImplicitlyDefinedFunctionScope() { 7028 S.PopExpressionEvaluationContext(); 7029 S.PopFunctionScopeInfo(); 7030 } 7031 }; 7032} 7033 7034Sema::ImplicitExceptionSpecification 7035Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) { 7036 // C++ [except.spec]p14: 7037 // An implicitly declared special member function (Clause 12) shall have an 7038 // exception-specification. [...] 7039 ImplicitExceptionSpecification ExceptSpec(Context); 7040 if (ClassDecl->isInvalidDecl()) 7041 return ExceptSpec; 7042 7043 // Direct base-class constructors. 7044 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 7045 BEnd = ClassDecl->bases_end(); 7046 B != BEnd; ++B) { 7047 if (B->isVirtual()) // Handled below. 7048 continue; 7049 7050 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 7051 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7052 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 7053 // If this is a deleted function, add it anyway. This might be conformant 7054 // with the standard. This might not. I'm not sure. It might not matter. 7055 if (Constructor) 7056 ExceptSpec.CalledDecl(Constructor); 7057 } 7058 } 7059 7060 // Virtual base-class constructors. 7061 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 7062 BEnd = ClassDecl->vbases_end(); 7063 B != BEnd; ++B) { 7064 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 7065 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7066 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 7067 // If this is a deleted function, add it anyway. This might be conformant 7068 // with the standard. This might not. I'm not sure. It might not matter. 7069 if (Constructor) 7070 ExceptSpec.CalledDecl(Constructor); 7071 } 7072 } 7073 7074 // Field constructors. 7075 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 7076 FEnd = ClassDecl->field_end(); 7077 F != FEnd; ++F) { 7078 if (F->hasInClassInitializer()) { 7079 if (Expr *E = F->getInClassInitializer()) 7080 ExceptSpec.CalledExpr(E); 7081 else if (!F->isInvalidDecl()) 7082 ExceptSpec.SetDelayed(); 7083 } else if (const RecordType *RecordTy 7084 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 7085 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 7086 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 7087 // If this is a deleted function, add it anyway. This might be conformant 7088 // with the standard. This might not. I'm not sure. It might not matter. 7089 // In particular, the problem is that this function never gets called. It 7090 // might just be ill-formed because this function attempts to refer to 7091 // a deleted function here. 7092 if (Constructor) 7093 ExceptSpec.CalledDecl(Constructor); 7094 } 7095 } 7096 7097 return ExceptSpec; 7098} 7099 7100CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 7101 CXXRecordDecl *ClassDecl) { 7102 // C++ [class.ctor]p5: 7103 // A default constructor for a class X is a constructor of class X 7104 // that can be called without an argument. If there is no 7105 // user-declared constructor for class X, a default constructor is 7106 // implicitly declared. An implicitly-declared default constructor 7107 // is an inline public member of its class. 7108 assert(!ClassDecl->hasUserDeclaredConstructor() && 7109 "Should not build implicit default constructor!"); 7110 7111 ImplicitExceptionSpecification Spec = 7112 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl); 7113 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 7114 7115 // Create the actual constructor declaration. 7116 CanQualType ClassType 7117 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 7118 SourceLocation ClassLoc = ClassDecl->getLocation(); 7119 DeclarationName Name 7120 = Context.DeclarationNames.getCXXConstructorName(ClassType); 7121 DeclarationNameInfo NameInfo(Name, ClassLoc); 7122 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 7123 Context, ClassDecl, ClassLoc, NameInfo, 7124 Context.getFunctionType(Context.VoidTy, 0, 0, EPI), /*TInfo=*/0, 7125 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 7126 /*isConstexpr=*/ClassDecl->defaultedDefaultConstructorIsConstexpr() && 7127 getLangOptions().CPlusPlus0x); 7128 DefaultCon->setAccess(AS_public); 7129 DefaultCon->setDefaulted(); 7130 DefaultCon->setImplicit(); 7131 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 7132 7133 // Note that we have declared this constructor. 7134 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 7135 7136 if (Scope *S = getScopeForContext(ClassDecl)) 7137 PushOnScopeChains(DefaultCon, S, false); 7138 ClassDecl->addDecl(DefaultCon); 7139 7140 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 7141 DefaultCon->setDeletedAsWritten(); 7142 7143 return DefaultCon; 7144} 7145 7146void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 7147 CXXConstructorDecl *Constructor) { 7148 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 7149 !Constructor->doesThisDeclarationHaveABody() && 7150 !Constructor->isDeleted()) && 7151 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 7152 7153 CXXRecordDecl *ClassDecl = Constructor->getParent(); 7154 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 7155 7156 ImplicitlyDefinedFunctionScope Scope(*this, Constructor); 7157 DiagnosticErrorTrap Trap(Diags); 7158 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) || 7159 Trap.hasErrorOccurred()) { 7160 Diag(CurrentLocation, diag::note_member_synthesized_at) 7161 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl); 7162 Constructor->setInvalidDecl(); 7163 return; 7164 } 7165 7166 SourceLocation Loc = Constructor->getLocation(); 7167 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc)); 7168 7169 Constructor->setUsed(); 7170 MarkVTableUsed(CurrentLocation, ClassDecl); 7171 7172 if (ASTMutationListener *L = getASTMutationListener()) { 7173 L->CompletedImplicitDefinition(Constructor); 7174 } 7175} 7176 7177/// Get any existing defaulted default constructor for the given class. Do not 7178/// implicitly define one if it does not exist. 7179static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self, 7180 CXXRecordDecl *D) { 7181 ASTContext &Context = Self.Context; 7182 QualType ClassType = Context.getTypeDeclType(D); 7183 DeclarationName ConstructorName 7184 = Context.DeclarationNames.getCXXConstructorName( 7185 Context.getCanonicalType(ClassType.getUnqualifiedType())); 7186 7187 DeclContext::lookup_const_iterator Con, ConEnd; 7188 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName); 7189 Con != ConEnd; ++Con) { 7190 // A function template cannot be defaulted. 7191 if (isa<FunctionTemplateDecl>(*Con)) 7192 continue; 7193 7194 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con); 7195 if (Constructor->isDefaultConstructor()) 7196 return Constructor->isDefaulted() ? Constructor : 0; 7197 } 7198 return 0; 7199} 7200 7201void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 7202 if (!D) return; 7203 AdjustDeclIfTemplate(D); 7204 7205 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D); 7206 CXXConstructorDecl *CtorDecl 7207 = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl); 7208 7209 if (!CtorDecl) return; 7210 7211 // Compute the exception specification for the default constructor. 7212 const FunctionProtoType *CtorTy = 7213 CtorDecl->getType()->castAs<FunctionProtoType>(); 7214 if (CtorTy->getExceptionSpecType() == EST_Delayed) { 7215 ImplicitExceptionSpecification Spec = 7216 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl); 7217 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 7218 assert(EPI.ExceptionSpecType != EST_Delayed); 7219 7220 CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI)); 7221 } 7222 7223 // If the default constructor is explicitly defaulted, checking the exception 7224 // specification is deferred until now. 7225 if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() && 7226 !ClassDecl->isDependentType()) 7227 CheckExplicitlyDefaultedDefaultConstructor(CtorDecl); 7228} 7229 7230void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) { 7231 // We start with an initial pass over the base classes to collect those that 7232 // inherit constructors from. If there are none, we can forgo all further 7233 // processing. 7234 typedef SmallVector<const RecordType *, 4> BasesVector; 7235 BasesVector BasesToInheritFrom; 7236 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(), 7237 BaseE = ClassDecl->bases_end(); 7238 BaseIt != BaseE; ++BaseIt) { 7239 if (BaseIt->getInheritConstructors()) { 7240 QualType Base = BaseIt->getType(); 7241 if (Base->isDependentType()) { 7242 // If we inherit constructors from anything that is dependent, just 7243 // abort processing altogether. We'll get another chance for the 7244 // instantiations. 7245 return; 7246 } 7247 BasesToInheritFrom.push_back(Base->castAs<RecordType>()); 7248 } 7249 } 7250 if (BasesToInheritFrom.empty()) 7251 return; 7252 7253 // Now collect the constructors that we already have in the current class. 7254 // Those take precedence over inherited constructors. 7255 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...] 7256 // unless there is a user-declared constructor with the same signature in 7257 // the class where the using-declaration appears. 7258 llvm::SmallSet<const Type *, 8> ExistingConstructors; 7259 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(), 7260 CtorE = ClassDecl->ctor_end(); 7261 CtorIt != CtorE; ++CtorIt) { 7262 ExistingConstructors.insert( 7263 Context.getCanonicalType(CtorIt->getType()).getTypePtr()); 7264 } 7265 7266 Scope *S = getScopeForContext(ClassDecl); 7267 DeclarationName CreatedCtorName = 7268 Context.DeclarationNames.getCXXConstructorName( 7269 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified()); 7270 7271 // Now comes the true work. 7272 // First, we keep a map from constructor types to the base that introduced 7273 // them. Needed for finding conflicting constructors. We also keep the 7274 // actually inserted declarations in there, for pretty diagnostics. 7275 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo; 7276 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap; 7277 ConstructorToSourceMap InheritedConstructors; 7278 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(), 7279 BaseE = BasesToInheritFrom.end(); 7280 BaseIt != BaseE; ++BaseIt) { 7281 const RecordType *Base = *BaseIt; 7282 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified(); 7283 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl()); 7284 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(), 7285 CtorE = BaseDecl->ctor_end(); 7286 CtorIt != CtorE; ++CtorIt) { 7287 // Find the using declaration for inheriting this base's constructors. 7288 DeclarationName Name = 7289 Context.DeclarationNames.getCXXConstructorName(CanonicalBase); 7290 UsingDecl *UD = dyn_cast_or_null<UsingDecl>( 7291 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName)); 7292 SourceLocation UsingLoc = UD ? UD->getLocation() : 7293 ClassDecl->getLocation(); 7294 7295 // C++0x [class.inhctor]p1: The candidate set of inherited constructors 7296 // from the class X named in the using-declaration consists of actual 7297 // constructors and notional constructors that result from the 7298 // transformation of defaulted parameters as follows: 7299 // - all non-template default constructors of X, and 7300 // - for each non-template constructor of X that has at least one 7301 // parameter with a default argument, the set of constructors that 7302 // results from omitting any ellipsis parameter specification and 7303 // successively omitting parameters with a default argument from the 7304 // end of the parameter-type-list. 7305 CXXConstructorDecl *BaseCtor = *CtorIt; 7306 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor(); 7307 const FunctionProtoType *BaseCtorType = 7308 BaseCtor->getType()->getAs<FunctionProtoType>(); 7309 7310 for (unsigned params = BaseCtor->getMinRequiredArguments(), 7311 maxParams = BaseCtor->getNumParams(); 7312 params <= maxParams; ++params) { 7313 // Skip default constructors. They're never inherited. 7314 if (params == 0) 7315 continue; 7316 // Skip copy and move constructors for the same reason. 7317 if (CanBeCopyOrMove && params == 1) 7318 continue; 7319 7320 // Build up a function type for this particular constructor. 7321 // FIXME: The working paper does not consider that the exception spec 7322 // for the inheriting constructor might be larger than that of the 7323 // source. This code doesn't yet, either. When it does, this code will 7324 // need to be delayed until after exception specifications and in-class 7325 // member initializers are attached. 7326 const Type *NewCtorType; 7327 if (params == maxParams) 7328 NewCtorType = BaseCtorType; 7329 else { 7330 SmallVector<QualType, 16> Args; 7331 for (unsigned i = 0; i < params; ++i) { 7332 Args.push_back(BaseCtorType->getArgType(i)); 7333 } 7334 FunctionProtoType::ExtProtoInfo ExtInfo = 7335 BaseCtorType->getExtProtoInfo(); 7336 ExtInfo.Variadic = false; 7337 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(), 7338 Args.data(), params, ExtInfo) 7339 .getTypePtr(); 7340 } 7341 const Type *CanonicalNewCtorType = 7342 Context.getCanonicalType(NewCtorType); 7343 7344 // Now that we have the type, first check if the class already has a 7345 // constructor with this signature. 7346 if (ExistingConstructors.count(CanonicalNewCtorType)) 7347 continue; 7348 7349 // Then we check if we have already declared an inherited constructor 7350 // with this signature. 7351 std::pair<ConstructorToSourceMap::iterator, bool> result = 7352 InheritedConstructors.insert(std::make_pair( 7353 CanonicalNewCtorType, 7354 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0))); 7355 if (!result.second) { 7356 // Already in the map. If it came from a different class, that's an 7357 // error. Not if it's from the same. 7358 CanQualType PreviousBase = result.first->second.first; 7359 if (CanonicalBase != PreviousBase) { 7360 const CXXConstructorDecl *PrevCtor = result.first->second.second; 7361 const CXXConstructorDecl *PrevBaseCtor = 7362 PrevCtor->getInheritedConstructor(); 7363 assert(PrevBaseCtor && "Conflicting constructor was not inherited"); 7364 7365 Diag(UsingLoc, diag::err_using_decl_constructor_conflict); 7366 Diag(BaseCtor->getLocation(), 7367 diag::note_using_decl_constructor_conflict_current_ctor); 7368 Diag(PrevBaseCtor->getLocation(), 7369 diag::note_using_decl_constructor_conflict_previous_ctor); 7370 Diag(PrevCtor->getLocation(), 7371 diag::note_using_decl_constructor_conflict_previous_using); 7372 } 7373 continue; 7374 } 7375 7376 // OK, we're there, now add the constructor. 7377 // C++0x [class.inhctor]p8: [...] that would be performed by a 7378 // user-written inline constructor [...] 7379 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc); 7380 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create( 7381 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0), 7382 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true, 7383 /*ImplicitlyDeclared=*/true, 7384 // FIXME: Due to a defect in the standard, we treat inherited 7385 // constructors as constexpr even if that makes them ill-formed. 7386 /*Constexpr=*/BaseCtor->isConstexpr()); 7387 NewCtor->setAccess(BaseCtor->getAccess()); 7388 7389 // Build up the parameter decls and add them. 7390 SmallVector<ParmVarDecl *, 16> ParamDecls; 7391 for (unsigned i = 0; i < params; ++i) { 7392 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor, 7393 UsingLoc, UsingLoc, 7394 /*IdentifierInfo=*/0, 7395 BaseCtorType->getArgType(i), 7396 /*TInfo=*/0, SC_None, 7397 SC_None, /*DefaultArg=*/0)); 7398 } 7399 NewCtor->setParams(ParamDecls); 7400 NewCtor->setInheritedConstructor(BaseCtor); 7401 7402 PushOnScopeChains(NewCtor, S, false); 7403 ClassDecl->addDecl(NewCtor); 7404 result.first->second.second = NewCtor; 7405 } 7406 } 7407 } 7408} 7409 7410Sema::ImplicitExceptionSpecification 7411Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) { 7412 // C++ [except.spec]p14: 7413 // An implicitly declared special member function (Clause 12) shall have 7414 // an exception-specification. 7415 ImplicitExceptionSpecification ExceptSpec(Context); 7416 if (ClassDecl->isInvalidDecl()) 7417 return ExceptSpec; 7418 7419 // Direct base-class destructors. 7420 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 7421 BEnd = ClassDecl->bases_end(); 7422 B != BEnd; ++B) { 7423 if (B->isVirtual()) // Handled below. 7424 continue; 7425 7426 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) 7427 ExceptSpec.CalledDecl( 7428 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 7429 } 7430 7431 // Virtual base-class destructors. 7432 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 7433 BEnd = ClassDecl->vbases_end(); 7434 B != BEnd; ++B) { 7435 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) 7436 ExceptSpec.CalledDecl( 7437 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 7438 } 7439 7440 // Field destructors. 7441 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 7442 FEnd = ClassDecl->field_end(); 7443 F != FEnd; ++F) { 7444 if (const RecordType *RecordTy 7445 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) 7446 ExceptSpec.CalledDecl( 7447 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl()))); 7448 } 7449 7450 return ExceptSpec; 7451} 7452 7453CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 7454 // C++ [class.dtor]p2: 7455 // If a class has no user-declared destructor, a destructor is 7456 // declared implicitly. An implicitly-declared destructor is an 7457 // inline public member of its class. 7458 7459 ImplicitExceptionSpecification Spec = 7460 ComputeDefaultedDtorExceptionSpec(ClassDecl); 7461 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 7462 7463 // Create the actual destructor declaration. 7464 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI); 7465 7466 CanQualType ClassType 7467 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 7468 SourceLocation ClassLoc = ClassDecl->getLocation(); 7469 DeclarationName Name 7470 = Context.DeclarationNames.getCXXDestructorName(ClassType); 7471 DeclarationNameInfo NameInfo(Name, ClassLoc); 7472 CXXDestructorDecl *Destructor 7473 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0, 7474 /*isInline=*/true, 7475 /*isImplicitlyDeclared=*/true); 7476 Destructor->setAccess(AS_public); 7477 Destructor->setDefaulted(); 7478 Destructor->setImplicit(); 7479 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 7480 7481 // Note that we have declared this destructor. 7482 ++ASTContext::NumImplicitDestructorsDeclared; 7483 7484 // Introduce this destructor into its scope. 7485 if (Scope *S = getScopeForContext(ClassDecl)) 7486 PushOnScopeChains(Destructor, S, false); 7487 ClassDecl->addDecl(Destructor); 7488 7489 // This could be uniqued if it ever proves significant. 7490 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty)); 7491 7492 if (ShouldDeleteDestructor(Destructor)) 7493 Destructor->setDeletedAsWritten(); 7494 7495 AddOverriddenMethods(ClassDecl, Destructor); 7496 7497 return Destructor; 7498} 7499 7500void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 7501 CXXDestructorDecl *Destructor) { 7502 assert((Destructor->isDefaulted() && 7503 !Destructor->doesThisDeclarationHaveABody()) && 7504 "DefineImplicitDestructor - call it for implicit default dtor"); 7505 CXXRecordDecl *ClassDecl = Destructor->getParent(); 7506 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 7507 7508 if (Destructor->isInvalidDecl()) 7509 return; 7510 7511 ImplicitlyDefinedFunctionScope Scope(*this, Destructor); 7512 7513 DiagnosticErrorTrap Trap(Diags); 7514 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 7515 Destructor->getParent()); 7516 7517 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) { 7518 Diag(CurrentLocation, diag::note_member_synthesized_at) 7519 << CXXDestructor << Context.getTagDeclType(ClassDecl); 7520 7521 Destructor->setInvalidDecl(); 7522 return; 7523 } 7524 7525 SourceLocation Loc = Destructor->getLocation(); 7526 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc)); 7527 Destructor->setImplicitlyDefined(true); 7528 Destructor->setUsed(); 7529 MarkVTableUsed(CurrentLocation, ClassDecl); 7530 7531 if (ASTMutationListener *L = getASTMutationListener()) { 7532 L->CompletedImplicitDefinition(Destructor); 7533 } 7534} 7535 7536void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl, 7537 CXXDestructorDecl *destructor) { 7538 // C++11 [class.dtor]p3: 7539 // A declaration of a destructor that does not have an exception- 7540 // specification is implicitly considered to have the same exception- 7541 // specification as an implicit declaration. 7542 const FunctionProtoType *dtorType = destructor->getType()-> 7543 getAs<FunctionProtoType>(); 7544 if (dtorType->hasExceptionSpec()) 7545 return; 7546 7547 ImplicitExceptionSpecification exceptSpec = 7548 ComputeDefaultedDtorExceptionSpec(classDecl); 7549 7550 // Replace the destructor's type, building off the existing one. Fortunately, 7551 // the only thing of interest in the destructor type is its extended info. 7552 // The return and arguments are fixed. 7553 FunctionProtoType::ExtProtoInfo epi = dtorType->getExtProtoInfo(); 7554 epi.ExceptionSpecType = exceptSpec.getExceptionSpecType(); 7555 epi.NumExceptions = exceptSpec.size(); 7556 epi.Exceptions = exceptSpec.data(); 7557 QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi); 7558 7559 destructor->setType(ty); 7560 7561 // FIXME: If the destructor has a body that could throw, and the newly created 7562 // spec doesn't allow exceptions, we should emit a warning, because this 7563 // change in behavior can break conforming C++03 programs at runtime. 7564 // However, we don't have a body yet, so it needs to be done somewhere else. 7565} 7566 7567/// \brief Builds a statement that copies/moves the given entity from \p From to 7568/// \c To. 7569/// 7570/// This routine is used to copy/move the members of a class with an 7571/// implicitly-declared copy/move assignment operator. When the entities being 7572/// copied are arrays, this routine builds for loops to copy them. 7573/// 7574/// \param S The Sema object used for type-checking. 7575/// 7576/// \param Loc The location where the implicit copy/move is being generated. 7577/// 7578/// \param T The type of the expressions being copied/moved. Both expressions 7579/// must have this type. 7580/// 7581/// \param To The expression we are copying/moving to. 7582/// 7583/// \param From The expression we are copying/moving from. 7584/// 7585/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 7586/// Otherwise, it's a non-static member subobject. 7587/// 7588/// \param Copying Whether we're copying or moving. 7589/// 7590/// \param Depth Internal parameter recording the depth of the recursion. 7591/// 7592/// \returns A statement or a loop that copies the expressions. 7593static StmtResult 7594BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 7595 Expr *To, Expr *From, 7596 bool CopyingBaseSubobject, bool Copying, 7597 unsigned Depth = 0) { 7598 // C++0x [class.copy]p28: 7599 // Each subobject is assigned in the manner appropriate to its type: 7600 // 7601 // - if the subobject is of class type, as if by a call to operator= with 7602 // the subobject as the object expression and the corresponding 7603 // subobject of x as a single function argument (as if by explicit 7604 // qualification; that is, ignoring any possible virtual overriding 7605 // functions in more derived classes); 7606 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 7607 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 7608 7609 // Look for operator=. 7610 DeclarationName Name 7611 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 7612 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 7613 S.LookupQualifiedName(OpLookup, ClassDecl, false); 7614 7615 // Filter out any result that isn't a copy/move-assignment operator. 7616 LookupResult::Filter F = OpLookup.makeFilter(); 7617 while (F.hasNext()) { 7618 NamedDecl *D = F.next(); 7619 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 7620 if (Copying ? Method->isCopyAssignmentOperator() : 7621 Method->isMoveAssignmentOperator()) 7622 continue; 7623 7624 F.erase(); 7625 } 7626 F.done(); 7627 7628 // Suppress the protected check (C++ [class.protected]) for each of the 7629 // assignment operators we found. This strange dance is required when 7630 // we're assigning via a base classes's copy-assignment operator. To 7631 // ensure that we're getting the right base class subobject (without 7632 // ambiguities), we need to cast "this" to that subobject type; to 7633 // ensure that we don't go through the virtual call mechanism, we need 7634 // to qualify the operator= name with the base class (see below). However, 7635 // this means that if the base class has a protected copy assignment 7636 // operator, the protected member access check will fail. So, we 7637 // rewrite "protected" access to "public" access in this case, since we 7638 // know by construction that we're calling from a derived class. 7639 if (CopyingBaseSubobject) { 7640 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 7641 L != LEnd; ++L) { 7642 if (L.getAccess() == AS_protected) 7643 L.setAccess(AS_public); 7644 } 7645 } 7646 7647 // Create the nested-name-specifier that will be used to qualify the 7648 // reference to operator=; this is required to suppress the virtual 7649 // call mechanism. 7650 CXXScopeSpec SS; 7651 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 7652 SS.MakeTrivial(S.Context, 7653 NestedNameSpecifier::Create(S.Context, 0, false, 7654 CanonicalT), 7655 Loc); 7656 7657 // Create the reference to operator=. 7658 ExprResult OpEqualRef 7659 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS, 7660 /*TemplateKWLoc=*/SourceLocation(), 7661 /*FirstQualifierInScope=*/0, 7662 OpLookup, 7663 /*TemplateArgs=*/0, 7664 /*SuppressQualifierCheck=*/true); 7665 if (OpEqualRef.isInvalid()) 7666 return StmtError(); 7667 7668 // Build the call to the assignment operator. 7669 7670 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0, 7671 OpEqualRef.takeAs<Expr>(), 7672 Loc, &From, 1, Loc); 7673 if (Call.isInvalid()) 7674 return StmtError(); 7675 7676 return S.Owned(Call.takeAs<Stmt>()); 7677 } 7678 7679 // - if the subobject is of scalar type, the built-in assignment 7680 // operator is used. 7681 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 7682 if (!ArrayTy) { 7683 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From); 7684 if (Assignment.isInvalid()) 7685 return StmtError(); 7686 7687 return S.Owned(Assignment.takeAs<Stmt>()); 7688 } 7689 7690 // - if the subobject is an array, each element is assigned, in the 7691 // manner appropriate to the element type; 7692 7693 // Construct a loop over the array bounds, e.g., 7694 // 7695 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 7696 // 7697 // that will copy each of the array elements. 7698 QualType SizeType = S.Context.getSizeType(); 7699 7700 // Create the iteration variable. 7701 IdentifierInfo *IterationVarName = 0; 7702 { 7703 SmallString<8> Str; 7704 llvm::raw_svector_ostream OS(Str); 7705 OS << "__i" << Depth; 7706 IterationVarName = &S.Context.Idents.get(OS.str()); 7707 } 7708 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 7709 IterationVarName, SizeType, 7710 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 7711 SC_None, SC_None); 7712 7713 // Initialize the iteration variable to zero. 7714 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 7715 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 7716 7717 // Create a reference to the iteration variable; we'll use this several 7718 // times throughout. 7719 Expr *IterationVarRef 7720 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take(); 7721 assert(IterationVarRef && "Reference to invented variable cannot fail!"); 7722 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take(); 7723 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!"); 7724 7725 // Create the DeclStmt that holds the iteration variable. 7726 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 7727 7728 // Create the comparison against the array bound. 7729 llvm::APInt Upper 7730 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 7731 Expr *Comparison 7732 = new (S.Context) BinaryOperator(IterationVarRefRVal, 7733 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 7734 BO_NE, S.Context.BoolTy, 7735 VK_RValue, OK_Ordinary, Loc); 7736 7737 // Create the pre-increment of the iteration variable. 7738 Expr *Increment 7739 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType, 7740 VK_LValue, OK_Ordinary, Loc); 7741 7742 // Subscript the "from" and "to" expressions with the iteration variable. 7743 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc, 7744 IterationVarRefRVal, 7745 Loc)); 7746 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc, 7747 IterationVarRefRVal, 7748 Loc)); 7749 if (!Copying) // Cast to rvalue 7750 From = CastForMoving(S, From); 7751 7752 // Build the copy/move for an individual element of the array. 7753 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(), 7754 To, From, CopyingBaseSubobject, 7755 Copying, Depth + 1); 7756 if (Copy.isInvalid()) 7757 return StmtError(); 7758 7759 // Construct the loop that copies all elements of this array. 7760 return S.ActOnForStmt(Loc, Loc, InitStmt, 7761 S.MakeFullExpr(Comparison), 7762 0, S.MakeFullExpr(Increment), 7763 Loc, Copy.take()); 7764} 7765 7766std::pair<Sema::ImplicitExceptionSpecification, bool> 7767Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst( 7768 CXXRecordDecl *ClassDecl) { 7769 if (ClassDecl->isInvalidDecl()) 7770 return std::make_pair(ImplicitExceptionSpecification(Context), false); 7771 7772 // C++ [class.copy]p10: 7773 // If the class definition does not explicitly declare a copy 7774 // assignment operator, one is declared implicitly. 7775 // The implicitly-defined copy assignment operator for a class X 7776 // will have the form 7777 // 7778 // X& X::operator=(const X&) 7779 // 7780 // if 7781 bool HasConstCopyAssignment = true; 7782 7783 // -- each direct base class B of X has a copy assignment operator 7784 // whose parameter is of type const B&, const volatile B& or B, 7785 // and 7786 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 7787 BaseEnd = ClassDecl->bases_end(); 7788 HasConstCopyAssignment && Base != BaseEnd; ++Base) { 7789 // We'll handle this below 7790 if (LangOpts.CPlusPlus0x && Base->isVirtual()) 7791 continue; 7792 7793 assert(!Base->getType()->isDependentType() && 7794 "Cannot generate implicit members for class with dependent bases."); 7795 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl(); 7796 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0, 7797 &HasConstCopyAssignment); 7798 } 7799 7800 // In C++11, the above citation has "or virtual" added 7801 if (LangOpts.CPlusPlus0x) { 7802 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 7803 BaseEnd = ClassDecl->vbases_end(); 7804 HasConstCopyAssignment && Base != BaseEnd; ++Base) { 7805 assert(!Base->getType()->isDependentType() && 7806 "Cannot generate implicit members for class with dependent bases."); 7807 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl(); 7808 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0, 7809 &HasConstCopyAssignment); 7810 } 7811 } 7812 7813 // -- for all the nonstatic data members of X that are of a class 7814 // type M (or array thereof), each such class type has a copy 7815 // assignment operator whose parameter is of type const M&, 7816 // const volatile M& or M. 7817 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 7818 FieldEnd = ClassDecl->field_end(); 7819 HasConstCopyAssignment && Field != FieldEnd; 7820 ++Field) { 7821 QualType FieldType = Context.getBaseElementType((*Field)->getType()); 7822 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 7823 LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const, false, 0, 7824 &HasConstCopyAssignment); 7825 } 7826 } 7827 7828 // Otherwise, the implicitly declared copy assignment operator will 7829 // have the form 7830 // 7831 // X& X::operator=(X&) 7832 7833 // C++ [except.spec]p14: 7834 // An implicitly declared special member function (Clause 12) shall have an 7835 // exception-specification. [...] 7836 7837 // It is unspecified whether or not an implicit copy assignment operator 7838 // attempts to deduplicate calls to assignment operators of virtual bases are 7839 // made. As such, this exception specification is effectively unspecified. 7840 // Based on a similar decision made for constness in C++0x, we're erring on 7841 // the side of assuming such calls to be made regardless of whether they 7842 // actually happen. 7843 ImplicitExceptionSpecification ExceptSpec(Context); 7844 unsigned ArgQuals = HasConstCopyAssignment ? Qualifiers::Const : 0; 7845 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 7846 BaseEnd = ClassDecl->bases_end(); 7847 Base != BaseEnd; ++Base) { 7848 if (Base->isVirtual()) 7849 continue; 7850 7851 CXXRecordDecl *BaseClassDecl 7852 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 7853 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 7854 ArgQuals, false, 0)) 7855 ExceptSpec.CalledDecl(CopyAssign); 7856 } 7857 7858 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 7859 BaseEnd = ClassDecl->vbases_end(); 7860 Base != BaseEnd; ++Base) { 7861 CXXRecordDecl *BaseClassDecl 7862 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 7863 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 7864 ArgQuals, false, 0)) 7865 ExceptSpec.CalledDecl(CopyAssign); 7866 } 7867 7868 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 7869 FieldEnd = ClassDecl->field_end(); 7870 Field != FieldEnd; 7871 ++Field) { 7872 QualType FieldType = Context.getBaseElementType((*Field)->getType()); 7873 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 7874 if (CXXMethodDecl *CopyAssign = 7875 LookupCopyingAssignment(FieldClassDecl, ArgQuals, false, 0)) 7876 ExceptSpec.CalledDecl(CopyAssign); 7877 } 7878 } 7879 7880 return std::make_pair(ExceptSpec, HasConstCopyAssignment); 7881} 7882 7883CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 7884 // Note: The following rules are largely analoguous to the copy 7885 // constructor rules. Note that virtual bases are not taken into account 7886 // for determining the argument type of the operator. Note also that 7887 // operators taking an object instead of a reference are allowed. 7888 7889 ImplicitExceptionSpecification Spec(Context); 7890 bool Const; 7891 llvm::tie(Spec, Const) = 7892 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl); 7893 7894 QualType ArgType = Context.getTypeDeclType(ClassDecl); 7895 QualType RetType = Context.getLValueReferenceType(ArgType); 7896 if (Const) 7897 ArgType = ArgType.withConst(); 7898 ArgType = Context.getLValueReferenceType(ArgType); 7899 7900 // An implicitly-declared copy assignment operator is an inline public 7901 // member of its class. 7902 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 7903 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 7904 SourceLocation ClassLoc = ClassDecl->getLocation(); 7905 DeclarationNameInfo NameInfo(Name, ClassLoc); 7906 CXXMethodDecl *CopyAssignment 7907 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 7908 Context.getFunctionType(RetType, &ArgType, 1, EPI), 7909 /*TInfo=*/0, /*isStatic=*/false, 7910 /*StorageClassAsWritten=*/SC_None, 7911 /*isInline=*/true, /*isConstexpr=*/false, 7912 SourceLocation()); 7913 CopyAssignment->setAccess(AS_public); 7914 CopyAssignment->setDefaulted(); 7915 CopyAssignment->setImplicit(); 7916 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment()); 7917 7918 // Add the parameter to the operator. 7919 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 7920 ClassLoc, ClassLoc, /*Id=*/0, 7921 ArgType, /*TInfo=*/0, 7922 SC_None, 7923 SC_None, 0); 7924 CopyAssignment->setParams(FromParam); 7925 7926 // Note that we have added this copy-assignment operator. 7927 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 7928 7929 if (Scope *S = getScopeForContext(ClassDecl)) 7930 PushOnScopeChains(CopyAssignment, S, false); 7931 ClassDecl->addDecl(CopyAssignment); 7932 7933 // C++0x [class.copy]p19: 7934 // .... If the class definition does not explicitly declare a copy 7935 // assignment operator, there is no user-declared move constructor, and 7936 // there is no user-declared move assignment operator, a copy assignment 7937 // operator is implicitly declared as defaulted. 7938 if ((ClassDecl->hasUserDeclaredMoveConstructor() && 7939 !getLangOptions().MicrosoftMode) || 7940 ClassDecl->hasUserDeclaredMoveAssignment() || 7941 ShouldDeleteCopyAssignmentOperator(CopyAssignment)) 7942 CopyAssignment->setDeletedAsWritten(); 7943 7944 AddOverriddenMethods(ClassDecl, CopyAssignment); 7945 return CopyAssignment; 7946} 7947 7948void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 7949 CXXMethodDecl *CopyAssignOperator) { 7950 assert((CopyAssignOperator->isDefaulted() && 7951 CopyAssignOperator->isOverloadedOperator() && 7952 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 7953 !CopyAssignOperator->doesThisDeclarationHaveABody()) && 7954 "DefineImplicitCopyAssignment called for wrong function"); 7955 7956 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 7957 7958 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) { 7959 CopyAssignOperator->setInvalidDecl(); 7960 return; 7961 } 7962 7963 CopyAssignOperator->setUsed(); 7964 7965 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator); 7966 DiagnosticErrorTrap Trap(Diags); 7967 7968 // C++0x [class.copy]p30: 7969 // The implicitly-defined or explicitly-defaulted copy assignment operator 7970 // for a non-union class X performs memberwise copy assignment of its 7971 // subobjects. The direct base classes of X are assigned first, in the 7972 // order of their declaration in the base-specifier-list, and then the 7973 // immediate non-static data members of X are assigned, in the order in 7974 // which they were declared in the class definition. 7975 7976 // The statements that form the synthesized function body. 7977 ASTOwningVector<Stmt*> Statements(*this); 7978 7979 // The parameter for the "other" object, which we are copying from. 7980 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 7981 Qualifiers OtherQuals = Other->getType().getQualifiers(); 7982 QualType OtherRefType = Other->getType(); 7983 if (const LValueReferenceType *OtherRef 7984 = OtherRefType->getAs<LValueReferenceType>()) { 7985 OtherRefType = OtherRef->getPointeeType(); 7986 OtherQuals = OtherRefType.getQualifiers(); 7987 } 7988 7989 // Our location for everything implicitly-generated. 7990 SourceLocation Loc = CopyAssignOperator->getLocation(); 7991 7992 // Construct a reference to the "other" object. We'll be using this 7993 // throughout the generated ASTs. 7994 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take(); 7995 assert(OtherRef && "Reference to parameter cannot fail!"); 7996 7997 // Construct the "this" pointer. We'll be using this throughout the generated 7998 // ASTs. 7999 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>(); 8000 assert(This && "Reference to this cannot fail!"); 8001 8002 // Assign base classes. 8003 bool Invalid = false; 8004 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 8005 E = ClassDecl->bases_end(); Base != E; ++Base) { 8006 // Form the assignment: 8007 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 8008 QualType BaseType = Base->getType().getUnqualifiedType(); 8009 if (!BaseType->isRecordType()) { 8010 Invalid = true; 8011 continue; 8012 } 8013 8014 CXXCastPath BasePath; 8015 BasePath.push_back(Base); 8016 8017 // Construct the "from" expression, which is an implicit cast to the 8018 // appropriately-qualified base type. 8019 Expr *From = OtherRef; 8020 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals), 8021 CK_UncheckedDerivedToBase, 8022 VK_LValue, &BasePath).take(); 8023 8024 // Dereference "this". 8025 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 8026 8027 // Implicitly cast "this" to the appropriately-qualified base type. 8028 To = ImpCastExprToType(To.take(), 8029 Context.getCVRQualifiedType(BaseType, 8030 CopyAssignOperator->getTypeQualifiers()), 8031 CK_UncheckedDerivedToBase, 8032 VK_LValue, &BasePath); 8033 8034 // Build the copy. 8035 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType, 8036 To.get(), From, 8037 /*CopyingBaseSubobject=*/true, 8038 /*Copying=*/true); 8039 if (Copy.isInvalid()) { 8040 Diag(CurrentLocation, diag::note_member_synthesized_at) 8041 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 8042 CopyAssignOperator->setInvalidDecl(); 8043 return; 8044 } 8045 8046 // Success! Record the copy. 8047 Statements.push_back(Copy.takeAs<Expr>()); 8048 } 8049 8050 // \brief Reference to the __builtin_memcpy function. 8051 Expr *BuiltinMemCpyRef = 0; 8052 // \brief Reference to the __builtin_objc_memmove_collectable function. 8053 Expr *CollectableMemCpyRef = 0; 8054 8055 // Assign non-static members. 8056 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8057 FieldEnd = ClassDecl->field_end(); 8058 Field != FieldEnd; ++Field) { 8059 if (Field->isUnnamedBitfield()) 8060 continue; 8061 8062 // Check for members of reference type; we can't copy those. 8063 if (Field->getType()->isReferenceType()) { 8064 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 8065 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 8066 Diag(Field->getLocation(), diag::note_declared_at); 8067 Diag(CurrentLocation, diag::note_member_synthesized_at) 8068 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 8069 Invalid = true; 8070 continue; 8071 } 8072 8073 // Check for members of const-qualified, non-class type. 8074 QualType BaseType = Context.getBaseElementType(Field->getType()); 8075 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 8076 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 8077 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 8078 Diag(Field->getLocation(), diag::note_declared_at); 8079 Diag(CurrentLocation, diag::note_member_synthesized_at) 8080 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 8081 Invalid = true; 8082 continue; 8083 } 8084 8085 // Suppress assigning zero-width bitfields. 8086 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 8087 continue; 8088 8089 QualType FieldType = Field->getType().getNonReferenceType(); 8090 if (FieldType->isIncompleteArrayType()) { 8091 assert(ClassDecl->hasFlexibleArrayMember() && 8092 "Incomplete array type is not valid"); 8093 continue; 8094 } 8095 8096 // Build references to the field in the object we're copying from and to. 8097 CXXScopeSpec SS; // Intentionally empty 8098 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 8099 LookupMemberName); 8100 MemberLookup.addDecl(*Field); 8101 MemberLookup.resolveKind(); 8102 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType, 8103 Loc, /*IsArrow=*/false, 8104 SS, SourceLocation(), 0, 8105 MemberLookup, 0); 8106 ExprResult To = BuildMemberReferenceExpr(This, This->getType(), 8107 Loc, /*IsArrow=*/true, 8108 SS, SourceLocation(), 0, 8109 MemberLookup, 0); 8110 assert(!From.isInvalid() && "Implicit field reference cannot fail"); 8111 assert(!To.isInvalid() && "Implicit field reference cannot fail"); 8112 8113 // If the field should be copied with __builtin_memcpy rather than via 8114 // explicit assignments, do so. This optimization only applies for arrays 8115 // of scalars and arrays of class type with trivial copy-assignment 8116 // operators. 8117 if (FieldType->isArrayType() && !FieldType.isVolatileQualified() 8118 && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) { 8119 // Compute the size of the memory buffer to be copied. 8120 QualType SizeType = Context.getSizeType(); 8121 llvm::APInt Size(Context.getTypeSize(SizeType), 8122 Context.getTypeSizeInChars(BaseType).getQuantity()); 8123 for (const ConstantArrayType *Array 8124 = Context.getAsConstantArrayType(FieldType); 8125 Array; 8126 Array = Context.getAsConstantArrayType(Array->getElementType())) { 8127 llvm::APInt ArraySize 8128 = Array->getSize().zextOrTrunc(Size.getBitWidth()); 8129 Size *= ArraySize; 8130 } 8131 8132 // Take the address of the field references for "from" and "to". 8133 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get()); 8134 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get()); 8135 8136 bool NeedsCollectableMemCpy = 8137 (BaseType->isRecordType() && 8138 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()); 8139 8140 if (NeedsCollectableMemCpy) { 8141 if (!CollectableMemCpyRef) { 8142 // Create a reference to the __builtin_objc_memmove_collectable function. 8143 LookupResult R(*this, 8144 &Context.Idents.get("__builtin_objc_memmove_collectable"), 8145 Loc, LookupOrdinaryName); 8146 LookupName(R, TUScope, true); 8147 8148 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>(); 8149 if (!CollectableMemCpy) { 8150 // Something went horribly wrong earlier, and we will have 8151 // complained about it. 8152 Invalid = true; 8153 continue; 8154 } 8155 8156 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy, 8157 CollectableMemCpy->getType(), 8158 VK_LValue, Loc, 0).take(); 8159 assert(CollectableMemCpyRef && "Builtin reference cannot fail"); 8160 } 8161 } 8162 // Create a reference to the __builtin_memcpy builtin function. 8163 else if (!BuiltinMemCpyRef) { 8164 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc, 8165 LookupOrdinaryName); 8166 LookupName(R, TUScope, true); 8167 8168 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>(); 8169 if (!BuiltinMemCpy) { 8170 // Something went horribly wrong earlier, and we will have complained 8171 // about it. 8172 Invalid = true; 8173 continue; 8174 } 8175 8176 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy, 8177 BuiltinMemCpy->getType(), 8178 VK_LValue, Loc, 0).take(); 8179 assert(BuiltinMemCpyRef && "Builtin reference cannot fail"); 8180 } 8181 8182 ASTOwningVector<Expr*> CallArgs(*this); 8183 CallArgs.push_back(To.takeAs<Expr>()); 8184 CallArgs.push_back(From.takeAs<Expr>()); 8185 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc)); 8186 ExprResult Call = ExprError(); 8187 if (NeedsCollectableMemCpy) 8188 Call = ActOnCallExpr(/*Scope=*/0, 8189 CollectableMemCpyRef, 8190 Loc, move_arg(CallArgs), 8191 Loc); 8192 else 8193 Call = ActOnCallExpr(/*Scope=*/0, 8194 BuiltinMemCpyRef, 8195 Loc, move_arg(CallArgs), 8196 Loc); 8197 8198 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 8199 Statements.push_back(Call.takeAs<Expr>()); 8200 continue; 8201 } 8202 8203 // Build the copy of this field. 8204 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType, 8205 To.get(), From.get(), 8206 /*CopyingBaseSubobject=*/false, 8207 /*Copying=*/true); 8208 if (Copy.isInvalid()) { 8209 Diag(CurrentLocation, diag::note_member_synthesized_at) 8210 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 8211 CopyAssignOperator->setInvalidDecl(); 8212 return; 8213 } 8214 8215 // Success! Record the copy. 8216 Statements.push_back(Copy.takeAs<Stmt>()); 8217 } 8218 8219 if (!Invalid) { 8220 // Add a "return *this;" 8221 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 8222 8223 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get()); 8224 if (Return.isInvalid()) 8225 Invalid = true; 8226 else { 8227 Statements.push_back(Return.takeAs<Stmt>()); 8228 8229 if (Trap.hasErrorOccurred()) { 8230 Diag(CurrentLocation, diag::note_member_synthesized_at) 8231 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 8232 Invalid = true; 8233 } 8234 } 8235 } 8236 8237 if (Invalid) { 8238 CopyAssignOperator->setInvalidDecl(); 8239 return; 8240 } 8241 8242 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements), 8243 /*isStmtExpr=*/false); 8244 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 8245 CopyAssignOperator->setBody(Body.takeAs<Stmt>()); 8246 8247 if (ASTMutationListener *L = getASTMutationListener()) { 8248 L->CompletedImplicitDefinition(CopyAssignOperator); 8249 } 8250} 8251 8252Sema::ImplicitExceptionSpecification 8253Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXRecordDecl *ClassDecl) { 8254 ImplicitExceptionSpecification ExceptSpec(Context); 8255 8256 if (ClassDecl->isInvalidDecl()) 8257 return ExceptSpec; 8258 8259 // C++0x [except.spec]p14: 8260 // An implicitly declared special member function (Clause 12) shall have an 8261 // exception-specification. [...] 8262 8263 // It is unspecified whether or not an implicit move assignment operator 8264 // attempts to deduplicate calls to assignment operators of virtual bases are 8265 // made. As such, this exception specification is effectively unspecified. 8266 // Based on a similar decision made for constness in C++0x, we're erring on 8267 // the side of assuming such calls to be made regardless of whether they 8268 // actually happen. 8269 // Note that a move constructor is not implicitly declared when there are 8270 // virtual bases, but it can still be user-declared and explicitly defaulted. 8271 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 8272 BaseEnd = ClassDecl->bases_end(); 8273 Base != BaseEnd; ++Base) { 8274 if (Base->isVirtual()) 8275 continue; 8276 8277 CXXRecordDecl *BaseClassDecl 8278 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8279 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 8280 false, 0)) 8281 ExceptSpec.CalledDecl(MoveAssign); 8282 } 8283 8284 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 8285 BaseEnd = ClassDecl->vbases_end(); 8286 Base != BaseEnd; ++Base) { 8287 CXXRecordDecl *BaseClassDecl 8288 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8289 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 8290 false, 0)) 8291 ExceptSpec.CalledDecl(MoveAssign); 8292 } 8293 8294 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8295 FieldEnd = ClassDecl->field_end(); 8296 Field != FieldEnd; 8297 ++Field) { 8298 QualType FieldType = Context.getBaseElementType((*Field)->getType()); 8299 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 8300 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(FieldClassDecl, 8301 false, 0)) 8302 ExceptSpec.CalledDecl(MoveAssign); 8303 } 8304 } 8305 8306 return ExceptSpec; 8307} 8308 8309CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 8310 // Note: The following rules are largely analoguous to the move 8311 // constructor rules. 8312 8313 ImplicitExceptionSpecification Spec( 8314 ComputeDefaultedMoveAssignmentExceptionSpec(ClassDecl)); 8315 8316 QualType ArgType = Context.getTypeDeclType(ClassDecl); 8317 QualType RetType = Context.getLValueReferenceType(ArgType); 8318 ArgType = Context.getRValueReferenceType(ArgType); 8319 8320 // An implicitly-declared move assignment operator is an inline public 8321 // member of its class. 8322 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 8323 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 8324 SourceLocation ClassLoc = ClassDecl->getLocation(); 8325 DeclarationNameInfo NameInfo(Name, ClassLoc); 8326 CXXMethodDecl *MoveAssignment 8327 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 8328 Context.getFunctionType(RetType, &ArgType, 1, EPI), 8329 /*TInfo=*/0, /*isStatic=*/false, 8330 /*StorageClassAsWritten=*/SC_None, 8331 /*isInline=*/true, 8332 /*isConstexpr=*/false, 8333 SourceLocation()); 8334 MoveAssignment->setAccess(AS_public); 8335 MoveAssignment->setDefaulted(); 8336 MoveAssignment->setImplicit(); 8337 MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment()); 8338 8339 // Add the parameter to the operator. 8340 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 8341 ClassLoc, ClassLoc, /*Id=*/0, 8342 ArgType, /*TInfo=*/0, 8343 SC_None, 8344 SC_None, 0); 8345 MoveAssignment->setParams(FromParam); 8346 8347 // Note that we have added this copy-assignment operator. 8348 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 8349 8350 // C++0x [class.copy]p9: 8351 // If the definition of a class X does not explicitly declare a move 8352 // assignment operator, one will be implicitly declared as defaulted if and 8353 // only if: 8354 // [...] 8355 // - the move assignment operator would not be implicitly defined as 8356 // deleted. 8357 if (ShouldDeleteMoveAssignmentOperator(MoveAssignment)) { 8358 // Cache this result so that we don't try to generate this over and over 8359 // on every lookup, leaking memory and wasting time. 8360 ClassDecl->setFailedImplicitMoveAssignment(); 8361 return 0; 8362 } 8363 8364 if (Scope *S = getScopeForContext(ClassDecl)) 8365 PushOnScopeChains(MoveAssignment, S, false); 8366 ClassDecl->addDecl(MoveAssignment); 8367 8368 AddOverriddenMethods(ClassDecl, MoveAssignment); 8369 return MoveAssignment; 8370} 8371 8372void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 8373 CXXMethodDecl *MoveAssignOperator) { 8374 assert((MoveAssignOperator->isDefaulted() && 8375 MoveAssignOperator->isOverloadedOperator() && 8376 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 8377 !MoveAssignOperator->doesThisDeclarationHaveABody()) && 8378 "DefineImplicitMoveAssignment called for wrong function"); 8379 8380 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 8381 8382 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) { 8383 MoveAssignOperator->setInvalidDecl(); 8384 return; 8385 } 8386 8387 MoveAssignOperator->setUsed(); 8388 8389 ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator); 8390 DiagnosticErrorTrap Trap(Diags); 8391 8392 // C++0x [class.copy]p28: 8393 // The implicitly-defined or move assignment operator for a non-union class 8394 // X performs memberwise move assignment of its subobjects. The direct base 8395 // classes of X are assigned first, in the order of their declaration in the 8396 // base-specifier-list, and then the immediate non-static data members of X 8397 // are assigned, in the order in which they were declared in the class 8398 // definition. 8399 8400 // The statements that form the synthesized function body. 8401 ASTOwningVector<Stmt*> Statements(*this); 8402 8403 // The parameter for the "other" object, which we are move from. 8404 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 8405 QualType OtherRefType = Other->getType()-> 8406 getAs<RValueReferenceType>()->getPointeeType(); 8407 assert(OtherRefType.getQualifiers() == 0 && 8408 "Bad argument type of defaulted move assignment"); 8409 8410 // Our location for everything implicitly-generated. 8411 SourceLocation Loc = MoveAssignOperator->getLocation(); 8412 8413 // Construct a reference to the "other" object. We'll be using this 8414 // throughout the generated ASTs. 8415 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take(); 8416 assert(OtherRef && "Reference to parameter cannot fail!"); 8417 // Cast to rvalue. 8418 OtherRef = CastForMoving(*this, OtherRef); 8419 8420 // Construct the "this" pointer. We'll be using this throughout the generated 8421 // ASTs. 8422 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>(); 8423 assert(This && "Reference to this cannot fail!"); 8424 8425 // Assign base classes. 8426 bool Invalid = false; 8427 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 8428 E = ClassDecl->bases_end(); Base != E; ++Base) { 8429 // Form the assignment: 8430 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 8431 QualType BaseType = Base->getType().getUnqualifiedType(); 8432 if (!BaseType->isRecordType()) { 8433 Invalid = true; 8434 continue; 8435 } 8436 8437 CXXCastPath BasePath; 8438 BasePath.push_back(Base); 8439 8440 // Construct the "from" expression, which is an implicit cast to the 8441 // appropriately-qualified base type. 8442 Expr *From = OtherRef; 8443 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase, 8444 VK_XValue, &BasePath).take(); 8445 8446 // Dereference "this". 8447 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 8448 8449 // Implicitly cast "this" to the appropriately-qualified base type. 8450 To = ImpCastExprToType(To.take(), 8451 Context.getCVRQualifiedType(BaseType, 8452 MoveAssignOperator->getTypeQualifiers()), 8453 CK_UncheckedDerivedToBase, 8454 VK_LValue, &BasePath); 8455 8456 // Build the move. 8457 StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType, 8458 To.get(), From, 8459 /*CopyingBaseSubobject=*/true, 8460 /*Copying=*/false); 8461 if (Move.isInvalid()) { 8462 Diag(CurrentLocation, diag::note_member_synthesized_at) 8463 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 8464 MoveAssignOperator->setInvalidDecl(); 8465 return; 8466 } 8467 8468 // Success! Record the move. 8469 Statements.push_back(Move.takeAs<Expr>()); 8470 } 8471 8472 // \brief Reference to the __builtin_memcpy function. 8473 Expr *BuiltinMemCpyRef = 0; 8474 // \brief Reference to the __builtin_objc_memmove_collectable function. 8475 Expr *CollectableMemCpyRef = 0; 8476 8477 // Assign non-static members. 8478 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8479 FieldEnd = ClassDecl->field_end(); 8480 Field != FieldEnd; ++Field) { 8481 if (Field->isUnnamedBitfield()) 8482 continue; 8483 8484 // Check for members of reference type; we can't move those. 8485 if (Field->getType()->isReferenceType()) { 8486 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 8487 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 8488 Diag(Field->getLocation(), diag::note_declared_at); 8489 Diag(CurrentLocation, diag::note_member_synthesized_at) 8490 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 8491 Invalid = true; 8492 continue; 8493 } 8494 8495 // Check for members of const-qualified, non-class type. 8496 QualType BaseType = Context.getBaseElementType(Field->getType()); 8497 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 8498 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 8499 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 8500 Diag(Field->getLocation(), diag::note_declared_at); 8501 Diag(CurrentLocation, diag::note_member_synthesized_at) 8502 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 8503 Invalid = true; 8504 continue; 8505 } 8506 8507 // Suppress assigning zero-width bitfields. 8508 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 8509 continue; 8510 8511 QualType FieldType = Field->getType().getNonReferenceType(); 8512 if (FieldType->isIncompleteArrayType()) { 8513 assert(ClassDecl->hasFlexibleArrayMember() && 8514 "Incomplete array type is not valid"); 8515 continue; 8516 } 8517 8518 // Build references to the field in the object we're copying from and to. 8519 CXXScopeSpec SS; // Intentionally empty 8520 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 8521 LookupMemberName); 8522 MemberLookup.addDecl(*Field); 8523 MemberLookup.resolveKind(); 8524 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType, 8525 Loc, /*IsArrow=*/false, 8526 SS, SourceLocation(), 0, 8527 MemberLookup, 0); 8528 ExprResult To = BuildMemberReferenceExpr(This, This->getType(), 8529 Loc, /*IsArrow=*/true, 8530 SS, SourceLocation(), 0, 8531 MemberLookup, 0); 8532 assert(!From.isInvalid() && "Implicit field reference cannot fail"); 8533 assert(!To.isInvalid() && "Implicit field reference cannot fail"); 8534 8535 assert(!From.get()->isLValue() && // could be xvalue or prvalue 8536 "Member reference with rvalue base must be rvalue except for reference " 8537 "members, which aren't allowed for move assignment."); 8538 8539 // If the field should be copied with __builtin_memcpy rather than via 8540 // explicit assignments, do so. This optimization only applies for arrays 8541 // of scalars and arrays of class type with trivial move-assignment 8542 // operators. 8543 if (FieldType->isArrayType() && !FieldType.isVolatileQualified() 8544 && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) { 8545 // Compute the size of the memory buffer to be copied. 8546 QualType SizeType = Context.getSizeType(); 8547 llvm::APInt Size(Context.getTypeSize(SizeType), 8548 Context.getTypeSizeInChars(BaseType).getQuantity()); 8549 for (const ConstantArrayType *Array 8550 = Context.getAsConstantArrayType(FieldType); 8551 Array; 8552 Array = Context.getAsConstantArrayType(Array->getElementType())) { 8553 llvm::APInt ArraySize 8554 = Array->getSize().zextOrTrunc(Size.getBitWidth()); 8555 Size *= ArraySize; 8556 } 8557 8558 // Take the address of the field references for "from" and "to". We 8559 // directly construct UnaryOperators here because semantic analysis 8560 // does not permit us to take the address of an xvalue. 8561 From = new (Context) UnaryOperator(From.get(), UO_AddrOf, 8562 Context.getPointerType(From.get()->getType()), 8563 VK_RValue, OK_Ordinary, Loc); 8564 To = new (Context) UnaryOperator(To.get(), UO_AddrOf, 8565 Context.getPointerType(To.get()->getType()), 8566 VK_RValue, OK_Ordinary, Loc); 8567 8568 bool NeedsCollectableMemCpy = 8569 (BaseType->isRecordType() && 8570 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()); 8571 8572 if (NeedsCollectableMemCpy) { 8573 if (!CollectableMemCpyRef) { 8574 // Create a reference to the __builtin_objc_memmove_collectable function. 8575 LookupResult R(*this, 8576 &Context.Idents.get("__builtin_objc_memmove_collectable"), 8577 Loc, LookupOrdinaryName); 8578 LookupName(R, TUScope, true); 8579 8580 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>(); 8581 if (!CollectableMemCpy) { 8582 // Something went horribly wrong earlier, and we will have 8583 // complained about it. 8584 Invalid = true; 8585 continue; 8586 } 8587 8588 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy, 8589 CollectableMemCpy->getType(), 8590 VK_LValue, Loc, 0).take(); 8591 assert(CollectableMemCpyRef && "Builtin reference cannot fail"); 8592 } 8593 } 8594 // Create a reference to the __builtin_memcpy builtin function. 8595 else if (!BuiltinMemCpyRef) { 8596 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc, 8597 LookupOrdinaryName); 8598 LookupName(R, TUScope, true); 8599 8600 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>(); 8601 if (!BuiltinMemCpy) { 8602 // Something went horribly wrong earlier, and we will have complained 8603 // about it. 8604 Invalid = true; 8605 continue; 8606 } 8607 8608 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy, 8609 BuiltinMemCpy->getType(), 8610 VK_LValue, Loc, 0).take(); 8611 assert(BuiltinMemCpyRef && "Builtin reference cannot fail"); 8612 } 8613 8614 ASTOwningVector<Expr*> CallArgs(*this); 8615 CallArgs.push_back(To.takeAs<Expr>()); 8616 CallArgs.push_back(From.takeAs<Expr>()); 8617 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc)); 8618 ExprResult Call = ExprError(); 8619 if (NeedsCollectableMemCpy) 8620 Call = ActOnCallExpr(/*Scope=*/0, 8621 CollectableMemCpyRef, 8622 Loc, move_arg(CallArgs), 8623 Loc); 8624 else 8625 Call = ActOnCallExpr(/*Scope=*/0, 8626 BuiltinMemCpyRef, 8627 Loc, move_arg(CallArgs), 8628 Loc); 8629 8630 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 8631 Statements.push_back(Call.takeAs<Expr>()); 8632 continue; 8633 } 8634 8635 // Build the move of this field. 8636 StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType, 8637 To.get(), From.get(), 8638 /*CopyingBaseSubobject=*/false, 8639 /*Copying=*/false); 8640 if (Move.isInvalid()) { 8641 Diag(CurrentLocation, diag::note_member_synthesized_at) 8642 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 8643 MoveAssignOperator->setInvalidDecl(); 8644 return; 8645 } 8646 8647 // Success! Record the copy. 8648 Statements.push_back(Move.takeAs<Stmt>()); 8649 } 8650 8651 if (!Invalid) { 8652 // Add a "return *this;" 8653 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 8654 8655 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get()); 8656 if (Return.isInvalid()) 8657 Invalid = true; 8658 else { 8659 Statements.push_back(Return.takeAs<Stmt>()); 8660 8661 if (Trap.hasErrorOccurred()) { 8662 Diag(CurrentLocation, diag::note_member_synthesized_at) 8663 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 8664 Invalid = true; 8665 } 8666 } 8667 } 8668 8669 if (Invalid) { 8670 MoveAssignOperator->setInvalidDecl(); 8671 return; 8672 } 8673 8674 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements), 8675 /*isStmtExpr=*/false); 8676 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 8677 MoveAssignOperator->setBody(Body.takeAs<Stmt>()); 8678 8679 if (ASTMutationListener *L = getASTMutationListener()) { 8680 L->CompletedImplicitDefinition(MoveAssignOperator); 8681 } 8682} 8683 8684std::pair<Sema::ImplicitExceptionSpecification, bool> 8685Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) { 8686 if (ClassDecl->isInvalidDecl()) 8687 return std::make_pair(ImplicitExceptionSpecification(Context), false); 8688 8689 // C++ [class.copy]p5: 8690 // The implicitly-declared copy constructor for a class X will 8691 // have the form 8692 // 8693 // X::X(const X&) 8694 // 8695 // if 8696 // FIXME: It ought to be possible to store this on the record. 8697 bool HasConstCopyConstructor = true; 8698 8699 // -- each direct or virtual base class B of X has a copy 8700 // constructor whose first parameter is of type const B& or 8701 // const volatile B&, and 8702 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 8703 BaseEnd = ClassDecl->bases_end(); 8704 HasConstCopyConstructor && Base != BaseEnd; 8705 ++Base) { 8706 // Virtual bases are handled below. 8707 if (Base->isVirtual()) 8708 continue; 8709 8710 CXXRecordDecl *BaseClassDecl 8711 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8712 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const, 8713 &HasConstCopyConstructor); 8714 } 8715 8716 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 8717 BaseEnd = ClassDecl->vbases_end(); 8718 HasConstCopyConstructor && Base != BaseEnd; 8719 ++Base) { 8720 CXXRecordDecl *BaseClassDecl 8721 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8722 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const, 8723 &HasConstCopyConstructor); 8724 } 8725 8726 // -- for all the nonstatic data members of X that are of a 8727 // class type M (or array thereof), each such class type 8728 // has a copy constructor whose first parameter is of type 8729 // const M& or const volatile M&. 8730 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8731 FieldEnd = ClassDecl->field_end(); 8732 HasConstCopyConstructor && Field != FieldEnd; 8733 ++Field) { 8734 QualType FieldType = Context.getBaseElementType((*Field)->getType()); 8735 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 8736 LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const, 8737 &HasConstCopyConstructor); 8738 } 8739 } 8740 // Otherwise, the implicitly declared copy constructor will have 8741 // the form 8742 // 8743 // X::X(X&) 8744 8745 // C++ [except.spec]p14: 8746 // An implicitly declared special member function (Clause 12) shall have an 8747 // exception-specification. [...] 8748 ImplicitExceptionSpecification ExceptSpec(Context); 8749 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0; 8750 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 8751 BaseEnd = ClassDecl->bases_end(); 8752 Base != BaseEnd; 8753 ++Base) { 8754 // Virtual bases are handled below. 8755 if (Base->isVirtual()) 8756 continue; 8757 8758 CXXRecordDecl *BaseClassDecl 8759 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8760 if (CXXConstructorDecl *CopyConstructor = 8761 LookupCopyingConstructor(BaseClassDecl, Quals)) 8762 ExceptSpec.CalledDecl(CopyConstructor); 8763 } 8764 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 8765 BaseEnd = ClassDecl->vbases_end(); 8766 Base != BaseEnd; 8767 ++Base) { 8768 CXXRecordDecl *BaseClassDecl 8769 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8770 if (CXXConstructorDecl *CopyConstructor = 8771 LookupCopyingConstructor(BaseClassDecl, Quals)) 8772 ExceptSpec.CalledDecl(CopyConstructor); 8773 } 8774 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8775 FieldEnd = ClassDecl->field_end(); 8776 Field != FieldEnd; 8777 ++Field) { 8778 QualType FieldType = Context.getBaseElementType((*Field)->getType()); 8779 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 8780 if (CXXConstructorDecl *CopyConstructor = 8781 LookupCopyingConstructor(FieldClassDecl, Quals)) 8782 ExceptSpec.CalledDecl(CopyConstructor); 8783 } 8784 } 8785 8786 return std::make_pair(ExceptSpec, HasConstCopyConstructor); 8787} 8788 8789CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 8790 CXXRecordDecl *ClassDecl) { 8791 // C++ [class.copy]p4: 8792 // If the class definition does not explicitly declare a copy 8793 // constructor, one is declared implicitly. 8794 8795 ImplicitExceptionSpecification Spec(Context); 8796 bool Const; 8797 llvm::tie(Spec, Const) = 8798 ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl); 8799 8800 QualType ClassType = Context.getTypeDeclType(ClassDecl); 8801 QualType ArgType = ClassType; 8802 if (Const) 8803 ArgType = ArgType.withConst(); 8804 ArgType = Context.getLValueReferenceType(ArgType); 8805 8806 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 8807 8808 DeclarationName Name 8809 = Context.DeclarationNames.getCXXConstructorName( 8810 Context.getCanonicalType(ClassType)); 8811 SourceLocation ClassLoc = ClassDecl->getLocation(); 8812 DeclarationNameInfo NameInfo(Name, ClassLoc); 8813 8814 // An implicitly-declared copy constructor is an inline public 8815 // member of its class. 8816 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 8817 Context, ClassDecl, ClassLoc, NameInfo, 8818 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0, 8819 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 8820 /*isConstexpr=*/ClassDecl->defaultedCopyConstructorIsConstexpr() && 8821 getLangOptions().CPlusPlus0x); 8822 CopyConstructor->setAccess(AS_public); 8823 CopyConstructor->setDefaulted(); 8824 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor()); 8825 8826 // Note that we have declared this constructor. 8827 ++ASTContext::NumImplicitCopyConstructorsDeclared; 8828 8829 // Add the parameter to the constructor. 8830 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 8831 ClassLoc, ClassLoc, 8832 /*IdentifierInfo=*/0, 8833 ArgType, /*TInfo=*/0, 8834 SC_None, 8835 SC_None, 0); 8836 CopyConstructor->setParams(FromParam); 8837 8838 if (Scope *S = getScopeForContext(ClassDecl)) 8839 PushOnScopeChains(CopyConstructor, S, false); 8840 ClassDecl->addDecl(CopyConstructor); 8841 8842 // C++11 [class.copy]p8: 8843 // ... If the class definition does not explicitly declare a copy 8844 // constructor, there is no user-declared move constructor, and there is no 8845 // user-declared move assignment operator, a copy constructor is implicitly 8846 // declared as defaulted. 8847 if (ClassDecl->hasUserDeclaredMoveConstructor() || 8848 (ClassDecl->hasUserDeclaredMoveAssignment() && 8849 !getLangOptions().MicrosoftMode) || 8850 ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) 8851 CopyConstructor->setDeletedAsWritten(); 8852 8853 return CopyConstructor; 8854} 8855 8856void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 8857 CXXConstructorDecl *CopyConstructor) { 8858 assert((CopyConstructor->isDefaulted() && 8859 CopyConstructor->isCopyConstructor() && 8860 !CopyConstructor->doesThisDeclarationHaveABody()) && 8861 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 8862 8863 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 8864 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 8865 8866 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor); 8867 DiagnosticErrorTrap Trap(Diags); 8868 8869 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) || 8870 Trap.hasErrorOccurred()) { 8871 Diag(CurrentLocation, diag::note_member_synthesized_at) 8872 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl); 8873 CopyConstructor->setInvalidDecl(); 8874 } else { 8875 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(), 8876 CopyConstructor->getLocation(), 8877 MultiStmtArg(*this, 0, 0), 8878 /*isStmtExpr=*/false) 8879 .takeAs<Stmt>()); 8880 CopyConstructor->setImplicitlyDefined(true); 8881 } 8882 8883 CopyConstructor->setUsed(); 8884 if (ASTMutationListener *L = getASTMutationListener()) { 8885 L->CompletedImplicitDefinition(CopyConstructor); 8886 } 8887} 8888 8889Sema::ImplicitExceptionSpecification 8890Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXRecordDecl *ClassDecl) { 8891 // C++ [except.spec]p14: 8892 // An implicitly declared special member function (Clause 12) shall have an 8893 // exception-specification. [...] 8894 ImplicitExceptionSpecification ExceptSpec(Context); 8895 if (ClassDecl->isInvalidDecl()) 8896 return ExceptSpec; 8897 8898 // Direct base-class constructors. 8899 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 8900 BEnd = ClassDecl->bases_end(); 8901 B != BEnd; ++B) { 8902 if (B->isVirtual()) // Handled below. 8903 continue; 8904 8905 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 8906 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8907 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl); 8908 // If this is a deleted function, add it anyway. This might be conformant 8909 // with the standard. This might not. I'm not sure. It might not matter. 8910 if (Constructor) 8911 ExceptSpec.CalledDecl(Constructor); 8912 } 8913 } 8914 8915 // Virtual base-class constructors. 8916 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 8917 BEnd = ClassDecl->vbases_end(); 8918 B != BEnd; ++B) { 8919 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 8920 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8921 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl); 8922 // If this is a deleted function, add it anyway. This might be conformant 8923 // with the standard. This might not. I'm not sure. It might not matter. 8924 if (Constructor) 8925 ExceptSpec.CalledDecl(Constructor); 8926 } 8927 } 8928 8929 // Field constructors. 8930 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 8931 FEnd = ClassDecl->field_end(); 8932 F != FEnd; ++F) { 8933 if (const RecordType *RecordTy 8934 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 8935 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8936 CXXConstructorDecl *Constructor = LookupMovingConstructor(FieldRecDecl); 8937 // If this is a deleted function, add it anyway. This might be conformant 8938 // with the standard. This might not. I'm not sure. It might not matter. 8939 // In particular, the problem is that this function never gets called. It 8940 // might just be ill-formed because this function attempts to refer to 8941 // a deleted function here. 8942 if (Constructor) 8943 ExceptSpec.CalledDecl(Constructor); 8944 } 8945 } 8946 8947 return ExceptSpec; 8948} 8949 8950CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 8951 CXXRecordDecl *ClassDecl) { 8952 ImplicitExceptionSpecification Spec( 8953 ComputeDefaultedMoveCtorExceptionSpec(ClassDecl)); 8954 8955 QualType ClassType = Context.getTypeDeclType(ClassDecl); 8956 QualType ArgType = Context.getRValueReferenceType(ClassType); 8957 8958 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 8959 8960 DeclarationName Name 8961 = Context.DeclarationNames.getCXXConstructorName( 8962 Context.getCanonicalType(ClassType)); 8963 SourceLocation ClassLoc = ClassDecl->getLocation(); 8964 DeclarationNameInfo NameInfo(Name, ClassLoc); 8965 8966 // C++0x [class.copy]p11: 8967 // An implicitly-declared copy/move constructor is an inline public 8968 // member of its class. 8969 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 8970 Context, ClassDecl, ClassLoc, NameInfo, 8971 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0, 8972 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 8973 /*isConstexpr=*/ClassDecl->defaultedMoveConstructorIsConstexpr() && 8974 getLangOptions().CPlusPlus0x); 8975 MoveConstructor->setAccess(AS_public); 8976 MoveConstructor->setDefaulted(); 8977 MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor()); 8978 8979 // Add the parameter to the constructor. 8980 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 8981 ClassLoc, ClassLoc, 8982 /*IdentifierInfo=*/0, 8983 ArgType, /*TInfo=*/0, 8984 SC_None, 8985 SC_None, 0); 8986 MoveConstructor->setParams(FromParam); 8987 8988 // C++0x [class.copy]p9: 8989 // If the definition of a class X does not explicitly declare a move 8990 // constructor, one will be implicitly declared as defaulted if and only if: 8991 // [...] 8992 // - the move constructor would not be implicitly defined as deleted. 8993 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 8994 // Cache this result so that we don't try to generate this over and over 8995 // on every lookup, leaking memory and wasting time. 8996 ClassDecl->setFailedImplicitMoveConstructor(); 8997 return 0; 8998 } 8999 9000 // Note that we have declared this constructor. 9001 ++ASTContext::NumImplicitMoveConstructorsDeclared; 9002 9003 if (Scope *S = getScopeForContext(ClassDecl)) 9004 PushOnScopeChains(MoveConstructor, S, false); 9005 ClassDecl->addDecl(MoveConstructor); 9006 9007 return MoveConstructor; 9008} 9009 9010void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 9011 CXXConstructorDecl *MoveConstructor) { 9012 assert((MoveConstructor->isDefaulted() && 9013 MoveConstructor->isMoveConstructor() && 9014 !MoveConstructor->doesThisDeclarationHaveABody()) && 9015 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 9016 9017 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 9018 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 9019 9020 ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor); 9021 DiagnosticErrorTrap Trap(Diags); 9022 9023 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) || 9024 Trap.hasErrorOccurred()) { 9025 Diag(CurrentLocation, diag::note_member_synthesized_at) 9026 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl); 9027 MoveConstructor->setInvalidDecl(); 9028 } else { 9029 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(), 9030 MoveConstructor->getLocation(), 9031 MultiStmtArg(*this, 0, 0), 9032 /*isStmtExpr=*/false) 9033 .takeAs<Stmt>()); 9034 MoveConstructor->setImplicitlyDefined(true); 9035 } 9036 9037 MoveConstructor->setUsed(); 9038 9039 if (ASTMutationListener *L = getASTMutationListener()) { 9040 L->CompletedImplicitDefinition(MoveConstructor); 9041 } 9042} 9043 9044ExprResult 9045Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 9046 CXXConstructorDecl *Constructor, 9047 MultiExprArg ExprArgs, 9048 bool HadMultipleCandidates, 9049 bool RequiresZeroInit, 9050 unsigned ConstructKind, 9051 SourceRange ParenRange) { 9052 bool Elidable = false; 9053 9054 // C++0x [class.copy]p34: 9055 // When certain criteria are met, an implementation is allowed to 9056 // omit the copy/move construction of a class object, even if the 9057 // copy/move constructor and/or destructor for the object have 9058 // side effects. [...] 9059 // - when a temporary class object that has not been bound to a 9060 // reference (12.2) would be copied/moved to a class object 9061 // with the same cv-unqualified type, the copy/move operation 9062 // can be omitted by constructing the temporary object 9063 // directly into the target of the omitted copy/move 9064 if (ConstructKind == CXXConstructExpr::CK_Complete && 9065 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) { 9066 Expr *SubExpr = ((Expr **)ExprArgs.get())[0]; 9067 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent()); 9068 } 9069 9070 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 9071 Elidable, move(ExprArgs), HadMultipleCandidates, 9072 RequiresZeroInit, ConstructKind, ParenRange); 9073} 9074 9075/// BuildCXXConstructExpr - Creates a complete call to a constructor, 9076/// including handling of its default argument expressions. 9077ExprResult 9078Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 9079 CXXConstructorDecl *Constructor, bool Elidable, 9080 MultiExprArg ExprArgs, 9081 bool HadMultipleCandidates, 9082 bool RequiresZeroInit, 9083 unsigned ConstructKind, 9084 SourceRange ParenRange) { 9085 unsigned NumExprs = ExprArgs.size(); 9086 Expr **Exprs = (Expr **)ExprArgs.release(); 9087 9088 for (specific_attr_iterator<NonNullAttr> 9089 i = Constructor->specific_attr_begin<NonNullAttr>(), 9090 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) { 9091 const NonNullAttr *NonNull = *i; 9092 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc); 9093 } 9094 9095 MarkFunctionReferenced(ConstructLoc, Constructor); 9096 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc, 9097 Constructor, Elidable, Exprs, NumExprs, 9098 HadMultipleCandidates, /*FIXME*/false, 9099 RequiresZeroInit, 9100 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 9101 ParenRange)); 9102} 9103 9104bool Sema::InitializeVarWithConstructor(VarDecl *VD, 9105 CXXConstructorDecl *Constructor, 9106 MultiExprArg Exprs, 9107 bool HadMultipleCandidates) { 9108 // FIXME: Provide the correct paren SourceRange when available. 9109 ExprResult TempResult = 9110 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor, 9111 move(Exprs), HadMultipleCandidates, false, 9112 CXXConstructExpr::CK_Complete, SourceRange()); 9113 if (TempResult.isInvalid()) 9114 return true; 9115 9116 Expr *Temp = TempResult.takeAs<Expr>(); 9117 CheckImplicitConversions(Temp, VD->getLocation()); 9118 MarkFunctionReferenced(VD->getLocation(), Constructor); 9119 Temp = MaybeCreateExprWithCleanups(Temp); 9120 VD->setInit(Temp); 9121 9122 return false; 9123} 9124 9125void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 9126 if (VD->isInvalidDecl()) return; 9127 9128 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 9129 if (ClassDecl->isInvalidDecl()) return; 9130 if (ClassDecl->hasTrivialDestructor()) return; 9131 if (ClassDecl->isDependentContext()) return; 9132 9133 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 9134 MarkFunctionReferenced(VD->getLocation(), Destructor); 9135 CheckDestructorAccess(VD->getLocation(), Destructor, 9136 PDiag(diag::err_access_dtor_var) 9137 << VD->getDeclName() 9138 << VD->getType()); 9139 9140 if (!VD->hasGlobalStorage()) return; 9141 9142 // Emit warning for non-trivial dtor in global scope (a real global, 9143 // class-static, function-static). 9144 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 9145 9146 // TODO: this should be re-enabled for static locals by !CXAAtExit 9147 if (!VD->isStaticLocal()) 9148 Diag(VD->getLocation(), diag::warn_global_destructor); 9149} 9150 9151/// \brief Given a constructor and the set of arguments provided for the 9152/// constructor, convert the arguments and add any required default arguments 9153/// to form a proper call to this constructor. 9154/// 9155/// \returns true if an error occurred, false otherwise. 9156bool 9157Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 9158 MultiExprArg ArgsPtr, 9159 SourceLocation Loc, 9160 ASTOwningVector<Expr*> &ConvertedArgs) { 9161 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 9162 unsigned NumArgs = ArgsPtr.size(); 9163 Expr **Args = (Expr **)ArgsPtr.get(); 9164 9165 const FunctionProtoType *Proto 9166 = Constructor->getType()->getAs<FunctionProtoType>(); 9167 assert(Proto && "Constructor without a prototype?"); 9168 unsigned NumArgsInProto = Proto->getNumArgs(); 9169 9170 // If too few arguments are available, we'll fill in the rest with defaults. 9171 if (NumArgs < NumArgsInProto) 9172 ConvertedArgs.reserve(NumArgsInProto); 9173 else 9174 ConvertedArgs.reserve(NumArgs); 9175 9176 VariadicCallType CallType = 9177 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 9178 SmallVector<Expr *, 8> AllArgs; 9179 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 9180 Proto, 0, Args, NumArgs, AllArgs, 9181 CallType); 9182 for (unsigned i =0, size = AllArgs.size(); i < size; i++) 9183 ConvertedArgs.push_back(AllArgs[i]); 9184 return Invalid; 9185} 9186 9187static inline bool 9188CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 9189 const FunctionDecl *FnDecl) { 9190 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 9191 if (isa<NamespaceDecl>(DC)) { 9192 return SemaRef.Diag(FnDecl->getLocation(), 9193 diag::err_operator_new_delete_declared_in_namespace) 9194 << FnDecl->getDeclName(); 9195 } 9196 9197 if (isa<TranslationUnitDecl>(DC) && 9198 FnDecl->getStorageClass() == SC_Static) { 9199 return SemaRef.Diag(FnDecl->getLocation(), 9200 diag::err_operator_new_delete_declared_static) 9201 << FnDecl->getDeclName(); 9202 } 9203 9204 return false; 9205} 9206 9207static inline bool 9208CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 9209 CanQualType ExpectedResultType, 9210 CanQualType ExpectedFirstParamType, 9211 unsigned DependentParamTypeDiag, 9212 unsigned InvalidParamTypeDiag) { 9213 QualType ResultType = 9214 FnDecl->getType()->getAs<FunctionType>()->getResultType(); 9215 9216 // Check that the result type is not dependent. 9217 if (ResultType->isDependentType()) 9218 return SemaRef.Diag(FnDecl->getLocation(), 9219 diag::err_operator_new_delete_dependent_result_type) 9220 << FnDecl->getDeclName() << ExpectedResultType; 9221 9222 // Check that the result type is what we expect. 9223 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 9224 return SemaRef.Diag(FnDecl->getLocation(), 9225 diag::err_operator_new_delete_invalid_result_type) 9226 << FnDecl->getDeclName() << ExpectedResultType; 9227 9228 // A function template must have at least 2 parameters. 9229 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 9230 return SemaRef.Diag(FnDecl->getLocation(), 9231 diag::err_operator_new_delete_template_too_few_parameters) 9232 << FnDecl->getDeclName(); 9233 9234 // The function decl must have at least 1 parameter. 9235 if (FnDecl->getNumParams() == 0) 9236 return SemaRef.Diag(FnDecl->getLocation(), 9237 diag::err_operator_new_delete_too_few_parameters) 9238 << FnDecl->getDeclName(); 9239 9240 // Check the the first parameter type is not dependent. 9241 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 9242 if (FirstParamType->isDependentType()) 9243 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 9244 << FnDecl->getDeclName() << ExpectedFirstParamType; 9245 9246 // Check that the first parameter type is what we expect. 9247 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 9248 ExpectedFirstParamType) 9249 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 9250 << FnDecl->getDeclName() << ExpectedFirstParamType; 9251 9252 return false; 9253} 9254 9255static bool 9256CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 9257 // C++ [basic.stc.dynamic.allocation]p1: 9258 // A program is ill-formed if an allocation function is declared in a 9259 // namespace scope other than global scope or declared static in global 9260 // scope. 9261 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 9262 return true; 9263 9264 CanQualType SizeTy = 9265 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 9266 9267 // C++ [basic.stc.dynamic.allocation]p1: 9268 // The return type shall be void*. The first parameter shall have type 9269 // std::size_t. 9270 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 9271 SizeTy, 9272 diag::err_operator_new_dependent_param_type, 9273 diag::err_operator_new_param_type)) 9274 return true; 9275 9276 // C++ [basic.stc.dynamic.allocation]p1: 9277 // The first parameter shall not have an associated default argument. 9278 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 9279 return SemaRef.Diag(FnDecl->getLocation(), 9280 diag::err_operator_new_default_arg) 9281 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 9282 9283 return false; 9284} 9285 9286static bool 9287CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 9288 // C++ [basic.stc.dynamic.deallocation]p1: 9289 // A program is ill-formed if deallocation functions are declared in a 9290 // namespace scope other than global scope or declared static in global 9291 // scope. 9292 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 9293 return true; 9294 9295 // C++ [basic.stc.dynamic.deallocation]p2: 9296 // Each deallocation function shall return void and its first parameter 9297 // shall be void*. 9298 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 9299 SemaRef.Context.VoidPtrTy, 9300 diag::err_operator_delete_dependent_param_type, 9301 diag::err_operator_delete_param_type)) 9302 return true; 9303 9304 return false; 9305} 9306 9307/// CheckOverloadedOperatorDeclaration - Check whether the declaration 9308/// of this overloaded operator is well-formed. If so, returns false; 9309/// otherwise, emits appropriate diagnostics and returns true. 9310bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 9311 assert(FnDecl && FnDecl->isOverloadedOperator() && 9312 "Expected an overloaded operator declaration"); 9313 9314 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 9315 9316 // C++ [over.oper]p5: 9317 // The allocation and deallocation functions, operator new, 9318 // operator new[], operator delete and operator delete[], are 9319 // described completely in 3.7.3. The attributes and restrictions 9320 // found in the rest of this subclause do not apply to them unless 9321 // explicitly stated in 3.7.3. 9322 if (Op == OO_Delete || Op == OO_Array_Delete) 9323 return CheckOperatorDeleteDeclaration(*this, FnDecl); 9324 9325 if (Op == OO_New || Op == OO_Array_New) 9326 return CheckOperatorNewDeclaration(*this, FnDecl); 9327 9328 // C++ [over.oper]p6: 9329 // An operator function shall either be a non-static member 9330 // function or be a non-member function and have at least one 9331 // parameter whose type is a class, a reference to a class, an 9332 // enumeration, or a reference to an enumeration. 9333 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 9334 if (MethodDecl->isStatic()) 9335 return Diag(FnDecl->getLocation(), 9336 diag::err_operator_overload_static) << FnDecl->getDeclName(); 9337 } else { 9338 bool ClassOrEnumParam = false; 9339 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 9340 ParamEnd = FnDecl->param_end(); 9341 Param != ParamEnd; ++Param) { 9342 QualType ParamType = (*Param)->getType().getNonReferenceType(); 9343 if (ParamType->isDependentType() || ParamType->isRecordType() || 9344 ParamType->isEnumeralType()) { 9345 ClassOrEnumParam = true; 9346 break; 9347 } 9348 } 9349 9350 if (!ClassOrEnumParam) 9351 return Diag(FnDecl->getLocation(), 9352 diag::err_operator_overload_needs_class_or_enum) 9353 << FnDecl->getDeclName(); 9354 } 9355 9356 // C++ [over.oper]p8: 9357 // An operator function cannot have default arguments (8.3.6), 9358 // except where explicitly stated below. 9359 // 9360 // Only the function-call operator allows default arguments 9361 // (C++ [over.call]p1). 9362 if (Op != OO_Call) { 9363 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(); 9364 Param != FnDecl->param_end(); ++Param) { 9365 if ((*Param)->hasDefaultArg()) 9366 return Diag((*Param)->getLocation(), 9367 diag::err_operator_overload_default_arg) 9368 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange(); 9369 } 9370 } 9371 9372 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 9373 { false, false, false } 9374#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 9375 , { Unary, Binary, MemberOnly } 9376#include "clang/Basic/OperatorKinds.def" 9377 }; 9378 9379 bool CanBeUnaryOperator = OperatorUses[Op][0]; 9380 bool CanBeBinaryOperator = OperatorUses[Op][1]; 9381 bool MustBeMemberOperator = OperatorUses[Op][2]; 9382 9383 // C++ [over.oper]p8: 9384 // [...] Operator functions cannot have more or fewer parameters 9385 // than the number required for the corresponding operator, as 9386 // described in the rest of this subclause. 9387 unsigned NumParams = FnDecl->getNumParams() 9388 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 9389 if (Op != OO_Call && 9390 ((NumParams == 1 && !CanBeUnaryOperator) || 9391 (NumParams == 2 && !CanBeBinaryOperator) || 9392 (NumParams < 1) || (NumParams > 2))) { 9393 // We have the wrong number of parameters. 9394 unsigned ErrorKind; 9395 if (CanBeUnaryOperator && CanBeBinaryOperator) { 9396 ErrorKind = 2; // 2 -> unary or binary. 9397 } else if (CanBeUnaryOperator) { 9398 ErrorKind = 0; // 0 -> unary 9399 } else { 9400 assert(CanBeBinaryOperator && 9401 "All non-call overloaded operators are unary or binary!"); 9402 ErrorKind = 1; // 1 -> binary 9403 } 9404 9405 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 9406 << FnDecl->getDeclName() << NumParams << ErrorKind; 9407 } 9408 9409 // Overloaded operators other than operator() cannot be variadic. 9410 if (Op != OO_Call && 9411 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 9412 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 9413 << FnDecl->getDeclName(); 9414 } 9415 9416 // Some operators must be non-static member functions. 9417 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 9418 return Diag(FnDecl->getLocation(), 9419 diag::err_operator_overload_must_be_member) 9420 << FnDecl->getDeclName(); 9421 } 9422 9423 // C++ [over.inc]p1: 9424 // The user-defined function called operator++ implements the 9425 // prefix and postfix ++ operator. If this function is a member 9426 // function with no parameters, or a non-member function with one 9427 // parameter of class or enumeration type, it defines the prefix 9428 // increment operator ++ for objects of that type. If the function 9429 // is a member function with one parameter (which shall be of type 9430 // int) or a non-member function with two parameters (the second 9431 // of which shall be of type int), it defines the postfix 9432 // increment operator ++ for objects of that type. 9433 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 9434 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 9435 bool ParamIsInt = false; 9436 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>()) 9437 ParamIsInt = BT->getKind() == BuiltinType::Int; 9438 9439 if (!ParamIsInt) 9440 return Diag(LastParam->getLocation(), 9441 diag::err_operator_overload_post_incdec_must_be_int) 9442 << LastParam->getType() << (Op == OO_MinusMinus); 9443 } 9444 9445 return false; 9446} 9447 9448/// CheckLiteralOperatorDeclaration - Check whether the declaration 9449/// of this literal operator function is well-formed. If so, returns 9450/// false; otherwise, emits appropriate diagnostics and returns true. 9451bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 9452 DeclContext *DC = FnDecl->getDeclContext(); 9453 Decl::Kind Kind = DC->getDeclKind(); 9454 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace && 9455 Kind != Decl::LinkageSpec) { 9456 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 9457 << FnDecl->getDeclName(); 9458 return true; 9459 } 9460 9461 bool Valid = false; 9462 9463 // template <char...> type operator "" name() is the only valid template 9464 // signature, and the only valid signature with no parameters. 9465 if (FnDecl->param_size() == 0) { 9466 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) { 9467 // Must have only one template parameter 9468 TemplateParameterList *Params = TpDecl->getTemplateParameters(); 9469 if (Params->size() == 1) { 9470 NonTypeTemplateParmDecl *PmDecl = 9471 cast<NonTypeTemplateParmDecl>(Params->getParam(0)); 9472 9473 // The template parameter must be a char parameter pack. 9474 if (PmDecl && PmDecl->isTemplateParameterPack() && 9475 Context.hasSameType(PmDecl->getType(), Context.CharTy)) 9476 Valid = true; 9477 } 9478 } 9479 } else { 9480 // Check the first parameter 9481 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 9482 9483 QualType T = (*Param)->getType(); 9484 9485 // unsigned long long int, long double, and any character type are allowed 9486 // as the only parameters. 9487 if (Context.hasSameType(T, Context.UnsignedLongLongTy) || 9488 Context.hasSameType(T, Context.LongDoubleTy) || 9489 Context.hasSameType(T, Context.CharTy) || 9490 Context.hasSameType(T, Context.WCharTy) || 9491 Context.hasSameType(T, Context.Char16Ty) || 9492 Context.hasSameType(T, Context.Char32Ty)) { 9493 if (++Param == FnDecl->param_end()) 9494 Valid = true; 9495 goto FinishedParams; 9496 } 9497 9498 // Otherwise it must be a pointer to const; let's strip those qualifiers. 9499 const PointerType *PT = T->getAs<PointerType>(); 9500 if (!PT) 9501 goto FinishedParams; 9502 T = PT->getPointeeType(); 9503 if (!T.isConstQualified()) 9504 goto FinishedParams; 9505 T = T.getUnqualifiedType(); 9506 9507 // Move on to the second parameter; 9508 ++Param; 9509 9510 // If there is no second parameter, the first must be a const char * 9511 if (Param == FnDecl->param_end()) { 9512 if (Context.hasSameType(T, Context.CharTy)) 9513 Valid = true; 9514 goto FinishedParams; 9515 } 9516 9517 // const char *, const wchar_t*, const char16_t*, and const char32_t* 9518 // are allowed as the first parameter to a two-parameter function 9519 if (!(Context.hasSameType(T, Context.CharTy) || 9520 Context.hasSameType(T, Context.WCharTy) || 9521 Context.hasSameType(T, Context.Char16Ty) || 9522 Context.hasSameType(T, Context.Char32Ty))) 9523 goto FinishedParams; 9524 9525 // The second and final parameter must be an std::size_t 9526 T = (*Param)->getType().getUnqualifiedType(); 9527 if (Context.hasSameType(T, Context.getSizeType()) && 9528 ++Param == FnDecl->param_end()) 9529 Valid = true; 9530 } 9531 9532 // FIXME: This diagnostic is absolutely terrible. 9533FinishedParams: 9534 if (!Valid) { 9535 Diag(FnDecl->getLocation(), diag::err_literal_operator_params) 9536 << FnDecl->getDeclName(); 9537 return true; 9538 } 9539 9540 StringRef LiteralName 9541 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 9542 if (LiteralName[0] != '_') { 9543 // C++0x [usrlit.suffix]p1: 9544 // Literal suffix identifiers that do not start with an underscore are 9545 // reserved for future standardization. 9546 bool IsHexFloat = true; 9547 if (LiteralName.size() > 1 && 9548 (LiteralName[0] == 'P' || LiteralName[0] == 'p')) { 9549 for (unsigned I = 1, N = LiteralName.size(); I < N; ++I) { 9550 if (!isdigit(LiteralName[I])) { 9551 IsHexFloat = false; 9552 break; 9553 } 9554 } 9555 } 9556 9557 if (IsHexFloat) 9558 Diag(FnDecl->getLocation(), diag::warn_user_literal_hexfloat) 9559 << LiteralName; 9560 else 9561 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved); 9562 } 9563 9564 return false; 9565} 9566 9567/// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 9568/// linkage specification, including the language and (if present) 9569/// the '{'. ExternLoc is the location of the 'extern', LangLoc is 9570/// the location of the language string literal, which is provided 9571/// by Lang/StrSize. LBraceLoc, if valid, provides the location of 9572/// the '{' brace. Otherwise, this linkage specification does not 9573/// have any braces. 9574Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 9575 SourceLocation LangLoc, 9576 StringRef Lang, 9577 SourceLocation LBraceLoc) { 9578 LinkageSpecDecl::LanguageIDs Language; 9579 if (Lang == "\"C\"") 9580 Language = LinkageSpecDecl::lang_c; 9581 else if (Lang == "\"C++\"") 9582 Language = LinkageSpecDecl::lang_cxx; 9583 else { 9584 Diag(LangLoc, diag::err_bad_language); 9585 return 0; 9586 } 9587 9588 // FIXME: Add all the various semantics of linkage specifications 9589 9590 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, 9591 ExternLoc, LangLoc, Language); 9592 CurContext->addDecl(D); 9593 PushDeclContext(S, D); 9594 return D; 9595} 9596 9597/// ActOnFinishLinkageSpecification - Complete the definition of 9598/// the C++ linkage specification LinkageSpec. If RBraceLoc is 9599/// valid, it's the position of the closing '}' brace in a linkage 9600/// specification that uses braces. 9601Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 9602 Decl *LinkageSpec, 9603 SourceLocation RBraceLoc) { 9604 if (LinkageSpec) { 9605 if (RBraceLoc.isValid()) { 9606 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 9607 LSDecl->setRBraceLoc(RBraceLoc); 9608 } 9609 PopDeclContext(); 9610 } 9611 return LinkageSpec; 9612} 9613 9614/// \brief Perform semantic analysis for the variable declaration that 9615/// occurs within a C++ catch clause, returning the newly-created 9616/// variable. 9617VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 9618 TypeSourceInfo *TInfo, 9619 SourceLocation StartLoc, 9620 SourceLocation Loc, 9621 IdentifierInfo *Name) { 9622 bool Invalid = false; 9623 QualType ExDeclType = TInfo->getType(); 9624 9625 // Arrays and functions decay. 9626 if (ExDeclType->isArrayType()) 9627 ExDeclType = Context.getArrayDecayedType(ExDeclType); 9628 else if (ExDeclType->isFunctionType()) 9629 ExDeclType = Context.getPointerType(ExDeclType); 9630 9631 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 9632 // The exception-declaration shall not denote a pointer or reference to an 9633 // incomplete type, other than [cv] void*. 9634 // N2844 forbids rvalue references. 9635 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 9636 Diag(Loc, diag::err_catch_rvalue_ref); 9637 Invalid = true; 9638 } 9639 9640 QualType BaseType = ExDeclType; 9641 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 9642 unsigned DK = diag::err_catch_incomplete; 9643 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 9644 BaseType = Ptr->getPointeeType(); 9645 Mode = 1; 9646 DK = diag::err_catch_incomplete_ptr; 9647 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 9648 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 9649 BaseType = Ref->getPointeeType(); 9650 Mode = 2; 9651 DK = diag::err_catch_incomplete_ref; 9652 } 9653 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 9654 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 9655 Invalid = true; 9656 9657 if (!Invalid && !ExDeclType->isDependentType() && 9658 RequireNonAbstractType(Loc, ExDeclType, 9659 diag::err_abstract_type_in_decl, 9660 AbstractVariableType)) 9661 Invalid = true; 9662 9663 // Only the non-fragile NeXT runtime currently supports C++ catches 9664 // of ObjC types, and no runtime supports catching ObjC types by value. 9665 if (!Invalid && getLangOptions().ObjC1) { 9666 QualType T = ExDeclType; 9667 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 9668 T = RT->getPointeeType(); 9669 9670 if (T->isObjCObjectType()) { 9671 Diag(Loc, diag::err_objc_object_catch); 9672 Invalid = true; 9673 } else if (T->isObjCObjectPointerType()) { 9674 if (!getLangOptions().ObjCNonFragileABI) 9675 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 9676 } 9677 } 9678 9679 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 9680 ExDeclType, TInfo, SC_None, SC_None); 9681 ExDecl->setExceptionVariable(true); 9682 9683 // In ARC, infer 'retaining' for variables of retainable type. 9684 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 9685 Invalid = true; 9686 9687 if (!Invalid && !ExDeclType->isDependentType()) { 9688 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 9689 // C++ [except.handle]p16: 9690 // The object declared in an exception-declaration or, if the 9691 // exception-declaration does not specify a name, a temporary (12.2) is 9692 // copy-initialized (8.5) from the exception object. [...] 9693 // The object is destroyed when the handler exits, after the destruction 9694 // of any automatic objects initialized within the handler. 9695 // 9696 // We just pretend to initialize the object with itself, then make sure 9697 // it can be destroyed later. 9698 QualType initType = ExDeclType; 9699 9700 InitializedEntity entity = 9701 InitializedEntity::InitializeVariable(ExDecl); 9702 InitializationKind initKind = 9703 InitializationKind::CreateCopy(Loc, SourceLocation()); 9704 9705 Expr *opaqueValue = 9706 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 9707 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1); 9708 ExprResult result = sequence.Perform(*this, entity, initKind, 9709 MultiExprArg(&opaqueValue, 1)); 9710 if (result.isInvalid()) 9711 Invalid = true; 9712 else { 9713 // If the constructor used was non-trivial, set this as the 9714 // "initializer". 9715 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take()); 9716 if (!construct->getConstructor()->isTrivial()) { 9717 Expr *init = MaybeCreateExprWithCleanups(construct); 9718 ExDecl->setInit(init); 9719 } 9720 9721 // And make sure it's destructable. 9722 FinalizeVarWithDestructor(ExDecl, recordType); 9723 } 9724 } 9725 } 9726 9727 if (Invalid) 9728 ExDecl->setInvalidDecl(); 9729 9730 return ExDecl; 9731} 9732 9733/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 9734/// handler. 9735Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 9736 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 9737 bool Invalid = D.isInvalidType(); 9738 9739 // Check for unexpanded parameter packs. 9740 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 9741 UPPC_ExceptionType)) { 9742 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 9743 D.getIdentifierLoc()); 9744 Invalid = true; 9745 } 9746 9747 IdentifierInfo *II = D.getIdentifier(); 9748 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 9749 LookupOrdinaryName, 9750 ForRedeclaration)) { 9751 // The scope should be freshly made just for us. There is just no way 9752 // it contains any previous declaration. 9753 assert(!S->isDeclScope(PrevDecl)); 9754 if (PrevDecl->isTemplateParameter()) { 9755 // Maybe we will complain about the shadowed template parameter. 9756 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 9757 PrevDecl = 0; 9758 } 9759 } 9760 9761 if (D.getCXXScopeSpec().isSet() && !Invalid) { 9762 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 9763 << D.getCXXScopeSpec().getRange(); 9764 Invalid = true; 9765 } 9766 9767 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 9768 D.getSourceRange().getBegin(), 9769 D.getIdentifierLoc(), 9770 D.getIdentifier()); 9771 if (Invalid) 9772 ExDecl->setInvalidDecl(); 9773 9774 // Add the exception declaration into this scope. 9775 if (II) 9776 PushOnScopeChains(ExDecl, S); 9777 else 9778 CurContext->addDecl(ExDecl); 9779 9780 ProcessDeclAttributes(S, ExDecl, D); 9781 return ExDecl; 9782} 9783 9784Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 9785 Expr *AssertExpr, 9786 Expr *AssertMessageExpr_, 9787 SourceLocation RParenLoc) { 9788 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_); 9789 9790 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) { 9791 // In a static_assert-declaration, the constant-expression shall be a 9792 // constant expression that can be contextually converted to bool. 9793 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 9794 if (Converted.isInvalid()) 9795 return 0; 9796 9797 llvm::APSInt Cond; 9798 if (VerifyIntegerConstantExpression(Converted.get(), &Cond, 9799 PDiag(diag::err_static_assert_expression_is_not_constant), 9800 /*AllowFold=*/false).isInvalid()) 9801 return 0; 9802 9803 if (!Cond) 9804 Diag(StaticAssertLoc, diag::err_static_assert_failed) 9805 << AssertMessage->getString() << AssertExpr->getSourceRange(); 9806 } 9807 9808 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 9809 return 0; 9810 9811 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 9812 AssertExpr, AssertMessage, RParenLoc); 9813 9814 CurContext->addDecl(Decl); 9815 return Decl; 9816} 9817 9818/// \brief Perform semantic analysis of the given friend type declaration. 9819/// 9820/// \returns A friend declaration that. 9821FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation Loc, 9822 SourceLocation FriendLoc, 9823 TypeSourceInfo *TSInfo) { 9824 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 9825 9826 QualType T = TSInfo->getType(); 9827 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 9828 9829 // C++03 [class.friend]p2: 9830 // An elaborated-type-specifier shall be used in a friend declaration 9831 // for a class.* 9832 // 9833 // * The class-key of the elaborated-type-specifier is required. 9834 if (!ActiveTemplateInstantiations.empty()) { 9835 // Do not complain about the form of friend template types during 9836 // template instantiation; we will already have complained when the 9837 // template was declared. 9838 } else if (!T->isElaboratedTypeSpecifier()) { 9839 // If we evaluated the type to a record type, suggest putting 9840 // a tag in front. 9841 if (const RecordType *RT = T->getAs<RecordType>()) { 9842 RecordDecl *RD = RT->getDecl(); 9843 9844 std::string InsertionText = std::string(" ") + RD->getKindName(); 9845 9846 Diag(TypeRange.getBegin(), 9847 getLangOptions().CPlusPlus0x ? 9848 diag::warn_cxx98_compat_unelaborated_friend_type : 9849 diag::ext_unelaborated_friend_type) 9850 << (unsigned) RD->getTagKind() 9851 << T 9852 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc), 9853 InsertionText); 9854 } else { 9855 Diag(FriendLoc, 9856 getLangOptions().CPlusPlus0x ? 9857 diag::warn_cxx98_compat_nonclass_type_friend : 9858 diag::ext_nonclass_type_friend) 9859 << T 9860 << SourceRange(FriendLoc, TypeRange.getEnd()); 9861 } 9862 } else if (T->getAs<EnumType>()) { 9863 Diag(FriendLoc, 9864 getLangOptions().CPlusPlus0x ? 9865 diag::warn_cxx98_compat_enum_friend : 9866 diag::ext_enum_friend) 9867 << T 9868 << SourceRange(FriendLoc, TypeRange.getEnd()); 9869 } 9870 9871 // C++0x [class.friend]p3: 9872 // If the type specifier in a friend declaration designates a (possibly 9873 // cv-qualified) class type, that class is declared as a friend; otherwise, 9874 // the friend declaration is ignored. 9875 9876 // FIXME: C++0x has some syntactic restrictions on friend type declarations 9877 // in [class.friend]p3 that we do not implement. 9878 9879 return FriendDecl::Create(Context, CurContext, Loc, TSInfo, FriendLoc); 9880} 9881 9882/// Handle a friend tag declaration where the scope specifier was 9883/// templated. 9884Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 9885 unsigned TagSpec, SourceLocation TagLoc, 9886 CXXScopeSpec &SS, 9887 IdentifierInfo *Name, SourceLocation NameLoc, 9888 AttributeList *Attr, 9889 MultiTemplateParamsArg TempParamLists) { 9890 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 9891 9892 bool isExplicitSpecialization = false; 9893 bool Invalid = false; 9894 9895 if (TemplateParameterList *TemplateParams 9896 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS, 9897 TempParamLists.get(), 9898 TempParamLists.size(), 9899 /*friend*/ true, 9900 isExplicitSpecialization, 9901 Invalid)) { 9902 if (TemplateParams->size() > 0) { 9903 // This is a declaration of a class template. 9904 if (Invalid) 9905 return 0; 9906 9907 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, 9908 SS, Name, NameLoc, Attr, 9909 TemplateParams, AS_public, 9910 /*ModulePrivateLoc=*/SourceLocation(), 9911 TempParamLists.size() - 1, 9912 (TemplateParameterList**) TempParamLists.release()).take(); 9913 } else { 9914 // The "template<>" header is extraneous. 9915 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 9916 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 9917 isExplicitSpecialization = true; 9918 } 9919 } 9920 9921 if (Invalid) return 0; 9922 9923 bool isAllExplicitSpecializations = true; 9924 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 9925 if (TempParamLists.get()[I]->size()) { 9926 isAllExplicitSpecializations = false; 9927 break; 9928 } 9929 } 9930 9931 // FIXME: don't ignore attributes. 9932 9933 // If it's explicit specializations all the way down, just forget 9934 // about the template header and build an appropriate non-templated 9935 // friend. TODO: for source fidelity, remember the headers. 9936 if (isAllExplicitSpecializations) { 9937 if (SS.isEmpty()) { 9938 bool Owned = false; 9939 bool IsDependent = false; 9940 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 9941 Attr, AS_public, 9942 /*ModulePrivateLoc=*/SourceLocation(), 9943 MultiTemplateParamsArg(), Owned, IsDependent, 9944 /*ScopedEnumKWLoc=*/SourceLocation(), 9945 /*ScopedEnumUsesClassTag=*/false, 9946 /*UnderlyingType=*/TypeResult()); 9947 } 9948 9949 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 9950 ElaboratedTypeKeyword Keyword 9951 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 9952 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 9953 *Name, NameLoc); 9954 if (T.isNull()) 9955 return 0; 9956 9957 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 9958 if (isa<DependentNameType>(T)) { 9959 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc()); 9960 TL.setElaboratedKeywordLoc(TagLoc); 9961 TL.setQualifierLoc(QualifierLoc); 9962 TL.setNameLoc(NameLoc); 9963 } else { 9964 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc()); 9965 TL.setElaboratedKeywordLoc(TagLoc); 9966 TL.setQualifierLoc(QualifierLoc); 9967 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc); 9968 } 9969 9970 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 9971 TSI, FriendLoc); 9972 Friend->setAccess(AS_public); 9973 CurContext->addDecl(Friend); 9974 return Friend; 9975 } 9976 9977 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 9978 9979 9980 9981 // Handle the case of a templated-scope friend class. e.g. 9982 // template <class T> class A<T>::B; 9983 // FIXME: we don't support these right now. 9984 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 9985 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 9986 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 9987 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc()); 9988 TL.setElaboratedKeywordLoc(TagLoc); 9989 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 9990 TL.setNameLoc(NameLoc); 9991 9992 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 9993 TSI, FriendLoc); 9994 Friend->setAccess(AS_public); 9995 Friend->setUnsupportedFriend(true); 9996 CurContext->addDecl(Friend); 9997 return Friend; 9998} 9999 10000 10001/// Handle a friend type declaration. This works in tandem with 10002/// ActOnTag. 10003/// 10004/// Notes on friend class templates: 10005/// 10006/// We generally treat friend class declarations as if they were 10007/// declaring a class. So, for example, the elaborated type specifier 10008/// in a friend declaration is required to obey the restrictions of a 10009/// class-head (i.e. no typedefs in the scope chain), template 10010/// parameters are required to match up with simple template-ids, &c. 10011/// However, unlike when declaring a template specialization, it's 10012/// okay to refer to a template specialization without an empty 10013/// template parameter declaration, e.g. 10014/// friend class A<T>::B<unsigned>; 10015/// We permit this as a special case; if there are any template 10016/// parameters present at all, require proper matching, i.e. 10017/// template <> template <class T> friend class A<int>::B; 10018Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 10019 MultiTemplateParamsArg TempParams) { 10020 SourceLocation Loc = DS.getSourceRange().getBegin(); 10021 10022 assert(DS.isFriendSpecified()); 10023 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 10024 10025 // Try to convert the decl specifier to a type. This works for 10026 // friend templates because ActOnTag never produces a ClassTemplateDecl 10027 // for a TUK_Friend. 10028 Declarator TheDeclarator(DS, Declarator::MemberContext); 10029 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 10030 QualType T = TSI->getType(); 10031 if (TheDeclarator.isInvalidType()) 10032 return 0; 10033 10034 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 10035 return 0; 10036 10037 // This is definitely an error in C++98. It's probably meant to 10038 // be forbidden in C++0x, too, but the specification is just 10039 // poorly written. 10040 // 10041 // The problem is with declarations like the following: 10042 // template <T> friend A<T>::foo; 10043 // where deciding whether a class C is a friend or not now hinges 10044 // on whether there exists an instantiation of A that causes 10045 // 'foo' to equal C. There are restrictions on class-heads 10046 // (which we declare (by fiat) elaborated friend declarations to 10047 // be) that makes this tractable. 10048 // 10049 // FIXME: handle "template <> friend class A<T>;", which 10050 // is possibly well-formed? Who even knows? 10051 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 10052 Diag(Loc, diag::err_tagless_friend_type_template) 10053 << DS.getSourceRange(); 10054 return 0; 10055 } 10056 10057 // C++98 [class.friend]p1: A friend of a class is a function 10058 // or class that is not a member of the class . . . 10059 // This is fixed in DR77, which just barely didn't make the C++03 10060 // deadline. It's also a very silly restriction that seriously 10061 // affects inner classes and which nobody else seems to implement; 10062 // thus we never diagnose it, not even in -pedantic. 10063 // 10064 // But note that we could warn about it: it's always useless to 10065 // friend one of your own members (it's not, however, worthless to 10066 // friend a member of an arbitrary specialization of your template). 10067 10068 Decl *D; 10069 if (unsigned NumTempParamLists = TempParams.size()) 10070 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 10071 NumTempParamLists, 10072 TempParams.release(), 10073 TSI, 10074 DS.getFriendSpecLoc()); 10075 else 10076 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 10077 10078 if (!D) 10079 return 0; 10080 10081 D->setAccess(AS_public); 10082 CurContext->addDecl(D); 10083 10084 return D; 10085} 10086 10087Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 10088 MultiTemplateParamsArg TemplateParams) { 10089 const DeclSpec &DS = D.getDeclSpec(); 10090 10091 assert(DS.isFriendSpecified()); 10092 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 10093 10094 SourceLocation Loc = D.getIdentifierLoc(); 10095 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 10096 10097 // C++ [class.friend]p1 10098 // A friend of a class is a function or class.... 10099 // Note that this sees through typedefs, which is intended. 10100 // It *doesn't* see through dependent types, which is correct 10101 // according to [temp.arg.type]p3: 10102 // If a declaration acquires a function type through a 10103 // type dependent on a template-parameter and this causes 10104 // a declaration that does not use the syntactic form of a 10105 // function declarator to have a function type, the program 10106 // is ill-formed. 10107 if (!TInfo->getType()->isFunctionType()) { 10108 Diag(Loc, diag::err_unexpected_friend); 10109 10110 // It might be worthwhile to try to recover by creating an 10111 // appropriate declaration. 10112 return 0; 10113 } 10114 10115 // C++ [namespace.memdef]p3 10116 // - If a friend declaration in a non-local class first declares a 10117 // class or function, the friend class or function is a member 10118 // of the innermost enclosing namespace. 10119 // - The name of the friend is not found by simple name lookup 10120 // until a matching declaration is provided in that namespace 10121 // scope (either before or after the class declaration granting 10122 // friendship). 10123 // - If a friend function is called, its name may be found by the 10124 // name lookup that considers functions from namespaces and 10125 // classes associated with the types of the function arguments. 10126 // - When looking for a prior declaration of a class or a function 10127 // declared as a friend, scopes outside the innermost enclosing 10128 // namespace scope are not considered. 10129 10130 CXXScopeSpec &SS = D.getCXXScopeSpec(); 10131 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 10132 DeclarationName Name = NameInfo.getName(); 10133 assert(Name); 10134 10135 // Check for unexpanded parameter packs. 10136 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 10137 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 10138 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 10139 return 0; 10140 10141 // The context we found the declaration in, or in which we should 10142 // create the declaration. 10143 DeclContext *DC; 10144 Scope *DCScope = S; 10145 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 10146 ForRedeclaration); 10147 10148 // FIXME: there are different rules in local classes 10149 10150 // There are four cases here. 10151 // - There's no scope specifier, in which case we just go to the 10152 // appropriate scope and look for a function or function template 10153 // there as appropriate. 10154 // Recover from invalid scope qualifiers as if they just weren't there. 10155 if (SS.isInvalid() || !SS.isSet()) { 10156 // C++0x [namespace.memdef]p3: 10157 // If the name in a friend declaration is neither qualified nor 10158 // a template-id and the declaration is a function or an 10159 // elaborated-type-specifier, the lookup to determine whether 10160 // the entity has been previously declared shall not consider 10161 // any scopes outside the innermost enclosing namespace. 10162 // C++0x [class.friend]p11: 10163 // If a friend declaration appears in a local class and the name 10164 // specified is an unqualified name, a prior declaration is 10165 // looked up without considering scopes that are outside the 10166 // innermost enclosing non-class scope. For a friend function 10167 // declaration, if there is no prior declaration, the program is 10168 // ill-formed. 10169 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass(); 10170 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 10171 10172 // Find the appropriate context according to the above. 10173 DC = CurContext; 10174 while (true) { 10175 // Skip class contexts. If someone can cite chapter and verse 10176 // for this behavior, that would be nice --- it's what GCC and 10177 // EDG do, and it seems like a reasonable intent, but the spec 10178 // really only says that checks for unqualified existing 10179 // declarations should stop at the nearest enclosing namespace, 10180 // not that they should only consider the nearest enclosing 10181 // namespace. 10182 while (DC->isRecord()) 10183 DC = DC->getParent(); 10184 10185 LookupQualifiedName(Previous, DC); 10186 10187 // TODO: decide what we think about using declarations. 10188 if (isLocal || !Previous.empty()) 10189 break; 10190 10191 if (isTemplateId) { 10192 if (isa<TranslationUnitDecl>(DC)) break; 10193 } else { 10194 if (DC->isFileContext()) break; 10195 } 10196 DC = DC->getParent(); 10197 } 10198 10199 // C++ [class.friend]p1: A friend of a class is a function or 10200 // class that is not a member of the class . . . 10201 // C++11 changes this for both friend types and functions. 10202 // Most C++ 98 compilers do seem to give an error here, so 10203 // we do, too. 10204 if (!Previous.empty() && DC->Equals(CurContext)) 10205 Diag(DS.getFriendSpecLoc(), 10206 getLangOptions().CPlusPlus0x ? 10207 diag::warn_cxx98_compat_friend_is_member : 10208 diag::err_friend_is_member); 10209 10210 DCScope = getScopeForDeclContext(S, DC); 10211 10212 // C++ [class.friend]p6: 10213 // A function can be defined in a friend declaration of a class if and 10214 // only if the class is a non-local class (9.8), the function name is 10215 // unqualified, and the function has namespace scope. 10216 if (isLocal && D.isFunctionDefinition()) { 10217 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 10218 } 10219 10220 // - There's a non-dependent scope specifier, in which case we 10221 // compute it and do a previous lookup there for a function 10222 // or function template. 10223 } else if (!SS.getScopeRep()->isDependent()) { 10224 DC = computeDeclContext(SS); 10225 if (!DC) return 0; 10226 10227 if (RequireCompleteDeclContext(SS, DC)) return 0; 10228 10229 LookupQualifiedName(Previous, DC); 10230 10231 // Ignore things found implicitly in the wrong scope. 10232 // TODO: better diagnostics for this case. Suggesting the right 10233 // qualified scope would be nice... 10234 LookupResult::Filter F = Previous.makeFilter(); 10235 while (F.hasNext()) { 10236 NamedDecl *D = F.next(); 10237 if (!DC->InEnclosingNamespaceSetOf( 10238 D->getDeclContext()->getRedeclContext())) 10239 F.erase(); 10240 } 10241 F.done(); 10242 10243 if (Previous.empty()) { 10244 D.setInvalidType(); 10245 Diag(Loc, diag::err_qualified_friend_not_found) 10246 << Name << TInfo->getType(); 10247 return 0; 10248 } 10249 10250 // C++ [class.friend]p1: A friend of a class is a function or 10251 // class that is not a member of the class . . . 10252 if (DC->Equals(CurContext)) 10253 Diag(DS.getFriendSpecLoc(), 10254 getLangOptions().CPlusPlus0x ? 10255 diag::warn_cxx98_compat_friend_is_member : 10256 diag::err_friend_is_member); 10257 10258 if (D.isFunctionDefinition()) { 10259 // C++ [class.friend]p6: 10260 // A function can be defined in a friend declaration of a class if and 10261 // only if the class is a non-local class (9.8), the function name is 10262 // unqualified, and the function has namespace scope. 10263 SemaDiagnosticBuilder DB 10264 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 10265 10266 DB << SS.getScopeRep(); 10267 if (DC->isFileContext()) 10268 DB << FixItHint::CreateRemoval(SS.getRange()); 10269 SS.clear(); 10270 } 10271 10272 // - There's a scope specifier that does not match any template 10273 // parameter lists, in which case we use some arbitrary context, 10274 // create a method or method template, and wait for instantiation. 10275 // - There's a scope specifier that does match some template 10276 // parameter lists, which we don't handle right now. 10277 } else { 10278 if (D.isFunctionDefinition()) { 10279 // C++ [class.friend]p6: 10280 // A function can be defined in a friend declaration of a class if and 10281 // only if the class is a non-local class (9.8), the function name is 10282 // unqualified, and the function has namespace scope. 10283 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 10284 << SS.getScopeRep(); 10285 } 10286 10287 DC = CurContext; 10288 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 10289 } 10290 10291 if (!DC->isRecord()) { 10292 // This implies that it has to be an operator or function. 10293 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName || 10294 D.getName().getKind() == UnqualifiedId::IK_DestructorName || 10295 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) { 10296 Diag(Loc, diag::err_introducing_special_friend) << 10297 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 : 10298 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2); 10299 return 0; 10300 } 10301 } 10302 10303 // FIXME: This is an egregious hack to cope with cases where the scope stack 10304 // does not contain the declaration context, i.e., in an out-of-line 10305 // definition of a class. 10306 Scope FakeDCScope(S, Scope::DeclScope, Diags); 10307 if (!DCScope) { 10308 FakeDCScope.setEntity(DC); 10309 DCScope = &FakeDCScope; 10310 } 10311 10312 bool AddToScope = true; 10313 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 10314 move(TemplateParams), AddToScope); 10315 if (!ND) return 0; 10316 10317 assert(ND->getDeclContext() == DC); 10318 assert(ND->getLexicalDeclContext() == CurContext); 10319 10320 // Add the function declaration to the appropriate lookup tables, 10321 // adjusting the redeclarations list as necessary. We don't 10322 // want to do this yet if the friending class is dependent. 10323 // 10324 // Also update the scope-based lookup if the target context's 10325 // lookup context is in lexical scope. 10326 if (!CurContext->isDependentContext()) { 10327 DC = DC->getRedeclContext(); 10328 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false); 10329 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 10330 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 10331 } 10332 10333 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 10334 D.getIdentifierLoc(), ND, 10335 DS.getFriendSpecLoc()); 10336 FrD->setAccess(AS_public); 10337 CurContext->addDecl(FrD); 10338 10339 if (ND->isInvalidDecl()) 10340 FrD->setInvalidDecl(); 10341 else { 10342 FunctionDecl *FD; 10343 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 10344 FD = FTD->getTemplatedDecl(); 10345 else 10346 FD = cast<FunctionDecl>(ND); 10347 10348 // Mark templated-scope function declarations as unsupported. 10349 if (FD->getNumTemplateParameterLists()) 10350 FrD->setUnsupportedFriend(true); 10351 } 10352 10353 return ND; 10354} 10355 10356void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 10357 AdjustDeclIfTemplate(Dcl); 10358 10359 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl); 10360 if (!Fn) { 10361 Diag(DelLoc, diag::err_deleted_non_function); 10362 return; 10363 } 10364 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 10365 Diag(DelLoc, diag::err_deleted_decl_not_first); 10366 Diag(Prev->getLocation(), diag::note_previous_declaration); 10367 // If the declaration wasn't the first, we delete the function anyway for 10368 // recovery. 10369 } 10370 Fn->setDeletedAsWritten(); 10371} 10372 10373void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 10374 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl); 10375 10376 if (MD) { 10377 if (MD->getParent()->isDependentType()) { 10378 MD->setDefaulted(); 10379 MD->setExplicitlyDefaulted(); 10380 return; 10381 } 10382 10383 CXXSpecialMember Member = getSpecialMember(MD); 10384 if (Member == CXXInvalid) { 10385 Diag(DefaultLoc, diag::err_default_special_members); 10386 return; 10387 } 10388 10389 MD->setDefaulted(); 10390 MD->setExplicitlyDefaulted(); 10391 10392 // If this definition appears within the record, do the checking when 10393 // the record is complete. 10394 const FunctionDecl *Primary = MD; 10395 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate) 10396 // Find the uninstantiated declaration that actually had the '= default' 10397 // on it. 10398 MD->getTemplateInstantiationPattern()->isDefined(Primary); 10399 10400 if (Primary == Primary->getCanonicalDecl()) 10401 return; 10402 10403 switch (Member) { 10404 case CXXDefaultConstructor: { 10405 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD); 10406 CheckExplicitlyDefaultedDefaultConstructor(CD); 10407 if (!CD->isInvalidDecl()) 10408 DefineImplicitDefaultConstructor(DefaultLoc, CD); 10409 break; 10410 } 10411 10412 case CXXCopyConstructor: { 10413 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD); 10414 CheckExplicitlyDefaultedCopyConstructor(CD); 10415 if (!CD->isInvalidDecl()) 10416 DefineImplicitCopyConstructor(DefaultLoc, CD); 10417 break; 10418 } 10419 10420 case CXXCopyAssignment: { 10421 CheckExplicitlyDefaultedCopyAssignment(MD); 10422 if (!MD->isInvalidDecl()) 10423 DefineImplicitCopyAssignment(DefaultLoc, MD); 10424 break; 10425 } 10426 10427 case CXXDestructor: { 10428 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD); 10429 CheckExplicitlyDefaultedDestructor(DD); 10430 if (!DD->isInvalidDecl()) 10431 DefineImplicitDestructor(DefaultLoc, DD); 10432 break; 10433 } 10434 10435 case CXXMoveConstructor: { 10436 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD); 10437 CheckExplicitlyDefaultedMoveConstructor(CD); 10438 if (!CD->isInvalidDecl()) 10439 DefineImplicitMoveConstructor(DefaultLoc, CD); 10440 break; 10441 } 10442 10443 case CXXMoveAssignment: { 10444 CheckExplicitlyDefaultedMoveAssignment(MD); 10445 if (!MD->isInvalidDecl()) 10446 DefineImplicitMoveAssignment(DefaultLoc, MD); 10447 break; 10448 } 10449 10450 case CXXInvalid: 10451 llvm_unreachable("Invalid special member."); 10452 } 10453 } else { 10454 Diag(DefaultLoc, diag::err_default_special_members); 10455 } 10456} 10457 10458static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 10459 for (Stmt::child_range CI = S->children(); CI; ++CI) { 10460 Stmt *SubStmt = *CI; 10461 if (!SubStmt) 10462 continue; 10463 if (isa<ReturnStmt>(SubStmt)) 10464 Self.Diag(SubStmt->getSourceRange().getBegin(), 10465 diag::err_return_in_constructor_handler); 10466 if (!isa<Expr>(SubStmt)) 10467 SearchForReturnInStmt(Self, SubStmt); 10468 } 10469} 10470 10471void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 10472 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 10473 CXXCatchStmt *Handler = TryBlock->getHandler(I); 10474 SearchForReturnInStmt(*this, Handler); 10475 } 10476} 10477 10478bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 10479 const CXXMethodDecl *Old) { 10480 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType(); 10481 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType(); 10482 10483 if (Context.hasSameType(NewTy, OldTy) || 10484 NewTy->isDependentType() || OldTy->isDependentType()) 10485 return false; 10486 10487 // Check if the return types are covariant 10488 QualType NewClassTy, OldClassTy; 10489 10490 /// Both types must be pointers or references to classes. 10491 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 10492 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 10493 NewClassTy = NewPT->getPointeeType(); 10494 OldClassTy = OldPT->getPointeeType(); 10495 } 10496 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 10497 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 10498 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 10499 NewClassTy = NewRT->getPointeeType(); 10500 OldClassTy = OldRT->getPointeeType(); 10501 } 10502 } 10503 } 10504 10505 // The return types aren't either both pointers or references to a class type. 10506 if (NewClassTy.isNull()) { 10507 Diag(New->getLocation(), 10508 diag::err_different_return_type_for_overriding_virtual_function) 10509 << New->getDeclName() << NewTy << OldTy; 10510 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 10511 10512 return true; 10513 } 10514 10515 // C++ [class.virtual]p6: 10516 // If the return type of D::f differs from the return type of B::f, the 10517 // class type in the return type of D::f shall be complete at the point of 10518 // declaration of D::f or shall be the class type D. 10519 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 10520 if (!RT->isBeingDefined() && 10521 RequireCompleteType(New->getLocation(), NewClassTy, 10522 PDiag(diag::err_covariant_return_incomplete) 10523 << New->getDeclName())) 10524 return true; 10525 } 10526 10527 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 10528 // Check if the new class derives from the old class. 10529 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 10530 Diag(New->getLocation(), 10531 diag::err_covariant_return_not_derived) 10532 << New->getDeclName() << NewTy << OldTy; 10533 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 10534 return true; 10535 } 10536 10537 // Check if we the conversion from derived to base is valid. 10538 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy, 10539 diag::err_covariant_return_inaccessible_base, 10540 diag::err_covariant_return_ambiguous_derived_to_base_conv, 10541 // FIXME: Should this point to the return type? 10542 New->getLocation(), SourceRange(), New->getDeclName(), 0)) { 10543 // FIXME: this note won't trigger for delayed access control 10544 // diagnostics, and it's impossible to get an undelayed error 10545 // here from access control during the original parse because 10546 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 10547 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 10548 return true; 10549 } 10550 } 10551 10552 // The qualifiers of the return types must be the same. 10553 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 10554 Diag(New->getLocation(), 10555 diag::err_covariant_return_type_different_qualifications) 10556 << New->getDeclName() << NewTy << OldTy; 10557 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 10558 return true; 10559 }; 10560 10561 10562 // The new class type must have the same or less qualifiers as the old type. 10563 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 10564 Diag(New->getLocation(), 10565 diag::err_covariant_return_type_class_type_more_qualified) 10566 << New->getDeclName() << NewTy << OldTy; 10567 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 10568 return true; 10569 }; 10570 10571 return false; 10572} 10573 10574/// \brief Mark the given method pure. 10575/// 10576/// \param Method the method to be marked pure. 10577/// 10578/// \param InitRange the source range that covers the "0" initializer. 10579bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 10580 SourceLocation EndLoc = InitRange.getEnd(); 10581 if (EndLoc.isValid()) 10582 Method->setRangeEnd(EndLoc); 10583 10584 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 10585 Method->setPure(); 10586 return false; 10587 } 10588 10589 if (!Method->isInvalidDecl()) 10590 Diag(Method->getLocation(), diag::err_non_virtual_pure) 10591 << Method->getDeclName() << InitRange; 10592 return true; 10593} 10594 10595/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 10596/// an initializer for the out-of-line declaration 'Dcl'. The scope 10597/// is a fresh scope pushed for just this purpose. 10598/// 10599/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 10600/// static data member of class X, names should be looked up in the scope of 10601/// class X. 10602void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 10603 // If there is no declaration, there was an error parsing it. 10604 if (D == 0 || D->isInvalidDecl()) return; 10605 10606 // We should only get called for declarations with scope specifiers, like: 10607 // int foo::bar; 10608 assert(D->isOutOfLine()); 10609 EnterDeclaratorContext(S, D->getDeclContext()); 10610} 10611 10612/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 10613/// initializer for the out-of-line declaration 'D'. 10614void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 10615 // If there is no declaration, there was an error parsing it. 10616 if (D == 0 || D->isInvalidDecl()) return; 10617 10618 assert(D->isOutOfLine()); 10619 ExitDeclaratorContext(S); 10620} 10621 10622/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 10623/// C++ if/switch/while/for statement. 10624/// e.g: "if (int x = f()) {...}" 10625DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 10626 // C++ 6.4p2: 10627 // The declarator shall not specify a function or an array. 10628 // The type-specifier-seq shall not contain typedef and shall not declare a 10629 // new class or enumeration. 10630 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 10631 "Parser allowed 'typedef' as storage class of condition decl."); 10632 10633 Decl *Dcl = ActOnDeclarator(S, D); 10634 if (!Dcl) 10635 return true; 10636 10637 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 10638 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 10639 << D.getSourceRange(); 10640 return true; 10641 } 10642 10643 return Dcl; 10644} 10645 10646void Sema::LoadExternalVTableUses() { 10647 if (!ExternalSource) 10648 return; 10649 10650 SmallVector<ExternalVTableUse, 4> VTables; 10651 ExternalSource->ReadUsedVTables(VTables); 10652 SmallVector<VTableUse, 4> NewUses; 10653 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 10654 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 10655 = VTablesUsed.find(VTables[I].Record); 10656 // Even if a definition wasn't required before, it may be required now. 10657 if (Pos != VTablesUsed.end()) { 10658 if (!Pos->second && VTables[I].DefinitionRequired) 10659 Pos->second = true; 10660 continue; 10661 } 10662 10663 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 10664 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 10665 } 10666 10667 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 10668} 10669 10670void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 10671 bool DefinitionRequired) { 10672 // Ignore any vtable uses in unevaluated operands or for classes that do 10673 // not have a vtable. 10674 if (!Class->isDynamicClass() || Class->isDependentContext() || 10675 CurContext->isDependentContext() || 10676 ExprEvalContexts.back().Context == Unevaluated) 10677 return; 10678 10679 // Try to insert this class into the map. 10680 LoadExternalVTableUses(); 10681 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 10682 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 10683 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 10684 if (!Pos.second) { 10685 // If we already had an entry, check to see if we are promoting this vtable 10686 // to required a definition. If so, we need to reappend to the VTableUses 10687 // list, since we may have already processed the first entry. 10688 if (DefinitionRequired && !Pos.first->second) { 10689 Pos.first->second = true; 10690 } else { 10691 // Otherwise, we can early exit. 10692 return; 10693 } 10694 } 10695 10696 // Local classes need to have their virtual members marked 10697 // immediately. For all other classes, we mark their virtual members 10698 // at the end of the translation unit. 10699 if (Class->isLocalClass()) 10700 MarkVirtualMembersReferenced(Loc, Class); 10701 else 10702 VTableUses.push_back(std::make_pair(Class, Loc)); 10703} 10704 10705bool Sema::DefineUsedVTables() { 10706 LoadExternalVTableUses(); 10707 if (VTableUses.empty()) 10708 return false; 10709 10710 // Note: The VTableUses vector could grow as a result of marking 10711 // the members of a class as "used", so we check the size each 10712 // time through the loop and prefer indices (with are stable) to 10713 // iterators (which are not). 10714 bool DefinedAnything = false; 10715 for (unsigned I = 0; I != VTableUses.size(); ++I) { 10716 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 10717 if (!Class) 10718 continue; 10719 10720 SourceLocation Loc = VTableUses[I].second; 10721 10722 // If this class has a key function, but that key function is 10723 // defined in another translation unit, we don't need to emit the 10724 // vtable even though we're using it. 10725 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class); 10726 if (KeyFunction && !KeyFunction->hasBody()) { 10727 switch (KeyFunction->getTemplateSpecializationKind()) { 10728 case TSK_Undeclared: 10729 case TSK_ExplicitSpecialization: 10730 case TSK_ExplicitInstantiationDeclaration: 10731 // The key function is in another translation unit. 10732 continue; 10733 10734 case TSK_ExplicitInstantiationDefinition: 10735 case TSK_ImplicitInstantiation: 10736 // We will be instantiating the key function. 10737 break; 10738 } 10739 } else if (!KeyFunction) { 10740 // If we have a class with no key function that is the subject 10741 // of an explicit instantiation declaration, suppress the 10742 // vtable; it will live with the explicit instantiation 10743 // definition. 10744 bool IsExplicitInstantiationDeclaration 10745 = Class->getTemplateSpecializationKind() 10746 == TSK_ExplicitInstantiationDeclaration; 10747 for (TagDecl::redecl_iterator R = Class->redecls_begin(), 10748 REnd = Class->redecls_end(); 10749 R != REnd; ++R) { 10750 TemplateSpecializationKind TSK 10751 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind(); 10752 if (TSK == TSK_ExplicitInstantiationDeclaration) 10753 IsExplicitInstantiationDeclaration = true; 10754 else if (TSK == TSK_ExplicitInstantiationDefinition) { 10755 IsExplicitInstantiationDeclaration = false; 10756 break; 10757 } 10758 } 10759 10760 if (IsExplicitInstantiationDeclaration) 10761 continue; 10762 } 10763 10764 // Mark all of the virtual members of this class as referenced, so 10765 // that we can build a vtable. Then, tell the AST consumer that a 10766 // vtable for this class is required. 10767 DefinedAnything = true; 10768 MarkVirtualMembersReferenced(Loc, Class); 10769 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 10770 Consumer.HandleVTable(Class, VTablesUsed[Canonical]); 10771 10772 // Optionally warn if we're emitting a weak vtable. 10773 if (Class->getLinkage() == ExternalLinkage && 10774 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) { 10775 const FunctionDecl *KeyFunctionDef = 0; 10776 if (!KeyFunction || 10777 (KeyFunction->hasBody(KeyFunctionDef) && 10778 KeyFunctionDef->isInlined())) 10779 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() == 10780 TSK_ExplicitInstantiationDefinition 10781 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable) 10782 << Class; 10783 } 10784 } 10785 VTableUses.clear(); 10786 10787 return DefinedAnything; 10788} 10789 10790void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 10791 const CXXRecordDecl *RD) { 10792 for (CXXRecordDecl::method_iterator i = RD->method_begin(), 10793 e = RD->method_end(); i != e; ++i) { 10794 CXXMethodDecl *MD = *i; 10795 10796 // C++ [basic.def.odr]p2: 10797 // [...] A virtual member function is used if it is not pure. [...] 10798 if (MD->isVirtual() && !MD->isPure()) 10799 MarkFunctionReferenced(Loc, MD); 10800 } 10801 10802 // Only classes that have virtual bases need a VTT. 10803 if (RD->getNumVBases() == 0) 10804 return; 10805 10806 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(), 10807 e = RD->bases_end(); i != e; ++i) { 10808 const CXXRecordDecl *Base = 10809 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl()); 10810 if (Base->getNumVBases() == 0) 10811 continue; 10812 MarkVirtualMembersReferenced(Loc, Base); 10813 } 10814} 10815 10816/// SetIvarInitializers - This routine builds initialization ASTs for the 10817/// Objective-C implementation whose ivars need be initialized. 10818void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 10819 if (!getLangOptions().CPlusPlus) 10820 return; 10821 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 10822 SmallVector<ObjCIvarDecl*, 8> ivars; 10823 CollectIvarsToConstructOrDestruct(OID, ivars); 10824 if (ivars.empty()) 10825 return; 10826 SmallVector<CXXCtorInitializer*, 32> AllToInit; 10827 for (unsigned i = 0; i < ivars.size(); i++) { 10828 FieldDecl *Field = ivars[i]; 10829 if (Field->isInvalidDecl()) 10830 continue; 10831 10832 CXXCtorInitializer *Member; 10833 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 10834 InitializationKind InitKind = 10835 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 10836 10837 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0); 10838 ExprResult MemberInit = 10839 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg()); 10840 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 10841 // Note, MemberInit could actually come back empty if no initialization 10842 // is required (e.g., because it would call a trivial default constructor) 10843 if (!MemberInit.get() || MemberInit.isInvalid()) 10844 continue; 10845 10846 Member = 10847 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 10848 SourceLocation(), 10849 MemberInit.takeAs<Expr>(), 10850 SourceLocation()); 10851 AllToInit.push_back(Member); 10852 10853 // Be sure that the destructor is accessible and is marked as referenced. 10854 if (const RecordType *RecordTy 10855 = Context.getBaseElementType(Field->getType()) 10856 ->getAs<RecordType>()) { 10857 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 10858 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 10859 MarkFunctionReferenced(Field->getLocation(), Destructor); 10860 CheckDestructorAccess(Field->getLocation(), Destructor, 10861 PDiag(diag::err_access_dtor_ivar) 10862 << Context.getBaseElementType(Field->getType())); 10863 } 10864 } 10865 } 10866 ObjCImplementation->setIvarInitializers(Context, 10867 AllToInit.data(), AllToInit.size()); 10868 } 10869} 10870 10871static 10872void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 10873 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid, 10874 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid, 10875 llvm::SmallSet<CXXConstructorDecl*, 4> &Current, 10876 Sema &S) { 10877 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(), 10878 CE = Current.end(); 10879 if (Ctor->isInvalidDecl()) 10880 return; 10881 10882 const FunctionDecl *FNTarget = 0; 10883 CXXConstructorDecl *Target; 10884 10885 // We ignore the result here since if we don't have a body, Target will be 10886 // null below. 10887 (void)Ctor->getTargetConstructor()->hasBody(FNTarget); 10888 Target 10889= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget)); 10890 10891 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 10892 // Avoid dereferencing a null pointer here. 10893 *TCanonical = Target ? Target->getCanonicalDecl() : 0; 10894 10895 if (!Current.insert(Canonical)) 10896 return; 10897 10898 // We know that beyond here, we aren't chaining into a cycle. 10899 if (!Target || !Target->isDelegatingConstructor() || 10900 Target->isInvalidDecl() || Valid.count(TCanonical)) { 10901 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI) 10902 Valid.insert(*CI); 10903 Current.clear(); 10904 // We've hit a cycle. 10905 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 10906 Current.count(TCanonical)) { 10907 // If we haven't diagnosed this cycle yet, do so now. 10908 if (!Invalid.count(TCanonical)) { 10909 S.Diag((*Ctor->init_begin())->getSourceLocation(), 10910 diag::warn_delegating_ctor_cycle) 10911 << Ctor; 10912 10913 // Don't add a note for a function delegating directo to itself. 10914 if (TCanonical != Canonical) 10915 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 10916 10917 CXXConstructorDecl *C = Target; 10918 while (C->getCanonicalDecl() != Canonical) { 10919 (void)C->getTargetConstructor()->hasBody(FNTarget); 10920 assert(FNTarget && "Ctor cycle through bodiless function"); 10921 10922 C 10923 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget)); 10924 S.Diag(C->getLocation(), diag::note_which_delegates_to); 10925 } 10926 } 10927 10928 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI) 10929 Invalid.insert(*CI); 10930 Current.clear(); 10931 } else { 10932 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 10933 } 10934} 10935 10936 10937void Sema::CheckDelegatingCtorCycles() { 10938 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 10939 10940 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(), 10941 CE = Current.end(); 10942 10943 for (DelegatingCtorDeclsType::iterator 10944 I = DelegatingCtorDecls.begin(ExternalSource), 10945 E = DelegatingCtorDecls.end(); 10946 I != E; ++I) { 10947 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 10948 } 10949 10950 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI) 10951 (*CI)->setInvalidDecl(); 10952} 10953 10954/// IdentifyCUDATarget - Determine the CUDA compilation target for this function 10955Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) { 10956 // Implicitly declared functions (e.g. copy constructors) are 10957 // __host__ __device__ 10958 if (D->isImplicit()) 10959 return CFT_HostDevice; 10960 10961 if (D->hasAttr<CUDAGlobalAttr>()) 10962 return CFT_Global; 10963 10964 if (D->hasAttr<CUDADeviceAttr>()) { 10965 if (D->hasAttr<CUDAHostAttr>()) 10966 return CFT_HostDevice; 10967 else 10968 return CFT_Device; 10969 } 10970 10971 return CFT_Host; 10972} 10973 10974bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget, 10975 CUDAFunctionTarget CalleeTarget) { 10976 // CUDA B.1.1 "The __device__ qualifier declares a function that is... 10977 // Callable from the device only." 10978 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device) 10979 return true; 10980 10981 // CUDA B.1.2 "The __global__ qualifier declares a function that is... 10982 // Callable from the host only." 10983 // CUDA B.1.3 "The __host__ qualifier declares a function that is... 10984 // Callable from the host only." 10985 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) && 10986 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global)) 10987 return true; 10988 10989 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice) 10990 return true; 10991 10992 return false; 10993} 10994