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