SemaDeclCXX.cpp revision 8f411c39283caf2a403739b0c5dd398a6df511dc
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/EvaluatedExprVisitor.h" 27#include "clang/AST/ExprCXX.h" 28#include "clang/AST/RecordLayout.h" 29#include "clang/AST/RecursiveASTVisitor.h" 30#include "clang/AST/StmtVisitor.h" 31#include "clang/AST/TypeLoc.h" 32#include "clang/AST/TypeOrdering.h" 33#include "clang/Sema/DeclSpec.h" 34#include "clang/Sema/ParsedTemplate.h" 35#include "clang/Basic/PartialDiagnostic.h" 36#include "clang/Lex/Preprocessor.h" 37#include "llvm/ADT/SmallString.h" 38#include "llvm/ADT/STLExtras.h" 39#include <map> 40#include <set> 41 42using namespace clang; 43 44//===----------------------------------------------------------------------===// 45// CheckDefaultArgumentVisitor 46//===----------------------------------------------------------------------===// 47 48namespace { 49 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 50 /// the default argument of a parameter to determine whether it 51 /// contains any ill-formed subexpressions. For example, this will 52 /// diagnose the use of local variables or parameters within the 53 /// default argument expression. 54 class CheckDefaultArgumentVisitor 55 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 56 Expr *DefaultArg; 57 Sema *S; 58 59 public: 60 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 61 : DefaultArg(defarg), S(s) {} 62 63 bool VisitExpr(Expr *Node); 64 bool VisitDeclRefExpr(DeclRefExpr *DRE); 65 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 66 bool VisitLambdaExpr(LambdaExpr *Lambda); 67 }; 68 69 /// VisitExpr - Visit all of the children of this expression. 70 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 71 bool IsInvalid = false; 72 for (Stmt::child_range I = Node->children(); I; ++I) 73 IsInvalid |= Visit(*I); 74 return IsInvalid; 75 } 76 77 /// VisitDeclRefExpr - Visit a reference to a declaration, to 78 /// determine whether this declaration can be used in the default 79 /// argument expression. 80 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 81 NamedDecl *Decl = DRE->getDecl(); 82 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 83 // C++ [dcl.fct.default]p9 84 // Default arguments are evaluated each time the function is 85 // called. The order of evaluation of function arguments is 86 // unspecified. Consequently, parameters of a function shall not 87 // be used in default argument expressions, even if they are not 88 // evaluated. Parameters of a function declared before a default 89 // argument expression are in scope and can hide namespace and 90 // class member names. 91 return S->Diag(DRE->getLocStart(), 92 diag::err_param_default_argument_references_param) 93 << Param->getDeclName() << DefaultArg->getSourceRange(); 94 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 95 // C++ [dcl.fct.default]p7 96 // Local variables shall not be used in default argument 97 // expressions. 98 if (VDecl->isLocalVarDecl()) 99 return S->Diag(DRE->getLocStart(), 100 diag::err_param_default_argument_references_local) 101 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 102 } 103 104 return false; 105 } 106 107 /// VisitCXXThisExpr - Visit a C++ "this" expression. 108 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 109 // C++ [dcl.fct.default]p8: 110 // The keyword this shall not be used in a default argument of a 111 // member function. 112 return S->Diag(ThisE->getLocStart(), 113 diag::err_param_default_argument_references_this) 114 << ThisE->getSourceRange(); 115 } 116 117 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) { 118 // C++11 [expr.lambda.prim]p13: 119 // A lambda-expression appearing in a default argument shall not 120 // implicitly or explicitly capture any entity. 121 if (Lambda->capture_begin() == Lambda->capture_end()) 122 return false; 123 124 return S->Diag(Lambda->getLocStart(), 125 diag::err_lambda_capture_default_arg); 126 } 127} 128 129void Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc, 130 CXXMethodDecl *Method) { 131 // If we have an MSAny spec already, don't bother. 132 if (!Method || ComputedEST == EST_MSAny) 133 return; 134 135 const FunctionProtoType *Proto 136 = Method->getType()->getAs<FunctionProtoType>(); 137 Proto = Self->ResolveExceptionSpec(CallLoc, Proto); 138 if (!Proto) 139 return; 140 141 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 142 143 // If this function can throw any exceptions, make a note of that. 144 if (EST == EST_MSAny || EST == EST_None) { 145 ClearExceptions(); 146 ComputedEST = EST; 147 return; 148 } 149 150 // FIXME: If the call to this decl is using any of its default arguments, we 151 // need to search them for potentially-throwing calls. 152 153 // If this function has a basic noexcept, it doesn't affect the outcome. 154 if (EST == EST_BasicNoexcept) 155 return; 156 157 // If we have a throw-all spec at this point, ignore the function. 158 if (ComputedEST == EST_None) 159 return; 160 161 // If we're still at noexcept(true) and there's a nothrow() callee, 162 // change to that specification. 163 if (EST == EST_DynamicNone) { 164 if (ComputedEST == EST_BasicNoexcept) 165 ComputedEST = EST_DynamicNone; 166 return; 167 } 168 169 // Check out noexcept specs. 170 if (EST == EST_ComputedNoexcept) { 171 FunctionProtoType::NoexceptResult NR = 172 Proto->getNoexceptSpec(Self->Context); 173 assert(NR != FunctionProtoType::NR_NoNoexcept && 174 "Must have noexcept result for EST_ComputedNoexcept."); 175 assert(NR != FunctionProtoType::NR_Dependent && 176 "Should not generate implicit declarations for dependent cases, " 177 "and don't know how to handle them anyway."); 178 179 // noexcept(false) -> no spec on the new function 180 if (NR == FunctionProtoType::NR_Throw) { 181 ClearExceptions(); 182 ComputedEST = EST_None; 183 } 184 // noexcept(true) won't change anything either. 185 return; 186 } 187 188 assert(EST == EST_Dynamic && "EST case not considered earlier."); 189 assert(ComputedEST != EST_None && 190 "Shouldn't collect exceptions when throw-all is guaranteed."); 191 ComputedEST = EST_Dynamic; 192 // Record the exceptions in this function's exception specification. 193 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(), 194 EEnd = Proto->exception_end(); 195 E != EEnd; ++E) 196 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E))) 197 Exceptions.push_back(*E); 198} 199 200void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) { 201 if (!E || ComputedEST == EST_MSAny) 202 return; 203 204 // FIXME: 205 // 206 // C++0x [except.spec]p14: 207 // [An] implicit exception-specification specifies the type-id T if and 208 // only if T is allowed by the exception-specification of a function directly 209 // invoked by f's implicit definition; f shall allow all exceptions if any 210 // function it directly invokes allows all exceptions, and f shall allow no 211 // exceptions if every function it directly invokes allows no exceptions. 212 // 213 // Note in particular that if an implicit exception-specification is generated 214 // for a function containing a throw-expression, that specification can still 215 // be noexcept(true). 216 // 217 // Note also that 'directly invoked' is not defined in the standard, and there 218 // is no indication that we should only consider potentially-evaluated calls. 219 // 220 // Ultimately we should implement the intent of the standard: the exception 221 // specification should be the set of exceptions which can be thrown by the 222 // implicit definition. For now, we assume that any non-nothrow expression can 223 // throw any exception. 224 225 if (Self->canThrow(E)) 226 ComputedEST = EST_None; 227} 228 229bool 230Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 231 SourceLocation EqualLoc) { 232 if (RequireCompleteType(Param->getLocation(), Param->getType(), 233 diag::err_typecheck_decl_incomplete_type)) { 234 Param->setInvalidDecl(); 235 return true; 236 } 237 238 // C++ [dcl.fct.default]p5 239 // A default argument expression is implicitly converted (clause 240 // 4) to the parameter type. The default argument expression has 241 // the same semantic constraints as the initializer expression in 242 // a declaration of a variable of the parameter type, using the 243 // copy-initialization semantics (8.5). 244 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 245 Param); 246 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 247 EqualLoc); 248 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1); 249 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); 250 if (Result.isInvalid()) 251 return true; 252 Arg = Result.takeAs<Expr>(); 253 254 CheckImplicitConversions(Arg, EqualLoc); 255 Arg = MaybeCreateExprWithCleanups(Arg); 256 257 // Okay: add the default argument to the parameter 258 Param->setDefaultArg(Arg); 259 260 // We have already instantiated this parameter; provide each of the 261 // instantiations with the uninstantiated default argument. 262 UnparsedDefaultArgInstantiationsMap::iterator InstPos 263 = UnparsedDefaultArgInstantiations.find(Param); 264 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 265 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 266 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 267 268 // We're done tracking this parameter's instantiations. 269 UnparsedDefaultArgInstantiations.erase(InstPos); 270 } 271 272 return false; 273} 274 275/// ActOnParamDefaultArgument - Check whether the default argument 276/// provided for a function parameter is well-formed. If so, attach it 277/// to the parameter declaration. 278void 279Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 280 Expr *DefaultArg) { 281 if (!param || !DefaultArg) 282 return; 283 284 ParmVarDecl *Param = cast<ParmVarDecl>(param); 285 UnparsedDefaultArgLocs.erase(Param); 286 287 // Default arguments are only permitted in C++ 288 if (!getLangOpts().CPlusPlus) { 289 Diag(EqualLoc, diag::err_param_default_argument) 290 << DefaultArg->getSourceRange(); 291 Param->setInvalidDecl(); 292 return; 293 } 294 295 // Check for unexpanded parameter packs. 296 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 297 Param->setInvalidDecl(); 298 return; 299 } 300 301 // Check that the default argument is well-formed 302 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this); 303 if (DefaultArgChecker.Visit(DefaultArg)) { 304 Param->setInvalidDecl(); 305 return; 306 } 307 308 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 309} 310 311/// ActOnParamUnparsedDefaultArgument - We've seen a default 312/// argument for a function parameter, but we can't parse it yet 313/// because we're inside a class definition. Note that this default 314/// argument will be parsed later. 315void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 316 SourceLocation EqualLoc, 317 SourceLocation ArgLoc) { 318 if (!param) 319 return; 320 321 ParmVarDecl *Param = cast<ParmVarDecl>(param); 322 if (Param) 323 Param->setUnparsedDefaultArg(); 324 325 UnparsedDefaultArgLocs[Param] = ArgLoc; 326} 327 328/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 329/// the default argument for the parameter param failed. 330void Sema::ActOnParamDefaultArgumentError(Decl *param) { 331 if (!param) 332 return; 333 334 ParmVarDecl *Param = cast<ParmVarDecl>(param); 335 336 Param->setInvalidDecl(); 337 338 UnparsedDefaultArgLocs.erase(Param); 339} 340 341/// CheckExtraCXXDefaultArguments - Check for any extra default 342/// arguments in the declarator, which is not a function declaration 343/// or definition and therefore is not permitted to have default 344/// arguments. This routine should be invoked for every declarator 345/// that is not a function declaration or definition. 346void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 347 // C++ [dcl.fct.default]p3 348 // A default argument expression shall be specified only in the 349 // parameter-declaration-clause of a function declaration or in a 350 // template-parameter (14.1). It shall not be specified for a 351 // parameter pack. If it is specified in a 352 // parameter-declaration-clause, it shall not occur within a 353 // declarator or abstract-declarator of a parameter-declaration. 354 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 355 DeclaratorChunk &chunk = D.getTypeObject(i); 356 if (chunk.Kind == DeclaratorChunk::Function) { 357 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) { 358 ParmVarDecl *Param = 359 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param); 360 if (Param->hasUnparsedDefaultArg()) { 361 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens; 362 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 363 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation()); 364 delete Toks; 365 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0; 366 } else if (Param->getDefaultArg()) { 367 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 368 << Param->getDefaultArg()->getSourceRange(); 369 Param->setDefaultArg(0); 370 } 371 } 372 } 373 } 374} 375 376// MergeCXXFunctionDecl - Merge two declarations of the same C++ 377// function, once we already know that they have the same 378// type. Subroutine of MergeFunctionDecl. Returns true if there was an 379// error, false otherwise. 380bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 381 Scope *S) { 382 bool Invalid = false; 383 384 // C++ [dcl.fct.default]p4: 385 // For non-template functions, default arguments can be added in 386 // later declarations of a function in the same 387 // scope. Declarations in different scopes have completely 388 // distinct sets of default arguments. That is, declarations in 389 // inner scopes do not acquire default arguments from 390 // declarations in outer scopes, and vice versa. In a given 391 // function declaration, all parameters subsequent to a 392 // parameter with a default argument shall have default 393 // arguments supplied in this or previous declarations. A 394 // default argument shall not be redefined by a later 395 // declaration (not even to the same value). 396 // 397 // C++ [dcl.fct.default]p6: 398 // Except for member functions of class templates, the default arguments 399 // in a member function definition that appears outside of the class 400 // definition are added to the set of default arguments provided by the 401 // member function declaration in the class definition. 402 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 403 ParmVarDecl *OldParam = Old->getParamDecl(p); 404 ParmVarDecl *NewParam = New->getParamDecl(p); 405 406 bool OldParamHasDfl = OldParam->hasDefaultArg(); 407 bool NewParamHasDfl = NewParam->hasDefaultArg(); 408 409 NamedDecl *ND = Old; 410 if (S && !isDeclInScope(ND, New->getDeclContext(), S)) 411 // Ignore default parameters of old decl if they are not in 412 // the same scope. 413 OldParamHasDfl = false; 414 415 if (OldParamHasDfl && NewParamHasDfl) { 416 417 unsigned DiagDefaultParamID = 418 diag::err_param_default_argument_redefinition; 419 420 // MSVC accepts that default parameters be redefined for member functions 421 // of template class. The new default parameter's value is ignored. 422 Invalid = true; 423 if (getLangOpts().MicrosoftExt) { 424 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New); 425 if (MD && MD->getParent()->getDescribedClassTemplate()) { 426 // Merge the old default argument into the new parameter. 427 NewParam->setHasInheritedDefaultArg(); 428 if (OldParam->hasUninstantiatedDefaultArg()) 429 NewParam->setUninstantiatedDefaultArg( 430 OldParam->getUninstantiatedDefaultArg()); 431 else 432 NewParam->setDefaultArg(OldParam->getInit()); 433 DiagDefaultParamID = diag::warn_param_default_argument_redefinition; 434 Invalid = false; 435 } 436 } 437 438 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 439 // hint here. Alternatively, we could walk the type-source information 440 // for NewParam to find the last source location in the type... but it 441 // isn't worth the effort right now. This is the kind of test case that 442 // is hard to get right: 443 // int f(int); 444 // void g(int (*fp)(int) = f); 445 // void g(int (*fp)(int) = &f); 446 Diag(NewParam->getLocation(), DiagDefaultParamID) 447 << NewParam->getDefaultArgRange(); 448 449 // Look for the function declaration where the default argument was 450 // actually written, which may be a declaration prior to Old. 451 for (FunctionDecl *Older = Old->getPreviousDecl(); 452 Older; Older = Older->getPreviousDecl()) { 453 if (!Older->getParamDecl(p)->hasDefaultArg()) 454 break; 455 456 OldParam = Older->getParamDecl(p); 457 } 458 459 Diag(OldParam->getLocation(), diag::note_previous_definition) 460 << OldParam->getDefaultArgRange(); 461 } else if (OldParamHasDfl) { 462 // Merge the old default argument into the new parameter. 463 // It's important to use getInit() here; getDefaultArg() 464 // strips off any top-level ExprWithCleanups. 465 NewParam->setHasInheritedDefaultArg(); 466 if (OldParam->hasUninstantiatedDefaultArg()) 467 NewParam->setUninstantiatedDefaultArg( 468 OldParam->getUninstantiatedDefaultArg()); 469 else 470 NewParam->setDefaultArg(OldParam->getInit()); 471 } else if (NewParamHasDfl) { 472 if (New->getDescribedFunctionTemplate()) { 473 // Paragraph 4, quoted above, only applies to non-template functions. 474 Diag(NewParam->getLocation(), 475 diag::err_param_default_argument_template_redecl) 476 << NewParam->getDefaultArgRange(); 477 Diag(Old->getLocation(), diag::note_template_prev_declaration) 478 << false; 479 } else if (New->getTemplateSpecializationKind() 480 != TSK_ImplicitInstantiation && 481 New->getTemplateSpecializationKind() != TSK_Undeclared) { 482 // C++ [temp.expr.spec]p21: 483 // Default function arguments shall not be specified in a declaration 484 // or a definition for one of the following explicit specializations: 485 // - the explicit specialization of a function template; 486 // - the explicit specialization of a member function template; 487 // - the explicit specialization of a member function of a class 488 // template where the class template specialization to which the 489 // member function specialization belongs is implicitly 490 // instantiated. 491 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 492 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 493 << New->getDeclName() 494 << NewParam->getDefaultArgRange(); 495 } else if (New->getDeclContext()->isDependentContext()) { 496 // C++ [dcl.fct.default]p6 (DR217): 497 // Default arguments for a member function of a class template shall 498 // be specified on the initial declaration of the member function 499 // within the class template. 500 // 501 // Reading the tea leaves a bit in DR217 and its reference to DR205 502 // leads me to the conclusion that one cannot add default function 503 // arguments for an out-of-line definition of a member function of a 504 // dependent type. 505 int WhichKind = 2; 506 if (CXXRecordDecl *Record 507 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 508 if (Record->getDescribedClassTemplate()) 509 WhichKind = 0; 510 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 511 WhichKind = 1; 512 else 513 WhichKind = 2; 514 } 515 516 Diag(NewParam->getLocation(), 517 diag::err_param_default_argument_member_template_redecl) 518 << WhichKind 519 << NewParam->getDefaultArgRange(); 520 } else if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(New)) { 521 CXXSpecialMember NewSM = getSpecialMember(Ctor), 522 OldSM = getSpecialMember(cast<CXXConstructorDecl>(Old)); 523 if (NewSM != OldSM) { 524 Diag(NewParam->getLocation(),diag::warn_default_arg_makes_ctor_special) 525 << NewParam->getDefaultArgRange() << NewSM; 526 Diag(Old->getLocation(), diag::note_previous_declaration_special) 527 << OldSM; 528 } 529 } 530 } 531 } 532 533 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 534 // template has a constexpr specifier then all its declarations shall 535 // contain the constexpr specifier. 536 if (New->isConstexpr() != Old->isConstexpr()) { 537 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 538 << New << New->isConstexpr(); 539 Diag(Old->getLocation(), diag::note_previous_declaration); 540 Invalid = true; 541 } 542 543 if (CheckEquivalentExceptionSpec(Old, New)) 544 Invalid = true; 545 546 return Invalid; 547} 548 549/// \brief Merge the exception specifications of two variable declarations. 550/// 551/// This is called when there's a redeclaration of a VarDecl. The function 552/// checks if the redeclaration might have an exception specification and 553/// validates compatibility and merges the specs if necessary. 554void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 555 // Shortcut if exceptions are disabled. 556 if (!getLangOpts().CXXExceptions) 557 return; 558 559 assert(Context.hasSameType(New->getType(), Old->getType()) && 560 "Should only be called if types are otherwise the same."); 561 562 QualType NewType = New->getType(); 563 QualType OldType = Old->getType(); 564 565 // We're only interested in pointers and references to functions, as well 566 // as pointers to member functions. 567 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 568 NewType = R->getPointeeType(); 569 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 570 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 571 NewType = P->getPointeeType(); 572 OldType = OldType->getAs<PointerType>()->getPointeeType(); 573 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 574 NewType = M->getPointeeType(); 575 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 576 } 577 578 if (!NewType->isFunctionProtoType()) 579 return; 580 581 // There's lots of special cases for functions. For function pointers, system 582 // libraries are hopefully not as broken so that we don't need these 583 // workarounds. 584 if (CheckEquivalentExceptionSpec( 585 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 586 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 587 New->setInvalidDecl(); 588 } 589} 590 591/// CheckCXXDefaultArguments - Verify that the default arguments for a 592/// function declaration are well-formed according to C++ 593/// [dcl.fct.default]. 594void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 595 unsigned NumParams = FD->getNumParams(); 596 unsigned p; 597 598 bool IsLambda = FD->getOverloadedOperator() == OO_Call && 599 isa<CXXMethodDecl>(FD) && 600 cast<CXXMethodDecl>(FD)->getParent()->isLambda(); 601 602 // Find first parameter with a default argument 603 for (p = 0; p < NumParams; ++p) { 604 ParmVarDecl *Param = FD->getParamDecl(p); 605 if (Param->hasDefaultArg()) { 606 // C++11 [expr.prim.lambda]p5: 607 // [...] Default arguments (8.3.6) shall not be specified in the 608 // parameter-declaration-clause of a lambda-declarator. 609 // 610 // FIXME: Core issue 974 strikes this sentence, we only provide an 611 // extension warning. 612 if (IsLambda) 613 Diag(Param->getLocation(), diag::ext_lambda_default_arguments) 614 << Param->getDefaultArgRange(); 615 break; 616 } 617 } 618 619 // C++ [dcl.fct.default]p4: 620 // In a given function declaration, all parameters 621 // subsequent to a parameter with a default argument shall 622 // have default arguments supplied in this or previous 623 // declarations. A default argument shall not be redefined 624 // by a later declaration (not even to the same value). 625 unsigned LastMissingDefaultArg = 0; 626 for (; p < NumParams; ++p) { 627 ParmVarDecl *Param = FD->getParamDecl(p); 628 if (!Param->hasDefaultArg()) { 629 if (Param->isInvalidDecl()) 630 /* We already complained about this parameter. */; 631 else if (Param->getIdentifier()) 632 Diag(Param->getLocation(), 633 diag::err_param_default_argument_missing_name) 634 << Param->getIdentifier(); 635 else 636 Diag(Param->getLocation(), 637 diag::err_param_default_argument_missing); 638 639 LastMissingDefaultArg = p; 640 } 641 } 642 643 if (LastMissingDefaultArg > 0) { 644 // Some default arguments were missing. Clear out all of the 645 // default arguments up to (and including) the last missing 646 // default argument, so that we leave the function parameters 647 // in a semantically valid state. 648 for (p = 0; p <= LastMissingDefaultArg; ++p) { 649 ParmVarDecl *Param = FD->getParamDecl(p); 650 if (Param->hasDefaultArg()) { 651 Param->setDefaultArg(0); 652 } 653 } 654 } 655} 656 657// CheckConstexprParameterTypes - Check whether a function's parameter types 658// are all literal types. If so, return true. If not, produce a suitable 659// diagnostic and return false. 660static bool CheckConstexprParameterTypes(Sema &SemaRef, 661 const FunctionDecl *FD) { 662 unsigned ArgIndex = 0; 663 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 664 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(), 665 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) { 666 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 667 SourceLocation ParamLoc = PD->getLocation(); 668 if (!(*i)->isDependentType() && 669 SemaRef.RequireLiteralType(ParamLoc, *i, 670 diag::err_constexpr_non_literal_param, 671 ArgIndex+1, PD->getSourceRange(), 672 isa<CXXConstructorDecl>(FD))) 673 return false; 674 } 675 return true; 676} 677 678/// \brief Get diagnostic %select index for tag kind for 679/// record diagnostic message. 680/// WARNING: Indexes apply to particular diagnostics only! 681/// 682/// \returns diagnostic %select index. 683static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 684 switch (Tag) { 685 case TTK_Struct: return 0; 686 case TTK_Interface: return 1; 687 case TTK_Class: return 2; 688 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 689 } 690} 691 692// CheckConstexprFunctionDecl - Check whether a function declaration satisfies 693// the requirements of a constexpr function definition or a constexpr 694// constructor definition. If so, return true. If not, produce appropriate 695// diagnostics and return false. 696// 697// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 698bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) { 699 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 700 if (MD && MD->isInstance()) { 701 // C++11 [dcl.constexpr]p4: 702 // The definition of a constexpr constructor shall satisfy the following 703 // constraints: 704 // - the class shall not have any virtual base classes; 705 const CXXRecordDecl *RD = MD->getParent(); 706 if (RD->getNumVBases()) { 707 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 708 << isa<CXXConstructorDecl>(NewFD) 709 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 710 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(), 711 E = RD->vbases_end(); I != E; ++I) 712 Diag(I->getLocStart(), 713 diag::note_constexpr_virtual_base_here) << I->getSourceRange(); 714 return false; 715 } 716 } 717 718 if (!isa<CXXConstructorDecl>(NewFD)) { 719 // C++11 [dcl.constexpr]p3: 720 // The definition of a constexpr function shall satisfy the following 721 // constraints: 722 // - it shall not be virtual; 723 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 724 if (Method && Method->isVirtual()) { 725 Diag(NewFD->getLocation(), diag::err_constexpr_virtual); 726 727 // If it's not obvious why this function is virtual, find an overridden 728 // function which uses the 'virtual' keyword. 729 const CXXMethodDecl *WrittenVirtual = Method; 730 while (!WrittenVirtual->isVirtualAsWritten()) 731 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 732 if (WrittenVirtual != Method) 733 Diag(WrittenVirtual->getLocation(), 734 diag::note_overridden_virtual_function); 735 return false; 736 } 737 738 // - its return type shall be a literal type; 739 QualType RT = NewFD->getResultType(); 740 if (!RT->isDependentType() && 741 RequireLiteralType(NewFD->getLocation(), RT, 742 diag::err_constexpr_non_literal_return)) 743 return false; 744 } 745 746 // - each of its parameter types shall be a literal type; 747 if (!CheckConstexprParameterTypes(*this, NewFD)) 748 return false; 749 750 return true; 751} 752 753/// Check the given declaration statement is legal within a constexpr function 754/// body. C++0x [dcl.constexpr]p3,p4. 755/// 756/// \return true if the body is OK, false if we have diagnosed a problem. 757static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 758 DeclStmt *DS) { 759 // C++0x [dcl.constexpr]p3 and p4: 760 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 761 // contain only 762 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(), 763 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) { 764 switch ((*DclIt)->getKind()) { 765 case Decl::StaticAssert: 766 case Decl::Using: 767 case Decl::UsingShadow: 768 case Decl::UsingDirective: 769 case Decl::UnresolvedUsingTypename: 770 // - static_assert-declarations 771 // - using-declarations, 772 // - using-directives, 773 continue; 774 775 case Decl::Typedef: 776 case Decl::TypeAlias: { 777 // - typedef declarations and alias-declarations that do not define 778 // classes or enumerations, 779 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt); 780 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 781 // Don't allow variably-modified types in constexpr functions. 782 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 783 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 784 << TL.getSourceRange() << TL.getType() 785 << isa<CXXConstructorDecl>(Dcl); 786 return false; 787 } 788 continue; 789 } 790 791 case Decl::Enum: 792 case Decl::CXXRecord: 793 // As an extension, we allow the declaration (but not the definition) of 794 // classes and enumerations in all declarations, not just in typedef and 795 // alias declarations. 796 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) { 797 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition) 798 << isa<CXXConstructorDecl>(Dcl); 799 return false; 800 } 801 continue; 802 803 case Decl::Var: 804 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration) 805 << isa<CXXConstructorDecl>(Dcl); 806 return false; 807 808 default: 809 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt) 810 << isa<CXXConstructorDecl>(Dcl); 811 return false; 812 } 813 } 814 815 return true; 816} 817 818/// Check that the given field is initialized within a constexpr constructor. 819/// 820/// \param Dcl The constexpr constructor being checked. 821/// \param Field The field being checked. This may be a member of an anonymous 822/// struct or union nested within the class being checked. 823/// \param Inits All declarations, including anonymous struct/union members and 824/// indirect members, for which any initialization was provided. 825/// \param Diagnosed Set to true if an error is produced. 826static void CheckConstexprCtorInitializer(Sema &SemaRef, 827 const FunctionDecl *Dcl, 828 FieldDecl *Field, 829 llvm::SmallSet<Decl*, 16> &Inits, 830 bool &Diagnosed) { 831 if (Field->isUnnamedBitfield()) 832 return; 833 834 if (Field->isAnonymousStructOrUnion() && 835 Field->getType()->getAsCXXRecordDecl()->isEmpty()) 836 return; 837 838 if (!Inits.count(Field)) { 839 if (!Diagnosed) { 840 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init); 841 Diagnosed = true; 842 } 843 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init); 844 } else if (Field->isAnonymousStructOrUnion()) { 845 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 846 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end(); 847 I != E; ++I) 848 // If an anonymous union contains an anonymous struct of which any member 849 // is initialized, all members must be initialized. 850 if (!RD->isUnion() || Inits.count(*I)) 851 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed); 852 } 853} 854 855/// Check the body for the given constexpr function declaration only contains 856/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 857/// 858/// \return true if the body is OK, false if we have diagnosed a problem. 859bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) { 860 if (isa<CXXTryStmt>(Body)) { 861 // C++11 [dcl.constexpr]p3: 862 // The definition of a constexpr function shall satisfy the following 863 // constraints: [...] 864 // - its function-body shall be = delete, = default, or a 865 // compound-statement 866 // 867 // C++11 [dcl.constexpr]p4: 868 // In the definition of a constexpr constructor, [...] 869 // - its function-body shall not be a function-try-block; 870 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block) 871 << isa<CXXConstructorDecl>(Dcl); 872 return false; 873 } 874 875 // - its function-body shall be [...] a compound-statement that contains only 876 CompoundStmt *CompBody = cast<CompoundStmt>(Body); 877 878 llvm::SmallVector<SourceLocation, 4> ReturnStmts; 879 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(), 880 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) { 881 switch ((*BodyIt)->getStmtClass()) { 882 case Stmt::NullStmtClass: 883 // - null statements, 884 continue; 885 886 case Stmt::DeclStmtClass: 887 // - static_assert-declarations 888 // - using-declarations, 889 // - using-directives, 890 // - typedef declarations and alias-declarations that do not define 891 // classes or enumerations, 892 if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt))) 893 return false; 894 continue; 895 896 case Stmt::ReturnStmtClass: 897 // - and exactly one return statement; 898 if (isa<CXXConstructorDecl>(Dcl)) 899 break; 900 901 ReturnStmts.push_back((*BodyIt)->getLocStart()); 902 continue; 903 904 default: 905 break; 906 } 907 908 Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt) 909 << isa<CXXConstructorDecl>(Dcl); 910 return false; 911 } 912 913 if (const CXXConstructorDecl *Constructor 914 = dyn_cast<CXXConstructorDecl>(Dcl)) { 915 const CXXRecordDecl *RD = Constructor->getParent(); 916 // DR1359: 917 // - every non-variant non-static data member and base class sub-object 918 // shall be initialized; 919 // - if the class is a non-empty union, or for each non-empty anonymous 920 // union member of a non-union class, exactly one non-static data member 921 // shall be initialized; 922 if (RD->isUnion()) { 923 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) { 924 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init); 925 return false; 926 } 927 } else if (!Constructor->isDependentContext() && 928 !Constructor->isDelegatingConstructor()) { 929 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 930 931 // Skip detailed checking if we have enough initializers, and we would 932 // allow at most one initializer per member. 933 bool AnyAnonStructUnionMembers = false; 934 unsigned Fields = 0; 935 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 936 E = RD->field_end(); I != E; ++I, ++Fields) { 937 if (I->isAnonymousStructOrUnion()) { 938 AnyAnonStructUnionMembers = true; 939 break; 940 } 941 } 942 if (AnyAnonStructUnionMembers || 943 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 944 // Check initialization of non-static data members. Base classes are 945 // always initialized so do not need to be checked. Dependent bases 946 // might not have initializers in the member initializer list. 947 llvm::SmallSet<Decl*, 16> Inits; 948 for (CXXConstructorDecl::init_const_iterator 949 I = Constructor->init_begin(), E = Constructor->init_end(); 950 I != E; ++I) { 951 if (FieldDecl *FD = (*I)->getMember()) 952 Inits.insert(FD); 953 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember()) 954 Inits.insert(ID->chain_begin(), ID->chain_end()); 955 } 956 957 bool Diagnosed = false; 958 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 959 E = RD->field_end(); I != E; ++I) 960 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed); 961 if (Diagnosed) 962 return false; 963 } 964 } 965 } else { 966 if (ReturnStmts.empty()) { 967 Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return); 968 return false; 969 } 970 if (ReturnStmts.size() > 1) { 971 Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return); 972 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 973 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return); 974 return false; 975 } 976 } 977 978 // C++11 [dcl.constexpr]p5: 979 // if no function argument values exist such that the function invocation 980 // substitution would produce a constant expression, the program is 981 // ill-formed; no diagnostic required. 982 // C++11 [dcl.constexpr]p3: 983 // - every constructor call and implicit conversion used in initializing the 984 // return value shall be one of those allowed in a constant expression. 985 // C++11 [dcl.constexpr]p4: 986 // - every constructor involved in initializing non-static data members and 987 // base class sub-objects shall be a constexpr constructor. 988 llvm::SmallVector<PartialDiagnosticAt, 8> Diags; 989 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) { 990 Diag(Dcl->getLocation(), diag::err_constexpr_function_never_constant_expr) 991 << isa<CXXConstructorDecl>(Dcl); 992 for (size_t I = 0, N = Diags.size(); I != N; ++I) 993 Diag(Diags[I].first, Diags[I].second); 994 return false; 995 } 996 997 return true; 998} 999 1000/// isCurrentClassName - Determine whether the identifier II is the 1001/// name of the class type currently being defined. In the case of 1002/// nested classes, this will only return true if II is the name of 1003/// the innermost class. 1004bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 1005 const CXXScopeSpec *SS) { 1006 assert(getLangOpts().CPlusPlus && "No class names in C!"); 1007 1008 CXXRecordDecl *CurDecl; 1009 if (SS && SS->isSet() && !SS->isInvalid()) { 1010 DeclContext *DC = computeDeclContext(*SS, true); 1011 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 1012 } else 1013 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1014 1015 if (CurDecl && CurDecl->getIdentifier()) 1016 return &II == CurDecl->getIdentifier(); 1017 else 1018 return false; 1019} 1020 1021/// \brief Check the validity of a C++ base class specifier. 1022/// 1023/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 1024/// and returns NULL otherwise. 1025CXXBaseSpecifier * 1026Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 1027 SourceRange SpecifierRange, 1028 bool Virtual, AccessSpecifier Access, 1029 TypeSourceInfo *TInfo, 1030 SourceLocation EllipsisLoc) { 1031 QualType BaseType = TInfo->getType(); 1032 1033 // C++ [class.union]p1: 1034 // A union shall not have base classes. 1035 if (Class->isUnion()) { 1036 Diag(Class->getLocation(), diag::err_base_clause_on_union) 1037 << SpecifierRange; 1038 return 0; 1039 } 1040 1041 if (EllipsisLoc.isValid() && 1042 !TInfo->getType()->containsUnexpandedParameterPack()) { 1043 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 1044 << TInfo->getTypeLoc().getSourceRange(); 1045 EllipsisLoc = SourceLocation(); 1046 } 1047 1048 if (BaseType->isDependentType()) 1049 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1050 Class->getTagKind() == TTK_Class, 1051 Access, TInfo, EllipsisLoc); 1052 1053 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 1054 1055 // Base specifiers must be record types. 1056 if (!BaseType->isRecordType()) { 1057 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 1058 return 0; 1059 } 1060 1061 // C++ [class.union]p1: 1062 // A union shall not be used as a base class. 1063 if (BaseType->isUnionType()) { 1064 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 1065 return 0; 1066 } 1067 1068 // C++ [class.derived]p2: 1069 // The class-name in a base-specifier shall not be an incompletely 1070 // defined class. 1071 if (RequireCompleteType(BaseLoc, BaseType, 1072 diag::err_incomplete_base_class, SpecifierRange)) { 1073 Class->setInvalidDecl(); 1074 return 0; 1075 } 1076 1077 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 1078 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 1079 assert(BaseDecl && "Record type has no declaration"); 1080 BaseDecl = BaseDecl->getDefinition(); 1081 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 1082 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 1083 assert(CXXBaseDecl && "Base type is not a C++ type"); 1084 1085 // C++ [class]p3: 1086 // If a class is marked final and it appears as a base-type-specifier in 1087 // base-clause, the program is ill-formed. 1088 if (CXXBaseDecl->hasAttr<FinalAttr>()) { 1089 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 1090 << CXXBaseDecl->getDeclName(); 1091 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl) 1092 << CXXBaseDecl->getDeclName(); 1093 return 0; 1094 } 1095 1096 if (BaseDecl->isInvalidDecl()) 1097 Class->setInvalidDecl(); 1098 1099 // Create the base specifier. 1100 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1101 Class->getTagKind() == TTK_Class, 1102 Access, TInfo, EllipsisLoc); 1103} 1104 1105/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 1106/// one entry in the base class list of a class specifier, for 1107/// example: 1108/// class foo : public bar, virtual private baz { 1109/// 'public bar' and 'virtual private baz' are each base-specifiers. 1110BaseResult 1111Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 1112 bool Virtual, AccessSpecifier Access, 1113 ParsedType basetype, SourceLocation BaseLoc, 1114 SourceLocation EllipsisLoc) { 1115 if (!classdecl) 1116 return true; 1117 1118 AdjustDeclIfTemplate(classdecl); 1119 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 1120 if (!Class) 1121 return true; 1122 1123 TypeSourceInfo *TInfo = 0; 1124 GetTypeFromParser(basetype, &TInfo); 1125 1126 if (EllipsisLoc.isInvalid() && 1127 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 1128 UPPC_BaseType)) 1129 return true; 1130 1131 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 1132 Virtual, Access, TInfo, 1133 EllipsisLoc)) 1134 return BaseSpec; 1135 else 1136 Class->setInvalidDecl(); 1137 1138 return true; 1139} 1140 1141/// \brief Performs the actual work of attaching the given base class 1142/// specifiers to a C++ class. 1143bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 1144 unsigned NumBases) { 1145 if (NumBases == 0) 1146 return false; 1147 1148 // Used to keep track of which base types we have already seen, so 1149 // that we can properly diagnose redundant direct base types. Note 1150 // that the key is always the unqualified canonical type of the base 1151 // class. 1152 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 1153 1154 // Copy non-redundant base specifiers into permanent storage. 1155 unsigned NumGoodBases = 0; 1156 bool Invalid = false; 1157 for (unsigned idx = 0; idx < NumBases; ++idx) { 1158 QualType NewBaseType 1159 = Context.getCanonicalType(Bases[idx]->getType()); 1160 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 1161 1162 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 1163 if (KnownBase) { 1164 // C++ [class.mi]p3: 1165 // A class shall not be specified as a direct base class of a 1166 // derived class more than once. 1167 Diag(Bases[idx]->getLocStart(), 1168 diag::err_duplicate_base_class) 1169 << KnownBase->getType() 1170 << Bases[idx]->getSourceRange(); 1171 1172 // Delete the duplicate base class specifier; we're going to 1173 // overwrite its pointer later. 1174 Context.Deallocate(Bases[idx]); 1175 1176 Invalid = true; 1177 } else { 1178 // Okay, add this new base class. 1179 KnownBase = Bases[idx]; 1180 Bases[NumGoodBases++] = Bases[idx]; 1181 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) 1182 if (const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl())) 1183 if (RD->hasAttr<WeakAttr>()) 1184 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context)); 1185 } 1186 } 1187 1188 // Attach the remaining base class specifiers to the derived class. 1189 Class->setBases(Bases, NumGoodBases); 1190 1191 // Delete the remaining (good) base class specifiers, since their 1192 // data has been copied into the CXXRecordDecl. 1193 for (unsigned idx = 0; idx < NumGoodBases; ++idx) 1194 Context.Deallocate(Bases[idx]); 1195 1196 return Invalid; 1197} 1198 1199/// ActOnBaseSpecifiers - Attach the given base specifiers to the 1200/// class, after checking whether there are any duplicate base 1201/// classes. 1202void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases, 1203 unsigned NumBases) { 1204 if (!ClassDecl || !Bases || !NumBases) 1205 return; 1206 1207 AdjustDeclIfTemplate(ClassDecl); 1208 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), 1209 (CXXBaseSpecifier**)(Bases), NumBases); 1210} 1211 1212static CXXRecordDecl *GetClassForType(QualType T) { 1213 if (const RecordType *RT = T->getAs<RecordType>()) 1214 return cast<CXXRecordDecl>(RT->getDecl()); 1215 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>()) 1216 return ICT->getDecl(); 1217 else 1218 return 0; 1219} 1220 1221/// \brief Determine whether the type \p Derived is a C++ class that is 1222/// derived from the type \p Base. 1223bool Sema::IsDerivedFrom(QualType Derived, QualType Base) { 1224 if (!getLangOpts().CPlusPlus) 1225 return false; 1226 1227 CXXRecordDecl *DerivedRD = GetClassForType(Derived); 1228 if (!DerivedRD) 1229 return false; 1230 1231 CXXRecordDecl *BaseRD = GetClassForType(Base); 1232 if (!BaseRD) 1233 return false; 1234 1235 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this. 1236 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD); 1237} 1238 1239/// \brief Determine whether the type \p Derived is a C++ class that is 1240/// derived from the type \p Base. 1241bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) { 1242 if (!getLangOpts().CPlusPlus) 1243 return false; 1244 1245 CXXRecordDecl *DerivedRD = GetClassForType(Derived); 1246 if (!DerivedRD) 1247 return false; 1248 1249 CXXRecordDecl *BaseRD = GetClassForType(Base); 1250 if (!BaseRD) 1251 return false; 1252 1253 return DerivedRD->isDerivedFrom(BaseRD, Paths); 1254} 1255 1256void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 1257 CXXCastPath &BasePathArray) { 1258 assert(BasePathArray.empty() && "Base path array must be empty!"); 1259 assert(Paths.isRecordingPaths() && "Must record paths!"); 1260 1261 const CXXBasePath &Path = Paths.front(); 1262 1263 // We first go backward and check if we have a virtual base. 1264 // FIXME: It would be better if CXXBasePath had the base specifier for 1265 // the nearest virtual base. 1266 unsigned Start = 0; 1267 for (unsigned I = Path.size(); I != 0; --I) { 1268 if (Path[I - 1].Base->isVirtual()) { 1269 Start = I - 1; 1270 break; 1271 } 1272 } 1273 1274 // Now add all bases. 1275 for (unsigned I = Start, E = Path.size(); I != E; ++I) 1276 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 1277} 1278 1279/// \brief Determine whether the given base path includes a virtual 1280/// base class. 1281bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) { 1282 for (CXXCastPath::const_iterator B = BasePath.begin(), 1283 BEnd = BasePath.end(); 1284 B != BEnd; ++B) 1285 if ((*B)->isVirtual()) 1286 return true; 1287 1288 return false; 1289} 1290 1291/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 1292/// conversion (where Derived and Base are class types) is 1293/// well-formed, meaning that the conversion is unambiguous (and 1294/// that all of the base classes are accessible). Returns true 1295/// and emits a diagnostic if the code is ill-formed, returns false 1296/// otherwise. Loc is the location where this routine should point to 1297/// if there is an error, and Range is the source range to highlight 1298/// if there is an error. 1299bool 1300Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1301 unsigned InaccessibleBaseID, 1302 unsigned AmbigiousBaseConvID, 1303 SourceLocation Loc, SourceRange Range, 1304 DeclarationName Name, 1305 CXXCastPath *BasePath) { 1306 // First, determine whether the path from Derived to Base is 1307 // ambiguous. This is slightly more expensive than checking whether 1308 // the Derived to Base conversion exists, because here we need to 1309 // explore multiple paths to determine if there is an ambiguity. 1310 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1311 /*DetectVirtual=*/false); 1312 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths); 1313 assert(DerivationOkay && 1314 "Can only be used with a derived-to-base conversion"); 1315 (void)DerivationOkay; 1316 1317 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 1318 if (InaccessibleBaseID) { 1319 // Check that the base class can be accessed. 1320 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(), 1321 InaccessibleBaseID)) { 1322 case AR_inaccessible: 1323 return true; 1324 case AR_accessible: 1325 case AR_dependent: 1326 case AR_delayed: 1327 break; 1328 } 1329 } 1330 1331 // Build a base path if necessary. 1332 if (BasePath) 1333 BuildBasePathArray(Paths, *BasePath); 1334 return false; 1335 } 1336 1337 // We know that the derived-to-base conversion is ambiguous, and 1338 // we're going to produce a diagnostic. Perform the derived-to-base 1339 // search just one more time to compute all of the possible paths so 1340 // that we can print them out. This is more expensive than any of 1341 // the previous derived-to-base checks we've done, but at this point 1342 // performance isn't as much of an issue. 1343 Paths.clear(); 1344 Paths.setRecordingPaths(true); 1345 bool StillOkay = IsDerivedFrom(Derived, Base, Paths); 1346 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 1347 (void)StillOkay; 1348 1349 // Build up a textual representation of the ambiguous paths, e.g., 1350 // D -> B -> A, that will be used to illustrate the ambiguous 1351 // conversions in the diagnostic. We only print one of the paths 1352 // to each base class subobject. 1353 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 1354 1355 Diag(Loc, AmbigiousBaseConvID) 1356 << Derived << Base << PathDisplayStr << Range << Name; 1357 return true; 1358} 1359 1360bool 1361Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1362 SourceLocation Loc, SourceRange Range, 1363 CXXCastPath *BasePath, 1364 bool IgnoreAccess) { 1365 return CheckDerivedToBaseConversion(Derived, Base, 1366 IgnoreAccess ? 0 1367 : diag::err_upcast_to_inaccessible_base, 1368 diag::err_ambiguous_derived_to_base_conv, 1369 Loc, Range, DeclarationName(), 1370 BasePath); 1371} 1372 1373 1374/// @brief Builds a string representing ambiguous paths from a 1375/// specific derived class to different subobjects of the same base 1376/// class. 1377/// 1378/// This function builds a string that can be used in error messages 1379/// to show the different paths that one can take through the 1380/// inheritance hierarchy to go from the derived class to different 1381/// subobjects of a base class. The result looks something like this: 1382/// @code 1383/// struct D -> struct B -> struct A 1384/// struct D -> struct C -> struct A 1385/// @endcode 1386std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 1387 std::string PathDisplayStr; 1388 std::set<unsigned> DisplayedPaths; 1389 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 1390 Path != Paths.end(); ++Path) { 1391 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 1392 // We haven't displayed a path to this particular base 1393 // class subobject yet. 1394 PathDisplayStr += "\n "; 1395 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 1396 for (CXXBasePath::const_iterator Element = Path->begin(); 1397 Element != Path->end(); ++Element) 1398 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 1399 } 1400 } 1401 1402 return PathDisplayStr; 1403} 1404 1405//===----------------------------------------------------------------------===// 1406// C++ class member Handling 1407//===----------------------------------------------------------------------===// 1408 1409/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 1410bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, 1411 SourceLocation ASLoc, 1412 SourceLocation ColonLoc, 1413 AttributeList *Attrs) { 1414 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 1415 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 1416 ASLoc, ColonLoc); 1417 CurContext->addHiddenDecl(ASDecl); 1418 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 1419} 1420 1421/// CheckOverrideControl - Check C++11 override control semantics. 1422void Sema::CheckOverrideControl(Decl *D) { 1423 if (D->isInvalidDecl()) 1424 return; 1425 1426 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 1427 1428 // Do we know which functions this declaration might be overriding? 1429 bool OverridesAreKnown = !MD || 1430 (!MD->getParent()->hasAnyDependentBases() && 1431 !MD->getType()->isDependentType()); 1432 1433 if (!MD || !MD->isVirtual()) { 1434 if (OverridesAreKnown) { 1435 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1436 Diag(OA->getLocation(), 1437 diag::override_keyword_only_allowed_on_virtual_member_functions) 1438 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 1439 D->dropAttr<OverrideAttr>(); 1440 } 1441 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1442 Diag(FA->getLocation(), 1443 diag::override_keyword_only_allowed_on_virtual_member_functions) 1444 << "final" << FixItHint::CreateRemoval(FA->getLocation()); 1445 D->dropAttr<FinalAttr>(); 1446 } 1447 } 1448 return; 1449 } 1450 1451 if (!OverridesAreKnown) 1452 return; 1453 1454 // C++11 [class.virtual]p5: 1455 // If a virtual function is marked with the virt-specifier override and 1456 // does not override a member function of a base class, the program is 1457 // ill-formed. 1458 bool HasOverriddenMethods = 1459 MD->begin_overridden_methods() != MD->end_overridden_methods(); 1460 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 1461 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 1462 << MD->getDeclName(); 1463} 1464 1465/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 1466/// function overrides a virtual member function marked 'final', according to 1467/// C++11 [class.virtual]p4. 1468bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 1469 const CXXMethodDecl *Old) { 1470 if (!Old->hasAttr<FinalAttr>()) 1471 return false; 1472 1473 Diag(New->getLocation(), diag::err_final_function_overridden) 1474 << New->getDeclName(); 1475 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 1476 return true; 1477} 1478 1479static bool InitializationHasSideEffects(const FieldDecl &FD) { 1480 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 1481 // FIXME: Destruction of ObjC lifetime types has side-effects. 1482 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 1483 return !RD->isCompleteDefinition() || 1484 !RD->hasTrivialDefaultConstructor() || 1485 !RD->hasTrivialDestructor(); 1486 return false; 1487} 1488 1489/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 1490/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 1491/// bitfield width if there is one, 'InitExpr' specifies the initializer if 1492/// one has been parsed, and 'InitStyle' is set if an in-class initializer is 1493/// present (but parsing it has been deferred). 1494Decl * 1495Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 1496 MultiTemplateParamsArg TemplateParameterLists, 1497 Expr *BW, const VirtSpecifiers &VS, 1498 InClassInitStyle InitStyle) { 1499 const DeclSpec &DS = D.getDeclSpec(); 1500 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 1501 DeclarationName Name = NameInfo.getName(); 1502 SourceLocation Loc = NameInfo.getLoc(); 1503 1504 // For anonymous bitfields, the location should point to the type. 1505 if (Loc.isInvalid()) 1506 Loc = D.getLocStart(); 1507 1508 Expr *BitWidth = static_cast<Expr*>(BW); 1509 1510 assert(isa<CXXRecordDecl>(CurContext)); 1511 assert(!DS.isFriendSpecified()); 1512 1513 bool isFunc = D.isDeclarationOfFunction(); 1514 1515 // C++ 9.2p6: A member shall not be declared to have automatic storage 1516 // duration (auto, register) or with the extern storage-class-specifier. 1517 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 1518 // data members and cannot be applied to names declared const or static, 1519 // and cannot be applied to reference members. 1520 switch (DS.getStorageClassSpec()) { 1521 case DeclSpec::SCS_unspecified: 1522 case DeclSpec::SCS_typedef: 1523 case DeclSpec::SCS_static: 1524 // FALL THROUGH. 1525 break; 1526 case DeclSpec::SCS_mutable: 1527 if (isFunc) { 1528 if (DS.getStorageClassSpecLoc().isValid()) 1529 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 1530 else 1531 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function); 1532 1533 // FIXME: It would be nicer if the keyword was ignored only for this 1534 // declarator. Otherwise we could get follow-up errors. 1535 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1536 } 1537 break; 1538 default: 1539 if (DS.getStorageClassSpecLoc().isValid()) 1540 Diag(DS.getStorageClassSpecLoc(), 1541 diag::err_storageclass_invalid_for_member); 1542 else 1543 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member); 1544 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1545 } 1546 1547 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 1548 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 1549 !isFunc); 1550 1551 Decl *Member; 1552 if (isInstField) { 1553 CXXScopeSpec &SS = D.getCXXScopeSpec(); 1554 1555 // Data members must have identifiers for names. 1556 if (!Name.isIdentifier()) { 1557 Diag(Loc, diag::err_bad_variable_name) 1558 << Name; 1559 return 0; 1560 } 1561 1562 IdentifierInfo *II = Name.getAsIdentifierInfo(); 1563 1564 // Member field could not be with "template" keyword. 1565 // So TemplateParameterLists should be empty in this case. 1566 if (TemplateParameterLists.size()) { 1567 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 1568 if (TemplateParams->size()) { 1569 // There is no such thing as a member field template. 1570 Diag(D.getIdentifierLoc(), diag::err_template_member) 1571 << II 1572 << SourceRange(TemplateParams->getTemplateLoc(), 1573 TemplateParams->getRAngleLoc()); 1574 } else { 1575 // There is an extraneous 'template<>' for this member. 1576 Diag(TemplateParams->getTemplateLoc(), 1577 diag::err_template_member_noparams) 1578 << II 1579 << SourceRange(TemplateParams->getTemplateLoc(), 1580 TemplateParams->getRAngleLoc()); 1581 } 1582 return 0; 1583 } 1584 1585 if (SS.isSet() && !SS.isInvalid()) { 1586 // The user provided a superfluous scope specifier inside a class 1587 // definition: 1588 // 1589 // class X { 1590 // int X::member; 1591 // }; 1592 if (DeclContext *DC = computeDeclContext(SS, false)) 1593 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc()); 1594 else 1595 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 1596 << Name << SS.getRange(); 1597 1598 SS.clear(); 1599 } 1600 1601 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth, 1602 InitStyle, AS); 1603 assert(Member && "HandleField never returns null"); 1604 } else { 1605 assert(InitStyle == ICIS_NoInit); 1606 1607 Member = HandleDeclarator(S, D, TemplateParameterLists); 1608 if (!Member) { 1609 return 0; 1610 } 1611 1612 // Non-instance-fields can't have a bitfield. 1613 if (BitWidth) { 1614 if (Member->isInvalidDecl()) { 1615 // don't emit another diagnostic. 1616 } else if (isa<VarDecl>(Member)) { 1617 // C++ 9.6p3: A bit-field shall not be a static member. 1618 // "static member 'A' cannot be a bit-field" 1619 Diag(Loc, diag::err_static_not_bitfield) 1620 << Name << BitWidth->getSourceRange(); 1621 } else if (isa<TypedefDecl>(Member)) { 1622 // "typedef member 'x' cannot be a bit-field" 1623 Diag(Loc, diag::err_typedef_not_bitfield) 1624 << Name << BitWidth->getSourceRange(); 1625 } else { 1626 // A function typedef ("typedef int f(); f a;"). 1627 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 1628 Diag(Loc, diag::err_not_integral_type_bitfield) 1629 << Name << cast<ValueDecl>(Member)->getType() 1630 << BitWidth->getSourceRange(); 1631 } 1632 1633 BitWidth = 0; 1634 Member->setInvalidDecl(); 1635 } 1636 1637 Member->setAccess(AS); 1638 1639 // If we have declared a member function template, set the access of the 1640 // templated declaration as well. 1641 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 1642 FunTmpl->getTemplatedDecl()->setAccess(AS); 1643 } 1644 1645 if (VS.isOverrideSpecified()) 1646 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context)); 1647 if (VS.isFinalSpecified()) 1648 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context)); 1649 1650 if (VS.getLastLocation().isValid()) { 1651 // Update the end location of a method that has a virt-specifiers. 1652 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 1653 MD->setRangeEnd(VS.getLastLocation()); 1654 } 1655 1656 CheckOverrideControl(Member); 1657 1658 assert((Name || isInstField) && "No identifier for non-field ?"); 1659 1660 if (isInstField) { 1661 FieldDecl *FD = cast<FieldDecl>(Member); 1662 FieldCollector->Add(FD); 1663 1664 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field, 1665 FD->getLocation()) 1666 != DiagnosticsEngine::Ignored) { 1667 // Remember all explicit private FieldDecls that have a name, no side 1668 // effects and are not part of a dependent type declaration. 1669 if (!FD->isImplicit() && FD->getDeclName() && 1670 FD->getAccess() == AS_private && 1671 !FD->hasAttr<UnusedAttr>() && 1672 !FD->getParent()->isDependentContext() && 1673 !InitializationHasSideEffects(*FD)) 1674 UnusedPrivateFields.insert(FD); 1675 } 1676 } 1677 1678 return Member; 1679} 1680 1681/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an 1682/// in-class initializer for a non-static C++ class member, and after 1683/// instantiating an in-class initializer in a class template. Such actions 1684/// are deferred until the class is complete. 1685void 1686Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc, 1687 Expr *InitExpr) { 1688 FieldDecl *FD = cast<FieldDecl>(D); 1689 assert(FD->getInClassInitStyle() != ICIS_NoInit && 1690 "must set init style when field is created"); 1691 1692 if (!InitExpr) { 1693 FD->setInvalidDecl(); 1694 FD->removeInClassInitializer(); 1695 return; 1696 } 1697 1698 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 1699 FD->setInvalidDecl(); 1700 FD->removeInClassInitializer(); 1701 return; 1702 } 1703 1704 ExprResult Init = InitExpr; 1705 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent() && 1706 !FD->getDeclContext()->isDependentContext()) { 1707 // Note: We don't type-check when we're in a dependent context, because 1708 // the initialization-substitution code does not properly handle direct 1709 // list initialization. We have the same hackaround for ctor-initializers. 1710 if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) { 1711 Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list) 1712 << /*at end of ctor*/1 << InitExpr->getSourceRange(); 1713 } 1714 Expr **Inits = &InitExpr; 1715 unsigned NumInits = 1; 1716 InitializedEntity Entity = InitializedEntity::InitializeMember(FD); 1717 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit 1718 ? InitializationKind::CreateDirectList(InitExpr->getLocStart()) 1719 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc); 1720 InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits); 1721 Init = Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits)); 1722 if (Init.isInvalid()) { 1723 FD->setInvalidDecl(); 1724 return; 1725 } 1726 1727 CheckImplicitConversions(Init.get(), InitLoc); 1728 } 1729 1730 // C++0x [class.base.init]p7: 1731 // The initialization of each base and member constitutes a 1732 // full-expression. 1733 Init = MaybeCreateExprWithCleanups(Init); 1734 if (Init.isInvalid()) { 1735 FD->setInvalidDecl(); 1736 return; 1737 } 1738 1739 InitExpr = Init.release(); 1740 1741 FD->setInClassInitializer(InitExpr); 1742} 1743 1744/// \brief Find the direct and/or virtual base specifiers that 1745/// correspond to the given base type, for use in base initialization 1746/// within a constructor. 1747static bool FindBaseInitializer(Sema &SemaRef, 1748 CXXRecordDecl *ClassDecl, 1749 QualType BaseType, 1750 const CXXBaseSpecifier *&DirectBaseSpec, 1751 const CXXBaseSpecifier *&VirtualBaseSpec) { 1752 // First, check for a direct base class. 1753 DirectBaseSpec = 0; 1754 for (CXXRecordDecl::base_class_const_iterator Base 1755 = ClassDecl->bases_begin(); 1756 Base != ClassDecl->bases_end(); ++Base) { 1757 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) { 1758 // We found a direct base of this type. That's what we're 1759 // initializing. 1760 DirectBaseSpec = &*Base; 1761 break; 1762 } 1763 } 1764 1765 // Check for a virtual base class. 1766 // FIXME: We might be able to short-circuit this if we know in advance that 1767 // there are no virtual bases. 1768 VirtualBaseSpec = 0; 1769 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 1770 // We haven't found a base yet; search the class hierarchy for a 1771 // virtual base class. 1772 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1773 /*DetectVirtual=*/false); 1774 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl), 1775 BaseType, Paths)) { 1776 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 1777 Path != Paths.end(); ++Path) { 1778 if (Path->back().Base->isVirtual()) { 1779 VirtualBaseSpec = Path->back().Base; 1780 break; 1781 } 1782 } 1783 } 1784 } 1785 1786 return DirectBaseSpec || VirtualBaseSpec; 1787} 1788 1789/// \brief Handle a C++ member initializer using braced-init-list syntax. 1790MemInitResult 1791Sema::ActOnMemInitializer(Decl *ConstructorD, 1792 Scope *S, 1793 CXXScopeSpec &SS, 1794 IdentifierInfo *MemberOrBase, 1795 ParsedType TemplateTypeTy, 1796 const DeclSpec &DS, 1797 SourceLocation IdLoc, 1798 Expr *InitList, 1799 SourceLocation EllipsisLoc) { 1800 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 1801 DS, IdLoc, InitList, 1802 EllipsisLoc); 1803} 1804 1805/// \brief Handle a C++ member initializer using parentheses syntax. 1806MemInitResult 1807Sema::ActOnMemInitializer(Decl *ConstructorD, 1808 Scope *S, 1809 CXXScopeSpec &SS, 1810 IdentifierInfo *MemberOrBase, 1811 ParsedType TemplateTypeTy, 1812 const DeclSpec &DS, 1813 SourceLocation IdLoc, 1814 SourceLocation LParenLoc, 1815 Expr **Args, unsigned NumArgs, 1816 SourceLocation RParenLoc, 1817 SourceLocation EllipsisLoc) { 1818 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, 1819 llvm::makeArrayRef(Args, NumArgs), 1820 RParenLoc); 1821 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 1822 DS, IdLoc, List, EllipsisLoc); 1823} 1824 1825namespace { 1826 1827// Callback to only accept typo corrections that can be a valid C++ member 1828// intializer: either a non-static field member or a base class. 1829class MemInitializerValidatorCCC : public CorrectionCandidateCallback { 1830 public: 1831 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 1832 : ClassDecl(ClassDecl) {} 1833 1834 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 1835 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 1836 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 1837 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 1838 else 1839 return isa<TypeDecl>(ND); 1840 } 1841 return false; 1842 } 1843 1844 private: 1845 CXXRecordDecl *ClassDecl; 1846}; 1847 1848} 1849 1850/// \brief Handle a C++ member initializer. 1851MemInitResult 1852Sema::BuildMemInitializer(Decl *ConstructorD, 1853 Scope *S, 1854 CXXScopeSpec &SS, 1855 IdentifierInfo *MemberOrBase, 1856 ParsedType TemplateTypeTy, 1857 const DeclSpec &DS, 1858 SourceLocation IdLoc, 1859 Expr *Init, 1860 SourceLocation EllipsisLoc) { 1861 if (!ConstructorD) 1862 return true; 1863 1864 AdjustDeclIfTemplate(ConstructorD); 1865 1866 CXXConstructorDecl *Constructor 1867 = dyn_cast<CXXConstructorDecl>(ConstructorD); 1868 if (!Constructor) { 1869 // The user wrote a constructor initializer on a function that is 1870 // not a C++ constructor. Ignore the error for now, because we may 1871 // have more member initializers coming; we'll diagnose it just 1872 // once in ActOnMemInitializers. 1873 return true; 1874 } 1875 1876 CXXRecordDecl *ClassDecl = Constructor->getParent(); 1877 1878 // C++ [class.base.init]p2: 1879 // Names in a mem-initializer-id are looked up in the scope of the 1880 // constructor's class and, if not found in that scope, are looked 1881 // up in the scope containing the constructor's definition. 1882 // [Note: if the constructor's class contains a member with the 1883 // same name as a direct or virtual base class of the class, a 1884 // mem-initializer-id naming the member or base class and composed 1885 // of a single identifier refers to the class member. A 1886 // mem-initializer-id for the hidden base class may be specified 1887 // using a qualified name. ] 1888 if (!SS.getScopeRep() && !TemplateTypeTy) { 1889 // Look for a member, first. 1890 DeclContext::lookup_result Result 1891 = ClassDecl->lookup(MemberOrBase); 1892 if (Result.first != Result.second) { 1893 ValueDecl *Member; 1894 if ((Member = dyn_cast<FieldDecl>(*Result.first)) || 1895 (Member = dyn_cast<IndirectFieldDecl>(*Result.first))) { 1896 if (EllipsisLoc.isValid()) 1897 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 1898 << MemberOrBase 1899 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 1900 1901 return BuildMemberInitializer(Member, Init, IdLoc); 1902 } 1903 } 1904 } 1905 // It didn't name a member, so see if it names a class. 1906 QualType BaseType; 1907 TypeSourceInfo *TInfo = 0; 1908 1909 if (TemplateTypeTy) { 1910 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 1911 } else if (DS.getTypeSpecType() == TST_decltype) { 1912 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 1913 } else { 1914 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 1915 LookupParsedName(R, S, &SS); 1916 1917 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 1918 if (!TyD) { 1919 if (R.isAmbiguous()) return true; 1920 1921 // We don't want access-control diagnostics here. 1922 R.suppressDiagnostics(); 1923 1924 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 1925 bool NotUnknownSpecialization = false; 1926 DeclContext *DC = computeDeclContext(SS, false); 1927 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 1928 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 1929 1930 if (!NotUnknownSpecialization) { 1931 // When the scope specifier can refer to a member of an unknown 1932 // specialization, we take it as a type name. 1933 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 1934 SS.getWithLocInContext(Context), 1935 *MemberOrBase, IdLoc); 1936 if (BaseType.isNull()) 1937 return true; 1938 1939 R.clear(); 1940 R.setLookupName(MemberOrBase); 1941 } 1942 } 1943 1944 // If no results were found, try to correct typos. 1945 TypoCorrection Corr; 1946 MemInitializerValidatorCCC Validator(ClassDecl); 1947 if (R.empty() && BaseType.isNull() && 1948 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 1949 Validator, ClassDecl))) { 1950 std::string CorrectedStr(Corr.getAsString(getLangOpts())); 1951 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts())); 1952 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 1953 // We have found a non-static data member with a similar 1954 // name to what was typed; complain and initialize that 1955 // member. 1956 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest) 1957 << MemberOrBase << true << CorrectedQuotedStr 1958 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr); 1959 Diag(Member->getLocation(), diag::note_previous_decl) 1960 << CorrectedQuotedStr; 1961 1962 return BuildMemberInitializer(Member, Init, IdLoc); 1963 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 1964 const CXXBaseSpecifier *DirectBaseSpec; 1965 const CXXBaseSpecifier *VirtualBaseSpec; 1966 if (FindBaseInitializer(*this, ClassDecl, 1967 Context.getTypeDeclType(Type), 1968 DirectBaseSpec, VirtualBaseSpec)) { 1969 // We have found a direct or virtual base class with a 1970 // similar name to what was typed; complain and initialize 1971 // that base class. 1972 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest) 1973 << MemberOrBase << false << CorrectedQuotedStr 1974 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr); 1975 1976 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec 1977 : VirtualBaseSpec; 1978 Diag(BaseSpec->getLocStart(), 1979 diag::note_base_class_specified_here) 1980 << BaseSpec->getType() 1981 << BaseSpec->getSourceRange(); 1982 1983 TyD = Type; 1984 } 1985 } 1986 } 1987 1988 if (!TyD && BaseType.isNull()) { 1989 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 1990 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 1991 return true; 1992 } 1993 } 1994 1995 if (BaseType.isNull()) { 1996 BaseType = Context.getTypeDeclType(TyD); 1997 if (SS.isSet()) { 1998 NestedNameSpecifier *Qualifier = 1999 static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 2000 2001 // FIXME: preserve source range information 2002 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType); 2003 } 2004 } 2005 } 2006 2007 if (!TInfo) 2008 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 2009 2010 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 2011} 2012 2013/// Checks a member initializer expression for cases where reference (or 2014/// pointer) members are bound to by-value parameters (or their addresses). 2015static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member, 2016 Expr *Init, 2017 SourceLocation IdLoc) { 2018 QualType MemberTy = Member->getType(); 2019 2020 // We only handle pointers and references currently. 2021 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers? 2022 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType()) 2023 return; 2024 2025 const bool IsPointer = MemberTy->isPointerType(); 2026 if (IsPointer) { 2027 if (const UnaryOperator *Op 2028 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) { 2029 // The only case we're worried about with pointers requires taking the 2030 // address. 2031 if (Op->getOpcode() != UO_AddrOf) 2032 return; 2033 2034 Init = Op->getSubExpr(); 2035 } else { 2036 // We only handle address-of expression initializers for pointers. 2037 return; 2038 } 2039 } 2040 2041 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) { 2042 // Taking the address of a temporary will be diagnosed as a hard error. 2043 if (IsPointer) 2044 return; 2045 2046 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary) 2047 << Member << Init->getSourceRange(); 2048 } else if (const DeclRefExpr *DRE 2049 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) { 2050 // We only warn when referring to a non-reference parameter declaration. 2051 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl()); 2052 if (!Parameter || Parameter->getType()->isReferenceType()) 2053 return; 2054 2055 S.Diag(Init->getExprLoc(), 2056 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr 2057 : diag::warn_bind_ref_member_to_parameter) 2058 << Member << Parameter << Init->getSourceRange(); 2059 } else { 2060 // Other initializers are fine. 2061 return; 2062 } 2063 2064 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here) 2065 << (unsigned)IsPointer; 2066} 2067 2068namespace { 2069 class UninitializedFieldVisitor 2070 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 2071 Sema &S; 2072 ValueDecl *VD; 2073 public: 2074 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 2075 UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context), 2076 S(S), VD(VD) { 2077 } 2078 2079 void HandleExpr(Expr *E) { 2080 if (!E) return; 2081 2082 // Expressions like x(x) sometimes lack the surrounding expressions 2083 // but need to be checked anyways. 2084 HandleValue(E); 2085 Visit(E); 2086 } 2087 2088 void HandleValue(Expr *E) { 2089 E = E->IgnoreParens(); 2090 2091 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 2092 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 2093 return; 2094 Expr *Base = E; 2095 while (isa<MemberExpr>(Base)) { 2096 ME = dyn_cast<MemberExpr>(Base); 2097 if (VarDecl *VarD = dyn_cast<VarDecl>(ME->getMemberDecl())) 2098 if (VarD->hasGlobalStorage()) 2099 return; 2100 Base = ME->getBase(); 2101 } 2102 2103 if (VD == ME->getMemberDecl() && isa<CXXThisExpr>(Base)) { 2104 unsigned diag = VD->getType()->isReferenceType() 2105 ? diag::warn_reference_field_is_uninit 2106 : diag::warn_field_is_uninit; 2107 S.Diag(ME->getExprLoc(), diag); 2108 return; 2109 } 2110 } 2111 2112 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 2113 HandleValue(CO->getTrueExpr()); 2114 HandleValue(CO->getFalseExpr()); 2115 return; 2116 } 2117 2118 if (BinaryConditionalOperator *BCO = 2119 dyn_cast<BinaryConditionalOperator>(E)) { 2120 HandleValue(BCO->getCommon()); 2121 HandleValue(BCO->getFalseExpr()); 2122 return; 2123 } 2124 2125 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 2126 switch (BO->getOpcode()) { 2127 default: 2128 return; 2129 case(BO_PtrMemD): 2130 case(BO_PtrMemI): 2131 HandleValue(BO->getLHS()); 2132 return; 2133 case(BO_Comma): 2134 HandleValue(BO->getRHS()); 2135 return; 2136 } 2137 } 2138 } 2139 2140 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 2141 if (E->getCastKind() == CK_LValueToRValue) 2142 HandleValue(E->getSubExpr()); 2143 2144 Inherited::VisitImplicitCastExpr(E); 2145 } 2146 2147 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 2148 Expr *Callee = E->getCallee(); 2149 if (isa<MemberExpr>(Callee)) 2150 HandleValue(Callee); 2151 2152 Inherited::VisitCXXMemberCallExpr(E); 2153 } 2154 }; 2155 static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E, 2156 ValueDecl *VD) { 2157 UninitializedFieldVisitor(S, VD).HandleExpr(E); 2158 } 2159} // namespace 2160 2161MemInitResult 2162Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 2163 SourceLocation IdLoc) { 2164 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 2165 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 2166 assert((DirectMember || IndirectMember) && 2167 "Member must be a FieldDecl or IndirectFieldDecl"); 2168 2169 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 2170 return true; 2171 2172 if (Member->isInvalidDecl()) 2173 return true; 2174 2175 // Diagnose value-uses of fields to initialize themselves, e.g. 2176 // foo(foo) 2177 // where foo is not also a parameter to the constructor. 2178 // TODO: implement -Wuninitialized and fold this into that framework. 2179 Expr **Args; 2180 unsigned NumArgs; 2181 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2182 Args = ParenList->getExprs(); 2183 NumArgs = ParenList->getNumExprs(); 2184 } else { 2185 InitListExpr *InitList = cast<InitListExpr>(Init); 2186 Args = InitList->getInits(); 2187 NumArgs = InitList->getNumInits(); 2188 } 2189 2190 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc) 2191 != DiagnosticsEngine::Ignored) 2192 for (unsigned i = 0; i < NumArgs; ++i) 2193 // FIXME: Warn about the case when other fields are used before being 2194 // uninitialized. For example, let this field be the i'th field. When 2195 // initializing the i'th field, throw a warning if any of the >= i'th 2196 // fields are used, as they are not yet initialized. 2197 // Right now we are only handling the case where the i'th field uses 2198 // itself in its initializer. 2199 CheckInitExprContainsUninitializedFields(*this, Args[i], Member); 2200 2201 SourceRange InitRange = Init->getSourceRange(); 2202 2203 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 2204 // Can't check initialization for a member of dependent type or when 2205 // any of the arguments are type-dependent expressions. 2206 DiscardCleanupsInEvaluationContext(); 2207 } else { 2208 bool InitList = false; 2209 if (isa<InitListExpr>(Init)) { 2210 InitList = true; 2211 Args = &Init; 2212 NumArgs = 1; 2213 2214 if (isStdInitializerList(Member->getType(), 0)) { 2215 Diag(IdLoc, diag::warn_dangling_std_initializer_list) 2216 << /*at end of ctor*/1 << InitRange; 2217 } 2218 } 2219 2220 // Initialize the member. 2221 InitializedEntity MemberEntity = 2222 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0) 2223 : InitializedEntity::InitializeMember(IndirectMember, 0); 2224 InitializationKind Kind = 2225 InitList ? InitializationKind::CreateDirectList(IdLoc) 2226 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 2227 InitRange.getEnd()); 2228 2229 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs); 2230 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, 2231 MultiExprArg(Args, NumArgs), 2232 0); 2233 if (MemberInit.isInvalid()) 2234 return true; 2235 2236 CheckImplicitConversions(MemberInit.get(), 2237 InitRange.getBegin()); 2238 2239 // C++0x [class.base.init]p7: 2240 // The initialization of each base and member constitutes a 2241 // full-expression. 2242 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 2243 if (MemberInit.isInvalid()) 2244 return true; 2245 2246 // If we are in a dependent context, template instantiation will 2247 // perform this type-checking again. Just save the arguments that we 2248 // received. 2249 // FIXME: This isn't quite ideal, since our ASTs don't capture all 2250 // of the information that we have about the member 2251 // initializer. However, deconstructing the ASTs is a dicey process, 2252 // and this approach is far more likely to get the corner cases right. 2253 if (CurContext->isDependentContext()) { 2254 // The existing Init will do fine. 2255 } else { 2256 Init = MemberInit.get(); 2257 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc); 2258 } 2259 } 2260 2261 if (DirectMember) { 2262 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 2263 InitRange.getBegin(), Init, 2264 InitRange.getEnd()); 2265 } else { 2266 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 2267 InitRange.getBegin(), Init, 2268 InitRange.getEnd()); 2269 } 2270} 2271 2272MemInitResult 2273Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 2274 CXXRecordDecl *ClassDecl) { 2275 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 2276 if (!LangOpts.CPlusPlus0x) 2277 return Diag(NameLoc, diag::err_delegating_ctor) 2278 << TInfo->getTypeLoc().getLocalSourceRange(); 2279 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 2280 2281 bool InitList = true; 2282 Expr **Args = &Init; 2283 unsigned NumArgs = 1; 2284 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2285 InitList = false; 2286 Args = ParenList->getExprs(); 2287 NumArgs = ParenList->getNumExprs(); 2288 } 2289 2290 SourceRange InitRange = Init->getSourceRange(); 2291 // Initialize the object. 2292 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 2293 QualType(ClassDecl->getTypeForDecl(), 0)); 2294 InitializationKind Kind = 2295 InitList ? InitializationKind::CreateDirectList(NameLoc) 2296 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 2297 InitRange.getEnd()); 2298 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs); 2299 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 2300 MultiExprArg(Args, NumArgs), 2301 0); 2302 if (DelegationInit.isInvalid()) 2303 return true; 2304 2305 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 2306 "Delegating constructor with no target?"); 2307 2308 CheckImplicitConversions(DelegationInit.get(), InitRange.getBegin()); 2309 2310 // C++0x [class.base.init]p7: 2311 // The initialization of each base and member constitutes a 2312 // full-expression. 2313 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit); 2314 if (DelegationInit.isInvalid()) 2315 return true; 2316 2317 // If we are in a dependent context, template instantiation will 2318 // perform this type-checking again. Just save the arguments that we 2319 // received in a ParenListExpr. 2320 // FIXME: This isn't quite ideal, since our ASTs don't capture all 2321 // of the information that we have about the base 2322 // initializer. However, deconstructing the ASTs is a dicey process, 2323 // and this approach is far more likely to get the corner cases right. 2324 if (CurContext->isDependentContext()) 2325 DelegationInit = Owned(Init); 2326 2327 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 2328 DelegationInit.takeAs<Expr>(), 2329 InitRange.getEnd()); 2330} 2331 2332MemInitResult 2333Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 2334 Expr *Init, CXXRecordDecl *ClassDecl, 2335 SourceLocation EllipsisLoc) { 2336 SourceLocation BaseLoc 2337 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 2338 2339 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 2340 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 2341 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2342 2343 // C++ [class.base.init]p2: 2344 // [...] Unless the mem-initializer-id names a nonstatic data 2345 // member of the constructor's class or a direct or virtual base 2346 // of that class, the mem-initializer is ill-formed. A 2347 // mem-initializer-list can initialize a base class using any 2348 // name that denotes that base class type. 2349 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 2350 2351 SourceRange InitRange = Init->getSourceRange(); 2352 if (EllipsisLoc.isValid()) { 2353 // This is a pack expansion. 2354 if (!BaseType->containsUnexpandedParameterPack()) { 2355 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2356 << SourceRange(BaseLoc, InitRange.getEnd()); 2357 2358 EllipsisLoc = SourceLocation(); 2359 } 2360 } else { 2361 // Check for any unexpanded parameter packs. 2362 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 2363 return true; 2364 2365 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 2366 return true; 2367 } 2368 2369 // Check for direct and virtual base classes. 2370 const CXXBaseSpecifier *DirectBaseSpec = 0; 2371 const CXXBaseSpecifier *VirtualBaseSpec = 0; 2372 if (!Dependent) { 2373 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 2374 BaseType)) 2375 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 2376 2377 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 2378 VirtualBaseSpec); 2379 2380 // C++ [base.class.init]p2: 2381 // Unless the mem-initializer-id names a nonstatic data member of the 2382 // constructor's class or a direct or virtual base of that class, the 2383 // mem-initializer is ill-formed. 2384 if (!DirectBaseSpec && !VirtualBaseSpec) { 2385 // If the class has any dependent bases, then it's possible that 2386 // one of those types will resolve to the same type as 2387 // BaseType. Therefore, just treat this as a dependent base 2388 // class initialization. FIXME: Should we try to check the 2389 // initialization anyway? It seems odd. 2390 if (ClassDecl->hasAnyDependentBases()) 2391 Dependent = true; 2392 else 2393 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 2394 << BaseType << Context.getTypeDeclType(ClassDecl) 2395 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2396 } 2397 } 2398 2399 if (Dependent) { 2400 DiscardCleanupsInEvaluationContext(); 2401 2402 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 2403 /*IsVirtual=*/false, 2404 InitRange.getBegin(), Init, 2405 InitRange.getEnd(), EllipsisLoc); 2406 } 2407 2408 // C++ [base.class.init]p2: 2409 // If a mem-initializer-id is ambiguous because it designates both 2410 // a direct non-virtual base class and an inherited virtual base 2411 // class, the mem-initializer is ill-formed. 2412 if (DirectBaseSpec && VirtualBaseSpec) 2413 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 2414 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2415 2416 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec); 2417 if (!BaseSpec) 2418 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec); 2419 2420 // Initialize the base. 2421 bool InitList = true; 2422 Expr **Args = &Init; 2423 unsigned NumArgs = 1; 2424 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2425 InitList = false; 2426 Args = ParenList->getExprs(); 2427 NumArgs = ParenList->getNumExprs(); 2428 } 2429 2430 InitializedEntity BaseEntity = 2431 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 2432 InitializationKind Kind = 2433 InitList ? InitializationKind::CreateDirectList(BaseLoc) 2434 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 2435 InitRange.getEnd()); 2436 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs); 2437 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, 2438 MultiExprArg(Args, NumArgs), 0); 2439 if (BaseInit.isInvalid()) 2440 return true; 2441 2442 CheckImplicitConversions(BaseInit.get(), InitRange.getBegin()); 2443 2444 // C++0x [class.base.init]p7: 2445 // The initialization of each base and member constitutes a 2446 // full-expression. 2447 BaseInit = MaybeCreateExprWithCleanups(BaseInit); 2448 if (BaseInit.isInvalid()) 2449 return true; 2450 2451 // If we are in a dependent context, template instantiation will 2452 // perform this type-checking again. Just save the arguments that we 2453 // received in a ParenListExpr. 2454 // FIXME: This isn't quite ideal, since our ASTs don't capture all 2455 // of the information that we have about the base 2456 // initializer. However, deconstructing the ASTs is a dicey process, 2457 // and this approach is far more likely to get the corner cases right. 2458 if (CurContext->isDependentContext()) 2459 BaseInit = Owned(Init); 2460 2461 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 2462 BaseSpec->isVirtual(), 2463 InitRange.getBegin(), 2464 BaseInit.takeAs<Expr>(), 2465 InitRange.getEnd(), EllipsisLoc); 2466} 2467 2468// Create a static_cast\<T&&>(expr). 2469static Expr *CastForMoving(Sema &SemaRef, Expr *E) { 2470 QualType ExprType = E->getType(); 2471 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType); 2472 SourceLocation ExprLoc = E->getLocStart(); 2473 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 2474 TargetType, ExprLoc); 2475 2476 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 2477 SourceRange(ExprLoc, ExprLoc), 2478 E->getSourceRange()).take(); 2479} 2480 2481/// ImplicitInitializerKind - How an implicit base or member initializer should 2482/// initialize its base or member. 2483enum ImplicitInitializerKind { 2484 IIK_Default, 2485 IIK_Copy, 2486 IIK_Move 2487}; 2488 2489static bool 2490BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 2491 ImplicitInitializerKind ImplicitInitKind, 2492 CXXBaseSpecifier *BaseSpec, 2493 bool IsInheritedVirtualBase, 2494 CXXCtorInitializer *&CXXBaseInit) { 2495 InitializedEntity InitEntity 2496 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 2497 IsInheritedVirtualBase); 2498 2499 ExprResult BaseInit; 2500 2501 switch (ImplicitInitKind) { 2502 case IIK_Default: { 2503 InitializationKind InitKind 2504 = InitializationKind::CreateDefault(Constructor->getLocation()); 2505 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0); 2506 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg()); 2507 break; 2508 } 2509 2510 case IIK_Move: 2511 case IIK_Copy: { 2512 bool Moving = ImplicitInitKind == IIK_Move; 2513 ParmVarDecl *Param = Constructor->getParamDecl(0); 2514 QualType ParamType = Param->getType().getNonReferenceType(); 2515 2516 Expr *CopyCtorArg = 2517 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 2518 SourceLocation(), Param, false, 2519 Constructor->getLocation(), ParamType, 2520 VK_LValue, 0); 2521 2522 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 2523 2524 // Cast to the base class to avoid ambiguities. 2525 QualType ArgTy = 2526 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 2527 ParamType.getQualifiers()); 2528 2529 if (Moving) { 2530 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 2531 } 2532 2533 CXXCastPath BasePath; 2534 BasePath.push_back(BaseSpec); 2535 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 2536 CK_UncheckedDerivedToBase, 2537 Moving ? VK_XValue : VK_LValue, 2538 &BasePath).take(); 2539 2540 InitializationKind InitKind 2541 = InitializationKind::CreateDirect(Constructor->getLocation(), 2542 SourceLocation(), SourceLocation()); 2543 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 2544 &CopyCtorArg, 1); 2545 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, 2546 MultiExprArg(&CopyCtorArg, 1)); 2547 break; 2548 } 2549 } 2550 2551 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 2552 if (BaseInit.isInvalid()) 2553 return true; 2554 2555 CXXBaseInit = 2556 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 2557 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 2558 SourceLocation()), 2559 BaseSpec->isVirtual(), 2560 SourceLocation(), 2561 BaseInit.takeAs<Expr>(), 2562 SourceLocation(), 2563 SourceLocation()); 2564 2565 return false; 2566} 2567 2568static bool RefersToRValueRef(Expr *MemRef) { 2569 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 2570 return Referenced->getType()->isRValueReferenceType(); 2571} 2572 2573static bool 2574BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 2575 ImplicitInitializerKind ImplicitInitKind, 2576 FieldDecl *Field, IndirectFieldDecl *Indirect, 2577 CXXCtorInitializer *&CXXMemberInit) { 2578 if (Field->isInvalidDecl()) 2579 return true; 2580 2581 SourceLocation Loc = Constructor->getLocation(); 2582 2583 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 2584 bool Moving = ImplicitInitKind == IIK_Move; 2585 ParmVarDecl *Param = Constructor->getParamDecl(0); 2586 QualType ParamType = Param->getType().getNonReferenceType(); 2587 2588 // Suppress copying zero-width bitfields. 2589 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0) 2590 return false; 2591 2592 Expr *MemberExprBase = 2593 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 2594 SourceLocation(), Param, false, 2595 Loc, ParamType, VK_LValue, 0); 2596 2597 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 2598 2599 if (Moving) { 2600 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 2601 } 2602 2603 // Build a reference to this field within the parameter. 2604 CXXScopeSpec SS; 2605 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 2606 Sema::LookupMemberName); 2607 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 2608 : cast<ValueDecl>(Field), AS_public); 2609 MemberLookup.resolveKind(); 2610 ExprResult CtorArg 2611 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 2612 ParamType, Loc, 2613 /*IsArrow=*/false, 2614 SS, 2615 /*TemplateKWLoc=*/SourceLocation(), 2616 /*FirstQualifierInScope=*/0, 2617 MemberLookup, 2618 /*TemplateArgs=*/0); 2619 if (CtorArg.isInvalid()) 2620 return true; 2621 2622 // C++11 [class.copy]p15: 2623 // - if a member m has rvalue reference type T&&, it is direct-initialized 2624 // with static_cast<T&&>(x.m); 2625 if (RefersToRValueRef(CtorArg.get())) { 2626 CtorArg = CastForMoving(SemaRef, CtorArg.take()); 2627 } 2628 2629 // When the field we are copying is an array, create index variables for 2630 // each dimension of the array. We use these index variables to subscript 2631 // the source array, and other clients (e.g., CodeGen) will perform the 2632 // necessary iteration with these index variables. 2633 SmallVector<VarDecl *, 4> IndexVariables; 2634 QualType BaseType = Field->getType(); 2635 QualType SizeType = SemaRef.Context.getSizeType(); 2636 bool InitializingArray = false; 2637 while (const ConstantArrayType *Array 2638 = SemaRef.Context.getAsConstantArrayType(BaseType)) { 2639 InitializingArray = true; 2640 // Create the iteration variable for this array index. 2641 IdentifierInfo *IterationVarName = 0; 2642 { 2643 SmallString<8> Str; 2644 llvm::raw_svector_ostream OS(Str); 2645 OS << "__i" << IndexVariables.size(); 2646 IterationVarName = &SemaRef.Context.Idents.get(OS.str()); 2647 } 2648 VarDecl *IterationVar 2649 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc, 2650 IterationVarName, SizeType, 2651 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc), 2652 SC_None, SC_None); 2653 IndexVariables.push_back(IterationVar); 2654 2655 // Create a reference to the iteration variable. 2656 ExprResult IterationVarRef 2657 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 2658 assert(!IterationVarRef.isInvalid() && 2659 "Reference to invented variable cannot fail!"); 2660 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take()); 2661 assert(!IterationVarRef.isInvalid() && 2662 "Conversion of invented variable cannot fail!"); 2663 2664 // Subscript the array with this iteration variable. 2665 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc, 2666 IterationVarRef.take(), 2667 Loc); 2668 if (CtorArg.isInvalid()) 2669 return true; 2670 2671 BaseType = Array->getElementType(); 2672 } 2673 2674 // The array subscript expression is an lvalue, which is wrong for moving. 2675 if (Moving && InitializingArray) 2676 CtorArg = CastForMoving(SemaRef, CtorArg.take()); 2677 2678 // Construct the entity that we will be initializing. For an array, this 2679 // will be first element in the array, which may require several levels 2680 // of array-subscript entities. 2681 SmallVector<InitializedEntity, 4> Entities; 2682 Entities.reserve(1 + IndexVariables.size()); 2683 if (Indirect) 2684 Entities.push_back(InitializedEntity::InitializeMember(Indirect)); 2685 else 2686 Entities.push_back(InitializedEntity::InitializeMember(Field)); 2687 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 2688 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context, 2689 0, 2690 Entities.back())); 2691 2692 // Direct-initialize to use the copy constructor. 2693 InitializationKind InitKind = 2694 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 2695 2696 Expr *CtorArgE = CtorArg.takeAs<Expr>(); 2697 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, 2698 &CtorArgE, 1); 2699 2700 ExprResult MemberInit 2701 = InitSeq.Perform(SemaRef, Entities.back(), InitKind, 2702 MultiExprArg(&CtorArgE, 1)); 2703 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 2704 if (MemberInit.isInvalid()) 2705 return true; 2706 2707 if (Indirect) { 2708 assert(IndexVariables.size() == 0 && 2709 "Indirect field improperly initialized"); 2710 CXXMemberInit 2711 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 2712 Loc, Loc, 2713 MemberInit.takeAs<Expr>(), 2714 Loc); 2715 } else 2716 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, 2717 Loc, MemberInit.takeAs<Expr>(), 2718 Loc, 2719 IndexVariables.data(), 2720 IndexVariables.size()); 2721 return false; 2722 } 2723 2724 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!"); 2725 2726 QualType FieldBaseElementType = 2727 SemaRef.Context.getBaseElementType(Field->getType()); 2728 2729 if (FieldBaseElementType->isRecordType()) { 2730 InitializedEntity InitEntity 2731 = Indirect? InitializedEntity::InitializeMember(Indirect) 2732 : InitializedEntity::InitializeMember(Field); 2733 InitializationKind InitKind = 2734 InitializationKind::CreateDefault(Loc); 2735 2736 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0); 2737 ExprResult MemberInit = 2738 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg()); 2739 2740 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 2741 if (MemberInit.isInvalid()) 2742 return true; 2743 2744 if (Indirect) 2745 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 2746 Indirect, Loc, 2747 Loc, 2748 MemberInit.get(), 2749 Loc); 2750 else 2751 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 2752 Field, Loc, Loc, 2753 MemberInit.get(), 2754 Loc); 2755 return false; 2756 } 2757 2758 if (!Field->getParent()->isUnion()) { 2759 if (FieldBaseElementType->isReferenceType()) { 2760 SemaRef.Diag(Constructor->getLocation(), 2761 diag::err_uninitialized_member_in_ctor) 2762 << (int)Constructor->isImplicit() 2763 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 2764 << 0 << Field->getDeclName(); 2765 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 2766 return true; 2767 } 2768 2769 if (FieldBaseElementType.isConstQualified()) { 2770 SemaRef.Diag(Constructor->getLocation(), 2771 diag::err_uninitialized_member_in_ctor) 2772 << (int)Constructor->isImplicit() 2773 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 2774 << 1 << Field->getDeclName(); 2775 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 2776 return true; 2777 } 2778 } 2779 2780 if (SemaRef.getLangOpts().ObjCAutoRefCount && 2781 FieldBaseElementType->isObjCRetainableType() && 2782 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None && 2783 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) { 2784 // ARC: 2785 // Default-initialize Objective-C pointers to NULL. 2786 CXXMemberInit 2787 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 2788 Loc, Loc, 2789 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 2790 Loc); 2791 return false; 2792 } 2793 2794 // Nothing to initialize. 2795 CXXMemberInit = 0; 2796 return false; 2797} 2798 2799namespace { 2800struct BaseAndFieldInfo { 2801 Sema &S; 2802 CXXConstructorDecl *Ctor; 2803 bool AnyErrorsInInits; 2804 ImplicitInitializerKind IIK; 2805 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 2806 SmallVector<CXXCtorInitializer*, 8> AllToInit; 2807 2808 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 2809 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 2810 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 2811 if (Generated && Ctor->isCopyConstructor()) 2812 IIK = IIK_Copy; 2813 else if (Generated && Ctor->isMoveConstructor()) 2814 IIK = IIK_Move; 2815 else 2816 IIK = IIK_Default; 2817 } 2818 2819 bool isImplicitCopyOrMove() const { 2820 switch (IIK) { 2821 case IIK_Copy: 2822 case IIK_Move: 2823 return true; 2824 2825 case IIK_Default: 2826 return false; 2827 } 2828 2829 llvm_unreachable("Invalid ImplicitInitializerKind!"); 2830 } 2831 2832 bool addFieldInitializer(CXXCtorInitializer *Init) { 2833 AllToInit.push_back(Init); 2834 2835 // Check whether this initializer makes the field "used". 2836 if (Init->getInit() && Init->getInit()->HasSideEffects(S.Context)) 2837 S.UnusedPrivateFields.remove(Init->getAnyMember()); 2838 2839 return false; 2840 } 2841}; 2842} 2843 2844/// \brief Determine whether the given indirect field declaration is somewhere 2845/// within an anonymous union. 2846static bool isWithinAnonymousUnion(IndirectFieldDecl *F) { 2847 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(), 2848 CEnd = F->chain_end(); 2849 C != CEnd; ++C) 2850 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext())) 2851 if (Record->isUnion()) 2852 return true; 2853 2854 return false; 2855} 2856 2857/// \brief Determine whether the given type is an incomplete or zero-lenfgth 2858/// array type. 2859static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 2860 if (T->isIncompleteArrayType()) 2861 return true; 2862 2863 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 2864 if (!ArrayT->getSize()) 2865 return true; 2866 2867 T = ArrayT->getElementType(); 2868 } 2869 2870 return false; 2871} 2872 2873static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 2874 FieldDecl *Field, 2875 IndirectFieldDecl *Indirect = 0) { 2876 2877 // Overwhelmingly common case: we have a direct initializer for this field. 2878 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) 2879 return Info.addFieldInitializer(Init); 2880 2881 // C++11 [class.base.init]p8: if the entity is a non-static data member that 2882 // has a brace-or-equal-initializer, the entity is initialized as specified 2883 // in [dcl.init]. 2884 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 2885 CXXCtorInitializer *Init; 2886 if (Indirect) 2887 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 2888 SourceLocation(), 2889 SourceLocation(), 0, 2890 SourceLocation()); 2891 else 2892 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 2893 SourceLocation(), 2894 SourceLocation(), 0, 2895 SourceLocation()); 2896 return Info.addFieldInitializer(Init); 2897 } 2898 2899 // Don't build an implicit initializer for union members if none was 2900 // explicitly specified. 2901 if (Field->getParent()->isUnion() || 2902 (Indirect && isWithinAnonymousUnion(Indirect))) 2903 return false; 2904 2905 // Don't initialize incomplete or zero-length arrays. 2906 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 2907 return false; 2908 2909 // Don't try to build an implicit initializer if there were semantic 2910 // errors in any of the initializers (and therefore we might be 2911 // missing some that the user actually wrote). 2912 if (Info.AnyErrorsInInits || Field->isInvalidDecl()) 2913 return false; 2914 2915 CXXCtorInitializer *Init = 0; 2916 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 2917 Indirect, Init)) 2918 return true; 2919 2920 if (!Init) 2921 return false; 2922 2923 return Info.addFieldInitializer(Init); 2924} 2925 2926bool 2927Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 2928 CXXCtorInitializer *Initializer) { 2929 assert(Initializer->isDelegatingInitializer()); 2930 Constructor->setNumCtorInitializers(1); 2931 CXXCtorInitializer **initializer = 2932 new (Context) CXXCtorInitializer*[1]; 2933 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 2934 Constructor->setCtorInitializers(initializer); 2935 2936 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 2937 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 2938 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 2939 } 2940 2941 DelegatingCtorDecls.push_back(Constructor); 2942 2943 return false; 2944} 2945 2946bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, 2947 CXXCtorInitializer **Initializers, 2948 unsigned NumInitializers, 2949 bool AnyErrors) { 2950 if (Constructor->isDependentContext()) { 2951 // Just store the initializers as written, they will be checked during 2952 // instantiation. 2953 if (NumInitializers > 0) { 2954 Constructor->setNumCtorInitializers(NumInitializers); 2955 CXXCtorInitializer **baseOrMemberInitializers = 2956 new (Context) CXXCtorInitializer*[NumInitializers]; 2957 memcpy(baseOrMemberInitializers, Initializers, 2958 NumInitializers * sizeof(CXXCtorInitializer*)); 2959 Constructor->setCtorInitializers(baseOrMemberInitializers); 2960 } 2961 2962 return false; 2963 } 2964 2965 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 2966 2967 // We need to build the initializer AST according to order of construction 2968 // and not what user specified in the Initializers list. 2969 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 2970 if (!ClassDecl) 2971 return true; 2972 2973 bool HadError = false; 2974 2975 for (unsigned i = 0; i < NumInitializers; i++) { 2976 CXXCtorInitializer *Member = Initializers[i]; 2977 2978 if (Member->isBaseInitializer()) 2979 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 2980 else 2981 Info.AllBaseFields[Member->getAnyMember()] = Member; 2982 } 2983 2984 // Keep track of the direct virtual bases. 2985 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 2986 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(), 2987 E = ClassDecl->bases_end(); I != E; ++I) { 2988 if (I->isVirtual()) 2989 DirectVBases.insert(I); 2990 } 2991 2992 // Push virtual bases before others. 2993 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 2994 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 2995 2996 if (CXXCtorInitializer *Value 2997 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) { 2998 Info.AllToInit.push_back(Value); 2999 } else if (!AnyErrors) { 3000 bool IsInheritedVirtualBase = !DirectVBases.count(VBase); 3001 CXXCtorInitializer *CXXBaseInit; 3002 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3003 VBase, IsInheritedVirtualBase, 3004 CXXBaseInit)) { 3005 HadError = true; 3006 continue; 3007 } 3008 3009 Info.AllToInit.push_back(CXXBaseInit); 3010 } 3011 } 3012 3013 // Non-virtual bases. 3014 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 3015 E = ClassDecl->bases_end(); Base != E; ++Base) { 3016 // Virtuals are in the virtual base list and already constructed. 3017 if (Base->isVirtual()) 3018 continue; 3019 3020 if (CXXCtorInitializer *Value 3021 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) { 3022 Info.AllToInit.push_back(Value); 3023 } else if (!AnyErrors) { 3024 CXXCtorInitializer *CXXBaseInit; 3025 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3026 Base, /*IsInheritedVirtualBase=*/false, 3027 CXXBaseInit)) { 3028 HadError = true; 3029 continue; 3030 } 3031 3032 Info.AllToInit.push_back(CXXBaseInit); 3033 } 3034 } 3035 3036 // Fields. 3037 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(), 3038 MemEnd = ClassDecl->decls_end(); 3039 Mem != MemEnd; ++Mem) { 3040 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) { 3041 // C++ [class.bit]p2: 3042 // A declaration for a bit-field that omits the identifier declares an 3043 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 3044 // initialized. 3045 if (F->isUnnamedBitfield()) 3046 continue; 3047 3048 // If we're not generating the implicit copy/move constructor, then we'll 3049 // handle anonymous struct/union fields based on their individual 3050 // indirect fields. 3051 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default) 3052 continue; 3053 3054 if (CollectFieldInitializer(*this, Info, F)) 3055 HadError = true; 3056 continue; 3057 } 3058 3059 // Beyond this point, we only consider default initialization. 3060 if (Info.IIK != IIK_Default) 3061 continue; 3062 3063 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) { 3064 if (F->getType()->isIncompleteArrayType()) { 3065 assert(ClassDecl->hasFlexibleArrayMember() && 3066 "Incomplete array type is not valid"); 3067 continue; 3068 } 3069 3070 // Initialize each field of an anonymous struct individually. 3071 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 3072 HadError = true; 3073 3074 continue; 3075 } 3076 } 3077 3078 NumInitializers = Info.AllToInit.size(); 3079 if (NumInitializers > 0) { 3080 Constructor->setNumCtorInitializers(NumInitializers); 3081 CXXCtorInitializer **baseOrMemberInitializers = 3082 new (Context) CXXCtorInitializer*[NumInitializers]; 3083 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 3084 NumInitializers * sizeof(CXXCtorInitializer*)); 3085 Constructor->setCtorInitializers(baseOrMemberInitializers); 3086 3087 // Constructors implicitly reference the base and member 3088 // destructors. 3089 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 3090 Constructor->getParent()); 3091 } 3092 3093 return HadError; 3094} 3095 3096static void *GetKeyForTopLevelField(FieldDecl *Field) { 3097 // For anonymous unions, use the class declaration as the key. 3098 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 3099 if (RT->getDecl()->isAnonymousStructOrUnion()) 3100 return static_cast<void *>(RT->getDecl()); 3101 } 3102 return static_cast<void *>(Field); 3103} 3104 3105static void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 3106 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr()); 3107} 3108 3109static void *GetKeyForMember(ASTContext &Context, 3110 CXXCtorInitializer *Member) { 3111 if (!Member->isAnyMemberInitializer()) 3112 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 3113 3114 // For fields injected into the class via declaration of an anonymous union, 3115 // use its anonymous union class declaration as the unique key. 3116 FieldDecl *Field = Member->getAnyMember(); 3117 3118 // If the field is a member of an anonymous struct or union, our key 3119 // is the anonymous record decl that's a direct child of the class. 3120 RecordDecl *RD = Field->getParent(); 3121 if (RD->isAnonymousStructOrUnion()) { 3122 while (true) { 3123 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext()); 3124 if (Parent->isAnonymousStructOrUnion()) 3125 RD = Parent; 3126 else 3127 break; 3128 } 3129 3130 return static_cast<void *>(RD); 3131 } 3132 3133 return static_cast<void *>(Field); 3134} 3135 3136static void 3137DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef, 3138 const CXXConstructorDecl *Constructor, 3139 CXXCtorInitializer **Inits, 3140 unsigned NumInits) { 3141 if (Constructor->getDeclContext()->isDependentContext()) 3142 return; 3143 3144 // Don't check initializers order unless the warning is enabled at the 3145 // location of at least one initializer. 3146 bool ShouldCheckOrder = false; 3147 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) { 3148 CXXCtorInitializer *Init = Inits[InitIndex]; 3149 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order, 3150 Init->getSourceLocation()) 3151 != DiagnosticsEngine::Ignored) { 3152 ShouldCheckOrder = true; 3153 break; 3154 } 3155 } 3156 if (!ShouldCheckOrder) 3157 return; 3158 3159 // Build the list of bases and members in the order that they'll 3160 // actually be initialized. The explicit initializers should be in 3161 // this same order but may be missing things. 3162 SmallVector<const void*, 32> IdealInitKeys; 3163 3164 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 3165 3166 // 1. Virtual bases. 3167 for (CXXRecordDecl::base_class_const_iterator VBase = 3168 ClassDecl->vbases_begin(), 3169 E = ClassDecl->vbases_end(); VBase != E; ++VBase) 3170 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType())); 3171 3172 // 2. Non-virtual bases. 3173 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(), 3174 E = ClassDecl->bases_end(); Base != E; ++Base) { 3175 if (Base->isVirtual()) 3176 continue; 3177 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType())); 3178 } 3179 3180 // 3. Direct fields. 3181 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 3182 E = ClassDecl->field_end(); Field != E; ++Field) { 3183 if (Field->isUnnamedBitfield()) 3184 continue; 3185 3186 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field)); 3187 } 3188 3189 unsigned NumIdealInits = IdealInitKeys.size(); 3190 unsigned IdealIndex = 0; 3191 3192 CXXCtorInitializer *PrevInit = 0; 3193 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) { 3194 CXXCtorInitializer *Init = Inits[InitIndex]; 3195 void *InitKey = GetKeyForMember(SemaRef.Context, Init); 3196 3197 // Scan forward to try to find this initializer in the idealized 3198 // initializers list. 3199 for (; IdealIndex != NumIdealInits; ++IdealIndex) 3200 if (InitKey == IdealInitKeys[IdealIndex]) 3201 break; 3202 3203 // If we didn't find this initializer, it must be because we 3204 // scanned past it on a previous iteration. That can only 3205 // happen if we're out of order; emit a warning. 3206 if (IdealIndex == NumIdealInits && PrevInit) { 3207 Sema::SemaDiagnosticBuilder D = 3208 SemaRef.Diag(PrevInit->getSourceLocation(), 3209 diag::warn_initializer_out_of_order); 3210 3211 if (PrevInit->isAnyMemberInitializer()) 3212 D << 0 << PrevInit->getAnyMember()->getDeclName(); 3213 else 3214 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 3215 3216 if (Init->isAnyMemberInitializer()) 3217 D << 0 << Init->getAnyMember()->getDeclName(); 3218 else 3219 D << 1 << Init->getTypeSourceInfo()->getType(); 3220 3221 // Move back to the initializer's location in the ideal list. 3222 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 3223 if (InitKey == IdealInitKeys[IdealIndex]) 3224 break; 3225 3226 assert(IdealIndex != NumIdealInits && 3227 "initializer not found in initializer list"); 3228 } 3229 3230 PrevInit = Init; 3231 } 3232} 3233 3234namespace { 3235bool CheckRedundantInit(Sema &S, 3236 CXXCtorInitializer *Init, 3237 CXXCtorInitializer *&PrevInit) { 3238 if (!PrevInit) { 3239 PrevInit = Init; 3240 return false; 3241 } 3242 3243 if (FieldDecl *Field = Init->getMember()) 3244 S.Diag(Init->getSourceLocation(), 3245 diag::err_multiple_mem_initialization) 3246 << Field->getDeclName() 3247 << Init->getSourceRange(); 3248 else { 3249 const Type *BaseClass = Init->getBaseClass(); 3250 assert(BaseClass && "neither field nor base"); 3251 S.Diag(Init->getSourceLocation(), 3252 diag::err_multiple_base_initialization) 3253 << QualType(BaseClass, 0) 3254 << Init->getSourceRange(); 3255 } 3256 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 3257 << 0 << PrevInit->getSourceRange(); 3258 3259 return true; 3260} 3261 3262typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 3263typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 3264 3265bool CheckRedundantUnionInit(Sema &S, 3266 CXXCtorInitializer *Init, 3267 RedundantUnionMap &Unions) { 3268 FieldDecl *Field = Init->getAnyMember(); 3269 RecordDecl *Parent = Field->getParent(); 3270 NamedDecl *Child = Field; 3271 3272 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 3273 if (Parent->isUnion()) { 3274 UnionEntry &En = Unions[Parent]; 3275 if (En.first && En.first != Child) { 3276 S.Diag(Init->getSourceLocation(), 3277 diag::err_multiple_mem_union_initialization) 3278 << Field->getDeclName() 3279 << Init->getSourceRange(); 3280 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 3281 << 0 << En.second->getSourceRange(); 3282 return true; 3283 } 3284 if (!En.first) { 3285 En.first = Child; 3286 En.second = Init; 3287 } 3288 if (!Parent->isAnonymousStructOrUnion()) 3289 return false; 3290 } 3291 3292 Child = Parent; 3293 Parent = cast<RecordDecl>(Parent->getDeclContext()); 3294 } 3295 3296 return false; 3297} 3298} 3299 3300/// ActOnMemInitializers - Handle the member initializers for a constructor. 3301void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 3302 SourceLocation ColonLoc, 3303 CXXCtorInitializer **meminits, 3304 unsigned NumMemInits, 3305 bool AnyErrors) { 3306 if (!ConstructorDecl) 3307 return; 3308 3309 AdjustDeclIfTemplate(ConstructorDecl); 3310 3311 CXXConstructorDecl *Constructor 3312 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 3313 3314 if (!Constructor) { 3315 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 3316 return; 3317 } 3318 3319 CXXCtorInitializer **MemInits = 3320 reinterpret_cast<CXXCtorInitializer **>(meminits); 3321 3322 // Mapping for the duplicate initializers check. 3323 // For member initializers, this is keyed with a FieldDecl*. 3324 // For base initializers, this is keyed with a Type*. 3325 llvm::DenseMap<void*, CXXCtorInitializer *> Members; 3326 3327 // Mapping for the inconsistent anonymous-union initializers check. 3328 RedundantUnionMap MemberUnions; 3329 3330 bool HadError = false; 3331 for (unsigned i = 0; i < NumMemInits; i++) { 3332 CXXCtorInitializer *Init = MemInits[i]; 3333 3334 // Set the source order index. 3335 Init->setSourceOrder(i); 3336 3337 if (Init->isAnyMemberInitializer()) { 3338 FieldDecl *Field = Init->getAnyMember(); 3339 if (CheckRedundantInit(*this, Init, Members[Field]) || 3340 CheckRedundantUnionInit(*this, Init, MemberUnions)) 3341 HadError = true; 3342 } else if (Init->isBaseInitializer()) { 3343 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0)); 3344 if (CheckRedundantInit(*this, Init, Members[Key])) 3345 HadError = true; 3346 } else { 3347 assert(Init->isDelegatingInitializer()); 3348 // This must be the only initializer 3349 if (NumMemInits != 1) { 3350 Diag(Init->getSourceLocation(), 3351 diag::err_delegating_initializer_alone) 3352 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 3353 // We will treat this as being the only initializer. 3354 } 3355 SetDelegatingInitializer(Constructor, MemInits[i]); 3356 // Return immediately as the initializer is set. 3357 return; 3358 } 3359 } 3360 3361 if (HadError) 3362 return; 3363 3364 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits); 3365 3366 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors); 3367} 3368 3369void 3370Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 3371 CXXRecordDecl *ClassDecl) { 3372 // Ignore dependent contexts. Also ignore unions, since their members never 3373 // have destructors implicitly called. 3374 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 3375 return; 3376 3377 // FIXME: all the access-control diagnostics are positioned on the 3378 // field/base declaration. That's probably good; that said, the 3379 // user might reasonably want to know why the destructor is being 3380 // emitted, and we currently don't say. 3381 3382 // Non-static data members. 3383 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(), 3384 E = ClassDecl->field_end(); I != E; ++I) { 3385 FieldDecl *Field = *I; 3386 if (Field->isInvalidDecl()) 3387 continue; 3388 3389 // Don't destroy incomplete or zero-length arrays. 3390 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 3391 continue; 3392 3393 QualType FieldType = Context.getBaseElementType(Field->getType()); 3394 3395 const RecordType* RT = FieldType->getAs<RecordType>(); 3396 if (!RT) 3397 continue; 3398 3399 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3400 if (FieldClassDecl->isInvalidDecl()) 3401 continue; 3402 if (FieldClassDecl->hasIrrelevantDestructor()) 3403 continue; 3404 // The destructor for an implicit anonymous union member is never invoked. 3405 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 3406 continue; 3407 3408 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 3409 assert(Dtor && "No dtor found for FieldClassDecl!"); 3410 CheckDestructorAccess(Field->getLocation(), Dtor, 3411 PDiag(diag::err_access_dtor_field) 3412 << Field->getDeclName() 3413 << FieldType); 3414 3415 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 3416 DiagnoseUseOfDecl(Dtor, Location); 3417 } 3418 3419 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 3420 3421 // Bases. 3422 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 3423 E = ClassDecl->bases_end(); Base != E; ++Base) { 3424 // Bases are always records in a well-formed non-dependent class. 3425 const RecordType *RT = Base->getType()->getAs<RecordType>(); 3426 3427 // Remember direct virtual bases. 3428 if (Base->isVirtual()) 3429 DirectVirtualBases.insert(RT); 3430 3431 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3432 // If our base class is invalid, we probably can't get its dtor anyway. 3433 if (BaseClassDecl->isInvalidDecl()) 3434 continue; 3435 if (BaseClassDecl->hasIrrelevantDestructor()) 3436 continue; 3437 3438 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 3439 assert(Dtor && "No dtor found for BaseClassDecl!"); 3440 3441 // FIXME: caret should be on the start of the class name 3442 CheckDestructorAccess(Base->getLocStart(), Dtor, 3443 PDiag(diag::err_access_dtor_base) 3444 << Base->getType() 3445 << Base->getSourceRange(), 3446 Context.getTypeDeclType(ClassDecl)); 3447 3448 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 3449 DiagnoseUseOfDecl(Dtor, Location); 3450 } 3451 3452 // Virtual bases. 3453 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 3454 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 3455 3456 // Bases are always records in a well-formed non-dependent class. 3457 const RecordType *RT = VBase->getType()->castAs<RecordType>(); 3458 3459 // Ignore direct virtual bases. 3460 if (DirectVirtualBases.count(RT)) 3461 continue; 3462 3463 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3464 // If our base class is invalid, we probably can't get its dtor anyway. 3465 if (BaseClassDecl->isInvalidDecl()) 3466 continue; 3467 if (BaseClassDecl->hasIrrelevantDestructor()) 3468 continue; 3469 3470 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 3471 assert(Dtor && "No dtor found for BaseClassDecl!"); 3472 CheckDestructorAccess(ClassDecl->getLocation(), Dtor, 3473 PDiag(diag::err_access_dtor_vbase) 3474 << VBase->getType(), 3475 Context.getTypeDeclType(ClassDecl)); 3476 3477 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 3478 DiagnoseUseOfDecl(Dtor, Location); 3479 } 3480} 3481 3482void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 3483 if (!CDtorDecl) 3484 return; 3485 3486 if (CXXConstructorDecl *Constructor 3487 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) 3488 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false); 3489} 3490 3491bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 3492 unsigned DiagID, AbstractDiagSelID SelID) { 3493 class NonAbstractTypeDiagnoser : public TypeDiagnoser { 3494 unsigned DiagID; 3495 AbstractDiagSelID SelID; 3496 3497 public: 3498 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID) 3499 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { } 3500 3501 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 3502 if (Suppressed) return; 3503 if (SelID == -1) 3504 S.Diag(Loc, DiagID) << T; 3505 else 3506 S.Diag(Loc, DiagID) << SelID << T; 3507 } 3508 } Diagnoser(DiagID, SelID); 3509 3510 return RequireNonAbstractType(Loc, T, Diagnoser); 3511} 3512 3513bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 3514 TypeDiagnoser &Diagnoser) { 3515 if (!getLangOpts().CPlusPlus) 3516 return false; 3517 3518 if (const ArrayType *AT = Context.getAsArrayType(T)) 3519 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 3520 3521 if (const PointerType *PT = T->getAs<PointerType>()) { 3522 // Find the innermost pointer type. 3523 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 3524 PT = T; 3525 3526 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 3527 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 3528 } 3529 3530 const RecordType *RT = T->getAs<RecordType>(); 3531 if (!RT) 3532 return false; 3533 3534 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 3535 3536 // We can't answer whether something is abstract until it has a 3537 // definition. If it's currently being defined, we'll walk back 3538 // over all the declarations when we have a full definition. 3539 const CXXRecordDecl *Def = RD->getDefinition(); 3540 if (!Def || Def->isBeingDefined()) 3541 return false; 3542 3543 if (!RD->isAbstract()) 3544 return false; 3545 3546 Diagnoser.diagnose(*this, Loc, T); 3547 DiagnoseAbstractType(RD); 3548 3549 return true; 3550} 3551 3552void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 3553 // Check if we've already emitted the list of pure virtual functions 3554 // for this class. 3555 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 3556 return; 3557 3558 CXXFinalOverriderMap FinalOverriders; 3559 RD->getFinalOverriders(FinalOverriders); 3560 3561 // Keep a set of seen pure methods so we won't diagnose the same method 3562 // more than once. 3563 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 3564 3565 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 3566 MEnd = FinalOverriders.end(); 3567 M != MEnd; 3568 ++M) { 3569 for (OverridingMethods::iterator SO = M->second.begin(), 3570 SOEnd = M->second.end(); 3571 SO != SOEnd; ++SO) { 3572 // C++ [class.abstract]p4: 3573 // A class is abstract if it contains or inherits at least one 3574 // pure virtual function for which the final overrider is pure 3575 // virtual. 3576 3577 // 3578 if (SO->second.size() != 1) 3579 continue; 3580 3581 if (!SO->second.front().Method->isPure()) 3582 continue; 3583 3584 if (!SeenPureMethods.insert(SO->second.front().Method)) 3585 continue; 3586 3587 Diag(SO->second.front().Method->getLocation(), 3588 diag::note_pure_virtual_function) 3589 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 3590 } 3591 } 3592 3593 if (!PureVirtualClassDiagSet) 3594 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 3595 PureVirtualClassDiagSet->insert(RD); 3596} 3597 3598namespace { 3599struct AbstractUsageInfo { 3600 Sema &S; 3601 CXXRecordDecl *Record; 3602 CanQualType AbstractType; 3603 bool Invalid; 3604 3605 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 3606 : S(S), Record(Record), 3607 AbstractType(S.Context.getCanonicalType( 3608 S.Context.getTypeDeclType(Record))), 3609 Invalid(false) {} 3610 3611 void DiagnoseAbstractType() { 3612 if (Invalid) return; 3613 S.DiagnoseAbstractType(Record); 3614 Invalid = true; 3615 } 3616 3617 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 3618}; 3619 3620struct CheckAbstractUsage { 3621 AbstractUsageInfo &Info; 3622 const NamedDecl *Ctx; 3623 3624 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 3625 : Info(Info), Ctx(Ctx) {} 3626 3627 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 3628 switch (TL.getTypeLocClass()) { 3629#define ABSTRACT_TYPELOC(CLASS, PARENT) 3630#define TYPELOC(CLASS, PARENT) \ 3631 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break; 3632#include "clang/AST/TypeLocNodes.def" 3633 } 3634 } 3635 3636 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 3637 Visit(TL.getResultLoc(), Sema::AbstractReturnType); 3638 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 3639 if (!TL.getArg(I)) 3640 continue; 3641 3642 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo(); 3643 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 3644 } 3645 } 3646 3647 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 3648 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 3649 } 3650 3651 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 3652 // Visit the type parameters from a permissive context. 3653 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 3654 TemplateArgumentLoc TAL = TL.getArgLoc(I); 3655 if (TAL.getArgument().getKind() == TemplateArgument::Type) 3656 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 3657 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 3658 // TODO: other template argument types? 3659 } 3660 } 3661 3662 // Visit pointee types from a permissive context. 3663#define CheckPolymorphic(Type) \ 3664 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 3665 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 3666 } 3667 CheckPolymorphic(PointerTypeLoc) 3668 CheckPolymorphic(ReferenceTypeLoc) 3669 CheckPolymorphic(MemberPointerTypeLoc) 3670 CheckPolymorphic(BlockPointerTypeLoc) 3671 CheckPolymorphic(AtomicTypeLoc) 3672 3673 /// Handle all the types we haven't given a more specific 3674 /// implementation for above. 3675 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 3676 // Every other kind of type that we haven't called out already 3677 // that has an inner type is either (1) sugar or (2) contains that 3678 // inner type in some way as a subobject. 3679 if (TypeLoc Next = TL.getNextTypeLoc()) 3680 return Visit(Next, Sel); 3681 3682 // If there's no inner type and we're in a permissive context, 3683 // don't diagnose. 3684 if (Sel == Sema::AbstractNone) return; 3685 3686 // Check whether the type matches the abstract type. 3687 QualType T = TL.getType(); 3688 if (T->isArrayType()) { 3689 Sel = Sema::AbstractArrayType; 3690 T = Info.S.Context.getBaseElementType(T); 3691 } 3692 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 3693 if (CT != Info.AbstractType) return; 3694 3695 // It matched; do some magic. 3696 if (Sel == Sema::AbstractArrayType) { 3697 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 3698 << T << TL.getSourceRange(); 3699 } else { 3700 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 3701 << Sel << T << TL.getSourceRange(); 3702 } 3703 Info.DiagnoseAbstractType(); 3704 } 3705}; 3706 3707void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 3708 Sema::AbstractDiagSelID Sel) { 3709 CheckAbstractUsage(*this, D).Visit(TL, Sel); 3710} 3711 3712} 3713 3714/// Check for invalid uses of an abstract type in a method declaration. 3715static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 3716 CXXMethodDecl *MD) { 3717 // No need to do the check on definitions, which require that 3718 // the return/param types be complete. 3719 if (MD->doesThisDeclarationHaveABody()) 3720 return; 3721 3722 // For safety's sake, just ignore it if we don't have type source 3723 // information. This should never happen for non-implicit methods, 3724 // but... 3725 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 3726 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 3727} 3728 3729/// Check for invalid uses of an abstract type within a class definition. 3730static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 3731 CXXRecordDecl *RD) { 3732 for (CXXRecordDecl::decl_iterator 3733 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) { 3734 Decl *D = *I; 3735 if (D->isImplicit()) continue; 3736 3737 // Methods and method templates. 3738 if (isa<CXXMethodDecl>(D)) { 3739 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 3740 } else if (isa<FunctionTemplateDecl>(D)) { 3741 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 3742 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 3743 3744 // Fields and static variables. 3745 } else if (isa<FieldDecl>(D)) { 3746 FieldDecl *FD = cast<FieldDecl>(D); 3747 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 3748 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 3749 } else if (isa<VarDecl>(D)) { 3750 VarDecl *VD = cast<VarDecl>(D); 3751 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 3752 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 3753 3754 // Nested classes and class templates. 3755 } else if (isa<CXXRecordDecl>(D)) { 3756 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 3757 } else if (isa<ClassTemplateDecl>(D)) { 3758 CheckAbstractClassUsage(Info, 3759 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 3760 } 3761 } 3762} 3763 3764/// \brief Perform semantic checks on a class definition that has been 3765/// completing, introducing implicitly-declared members, checking for 3766/// abstract types, etc. 3767void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 3768 if (!Record) 3769 return; 3770 3771 if (Record->isAbstract() && !Record->isInvalidDecl()) { 3772 AbstractUsageInfo Info(*this, Record); 3773 CheckAbstractClassUsage(Info, Record); 3774 } 3775 3776 // If this is not an aggregate type and has no user-declared constructor, 3777 // complain about any non-static data members of reference or const scalar 3778 // type, since they will never get initializers. 3779 if (!Record->isInvalidDecl() && !Record->isDependentType() && 3780 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 3781 !Record->isLambda()) { 3782 bool Complained = false; 3783 for (RecordDecl::field_iterator F = Record->field_begin(), 3784 FEnd = Record->field_end(); 3785 F != FEnd; ++F) { 3786 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 3787 continue; 3788 3789 if (F->getType()->isReferenceType() || 3790 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 3791 if (!Complained) { 3792 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 3793 << Record->getTagKind() << Record; 3794 Complained = true; 3795 } 3796 3797 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 3798 << F->getType()->isReferenceType() 3799 << F->getDeclName(); 3800 } 3801 } 3802 } 3803 3804 if (Record->isDynamicClass() && !Record->isDependentType()) 3805 DynamicClasses.push_back(Record); 3806 3807 if (Record->getIdentifier()) { 3808 // C++ [class.mem]p13: 3809 // If T is the name of a class, then each of the following shall have a 3810 // name different from T: 3811 // - every member of every anonymous union that is a member of class T. 3812 // 3813 // C++ [class.mem]p14: 3814 // In addition, if class T has a user-declared constructor (12.1), every 3815 // non-static data member of class T shall have a name different from T. 3816 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 3817 R.first != R.second; ++R.first) { 3818 NamedDecl *D = *R.first; 3819 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 3820 isa<IndirectFieldDecl>(D)) { 3821 Diag(D->getLocation(), diag::err_member_name_of_class) 3822 << D->getDeclName(); 3823 break; 3824 } 3825 } 3826 } 3827 3828 // Warn if the class has virtual methods but non-virtual public destructor. 3829 if (Record->isPolymorphic() && !Record->isDependentType()) { 3830 CXXDestructorDecl *dtor = Record->getDestructor(); 3831 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) 3832 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 3833 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 3834 } 3835 3836 // See if a method overloads virtual methods in a base 3837 /// class without overriding any. 3838 if (!Record->isDependentType()) { 3839 for (CXXRecordDecl::method_iterator M = Record->method_begin(), 3840 MEnd = Record->method_end(); 3841 M != MEnd; ++M) { 3842 if (!M->isStatic()) 3843 DiagnoseHiddenVirtualMethods(Record, *M); 3844 } 3845 } 3846 3847 // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member 3848 // function that is not a constructor declares that member function to be 3849 // const. [...] The class of which that function is a member shall be 3850 // a literal type. 3851 // 3852 // If the class has virtual bases, any constexpr members will already have 3853 // been diagnosed by the checks performed on the member declaration, so 3854 // suppress this (less useful) diagnostic. 3855 if (LangOpts.CPlusPlus0x && !Record->isDependentType() && 3856 !Record->isLiteral() && !Record->getNumVBases()) { 3857 for (CXXRecordDecl::method_iterator M = Record->method_begin(), 3858 MEnd = Record->method_end(); 3859 M != MEnd; ++M) { 3860 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) { 3861 switch (Record->getTemplateSpecializationKind()) { 3862 case TSK_ImplicitInstantiation: 3863 case TSK_ExplicitInstantiationDeclaration: 3864 case TSK_ExplicitInstantiationDefinition: 3865 // If a template instantiates to a non-literal type, but its members 3866 // instantiate to constexpr functions, the template is technically 3867 // ill-formed, but we allow it for sanity. 3868 continue; 3869 3870 case TSK_Undeclared: 3871 case TSK_ExplicitSpecialization: 3872 RequireLiteralType(M->getLocation(), Context.getRecordType(Record), 3873 diag::err_constexpr_method_non_literal); 3874 break; 3875 } 3876 3877 // Only produce one error per class. 3878 break; 3879 } 3880 } 3881 } 3882 3883 // Declare inherited constructors. We do this eagerly here because: 3884 // - The standard requires an eager diagnostic for conflicting inherited 3885 // constructors from different classes. 3886 // - The lazy declaration of the other implicit constructors is so as to not 3887 // waste space and performance on classes that are not meant to be 3888 // instantiated (e.g. meta-functions). This doesn't apply to classes that 3889 // have inherited constructors. 3890 DeclareInheritedConstructors(Record); 3891} 3892 3893void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) { 3894 for (CXXRecordDecl::method_iterator MI = Record->method_begin(), 3895 ME = Record->method_end(); 3896 MI != ME; ++MI) 3897 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) 3898 CheckExplicitlyDefaultedSpecialMember(*MI); 3899} 3900 3901/// Is the special member function which would be selected to perform the 3902/// specified operation on the specified class type a constexpr constructor? 3903static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 3904 Sema::CXXSpecialMember CSM, 3905 bool ConstArg) { 3906 Sema::SpecialMemberOverloadResult *SMOR = 3907 S.LookupSpecialMember(ClassDecl, CSM, ConstArg, 3908 false, false, false, false); 3909 if (!SMOR || !SMOR->getMethod()) 3910 // A constructor we wouldn't select can't be "involved in initializing" 3911 // anything. 3912 return true; 3913 return SMOR->getMethod()->isConstexpr(); 3914} 3915 3916/// Determine whether the specified special member function would be constexpr 3917/// if it were implicitly defined. 3918static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 3919 Sema::CXXSpecialMember CSM, 3920 bool ConstArg) { 3921 if (!S.getLangOpts().CPlusPlus0x) 3922 return false; 3923 3924 // C++11 [dcl.constexpr]p4: 3925 // In the definition of a constexpr constructor [...] 3926 switch (CSM) { 3927 case Sema::CXXDefaultConstructor: 3928 // Since default constructor lookup is essentially trivial (and cannot 3929 // involve, for instance, template instantiation), we compute whether a 3930 // defaulted default constructor is constexpr directly within CXXRecordDecl. 3931 // 3932 // This is important for performance; we need to know whether the default 3933 // constructor is constexpr to determine whether the type is a literal type. 3934 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 3935 3936 case Sema::CXXCopyConstructor: 3937 case Sema::CXXMoveConstructor: 3938 // For copy or move constructors, we need to perform overload resolution. 3939 break; 3940 3941 case Sema::CXXCopyAssignment: 3942 case Sema::CXXMoveAssignment: 3943 case Sema::CXXDestructor: 3944 case Sema::CXXInvalid: 3945 return false; 3946 } 3947 3948 // -- if the class is a non-empty union, or for each non-empty anonymous 3949 // union member of a non-union class, exactly one non-static data member 3950 // shall be initialized; [DR1359] 3951 // 3952 // If we squint, this is guaranteed, since exactly one non-static data member 3953 // will be initialized (if the constructor isn't deleted), we just don't know 3954 // which one. 3955 if (ClassDecl->isUnion()) 3956 return true; 3957 3958 // -- the class shall not have any virtual base classes; 3959 if (ClassDecl->getNumVBases()) 3960 return false; 3961 3962 // -- every constructor involved in initializing [...] base class 3963 // sub-objects shall be a constexpr constructor; 3964 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 3965 BEnd = ClassDecl->bases_end(); 3966 B != BEnd; ++B) { 3967 const RecordType *BaseType = B->getType()->getAs<RecordType>(); 3968 if (!BaseType) continue; 3969 3970 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 3971 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg)) 3972 return false; 3973 } 3974 3975 // -- every constructor involved in initializing non-static data members 3976 // [...] shall be a constexpr constructor; 3977 // -- every non-static data member and base class sub-object shall be 3978 // initialized 3979 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 3980 FEnd = ClassDecl->field_end(); 3981 F != FEnd; ++F) { 3982 if (F->isInvalidDecl()) 3983 continue; 3984 if (const RecordType *RecordTy = 3985 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 3986 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 3987 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg)) 3988 return false; 3989 } 3990 } 3991 3992 // All OK, it's constexpr! 3993 return true; 3994} 3995 3996static Sema::ImplicitExceptionSpecification 3997computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 3998 switch (S.getSpecialMember(MD)) { 3999 case Sema::CXXDefaultConstructor: 4000 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD); 4001 case Sema::CXXCopyConstructor: 4002 return S.ComputeDefaultedCopyCtorExceptionSpec(MD); 4003 case Sema::CXXCopyAssignment: 4004 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD); 4005 case Sema::CXXMoveConstructor: 4006 return S.ComputeDefaultedMoveCtorExceptionSpec(MD); 4007 case Sema::CXXMoveAssignment: 4008 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD); 4009 case Sema::CXXDestructor: 4010 return S.ComputeDefaultedDtorExceptionSpec(MD); 4011 case Sema::CXXInvalid: 4012 break; 4013 } 4014 llvm_unreachable("only special members have implicit exception specs"); 4015} 4016 4017static void 4018updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT, 4019 const Sema::ImplicitExceptionSpecification &ExceptSpec) { 4020 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 4021 ExceptSpec.getEPI(EPI); 4022 const FunctionProtoType *NewFPT = cast<FunctionProtoType>( 4023 S.Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(), 4024 FPT->getNumArgs(), EPI)); 4025 FD->setType(QualType(NewFPT, 0)); 4026} 4027 4028void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 4029 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 4030 if (FPT->getExceptionSpecType() != EST_Unevaluated) 4031 return; 4032 4033 // Evaluate the exception specification. 4034 ImplicitExceptionSpecification ExceptSpec = 4035 computeImplicitExceptionSpec(*this, Loc, MD); 4036 4037 // Update the type of the special member to use it. 4038 updateExceptionSpec(*this, MD, FPT, ExceptSpec); 4039 4040 // A user-provided destructor can be defined outside the class. When that 4041 // happens, be sure to update the exception specification on both 4042 // declarations. 4043 const FunctionProtoType *CanonicalFPT = 4044 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 4045 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 4046 updateExceptionSpec(*this, MD->getCanonicalDecl(), 4047 CanonicalFPT, ExceptSpec); 4048} 4049 4050static bool isImplicitCopyCtorArgConst(Sema &S, CXXRecordDecl *ClassDecl); 4051static bool isImplicitCopyAssignmentArgConst(Sema &S, CXXRecordDecl *ClassDecl); 4052 4053void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 4054 CXXRecordDecl *RD = MD->getParent(); 4055 CXXSpecialMember CSM = getSpecialMember(MD); 4056 4057 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 4058 "not an explicitly-defaulted special member"); 4059 4060 // Whether this was the first-declared instance of the constructor. 4061 // This affects whether we implicitly add an exception spec and constexpr. 4062 bool First = MD == MD->getCanonicalDecl(); 4063 4064 bool HadError = false; 4065 4066 // C++11 [dcl.fct.def.default]p1: 4067 // A function that is explicitly defaulted shall 4068 // -- be a special member function (checked elsewhere), 4069 // -- have the same type (except for ref-qualifiers, and except that a 4070 // copy operation can take a non-const reference) as an implicit 4071 // declaration, and 4072 // -- not have default arguments. 4073 unsigned ExpectedParams = 1; 4074 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 4075 ExpectedParams = 0; 4076 if (MD->getNumParams() != ExpectedParams) { 4077 // This also checks for default arguments: a copy or move constructor with a 4078 // default argument is classified as a default constructor, and assignment 4079 // operations and destructors can't have default arguments. 4080 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 4081 << CSM << MD->getSourceRange(); 4082 HadError = true; 4083 } 4084 4085 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 4086 4087 // Compute argument constness, constexpr, and triviality. 4088 bool CanHaveConstParam = false; 4089 bool Trivial = false; 4090 switch (CSM) { 4091 case CXXDefaultConstructor: 4092 Trivial = RD->hasTrivialDefaultConstructor(); 4093 break; 4094 case CXXCopyConstructor: 4095 CanHaveConstParam = isImplicitCopyCtorArgConst(*this, RD); 4096 Trivial = RD->hasTrivialCopyConstructor(); 4097 break; 4098 case CXXCopyAssignment: 4099 CanHaveConstParam = isImplicitCopyAssignmentArgConst(*this, RD); 4100 Trivial = RD->hasTrivialCopyAssignment(); 4101 break; 4102 case CXXMoveConstructor: 4103 Trivial = RD->hasTrivialMoveConstructor(); 4104 break; 4105 case CXXMoveAssignment: 4106 Trivial = RD->hasTrivialMoveAssignment(); 4107 break; 4108 case CXXDestructor: 4109 Trivial = RD->hasTrivialDestructor(); 4110 break; 4111 case CXXInvalid: 4112 llvm_unreachable("non-special member explicitly defaulted!"); 4113 } 4114 4115 QualType ReturnType = Context.VoidTy; 4116 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 4117 // Check for return type matching. 4118 ReturnType = Type->getResultType(); 4119 QualType ExpectedReturnType = 4120 Context.getLValueReferenceType(Context.getTypeDeclType(RD)); 4121 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 4122 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 4123 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 4124 HadError = true; 4125 } 4126 4127 // A defaulted special member cannot have cv-qualifiers. 4128 if (Type->getTypeQuals()) { 4129 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 4130 << (CSM == CXXMoveAssignment); 4131 HadError = true; 4132 } 4133 } 4134 4135 // Check for parameter type matching. 4136 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType(); 4137 bool HasConstParam = false; 4138 if (ExpectedParams && ArgType->isReferenceType()) { 4139 // Argument must be reference to possibly-const T. 4140 QualType ReferentType = ArgType->getPointeeType(); 4141 HasConstParam = ReferentType.isConstQualified(); 4142 4143 if (ReferentType.isVolatileQualified()) { 4144 Diag(MD->getLocation(), 4145 diag::err_defaulted_special_member_volatile_param) << CSM; 4146 HadError = true; 4147 } 4148 4149 if (HasConstParam && !CanHaveConstParam) { 4150 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 4151 Diag(MD->getLocation(), 4152 diag::err_defaulted_special_member_copy_const_param) 4153 << (CSM == CXXCopyAssignment); 4154 // FIXME: Explain why this special member can't be const. 4155 } else { 4156 Diag(MD->getLocation(), 4157 diag::err_defaulted_special_member_move_const_param) 4158 << (CSM == CXXMoveAssignment); 4159 } 4160 HadError = true; 4161 } 4162 4163 // If a function is explicitly defaulted on its first declaration, it shall 4164 // have the same parameter type as if it had been implicitly declared. 4165 // (Presumably this is to prevent it from being trivial?) 4166 if (!HasConstParam && CanHaveConstParam && First) 4167 Diag(MD->getLocation(), 4168 diag::err_defaulted_special_member_copy_non_const_param) 4169 << (CSM == CXXCopyAssignment); 4170 } else if (ExpectedParams) { 4171 // A copy assignment operator can take its argument by value, but a 4172 // defaulted one cannot. 4173 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 4174 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 4175 HadError = true; 4176 } 4177 4178 // Rebuild the type with the implicit exception specification added, if we 4179 // are going to need it. 4180 const FunctionProtoType *ImplicitType = 0; 4181 if (First || Type->hasExceptionSpec()) { 4182 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 4183 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI); 4184 ImplicitType = cast<FunctionProtoType>( 4185 Context.getFunctionType(ReturnType, &ArgType, ExpectedParams, EPI)); 4186 } 4187 4188 // C++11 [dcl.fct.def.default]p2: 4189 // An explicitly-defaulted function may be declared constexpr only if it 4190 // would have been implicitly declared as constexpr, 4191 // Do not apply this rule to members of class templates, since core issue 1358 4192 // makes such functions always instantiate to constexpr functions. For 4193 // non-constructors, this is checked elsewhere. 4194 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 4195 HasConstParam); 4196 if (isa<CXXConstructorDecl>(MD) && MD->isConstexpr() && !Constexpr && 4197 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 4198 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM; 4199 // FIXME: Explain why the constructor can't be constexpr. 4200 HadError = true; 4201 } 4202 // and may have an explicit exception-specification only if it is compatible 4203 // with the exception-specification on the implicit declaration. 4204 if (Type->hasExceptionSpec() && 4205 CheckEquivalentExceptionSpec( 4206 PDiag(diag::err_incorrect_defaulted_exception_spec) << CSM, 4207 PDiag(), ImplicitType, SourceLocation(), Type, MD->getLocation())) 4208 HadError = true; 4209 4210 // If a function is explicitly defaulted on its first declaration, 4211 if (First) { 4212 // -- it is implicitly considered to be constexpr if the implicit 4213 // definition would be, 4214 MD->setConstexpr(Constexpr); 4215 4216 // -- it is implicitly considered to have the same exception-specification 4217 // as if it had been implicitly declared, 4218 MD->setType(QualType(ImplicitType, 0)); 4219 4220 // Such a function is also trivial if the implicitly-declared function 4221 // would have been. 4222 MD->setTrivial(Trivial); 4223 } 4224 4225 if (ShouldDeleteSpecialMember(MD, CSM)) { 4226 if (First) { 4227 MD->setDeletedAsWritten(); 4228 } else { 4229 // C++11 [dcl.fct.def.default]p4: 4230 // [For a] user-provided explicitly-defaulted function [...] if such a 4231 // function is implicitly defined as deleted, the program is ill-formed. 4232 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 4233 HadError = true; 4234 } 4235 } 4236 4237 if (HadError) 4238 MD->setInvalidDecl(); 4239} 4240 4241namespace { 4242struct SpecialMemberDeletionInfo { 4243 Sema &S; 4244 CXXMethodDecl *MD; 4245 Sema::CXXSpecialMember CSM; 4246 bool Diagnose; 4247 4248 // Properties of the special member, computed for convenience. 4249 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg; 4250 SourceLocation Loc; 4251 4252 bool AllFieldsAreConst; 4253 4254 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 4255 Sema::CXXSpecialMember CSM, bool Diagnose) 4256 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose), 4257 IsConstructor(false), IsAssignment(false), IsMove(false), 4258 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()), 4259 AllFieldsAreConst(true) { 4260 switch (CSM) { 4261 case Sema::CXXDefaultConstructor: 4262 case Sema::CXXCopyConstructor: 4263 IsConstructor = true; 4264 break; 4265 case Sema::CXXMoveConstructor: 4266 IsConstructor = true; 4267 IsMove = true; 4268 break; 4269 case Sema::CXXCopyAssignment: 4270 IsAssignment = true; 4271 break; 4272 case Sema::CXXMoveAssignment: 4273 IsAssignment = true; 4274 IsMove = true; 4275 break; 4276 case Sema::CXXDestructor: 4277 break; 4278 case Sema::CXXInvalid: 4279 llvm_unreachable("invalid special member kind"); 4280 } 4281 4282 if (MD->getNumParams()) { 4283 ConstArg = MD->getParamDecl(0)->getType().isConstQualified(); 4284 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified(); 4285 } 4286 } 4287 4288 bool inUnion() const { return MD->getParent()->isUnion(); } 4289 4290 /// Look up the corresponding special member in the given class. 4291 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class, 4292 unsigned Quals) { 4293 unsigned TQ = MD->getTypeQualifiers(); 4294 // cv-qualifiers on class members don't affect default ctor / dtor calls. 4295 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 4296 Quals = 0; 4297 return S.LookupSpecialMember(Class, CSM, 4298 ConstArg || (Quals & Qualifiers::Const), 4299 VolatileArg || (Quals & Qualifiers::Volatile), 4300 MD->getRefQualifier() == RQ_RValue, 4301 TQ & Qualifiers::Const, 4302 TQ & Qualifiers::Volatile); 4303 } 4304 4305 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 4306 4307 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 4308 bool shouldDeleteForField(FieldDecl *FD); 4309 bool shouldDeleteForAllConstMembers(); 4310 4311 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 4312 unsigned Quals); 4313 bool shouldDeleteForSubobjectCall(Subobject Subobj, 4314 Sema::SpecialMemberOverloadResult *SMOR, 4315 bool IsDtorCallInCtor); 4316 4317 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 4318}; 4319} 4320 4321/// Is the given special member inaccessible when used on the given 4322/// sub-object. 4323bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 4324 CXXMethodDecl *target) { 4325 /// If we're operating on a base class, the object type is the 4326 /// type of this special member. 4327 QualType objectTy; 4328 AccessSpecifier access = target->getAccess(); 4329 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 4330 objectTy = S.Context.getTypeDeclType(MD->getParent()); 4331 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 4332 4333 // If we're operating on a field, the object type is the type of the field. 4334 } else { 4335 objectTy = S.Context.getTypeDeclType(target->getParent()); 4336 } 4337 4338 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 4339} 4340 4341/// Check whether we should delete a special member due to the implicit 4342/// definition containing a call to a special member of a subobject. 4343bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 4344 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR, 4345 bool IsDtorCallInCtor) { 4346 CXXMethodDecl *Decl = SMOR->getMethod(); 4347 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 4348 4349 int DiagKind = -1; 4350 4351 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 4352 DiagKind = !Decl ? 0 : 1; 4353 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 4354 DiagKind = 2; 4355 else if (!isAccessible(Subobj, Decl)) 4356 DiagKind = 3; 4357 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 4358 !Decl->isTrivial()) { 4359 // A member of a union must have a trivial corresponding special member. 4360 // As a weird special case, a destructor call from a union's constructor 4361 // must be accessible and non-deleted, but need not be trivial. Such a 4362 // destructor is never actually called, but is semantically checked as 4363 // if it were. 4364 DiagKind = 4; 4365 } 4366 4367 if (DiagKind == -1) 4368 return false; 4369 4370 if (Diagnose) { 4371 if (Field) { 4372 S.Diag(Field->getLocation(), 4373 diag::note_deleted_special_member_class_subobject) 4374 << CSM << MD->getParent() << /*IsField*/true 4375 << Field << DiagKind << IsDtorCallInCtor; 4376 } else { 4377 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 4378 S.Diag(Base->getLocStart(), 4379 diag::note_deleted_special_member_class_subobject) 4380 << CSM << MD->getParent() << /*IsField*/false 4381 << Base->getType() << DiagKind << IsDtorCallInCtor; 4382 } 4383 4384 if (DiagKind == 1) 4385 S.NoteDeletedFunction(Decl); 4386 // FIXME: Explain inaccessibility if DiagKind == 3. 4387 } 4388 4389 return true; 4390} 4391 4392/// Check whether we should delete a special member function due to having a 4393/// direct or virtual base class or non-static data member of class type M. 4394bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 4395 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 4396 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 4397 4398 // C++11 [class.ctor]p5: 4399 // -- any direct or virtual base class, or non-static data member with no 4400 // brace-or-equal-initializer, has class type M (or array thereof) and 4401 // either M has no default constructor or overload resolution as applied 4402 // to M's default constructor results in an ambiguity or in a function 4403 // that is deleted or inaccessible 4404 // C++11 [class.copy]p11, C++11 [class.copy]p23: 4405 // -- a direct or virtual base class B that cannot be copied/moved because 4406 // overload resolution, as applied to B's corresponding special member, 4407 // results in an ambiguity or a function that is deleted or inaccessible 4408 // from the defaulted special member 4409 // C++11 [class.dtor]p5: 4410 // -- any direct or virtual base class [...] has a type with a destructor 4411 // that is deleted or inaccessible 4412 if (!(CSM == Sema::CXXDefaultConstructor && 4413 Field && Field->hasInClassInitializer()) && 4414 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false)) 4415 return true; 4416 4417 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 4418 // -- any direct or virtual base class or non-static data member has a 4419 // type with a destructor that is deleted or inaccessible 4420 if (IsConstructor) { 4421 Sema::SpecialMemberOverloadResult *SMOR = 4422 S.LookupSpecialMember(Class, Sema::CXXDestructor, 4423 false, false, false, false, false); 4424 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 4425 return true; 4426 } 4427 4428 return false; 4429} 4430 4431/// Check whether we should delete a special member function due to the class 4432/// having a particular direct or virtual base class. 4433bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 4434 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 4435 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 4436} 4437 4438/// Check whether we should delete a special member function due to the class 4439/// having a particular non-static data member. 4440bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 4441 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 4442 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 4443 4444 if (CSM == Sema::CXXDefaultConstructor) { 4445 // For a default constructor, all references must be initialized in-class 4446 // and, if a union, it must have a non-const member. 4447 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 4448 if (Diagnose) 4449 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 4450 << MD->getParent() << FD << FieldType << /*Reference*/0; 4451 return true; 4452 } 4453 // C++11 [class.ctor]p5: any non-variant non-static data member of 4454 // const-qualified type (or array thereof) with no 4455 // brace-or-equal-initializer does not have a user-provided default 4456 // constructor. 4457 if (!inUnion() && FieldType.isConstQualified() && 4458 !FD->hasInClassInitializer() && 4459 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 4460 if (Diagnose) 4461 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 4462 << MD->getParent() << FD << FD->getType() << /*Const*/1; 4463 return true; 4464 } 4465 4466 if (inUnion() && !FieldType.isConstQualified()) 4467 AllFieldsAreConst = false; 4468 } else if (CSM == Sema::CXXCopyConstructor) { 4469 // For a copy constructor, data members must not be of rvalue reference 4470 // type. 4471 if (FieldType->isRValueReferenceType()) { 4472 if (Diagnose) 4473 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 4474 << MD->getParent() << FD << FieldType; 4475 return true; 4476 } 4477 } else if (IsAssignment) { 4478 // For an assignment operator, data members must not be of reference type. 4479 if (FieldType->isReferenceType()) { 4480 if (Diagnose) 4481 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 4482 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0; 4483 return true; 4484 } 4485 if (!FieldRecord && FieldType.isConstQualified()) { 4486 // C++11 [class.copy]p23: 4487 // -- a non-static data member of const non-class type (or array thereof) 4488 if (Diagnose) 4489 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 4490 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1; 4491 return true; 4492 } 4493 } 4494 4495 if (FieldRecord) { 4496 // Some additional restrictions exist on the variant members. 4497 if (!inUnion() && FieldRecord->isUnion() && 4498 FieldRecord->isAnonymousStructOrUnion()) { 4499 bool AllVariantFieldsAreConst = true; 4500 4501 // FIXME: Handle anonymous unions declared within anonymous unions. 4502 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(), 4503 UE = FieldRecord->field_end(); 4504 UI != UE; ++UI) { 4505 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 4506 4507 if (!UnionFieldType.isConstQualified()) 4508 AllVariantFieldsAreConst = false; 4509 4510 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 4511 if (UnionFieldRecord && 4512 shouldDeleteForClassSubobject(UnionFieldRecord, *UI, 4513 UnionFieldType.getCVRQualifiers())) 4514 return true; 4515 } 4516 4517 // At least one member in each anonymous union must be non-const 4518 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 4519 FieldRecord->field_begin() != FieldRecord->field_end()) { 4520 if (Diagnose) 4521 S.Diag(FieldRecord->getLocation(), 4522 diag::note_deleted_default_ctor_all_const) 4523 << MD->getParent() << /*anonymous union*/1; 4524 return true; 4525 } 4526 4527 // Don't check the implicit member of the anonymous union type. 4528 // This is technically non-conformant, but sanity demands it. 4529 return false; 4530 } 4531 4532 if (shouldDeleteForClassSubobject(FieldRecord, FD, 4533 FieldType.getCVRQualifiers())) 4534 return true; 4535 } 4536 4537 return false; 4538} 4539 4540/// C++11 [class.ctor] p5: 4541/// A defaulted default constructor for a class X is defined as deleted if 4542/// X is a union and all of its variant members are of const-qualified type. 4543bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 4544 // This is a silly definition, because it gives an empty union a deleted 4545 // default constructor. Don't do that. 4546 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst && 4547 (MD->getParent()->field_begin() != MD->getParent()->field_end())) { 4548 if (Diagnose) 4549 S.Diag(MD->getParent()->getLocation(), 4550 diag::note_deleted_default_ctor_all_const) 4551 << MD->getParent() << /*not anonymous union*/0; 4552 return true; 4553 } 4554 return false; 4555} 4556 4557/// Determine whether a defaulted special member function should be defined as 4558/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 4559/// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 4560bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 4561 bool Diagnose) { 4562 if (MD->isInvalidDecl()) 4563 return false; 4564 CXXRecordDecl *RD = MD->getParent(); 4565 assert(!RD->isDependentType() && "do deletion after instantiation"); 4566 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl()) 4567 return false; 4568 4569 // C++11 [expr.lambda.prim]p19: 4570 // The closure type associated with a lambda-expression has a 4571 // deleted (8.4.3) default constructor and a deleted copy 4572 // assignment operator. 4573 if (RD->isLambda() && 4574 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 4575 if (Diagnose) 4576 Diag(RD->getLocation(), diag::note_lambda_decl); 4577 return true; 4578 } 4579 4580 // For an anonymous struct or union, the copy and assignment special members 4581 // will never be used, so skip the check. For an anonymous union declared at 4582 // namespace scope, the constructor and destructor are used. 4583 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 4584 RD->isAnonymousStructOrUnion()) 4585 return false; 4586 4587 // C++11 [class.copy]p7, p18: 4588 // If the class definition declares a move constructor or move assignment 4589 // operator, an implicitly declared copy constructor or copy assignment 4590 // operator is defined as deleted. 4591 if (MD->isImplicit() && 4592 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 4593 CXXMethodDecl *UserDeclaredMove = 0; 4594 4595 // In Microsoft mode, a user-declared move only causes the deletion of the 4596 // corresponding copy operation, not both copy operations. 4597 if (RD->hasUserDeclaredMoveConstructor() && 4598 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) { 4599 if (!Diagnose) return true; 4600 UserDeclaredMove = RD->getMoveConstructor(); 4601 assert(UserDeclaredMove); 4602 } else if (RD->hasUserDeclaredMoveAssignment() && 4603 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) { 4604 if (!Diagnose) return true; 4605 UserDeclaredMove = RD->getMoveAssignmentOperator(); 4606 assert(UserDeclaredMove); 4607 } 4608 4609 if (UserDeclaredMove) { 4610 Diag(UserDeclaredMove->getLocation(), 4611 diag::note_deleted_copy_user_declared_move) 4612 << (CSM == CXXCopyAssignment) << RD 4613 << UserDeclaredMove->isMoveAssignmentOperator(); 4614 return true; 4615 } 4616 } 4617 4618 // Do access control from the special member function 4619 ContextRAII MethodContext(*this, MD); 4620 4621 // C++11 [class.dtor]p5: 4622 // -- for a virtual destructor, lookup of the non-array deallocation function 4623 // results in an ambiguity or in a function that is deleted or inaccessible 4624 if (CSM == CXXDestructor && MD->isVirtual()) { 4625 FunctionDecl *OperatorDelete = 0; 4626 DeclarationName Name = 4627 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 4628 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 4629 OperatorDelete, false)) { 4630 if (Diagnose) 4631 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 4632 return true; 4633 } 4634 } 4635 4636 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose); 4637 4638 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 4639 BE = RD->bases_end(); BI != BE; ++BI) 4640 if (!BI->isVirtual() && 4641 SMI.shouldDeleteForBase(BI)) 4642 return true; 4643 4644 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(), 4645 BE = RD->vbases_end(); BI != BE; ++BI) 4646 if (SMI.shouldDeleteForBase(BI)) 4647 return true; 4648 4649 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 4650 FE = RD->field_end(); FI != FE; ++FI) 4651 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() && 4652 SMI.shouldDeleteForField(*FI)) 4653 return true; 4654 4655 if (SMI.shouldDeleteForAllConstMembers()) 4656 return true; 4657 4658 return false; 4659} 4660 4661/// \brief Data used with FindHiddenVirtualMethod 4662namespace { 4663 struct FindHiddenVirtualMethodData { 4664 Sema *S; 4665 CXXMethodDecl *Method; 4666 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 4667 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 4668 }; 4669} 4670 4671/// \brief Member lookup function that determines whether a given C++ 4672/// method overloads virtual methods in a base class without overriding any, 4673/// to be used with CXXRecordDecl::lookupInBases(). 4674static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier, 4675 CXXBasePath &Path, 4676 void *UserData) { 4677 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 4678 4679 FindHiddenVirtualMethodData &Data 4680 = *static_cast<FindHiddenVirtualMethodData*>(UserData); 4681 4682 DeclarationName Name = Data.Method->getDeclName(); 4683 assert(Name.getNameKind() == DeclarationName::Identifier); 4684 4685 bool foundSameNameMethod = false; 4686 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 4687 for (Path.Decls = BaseRecord->lookup(Name); 4688 Path.Decls.first != Path.Decls.second; 4689 ++Path.Decls.first) { 4690 NamedDecl *D = *Path.Decls.first; 4691 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 4692 MD = MD->getCanonicalDecl(); 4693 foundSameNameMethod = true; 4694 // Interested only in hidden virtual methods. 4695 if (!MD->isVirtual()) 4696 continue; 4697 // If the method we are checking overrides a method from its base 4698 // don't warn about the other overloaded methods. 4699 if (!Data.S->IsOverload(Data.Method, MD, false)) 4700 return true; 4701 // Collect the overload only if its hidden. 4702 if (!Data.OverridenAndUsingBaseMethods.count(MD)) 4703 overloadedMethods.push_back(MD); 4704 } 4705 } 4706 4707 if (foundSameNameMethod) 4708 Data.OverloadedMethods.append(overloadedMethods.begin(), 4709 overloadedMethods.end()); 4710 return foundSameNameMethod; 4711} 4712 4713/// \brief See if a method overloads virtual methods in a base class without 4714/// overriding any. 4715void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 4716 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual, 4717 MD->getLocation()) == DiagnosticsEngine::Ignored) 4718 return; 4719 if (!MD->getDeclName().isIdentifier()) 4720 return; 4721 4722 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 4723 /*bool RecordPaths=*/false, 4724 /*bool DetectVirtual=*/false); 4725 FindHiddenVirtualMethodData Data; 4726 Data.Method = MD; 4727 Data.S = this; 4728 4729 // Keep the base methods that were overriden or introduced in the subclass 4730 // by 'using' in a set. A base method not in this set is hidden. 4731 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName()); 4732 res.first != res.second; ++res.first) { 4733 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first)) 4734 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 4735 E = MD->end_overridden_methods(); 4736 I != E; ++I) 4737 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl()); 4738 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first)) 4739 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl())) 4740 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl()); 4741 } 4742 4743 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) && 4744 !Data.OverloadedMethods.empty()) { 4745 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 4746 << MD << (Data.OverloadedMethods.size() > 1); 4747 4748 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) { 4749 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i]; 4750 Diag(overloadedMD->getLocation(), 4751 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 4752 } 4753 } 4754} 4755 4756void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 4757 Decl *TagDecl, 4758 SourceLocation LBrac, 4759 SourceLocation RBrac, 4760 AttributeList *AttrList) { 4761 if (!TagDecl) 4762 return; 4763 4764 AdjustDeclIfTemplate(TagDecl); 4765 4766 for (const AttributeList* l = AttrList; l; l = l->getNext()) { 4767 if (l->getKind() != AttributeList::AT_Visibility) 4768 continue; 4769 l->setInvalid(); 4770 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) << 4771 l->getName(); 4772 } 4773 4774 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 4775 // strict aliasing violation! 4776 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 4777 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 4778 4779 CheckCompletedCXXClass( 4780 dyn_cast_or_null<CXXRecordDecl>(TagDecl)); 4781} 4782 4783/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 4784/// special functions, such as the default constructor, copy 4785/// constructor, or destructor, to the given C++ class (C++ 4786/// [special]p1). This routine can only be executed just before the 4787/// definition of the class is complete. 4788void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 4789 if (!ClassDecl->hasUserDeclaredConstructor()) 4790 ++ASTContext::NumImplicitDefaultConstructors; 4791 4792 if (!ClassDecl->hasUserDeclaredCopyConstructor()) 4793 ++ASTContext::NumImplicitCopyConstructors; 4794 4795 if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveConstructor()) 4796 ++ASTContext::NumImplicitMoveConstructors; 4797 4798 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 4799 ++ASTContext::NumImplicitCopyAssignmentOperators; 4800 4801 // If we have a dynamic class, then the copy assignment operator may be 4802 // virtual, so we have to declare it immediately. This ensures that, e.g., 4803 // it shows up in the right place in the vtable and that we diagnose 4804 // problems with the implicit exception specification. 4805 if (ClassDecl->isDynamicClass()) 4806 DeclareImplicitCopyAssignment(ClassDecl); 4807 } 4808 4809 if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveAssignment()) { 4810 ++ASTContext::NumImplicitMoveAssignmentOperators; 4811 4812 // Likewise for the move assignment operator. 4813 if (ClassDecl->isDynamicClass()) 4814 DeclareImplicitMoveAssignment(ClassDecl); 4815 } 4816 4817 if (!ClassDecl->hasUserDeclaredDestructor()) { 4818 ++ASTContext::NumImplicitDestructors; 4819 4820 // If we have a dynamic class, then the destructor may be virtual, so we 4821 // have to declare the destructor immediately. This ensures that, e.g., it 4822 // shows up in the right place in the vtable and that we diagnose problems 4823 // with the implicit exception specification. 4824 if (ClassDecl->isDynamicClass()) 4825 DeclareImplicitDestructor(ClassDecl); 4826 } 4827} 4828 4829void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) { 4830 if (!D) 4831 return; 4832 4833 int NumParamList = D->getNumTemplateParameterLists(); 4834 for (int i = 0; i < NumParamList; i++) { 4835 TemplateParameterList* Params = D->getTemplateParameterList(i); 4836 for (TemplateParameterList::iterator Param = Params->begin(), 4837 ParamEnd = Params->end(); 4838 Param != ParamEnd; ++Param) { 4839 NamedDecl *Named = cast<NamedDecl>(*Param); 4840 if (Named->getDeclName()) { 4841 S->AddDecl(Named); 4842 IdResolver.AddDecl(Named); 4843 } 4844 } 4845 } 4846} 4847 4848void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 4849 if (!D) 4850 return; 4851 4852 TemplateParameterList *Params = 0; 4853 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) 4854 Params = Template->getTemplateParameters(); 4855 else if (ClassTemplatePartialSpecializationDecl *PartialSpec 4856 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 4857 Params = PartialSpec->getTemplateParameters(); 4858 else 4859 return; 4860 4861 for (TemplateParameterList::iterator Param = Params->begin(), 4862 ParamEnd = Params->end(); 4863 Param != ParamEnd; ++Param) { 4864 NamedDecl *Named = cast<NamedDecl>(*Param); 4865 if (Named->getDeclName()) { 4866 S->AddDecl(Named); 4867 IdResolver.AddDecl(Named); 4868 } 4869 } 4870} 4871 4872void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 4873 if (!RecordD) return; 4874 AdjustDeclIfTemplate(RecordD); 4875 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 4876 PushDeclContext(S, Record); 4877} 4878 4879void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 4880 if (!RecordD) return; 4881 PopDeclContext(); 4882} 4883 4884/// ActOnStartDelayedCXXMethodDeclaration - We have completed 4885/// parsing a top-level (non-nested) C++ class, and we are now 4886/// parsing those parts of the given Method declaration that could 4887/// not be parsed earlier (C++ [class.mem]p2), such as default 4888/// arguments. This action should enter the scope of the given 4889/// Method declaration as if we had just parsed the qualified method 4890/// name. However, it should not bring the parameters into scope; 4891/// that will be performed by ActOnDelayedCXXMethodParameter. 4892void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 4893} 4894 4895/// ActOnDelayedCXXMethodParameter - We've already started a delayed 4896/// C++ method declaration. We're (re-)introducing the given 4897/// function parameter into scope for use in parsing later parts of 4898/// the method declaration. For example, we could see an 4899/// ActOnParamDefaultArgument event for this parameter. 4900void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 4901 if (!ParamD) 4902 return; 4903 4904 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 4905 4906 // If this parameter has an unparsed default argument, clear it out 4907 // to make way for the parsed default argument. 4908 if (Param->hasUnparsedDefaultArg()) 4909 Param->setDefaultArg(0); 4910 4911 S->AddDecl(Param); 4912 if (Param->getDeclName()) 4913 IdResolver.AddDecl(Param); 4914} 4915 4916/// ActOnFinishDelayedCXXMethodDeclaration - We have finished 4917/// processing the delayed method declaration for Method. The method 4918/// declaration is now considered finished. There may be a separate 4919/// ActOnStartOfFunctionDef action later (not necessarily 4920/// immediately!) for this method, if it was also defined inside the 4921/// class body. 4922void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 4923 if (!MethodD) 4924 return; 4925 4926 AdjustDeclIfTemplate(MethodD); 4927 4928 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 4929 4930 // Now that we have our default arguments, check the constructor 4931 // again. It could produce additional diagnostics or affect whether 4932 // the class has implicitly-declared destructors, among other 4933 // things. 4934 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 4935 CheckConstructor(Constructor); 4936 4937 // Check the default arguments, which we may have added. 4938 if (!Method->isInvalidDecl()) 4939 CheckCXXDefaultArguments(Method); 4940} 4941 4942/// CheckConstructorDeclarator - Called by ActOnDeclarator to check 4943/// the well-formedness of the constructor declarator @p D with type @p 4944/// R. If there are any errors in the declarator, this routine will 4945/// emit diagnostics and set the invalid bit to true. In any case, the type 4946/// will be updated to reflect a well-formed type for the constructor and 4947/// returned. 4948QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 4949 StorageClass &SC) { 4950 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 4951 4952 // C++ [class.ctor]p3: 4953 // A constructor shall not be virtual (10.3) or static (9.4). A 4954 // constructor can be invoked for a const, volatile or const 4955 // volatile object. A constructor shall not be declared const, 4956 // volatile, or const volatile (9.3.2). 4957 if (isVirtual) { 4958 if (!D.isInvalidType()) 4959 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 4960 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 4961 << SourceRange(D.getIdentifierLoc()); 4962 D.setInvalidType(); 4963 } 4964 if (SC == SC_Static) { 4965 if (!D.isInvalidType()) 4966 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 4967 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 4968 << SourceRange(D.getIdentifierLoc()); 4969 D.setInvalidType(); 4970 SC = SC_None; 4971 } 4972 4973 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 4974 if (FTI.TypeQuals != 0) { 4975 if (FTI.TypeQuals & Qualifiers::Const) 4976 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 4977 << "const" << SourceRange(D.getIdentifierLoc()); 4978 if (FTI.TypeQuals & Qualifiers::Volatile) 4979 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 4980 << "volatile" << SourceRange(D.getIdentifierLoc()); 4981 if (FTI.TypeQuals & Qualifiers::Restrict) 4982 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 4983 << "restrict" << SourceRange(D.getIdentifierLoc()); 4984 D.setInvalidType(); 4985 } 4986 4987 // C++0x [class.ctor]p4: 4988 // A constructor shall not be declared with a ref-qualifier. 4989 if (FTI.hasRefQualifier()) { 4990 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 4991 << FTI.RefQualifierIsLValueRef 4992 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 4993 D.setInvalidType(); 4994 } 4995 4996 // Rebuild the function type "R" without any type qualifiers (in 4997 // case any of the errors above fired) and with "void" as the 4998 // return type, since constructors don't have return types. 4999 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 5000 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType()) 5001 return R; 5002 5003 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 5004 EPI.TypeQuals = 0; 5005 EPI.RefQualifier = RQ_None; 5006 5007 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(), 5008 Proto->getNumArgs(), EPI); 5009} 5010 5011/// CheckConstructor - Checks a fully-formed constructor for 5012/// well-formedness, issuing any diagnostics required. Returns true if 5013/// the constructor declarator is invalid. 5014void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 5015 CXXRecordDecl *ClassDecl 5016 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 5017 if (!ClassDecl) 5018 return Constructor->setInvalidDecl(); 5019 5020 // C++ [class.copy]p3: 5021 // A declaration of a constructor for a class X is ill-formed if 5022 // its first parameter is of type (optionally cv-qualified) X and 5023 // either there are no other parameters or else all other 5024 // parameters have default arguments. 5025 if (!Constructor->isInvalidDecl() && 5026 ((Constructor->getNumParams() == 1) || 5027 (Constructor->getNumParams() > 1 && 5028 Constructor->getParamDecl(1)->hasDefaultArg())) && 5029 Constructor->getTemplateSpecializationKind() 5030 != TSK_ImplicitInstantiation) { 5031 QualType ParamType = Constructor->getParamDecl(0)->getType(); 5032 QualType ClassTy = Context.getTagDeclType(ClassDecl); 5033 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 5034 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 5035 const char *ConstRef 5036 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 5037 : " const &"; 5038 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 5039 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 5040 5041 // FIXME: Rather that making the constructor invalid, we should endeavor 5042 // to fix the type. 5043 Constructor->setInvalidDecl(); 5044 } 5045 } 5046} 5047 5048/// CheckDestructor - Checks a fully-formed destructor definition for 5049/// well-formedness, issuing any diagnostics required. Returns true 5050/// on error. 5051bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 5052 CXXRecordDecl *RD = Destructor->getParent(); 5053 5054 if (Destructor->isVirtual()) { 5055 SourceLocation Loc; 5056 5057 if (!Destructor->isImplicit()) 5058 Loc = Destructor->getLocation(); 5059 else 5060 Loc = RD->getLocation(); 5061 5062 // If we have a virtual destructor, look up the deallocation function 5063 FunctionDecl *OperatorDelete = 0; 5064 DeclarationName Name = 5065 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 5066 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 5067 return true; 5068 5069 MarkFunctionReferenced(Loc, OperatorDelete); 5070 5071 Destructor->setOperatorDelete(OperatorDelete); 5072 } 5073 5074 return false; 5075} 5076 5077static inline bool 5078FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) { 5079 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 5080 FTI.ArgInfo[0].Param && 5081 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()); 5082} 5083 5084/// CheckDestructorDeclarator - Called by ActOnDeclarator to check 5085/// the well-formednes of the destructor declarator @p D with type @p 5086/// R. If there are any errors in the declarator, this routine will 5087/// emit diagnostics and set the declarator to invalid. Even if this happens, 5088/// will be updated to reflect a well-formed type for the destructor and 5089/// returned. 5090QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 5091 StorageClass& SC) { 5092 // C++ [class.dtor]p1: 5093 // [...] A typedef-name that names a class is a class-name 5094 // (7.1.3); however, a typedef-name that names a class shall not 5095 // be used as the identifier in the declarator for a destructor 5096 // declaration. 5097 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 5098 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 5099 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 5100 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 5101 else if (const TemplateSpecializationType *TST = 5102 DeclaratorType->getAs<TemplateSpecializationType>()) 5103 if (TST->isTypeAlias()) 5104 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 5105 << DeclaratorType << 1; 5106 5107 // C++ [class.dtor]p2: 5108 // A destructor is used to destroy objects of its class type. A 5109 // destructor takes no parameters, and no return type can be 5110 // specified for it (not even void). The address of a destructor 5111 // shall not be taken. A destructor shall not be static. A 5112 // destructor can be invoked for a const, volatile or const 5113 // volatile object. A destructor shall not be declared const, 5114 // volatile or const volatile (9.3.2). 5115 if (SC == SC_Static) { 5116 if (!D.isInvalidType()) 5117 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 5118 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 5119 << SourceRange(D.getIdentifierLoc()) 5120 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5121 5122 SC = SC_None; 5123 } 5124 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 5125 // Destructors don't have return types, but the parser will 5126 // happily parse something like: 5127 // 5128 // class X { 5129 // float ~X(); 5130 // }; 5131 // 5132 // The return type will be eliminated later. 5133 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 5134 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 5135 << SourceRange(D.getIdentifierLoc()); 5136 } 5137 5138 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 5139 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 5140 if (FTI.TypeQuals & Qualifiers::Const) 5141 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 5142 << "const" << SourceRange(D.getIdentifierLoc()); 5143 if (FTI.TypeQuals & Qualifiers::Volatile) 5144 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 5145 << "volatile" << SourceRange(D.getIdentifierLoc()); 5146 if (FTI.TypeQuals & Qualifiers::Restrict) 5147 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 5148 << "restrict" << SourceRange(D.getIdentifierLoc()); 5149 D.setInvalidType(); 5150 } 5151 5152 // C++0x [class.dtor]p2: 5153 // A destructor shall not be declared with a ref-qualifier. 5154 if (FTI.hasRefQualifier()) { 5155 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 5156 << FTI.RefQualifierIsLValueRef 5157 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 5158 D.setInvalidType(); 5159 } 5160 5161 // Make sure we don't have any parameters. 5162 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) { 5163 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 5164 5165 // Delete the parameters. 5166 FTI.freeArgs(); 5167 D.setInvalidType(); 5168 } 5169 5170 // Make sure the destructor isn't variadic. 5171 if (FTI.isVariadic) { 5172 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 5173 D.setInvalidType(); 5174 } 5175 5176 // Rebuild the function type "R" without any type qualifiers or 5177 // parameters (in case any of the errors above fired) and with 5178 // "void" as the return type, since destructors don't have return 5179 // types. 5180 if (!D.isInvalidType()) 5181 return R; 5182 5183 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 5184 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 5185 EPI.Variadic = false; 5186 EPI.TypeQuals = 0; 5187 EPI.RefQualifier = RQ_None; 5188 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI); 5189} 5190 5191/// CheckConversionDeclarator - Called by ActOnDeclarator to check the 5192/// well-formednes of the conversion function declarator @p D with 5193/// type @p R. If there are any errors in the declarator, this routine 5194/// will emit diagnostics and return true. Otherwise, it will return 5195/// false. Either way, the type @p R will be updated to reflect a 5196/// well-formed type for the conversion operator. 5197void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 5198 StorageClass& SC) { 5199 // C++ [class.conv.fct]p1: 5200 // Neither parameter types nor return type can be specified. The 5201 // type of a conversion function (8.3.5) is "function taking no 5202 // parameter returning conversion-type-id." 5203 if (SC == SC_Static) { 5204 if (!D.isInvalidType()) 5205 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 5206 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 5207 << SourceRange(D.getIdentifierLoc()); 5208 D.setInvalidType(); 5209 SC = SC_None; 5210 } 5211 5212 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId); 5213 5214 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 5215 // Conversion functions don't have return types, but the parser will 5216 // happily parse something like: 5217 // 5218 // class X { 5219 // float operator bool(); 5220 // }; 5221 // 5222 // The return type will be changed later anyway. 5223 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 5224 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 5225 << SourceRange(D.getIdentifierLoc()); 5226 D.setInvalidType(); 5227 } 5228 5229 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 5230 5231 // Make sure we don't have any parameters. 5232 if (Proto->getNumArgs() > 0) { 5233 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 5234 5235 // Delete the parameters. 5236 D.getFunctionTypeInfo().freeArgs(); 5237 D.setInvalidType(); 5238 } else if (Proto->isVariadic()) { 5239 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 5240 D.setInvalidType(); 5241 } 5242 5243 // Diagnose "&operator bool()" and other such nonsense. This 5244 // is actually a gcc extension which we don't support. 5245 if (Proto->getResultType() != ConvType) { 5246 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 5247 << Proto->getResultType(); 5248 D.setInvalidType(); 5249 ConvType = Proto->getResultType(); 5250 } 5251 5252 // C++ [class.conv.fct]p4: 5253 // The conversion-type-id shall not represent a function type nor 5254 // an array type. 5255 if (ConvType->isArrayType()) { 5256 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 5257 ConvType = Context.getPointerType(ConvType); 5258 D.setInvalidType(); 5259 } else if (ConvType->isFunctionType()) { 5260 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 5261 ConvType = Context.getPointerType(ConvType); 5262 D.setInvalidType(); 5263 } 5264 5265 // Rebuild the function type "R" without any parameters (in case any 5266 // of the errors above fired) and with the conversion type as the 5267 // return type. 5268 if (D.isInvalidType()) 5269 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo()); 5270 5271 // C++0x explicit conversion operators. 5272 if (D.getDeclSpec().isExplicitSpecified()) 5273 Diag(D.getDeclSpec().getExplicitSpecLoc(), 5274 getLangOpts().CPlusPlus0x ? 5275 diag::warn_cxx98_compat_explicit_conversion_functions : 5276 diag::ext_explicit_conversion_functions) 5277 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 5278} 5279 5280/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 5281/// the declaration of the given C++ conversion function. This routine 5282/// is responsible for recording the conversion function in the C++ 5283/// class, if possible. 5284Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 5285 assert(Conversion && "Expected to receive a conversion function declaration"); 5286 5287 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 5288 5289 // Make sure we aren't redeclaring the conversion function. 5290 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 5291 5292 // C++ [class.conv.fct]p1: 5293 // [...] A conversion function is never used to convert a 5294 // (possibly cv-qualified) object to the (possibly cv-qualified) 5295 // same object type (or a reference to it), to a (possibly 5296 // cv-qualified) base class of that type (or a reference to it), 5297 // or to (possibly cv-qualified) void. 5298 // FIXME: Suppress this warning if the conversion function ends up being a 5299 // virtual function that overrides a virtual function in a base class. 5300 QualType ClassType 5301 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 5302 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 5303 ConvType = ConvTypeRef->getPointeeType(); 5304 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 5305 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 5306 /* Suppress diagnostics for instantiations. */; 5307 else if (ConvType->isRecordType()) { 5308 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 5309 if (ConvType == ClassType) 5310 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 5311 << ClassType; 5312 else if (IsDerivedFrom(ClassType, ConvType)) 5313 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 5314 << ClassType << ConvType; 5315 } else if (ConvType->isVoidType()) { 5316 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 5317 << ClassType << ConvType; 5318 } 5319 5320 if (FunctionTemplateDecl *ConversionTemplate 5321 = Conversion->getDescribedFunctionTemplate()) 5322 return ConversionTemplate; 5323 5324 return Conversion; 5325} 5326 5327//===----------------------------------------------------------------------===// 5328// Namespace Handling 5329//===----------------------------------------------------------------------===// 5330 5331 5332 5333/// ActOnStartNamespaceDef - This is called at the start of a namespace 5334/// definition. 5335Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 5336 SourceLocation InlineLoc, 5337 SourceLocation NamespaceLoc, 5338 SourceLocation IdentLoc, 5339 IdentifierInfo *II, 5340 SourceLocation LBrace, 5341 AttributeList *AttrList) { 5342 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 5343 // For anonymous namespace, take the location of the left brace. 5344 SourceLocation Loc = II ? IdentLoc : LBrace; 5345 bool IsInline = InlineLoc.isValid(); 5346 bool IsInvalid = false; 5347 bool IsStd = false; 5348 bool AddToKnown = false; 5349 Scope *DeclRegionScope = NamespcScope->getParent(); 5350 5351 NamespaceDecl *PrevNS = 0; 5352 if (II) { 5353 // C++ [namespace.def]p2: 5354 // The identifier in an original-namespace-definition shall not 5355 // have been previously defined in the declarative region in 5356 // which the original-namespace-definition appears. The 5357 // identifier in an original-namespace-definition is the name of 5358 // the namespace. Subsequently in that declarative region, it is 5359 // treated as an original-namespace-name. 5360 // 5361 // Since namespace names are unique in their scope, and we don't 5362 // look through using directives, just look for any ordinary names. 5363 5364 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member | 5365 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag | 5366 Decl::IDNS_Namespace; 5367 NamedDecl *PrevDecl = 0; 5368 for (DeclContext::lookup_result R 5369 = CurContext->getRedeclContext()->lookup(II); 5370 R.first != R.second; ++R.first) { 5371 if ((*R.first)->getIdentifierNamespace() & IDNS) { 5372 PrevDecl = *R.first; 5373 break; 5374 } 5375 } 5376 5377 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 5378 5379 if (PrevNS) { 5380 // This is an extended namespace definition. 5381 if (IsInline != PrevNS->isInline()) { 5382 // inline-ness must match 5383 if (PrevNS->isInline()) { 5384 // The user probably just forgot the 'inline', so suggest that it 5385 // be added back. 5386 Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 5387 << FixItHint::CreateInsertion(NamespaceLoc, "inline "); 5388 } else { 5389 Diag(Loc, diag::err_inline_namespace_mismatch) 5390 << IsInline; 5391 } 5392 Diag(PrevNS->getLocation(), diag::note_previous_definition); 5393 5394 IsInline = PrevNS->isInline(); 5395 } 5396 } else if (PrevDecl) { 5397 // This is an invalid name redefinition. 5398 Diag(Loc, diag::err_redefinition_different_kind) 5399 << II; 5400 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 5401 IsInvalid = true; 5402 // Continue on to push Namespc as current DeclContext and return it. 5403 } else if (II->isStr("std") && 5404 CurContext->getRedeclContext()->isTranslationUnit()) { 5405 // This is the first "real" definition of the namespace "std", so update 5406 // our cache of the "std" namespace to point at this definition. 5407 PrevNS = getStdNamespace(); 5408 IsStd = true; 5409 AddToKnown = !IsInline; 5410 } else { 5411 // We've seen this namespace for the first time. 5412 AddToKnown = !IsInline; 5413 } 5414 } else { 5415 // Anonymous namespaces. 5416 5417 // Determine whether the parent already has an anonymous namespace. 5418 DeclContext *Parent = CurContext->getRedeclContext(); 5419 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 5420 PrevNS = TU->getAnonymousNamespace(); 5421 } else { 5422 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 5423 PrevNS = ND->getAnonymousNamespace(); 5424 } 5425 5426 if (PrevNS && IsInline != PrevNS->isInline()) { 5427 // inline-ness must match 5428 Diag(Loc, diag::err_inline_namespace_mismatch) 5429 << IsInline; 5430 Diag(PrevNS->getLocation(), diag::note_previous_definition); 5431 5432 // Recover by ignoring the new namespace's inline status. 5433 IsInline = PrevNS->isInline(); 5434 } 5435 } 5436 5437 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 5438 StartLoc, Loc, II, PrevNS); 5439 if (IsInvalid) 5440 Namespc->setInvalidDecl(); 5441 5442 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 5443 5444 // FIXME: Should we be merging attributes? 5445 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 5446 PushNamespaceVisibilityAttr(Attr, Loc); 5447 5448 if (IsStd) 5449 StdNamespace = Namespc; 5450 if (AddToKnown) 5451 KnownNamespaces[Namespc] = false; 5452 5453 if (II) { 5454 PushOnScopeChains(Namespc, DeclRegionScope); 5455 } else { 5456 // Link the anonymous namespace into its parent. 5457 DeclContext *Parent = CurContext->getRedeclContext(); 5458 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 5459 TU->setAnonymousNamespace(Namespc); 5460 } else { 5461 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 5462 } 5463 5464 CurContext->addDecl(Namespc); 5465 5466 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 5467 // behaves as if it were replaced by 5468 // namespace unique { /* empty body */ } 5469 // using namespace unique; 5470 // namespace unique { namespace-body } 5471 // where all occurrences of 'unique' in a translation unit are 5472 // replaced by the same identifier and this identifier differs 5473 // from all other identifiers in the entire program. 5474 5475 // We just create the namespace with an empty name and then add an 5476 // implicit using declaration, just like the standard suggests. 5477 // 5478 // CodeGen enforces the "universally unique" aspect by giving all 5479 // declarations semantically contained within an anonymous 5480 // namespace internal linkage. 5481 5482 if (!PrevNS) { 5483 UsingDirectiveDecl* UD 5484 = UsingDirectiveDecl::Create(Context, CurContext, 5485 /* 'using' */ LBrace, 5486 /* 'namespace' */ SourceLocation(), 5487 /* qualifier */ NestedNameSpecifierLoc(), 5488 /* identifier */ SourceLocation(), 5489 Namespc, 5490 /* Ancestor */ CurContext); 5491 UD->setImplicit(); 5492 CurContext->addDecl(UD); 5493 } 5494 } 5495 5496 ActOnDocumentableDecl(Namespc); 5497 5498 // Although we could have an invalid decl (i.e. the namespace name is a 5499 // redefinition), push it as current DeclContext and try to continue parsing. 5500 // FIXME: We should be able to push Namespc here, so that the each DeclContext 5501 // for the namespace has the declarations that showed up in that particular 5502 // namespace definition. 5503 PushDeclContext(NamespcScope, Namespc); 5504 return Namespc; 5505} 5506 5507/// getNamespaceDecl - Returns the namespace a decl represents. If the decl 5508/// is a namespace alias, returns the namespace it points to. 5509static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 5510 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 5511 return AD->getNamespace(); 5512 return dyn_cast_or_null<NamespaceDecl>(D); 5513} 5514 5515/// ActOnFinishNamespaceDef - This callback is called after a namespace is 5516/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 5517void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 5518 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 5519 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 5520 Namespc->setRBraceLoc(RBrace); 5521 PopDeclContext(); 5522 if (Namespc->hasAttr<VisibilityAttr>()) 5523 PopPragmaVisibility(true, RBrace); 5524} 5525 5526CXXRecordDecl *Sema::getStdBadAlloc() const { 5527 return cast_or_null<CXXRecordDecl>( 5528 StdBadAlloc.get(Context.getExternalSource())); 5529} 5530 5531NamespaceDecl *Sema::getStdNamespace() const { 5532 return cast_or_null<NamespaceDecl>( 5533 StdNamespace.get(Context.getExternalSource())); 5534} 5535 5536/// \brief Retrieve the special "std" namespace, which may require us to 5537/// implicitly define the namespace. 5538NamespaceDecl *Sema::getOrCreateStdNamespace() { 5539 if (!StdNamespace) { 5540 // The "std" namespace has not yet been defined, so build one implicitly. 5541 StdNamespace = NamespaceDecl::Create(Context, 5542 Context.getTranslationUnitDecl(), 5543 /*Inline=*/false, 5544 SourceLocation(), SourceLocation(), 5545 &PP.getIdentifierTable().get("std"), 5546 /*PrevDecl=*/0); 5547 getStdNamespace()->setImplicit(true); 5548 } 5549 5550 return getStdNamespace(); 5551} 5552 5553bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 5554 assert(getLangOpts().CPlusPlus && 5555 "Looking for std::initializer_list outside of C++."); 5556 5557 // We're looking for implicit instantiations of 5558 // template <typename E> class std::initializer_list. 5559 5560 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 5561 return false; 5562 5563 ClassTemplateDecl *Template = 0; 5564 const TemplateArgument *Arguments = 0; 5565 5566 if (const RecordType *RT = Ty->getAs<RecordType>()) { 5567 5568 ClassTemplateSpecializationDecl *Specialization = 5569 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 5570 if (!Specialization) 5571 return false; 5572 5573 Template = Specialization->getSpecializedTemplate(); 5574 Arguments = Specialization->getTemplateArgs().data(); 5575 } else if (const TemplateSpecializationType *TST = 5576 Ty->getAs<TemplateSpecializationType>()) { 5577 Template = dyn_cast_or_null<ClassTemplateDecl>( 5578 TST->getTemplateName().getAsTemplateDecl()); 5579 Arguments = TST->getArgs(); 5580 } 5581 if (!Template) 5582 return false; 5583 5584 if (!StdInitializerList) { 5585 // Haven't recognized std::initializer_list yet, maybe this is it. 5586 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 5587 if (TemplateClass->getIdentifier() != 5588 &PP.getIdentifierTable().get("initializer_list") || 5589 !getStdNamespace()->InEnclosingNamespaceSetOf( 5590 TemplateClass->getDeclContext())) 5591 return false; 5592 // This is a template called std::initializer_list, but is it the right 5593 // template? 5594 TemplateParameterList *Params = Template->getTemplateParameters(); 5595 if (Params->getMinRequiredArguments() != 1) 5596 return false; 5597 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 5598 return false; 5599 5600 // It's the right template. 5601 StdInitializerList = Template; 5602 } 5603 5604 if (Template != StdInitializerList) 5605 return false; 5606 5607 // This is an instance of std::initializer_list. Find the argument type. 5608 if (Element) 5609 *Element = Arguments[0].getAsType(); 5610 return true; 5611} 5612 5613static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 5614 NamespaceDecl *Std = S.getStdNamespace(); 5615 if (!Std) { 5616 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 5617 return 0; 5618 } 5619 5620 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 5621 Loc, Sema::LookupOrdinaryName); 5622 if (!S.LookupQualifiedName(Result, Std)) { 5623 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 5624 return 0; 5625 } 5626 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 5627 if (!Template) { 5628 Result.suppressDiagnostics(); 5629 // We found something weird. Complain about the first thing we found. 5630 NamedDecl *Found = *Result.begin(); 5631 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 5632 return 0; 5633 } 5634 5635 // We found some template called std::initializer_list. Now verify that it's 5636 // correct. 5637 TemplateParameterList *Params = Template->getTemplateParameters(); 5638 if (Params->getMinRequiredArguments() != 1 || 5639 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 5640 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 5641 return 0; 5642 } 5643 5644 return Template; 5645} 5646 5647QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 5648 if (!StdInitializerList) { 5649 StdInitializerList = LookupStdInitializerList(*this, Loc); 5650 if (!StdInitializerList) 5651 return QualType(); 5652 } 5653 5654 TemplateArgumentListInfo Args(Loc, Loc); 5655 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 5656 Context.getTrivialTypeSourceInfo(Element, 5657 Loc))); 5658 return Context.getCanonicalType( 5659 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 5660} 5661 5662bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) { 5663 // C++ [dcl.init.list]p2: 5664 // A constructor is an initializer-list constructor if its first parameter 5665 // is of type std::initializer_list<E> or reference to possibly cv-qualified 5666 // std::initializer_list<E> for some type E, and either there are no other 5667 // parameters or else all other parameters have default arguments. 5668 if (Ctor->getNumParams() < 1 || 5669 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 5670 return false; 5671 5672 QualType ArgType = Ctor->getParamDecl(0)->getType(); 5673 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 5674 ArgType = RT->getPointeeType().getUnqualifiedType(); 5675 5676 return isStdInitializerList(ArgType, 0); 5677} 5678 5679/// \brief Determine whether a using statement is in a context where it will be 5680/// apply in all contexts. 5681static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 5682 switch (CurContext->getDeclKind()) { 5683 case Decl::TranslationUnit: 5684 return true; 5685 case Decl::LinkageSpec: 5686 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 5687 default: 5688 return false; 5689 } 5690} 5691 5692namespace { 5693 5694// Callback to only accept typo corrections that are namespaces. 5695class NamespaceValidatorCCC : public CorrectionCandidateCallback { 5696 public: 5697 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 5698 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 5699 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 5700 } 5701 return false; 5702 } 5703}; 5704 5705} 5706 5707static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 5708 CXXScopeSpec &SS, 5709 SourceLocation IdentLoc, 5710 IdentifierInfo *Ident) { 5711 NamespaceValidatorCCC Validator; 5712 R.clear(); 5713 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(), 5714 R.getLookupKind(), Sc, &SS, 5715 Validator)) { 5716 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 5717 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts())); 5718 if (DeclContext *DC = S.computeDeclContext(SS, false)) 5719 S.Diag(IdentLoc, diag::err_using_directive_member_suggest) 5720 << Ident << DC << CorrectedQuotedStr << SS.getRange() 5721 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr); 5722 else 5723 S.Diag(IdentLoc, diag::err_using_directive_suggest) 5724 << Ident << CorrectedQuotedStr 5725 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr); 5726 5727 S.Diag(Corrected.getCorrectionDecl()->getLocation(), 5728 diag::note_namespace_defined_here) << CorrectedQuotedStr; 5729 5730 R.addDecl(Corrected.getCorrectionDecl()); 5731 return true; 5732 } 5733 return false; 5734} 5735 5736Decl *Sema::ActOnUsingDirective(Scope *S, 5737 SourceLocation UsingLoc, 5738 SourceLocation NamespcLoc, 5739 CXXScopeSpec &SS, 5740 SourceLocation IdentLoc, 5741 IdentifierInfo *NamespcName, 5742 AttributeList *AttrList) { 5743 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 5744 assert(NamespcName && "Invalid NamespcName."); 5745 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 5746 5747 // This can only happen along a recovery path. 5748 while (S->getFlags() & Scope::TemplateParamScope) 5749 S = S->getParent(); 5750 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 5751 5752 UsingDirectiveDecl *UDir = 0; 5753 NestedNameSpecifier *Qualifier = 0; 5754 if (SS.isSet()) 5755 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 5756 5757 // Lookup namespace name. 5758 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 5759 LookupParsedName(R, S, &SS); 5760 if (R.isAmbiguous()) 5761 return 0; 5762 5763 if (R.empty()) { 5764 R.clear(); 5765 // Allow "using namespace std;" or "using namespace ::std;" even if 5766 // "std" hasn't been defined yet, for GCC compatibility. 5767 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 5768 NamespcName->isStr("std")) { 5769 Diag(IdentLoc, diag::ext_using_undefined_std); 5770 R.addDecl(getOrCreateStdNamespace()); 5771 R.resolveKind(); 5772 } 5773 // Otherwise, attempt typo correction. 5774 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 5775 } 5776 5777 if (!R.empty()) { 5778 NamedDecl *Named = R.getFoundDecl(); 5779 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named)) 5780 && "expected namespace decl"); 5781 // C++ [namespace.udir]p1: 5782 // A using-directive specifies that the names in the nominated 5783 // namespace can be used in the scope in which the 5784 // using-directive appears after the using-directive. During 5785 // unqualified name lookup (3.4.1), the names appear as if they 5786 // were declared in the nearest enclosing namespace which 5787 // contains both the using-directive and the nominated 5788 // namespace. [Note: in this context, "contains" means "contains 5789 // directly or indirectly". ] 5790 5791 // Find enclosing context containing both using-directive and 5792 // nominated namespace. 5793 NamespaceDecl *NS = getNamespaceDecl(Named); 5794 DeclContext *CommonAncestor = cast<DeclContext>(NS); 5795 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 5796 CommonAncestor = CommonAncestor->getParent(); 5797 5798 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 5799 SS.getWithLocInContext(Context), 5800 IdentLoc, Named, CommonAncestor); 5801 5802 if (IsUsingDirectiveInToplevelContext(CurContext) && 5803 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 5804 Diag(IdentLoc, diag::warn_using_directive_in_header); 5805 } 5806 5807 PushUsingDirective(S, UDir); 5808 } else { 5809 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 5810 } 5811 5812 // FIXME: We ignore attributes for now. 5813 return UDir; 5814} 5815 5816void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 5817 // If the scope has an associated entity and the using directive is at 5818 // namespace or translation unit scope, add the UsingDirectiveDecl into 5819 // its lookup structure so qualified name lookup can find it. 5820 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()); 5821 if (Ctx && !Ctx->isFunctionOrMethod()) 5822 Ctx->addDecl(UDir); 5823 else 5824 // Otherwise, it is at block sope. The using-directives will affect lookup 5825 // only to the end of the scope. 5826 S->PushUsingDirective(UDir); 5827} 5828 5829 5830Decl *Sema::ActOnUsingDeclaration(Scope *S, 5831 AccessSpecifier AS, 5832 bool HasUsingKeyword, 5833 SourceLocation UsingLoc, 5834 CXXScopeSpec &SS, 5835 UnqualifiedId &Name, 5836 AttributeList *AttrList, 5837 bool IsTypeName, 5838 SourceLocation TypenameLoc) { 5839 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 5840 5841 switch (Name.getKind()) { 5842 case UnqualifiedId::IK_ImplicitSelfParam: 5843 case UnqualifiedId::IK_Identifier: 5844 case UnqualifiedId::IK_OperatorFunctionId: 5845 case UnqualifiedId::IK_LiteralOperatorId: 5846 case UnqualifiedId::IK_ConversionFunctionId: 5847 break; 5848 5849 case UnqualifiedId::IK_ConstructorName: 5850 case UnqualifiedId::IK_ConstructorTemplateId: 5851 // C++11 inheriting constructors. 5852 Diag(Name.getLocStart(), 5853 getLangOpts().CPlusPlus0x ? 5854 // FIXME: Produce warn_cxx98_compat_using_decl_constructor 5855 // instead once inheriting constructors work. 5856 diag::err_using_decl_constructor_unsupported : 5857 diag::err_using_decl_constructor) 5858 << SS.getRange(); 5859 5860 if (getLangOpts().CPlusPlus0x) break; 5861 5862 return 0; 5863 5864 case UnqualifiedId::IK_DestructorName: 5865 Diag(Name.getLocStart(), diag::err_using_decl_destructor) 5866 << SS.getRange(); 5867 return 0; 5868 5869 case UnqualifiedId::IK_TemplateId: 5870 Diag(Name.getLocStart(), diag::err_using_decl_template_id) 5871 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 5872 return 0; 5873 } 5874 5875 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 5876 DeclarationName TargetName = TargetNameInfo.getName(); 5877 if (!TargetName) 5878 return 0; 5879 5880 // Warn about using declarations. 5881 // TODO: store that the declaration was written without 'using' and 5882 // talk about access decls instead of using decls in the 5883 // diagnostics. 5884 if (!HasUsingKeyword) { 5885 UsingLoc = Name.getLocStart(); 5886 5887 Diag(UsingLoc, diag::warn_access_decl_deprecated) 5888 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 5889 } 5890 5891 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 5892 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 5893 return 0; 5894 5895 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 5896 TargetNameInfo, AttrList, 5897 /* IsInstantiation */ false, 5898 IsTypeName, TypenameLoc); 5899 if (UD) 5900 PushOnScopeChains(UD, S, /*AddToContext*/ false); 5901 5902 return UD; 5903} 5904 5905/// \brief Determine whether a using declaration considers the given 5906/// declarations as "equivalent", e.g., if they are redeclarations of 5907/// the same entity or are both typedefs of the same type. 5908static bool 5909IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2, 5910 bool &SuppressRedeclaration) { 5911 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) { 5912 SuppressRedeclaration = false; 5913 return true; 5914 } 5915 5916 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 5917 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) { 5918 SuppressRedeclaration = true; 5919 return Context.hasSameType(TD1->getUnderlyingType(), 5920 TD2->getUnderlyingType()); 5921 } 5922 5923 return false; 5924} 5925 5926 5927/// Determines whether to create a using shadow decl for a particular 5928/// decl, given the set of decls existing prior to this using lookup. 5929bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 5930 const LookupResult &Previous) { 5931 // Diagnose finding a decl which is not from a base class of the 5932 // current class. We do this now because there are cases where this 5933 // function will silently decide not to build a shadow decl, which 5934 // will pre-empt further diagnostics. 5935 // 5936 // We don't need to do this in C++0x because we do the check once on 5937 // the qualifier. 5938 // 5939 // FIXME: diagnose the following if we care enough: 5940 // struct A { int foo; }; 5941 // struct B : A { using A::foo; }; 5942 // template <class T> struct C : A {}; 5943 // template <class T> struct D : C<T> { using B::foo; } // <--- 5944 // This is invalid (during instantiation) in C++03 because B::foo 5945 // resolves to the using decl in B, which is not a base class of D<T>. 5946 // We can't diagnose it immediately because C<T> is an unknown 5947 // specialization. The UsingShadowDecl in D<T> then points directly 5948 // to A::foo, which will look well-formed when we instantiate. 5949 // The right solution is to not collapse the shadow-decl chain. 5950 if (!getLangOpts().CPlusPlus0x && CurContext->isRecord()) { 5951 DeclContext *OrigDC = Orig->getDeclContext(); 5952 5953 // Handle enums and anonymous structs. 5954 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 5955 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 5956 while (OrigRec->isAnonymousStructOrUnion()) 5957 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 5958 5959 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 5960 if (OrigDC == CurContext) { 5961 Diag(Using->getLocation(), 5962 diag::err_using_decl_nested_name_specifier_is_current_class) 5963 << Using->getQualifierLoc().getSourceRange(); 5964 Diag(Orig->getLocation(), diag::note_using_decl_target); 5965 return true; 5966 } 5967 5968 Diag(Using->getQualifierLoc().getBeginLoc(), 5969 diag::err_using_decl_nested_name_specifier_is_not_base_class) 5970 << Using->getQualifier() 5971 << cast<CXXRecordDecl>(CurContext) 5972 << Using->getQualifierLoc().getSourceRange(); 5973 Diag(Orig->getLocation(), diag::note_using_decl_target); 5974 return true; 5975 } 5976 } 5977 5978 if (Previous.empty()) return false; 5979 5980 NamedDecl *Target = Orig; 5981 if (isa<UsingShadowDecl>(Target)) 5982 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 5983 5984 // If the target happens to be one of the previous declarations, we 5985 // don't have a conflict. 5986 // 5987 // FIXME: but we might be increasing its access, in which case we 5988 // should redeclare it. 5989 NamedDecl *NonTag = 0, *Tag = 0; 5990 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 5991 I != E; ++I) { 5992 NamedDecl *D = (*I)->getUnderlyingDecl(); 5993 bool Result; 5994 if (IsEquivalentForUsingDecl(Context, D, Target, Result)) 5995 return Result; 5996 5997 (isa<TagDecl>(D) ? Tag : NonTag) = D; 5998 } 5999 6000 if (Target->isFunctionOrFunctionTemplate()) { 6001 FunctionDecl *FD; 6002 if (isa<FunctionTemplateDecl>(Target)) 6003 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl(); 6004 else 6005 FD = cast<FunctionDecl>(Target); 6006 6007 NamedDecl *OldDecl = 0; 6008 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) { 6009 case Ovl_Overload: 6010 return false; 6011 6012 case Ovl_NonFunction: 6013 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6014 break; 6015 6016 // We found a decl with the exact signature. 6017 case Ovl_Match: 6018 // If we're in a record, we want to hide the target, so we 6019 // return true (without a diagnostic) to tell the caller not to 6020 // build a shadow decl. 6021 if (CurContext->isRecord()) 6022 return true; 6023 6024 // If we're not in a record, this is an error. 6025 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6026 break; 6027 } 6028 6029 Diag(Target->getLocation(), diag::note_using_decl_target); 6030 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 6031 return true; 6032 } 6033 6034 // Target is not a function. 6035 6036 if (isa<TagDecl>(Target)) { 6037 // No conflict between a tag and a non-tag. 6038 if (!Tag) return false; 6039 6040 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6041 Diag(Target->getLocation(), diag::note_using_decl_target); 6042 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 6043 return true; 6044 } 6045 6046 // No conflict between a tag and a non-tag. 6047 if (!NonTag) return false; 6048 6049 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6050 Diag(Target->getLocation(), diag::note_using_decl_target); 6051 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 6052 return true; 6053} 6054 6055/// Builds a shadow declaration corresponding to a 'using' declaration. 6056UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 6057 UsingDecl *UD, 6058 NamedDecl *Orig) { 6059 6060 // If we resolved to another shadow declaration, just coalesce them. 6061 NamedDecl *Target = Orig; 6062 if (isa<UsingShadowDecl>(Target)) { 6063 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 6064 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 6065 } 6066 6067 UsingShadowDecl *Shadow 6068 = UsingShadowDecl::Create(Context, CurContext, 6069 UD->getLocation(), UD, Target); 6070 UD->addShadowDecl(Shadow); 6071 6072 Shadow->setAccess(UD->getAccess()); 6073 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 6074 Shadow->setInvalidDecl(); 6075 6076 if (S) 6077 PushOnScopeChains(Shadow, S); 6078 else 6079 CurContext->addDecl(Shadow); 6080 6081 6082 return Shadow; 6083} 6084 6085/// Hides a using shadow declaration. This is required by the current 6086/// using-decl implementation when a resolvable using declaration in a 6087/// class is followed by a declaration which would hide or override 6088/// one or more of the using decl's targets; for example: 6089/// 6090/// struct Base { void foo(int); }; 6091/// struct Derived : Base { 6092/// using Base::foo; 6093/// void foo(int); 6094/// }; 6095/// 6096/// The governing language is C++03 [namespace.udecl]p12: 6097/// 6098/// When a using-declaration brings names from a base class into a 6099/// derived class scope, member functions in the derived class 6100/// override and/or hide member functions with the same name and 6101/// parameter types in a base class (rather than conflicting). 6102/// 6103/// There are two ways to implement this: 6104/// (1) optimistically create shadow decls when they're not hidden 6105/// by existing declarations, or 6106/// (2) don't create any shadow decls (or at least don't make them 6107/// visible) until we've fully parsed/instantiated the class. 6108/// The problem with (1) is that we might have to retroactively remove 6109/// a shadow decl, which requires several O(n) operations because the 6110/// decl structures are (very reasonably) not designed for removal. 6111/// (2) avoids this but is very fiddly and phase-dependent. 6112void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 6113 if (Shadow->getDeclName().getNameKind() == 6114 DeclarationName::CXXConversionFunctionName) 6115 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 6116 6117 // Remove it from the DeclContext... 6118 Shadow->getDeclContext()->removeDecl(Shadow); 6119 6120 // ...and the scope, if applicable... 6121 if (S) { 6122 S->RemoveDecl(Shadow); 6123 IdResolver.RemoveDecl(Shadow); 6124 } 6125 6126 // ...and the using decl. 6127 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 6128 6129 // TODO: complain somehow if Shadow was used. It shouldn't 6130 // be possible for this to happen, because...? 6131} 6132 6133/// Builds a using declaration. 6134/// 6135/// \param IsInstantiation - Whether this call arises from an 6136/// instantiation of an unresolved using declaration. We treat 6137/// the lookup differently for these declarations. 6138NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 6139 SourceLocation UsingLoc, 6140 CXXScopeSpec &SS, 6141 const DeclarationNameInfo &NameInfo, 6142 AttributeList *AttrList, 6143 bool IsInstantiation, 6144 bool IsTypeName, 6145 SourceLocation TypenameLoc) { 6146 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 6147 SourceLocation IdentLoc = NameInfo.getLoc(); 6148 assert(IdentLoc.isValid() && "Invalid TargetName location."); 6149 6150 // FIXME: We ignore attributes for now. 6151 6152 if (SS.isEmpty()) { 6153 Diag(IdentLoc, diag::err_using_requires_qualname); 6154 return 0; 6155 } 6156 6157 // Do the redeclaration lookup in the current scope. 6158 LookupResult Previous(*this, NameInfo, LookupUsingDeclName, 6159 ForRedeclaration); 6160 Previous.setHideTags(false); 6161 if (S) { 6162 LookupName(Previous, S); 6163 6164 // It is really dumb that we have to do this. 6165 LookupResult::Filter F = Previous.makeFilter(); 6166 while (F.hasNext()) { 6167 NamedDecl *D = F.next(); 6168 if (!isDeclInScope(D, CurContext, S)) 6169 F.erase(); 6170 } 6171 F.done(); 6172 } else { 6173 assert(IsInstantiation && "no scope in non-instantiation"); 6174 assert(CurContext->isRecord() && "scope not record in instantiation"); 6175 LookupQualifiedName(Previous, CurContext); 6176 } 6177 6178 // Check for invalid redeclarations. 6179 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous)) 6180 return 0; 6181 6182 // Check for bad qualifiers. 6183 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc)) 6184 return 0; 6185 6186 DeclContext *LookupContext = computeDeclContext(SS); 6187 NamedDecl *D; 6188 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 6189 if (!LookupContext) { 6190 if (IsTypeName) { 6191 // FIXME: not all declaration name kinds are legal here 6192 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 6193 UsingLoc, TypenameLoc, 6194 QualifierLoc, 6195 IdentLoc, NameInfo.getName()); 6196 } else { 6197 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 6198 QualifierLoc, NameInfo); 6199 } 6200 } else { 6201 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 6202 NameInfo, IsTypeName); 6203 } 6204 D->setAccess(AS); 6205 CurContext->addDecl(D); 6206 6207 if (!LookupContext) return D; 6208 UsingDecl *UD = cast<UsingDecl>(D); 6209 6210 if (RequireCompleteDeclContext(SS, LookupContext)) { 6211 UD->setInvalidDecl(); 6212 return UD; 6213 } 6214 6215 // The normal rules do not apply to inheriting constructor declarations. 6216 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) { 6217 if (CheckInheritingConstructorUsingDecl(UD)) 6218 UD->setInvalidDecl(); 6219 return UD; 6220 } 6221 6222 // Otherwise, look up the target name. 6223 6224 LookupResult R(*this, NameInfo, LookupOrdinaryName); 6225 6226 // Unlike most lookups, we don't always want to hide tag 6227 // declarations: tag names are visible through the using declaration 6228 // even if hidden by ordinary names, *except* in a dependent context 6229 // where it's important for the sanity of two-phase lookup. 6230 if (!IsInstantiation) 6231 R.setHideTags(false); 6232 6233 // For the purposes of this lookup, we have a base object type 6234 // equal to that of the current context. 6235 if (CurContext->isRecord()) { 6236 R.setBaseObjectType( 6237 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 6238 } 6239 6240 LookupQualifiedName(R, LookupContext); 6241 6242 if (R.empty()) { 6243 Diag(IdentLoc, diag::err_no_member) 6244 << NameInfo.getName() << LookupContext << SS.getRange(); 6245 UD->setInvalidDecl(); 6246 return UD; 6247 } 6248 6249 if (R.isAmbiguous()) { 6250 UD->setInvalidDecl(); 6251 return UD; 6252 } 6253 6254 if (IsTypeName) { 6255 // If we asked for a typename and got a non-type decl, error out. 6256 if (!R.getAsSingle<TypeDecl>()) { 6257 Diag(IdentLoc, diag::err_using_typename_non_type); 6258 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 6259 Diag((*I)->getUnderlyingDecl()->getLocation(), 6260 diag::note_using_decl_target); 6261 UD->setInvalidDecl(); 6262 return UD; 6263 } 6264 } else { 6265 // If we asked for a non-typename and we got a type, error out, 6266 // but only if this is an instantiation of an unresolved using 6267 // decl. Otherwise just silently find the type name. 6268 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 6269 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 6270 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 6271 UD->setInvalidDecl(); 6272 return UD; 6273 } 6274 } 6275 6276 // C++0x N2914 [namespace.udecl]p6: 6277 // A using-declaration shall not name a namespace. 6278 if (R.getAsSingle<NamespaceDecl>()) { 6279 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 6280 << SS.getRange(); 6281 UD->setInvalidDecl(); 6282 return UD; 6283 } 6284 6285 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 6286 if (!CheckUsingShadowDecl(UD, *I, Previous)) 6287 BuildUsingShadowDecl(S, UD, *I); 6288 } 6289 6290 return UD; 6291} 6292 6293/// Additional checks for a using declaration referring to a constructor name. 6294bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 6295 assert(!UD->isTypeName() && "expecting a constructor name"); 6296 6297 const Type *SourceType = UD->getQualifier()->getAsType(); 6298 assert(SourceType && 6299 "Using decl naming constructor doesn't have type in scope spec."); 6300 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 6301 6302 // Check whether the named type is a direct base class. 6303 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified(); 6304 CXXRecordDecl::base_class_iterator BaseIt, BaseE; 6305 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end(); 6306 BaseIt != BaseE; ++BaseIt) { 6307 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified(); 6308 if (CanonicalSourceType == BaseType) 6309 break; 6310 if (BaseIt->getType()->isDependentType()) 6311 break; 6312 } 6313 6314 if (BaseIt == BaseE) { 6315 // Did not find SourceType in the bases. 6316 Diag(UD->getUsingLocation(), 6317 diag::err_using_decl_constructor_not_in_direct_base) 6318 << UD->getNameInfo().getSourceRange() 6319 << QualType(SourceType, 0) << TargetClass; 6320 return true; 6321 } 6322 6323 if (!CurContext->isDependentContext()) 6324 BaseIt->setInheritConstructors(); 6325 6326 return false; 6327} 6328 6329/// Checks that the given using declaration is not an invalid 6330/// redeclaration. Note that this is checking only for the using decl 6331/// itself, not for any ill-formedness among the UsingShadowDecls. 6332bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 6333 bool isTypeName, 6334 const CXXScopeSpec &SS, 6335 SourceLocation NameLoc, 6336 const LookupResult &Prev) { 6337 // C++03 [namespace.udecl]p8: 6338 // C++0x [namespace.udecl]p10: 6339 // A using-declaration is a declaration and can therefore be used 6340 // repeatedly where (and only where) multiple declarations are 6341 // allowed. 6342 // 6343 // That's in non-member contexts. 6344 if (!CurContext->getRedeclContext()->isRecord()) 6345 return false; 6346 6347 NestedNameSpecifier *Qual 6348 = static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 6349 6350 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 6351 NamedDecl *D = *I; 6352 6353 bool DTypename; 6354 NestedNameSpecifier *DQual; 6355 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 6356 DTypename = UD->isTypeName(); 6357 DQual = UD->getQualifier(); 6358 } else if (UnresolvedUsingValueDecl *UD 6359 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 6360 DTypename = false; 6361 DQual = UD->getQualifier(); 6362 } else if (UnresolvedUsingTypenameDecl *UD 6363 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 6364 DTypename = true; 6365 DQual = UD->getQualifier(); 6366 } else continue; 6367 6368 // using decls differ if one says 'typename' and the other doesn't. 6369 // FIXME: non-dependent using decls? 6370 if (isTypeName != DTypename) continue; 6371 6372 // using decls differ if they name different scopes (but note that 6373 // template instantiation can cause this check to trigger when it 6374 // didn't before instantiation). 6375 if (Context.getCanonicalNestedNameSpecifier(Qual) != 6376 Context.getCanonicalNestedNameSpecifier(DQual)) 6377 continue; 6378 6379 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 6380 Diag(D->getLocation(), diag::note_using_decl) << 1; 6381 return true; 6382 } 6383 6384 return false; 6385} 6386 6387 6388/// Checks that the given nested-name qualifier used in a using decl 6389/// in the current context is appropriately related to the current 6390/// scope. If an error is found, diagnoses it and returns true. 6391bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 6392 const CXXScopeSpec &SS, 6393 SourceLocation NameLoc) { 6394 DeclContext *NamedContext = computeDeclContext(SS); 6395 6396 if (!CurContext->isRecord()) { 6397 // C++03 [namespace.udecl]p3: 6398 // C++0x [namespace.udecl]p8: 6399 // A using-declaration for a class member shall be a member-declaration. 6400 6401 // If we weren't able to compute a valid scope, it must be a 6402 // dependent class scope. 6403 if (!NamedContext || NamedContext->isRecord()) { 6404 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 6405 << SS.getRange(); 6406 return true; 6407 } 6408 6409 // Otherwise, everything is known to be fine. 6410 return false; 6411 } 6412 6413 // The current scope is a record. 6414 6415 // If the named context is dependent, we can't decide much. 6416 if (!NamedContext) { 6417 // FIXME: in C++0x, we can diagnose if we can prove that the 6418 // nested-name-specifier does not refer to a base class, which is 6419 // still possible in some cases. 6420 6421 // Otherwise we have to conservatively report that things might be 6422 // okay. 6423 return false; 6424 } 6425 6426 if (!NamedContext->isRecord()) { 6427 // Ideally this would point at the last name in the specifier, 6428 // but we don't have that level of source info. 6429 Diag(SS.getRange().getBegin(), 6430 diag::err_using_decl_nested_name_specifier_is_not_class) 6431 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange(); 6432 return true; 6433 } 6434 6435 if (!NamedContext->isDependentContext() && 6436 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 6437 return true; 6438 6439 if (getLangOpts().CPlusPlus0x) { 6440 // C++0x [namespace.udecl]p3: 6441 // In a using-declaration used as a member-declaration, the 6442 // nested-name-specifier shall name a base class of the class 6443 // being defined. 6444 6445 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 6446 cast<CXXRecordDecl>(NamedContext))) { 6447 if (CurContext == NamedContext) { 6448 Diag(NameLoc, 6449 diag::err_using_decl_nested_name_specifier_is_current_class) 6450 << SS.getRange(); 6451 return true; 6452 } 6453 6454 Diag(SS.getRange().getBegin(), 6455 diag::err_using_decl_nested_name_specifier_is_not_base_class) 6456 << (NestedNameSpecifier*) SS.getScopeRep() 6457 << cast<CXXRecordDecl>(CurContext) 6458 << SS.getRange(); 6459 return true; 6460 } 6461 6462 return false; 6463 } 6464 6465 // C++03 [namespace.udecl]p4: 6466 // A using-declaration used as a member-declaration shall refer 6467 // to a member of a base class of the class being defined [etc.]. 6468 6469 // Salient point: SS doesn't have to name a base class as long as 6470 // lookup only finds members from base classes. Therefore we can 6471 // diagnose here only if we can prove that that can't happen, 6472 // i.e. if the class hierarchies provably don't intersect. 6473 6474 // TODO: it would be nice if "definitely valid" results were cached 6475 // in the UsingDecl and UsingShadowDecl so that these checks didn't 6476 // need to be repeated. 6477 6478 struct UserData { 6479 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases; 6480 6481 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) { 6482 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 6483 Data->Bases.insert(Base); 6484 return true; 6485 } 6486 6487 bool hasDependentBases(const CXXRecordDecl *Class) { 6488 return !Class->forallBases(collect, this); 6489 } 6490 6491 /// Returns true if the base is dependent or is one of the 6492 /// accumulated base classes. 6493 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) { 6494 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 6495 return !Data->Bases.count(Base); 6496 } 6497 6498 bool mightShareBases(const CXXRecordDecl *Class) { 6499 return Bases.count(Class) || !Class->forallBases(doesNotContain, this); 6500 } 6501 }; 6502 6503 UserData Data; 6504 6505 // Returns false if we find a dependent base. 6506 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext))) 6507 return false; 6508 6509 // Returns false if the class has a dependent base or if it or one 6510 // of its bases is present in the base set of the current context. 6511 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext))) 6512 return false; 6513 6514 Diag(SS.getRange().getBegin(), 6515 diag::err_using_decl_nested_name_specifier_is_not_base_class) 6516 << (NestedNameSpecifier*) SS.getScopeRep() 6517 << cast<CXXRecordDecl>(CurContext) 6518 << SS.getRange(); 6519 6520 return true; 6521} 6522 6523Decl *Sema::ActOnAliasDeclaration(Scope *S, 6524 AccessSpecifier AS, 6525 MultiTemplateParamsArg TemplateParamLists, 6526 SourceLocation UsingLoc, 6527 UnqualifiedId &Name, 6528 TypeResult Type) { 6529 // Skip up to the relevant declaration scope. 6530 while (S->getFlags() & Scope::TemplateParamScope) 6531 S = S->getParent(); 6532 assert((S->getFlags() & Scope::DeclScope) && 6533 "got alias-declaration outside of declaration scope"); 6534 6535 if (Type.isInvalid()) 6536 return 0; 6537 6538 bool Invalid = false; 6539 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 6540 TypeSourceInfo *TInfo = 0; 6541 GetTypeFromParser(Type.get(), &TInfo); 6542 6543 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 6544 return 0; 6545 6546 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 6547 UPPC_DeclarationType)) { 6548 Invalid = true; 6549 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 6550 TInfo->getTypeLoc().getBeginLoc()); 6551 } 6552 6553 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration); 6554 LookupName(Previous, S); 6555 6556 // Warn about shadowing the name of a template parameter. 6557 if (Previous.isSingleResult() && 6558 Previous.getFoundDecl()->isTemplateParameter()) { 6559 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 6560 Previous.clear(); 6561 } 6562 6563 assert(Name.Kind == UnqualifiedId::IK_Identifier && 6564 "name in alias declaration must be an identifier"); 6565 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 6566 Name.StartLocation, 6567 Name.Identifier, TInfo); 6568 6569 NewTD->setAccess(AS); 6570 6571 if (Invalid) 6572 NewTD->setInvalidDecl(); 6573 6574 CheckTypedefForVariablyModifiedType(S, NewTD); 6575 Invalid |= NewTD->isInvalidDecl(); 6576 6577 bool Redeclaration = false; 6578 6579 NamedDecl *NewND; 6580 if (TemplateParamLists.size()) { 6581 TypeAliasTemplateDecl *OldDecl = 0; 6582 TemplateParameterList *OldTemplateParams = 0; 6583 6584 if (TemplateParamLists.size() != 1) { 6585 Diag(UsingLoc, diag::err_alias_template_extra_headers) 6586 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 6587 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 6588 } 6589 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 6590 6591 // Only consider previous declarations in the same scope. 6592 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 6593 /*ExplicitInstantiationOrSpecialization*/false); 6594 if (!Previous.empty()) { 6595 Redeclaration = true; 6596 6597 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 6598 if (!OldDecl && !Invalid) { 6599 Diag(UsingLoc, diag::err_redefinition_different_kind) 6600 << Name.Identifier; 6601 6602 NamedDecl *OldD = Previous.getRepresentativeDecl(); 6603 if (OldD->getLocation().isValid()) 6604 Diag(OldD->getLocation(), diag::note_previous_definition); 6605 6606 Invalid = true; 6607 } 6608 6609 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 6610 if (TemplateParameterListsAreEqual(TemplateParams, 6611 OldDecl->getTemplateParameters(), 6612 /*Complain=*/true, 6613 TPL_TemplateMatch)) 6614 OldTemplateParams = OldDecl->getTemplateParameters(); 6615 else 6616 Invalid = true; 6617 6618 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 6619 if (!Invalid && 6620 !Context.hasSameType(OldTD->getUnderlyingType(), 6621 NewTD->getUnderlyingType())) { 6622 // FIXME: The C++0x standard does not clearly say this is ill-formed, 6623 // but we can't reasonably accept it. 6624 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 6625 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 6626 if (OldTD->getLocation().isValid()) 6627 Diag(OldTD->getLocation(), diag::note_previous_definition); 6628 Invalid = true; 6629 } 6630 } 6631 } 6632 6633 // Merge any previous default template arguments into our parameters, 6634 // and check the parameter list. 6635 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 6636 TPC_TypeAliasTemplate)) 6637 return 0; 6638 6639 TypeAliasTemplateDecl *NewDecl = 6640 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 6641 Name.Identifier, TemplateParams, 6642 NewTD); 6643 6644 NewDecl->setAccess(AS); 6645 6646 if (Invalid) 6647 NewDecl->setInvalidDecl(); 6648 else if (OldDecl) 6649 NewDecl->setPreviousDeclaration(OldDecl); 6650 6651 NewND = NewDecl; 6652 } else { 6653 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 6654 NewND = NewTD; 6655 } 6656 6657 if (!Redeclaration) 6658 PushOnScopeChains(NewND, S); 6659 6660 ActOnDocumentableDecl(NewND); 6661 return NewND; 6662} 6663 6664Decl *Sema::ActOnNamespaceAliasDef(Scope *S, 6665 SourceLocation NamespaceLoc, 6666 SourceLocation AliasLoc, 6667 IdentifierInfo *Alias, 6668 CXXScopeSpec &SS, 6669 SourceLocation IdentLoc, 6670 IdentifierInfo *Ident) { 6671 6672 // Lookup the namespace name. 6673 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 6674 LookupParsedName(R, S, &SS); 6675 6676 // Check if we have a previous declaration with the same name. 6677 NamedDecl *PrevDecl 6678 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName, 6679 ForRedeclaration); 6680 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S)) 6681 PrevDecl = 0; 6682 6683 if (PrevDecl) { 6684 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 6685 // We already have an alias with the same name that points to the same 6686 // namespace, so don't create a new one. 6687 // FIXME: At some point, we'll want to create the (redundant) 6688 // declaration to maintain better source information. 6689 if (!R.isAmbiguous() && !R.empty() && 6690 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl()))) 6691 return 0; 6692 } 6693 6694 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition : 6695 diag::err_redefinition_different_kind; 6696 Diag(AliasLoc, DiagID) << Alias; 6697 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 6698 return 0; 6699 } 6700 6701 if (R.isAmbiguous()) 6702 return 0; 6703 6704 if (R.empty()) { 6705 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 6706 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 6707 return 0; 6708 } 6709 } 6710 6711 NamespaceAliasDecl *AliasDecl = 6712 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 6713 Alias, SS.getWithLocInContext(Context), 6714 IdentLoc, R.getFoundDecl()); 6715 6716 PushOnScopeChains(AliasDecl, S); 6717 return AliasDecl; 6718} 6719 6720namespace { 6721 /// \brief Scoped object used to handle the state changes required in Sema 6722 /// to implicitly define the body of a C++ member function; 6723 class ImplicitlyDefinedFunctionScope { 6724 Sema &S; 6725 Sema::ContextRAII SavedContext; 6726 6727 public: 6728 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method) 6729 : S(S), SavedContext(S, Method) 6730 { 6731 S.PushFunctionScope(); 6732 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated); 6733 } 6734 6735 ~ImplicitlyDefinedFunctionScope() { 6736 S.PopExpressionEvaluationContext(); 6737 S.PopFunctionScopeInfo(); 6738 } 6739 }; 6740} 6741 6742Sema::ImplicitExceptionSpecification 6743Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, 6744 CXXMethodDecl *MD) { 6745 CXXRecordDecl *ClassDecl = MD->getParent(); 6746 6747 // C++ [except.spec]p14: 6748 // An implicitly declared special member function (Clause 12) shall have an 6749 // exception-specification. [...] 6750 ImplicitExceptionSpecification ExceptSpec(*this); 6751 if (ClassDecl->isInvalidDecl()) 6752 return ExceptSpec; 6753 6754 // Direct base-class constructors. 6755 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 6756 BEnd = ClassDecl->bases_end(); 6757 B != BEnd; ++B) { 6758 if (B->isVirtual()) // Handled below. 6759 continue; 6760 6761 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 6762 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 6763 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 6764 // If this is a deleted function, add it anyway. This might be conformant 6765 // with the standard. This might not. I'm not sure. It might not matter. 6766 if (Constructor) 6767 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 6768 } 6769 } 6770 6771 // Virtual base-class constructors. 6772 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 6773 BEnd = ClassDecl->vbases_end(); 6774 B != BEnd; ++B) { 6775 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 6776 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 6777 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 6778 // If this is a deleted function, add it anyway. This might be conformant 6779 // with the standard. This might not. I'm not sure. It might not matter. 6780 if (Constructor) 6781 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 6782 } 6783 } 6784 6785 // Field constructors. 6786 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 6787 FEnd = ClassDecl->field_end(); 6788 F != FEnd; ++F) { 6789 if (F->hasInClassInitializer()) { 6790 if (Expr *E = F->getInClassInitializer()) 6791 ExceptSpec.CalledExpr(E); 6792 else if (!F->isInvalidDecl()) 6793 // DR1351: 6794 // If the brace-or-equal-initializer of a non-static data member 6795 // invokes a defaulted default constructor of its class or of an 6796 // enclosing class in a potentially evaluated subexpression, the 6797 // program is ill-formed. 6798 // 6799 // This resolution is unworkable: the exception specification of the 6800 // default constructor can be needed in an unevaluated context, in 6801 // particular, in the operand of a noexcept-expression, and we can be 6802 // unable to compute an exception specification for an enclosed class. 6803 // 6804 // We do not allow an in-class initializer to require the evaluation 6805 // of the exception specification for any in-class initializer whose 6806 // definition is not lexically complete. 6807 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD; 6808 } else if (const RecordType *RecordTy 6809 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 6810 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 6811 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 6812 // If this is a deleted function, add it anyway. This might be conformant 6813 // with the standard. This might not. I'm not sure. It might not matter. 6814 // In particular, the problem is that this function never gets called. It 6815 // might just be ill-formed because this function attempts to refer to 6816 // a deleted function here. 6817 if (Constructor) 6818 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 6819 } 6820 } 6821 6822 return ExceptSpec; 6823} 6824 6825CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 6826 CXXRecordDecl *ClassDecl) { 6827 // C++ [class.ctor]p5: 6828 // A default constructor for a class X is a constructor of class X 6829 // that can be called without an argument. If there is no 6830 // user-declared constructor for class X, a default constructor is 6831 // implicitly declared. An implicitly-declared default constructor 6832 // is an inline public member of its class. 6833 assert(!ClassDecl->hasUserDeclaredConstructor() && 6834 "Should not build implicit default constructor!"); 6835 6836 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 6837 CXXDefaultConstructor, 6838 false); 6839 6840 // Create the actual constructor declaration. 6841 CanQualType ClassType 6842 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 6843 SourceLocation ClassLoc = ClassDecl->getLocation(); 6844 DeclarationName Name 6845 = Context.DeclarationNames.getCXXConstructorName(ClassType); 6846 DeclarationNameInfo NameInfo(Name, ClassLoc); 6847 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 6848 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0, 6849 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 6850 Constexpr); 6851 DefaultCon->setAccess(AS_public); 6852 DefaultCon->setDefaulted(); 6853 DefaultCon->setImplicit(); 6854 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 6855 6856 // Build an exception specification pointing back at this constructor. 6857 FunctionProtoType::ExtProtoInfo EPI; 6858 EPI.ExceptionSpecType = EST_Unevaluated; 6859 EPI.ExceptionSpecDecl = DefaultCon; 6860 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI)); 6861 6862 // Note that we have declared this constructor. 6863 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 6864 6865 if (Scope *S = getScopeForContext(ClassDecl)) 6866 PushOnScopeChains(DefaultCon, S, false); 6867 ClassDecl->addDecl(DefaultCon); 6868 6869 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 6870 DefaultCon->setDeletedAsWritten(); 6871 6872 return DefaultCon; 6873} 6874 6875void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 6876 CXXConstructorDecl *Constructor) { 6877 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 6878 !Constructor->doesThisDeclarationHaveABody() && 6879 !Constructor->isDeleted()) && 6880 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 6881 6882 CXXRecordDecl *ClassDecl = Constructor->getParent(); 6883 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 6884 6885 ImplicitlyDefinedFunctionScope Scope(*this, Constructor); 6886 DiagnosticErrorTrap Trap(Diags); 6887 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) || 6888 Trap.hasErrorOccurred()) { 6889 Diag(CurrentLocation, diag::note_member_synthesized_at) 6890 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl); 6891 Constructor->setInvalidDecl(); 6892 return; 6893 } 6894 6895 SourceLocation Loc = Constructor->getLocation(); 6896 Constructor->setBody(new (Context) CompoundStmt(Loc)); 6897 6898 Constructor->setUsed(); 6899 MarkVTableUsed(CurrentLocation, ClassDecl); 6900 6901 if (ASTMutationListener *L = getASTMutationListener()) { 6902 L->CompletedImplicitDefinition(Constructor); 6903 } 6904} 6905 6906void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 6907 if (!D) return; 6908 AdjustDeclIfTemplate(D); 6909 6910 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D); 6911 6912 if (!ClassDecl->isDependentType()) 6913 CheckExplicitlyDefaultedMethods(ClassDecl); 6914} 6915 6916void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) { 6917 // We start with an initial pass over the base classes to collect those that 6918 // inherit constructors from. If there are none, we can forgo all further 6919 // processing. 6920 typedef SmallVector<const RecordType *, 4> BasesVector; 6921 BasesVector BasesToInheritFrom; 6922 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(), 6923 BaseE = ClassDecl->bases_end(); 6924 BaseIt != BaseE; ++BaseIt) { 6925 if (BaseIt->getInheritConstructors()) { 6926 QualType Base = BaseIt->getType(); 6927 if (Base->isDependentType()) { 6928 // If we inherit constructors from anything that is dependent, just 6929 // abort processing altogether. We'll get another chance for the 6930 // instantiations. 6931 return; 6932 } 6933 BasesToInheritFrom.push_back(Base->castAs<RecordType>()); 6934 } 6935 } 6936 if (BasesToInheritFrom.empty()) 6937 return; 6938 6939 // Now collect the constructors that we already have in the current class. 6940 // Those take precedence over inherited constructors. 6941 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...] 6942 // unless there is a user-declared constructor with the same signature in 6943 // the class where the using-declaration appears. 6944 llvm::SmallSet<const Type *, 8> ExistingConstructors; 6945 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(), 6946 CtorE = ClassDecl->ctor_end(); 6947 CtorIt != CtorE; ++CtorIt) { 6948 ExistingConstructors.insert( 6949 Context.getCanonicalType(CtorIt->getType()).getTypePtr()); 6950 } 6951 6952 DeclarationName CreatedCtorName = 6953 Context.DeclarationNames.getCXXConstructorName( 6954 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified()); 6955 6956 // Now comes the true work. 6957 // First, we keep a map from constructor types to the base that introduced 6958 // them. Needed for finding conflicting constructors. We also keep the 6959 // actually inserted declarations in there, for pretty diagnostics. 6960 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo; 6961 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap; 6962 ConstructorToSourceMap InheritedConstructors; 6963 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(), 6964 BaseE = BasesToInheritFrom.end(); 6965 BaseIt != BaseE; ++BaseIt) { 6966 const RecordType *Base = *BaseIt; 6967 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified(); 6968 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl()); 6969 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(), 6970 CtorE = BaseDecl->ctor_end(); 6971 CtorIt != CtorE; ++CtorIt) { 6972 // Find the using declaration for inheriting this base's constructors. 6973 // FIXME: Don't perform name lookup just to obtain a source location! 6974 DeclarationName Name = 6975 Context.DeclarationNames.getCXXConstructorName(CanonicalBase); 6976 LookupResult Result(*this, Name, SourceLocation(), LookupUsingDeclName); 6977 LookupQualifiedName(Result, CurContext); 6978 UsingDecl *UD = Result.getAsSingle<UsingDecl>(); 6979 SourceLocation UsingLoc = UD ? UD->getLocation() : 6980 ClassDecl->getLocation(); 6981 6982 // C++0x [class.inhctor]p1: The candidate set of inherited constructors 6983 // from the class X named in the using-declaration consists of actual 6984 // constructors and notional constructors that result from the 6985 // transformation of defaulted parameters as follows: 6986 // - all non-template default constructors of X, and 6987 // - for each non-template constructor of X that has at least one 6988 // parameter with a default argument, the set of constructors that 6989 // results from omitting any ellipsis parameter specification and 6990 // successively omitting parameters with a default argument from the 6991 // end of the parameter-type-list. 6992 CXXConstructorDecl *BaseCtor = *CtorIt; 6993 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor(); 6994 const FunctionProtoType *BaseCtorType = 6995 BaseCtor->getType()->getAs<FunctionProtoType>(); 6996 6997 for (unsigned params = BaseCtor->getMinRequiredArguments(), 6998 maxParams = BaseCtor->getNumParams(); 6999 params <= maxParams; ++params) { 7000 // Skip default constructors. They're never inherited. 7001 if (params == 0) 7002 continue; 7003 // Skip copy and move constructors for the same reason. 7004 if (CanBeCopyOrMove && params == 1) 7005 continue; 7006 7007 // Build up a function type for this particular constructor. 7008 // FIXME: The working paper does not consider that the exception spec 7009 // for the inheriting constructor might be larger than that of the 7010 // source. This code doesn't yet, either. When it does, this code will 7011 // need to be delayed until after exception specifications and in-class 7012 // member initializers are attached. 7013 const Type *NewCtorType; 7014 if (params == maxParams) 7015 NewCtorType = BaseCtorType; 7016 else { 7017 SmallVector<QualType, 16> Args; 7018 for (unsigned i = 0; i < params; ++i) { 7019 Args.push_back(BaseCtorType->getArgType(i)); 7020 } 7021 FunctionProtoType::ExtProtoInfo ExtInfo = 7022 BaseCtorType->getExtProtoInfo(); 7023 ExtInfo.Variadic = false; 7024 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(), 7025 Args.data(), params, ExtInfo) 7026 .getTypePtr(); 7027 } 7028 const Type *CanonicalNewCtorType = 7029 Context.getCanonicalType(NewCtorType); 7030 7031 // Now that we have the type, first check if the class already has a 7032 // constructor with this signature. 7033 if (ExistingConstructors.count(CanonicalNewCtorType)) 7034 continue; 7035 7036 // Then we check if we have already declared an inherited constructor 7037 // with this signature. 7038 std::pair<ConstructorToSourceMap::iterator, bool> result = 7039 InheritedConstructors.insert(std::make_pair( 7040 CanonicalNewCtorType, 7041 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0))); 7042 if (!result.second) { 7043 // Already in the map. If it came from a different class, that's an 7044 // error. Not if it's from the same. 7045 CanQualType PreviousBase = result.first->second.first; 7046 if (CanonicalBase != PreviousBase) { 7047 const CXXConstructorDecl *PrevCtor = result.first->second.second; 7048 const CXXConstructorDecl *PrevBaseCtor = 7049 PrevCtor->getInheritedConstructor(); 7050 assert(PrevBaseCtor && "Conflicting constructor was not inherited"); 7051 7052 Diag(UsingLoc, diag::err_using_decl_constructor_conflict); 7053 Diag(BaseCtor->getLocation(), 7054 diag::note_using_decl_constructor_conflict_current_ctor); 7055 Diag(PrevBaseCtor->getLocation(), 7056 diag::note_using_decl_constructor_conflict_previous_ctor); 7057 Diag(PrevCtor->getLocation(), 7058 diag::note_using_decl_constructor_conflict_previous_using); 7059 } 7060 continue; 7061 } 7062 7063 // OK, we're there, now add the constructor. 7064 // C++0x [class.inhctor]p8: [...] that would be performed by a 7065 // user-written inline constructor [...] 7066 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc); 7067 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create( 7068 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0), 7069 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true, 7070 /*ImplicitlyDeclared=*/true, 7071 // FIXME: Due to a defect in the standard, we treat inherited 7072 // constructors as constexpr even if that makes them ill-formed. 7073 /*Constexpr=*/BaseCtor->isConstexpr()); 7074 NewCtor->setAccess(BaseCtor->getAccess()); 7075 7076 // Build up the parameter decls and add them. 7077 SmallVector<ParmVarDecl *, 16> ParamDecls; 7078 for (unsigned i = 0; i < params; ++i) { 7079 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor, 7080 UsingLoc, UsingLoc, 7081 /*IdentifierInfo=*/0, 7082 BaseCtorType->getArgType(i), 7083 /*TInfo=*/0, SC_None, 7084 SC_None, /*DefaultArg=*/0)); 7085 } 7086 NewCtor->setParams(ParamDecls); 7087 NewCtor->setInheritedConstructor(BaseCtor); 7088 7089 ClassDecl->addDecl(NewCtor); 7090 result.first->second.second = NewCtor; 7091 } 7092 } 7093 } 7094} 7095 7096Sema::ImplicitExceptionSpecification 7097Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) { 7098 CXXRecordDecl *ClassDecl = MD->getParent(); 7099 7100 // C++ [except.spec]p14: 7101 // An implicitly declared special member function (Clause 12) shall have 7102 // an exception-specification. 7103 ImplicitExceptionSpecification ExceptSpec(*this); 7104 if (ClassDecl->isInvalidDecl()) 7105 return ExceptSpec; 7106 7107 // Direct base-class destructors. 7108 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 7109 BEnd = ClassDecl->bases_end(); 7110 B != BEnd; ++B) { 7111 if (B->isVirtual()) // Handled below. 7112 continue; 7113 7114 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) 7115 ExceptSpec.CalledDecl(B->getLocStart(), 7116 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 7117 } 7118 7119 // Virtual base-class destructors. 7120 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 7121 BEnd = ClassDecl->vbases_end(); 7122 B != BEnd; ++B) { 7123 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) 7124 ExceptSpec.CalledDecl(B->getLocStart(), 7125 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 7126 } 7127 7128 // Field destructors. 7129 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 7130 FEnd = ClassDecl->field_end(); 7131 F != FEnd; ++F) { 7132 if (const RecordType *RecordTy 7133 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) 7134 ExceptSpec.CalledDecl(F->getLocation(), 7135 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl()))); 7136 } 7137 7138 return ExceptSpec; 7139} 7140 7141CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 7142 // C++ [class.dtor]p2: 7143 // If a class has no user-declared destructor, a destructor is 7144 // declared implicitly. An implicitly-declared destructor is an 7145 // inline public member of its class. 7146 7147 // Create the actual destructor declaration. 7148 CanQualType ClassType 7149 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 7150 SourceLocation ClassLoc = ClassDecl->getLocation(); 7151 DeclarationName Name 7152 = Context.DeclarationNames.getCXXDestructorName(ClassType); 7153 DeclarationNameInfo NameInfo(Name, ClassLoc); 7154 CXXDestructorDecl *Destructor 7155 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 7156 QualType(), 0, /*isInline=*/true, 7157 /*isImplicitlyDeclared=*/true); 7158 Destructor->setAccess(AS_public); 7159 Destructor->setDefaulted(); 7160 Destructor->setImplicit(); 7161 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 7162 7163 // Build an exception specification pointing back at this destructor. 7164 FunctionProtoType::ExtProtoInfo EPI; 7165 EPI.ExceptionSpecType = EST_Unevaluated; 7166 EPI.ExceptionSpecDecl = Destructor; 7167 Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI)); 7168 7169 // Note that we have declared this destructor. 7170 ++ASTContext::NumImplicitDestructorsDeclared; 7171 7172 // Introduce this destructor into its scope. 7173 if (Scope *S = getScopeForContext(ClassDecl)) 7174 PushOnScopeChains(Destructor, S, false); 7175 ClassDecl->addDecl(Destructor); 7176 7177 AddOverriddenMethods(ClassDecl, Destructor); 7178 7179 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 7180 Destructor->setDeletedAsWritten(); 7181 7182 return Destructor; 7183} 7184 7185void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 7186 CXXDestructorDecl *Destructor) { 7187 assert((Destructor->isDefaulted() && 7188 !Destructor->doesThisDeclarationHaveABody() && 7189 !Destructor->isDeleted()) && 7190 "DefineImplicitDestructor - call it for implicit default dtor"); 7191 CXXRecordDecl *ClassDecl = Destructor->getParent(); 7192 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 7193 7194 if (Destructor->isInvalidDecl()) 7195 return; 7196 7197 ImplicitlyDefinedFunctionScope Scope(*this, Destructor); 7198 7199 DiagnosticErrorTrap Trap(Diags); 7200 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 7201 Destructor->getParent()); 7202 7203 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) { 7204 Diag(CurrentLocation, diag::note_member_synthesized_at) 7205 << CXXDestructor << Context.getTagDeclType(ClassDecl); 7206 7207 Destructor->setInvalidDecl(); 7208 return; 7209 } 7210 7211 SourceLocation Loc = Destructor->getLocation(); 7212 Destructor->setBody(new (Context) CompoundStmt(Loc)); 7213 Destructor->setImplicitlyDefined(true); 7214 Destructor->setUsed(); 7215 MarkVTableUsed(CurrentLocation, ClassDecl); 7216 7217 if (ASTMutationListener *L = getASTMutationListener()) { 7218 L->CompletedImplicitDefinition(Destructor); 7219 } 7220} 7221 7222/// \brief Perform any semantic analysis which needs to be delayed until all 7223/// pending class member declarations have been parsed. 7224void Sema::ActOnFinishCXXMemberDecls() { 7225 // Perform any deferred checking of exception specifications for virtual 7226 // destructors. 7227 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size(); 7228 i != e; ++i) { 7229 const CXXDestructorDecl *Dtor = 7230 DelayedDestructorExceptionSpecChecks[i].first; 7231 assert(!Dtor->getParent()->isDependentType() && 7232 "Should not ever add destructors of templates into the list."); 7233 CheckOverridingFunctionExceptionSpec(Dtor, 7234 DelayedDestructorExceptionSpecChecks[i].second); 7235 } 7236 DelayedDestructorExceptionSpecChecks.clear(); 7237} 7238 7239void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 7240 CXXDestructorDecl *Destructor) { 7241 assert(getLangOpts().CPlusPlus0x && 7242 "adjusting dtor exception specs was introduced in c++11"); 7243 7244 // C++11 [class.dtor]p3: 7245 // A declaration of a destructor that does not have an exception- 7246 // specification is implicitly considered to have the same exception- 7247 // specification as an implicit declaration. 7248 const FunctionProtoType *DtorType = Destructor->getType()-> 7249 getAs<FunctionProtoType>(); 7250 if (DtorType->hasExceptionSpec()) 7251 return; 7252 7253 // Replace the destructor's type, building off the existing one. Fortunately, 7254 // the only thing of interest in the destructor type is its extended info. 7255 // The return and arguments are fixed. 7256 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 7257 EPI.ExceptionSpecType = EST_Unevaluated; 7258 EPI.ExceptionSpecDecl = Destructor; 7259 Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI)); 7260 7261 // FIXME: If the destructor has a body that could throw, and the newly created 7262 // spec doesn't allow exceptions, we should emit a warning, because this 7263 // change in behavior can break conforming C++03 programs at runtime. 7264 // However, we don't have a body or an exception specification yet, so it 7265 // needs to be done somewhere else. 7266} 7267 7268/// \brief Builds a statement that copies/moves the given entity from \p From to 7269/// \c To. 7270/// 7271/// This routine is used to copy/move the members of a class with an 7272/// implicitly-declared copy/move assignment operator. When the entities being 7273/// copied are arrays, this routine builds for loops to copy them. 7274/// 7275/// \param S The Sema object used for type-checking. 7276/// 7277/// \param Loc The location where the implicit copy/move is being generated. 7278/// 7279/// \param T The type of the expressions being copied/moved. Both expressions 7280/// must have this type. 7281/// 7282/// \param To The expression we are copying/moving to. 7283/// 7284/// \param From The expression we are copying/moving from. 7285/// 7286/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 7287/// Otherwise, it's a non-static member subobject. 7288/// 7289/// \param Copying Whether we're copying or moving. 7290/// 7291/// \param Depth Internal parameter recording the depth of the recursion. 7292/// 7293/// \returns A statement or a loop that copies the expressions. 7294static StmtResult 7295BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 7296 Expr *To, Expr *From, 7297 bool CopyingBaseSubobject, bool Copying, 7298 unsigned Depth = 0) { 7299 // C++0x [class.copy]p28: 7300 // Each subobject is assigned in the manner appropriate to its type: 7301 // 7302 // - if the subobject is of class type, as if by a call to operator= with 7303 // the subobject as the object expression and the corresponding 7304 // subobject of x as a single function argument (as if by explicit 7305 // qualification; that is, ignoring any possible virtual overriding 7306 // functions in more derived classes); 7307 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 7308 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 7309 7310 // Look for operator=. 7311 DeclarationName Name 7312 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 7313 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 7314 S.LookupQualifiedName(OpLookup, ClassDecl, false); 7315 7316 // Filter out any result that isn't a copy/move-assignment operator. 7317 LookupResult::Filter F = OpLookup.makeFilter(); 7318 while (F.hasNext()) { 7319 NamedDecl *D = F.next(); 7320 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 7321 if (Method->isCopyAssignmentOperator() || 7322 (!Copying && Method->isMoveAssignmentOperator())) 7323 continue; 7324 7325 F.erase(); 7326 } 7327 F.done(); 7328 7329 // Suppress the protected check (C++ [class.protected]) for each of the 7330 // assignment operators we found. This strange dance is required when 7331 // we're assigning via a base classes's copy-assignment operator. To 7332 // ensure that we're getting the right base class subobject (without 7333 // ambiguities), we need to cast "this" to that subobject type; to 7334 // ensure that we don't go through the virtual call mechanism, we need 7335 // to qualify the operator= name with the base class (see below). However, 7336 // this means that if the base class has a protected copy assignment 7337 // operator, the protected member access check will fail. So, we 7338 // rewrite "protected" access to "public" access in this case, since we 7339 // know by construction that we're calling from a derived class. 7340 if (CopyingBaseSubobject) { 7341 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 7342 L != LEnd; ++L) { 7343 if (L.getAccess() == AS_protected) 7344 L.setAccess(AS_public); 7345 } 7346 } 7347 7348 // Create the nested-name-specifier that will be used to qualify the 7349 // reference to operator=; this is required to suppress the virtual 7350 // call mechanism. 7351 CXXScopeSpec SS; 7352 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 7353 SS.MakeTrivial(S.Context, 7354 NestedNameSpecifier::Create(S.Context, 0, false, 7355 CanonicalT), 7356 Loc); 7357 7358 // Create the reference to operator=. 7359 ExprResult OpEqualRef 7360 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS, 7361 /*TemplateKWLoc=*/SourceLocation(), 7362 /*FirstQualifierInScope=*/0, 7363 OpLookup, 7364 /*TemplateArgs=*/0, 7365 /*SuppressQualifierCheck=*/true); 7366 if (OpEqualRef.isInvalid()) 7367 return StmtError(); 7368 7369 // Build the call to the assignment operator. 7370 7371 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0, 7372 OpEqualRef.takeAs<Expr>(), 7373 Loc, &From, 1, Loc); 7374 if (Call.isInvalid()) 7375 return StmtError(); 7376 7377 return S.Owned(Call.takeAs<Stmt>()); 7378 } 7379 7380 // - if the subobject is of scalar type, the built-in assignment 7381 // operator is used. 7382 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 7383 if (!ArrayTy) { 7384 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From); 7385 if (Assignment.isInvalid()) 7386 return StmtError(); 7387 7388 return S.Owned(Assignment.takeAs<Stmt>()); 7389 } 7390 7391 // - if the subobject is an array, each element is assigned, in the 7392 // manner appropriate to the element type; 7393 7394 // Construct a loop over the array bounds, e.g., 7395 // 7396 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 7397 // 7398 // that will copy each of the array elements. 7399 QualType SizeType = S.Context.getSizeType(); 7400 7401 // Create the iteration variable. 7402 IdentifierInfo *IterationVarName = 0; 7403 { 7404 SmallString<8> Str; 7405 llvm::raw_svector_ostream OS(Str); 7406 OS << "__i" << Depth; 7407 IterationVarName = &S.Context.Idents.get(OS.str()); 7408 } 7409 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 7410 IterationVarName, SizeType, 7411 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 7412 SC_None, SC_None); 7413 7414 // Initialize the iteration variable to zero. 7415 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 7416 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 7417 7418 // Create a reference to the iteration variable; we'll use this several 7419 // times throughout. 7420 Expr *IterationVarRef 7421 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take(); 7422 assert(IterationVarRef && "Reference to invented variable cannot fail!"); 7423 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take(); 7424 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!"); 7425 7426 // Create the DeclStmt that holds the iteration variable. 7427 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 7428 7429 // Create the comparison against the array bound. 7430 llvm::APInt Upper 7431 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 7432 Expr *Comparison 7433 = new (S.Context) BinaryOperator(IterationVarRefRVal, 7434 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 7435 BO_NE, S.Context.BoolTy, 7436 VK_RValue, OK_Ordinary, Loc); 7437 7438 // Create the pre-increment of the iteration variable. 7439 Expr *Increment 7440 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType, 7441 VK_LValue, OK_Ordinary, Loc); 7442 7443 // Subscript the "from" and "to" expressions with the iteration variable. 7444 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc, 7445 IterationVarRefRVal, 7446 Loc)); 7447 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc, 7448 IterationVarRefRVal, 7449 Loc)); 7450 if (!Copying) // Cast to rvalue 7451 From = CastForMoving(S, From); 7452 7453 // Build the copy/move for an individual element of the array. 7454 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(), 7455 To, From, CopyingBaseSubobject, 7456 Copying, Depth + 1); 7457 if (Copy.isInvalid()) 7458 return StmtError(); 7459 7460 // Construct the loop that copies all elements of this array. 7461 return S.ActOnForStmt(Loc, Loc, InitStmt, 7462 S.MakeFullExpr(Comparison), 7463 0, S.MakeFullExpr(Increment), 7464 Loc, Copy.take()); 7465} 7466 7467/// Determine whether an implicit copy assignment operator for ClassDecl has a 7468/// const argument. 7469/// FIXME: It ought to be possible to store this on the record. 7470static bool isImplicitCopyAssignmentArgConst(Sema &S, 7471 CXXRecordDecl *ClassDecl) { 7472 if (ClassDecl->isInvalidDecl()) 7473 return true; 7474 7475 // C++ [class.copy]p10: 7476 // If the class definition does not explicitly declare a copy 7477 // assignment operator, one is declared implicitly. 7478 // The implicitly-defined copy assignment operator for a class X 7479 // will have the form 7480 // 7481 // X& X::operator=(const X&) 7482 // 7483 // if 7484 // -- each direct base class B of X has a copy assignment operator 7485 // whose parameter is of type const B&, const volatile B& or B, 7486 // and 7487 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 7488 BaseEnd = ClassDecl->bases_end(); 7489 Base != BaseEnd; ++Base) { 7490 // We'll handle this below 7491 if (S.getLangOpts().CPlusPlus0x && Base->isVirtual()) 7492 continue; 7493 7494 assert(!Base->getType()->isDependentType() && 7495 "Cannot generate implicit members for class with dependent bases."); 7496 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl(); 7497 if (!S.LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0)) 7498 return false; 7499 } 7500 7501 // In C++11, the above citation has "or virtual" added 7502 if (S.getLangOpts().CPlusPlus0x) { 7503 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 7504 BaseEnd = ClassDecl->vbases_end(); 7505 Base != BaseEnd; ++Base) { 7506 assert(!Base->getType()->isDependentType() && 7507 "Cannot generate implicit members for class with dependent bases."); 7508 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl(); 7509 if (!S.LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, 7510 false, 0)) 7511 return false; 7512 } 7513 } 7514 7515 // -- for all the nonstatic data members of X that are of a class 7516 // type M (or array thereof), each such class type has a copy 7517 // assignment operator whose parameter is of type const M&, 7518 // const volatile M& or M. 7519 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 7520 FieldEnd = ClassDecl->field_end(); 7521 Field != FieldEnd; ++Field) { 7522 QualType FieldType = S.Context.getBaseElementType(Field->getType()); 7523 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) 7524 if (!S.LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const, 7525 false, 0)) 7526 return false; 7527 } 7528 7529 // Otherwise, the implicitly declared copy assignment operator will 7530 // have the form 7531 // 7532 // X& X::operator=(X&) 7533 7534 return true; 7535} 7536 7537Sema::ImplicitExceptionSpecification 7538Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) { 7539 CXXRecordDecl *ClassDecl = MD->getParent(); 7540 7541 ImplicitExceptionSpecification ExceptSpec(*this); 7542 if (ClassDecl->isInvalidDecl()) 7543 return ExceptSpec; 7544 7545 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 7546 assert(T->getNumArgs() == 1 && "not a copy assignment op"); 7547 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers(); 7548 7549 // C++ [except.spec]p14: 7550 // An implicitly declared special member function (Clause 12) shall have an 7551 // exception-specification. [...] 7552 7553 // It is unspecified whether or not an implicit copy assignment operator 7554 // attempts to deduplicate calls to assignment operators of virtual bases are 7555 // made. As such, this exception specification is effectively unspecified. 7556 // Based on a similar decision made for constness in C++0x, we're erring on 7557 // the side of assuming such calls to be made regardless of whether they 7558 // actually happen. 7559 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 7560 BaseEnd = ClassDecl->bases_end(); 7561 Base != BaseEnd; ++Base) { 7562 if (Base->isVirtual()) 7563 continue; 7564 7565 CXXRecordDecl *BaseClassDecl 7566 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 7567 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 7568 ArgQuals, false, 0)) 7569 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign); 7570 } 7571 7572 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 7573 BaseEnd = ClassDecl->vbases_end(); 7574 Base != BaseEnd; ++Base) { 7575 CXXRecordDecl *BaseClassDecl 7576 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 7577 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 7578 ArgQuals, false, 0)) 7579 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign); 7580 } 7581 7582 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 7583 FieldEnd = ClassDecl->field_end(); 7584 Field != FieldEnd; 7585 ++Field) { 7586 QualType FieldType = Context.getBaseElementType(Field->getType()); 7587 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 7588 if (CXXMethodDecl *CopyAssign = 7589 LookupCopyingAssignment(FieldClassDecl, 7590 ArgQuals | FieldType.getCVRQualifiers(), 7591 false, 0)) 7592 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign); 7593 } 7594 } 7595 7596 return ExceptSpec; 7597} 7598 7599CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 7600 // Note: The following rules are largely analoguous to the copy 7601 // constructor rules. Note that virtual bases are not taken into account 7602 // for determining the argument type of the operator. Note also that 7603 // operators taking an object instead of a reference are allowed. 7604 7605 QualType ArgType = Context.getTypeDeclType(ClassDecl); 7606 QualType RetType = Context.getLValueReferenceType(ArgType); 7607 if (isImplicitCopyAssignmentArgConst(*this, ClassDecl)) 7608 ArgType = ArgType.withConst(); 7609 ArgType = Context.getLValueReferenceType(ArgType); 7610 7611 // An implicitly-declared copy assignment operator is an inline public 7612 // member of its class. 7613 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 7614 SourceLocation ClassLoc = ClassDecl->getLocation(); 7615 DeclarationNameInfo NameInfo(Name, ClassLoc); 7616 CXXMethodDecl *CopyAssignment 7617 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 7618 /*TInfo=*/0, /*isStatic=*/false, 7619 /*StorageClassAsWritten=*/SC_None, 7620 /*isInline=*/true, /*isConstexpr=*/false, 7621 SourceLocation()); 7622 CopyAssignment->setAccess(AS_public); 7623 CopyAssignment->setDefaulted(); 7624 CopyAssignment->setImplicit(); 7625 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment()); 7626 7627 // Build an exception specification pointing back at this member. 7628 FunctionProtoType::ExtProtoInfo EPI; 7629 EPI.ExceptionSpecType = EST_Unevaluated; 7630 EPI.ExceptionSpecDecl = CopyAssignment; 7631 CopyAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI)); 7632 7633 // Add the parameter to the operator. 7634 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 7635 ClassLoc, ClassLoc, /*Id=*/0, 7636 ArgType, /*TInfo=*/0, 7637 SC_None, 7638 SC_None, 0); 7639 CopyAssignment->setParams(FromParam); 7640 7641 // Note that we have added this copy-assignment operator. 7642 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 7643 7644 if (Scope *S = getScopeForContext(ClassDecl)) 7645 PushOnScopeChains(CopyAssignment, S, false); 7646 ClassDecl->addDecl(CopyAssignment); 7647 7648 // C++0x [class.copy]p19: 7649 // .... If the class definition does not explicitly declare a copy 7650 // assignment operator, there is no user-declared move constructor, and 7651 // there is no user-declared move assignment operator, a copy assignment 7652 // operator is implicitly declared as defaulted. 7653 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 7654 CopyAssignment->setDeletedAsWritten(); 7655 7656 AddOverriddenMethods(ClassDecl, CopyAssignment); 7657 return CopyAssignment; 7658} 7659 7660void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 7661 CXXMethodDecl *CopyAssignOperator) { 7662 assert((CopyAssignOperator->isDefaulted() && 7663 CopyAssignOperator->isOverloadedOperator() && 7664 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 7665 !CopyAssignOperator->doesThisDeclarationHaveABody() && 7666 !CopyAssignOperator->isDeleted()) && 7667 "DefineImplicitCopyAssignment called for wrong function"); 7668 7669 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 7670 7671 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) { 7672 CopyAssignOperator->setInvalidDecl(); 7673 return; 7674 } 7675 7676 CopyAssignOperator->setUsed(); 7677 7678 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator); 7679 DiagnosticErrorTrap Trap(Diags); 7680 7681 // C++0x [class.copy]p30: 7682 // The implicitly-defined or explicitly-defaulted copy assignment operator 7683 // for a non-union class X performs memberwise copy assignment of its 7684 // subobjects. The direct base classes of X are assigned first, in the 7685 // order of their declaration in the base-specifier-list, and then the 7686 // immediate non-static data members of X are assigned, in the order in 7687 // which they were declared in the class definition. 7688 7689 // The statements that form the synthesized function body. 7690 SmallVector<Stmt*, 8> Statements; 7691 7692 // The parameter for the "other" object, which we are copying from. 7693 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 7694 Qualifiers OtherQuals = Other->getType().getQualifiers(); 7695 QualType OtherRefType = Other->getType(); 7696 if (const LValueReferenceType *OtherRef 7697 = OtherRefType->getAs<LValueReferenceType>()) { 7698 OtherRefType = OtherRef->getPointeeType(); 7699 OtherQuals = OtherRefType.getQualifiers(); 7700 } 7701 7702 // Our location for everything implicitly-generated. 7703 SourceLocation Loc = CopyAssignOperator->getLocation(); 7704 7705 // Construct a reference to the "other" object. We'll be using this 7706 // throughout the generated ASTs. 7707 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take(); 7708 assert(OtherRef && "Reference to parameter cannot fail!"); 7709 7710 // Construct the "this" pointer. We'll be using this throughout the generated 7711 // ASTs. 7712 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>(); 7713 assert(This && "Reference to this cannot fail!"); 7714 7715 // Assign base classes. 7716 bool Invalid = false; 7717 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 7718 E = ClassDecl->bases_end(); Base != E; ++Base) { 7719 // Form the assignment: 7720 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 7721 QualType BaseType = Base->getType().getUnqualifiedType(); 7722 if (!BaseType->isRecordType()) { 7723 Invalid = true; 7724 continue; 7725 } 7726 7727 CXXCastPath BasePath; 7728 BasePath.push_back(Base); 7729 7730 // Construct the "from" expression, which is an implicit cast to the 7731 // appropriately-qualified base type. 7732 Expr *From = OtherRef; 7733 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals), 7734 CK_UncheckedDerivedToBase, 7735 VK_LValue, &BasePath).take(); 7736 7737 // Dereference "this". 7738 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 7739 7740 // Implicitly cast "this" to the appropriately-qualified base type. 7741 To = ImpCastExprToType(To.take(), 7742 Context.getCVRQualifiedType(BaseType, 7743 CopyAssignOperator->getTypeQualifiers()), 7744 CK_UncheckedDerivedToBase, 7745 VK_LValue, &BasePath); 7746 7747 // Build the copy. 7748 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType, 7749 To.get(), From, 7750 /*CopyingBaseSubobject=*/true, 7751 /*Copying=*/true); 7752 if (Copy.isInvalid()) { 7753 Diag(CurrentLocation, diag::note_member_synthesized_at) 7754 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 7755 CopyAssignOperator->setInvalidDecl(); 7756 return; 7757 } 7758 7759 // Success! Record the copy. 7760 Statements.push_back(Copy.takeAs<Expr>()); 7761 } 7762 7763 // \brief Reference to the __builtin_memcpy function. 7764 Expr *BuiltinMemCpyRef = 0; 7765 // \brief Reference to the __builtin_objc_memmove_collectable function. 7766 Expr *CollectableMemCpyRef = 0; 7767 7768 // Assign non-static members. 7769 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 7770 FieldEnd = ClassDecl->field_end(); 7771 Field != FieldEnd; ++Field) { 7772 if (Field->isUnnamedBitfield()) 7773 continue; 7774 7775 // Check for members of reference type; we can't copy those. 7776 if (Field->getType()->isReferenceType()) { 7777 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 7778 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 7779 Diag(Field->getLocation(), diag::note_declared_at); 7780 Diag(CurrentLocation, diag::note_member_synthesized_at) 7781 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 7782 Invalid = true; 7783 continue; 7784 } 7785 7786 // Check for members of const-qualified, non-class type. 7787 QualType BaseType = Context.getBaseElementType(Field->getType()); 7788 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 7789 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 7790 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 7791 Diag(Field->getLocation(), diag::note_declared_at); 7792 Diag(CurrentLocation, diag::note_member_synthesized_at) 7793 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 7794 Invalid = true; 7795 continue; 7796 } 7797 7798 // Suppress assigning zero-width bitfields. 7799 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 7800 continue; 7801 7802 QualType FieldType = Field->getType().getNonReferenceType(); 7803 if (FieldType->isIncompleteArrayType()) { 7804 assert(ClassDecl->hasFlexibleArrayMember() && 7805 "Incomplete array type is not valid"); 7806 continue; 7807 } 7808 7809 // Build references to the field in the object we're copying from and to. 7810 CXXScopeSpec SS; // Intentionally empty 7811 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 7812 LookupMemberName); 7813 MemberLookup.addDecl(*Field); 7814 MemberLookup.resolveKind(); 7815 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType, 7816 Loc, /*IsArrow=*/false, 7817 SS, SourceLocation(), 0, 7818 MemberLookup, 0); 7819 ExprResult To = BuildMemberReferenceExpr(This, This->getType(), 7820 Loc, /*IsArrow=*/true, 7821 SS, SourceLocation(), 0, 7822 MemberLookup, 0); 7823 assert(!From.isInvalid() && "Implicit field reference cannot fail"); 7824 assert(!To.isInvalid() && "Implicit field reference cannot fail"); 7825 7826 // If the field should be copied with __builtin_memcpy rather than via 7827 // explicit assignments, do so. This optimization only applies for arrays 7828 // of scalars and arrays of class type with trivial copy-assignment 7829 // operators. 7830 if (FieldType->isArrayType() && !FieldType.isVolatileQualified() 7831 && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) { 7832 // Compute the size of the memory buffer to be copied. 7833 QualType SizeType = Context.getSizeType(); 7834 llvm::APInt Size(Context.getTypeSize(SizeType), 7835 Context.getTypeSizeInChars(BaseType).getQuantity()); 7836 for (const ConstantArrayType *Array 7837 = Context.getAsConstantArrayType(FieldType); 7838 Array; 7839 Array = Context.getAsConstantArrayType(Array->getElementType())) { 7840 llvm::APInt ArraySize 7841 = Array->getSize().zextOrTrunc(Size.getBitWidth()); 7842 Size *= ArraySize; 7843 } 7844 7845 // Take the address of the field references for "from" and "to". 7846 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get()); 7847 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get()); 7848 7849 bool NeedsCollectableMemCpy = 7850 (BaseType->isRecordType() && 7851 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()); 7852 7853 if (NeedsCollectableMemCpy) { 7854 if (!CollectableMemCpyRef) { 7855 // Create a reference to the __builtin_objc_memmove_collectable function. 7856 LookupResult R(*this, 7857 &Context.Idents.get("__builtin_objc_memmove_collectable"), 7858 Loc, LookupOrdinaryName); 7859 LookupName(R, TUScope, true); 7860 7861 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>(); 7862 if (!CollectableMemCpy) { 7863 // Something went horribly wrong earlier, and we will have 7864 // complained about it. 7865 Invalid = true; 7866 continue; 7867 } 7868 7869 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy, 7870 Context.BuiltinFnTy, 7871 VK_RValue, Loc, 0).take(); 7872 assert(CollectableMemCpyRef && "Builtin reference cannot fail"); 7873 } 7874 } 7875 // Create a reference to the __builtin_memcpy builtin function. 7876 else if (!BuiltinMemCpyRef) { 7877 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc, 7878 LookupOrdinaryName); 7879 LookupName(R, TUScope, true); 7880 7881 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>(); 7882 if (!BuiltinMemCpy) { 7883 // Something went horribly wrong earlier, and we will have complained 7884 // about it. 7885 Invalid = true; 7886 continue; 7887 } 7888 7889 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy, 7890 Context.BuiltinFnTy, 7891 VK_RValue, Loc, 0).take(); 7892 assert(BuiltinMemCpyRef && "Builtin reference cannot fail"); 7893 } 7894 7895 SmallVector<Expr*, 8> CallArgs; 7896 CallArgs.push_back(To.takeAs<Expr>()); 7897 CallArgs.push_back(From.takeAs<Expr>()); 7898 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc)); 7899 ExprResult Call = ExprError(); 7900 if (NeedsCollectableMemCpy) 7901 Call = ActOnCallExpr(/*Scope=*/0, 7902 CollectableMemCpyRef, 7903 Loc, CallArgs, 7904 Loc); 7905 else 7906 Call = ActOnCallExpr(/*Scope=*/0, 7907 BuiltinMemCpyRef, 7908 Loc, CallArgs, 7909 Loc); 7910 7911 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 7912 Statements.push_back(Call.takeAs<Expr>()); 7913 continue; 7914 } 7915 7916 // Build the copy of this field. 7917 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType, 7918 To.get(), From.get(), 7919 /*CopyingBaseSubobject=*/false, 7920 /*Copying=*/true); 7921 if (Copy.isInvalid()) { 7922 Diag(CurrentLocation, diag::note_member_synthesized_at) 7923 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 7924 CopyAssignOperator->setInvalidDecl(); 7925 return; 7926 } 7927 7928 // Success! Record the copy. 7929 Statements.push_back(Copy.takeAs<Stmt>()); 7930 } 7931 7932 if (!Invalid) { 7933 // Add a "return *this;" 7934 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 7935 7936 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get()); 7937 if (Return.isInvalid()) 7938 Invalid = true; 7939 else { 7940 Statements.push_back(Return.takeAs<Stmt>()); 7941 7942 if (Trap.hasErrorOccurred()) { 7943 Diag(CurrentLocation, diag::note_member_synthesized_at) 7944 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 7945 Invalid = true; 7946 } 7947 } 7948 } 7949 7950 if (Invalid) { 7951 CopyAssignOperator->setInvalidDecl(); 7952 return; 7953 } 7954 7955 StmtResult Body; 7956 { 7957 CompoundScopeRAII CompoundScope(*this); 7958 Body = ActOnCompoundStmt(Loc, Loc, Statements, 7959 /*isStmtExpr=*/false); 7960 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 7961 } 7962 CopyAssignOperator->setBody(Body.takeAs<Stmt>()); 7963 7964 if (ASTMutationListener *L = getASTMutationListener()) { 7965 L->CompletedImplicitDefinition(CopyAssignOperator); 7966 } 7967} 7968 7969Sema::ImplicitExceptionSpecification 7970Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) { 7971 CXXRecordDecl *ClassDecl = MD->getParent(); 7972 7973 ImplicitExceptionSpecification ExceptSpec(*this); 7974 if (ClassDecl->isInvalidDecl()) 7975 return ExceptSpec; 7976 7977 // C++0x [except.spec]p14: 7978 // An implicitly declared special member function (Clause 12) shall have an 7979 // exception-specification. [...] 7980 7981 // It is unspecified whether or not an implicit move assignment operator 7982 // attempts to deduplicate calls to assignment operators of virtual bases are 7983 // made. As such, this exception specification is effectively unspecified. 7984 // Based on a similar decision made for constness in C++0x, we're erring on 7985 // the side of assuming such calls to be made regardless of whether they 7986 // actually happen. 7987 // Note that a move constructor is not implicitly declared when there are 7988 // virtual bases, but it can still be user-declared and explicitly defaulted. 7989 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 7990 BaseEnd = ClassDecl->bases_end(); 7991 Base != BaseEnd; ++Base) { 7992 if (Base->isVirtual()) 7993 continue; 7994 7995 CXXRecordDecl *BaseClassDecl 7996 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 7997 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 7998 0, false, 0)) 7999 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign); 8000 } 8001 8002 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 8003 BaseEnd = ClassDecl->vbases_end(); 8004 Base != BaseEnd; ++Base) { 8005 CXXRecordDecl *BaseClassDecl 8006 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8007 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 8008 0, false, 0)) 8009 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign); 8010 } 8011 8012 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8013 FieldEnd = ClassDecl->field_end(); 8014 Field != FieldEnd; 8015 ++Field) { 8016 QualType FieldType = Context.getBaseElementType(Field->getType()); 8017 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 8018 if (CXXMethodDecl *MoveAssign = 8019 LookupMovingAssignment(FieldClassDecl, 8020 FieldType.getCVRQualifiers(), 8021 false, 0)) 8022 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign); 8023 } 8024 } 8025 8026 return ExceptSpec; 8027} 8028 8029/// Determine whether the class type has any direct or indirect virtual base 8030/// classes which have a non-trivial move assignment operator. 8031static bool 8032hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) { 8033 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 8034 BaseEnd = ClassDecl->vbases_end(); 8035 Base != BaseEnd; ++Base) { 8036 CXXRecordDecl *BaseClass = 8037 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8038 8039 // Try to declare the move assignment. If it would be deleted, then the 8040 // class does not have a non-trivial move assignment. 8041 if (BaseClass->needsImplicitMoveAssignment()) 8042 S.DeclareImplicitMoveAssignment(BaseClass); 8043 8044 // If the class has both a trivial move assignment and a non-trivial move 8045 // assignment, hasTrivialMoveAssignment() is false. 8046 if (BaseClass->hasDeclaredMoveAssignment() && 8047 !BaseClass->hasTrivialMoveAssignment()) 8048 return true; 8049 } 8050 8051 return false; 8052} 8053 8054/// Determine whether the given type either has a move constructor or is 8055/// trivially copyable. 8056static bool 8057hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) { 8058 Type = S.Context.getBaseElementType(Type); 8059 8060 // FIXME: Technically, non-trivially-copyable non-class types, such as 8061 // reference types, are supposed to return false here, but that appears 8062 // to be a standard defect. 8063 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl(); 8064 if (!ClassDecl || !ClassDecl->getDefinition()) 8065 return true; 8066 8067 if (Type.isTriviallyCopyableType(S.Context)) 8068 return true; 8069 8070 if (IsConstructor) { 8071 if (ClassDecl->needsImplicitMoveConstructor()) 8072 S.DeclareImplicitMoveConstructor(ClassDecl); 8073 return ClassDecl->hasDeclaredMoveConstructor(); 8074 } 8075 8076 if (ClassDecl->needsImplicitMoveAssignment()) 8077 S.DeclareImplicitMoveAssignment(ClassDecl); 8078 return ClassDecl->hasDeclaredMoveAssignment(); 8079} 8080 8081/// Determine whether all non-static data members and direct or virtual bases 8082/// of class \p ClassDecl have either a move operation, or are trivially 8083/// copyable. 8084static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl, 8085 bool IsConstructor) { 8086 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 8087 BaseEnd = ClassDecl->bases_end(); 8088 Base != BaseEnd; ++Base) { 8089 if (Base->isVirtual()) 8090 continue; 8091 8092 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor)) 8093 return false; 8094 } 8095 8096 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 8097 BaseEnd = ClassDecl->vbases_end(); 8098 Base != BaseEnd; ++Base) { 8099 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor)) 8100 return false; 8101 } 8102 8103 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8104 FieldEnd = ClassDecl->field_end(); 8105 Field != FieldEnd; ++Field) { 8106 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor)) 8107 return false; 8108 } 8109 8110 return true; 8111} 8112 8113CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 8114 // C++11 [class.copy]p20: 8115 // If the definition of a class X does not explicitly declare a move 8116 // assignment operator, one will be implicitly declared as defaulted 8117 // if and only if: 8118 // 8119 // - [first 4 bullets] 8120 assert(ClassDecl->needsImplicitMoveAssignment()); 8121 8122 // [Checked after we build the declaration] 8123 // - the move assignment operator would not be implicitly defined as 8124 // deleted, 8125 8126 // [DR1402]: 8127 // - X has no direct or indirect virtual base class with a non-trivial 8128 // move assignment operator, and 8129 // - each of X's non-static data members and direct or virtual base classes 8130 // has a type that either has a move assignment operator or is trivially 8131 // copyable. 8132 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) || 8133 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) { 8134 ClassDecl->setFailedImplicitMoveAssignment(); 8135 return 0; 8136 } 8137 8138 // Note: The following rules are largely analoguous to the move 8139 // constructor rules. 8140 8141 QualType ArgType = Context.getTypeDeclType(ClassDecl); 8142 QualType RetType = Context.getLValueReferenceType(ArgType); 8143 ArgType = Context.getRValueReferenceType(ArgType); 8144 8145 // An implicitly-declared move assignment operator is an inline public 8146 // member of its class. 8147 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 8148 SourceLocation ClassLoc = ClassDecl->getLocation(); 8149 DeclarationNameInfo NameInfo(Name, ClassLoc); 8150 CXXMethodDecl *MoveAssignment 8151 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 8152 /*TInfo=*/0, /*isStatic=*/false, 8153 /*StorageClassAsWritten=*/SC_None, 8154 /*isInline=*/true, 8155 /*isConstexpr=*/false, 8156 SourceLocation()); 8157 MoveAssignment->setAccess(AS_public); 8158 MoveAssignment->setDefaulted(); 8159 MoveAssignment->setImplicit(); 8160 MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment()); 8161 8162 // Build an exception specification pointing back at this member. 8163 FunctionProtoType::ExtProtoInfo EPI; 8164 EPI.ExceptionSpecType = EST_Unevaluated; 8165 EPI.ExceptionSpecDecl = MoveAssignment; 8166 MoveAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI)); 8167 8168 // Add the parameter to the operator. 8169 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 8170 ClassLoc, ClassLoc, /*Id=*/0, 8171 ArgType, /*TInfo=*/0, 8172 SC_None, 8173 SC_None, 0); 8174 MoveAssignment->setParams(FromParam); 8175 8176 // Note that we have added this copy-assignment operator. 8177 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 8178 8179 // C++0x [class.copy]p9: 8180 // If the definition of a class X does not explicitly declare a move 8181 // assignment operator, one will be implicitly declared as defaulted if and 8182 // only if: 8183 // [...] 8184 // - the move assignment operator would not be implicitly defined as 8185 // deleted. 8186 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 8187 // Cache this result so that we don't try to generate this over and over 8188 // on every lookup, leaking memory and wasting time. 8189 ClassDecl->setFailedImplicitMoveAssignment(); 8190 return 0; 8191 } 8192 8193 if (Scope *S = getScopeForContext(ClassDecl)) 8194 PushOnScopeChains(MoveAssignment, S, false); 8195 ClassDecl->addDecl(MoveAssignment); 8196 8197 AddOverriddenMethods(ClassDecl, MoveAssignment); 8198 return MoveAssignment; 8199} 8200 8201void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 8202 CXXMethodDecl *MoveAssignOperator) { 8203 assert((MoveAssignOperator->isDefaulted() && 8204 MoveAssignOperator->isOverloadedOperator() && 8205 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 8206 !MoveAssignOperator->doesThisDeclarationHaveABody() && 8207 !MoveAssignOperator->isDeleted()) && 8208 "DefineImplicitMoveAssignment called for wrong function"); 8209 8210 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 8211 8212 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) { 8213 MoveAssignOperator->setInvalidDecl(); 8214 return; 8215 } 8216 8217 MoveAssignOperator->setUsed(); 8218 8219 ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator); 8220 DiagnosticErrorTrap Trap(Diags); 8221 8222 // C++0x [class.copy]p28: 8223 // The implicitly-defined or move assignment operator for a non-union class 8224 // X performs memberwise move assignment of its subobjects. The direct base 8225 // classes of X are assigned first, in the order of their declaration in the 8226 // base-specifier-list, and then the immediate non-static data members of X 8227 // are assigned, in the order in which they were declared in the class 8228 // definition. 8229 8230 // The statements that form the synthesized function body. 8231 SmallVector<Stmt*, 8> Statements; 8232 8233 // The parameter for the "other" object, which we are move from. 8234 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 8235 QualType OtherRefType = Other->getType()-> 8236 getAs<RValueReferenceType>()->getPointeeType(); 8237 assert(OtherRefType.getQualifiers() == 0 && 8238 "Bad argument type of defaulted move assignment"); 8239 8240 // Our location for everything implicitly-generated. 8241 SourceLocation Loc = MoveAssignOperator->getLocation(); 8242 8243 // Construct a reference to the "other" object. We'll be using this 8244 // throughout the generated ASTs. 8245 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take(); 8246 assert(OtherRef && "Reference to parameter cannot fail!"); 8247 // Cast to rvalue. 8248 OtherRef = CastForMoving(*this, OtherRef); 8249 8250 // Construct the "this" pointer. We'll be using this throughout the generated 8251 // ASTs. 8252 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>(); 8253 assert(This && "Reference to this cannot fail!"); 8254 8255 // Assign base classes. 8256 bool Invalid = false; 8257 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 8258 E = ClassDecl->bases_end(); Base != E; ++Base) { 8259 // Form the assignment: 8260 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 8261 QualType BaseType = Base->getType().getUnqualifiedType(); 8262 if (!BaseType->isRecordType()) { 8263 Invalid = true; 8264 continue; 8265 } 8266 8267 CXXCastPath BasePath; 8268 BasePath.push_back(Base); 8269 8270 // Construct the "from" expression, which is an implicit cast to the 8271 // appropriately-qualified base type. 8272 Expr *From = OtherRef; 8273 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase, 8274 VK_XValue, &BasePath).take(); 8275 8276 // Dereference "this". 8277 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 8278 8279 // Implicitly cast "this" to the appropriately-qualified base type. 8280 To = ImpCastExprToType(To.take(), 8281 Context.getCVRQualifiedType(BaseType, 8282 MoveAssignOperator->getTypeQualifiers()), 8283 CK_UncheckedDerivedToBase, 8284 VK_LValue, &BasePath); 8285 8286 // Build the move. 8287 StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType, 8288 To.get(), From, 8289 /*CopyingBaseSubobject=*/true, 8290 /*Copying=*/false); 8291 if (Move.isInvalid()) { 8292 Diag(CurrentLocation, diag::note_member_synthesized_at) 8293 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 8294 MoveAssignOperator->setInvalidDecl(); 8295 return; 8296 } 8297 8298 // Success! Record the move. 8299 Statements.push_back(Move.takeAs<Expr>()); 8300 } 8301 8302 // \brief Reference to the __builtin_memcpy function. 8303 Expr *BuiltinMemCpyRef = 0; 8304 // \brief Reference to the __builtin_objc_memmove_collectable function. 8305 Expr *CollectableMemCpyRef = 0; 8306 8307 // Assign non-static members. 8308 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8309 FieldEnd = ClassDecl->field_end(); 8310 Field != FieldEnd; ++Field) { 8311 if (Field->isUnnamedBitfield()) 8312 continue; 8313 8314 // Check for members of reference type; we can't move those. 8315 if (Field->getType()->isReferenceType()) { 8316 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 8317 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 8318 Diag(Field->getLocation(), diag::note_declared_at); 8319 Diag(CurrentLocation, diag::note_member_synthesized_at) 8320 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 8321 Invalid = true; 8322 continue; 8323 } 8324 8325 // Check for members of const-qualified, non-class type. 8326 QualType BaseType = Context.getBaseElementType(Field->getType()); 8327 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 8328 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 8329 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 8330 Diag(Field->getLocation(), diag::note_declared_at); 8331 Diag(CurrentLocation, diag::note_member_synthesized_at) 8332 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 8333 Invalid = true; 8334 continue; 8335 } 8336 8337 // Suppress assigning zero-width bitfields. 8338 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 8339 continue; 8340 8341 QualType FieldType = Field->getType().getNonReferenceType(); 8342 if (FieldType->isIncompleteArrayType()) { 8343 assert(ClassDecl->hasFlexibleArrayMember() && 8344 "Incomplete array type is not valid"); 8345 continue; 8346 } 8347 8348 // Build references to the field in the object we're copying from and to. 8349 CXXScopeSpec SS; // Intentionally empty 8350 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 8351 LookupMemberName); 8352 MemberLookup.addDecl(*Field); 8353 MemberLookup.resolveKind(); 8354 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType, 8355 Loc, /*IsArrow=*/false, 8356 SS, SourceLocation(), 0, 8357 MemberLookup, 0); 8358 ExprResult To = BuildMemberReferenceExpr(This, This->getType(), 8359 Loc, /*IsArrow=*/true, 8360 SS, SourceLocation(), 0, 8361 MemberLookup, 0); 8362 assert(!From.isInvalid() && "Implicit field reference cannot fail"); 8363 assert(!To.isInvalid() && "Implicit field reference cannot fail"); 8364 8365 assert(!From.get()->isLValue() && // could be xvalue or prvalue 8366 "Member reference with rvalue base must be rvalue except for reference " 8367 "members, which aren't allowed for move assignment."); 8368 8369 // If the field should be copied with __builtin_memcpy rather than via 8370 // explicit assignments, do so. This optimization only applies for arrays 8371 // of scalars and arrays of class type with trivial move-assignment 8372 // operators. 8373 if (FieldType->isArrayType() && !FieldType.isVolatileQualified() 8374 && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) { 8375 // Compute the size of the memory buffer to be copied. 8376 QualType SizeType = Context.getSizeType(); 8377 llvm::APInt Size(Context.getTypeSize(SizeType), 8378 Context.getTypeSizeInChars(BaseType).getQuantity()); 8379 for (const ConstantArrayType *Array 8380 = Context.getAsConstantArrayType(FieldType); 8381 Array; 8382 Array = Context.getAsConstantArrayType(Array->getElementType())) { 8383 llvm::APInt ArraySize 8384 = Array->getSize().zextOrTrunc(Size.getBitWidth()); 8385 Size *= ArraySize; 8386 } 8387 8388 // Take the address of the field references for "from" and "to". We 8389 // directly construct UnaryOperators here because semantic analysis 8390 // does not permit us to take the address of an xvalue. 8391 From = new (Context) UnaryOperator(From.get(), UO_AddrOf, 8392 Context.getPointerType(From.get()->getType()), 8393 VK_RValue, OK_Ordinary, Loc); 8394 To = new (Context) UnaryOperator(To.get(), UO_AddrOf, 8395 Context.getPointerType(To.get()->getType()), 8396 VK_RValue, OK_Ordinary, Loc); 8397 8398 bool NeedsCollectableMemCpy = 8399 (BaseType->isRecordType() && 8400 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()); 8401 8402 if (NeedsCollectableMemCpy) { 8403 if (!CollectableMemCpyRef) { 8404 // Create a reference to the __builtin_objc_memmove_collectable function. 8405 LookupResult R(*this, 8406 &Context.Idents.get("__builtin_objc_memmove_collectable"), 8407 Loc, LookupOrdinaryName); 8408 LookupName(R, TUScope, true); 8409 8410 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>(); 8411 if (!CollectableMemCpy) { 8412 // Something went horribly wrong earlier, and we will have 8413 // complained about it. 8414 Invalid = true; 8415 continue; 8416 } 8417 8418 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy, 8419 Context.BuiltinFnTy, 8420 VK_RValue, Loc, 0).take(); 8421 assert(CollectableMemCpyRef && "Builtin reference cannot fail"); 8422 } 8423 } 8424 // Create a reference to the __builtin_memcpy builtin function. 8425 else if (!BuiltinMemCpyRef) { 8426 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc, 8427 LookupOrdinaryName); 8428 LookupName(R, TUScope, true); 8429 8430 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>(); 8431 if (!BuiltinMemCpy) { 8432 // Something went horribly wrong earlier, and we will have complained 8433 // about it. 8434 Invalid = true; 8435 continue; 8436 } 8437 8438 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy, 8439 Context.BuiltinFnTy, 8440 VK_RValue, Loc, 0).take(); 8441 assert(BuiltinMemCpyRef && "Builtin reference cannot fail"); 8442 } 8443 8444 SmallVector<Expr*, 8> CallArgs; 8445 CallArgs.push_back(To.takeAs<Expr>()); 8446 CallArgs.push_back(From.takeAs<Expr>()); 8447 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc)); 8448 ExprResult Call = ExprError(); 8449 if (NeedsCollectableMemCpy) 8450 Call = ActOnCallExpr(/*Scope=*/0, 8451 CollectableMemCpyRef, 8452 Loc, CallArgs, 8453 Loc); 8454 else 8455 Call = ActOnCallExpr(/*Scope=*/0, 8456 BuiltinMemCpyRef, 8457 Loc, CallArgs, 8458 Loc); 8459 8460 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 8461 Statements.push_back(Call.takeAs<Expr>()); 8462 continue; 8463 } 8464 8465 // Build the move of this field. 8466 StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType, 8467 To.get(), From.get(), 8468 /*CopyingBaseSubobject=*/false, 8469 /*Copying=*/false); 8470 if (Move.isInvalid()) { 8471 Diag(CurrentLocation, diag::note_member_synthesized_at) 8472 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 8473 MoveAssignOperator->setInvalidDecl(); 8474 return; 8475 } 8476 8477 // Success! Record the copy. 8478 Statements.push_back(Move.takeAs<Stmt>()); 8479 } 8480 8481 if (!Invalid) { 8482 // Add a "return *this;" 8483 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 8484 8485 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get()); 8486 if (Return.isInvalid()) 8487 Invalid = true; 8488 else { 8489 Statements.push_back(Return.takeAs<Stmt>()); 8490 8491 if (Trap.hasErrorOccurred()) { 8492 Diag(CurrentLocation, diag::note_member_synthesized_at) 8493 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 8494 Invalid = true; 8495 } 8496 } 8497 } 8498 8499 if (Invalid) { 8500 MoveAssignOperator->setInvalidDecl(); 8501 return; 8502 } 8503 8504 StmtResult Body; 8505 { 8506 CompoundScopeRAII CompoundScope(*this); 8507 Body = ActOnCompoundStmt(Loc, Loc, Statements, 8508 /*isStmtExpr=*/false); 8509 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 8510 } 8511 MoveAssignOperator->setBody(Body.takeAs<Stmt>()); 8512 8513 if (ASTMutationListener *L = getASTMutationListener()) { 8514 L->CompletedImplicitDefinition(MoveAssignOperator); 8515 } 8516} 8517 8518/// Determine whether an implicit copy constructor for ClassDecl has a const 8519/// argument. 8520/// FIXME: It ought to be possible to store this on the record. 8521static bool isImplicitCopyCtorArgConst(Sema &S, CXXRecordDecl *ClassDecl) { 8522 if (ClassDecl->isInvalidDecl()) 8523 return true; 8524 8525 // C++ [class.copy]p5: 8526 // The implicitly-declared copy constructor for a class X will 8527 // have the form 8528 // 8529 // X::X(const X&) 8530 // 8531 // if 8532 // -- each direct or virtual base class B of X has a copy 8533 // constructor whose first parameter is of type const B& or 8534 // const volatile B&, and 8535 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 8536 BaseEnd = ClassDecl->bases_end(); 8537 Base != BaseEnd; ++Base) { 8538 // Virtual bases are handled below. 8539 if (Base->isVirtual()) 8540 continue; 8541 8542 CXXRecordDecl *BaseClassDecl 8543 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8544 // FIXME: This lookup is wrong. If the copy ctor for a member or base is 8545 // ambiguous, we should still produce a constructor with a const-qualified 8546 // parameter. 8547 if (!S.LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const)) 8548 return false; 8549 } 8550 8551 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 8552 BaseEnd = ClassDecl->vbases_end(); 8553 Base != BaseEnd; ++Base) { 8554 CXXRecordDecl *BaseClassDecl 8555 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8556 if (!S.LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const)) 8557 return false; 8558 } 8559 8560 // -- for all the nonstatic data members of X that are of a 8561 // class type M (or array thereof), each such class type 8562 // has a copy constructor whose first parameter is of type 8563 // const M& or const volatile M&. 8564 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8565 FieldEnd = ClassDecl->field_end(); 8566 Field != FieldEnd; ++Field) { 8567 QualType FieldType = S.Context.getBaseElementType(Field->getType()); 8568 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 8569 if (!S.LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const)) 8570 return false; 8571 } 8572 } 8573 8574 // Otherwise, the implicitly declared copy constructor will have 8575 // the form 8576 // 8577 // X::X(X&) 8578 8579 return true; 8580} 8581 8582Sema::ImplicitExceptionSpecification 8583Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) { 8584 CXXRecordDecl *ClassDecl = MD->getParent(); 8585 8586 ImplicitExceptionSpecification ExceptSpec(*this); 8587 if (ClassDecl->isInvalidDecl()) 8588 return ExceptSpec; 8589 8590 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 8591 assert(T->getNumArgs() >= 1 && "not a copy ctor"); 8592 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers(); 8593 8594 // C++ [except.spec]p14: 8595 // An implicitly declared special member function (Clause 12) shall have an 8596 // exception-specification. [...] 8597 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 8598 BaseEnd = ClassDecl->bases_end(); 8599 Base != BaseEnd; 8600 ++Base) { 8601 // Virtual bases are handled below. 8602 if (Base->isVirtual()) 8603 continue; 8604 8605 CXXRecordDecl *BaseClassDecl 8606 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8607 if (CXXConstructorDecl *CopyConstructor = 8608 LookupCopyingConstructor(BaseClassDecl, Quals)) 8609 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor); 8610 } 8611 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 8612 BaseEnd = ClassDecl->vbases_end(); 8613 Base != BaseEnd; 8614 ++Base) { 8615 CXXRecordDecl *BaseClassDecl 8616 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8617 if (CXXConstructorDecl *CopyConstructor = 8618 LookupCopyingConstructor(BaseClassDecl, Quals)) 8619 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor); 8620 } 8621 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8622 FieldEnd = ClassDecl->field_end(); 8623 Field != FieldEnd; 8624 ++Field) { 8625 QualType FieldType = Context.getBaseElementType(Field->getType()); 8626 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 8627 if (CXXConstructorDecl *CopyConstructor = 8628 LookupCopyingConstructor(FieldClassDecl, 8629 Quals | FieldType.getCVRQualifiers())) 8630 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor); 8631 } 8632 } 8633 8634 return ExceptSpec; 8635} 8636 8637CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 8638 CXXRecordDecl *ClassDecl) { 8639 // C++ [class.copy]p4: 8640 // If the class definition does not explicitly declare a copy 8641 // constructor, one is declared implicitly. 8642 8643 QualType ClassType = Context.getTypeDeclType(ClassDecl); 8644 QualType ArgType = ClassType; 8645 bool Const = isImplicitCopyCtorArgConst(*this, ClassDecl); 8646 if (Const) 8647 ArgType = ArgType.withConst(); 8648 ArgType = Context.getLValueReferenceType(ArgType); 8649 8650 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 8651 CXXCopyConstructor, 8652 Const); 8653 8654 DeclarationName Name 8655 = Context.DeclarationNames.getCXXConstructorName( 8656 Context.getCanonicalType(ClassType)); 8657 SourceLocation ClassLoc = ClassDecl->getLocation(); 8658 DeclarationNameInfo NameInfo(Name, ClassLoc); 8659 8660 // An implicitly-declared copy constructor is an inline public 8661 // member of its class. 8662 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 8663 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0, 8664 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 8665 Constexpr); 8666 CopyConstructor->setAccess(AS_public); 8667 CopyConstructor->setDefaulted(); 8668 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor()); 8669 8670 // Build an exception specification pointing back at this member. 8671 FunctionProtoType::ExtProtoInfo EPI; 8672 EPI.ExceptionSpecType = EST_Unevaluated; 8673 EPI.ExceptionSpecDecl = CopyConstructor; 8674 CopyConstructor->setType( 8675 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI)); 8676 8677 // Note that we have declared this constructor. 8678 ++ASTContext::NumImplicitCopyConstructorsDeclared; 8679 8680 // Add the parameter to the constructor. 8681 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 8682 ClassLoc, ClassLoc, 8683 /*IdentifierInfo=*/0, 8684 ArgType, /*TInfo=*/0, 8685 SC_None, 8686 SC_None, 0); 8687 CopyConstructor->setParams(FromParam); 8688 8689 if (Scope *S = getScopeForContext(ClassDecl)) 8690 PushOnScopeChains(CopyConstructor, S, false); 8691 ClassDecl->addDecl(CopyConstructor); 8692 8693 // C++11 [class.copy]p8: 8694 // ... If the class definition does not explicitly declare a copy 8695 // constructor, there is no user-declared move constructor, and there is no 8696 // user-declared move assignment operator, a copy constructor is implicitly 8697 // declared as defaulted. 8698 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) 8699 CopyConstructor->setDeletedAsWritten(); 8700 8701 return CopyConstructor; 8702} 8703 8704void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 8705 CXXConstructorDecl *CopyConstructor) { 8706 assert((CopyConstructor->isDefaulted() && 8707 CopyConstructor->isCopyConstructor() && 8708 !CopyConstructor->doesThisDeclarationHaveABody() && 8709 !CopyConstructor->isDeleted()) && 8710 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 8711 8712 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 8713 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 8714 8715 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor); 8716 DiagnosticErrorTrap Trap(Diags); 8717 8718 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) || 8719 Trap.hasErrorOccurred()) { 8720 Diag(CurrentLocation, diag::note_member_synthesized_at) 8721 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl); 8722 CopyConstructor->setInvalidDecl(); 8723 } else { 8724 Sema::CompoundScopeRAII CompoundScope(*this); 8725 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(), 8726 CopyConstructor->getLocation(), 8727 MultiStmtArg(), 8728 /*isStmtExpr=*/false) 8729 .takeAs<Stmt>()); 8730 CopyConstructor->setImplicitlyDefined(true); 8731 } 8732 8733 CopyConstructor->setUsed(); 8734 if (ASTMutationListener *L = getASTMutationListener()) { 8735 L->CompletedImplicitDefinition(CopyConstructor); 8736 } 8737} 8738 8739Sema::ImplicitExceptionSpecification 8740Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) { 8741 CXXRecordDecl *ClassDecl = MD->getParent(); 8742 8743 // C++ [except.spec]p14: 8744 // An implicitly declared special member function (Clause 12) shall have an 8745 // exception-specification. [...] 8746 ImplicitExceptionSpecification ExceptSpec(*this); 8747 if (ClassDecl->isInvalidDecl()) 8748 return ExceptSpec; 8749 8750 // Direct base-class constructors. 8751 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 8752 BEnd = ClassDecl->bases_end(); 8753 B != BEnd; ++B) { 8754 if (B->isVirtual()) // Handled below. 8755 continue; 8756 8757 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 8758 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8759 CXXConstructorDecl *Constructor = 8760 LookupMovingConstructor(BaseClassDecl, 0); 8761 // If this is a deleted function, add it anyway. This might be conformant 8762 // with the standard. This might not. I'm not sure. It might not matter. 8763 if (Constructor) 8764 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 8765 } 8766 } 8767 8768 // Virtual base-class constructors. 8769 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 8770 BEnd = ClassDecl->vbases_end(); 8771 B != BEnd; ++B) { 8772 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 8773 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8774 CXXConstructorDecl *Constructor = 8775 LookupMovingConstructor(BaseClassDecl, 0); 8776 // If this is a deleted function, add it anyway. This might be conformant 8777 // with the standard. This might not. I'm not sure. It might not matter. 8778 if (Constructor) 8779 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 8780 } 8781 } 8782 8783 // Field constructors. 8784 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 8785 FEnd = ClassDecl->field_end(); 8786 F != FEnd; ++F) { 8787 QualType FieldType = Context.getBaseElementType(F->getType()); 8788 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) { 8789 CXXConstructorDecl *Constructor = 8790 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers()); 8791 // If this is a deleted function, add it anyway. This might be conformant 8792 // with the standard. This might not. I'm not sure. It might not matter. 8793 // In particular, the problem is that this function never gets called. It 8794 // might just be ill-formed because this function attempts to refer to 8795 // a deleted function here. 8796 if (Constructor) 8797 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 8798 } 8799 } 8800 8801 return ExceptSpec; 8802} 8803 8804CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 8805 CXXRecordDecl *ClassDecl) { 8806 // C++11 [class.copy]p9: 8807 // If the definition of a class X does not explicitly declare a move 8808 // constructor, one will be implicitly declared as defaulted if and only if: 8809 // 8810 // - [first 4 bullets] 8811 assert(ClassDecl->needsImplicitMoveConstructor()); 8812 8813 // [Checked after we build the declaration] 8814 // - the move assignment operator would not be implicitly defined as 8815 // deleted, 8816 8817 // [DR1402]: 8818 // - each of X's non-static data members and direct or virtual base classes 8819 // has a type that either has a move constructor or is trivially copyable. 8820 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) { 8821 ClassDecl->setFailedImplicitMoveConstructor(); 8822 return 0; 8823 } 8824 8825 QualType ClassType = Context.getTypeDeclType(ClassDecl); 8826 QualType ArgType = Context.getRValueReferenceType(ClassType); 8827 8828 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 8829 CXXMoveConstructor, 8830 false); 8831 8832 DeclarationName Name 8833 = Context.DeclarationNames.getCXXConstructorName( 8834 Context.getCanonicalType(ClassType)); 8835 SourceLocation ClassLoc = ClassDecl->getLocation(); 8836 DeclarationNameInfo NameInfo(Name, ClassLoc); 8837 8838 // C++0x [class.copy]p11: 8839 // An implicitly-declared copy/move constructor is an inline public 8840 // member of its class. 8841 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 8842 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0, 8843 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 8844 Constexpr); 8845 MoveConstructor->setAccess(AS_public); 8846 MoveConstructor->setDefaulted(); 8847 MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor()); 8848 8849 // Build an exception specification pointing back at this member. 8850 FunctionProtoType::ExtProtoInfo EPI; 8851 EPI.ExceptionSpecType = EST_Unevaluated; 8852 EPI.ExceptionSpecDecl = MoveConstructor; 8853 MoveConstructor->setType( 8854 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI)); 8855 8856 // Add the parameter to the constructor. 8857 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 8858 ClassLoc, ClassLoc, 8859 /*IdentifierInfo=*/0, 8860 ArgType, /*TInfo=*/0, 8861 SC_None, 8862 SC_None, 0); 8863 MoveConstructor->setParams(FromParam); 8864 8865 // C++0x [class.copy]p9: 8866 // If the definition of a class X does not explicitly declare a move 8867 // constructor, one will be implicitly declared as defaulted if and only if: 8868 // [...] 8869 // - the move constructor would not be implicitly defined as deleted. 8870 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 8871 // Cache this result so that we don't try to generate this over and over 8872 // on every lookup, leaking memory and wasting time. 8873 ClassDecl->setFailedImplicitMoveConstructor(); 8874 return 0; 8875 } 8876 8877 // Note that we have declared this constructor. 8878 ++ASTContext::NumImplicitMoveConstructorsDeclared; 8879 8880 if (Scope *S = getScopeForContext(ClassDecl)) 8881 PushOnScopeChains(MoveConstructor, S, false); 8882 ClassDecl->addDecl(MoveConstructor); 8883 8884 return MoveConstructor; 8885} 8886 8887void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 8888 CXXConstructorDecl *MoveConstructor) { 8889 assert((MoveConstructor->isDefaulted() && 8890 MoveConstructor->isMoveConstructor() && 8891 !MoveConstructor->doesThisDeclarationHaveABody() && 8892 !MoveConstructor->isDeleted()) && 8893 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 8894 8895 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 8896 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 8897 8898 ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor); 8899 DiagnosticErrorTrap Trap(Diags); 8900 8901 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) || 8902 Trap.hasErrorOccurred()) { 8903 Diag(CurrentLocation, diag::note_member_synthesized_at) 8904 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl); 8905 MoveConstructor->setInvalidDecl(); 8906 } else { 8907 Sema::CompoundScopeRAII CompoundScope(*this); 8908 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(), 8909 MoveConstructor->getLocation(), 8910 MultiStmtArg(), 8911 /*isStmtExpr=*/false) 8912 .takeAs<Stmt>()); 8913 MoveConstructor->setImplicitlyDefined(true); 8914 } 8915 8916 MoveConstructor->setUsed(); 8917 8918 if (ASTMutationListener *L = getASTMutationListener()) { 8919 L->CompletedImplicitDefinition(MoveConstructor); 8920 } 8921} 8922 8923bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 8924 return FD->isDeleted() && 8925 (FD->isDefaulted() || FD->isImplicit()) && 8926 isa<CXXMethodDecl>(FD); 8927} 8928 8929/// \brief Mark the call operator of the given lambda closure type as "used". 8930static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) { 8931 CXXMethodDecl *CallOperator 8932 = cast<CXXMethodDecl>( 8933 *Lambda->lookup( 8934 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).first); 8935 CallOperator->setReferenced(); 8936 CallOperator->setUsed(); 8937} 8938 8939void Sema::DefineImplicitLambdaToFunctionPointerConversion( 8940 SourceLocation CurrentLocation, 8941 CXXConversionDecl *Conv) 8942{ 8943 CXXRecordDecl *Lambda = Conv->getParent(); 8944 8945 // Make sure that the lambda call operator is marked used. 8946 markLambdaCallOperatorUsed(*this, Lambda); 8947 8948 Conv->setUsed(); 8949 8950 ImplicitlyDefinedFunctionScope Scope(*this, Conv); 8951 DiagnosticErrorTrap Trap(Diags); 8952 8953 // Return the address of the __invoke function. 8954 DeclarationName InvokeName = &Context.Idents.get("__invoke"); 8955 CXXMethodDecl *Invoke 8956 = cast<CXXMethodDecl>(*Lambda->lookup(InvokeName).first); 8957 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(), 8958 VK_LValue, Conv->getLocation()).take(); 8959 assert(FunctionRef && "Can't refer to __invoke function?"); 8960 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take(); 8961 Conv->setBody(new (Context) CompoundStmt(Context, &Return, 1, 8962 Conv->getLocation(), 8963 Conv->getLocation())); 8964 8965 // Fill in the __invoke function with a dummy implementation. IR generation 8966 // will fill in the actual details. 8967 Invoke->setUsed(); 8968 Invoke->setReferenced(); 8969 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation())); 8970 8971 if (ASTMutationListener *L = getASTMutationListener()) { 8972 L->CompletedImplicitDefinition(Conv); 8973 L->CompletedImplicitDefinition(Invoke); 8974 } 8975} 8976 8977void Sema::DefineImplicitLambdaToBlockPointerConversion( 8978 SourceLocation CurrentLocation, 8979 CXXConversionDecl *Conv) 8980{ 8981 Conv->setUsed(); 8982 8983 ImplicitlyDefinedFunctionScope Scope(*this, Conv); 8984 DiagnosticErrorTrap Trap(Diags); 8985 8986 // Copy-initialize the lambda object as needed to capture it. 8987 Expr *This = ActOnCXXThis(CurrentLocation).take(); 8988 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take(); 8989 8990 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 8991 Conv->getLocation(), 8992 Conv, DerefThis); 8993 8994 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 8995 // behavior. Note that only the general conversion function does this 8996 // (since it's unusable otherwise); in the case where we inline the 8997 // block literal, it has block literal lifetime semantics. 8998 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 8999 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 9000 CK_CopyAndAutoreleaseBlockObject, 9001 BuildBlock.get(), 0, VK_RValue); 9002 9003 if (BuildBlock.isInvalid()) { 9004 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 9005 Conv->setInvalidDecl(); 9006 return; 9007 } 9008 9009 // Create the return statement that returns the block from the conversion 9010 // function. 9011 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get()); 9012 if (Return.isInvalid()) { 9013 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 9014 Conv->setInvalidDecl(); 9015 return; 9016 } 9017 9018 // Set the body of the conversion function. 9019 Stmt *ReturnS = Return.take(); 9020 Conv->setBody(new (Context) CompoundStmt(Context, &ReturnS, 1, 9021 Conv->getLocation(), 9022 Conv->getLocation())); 9023 9024 // We're done; notify the mutation listener, if any. 9025 if (ASTMutationListener *L = getASTMutationListener()) { 9026 L->CompletedImplicitDefinition(Conv); 9027 } 9028} 9029 9030/// \brief Determine whether the given list arguments contains exactly one 9031/// "real" (non-default) argument. 9032static bool hasOneRealArgument(MultiExprArg Args) { 9033 switch (Args.size()) { 9034 case 0: 9035 return false; 9036 9037 default: 9038 if (!Args[1]->isDefaultArgument()) 9039 return false; 9040 9041 // fall through 9042 case 1: 9043 return !Args[0]->isDefaultArgument(); 9044 } 9045 9046 return false; 9047} 9048 9049ExprResult 9050Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 9051 CXXConstructorDecl *Constructor, 9052 MultiExprArg ExprArgs, 9053 bool HadMultipleCandidates, 9054 bool RequiresZeroInit, 9055 unsigned ConstructKind, 9056 SourceRange ParenRange) { 9057 bool Elidable = false; 9058 9059 // C++0x [class.copy]p34: 9060 // When certain criteria are met, an implementation is allowed to 9061 // omit the copy/move construction of a class object, even if the 9062 // copy/move constructor and/or destructor for the object have 9063 // side effects. [...] 9064 // - when a temporary class object that has not been bound to a 9065 // reference (12.2) would be copied/moved to a class object 9066 // with the same cv-unqualified type, the copy/move operation 9067 // can be omitted by constructing the temporary object 9068 // directly into the target of the omitted copy/move 9069 if (ConstructKind == CXXConstructExpr::CK_Complete && 9070 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 9071 Expr *SubExpr = ExprArgs[0]; 9072 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent()); 9073 } 9074 9075 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 9076 Elidable, ExprArgs, HadMultipleCandidates, 9077 RequiresZeroInit, ConstructKind, ParenRange); 9078} 9079 9080/// BuildCXXConstructExpr - Creates a complete call to a constructor, 9081/// including handling of its default argument expressions. 9082ExprResult 9083Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 9084 CXXConstructorDecl *Constructor, bool Elidable, 9085 MultiExprArg ExprArgs, 9086 bool HadMultipleCandidates, 9087 bool RequiresZeroInit, 9088 unsigned ConstructKind, 9089 SourceRange ParenRange) { 9090 MarkFunctionReferenced(ConstructLoc, Constructor); 9091 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc, 9092 Constructor, Elidable, ExprArgs, 9093 HadMultipleCandidates, /*FIXME*/false, 9094 RequiresZeroInit, 9095 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 9096 ParenRange)); 9097} 9098 9099bool Sema::InitializeVarWithConstructor(VarDecl *VD, 9100 CXXConstructorDecl *Constructor, 9101 MultiExprArg Exprs, 9102 bool HadMultipleCandidates) { 9103 // FIXME: Provide the correct paren SourceRange when available. 9104 ExprResult TempResult = 9105 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor, 9106 Exprs, HadMultipleCandidates, false, 9107 CXXConstructExpr::CK_Complete, SourceRange()); 9108 if (TempResult.isInvalid()) 9109 return true; 9110 9111 Expr *Temp = TempResult.takeAs<Expr>(); 9112 CheckImplicitConversions(Temp, VD->getLocation()); 9113 MarkFunctionReferenced(VD->getLocation(), Constructor); 9114 Temp = MaybeCreateExprWithCleanups(Temp); 9115 VD->setInit(Temp); 9116 9117 return false; 9118} 9119 9120void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 9121 if (VD->isInvalidDecl()) return; 9122 9123 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 9124 if (ClassDecl->isInvalidDecl()) return; 9125 if (ClassDecl->hasIrrelevantDestructor()) return; 9126 if (ClassDecl->isDependentContext()) return; 9127 9128 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 9129 MarkFunctionReferenced(VD->getLocation(), Destructor); 9130 CheckDestructorAccess(VD->getLocation(), Destructor, 9131 PDiag(diag::err_access_dtor_var) 9132 << VD->getDeclName() 9133 << VD->getType()); 9134 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 9135 9136 if (!VD->hasGlobalStorage()) return; 9137 9138 // Emit warning for non-trivial dtor in global scope (a real global, 9139 // class-static, function-static). 9140 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 9141 9142 // TODO: this should be re-enabled for static locals by !CXAAtExit 9143 if (!VD->isStaticLocal()) 9144 Diag(VD->getLocation(), diag::warn_global_destructor); 9145} 9146 9147/// \brief Given a constructor and the set of arguments provided for the 9148/// constructor, convert the arguments and add any required default arguments 9149/// to form a proper call to this constructor. 9150/// 9151/// \returns true if an error occurred, false otherwise. 9152bool 9153Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 9154 MultiExprArg ArgsPtr, 9155 SourceLocation Loc, 9156 SmallVectorImpl<Expr*> &ConvertedArgs, 9157 bool AllowExplicit) { 9158 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 9159 unsigned NumArgs = ArgsPtr.size(); 9160 Expr **Args = ArgsPtr.data(); 9161 9162 const FunctionProtoType *Proto 9163 = Constructor->getType()->getAs<FunctionProtoType>(); 9164 assert(Proto && "Constructor without a prototype?"); 9165 unsigned NumArgsInProto = Proto->getNumArgs(); 9166 9167 // If too few arguments are available, we'll fill in the rest with defaults. 9168 if (NumArgs < NumArgsInProto) 9169 ConvertedArgs.reserve(NumArgsInProto); 9170 else 9171 ConvertedArgs.reserve(NumArgs); 9172 9173 VariadicCallType CallType = 9174 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 9175 SmallVector<Expr *, 8> AllArgs; 9176 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 9177 Proto, 0, Args, NumArgs, AllArgs, 9178 CallType, AllowExplicit); 9179 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 9180 9181 DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size()); 9182 9183 CheckConstructorCall(Constructor, AllArgs.data(), AllArgs.size(), 9184 Proto, Loc); 9185 9186 return Invalid; 9187} 9188 9189static inline bool 9190CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 9191 const FunctionDecl *FnDecl) { 9192 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 9193 if (isa<NamespaceDecl>(DC)) { 9194 return SemaRef.Diag(FnDecl->getLocation(), 9195 diag::err_operator_new_delete_declared_in_namespace) 9196 << FnDecl->getDeclName(); 9197 } 9198 9199 if (isa<TranslationUnitDecl>(DC) && 9200 FnDecl->getStorageClass() == SC_Static) { 9201 return SemaRef.Diag(FnDecl->getLocation(), 9202 diag::err_operator_new_delete_declared_static) 9203 << FnDecl->getDeclName(); 9204 } 9205 9206 return false; 9207} 9208 9209static inline bool 9210CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 9211 CanQualType ExpectedResultType, 9212 CanQualType ExpectedFirstParamType, 9213 unsigned DependentParamTypeDiag, 9214 unsigned InvalidParamTypeDiag) { 9215 QualType ResultType = 9216 FnDecl->getType()->getAs<FunctionType>()->getResultType(); 9217 9218 // Check that the result type is not dependent. 9219 if (ResultType->isDependentType()) 9220 return SemaRef.Diag(FnDecl->getLocation(), 9221 diag::err_operator_new_delete_dependent_result_type) 9222 << FnDecl->getDeclName() << ExpectedResultType; 9223 9224 // Check that the result type is what we expect. 9225 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 9226 return SemaRef.Diag(FnDecl->getLocation(), 9227 diag::err_operator_new_delete_invalid_result_type) 9228 << FnDecl->getDeclName() << ExpectedResultType; 9229 9230 // A function template must have at least 2 parameters. 9231 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 9232 return SemaRef.Diag(FnDecl->getLocation(), 9233 diag::err_operator_new_delete_template_too_few_parameters) 9234 << FnDecl->getDeclName(); 9235 9236 // The function decl must have at least 1 parameter. 9237 if (FnDecl->getNumParams() == 0) 9238 return SemaRef.Diag(FnDecl->getLocation(), 9239 diag::err_operator_new_delete_too_few_parameters) 9240 << FnDecl->getDeclName(); 9241 9242 // Check the first parameter type is not dependent. 9243 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 9244 if (FirstParamType->isDependentType()) 9245 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 9246 << FnDecl->getDeclName() << ExpectedFirstParamType; 9247 9248 // Check that the first parameter type is what we expect. 9249 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 9250 ExpectedFirstParamType) 9251 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 9252 << FnDecl->getDeclName() << ExpectedFirstParamType; 9253 9254 return false; 9255} 9256 9257static bool 9258CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 9259 // C++ [basic.stc.dynamic.allocation]p1: 9260 // A program is ill-formed if an allocation function is declared in a 9261 // namespace scope other than global scope or declared static in global 9262 // scope. 9263 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 9264 return true; 9265 9266 CanQualType SizeTy = 9267 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 9268 9269 // C++ [basic.stc.dynamic.allocation]p1: 9270 // The return type shall be void*. The first parameter shall have type 9271 // std::size_t. 9272 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 9273 SizeTy, 9274 diag::err_operator_new_dependent_param_type, 9275 diag::err_operator_new_param_type)) 9276 return true; 9277 9278 // C++ [basic.stc.dynamic.allocation]p1: 9279 // The first parameter shall not have an associated default argument. 9280 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 9281 return SemaRef.Diag(FnDecl->getLocation(), 9282 diag::err_operator_new_default_arg) 9283 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 9284 9285 return false; 9286} 9287 9288static bool 9289CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 9290 // C++ [basic.stc.dynamic.deallocation]p1: 9291 // A program is ill-formed if deallocation functions are declared in a 9292 // namespace scope other than global scope or declared static in global 9293 // scope. 9294 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 9295 return true; 9296 9297 // C++ [basic.stc.dynamic.deallocation]p2: 9298 // Each deallocation function shall return void and its first parameter 9299 // shall be void*. 9300 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 9301 SemaRef.Context.VoidPtrTy, 9302 diag::err_operator_delete_dependent_param_type, 9303 diag::err_operator_delete_param_type)) 9304 return true; 9305 9306 return false; 9307} 9308 9309/// CheckOverloadedOperatorDeclaration - Check whether the declaration 9310/// of this overloaded operator is well-formed. If so, returns false; 9311/// otherwise, emits appropriate diagnostics and returns true. 9312bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 9313 assert(FnDecl && FnDecl->isOverloadedOperator() && 9314 "Expected an overloaded operator declaration"); 9315 9316 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 9317 9318 // C++ [over.oper]p5: 9319 // The allocation and deallocation functions, operator new, 9320 // operator new[], operator delete and operator delete[], are 9321 // described completely in 3.7.3. The attributes and restrictions 9322 // found in the rest of this subclause do not apply to them unless 9323 // explicitly stated in 3.7.3. 9324 if (Op == OO_Delete || Op == OO_Array_Delete) 9325 return CheckOperatorDeleteDeclaration(*this, FnDecl); 9326 9327 if (Op == OO_New || Op == OO_Array_New) 9328 return CheckOperatorNewDeclaration(*this, FnDecl); 9329 9330 // C++ [over.oper]p6: 9331 // An operator function shall either be a non-static member 9332 // function or be a non-member function and have at least one 9333 // parameter whose type is a class, a reference to a class, an 9334 // enumeration, or a reference to an enumeration. 9335 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 9336 if (MethodDecl->isStatic()) 9337 return Diag(FnDecl->getLocation(), 9338 diag::err_operator_overload_static) << FnDecl->getDeclName(); 9339 } else { 9340 bool ClassOrEnumParam = false; 9341 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 9342 ParamEnd = FnDecl->param_end(); 9343 Param != ParamEnd; ++Param) { 9344 QualType ParamType = (*Param)->getType().getNonReferenceType(); 9345 if (ParamType->isDependentType() || ParamType->isRecordType() || 9346 ParamType->isEnumeralType()) { 9347 ClassOrEnumParam = true; 9348 break; 9349 } 9350 } 9351 9352 if (!ClassOrEnumParam) 9353 return Diag(FnDecl->getLocation(), 9354 diag::err_operator_overload_needs_class_or_enum) 9355 << FnDecl->getDeclName(); 9356 } 9357 9358 // C++ [over.oper]p8: 9359 // An operator function cannot have default arguments (8.3.6), 9360 // except where explicitly stated below. 9361 // 9362 // Only the function-call operator allows default arguments 9363 // (C++ [over.call]p1). 9364 if (Op != OO_Call) { 9365 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(); 9366 Param != FnDecl->param_end(); ++Param) { 9367 if ((*Param)->hasDefaultArg()) 9368 return Diag((*Param)->getLocation(), 9369 diag::err_operator_overload_default_arg) 9370 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange(); 9371 } 9372 } 9373 9374 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 9375 { false, false, false } 9376#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 9377 , { Unary, Binary, MemberOnly } 9378#include "clang/Basic/OperatorKinds.def" 9379 }; 9380 9381 bool CanBeUnaryOperator = OperatorUses[Op][0]; 9382 bool CanBeBinaryOperator = OperatorUses[Op][1]; 9383 bool MustBeMemberOperator = OperatorUses[Op][2]; 9384 9385 // C++ [over.oper]p8: 9386 // [...] Operator functions cannot have more or fewer parameters 9387 // than the number required for the corresponding operator, as 9388 // described in the rest of this subclause. 9389 unsigned NumParams = FnDecl->getNumParams() 9390 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 9391 if (Op != OO_Call && 9392 ((NumParams == 1 && !CanBeUnaryOperator) || 9393 (NumParams == 2 && !CanBeBinaryOperator) || 9394 (NumParams < 1) || (NumParams > 2))) { 9395 // We have the wrong number of parameters. 9396 unsigned ErrorKind; 9397 if (CanBeUnaryOperator && CanBeBinaryOperator) { 9398 ErrorKind = 2; // 2 -> unary or binary. 9399 } else if (CanBeUnaryOperator) { 9400 ErrorKind = 0; // 0 -> unary 9401 } else { 9402 assert(CanBeBinaryOperator && 9403 "All non-call overloaded operators are unary or binary!"); 9404 ErrorKind = 1; // 1 -> binary 9405 } 9406 9407 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 9408 << FnDecl->getDeclName() << NumParams << ErrorKind; 9409 } 9410 9411 // Overloaded operators other than operator() cannot be variadic. 9412 if (Op != OO_Call && 9413 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 9414 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 9415 << FnDecl->getDeclName(); 9416 } 9417 9418 // Some operators must be non-static member functions. 9419 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 9420 return Diag(FnDecl->getLocation(), 9421 diag::err_operator_overload_must_be_member) 9422 << FnDecl->getDeclName(); 9423 } 9424 9425 // C++ [over.inc]p1: 9426 // The user-defined function called operator++ implements the 9427 // prefix and postfix ++ operator. If this function is a member 9428 // function with no parameters, or a non-member function with one 9429 // parameter of class or enumeration type, it defines the prefix 9430 // increment operator ++ for objects of that type. If the function 9431 // is a member function with one parameter (which shall be of type 9432 // int) or a non-member function with two parameters (the second 9433 // of which shall be of type int), it defines the postfix 9434 // increment operator ++ for objects of that type. 9435 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 9436 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 9437 bool ParamIsInt = false; 9438 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>()) 9439 ParamIsInt = BT->getKind() == BuiltinType::Int; 9440 9441 if (!ParamIsInt) 9442 return Diag(LastParam->getLocation(), 9443 diag::err_operator_overload_post_incdec_must_be_int) 9444 << LastParam->getType() << (Op == OO_MinusMinus); 9445 } 9446 9447 return false; 9448} 9449 9450/// CheckLiteralOperatorDeclaration - Check whether the declaration 9451/// of this literal operator function is well-formed. If so, returns 9452/// false; otherwise, emits appropriate diagnostics and returns true. 9453bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 9454 if (isa<CXXMethodDecl>(FnDecl)) { 9455 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 9456 << FnDecl->getDeclName(); 9457 return true; 9458 } 9459 9460 if (FnDecl->isExternC()) { 9461 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 9462 return true; 9463 } 9464 9465 bool Valid = false; 9466 9467 // This might be the definition of a literal operator template. 9468 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 9469 // This might be a specialization of a literal operator template. 9470 if (!TpDecl) 9471 TpDecl = FnDecl->getPrimaryTemplate(); 9472 9473 // template <char...> type operator "" name() is the only valid template 9474 // signature, and the only valid signature with no parameters. 9475 if (TpDecl) { 9476 if (FnDecl->param_size() == 0) { 9477 // Must have only one template parameter 9478 TemplateParameterList *Params = TpDecl->getTemplateParameters(); 9479 if (Params->size() == 1) { 9480 NonTypeTemplateParmDecl *PmDecl = 9481 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0)); 9482 9483 // The template parameter must be a char parameter pack. 9484 if (PmDecl && PmDecl->isTemplateParameterPack() && 9485 Context.hasSameType(PmDecl->getType(), Context.CharTy)) 9486 Valid = true; 9487 } 9488 } 9489 } else if (FnDecl->param_size()) { 9490 // Check the first parameter 9491 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 9492 9493 QualType T = (*Param)->getType().getUnqualifiedType(); 9494 9495 // unsigned long long int, long double, and any character type are allowed 9496 // as the only parameters. 9497 if (Context.hasSameType(T, Context.UnsignedLongLongTy) || 9498 Context.hasSameType(T, Context.LongDoubleTy) || 9499 Context.hasSameType(T, Context.CharTy) || 9500 Context.hasSameType(T, Context.WCharTy) || 9501 Context.hasSameType(T, Context.Char16Ty) || 9502 Context.hasSameType(T, Context.Char32Ty)) { 9503 if (++Param == FnDecl->param_end()) 9504 Valid = true; 9505 goto FinishedParams; 9506 } 9507 9508 // Otherwise it must be a pointer to const; let's strip those qualifiers. 9509 const PointerType *PT = T->getAs<PointerType>(); 9510 if (!PT) 9511 goto FinishedParams; 9512 T = PT->getPointeeType(); 9513 if (!T.isConstQualified() || T.isVolatileQualified()) 9514 goto FinishedParams; 9515 T = T.getUnqualifiedType(); 9516 9517 // Move on to the second parameter; 9518 ++Param; 9519 9520 // If there is no second parameter, the first must be a const char * 9521 if (Param == FnDecl->param_end()) { 9522 if (Context.hasSameType(T, Context.CharTy)) 9523 Valid = true; 9524 goto FinishedParams; 9525 } 9526 9527 // const char *, const wchar_t*, const char16_t*, and const char32_t* 9528 // are allowed as the first parameter to a two-parameter function 9529 if (!(Context.hasSameType(T, Context.CharTy) || 9530 Context.hasSameType(T, Context.WCharTy) || 9531 Context.hasSameType(T, Context.Char16Ty) || 9532 Context.hasSameType(T, Context.Char32Ty))) 9533 goto FinishedParams; 9534 9535 // The second and final parameter must be an std::size_t 9536 T = (*Param)->getType().getUnqualifiedType(); 9537 if (Context.hasSameType(T, Context.getSizeType()) && 9538 ++Param == FnDecl->param_end()) 9539 Valid = true; 9540 } 9541 9542 // FIXME: This diagnostic is absolutely terrible. 9543FinishedParams: 9544 if (!Valid) { 9545 Diag(FnDecl->getLocation(), diag::err_literal_operator_params) 9546 << FnDecl->getDeclName(); 9547 return true; 9548 } 9549 9550 // A parameter-declaration-clause containing a default argument is not 9551 // equivalent to any of the permitted forms. 9552 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 9553 ParamEnd = FnDecl->param_end(); 9554 Param != ParamEnd; ++Param) { 9555 if ((*Param)->hasDefaultArg()) { 9556 Diag((*Param)->getDefaultArgRange().getBegin(), 9557 diag::err_literal_operator_default_argument) 9558 << (*Param)->getDefaultArgRange(); 9559 break; 9560 } 9561 } 9562 9563 StringRef LiteralName 9564 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 9565 if (LiteralName[0] != '_') { 9566 // C++11 [usrlit.suffix]p1: 9567 // Literal suffix identifiers that do not start with an underscore 9568 // are reserved for future standardization. 9569 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved); 9570 } 9571 9572 return false; 9573} 9574 9575/// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 9576/// linkage specification, including the language and (if present) 9577/// the '{'. ExternLoc is the location of the 'extern', LangLoc is 9578/// the location of the language string literal, which is provided 9579/// by Lang/StrSize. LBraceLoc, if valid, provides the location of 9580/// the '{' brace. Otherwise, this linkage specification does not 9581/// have any braces. 9582Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 9583 SourceLocation LangLoc, 9584 StringRef Lang, 9585 SourceLocation LBraceLoc) { 9586 LinkageSpecDecl::LanguageIDs Language; 9587 if (Lang == "\"C\"") 9588 Language = LinkageSpecDecl::lang_c; 9589 else if (Lang == "\"C++\"") 9590 Language = LinkageSpecDecl::lang_cxx; 9591 else { 9592 Diag(LangLoc, diag::err_bad_language); 9593 return 0; 9594 } 9595 9596 // FIXME: Add all the various semantics of linkage specifications 9597 9598 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, 9599 ExternLoc, LangLoc, Language); 9600 CurContext->addDecl(D); 9601 PushDeclContext(S, D); 9602 return D; 9603} 9604 9605/// ActOnFinishLinkageSpecification - Complete the definition of 9606/// the C++ linkage specification LinkageSpec. If RBraceLoc is 9607/// valid, it's the position of the closing '}' brace in a linkage 9608/// specification that uses braces. 9609Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 9610 Decl *LinkageSpec, 9611 SourceLocation RBraceLoc) { 9612 if (LinkageSpec) { 9613 if (RBraceLoc.isValid()) { 9614 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 9615 LSDecl->setRBraceLoc(RBraceLoc); 9616 } 9617 PopDeclContext(); 9618 } 9619 return LinkageSpec; 9620} 9621 9622/// \brief Perform semantic analysis for the variable declaration that 9623/// occurs within a C++ catch clause, returning the newly-created 9624/// variable. 9625VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 9626 TypeSourceInfo *TInfo, 9627 SourceLocation StartLoc, 9628 SourceLocation Loc, 9629 IdentifierInfo *Name) { 9630 bool Invalid = false; 9631 QualType ExDeclType = TInfo->getType(); 9632 9633 // Arrays and functions decay. 9634 if (ExDeclType->isArrayType()) 9635 ExDeclType = Context.getArrayDecayedType(ExDeclType); 9636 else if (ExDeclType->isFunctionType()) 9637 ExDeclType = Context.getPointerType(ExDeclType); 9638 9639 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 9640 // The exception-declaration shall not denote a pointer or reference to an 9641 // incomplete type, other than [cv] void*. 9642 // N2844 forbids rvalue references. 9643 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 9644 Diag(Loc, diag::err_catch_rvalue_ref); 9645 Invalid = true; 9646 } 9647 9648 QualType BaseType = ExDeclType; 9649 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 9650 unsigned DK = diag::err_catch_incomplete; 9651 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 9652 BaseType = Ptr->getPointeeType(); 9653 Mode = 1; 9654 DK = diag::err_catch_incomplete_ptr; 9655 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 9656 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 9657 BaseType = Ref->getPointeeType(); 9658 Mode = 2; 9659 DK = diag::err_catch_incomplete_ref; 9660 } 9661 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 9662 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 9663 Invalid = true; 9664 9665 if (!Invalid && !ExDeclType->isDependentType() && 9666 RequireNonAbstractType(Loc, ExDeclType, 9667 diag::err_abstract_type_in_decl, 9668 AbstractVariableType)) 9669 Invalid = true; 9670 9671 // Only the non-fragile NeXT runtime currently supports C++ catches 9672 // of ObjC types, and no runtime supports catching ObjC types by value. 9673 if (!Invalid && getLangOpts().ObjC1) { 9674 QualType T = ExDeclType; 9675 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 9676 T = RT->getPointeeType(); 9677 9678 if (T->isObjCObjectType()) { 9679 Diag(Loc, diag::err_objc_object_catch); 9680 Invalid = true; 9681 } else if (T->isObjCObjectPointerType()) { 9682 // FIXME: should this be a test for macosx-fragile specifically? 9683 if (getLangOpts().ObjCRuntime.isFragile()) 9684 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 9685 } 9686 } 9687 9688 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 9689 ExDeclType, TInfo, SC_None, SC_None); 9690 ExDecl->setExceptionVariable(true); 9691 9692 // In ARC, infer 'retaining' for variables of retainable type. 9693 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 9694 Invalid = true; 9695 9696 if (!Invalid && !ExDeclType->isDependentType()) { 9697 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 9698 // C++ [except.handle]p16: 9699 // The object declared in an exception-declaration or, if the 9700 // exception-declaration does not specify a name, a temporary (12.2) is 9701 // copy-initialized (8.5) from the exception object. [...] 9702 // The object is destroyed when the handler exits, after the destruction 9703 // of any automatic objects initialized within the handler. 9704 // 9705 // We just pretend to initialize the object with itself, then make sure 9706 // it can be destroyed later. 9707 QualType initType = ExDeclType; 9708 9709 InitializedEntity entity = 9710 InitializedEntity::InitializeVariable(ExDecl); 9711 InitializationKind initKind = 9712 InitializationKind::CreateCopy(Loc, SourceLocation()); 9713 9714 Expr *opaqueValue = 9715 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 9716 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1); 9717 ExprResult result = sequence.Perform(*this, entity, initKind, 9718 MultiExprArg(&opaqueValue, 1)); 9719 if (result.isInvalid()) 9720 Invalid = true; 9721 else { 9722 // If the constructor used was non-trivial, set this as the 9723 // "initializer". 9724 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take()); 9725 if (!construct->getConstructor()->isTrivial()) { 9726 Expr *init = MaybeCreateExprWithCleanups(construct); 9727 ExDecl->setInit(init); 9728 } 9729 9730 // And make sure it's destructable. 9731 FinalizeVarWithDestructor(ExDecl, recordType); 9732 } 9733 } 9734 } 9735 9736 if (Invalid) 9737 ExDecl->setInvalidDecl(); 9738 9739 return ExDecl; 9740} 9741 9742/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 9743/// handler. 9744Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 9745 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 9746 bool Invalid = D.isInvalidType(); 9747 9748 // Check for unexpanded parameter packs. 9749 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 9750 UPPC_ExceptionType)) { 9751 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 9752 D.getIdentifierLoc()); 9753 Invalid = true; 9754 } 9755 9756 IdentifierInfo *II = D.getIdentifier(); 9757 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 9758 LookupOrdinaryName, 9759 ForRedeclaration)) { 9760 // The scope should be freshly made just for us. There is just no way 9761 // it contains any previous declaration. 9762 assert(!S->isDeclScope(PrevDecl)); 9763 if (PrevDecl->isTemplateParameter()) { 9764 // Maybe we will complain about the shadowed template parameter. 9765 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 9766 PrevDecl = 0; 9767 } 9768 } 9769 9770 if (D.getCXXScopeSpec().isSet() && !Invalid) { 9771 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 9772 << D.getCXXScopeSpec().getRange(); 9773 Invalid = true; 9774 } 9775 9776 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 9777 D.getLocStart(), 9778 D.getIdentifierLoc(), 9779 D.getIdentifier()); 9780 if (Invalid) 9781 ExDecl->setInvalidDecl(); 9782 9783 // Add the exception declaration into this scope. 9784 if (II) 9785 PushOnScopeChains(ExDecl, S); 9786 else 9787 CurContext->addDecl(ExDecl); 9788 9789 ProcessDeclAttributes(S, ExDecl, D); 9790 return ExDecl; 9791} 9792 9793Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 9794 Expr *AssertExpr, 9795 Expr *AssertMessageExpr, 9796 SourceLocation RParenLoc) { 9797 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr); 9798 9799 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 9800 return 0; 9801 9802 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 9803 AssertMessage, RParenLoc, false); 9804} 9805 9806Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 9807 Expr *AssertExpr, 9808 StringLiteral *AssertMessage, 9809 SourceLocation RParenLoc, 9810 bool Failed) { 9811 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 9812 !Failed) { 9813 // In a static_assert-declaration, the constant-expression shall be a 9814 // constant expression that can be contextually converted to bool. 9815 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 9816 if (Converted.isInvalid()) 9817 Failed = true; 9818 9819 llvm::APSInt Cond; 9820 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 9821 diag::err_static_assert_expression_is_not_constant, 9822 /*AllowFold=*/false).isInvalid()) 9823 Failed = true; 9824 9825 if (!Failed && !Cond) { 9826 llvm::SmallString<256> MsgBuffer; 9827 llvm::raw_svector_ostream Msg(MsgBuffer); 9828 AssertMessage->printPretty(Msg, 0, getPrintingPolicy()); 9829 Diag(StaticAssertLoc, diag::err_static_assert_failed) 9830 << Msg.str() << AssertExpr->getSourceRange(); 9831 Failed = true; 9832 } 9833 } 9834 9835 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 9836 AssertExpr, AssertMessage, RParenLoc, 9837 Failed); 9838 9839 CurContext->addDecl(Decl); 9840 return Decl; 9841} 9842 9843/// \brief Perform semantic analysis of the given friend type declaration. 9844/// 9845/// \returns A friend declaration that. 9846FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation Loc, 9847 SourceLocation FriendLoc, 9848 TypeSourceInfo *TSInfo) { 9849 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 9850 9851 QualType T = TSInfo->getType(); 9852 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 9853 9854 // C++03 [class.friend]p2: 9855 // An elaborated-type-specifier shall be used in a friend declaration 9856 // for a class.* 9857 // 9858 // * The class-key of the elaborated-type-specifier is required. 9859 if (!ActiveTemplateInstantiations.empty()) { 9860 // Do not complain about the form of friend template types during 9861 // template instantiation; we will already have complained when the 9862 // template was declared. 9863 } else if (!T->isElaboratedTypeSpecifier()) { 9864 // If we evaluated the type to a record type, suggest putting 9865 // a tag in front. 9866 if (const RecordType *RT = T->getAs<RecordType>()) { 9867 RecordDecl *RD = RT->getDecl(); 9868 9869 std::string InsertionText = std::string(" ") + RD->getKindName(); 9870 9871 Diag(TypeRange.getBegin(), 9872 getLangOpts().CPlusPlus0x ? 9873 diag::warn_cxx98_compat_unelaborated_friend_type : 9874 diag::ext_unelaborated_friend_type) 9875 << (unsigned) RD->getTagKind() 9876 << T 9877 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc), 9878 InsertionText); 9879 } else { 9880 Diag(FriendLoc, 9881 getLangOpts().CPlusPlus0x ? 9882 diag::warn_cxx98_compat_nonclass_type_friend : 9883 diag::ext_nonclass_type_friend) 9884 << T 9885 << SourceRange(FriendLoc, TypeRange.getEnd()); 9886 } 9887 } else if (T->getAs<EnumType>()) { 9888 Diag(FriendLoc, 9889 getLangOpts().CPlusPlus0x ? 9890 diag::warn_cxx98_compat_enum_friend : 9891 diag::ext_enum_friend) 9892 << T 9893 << SourceRange(FriendLoc, TypeRange.getEnd()); 9894 } 9895 9896 // C++0x [class.friend]p3: 9897 // If the type specifier in a friend declaration designates a (possibly 9898 // cv-qualified) class type, that class is declared as a friend; otherwise, 9899 // the friend declaration is ignored. 9900 9901 // FIXME: C++0x has some syntactic restrictions on friend type declarations 9902 // in [class.friend]p3 that we do not implement. 9903 9904 return FriendDecl::Create(Context, CurContext, Loc, TSInfo, FriendLoc); 9905} 9906 9907/// Handle a friend tag declaration where the scope specifier was 9908/// templated. 9909Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 9910 unsigned TagSpec, SourceLocation TagLoc, 9911 CXXScopeSpec &SS, 9912 IdentifierInfo *Name, SourceLocation NameLoc, 9913 AttributeList *Attr, 9914 MultiTemplateParamsArg TempParamLists) { 9915 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 9916 9917 bool isExplicitSpecialization = false; 9918 bool Invalid = false; 9919 9920 if (TemplateParameterList *TemplateParams 9921 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS, 9922 TempParamLists.data(), 9923 TempParamLists.size(), 9924 /*friend*/ true, 9925 isExplicitSpecialization, 9926 Invalid)) { 9927 if (TemplateParams->size() > 0) { 9928 // This is a declaration of a class template. 9929 if (Invalid) 9930 return 0; 9931 9932 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, 9933 SS, Name, NameLoc, Attr, 9934 TemplateParams, AS_public, 9935 /*ModulePrivateLoc=*/SourceLocation(), 9936 TempParamLists.size() - 1, 9937 TempParamLists.data()).take(); 9938 } else { 9939 // The "template<>" header is extraneous. 9940 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 9941 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 9942 isExplicitSpecialization = true; 9943 } 9944 } 9945 9946 if (Invalid) return 0; 9947 9948 bool isAllExplicitSpecializations = true; 9949 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 9950 if (TempParamLists[I]->size()) { 9951 isAllExplicitSpecializations = false; 9952 break; 9953 } 9954 } 9955 9956 // FIXME: don't ignore attributes. 9957 9958 // If it's explicit specializations all the way down, just forget 9959 // about the template header and build an appropriate non-templated 9960 // friend. TODO: for source fidelity, remember the headers. 9961 if (isAllExplicitSpecializations) { 9962 if (SS.isEmpty()) { 9963 bool Owned = false; 9964 bool IsDependent = false; 9965 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 9966 Attr, AS_public, 9967 /*ModulePrivateLoc=*/SourceLocation(), 9968 MultiTemplateParamsArg(), Owned, IsDependent, 9969 /*ScopedEnumKWLoc=*/SourceLocation(), 9970 /*ScopedEnumUsesClassTag=*/false, 9971 /*UnderlyingType=*/TypeResult()); 9972 } 9973 9974 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 9975 ElaboratedTypeKeyword Keyword 9976 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 9977 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 9978 *Name, NameLoc); 9979 if (T.isNull()) 9980 return 0; 9981 9982 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 9983 if (isa<DependentNameType>(T)) { 9984 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc()); 9985 TL.setElaboratedKeywordLoc(TagLoc); 9986 TL.setQualifierLoc(QualifierLoc); 9987 TL.setNameLoc(NameLoc); 9988 } else { 9989 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc()); 9990 TL.setElaboratedKeywordLoc(TagLoc); 9991 TL.setQualifierLoc(QualifierLoc); 9992 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc); 9993 } 9994 9995 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 9996 TSI, FriendLoc); 9997 Friend->setAccess(AS_public); 9998 CurContext->addDecl(Friend); 9999 return Friend; 10000 } 10001 10002 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 10003 10004 10005 10006 // Handle the case of a templated-scope friend class. e.g. 10007 // template <class T> class A<T>::B; 10008 // FIXME: we don't support these right now. 10009 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 10010 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 10011 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 10012 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc()); 10013 TL.setElaboratedKeywordLoc(TagLoc); 10014 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 10015 TL.setNameLoc(NameLoc); 10016 10017 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 10018 TSI, FriendLoc); 10019 Friend->setAccess(AS_public); 10020 Friend->setUnsupportedFriend(true); 10021 CurContext->addDecl(Friend); 10022 return Friend; 10023} 10024 10025 10026/// Handle a friend type declaration. This works in tandem with 10027/// ActOnTag. 10028/// 10029/// Notes on friend class templates: 10030/// 10031/// We generally treat friend class declarations as if they were 10032/// declaring a class. So, for example, the elaborated type specifier 10033/// in a friend declaration is required to obey the restrictions of a 10034/// class-head (i.e. no typedefs in the scope chain), template 10035/// parameters are required to match up with simple template-ids, &c. 10036/// However, unlike when declaring a template specialization, it's 10037/// okay to refer to a template specialization without an empty 10038/// template parameter declaration, e.g. 10039/// friend class A<T>::B<unsigned>; 10040/// We permit this as a special case; if there are any template 10041/// parameters present at all, require proper matching, i.e. 10042/// template <> template \<class T> friend class A<int>::B; 10043Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 10044 MultiTemplateParamsArg TempParams) { 10045 SourceLocation Loc = DS.getLocStart(); 10046 10047 assert(DS.isFriendSpecified()); 10048 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 10049 10050 // Try to convert the decl specifier to a type. This works for 10051 // friend templates because ActOnTag never produces a ClassTemplateDecl 10052 // for a TUK_Friend. 10053 Declarator TheDeclarator(DS, Declarator::MemberContext); 10054 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 10055 QualType T = TSI->getType(); 10056 if (TheDeclarator.isInvalidType()) 10057 return 0; 10058 10059 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 10060 return 0; 10061 10062 // This is definitely an error in C++98. It's probably meant to 10063 // be forbidden in C++0x, too, but the specification is just 10064 // poorly written. 10065 // 10066 // The problem is with declarations like the following: 10067 // template <T> friend A<T>::foo; 10068 // where deciding whether a class C is a friend or not now hinges 10069 // on whether there exists an instantiation of A that causes 10070 // 'foo' to equal C. There are restrictions on class-heads 10071 // (which we declare (by fiat) elaborated friend declarations to 10072 // be) that makes this tractable. 10073 // 10074 // FIXME: handle "template <> friend class A<T>;", which 10075 // is possibly well-formed? Who even knows? 10076 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 10077 Diag(Loc, diag::err_tagless_friend_type_template) 10078 << DS.getSourceRange(); 10079 return 0; 10080 } 10081 10082 // C++98 [class.friend]p1: A friend of a class is a function 10083 // or class that is not a member of the class . . . 10084 // This is fixed in DR77, which just barely didn't make the C++03 10085 // deadline. It's also a very silly restriction that seriously 10086 // affects inner classes and which nobody else seems to implement; 10087 // thus we never diagnose it, not even in -pedantic. 10088 // 10089 // But note that we could warn about it: it's always useless to 10090 // friend one of your own members (it's not, however, worthless to 10091 // friend a member of an arbitrary specialization of your template). 10092 10093 Decl *D; 10094 if (unsigned NumTempParamLists = TempParams.size()) 10095 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 10096 NumTempParamLists, 10097 TempParams.data(), 10098 TSI, 10099 DS.getFriendSpecLoc()); 10100 else 10101 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 10102 10103 if (!D) 10104 return 0; 10105 10106 D->setAccess(AS_public); 10107 CurContext->addDecl(D); 10108 10109 return D; 10110} 10111 10112Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 10113 MultiTemplateParamsArg TemplateParams) { 10114 const DeclSpec &DS = D.getDeclSpec(); 10115 10116 assert(DS.isFriendSpecified()); 10117 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 10118 10119 SourceLocation Loc = D.getIdentifierLoc(); 10120 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 10121 10122 // C++ [class.friend]p1 10123 // A friend of a class is a function or class.... 10124 // Note that this sees through typedefs, which is intended. 10125 // It *doesn't* see through dependent types, which is correct 10126 // according to [temp.arg.type]p3: 10127 // If a declaration acquires a function type through a 10128 // type dependent on a template-parameter and this causes 10129 // a declaration that does not use the syntactic form of a 10130 // function declarator to have a function type, the program 10131 // is ill-formed. 10132 if (!TInfo->getType()->isFunctionType()) { 10133 Diag(Loc, diag::err_unexpected_friend); 10134 10135 // It might be worthwhile to try to recover by creating an 10136 // appropriate declaration. 10137 return 0; 10138 } 10139 10140 // C++ [namespace.memdef]p3 10141 // - If a friend declaration in a non-local class first declares a 10142 // class or function, the friend class or function is a member 10143 // of the innermost enclosing namespace. 10144 // - The name of the friend is not found by simple name lookup 10145 // until a matching declaration is provided in that namespace 10146 // scope (either before or after the class declaration granting 10147 // friendship). 10148 // - If a friend function is called, its name may be found by the 10149 // name lookup that considers functions from namespaces and 10150 // classes associated with the types of the function arguments. 10151 // - When looking for a prior declaration of a class or a function 10152 // declared as a friend, scopes outside the innermost enclosing 10153 // namespace scope are not considered. 10154 10155 CXXScopeSpec &SS = D.getCXXScopeSpec(); 10156 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 10157 DeclarationName Name = NameInfo.getName(); 10158 assert(Name); 10159 10160 // Check for unexpanded parameter packs. 10161 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 10162 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 10163 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 10164 return 0; 10165 10166 // The context we found the declaration in, or in which we should 10167 // create the declaration. 10168 DeclContext *DC; 10169 Scope *DCScope = S; 10170 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 10171 ForRedeclaration); 10172 10173 // FIXME: there are different rules in local classes 10174 10175 // There are four cases here. 10176 // - There's no scope specifier, in which case we just go to the 10177 // appropriate scope and look for a function or function template 10178 // there as appropriate. 10179 // Recover from invalid scope qualifiers as if they just weren't there. 10180 if (SS.isInvalid() || !SS.isSet()) { 10181 // C++0x [namespace.memdef]p3: 10182 // If the name in a friend declaration is neither qualified nor 10183 // a template-id and the declaration is a function or an 10184 // elaborated-type-specifier, the lookup to determine whether 10185 // the entity has been previously declared shall not consider 10186 // any scopes outside the innermost enclosing namespace. 10187 // C++0x [class.friend]p11: 10188 // If a friend declaration appears in a local class and the name 10189 // specified is an unqualified name, a prior declaration is 10190 // looked up without considering scopes that are outside the 10191 // innermost enclosing non-class scope. For a friend function 10192 // declaration, if there is no prior declaration, the program is 10193 // ill-formed. 10194 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass(); 10195 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 10196 10197 // Find the appropriate context according to the above. 10198 DC = CurContext; 10199 while (true) { 10200 // Skip class contexts. If someone can cite chapter and verse 10201 // for this behavior, that would be nice --- it's what GCC and 10202 // EDG do, and it seems like a reasonable intent, but the spec 10203 // really only says that checks for unqualified existing 10204 // declarations should stop at the nearest enclosing namespace, 10205 // not that they should only consider the nearest enclosing 10206 // namespace. 10207 while (DC->isRecord() || DC->isTransparentContext()) 10208 DC = DC->getParent(); 10209 10210 LookupQualifiedName(Previous, DC); 10211 10212 // TODO: decide what we think about using declarations. 10213 if (isLocal || !Previous.empty()) 10214 break; 10215 10216 if (isTemplateId) { 10217 if (isa<TranslationUnitDecl>(DC)) break; 10218 } else { 10219 if (DC->isFileContext()) break; 10220 } 10221 DC = DC->getParent(); 10222 } 10223 10224 // C++ [class.friend]p1: A friend of a class is a function or 10225 // class that is not a member of the class . . . 10226 // C++11 changes this for both friend types and functions. 10227 // Most C++ 98 compilers do seem to give an error here, so 10228 // we do, too. 10229 if (!Previous.empty() && DC->Equals(CurContext)) 10230 Diag(DS.getFriendSpecLoc(), 10231 getLangOpts().CPlusPlus0x ? 10232 diag::warn_cxx98_compat_friend_is_member : 10233 diag::err_friend_is_member); 10234 10235 DCScope = getScopeForDeclContext(S, DC); 10236 10237 // C++ [class.friend]p6: 10238 // A function can be defined in a friend declaration of a class if and 10239 // only if the class is a non-local class (9.8), the function name is 10240 // unqualified, and the function has namespace scope. 10241 if (isLocal && D.isFunctionDefinition()) { 10242 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 10243 } 10244 10245 // - There's a non-dependent scope specifier, in which case we 10246 // compute it and do a previous lookup there for a function 10247 // or function template. 10248 } else if (!SS.getScopeRep()->isDependent()) { 10249 DC = computeDeclContext(SS); 10250 if (!DC) return 0; 10251 10252 if (RequireCompleteDeclContext(SS, DC)) return 0; 10253 10254 LookupQualifiedName(Previous, DC); 10255 10256 // Ignore things found implicitly in the wrong scope. 10257 // TODO: better diagnostics for this case. Suggesting the right 10258 // qualified scope would be nice... 10259 LookupResult::Filter F = Previous.makeFilter(); 10260 while (F.hasNext()) { 10261 NamedDecl *D = F.next(); 10262 if (!DC->InEnclosingNamespaceSetOf( 10263 D->getDeclContext()->getRedeclContext())) 10264 F.erase(); 10265 } 10266 F.done(); 10267 10268 if (Previous.empty()) { 10269 D.setInvalidType(); 10270 Diag(Loc, diag::err_qualified_friend_not_found) 10271 << Name << TInfo->getType(); 10272 return 0; 10273 } 10274 10275 // C++ [class.friend]p1: A friend of a class is a function or 10276 // class that is not a member of the class . . . 10277 if (DC->Equals(CurContext)) 10278 Diag(DS.getFriendSpecLoc(), 10279 getLangOpts().CPlusPlus0x ? 10280 diag::warn_cxx98_compat_friend_is_member : 10281 diag::err_friend_is_member); 10282 10283 if (D.isFunctionDefinition()) { 10284 // C++ [class.friend]p6: 10285 // A function can be defined in a friend declaration of a class if and 10286 // only if the class is a non-local class (9.8), the function name is 10287 // unqualified, and the function has namespace scope. 10288 SemaDiagnosticBuilder DB 10289 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 10290 10291 DB << SS.getScopeRep(); 10292 if (DC->isFileContext()) 10293 DB << FixItHint::CreateRemoval(SS.getRange()); 10294 SS.clear(); 10295 } 10296 10297 // - There's a scope specifier that does not match any template 10298 // parameter lists, in which case we use some arbitrary context, 10299 // create a method or method template, and wait for instantiation. 10300 // - There's a scope specifier that does match some template 10301 // parameter lists, which we don't handle right now. 10302 } else { 10303 if (D.isFunctionDefinition()) { 10304 // C++ [class.friend]p6: 10305 // A function can be defined in a friend declaration of a class if and 10306 // only if the class is a non-local class (9.8), the function name is 10307 // unqualified, and the function has namespace scope. 10308 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 10309 << SS.getScopeRep(); 10310 } 10311 10312 DC = CurContext; 10313 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 10314 } 10315 10316 if (!DC->isRecord()) { 10317 // This implies that it has to be an operator or function. 10318 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName || 10319 D.getName().getKind() == UnqualifiedId::IK_DestructorName || 10320 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) { 10321 Diag(Loc, diag::err_introducing_special_friend) << 10322 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 : 10323 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2); 10324 return 0; 10325 } 10326 } 10327 10328 // FIXME: This is an egregious hack to cope with cases where the scope stack 10329 // does not contain the declaration context, i.e., in an out-of-line 10330 // definition of a class. 10331 Scope FakeDCScope(S, Scope::DeclScope, Diags); 10332 if (!DCScope) { 10333 FakeDCScope.setEntity(DC); 10334 DCScope = &FakeDCScope; 10335 } 10336 10337 bool AddToScope = true; 10338 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 10339 TemplateParams, AddToScope); 10340 if (!ND) return 0; 10341 10342 assert(ND->getDeclContext() == DC); 10343 assert(ND->getLexicalDeclContext() == CurContext); 10344 10345 // Add the function declaration to the appropriate lookup tables, 10346 // adjusting the redeclarations list as necessary. We don't 10347 // want to do this yet if the friending class is dependent. 10348 // 10349 // Also update the scope-based lookup if the target context's 10350 // lookup context is in lexical scope. 10351 if (!CurContext->isDependentContext()) { 10352 DC = DC->getRedeclContext(); 10353 DC->makeDeclVisibleInContext(ND); 10354 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 10355 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 10356 } 10357 10358 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 10359 D.getIdentifierLoc(), ND, 10360 DS.getFriendSpecLoc()); 10361 FrD->setAccess(AS_public); 10362 CurContext->addDecl(FrD); 10363 10364 if (ND->isInvalidDecl()) { 10365 FrD->setInvalidDecl(); 10366 } else { 10367 if (DC->isRecord()) CheckFriendAccess(ND); 10368 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 // Don't consider the implicit declaration we generate for explicit 10393 // specializations. FIXME: Do not generate these implicit declarations. 10394 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization 10395 || Prev->getPreviousDecl()) && !Prev->isDefined()) { 10396 Diag(DelLoc, diag::err_deleted_decl_not_first); 10397 Diag(Prev->getLocation(), diag::note_previous_declaration); 10398 } 10399 // If the declaration wasn't the first, we delete the function anyway for 10400 // recovery. 10401 } 10402 Fn->setDeletedAsWritten(); 10403 10404 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl); 10405 if (!MD) 10406 return; 10407 10408 // A deleted special member function is trivial if the corresponding 10409 // implicitly-declared function would have been. 10410 switch (getSpecialMember(MD)) { 10411 case CXXInvalid: 10412 break; 10413 case CXXDefaultConstructor: 10414 MD->setTrivial(MD->getParent()->hasTrivialDefaultConstructor()); 10415 break; 10416 case CXXCopyConstructor: 10417 MD->setTrivial(MD->getParent()->hasTrivialCopyConstructor()); 10418 break; 10419 case CXXMoveConstructor: 10420 MD->setTrivial(MD->getParent()->hasTrivialMoveConstructor()); 10421 break; 10422 case CXXCopyAssignment: 10423 MD->setTrivial(MD->getParent()->hasTrivialCopyAssignment()); 10424 break; 10425 case CXXMoveAssignment: 10426 MD->setTrivial(MD->getParent()->hasTrivialMoveAssignment()); 10427 break; 10428 case CXXDestructor: 10429 MD->setTrivial(MD->getParent()->hasTrivialDestructor()); 10430 break; 10431 } 10432} 10433 10434void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 10435 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl); 10436 10437 if (MD) { 10438 if (MD->getParent()->isDependentType()) { 10439 MD->setDefaulted(); 10440 MD->setExplicitlyDefaulted(); 10441 return; 10442 } 10443 10444 CXXSpecialMember Member = getSpecialMember(MD); 10445 if (Member == CXXInvalid) { 10446 Diag(DefaultLoc, diag::err_default_special_members); 10447 return; 10448 } 10449 10450 MD->setDefaulted(); 10451 MD->setExplicitlyDefaulted(); 10452 10453 // If this definition appears within the record, do the checking when 10454 // the record is complete. 10455 const FunctionDecl *Primary = MD; 10456 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 10457 // Find the uninstantiated declaration that actually had the '= default' 10458 // on it. 10459 Pattern->isDefined(Primary); 10460 10461 if (Primary == Primary->getCanonicalDecl()) 10462 return; 10463 10464 CheckExplicitlyDefaultedSpecialMember(MD); 10465 10466 switch (Member) { 10467 case CXXDefaultConstructor: { 10468 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD); 10469 if (!CD->isInvalidDecl()) 10470 DefineImplicitDefaultConstructor(DefaultLoc, CD); 10471 break; 10472 } 10473 10474 case CXXCopyConstructor: { 10475 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD); 10476 if (!CD->isInvalidDecl()) 10477 DefineImplicitCopyConstructor(DefaultLoc, CD); 10478 break; 10479 } 10480 10481 case CXXCopyAssignment: { 10482 if (!MD->isInvalidDecl()) 10483 DefineImplicitCopyAssignment(DefaultLoc, MD); 10484 break; 10485 } 10486 10487 case CXXDestructor: { 10488 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD); 10489 if (!DD->isInvalidDecl()) 10490 DefineImplicitDestructor(DefaultLoc, DD); 10491 break; 10492 } 10493 10494 case CXXMoveConstructor: { 10495 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD); 10496 if (!CD->isInvalidDecl()) 10497 DefineImplicitMoveConstructor(DefaultLoc, CD); 10498 break; 10499 } 10500 10501 case CXXMoveAssignment: { 10502 if (!MD->isInvalidDecl()) 10503 DefineImplicitMoveAssignment(DefaultLoc, MD); 10504 break; 10505 } 10506 10507 case CXXInvalid: 10508 llvm_unreachable("Invalid special member."); 10509 } 10510 } else { 10511 Diag(DefaultLoc, diag::err_default_special_members); 10512 } 10513} 10514 10515static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 10516 for (Stmt::child_range CI = S->children(); CI; ++CI) { 10517 Stmt *SubStmt = *CI; 10518 if (!SubStmt) 10519 continue; 10520 if (isa<ReturnStmt>(SubStmt)) 10521 Self.Diag(SubStmt->getLocStart(), 10522 diag::err_return_in_constructor_handler); 10523 if (!isa<Expr>(SubStmt)) 10524 SearchForReturnInStmt(Self, SubStmt); 10525 } 10526} 10527 10528void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 10529 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 10530 CXXCatchStmt *Handler = TryBlock->getHandler(I); 10531 SearchForReturnInStmt(*this, Handler); 10532 } 10533} 10534 10535bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 10536 const CXXMethodDecl *Old) { 10537 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType(); 10538 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType(); 10539 10540 if (Context.hasSameType(NewTy, OldTy) || 10541 NewTy->isDependentType() || OldTy->isDependentType()) 10542 return false; 10543 10544 // Check if the return types are covariant 10545 QualType NewClassTy, OldClassTy; 10546 10547 /// Both types must be pointers or references to classes. 10548 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 10549 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 10550 NewClassTy = NewPT->getPointeeType(); 10551 OldClassTy = OldPT->getPointeeType(); 10552 } 10553 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 10554 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 10555 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 10556 NewClassTy = NewRT->getPointeeType(); 10557 OldClassTy = OldRT->getPointeeType(); 10558 } 10559 } 10560 } 10561 10562 // The return types aren't either both pointers or references to a class type. 10563 if (NewClassTy.isNull()) { 10564 Diag(New->getLocation(), 10565 diag::err_different_return_type_for_overriding_virtual_function) 10566 << New->getDeclName() << NewTy << OldTy; 10567 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 10568 10569 return true; 10570 } 10571 10572 // C++ [class.virtual]p6: 10573 // If the return type of D::f differs from the return type of B::f, the 10574 // class type in the return type of D::f shall be complete at the point of 10575 // declaration of D::f or shall be the class type D. 10576 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 10577 if (!RT->isBeingDefined() && 10578 RequireCompleteType(New->getLocation(), NewClassTy, 10579 diag::err_covariant_return_incomplete, 10580 New->getDeclName())) 10581 return true; 10582 } 10583 10584 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 10585 // Check if the new class derives from the old class. 10586 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 10587 Diag(New->getLocation(), 10588 diag::err_covariant_return_not_derived) 10589 << New->getDeclName() << NewTy << OldTy; 10590 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 10591 return true; 10592 } 10593 10594 // Check if we the conversion from derived to base is valid. 10595 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy, 10596 diag::err_covariant_return_inaccessible_base, 10597 diag::err_covariant_return_ambiguous_derived_to_base_conv, 10598 // FIXME: Should this point to the return type? 10599 New->getLocation(), SourceRange(), New->getDeclName(), 0)) { 10600 // FIXME: this note won't trigger for delayed access control 10601 // diagnostics, and it's impossible to get an undelayed error 10602 // here from access control during the original parse because 10603 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 10604 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 10605 return true; 10606 } 10607 } 10608 10609 // The qualifiers of the return types must be the same. 10610 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 10611 Diag(New->getLocation(), 10612 diag::err_covariant_return_type_different_qualifications) 10613 << New->getDeclName() << NewTy << OldTy; 10614 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 10615 return true; 10616 }; 10617 10618 10619 // The new class type must have the same or less qualifiers as the old type. 10620 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 10621 Diag(New->getLocation(), 10622 diag::err_covariant_return_type_class_type_more_qualified) 10623 << New->getDeclName() << NewTy << OldTy; 10624 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 10625 return true; 10626 }; 10627 10628 return false; 10629} 10630 10631/// \brief Mark the given method pure. 10632/// 10633/// \param Method the method to be marked pure. 10634/// 10635/// \param InitRange the source range that covers the "0" initializer. 10636bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 10637 SourceLocation EndLoc = InitRange.getEnd(); 10638 if (EndLoc.isValid()) 10639 Method->setRangeEnd(EndLoc); 10640 10641 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 10642 Method->setPure(); 10643 return false; 10644 } 10645 10646 if (!Method->isInvalidDecl()) 10647 Diag(Method->getLocation(), diag::err_non_virtual_pure) 10648 << Method->getDeclName() << InitRange; 10649 return true; 10650} 10651 10652/// \brief Determine whether the given declaration is a static data member. 10653static bool isStaticDataMember(Decl *D) { 10654 VarDecl *Var = dyn_cast_or_null<VarDecl>(D); 10655 if (!Var) 10656 return false; 10657 10658 return Var->isStaticDataMember(); 10659} 10660/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 10661/// an initializer for the out-of-line declaration 'Dcl'. The scope 10662/// is a fresh scope pushed for just this purpose. 10663/// 10664/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 10665/// static data member of class X, names should be looked up in the scope of 10666/// class X. 10667void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 10668 // If there is no declaration, there was an error parsing it. 10669 if (D == 0 || D->isInvalidDecl()) return; 10670 10671 // We should only get called for declarations with scope specifiers, like: 10672 // int foo::bar; 10673 assert(D->isOutOfLine()); 10674 EnterDeclaratorContext(S, D->getDeclContext()); 10675 10676 // If we are parsing the initializer for a static data member, push a 10677 // new expression evaluation context that is associated with this static 10678 // data member. 10679 if (isStaticDataMember(D)) 10680 PushExpressionEvaluationContext(PotentiallyEvaluated, D); 10681} 10682 10683/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 10684/// initializer for the out-of-line declaration 'D'. 10685void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 10686 // If there is no declaration, there was an error parsing it. 10687 if (D == 0 || D->isInvalidDecl()) return; 10688 10689 if (isStaticDataMember(D)) 10690 PopExpressionEvaluationContext(); 10691 10692 assert(D->isOutOfLine()); 10693 ExitDeclaratorContext(S); 10694} 10695 10696/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 10697/// C++ if/switch/while/for statement. 10698/// e.g: "if (int x = f()) {...}" 10699DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 10700 // C++ 6.4p2: 10701 // The declarator shall not specify a function or an array. 10702 // The type-specifier-seq shall not contain typedef and shall not declare a 10703 // new class or enumeration. 10704 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 10705 "Parser allowed 'typedef' as storage class of condition decl."); 10706 10707 Decl *Dcl = ActOnDeclarator(S, D); 10708 if (!Dcl) 10709 return true; 10710 10711 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 10712 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 10713 << D.getSourceRange(); 10714 return true; 10715 } 10716 10717 return Dcl; 10718} 10719 10720void Sema::LoadExternalVTableUses() { 10721 if (!ExternalSource) 10722 return; 10723 10724 SmallVector<ExternalVTableUse, 4> VTables; 10725 ExternalSource->ReadUsedVTables(VTables); 10726 SmallVector<VTableUse, 4> NewUses; 10727 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 10728 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 10729 = VTablesUsed.find(VTables[I].Record); 10730 // Even if a definition wasn't required before, it may be required now. 10731 if (Pos != VTablesUsed.end()) { 10732 if (!Pos->second && VTables[I].DefinitionRequired) 10733 Pos->second = true; 10734 continue; 10735 } 10736 10737 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 10738 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 10739 } 10740 10741 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 10742} 10743 10744void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 10745 bool DefinitionRequired) { 10746 // Ignore any vtable uses in unevaluated operands or for classes that do 10747 // not have a vtable. 10748 if (!Class->isDynamicClass() || Class->isDependentContext() || 10749 CurContext->isDependentContext() || 10750 ExprEvalContexts.back().Context == Unevaluated) 10751 return; 10752 10753 // Try to insert this class into the map. 10754 LoadExternalVTableUses(); 10755 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 10756 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 10757 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 10758 if (!Pos.second) { 10759 // If we already had an entry, check to see if we are promoting this vtable 10760 // to required a definition. If so, we need to reappend to the VTableUses 10761 // list, since we may have already processed the first entry. 10762 if (DefinitionRequired && !Pos.first->second) { 10763 Pos.first->second = true; 10764 } else { 10765 // Otherwise, we can early exit. 10766 return; 10767 } 10768 } 10769 10770 // Local classes need to have their virtual members marked 10771 // immediately. For all other classes, we mark their virtual members 10772 // at the end of the translation unit. 10773 if (Class->isLocalClass()) 10774 MarkVirtualMembersReferenced(Loc, Class); 10775 else 10776 VTableUses.push_back(std::make_pair(Class, Loc)); 10777} 10778 10779bool Sema::DefineUsedVTables() { 10780 LoadExternalVTableUses(); 10781 if (VTableUses.empty()) 10782 return false; 10783 10784 // Note: The VTableUses vector could grow as a result of marking 10785 // the members of a class as "used", so we check the size each 10786 // time through the loop and prefer indices (which are stable) to 10787 // iterators (which are not). 10788 bool DefinedAnything = false; 10789 for (unsigned I = 0; I != VTableUses.size(); ++I) { 10790 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 10791 if (!Class) 10792 continue; 10793 10794 SourceLocation Loc = VTableUses[I].second; 10795 10796 bool DefineVTable = true; 10797 10798 // If this class has a key function, but that key function is 10799 // defined in another translation unit, we don't need to emit the 10800 // vtable even though we're using it. 10801 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class); 10802 if (KeyFunction && !KeyFunction->hasBody()) { 10803 switch (KeyFunction->getTemplateSpecializationKind()) { 10804 case TSK_Undeclared: 10805 case TSK_ExplicitSpecialization: 10806 case TSK_ExplicitInstantiationDeclaration: 10807 // The key function is in another translation unit. 10808 DefineVTable = false; 10809 break; 10810 10811 case TSK_ExplicitInstantiationDefinition: 10812 case TSK_ImplicitInstantiation: 10813 // We will be instantiating the key function. 10814 break; 10815 } 10816 } else if (!KeyFunction) { 10817 // If we have a class with no key function that is the subject 10818 // of an explicit instantiation declaration, suppress the 10819 // vtable; it will live with the explicit instantiation 10820 // definition. 10821 bool IsExplicitInstantiationDeclaration 10822 = Class->getTemplateSpecializationKind() 10823 == TSK_ExplicitInstantiationDeclaration; 10824 for (TagDecl::redecl_iterator R = Class->redecls_begin(), 10825 REnd = Class->redecls_end(); 10826 R != REnd; ++R) { 10827 TemplateSpecializationKind TSK 10828 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind(); 10829 if (TSK == TSK_ExplicitInstantiationDeclaration) 10830 IsExplicitInstantiationDeclaration = true; 10831 else if (TSK == TSK_ExplicitInstantiationDefinition) { 10832 IsExplicitInstantiationDeclaration = false; 10833 break; 10834 } 10835 } 10836 10837 if (IsExplicitInstantiationDeclaration) 10838 DefineVTable = false; 10839 } 10840 10841 // The exception specifications for all virtual members may be needed even 10842 // if we are not providing an authoritative form of the vtable in this TU. 10843 // We may choose to emit it available_externally anyway. 10844 if (!DefineVTable) { 10845 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 10846 continue; 10847 } 10848 10849 // Mark all of the virtual members of this class as referenced, so 10850 // that we can build a vtable. Then, tell the AST consumer that a 10851 // vtable for this class is required. 10852 DefinedAnything = true; 10853 MarkVirtualMembersReferenced(Loc, Class); 10854 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 10855 Consumer.HandleVTable(Class, VTablesUsed[Canonical]); 10856 10857 // Optionally warn if we're emitting a weak vtable. 10858 if (Class->getLinkage() == ExternalLinkage && 10859 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) { 10860 const FunctionDecl *KeyFunctionDef = 0; 10861 if (!KeyFunction || 10862 (KeyFunction->hasBody(KeyFunctionDef) && 10863 KeyFunctionDef->isInlined())) 10864 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() == 10865 TSK_ExplicitInstantiationDefinition 10866 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable) 10867 << Class; 10868 } 10869 } 10870 VTableUses.clear(); 10871 10872 return DefinedAnything; 10873} 10874 10875void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 10876 const CXXRecordDecl *RD) { 10877 for (CXXRecordDecl::method_iterator I = RD->method_begin(), 10878 E = RD->method_end(); I != E; ++I) 10879 if ((*I)->isVirtual() && !(*I)->isPure()) 10880 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>()); 10881} 10882 10883void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 10884 const CXXRecordDecl *RD) { 10885 // Mark all functions which will appear in RD's vtable as used. 10886 CXXFinalOverriderMap FinalOverriders; 10887 RD->getFinalOverriders(FinalOverriders); 10888 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 10889 E = FinalOverriders.end(); 10890 I != E; ++I) { 10891 for (OverridingMethods::const_iterator OI = I->second.begin(), 10892 OE = I->second.end(); 10893 OI != OE; ++OI) { 10894 assert(OI->second.size() > 0 && "no final overrider"); 10895 CXXMethodDecl *Overrider = OI->second.front().Method; 10896 10897 // C++ [basic.def.odr]p2: 10898 // [...] A virtual member function is used if it is not pure. [...] 10899 if (!Overrider->isPure()) 10900 MarkFunctionReferenced(Loc, Overrider); 10901 } 10902 } 10903 10904 // Only classes that have virtual bases need a VTT. 10905 if (RD->getNumVBases() == 0) 10906 return; 10907 10908 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(), 10909 e = RD->bases_end(); i != e; ++i) { 10910 const CXXRecordDecl *Base = 10911 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl()); 10912 if (Base->getNumVBases() == 0) 10913 continue; 10914 MarkVirtualMembersReferenced(Loc, Base); 10915 } 10916} 10917 10918/// SetIvarInitializers - This routine builds initialization ASTs for the 10919/// Objective-C implementation whose ivars need be initialized. 10920void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 10921 if (!getLangOpts().CPlusPlus) 10922 return; 10923 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 10924 SmallVector<ObjCIvarDecl*, 8> ivars; 10925 CollectIvarsToConstructOrDestruct(OID, ivars); 10926 if (ivars.empty()) 10927 return; 10928 SmallVector<CXXCtorInitializer*, 32> AllToInit; 10929 for (unsigned i = 0; i < ivars.size(); i++) { 10930 FieldDecl *Field = ivars[i]; 10931 if (Field->isInvalidDecl()) 10932 continue; 10933 10934 CXXCtorInitializer *Member; 10935 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 10936 InitializationKind InitKind = 10937 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 10938 10939 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0); 10940 ExprResult MemberInit = 10941 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg()); 10942 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 10943 // Note, MemberInit could actually come back empty if no initialization 10944 // is required (e.g., because it would call a trivial default constructor) 10945 if (!MemberInit.get() || MemberInit.isInvalid()) 10946 continue; 10947 10948 Member = 10949 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 10950 SourceLocation(), 10951 MemberInit.takeAs<Expr>(), 10952 SourceLocation()); 10953 AllToInit.push_back(Member); 10954 10955 // Be sure that the destructor is accessible and is marked as referenced. 10956 if (const RecordType *RecordTy 10957 = Context.getBaseElementType(Field->getType()) 10958 ->getAs<RecordType>()) { 10959 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 10960 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 10961 MarkFunctionReferenced(Field->getLocation(), Destructor); 10962 CheckDestructorAccess(Field->getLocation(), Destructor, 10963 PDiag(diag::err_access_dtor_ivar) 10964 << Context.getBaseElementType(Field->getType())); 10965 } 10966 } 10967 } 10968 ObjCImplementation->setIvarInitializers(Context, 10969 AllToInit.data(), AllToInit.size()); 10970 } 10971} 10972 10973static 10974void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 10975 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid, 10976 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid, 10977 llvm::SmallSet<CXXConstructorDecl*, 4> &Current, 10978 Sema &S) { 10979 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(), 10980 CE = Current.end(); 10981 if (Ctor->isInvalidDecl()) 10982 return; 10983 10984 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 10985 10986 // Target may not be determinable yet, for instance if this is a dependent 10987 // call in an uninstantiated template. 10988 if (Target) { 10989 const FunctionDecl *FNTarget = 0; 10990 (void)Target->hasBody(FNTarget); 10991 Target = const_cast<CXXConstructorDecl*>( 10992 cast_or_null<CXXConstructorDecl>(FNTarget)); 10993 } 10994 10995 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 10996 // Avoid dereferencing a null pointer here. 10997 *TCanonical = Target ? Target->getCanonicalDecl() : 0; 10998 10999 if (!Current.insert(Canonical)) 11000 return; 11001 11002 // We know that beyond here, we aren't chaining into a cycle. 11003 if (!Target || !Target->isDelegatingConstructor() || 11004 Target->isInvalidDecl() || Valid.count(TCanonical)) { 11005 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI) 11006 Valid.insert(*CI); 11007 Current.clear(); 11008 // We've hit a cycle. 11009 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 11010 Current.count(TCanonical)) { 11011 // If we haven't diagnosed this cycle yet, do so now. 11012 if (!Invalid.count(TCanonical)) { 11013 S.Diag((*Ctor->init_begin())->getSourceLocation(), 11014 diag::warn_delegating_ctor_cycle) 11015 << Ctor; 11016 11017 // Don't add a note for a function delegating directly to itself. 11018 if (TCanonical != Canonical) 11019 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 11020 11021 CXXConstructorDecl *C = Target; 11022 while (C->getCanonicalDecl() != Canonical) { 11023 const FunctionDecl *FNTarget = 0; 11024 (void)C->getTargetConstructor()->hasBody(FNTarget); 11025 assert(FNTarget && "Ctor cycle through bodiless function"); 11026 11027 C = const_cast<CXXConstructorDecl*>( 11028 cast<CXXConstructorDecl>(FNTarget)); 11029 S.Diag(C->getLocation(), diag::note_which_delegates_to); 11030 } 11031 } 11032 11033 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI) 11034 Invalid.insert(*CI); 11035 Current.clear(); 11036 } else { 11037 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 11038 } 11039} 11040 11041 11042void Sema::CheckDelegatingCtorCycles() { 11043 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 11044 11045 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(), 11046 CE = Current.end(); 11047 11048 for (DelegatingCtorDeclsType::iterator 11049 I = DelegatingCtorDecls.begin(ExternalSource), 11050 E = DelegatingCtorDecls.end(); 11051 I != E; ++I) 11052 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 11053 11054 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI) 11055 (*CI)->setInvalidDecl(); 11056} 11057 11058namespace { 11059 /// \brief AST visitor that finds references to the 'this' expression. 11060 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 11061 Sema &S; 11062 11063 public: 11064 explicit FindCXXThisExpr(Sema &S) : S(S) { } 11065 11066 bool VisitCXXThisExpr(CXXThisExpr *E) { 11067 S.Diag(E->getLocation(), diag::err_this_static_member_func) 11068 << E->isImplicit(); 11069 return false; 11070 } 11071 }; 11072} 11073 11074bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 11075 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 11076 if (!TSInfo) 11077 return false; 11078 11079 TypeLoc TL = TSInfo->getTypeLoc(); 11080 FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL); 11081 if (!ProtoTL) 11082 return false; 11083 11084 // C++11 [expr.prim.general]p3: 11085 // [The expression this] shall not appear before the optional 11086 // cv-qualifier-seq and it shall not appear within the declaration of a 11087 // static member function (although its type and value category are defined 11088 // within a static member function as they are within a non-static member 11089 // function). [ Note: this is because declaration matching does not occur 11090 // until the complete declarator is known. - end note ] 11091 const FunctionProtoType *Proto = ProtoTL->getTypePtr(); 11092 FindCXXThisExpr Finder(*this); 11093 11094 // If the return type came after the cv-qualifier-seq, check it now. 11095 if (Proto->hasTrailingReturn() && 11096 !Finder.TraverseTypeLoc(ProtoTL->getResultLoc())) 11097 return true; 11098 11099 // Check the exception specification. 11100 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 11101 return true; 11102 11103 return checkThisInStaticMemberFunctionAttributes(Method); 11104} 11105 11106bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 11107 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 11108 if (!TSInfo) 11109 return false; 11110 11111 TypeLoc TL = TSInfo->getTypeLoc(); 11112 FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL); 11113 if (!ProtoTL) 11114 return false; 11115 11116 const FunctionProtoType *Proto = ProtoTL->getTypePtr(); 11117 FindCXXThisExpr Finder(*this); 11118 11119 switch (Proto->getExceptionSpecType()) { 11120 case EST_Uninstantiated: 11121 case EST_Unevaluated: 11122 case EST_BasicNoexcept: 11123 case EST_DynamicNone: 11124 case EST_MSAny: 11125 case EST_None: 11126 break; 11127 11128 case EST_ComputedNoexcept: 11129 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 11130 return true; 11131 11132 case EST_Dynamic: 11133 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(), 11134 EEnd = Proto->exception_end(); 11135 E != EEnd; ++E) { 11136 if (!Finder.TraverseType(*E)) 11137 return true; 11138 } 11139 break; 11140 } 11141 11142 return false; 11143} 11144 11145bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 11146 FindCXXThisExpr Finder(*this); 11147 11148 // Check attributes. 11149 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end(); 11150 A != AEnd; ++A) { 11151 // FIXME: This should be emitted by tblgen. 11152 Expr *Arg = 0; 11153 ArrayRef<Expr *> Args; 11154 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A)) 11155 Arg = G->getArg(); 11156 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A)) 11157 Arg = G->getArg(); 11158 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A)) 11159 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size()); 11160 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A)) 11161 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size()); 11162 else if (ExclusiveLockFunctionAttr *ELF 11163 = dyn_cast<ExclusiveLockFunctionAttr>(*A)) 11164 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size()); 11165 else if (SharedLockFunctionAttr *SLF 11166 = dyn_cast<SharedLockFunctionAttr>(*A)) 11167 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size()); 11168 else if (ExclusiveTrylockFunctionAttr *ETLF 11169 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) { 11170 Arg = ETLF->getSuccessValue(); 11171 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size()); 11172 } else if (SharedTrylockFunctionAttr *STLF 11173 = dyn_cast<SharedTrylockFunctionAttr>(*A)) { 11174 Arg = STLF->getSuccessValue(); 11175 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size()); 11176 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A)) 11177 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size()); 11178 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A)) 11179 Arg = LR->getArg(); 11180 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A)) 11181 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size()); 11182 else if (ExclusiveLocksRequiredAttr *ELR 11183 = dyn_cast<ExclusiveLocksRequiredAttr>(*A)) 11184 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size()); 11185 else if (SharedLocksRequiredAttr *SLR 11186 = dyn_cast<SharedLocksRequiredAttr>(*A)) 11187 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size()); 11188 11189 if (Arg && !Finder.TraverseStmt(Arg)) 11190 return true; 11191 11192 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 11193 if (!Finder.TraverseStmt(Args[I])) 11194 return true; 11195 } 11196 } 11197 11198 return false; 11199} 11200 11201void 11202Sema::checkExceptionSpecification(ExceptionSpecificationType EST, 11203 ArrayRef<ParsedType> DynamicExceptions, 11204 ArrayRef<SourceRange> DynamicExceptionRanges, 11205 Expr *NoexceptExpr, 11206 llvm::SmallVectorImpl<QualType> &Exceptions, 11207 FunctionProtoType::ExtProtoInfo &EPI) { 11208 Exceptions.clear(); 11209 EPI.ExceptionSpecType = EST; 11210 if (EST == EST_Dynamic) { 11211 Exceptions.reserve(DynamicExceptions.size()); 11212 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 11213 // FIXME: Preserve type source info. 11214 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 11215 11216 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 11217 collectUnexpandedParameterPacks(ET, Unexpanded); 11218 if (!Unexpanded.empty()) { 11219 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(), 11220 UPPC_ExceptionType, 11221 Unexpanded); 11222 continue; 11223 } 11224 11225 // Check that the type is valid for an exception spec, and 11226 // drop it if not. 11227 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 11228 Exceptions.push_back(ET); 11229 } 11230 EPI.NumExceptions = Exceptions.size(); 11231 EPI.Exceptions = Exceptions.data(); 11232 return; 11233 } 11234 11235 if (EST == EST_ComputedNoexcept) { 11236 // If an error occurred, there's no expression here. 11237 if (NoexceptExpr) { 11238 assert((NoexceptExpr->isTypeDependent() || 11239 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 11240 Context.BoolTy) && 11241 "Parser should have made sure that the expression is boolean"); 11242 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 11243 EPI.ExceptionSpecType = EST_BasicNoexcept; 11244 return; 11245 } 11246 11247 if (!NoexceptExpr->isValueDependent()) 11248 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0, 11249 diag::err_noexcept_needs_constant_expression, 11250 /*AllowFold*/ false).take(); 11251 EPI.NoexceptExpr = NoexceptExpr; 11252 } 11253 return; 11254 } 11255} 11256 11257/// IdentifyCUDATarget - Determine the CUDA compilation target for this function 11258Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) { 11259 // Implicitly declared functions (e.g. copy constructors) are 11260 // __host__ __device__ 11261 if (D->isImplicit()) 11262 return CFT_HostDevice; 11263 11264 if (D->hasAttr<CUDAGlobalAttr>()) 11265 return CFT_Global; 11266 11267 if (D->hasAttr<CUDADeviceAttr>()) { 11268 if (D->hasAttr<CUDAHostAttr>()) 11269 return CFT_HostDevice; 11270 else 11271 return CFT_Device; 11272 } 11273 11274 return CFT_Host; 11275} 11276 11277bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget, 11278 CUDAFunctionTarget CalleeTarget) { 11279 // CUDA B.1.1 "The __device__ qualifier declares a function that is... 11280 // Callable from the device only." 11281 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device) 11282 return true; 11283 11284 // CUDA B.1.2 "The __global__ qualifier declares a function that is... 11285 // Callable from the host only." 11286 // CUDA B.1.3 "The __host__ qualifier declares a function that is... 11287 // Callable from the host only." 11288 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) && 11289 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global)) 11290 return true; 11291 11292 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice) 11293 return true; 11294 11295 return false; 11296} 11297