SemaDeclCXX.cpp revision afee0ff915b87f92e8c07c72d31c3165aacf6fa8
1//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements semantic analysis for C++ declarations. 11// 12//===----------------------------------------------------------------------===// 13 14#include "clang/Sema/SemaInternal.h" 15#include "clang/AST/ASTConsumer.h" 16#include "clang/AST/ASTContext.h" 17#include "clang/AST/ASTMutationListener.h" 18#include "clang/AST/CXXInheritance.h" 19#include "clang/AST/CharUnits.h" 20#include "clang/AST/DeclVisitor.h" 21#include "clang/AST/EvaluatedExprVisitor.h" 22#include "clang/AST/ExprCXX.h" 23#include "clang/AST/RecordLayout.h" 24#include "clang/AST/RecursiveASTVisitor.h" 25#include "clang/AST/StmtVisitor.h" 26#include "clang/AST/TypeLoc.h" 27#include "clang/AST/TypeOrdering.h" 28#include "clang/Basic/PartialDiagnostic.h" 29#include "clang/Lex/Preprocessor.h" 30#include "clang/Sema/CXXFieldCollector.h" 31#include "clang/Sema/DeclSpec.h" 32#include "clang/Sema/Initialization.h" 33#include "clang/Sema/Lookup.h" 34#include "clang/Sema/ParsedTemplate.h" 35#include "clang/Sema/Scope.h" 36#include "clang/Sema/ScopeInfo.h" 37#include "llvm/ADT/STLExtras.h" 38#include "llvm/ADT/SmallString.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 } 521 } 522 } 523 524 // DR1344: If a default argument is added outside a class definition and that 525 // default argument makes the function a special member function, the program 526 // is ill-formed. This can only happen for constructors. 527 if (isa<CXXConstructorDecl>(New) && 528 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 529 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 530 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 531 if (NewSM != OldSM) { 532 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 533 assert(NewParam->hasDefaultArg()); 534 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 535 << NewParam->getDefaultArgRange() << NewSM; 536 Diag(Old->getLocation(), diag::note_previous_declaration); 537 } 538 } 539 540 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 541 // template has a constexpr specifier then all its declarations shall 542 // contain the constexpr specifier. 543 if (New->isConstexpr() != Old->isConstexpr()) { 544 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 545 << New << New->isConstexpr(); 546 Diag(Old->getLocation(), diag::note_previous_declaration); 547 Invalid = true; 548 } 549 550 if (CheckEquivalentExceptionSpec(Old, New)) 551 Invalid = true; 552 553 return Invalid; 554} 555 556/// \brief Merge the exception specifications of two variable declarations. 557/// 558/// This is called when there's a redeclaration of a VarDecl. The function 559/// checks if the redeclaration might have an exception specification and 560/// validates compatibility and merges the specs if necessary. 561void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 562 // Shortcut if exceptions are disabled. 563 if (!getLangOpts().CXXExceptions) 564 return; 565 566 assert(Context.hasSameType(New->getType(), Old->getType()) && 567 "Should only be called if types are otherwise the same."); 568 569 QualType NewType = New->getType(); 570 QualType OldType = Old->getType(); 571 572 // We're only interested in pointers and references to functions, as well 573 // as pointers to member functions. 574 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 575 NewType = R->getPointeeType(); 576 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 577 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 578 NewType = P->getPointeeType(); 579 OldType = OldType->getAs<PointerType>()->getPointeeType(); 580 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 581 NewType = M->getPointeeType(); 582 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 583 } 584 585 if (!NewType->isFunctionProtoType()) 586 return; 587 588 // There's lots of special cases for functions. For function pointers, system 589 // libraries are hopefully not as broken so that we don't need these 590 // workarounds. 591 if (CheckEquivalentExceptionSpec( 592 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 593 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 594 New->setInvalidDecl(); 595 } 596} 597 598/// CheckCXXDefaultArguments - Verify that the default arguments for a 599/// function declaration are well-formed according to C++ 600/// [dcl.fct.default]. 601void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 602 unsigned NumParams = FD->getNumParams(); 603 unsigned p; 604 605 bool IsLambda = FD->getOverloadedOperator() == OO_Call && 606 isa<CXXMethodDecl>(FD) && 607 cast<CXXMethodDecl>(FD)->getParent()->isLambda(); 608 609 // Find first parameter with a default argument 610 for (p = 0; p < NumParams; ++p) { 611 ParmVarDecl *Param = FD->getParamDecl(p); 612 if (Param->hasDefaultArg()) { 613 // C++11 [expr.prim.lambda]p5: 614 // [...] Default arguments (8.3.6) shall not be specified in the 615 // parameter-declaration-clause of a lambda-declarator. 616 // 617 // FIXME: Core issue 974 strikes this sentence, we only provide an 618 // extension warning. 619 if (IsLambda) 620 Diag(Param->getLocation(), diag::ext_lambda_default_arguments) 621 << Param->getDefaultArgRange(); 622 break; 623 } 624 } 625 626 // C++ [dcl.fct.default]p4: 627 // In a given function declaration, all parameters 628 // subsequent to a parameter with a default argument shall 629 // have default arguments supplied in this or previous 630 // declarations. A default argument shall not be redefined 631 // by a later declaration (not even to the same value). 632 unsigned LastMissingDefaultArg = 0; 633 for (; p < NumParams; ++p) { 634 ParmVarDecl *Param = FD->getParamDecl(p); 635 if (!Param->hasDefaultArg()) { 636 if (Param->isInvalidDecl()) 637 /* We already complained about this parameter. */; 638 else if (Param->getIdentifier()) 639 Diag(Param->getLocation(), 640 diag::err_param_default_argument_missing_name) 641 << Param->getIdentifier(); 642 else 643 Diag(Param->getLocation(), 644 diag::err_param_default_argument_missing); 645 646 LastMissingDefaultArg = p; 647 } 648 } 649 650 if (LastMissingDefaultArg > 0) { 651 // Some default arguments were missing. Clear out all of the 652 // default arguments up to (and including) the last missing 653 // default argument, so that we leave the function parameters 654 // in a semantically valid state. 655 for (p = 0; p <= LastMissingDefaultArg; ++p) { 656 ParmVarDecl *Param = FD->getParamDecl(p); 657 if (Param->hasDefaultArg()) { 658 Param->setDefaultArg(0); 659 } 660 } 661 } 662} 663 664// CheckConstexprParameterTypes - Check whether a function's parameter types 665// are all literal types. If so, return true. If not, produce a suitable 666// diagnostic and return false. 667static bool CheckConstexprParameterTypes(Sema &SemaRef, 668 const FunctionDecl *FD) { 669 unsigned ArgIndex = 0; 670 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 671 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(), 672 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) { 673 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 674 SourceLocation ParamLoc = PD->getLocation(); 675 if (!(*i)->isDependentType() && 676 SemaRef.RequireLiteralType(ParamLoc, *i, 677 diag::err_constexpr_non_literal_param, 678 ArgIndex+1, PD->getSourceRange(), 679 isa<CXXConstructorDecl>(FD))) 680 return false; 681 } 682 return true; 683} 684 685/// \brief Get diagnostic %select index for tag kind for 686/// record diagnostic message. 687/// WARNING: Indexes apply to particular diagnostics only! 688/// 689/// \returns diagnostic %select index. 690static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 691 switch (Tag) { 692 case TTK_Struct: return 0; 693 case TTK_Interface: return 1; 694 case TTK_Class: return 2; 695 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 696 } 697} 698 699// CheckConstexprFunctionDecl - Check whether a function declaration satisfies 700// the requirements of a constexpr function definition or a constexpr 701// constructor definition. If so, return true. If not, produce appropriate 702// diagnostics and return false. 703// 704// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 705bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) { 706 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 707 if (MD && MD->isInstance()) { 708 // C++11 [dcl.constexpr]p4: 709 // The definition of a constexpr constructor shall satisfy the following 710 // constraints: 711 // - the class shall not have any virtual base classes; 712 const CXXRecordDecl *RD = MD->getParent(); 713 if (RD->getNumVBases()) { 714 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 715 << isa<CXXConstructorDecl>(NewFD) 716 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 717 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(), 718 E = RD->vbases_end(); I != E; ++I) 719 Diag(I->getLocStart(), 720 diag::note_constexpr_virtual_base_here) << I->getSourceRange(); 721 return false; 722 } 723 } 724 725 if (!isa<CXXConstructorDecl>(NewFD)) { 726 // C++11 [dcl.constexpr]p3: 727 // The definition of a constexpr function shall satisfy the following 728 // constraints: 729 // - it shall not be virtual; 730 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 731 if (Method && Method->isVirtual()) { 732 Diag(NewFD->getLocation(), diag::err_constexpr_virtual); 733 734 // If it's not obvious why this function is virtual, find an overridden 735 // function which uses the 'virtual' keyword. 736 const CXXMethodDecl *WrittenVirtual = Method; 737 while (!WrittenVirtual->isVirtualAsWritten()) 738 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 739 if (WrittenVirtual != Method) 740 Diag(WrittenVirtual->getLocation(), 741 diag::note_overridden_virtual_function); 742 return false; 743 } 744 745 // - its return type shall be a literal type; 746 QualType RT = NewFD->getResultType(); 747 if (!RT->isDependentType() && 748 RequireLiteralType(NewFD->getLocation(), RT, 749 diag::err_constexpr_non_literal_return)) 750 return false; 751 } 752 753 // - each of its parameter types shall be a literal type; 754 if (!CheckConstexprParameterTypes(*this, NewFD)) 755 return false; 756 757 return true; 758} 759 760/// Check the given declaration statement is legal within a constexpr function 761/// body. C++0x [dcl.constexpr]p3,p4. 762/// 763/// \return true if the body is OK, false if we have diagnosed a problem. 764static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 765 DeclStmt *DS) { 766 // C++0x [dcl.constexpr]p3 and p4: 767 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 768 // contain only 769 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(), 770 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) { 771 switch ((*DclIt)->getKind()) { 772 case Decl::StaticAssert: 773 case Decl::Using: 774 case Decl::UsingShadow: 775 case Decl::UsingDirective: 776 case Decl::UnresolvedUsingTypename: 777 // - static_assert-declarations 778 // - using-declarations, 779 // - using-directives, 780 continue; 781 782 case Decl::Typedef: 783 case Decl::TypeAlias: { 784 // - typedef declarations and alias-declarations that do not define 785 // classes or enumerations, 786 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt); 787 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 788 // Don't allow variably-modified types in constexpr functions. 789 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 790 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 791 << TL.getSourceRange() << TL.getType() 792 << isa<CXXConstructorDecl>(Dcl); 793 return false; 794 } 795 continue; 796 } 797 798 case Decl::Enum: 799 case Decl::CXXRecord: 800 // As an extension, we allow the declaration (but not the definition) of 801 // classes and enumerations in all declarations, not just in typedef and 802 // alias declarations. 803 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) { 804 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition) 805 << isa<CXXConstructorDecl>(Dcl); 806 return false; 807 } 808 continue; 809 810 case Decl::Var: 811 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration) 812 << isa<CXXConstructorDecl>(Dcl); 813 return false; 814 815 default: 816 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt) 817 << isa<CXXConstructorDecl>(Dcl); 818 return false; 819 } 820 } 821 822 return true; 823} 824 825/// Check that the given field is initialized within a constexpr constructor. 826/// 827/// \param Dcl The constexpr constructor being checked. 828/// \param Field The field being checked. This may be a member of an anonymous 829/// struct or union nested within the class being checked. 830/// \param Inits All declarations, including anonymous struct/union members and 831/// indirect members, for which any initialization was provided. 832/// \param Diagnosed Set to true if an error is produced. 833static void CheckConstexprCtorInitializer(Sema &SemaRef, 834 const FunctionDecl *Dcl, 835 FieldDecl *Field, 836 llvm::SmallSet<Decl*, 16> &Inits, 837 bool &Diagnosed) { 838 if (Field->isUnnamedBitfield()) 839 return; 840 841 if (Field->isAnonymousStructOrUnion() && 842 Field->getType()->getAsCXXRecordDecl()->isEmpty()) 843 return; 844 845 if (!Inits.count(Field)) { 846 if (!Diagnosed) { 847 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init); 848 Diagnosed = true; 849 } 850 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init); 851 } else if (Field->isAnonymousStructOrUnion()) { 852 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 853 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end(); 854 I != E; ++I) 855 // If an anonymous union contains an anonymous struct of which any member 856 // is initialized, all members must be initialized. 857 if (!RD->isUnion() || Inits.count(*I)) 858 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed); 859 } 860} 861 862/// Check the body for the given constexpr function declaration only contains 863/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 864/// 865/// \return true if the body is OK, false if we have diagnosed a problem. 866bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) { 867 if (isa<CXXTryStmt>(Body)) { 868 // C++11 [dcl.constexpr]p3: 869 // The definition of a constexpr function shall satisfy the following 870 // constraints: [...] 871 // - its function-body shall be = delete, = default, or a 872 // compound-statement 873 // 874 // C++11 [dcl.constexpr]p4: 875 // In the definition of a constexpr constructor, [...] 876 // - its function-body shall not be a function-try-block; 877 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block) 878 << isa<CXXConstructorDecl>(Dcl); 879 return false; 880 } 881 882 // - its function-body shall be [...] a compound-statement that contains only 883 CompoundStmt *CompBody = cast<CompoundStmt>(Body); 884 885 llvm::SmallVector<SourceLocation, 4> ReturnStmts; 886 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(), 887 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) { 888 switch ((*BodyIt)->getStmtClass()) { 889 case Stmt::NullStmtClass: 890 // - null statements, 891 continue; 892 893 case Stmt::DeclStmtClass: 894 // - static_assert-declarations 895 // - using-declarations, 896 // - using-directives, 897 // - typedef declarations and alias-declarations that do not define 898 // classes or enumerations, 899 if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt))) 900 return false; 901 continue; 902 903 case Stmt::ReturnStmtClass: 904 // - and exactly one return statement; 905 if (isa<CXXConstructorDecl>(Dcl)) 906 break; 907 908 ReturnStmts.push_back((*BodyIt)->getLocStart()); 909 continue; 910 911 default: 912 break; 913 } 914 915 Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt) 916 << isa<CXXConstructorDecl>(Dcl); 917 return false; 918 } 919 920 if (const CXXConstructorDecl *Constructor 921 = dyn_cast<CXXConstructorDecl>(Dcl)) { 922 const CXXRecordDecl *RD = Constructor->getParent(); 923 // DR1359: 924 // - every non-variant non-static data member and base class sub-object 925 // shall be initialized; 926 // - if the class is a non-empty union, or for each non-empty anonymous 927 // union member of a non-union class, exactly one non-static data member 928 // shall be initialized; 929 if (RD->isUnion()) { 930 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) { 931 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init); 932 return false; 933 } 934 } else if (!Constructor->isDependentContext() && 935 !Constructor->isDelegatingConstructor()) { 936 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 937 938 // Skip detailed checking if we have enough initializers, and we would 939 // allow at most one initializer per member. 940 bool AnyAnonStructUnionMembers = false; 941 unsigned Fields = 0; 942 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 943 E = RD->field_end(); I != E; ++I, ++Fields) { 944 if (I->isAnonymousStructOrUnion()) { 945 AnyAnonStructUnionMembers = true; 946 break; 947 } 948 } 949 if (AnyAnonStructUnionMembers || 950 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 951 // Check initialization of non-static data members. Base classes are 952 // always initialized so do not need to be checked. Dependent bases 953 // might not have initializers in the member initializer list. 954 llvm::SmallSet<Decl*, 16> Inits; 955 for (CXXConstructorDecl::init_const_iterator 956 I = Constructor->init_begin(), E = Constructor->init_end(); 957 I != E; ++I) { 958 if (FieldDecl *FD = (*I)->getMember()) 959 Inits.insert(FD); 960 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember()) 961 Inits.insert(ID->chain_begin(), ID->chain_end()); 962 } 963 964 bool Diagnosed = false; 965 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 966 E = RD->field_end(); I != E; ++I) 967 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed); 968 if (Diagnosed) 969 return false; 970 } 971 } 972 } else { 973 if (ReturnStmts.empty()) { 974 Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return); 975 return false; 976 } 977 if (ReturnStmts.size() > 1) { 978 Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return); 979 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 980 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return); 981 return false; 982 } 983 } 984 985 // C++11 [dcl.constexpr]p5: 986 // if no function argument values exist such that the function invocation 987 // substitution would produce a constant expression, the program is 988 // ill-formed; no diagnostic required. 989 // C++11 [dcl.constexpr]p3: 990 // - every constructor call and implicit conversion used in initializing the 991 // return value shall be one of those allowed in a constant expression. 992 // C++11 [dcl.constexpr]p4: 993 // - every constructor involved in initializing non-static data members and 994 // base class sub-objects shall be a constexpr constructor. 995 llvm::SmallVector<PartialDiagnosticAt, 8> Diags; 996 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) { 997 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr) 998 << isa<CXXConstructorDecl>(Dcl); 999 for (size_t I = 0, N = Diags.size(); I != N; ++I) 1000 Diag(Diags[I].first, Diags[I].second); 1001 // Don't return false here: we allow this for compatibility in 1002 // system headers. 1003 } 1004 1005 return true; 1006} 1007 1008/// isCurrentClassName - Determine whether the identifier II is the 1009/// name of the class type currently being defined. In the case of 1010/// nested classes, this will only return true if II is the name of 1011/// the innermost class. 1012bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 1013 const CXXScopeSpec *SS) { 1014 assert(getLangOpts().CPlusPlus && "No class names in C!"); 1015 1016 CXXRecordDecl *CurDecl; 1017 if (SS && SS->isSet() && !SS->isInvalid()) { 1018 DeclContext *DC = computeDeclContext(*SS, true); 1019 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 1020 } else 1021 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1022 1023 if (CurDecl && CurDecl->getIdentifier()) 1024 return &II == CurDecl->getIdentifier(); 1025 else 1026 return false; 1027} 1028 1029/// \brief Determine whether the given class is a base class of the given 1030/// class, including looking at dependent bases. 1031static bool findCircularInheritance(const CXXRecordDecl *Class, 1032 const CXXRecordDecl *Current) { 1033 SmallVector<const CXXRecordDecl*, 8> Queue; 1034 1035 Class = Class->getCanonicalDecl(); 1036 while (true) { 1037 for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(), 1038 E = Current->bases_end(); 1039 I != E; ++I) { 1040 CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 1041 if (!Base) 1042 continue; 1043 1044 Base = Base->getDefinition(); 1045 if (!Base) 1046 continue; 1047 1048 if (Base->getCanonicalDecl() == Class) 1049 return true; 1050 1051 Queue.push_back(Base); 1052 } 1053 1054 if (Queue.empty()) 1055 return false; 1056 1057 Current = Queue.back(); 1058 Queue.pop_back(); 1059 } 1060 1061 return false; 1062} 1063 1064/// \brief Check the validity of a C++ base class specifier. 1065/// 1066/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 1067/// and returns NULL otherwise. 1068CXXBaseSpecifier * 1069Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 1070 SourceRange SpecifierRange, 1071 bool Virtual, AccessSpecifier Access, 1072 TypeSourceInfo *TInfo, 1073 SourceLocation EllipsisLoc) { 1074 QualType BaseType = TInfo->getType(); 1075 1076 // C++ [class.union]p1: 1077 // A union shall not have base classes. 1078 if (Class->isUnion()) { 1079 Diag(Class->getLocation(), diag::err_base_clause_on_union) 1080 << SpecifierRange; 1081 return 0; 1082 } 1083 1084 if (EllipsisLoc.isValid() && 1085 !TInfo->getType()->containsUnexpandedParameterPack()) { 1086 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 1087 << TInfo->getTypeLoc().getSourceRange(); 1088 EllipsisLoc = SourceLocation(); 1089 } 1090 1091 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 1092 1093 if (BaseType->isDependentType()) { 1094 // Make sure that we don't have circular inheritance among our dependent 1095 // bases. For non-dependent bases, the check for completeness below handles 1096 // this. 1097 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 1098 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 1099 ((BaseDecl = BaseDecl->getDefinition()) && 1100 findCircularInheritance(Class, BaseDecl))) { 1101 Diag(BaseLoc, diag::err_circular_inheritance) 1102 << BaseType << Context.getTypeDeclType(Class); 1103 1104 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 1105 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 1106 << BaseType; 1107 1108 return 0; 1109 } 1110 } 1111 1112 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1113 Class->getTagKind() == TTK_Class, 1114 Access, TInfo, EllipsisLoc); 1115 } 1116 1117 // Base specifiers must be record types. 1118 if (!BaseType->isRecordType()) { 1119 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 1120 return 0; 1121 } 1122 1123 // C++ [class.union]p1: 1124 // A union shall not be used as a base class. 1125 if (BaseType->isUnionType()) { 1126 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 1127 return 0; 1128 } 1129 1130 // C++ [class.derived]p2: 1131 // The class-name in a base-specifier shall not be an incompletely 1132 // defined class. 1133 if (RequireCompleteType(BaseLoc, BaseType, 1134 diag::err_incomplete_base_class, SpecifierRange)) { 1135 Class->setInvalidDecl(); 1136 return 0; 1137 } 1138 1139 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 1140 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 1141 assert(BaseDecl && "Record type has no declaration"); 1142 BaseDecl = BaseDecl->getDefinition(); 1143 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 1144 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 1145 assert(CXXBaseDecl && "Base type is not a C++ type"); 1146 1147 // C++ [class]p3: 1148 // If a class is marked final and it appears as a base-type-specifier in 1149 // base-clause, the program is ill-formed. 1150 if (CXXBaseDecl->hasAttr<FinalAttr>()) { 1151 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 1152 << CXXBaseDecl->getDeclName(); 1153 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl) 1154 << CXXBaseDecl->getDeclName(); 1155 return 0; 1156 } 1157 1158 if (BaseDecl->isInvalidDecl()) 1159 Class->setInvalidDecl(); 1160 1161 // Create the base specifier. 1162 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1163 Class->getTagKind() == TTK_Class, 1164 Access, TInfo, EllipsisLoc); 1165} 1166 1167/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 1168/// one entry in the base class list of a class specifier, for 1169/// example: 1170/// class foo : public bar, virtual private baz { 1171/// 'public bar' and 'virtual private baz' are each base-specifiers. 1172BaseResult 1173Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 1174 bool Virtual, AccessSpecifier Access, 1175 ParsedType basetype, SourceLocation BaseLoc, 1176 SourceLocation EllipsisLoc) { 1177 if (!classdecl) 1178 return true; 1179 1180 AdjustDeclIfTemplate(classdecl); 1181 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 1182 if (!Class) 1183 return true; 1184 1185 TypeSourceInfo *TInfo = 0; 1186 GetTypeFromParser(basetype, &TInfo); 1187 1188 if (EllipsisLoc.isInvalid() && 1189 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 1190 UPPC_BaseType)) 1191 return true; 1192 1193 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 1194 Virtual, Access, TInfo, 1195 EllipsisLoc)) 1196 return BaseSpec; 1197 else 1198 Class->setInvalidDecl(); 1199 1200 return true; 1201} 1202 1203/// \brief Performs the actual work of attaching the given base class 1204/// specifiers to a C++ class. 1205bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 1206 unsigned NumBases) { 1207 if (NumBases == 0) 1208 return false; 1209 1210 // Used to keep track of which base types we have already seen, so 1211 // that we can properly diagnose redundant direct base types. Note 1212 // that the key is always the unqualified canonical type of the base 1213 // class. 1214 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 1215 1216 // Copy non-redundant base specifiers into permanent storage. 1217 unsigned NumGoodBases = 0; 1218 bool Invalid = false; 1219 for (unsigned idx = 0; idx < NumBases; ++idx) { 1220 QualType NewBaseType 1221 = Context.getCanonicalType(Bases[idx]->getType()); 1222 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 1223 1224 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 1225 if (KnownBase) { 1226 // C++ [class.mi]p3: 1227 // A class shall not be specified as a direct base class of a 1228 // derived class more than once. 1229 Diag(Bases[idx]->getLocStart(), 1230 diag::err_duplicate_base_class) 1231 << KnownBase->getType() 1232 << Bases[idx]->getSourceRange(); 1233 1234 // Delete the duplicate base class specifier; we're going to 1235 // overwrite its pointer later. 1236 Context.Deallocate(Bases[idx]); 1237 1238 Invalid = true; 1239 } else { 1240 // Okay, add this new base class. 1241 KnownBase = Bases[idx]; 1242 Bases[NumGoodBases++] = Bases[idx]; 1243 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 1244 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 1245 if (Class->isInterface() && 1246 (!RD->isInterface() || 1247 KnownBase->getAccessSpecifier() != AS_public)) { 1248 // The Microsoft extension __interface does not permit bases that 1249 // are not themselves public interfaces. 1250 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface) 1251 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName() 1252 << RD->getSourceRange(); 1253 Invalid = true; 1254 } 1255 if (RD->hasAttr<WeakAttr>()) 1256 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context)); 1257 } 1258 } 1259 } 1260 1261 // Attach the remaining base class specifiers to the derived class. 1262 Class->setBases(Bases, NumGoodBases); 1263 1264 // Delete the remaining (good) base class specifiers, since their 1265 // data has been copied into the CXXRecordDecl. 1266 for (unsigned idx = 0; idx < NumGoodBases; ++idx) 1267 Context.Deallocate(Bases[idx]); 1268 1269 return Invalid; 1270} 1271 1272/// ActOnBaseSpecifiers - Attach the given base specifiers to the 1273/// class, after checking whether there are any duplicate base 1274/// classes. 1275void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases, 1276 unsigned NumBases) { 1277 if (!ClassDecl || !Bases || !NumBases) 1278 return; 1279 1280 AdjustDeclIfTemplate(ClassDecl); 1281 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), 1282 (CXXBaseSpecifier**)(Bases), NumBases); 1283} 1284 1285static CXXRecordDecl *GetClassForType(QualType T) { 1286 if (const RecordType *RT = T->getAs<RecordType>()) 1287 return cast<CXXRecordDecl>(RT->getDecl()); 1288 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>()) 1289 return ICT->getDecl(); 1290 else 1291 return 0; 1292} 1293 1294/// \brief Determine whether the type \p Derived is a C++ class that is 1295/// derived from the type \p Base. 1296bool Sema::IsDerivedFrom(QualType Derived, QualType Base) { 1297 if (!getLangOpts().CPlusPlus) 1298 return false; 1299 1300 CXXRecordDecl *DerivedRD = GetClassForType(Derived); 1301 if (!DerivedRD) 1302 return false; 1303 1304 CXXRecordDecl *BaseRD = GetClassForType(Base); 1305 if (!BaseRD) 1306 return false; 1307 1308 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this. 1309 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD); 1310} 1311 1312/// \brief Determine whether the type \p Derived is a C++ class that is 1313/// derived from the type \p Base. 1314bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) { 1315 if (!getLangOpts().CPlusPlus) 1316 return false; 1317 1318 CXXRecordDecl *DerivedRD = GetClassForType(Derived); 1319 if (!DerivedRD) 1320 return false; 1321 1322 CXXRecordDecl *BaseRD = GetClassForType(Base); 1323 if (!BaseRD) 1324 return false; 1325 1326 return DerivedRD->isDerivedFrom(BaseRD, Paths); 1327} 1328 1329void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 1330 CXXCastPath &BasePathArray) { 1331 assert(BasePathArray.empty() && "Base path array must be empty!"); 1332 assert(Paths.isRecordingPaths() && "Must record paths!"); 1333 1334 const CXXBasePath &Path = Paths.front(); 1335 1336 // We first go backward and check if we have a virtual base. 1337 // FIXME: It would be better if CXXBasePath had the base specifier for 1338 // the nearest virtual base. 1339 unsigned Start = 0; 1340 for (unsigned I = Path.size(); I != 0; --I) { 1341 if (Path[I - 1].Base->isVirtual()) { 1342 Start = I - 1; 1343 break; 1344 } 1345 } 1346 1347 // Now add all bases. 1348 for (unsigned I = Start, E = Path.size(); I != E; ++I) 1349 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 1350} 1351 1352/// \brief Determine whether the given base path includes a virtual 1353/// base class. 1354bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) { 1355 for (CXXCastPath::const_iterator B = BasePath.begin(), 1356 BEnd = BasePath.end(); 1357 B != BEnd; ++B) 1358 if ((*B)->isVirtual()) 1359 return true; 1360 1361 return false; 1362} 1363 1364/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 1365/// conversion (where Derived and Base are class types) is 1366/// well-formed, meaning that the conversion is unambiguous (and 1367/// that all of the base classes are accessible). Returns true 1368/// and emits a diagnostic if the code is ill-formed, returns false 1369/// otherwise. Loc is the location where this routine should point to 1370/// if there is an error, and Range is the source range to highlight 1371/// if there is an error. 1372bool 1373Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1374 unsigned InaccessibleBaseID, 1375 unsigned AmbigiousBaseConvID, 1376 SourceLocation Loc, SourceRange Range, 1377 DeclarationName Name, 1378 CXXCastPath *BasePath) { 1379 // First, determine whether the path from Derived to Base is 1380 // ambiguous. This is slightly more expensive than checking whether 1381 // the Derived to Base conversion exists, because here we need to 1382 // explore multiple paths to determine if there is an ambiguity. 1383 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1384 /*DetectVirtual=*/false); 1385 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths); 1386 assert(DerivationOkay && 1387 "Can only be used with a derived-to-base conversion"); 1388 (void)DerivationOkay; 1389 1390 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 1391 if (InaccessibleBaseID) { 1392 // Check that the base class can be accessed. 1393 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(), 1394 InaccessibleBaseID)) { 1395 case AR_inaccessible: 1396 return true; 1397 case AR_accessible: 1398 case AR_dependent: 1399 case AR_delayed: 1400 break; 1401 } 1402 } 1403 1404 // Build a base path if necessary. 1405 if (BasePath) 1406 BuildBasePathArray(Paths, *BasePath); 1407 return false; 1408 } 1409 1410 // We know that the derived-to-base conversion is ambiguous, and 1411 // we're going to produce a diagnostic. Perform the derived-to-base 1412 // search just one more time to compute all of the possible paths so 1413 // that we can print them out. This is more expensive than any of 1414 // the previous derived-to-base checks we've done, but at this point 1415 // performance isn't as much of an issue. 1416 Paths.clear(); 1417 Paths.setRecordingPaths(true); 1418 bool StillOkay = IsDerivedFrom(Derived, Base, Paths); 1419 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 1420 (void)StillOkay; 1421 1422 // Build up a textual representation of the ambiguous paths, e.g., 1423 // D -> B -> A, that will be used to illustrate the ambiguous 1424 // conversions in the diagnostic. We only print one of the paths 1425 // to each base class subobject. 1426 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 1427 1428 Diag(Loc, AmbigiousBaseConvID) 1429 << Derived << Base << PathDisplayStr << Range << Name; 1430 return true; 1431} 1432 1433bool 1434Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1435 SourceLocation Loc, SourceRange Range, 1436 CXXCastPath *BasePath, 1437 bool IgnoreAccess) { 1438 return CheckDerivedToBaseConversion(Derived, Base, 1439 IgnoreAccess ? 0 1440 : diag::err_upcast_to_inaccessible_base, 1441 diag::err_ambiguous_derived_to_base_conv, 1442 Loc, Range, DeclarationName(), 1443 BasePath); 1444} 1445 1446 1447/// @brief Builds a string representing ambiguous paths from a 1448/// specific derived class to different subobjects of the same base 1449/// class. 1450/// 1451/// This function builds a string that can be used in error messages 1452/// to show the different paths that one can take through the 1453/// inheritance hierarchy to go from the derived class to different 1454/// subobjects of a base class. The result looks something like this: 1455/// @code 1456/// struct D -> struct B -> struct A 1457/// struct D -> struct C -> struct A 1458/// @endcode 1459std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 1460 std::string PathDisplayStr; 1461 std::set<unsigned> DisplayedPaths; 1462 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 1463 Path != Paths.end(); ++Path) { 1464 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 1465 // We haven't displayed a path to this particular base 1466 // class subobject yet. 1467 PathDisplayStr += "\n "; 1468 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 1469 for (CXXBasePath::const_iterator Element = Path->begin(); 1470 Element != Path->end(); ++Element) 1471 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 1472 } 1473 } 1474 1475 return PathDisplayStr; 1476} 1477 1478//===----------------------------------------------------------------------===// 1479// C++ class member Handling 1480//===----------------------------------------------------------------------===// 1481 1482/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 1483bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, 1484 SourceLocation ASLoc, 1485 SourceLocation ColonLoc, 1486 AttributeList *Attrs) { 1487 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 1488 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 1489 ASLoc, ColonLoc); 1490 CurContext->addHiddenDecl(ASDecl); 1491 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 1492} 1493 1494/// CheckOverrideControl - Check C++11 override control semantics. 1495void Sema::CheckOverrideControl(Decl *D) { 1496 if (D->isInvalidDecl()) 1497 return; 1498 1499 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 1500 1501 // Do we know which functions this declaration might be overriding? 1502 bool OverridesAreKnown = !MD || 1503 (!MD->getParent()->hasAnyDependentBases() && 1504 !MD->getType()->isDependentType()); 1505 1506 if (!MD || !MD->isVirtual()) { 1507 if (OverridesAreKnown) { 1508 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1509 Diag(OA->getLocation(), 1510 diag::override_keyword_only_allowed_on_virtual_member_functions) 1511 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 1512 D->dropAttr<OverrideAttr>(); 1513 } 1514 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1515 Diag(FA->getLocation(), 1516 diag::override_keyword_only_allowed_on_virtual_member_functions) 1517 << "final" << FixItHint::CreateRemoval(FA->getLocation()); 1518 D->dropAttr<FinalAttr>(); 1519 } 1520 } 1521 return; 1522 } 1523 1524 if (!OverridesAreKnown) 1525 return; 1526 1527 // C++11 [class.virtual]p5: 1528 // If a virtual function is marked with the virt-specifier override and 1529 // does not override a member function of a base class, the program is 1530 // ill-formed. 1531 bool HasOverriddenMethods = 1532 MD->begin_overridden_methods() != MD->end_overridden_methods(); 1533 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 1534 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 1535 << MD->getDeclName(); 1536} 1537 1538/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 1539/// function overrides a virtual member function marked 'final', according to 1540/// C++11 [class.virtual]p4. 1541bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 1542 const CXXMethodDecl *Old) { 1543 if (!Old->hasAttr<FinalAttr>()) 1544 return false; 1545 1546 Diag(New->getLocation(), diag::err_final_function_overridden) 1547 << New->getDeclName(); 1548 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 1549 return true; 1550} 1551 1552static bool InitializationHasSideEffects(const FieldDecl &FD) { 1553 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 1554 // FIXME: Destruction of ObjC lifetime types has side-effects. 1555 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 1556 return !RD->isCompleteDefinition() || 1557 !RD->hasTrivialDefaultConstructor() || 1558 !RD->hasTrivialDestructor(); 1559 return false; 1560} 1561 1562/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 1563/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 1564/// bitfield width if there is one, 'InitExpr' specifies the initializer if 1565/// one has been parsed, and 'InitStyle' is set if an in-class initializer is 1566/// present (but parsing it has been deferred). 1567Decl * 1568Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 1569 MultiTemplateParamsArg TemplateParameterLists, 1570 Expr *BW, const VirtSpecifiers &VS, 1571 InClassInitStyle InitStyle) { 1572 const DeclSpec &DS = D.getDeclSpec(); 1573 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 1574 DeclarationName Name = NameInfo.getName(); 1575 SourceLocation Loc = NameInfo.getLoc(); 1576 1577 // For anonymous bitfields, the location should point to the type. 1578 if (Loc.isInvalid()) 1579 Loc = D.getLocStart(); 1580 1581 Expr *BitWidth = static_cast<Expr*>(BW); 1582 1583 assert(isa<CXXRecordDecl>(CurContext)); 1584 assert(!DS.isFriendSpecified()); 1585 1586 bool isFunc = D.isDeclarationOfFunction(); 1587 1588 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 1589 // The Microsoft extension __interface only permits public member functions 1590 // and prohibits constructors, destructors, operators, non-public member 1591 // functions, static methods and data members. 1592 unsigned InvalidDecl; 1593 bool ShowDeclName = true; 1594 if (!isFunc) 1595 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1; 1596 else if (AS != AS_public) 1597 InvalidDecl = 2; 1598 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 1599 InvalidDecl = 3; 1600 else switch (Name.getNameKind()) { 1601 case DeclarationName::CXXConstructorName: 1602 InvalidDecl = 4; 1603 ShowDeclName = false; 1604 break; 1605 1606 case DeclarationName::CXXDestructorName: 1607 InvalidDecl = 5; 1608 ShowDeclName = false; 1609 break; 1610 1611 case DeclarationName::CXXOperatorName: 1612 case DeclarationName::CXXConversionFunctionName: 1613 InvalidDecl = 6; 1614 break; 1615 1616 default: 1617 InvalidDecl = 0; 1618 break; 1619 } 1620 1621 if (InvalidDecl) { 1622 if (ShowDeclName) 1623 Diag(Loc, diag::err_invalid_member_in_interface) 1624 << (InvalidDecl-1) << Name; 1625 else 1626 Diag(Loc, diag::err_invalid_member_in_interface) 1627 << (InvalidDecl-1) << ""; 1628 return 0; 1629 } 1630 } 1631 1632 // C++ 9.2p6: A member shall not be declared to have automatic storage 1633 // duration (auto, register) or with the extern storage-class-specifier. 1634 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 1635 // data members and cannot be applied to names declared const or static, 1636 // and cannot be applied to reference members. 1637 switch (DS.getStorageClassSpec()) { 1638 case DeclSpec::SCS_unspecified: 1639 case DeclSpec::SCS_typedef: 1640 case DeclSpec::SCS_static: 1641 // FALL THROUGH. 1642 break; 1643 case DeclSpec::SCS_mutable: 1644 if (isFunc) { 1645 if (DS.getStorageClassSpecLoc().isValid()) 1646 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 1647 else 1648 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function); 1649 1650 // FIXME: It would be nicer if the keyword was ignored only for this 1651 // declarator. Otherwise we could get follow-up errors. 1652 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1653 } 1654 break; 1655 default: 1656 if (DS.getStorageClassSpecLoc().isValid()) 1657 Diag(DS.getStorageClassSpecLoc(), 1658 diag::err_storageclass_invalid_for_member); 1659 else 1660 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member); 1661 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1662 } 1663 1664 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 1665 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 1666 !isFunc); 1667 1668 Decl *Member; 1669 if (isInstField) { 1670 CXXScopeSpec &SS = D.getCXXScopeSpec(); 1671 1672 // Data members must have identifiers for names. 1673 if (!Name.isIdentifier()) { 1674 Diag(Loc, diag::err_bad_variable_name) 1675 << Name; 1676 return 0; 1677 } 1678 1679 IdentifierInfo *II = Name.getAsIdentifierInfo(); 1680 1681 // Member field could not be with "template" keyword. 1682 // So TemplateParameterLists should be empty in this case. 1683 if (TemplateParameterLists.size()) { 1684 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 1685 if (TemplateParams->size()) { 1686 // There is no such thing as a member field template. 1687 Diag(D.getIdentifierLoc(), diag::err_template_member) 1688 << II 1689 << SourceRange(TemplateParams->getTemplateLoc(), 1690 TemplateParams->getRAngleLoc()); 1691 } else { 1692 // There is an extraneous 'template<>' for this member. 1693 Diag(TemplateParams->getTemplateLoc(), 1694 diag::err_template_member_noparams) 1695 << II 1696 << SourceRange(TemplateParams->getTemplateLoc(), 1697 TemplateParams->getRAngleLoc()); 1698 } 1699 return 0; 1700 } 1701 1702 if (SS.isSet() && !SS.isInvalid()) { 1703 // The user provided a superfluous scope specifier inside a class 1704 // definition: 1705 // 1706 // class X { 1707 // int X::member; 1708 // }; 1709 if (DeclContext *DC = computeDeclContext(SS, false)) 1710 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc()); 1711 else 1712 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 1713 << Name << SS.getRange(); 1714 1715 SS.clear(); 1716 } 1717 1718 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth, 1719 InitStyle, AS); 1720 assert(Member && "HandleField never returns null"); 1721 } else { 1722 assert(InitStyle == ICIS_NoInit); 1723 1724 Member = HandleDeclarator(S, D, TemplateParameterLists); 1725 if (!Member) { 1726 return 0; 1727 } 1728 1729 // Non-instance-fields can't have a bitfield. 1730 if (BitWidth) { 1731 if (Member->isInvalidDecl()) { 1732 // don't emit another diagnostic. 1733 } else if (isa<VarDecl>(Member)) { 1734 // C++ 9.6p3: A bit-field shall not be a static member. 1735 // "static member 'A' cannot be a bit-field" 1736 Diag(Loc, diag::err_static_not_bitfield) 1737 << Name << BitWidth->getSourceRange(); 1738 } else if (isa<TypedefDecl>(Member)) { 1739 // "typedef member 'x' cannot be a bit-field" 1740 Diag(Loc, diag::err_typedef_not_bitfield) 1741 << Name << BitWidth->getSourceRange(); 1742 } else { 1743 // A function typedef ("typedef int f(); f a;"). 1744 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 1745 Diag(Loc, diag::err_not_integral_type_bitfield) 1746 << Name << cast<ValueDecl>(Member)->getType() 1747 << BitWidth->getSourceRange(); 1748 } 1749 1750 BitWidth = 0; 1751 Member->setInvalidDecl(); 1752 } 1753 1754 Member->setAccess(AS); 1755 1756 // If we have declared a member function template, set the access of the 1757 // templated declaration as well. 1758 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 1759 FunTmpl->getTemplatedDecl()->setAccess(AS); 1760 } 1761 1762 if (VS.isOverrideSpecified()) 1763 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context)); 1764 if (VS.isFinalSpecified()) 1765 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context)); 1766 1767 if (VS.getLastLocation().isValid()) { 1768 // Update the end location of a method that has a virt-specifiers. 1769 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 1770 MD->setRangeEnd(VS.getLastLocation()); 1771 } 1772 1773 CheckOverrideControl(Member); 1774 1775 assert((Name || isInstField) && "No identifier for non-field ?"); 1776 1777 if (isInstField) { 1778 FieldDecl *FD = cast<FieldDecl>(Member); 1779 FieldCollector->Add(FD); 1780 1781 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field, 1782 FD->getLocation()) 1783 != DiagnosticsEngine::Ignored) { 1784 // Remember all explicit private FieldDecls that have a name, no side 1785 // effects and are not part of a dependent type declaration. 1786 if (!FD->isImplicit() && FD->getDeclName() && 1787 FD->getAccess() == AS_private && 1788 !FD->hasAttr<UnusedAttr>() && 1789 !FD->getParent()->isDependentContext() && 1790 !InitializationHasSideEffects(*FD)) 1791 UnusedPrivateFields.insert(FD); 1792 } 1793 } 1794 1795 return Member; 1796} 1797 1798namespace { 1799 class UninitializedFieldVisitor 1800 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 1801 Sema &S; 1802 ValueDecl *VD; 1803 public: 1804 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 1805 UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context), 1806 S(S) { 1807 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD)) 1808 this->VD = IFD->getAnonField(); 1809 else 1810 this->VD = VD; 1811 } 1812 1813 void HandleExpr(Expr *E) { 1814 if (!E) return; 1815 1816 // Expressions like x(x) sometimes lack the surrounding expressions 1817 // but need to be checked anyways. 1818 HandleValue(E); 1819 Visit(E); 1820 } 1821 1822 void HandleValue(Expr *E) { 1823 E = E->IgnoreParens(); 1824 1825 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 1826 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 1827 return; 1828 1829 // FieldME is the inner-most MemberExpr that is not an anonymous struct 1830 // or union. 1831 MemberExpr *FieldME = ME; 1832 1833 Expr *Base = E; 1834 while (isa<MemberExpr>(Base)) { 1835 ME = cast<MemberExpr>(Base); 1836 1837 if (isa<VarDecl>(ME->getMemberDecl())) 1838 return; 1839 1840 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 1841 if (!FD->isAnonymousStructOrUnion()) 1842 FieldME = ME; 1843 1844 Base = ME->getBase(); 1845 } 1846 1847 if (VD == FieldME->getMemberDecl() && isa<CXXThisExpr>(Base)) { 1848 unsigned diag = VD->getType()->isReferenceType() 1849 ? diag::warn_reference_field_is_uninit 1850 : diag::warn_field_is_uninit; 1851 S.Diag(FieldME->getExprLoc(), diag) << VD; 1852 } 1853 return; 1854 } 1855 1856 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 1857 HandleValue(CO->getTrueExpr()); 1858 HandleValue(CO->getFalseExpr()); 1859 return; 1860 } 1861 1862 if (BinaryConditionalOperator *BCO = 1863 dyn_cast<BinaryConditionalOperator>(E)) { 1864 HandleValue(BCO->getCommon()); 1865 HandleValue(BCO->getFalseExpr()); 1866 return; 1867 } 1868 1869 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 1870 switch (BO->getOpcode()) { 1871 default: 1872 return; 1873 case(BO_PtrMemD): 1874 case(BO_PtrMemI): 1875 HandleValue(BO->getLHS()); 1876 return; 1877 case(BO_Comma): 1878 HandleValue(BO->getRHS()); 1879 return; 1880 } 1881 } 1882 } 1883 1884 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 1885 if (E->getCastKind() == CK_LValueToRValue) 1886 HandleValue(E->getSubExpr()); 1887 1888 Inherited::VisitImplicitCastExpr(E); 1889 } 1890 1891 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 1892 Expr *Callee = E->getCallee(); 1893 if (isa<MemberExpr>(Callee)) 1894 HandleValue(Callee); 1895 1896 Inherited::VisitCXXMemberCallExpr(E); 1897 } 1898 }; 1899 static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E, 1900 ValueDecl *VD) { 1901 UninitializedFieldVisitor(S, VD).HandleExpr(E); 1902 } 1903} // namespace 1904 1905/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an 1906/// in-class initializer for a non-static C++ class member, and after 1907/// instantiating an in-class initializer in a class template. Such actions 1908/// are deferred until the class is complete. 1909void 1910Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc, 1911 Expr *InitExpr) { 1912 FieldDecl *FD = cast<FieldDecl>(D); 1913 assert(FD->getInClassInitStyle() != ICIS_NoInit && 1914 "must set init style when field is created"); 1915 1916 if (!InitExpr) { 1917 FD->setInvalidDecl(); 1918 FD->removeInClassInitializer(); 1919 return; 1920 } 1921 1922 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 1923 FD->setInvalidDecl(); 1924 FD->removeInClassInitializer(); 1925 return; 1926 } 1927 1928 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, InitLoc) 1929 != DiagnosticsEngine::Ignored) { 1930 CheckInitExprContainsUninitializedFields(*this, InitExpr, FD); 1931 } 1932 1933 ExprResult Init = InitExpr; 1934 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent() && 1935 !FD->getDeclContext()->isDependentContext()) { 1936 // Note: We don't type-check when we're in a dependent context, because 1937 // the initialization-substitution code does not properly handle direct 1938 // list initialization. We have the same hackaround for ctor-initializers. 1939 if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) { 1940 Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list) 1941 << /*at end of ctor*/1 << InitExpr->getSourceRange(); 1942 } 1943 Expr **Inits = &InitExpr; 1944 unsigned NumInits = 1; 1945 InitializedEntity Entity = InitializedEntity::InitializeMember(FD); 1946 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit 1947 ? InitializationKind::CreateDirectList(InitExpr->getLocStart()) 1948 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc); 1949 InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits); 1950 Init = Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits)); 1951 if (Init.isInvalid()) { 1952 FD->setInvalidDecl(); 1953 return; 1954 } 1955 1956 CheckImplicitConversions(Init.get(), InitLoc); 1957 } 1958 1959 // C++0x [class.base.init]p7: 1960 // The initialization of each base and member constitutes a 1961 // full-expression. 1962 Init = MaybeCreateExprWithCleanups(Init); 1963 if (Init.isInvalid()) { 1964 FD->setInvalidDecl(); 1965 return; 1966 } 1967 1968 InitExpr = Init.release(); 1969 1970 FD->setInClassInitializer(InitExpr); 1971} 1972 1973/// \brief Find the direct and/or virtual base specifiers that 1974/// correspond to the given base type, for use in base initialization 1975/// within a constructor. 1976static bool FindBaseInitializer(Sema &SemaRef, 1977 CXXRecordDecl *ClassDecl, 1978 QualType BaseType, 1979 const CXXBaseSpecifier *&DirectBaseSpec, 1980 const CXXBaseSpecifier *&VirtualBaseSpec) { 1981 // First, check for a direct base class. 1982 DirectBaseSpec = 0; 1983 for (CXXRecordDecl::base_class_const_iterator Base 1984 = ClassDecl->bases_begin(); 1985 Base != ClassDecl->bases_end(); ++Base) { 1986 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) { 1987 // We found a direct base of this type. That's what we're 1988 // initializing. 1989 DirectBaseSpec = &*Base; 1990 break; 1991 } 1992 } 1993 1994 // Check for a virtual base class. 1995 // FIXME: We might be able to short-circuit this if we know in advance that 1996 // there are no virtual bases. 1997 VirtualBaseSpec = 0; 1998 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 1999 // We haven't found a base yet; search the class hierarchy for a 2000 // virtual base class. 2001 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2002 /*DetectVirtual=*/false); 2003 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl), 2004 BaseType, Paths)) { 2005 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2006 Path != Paths.end(); ++Path) { 2007 if (Path->back().Base->isVirtual()) { 2008 VirtualBaseSpec = Path->back().Base; 2009 break; 2010 } 2011 } 2012 } 2013 } 2014 2015 return DirectBaseSpec || VirtualBaseSpec; 2016} 2017 2018/// \brief Handle a C++ member initializer using braced-init-list syntax. 2019MemInitResult 2020Sema::ActOnMemInitializer(Decl *ConstructorD, 2021 Scope *S, 2022 CXXScopeSpec &SS, 2023 IdentifierInfo *MemberOrBase, 2024 ParsedType TemplateTypeTy, 2025 const DeclSpec &DS, 2026 SourceLocation IdLoc, 2027 Expr *InitList, 2028 SourceLocation EllipsisLoc) { 2029 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2030 DS, IdLoc, InitList, 2031 EllipsisLoc); 2032} 2033 2034/// \brief Handle a C++ member initializer using parentheses syntax. 2035MemInitResult 2036Sema::ActOnMemInitializer(Decl *ConstructorD, 2037 Scope *S, 2038 CXXScopeSpec &SS, 2039 IdentifierInfo *MemberOrBase, 2040 ParsedType TemplateTypeTy, 2041 const DeclSpec &DS, 2042 SourceLocation IdLoc, 2043 SourceLocation LParenLoc, 2044 Expr **Args, unsigned NumArgs, 2045 SourceLocation RParenLoc, 2046 SourceLocation EllipsisLoc) { 2047 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, 2048 llvm::makeArrayRef(Args, NumArgs), 2049 RParenLoc); 2050 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2051 DS, IdLoc, List, EllipsisLoc); 2052} 2053 2054namespace { 2055 2056// Callback to only accept typo corrections that can be a valid C++ member 2057// intializer: either a non-static field member or a base class. 2058class MemInitializerValidatorCCC : public CorrectionCandidateCallback { 2059 public: 2060 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 2061 : ClassDecl(ClassDecl) {} 2062 2063 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 2064 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 2065 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 2066 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 2067 else 2068 return isa<TypeDecl>(ND); 2069 } 2070 return false; 2071 } 2072 2073 private: 2074 CXXRecordDecl *ClassDecl; 2075}; 2076 2077} 2078 2079/// \brief Handle a C++ member initializer. 2080MemInitResult 2081Sema::BuildMemInitializer(Decl *ConstructorD, 2082 Scope *S, 2083 CXXScopeSpec &SS, 2084 IdentifierInfo *MemberOrBase, 2085 ParsedType TemplateTypeTy, 2086 const DeclSpec &DS, 2087 SourceLocation IdLoc, 2088 Expr *Init, 2089 SourceLocation EllipsisLoc) { 2090 if (!ConstructorD) 2091 return true; 2092 2093 AdjustDeclIfTemplate(ConstructorD); 2094 2095 CXXConstructorDecl *Constructor 2096 = dyn_cast<CXXConstructorDecl>(ConstructorD); 2097 if (!Constructor) { 2098 // The user wrote a constructor initializer on a function that is 2099 // not a C++ constructor. Ignore the error for now, because we may 2100 // have more member initializers coming; we'll diagnose it just 2101 // once in ActOnMemInitializers. 2102 return true; 2103 } 2104 2105 CXXRecordDecl *ClassDecl = Constructor->getParent(); 2106 2107 // C++ [class.base.init]p2: 2108 // Names in a mem-initializer-id are looked up in the scope of the 2109 // constructor's class and, if not found in that scope, are looked 2110 // up in the scope containing the constructor's definition. 2111 // [Note: if the constructor's class contains a member with the 2112 // same name as a direct or virtual base class of the class, a 2113 // mem-initializer-id naming the member or base class and composed 2114 // of a single identifier refers to the class member. A 2115 // mem-initializer-id for the hidden base class may be specified 2116 // using a qualified name. ] 2117 if (!SS.getScopeRep() && !TemplateTypeTy) { 2118 // Look for a member, first. 2119 DeclContext::lookup_result Result 2120 = ClassDecl->lookup(MemberOrBase); 2121 if (Result.first != Result.second) { 2122 ValueDecl *Member; 2123 if ((Member = dyn_cast<FieldDecl>(*Result.first)) || 2124 (Member = dyn_cast<IndirectFieldDecl>(*Result.first))) { 2125 if (EllipsisLoc.isValid()) 2126 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 2127 << MemberOrBase 2128 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 2129 2130 return BuildMemberInitializer(Member, Init, IdLoc); 2131 } 2132 } 2133 } 2134 // It didn't name a member, so see if it names a class. 2135 QualType BaseType; 2136 TypeSourceInfo *TInfo = 0; 2137 2138 if (TemplateTypeTy) { 2139 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 2140 } else if (DS.getTypeSpecType() == TST_decltype) { 2141 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 2142 } else { 2143 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 2144 LookupParsedName(R, S, &SS); 2145 2146 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 2147 if (!TyD) { 2148 if (R.isAmbiguous()) return true; 2149 2150 // We don't want access-control diagnostics here. 2151 R.suppressDiagnostics(); 2152 2153 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 2154 bool NotUnknownSpecialization = false; 2155 DeclContext *DC = computeDeclContext(SS, false); 2156 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 2157 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 2158 2159 if (!NotUnknownSpecialization) { 2160 // When the scope specifier can refer to a member of an unknown 2161 // specialization, we take it as a type name. 2162 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 2163 SS.getWithLocInContext(Context), 2164 *MemberOrBase, IdLoc); 2165 if (BaseType.isNull()) 2166 return true; 2167 2168 R.clear(); 2169 R.setLookupName(MemberOrBase); 2170 } 2171 } 2172 2173 // If no results were found, try to correct typos. 2174 TypoCorrection Corr; 2175 MemInitializerValidatorCCC Validator(ClassDecl); 2176 if (R.empty() && BaseType.isNull() && 2177 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 2178 Validator, ClassDecl))) { 2179 std::string CorrectedStr(Corr.getAsString(getLangOpts())); 2180 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts())); 2181 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 2182 // We have found a non-static data member with a similar 2183 // name to what was typed; complain and initialize that 2184 // member. 2185 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest) 2186 << MemberOrBase << true << CorrectedQuotedStr 2187 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr); 2188 Diag(Member->getLocation(), diag::note_previous_decl) 2189 << CorrectedQuotedStr; 2190 2191 return BuildMemberInitializer(Member, Init, IdLoc); 2192 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 2193 const CXXBaseSpecifier *DirectBaseSpec; 2194 const CXXBaseSpecifier *VirtualBaseSpec; 2195 if (FindBaseInitializer(*this, ClassDecl, 2196 Context.getTypeDeclType(Type), 2197 DirectBaseSpec, VirtualBaseSpec)) { 2198 // We have found a direct or virtual base class with a 2199 // similar name to what was typed; complain and initialize 2200 // that base class. 2201 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest) 2202 << MemberOrBase << false << CorrectedQuotedStr 2203 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr); 2204 2205 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec 2206 : VirtualBaseSpec; 2207 Diag(BaseSpec->getLocStart(), 2208 diag::note_base_class_specified_here) 2209 << BaseSpec->getType() 2210 << BaseSpec->getSourceRange(); 2211 2212 TyD = Type; 2213 } 2214 } 2215 } 2216 2217 if (!TyD && BaseType.isNull()) { 2218 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 2219 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 2220 return true; 2221 } 2222 } 2223 2224 if (BaseType.isNull()) { 2225 BaseType = Context.getTypeDeclType(TyD); 2226 if (SS.isSet()) { 2227 NestedNameSpecifier *Qualifier = 2228 static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 2229 2230 // FIXME: preserve source range information 2231 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType); 2232 } 2233 } 2234 } 2235 2236 if (!TInfo) 2237 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 2238 2239 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 2240} 2241 2242/// Checks a member initializer expression for cases where reference (or 2243/// pointer) members are bound to by-value parameters (or their addresses). 2244static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member, 2245 Expr *Init, 2246 SourceLocation IdLoc) { 2247 QualType MemberTy = Member->getType(); 2248 2249 // We only handle pointers and references currently. 2250 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers? 2251 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType()) 2252 return; 2253 2254 const bool IsPointer = MemberTy->isPointerType(); 2255 if (IsPointer) { 2256 if (const UnaryOperator *Op 2257 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) { 2258 // The only case we're worried about with pointers requires taking the 2259 // address. 2260 if (Op->getOpcode() != UO_AddrOf) 2261 return; 2262 2263 Init = Op->getSubExpr(); 2264 } else { 2265 // We only handle address-of expression initializers for pointers. 2266 return; 2267 } 2268 } 2269 2270 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) { 2271 // Taking the address of a temporary will be diagnosed as a hard error. 2272 if (IsPointer) 2273 return; 2274 2275 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary) 2276 << Member << Init->getSourceRange(); 2277 } else if (const DeclRefExpr *DRE 2278 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) { 2279 // We only warn when referring to a non-reference parameter declaration. 2280 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl()); 2281 if (!Parameter || Parameter->getType()->isReferenceType()) 2282 return; 2283 2284 S.Diag(Init->getExprLoc(), 2285 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr 2286 : diag::warn_bind_ref_member_to_parameter) 2287 << Member << Parameter << Init->getSourceRange(); 2288 } else { 2289 // Other initializers are fine. 2290 return; 2291 } 2292 2293 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here) 2294 << (unsigned)IsPointer; 2295} 2296 2297MemInitResult 2298Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 2299 SourceLocation IdLoc) { 2300 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 2301 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 2302 assert((DirectMember || IndirectMember) && 2303 "Member must be a FieldDecl or IndirectFieldDecl"); 2304 2305 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 2306 return true; 2307 2308 if (Member->isInvalidDecl()) 2309 return true; 2310 2311 // Diagnose value-uses of fields to initialize themselves, e.g. 2312 // foo(foo) 2313 // where foo is not also a parameter to the constructor. 2314 // TODO: implement -Wuninitialized and fold this into that framework. 2315 Expr **Args; 2316 unsigned NumArgs; 2317 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2318 Args = ParenList->getExprs(); 2319 NumArgs = ParenList->getNumExprs(); 2320 } else { 2321 InitListExpr *InitList = cast<InitListExpr>(Init); 2322 Args = InitList->getInits(); 2323 NumArgs = InitList->getNumInits(); 2324 } 2325 2326 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc) 2327 != DiagnosticsEngine::Ignored) 2328 for (unsigned i = 0; i < NumArgs; ++i) 2329 // FIXME: Warn about the case when other fields are used before being 2330 // initialized. For example, let this field be the i'th field. When 2331 // initializing the i'th field, throw a warning if any of the >= i'th 2332 // fields are used, as they are not yet initialized. 2333 // Right now we are only handling the case where the i'th field uses 2334 // itself in its initializer. 2335 // Also need to take into account that some fields may be initialized by 2336 // in-class initializers, see C++11 [class.base.init]p9. 2337 CheckInitExprContainsUninitializedFields(*this, Args[i], Member); 2338 2339 SourceRange InitRange = Init->getSourceRange(); 2340 2341 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 2342 // Can't check initialization for a member of dependent type or when 2343 // any of the arguments are type-dependent expressions. 2344 DiscardCleanupsInEvaluationContext(); 2345 } else { 2346 bool InitList = false; 2347 if (isa<InitListExpr>(Init)) { 2348 InitList = true; 2349 Args = &Init; 2350 NumArgs = 1; 2351 2352 if (isStdInitializerList(Member->getType(), 0)) { 2353 Diag(IdLoc, diag::warn_dangling_std_initializer_list) 2354 << /*at end of ctor*/1 << InitRange; 2355 } 2356 } 2357 2358 // Initialize the member. 2359 InitializedEntity MemberEntity = 2360 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0) 2361 : InitializedEntity::InitializeMember(IndirectMember, 0); 2362 InitializationKind Kind = 2363 InitList ? InitializationKind::CreateDirectList(IdLoc) 2364 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 2365 InitRange.getEnd()); 2366 2367 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs); 2368 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, 2369 MultiExprArg(Args, NumArgs), 2370 0); 2371 if (MemberInit.isInvalid()) 2372 return true; 2373 2374 CheckImplicitConversions(MemberInit.get(), 2375 InitRange.getBegin()); 2376 2377 // C++0x [class.base.init]p7: 2378 // The initialization of each base and member constitutes a 2379 // full-expression. 2380 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 2381 if (MemberInit.isInvalid()) 2382 return true; 2383 2384 // If we are in a dependent context, template instantiation will 2385 // perform this type-checking again. Just save the arguments that we 2386 // received. 2387 // FIXME: This isn't quite ideal, since our ASTs don't capture all 2388 // of the information that we have about the member 2389 // initializer. However, deconstructing the ASTs is a dicey process, 2390 // and this approach is far more likely to get the corner cases right. 2391 if (CurContext->isDependentContext()) { 2392 // The existing Init will do fine. 2393 } else { 2394 Init = MemberInit.get(); 2395 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc); 2396 } 2397 } 2398 2399 if (DirectMember) { 2400 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 2401 InitRange.getBegin(), Init, 2402 InitRange.getEnd()); 2403 } else { 2404 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 2405 InitRange.getBegin(), Init, 2406 InitRange.getEnd()); 2407 } 2408} 2409 2410MemInitResult 2411Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 2412 CXXRecordDecl *ClassDecl) { 2413 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 2414 if (!LangOpts.CPlusPlus0x) 2415 return Diag(NameLoc, diag::err_delegating_ctor) 2416 << TInfo->getTypeLoc().getLocalSourceRange(); 2417 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 2418 2419 bool InitList = true; 2420 Expr **Args = &Init; 2421 unsigned NumArgs = 1; 2422 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2423 InitList = false; 2424 Args = ParenList->getExprs(); 2425 NumArgs = ParenList->getNumExprs(); 2426 } 2427 2428 SourceRange InitRange = Init->getSourceRange(); 2429 // Initialize the object. 2430 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 2431 QualType(ClassDecl->getTypeForDecl(), 0)); 2432 InitializationKind Kind = 2433 InitList ? InitializationKind::CreateDirectList(NameLoc) 2434 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 2435 InitRange.getEnd()); 2436 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs); 2437 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 2438 MultiExprArg(Args, NumArgs), 2439 0); 2440 if (DelegationInit.isInvalid()) 2441 return true; 2442 2443 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 2444 "Delegating constructor with no target?"); 2445 2446 CheckImplicitConversions(DelegationInit.get(), InitRange.getBegin()); 2447 2448 // C++0x [class.base.init]p7: 2449 // The initialization of each base and member constitutes a 2450 // full-expression. 2451 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit); 2452 if (DelegationInit.isInvalid()) 2453 return true; 2454 2455 // If we are in a dependent context, template instantiation will 2456 // perform this type-checking again. Just save the arguments that we 2457 // received in a ParenListExpr. 2458 // FIXME: This isn't quite ideal, since our ASTs don't capture all 2459 // of the information that we have about the base 2460 // initializer. However, deconstructing the ASTs is a dicey process, 2461 // and this approach is far more likely to get the corner cases right. 2462 if (CurContext->isDependentContext()) 2463 DelegationInit = Owned(Init); 2464 2465 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 2466 DelegationInit.takeAs<Expr>(), 2467 InitRange.getEnd()); 2468} 2469 2470MemInitResult 2471Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 2472 Expr *Init, CXXRecordDecl *ClassDecl, 2473 SourceLocation EllipsisLoc) { 2474 SourceLocation BaseLoc 2475 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 2476 2477 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 2478 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 2479 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2480 2481 // C++ [class.base.init]p2: 2482 // [...] Unless the mem-initializer-id names a nonstatic data 2483 // member of the constructor's class or a direct or virtual base 2484 // of that class, the mem-initializer is ill-formed. A 2485 // mem-initializer-list can initialize a base class using any 2486 // name that denotes that base class type. 2487 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 2488 2489 SourceRange InitRange = Init->getSourceRange(); 2490 if (EllipsisLoc.isValid()) { 2491 // This is a pack expansion. 2492 if (!BaseType->containsUnexpandedParameterPack()) { 2493 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2494 << SourceRange(BaseLoc, InitRange.getEnd()); 2495 2496 EllipsisLoc = SourceLocation(); 2497 } 2498 } else { 2499 // Check for any unexpanded parameter packs. 2500 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 2501 return true; 2502 2503 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 2504 return true; 2505 } 2506 2507 // Check for direct and virtual base classes. 2508 const CXXBaseSpecifier *DirectBaseSpec = 0; 2509 const CXXBaseSpecifier *VirtualBaseSpec = 0; 2510 if (!Dependent) { 2511 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 2512 BaseType)) 2513 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 2514 2515 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 2516 VirtualBaseSpec); 2517 2518 // C++ [base.class.init]p2: 2519 // Unless the mem-initializer-id names a nonstatic data member of the 2520 // constructor's class or a direct or virtual base of that class, the 2521 // mem-initializer is ill-formed. 2522 if (!DirectBaseSpec && !VirtualBaseSpec) { 2523 // If the class has any dependent bases, then it's possible that 2524 // one of those types will resolve to the same type as 2525 // BaseType. Therefore, just treat this as a dependent base 2526 // class initialization. FIXME: Should we try to check the 2527 // initialization anyway? It seems odd. 2528 if (ClassDecl->hasAnyDependentBases()) 2529 Dependent = true; 2530 else 2531 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 2532 << BaseType << Context.getTypeDeclType(ClassDecl) 2533 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2534 } 2535 } 2536 2537 if (Dependent) { 2538 DiscardCleanupsInEvaluationContext(); 2539 2540 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 2541 /*IsVirtual=*/false, 2542 InitRange.getBegin(), Init, 2543 InitRange.getEnd(), EllipsisLoc); 2544 } 2545 2546 // C++ [base.class.init]p2: 2547 // If a mem-initializer-id is ambiguous because it designates both 2548 // a direct non-virtual base class and an inherited virtual base 2549 // class, the mem-initializer is ill-formed. 2550 if (DirectBaseSpec && VirtualBaseSpec) 2551 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 2552 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2553 2554 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec); 2555 if (!BaseSpec) 2556 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec); 2557 2558 // Initialize the base. 2559 bool InitList = true; 2560 Expr **Args = &Init; 2561 unsigned NumArgs = 1; 2562 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2563 InitList = false; 2564 Args = ParenList->getExprs(); 2565 NumArgs = ParenList->getNumExprs(); 2566 } 2567 2568 InitializedEntity BaseEntity = 2569 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 2570 InitializationKind Kind = 2571 InitList ? InitializationKind::CreateDirectList(BaseLoc) 2572 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 2573 InitRange.getEnd()); 2574 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs); 2575 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, 2576 MultiExprArg(Args, NumArgs), 0); 2577 if (BaseInit.isInvalid()) 2578 return true; 2579 2580 CheckImplicitConversions(BaseInit.get(), InitRange.getBegin()); 2581 2582 // C++0x [class.base.init]p7: 2583 // The initialization of each base and member constitutes a 2584 // full-expression. 2585 BaseInit = MaybeCreateExprWithCleanups(BaseInit); 2586 if (BaseInit.isInvalid()) 2587 return true; 2588 2589 // If we are in a dependent context, template instantiation will 2590 // perform this type-checking again. Just save the arguments that we 2591 // received in a ParenListExpr. 2592 // FIXME: This isn't quite ideal, since our ASTs don't capture all 2593 // of the information that we have about the base 2594 // initializer. However, deconstructing the ASTs is a dicey process, 2595 // and this approach is far more likely to get the corner cases right. 2596 if (CurContext->isDependentContext()) 2597 BaseInit = Owned(Init); 2598 2599 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 2600 BaseSpec->isVirtual(), 2601 InitRange.getBegin(), 2602 BaseInit.takeAs<Expr>(), 2603 InitRange.getEnd(), EllipsisLoc); 2604} 2605 2606// Create a static_cast\<T&&>(expr). 2607static Expr *CastForMoving(Sema &SemaRef, Expr *E) { 2608 QualType ExprType = E->getType(); 2609 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType); 2610 SourceLocation ExprLoc = E->getLocStart(); 2611 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 2612 TargetType, ExprLoc); 2613 2614 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 2615 SourceRange(ExprLoc, ExprLoc), 2616 E->getSourceRange()).take(); 2617} 2618 2619/// ImplicitInitializerKind - How an implicit base or member initializer should 2620/// initialize its base or member. 2621enum ImplicitInitializerKind { 2622 IIK_Default, 2623 IIK_Copy, 2624 IIK_Move 2625}; 2626 2627static bool 2628BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 2629 ImplicitInitializerKind ImplicitInitKind, 2630 CXXBaseSpecifier *BaseSpec, 2631 bool IsInheritedVirtualBase, 2632 CXXCtorInitializer *&CXXBaseInit) { 2633 InitializedEntity InitEntity 2634 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 2635 IsInheritedVirtualBase); 2636 2637 ExprResult BaseInit; 2638 2639 switch (ImplicitInitKind) { 2640 case IIK_Default: { 2641 InitializationKind InitKind 2642 = InitializationKind::CreateDefault(Constructor->getLocation()); 2643 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0); 2644 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg()); 2645 break; 2646 } 2647 2648 case IIK_Move: 2649 case IIK_Copy: { 2650 bool Moving = ImplicitInitKind == IIK_Move; 2651 ParmVarDecl *Param = Constructor->getParamDecl(0); 2652 QualType ParamType = Param->getType().getNonReferenceType(); 2653 2654 Expr *CopyCtorArg = 2655 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 2656 SourceLocation(), Param, false, 2657 Constructor->getLocation(), ParamType, 2658 VK_LValue, 0); 2659 2660 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 2661 2662 // Cast to the base class to avoid ambiguities. 2663 QualType ArgTy = 2664 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 2665 ParamType.getQualifiers()); 2666 2667 if (Moving) { 2668 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 2669 } 2670 2671 CXXCastPath BasePath; 2672 BasePath.push_back(BaseSpec); 2673 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 2674 CK_UncheckedDerivedToBase, 2675 Moving ? VK_XValue : VK_LValue, 2676 &BasePath).take(); 2677 2678 InitializationKind InitKind 2679 = InitializationKind::CreateDirect(Constructor->getLocation(), 2680 SourceLocation(), SourceLocation()); 2681 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 2682 &CopyCtorArg, 1); 2683 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, 2684 MultiExprArg(&CopyCtorArg, 1)); 2685 break; 2686 } 2687 } 2688 2689 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 2690 if (BaseInit.isInvalid()) 2691 return true; 2692 2693 CXXBaseInit = 2694 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 2695 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 2696 SourceLocation()), 2697 BaseSpec->isVirtual(), 2698 SourceLocation(), 2699 BaseInit.takeAs<Expr>(), 2700 SourceLocation(), 2701 SourceLocation()); 2702 2703 return false; 2704} 2705 2706static bool RefersToRValueRef(Expr *MemRef) { 2707 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 2708 return Referenced->getType()->isRValueReferenceType(); 2709} 2710 2711static bool 2712BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 2713 ImplicitInitializerKind ImplicitInitKind, 2714 FieldDecl *Field, IndirectFieldDecl *Indirect, 2715 CXXCtorInitializer *&CXXMemberInit) { 2716 if (Field->isInvalidDecl()) 2717 return true; 2718 2719 SourceLocation Loc = Constructor->getLocation(); 2720 2721 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 2722 bool Moving = ImplicitInitKind == IIK_Move; 2723 ParmVarDecl *Param = Constructor->getParamDecl(0); 2724 QualType ParamType = Param->getType().getNonReferenceType(); 2725 2726 // Suppress copying zero-width bitfields. 2727 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0) 2728 return false; 2729 2730 Expr *MemberExprBase = 2731 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 2732 SourceLocation(), Param, false, 2733 Loc, ParamType, VK_LValue, 0); 2734 2735 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 2736 2737 if (Moving) { 2738 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 2739 } 2740 2741 // Build a reference to this field within the parameter. 2742 CXXScopeSpec SS; 2743 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 2744 Sema::LookupMemberName); 2745 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 2746 : cast<ValueDecl>(Field), AS_public); 2747 MemberLookup.resolveKind(); 2748 ExprResult CtorArg 2749 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 2750 ParamType, Loc, 2751 /*IsArrow=*/false, 2752 SS, 2753 /*TemplateKWLoc=*/SourceLocation(), 2754 /*FirstQualifierInScope=*/0, 2755 MemberLookup, 2756 /*TemplateArgs=*/0); 2757 if (CtorArg.isInvalid()) 2758 return true; 2759 2760 // C++11 [class.copy]p15: 2761 // - if a member m has rvalue reference type T&&, it is direct-initialized 2762 // with static_cast<T&&>(x.m); 2763 if (RefersToRValueRef(CtorArg.get())) { 2764 CtorArg = CastForMoving(SemaRef, CtorArg.take()); 2765 } 2766 2767 // When the field we are copying is an array, create index variables for 2768 // each dimension of the array. We use these index variables to subscript 2769 // the source array, and other clients (e.g., CodeGen) will perform the 2770 // necessary iteration with these index variables. 2771 SmallVector<VarDecl *, 4> IndexVariables; 2772 QualType BaseType = Field->getType(); 2773 QualType SizeType = SemaRef.Context.getSizeType(); 2774 bool InitializingArray = false; 2775 while (const ConstantArrayType *Array 2776 = SemaRef.Context.getAsConstantArrayType(BaseType)) { 2777 InitializingArray = true; 2778 // Create the iteration variable for this array index. 2779 IdentifierInfo *IterationVarName = 0; 2780 { 2781 SmallString<8> Str; 2782 llvm::raw_svector_ostream OS(Str); 2783 OS << "__i" << IndexVariables.size(); 2784 IterationVarName = &SemaRef.Context.Idents.get(OS.str()); 2785 } 2786 VarDecl *IterationVar 2787 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc, 2788 IterationVarName, SizeType, 2789 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc), 2790 SC_None, SC_None); 2791 IndexVariables.push_back(IterationVar); 2792 2793 // Create a reference to the iteration variable. 2794 ExprResult IterationVarRef 2795 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 2796 assert(!IterationVarRef.isInvalid() && 2797 "Reference to invented variable cannot fail!"); 2798 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take()); 2799 assert(!IterationVarRef.isInvalid() && 2800 "Conversion of invented variable cannot fail!"); 2801 2802 // Subscript the array with this iteration variable. 2803 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc, 2804 IterationVarRef.take(), 2805 Loc); 2806 if (CtorArg.isInvalid()) 2807 return true; 2808 2809 BaseType = Array->getElementType(); 2810 } 2811 2812 // The array subscript expression is an lvalue, which is wrong for moving. 2813 if (Moving && InitializingArray) 2814 CtorArg = CastForMoving(SemaRef, CtorArg.take()); 2815 2816 // Construct the entity that we will be initializing. For an array, this 2817 // will be first element in the array, which may require several levels 2818 // of array-subscript entities. 2819 SmallVector<InitializedEntity, 4> Entities; 2820 Entities.reserve(1 + IndexVariables.size()); 2821 if (Indirect) 2822 Entities.push_back(InitializedEntity::InitializeMember(Indirect)); 2823 else 2824 Entities.push_back(InitializedEntity::InitializeMember(Field)); 2825 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 2826 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context, 2827 0, 2828 Entities.back())); 2829 2830 // Direct-initialize to use the copy constructor. 2831 InitializationKind InitKind = 2832 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 2833 2834 Expr *CtorArgE = CtorArg.takeAs<Expr>(); 2835 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, 2836 &CtorArgE, 1); 2837 2838 ExprResult MemberInit 2839 = InitSeq.Perform(SemaRef, Entities.back(), InitKind, 2840 MultiExprArg(&CtorArgE, 1)); 2841 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 2842 if (MemberInit.isInvalid()) 2843 return true; 2844 2845 if (Indirect) { 2846 assert(IndexVariables.size() == 0 && 2847 "Indirect field improperly initialized"); 2848 CXXMemberInit 2849 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 2850 Loc, Loc, 2851 MemberInit.takeAs<Expr>(), 2852 Loc); 2853 } else 2854 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, 2855 Loc, MemberInit.takeAs<Expr>(), 2856 Loc, 2857 IndexVariables.data(), 2858 IndexVariables.size()); 2859 return false; 2860 } 2861 2862 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!"); 2863 2864 QualType FieldBaseElementType = 2865 SemaRef.Context.getBaseElementType(Field->getType()); 2866 2867 if (FieldBaseElementType->isRecordType()) { 2868 InitializedEntity InitEntity 2869 = Indirect? InitializedEntity::InitializeMember(Indirect) 2870 : InitializedEntity::InitializeMember(Field); 2871 InitializationKind InitKind = 2872 InitializationKind::CreateDefault(Loc); 2873 2874 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0); 2875 ExprResult MemberInit = 2876 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg()); 2877 2878 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 2879 if (MemberInit.isInvalid()) 2880 return true; 2881 2882 if (Indirect) 2883 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 2884 Indirect, Loc, 2885 Loc, 2886 MemberInit.get(), 2887 Loc); 2888 else 2889 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 2890 Field, Loc, Loc, 2891 MemberInit.get(), 2892 Loc); 2893 return false; 2894 } 2895 2896 if (!Field->getParent()->isUnion()) { 2897 if (FieldBaseElementType->isReferenceType()) { 2898 SemaRef.Diag(Constructor->getLocation(), 2899 diag::err_uninitialized_member_in_ctor) 2900 << (int)Constructor->isImplicit() 2901 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 2902 << 0 << Field->getDeclName(); 2903 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 2904 return true; 2905 } 2906 2907 if (FieldBaseElementType.isConstQualified()) { 2908 SemaRef.Diag(Constructor->getLocation(), 2909 diag::err_uninitialized_member_in_ctor) 2910 << (int)Constructor->isImplicit() 2911 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 2912 << 1 << Field->getDeclName(); 2913 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 2914 return true; 2915 } 2916 } 2917 2918 if (SemaRef.getLangOpts().ObjCAutoRefCount && 2919 FieldBaseElementType->isObjCRetainableType() && 2920 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None && 2921 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) { 2922 // ARC: 2923 // Default-initialize Objective-C pointers to NULL. 2924 CXXMemberInit 2925 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 2926 Loc, Loc, 2927 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 2928 Loc); 2929 return false; 2930 } 2931 2932 // Nothing to initialize. 2933 CXXMemberInit = 0; 2934 return false; 2935} 2936 2937namespace { 2938struct BaseAndFieldInfo { 2939 Sema &S; 2940 CXXConstructorDecl *Ctor; 2941 bool AnyErrorsInInits; 2942 ImplicitInitializerKind IIK; 2943 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 2944 SmallVector<CXXCtorInitializer*, 8> AllToInit; 2945 2946 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 2947 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 2948 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 2949 if (Generated && Ctor->isCopyConstructor()) 2950 IIK = IIK_Copy; 2951 else if (Generated && Ctor->isMoveConstructor()) 2952 IIK = IIK_Move; 2953 else 2954 IIK = IIK_Default; 2955 } 2956 2957 bool isImplicitCopyOrMove() const { 2958 switch (IIK) { 2959 case IIK_Copy: 2960 case IIK_Move: 2961 return true; 2962 2963 case IIK_Default: 2964 return false; 2965 } 2966 2967 llvm_unreachable("Invalid ImplicitInitializerKind!"); 2968 } 2969 2970 bool addFieldInitializer(CXXCtorInitializer *Init) { 2971 AllToInit.push_back(Init); 2972 2973 // Check whether this initializer makes the field "used". 2974 if (Init->getInit() && Init->getInit()->HasSideEffects(S.Context)) 2975 S.UnusedPrivateFields.remove(Init->getAnyMember()); 2976 2977 return false; 2978 } 2979}; 2980} 2981 2982/// \brief Determine whether the given indirect field declaration is somewhere 2983/// within an anonymous union. 2984static bool isWithinAnonymousUnion(IndirectFieldDecl *F) { 2985 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(), 2986 CEnd = F->chain_end(); 2987 C != CEnd; ++C) 2988 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext())) 2989 if (Record->isUnion()) 2990 return true; 2991 2992 return false; 2993} 2994 2995/// \brief Determine whether the given type is an incomplete or zero-lenfgth 2996/// array type. 2997static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 2998 if (T->isIncompleteArrayType()) 2999 return true; 3000 3001 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 3002 if (!ArrayT->getSize()) 3003 return true; 3004 3005 T = ArrayT->getElementType(); 3006 } 3007 3008 return false; 3009} 3010 3011static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 3012 FieldDecl *Field, 3013 IndirectFieldDecl *Indirect = 0) { 3014 3015 // Overwhelmingly common case: we have a direct initializer for this field. 3016 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) 3017 return Info.addFieldInitializer(Init); 3018 3019 // C++11 [class.base.init]p8: if the entity is a non-static data member that 3020 // has a brace-or-equal-initializer, the entity is initialized as specified 3021 // in [dcl.init]. 3022 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 3023 CXXCtorInitializer *Init; 3024 if (Indirect) 3025 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 3026 SourceLocation(), 3027 SourceLocation(), 0, 3028 SourceLocation()); 3029 else 3030 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 3031 SourceLocation(), 3032 SourceLocation(), 0, 3033 SourceLocation()); 3034 return Info.addFieldInitializer(Init); 3035 } 3036 3037 // Don't build an implicit initializer for union members if none was 3038 // explicitly specified. 3039 if (Field->getParent()->isUnion() || 3040 (Indirect && isWithinAnonymousUnion(Indirect))) 3041 return false; 3042 3043 // Don't initialize incomplete or zero-length arrays. 3044 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 3045 return false; 3046 3047 // Don't try to build an implicit initializer if there were semantic 3048 // errors in any of the initializers (and therefore we might be 3049 // missing some that the user actually wrote). 3050 if (Info.AnyErrorsInInits || Field->isInvalidDecl()) 3051 return false; 3052 3053 CXXCtorInitializer *Init = 0; 3054 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 3055 Indirect, Init)) 3056 return true; 3057 3058 if (!Init) 3059 return false; 3060 3061 return Info.addFieldInitializer(Init); 3062} 3063 3064bool 3065Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 3066 CXXCtorInitializer *Initializer) { 3067 assert(Initializer->isDelegatingInitializer()); 3068 Constructor->setNumCtorInitializers(1); 3069 CXXCtorInitializer **initializer = 3070 new (Context) CXXCtorInitializer*[1]; 3071 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 3072 Constructor->setCtorInitializers(initializer); 3073 3074 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 3075 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 3076 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 3077 } 3078 3079 DelegatingCtorDecls.push_back(Constructor); 3080 3081 return false; 3082} 3083 3084bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, 3085 CXXCtorInitializer **Initializers, 3086 unsigned NumInitializers, 3087 bool AnyErrors) { 3088 if (Constructor->isDependentContext()) { 3089 // Just store the initializers as written, they will be checked during 3090 // instantiation. 3091 if (NumInitializers > 0) { 3092 Constructor->setNumCtorInitializers(NumInitializers); 3093 CXXCtorInitializer **baseOrMemberInitializers = 3094 new (Context) CXXCtorInitializer*[NumInitializers]; 3095 memcpy(baseOrMemberInitializers, Initializers, 3096 NumInitializers * sizeof(CXXCtorInitializer*)); 3097 Constructor->setCtorInitializers(baseOrMemberInitializers); 3098 } 3099 3100 // Let template instantiation know whether we had errors. 3101 if (AnyErrors) 3102 Constructor->setInvalidDecl(); 3103 3104 return false; 3105 } 3106 3107 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 3108 3109 // We need to build the initializer AST according to order of construction 3110 // and not what user specified in the Initializers list. 3111 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 3112 if (!ClassDecl) 3113 return true; 3114 3115 bool HadError = false; 3116 3117 for (unsigned i = 0; i < NumInitializers; i++) { 3118 CXXCtorInitializer *Member = Initializers[i]; 3119 3120 if (Member->isBaseInitializer()) 3121 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 3122 else 3123 Info.AllBaseFields[Member->getAnyMember()] = Member; 3124 } 3125 3126 // Keep track of the direct virtual bases. 3127 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 3128 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(), 3129 E = ClassDecl->bases_end(); I != E; ++I) { 3130 if (I->isVirtual()) 3131 DirectVBases.insert(I); 3132 } 3133 3134 // Push virtual bases before others. 3135 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 3136 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 3137 3138 if (CXXCtorInitializer *Value 3139 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) { 3140 Info.AllToInit.push_back(Value); 3141 } else if (!AnyErrors) { 3142 bool IsInheritedVirtualBase = !DirectVBases.count(VBase); 3143 CXXCtorInitializer *CXXBaseInit; 3144 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3145 VBase, IsInheritedVirtualBase, 3146 CXXBaseInit)) { 3147 HadError = true; 3148 continue; 3149 } 3150 3151 Info.AllToInit.push_back(CXXBaseInit); 3152 } 3153 } 3154 3155 // Non-virtual bases. 3156 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 3157 E = ClassDecl->bases_end(); Base != E; ++Base) { 3158 // Virtuals are in the virtual base list and already constructed. 3159 if (Base->isVirtual()) 3160 continue; 3161 3162 if (CXXCtorInitializer *Value 3163 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) { 3164 Info.AllToInit.push_back(Value); 3165 } else if (!AnyErrors) { 3166 CXXCtorInitializer *CXXBaseInit; 3167 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3168 Base, /*IsInheritedVirtualBase=*/false, 3169 CXXBaseInit)) { 3170 HadError = true; 3171 continue; 3172 } 3173 3174 Info.AllToInit.push_back(CXXBaseInit); 3175 } 3176 } 3177 3178 // Fields. 3179 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(), 3180 MemEnd = ClassDecl->decls_end(); 3181 Mem != MemEnd; ++Mem) { 3182 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) { 3183 // C++ [class.bit]p2: 3184 // A declaration for a bit-field that omits the identifier declares an 3185 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 3186 // initialized. 3187 if (F->isUnnamedBitfield()) 3188 continue; 3189 3190 // If we're not generating the implicit copy/move constructor, then we'll 3191 // handle anonymous struct/union fields based on their individual 3192 // indirect fields. 3193 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default) 3194 continue; 3195 3196 if (CollectFieldInitializer(*this, Info, F)) 3197 HadError = true; 3198 continue; 3199 } 3200 3201 // Beyond this point, we only consider default initialization. 3202 if (Info.IIK != IIK_Default) 3203 continue; 3204 3205 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) { 3206 if (F->getType()->isIncompleteArrayType()) { 3207 assert(ClassDecl->hasFlexibleArrayMember() && 3208 "Incomplete array type is not valid"); 3209 continue; 3210 } 3211 3212 // Initialize each field of an anonymous struct individually. 3213 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 3214 HadError = true; 3215 3216 continue; 3217 } 3218 } 3219 3220 NumInitializers = Info.AllToInit.size(); 3221 if (NumInitializers > 0) { 3222 Constructor->setNumCtorInitializers(NumInitializers); 3223 CXXCtorInitializer **baseOrMemberInitializers = 3224 new (Context) CXXCtorInitializer*[NumInitializers]; 3225 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 3226 NumInitializers * sizeof(CXXCtorInitializer*)); 3227 Constructor->setCtorInitializers(baseOrMemberInitializers); 3228 3229 // Constructors implicitly reference the base and member 3230 // destructors. 3231 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 3232 Constructor->getParent()); 3233 } 3234 3235 return HadError; 3236} 3237 3238static void *GetKeyForTopLevelField(FieldDecl *Field) { 3239 // For anonymous unions, use the class declaration as the key. 3240 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 3241 if (RT->getDecl()->isAnonymousStructOrUnion()) 3242 return static_cast<void *>(RT->getDecl()); 3243 } 3244 return static_cast<void *>(Field); 3245} 3246 3247static void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 3248 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr()); 3249} 3250 3251static void *GetKeyForMember(ASTContext &Context, 3252 CXXCtorInitializer *Member) { 3253 if (!Member->isAnyMemberInitializer()) 3254 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 3255 3256 // For fields injected into the class via declaration of an anonymous union, 3257 // use its anonymous union class declaration as the unique key. 3258 FieldDecl *Field = Member->getAnyMember(); 3259 3260 // If the field is a member of an anonymous struct or union, our key 3261 // is the anonymous record decl that's a direct child of the class. 3262 RecordDecl *RD = Field->getParent(); 3263 if (RD->isAnonymousStructOrUnion()) { 3264 while (true) { 3265 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext()); 3266 if (Parent->isAnonymousStructOrUnion()) 3267 RD = Parent; 3268 else 3269 break; 3270 } 3271 3272 return static_cast<void *>(RD); 3273 } 3274 3275 return static_cast<void *>(Field); 3276} 3277 3278static void 3279DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef, 3280 const CXXConstructorDecl *Constructor, 3281 CXXCtorInitializer **Inits, 3282 unsigned NumInits) { 3283 if (Constructor->getDeclContext()->isDependentContext()) 3284 return; 3285 3286 // Don't check initializers order unless the warning is enabled at the 3287 // location of at least one initializer. 3288 bool ShouldCheckOrder = false; 3289 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) { 3290 CXXCtorInitializer *Init = Inits[InitIndex]; 3291 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order, 3292 Init->getSourceLocation()) 3293 != DiagnosticsEngine::Ignored) { 3294 ShouldCheckOrder = true; 3295 break; 3296 } 3297 } 3298 if (!ShouldCheckOrder) 3299 return; 3300 3301 // Build the list of bases and members in the order that they'll 3302 // actually be initialized. The explicit initializers should be in 3303 // this same order but may be missing things. 3304 SmallVector<const void*, 32> IdealInitKeys; 3305 3306 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 3307 3308 // 1. Virtual bases. 3309 for (CXXRecordDecl::base_class_const_iterator VBase = 3310 ClassDecl->vbases_begin(), 3311 E = ClassDecl->vbases_end(); VBase != E; ++VBase) 3312 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType())); 3313 3314 // 2. Non-virtual bases. 3315 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(), 3316 E = ClassDecl->bases_end(); Base != E; ++Base) { 3317 if (Base->isVirtual()) 3318 continue; 3319 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType())); 3320 } 3321 3322 // 3. Direct fields. 3323 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 3324 E = ClassDecl->field_end(); Field != E; ++Field) { 3325 if (Field->isUnnamedBitfield()) 3326 continue; 3327 3328 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field)); 3329 } 3330 3331 unsigned NumIdealInits = IdealInitKeys.size(); 3332 unsigned IdealIndex = 0; 3333 3334 CXXCtorInitializer *PrevInit = 0; 3335 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) { 3336 CXXCtorInitializer *Init = Inits[InitIndex]; 3337 void *InitKey = GetKeyForMember(SemaRef.Context, Init); 3338 3339 // Scan forward to try to find this initializer in the idealized 3340 // initializers list. 3341 for (; IdealIndex != NumIdealInits; ++IdealIndex) 3342 if (InitKey == IdealInitKeys[IdealIndex]) 3343 break; 3344 3345 // If we didn't find this initializer, it must be because we 3346 // scanned past it on a previous iteration. That can only 3347 // happen if we're out of order; emit a warning. 3348 if (IdealIndex == NumIdealInits && PrevInit) { 3349 Sema::SemaDiagnosticBuilder D = 3350 SemaRef.Diag(PrevInit->getSourceLocation(), 3351 diag::warn_initializer_out_of_order); 3352 3353 if (PrevInit->isAnyMemberInitializer()) 3354 D << 0 << PrevInit->getAnyMember()->getDeclName(); 3355 else 3356 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 3357 3358 if (Init->isAnyMemberInitializer()) 3359 D << 0 << Init->getAnyMember()->getDeclName(); 3360 else 3361 D << 1 << Init->getTypeSourceInfo()->getType(); 3362 3363 // Move back to the initializer's location in the ideal list. 3364 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 3365 if (InitKey == IdealInitKeys[IdealIndex]) 3366 break; 3367 3368 assert(IdealIndex != NumIdealInits && 3369 "initializer not found in initializer list"); 3370 } 3371 3372 PrevInit = Init; 3373 } 3374} 3375 3376namespace { 3377bool CheckRedundantInit(Sema &S, 3378 CXXCtorInitializer *Init, 3379 CXXCtorInitializer *&PrevInit) { 3380 if (!PrevInit) { 3381 PrevInit = Init; 3382 return false; 3383 } 3384 3385 if (FieldDecl *Field = Init->getMember()) 3386 S.Diag(Init->getSourceLocation(), 3387 diag::err_multiple_mem_initialization) 3388 << Field->getDeclName() 3389 << Init->getSourceRange(); 3390 else { 3391 const Type *BaseClass = Init->getBaseClass(); 3392 assert(BaseClass && "neither field nor base"); 3393 S.Diag(Init->getSourceLocation(), 3394 diag::err_multiple_base_initialization) 3395 << QualType(BaseClass, 0) 3396 << Init->getSourceRange(); 3397 } 3398 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 3399 << 0 << PrevInit->getSourceRange(); 3400 3401 return true; 3402} 3403 3404typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 3405typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 3406 3407bool CheckRedundantUnionInit(Sema &S, 3408 CXXCtorInitializer *Init, 3409 RedundantUnionMap &Unions) { 3410 FieldDecl *Field = Init->getAnyMember(); 3411 RecordDecl *Parent = Field->getParent(); 3412 NamedDecl *Child = Field; 3413 3414 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 3415 if (Parent->isUnion()) { 3416 UnionEntry &En = Unions[Parent]; 3417 if (En.first && En.first != Child) { 3418 S.Diag(Init->getSourceLocation(), 3419 diag::err_multiple_mem_union_initialization) 3420 << Field->getDeclName() 3421 << Init->getSourceRange(); 3422 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 3423 << 0 << En.second->getSourceRange(); 3424 return true; 3425 } 3426 if (!En.first) { 3427 En.first = Child; 3428 En.second = Init; 3429 } 3430 if (!Parent->isAnonymousStructOrUnion()) 3431 return false; 3432 } 3433 3434 Child = Parent; 3435 Parent = cast<RecordDecl>(Parent->getDeclContext()); 3436 } 3437 3438 return false; 3439} 3440} 3441 3442/// ActOnMemInitializers - Handle the member initializers for a constructor. 3443void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 3444 SourceLocation ColonLoc, 3445 CXXCtorInitializer **meminits, 3446 unsigned NumMemInits, 3447 bool AnyErrors) { 3448 if (!ConstructorDecl) 3449 return; 3450 3451 AdjustDeclIfTemplate(ConstructorDecl); 3452 3453 CXXConstructorDecl *Constructor 3454 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 3455 3456 if (!Constructor) { 3457 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 3458 return; 3459 } 3460 3461 CXXCtorInitializer **MemInits = 3462 reinterpret_cast<CXXCtorInitializer **>(meminits); 3463 3464 // Mapping for the duplicate initializers check. 3465 // For member initializers, this is keyed with a FieldDecl*. 3466 // For base initializers, this is keyed with a Type*. 3467 llvm::DenseMap<void*, CXXCtorInitializer *> Members; 3468 3469 // Mapping for the inconsistent anonymous-union initializers check. 3470 RedundantUnionMap MemberUnions; 3471 3472 bool HadError = false; 3473 for (unsigned i = 0; i < NumMemInits; i++) { 3474 CXXCtorInitializer *Init = MemInits[i]; 3475 3476 // Set the source order index. 3477 Init->setSourceOrder(i); 3478 3479 if (Init->isAnyMemberInitializer()) { 3480 FieldDecl *Field = Init->getAnyMember(); 3481 if (CheckRedundantInit(*this, Init, Members[Field]) || 3482 CheckRedundantUnionInit(*this, Init, MemberUnions)) 3483 HadError = true; 3484 } else if (Init->isBaseInitializer()) { 3485 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0)); 3486 if (CheckRedundantInit(*this, Init, Members[Key])) 3487 HadError = true; 3488 } else { 3489 assert(Init->isDelegatingInitializer()); 3490 // This must be the only initializer 3491 if (NumMemInits != 1) { 3492 Diag(Init->getSourceLocation(), 3493 diag::err_delegating_initializer_alone) 3494 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 3495 // We will treat this as being the only initializer. 3496 } 3497 SetDelegatingInitializer(Constructor, MemInits[i]); 3498 // Return immediately as the initializer is set. 3499 return; 3500 } 3501 } 3502 3503 if (HadError) 3504 return; 3505 3506 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits); 3507 3508 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors); 3509} 3510 3511void 3512Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 3513 CXXRecordDecl *ClassDecl) { 3514 // Ignore dependent contexts. Also ignore unions, since their members never 3515 // have destructors implicitly called. 3516 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 3517 return; 3518 3519 // FIXME: all the access-control diagnostics are positioned on the 3520 // field/base declaration. That's probably good; that said, the 3521 // user might reasonably want to know why the destructor is being 3522 // emitted, and we currently don't say. 3523 3524 // Non-static data members. 3525 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(), 3526 E = ClassDecl->field_end(); I != E; ++I) { 3527 FieldDecl *Field = *I; 3528 if (Field->isInvalidDecl()) 3529 continue; 3530 3531 // Don't destroy incomplete or zero-length arrays. 3532 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 3533 continue; 3534 3535 QualType FieldType = Context.getBaseElementType(Field->getType()); 3536 3537 const RecordType* RT = FieldType->getAs<RecordType>(); 3538 if (!RT) 3539 continue; 3540 3541 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3542 if (FieldClassDecl->isInvalidDecl()) 3543 continue; 3544 if (FieldClassDecl->hasIrrelevantDestructor()) 3545 continue; 3546 // The destructor for an implicit anonymous union member is never invoked. 3547 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 3548 continue; 3549 3550 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 3551 assert(Dtor && "No dtor found for FieldClassDecl!"); 3552 CheckDestructorAccess(Field->getLocation(), Dtor, 3553 PDiag(diag::err_access_dtor_field) 3554 << Field->getDeclName() 3555 << FieldType); 3556 3557 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 3558 DiagnoseUseOfDecl(Dtor, Location); 3559 } 3560 3561 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 3562 3563 // Bases. 3564 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 3565 E = ClassDecl->bases_end(); Base != E; ++Base) { 3566 // Bases are always records in a well-formed non-dependent class. 3567 const RecordType *RT = Base->getType()->getAs<RecordType>(); 3568 3569 // Remember direct virtual bases. 3570 if (Base->isVirtual()) 3571 DirectVirtualBases.insert(RT); 3572 3573 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3574 // If our base class is invalid, we probably can't get its dtor anyway. 3575 if (BaseClassDecl->isInvalidDecl()) 3576 continue; 3577 if (BaseClassDecl->hasIrrelevantDestructor()) 3578 continue; 3579 3580 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 3581 assert(Dtor && "No dtor found for BaseClassDecl!"); 3582 3583 // FIXME: caret should be on the start of the class name 3584 CheckDestructorAccess(Base->getLocStart(), Dtor, 3585 PDiag(diag::err_access_dtor_base) 3586 << Base->getType() 3587 << Base->getSourceRange(), 3588 Context.getTypeDeclType(ClassDecl)); 3589 3590 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 3591 DiagnoseUseOfDecl(Dtor, Location); 3592 } 3593 3594 // Virtual bases. 3595 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 3596 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 3597 3598 // Bases are always records in a well-formed non-dependent class. 3599 const RecordType *RT = VBase->getType()->castAs<RecordType>(); 3600 3601 // Ignore direct virtual bases. 3602 if (DirectVirtualBases.count(RT)) 3603 continue; 3604 3605 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3606 // If our base class is invalid, we probably can't get its dtor anyway. 3607 if (BaseClassDecl->isInvalidDecl()) 3608 continue; 3609 if (BaseClassDecl->hasIrrelevantDestructor()) 3610 continue; 3611 3612 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 3613 assert(Dtor && "No dtor found for BaseClassDecl!"); 3614 CheckDestructorAccess(ClassDecl->getLocation(), Dtor, 3615 PDiag(diag::err_access_dtor_vbase) 3616 << VBase->getType(), 3617 Context.getTypeDeclType(ClassDecl)); 3618 3619 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 3620 DiagnoseUseOfDecl(Dtor, Location); 3621 } 3622} 3623 3624void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 3625 if (!CDtorDecl) 3626 return; 3627 3628 if (CXXConstructorDecl *Constructor 3629 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) 3630 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false); 3631} 3632 3633bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 3634 unsigned DiagID, AbstractDiagSelID SelID) { 3635 class NonAbstractTypeDiagnoser : public TypeDiagnoser { 3636 unsigned DiagID; 3637 AbstractDiagSelID SelID; 3638 3639 public: 3640 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID) 3641 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { } 3642 3643 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 3644 if (Suppressed) return; 3645 if (SelID == -1) 3646 S.Diag(Loc, DiagID) << T; 3647 else 3648 S.Diag(Loc, DiagID) << SelID << T; 3649 } 3650 } Diagnoser(DiagID, SelID); 3651 3652 return RequireNonAbstractType(Loc, T, Diagnoser); 3653} 3654 3655bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 3656 TypeDiagnoser &Diagnoser) { 3657 if (!getLangOpts().CPlusPlus) 3658 return false; 3659 3660 if (const ArrayType *AT = Context.getAsArrayType(T)) 3661 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 3662 3663 if (const PointerType *PT = T->getAs<PointerType>()) { 3664 // Find the innermost pointer type. 3665 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 3666 PT = T; 3667 3668 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 3669 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 3670 } 3671 3672 const RecordType *RT = T->getAs<RecordType>(); 3673 if (!RT) 3674 return false; 3675 3676 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 3677 3678 // We can't answer whether something is abstract until it has a 3679 // definition. If it's currently being defined, we'll walk back 3680 // over all the declarations when we have a full definition. 3681 const CXXRecordDecl *Def = RD->getDefinition(); 3682 if (!Def || Def->isBeingDefined()) 3683 return false; 3684 3685 if (!RD->isAbstract()) 3686 return false; 3687 3688 Diagnoser.diagnose(*this, Loc, T); 3689 DiagnoseAbstractType(RD); 3690 3691 return true; 3692} 3693 3694void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 3695 // Check if we've already emitted the list of pure virtual functions 3696 // for this class. 3697 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 3698 return; 3699 3700 CXXFinalOverriderMap FinalOverriders; 3701 RD->getFinalOverriders(FinalOverriders); 3702 3703 // Keep a set of seen pure methods so we won't diagnose the same method 3704 // more than once. 3705 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 3706 3707 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 3708 MEnd = FinalOverriders.end(); 3709 M != MEnd; 3710 ++M) { 3711 for (OverridingMethods::iterator SO = M->second.begin(), 3712 SOEnd = M->second.end(); 3713 SO != SOEnd; ++SO) { 3714 // C++ [class.abstract]p4: 3715 // A class is abstract if it contains or inherits at least one 3716 // pure virtual function for which the final overrider is pure 3717 // virtual. 3718 3719 // 3720 if (SO->second.size() != 1) 3721 continue; 3722 3723 if (!SO->second.front().Method->isPure()) 3724 continue; 3725 3726 if (!SeenPureMethods.insert(SO->second.front().Method)) 3727 continue; 3728 3729 Diag(SO->second.front().Method->getLocation(), 3730 diag::note_pure_virtual_function) 3731 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 3732 } 3733 } 3734 3735 if (!PureVirtualClassDiagSet) 3736 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 3737 PureVirtualClassDiagSet->insert(RD); 3738} 3739 3740namespace { 3741struct AbstractUsageInfo { 3742 Sema &S; 3743 CXXRecordDecl *Record; 3744 CanQualType AbstractType; 3745 bool Invalid; 3746 3747 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 3748 : S(S), Record(Record), 3749 AbstractType(S.Context.getCanonicalType( 3750 S.Context.getTypeDeclType(Record))), 3751 Invalid(false) {} 3752 3753 void DiagnoseAbstractType() { 3754 if (Invalid) return; 3755 S.DiagnoseAbstractType(Record); 3756 Invalid = true; 3757 } 3758 3759 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 3760}; 3761 3762struct CheckAbstractUsage { 3763 AbstractUsageInfo &Info; 3764 const NamedDecl *Ctx; 3765 3766 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 3767 : Info(Info), Ctx(Ctx) {} 3768 3769 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 3770 switch (TL.getTypeLocClass()) { 3771#define ABSTRACT_TYPELOC(CLASS, PARENT) 3772#define TYPELOC(CLASS, PARENT) \ 3773 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break; 3774#include "clang/AST/TypeLocNodes.def" 3775 } 3776 } 3777 3778 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 3779 Visit(TL.getResultLoc(), Sema::AbstractReturnType); 3780 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 3781 if (!TL.getArg(I)) 3782 continue; 3783 3784 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo(); 3785 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 3786 } 3787 } 3788 3789 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 3790 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 3791 } 3792 3793 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 3794 // Visit the type parameters from a permissive context. 3795 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 3796 TemplateArgumentLoc TAL = TL.getArgLoc(I); 3797 if (TAL.getArgument().getKind() == TemplateArgument::Type) 3798 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 3799 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 3800 // TODO: other template argument types? 3801 } 3802 } 3803 3804 // Visit pointee types from a permissive context. 3805#define CheckPolymorphic(Type) \ 3806 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 3807 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 3808 } 3809 CheckPolymorphic(PointerTypeLoc) 3810 CheckPolymorphic(ReferenceTypeLoc) 3811 CheckPolymorphic(MemberPointerTypeLoc) 3812 CheckPolymorphic(BlockPointerTypeLoc) 3813 CheckPolymorphic(AtomicTypeLoc) 3814 3815 /// Handle all the types we haven't given a more specific 3816 /// implementation for above. 3817 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 3818 // Every other kind of type that we haven't called out already 3819 // that has an inner type is either (1) sugar or (2) contains that 3820 // inner type in some way as a subobject. 3821 if (TypeLoc Next = TL.getNextTypeLoc()) 3822 return Visit(Next, Sel); 3823 3824 // If there's no inner type and we're in a permissive context, 3825 // don't diagnose. 3826 if (Sel == Sema::AbstractNone) return; 3827 3828 // Check whether the type matches the abstract type. 3829 QualType T = TL.getType(); 3830 if (T->isArrayType()) { 3831 Sel = Sema::AbstractArrayType; 3832 T = Info.S.Context.getBaseElementType(T); 3833 } 3834 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 3835 if (CT != Info.AbstractType) return; 3836 3837 // It matched; do some magic. 3838 if (Sel == Sema::AbstractArrayType) { 3839 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 3840 << T << TL.getSourceRange(); 3841 } else { 3842 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 3843 << Sel << T << TL.getSourceRange(); 3844 } 3845 Info.DiagnoseAbstractType(); 3846 } 3847}; 3848 3849void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 3850 Sema::AbstractDiagSelID Sel) { 3851 CheckAbstractUsage(*this, D).Visit(TL, Sel); 3852} 3853 3854} 3855 3856/// Check for invalid uses of an abstract type in a method declaration. 3857static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 3858 CXXMethodDecl *MD) { 3859 // No need to do the check on definitions, which require that 3860 // the return/param types be complete. 3861 if (MD->doesThisDeclarationHaveABody()) 3862 return; 3863 3864 // For safety's sake, just ignore it if we don't have type source 3865 // information. This should never happen for non-implicit methods, 3866 // but... 3867 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 3868 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 3869} 3870 3871/// Check for invalid uses of an abstract type within a class definition. 3872static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 3873 CXXRecordDecl *RD) { 3874 for (CXXRecordDecl::decl_iterator 3875 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) { 3876 Decl *D = *I; 3877 if (D->isImplicit()) continue; 3878 3879 // Methods and method templates. 3880 if (isa<CXXMethodDecl>(D)) { 3881 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 3882 } else if (isa<FunctionTemplateDecl>(D)) { 3883 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 3884 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 3885 3886 // Fields and static variables. 3887 } else if (isa<FieldDecl>(D)) { 3888 FieldDecl *FD = cast<FieldDecl>(D); 3889 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 3890 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 3891 } else if (isa<VarDecl>(D)) { 3892 VarDecl *VD = cast<VarDecl>(D); 3893 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 3894 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 3895 3896 // Nested classes and class templates. 3897 } else if (isa<CXXRecordDecl>(D)) { 3898 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 3899 } else if (isa<ClassTemplateDecl>(D)) { 3900 CheckAbstractClassUsage(Info, 3901 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 3902 } 3903 } 3904} 3905 3906/// \brief Perform semantic checks on a class definition that has been 3907/// completing, introducing implicitly-declared members, checking for 3908/// abstract types, etc. 3909void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 3910 if (!Record) 3911 return; 3912 3913 if (Record->isAbstract() && !Record->isInvalidDecl()) { 3914 AbstractUsageInfo Info(*this, Record); 3915 CheckAbstractClassUsage(Info, Record); 3916 } 3917 3918 // If this is not an aggregate type and has no user-declared constructor, 3919 // complain about any non-static data members of reference or const scalar 3920 // type, since they will never get initializers. 3921 if (!Record->isInvalidDecl() && !Record->isDependentType() && 3922 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 3923 !Record->isLambda()) { 3924 bool Complained = false; 3925 for (RecordDecl::field_iterator F = Record->field_begin(), 3926 FEnd = Record->field_end(); 3927 F != FEnd; ++F) { 3928 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 3929 continue; 3930 3931 if (F->getType()->isReferenceType() || 3932 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 3933 if (!Complained) { 3934 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 3935 << Record->getTagKind() << Record; 3936 Complained = true; 3937 } 3938 3939 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 3940 << F->getType()->isReferenceType() 3941 << F->getDeclName(); 3942 } 3943 } 3944 } 3945 3946 if (Record->isDynamicClass() && !Record->isDependentType()) 3947 DynamicClasses.push_back(Record); 3948 3949 if (Record->getIdentifier()) { 3950 // C++ [class.mem]p13: 3951 // If T is the name of a class, then each of the following shall have a 3952 // name different from T: 3953 // - every member of every anonymous union that is a member of class T. 3954 // 3955 // C++ [class.mem]p14: 3956 // In addition, if class T has a user-declared constructor (12.1), every 3957 // non-static data member of class T shall have a name different from T. 3958 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 3959 R.first != R.second; ++R.first) { 3960 NamedDecl *D = *R.first; 3961 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 3962 isa<IndirectFieldDecl>(D)) { 3963 Diag(D->getLocation(), diag::err_member_name_of_class) 3964 << D->getDeclName(); 3965 break; 3966 } 3967 } 3968 } 3969 3970 // Warn if the class has virtual methods but non-virtual public destructor. 3971 if (Record->isPolymorphic() && !Record->isDependentType()) { 3972 CXXDestructorDecl *dtor = Record->getDestructor(); 3973 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) 3974 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 3975 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 3976 } 3977 3978 if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) { 3979 Diag(Record->getLocation(), diag::warn_abstract_final_class); 3980 DiagnoseAbstractType(Record); 3981 } 3982 3983 // See if a method overloads virtual methods in a base 3984 /// class without overriding any. 3985 if (!Record->isDependentType()) { 3986 for (CXXRecordDecl::method_iterator M = Record->method_begin(), 3987 MEnd = Record->method_end(); 3988 M != MEnd; ++M) { 3989 if (!M->isStatic()) 3990 DiagnoseHiddenVirtualMethods(Record, *M); 3991 } 3992 } 3993 3994 // Declare inherited constructors. We do this eagerly here because: 3995 // - The standard requires an eager diagnostic for conflicting inherited 3996 // constructors from different classes. 3997 // - The lazy declaration of the other implicit constructors is so as to not 3998 // waste space and performance on classes that are not meant to be 3999 // instantiated (e.g. meta-functions). This doesn't apply to classes that 4000 // have inherited constructors. 4001 DeclareInheritedConstructors(Record); 4002} 4003 4004void Sema::CheckExplicitlyDefaultedAndDeletedMethods(CXXRecordDecl *Record) { 4005 for (CXXRecordDecl::method_iterator MI = Record->method_begin(), 4006 ME = Record->method_end(); 4007 MI != ME; ++MI) { 4008 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) 4009 CheckExplicitlyDefaultedSpecialMember(*MI); 4010 4011 if (!MI->isImplicit() && !MI->isUserProvided()) { 4012 // For an explicitly defaulted or deleted special member, we defer 4013 // determining triviality until the class is complete. That time is now! 4014 CXXSpecialMember CSM = getSpecialMember(*MI); 4015 if (CSM != CXXInvalid) { 4016 MI->setTrivial(SpecialMemberIsTrivial(*MI, CSM)); 4017 4018 // Inform the class that we've finished declaring this member. 4019 Record->finishedDefaultedOrDeletedMember(*MI); 4020 } 4021 } 4022 } 4023} 4024 4025/// Is the special member function which would be selected to perform the 4026/// specified operation on the specified class type a constexpr constructor? 4027static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 4028 Sema::CXXSpecialMember CSM, 4029 bool ConstArg) { 4030 Sema::SpecialMemberOverloadResult *SMOR = 4031 S.LookupSpecialMember(ClassDecl, CSM, ConstArg, 4032 false, false, false, false); 4033 if (!SMOR || !SMOR->getMethod()) 4034 // A constructor we wouldn't select can't be "involved in initializing" 4035 // anything. 4036 return true; 4037 return SMOR->getMethod()->isConstexpr(); 4038} 4039 4040/// Determine whether the specified special member function would be constexpr 4041/// if it were implicitly defined. 4042static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 4043 Sema::CXXSpecialMember CSM, 4044 bool ConstArg) { 4045 if (!S.getLangOpts().CPlusPlus0x) 4046 return false; 4047 4048 // C++11 [dcl.constexpr]p4: 4049 // In the definition of a constexpr constructor [...] 4050 switch (CSM) { 4051 case Sema::CXXDefaultConstructor: 4052 // Since default constructor lookup is essentially trivial (and cannot 4053 // involve, for instance, template instantiation), we compute whether a 4054 // defaulted default constructor is constexpr directly within CXXRecordDecl. 4055 // 4056 // This is important for performance; we need to know whether the default 4057 // constructor is constexpr to determine whether the type is a literal type. 4058 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 4059 4060 case Sema::CXXCopyConstructor: 4061 case Sema::CXXMoveConstructor: 4062 // For copy or move constructors, we need to perform overload resolution. 4063 break; 4064 4065 case Sema::CXXCopyAssignment: 4066 case Sema::CXXMoveAssignment: 4067 case Sema::CXXDestructor: 4068 case Sema::CXXInvalid: 4069 return false; 4070 } 4071 4072 // -- if the class is a non-empty union, or for each non-empty anonymous 4073 // union member of a non-union class, exactly one non-static data member 4074 // shall be initialized; [DR1359] 4075 // 4076 // If we squint, this is guaranteed, since exactly one non-static data member 4077 // will be initialized (if the constructor isn't deleted), we just don't know 4078 // which one. 4079 if (ClassDecl->isUnion()) 4080 return true; 4081 4082 // -- the class shall not have any virtual base classes; 4083 if (ClassDecl->getNumVBases()) 4084 return false; 4085 4086 // -- every constructor involved in initializing [...] base class 4087 // sub-objects shall be a constexpr constructor; 4088 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 4089 BEnd = ClassDecl->bases_end(); 4090 B != BEnd; ++B) { 4091 const RecordType *BaseType = B->getType()->getAs<RecordType>(); 4092 if (!BaseType) continue; 4093 4094 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 4095 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg)) 4096 return false; 4097 } 4098 4099 // -- every constructor involved in initializing non-static data members 4100 // [...] shall be a constexpr constructor; 4101 // -- every non-static data member and base class sub-object shall be 4102 // initialized 4103 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 4104 FEnd = ClassDecl->field_end(); 4105 F != FEnd; ++F) { 4106 if (F->isInvalidDecl()) 4107 continue; 4108 if (const RecordType *RecordTy = 4109 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 4110 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 4111 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg)) 4112 return false; 4113 } 4114 } 4115 4116 // All OK, it's constexpr! 4117 return true; 4118} 4119 4120static Sema::ImplicitExceptionSpecification 4121computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 4122 switch (S.getSpecialMember(MD)) { 4123 case Sema::CXXDefaultConstructor: 4124 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD); 4125 case Sema::CXXCopyConstructor: 4126 return S.ComputeDefaultedCopyCtorExceptionSpec(MD); 4127 case Sema::CXXCopyAssignment: 4128 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD); 4129 case Sema::CXXMoveConstructor: 4130 return S.ComputeDefaultedMoveCtorExceptionSpec(MD); 4131 case Sema::CXXMoveAssignment: 4132 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD); 4133 case Sema::CXXDestructor: 4134 return S.ComputeDefaultedDtorExceptionSpec(MD); 4135 case Sema::CXXInvalid: 4136 break; 4137 } 4138 llvm_unreachable("only special members have implicit exception specs"); 4139} 4140 4141static void 4142updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT, 4143 const Sema::ImplicitExceptionSpecification &ExceptSpec) { 4144 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 4145 ExceptSpec.getEPI(EPI); 4146 const FunctionProtoType *NewFPT = cast<FunctionProtoType>( 4147 S.Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(), 4148 FPT->getNumArgs(), EPI)); 4149 FD->setType(QualType(NewFPT, 0)); 4150} 4151 4152void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 4153 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 4154 if (FPT->getExceptionSpecType() != EST_Unevaluated) 4155 return; 4156 4157 // Evaluate the exception specification. 4158 ImplicitExceptionSpecification ExceptSpec = 4159 computeImplicitExceptionSpec(*this, Loc, MD); 4160 4161 // Update the type of the special member to use it. 4162 updateExceptionSpec(*this, MD, FPT, ExceptSpec); 4163 4164 // A user-provided destructor can be defined outside the class. When that 4165 // happens, be sure to update the exception specification on both 4166 // declarations. 4167 const FunctionProtoType *CanonicalFPT = 4168 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 4169 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 4170 updateExceptionSpec(*this, MD->getCanonicalDecl(), 4171 CanonicalFPT, ExceptSpec); 4172} 4173 4174void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 4175 CXXRecordDecl *RD = MD->getParent(); 4176 CXXSpecialMember CSM = getSpecialMember(MD); 4177 4178 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 4179 "not an explicitly-defaulted special member"); 4180 4181 // Whether this was the first-declared instance of the constructor. 4182 // This affects whether we implicitly add an exception spec and constexpr. 4183 bool First = MD == MD->getCanonicalDecl(); 4184 4185 bool HadError = false; 4186 4187 // C++11 [dcl.fct.def.default]p1: 4188 // A function that is explicitly defaulted shall 4189 // -- be a special member function (checked elsewhere), 4190 // -- have the same type (except for ref-qualifiers, and except that a 4191 // copy operation can take a non-const reference) as an implicit 4192 // declaration, and 4193 // -- not have default arguments. 4194 unsigned ExpectedParams = 1; 4195 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 4196 ExpectedParams = 0; 4197 if (MD->getNumParams() != ExpectedParams) { 4198 // This also checks for default arguments: a copy or move constructor with a 4199 // default argument is classified as a default constructor, and assignment 4200 // operations and destructors can't have default arguments. 4201 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 4202 << CSM << MD->getSourceRange(); 4203 HadError = true; 4204 } else if (MD->isVariadic()) { 4205 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 4206 << CSM << MD->getSourceRange(); 4207 HadError = true; 4208 } 4209 4210 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 4211 4212 bool CanHaveConstParam = false; 4213 if (CSM == CXXCopyConstructor) 4214 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 4215 else if (CSM == CXXCopyAssignment) 4216 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 4217 4218 QualType ReturnType = Context.VoidTy; 4219 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 4220 // Check for return type matching. 4221 ReturnType = Type->getResultType(); 4222 QualType ExpectedReturnType = 4223 Context.getLValueReferenceType(Context.getTypeDeclType(RD)); 4224 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 4225 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 4226 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 4227 HadError = true; 4228 } 4229 4230 // A defaulted special member cannot have cv-qualifiers. 4231 if (Type->getTypeQuals()) { 4232 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 4233 << (CSM == CXXMoveAssignment); 4234 HadError = true; 4235 } 4236 } 4237 4238 // Check for parameter type matching. 4239 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType(); 4240 bool HasConstParam = false; 4241 if (ExpectedParams && ArgType->isReferenceType()) { 4242 // Argument must be reference to possibly-const T. 4243 QualType ReferentType = ArgType->getPointeeType(); 4244 HasConstParam = ReferentType.isConstQualified(); 4245 4246 if (ReferentType.isVolatileQualified()) { 4247 Diag(MD->getLocation(), 4248 diag::err_defaulted_special_member_volatile_param) << CSM; 4249 HadError = true; 4250 } 4251 4252 if (HasConstParam && !CanHaveConstParam) { 4253 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 4254 Diag(MD->getLocation(), 4255 diag::err_defaulted_special_member_copy_const_param) 4256 << (CSM == CXXCopyAssignment); 4257 // FIXME: Explain why this special member can't be const. 4258 } else { 4259 Diag(MD->getLocation(), 4260 diag::err_defaulted_special_member_move_const_param) 4261 << (CSM == CXXMoveAssignment); 4262 } 4263 HadError = true; 4264 } 4265 } else if (ExpectedParams) { 4266 // A copy assignment operator can take its argument by value, but a 4267 // defaulted one cannot. 4268 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 4269 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 4270 HadError = true; 4271 } 4272 4273 // Rebuild the type with the implicit exception specification added, if we 4274 // are going to need it. 4275 const FunctionProtoType *ImplicitType = 0; 4276 if (First || Type->hasExceptionSpec()) { 4277 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 4278 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI); 4279 ImplicitType = cast<FunctionProtoType>( 4280 Context.getFunctionType(ReturnType, &ArgType, ExpectedParams, EPI)); 4281 } 4282 4283 // C++11 [dcl.fct.def.default]p2: 4284 // An explicitly-defaulted function may be declared constexpr only if it 4285 // would have been implicitly declared as constexpr, 4286 // Do not apply this rule to members of class templates, since core issue 1358 4287 // makes such functions always instantiate to constexpr functions. For 4288 // non-constructors, this is checked elsewhere. 4289 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 4290 HasConstParam); 4291 if (isa<CXXConstructorDecl>(MD) && MD->isConstexpr() && !Constexpr && 4292 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 4293 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM; 4294 // FIXME: Explain why the constructor can't be constexpr. 4295 HadError = true; 4296 } 4297 // and may have an explicit exception-specification only if it is compatible 4298 // with the exception-specification on the implicit declaration. 4299 if (Type->hasExceptionSpec() && 4300 CheckEquivalentExceptionSpec( 4301 PDiag(diag::err_incorrect_defaulted_exception_spec) << CSM, 4302 PDiag(), ImplicitType, SourceLocation(), Type, MD->getLocation())) 4303 HadError = true; 4304 4305 // If a function is explicitly defaulted on its first declaration, 4306 if (First) { 4307 // -- it is implicitly considered to be constexpr if the implicit 4308 // definition would be, 4309 MD->setConstexpr(Constexpr); 4310 4311 // -- it is implicitly considered to have the same exception-specification 4312 // as if it had been implicitly declared, 4313 MD->setType(QualType(ImplicitType, 0)); 4314 } 4315 4316 if (ShouldDeleteSpecialMember(MD, CSM)) { 4317 if (First) { 4318 MD->setDeletedAsWritten(); 4319 } else { 4320 // C++11 [dcl.fct.def.default]p4: 4321 // [For a] user-provided explicitly-defaulted function [...] if such a 4322 // function is implicitly defined as deleted, the program is ill-formed. 4323 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 4324 HadError = true; 4325 } 4326 } 4327 4328 if (HadError) 4329 MD->setInvalidDecl(); 4330} 4331 4332namespace { 4333struct SpecialMemberDeletionInfo { 4334 Sema &S; 4335 CXXMethodDecl *MD; 4336 Sema::CXXSpecialMember CSM; 4337 bool Diagnose; 4338 4339 // Properties of the special member, computed for convenience. 4340 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg; 4341 SourceLocation Loc; 4342 4343 bool AllFieldsAreConst; 4344 4345 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 4346 Sema::CXXSpecialMember CSM, bool Diagnose) 4347 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose), 4348 IsConstructor(false), IsAssignment(false), IsMove(false), 4349 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()), 4350 AllFieldsAreConst(true) { 4351 switch (CSM) { 4352 case Sema::CXXDefaultConstructor: 4353 case Sema::CXXCopyConstructor: 4354 IsConstructor = true; 4355 break; 4356 case Sema::CXXMoveConstructor: 4357 IsConstructor = true; 4358 IsMove = true; 4359 break; 4360 case Sema::CXXCopyAssignment: 4361 IsAssignment = true; 4362 break; 4363 case Sema::CXXMoveAssignment: 4364 IsAssignment = true; 4365 IsMove = true; 4366 break; 4367 case Sema::CXXDestructor: 4368 break; 4369 case Sema::CXXInvalid: 4370 llvm_unreachable("invalid special member kind"); 4371 } 4372 4373 if (MD->getNumParams()) { 4374 ConstArg = MD->getParamDecl(0)->getType().isConstQualified(); 4375 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified(); 4376 } 4377 } 4378 4379 bool inUnion() const { return MD->getParent()->isUnion(); } 4380 4381 /// Look up the corresponding special member in the given class. 4382 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class, 4383 unsigned Quals) { 4384 unsigned TQ = MD->getTypeQualifiers(); 4385 // cv-qualifiers on class members don't affect default ctor / dtor calls. 4386 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 4387 Quals = 0; 4388 return S.LookupSpecialMember(Class, CSM, 4389 ConstArg || (Quals & Qualifiers::Const), 4390 VolatileArg || (Quals & Qualifiers::Volatile), 4391 MD->getRefQualifier() == RQ_RValue, 4392 TQ & Qualifiers::Const, 4393 TQ & Qualifiers::Volatile); 4394 } 4395 4396 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 4397 4398 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 4399 bool shouldDeleteForField(FieldDecl *FD); 4400 bool shouldDeleteForAllConstMembers(); 4401 4402 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 4403 unsigned Quals); 4404 bool shouldDeleteForSubobjectCall(Subobject Subobj, 4405 Sema::SpecialMemberOverloadResult *SMOR, 4406 bool IsDtorCallInCtor); 4407 4408 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 4409}; 4410} 4411 4412/// Is the given special member inaccessible when used on the given 4413/// sub-object. 4414bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 4415 CXXMethodDecl *target) { 4416 /// If we're operating on a base class, the object type is the 4417 /// type of this special member. 4418 QualType objectTy; 4419 AccessSpecifier access = target->getAccess(); 4420 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 4421 objectTy = S.Context.getTypeDeclType(MD->getParent()); 4422 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 4423 4424 // If we're operating on a field, the object type is the type of the field. 4425 } else { 4426 objectTy = S.Context.getTypeDeclType(target->getParent()); 4427 } 4428 4429 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 4430} 4431 4432/// Check whether we should delete a special member due to the implicit 4433/// definition containing a call to a special member of a subobject. 4434bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 4435 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR, 4436 bool IsDtorCallInCtor) { 4437 CXXMethodDecl *Decl = SMOR->getMethod(); 4438 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 4439 4440 int DiagKind = -1; 4441 4442 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 4443 DiagKind = !Decl ? 0 : 1; 4444 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 4445 DiagKind = 2; 4446 else if (!isAccessible(Subobj, Decl)) 4447 DiagKind = 3; 4448 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 4449 !Decl->isTrivial()) { 4450 // A member of a union must have a trivial corresponding special member. 4451 // As a weird special case, a destructor call from a union's constructor 4452 // must be accessible and non-deleted, but need not be trivial. Such a 4453 // destructor is never actually called, but is semantically checked as 4454 // if it were. 4455 DiagKind = 4; 4456 } 4457 4458 if (DiagKind == -1) 4459 return false; 4460 4461 if (Diagnose) { 4462 if (Field) { 4463 S.Diag(Field->getLocation(), 4464 diag::note_deleted_special_member_class_subobject) 4465 << CSM << MD->getParent() << /*IsField*/true 4466 << Field << DiagKind << IsDtorCallInCtor; 4467 } else { 4468 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 4469 S.Diag(Base->getLocStart(), 4470 diag::note_deleted_special_member_class_subobject) 4471 << CSM << MD->getParent() << /*IsField*/false 4472 << Base->getType() << DiagKind << IsDtorCallInCtor; 4473 } 4474 4475 if (DiagKind == 1) 4476 S.NoteDeletedFunction(Decl); 4477 // FIXME: Explain inaccessibility if DiagKind == 3. 4478 } 4479 4480 return true; 4481} 4482 4483/// Check whether we should delete a special member function due to having a 4484/// direct or virtual base class or non-static data member of class type M. 4485bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 4486 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 4487 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 4488 4489 // C++11 [class.ctor]p5: 4490 // -- any direct or virtual base class, or non-static data member with no 4491 // brace-or-equal-initializer, has class type M (or array thereof) and 4492 // either M has no default constructor or overload resolution as applied 4493 // to M's default constructor results in an ambiguity or in a function 4494 // that is deleted or inaccessible 4495 // C++11 [class.copy]p11, C++11 [class.copy]p23: 4496 // -- a direct or virtual base class B that cannot be copied/moved because 4497 // overload resolution, as applied to B's corresponding special member, 4498 // results in an ambiguity or a function that is deleted or inaccessible 4499 // from the defaulted special member 4500 // C++11 [class.dtor]p5: 4501 // -- any direct or virtual base class [...] has a type with a destructor 4502 // that is deleted or inaccessible 4503 if (!(CSM == Sema::CXXDefaultConstructor && 4504 Field && Field->hasInClassInitializer()) && 4505 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false)) 4506 return true; 4507 4508 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 4509 // -- any direct or virtual base class or non-static data member has a 4510 // type with a destructor that is deleted or inaccessible 4511 if (IsConstructor) { 4512 Sema::SpecialMemberOverloadResult *SMOR = 4513 S.LookupSpecialMember(Class, Sema::CXXDestructor, 4514 false, false, false, false, false); 4515 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 4516 return true; 4517 } 4518 4519 return false; 4520} 4521 4522/// Check whether we should delete a special member function due to the class 4523/// having a particular direct or virtual base class. 4524bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 4525 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 4526 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 4527} 4528 4529/// Check whether we should delete a special member function due to the class 4530/// having a particular non-static data member. 4531bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 4532 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 4533 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 4534 4535 if (CSM == Sema::CXXDefaultConstructor) { 4536 // For a default constructor, all references must be initialized in-class 4537 // and, if a union, it must have a non-const member. 4538 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 4539 if (Diagnose) 4540 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 4541 << MD->getParent() << FD << FieldType << /*Reference*/0; 4542 return true; 4543 } 4544 // C++11 [class.ctor]p5: any non-variant non-static data member of 4545 // const-qualified type (or array thereof) with no 4546 // brace-or-equal-initializer does not have a user-provided default 4547 // constructor. 4548 if (!inUnion() && FieldType.isConstQualified() && 4549 !FD->hasInClassInitializer() && 4550 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 4551 if (Diagnose) 4552 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 4553 << MD->getParent() << FD << FD->getType() << /*Const*/1; 4554 return true; 4555 } 4556 4557 if (inUnion() && !FieldType.isConstQualified()) 4558 AllFieldsAreConst = false; 4559 } else if (CSM == Sema::CXXCopyConstructor) { 4560 // For a copy constructor, data members must not be of rvalue reference 4561 // type. 4562 if (FieldType->isRValueReferenceType()) { 4563 if (Diagnose) 4564 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 4565 << MD->getParent() << FD << FieldType; 4566 return true; 4567 } 4568 } else if (IsAssignment) { 4569 // For an assignment operator, data members must not be of reference type. 4570 if (FieldType->isReferenceType()) { 4571 if (Diagnose) 4572 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 4573 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0; 4574 return true; 4575 } 4576 if (!FieldRecord && FieldType.isConstQualified()) { 4577 // C++11 [class.copy]p23: 4578 // -- a non-static data member of const non-class type (or array thereof) 4579 if (Diagnose) 4580 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 4581 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1; 4582 return true; 4583 } 4584 } 4585 4586 if (FieldRecord) { 4587 // Some additional restrictions exist on the variant members. 4588 if (!inUnion() && FieldRecord->isUnion() && 4589 FieldRecord->isAnonymousStructOrUnion()) { 4590 bool AllVariantFieldsAreConst = true; 4591 4592 // FIXME: Handle anonymous unions declared within anonymous unions. 4593 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(), 4594 UE = FieldRecord->field_end(); 4595 UI != UE; ++UI) { 4596 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 4597 4598 if (!UnionFieldType.isConstQualified()) 4599 AllVariantFieldsAreConst = false; 4600 4601 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 4602 if (UnionFieldRecord && 4603 shouldDeleteForClassSubobject(UnionFieldRecord, *UI, 4604 UnionFieldType.getCVRQualifiers())) 4605 return true; 4606 } 4607 4608 // At least one member in each anonymous union must be non-const 4609 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 4610 FieldRecord->field_begin() != FieldRecord->field_end()) { 4611 if (Diagnose) 4612 S.Diag(FieldRecord->getLocation(), 4613 diag::note_deleted_default_ctor_all_const) 4614 << MD->getParent() << /*anonymous union*/1; 4615 return true; 4616 } 4617 4618 // Don't check the implicit member of the anonymous union type. 4619 // This is technically non-conformant, but sanity demands it. 4620 return false; 4621 } 4622 4623 if (shouldDeleteForClassSubobject(FieldRecord, FD, 4624 FieldType.getCVRQualifiers())) 4625 return true; 4626 } 4627 4628 return false; 4629} 4630 4631/// C++11 [class.ctor] p5: 4632/// A defaulted default constructor for a class X is defined as deleted if 4633/// X is a union and all of its variant members are of const-qualified type. 4634bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 4635 // This is a silly definition, because it gives an empty union a deleted 4636 // default constructor. Don't do that. 4637 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst && 4638 (MD->getParent()->field_begin() != MD->getParent()->field_end())) { 4639 if (Diagnose) 4640 S.Diag(MD->getParent()->getLocation(), 4641 diag::note_deleted_default_ctor_all_const) 4642 << MD->getParent() << /*not anonymous union*/0; 4643 return true; 4644 } 4645 return false; 4646} 4647 4648/// Determine whether a defaulted special member function should be defined as 4649/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 4650/// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 4651bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 4652 bool Diagnose) { 4653 if (MD->isInvalidDecl()) 4654 return false; 4655 CXXRecordDecl *RD = MD->getParent(); 4656 assert(!RD->isDependentType() && "do deletion after instantiation"); 4657 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl()) 4658 return false; 4659 4660 // C++11 [expr.lambda.prim]p19: 4661 // The closure type associated with a lambda-expression has a 4662 // deleted (8.4.3) default constructor and a deleted copy 4663 // assignment operator. 4664 if (RD->isLambda() && 4665 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 4666 if (Diagnose) 4667 Diag(RD->getLocation(), diag::note_lambda_decl); 4668 return true; 4669 } 4670 4671 // For an anonymous struct or union, the copy and assignment special members 4672 // will never be used, so skip the check. For an anonymous union declared at 4673 // namespace scope, the constructor and destructor are used. 4674 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 4675 RD->isAnonymousStructOrUnion()) 4676 return false; 4677 4678 // C++11 [class.copy]p7, p18: 4679 // If the class definition declares a move constructor or move assignment 4680 // operator, an implicitly declared copy constructor or copy assignment 4681 // operator is defined as deleted. 4682 if (MD->isImplicit() && 4683 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 4684 CXXMethodDecl *UserDeclaredMove = 0; 4685 4686 // In Microsoft mode, a user-declared move only causes the deletion of the 4687 // corresponding copy operation, not both copy operations. 4688 if (RD->hasUserDeclaredMoveConstructor() && 4689 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) { 4690 if (!Diagnose) return true; 4691 4692 // Find any user-declared move constructor. 4693 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(), 4694 E = RD->ctor_end(); I != E; ++I) { 4695 if (I->isMoveConstructor()) { 4696 UserDeclaredMove = *I; 4697 break; 4698 } 4699 } 4700 assert(UserDeclaredMove); 4701 } else if (RD->hasUserDeclaredMoveAssignment() && 4702 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) { 4703 if (!Diagnose) return true; 4704 4705 // Find any user-declared move assignment operator. 4706 for (CXXRecordDecl::method_iterator I = RD->method_begin(), 4707 E = RD->method_end(); I != E; ++I) { 4708 if (I->isMoveAssignmentOperator()) { 4709 UserDeclaredMove = *I; 4710 break; 4711 } 4712 } 4713 assert(UserDeclaredMove); 4714 } 4715 4716 if (UserDeclaredMove) { 4717 Diag(UserDeclaredMove->getLocation(), 4718 diag::note_deleted_copy_user_declared_move) 4719 << (CSM == CXXCopyAssignment) << RD 4720 << UserDeclaredMove->isMoveAssignmentOperator(); 4721 return true; 4722 } 4723 } 4724 4725 // Do access control from the special member function 4726 ContextRAII MethodContext(*this, MD); 4727 4728 // C++11 [class.dtor]p5: 4729 // -- for a virtual destructor, lookup of the non-array deallocation function 4730 // results in an ambiguity or in a function that is deleted or inaccessible 4731 if (CSM == CXXDestructor && MD->isVirtual()) { 4732 FunctionDecl *OperatorDelete = 0; 4733 DeclarationName Name = 4734 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 4735 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 4736 OperatorDelete, false)) { 4737 if (Diagnose) 4738 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 4739 return true; 4740 } 4741 } 4742 4743 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose); 4744 4745 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 4746 BE = RD->bases_end(); BI != BE; ++BI) 4747 if (!BI->isVirtual() && 4748 SMI.shouldDeleteForBase(BI)) 4749 return true; 4750 4751 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(), 4752 BE = RD->vbases_end(); BI != BE; ++BI) 4753 if (SMI.shouldDeleteForBase(BI)) 4754 return true; 4755 4756 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 4757 FE = RD->field_end(); FI != FE; ++FI) 4758 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() && 4759 SMI.shouldDeleteForField(*FI)) 4760 return true; 4761 4762 if (SMI.shouldDeleteForAllConstMembers()) 4763 return true; 4764 4765 return false; 4766} 4767 4768/// Perform lookup for a special member of the specified kind, and determine 4769/// whether it is trivial. If the triviality can be determined without the 4770/// lookup, skip it. This is intended for use when determining whether a 4771/// special member of a containing object is trivial, and thus does not ever 4772/// perform overload resolution for default constructors. 4773/// 4774/// If \p Selected is not \c NULL, \c *Selected will be filled in with the 4775/// member that was most likely to be intended to be trivial, if any. 4776static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 4777 Sema::CXXSpecialMember CSM, unsigned Quals, 4778 CXXMethodDecl **Selected) { 4779 if (Selected) 4780 *Selected = 0; 4781 4782 switch (CSM) { 4783 case Sema::CXXInvalid: 4784 llvm_unreachable("not a special member"); 4785 4786 case Sema::CXXDefaultConstructor: 4787 // C++11 [class.ctor]p5: 4788 // A default constructor is trivial if: 4789 // - all the [direct subobjects] have trivial default constructors 4790 // 4791 // Note, no overload resolution is performed in this case. 4792 if (RD->hasTrivialDefaultConstructor()) 4793 return true; 4794 4795 if (Selected) { 4796 // If there's a default constructor which could have been trivial, dig it 4797 // out. Otherwise, if there's any user-provided default constructor, point 4798 // to that as an example of why there's not a trivial one. 4799 CXXConstructorDecl *DefCtor = 0; 4800 if (RD->needsImplicitDefaultConstructor()) 4801 S.DeclareImplicitDefaultConstructor(RD); 4802 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), 4803 CE = RD->ctor_end(); CI != CE; ++CI) { 4804 if (!CI->isDefaultConstructor()) 4805 continue; 4806 DefCtor = *CI; 4807 if (!DefCtor->isUserProvided()) 4808 break; 4809 } 4810 4811 *Selected = DefCtor; 4812 } 4813 4814 return false; 4815 4816 case Sema::CXXDestructor: 4817 // C++11 [class.dtor]p5: 4818 // A destructor is trivial if: 4819 // - all the direct [subobjects] have trivial destructors 4820 if (RD->hasTrivialDestructor()) 4821 return true; 4822 4823 if (Selected) { 4824 if (RD->needsImplicitDestructor()) 4825 S.DeclareImplicitDestructor(RD); 4826 *Selected = RD->getDestructor(); 4827 } 4828 4829 return false; 4830 4831 case Sema::CXXCopyConstructor: 4832 // C++11 [class.copy]p12: 4833 // A copy constructor is trivial if: 4834 // - the constructor selected to copy each direct [subobject] is trivial 4835 if (RD->hasTrivialCopyConstructor()) { 4836 if (Quals == Qualifiers::Const) 4837 // We must either select the trivial copy constructor or reach an 4838 // ambiguity; no need to actually perform overload resolution. 4839 return true; 4840 } else if (!Selected) { 4841 return false; 4842 } 4843 // In C++98, we are not supposed to perform overload resolution here, but we 4844 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 4845 // cases like B as having a non-trivial copy constructor: 4846 // struct A { template<typename T> A(T&); }; 4847 // struct B { mutable A a; }; 4848 goto NeedOverloadResolution; 4849 4850 case Sema::CXXCopyAssignment: 4851 // C++11 [class.copy]p25: 4852 // A copy assignment operator is trivial if: 4853 // - the assignment operator selected to copy each direct [subobject] is 4854 // trivial 4855 if (RD->hasTrivialCopyAssignment()) { 4856 if (Quals == Qualifiers::Const) 4857 return true; 4858 } else if (!Selected) { 4859 return false; 4860 } 4861 // In C++98, we are not supposed to perform overload resolution here, but we 4862 // treat that as a language defect. 4863 goto NeedOverloadResolution; 4864 4865 case Sema::CXXMoveConstructor: 4866 case Sema::CXXMoveAssignment: 4867 NeedOverloadResolution: 4868 Sema::SpecialMemberOverloadResult *SMOR = 4869 S.LookupSpecialMember(RD, CSM, 4870 Quals & Qualifiers::Const, 4871 Quals & Qualifiers::Volatile, 4872 /*RValueThis*/false, /*ConstThis*/false, 4873 /*VolatileThis*/false); 4874 4875 // The standard doesn't describe how to behave if the lookup is ambiguous. 4876 // We treat it as not making the member non-trivial, just like the standard 4877 // mandates for the default constructor. This should rarely matter, because 4878 // the member will also be deleted. 4879 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 4880 return true; 4881 4882 if (!SMOR->getMethod()) { 4883 assert(SMOR->getKind() == 4884 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 4885 return false; 4886 } 4887 4888 // We deliberately don't check if we found a deleted special member. We're 4889 // not supposed to! 4890 if (Selected) 4891 *Selected = SMOR->getMethod(); 4892 return SMOR->getMethod()->isTrivial(); 4893 } 4894 4895 llvm_unreachable("unknown special method kind"); 4896} 4897 4898CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 4899 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end(); 4900 CI != CE; ++CI) 4901 if (!CI->isImplicit()) 4902 return *CI; 4903 4904 // Look for constructor templates. 4905 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 4906 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 4907 if (CXXConstructorDecl *CD = 4908 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 4909 return CD; 4910 } 4911 4912 return 0; 4913} 4914 4915/// The kind of subobject we are checking for triviality. The values of this 4916/// enumeration are used in diagnostics. 4917enum TrivialSubobjectKind { 4918 /// The subobject is a base class. 4919 TSK_BaseClass, 4920 /// The subobject is a non-static data member. 4921 TSK_Field, 4922 /// The object is actually the complete object. 4923 TSK_CompleteObject 4924}; 4925 4926/// Check whether the special member selected for a given type would be trivial. 4927static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 4928 QualType SubType, 4929 Sema::CXXSpecialMember CSM, 4930 TrivialSubobjectKind Kind, 4931 bool Diagnose) { 4932 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 4933 if (!SubRD) 4934 return true; 4935 4936 CXXMethodDecl *Selected; 4937 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 4938 Diagnose ? &Selected : 0)) 4939 return true; 4940 4941 if (Diagnose) { 4942 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 4943 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 4944 << Kind << SubType.getUnqualifiedType(); 4945 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 4946 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 4947 } else if (!Selected) 4948 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 4949 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 4950 else if (Selected->isUserProvided()) { 4951 if (Kind == TSK_CompleteObject) 4952 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 4953 << Kind << SubType.getUnqualifiedType() << CSM; 4954 else { 4955 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 4956 << Kind << SubType.getUnqualifiedType() << CSM; 4957 S.Diag(Selected->getLocation(), diag::note_declared_at); 4958 } 4959 } else { 4960 if (Kind != TSK_CompleteObject) 4961 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 4962 << Kind << SubType.getUnqualifiedType() << CSM; 4963 4964 // Explain why the defaulted or deleted special member isn't trivial. 4965 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose); 4966 } 4967 } 4968 4969 return false; 4970} 4971 4972/// Check whether the members of a class type allow a special member to be 4973/// trivial. 4974static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 4975 Sema::CXXSpecialMember CSM, 4976 bool ConstArg, bool Diagnose) { 4977 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 4978 FE = RD->field_end(); FI != FE; ++FI) { 4979 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 4980 continue; 4981 4982 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 4983 4984 // Pretend anonymous struct or union members are members of this class. 4985 if (FI->isAnonymousStructOrUnion()) { 4986 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 4987 CSM, ConstArg, Diagnose)) 4988 return false; 4989 continue; 4990 } 4991 4992 // C++11 [class.ctor]p5: 4993 // A default constructor is trivial if [...] 4994 // -- no non-static data member of its class has a 4995 // brace-or-equal-initializer 4996 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 4997 if (Diagnose) 4998 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI; 4999 return false; 5000 } 5001 5002 // Objective C ARC 4.3.5: 5003 // [...] nontrivally ownership-qualified types are [...] not trivially 5004 // default constructible, copy constructible, move constructible, copy 5005 // assignable, move assignable, or destructible [...] 5006 if (S.getLangOpts().ObjCAutoRefCount && 5007 FieldType.hasNonTrivialObjCLifetime()) { 5008 if (Diagnose) 5009 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 5010 << RD << FieldType.getObjCLifetime(); 5011 return false; 5012 } 5013 5014 if (ConstArg && !FI->isMutable()) 5015 FieldType.addConst(); 5016 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM, 5017 TSK_Field, Diagnose)) 5018 return false; 5019 } 5020 5021 return true; 5022} 5023 5024/// Diagnose why the specified class does not have a trivial special member of 5025/// the given kind. 5026void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 5027 QualType Ty = Context.getRecordType(RD); 5028 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) 5029 Ty.addConst(); 5030 5031 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM, 5032 TSK_CompleteObject, /*Diagnose*/true); 5033} 5034 5035/// Determine whether a defaulted or deleted special member function is trivial, 5036/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 5037/// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 5038bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 5039 bool Diagnose) { 5040 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 5041 5042 CXXRecordDecl *RD = MD->getParent(); 5043 5044 bool ConstArg = false; 5045 ParmVarDecl *Param0 = MD->getNumParams() ? MD->getParamDecl(0) : 0; 5046 5047 // C++11 [class.copy]p12, p25: 5048 // A [special member] is trivial if its declared parameter type is the same 5049 // as if it had been implicitly declared [...] 5050 switch (CSM) { 5051 case CXXDefaultConstructor: 5052 case CXXDestructor: 5053 // Trivial default constructors and destructors cannot have parameters. 5054 break; 5055 5056 case CXXCopyConstructor: 5057 case CXXCopyAssignment: { 5058 // Trivial copy operations always have const, non-volatile parameter types. 5059 ConstArg = true; 5060 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 5061 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 5062 if (Diagnose) 5063 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 5064 << Param0->getSourceRange() << Param0->getType() 5065 << Context.getLValueReferenceType( 5066 Context.getRecordType(RD).withConst()); 5067 return false; 5068 } 5069 break; 5070 } 5071 5072 case CXXMoveConstructor: 5073 case CXXMoveAssignment: { 5074 // Trivial move operations always have non-cv-qualified parameters. 5075 const RValueReferenceType *RT = 5076 Param0->getType()->getAs<RValueReferenceType>(); 5077 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 5078 if (Diagnose) 5079 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 5080 << Param0->getSourceRange() << Param0->getType() 5081 << Context.getRValueReferenceType(Context.getRecordType(RD)); 5082 return false; 5083 } 5084 break; 5085 } 5086 5087 case CXXInvalid: 5088 llvm_unreachable("not a special member"); 5089 } 5090 5091 // FIXME: We require that the parameter-declaration-clause is equivalent to 5092 // that of an implicit declaration, not just that the declared parameter type 5093 // matches, in order to prevent absuridities like a function simultaneously 5094 // being a trivial copy constructor and a non-trivial default constructor. 5095 // This issue has not yet been assigned a core issue number. 5096 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 5097 if (Diagnose) 5098 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 5099 diag::note_nontrivial_default_arg) 5100 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 5101 return false; 5102 } 5103 if (MD->isVariadic()) { 5104 if (Diagnose) 5105 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 5106 return false; 5107 } 5108 5109 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 5110 // A copy/move [constructor or assignment operator] is trivial if 5111 // -- the [member] selected to copy/move each direct base class subobject 5112 // is trivial 5113 // 5114 // C++11 [class.copy]p12, C++11 [class.copy]p25: 5115 // A [default constructor or destructor] is trivial if 5116 // -- all the direct base classes have trivial [default constructors or 5117 // destructors] 5118 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 5119 BE = RD->bases_end(); BI != BE; ++BI) 5120 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(), 5121 ConstArg ? BI->getType().withConst() 5122 : BI->getType(), 5123 CSM, TSK_BaseClass, Diagnose)) 5124 return false; 5125 5126 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 5127 // A copy/move [constructor or assignment operator] for a class X is 5128 // trivial if 5129 // -- for each non-static data member of X that is of class type (or array 5130 // thereof), the constructor selected to copy/move that member is 5131 // trivial 5132 // 5133 // C++11 [class.copy]p12, C++11 [class.copy]p25: 5134 // A [default constructor or destructor] is trivial if 5135 // -- for all of the non-static data members of its class that are of class 5136 // type (or array thereof), each such class has a trivial [default 5137 // constructor or destructor] 5138 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose)) 5139 return false; 5140 5141 // C++11 [class.dtor]p5: 5142 // A destructor is trivial if [...] 5143 // -- the destructor is not virtual 5144 if (CSM == CXXDestructor && MD->isVirtual()) { 5145 if (Diagnose) 5146 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 5147 return false; 5148 } 5149 5150 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 5151 // A [special member] for class X is trivial if [...] 5152 // -- class X has no virtual functions and no virtual base classes 5153 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 5154 if (!Diagnose) 5155 return false; 5156 5157 if (RD->getNumVBases()) { 5158 // Check for virtual bases. We already know that the corresponding 5159 // member in all bases is trivial, so vbases must all be direct. 5160 CXXBaseSpecifier &BS = *RD->vbases_begin(); 5161 assert(BS.isVirtual()); 5162 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1; 5163 return false; 5164 } 5165 5166 // Must have a virtual method. 5167 for (CXXRecordDecl::method_iterator MI = RD->method_begin(), 5168 ME = RD->method_end(); MI != ME; ++MI) { 5169 if (MI->isVirtual()) { 5170 SourceLocation MLoc = MI->getLocStart(); 5171 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 5172 return false; 5173 } 5174 } 5175 5176 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 5177 } 5178 5179 // Looks like it's trivial! 5180 return true; 5181} 5182 5183/// \brief Data used with FindHiddenVirtualMethod 5184namespace { 5185 struct FindHiddenVirtualMethodData { 5186 Sema *S; 5187 CXXMethodDecl *Method; 5188 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 5189 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 5190 }; 5191} 5192 5193/// \brief Check whether any most overriden method from MD in Methods 5194static bool CheckMostOverridenMethods(const CXXMethodDecl *MD, 5195 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) { 5196 if (MD->size_overridden_methods() == 0) 5197 return Methods.count(MD->getCanonicalDecl()); 5198 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 5199 E = MD->end_overridden_methods(); 5200 I != E; ++I) 5201 if (CheckMostOverridenMethods(*I, Methods)) 5202 return true; 5203 return false; 5204} 5205 5206/// \brief Member lookup function that determines whether a given C++ 5207/// method overloads virtual methods in a base class without overriding any, 5208/// to be used with CXXRecordDecl::lookupInBases(). 5209static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier, 5210 CXXBasePath &Path, 5211 void *UserData) { 5212 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 5213 5214 FindHiddenVirtualMethodData &Data 5215 = *static_cast<FindHiddenVirtualMethodData*>(UserData); 5216 5217 DeclarationName Name = Data.Method->getDeclName(); 5218 assert(Name.getNameKind() == DeclarationName::Identifier); 5219 5220 bool foundSameNameMethod = false; 5221 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 5222 for (Path.Decls = BaseRecord->lookup(Name); 5223 Path.Decls.first != Path.Decls.second; 5224 ++Path.Decls.first) { 5225 NamedDecl *D = *Path.Decls.first; 5226 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 5227 MD = MD->getCanonicalDecl(); 5228 foundSameNameMethod = true; 5229 // Interested only in hidden virtual methods. 5230 if (!MD->isVirtual()) 5231 continue; 5232 // If the method we are checking overrides a method from its base 5233 // don't warn about the other overloaded methods. 5234 if (!Data.S->IsOverload(Data.Method, MD, false)) 5235 return true; 5236 // Collect the overload only if its hidden. 5237 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods)) 5238 overloadedMethods.push_back(MD); 5239 } 5240 } 5241 5242 if (foundSameNameMethod) 5243 Data.OverloadedMethods.append(overloadedMethods.begin(), 5244 overloadedMethods.end()); 5245 return foundSameNameMethod; 5246} 5247 5248/// \brief Add the most overriden methods from MD to Methods 5249static void AddMostOverridenMethods(const CXXMethodDecl *MD, 5250 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) { 5251 if (MD->size_overridden_methods() == 0) 5252 Methods.insert(MD->getCanonicalDecl()); 5253 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 5254 E = MD->end_overridden_methods(); 5255 I != E; ++I) 5256 AddMostOverridenMethods(*I, Methods); 5257} 5258 5259/// \brief See if a method overloads virtual methods in a base class without 5260/// overriding any. 5261void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 5262 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual, 5263 MD->getLocation()) == DiagnosticsEngine::Ignored) 5264 return; 5265 if (!MD->getDeclName().isIdentifier()) 5266 return; 5267 5268 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 5269 /*bool RecordPaths=*/false, 5270 /*bool DetectVirtual=*/false); 5271 FindHiddenVirtualMethodData Data; 5272 Data.Method = MD; 5273 Data.S = this; 5274 5275 // Keep the base methods that were overriden or introduced in the subclass 5276 // by 'using' in a set. A base method not in this set is hidden. 5277 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName()); 5278 res.first != res.second; ++res.first) { 5279 NamedDecl *ND = *res.first; 5280 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first)) 5281 ND = shad->getTargetDecl(); 5282 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 5283 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods); 5284 } 5285 5286 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) && 5287 !Data.OverloadedMethods.empty()) { 5288 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 5289 << MD << (Data.OverloadedMethods.size() > 1); 5290 5291 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) { 5292 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i]; 5293 Diag(overloadedMD->getLocation(), 5294 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 5295 } 5296 } 5297} 5298 5299void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 5300 Decl *TagDecl, 5301 SourceLocation LBrac, 5302 SourceLocation RBrac, 5303 AttributeList *AttrList) { 5304 if (!TagDecl) 5305 return; 5306 5307 AdjustDeclIfTemplate(TagDecl); 5308 5309 for (const AttributeList* l = AttrList; l; l = l->getNext()) { 5310 if (l->getKind() != AttributeList::AT_Visibility) 5311 continue; 5312 l->setInvalid(); 5313 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) << 5314 l->getName(); 5315 } 5316 5317 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 5318 // strict aliasing violation! 5319 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 5320 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 5321 5322 CheckCompletedCXXClass( 5323 dyn_cast_or_null<CXXRecordDecl>(TagDecl)); 5324} 5325 5326/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 5327/// special functions, such as the default constructor, copy 5328/// constructor, or destructor, to the given C++ class (C++ 5329/// [special]p1). This routine can only be executed just before the 5330/// definition of the class is complete. 5331void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 5332 if (!ClassDecl->hasUserDeclaredConstructor()) 5333 ++ASTContext::NumImplicitDefaultConstructors; 5334 5335 if (!ClassDecl->hasUserDeclaredCopyConstructor()) { 5336 ++ASTContext::NumImplicitCopyConstructors; 5337 5338 // If the properties or semantics of the copy constructor couldn't be 5339 // determined while the class was being declared, force a declaration 5340 // of it now. 5341 if (ClassDecl->needsOverloadResolutionForCopyConstructor()) 5342 DeclareImplicitCopyConstructor(ClassDecl); 5343 } 5344 5345 if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveConstructor()) { 5346 ++ASTContext::NumImplicitMoveConstructors; 5347 5348 if (ClassDecl->needsOverloadResolutionForMoveConstructor()) 5349 DeclareImplicitMoveConstructor(ClassDecl); 5350 } 5351 5352 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 5353 ++ASTContext::NumImplicitCopyAssignmentOperators; 5354 5355 // If we have a dynamic class, then the copy assignment operator may be 5356 // virtual, so we have to declare it immediately. This ensures that, e.g., 5357 // it shows up in the right place in the vtable and that we diagnose 5358 // problems with the implicit exception specification. 5359 if (ClassDecl->isDynamicClass() || 5360 ClassDecl->needsOverloadResolutionForCopyAssignment()) 5361 DeclareImplicitCopyAssignment(ClassDecl); 5362 } 5363 5364 if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveAssignment()) { 5365 ++ASTContext::NumImplicitMoveAssignmentOperators; 5366 5367 // Likewise for the move assignment operator. 5368 if (ClassDecl->isDynamicClass() || 5369 ClassDecl->needsOverloadResolutionForMoveAssignment()) 5370 DeclareImplicitMoveAssignment(ClassDecl); 5371 } 5372 5373 if (!ClassDecl->hasUserDeclaredDestructor()) { 5374 ++ASTContext::NumImplicitDestructors; 5375 5376 // If we have a dynamic class, then the destructor may be virtual, so we 5377 // have to declare the destructor immediately. This ensures that, e.g., it 5378 // shows up in the right place in the vtable and that we diagnose problems 5379 // with the implicit exception specification. 5380 if (ClassDecl->isDynamicClass() || 5381 ClassDecl->needsOverloadResolutionForDestructor()) 5382 DeclareImplicitDestructor(ClassDecl); 5383 } 5384} 5385 5386void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) { 5387 if (!D) 5388 return; 5389 5390 int NumParamList = D->getNumTemplateParameterLists(); 5391 for (int i = 0; i < NumParamList; i++) { 5392 TemplateParameterList* Params = D->getTemplateParameterList(i); 5393 for (TemplateParameterList::iterator Param = Params->begin(), 5394 ParamEnd = Params->end(); 5395 Param != ParamEnd; ++Param) { 5396 NamedDecl *Named = cast<NamedDecl>(*Param); 5397 if (Named->getDeclName()) { 5398 S->AddDecl(Named); 5399 IdResolver.AddDecl(Named); 5400 } 5401 } 5402 } 5403} 5404 5405void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 5406 if (!D) 5407 return; 5408 5409 TemplateParameterList *Params = 0; 5410 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) 5411 Params = Template->getTemplateParameters(); 5412 else if (ClassTemplatePartialSpecializationDecl *PartialSpec 5413 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 5414 Params = PartialSpec->getTemplateParameters(); 5415 else 5416 return; 5417 5418 for (TemplateParameterList::iterator Param = Params->begin(), 5419 ParamEnd = Params->end(); 5420 Param != ParamEnd; ++Param) { 5421 NamedDecl *Named = cast<NamedDecl>(*Param); 5422 if (Named->getDeclName()) { 5423 S->AddDecl(Named); 5424 IdResolver.AddDecl(Named); 5425 } 5426 } 5427} 5428 5429void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 5430 if (!RecordD) return; 5431 AdjustDeclIfTemplate(RecordD); 5432 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 5433 PushDeclContext(S, Record); 5434} 5435 5436void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 5437 if (!RecordD) return; 5438 PopDeclContext(); 5439} 5440 5441/// ActOnStartDelayedCXXMethodDeclaration - We have completed 5442/// parsing a top-level (non-nested) C++ class, and we are now 5443/// parsing those parts of the given Method declaration that could 5444/// not be parsed earlier (C++ [class.mem]p2), such as default 5445/// arguments. This action should enter the scope of the given 5446/// Method declaration as if we had just parsed the qualified method 5447/// name. However, it should not bring the parameters into scope; 5448/// that will be performed by ActOnDelayedCXXMethodParameter. 5449void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 5450} 5451 5452/// ActOnDelayedCXXMethodParameter - We've already started a delayed 5453/// C++ method declaration. We're (re-)introducing the given 5454/// function parameter into scope for use in parsing later parts of 5455/// the method declaration. For example, we could see an 5456/// ActOnParamDefaultArgument event for this parameter. 5457void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 5458 if (!ParamD) 5459 return; 5460 5461 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 5462 5463 // If this parameter has an unparsed default argument, clear it out 5464 // to make way for the parsed default argument. 5465 if (Param->hasUnparsedDefaultArg()) 5466 Param->setDefaultArg(0); 5467 5468 S->AddDecl(Param); 5469 if (Param->getDeclName()) 5470 IdResolver.AddDecl(Param); 5471} 5472 5473/// ActOnFinishDelayedCXXMethodDeclaration - We have finished 5474/// processing the delayed method declaration for Method. The method 5475/// declaration is now considered finished. There may be a separate 5476/// ActOnStartOfFunctionDef action later (not necessarily 5477/// immediately!) for this method, if it was also defined inside the 5478/// class body. 5479void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 5480 if (!MethodD) 5481 return; 5482 5483 AdjustDeclIfTemplate(MethodD); 5484 5485 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 5486 5487 // Now that we have our default arguments, check the constructor 5488 // again. It could produce additional diagnostics or affect whether 5489 // the class has implicitly-declared destructors, among other 5490 // things. 5491 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 5492 CheckConstructor(Constructor); 5493 5494 // Check the default arguments, which we may have added. 5495 if (!Method->isInvalidDecl()) 5496 CheckCXXDefaultArguments(Method); 5497} 5498 5499/// CheckConstructorDeclarator - Called by ActOnDeclarator to check 5500/// the well-formedness of the constructor declarator @p D with type @p 5501/// R. If there are any errors in the declarator, this routine will 5502/// emit diagnostics and set the invalid bit to true. In any case, the type 5503/// will be updated to reflect a well-formed type for the constructor and 5504/// returned. 5505QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 5506 StorageClass &SC) { 5507 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 5508 5509 // C++ [class.ctor]p3: 5510 // A constructor shall not be virtual (10.3) or static (9.4). A 5511 // constructor can be invoked for a const, volatile or const 5512 // volatile object. A constructor shall not be declared const, 5513 // volatile, or const volatile (9.3.2). 5514 if (isVirtual) { 5515 if (!D.isInvalidType()) 5516 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 5517 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 5518 << SourceRange(D.getIdentifierLoc()); 5519 D.setInvalidType(); 5520 } 5521 if (SC == SC_Static) { 5522 if (!D.isInvalidType()) 5523 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 5524 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 5525 << SourceRange(D.getIdentifierLoc()); 5526 D.setInvalidType(); 5527 SC = SC_None; 5528 } 5529 5530 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 5531 if (FTI.TypeQuals != 0) { 5532 if (FTI.TypeQuals & Qualifiers::Const) 5533 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 5534 << "const" << SourceRange(D.getIdentifierLoc()); 5535 if (FTI.TypeQuals & Qualifiers::Volatile) 5536 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 5537 << "volatile" << SourceRange(D.getIdentifierLoc()); 5538 if (FTI.TypeQuals & Qualifiers::Restrict) 5539 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 5540 << "restrict" << SourceRange(D.getIdentifierLoc()); 5541 D.setInvalidType(); 5542 } 5543 5544 // C++0x [class.ctor]p4: 5545 // A constructor shall not be declared with a ref-qualifier. 5546 if (FTI.hasRefQualifier()) { 5547 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 5548 << FTI.RefQualifierIsLValueRef 5549 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 5550 D.setInvalidType(); 5551 } 5552 5553 // Rebuild the function type "R" without any type qualifiers (in 5554 // case any of the errors above fired) and with "void" as the 5555 // return type, since constructors don't have return types. 5556 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 5557 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType()) 5558 return R; 5559 5560 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 5561 EPI.TypeQuals = 0; 5562 EPI.RefQualifier = RQ_None; 5563 5564 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(), 5565 Proto->getNumArgs(), EPI); 5566} 5567 5568/// CheckConstructor - Checks a fully-formed constructor for 5569/// well-formedness, issuing any diagnostics required. Returns true if 5570/// the constructor declarator is invalid. 5571void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 5572 CXXRecordDecl *ClassDecl 5573 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 5574 if (!ClassDecl) 5575 return Constructor->setInvalidDecl(); 5576 5577 // C++ [class.copy]p3: 5578 // A declaration of a constructor for a class X is ill-formed if 5579 // its first parameter is of type (optionally cv-qualified) X and 5580 // either there are no other parameters or else all other 5581 // parameters have default arguments. 5582 if (!Constructor->isInvalidDecl() && 5583 ((Constructor->getNumParams() == 1) || 5584 (Constructor->getNumParams() > 1 && 5585 Constructor->getParamDecl(1)->hasDefaultArg())) && 5586 Constructor->getTemplateSpecializationKind() 5587 != TSK_ImplicitInstantiation) { 5588 QualType ParamType = Constructor->getParamDecl(0)->getType(); 5589 QualType ClassTy = Context.getTagDeclType(ClassDecl); 5590 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 5591 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 5592 const char *ConstRef 5593 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 5594 : " const &"; 5595 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 5596 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 5597 5598 // FIXME: Rather that making the constructor invalid, we should endeavor 5599 // to fix the type. 5600 Constructor->setInvalidDecl(); 5601 } 5602 } 5603} 5604 5605/// CheckDestructor - Checks a fully-formed destructor definition for 5606/// well-formedness, issuing any diagnostics required. Returns true 5607/// on error. 5608bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 5609 CXXRecordDecl *RD = Destructor->getParent(); 5610 5611 if (Destructor->isVirtual()) { 5612 SourceLocation Loc; 5613 5614 if (!Destructor->isImplicit()) 5615 Loc = Destructor->getLocation(); 5616 else 5617 Loc = RD->getLocation(); 5618 5619 // If we have a virtual destructor, look up the deallocation function 5620 FunctionDecl *OperatorDelete = 0; 5621 DeclarationName Name = 5622 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 5623 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 5624 return true; 5625 5626 MarkFunctionReferenced(Loc, OperatorDelete); 5627 5628 Destructor->setOperatorDelete(OperatorDelete); 5629 } 5630 5631 return false; 5632} 5633 5634static inline bool 5635FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) { 5636 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 5637 FTI.ArgInfo[0].Param && 5638 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()); 5639} 5640 5641/// CheckDestructorDeclarator - Called by ActOnDeclarator to check 5642/// the well-formednes of the destructor declarator @p D with type @p 5643/// R. If there are any errors in the declarator, this routine will 5644/// emit diagnostics and set the declarator to invalid. Even if this happens, 5645/// will be updated to reflect a well-formed type for the destructor and 5646/// returned. 5647QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 5648 StorageClass& SC) { 5649 // C++ [class.dtor]p1: 5650 // [...] A typedef-name that names a class is a class-name 5651 // (7.1.3); however, a typedef-name that names a class shall not 5652 // be used as the identifier in the declarator for a destructor 5653 // declaration. 5654 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 5655 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 5656 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 5657 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 5658 else if (const TemplateSpecializationType *TST = 5659 DeclaratorType->getAs<TemplateSpecializationType>()) 5660 if (TST->isTypeAlias()) 5661 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 5662 << DeclaratorType << 1; 5663 5664 // C++ [class.dtor]p2: 5665 // A destructor is used to destroy objects of its class type. A 5666 // destructor takes no parameters, and no return type can be 5667 // specified for it (not even void). The address of a destructor 5668 // shall not be taken. A destructor shall not be static. A 5669 // destructor can be invoked for a const, volatile or const 5670 // volatile object. A destructor shall not be declared const, 5671 // volatile or const volatile (9.3.2). 5672 if (SC == SC_Static) { 5673 if (!D.isInvalidType()) 5674 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 5675 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 5676 << SourceRange(D.getIdentifierLoc()) 5677 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5678 5679 SC = SC_None; 5680 } 5681 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 5682 // Destructors don't have return types, but the parser will 5683 // happily parse something like: 5684 // 5685 // class X { 5686 // float ~X(); 5687 // }; 5688 // 5689 // The return type will be eliminated later. 5690 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 5691 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 5692 << SourceRange(D.getIdentifierLoc()); 5693 } 5694 5695 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 5696 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 5697 if (FTI.TypeQuals & Qualifiers::Const) 5698 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 5699 << "const" << SourceRange(D.getIdentifierLoc()); 5700 if (FTI.TypeQuals & Qualifiers::Volatile) 5701 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 5702 << "volatile" << SourceRange(D.getIdentifierLoc()); 5703 if (FTI.TypeQuals & Qualifiers::Restrict) 5704 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 5705 << "restrict" << SourceRange(D.getIdentifierLoc()); 5706 D.setInvalidType(); 5707 } 5708 5709 // C++0x [class.dtor]p2: 5710 // A destructor shall not be declared with a ref-qualifier. 5711 if (FTI.hasRefQualifier()) { 5712 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 5713 << FTI.RefQualifierIsLValueRef 5714 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 5715 D.setInvalidType(); 5716 } 5717 5718 // Make sure we don't have any parameters. 5719 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) { 5720 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 5721 5722 // Delete the parameters. 5723 FTI.freeArgs(); 5724 D.setInvalidType(); 5725 } 5726 5727 // Make sure the destructor isn't variadic. 5728 if (FTI.isVariadic) { 5729 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 5730 D.setInvalidType(); 5731 } 5732 5733 // Rebuild the function type "R" without any type qualifiers or 5734 // parameters (in case any of the errors above fired) and with 5735 // "void" as the return type, since destructors don't have return 5736 // types. 5737 if (!D.isInvalidType()) 5738 return R; 5739 5740 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 5741 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 5742 EPI.Variadic = false; 5743 EPI.TypeQuals = 0; 5744 EPI.RefQualifier = RQ_None; 5745 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI); 5746} 5747 5748/// CheckConversionDeclarator - Called by ActOnDeclarator to check the 5749/// well-formednes of the conversion function declarator @p D with 5750/// type @p R. If there are any errors in the declarator, this routine 5751/// will emit diagnostics and return true. Otherwise, it will return 5752/// false. Either way, the type @p R will be updated to reflect a 5753/// well-formed type for the conversion operator. 5754void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 5755 StorageClass& SC) { 5756 // C++ [class.conv.fct]p1: 5757 // Neither parameter types nor return type can be specified. The 5758 // type of a conversion function (8.3.5) is "function taking no 5759 // parameter returning conversion-type-id." 5760 if (SC == SC_Static) { 5761 if (!D.isInvalidType()) 5762 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 5763 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 5764 << SourceRange(D.getIdentifierLoc()); 5765 D.setInvalidType(); 5766 SC = SC_None; 5767 } 5768 5769 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId); 5770 5771 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 5772 // Conversion functions don't have return types, but the parser will 5773 // happily parse something like: 5774 // 5775 // class X { 5776 // float operator bool(); 5777 // }; 5778 // 5779 // The return type will be changed later anyway. 5780 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 5781 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 5782 << SourceRange(D.getIdentifierLoc()); 5783 D.setInvalidType(); 5784 } 5785 5786 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 5787 5788 // Make sure we don't have any parameters. 5789 if (Proto->getNumArgs() > 0) { 5790 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 5791 5792 // Delete the parameters. 5793 D.getFunctionTypeInfo().freeArgs(); 5794 D.setInvalidType(); 5795 } else if (Proto->isVariadic()) { 5796 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 5797 D.setInvalidType(); 5798 } 5799 5800 // Diagnose "&operator bool()" and other such nonsense. This 5801 // is actually a gcc extension which we don't support. 5802 if (Proto->getResultType() != ConvType) { 5803 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 5804 << Proto->getResultType(); 5805 D.setInvalidType(); 5806 ConvType = Proto->getResultType(); 5807 } 5808 5809 // C++ [class.conv.fct]p4: 5810 // The conversion-type-id shall not represent a function type nor 5811 // an array type. 5812 if (ConvType->isArrayType()) { 5813 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 5814 ConvType = Context.getPointerType(ConvType); 5815 D.setInvalidType(); 5816 } else if (ConvType->isFunctionType()) { 5817 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 5818 ConvType = Context.getPointerType(ConvType); 5819 D.setInvalidType(); 5820 } 5821 5822 // Rebuild the function type "R" without any parameters (in case any 5823 // of the errors above fired) and with the conversion type as the 5824 // return type. 5825 if (D.isInvalidType()) 5826 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo()); 5827 5828 // C++0x explicit conversion operators. 5829 if (D.getDeclSpec().isExplicitSpecified()) 5830 Diag(D.getDeclSpec().getExplicitSpecLoc(), 5831 getLangOpts().CPlusPlus0x ? 5832 diag::warn_cxx98_compat_explicit_conversion_functions : 5833 diag::ext_explicit_conversion_functions) 5834 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 5835} 5836 5837/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 5838/// the declaration of the given C++ conversion function. This routine 5839/// is responsible for recording the conversion function in the C++ 5840/// class, if possible. 5841Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 5842 assert(Conversion && "Expected to receive a conversion function declaration"); 5843 5844 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 5845 5846 // Make sure we aren't redeclaring the conversion function. 5847 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 5848 5849 // C++ [class.conv.fct]p1: 5850 // [...] A conversion function is never used to convert a 5851 // (possibly cv-qualified) object to the (possibly cv-qualified) 5852 // same object type (or a reference to it), to a (possibly 5853 // cv-qualified) base class of that type (or a reference to it), 5854 // or to (possibly cv-qualified) void. 5855 // FIXME: Suppress this warning if the conversion function ends up being a 5856 // virtual function that overrides a virtual function in a base class. 5857 QualType ClassType 5858 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 5859 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 5860 ConvType = ConvTypeRef->getPointeeType(); 5861 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 5862 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 5863 /* Suppress diagnostics for instantiations. */; 5864 else if (ConvType->isRecordType()) { 5865 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 5866 if (ConvType == ClassType) 5867 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 5868 << ClassType; 5869 else if (IsDerivedFrom(ClassType, ConvType)) 5870 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 5871 << ClassType << ConvType; 5872 } else if (ConvType->isVoidType()) { 5873 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 5874 << ClassType << ConvType; 5875 } 5876 5877 if (FunctionTemplateDecl *ConversionTemplate 5878 = Conversion->getDescribedFunctionTemplate()) 5879 return ConversionTemplate; 5880 5881 return Conversion; 5882} 5883 5884//===----------------------------------------------------------------------===// 5885// Namespace Handling 5886//===----------------------------------------------------------------------===// 5887 5888/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is 5889/// reopened. 5890static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 5891 SourceLocation Loc, 5892 IdentifierInfo *II, bool *IsInline, 5893 NamespaceDecl *PrevNS) { 5894 assert(*IsInline != PrevNS->isInline()); 5895 5896 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 5897 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 5898 // inline namespaces, with the intention of bringing names into namespace std. 5899 // 5900 // We support this just well enough to get that case working; this is not 5901 // sufficient to support reopening namespaces as inline in general. 5902 if (*IsInline && II && II->getName().startswith("__atomic") && 5903 S.getSourceManager().isInSystemHeader(Loc)) { 5904 // Mark all prior declarations of the namespace as inline. 5905 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 5906 NS = NS->getPreviousDecl()) 5907 NS->setInline(*IsInline); 5908 // Patch up the lookup table for the containing namespace. This isn't really 5909 // correct, but it's good enough for this particular case. 5910 for (DeclContext::decl_iterator I = PrevNS->decls_begin(), 5911 E = PrevNS->decls_end(); I != E; ++I) 5912 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I)) 5913 PrevNS->getParent()->makeDeclVisibleInContext(ND); 5914 return; 5915 } 5916 5917 if (PrevNS->isInline()) 5918 // The user probably just forgot the 'inline', so suggest that it 5919 // be added back. 5920 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 5921 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 5922 else 5923 S.Diag(Loc, diag::err_inline_namespace_mismatch) 5924 << IsInline; 5925 5926 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 5927 *IsInline = PrevNS->isInline(); 5928} 5929 5930/// ActOnStartNamespaceDef - This is called at the start of a namespace 5931/// definition. 5932Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 5933 SourceLocation InlineLoc, 5934 SourceLocation NamespaceLoc, 5935 SourceLocation IdentLoc, 5936 IdentifierInfo *II, 5937 SourceLocation LBrace, 5938 AttributeList *AttrList) { 5939 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 5940 // For anonymous namespace, take the location of the left brace. 5941 SourceLocation Loc = II ? IdentLoc : LBrace; 5942 bool IsInline = InlineLoc.isValid(); 5943 bool IsInvalid = false; 5944 bool IsStd = false; 5945 bool AddToKnown = false; 5946 Scope *DeclRegionScope = NamespcScope->getParent(); 5947 5948 NamespaceDecl *PrevNS = 0; 5949 if (II) { 5950 // C++ [namespace.def]p2: 5951 // The identifier in an original-namespace-definition shall not 5952 // have been previously defined in the declarative region in 5953 // which the original-namespace-definition appears. The 5954 // identifier in an original-namespace-definition is the name of 5955 // the namespace. Subsequently in that declarative region, it is 5956 // treated as an original-namespace-name. 5957 // 5958 // Since namespace names are unique in their scope, and we don't 5959 // look through using directives, just look for any ordinary names. 5960 5961 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member | 5962 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag | 5963 Decl::IDNS_Namespace; 5964 NamedDecl *PrevDecl = 0; 5965 for (DeclContext::lookup_result R 5966 = CurContext->getRedeclContext()->lookup(II); 5967 R.first != R.second; ++R.first) { 5968 if ((*R.first)->getIdentifierNamespace() & IDNS) { 5969 PrevDecl = *R.first; 5970 break; 5971 } 5972 } 5973 5974 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 5975 5976 if (PrevNS) { 5977 // This is an extended namespace definition. 5978 if (IsInline != PrevNS->isInline()) 5979 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 5980 &IsInline, PrevNS); 5981 } else if (PrevDecl) { 5982 // This is an invalid name redefinition. 5983 Diag(Loc, diag::err_redefinition_different_kind) 5984 << II; 5985 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 5986 IsInvalid = true; 5987 // Continue on to push Namespc as current DeclContext and return it. 5988 } else if (II->isStr("std") && 5989 CurContext->getRedeclContext()->isTranslationUnit()) { 5990 // This is the first "real" definition of the namespace "std", so update 5991 // our cache of the "std" namespace to point at this definition. 5992 PrevNS = getStdNamespace(); 5993 IsStd = true; 5994 AddToKnown = !IsInline; 5995 } else { 5996 // We've seen this namespace for the first time. 5997 AddToKnown = !IsInline; 5998 } 5999 } else { 6000 // Anonymous namespaces. 6001 6002 // Determine whether the parent already has an anonymous namespace. 6003 DeclContext *Parent = CurContext->getRedeclContext(); 6004 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 6005 PrevNS = TU->getAnonymousNamespace(); 6006 } else { 6007 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 6008 PrevNS = ND->getAnonymousNamespace(); 6009 } 6010 6011 if (PrevNS && IsInline != PrevNS->isInline()) 6012 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 6013 &IsInline, PrevNS); 6014 } 6015 6016 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 6017 StartLoc, Loc, II, PrevNS); 6018 if (IsInvalid) 6019 Namespc->setInvalidDecl(); 6020 6021 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 6022 6023 // FIXME: Should we be merging attributes? 6024 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 6025 PushNamespaceVisibilityAttr(Attr, Loc); 6026 6027 if (IsStd) 6028 StdNamespace = Namespc; 6029 if (AddToKnown) 6030 KnownNamespaces[Namespc] = false; 6031 6032 if (II) { 6033 PushOnScopeChains(Namespc, DeclRegionScope); 6034 } else { 6035 // Link the anonymous namespace into its parent. 6036 DeclContext *Parent = CurContext->getRedeclContext(); 6037 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 6038 TU->setAnonymousNamespace(Namespc); 6039 } else { 6040 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 6041 } 6042 6043 CurContext->addDecl(Namespc); 6044 6045 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 6046 // behaves as if it were replaced by 6047 // namespace unique { /* empty body */ } 6048 // using namespace unique; 6049 // namespace unique { namespace-body } 6050 // where all occurrences of 'unique' in a translation unit are 6051 // replaced by the same identifier and this identifier differs 6052 // from all other identifiers in the entire program. 6053 6054 // We just create the namespace with an empty name and then add an 6055 // implicit using declaration, just like the standard suggests. 6056 // 6057 // CodeGen enforces the "universally unique" aspect by giving all 6058 // declarations semantically contained within an anonymous 6059 // namespace internal linkage. 6060 6061 if (!PrevNS) { 6062 UsingDirectiveDecl* UD 6063 = UsingDirectiveDecl::Create(Context, Parent, 6064 /* 'using' */ LBrace, 6065 /* 'namespace' */ SourceLocation(), 6066 /* qualifier */ NestedNameSpecifierLoc(), 6067 /* identifier */ SourceLocation(), 6068 Namespc, 6069 /* Ancestor */ Parent); 6070 UD->setImplicit(); 6071 Parent->addDecl(UD); 6072 } 6073 } 6074 6075 ActOnDocumentableDecl(Namespc); 6076 6077 // Although we could have an invalid decl (i.e. the namespace name is a 6078 // redefinition), push it as current DeclContext and try to continue parsing. 6079 // FIXME: We should be able to push Namespc here, so that the each DeclContext 6080 // for the namespace has the declarations that showed up in that particular 6081 // namespace definition. 6082 PushDeclContext(NamespcScope, Namespc); 6083 return Namespc; 6084} 6085 6086/// getNamespaceDecl - Returns the namespace a decl represents. If the decl 6087/// is a namespace alias, returns the namespace it points to. 6088static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 6089 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 6090 return AD->getNamespace(); 6091 return dyn_cast_or_null<NamespaceDecl>(D); 6092} 6093 6094/// ActOnFinishNamespaceDef - This callback is called after a namespace is 6095/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 6096void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 6097 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 6098 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 6099 Namespc->setRBraceLoc(RBrace); 6100 PopDeclContext(); 6101 if (Namespc->hasAttr<VisibilityAttr>()) 6102 PopPragmaVisibility(true, RBrace); 6103} 6104 6105CXXRecordDecl *Sema::getStdBadAlloc() const { 6106 return cast_or_null<CXXRecordDecl>( 6107 StdBadAlloc.get(Context.getExternalSource())); 6108} 6109 6110NamespaceDecl *Sema::getStdNamespace() const { 6111 return cast_or_null<NamespaceDecl>( 6112 StdNamespace.get(Context.getExternalSource())); 6113} 6114 6115/// \brief Retrieve the special "std" namespace, which may require us to 6116/// implicitly define the namespace. 6117NamespaceDecl *Sema::getOrCreateStdNamespace() { 6118 if (!StdNamespace) { 6119 // The "std" namespace has not yet been defined, so build one implicitly. 6120 StdNamespace = NamespaceDecl::Create(Context, 6121 Context.getTranslationUnitDecl(), 6122 /*Inline=*/false, 6123 SourceLocation(), SourceLocation(), 6124 &PP.getIdentifierTable().get("std"), 6125 /*PrevDecl=*/0); 6126 getStdNamespace()->setImplicit(true); 6127 } 6128 6129 return getStdNamespace(); 6130} 6131 6132bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 6133 assert(getLangOpts().CPlusPlus && 6134 "Looking for std::initializer_list outside of C++."); 6135 6136 // We're looking for implicit instantiations of 6137 // template <typename E> class std::initializer_list. 6138 6139 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 6140 return false; 6141 6142 ClassTemplateDecl *Template = 0; 6143 const TemplateArgument *Arguments = 0; 6144 6145 if (const RecordType *RT = Ty->getAs<RecordType>()) { 6146 6147 ClassTemplateSpecializationDecl *Specialization = 6148 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 6149 if (!Specialization) 6150 return false; 6151 6152 Template = Specialization->getSpecializedTemplate(); 6153 Arguments = Specialization->getTemplateArgs().data(); 6154 } else if (const TemplateSpecializationType *TST = 6155 Ty->getAs<TemplateSpecializationType>()) { 6156 Template = dyn_cast_or_null<ClassTemplateDecl>( 6157 TST->getTemplateName().getAsTemplateDecl()); 6158 Arguments = TST->getArgs(); 6159 } 6160 if (!Template) 6161 return false; 6162 6163 if (!StdInitializerList) { 6164 // Haven't recognized std::initializer_list yet, maybe this is it. 6165 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 6166 if (TemplateClass->getIdentifier() != 6167 &PP.getIdentifierTable().get("initializer_list") || 6168 !getStdNamespace()->InEnclosingNamespaceSetOf( 6169 TemplateClass->getDeclContext())) 6170 return false; 6171 // This is a template called std::initializer_list, but is it the right 6172 // template? 6173 TemplateParameterList *Params = Template->getTemplateParameters(); 6174 if (Params->getMinRequiredArguments() != 1) 6175 return false; 6176 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 6177 return false; 6178 6179 // It's the right template. 6180 StdInitializerList = Template; 6181 } 6182 6183 if (Template != StdInitializerList) 6184 return false; 6185 6186 // This is an instance of std::initializer_list. Find the argument type. 6187 if (Element) 6188 *Element = Arguments[0].getAsType(); 6189 return true; 6190} 6191 6192static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 6193 NamespaceDecl *Std = S.getStdNamespace(); 6194 if (!Std) { 6195 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 6196 return 0; 6197 } 6198 6199 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 6200 Loc, Sema::LookupOrdinaryName); 6201 if (!S.LookupQualifiedName(Result, Std)) { 6202 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 6203 return 0; 6204 } 6205 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 6206 if (!Template) { 6207 Result.suppressDiagnostics(); 6208 // We found something weird. Complain about the first thing we found. 6209 NamedDecl *Found = *Result.begin(); 6210 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 6211 return 0; 6212 } 6213 6214 // We found some template called std::initializer_list. Now verify that it's 6215 // correct. 6216 TemplateParameterList *Params = Template->getTemplateParameters(); 6217 if (Params->getMinRequiredArguments() != 1 || 6218 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 6219 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 6220 return 0; 6221 } 6222 6223 return Template; 6224} 6225 6226QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 6227 if (!StdInitializerList) { 6228 StdInitializerList = LookupStdInitializerList(*this, Loc); 6229 if (!StdInitializerList) 6230 return QualType(); 6231 } 6232 6233 TemplateArgumentListInfo Args(Loc, Loc); 6234 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 6235 Context.getTrivialTypeSourceInfo(Element, 6236 Loc))); 6237 return Context.getCanonicalType( 6238 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 6239} 6240 6241bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) { 6242 // C++ [dcl.init.list]p2: 6243 // A constructor is an initializer-list constructor if its first parameter 6244 // is of type std::initializer_list<E> or reference to possibly cv-qualified 6245 // std::initializer_list<E> for some type E, and either there are no other 6246 // parameters or else all other parameters have default arguments. 6247 if (Ctor->getNumParams() < 1 || 6248 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 6249 return false; 6250 6251 QualType ArgType = Ctor->getParamDecl(0)->getType(); 6252 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 6253 ArgType = RT->getPointeeType().getUnqualifiedType(); 6254 6255 return isStdInitializerList(ArgType, 0); 6256} 6257 6258/// \brief Determine whether a using statement is in a context where it will be 6259/// apply in all contexts. 6260static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 6261 switch (CurContext->getDeclKind()) { 6262 case Decl::TranslationUnit: 6263 return true; 6264 case Decl::LinkageSpec: 6265 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 6266 default: 6267 return false; 6268 } 6269} 6270 6271namespace { 6272 6273// Callback to only accept typo corrections that are namespaces. 6274class NamespaceValidatorCCC : public CorrectionCandidateCallback { 6275 public: 6276 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 6277 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 6278 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 6279 } 6280 return false; 6281 } 6282}; 6283 6284} 6285 6286static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 6287 CXXScopeSpec &SS, 6288 SourceLocation IdentLoc, 6289 IdentifierInfo *Ident) { 6290 NamespaceValidatorCCC Validator; 6291 R.clear(); 6292 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(), 6293 R.getLookupKind(), Sc, &SS, 6294 Validator)) { 6295 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 6296 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts())); 6297 if (DeclContext *DC = S.computeDeclContext(SS, false)) 6298 S.Diag(IdentLoc, diag::err_using_directive_member_suggest) 6299 << Ident << DC << CorrectedQuotedStr << SS.getRange() 6300 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(), 6301 CorrectedStr); 6302 else 6303 S.Diag(IdentLoc, diag::err_using_directive_suggest) 6304 << Ident << CorrectedQuotedStr 6305 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr); 6306 6307 S.Diag(Corrected.getCorrectionDecl()->getLocation(), 6308 diag::note_namespace_defined_here) << CorrectedQuotedStr; 6309 6310 R.addDecl(Corrected.getCorrectionDecl()); 6311 return true; 6312 } 6313 return false; 6314} 6315 6316Decl *Sema::ActOnUsingDirective(Scope *S, 6317 SourceLocation UsingLoc, 6318 SourceLocation NamespcLoc, 6319 CXXScopeSpec &SS, 6320 SourceLocation IdentLoc, 6321 IdentifierInfo *NamespcName, 6322 AttributeList *AttrList) { 6323 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 6324 assert(NamespcName && "Invalid NamespcName."); 6325 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 6326 6327 // This can only happen along a recovery path. 6328 while (S->getFlags() & Scope::TemplateParamScope) 6329 S = S->getParent(); 6330 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 6331 6332 UsingDirectiveDecl *UDir = 0; 6333 NestedNameSpecifier *Qualifier = 0; 6334 if (SS.isSet()) 6335 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 6336 6337 // Lookup namespace name. 6338 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 6339 LookupParsedName(R, S, &SS); 6340 if (R.isAmbiguous()) 6341 return 0; 6342 6343 if (R.empty()) { 6344 R.clear(); 6345 // Allow "using namespace std;" or "using namespace ::std;" even if 6346 // "std" hasn't been defined yet, for GCC compatibility. 6347 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 6348 NamespcName->isStr("std")) { 6349 Diag(IdentLoc, diag::ext_using_undefined_std); 6350 R.addDecl(getOrCreateStdNamespace()); 6351 R.resolveKind(); 6352 } 6353 // Otherwise, attempt typo correction. 6354 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 6355 } 6356 6357 if (!R.empty()) { 6358 NamedDecl *Named = R.getFoundDecl(); 6359 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named)) 6360 && "expected namespace decl"); 6361 // C++ [namespace.udir]p1: 6362 // A using-directive specifies that the names in the nominated 6363 // namespace can be used in the scope in which the 6364 // using-directive appears after the using-directive. During 6365 // unqualified name lookup (3.4.1), the names appear as if they 6366 // were declared in the nearest enclosing namespace which 6367 // contains both the using-directive and the nominated 6368 // namespace. [Note: in this context, "contains" means "contains 6369 // directly or indirectly". ] 6370 6371 // Find enclosing context containing both using-directive and 6372 // nominated namespace. 6373 NamespaceDecl *NS = getNamespaceDecl(Named); 6374 DeclContext *CommonAncestor = cast<DeclContext>(NS); 6375 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 6376 CommonAncestor = CommonAncestor->getParent(); 6377 6378 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 6379 SS.getWithLocInContext(Context), 6380 IdentLoc, Named, CommonAncestor); 6381 6382 if (IsUsingDirectiveInToplevelContext(CurContext) && 6383 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 6384 Diag(IdentLoc, diag::warn_using_directive_in_header); 6385 } 6386 6387 PushUsingDirective(S, UDir); 6388 } else { 6389 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 6390 } 6391 6392 // FIXME: We ignore attributes for now. 6393 return UDir; 6394} 6395 6396void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 6397 // If the scope has an associated entity and the using directive is at 6398 // namespace or translation unit scope, add the UsingDirectiveDecl into 6399 // its lookup structure so qualified name lookup can find it. 6400 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()); 6401 if (Ctx && !Ctx->isFunctionOrMethod()) 6402 Ctx->addDecl(UDir); 6403 else 6404 // Otherwise, it is at block sope. The using-directives will affect lookup 6405 // only to the end of the scope. 6406 S->PushUsingDirective(UDir); 6407} 6408 6409 6410Decl *Sema::ActOnUsingDeclaration(Scope *S, 6411 AccessSpecifier AS, 6412 bool HasUsingKeyword, 6413 SourceLocation UsingLoc, 6414 CXXScopeSpec &SS, 6415 UnqualifiedId &Name, 6416 AttributeList *AttrList, 6417 bool IsTypeName, 6418 SourceLocation TypenameLoc) { 6419 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 6420 6421 switch (Name.getKind()) { 6422 case UnqualifiedId::IK_ImplicitSelfParam: 6423 case UnqualifiedId::IK_Identifier: 6424 case UnqualifiedId::IK_OperatorFunctionId: 6425 case UnqualifiedId::IK_LiteralOperatorId: 6426 case UnqualifiedId::IK_ConversionFunctionId: 6427 break; 6428 6429 case UnqualifiedId::IK_ConstructorName: 6430 case UnqualifiedId::IK_ConstructorTemplateId: 6431 // C++11 inheriting constructors. 6432 Diag(Name.getLocStart(), 6433 getLangOpts().CPlusPlus0x ? 6434 // FIXME: Produce warn_cxx98_compat_using_decl_constructor 6435 // instead once inheriting constructors work. 6436 diag::err_using_decl_constructor_unsupported : 6437 diag::err_using_decl_constructor) 6438 << SS.getRange(); 6439 6440 if (getLangOpts().CPlusPlus0x) break; 6441 6442 return 0; 6443 6444 case UnqualifiedId::IK_DestructorName: 6445 Diag(Name.getLocStart(), diag::err_using_decl_destructor) 6446 << SS.getRange(); 6447 return 0; 6448 6449 case UnqualifiedId::IK_TemplateId: 6450 Diag(Name.getLocStart(), diag::err_using_decl_template_id) 6451 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 6452 return 0; 6453 } 6454 6455 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 6456 DeclarationName TargetName = TargetNameInfo.getName(); 6457 if (!TargetName) 6458 return 0; 6459 6460 // Warn about using declarations. 6461 // TODO: store that the declaration was written without 'using' and 6462 // talk about access decls instead of using decls in the 6463 // diagnostics. 6464 if (!HasUsingKeyword) { 6465 UsingLoc = Name.getLocStart(); 6466 6467 Diag(UsingLoc, diag::warn_access_decl_deprecated) 6468 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 6469 } 6470 6471 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 6472 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 6473 return 0; 6474 6475 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 6476 TargetNameInfo, AttrList, 6477 /* IsInstantiation */ false, 6478 IsTypeName, TypenameLoc); 6479 if (UD) 6480 PushOnScopeChains(UD, S, /*AddToContext*/ false); 6481 6482 return UD; 6483} 6484 6485/// \brief Determine whether a using declaration considers the given 6486/// declarations as "equivalent", e.g., if they are redeclarations of 6487/// the same entity or are both typedefs of the same type. 6488static bool 6489IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2, 6490 bool &SuppressRedeclaration) { 6491 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) { 6492 SuppressRedeclaration = false; 6493 return true; 6494 } 6495 6496 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 6497 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) { 6498 SuppressRedeclaration = true; 6499 return Context.hasSameType(TD1->getUnderlyingType(), 6500 TD2->getUnderlyingType()); 6501 } 6502 6503 return false; 6504} 6505 6506 6507/// Determines whether to create a using shadow decl for a particular 6508/// decl, given the set of decls existing prior to this using lookup. 6509bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 6510 const LookupResult &Previous) { 6511 // Diagnose finding a decl which is not from a base class of the 6512 // current class. We do this now because there are cases where this 6513 // function will silently decide not to build a shadow decl, which 6514 // will pre-empt further diagnostics. 6515 // 6516 // We don't need to do this in C++0x because we do the check once on 6517 // the qualifier. 6518 // 6519 // FIXME: diagnose the following if we care enough: 6520 // struct A { int foo; }; 6521 // struct B : A { using A::foo; }; 6522 // template <class T> struct C : A {}; 6523 // template <class T> struct D : C<T> { using B::foo; } // <--- 6524 // This is invalid (during instantiation) in C++03 because B::foo 6525 // resolves to the using decl in B, which is not a base class of D<T>. 6526 // We can't diagnose it immediately because C<T> is an unknown 6527 // specialization. The UsingShadowDecl in D<T> then points directly 6528 // to A::foo, which will look well-formed when we instantiate. 6529 // The right solution is to not collapse the shadow-decl chain. 6530 if (!getLangOpts().CPlusPlus0x && CurContext->isRecord()) { 6531 DeclContext *OrigDC = Orig->getDeclContext(); 6532 6533 // Handle enums and anonymous structs. 6534 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 6535 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 6536 while (OrigRec->isAnonymousStructOrUnion()) 6537 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 6538 6539 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 6540 if (OrigDC == CurContext) { 6541 Diag(Using->getLocation(), 6542 diag::err_using_decl_nested_name_specifier_is_current_class) 6543 << Using->getQualifierLoc().getSourceRange(); 6544 Diag(Orig->getLocation(), diag::note_using_decl_target); 6545 return true; 6546 } 6547 6548 Diag(Using->getQualifierLoc().getBeginLoc(), 6549 diag::err_using_decl_nested_name_specifier_is_not_base_class) 6550 << Using->getQualifier() 6551 << cast<CXXRecordDecl>(CurContext) 6552 << Using->getQualifierLoc().getSourceRange(); 6553 Diag(Orig->getLocation(), diag::note_using_decl_target); 6554 return true; 6555 } 6556 } 6557 6558 if (Previous.empty()) return false; 6559 6560 NamedDecl *Target = Orig; 6561 if (isa<UsingShadowDecl>(Target)) 6562 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 6563 6564 // If the target happens to be one of the previous declarations, we 6565 // don't have a conflict. 6566 // 6567 // FIXME: but we might be increasing its access, in which case we 6568 // should redeclare it. 6569 NamedDecl *NonTag = 0, *Tag = 0; 6570 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 6571 I != E; ++I) { 6572 NamedDecl *D = (*I)->getUnderlyingDecl(); 6573 bool Result; 6574 if (IsEquivalentForUsingDecl(Context, D, Target, Result)) 6575 return Result; 6576 6577 (isa<TagDecl>(D) ? Tag : NonTag) = D; 6578 } 6579 6580 if (Target->isFunctionOrFunctionTemplate()) { 6581 FunctionDecl *FD; 6582 if (isa<FunctionTemplateDecl>(Target)) 6583 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl(); 6584 else 6585 FD = cast<FunctionDecl>(Target); 6586 6587 NamedDecl *OldDecl = 0; 6588 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) { 6589 case Ovl_Overload: 6590 return false; 6591 6592 case Ovl_NonFunction: 6593 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6594 break; 6595 6596 // We found a decl with the exact signature. 6597 case Ovl_Match: 6598 // If we're in a record, we want to hide the target, so we 6599 // return true (without a diagnostic) to tell the caller not to 6600 // build a shadow decl. 6601 if (CurContext->isRecord()) 6602 return true; 6603 6604 // If we're not in a record, this is an error. 6605 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6606 break; 6607 } 6608 6609 Diag(Target->getLocation(), diag::note_using_decl_target); 6610 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 6611 return true; 6612 } 6613 6614 // Target is not a function. 6615 6616 if (isa<TagDecl>(Target)) { 6617 // No conflict between a tag and a non-tag. 6618 if (!Tag) return false; 6619 6620 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6621 Diag(Target->getLocation(), diag::note_using_decl_target); 6622 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 6623 return true; 6624 } 6625 6626 // No conflict between a tag and a non-tag. 6627 if (!NonTag) return false; 6628 6629 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6630 Diag(Target->getLocation(), diag::note_using_decl_target); 6631 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 6632 return true; 6633} 6634 6635/// Builds a shadow declaration corresponding to a 'using' declaration. 6636UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 6637 UsingDecl *UD, 6638 NamedDecl *Orig) { 6639 6640 // If we resolved to another shadow declaration, just coalesce them. 6641 NamedDecl *Target = Orig; 6642 if (isa<UsingShadowDecl>(Target)) { 6643 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 6644 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 6645 } 6646 6647 UsingShadowDecl *Shadow 6648 = UsingShadowDecl::Create(Context, CurContext, 6649 UD->getLocation(), UD, Target); 6650 UD->addShadowDecl(Shadow); 6651 6652 Shadow->setAccess(UD->getAccess()); 6653 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 6654 Shadow->setInvalidDecl(); 6655 6656 if (S) 6657 PushOnScopeChains(Shadow, S); 6658 else 6659 CurContext->addDecl(Shadow); 6660 6661 6662 return Shadow; 6663} 6664 6665/// Hides a using shadow declaration. This is required by the current 6666/// using-decl implementation when a resolvable using declaration in a 6667/// class is followed by a declaration which would hide or override 6668/// one or more of the using decl's targets; for example: 6669/// 6670/// struct Base { void foo(int); }; 6671/// struct Derived : Base { 6672/// using Base::foo; 6673/// void foo(int); 6674/// }; 6675/// 6676/// The governing language is C++03 [namespace.udecl]p12: 6677/// 6678/// When a using-declaration brings names from a base class into a 6679/// derived class scope, member functions in the derived class 6680/// override and/or hide member functions with the same name and 6681/// parameter types in a base class (rather than conflicting). 6682/// 6683/// There are two ways to implement this: 6684/// (1) optimistically create shadow decls when they're not hidden 6685/// by existing declarations, or 6686/// (2) don't create any shadow decls (or at least don't make them 6687/// visible) until we've fully parsed/instantiated the class. 6688/// The problem with (1) is that we might have to retroactively remove 6689/// a shadow decl, which requires several O(n) operations because the 6690/// decl structures are (very reasonably) not designed for removal. 6691/// (2) avoids this but is very fiddly and phase-dependent. 6692void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 6693 if (Shadow->getDeclName().getNameKind() == 6694 DeclarationName::CXXConversionFunctionName) 6695 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 6696 6697 // Remove it from the DeclContext... 6698 Shadow->getDeclContext()->removeDecl(Shadow); 6699 6700 // ...and the scope, if applicable... 6701 if (S) { 6702 S->RemoveDecl(Shadow); 6703 IdResolver.RemoveDecl(Shadow); 6704 } 6705 6706 // ...and the using decl. 6707 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 6708 6709 // TODO: complain somehow if Shadow was used. It shouldn't 6710 // be possible for this to happen, because...? 6711} 6712 6713/// Builds a using declaration. 6714/// 6715/// \param IsInstantiation - Whether this call arises from an 6716/// instantiation of an unresolved using declaration. We treat 6717/// the lookup differently for these declarations. 6718NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 6719 SourceLocation UsingLoc, 6720 CXXScopeSpec &SS, 6721 const DeclarationNameInfo &NameInfo, 6722 AttributeList *AttrList, 6723 bool IsInstantiation, 6724 bool IsTypeName, 6725 SourceLocation TypenameLoc) { 6726 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 6727 SourceLocation IdentLoc = NameInfo.getLoc(); 6728 assert(IdentLoc.isValid() && "Invalid TargetName location."); 6729 6730 // FIXME: We ignore attributes for now. 6731 6732 if (SS.isEmpty()) { 6733 Diag(IdentLoc, diag::err_using_requires_qualname); 6734 return 0; 6735 } 6736 6737 // Do the redeclaration lookup in the current scope. 6738 LookupResult Previous(*this, NameInfo, LookupUsingDeclName, 6739 ForRedeclaration); 6740 Previous.setHideTags(false); 6741 if (S) { 6742 LookupName(Previous, S); 6743 6744 // It is really dumb that we have to do this. 6745 LookupResult::Filter F = Previous.makeFilter(); 6746 while (F.hasNext()) { 6747 NamedDecl *D = F.next(); 6748 if (!isDeclInScope(D, CurContext, S)) 6749 F.erase(); 6750 } 6751 F.done(); 6752 } else { 6753 assert(IsInstantiation && "no scope in non-instantiation"); 6754 assert(CurContext->isRecord() && "scope not record in instantiation"); 6755 LookupQualifiedName(Previous, CurContext); 6756 } 6757 6758 // Check for invalid redeclarations. 6759 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous)) 6760 return 0; 6761 6762 // Check for bad qualifiers. 6763 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc)) 6764 return 0; 6765 6766 DeclContext *LookupContext = computeDeclContext(SS); 6767 NamedDecl *D; 6768 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 6769 if (!LookupContext) { 6770 if (IsTypeName) { 6771 // FIXME: not all declaration name kinds are legal here 6772 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 6773 UsingLoc, TypenameLoc, 6774 QualifierLoc, 6775 IdentLoc, NameInfo.getName()); 6776 } else { 6777 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 6778 QualifierLoc, NameInfo); 6779 } 6780 } else { 6781 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 6782 NameInfo, IsTypeName); 6783 } 6784 D->setAccess(AS); 6785 CurContext->addDecl(D); 6786 6787 if (!LookupContext) return D; 6788 UsingDecl *UD = cast<UsingDecl>(D); 6789 6790 if (RequireCompleteDeclContext(SS, LookupContext)) { 6791 UD->setInvalidDecl(); 6792 return UD; 6793 } 6794 6795 // The normal rules do not apply to inheriting constructor declarations. 6796 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) { 6797 if (CheckInheritingConstructorUsingDecl(UD)) 6798 UD->setInvalidDecl(); 6799 return UD; 6800 } 6801 6802 // Otherwise, look up the target name. 6803 6804 LookupResult R(*this, NameInfo, LookupOrdinaryName); 6805 6806 // Unlike most lookups, we don't always want to hide tag 6807 // declarations: tag names are visible through the using declaration 6808 // even if hidden by ordinary names, *except* in a dependent context 6809 // where it's important for the sanity of two-phase lookup. 6810 if (!IsInstantiation) 6811 R.setHideTags(false); 6812 6813 // For the purposes of this lookup, we have a base object type 6814 // equal to that of the current context. 6815 if (CurContext->isRecord()) { 6816 R.setBaseObjectType( 6817 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 6818 } 6819 6820 LookupQualifiedName(R, LookupContext); 6821 6822 if (R.empty()) { 6823 Diag(IdentLoc, diag::err_no_member) 6824 << NameInfo.getName() << LookupContext << SS.getRange(); 6825 UD->setInvalidDecl(); 6826 return UD; 6827 } 6828 6829 if (R.isAmbiguous()) { 6830 UD->setInvalidDecl(); 6831 return UD; 6832 } 6833 6834 if (IsTypeName) { 6835 // If we asked for a typename and got a non-type decl, error out. 6836 if (!R.getAsSingle<TypeDecl>()) { 6837 Diag(IdentLoc, diag::err_using_typename_non_type); 6838 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 6839 Diag((*I)->getUnderlyingDecl()->getLocation(), 6840 diag::note_using_decl_target); 6841 UD->setInvalidDecl(); 6842 return UD; 6843 } 6844 } else { 6845 // If we asked for a non-typename and we got a type, error out, 6846 // but only if this is an instantiation of an unresolved using 6847 // decl. Otherwise just silently find the type name. 6848 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 6849 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 6850 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 6851 UD->setInvalidDecl(); 6852 return UD; 6853 } 6854 } 6855 6856 // C++0x N2914 [namespace.udecl]p6: 6857 // A using-declaration shall not name a namespace. 6858 if (R.getAsSingle<NamespaceDecl>()) { 6859 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 6860 << SS.getRange(); 6861 UD->setInvalidDecl(); 6862 return UD; 6863 } 6864 6865 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 6866 if (!CheckUsingShadowDecl(UD, *I, Previous)) 6867 BuildUsingShadowDecl(S, UD, *I); 6868 } 6869 6870 return UD; 6871} 6872 6873/// Additional checks for a using declaration referring to a constructor name. 6874bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 6875 assert(!UD->isTypeName() && "expecting a constructor name"); 6876 6877 const Type *SourceType = UD->getQualifier()->getAsType(); 6878 assert(SourceType && 6879 "Using decl naming constructor doesn't have type in scope spec."); 6880 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 6881 6882 // Check whether the named type is a direct base class. 6883 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified(); 6884 CXXRecordDecl::base_class_iterator BaseIt, BaseE; 6885 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end(); 6886 BaseIt != BaseE; ++BaseIt) { 6887 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified(); 6888 if (CanonicalSourceType == BaseType) 6889 break; 6890 if (BaseIt->getType()->isDependentType()) 6891 break; 6892 } 6893 6894 if (BaseIt == BaseE) { 6895 // Did not find SourceType in the bases. 6896 Diag(UD->getUsingLocation(), 6897 diag::err_using_decl_constructor_not_in_direct_base) 6898 << UD->getNameInfo().getSourceRange() 6899 << QualType(SourceType, 0) << TargetClass; 6900 return true; 6901 } 6902 6903 if (!CurContext->isDependentContext()) 6904 BaseIt->setInheritConstructors(); 6905 6906 return false; 6907} 6908 6909/// Checks that the given using declaration is not an invalid 6910/// redeclaration. Note that this is checking only for the using decl 6911/// itself, not for any ill-formedness among the UsingShadowDecls. 6912bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 6913 bool isTypeName, 6914 const CXXScopeSpec &SS, 6915 SourceLocation NameLoc, 6916 const LookupResult &Prev) { 6917 // C++03 [namespace.udecl]p8: 6918 // C++0x [namespace.udecl]p10: 6919 // A using-declaration is a declaration and can therefore be used 6920 // repeatedly where (and only where) multiple declarations are 6921 // allowed. 6922 // 6923 // That's in non-member contexts. 6924 if (!CurContext->getRedeclContext()->isRecord()) 6925 return false; 6926 6927 NestedNameSpecifier *Qual 6928 = static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 6929 6930 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 6931 NamedDecl *D = *I; 6932 6933 bool DTypename; 6934 NestedNameSpecifier *DQual; 6935 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 6936 DTypename = UD->isTypeName(); 6937 DQual = UD->getQualifier(); 6938 } else if (UnresolvedUsingValueDecl *UD 6939 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 6940 DTypename = false; 6941 DQual = UD->getQualifier(); 6942 } else if (UnresolvedUsingTypenameDecl *UD 6943 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 6944 DTypename = true; 6945 DQual = UD->getQualifier(); 6946 } else continue; 6947 6948 // using decls differ if one says 'typename' and the other doesn't. 6949 // FIXME: non-dependent using decls? 6950 if (isTypeName != DTypename) continue; 6951 6952 // using decls differ if they name different scopes (but note that 6953 // template instantiation can cause this check to trigger when it 6954 // didn't before instantiation). 6955 if (Context.getCanonicalNestedNameSpecifier(Qual) != 6956 Context.getCanonicalNestedNameSpecifier(DQual)) 6957 continue; 6958 6959 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 6960 Diag(D->getLocation(), diag::note_using_decl) << 1; 6961 return true; 6962 } 6963 6964 return false; 6965} 6966 6967 6968/// Checks that the given nested-name qualifier used in a using decl 6969/// in the current context is appropriately related to the current 6970/// scope. If an error is found, diagnoses it and returns true. 6971bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 6972 const CXXScopeSpec &SS, 6973 SourceLocation NameLoc) { 6974 DeclContext *NamedContext = computeDeclContext(SS); 6975 6976 if (!CurContext->isRecord()) { 6977 // C++03 [namespace.udecl]p3: 6978 // C++0x [namespace.udecl]p8: 6979 // A using-declaration for a class member shall be a member-declaration. 6980 6981 // If we weren't able to compute a valid scope, it must be a 6982 // dependent class scope. 6983 if (!NamedContext || NamedContext->isRecord()) { 6984 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 6985 << SS.getRange(); 6986 return true; 6987 } 6988 6989 // Otherwise, everything is known to be fine. 6990 return false; 6991 } 6992 6993 // The current scope is a record. 6994 6995 // If the named context is dependent, we can't decide much. 6996 if (!NamedContext) { 6997 // FIXME: in C++0x, we can diagnose if we can prove that the 6998 // nested-name-specifier does not refer to a base class, which is 6999 // still possible in some cases. 7000 7001 // Otherwise we have to conservatively report that things might be 7002 // okay. 7003 return false; 7004 } 7005 7006 if (!NamedContext->isRecord()) { 7007 // Ideally this would point at the last name in the specifier, 7008 // but we don't have that level of source info. 7009 Diag(SS.getRange().getBegin(), 7010 diag::err_using_decl_nested_name_specifier_is_not_class) 7011 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange(); 7012 return true; 7013 } 7014 7015 if (!NamedContext->isDependentContext() && 7016 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 7017 return true; 7018 7019 if (getLangOpts().CPlusPlus0x) { 7020 // C++0x [namespace.udecl]p3: 7021 // In a using-declaration used as a member-declaration, the 7022 // nested-name-specifier shall name a base class of the class 7023 // being defined. 7024 7025 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 7026 cast<CXXRecordDecl>(NamedContext))) { 7027 if (CurContext == NamedContext) { 7028 Diag(NameLoc, 7029 diag::err_using_decl_nested_name_specifier_is_current_class) 7030 << SS.getRange(); 7031 return true; 7032 } 7033 7034 Diag(SS.getRange().getBegin(), 7035 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7036 << (NestedNameSpecifier*) SS.getScopeRep() 7037 << cast<CXXRecordDecl>(CurContext) 7038 << SS.getRange(); 7039 return true; 7040 } 7041 7042 return false; 7043 } 7044 7045 // C++03 [namespace.udecl]p4: 7046 // A using-declaration used as a member-declaration shall refer 7047 // to a member of a base class of the class being defined [etc.]. 7048 7049 // Salient point: SS doesn't have to name a base class as long as 7050 // lookup only finds members from base classes. Therefore we can 7051 // diagnose here only if we can prove that that can't happen, 7052 // i.e. if the class hierarchies provably don't intersect. 7053 7054 // TODO: it would be nice if "definitely valid" results were cached 7055 // in the UsingDecl and UsingShadowDecl so that these checks didn't 7056 // need to be repeated. 7057 7058 struct UserData { 7059 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases; 7060 7061 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) { 7062 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 7063 Data->Bases.insert(Base); 7064 return true; 7065 } 7066 7067 bool hasDependentBases(const CXXRecordDecl *Class) { 7068 return !Class->forallBases(collect, this); 7069 } 7070 7071 /// Returns true if the base is dependent or is one of the 7072 /// accumulated base classes. 7073 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) { 7074 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 7075 return !Data->Bases.count(Base); 7076 } 7077 7078 bool mightShareBases(const CXXRecordDecl *Class) { 7079 return Bases.count(Class) || !Class->forallBases(doesNotContain, this); 7080 } 7081 }; 7082 7083 UserData Data; 7084 7085 // Returns false if we find a dependent base. 7086 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext))) 7087 return false; 7088 7089 // Returns false if the class has a dependent base or if it or one 7090 // of its bases is present in the base set of the current context. 7091 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext))) 7092 return false; 7093 7094 Diag(SS.getRange().getBegin(), 7095 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7096 << (NestedNameSpecifier*) SS.getScopeRep() 7097 << cast<CXXRecordDecl>(CurContext) 7098 << SS.getRange(); 7099 7100 return true; 7101} 7102 7103Decl *Sema::ActOnAliasDeclaration(Scope *S, 7104 AccessSpecifier AS, 7105 MultiTemplateParamsArg TemplateParamLists, 7106 SourceLocation UsingLoc, 7107 UnqualifiedId &Name, 7108 TypeResult Type) { 7109 // Skip up to the relevant declaration scope. 7110 while (S->getFlags() & Scope::TemplateParamScope) 7111 S = S->getParent(); 7112 assert((S->getFlags() & Scope::DeclScope) && 7113 "got alias-declaration outside of declaration scope"); 7114 7115 if (Type.isInvalid()) 7116 return 0; 7117 7118 bool Invalid = false; 7119 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 7120 TypeSourceInfo *TInfo = 0; 7121 GetTypeFromParser(Type.get(), &TInfo); 7122 7123 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 7124 return 0; 7125 7126 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 7127 UPPC_DeclarationType)) { 7128 Invalid = true; 7129 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 7130 TInfo->getTypeLoc().getBeginLoc()); 7131 } 7132 7133 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration); 7134 LookupName(Previous, S); 7135 7136 // Warn about shadowing the name of a template parameter. 7137 if (Previous.isSingleResult() && 7138 Previous.getFoundDecl()->isTemplateParameter()) { 7139 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 7140 Previous.clear(); 7141 } 7142 7143 assert(Name.Kind == UnqualifiedId::IK_Identifier && 7144 "name in alias declaration must be an identifier"); 7145 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 7146 Name.StartLocation, 7147 Name.Identifier, TInfo); 7148 7149 NewTD->setAccess(AS); 7150 7151 if (Invalid) 7152 NewTD->setInvalidDecl(); 7153 7154 CheckTypedefForVariablyModifiedType(S, NewTD); 7155 Invalid |= NewTD->isInvalidDecl(); 7156 7157 bool Redeclaration = false; 7158 7159 NamedDecl *NewND; 7160 if (TemplateParamLists.size()) { 7161 TypeAliasTemplateDecl *OldDecl = 0; 7162 TemplateParameterList *OldTemplateParams = 0; 7163 7164 if (TemplateParamLists.size() != 1) { 7165 Diag(UsingLoc, diag::err_alias_template_extra_headers) 7166 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 7167 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 7168 } 7169 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 7170 7171 // Only consider previous declarations in the same scope. 7172 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 7173 /*ExplicitInstantiationOrSpecialization*/false); 7174 if (!Previous.empty()) { 7175 Redeclaration = true; 7176 7177 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 7178 if (!OldDecl && !Invalid) { 7179 Diag(UsingLoc, diag::err_redefinition_different_kind) 7180 << Name.Identifier; 7181 7182 NamedDecl *OldD = Previous.getRepresentativeDecl(); 7183 if (OldD->getLocation().isValid()) 7184 Diag(OldD->getLocation(), diag::note_previous_definition); 7185 7186 Invalid = true; 7187 } 7188 7189 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 7190 if (TemplateParameterListsAreEqual(TemplateParams, 7191 OldDecl->getTemplateParameters(), 7192 /*Complain=*/true, 7193 TPL_TemplateMatch)) 7194 OldTemplateParams = OldDecl->getTemplateParameters(); 7195 else 7196 Invalid = true; 7197 7198 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 7199 if (!Invalid && 7200 !Context.hasSameType(OldTD->getUnderlyingType(), 7201 NewTD->getUnderlyingType())) { 7202 // FIXME: The C++0x standard does not clearly say this is ill-formed, 7203 // but we can't reasonably accept it. 7204 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 7205 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 7206 if (OldTD->getLocation().isValid()) 7207 Diag(OldTD->getLocation(), diag::note_previous_definition); 7208 Invalid = true; 7209 } 7210 } 7211 } 7212 7213 // Merge any previous default template arguments into our parameters, 7214 // and check the parameter list. 7215 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 7216 TPC_TypeAliasTemplate)) 7217 return 0; 7218 7219 TypeAliasTemplateDecl *NewDecl = 7220 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 7221 Name.Identifier, TemplateParams, 7222 NewTD); 7223 7224 NewDecl->setAccess(AS); 7225 7226 if (Invalid) 7227 NewDecl->setInvalidDecl(); 7228 else if (OldDecl) 7229 NewDecl->setPreviousDeclaration(OldDecl); 7230 7231 NewND = NewDecl; 7232 } else { 7233 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 7234 NewND = NewTD; 7235 } 7236 7237 if (!Redeclaration) 7238 PushOnScopeChains(NewND, S); 7239 7240 ActOnDocumentableDecl(NewND); 7241 return NewND; 7242} 7243 7244Decl *Sema::ActOnNamespaceAliasDef(Scope *S, 7245 SourceLocation NamespaceLoc, 7246 SourceLocation AliasLoc, 7247 IdentifierInfo *Alias, 7248 CXXScopeSpec &SS, 7249 SourceLocation IdentLoc, 7250 IdentifierInfo *Ident) { 7251 7252 // Lookup the namespace name. 7253 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 7254 LookupParsedName(R, S, &SS); 7255 7256 // Check if we have a previous declaration with the same name. 7257 NamedDecl *PrevDecl 7258 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName, 7259 ForRedeclaration); 7260 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S)) 7261 PrevDecl = 0; 7262 7263 if (PrevDecl) { 7264 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 7265 // We already have an alias with the same name that points to the same 7266 // namespace, so don't create a new one. 7267 // FIXME: At some point, we'll want to create the (redundant) 7268 // declaration to maintain better source information. 7269 if (!R.isAmbiguous() && !R.empty() && 7270 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl()))) 7271 return 0; 7272 } 7273 7274 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition : 7275 diag::err_redefinition_different_kind; 7276 Diag(AliasLoc, DiagID) << Alias; 7277 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 7278 return 0; 7279 } 7280 7281 if (R.isAmbiguous()) 7282 return 0; 7283 7284 if (R.empty()) { 7285 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 7286 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 7287 return 0; 7288 } 7289 } 7290 7291 NamespaceAliasDecl *AliasDecl = 7292 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 7293 Alias, SS.getWithLocInContext(Context), 7294 IdentLoc, R.getFoundDecl()); 7295 7296 PushOnScopeChains(AliasDecl, S); 7297 return AliasDecl; 7298} 7299 7300Sema::ImplicitExceptionSpecification 7301Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, 7302 CXXMethodDecl *MD) { 7303 CXXRecordDecl *ClassDecl = MD->getParent(); 7304 7305 // C++ [except.spec]p14: 7306 // An implicitly declared special member function (Clause 12) shall have an 7307 // exception-specification. [...] 7308 ImplicitExceptionSpecification ExceptSpec(*this); 7309 if (ClassDecl->isInvalidDecl()) 7310 return ExceptSpec; 7311 7312 // Direct base-class constructors. 7313 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 7314 BEnd = ClassDecl->bases_end(); 7315 B != BEnd; ++B) { 7316 if (B->isVirtual()) // Handled below. 7317 continue; 7318 7319 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 7320 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7321 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 7322 // If this is a deleted function, add it anyway. This might be conformant 7323 // with the standard. This might not. I'm not sure. It might not matter. 7324 if (Constructor) 7325 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 7326 } 7327 } 7328 7329 // Virtual base-class constructors. 7330 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 7331 BEnd = ClassDecl->vbases_end(); 7332 B != BEnd; ++B) { 7333 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 7334 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7335 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 7336 // If this is a deleted function, add it anyway. This might be conformant 7337 // with the standard. This might not. I'm not sure. It might not matter. 7338 if (Constructor) 7339 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 7340 } 7341 } 7342 7343 // Field constructors. 7344 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 7345 FEnd = ClassDecl->field_end(); 7346 F != FEnd; ++F) { 7347 if (F->hasInClassInitializer()) { 7348 if (Expr *E = F->getInClassInitializer()) 7349 ExceptSpec.CalledExpr(E); 7350 else if (!F->isInvalidDecl()) 7351 // DR1351: 7352 // If the brace-or-equal-initializer of a non-static data member 7353 // invokes a defaulted default constructor of its class or of an 7354 // enclosing class in a potentially evaluated subexpression, the 7355 // program is ill-formed. 7356 // 7357 // This resolution is unworkable: the exception specification of the 7358 // default constructor can be needed in an unevaluated context, in 7359 // particular, in the operand of a noexcept-expression, and we can be 7360 // unable to compute an exception specification for an enclosed class. 7361 // 7362 // We do not allow an in-class initializer to require the evaluation 7363 // of the exception specification for any in-class initializer whose 7364 // definition is not lexically complete. 7365 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD; 7366 } else if (const RecordType *RecordTy 7367 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 7368 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 7369 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 7370 // If this is a deleted function, add it anyway. This might be conformant 7371 // with the standard. This might not. I'm not sure. It might not matter. 7372 // In particular, the problem is that this function never gets called. It 7373 // might just be ill-formed because this function attempts to refer to 7374 // a deleted function here. 7375 if (Constructor) 7376 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 7377 } 7378 } 7379 7380 return ExceptSpec; 7381} 7382 7383namespace { 7384/// RAII object to register a special member as being currently declared. 7385struct DeclaringSpecialMember { 7386 Sema &S; 7387 Sema::SpecialMemberDecl D; 7388 bool WasAlreadyBeingDeclared; 7389 7390 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 7391 : S(S), D(RD, CSM) { 7392 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D); 7393 if (WasAlreadyBeingDeclared) 7394 // This almost never happens, but if it does, ensure that our cache 7395 // doesn't contain a stale result. 7396 S.SpecialMemberCache.clear(); 7397 7398 // FIXME: Register a note to be produced if we encounter an error while 7399 // declaring the special member. 7400 } 7401 ~DeclaringSpecialMember() { 7402 if (!WasAlreadyBeingDeclared) 7403 S.SpecialMembersBeingDeclared.erase(D); 7404 } 7405 7406 /// \brief Are we already trying to declare this special member? 7407 bool isAlreadyBeingDeclared() const { 7408 return WasAlreadyBeingDeclared; 7409 } 7410}; 7411} 7412 7413CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 7414 CXXRecordDecl *ClassDecl) { 7415 // C++ [class.ctor]p5: 7416 // A default constructor for a class X is a constructor of class X 7417 // that can be called without an argument. If there is no 7418 // user-declared constructor for class X, a default constructor is 7419 // implicitly declared. An implicitly-declared default constructor 7420 // is an inline public member of its class. 7421 assert(ClassDecl->needsImplicitDefaultConstructor() && 7422 "Should not build implicit default constructor!"); 7423 7424 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 7425 if (DSM.isAlreadyBeingDeclared()) 7426 return 0; 7427 7428 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 7429 CXXDefaultConstructor, 7430 false); 7431 7432 // Create the actual constructor declaration. 7433 CanQualType ClassType 7434 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 7435 SourceLocation ClassLoc = ClassDecl->getLocation(); 7436 DeclarationName Name 7437 = Context.DeclarationNames.getCXXConstructorName(ClassType); 7438 DeclarationNameInfo NameInfo(Name, ClassLoc); 7439 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 7440 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0, 7441 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 7442 Constexpr); 7443 DefaultCon->setAccess(AS_public); 7444 DefaultCon->setDefaulted(); 7445 DefaultCon->setImplicit(); 7446 7447 // Build an exception specification pointing back at this constructor. 7448 FunctionProtoType::ExtProtoInfo EPI; 7449 EPI.ExceptionSpecType = EST_Unevaluated; 7450 EPI.ExceptionSpecDecl = DefaultCon; 7451 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI)); 7452 7453 // We don't need to use SpecialMemberIsTrivial here; triviality for default 7454 // constructors is easy to compute. 7455 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 7456 7457 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 7458 DefaultCon->setDeletedAsWritten(); 7459 7460 // Note that we have declared this constructor. 7461 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 7462 7463 if (Scope *S = getScopeForContext(ClassDecl)) 7464 PushOnScopeChains(DefaultCon, S, false); 7465 ClassDecl->addDecl(DefaultCon); 7466 7467 return DefaultCon; 7468} 7469 7470void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 7471 CXXConstructorDecl *Constructor) { 7472 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 7473 !Constructor->doesThisDeclarationHaveABody() && 7474 !Constructor->isDeleted()) && 7475 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 7476 7477 CXXRecordDecl *ClassDecl = Constructor->getParent(); 7478 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 7479 7480 SynthesizedFunctionScope Scope(*this, Constructor); 7481 DiagnosticErrorTrap Trap(Diags); 7482 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) || 7483 Trap.hasErrorOccurred()) { 7484 Diag(CurrentLocation, diag::note_member_synthesized_at) 7485 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl); 7486 Constructor->setInvalidDecl(); 7487 return; 7488 } 7489 7490 SourceLocation Loc = Constructor->getLocation(); 7491 Constructor->setBody(new (Context) CompoundStmt(Loc)); 7492 7493 Constructor->setUsed(); 7494 MarkVTableUsed(CurrentLocation, ClassDecl); 7495 7496 if (ASTMutationListener *L = getASTMutationListener()) { 7497 L->CompletedImplicitDefinition(Constructor); 7498 } 7499} 7500 7501void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 7502 if (!D) return; 7503 AdjustDeclIfTemplate(D); 7504 7505 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D); 7506 7507 if (!ClassDecl->isDependentType()) 7508 CheckExplicitlyDefaultedAndDeletedMethods(ClassDecl); 7509 7510 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member 7511 // function that is not a constructor declares that member function to be 7512 // const. [...] The class of which that function is a member shall be 7513 // a literal type. 7514 // 7515 // If the class has virtual bases, any constexpr members will already have 7516 // been diagnosed by the checks performed on the member declaration, so 7517 // suppress this (less useful) diagnostic. 7518 // 7519 // We delay this until we know whether an explicitly-defaulted (or deleted) 7520 // destructor for the class is trivial. 7521 if (LangOpts.CPlusPlus0x && !ClassDecl->isDependentType() && 7522 !ClassDecl->isLiteral() && !ClassDecl->getNumVBases()) { 7523 for (CXXRecordDecl::method_iterator M = ClassDecl->method_begin(), 7524 MEnd = ClassDecl->method_end(); 7525 M != MEnd; ++M) { 7526 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) { 7527 switch (ClassDecl->getTemplateSpecializationKind()) { 7528 case TSK_ImplicitInstantiation: 7529 case TSK_ExplicitInstantiationDeclaration: 7530 case TSK_ExplicitInstantiationDefinition: 7531 // If a template instantiates to a non-literal type, but its members 7532 // instantiate to constexpr functions, the template is technically 7533 // ill-formed, but we allow it for sanity. 7534 continue; 7535 7536 case TSK_Undeclared: 7537 case TSK_ExplicitSpecialization: 7538 RequireLiteralType(M->getLocation(), Context.getRecordType(ClassDecl), 7539 diag::err_constexpr_method_non_literal); 7540 break; 7541 } 7542 7543 // Only produce one error per class. 7544 break; 7545 } 7546 } 7547 } 7548} 7549 7550void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) { 7551 // We start with an initial pass over the base classes to collect those that 7552 // inherit constructors from. If there are none, we can forgo all further 7553 // processing. 7554 typedef SmallVector<const RecordType *, 4> BasesVector; 7555 BasesVector BasesToInheritFrom; 7556 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(), 7557 BaseE = ClassDecl->bases_end(); 7558 BaseIt != BaseE; ++BaseIt) { 7559 if (BaseIt->getInheritConstructors()) { 7560 QualType Base = BaseIt->getType(); 7561 if (Base->isDependentType()) { 7562 // If we inherit constructors from anything that is dependent, just 7563 // abort processing altogether. We'll get another chance for the 7564 // instantiations. 7565 return; 7566 } 7567 BasesToInheritFrom.push_back(Base->castAs<RecordType>()); 7568 } 7569 } 7570 if (BasesToInheritFrom.empty()) 7571 return; 7572 7573 // Now collect the constructors that we already have in the current class. 7574 // Those take precedence over inherited constructors. 7575 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...] 7576 // unless there is a user-declared constructor with the same signature in 7577 // the class where the using-declaration appears. 7578 llvm::SmallSet<const Type *, 8> ExistingConstructors; 7579 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(), 7580 CtorE = ClassDecl->ctor_end(); 7581 CtorIt != CtorE; ++CtorIt) { 7582 ExistingConstructors.insert( 7583 Context.getCanonicalType(CtorIt->getType()).getTypePtr()); 7584 } 7585 7586 DeclarationName CreatedCtorName = 7587 Context.DeclarationNames.getCXXConstructorName( 7588 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified()); 7589 7590 // Now comes the true work. 7591 // First, we keep a map from constructor types to the base that introduced 7592 // them. Needed for finding conflicting constructors. We also keep the 7593 // actually inserted declarations in there, for pretty diagnostics. 7594 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo; 7595 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap; 7596 ConstructorToSourceMap InheritedConstructors; 7597 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(), 7598 BaseE = BasesToInheritFrom.end(); 7599 BaseIt != BaseE; ++BaseIt) { 7600 const RecordType *Base = *BaseIt; 7601 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified(); 7602 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl()); 7603 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(), 7604 CtorE = BaseDecl->ctor_end(); 7605 CtorIt != CtorE; ++CtorIt) { 7606 // Find the using declaration for inheriting this base's constructors. 7607 // FIXME: Don't perform name lookup just to obtain a source location! 7608 DeclarationName Name = 7609 Context.DeclarationNames.getCXXConstructorName(CanonicalBase); 7610 LookupResult Result(*this, Name, SourceLocation(), LookupUsingDeclName); 7611 LookupQualifiedName(Result, CurContext); 7612 UsingDecl *UD = Result.getAsSingle<UsingDecl>(); 7613 SourceLocation UsingLoc = UD ? UD->getLocation() : 7614 ClassDecl->getLocation(); 7615 7616 // C++0x [class.inhctor]p1: The candidate set of inherited constructors 7617 // from the class X named in the using-declaration consists of actual 7618 // constructors and notional constructors that result from the 7619 // transformation of defaulted parameters as follows: 7620 // - all non-template default constructors of X, and 7621 // - for each non-template constructor of X that has at least one 7622 // parameter with a default argument, the set of constructors that 7623 // results from omitting any ellipsis parameter specification and 7624 // successively omitting parameters with a default argument from the 7625 // end of the parameter-type-list. 7626 CXXConstructorDecl *BaseCtor = *CtorIt; 7627 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor(); 7628 const FunctionProtoType *BaseCtorType = 7629 BaseCtor->getType()->getAs<FunctionProtoType>(); 7630 7631 for (unsigned params = BaseCtor->getMinRequiredArguments(), 7632 maxParams = BaseCtor->getNumParams(); 7633 params <= maxParams; ++params) { 7634 // Skip default constructors. They're never inherited. 7635 if (params == 0) 7636 continue; 7637 // Skip copy and move constructors for the same reason. 7638 if (CanBeCopyOrMove && params == 1) 7639 continue; 7640 7641 // Build up a function type for this particular constructor. 7642 // FIXME: The working paper does not consider that the exception spec 7643 // for the inheriting constructor might be larger than that of the 7644 // source. This code doesn't yet, either. When it does, this code will 7645 // need to be delayed until after exception specifications and in-class 7646 // member initializers are attached. 7647 const Type *NewCtorType; 7648 if (params == maxParams) 7649 NewCtorType = BaseCtorType; 7650 else { 7651 SmallVector<QualType, 16> Args; 7652 for (unsigned i = 0; i < params; ++i) { 7653 Args.push_back(BaseCtorType->getArgType(i)); 7654 } 7655 FunctionProtoType::ExtProtoInfo ExtInfo = 7656 BaseCtorType->getExtProtoInfo(); 7657 ExtInfo.Variadic = false; 7658 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(), 7659 Args.data(), params, ExtInfo) 7660 .getTypePtr(); 7661 } 7662 const Type *CanonicalNewCtorType = 7663 Context.getCanonicalType(NewCtorType); 7664 7665 // Now that we have the type, first check if the class already has a 7666 // constructor with this signature. 7667 if (ExistingConstructors.count(CanonicalNewCtorType)) 7668 continue; 7669 7670 // Then we check if we have already declared an inherited constructor 7671 // with this signature. 7672 std::pair<ConstructorToSourceMap::iterator, bool> result = 7673 InheritedConstructors.insert(std::make_pair( 7674 CanonicalNewCtorType, 7675 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0))); 7676 if (!result.second) { 7677 // Already in the map. If it came from a different class, that's an 7678 // error. Not if it's from the same. 7679 CanQualType PreviousBase = result.first->second.first; 7680 if (CanonicalBase != PreviousBase) { 7681 const CXXConstructorDecl *PrevCtor = result.first->second.second; 7682 const CXXConstructorDecl *PrevBaseCtor = 7683 PrevCtor->getInheritedConstructor(); 7684 assert(PrevBaseCtor && "Conflicting constructor was not inherited"); 7685 7686 Diag(UsingLoc, diag::err_using_decl_constructor_conflict); 7687 Diag(BaseCtor->getLocation(), 7688 diag::note_using_decl_constructor_conflict_current_ctor); 7689 Diag(PrevBaseCtor->getLocation(), 7690 diag::note_using_decl_constructor_conflict_previous_ctor); 7691 Diag(PrevCtor->getLocation(), 7692 diag::note_using_decl_constructor_conflict_previous_using); 7693 } 7694 continue; 7695 } 7696 7697 // OK, we're there, now add the constructor. 7698 // C++0x [class.inhctor]p8: [...] that would be performed by a 7699 // user-written inline constructor [...] 7700 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc); 7701 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create( 7702 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0), 7703 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true, 7704 /*ImplicitlyDeclared=*/true, 7705 // FIXME: Due to a defect in the standard, we treat inherited 7706 // constructors as constexpr even if that makes them ill-formed. 7707 /*Constexpr=*/BaseCtor->isConstexpr()); 7708 NewCtor->setAccess(BaseCtor->getAccess()); 7709 7710 // Build up the parameter decls and add them. 7711 SmallVector<ParmVarDecl *, 16> ParamDecls; 7712 for (unsigned i = 0; i < params; ++i) { 7713 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor, 7714 UsingLoc, UsingLoc, 7715 /*IdentifierInfo=*/0, 7716 BaseCtorType->getArgType(i), 7717 /*TInfo=*/0, SC_None, 7718 SC_None, /*DefaultArg=*/0)); 7719 } 7720 NewCtor->setParams(ParamDecls); 7721 NewCtor->setInheritedConstructor(BaseCtor); 7722 7723 ClassDecl->addDecl(NewCtor); 7724 result.first->second.second = NewCtor; 7725 } 7726 } 7727 } 7728} 7729 7730Sema::ImplicitExceptionSpecification 7731Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) { 7732 CXXRecordDecl *ClassDecl = MD->getParent(); 7733 7734 // C++ [except.spec]p14: 7735 // An implicitly declared special member function (Clause 12) shall have 7736 // an exception-specification. 7737 ImplicitExceptionSpecification ExceptSpec(*this); 7738 if (ClassDecl->isInvalidDecl()) 7739 return ExceptSpec; 7740 7741 // Direct base-class destructors. 7742 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 7743 BEnd = ClassDecl->bases_end(); 7744 B != BEnd; ++B) { 7745 if (B->isVirtual()) // Handled below. 7746 continue; 7747 7748 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) 7749 ExceptSpec.CalledDecl(B->getLocStart(), 7750 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 7751 } 7752 7753 // Virtual base-class destructors. 7754 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 7755 BEnd = ClassDecl->vbases_end(); 7756 B != BEnd; ++B) { 7757 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) 7758 ExceptSpec.CalledDecl(B->getLocStart(), 7759 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 7760 } 7761 7762 // Field destructors. 7763 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 7764 FEnd = ClassDecl->field_end(); 7765 F != FEnd; ++F) { 7766 if (const RecordType *RecordTy 7767 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) 7768 ExceptSpec.CalledDecl(F->getLocation(), 7769 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl()))); 7770 } 7771 7772 return ExceptSpec; 7773} 7774 7775CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 7776 // C++ [class.dtor]p2: 7777 // If a class has no user-declared destructor, a destructor is 7778 // declared implicitly. An implicitly-declared destructor is an 7779 // inline public member of its class. 7780 assert(ClassDecl->needsImplicitDestructor()); 7781 7782 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 7783 if (DSM.isAlreadyBeingDeclared()) 7784 return 0; 7785 7786 // Create the actual destructor declaration. 7787 CanQualType ClassType 7788 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 7789 SourceLocation ClassLoc = ClassDecl->getLocation(); 7790 DeclarationName Name 7791 = Context.DeclarationNames.getCXXDestructorName(ClassType); 7792 DeclarationNameInfo NameInfo(Name, ClassLoc); 7793 CXXDestructorDecl *Destructor 7794 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 7795 QualType(), 0, /*isInline=*/true, 7796 /*isImplicitlyDeclared=*/true); 7797 Destructor->setAccess(AS_public); 7798 Destructor->setDefaulted(); 7799 Destructor->setImplicit(); 7800 7801 // Build an exception specification pointing back at this destructor. 7802 FunctionProtoType::ExtProtoInfo EPI; 7803 EPI.ExceptionSpecType = EST_Unevaluated; 7804 EPI.ExceptionSpecDecl = Destructor; 7805 Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI)); 7806 7807 AddOverriddenMethods(ClassDecl, Destructor); 7808 7809 // We don't need to use SpecialMemberIsTrivial here; triviality for 7810 // destructors is easy to compute. 7811 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 7812 7813 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 7814 Destructor->setDeletedAsWritten(); 7815 7816 // Note that we have declared this destructor. 7817 ++ASTContext::NumImplicitDestructorsDeclared; 7818 7819 // Introduce this destructor into its scope. 7820 if (Scope *S = getScopeForContext(ClassDecl)) 7821 PushOnScopeChains(Destructor, S, false); 7822 ClassDecl->addDecl(Destructor); 7823 7824 return Destructor; 7825} 7826 7827void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 7828 CXXDestructorDecl *Destructor) { 7829 assert((Destructor->isDefaulted() && 7830 !Destructor->doesThisDeclarationHaveABody() && 7831 !Destructor->isDeleted()) && 7832 "DefineImplicitDestructor - call it for implicit default dtor"); 7833 CXXRecordDecl *ClassDecl = Destructor->getParent(); 7834 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 7835 7836 if (Destructor->isInvalidDecl()) 7837 return; 7838 7839 SynthesizedFunctionScope Scope(*this, Destructor); 7840 7841 DiagnosticErrorTrap Trap(Diags); 7842 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 7843 Destructor->getParent()); 7844 7845 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) { 7846 Diag(CurrentLocation, diag::note_member_synthesized_at) 7847 << CXXDestructor << Context.getTagDeclType(ClassDecl); 7848 7849 Destructor->setInvalidDecl(); 7850 return; 7851 } 7852 7853 SourceLocation Loc = Destructor->getLocation(); 7854 Destructor->setBody(new (Context) CompoundStmt(Loc)); 7855 Destructor->setImplicitlyDefined(true); 7856 Destructor->setUsed(); 7857 MarkVTableUsed(CurrentLocation, ClassDecl); 7858 7859 if (ASTMutationListener *L = getASTMutationListener()) { 7860 L->CompletedImplicitDefinition(Destructor); 7861 } 7862} 7863 7864/// \brief Perform any semantic analysis which needs to be delayed until all 7865/// pending class member declarations have been parsed. 7866void Sema::ActOnFinishCXXMemberDecls() { 7867 // Perform any deferred checking of exception specifications for virtual 7868 // destructors. 7869 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size(); 7870 i != e; ++i) { 7871 const CXXDestructorDecl *Dtor = 7872 DelayedDestructorExceptionSpecChecks[i].first; 7873 assert(!Dtor->getParent()->isDependentType() && 7874 "Should not ever add destructors of templates into the list."); 7875 CheckOverridingFunctionExceptionSpec(Dtor, 7876 DelayedDestructorExceptionSpecChecks[i].second); 7877 } 7878 DelayedDestructorExceptionSpecChecks.clear(); 7879} 7880 7881void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 7882 CXXDestructorDecl *Destructor) { 7883 assert(getLangOpts().CPlusPlus0x && 7884 "adjusting dtor exception specs was introduced in c++11"); 7885 7886 // C++11 [class.dtor]p3: 7887 // A declaration of a destructor that does not have an exception- 7888 // specification is implicitly considered to have the same exception- 7889 // specification as an implicit declaration. 7890 const FunctionProtoType *DtorType = Destructor->getType()-> 7891 getAs<FunctionProtoType>(); 7892 if (DtorType->hasExceptionSpec()) 7893 return; 7894 7895 // Replace the destructor's type, building off the existing one. Fortunately, 7896 // the only thing of interest in the destructor type is its extended info. 7897 // The return and arguments are fixed. 7898 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 7899 EPI.ExceptionSpecType = EST_Unevaluated; 7900 EPI.ExceptionSpecDecl = Destructor; 7901 Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI)); 7902 7903 // FIXME: If the destructor has a body that could throw, and the newly created 7904 // spec doesn't allow exceptions, we should emit a warning, because this 7905 // change in behavior can break conforming C++03 programs at runtime. 7906 // However, we don't have a body or an exception specification yet, so it 7907 // needs to be done somewhere else. 7908} 7909 7910/// When generating a defaulted copy or move assignment operator, if a field 7911/// should be copied with __builtin_memcpy rather than via explicit assignments, 7912/// do so. This optimization only applies for arrays of scalars, and for arrays 7913/// of class type where the selected copy/move-assignment operator is trivial. 7914static StmtResult 7915buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 7916 Expr *To, Expr *From) { 7917 // Compute the size of the memory buffer to be copied. 7918 QualType SizeType = S.Context.getSizeType(); 7919 llvm::APInt Size(S.Context.getTypeSize(SizeType), 7920 S.Context.getTypeSizeInChars(T).getQuantity()); 7921 7922 // Take the address of the field references for "from" and "to". We 7923 // directly construct UnaryOperators here because semantic analysis 7924 // does not permit us to take the address of an xvalue. 7925 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 7926 S.Context.getPointerType(From->getType()), 7927 VK_RValue, OK_Ordinary, Loc); 7928 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 7929 S.Context.getPointerType(To->getType()), 7930 VK_RValue, OK_Ordinary, Loc); 7931 7932 const Type *E = T->getBaseElementTypeUnsafe(); 7933 bool NeedsCollectableMemCpy = 7934 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 7935 7936 // Create a reference to the __builtin_objc_memmove_collectable function 7937 StringRef MemCpyName = NeedsCollectableMemCpy ? 7938 "__builtin_objc_memmove_collectable" : 7939 "__builtin_memcpy"; 7940 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 7941 Sema::LookupOrdinaryName); 7942 S.LookupName(R, S.TUScope, true); 7943 7944 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 7945 if (!MemCpy) 7946 // Something went horribly wrong earlier, and we will have complained 7947 // about it. 7948 return StmtError(); 7949 7950 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 7951 VK_RValue, Loc, 0); 7952 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 7953 7954 Expr *CallArgs[] = { 7955 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 7956 }; 7957 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(), 7958 Loc, CallArgs, Loc); 7959 7960 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 7961 return S.Owned(Call.takeAs<Stmt>()); 7962} 7963 7964/// \brief Builds a statement that copies/moves the given entity from \p From to 7965/// \c To. 7966/// 7967/// This routine is used to copy/move the members of a class with an 7968/// implicitly-declared copy/move assignment operator. When the entities being 7969/// copied are arrays, this routine builds for loops to copy them. 7970/// 7971/// \param S The Sema object used for type-checking. 7972/// 7973/// \param Loc The location where the implicit copy/move is being generated. 7974/// 7975/// \param T The type of the expressions being copied/moved. Both expressions 7976/// must have this type. 7977/// 7978/// \param To The expression we are copying/moving to. 7979/// 7980/// \param From The expression we are copying/moving from. 7981/// 7982/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 7983/// Otherwise, it's a non-static member subobject. 7984/// 7985/// \param Copying Whether we're copying or moving. 7986/// 7987/// \param Depth Internal parameter recording the depth of the recursion. 7988/// 7989/// \returns A statement or a loop that copies the expressions, or StmtResult(0) 7990/// if a memcpy should be used instead. 7991static StmtResult 7992buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 7993 Expr *To, Expr *From, 7994 bool CopyingBaseSubobject, bool Copying, 7995 unsigned Depth = 0) { 7996 // C++11 [class.copy]p28: 7997 // Each subobject is assigned in the manner appropriate to its type: 7998 // 7999 // - if the subobject is of class type, as if by a call to operator= with 8000 // the subobject as the object expression and the corresponding 8001 // subobject of x as a single function argument (as if by explicit 8002 // qualification; that is, ignoring any possible virtual overriding 8003 // functions in more derived classes); 8004 // 8005 // C++03 [class.copy]p13: 8006 // - if the subobject is of class type, the copy assignment operator for 8007 // the class is used (as if by explicit qualification; that is, 8008 // ignoring any possible virtual overriding functions in more derived 8009 // classes); 8010 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 8011 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8012 8013 // Look for operator=. 8014 DeclarationName Name 8015 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 8016 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 8017 S.LookupQualifiedName(OpLookup, ClassDecl, false); 8018 8019 // Prior to C++11, filter out any result that isn't a copy/move-assignment 8020 // operator. 8021 if (!S.getLangOpts().CPlusPlus0x) { 8022 LookupResult::Filter F = OpLookup.makeFilter(); 8023 while (F.hasNext()) { 8024 NamedDecl *D = F.next(); 8025 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 8026 if (Method->isCopyAssignmentOperator() || 8027 (!Copying && Method->isMoveAssignmentOperator())) 8028 continue; 8029 8030 F.erase(); 8031 } 8032 F.done(); 8033 } 8034 8035 // Suppress the protected check (C++ [class.protected]) for each of the 8036 // assignment operators we found. This strange dance is required when 8037 // we're assigning via a base classes's copy-assignment operator. To 8038 // ensure that we're getting the right base class subobject (without 8039 // ambiguities), we need to cast "this" to that subobject type; to 8040 // ensure that we don't go through the virtual call mechanism, we need 8041 // to qualify the operator= name with the base class (see below). However, 8042 // this means that if the base class has a protected copy assignment 8043 // operator, the protected member access check will fail. So, we 8044 // rewrite "protected" access to "public" access in this case, since we 8045 // know by construction that we're calling from a derived class. 8046 if (CopyingBaseSubobject) { 8047 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 8048 L != LEnd; ++L) { 8049 if (L.getAccess() == AS_protected) 8050 L.setAccess(AS_public); 8051 } 8052 } 8053 8054 // Create the nested-name-specifier that will be used to qualify the 8055 // reference to operator=; this is required to suppress the virtual 8056 // call mechanism. 8057 CXXScopeSpec SS; 8058 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 8059 SS.MakeTrivial(S.Context, 8060 NestedNameSpecifier::Create(S.Context, 0, false, 8061 CanonicalT), 8062 Loc); 8063 8064 // Create the reference to operator=. 8065 ExprResult OpEqualRef 8066 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS, 8067 /*TemplateKWLoc=*/SourceLocation(), 8068 /*FirstQualifierInScope=*/0, 8069 OpLookup, 8070 /*TemplateArgs=*/0, 8071 /*SuppressQualifierCheck=*/true); 8072 if (OpEqualRef.isInvalid()) 8073 return StmtError(); 8074 8075 // Build the call to the assignment operator. 8076 8077 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0, 8078 OpEqualRef.takeAs<Expr>(), 8079 Loc, &From, 1, Loc); 8080 if (Call.isInvalid()) 8081 return StmtError(); 8082 8083 // If we built a call to a trivial 'operator=' while copying an array, 8084 // bail out. We'll replace the whole shebang with a memcpy. 8085 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 8086 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 8087 return StmtResult((Stmt*)0); 8088 8089 // Convert to an expression-statement, and clean up any produced 8090 // temporaries. 8091 return S.ActOnExprStmt(S.MakeFullExpr(Call.take(), Loc)); 8092 } 8093 8094 // - if the subobject is of scalar type, the built-in assignment 8095 // operator is used. 8096 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 8097 if (!ArrayTy) { 8098 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From); 8099 if (Assignment.isInvalid()) 8100 return StmtError(); 8101 return S.ActOnExprStmt(S.MakeFullExpr(Assignment.take(), Loc)); 8102 } 8103 8104 // - if the subobject is an array, each element is assigned, in the 8105 // manner appropriate to the element type; 8106 8107 // Construct a loop over the array bounds, e.g., 8108 // 8109 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 8110 // 8111 // that will copy each of the array elements. 8112 QualType SizeType = S.Context.getSizeType(); 8113 8114 // Create the iteration variable. 8115 IdentifierInfo *IterationVarName = 0; 8116 { 8117 SmallString<8> Str; 8118 llvm::raw_svector_ostream OS(Str); 8119 OS << "__i" << Depth; 8120 IterationVarName = &S.Context.Idents.get(OS.str()); 8121 } 8122 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 8123 IterationVarName, SizeType, 8124 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 8125 SC_None, SC_None); 8126 8127 // Initialize the iteration variable to zero. 8128 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 8129 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 8130 8131 // Create a reference to the iteration variable; we'll use this several 8132 // times throughout. 8133 Expr *IterationVarRef 8134 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take(); 8135 assert(IterationVarRef && "Reference to invented variable cannot fail!"); 8136 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take(); 8137 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!"); 8138 8139 // Create the DeclStmt that holds the iteration variable. 8140 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 8141 8142 // Subscript the "from" and "to" expressions with the iteration variable. 8143 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc, 8144 IterationVarRefRVal, 8145 Loc)); 8146 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc, 8147 IterationVarRefRVal, 8148 Loc)); 8149 if (!Copying) // Cast to rvalue 8150 From = CastForMoving(S, From); 8151 8152 // Build the copy/move for an individual element of the array. 8153 StmtResult Copy = 8154 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 8155 To, From, CopyingBaseSubobject, 8156 Copying, Depth + 1); 8157 // Bail out if copying fails or if we determined that we should use memcpy. 8158 if (Copy.isInvalid() || !Copy.get()) 8159 return Copy; 8160 8161 // Create the comparison against the array bound. 8162 llvm::APInt Upper 8163 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 8164 Expr *Comparison 8165 = new (S.Context) BinaryOperator(IterationVarRefRVal, 8166 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 8167 BO_NE, S.Context.BoolTy, 8168 VK_RValue, OK_Ordinary, Loc, false); 8169 8170 // Create the pre-increment of the iteration variable. 8171 Expr *Increment 8172 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType, 8173 VK_LValue, OK_Ordinary, Loc); 8174 8175 // Construct the loop that copies all elements of this array. 8176 return S.ActOnForStmt(Loc, Loc, InitStmt, 8177 S.MakeFullExpr(Comparison), 8178 0, S.MakeFullExpr(Increment), 8179 Loc, Copy.take()); 8180} 8181 8182static StmtResult 8183buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 8184 Expr *To, Expr *From, 8185 bool CopyingBaseSubobject, bool Copying) { 8186 // Maybe we should use a memcpy? 8187 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 8188 T.isTriviallyCopyableType(S.Context)) 8189 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 8190 8191 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 8192 CopyingBaseSubobject, 8193 Copying, 0)); 8194 8195 // If we ended up picking a trivial assignment operator for an array of a 8196 // non-trivially-copyable class type, just emit a memcpy. 8197 if (!Result.isInvalid() && !Result.get()) 8198 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 8199 8200 return Result; 8201} 8202 8203Sema::ImplicitExceptionSpecification 8204Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) { 8205 CXXRecordDecl *ClassDecl = MD->getParent(); 8206 8207 ImplicitExceptionSpecification ExceptSpec(*this); 8208 if (ClassDecl->isInvalidDecl()) 8209 return ExceptSpec; 8210 8211 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 8212 assert(T->getNumArgs() == 1 && "not a copy assignment op"); 8213 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers(); 8214 8215 // C++ [except.spec]p14: 8216 // An implicitly declared special member function (Clause 12) shall have an 8217 // exception-specification. [...] 8218 8219 // It is unspecified whether or not an implicit copy assignment operator 8220 // attempts to deduplicate calls to assignment operators of virtual bases are 8221 // made. As such, this exception specification is effectively unspecified. 8222 // Based on a similar decision made for constness in C++0x, we're erring on 8223 // the side of assuming such calls to be made regardless of whether they 8224 // actually happen. 8225 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 8226 BaseEnd = ClassDecl->bases_end(); 8227 Base != BaseEnd; ++Base) { 8228 if (Base->isVirtual()) 8229 continue; 8230 8231 CXXRecordDecl *BaseClassDecl 8232 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8233 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 8234 ArgQuals, false, 0)) 8235 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign); 8236 } 8237 8238 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 8239 BaseEnd = ClassDecl->vbases_end(); 8240 Base != BaseEnd; ++Base) { 8241 CXXRecordDecl *BaseClassDecl 8242 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8243 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 8244 ArgQuals, false, 0)) 8245 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign); 8246 } 8247 8248 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8249 FieldEnd = ClassDecl->field_end(); 8250 Field != FieldEnd; 8251 ++Field) { 8252 QualType FieldType = Context.getBaseElementType(Field->getType()); 8253 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 8254 if (CXXMethodDecl *CopyAssign = 8255 LookupCopyingAssignment(FieldClassDecl, 8256 ArgQuals | FieldType.getCVRQualifiers(), 8257 false, 0)) 8258 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign); 8259 } 8260 } 8261 8262 return ExceptSpec; 8263} 8264 8265CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 8266 // Note: The following rules are largely analoguous to the copy 8267 // constructor rules. Note that virtual bases are not taken into account 8268 // for determining the argument type of the operator. Note also that 8269 // operators taking an object instead of a reference are allowed. 8270 assert(ClassDecl->needsImplicitCopyAssignment()); 8271 8272 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 8273 if (DSM.isAlreadyBeingDeclared()) 8274 return 0; 8275 8276 QualType ArgType = Context.getTypeDeclType(ClassDecl); 8277 QualType RetType = Context.getLValueReferenceType(ArgType); 8278 if (ClassDecl->implicitCopyAssignmentHasConstParam()) 8279 ArgType = ArgType.withConst(); 8280 ArgType = Context.getLValueReferenceType(ArgType); 8281 8282 // An implicitly-declared copy assignment operator is an inline public 8283 // member of its class. 8284 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 8285 SourceLocation ClassLoc = ClassDecl->getLocation(); 8286 DeclarationNameInfo NameInfo(Name, ClassLoc); 8287 CXXMethodDecl *CopyAssignment 8288 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 8289 /*TInfo=*/0, /*isStatic=*/false, 8290 /*StorageClassAsWritten=*/SC_None, 8291 /*isInline=*/true, /*isConstexpr=*/false, 8292 SourceLocation()); 8293 CopyAssignment->setAccess(AS_public); 8294 CopyAssignment->setDefaulted(); 8295 CopyAssignment->setImplicit(); 8296 8297 // Build an exception specification pointing back at this member. 8298 FunctionProtoType::ExtProtoInfo EPI; 8299 EPI.ExceptionSpecType = EST_Unevaluated; 8300 EPI.ExceptionSpecDecl = CopyAssignment; 8301 CopyAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI)); 8302 8303 // Add the parameter to the operator. 8304 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 8305 ClassLoc, ClassLoc, /*Id=*/0, 8306 ArgType, /*TInfo=*/0, 8307 SC_None, 8308 SC_None, 0); 8309 CopyAssignment->setParams(FromParam); 8310 8311 AddOverriddenMethods(ClassDecl, CopyAssignment); 8312 8313 CopyAssignment->setTrivial( 8314 ClassDecl->needsOverloadResolutionForCopyAssignment() 8315 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 8316 : ClassDecl->hasTrivialCopyAssignment()); 8317 8318 // C++0x [class.copy]p19: 8319 // .... If the class definition does not explicitly declare a copy 8320 // assignment operator, there is no user-declared move constructor, and 8321 // there is no user-declared move assignment operator, a copy assignment 8322 // operator is implicitly declared as defaulted. 8323 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 8324 CopyAssignment->setDeletedAsWritten(); 8325 8326 // Note that we have added this copy-assignment operator. 8327 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 8328 8329 if (Scope *S = getScopeForContext(ClassDecl)) 8330 PushOnScopeChains(CopyAssignment, S, false); 8331 ClassDecl->addDecl(CopyAssignment); 8332 8333 return CopyAssignment; 8334} 8335 8336void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 8337 CXXMethodDecl *CopyAssignOperator) { 8338 assert((CopyAssignOperator->isDefaulted() && 8339 CopyAssignOperator->isOverloadedOperator() && 8340 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 8341 !CopyAssignOperator->doesThisDeclarationHaveABody() && 8342 !CopyAssignOperator->isDeleted()) && 8343 "DefineImplicitCopyAssignment called for wrong function"); 8344 8345 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 8346 8347 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) { 8348 CopyAssignOperator->setInvalidDecl(); 8349 return; 8350 } 8351 8352 CopyAssignOperator->setUsed(); 8353 8354 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 8355 DiagnosticErrorTrap Trap(Diags); 8356 8357 // C++0x [class.copy]p30: 8358 // The implicitly-defined or explicitly-defaulted copy assignment operator 8359 // for a non-union class X performs memberwise copy assignment of its 8360 // subobjects. The direct base classes of X are assigned first, in the 8361 // order of their declaration in the base-specifier-list, and then the 8362 // immediate non-static data members of X are assigned, in the order in 8363 // which they were declared in the class definition. 8364 8365 // The statements that form the synthesized function body. 8366 SmallVector<Stmt*, 8> Statements; 8367 8368 // The parameter for the "other" object, which we are copying from. 8369 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 8370 Qualifiers OtherQuals = Other->getType().getQualifiers(); 8371 QualType OtherRefType = Other->getType(); 8372 if (const LValueReferenceType *OtherRef 8373 = OtherRefType->getAs<LValueReferenceType>()) { 8374 OtherRefType = OtherRef->getPointeeType(); 8375 OtherQuals = OtherRefType.getQualifiers(); 8376 } 8377 8378 // Our location for everything implicitly-generated. 8379 SourceLocation Loc = CopyAssignOperator->getLocation(); 8380 8381 // Construct a reference to the "other" object. We'll be using this 8382 // throughout the generated ASTs. 8383 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take(); 8384 assert(OtherRef && "Reference to parameter cannot fail!"); 8385 8386 // Construct the "this" pointer. We'll be using this throughout the generated 8387 // ASTs. 8388 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>(); 8389 assert(This && "Reference to this cannot fail!"); 8390 8391 // Assign base classes. 8392 bool Invalid = false; 8393 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 8394 E = ClassDecl->bases_end(); Base != E; ++Base) { 8395 // Form the assignment: 8396 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 8397 QualType BaseType = Base->getType().getUnqualifiedType(); 8398 if (!BaseType->isRecordType()) { 8399 Invalid = true; 8400 continue; 8401 } 8402 8403 CXXCastPath BasePath; 8404 BasePath.push_back(Base); 8405 8406 // Construct the "from" expression, which is an implicit cast to the 8407 // appropriately-qualified base type. 8408 Expr *From = OtherRef; 8409 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals), 8410 CK_UncheckedDerivedToBase, 8411 VK_LValue, &BasePath).take(); 8412 8413 // Dereference "this". 8414 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 8415 8416 // Implicitly cast "this" to the appropriately-qualified base type. 8417 To = ImpCastExprToType(To.take(), 8418 Context.getCVRQualifiedType(BaseType, 8419 CopyAssignOperator->getTypeQualifiers()), 8420 CK_UncheckedDerivedToBase, 8421 VK_LValue, &BasePath); 8422 8423 // Build the copy. 8424 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 8425 To.get(), From, 8426 /*CopyingBaseSubobject=*/true, 8427 /*Copying=*/true); 8428 if (Copy.isInvalid()) { 8429 Diag(CurrentLocation, diag::note_member_synthesized_at) 8430 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 8431 CopyAssignOperator->setInvalidDecl(); 8432 return; 8433 } 8434 8435 // Success! Record the copy. 8436 Statements.push_back(Copy.takeAs<Expr>()); 8437 } 8438 8439 // Assign non-static members. 8440 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8441 FieldEnd = ClassDecl->field_end(); 8442 Field != FieldEnd; ++Field) { 8443 if (Field->isUnnamedBitfield()) 8444 continue; 8445 8446 // Check for members of reference type; we can't copy those. 8447 if (Field->getType()->isReferenceType()) { 8448 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 8449 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 8450 Diag(Field->getLocation(), diag::note_declared_at); 8451 Diag(CurrentLocation, diag::note_member_synthesized_at) 8452 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 8453 Invalid = true; 8454 continue; 8455 } 8456 8457 // Check for members of const-qualified, non-class type. 8458 QualType BaseType = Context.getBaseElementType(Field->getType()); 8459 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 8460 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 8461 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 8462 Diag(Field->getLocation(), diag::note_declared_at); 8463 Diag(CurrentLocation, diag::note_member_synthesized_at) 8464 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 8465 Invalid = true; 8466 continue; 8467 } 8468 8469 // Suppress assigning zero-width bitfields. 8470 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 8471 continue; 8472 8473 QualType FieldType = Field->getType().getNonReferenceType(); 8474 if (FieldType->isIncompleteArrayType()) { 8475 assert(ClassDecl->hasFlexibleArrayMember() && 8476 "Incomplete array type is not valid"); 8477 continue; 8478 } 8479 8480 // Build references to the field in the object we're copying from and to. 8481 CXXScopeSpec SS; // Intentionally empty 8482 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 8483 LookupMemberName); 8484 MemberLookup.addDecl(*Field); 8485 MemberLookup.resolveKind(); 8486 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType, 8487 Loc, /*IsArrow=*/false, 8488 SS, SourceLocation(), 0, 8489 MemberLookup, 0); 8490 ExprResult To = BuildMemberReferenceExpr(This, This->getType(), 8491 Loc, /*IsArrow=*/true, 8492 SS, SourceLocation(), 0, 8493 MemberLookup, 0); 8494 assert(!From.isInvalid() && "Implicit field reference cannot fail"); 8495 assert(!To.isInvalid() && "Implicit field reference cannot fail"); 8496 8497 // Build the copy of this field. 8498 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 8499 To.get(), From.get(), 8500 /*CopyingBaseSubobject=*/false, 8501 /*Copying=*/true); 8502 if (Copy.isInvalid()) { 8503 Diag(CurrentLocation, diag::note_member_synthesized_at) 8504 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 8505 CopyAssignOperator->setInvalidDecl(); 8506 return; 8507 } 8508 8509 // Success! Record the copy. 8510 Statements.push_back(Copy.takeAs<Stmt>()); 8511 } 8512 8513 if (!Invalid) { 8514 // Add a "return *this;" 8515 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 8516 8517 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get()); 8518 if (Return.isInvalid()) 8519 Invalid = true; 8520 else { 8521 Statements.push_back(Return.takeAs<Stmt>()); 8522 8523 if (Trap.hasErrorOccurred()) { 8524 Diag(CurrentLocation, diag::note_member_synthesized_at) 8525 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 8526 Invalid = true; 8527 } 8528 } 8529 } 8530 8531 if (Invalid) { 8532 CopyAssignOperator->setInvalidDecl(); 8533 return; 8534 } 8535 8536 StmtResult Body; 8537 { 8538 CompoundScopeRAII CompoundScope(*this); 8539 Body = ActOnCompoundStmt(Loc, Loc, Statements, 8540 /*isStmtExpr=*/false); 8541 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 8542 } 8543 CopyAssignOperator->setBody(Body.takeAs<Stmt>()); 8544 8545 if (ASTMutationListener *L = getASTMutationListener()) { 8546 L->CompletedImplicitDefinition(CopyAssignOperator); 8547 } 8548} 8549 8550Sema::ImplicitExceptionSpecification 8551Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) { 8552 CXXRecordDecl *ClassDecl = MD->getParent(); 8553 8554 ImplicitExceptionSpecification ExceptSpec(*this); 8555 if (ClassDecl->isInvalidDecl()) 8556 return ExceptSpec; 8557 8558 // C++0x [except.spec]p14: 8559 // An implicitly declared special member function (Clause 12) shall have an 8560 // exception-specification. [...] 8561 8562 // It is unspecified whether or not an implicit move assignment operator 8563 // attempts to deduplicate calls to assignment operators of virtual bases are 8564 // made. As such, this exception specification is effectively unspecified. 8565 // Based on a similar decision made for constness in C++0x, we're erring on 8566 // the side of assuming such calls to be made regardless of whether they 8567 // actually happen. 8568 // Note that a move constructor is not implicitly declared when there are 8569 // virtual bases, but it can still be user-declared and explicitly defaulted. 8570 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 8571 BaseEnd = ClassDecl->bases_end(); 8572 Base != BaseEnd; ++Base) { 8573 if (Base->isVirtual()) 8574 continue; 8575 8576 CXXRecordDecl *BaseClassDecl 8577 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8578 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 8579 0, false, 0)) 8580 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign); 8581 } 8582 8583 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 8584 BaseEnd = ClassDecl->vbases_end(); 8585 Base != BaseEnd; ++Base) { 8586 CXXRecordDecl *BaseClassDecl 8587 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8588 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 8589 0, false, 0)) 8590 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign); 8591 } 8592 8593 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8594 FieldEnd = ClassDecl->field_end(); 8595 Field != FieldEnd; 8596 ++Field) { 8597 QualType FieldType = Context.getBaseElementType(Field->getType()); 8598 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 8599 if (CXXMethodDecl *MoveAssign = 8600 LookupMovingAssignment(FieldClassDecl, 8601 FieldType.getCVRQualifiers(), 8602 false, 0)) 8603 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign); 8604 } 8605 } 8606 8607 return ExceptSpec; 8608} 8609 8610/// Determine whether the class type has any direct or indirect virtual base 8611/// classes which have a non-trivial move assignment operator. 8612static bool 8613hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) { 8614 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 8615 BaseEnd = ClassDecl->vbases_end(); 8616 Base != BaseEnd; ++Base) { 8617 CXXRecordDecl *BaseClass = 8618 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8619 8620 // Try to declare the move assignment. If it would be deleted, then the 8621 // class does not have a non-trivial move assignment. 8622 if (BaseClass->needsImplicitMoveAssignment()) 8623 S.DeclareImplicitMoveAssignment(BaseClass); 8624 8625 if (BaseClass->hasNonTrivialMoveAssignment()) 8626 return true; 8627 } 8628 8629 return false; 8630} 8631 8632/// Determine whether the given type either has a move constructor or is 8633/// trivially copyable. 8634static bool 8635hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) { 8636 Type = S.Context.getBaseElementType(Type); 8637 8638 // FIXME: Technically, non-trivially-copyable non-class types, such as 8639 // reference types, are supposed to return false here, but that appears 8640 // to be a standard defect. 8641 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl(); 8642 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl()) 8643 return true; 8644 8645 if (Type.isTriviallyCopyableType(S.Context)) 8646 return true; 8647 8648 if (IsConstructor) { 8649 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to 8650 // give the right answer. 8651 if (ClassDecl->needsImplicitMoveConstructor()) 8652 S.DeclareImplicitMoveConstructor(ClassDecl); 8653 return ClassDecl->hasMoveConstructor(); 8654 } 8655 8656 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to 8657 // give the right answer. 8658 if (ClassDecl->needsImplicitMoveAssignment()) 8659 S.DeclareImplicitMoveAssignment(ClassDecl); 8660 return ClassDecl->hasMoveAssignment(); 8661} 8662 8663/// Determine whether all non-static data members and direct or virtual bases 8664/// of class \p ClassDecl have either a move operation, or are trivially 8665/// copyable. 8666static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl, 8667 bool IsConstructor) { 8668 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 8669 BaseEnd = ClassDecl->bases_end(); 8670 Base != BaseEnd; ++Base) { 8671 if (Base->isVirtual()) 8672 continue; 8673 8674 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor)) 8675 return false; 8676 } 8677 8678 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 8679 BaseEnd = ClassDecl->vbases_end(); 8680 Base != BaseEnd; ++Base) { 8681 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor)) 8682 return false; 8683 } 8684 8685 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8686 FieldEnd = ClassDecl->field_end(); 8687 Field != FieldEnd; ++Field) { 8688 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor)) 8689 return false; 8690 } 8691 8692 return true; 8693} 8694 8695CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 8696 // C++11 [class.copy]p20: 8697 // If the definition of a class X does not explicitly declare a move 8698 // assignment operator, one will be implicitly declared as defaulted 8699 // if and only if: 8700 // 8701 // - [first 4 bullets] 8702 assert(ClassDecl->needsImplicitMoveAssignment()); 8703 8704 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 8705 if (DSM.isAlreadyBeingDeclared()) 8706 return 0; 8707 8708 // [Checked after we build the declaration] 8709 // - the move assignment operator would not be implicitly defined as 8710 // deleted, 8711 8712 // [DR1402]: 8713 // - X has no direct or indirect virtual base class with a non-trivial 8714 // move assignment operator, and 8715 // - each of X's non-static data members and direct or virtual base classes 8716 // has a type that either has a move assignment operator or is trivially 8717 // copyable. 8718 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) || 8719 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) { 8720 ClassDecl->setFailedImplicitMoveAssignment(); 8721 return 0; 8722 } 8723 8724 // Note: The following rules are largely analoguous to the move 8725 // constructor rules. 8726 8727 QualType ArgType = Context.getTypeDeclType(ClassDecl); 8728 QualType RetType = Context.getLValueReferenceType(ArgType); 8729 ArgType = Context.getRValueReferenceType(ArgType); 8730 8731 // An implicitly-declared move assignment operator is an inline public 8732 // member of its class. 8733 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 8734 SourceLocation ClassLoc = ClassDecl->getLocation(); 8735 DeclarationNameInfo NameInfo(Name, ClassLoc); 8736 CXXMethodDecl *MoveAssignment 8737 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 8738 /*TInfo=*/0, /*isStatic=*/false, 8739 /*StorageClassAsWritten=*/SC_None, 8740 /*isInline=*/true, 8741 /*isConstexpr=*/false, 8742 SourceLocation()); 8743 MoveAssignment->setAccess(AS_public); 8744 MoveAssignment->setDefaulted(); 8745 MoveAssignment->setImplicit(); 8746 8747 // Build an exception specification pointing back at this member. 8748 FunctionProtoType::ExtProtoInfo EPI; 8749 EPI.ExceptionSpecType = EST_Unevaluated; 8750 EPI.ExceptionSpecDecl = MoveAssignment; 8751 MoveAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI)); 8752 8753 // Add the parameter to the operator. 8754 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 8755 ClassLoc, ClassLoc, /*Id=*/0, 8756 ArgType, /*TInfo=*/0, 8757 SC_None, 8758 SC_None, 0); 8759 MoveAssignment->setParams(FromParam); 8760 8761 AddOverriddenMethods(ClassDecl, MoveAssignment); 8762 8763 MoveAssignment->setTrivial( 8764 ClassDecl->needsOverloadResolutionForMoveAssignment() 8765 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 8766 : ClassDecl->hasTrivialMoveAssignment()); 8767 8768 // C++0x [class.copy]p9: 8769 // If the definition of a class X does not explicitly declare a move 8770 // assignment operator, one will be implicitly declared as defaulted if and 8771 // only if: 8772 // [...] 8773 // - the move assignment operator would not be implicitly defined as 8774 // deleted. 8775 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 8776 // Cache this result so that we don't try to generate this over and over 8777 // on every lookup, leaking memory and wasting time. 8778 ClassDecl->setFailedImplicitMoveAssignment(); 8779 return 0; 8780 } 8781 8782 // Note that we have added this copy-assignment operator. 8783 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 8784 8785 if (Scope *S = getScopeForContext(ClassDecl)) 8786 PushOnScopeChains(MoveAssignment, S, false); 8787 ClassDecl->addDecl(MoveAssignment); 8788 8789 return MoveAssignment; 8790} 8791 8792void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 8793 CXXMethodDecl *MoveAssignOperator) { 8794 assert((MoveAssignOperator->isDefaulted() && 8795 MoveAssignOperator->isOverloadedOperator() && 8796 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 8797 !MoveAssignOperator->doesThisDeclarationHaveABody() && 8798 !MoveAssignOperator->isDeleted()) && 8799 "DefineImplicitMoveAssignment called for wrong function"); 8800 8801 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 8802 8803 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) { 8804 MoveAssignOperator->setInvalidDecl(); 8805 return; 8806 } 8807 8808 MoveAssignOperator->setUsed(); 8809 8810 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 8811 DiagnosticErrorTrap Trap(Diags); 8812 8813 // C++0x [class.copy]p28: 8814 // The implicitly-defined or move assignment operator for a non-union class 8815 // X performs memberwise move assignment of its subobjects. The direct base 8816 // classes of X are assigned first, in the order of their declaration in the 8817 // base-specifier-list, and then the immediate non-static data members of X 8818 // are assigned, in the order in which they were declared in the class 8819 // definition. 8820 8821 // The statements that form the synthesized function body. 8822 SmallVector<Stmt*, 8> Statements; 8823 8824 // The parameter for the "other" object, which we are move from. 8825 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 8826 QualType OtherRefType = Other->getType()-> 8827 getAs<RValueReferenceType>()->getPointeeType(); 8828 assert(OtherRefType.getQualifiers() == 0 && 8829 "Bad argument type of defaulted move assignment"); 8830 8831 // Our location for everything implicitly-generated. 8832 SourceLocation Loc = MoveAssignOperator->getLocation(); 8833 8834 // Construct a reference to the "other" object. We'll be using this 8835 // throughout the generated ASTs. 8836 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take(); 8837 assert(OtherRef && "Reference to parameter cannot fail!"); 8838 // Cast to rvalue. 8839 OtherRef = CastForMoving(*this, OtherRef); 8840 8841 // Construct the "this" pointer. We'll be using this throughout the generated 8842 // ASTs. 8843 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>(); 8844 assert(This && "Reference to this cannot fail!"); 8845 8846 // Assign base classes. 8847 bool Invalid = false; 8848 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 8849 E = ClassDecl->bases_end(); Base != E; ++Base) { 8850 // Form the assignment: 8851 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 8852 QualType BaseType = Base->getType().getUnqualifiedType(); 8853 if (!BaseType->isRecordType()) { 8854 Invalid = true; 8855 continue; 8856 } 8857 8858 CXXCastPath BasePath; 8859 BasePath.push_back(Base); 8860 8861 // Construct the "from" expression, which is an implicit cast to the 8862 // appropriately-qualified base type. 8863 Expr *From = OtherRef; 8864 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase, 8865 VK_XValue, &BasePath).take(); 8866 8867 // Dereference "this". 8868 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 8869 8870 // Implicitly cast "this" to the appropriately-qualified base type. 8871 To = ImpCastExprToType(To.take(), 8872 Context.getCVRQualifiedType(BaseType, 8873 MoveAssignOperator->getTypeQualifiers()), 8874 CK_UncheckedDerivedToBase, 8875 VK_LValue, &BasePath); 8876 8877 // Build the move. 8878 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 8879 To.get(), From, 8880 /*CopyingBaseSubobject=*/true, 8881 /*Copying=*/false); 8882 if (Move.isInvalid()) { 8883 Diag(CurrentLocation, diag::note_member_synthesized_at) 8884 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 8885 MoveAssignOperator->setInvalidDecl(); 8886 return; 8887 } 8888 8889 // Success! Record the move. 8890 Statements.push_back(Move.takeAs<Expr>()); 8891 } 8892 8893 // Assign non-static members. 8894 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8895 FieldEnd = ClassDecl->field_end(); 8896 Field != FieldEnd; ++Field) { 8897 if (Field->isUnnamedBitfield()) 8898 continue; 8899 8900 // Check for members of reference type; we can't move those. 8901 if (Field->getType()->isReferenceType()) { 8902 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 8903 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 8904 Diag(Field->getLocation(), diag::note_declared_at); 8905 Diag(CurrentLocation, diag::note_member_synthesized_at) 8906 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 8907 Invalid = true; 8908 continue; 8909 } 8910 8911 // Check for members of const-qualified, non-class type. 8912 QualType BaseType = Context.getBaseElementType(Field->getType()); 8913 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 8914 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 8915 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 8916 Diag(Field->getLocation(), diag::note_declared_at); 8917 Diag(CurrentLocation, diag::note_member_synthesized_at) 8918 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 8919 Invalid = true; 8920 continue; 8921 } 8922 8923 // Suppress assigning zero-width bitfields. 8924 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 8925 continue; 8926 8927 QualType FieldType = Field->getType().getNonReferenceType(); 8928 if (FieldType->isIncompleteArrayType()) { 8929 assert(ClassDecl->hasFlexibleArrayMember() && 8930 "Incomplete array type is not valid"); 8931 continue; 8932 } 8933 8934 // Build references to the field in the object we're copying from and to. 8935 CXXScopeSpec SS; // Intentionally empty 8936 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 8937 LookupMemberName); 8938 MemberLookup.addDecl(*Field); 8939 MemberLookup.resolveKind(); 8940 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType, 8941 Loc, /*IsArrow=*/false, 8942 SS, SourceLocation(), 0, 8943 MemberLookup, 0); 8944 ExprResult To = BuildMemberReferenceExpr(This, This->getType(), 8945 Loc, /*IsArrow=*/true, 8946 SS, SourceLocation(), 0, 8947 MemberLookup, 0); 8948 assert(!From.isInvalid() && "Implicit field reference cannot fail"); 8949 assert(!To.isInvalid() && "Implicit field reference cannot fail"); 8950 8951 assert(!From.get()->isLValue() && // could be xvalue or prvalue 8952 "Member reference with rvalue base must be rvalue except for reference " 8953 "members, which aren't allowed for move assignment."); 8954 8955 // Build the move of this field. 8956 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 8957 To.get(), From.get(), 8958 /*CopyingBaseSubobject=*/false, 8959 /*Copying=*/false); 8960 if (Move.isInvalid()) { 8961 Diag(CurrentLocation, diag::note_member_synthesized_at) 8962 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 8963 MoveAssignOperator->setInvalidDecl(); 8964 return; 8965 } 8966 8967 // Success! Record the copy. 8968 Statements.push_back(Move.takeAs<Stmt>()); 8969 } 8970 8971 if (!Invalid) { 8972 // Add a "return *this;" 8973 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 8974 8975 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get()); 8976 if (Return.isInvalid()) 8977 Invalid = true; 8978 else { 8979 Statements.push_back(Return.takeAs<Stmt>()); 8980 8981 if (Trap.hasErrorOccurred()) { 8982 Diag(CurrentLocation, diag::note_member_synthesized_at) 8983 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 8984 Invalid = true; 8985 } 8986 } 8987 } 8988 8989 if (Invalid) { 8990 MoveAssignOperator->setInvalidDecl(); 8991 return; 8992 } 8993 8994 StmtResult Body; 8995 { 8996 CompoundScopeRAII CompoundScope(*this); 8997 Body = ActOnCompoundStmt(Loc, Loc, Statements, 8998 /*isStmtExpr=*/false); 8999 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 9000 } 9001 MoveAssignOperator->setBody(Body.takeAs<Stmt>()); 9002 9003 if (ASTMutationListener *L = getASTMutationListener()) { 9004 L->CompletedImplicitDefinition(MoveAssignOperator); 9005 } 9006} 9007 9008Sema::ImplicitExceptionSpecification 9009Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) { 9010 CXXRecordDecl *ClassDecl = MD->getParent(); 9011 9012 ImplicitExceptionSpecification ExceptSpec(*this); 9013 if (ClassDecl->isInvalidDecl()) 9014 return ExceptSpec; 9015 9016 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 9017 assert(T->getNumArgs() >= 1 && "not a copy ctor"); 9018 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers(); 9019 9020 // C++ [except.spec]p14: 9021 // An implicitly declared special member function (Clause 12) shall have an 9022 // exception-specification. [...] 9023 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 9024 BaseEnd = ClassDecl->bases_end(); 9025 Base != BaseEnd; 9026 ++Base) { 9027 // Virtual bases are handled below. 9028 if (Base->isVirtual()) 9029 continue; 9030 9031 CXXRecordDecl *BaseClassDecl 9032 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9033 if (CXXConstructorDecl *CopyConstructor = 9034 LookupCopyingConstructor(BaseClassDecl, Quals)) 9035 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor); 9036 } 9037 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 9038 BaseEnd = ClassDecl->vbases_end(); 9039 Base != BaseEnd; 9040 ++Base) { 9041 CXXRecordDecl *BaseClassDecl 9042 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9043 if (CXXConstructorDecl *CopyConstructor = 9044 LookupCopyingConstructor(BaseClassDecl, Quals)) 9045 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor); 9046 } 9047 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 9048 FieldEnd = ClassDecl->field_end(); 9049 Field != FieldEnd; 9050 ++Field) { 9051 QualType FieldType = Context.getBaseElementType(Field->getType()); 9052 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 9053 if (CXXConstructorDecl *CopyConstructor = 9054 LookupCopyingConstructor(FieldClassDecl, 9055 Quals | FieldType.getCVRQualifiers())) 9056 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor); 9057 } 9058 } 9059 9060 return ExceptSpec; 9061} 9062 9063CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 9064 CXXRecordDecl *ClassDecl) { 9065 // C++ [class.copy]p4: 9066 // If the class definition does not explicitly declare a copy 9067 // constructor, one is declared implicitly. 9068 assert(ClassDecl->needsImplicitCopyConstructor()); 9069 9070 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 9071 if (DSM.isAlreadyBeingDeclared()) 9072 return 0; 9073 9074 QualType ClassType = Context.getTypeDeclType(ClassDecl); 9075 QualType ArgType = ClassType; 9076 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 9077 if (Const) 9078 ArgType = ArgType.withConst(); 9079 ArgType = Context.getLValueReferenceType(ArgType); 9080 9081 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9082 CXXCopyConstructor, 9083 Const); 9084 9085 DeclarationName Name 9086 = Context.DeclarationNames.getCXXConstructorName( 9087 Context.getCanonicalType(ClassType)); 9088 SourceLocation ClassLoc = ClassDecl->getLocation(); 9089 DeclarationNameInfo NameInfo(Name, ClassLoc); 9090 9091 // An implicitly-declared copy constructor is an inline public 9092 // member of its class. 9093 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 9094 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0, 9095 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 9096 Constexpr); 9097 CopyConstructor->setAccess(AS_public); 9098 CopyConstructor->setDefaulted(); 9099 9100 // Build an exception specification pointing back at this member. 9101 FunctionProtoType::ExtProtoInfo EPI; 9102 EPI.ExceptionSpecType = EST_Unevaluated; 9103 EPI.ExceptionSpecDecl = CopyConstructor; 9104 CopyConstructor->setType( 9105 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI)); 9106 9107 // Add the parameter to the constructor. 9108 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 9109 ClassLoc, ClassLoc, 9110 /*IdentifierInfo=*/0, 9111 ArgType, /*TInfo=*/0, 9112 SC_None, 9113 SC_None, 0); 9114 CopyConstructor->setParams(FromParam); 9115 9116 CopyConstructor->setTrivial( 9117 ClassDecl->needsOverloadResolutionForCopyConstructor() 9118 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 9119 : ClassDecl->hasTrivialCopyConstructor()); 9120 9121 // C++11 [class.copy]p8: 9122 // ... If the class definition does not explicitly declare a copy 9123 // constructor, there is no user-declared move constructor, and there is no 9124 // user-declared move assignment operator, a copy constructor is implicitly 9125 // declared as defaulted. 9126 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) 9127 CopyConstructor->setDeletedAsWritten(); 9128 9129 // Note that we have declared this constructor. 9130 ++ASTContext::NumImplicitCopyConstructorsDeclared; 9131 9132 if (Scope *S = getScopeForContext(ClassDecl)) 9133 PushOnScopeChains(CopyConstructor, S, false); 9134 ClassDecl->addDecl(CopyConstructor); 9135 9136 return CopyConstructor; 9137} 9138 9139void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 9140 CXXConstructorDecl *CopyConstructor) { 9141 assert((CopyConstructor->isDefaulted() && 9142 CopyConstructor->isCopyConstructor() && 9143 !CopyConstructor->doesThisDeclarationHaveABody() && 9144 !CopyConstructor->isDeleted()) && 9145 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 9146 9147 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 9148 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 9149 9150 SynthesizedFunctionScope Scope(*this, CopyConstructor); 9151 DiagnosticErrorTrap Trap(Diags); 9152 9153 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) || 9154 Trap.hasErrorOccurred()) { 9155 Diag(CurrentLocation, diag::note_member_synthesized_at) 9156 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl); 9157 CopyConstructor->setInvalidDecl(); 9158 } else { 9159 Sema::CompoundScopeRAII CompoundScope(*this); 9160 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(), 9161 CopyConstructor->getLocation(), 9162 MultiStmtArg(), 9163 /*isStmtExpr=*/false) 9164 .takeAs<Stmt>()); 9165 CopyConstructor->setImplicitlyDefined(true); 9166 } 9167 9168 CopyConstructor->setUsed(); 9169 if (ASTMutationListener *L = getASTMutationListener()) { 9170 L->CompletedImplicitDefinition(CopyConstructor); 9171 } 9172} 9173 9174Sema::ImplicitExceptionSpecification 9175Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) { 9176 CXXRecordDecl *ClassDecl = MD->getParent(); 9177 9178 // C++ [except.spec]p14: 9179 // An implicitly declared special member function (Clause 12) shall have an 9180 // exception-specification. [...] 9181 ImplicitExceptionSpecification ExceptSpec(*this); 9182 if (ClassDecl->isInvalidDecl()) 9183 return ExceptSpec; 9184 9185 // Direct base-class constructors. 9186 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 9187 BEnd = ClassDecl->bases_end(); 9188 B != BEnd; ++B) { 9189 if (B->isVirtual()) // Handled below. 9190 continue; 9191 9192 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 9193 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 9194 CXXConstructorDecl *Constructor = 9195 LookupMovingConstructor(BaseClassDecl, 0); 9196 // If this is a deleted function, add it anyway. This might be conformant 9197 // with the standard. This might not. I'm not sure. It might not matter. 9198 if (Constructor) 9199 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 9200 } 9201 } 9202 9203 // Virtual base-class constructors. 9204 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 9205 BEnd = ClassDecl->vbases_end(); 9206 B != BEnd; ++B) { 9207 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 9208 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 9209 CXXConstructorDecl *Constructor = 9210 LookupMovingConstructor(BaseClassDecl, 0); 9211 // If this is a deleted function, add it anyway. This might be conformant 9212 // with the standard. This might not. I'm not sure. It might not matter. 9213 if (Constructor) 9214 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 9215 } 9216 } 9217 9218 // Field constructors. 9219 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 9220 FEnd = ClassDecl->field_end(); 9221 F != FEnd; ++F) { 9222 QualType FieldType = Context.getBaseElementType(F->getType()); 9223 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) { 9224 CXXConstructorDecl *Constructor = 9225 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers()); 9226 // If this is a deleted function, add it anyway. This might be conformant 9227 // with the standard. This might not. I'm not sure. It might not matter. 9228 // In particular, the problem is that this function never gets called. It 9229 // might just be ill-formed because this function attempts to refer to 9230 // a deleted function here. 9231 if (Constructor) 9232 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 9233 } 9234 } 9235 9236 return ExceptSpec; 9237} 9238 9239CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 9240 CXXRecordDecl *ClassDecl) { 9241 // C++11 [class.copy]p9: 9242 // If the definition of a class X does not explicitly declare a move 9243 // constructor, one will be implicitly declared as defaulted if and only if: 9244 // 9245 // - [first 4 bullets] 9246 assert(ClassDecl->needsImplicitMoveConstructor()); 9247 9248 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 9249 if (DSM.isAlreadyBeingDeclared()) 9250 return 0; 9251 9252 // [Checked after we build the declaration] 9253 // - the move assignment operator would not be implicitly defined as 9254 // deleted, 9255 9256 // [DR1402]: 9257 // - each of X's non-static data members and direct or virtual base classes 9258 // has a type that either has a move constructor or is trivially copyable. 9259 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) { 9260 ClassDecl->setFailedImplicitMoveConstructor(); 9261 return 0; 9262 } 9263 9264 QualType ClassType = Context.getTypeDeclType(ClassDecl); 9265 QualType ArgType = Context.getRValueReferenceType(ClassType); 9266 9267 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9268 CXXMoveConstructor, 9269 false); 9270 9271 DeclarationName Name 9272 = Context.DeclarationNames.getCXXConstructorName( 9273 Context.getCanonicalType(ClassType)); 9274 SourceLocation ClassLoc = ClassDecl->getLocation(); 9275 DeclarationNameInfo NameInfo(Name, ClassLoc); 9276 9277 // C++0x [class.copy]p11: 9278 // An implicitly-declared copy/move constructor is an inline public 9279 // member of its class. 9280 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 9281 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0, 9282 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 9283 Constexpr); 9284 MoveConstructor->setAccess(AS_public); 9285 MoveConstructor->setDefaulted(); 9286 9287 // Build an exception specification pointing back at this member. 9288 FunctionProtoType::ExtProtoInfo EPI; 9289 EPI.ExceptionSpecType = EST_Unevaluated; 9290 EPI.ExceptionSpecDecl = MoveConstructor; 9291 MoveConstructor->setType( 9292 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI)); 9293 9294 // Add the parameter to the constructor. 9295 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 9296 ClassLoc, ClassLoc, 9297 /*IdentifierInfo=*/0, 9298 ArgType, /*TInfo=*/0, 9299 SC_None, 9300 SC_None, 0); 9301 MoveConstructor->setParams(FromParam); 9302 9303 MoveConstructor->setTrivial( 9304 ClassDecl->needsOverloadResolutionForMoveConstructor() 9305 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 9306 : ClassDecl->hasTrivialMoveConstructor()); 9307 9308 // C++0x [class.copy]p9: 9309 // If the definition of a class X does not explicitly declare a move 9310 // constructor, one will be implicitly declared as defaulted if and only if: 9311 // [...] 9312 // - the move constructor would not be implicitly defined as deleted. 9313 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 9314 // Cache this result so that we don't try to generate this over and over 9315 // on every lookup, leaking memory and wasting time. 9316 ClassDecl->setFailedImplicitMoveConstructor(); 9317 return 0; 9318 } 9319 9320 // Note that we have declared this constructor. 9321 ++ASTContext::NumImplicitMoveConstructorsDeclared; 9322 9323 if (Scope *S = getScopeForContext(ClassDecl)) 9324 PushOnScopeChains(MoveConstructor, S, false); 9325 ClassDecl->addDecl(MoveConstructor); 9326 9327 return MoveConstructor; 9328} 9329 9330void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 9331 CXXConstructorDecl *MoveConstructor) { 9332 assert((MoveConstructor->isDefaulted() && 9333 MoveConstructor->isMoveConstructor() && 9334 !MoveConstructor->doesThisDeclarationHaveABody() && 9335 !MoveConstructor->isDeleted()) && 9336 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 9337 9338 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 9339 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 9340 9341 SynthesizedFunctionScope Scope(*this, MoveConstructor); 9342 DiagnosticErrorTrap Trap(Diags); 9343 9344 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) || 9345 Trap.hasErrorOccurred()) { 9346 Diag(CurrentLocation, diag::note_member_synthesized_at) 9347 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl); 9348 MoveConstructor->setInvalidDecl(); 9349 } else { 9350 Sema::CompoundScopeRAII CompoundScope(*this); 9351 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(), 9352 MoveConstructor->getLocation(), 9353 MultiStmtArg(), 9354 /*isStmtExpr=*/false) 9355 .takeAs<Stmt>()); 9356 MoveConstructor->setImplicitlyDefined(true); 9357 } 9358 9359 MoveConstructor->setUsed(); 9360 9361 if (ASTMutationListener *L = getASTMutationListener()) { 9362 L->CompletedImplicitDefinition(MoveConstructor); 9363 } 9364} 9365 9366bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 9367 return FD->isDeleted() && 9368 (FD->isDefaulted() || FD->isImplicit()) && 9369 isa<CXXMethodDecl>(FD); 9370} 9371 9372/// \brief Mark the call operator of the given lambda closure type as "used". 9373static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) { 9374 CXXMethodDecl *CallOperator 9375 = cast<CXXMethodDecl>( 9376 *Lambda->lookup( 9377 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).first); 9378 CallOperator->setReferenced(); 9379 CallOperator->setUsed(); 9380} 9381 9382void Sema::DefineImplicitLambdaToFunctionPointerConversion( 9383 SourceLocation CurrentLocation, 9384 CXXConversionDecl *Conv) 9385{ 9386 CXXRecordDecl *Lambda = Conv->getParent(); 9387 9388 // Make sure that the lambda call operator is marked used. 9389 markLambdaCallOperatorUsed(*this, Lambda); 9390 9391 Conv->setUsed(); 9392 9393 SynthesizedFunctionScope Scope(*this, Conv); 9394 DiagnosticErrorTrap Trap(Diags); 9395 9396 // Return the address of the __invoke function. 9397 DeclarationName InvokeName = &Context.Idents.get("__invoke"); 9398 CXXMethodDecl *Invoke 9399 = cast<CXXMethodDecl>(*Lambda->lookup(InvokeName).first); 9400 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(), 9401 VK_LValue, Conv->getLocation()).take(); 9402 assert(FunctionRef && "Can't refer to __invoke function?"); 9403 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take(); 9404 Conv->setBody(new (Context) CompoundStmt(Context, &Return, 1, 9405 Conv->getLocation(), 9406 Conv->getLocation())); 9407 9408 // Fill in the __invoke function with a dummy implementation. IR generation 9409 // will fill in the actual details. 9410 Invoke->setUsed(); 9411 Invoke->setReferenced(); 9412 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation())); 9413 9414 if (ASTMutationListener *L = getASTMutationListener()) { 9415 L->CompletedImplicitDefinition(Conv); 9416 L->CompletedImplicitDefinition(Invoke); 9417 } 9418} 9419 9420void Sema::DefineImplicitLambdaToBlockPointerConversion( 9421 SourceLocation CurrentLocation, 9422 CXXConversionDecl *Conv) 9423{ 9424 Conv->setUsed(); 9425 9426 SynthesizedFunctionScope Scope(*this, Conv); 9427 DiagnosticErrorTrap Trap(Diags); 9428 9429 // Copy-initialize the lambda object as needed to capture it. 9430 Expr *This = ActOnCXXThis(CurrentLocation).take(); 9431 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take(); 9432 9433 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 9434 Conv->getLocation(), 9435 Conv, DerefThis); 9436 9437 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 9438 // behavior. Note that only the general conversion function does this 9439 // (since it's unusable otherwise); in the case where we inline the 9440 // block literal, it has block literal lifetime semantics. 9441 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 9442 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 9443 CK_CopyAndAutoreleaseBlockObject, 9444 BuildBlock.get(), 0, VK_RValue); 9445 9446 if (BuildBlock.isInvalid()) { 9447 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 9448 Conv->setInvalidDecl(); 9449 return; 9450 } 9451 9452 // Create the return statement that returns the block from the conversion 9453 // function. 9454 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get()); 9455 if (Return.isInvalid()) { 9456 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 9457 Conv->setInvalidDecl(); 9458 return; 9459 } 9460 9461 // Set the body of the conversion function. 9462 Stmt *ReturnS = Return.take(); 9463 Conv->setBody(new (Context) CompoundStmt(Context, &ReturnS, 1, 9464 Conv->getLocation(), 9465 Conv->getLocation())); 9466 9467 // We're done; notify the mutation listener, if any. 9468 if (ASTMutationListener *L = getASTMutationListener()) { 9469 L->CompletedImplicitDefinition(Conv); 9470 } 9471} 9472 9473/// \brief Determine whether the given list arguments contains exactly one 9474/// "real" (non-default) argument. 9475static bool hasOneRealArgument(MultiExprArg Args) { 9476 switch (Args.size()) { 9477 case 0: 9478 return false; 9479 9480 default: 9481 if (!Args[1]->isDefaultArgument()) 9482 return false; 9483 9484 // fall through 9485 case 1: 9486 return !Args[0]->isDefaultArgument(); 9487 } 9488 9489 return false; 9490} 9491 9492ExprResult 9493Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 9494 CXXConstructorDecl *Constructor, 9495 MultiExprArg ExprArgs, 9496 bool HadMultipleCandidates, 9497 bool RequiresZeroInit, 9498 unsigned ConstructKind, 9499 SourceRange ParenRange) { 9500 bool Elidable = false; 9501 9502 // C++0x [class.copy]p34: 9503 // When certain criteria are met, an implementation is allowed to 9504 // omit the copy/move construction of a class object, even if the 9505 // copy/move constructor and/or destructor for the object have 9506 // side effects. [...] 9507 // - when a temporary class object that has not been bound to a 9508 // reference (12.2) would be copied/moved to a class object 9509 // with the same cv-unqualified type, the copy/move operation 9510 // can be omitted by constructing the temporary object 9511 // directly into the target of the omitted copy/move 9512 if (ConstructKind == CXXConstructExpr::CK_Complete && 9513 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 9514 Expr *SubExpr = ExprArgs[0]; 9515 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent()); 9516 } 9517 9518 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 9519 Elidable, ExprArgs, HadMultipleCandidates, 9520 RequiresZeroInit, ConstructKind, ParenRange); 9521} 9522 9523/// BuildCXXConstructExpr - Creates a complete call to a constructor, 9524/// including handling of its default argument expressions. 9525ExprResult 9526Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 9527 CXXConstructorDecl *Constructor, bool Elidable, 9528 MultiExprArg ExprArgs, 9529 bool HadMultipleCandidates, 9530 bool RequiresZeroInit, 9531 unsigned ConstructKind, 9532 SourceRange ParenRange) { 9533 MarkFunctionReferenced(ConstructLoc, Constructor); 9534 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc, 9535 Constructor, Elidable, ExprArgs, 9536 HadMultipleCandidates, /*FIXME*/false, 9537 RequiresZeroInit, 9538 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 9539 ParenRange)); 9540} 9541 9542bool Sema::InitializeVarWithConstructor(VarDecl *VD, 9543 CXXConstructorDecl *Constructor, 9544 MultiExprArg Exprs, 9545 bool HadMultipleCandidates) { 9546 // FIXME: Provide the correct paren SourceRange when available. 9547 ExprResult TempResult = 9548 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor, 9549 Exprs, HadMultipleCandidates, false, 9550 CXXConstructExpr::CK_Complete, SourceRange()); 9551 if (TempResult.isInvalid()) 9552 return true; 9553 9554 Expr *Temp = TempResult.takeAs<Expr>(); 9555 CheckImplicitConversions(Temp, VD->getLocation()); 9556 MarkFunctionReferenced(VD->getLocation(), Constructor); 9557 Temp = MaybeCreateExprWithCleanups(Temp); 9558 VD->setInit(Temp); 9559 9560 return false; 9561} 9562 9563void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 9564 if (VD->isInvalidDecl()) return; 9565 9566 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 9567 if (ClassDecl->isInvalidDecl()) return; 9568 if (ClassDecl->hasIrrelevantDestructor()) return; 9569 if (ClassDecl->isDependentContext()) return; 9570 9571 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 9572 MarkFunctionReferenced(VD->getLocation(), Destructor); 9573 CheckDestructorAccess(VD->getLocation(), Destructor, 9574 PDiag(diag::err_access_dtor_var) 9575 << VD->getDeclName() 9576 << VD->getType()); 9577 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 9578 9579 if (!VD->hasGlobalStorage()) return; 9580 9581 // Emit warning for non-trivial dtor in global scope (a real global, 9582 // class-static, function-static). 9583 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 9584 9585 // TODO: this should be re-enabled for static locals by !CXAAtExit 9586 if (!VD->isStaticLocal()) 9587 Diag(VD->getLocation(), diag::warn_global_destructor); 9588} 9589 9590/// \brief Given a constructor and the set of arguments provided for the 9591/// constructor, convert the arguments and add any required default arguments 9592/// to form a proper call to this constructor. 9593/// 9594/// \returns true if an error occurred, false otherwise. 9595bool 9596Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 9597 MultiExprArg ArgsPtr, 9598 SourceLocation Loc, 9599 SmallVectorImpl<Expr*> &ConvertedArgs, 9600 bool AllowExplicit) { 9601 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 9602 unsigned NumArgs = ArgsPtr.size(); 9603 Expr **Args = ArgsPtr.data(); 9604 9605 const FunctionProtoType *Proto 9606 = Constructor->getType()->getAs<FunctionProtoType>(); 9607 assert(Proto && "Constructor without a prototype?"); 9608 unsigned NumArgsInProto = Proto->getNumArgs(); 9609 9610 // If too few arguments are available, we'll fill in the rest with defaults. 9611 if (NumArgs < NumArgsInProto) 9612 ConvertedArgs.reserve(NumArgsInProto); 9613 else 9614 ConvertedArgs.reserve(NumArgs); 9615 9616 VariadicCallType CallType = 9617 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 9618 SmallVector<Expr *, 8> AllArgs; 9619 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 9620 Proto, 0, Args, NumArgs, AllArgs, 9621 CallType, AllowExplicit); 9622 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 9623 9624 DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size()); 9625 9626 CheckConstructorCall(Constructor, AllArgs.data(), AllArgs.size(), 9627 Proto, Loc); 9628 9629 return Invalid; 9630} 9631 9632static inline bool 9633CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 9634 const FunctionDecl *FnDecl) { 9635 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 9636 if (isa<NamespaceDecl>(DC)) { 9637 return SemaRef.Diag(FnDecl->getLocation(), 9638 diag::err_operator_new_delete_declared_in_namespace) 9639 << FnDecl->getDeclName(); 9640 } 9641 9642 if (isa<TranslationUnitDecl>(DC) && 9643 FnDecl->getStorageClass() == SC_Static) { 9644 return SemaRef.Diag(FnDecl->getLocation(), 9645 diag::err_operator_new_delete_declared_static) 9646 << FnDecl->getDeclName(); 9647 } 9648 9649 return false; 9650} 9651 9652static inline bool 9653CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 9654 CanQualType ExpectedResultType, 9655 CanQualType ExpectedFirstParamType, 9656 unsigned DependentParamTypeDiag, 9657 unsigned InvalidParamTypeDiag) { 9658 QualType ResultType = 9659 FnDecl->getType()->getAs<FunctionType>()->getResultType(); 9660 9661 // Check that the result type is not dependent. 9662 if (ResultType->isDependentType()) 9663 return SemaRef.Diag(FnDecl->getLocation(), 9664 diag::err_operator_new_delete_dependent_result_type) 9665 << FnDecl->getDeclName() << ExpectedResultType; 9666 9667 // Check that the result type is what we expect. 9668 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 9669 return SemaRef.Diag(FnDecl->getLocation(), 9670 diag::err_operator_new_delete_invalid_result_type) 9671 << FnDecl->getDeclName() << ExpectedResultType; 9672 9673 // A function template must have at least 2 parameters. 9674 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 9675 return SemaRef.Diag(FnDecl->getLocation(), 9676 diag::err_operator_new_delete_template_too_few_parameters) 9677 << FnDecl->getDeclName(); 9678 9679 // The function decl must have at least 1 parameter. 9680 if (FnDecl->getNumParams() == 0) 9681 return SemaRef.Diag(FnDecl->getLocation(), 9682 diag::err_operator_new_delete_too_few_parameters) 9683 << FnDecl->getDeclName(); 9684 9685 // Check the first parameter type is not dependent. 9686 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 9687 if (FirstParamType->isDependentType()) 9688 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 9689 << FnDecl->getDeclName() << ExpectedFirstParamType; 9690 9691 // Check that the first parameter type is what we expect. 9692 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 9693 ExpectedFirstParamType) 9694 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 9695 << FnDecl->getDeclName() << ExpectedFirstParamType; 9696 9697 return false; 9698} 9699 9700static bool 9701CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 9702 // C++ [basic.stc.dynamic.allocation]p1: 9703 // A program is ill-formed if an allocation function is declared in a 9704 // namespace scope other than global scope or declared static in global 9705 // scope. 9706 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 9707 return true; 9708 9709 CanQualType SizeTy = 9710 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 9711 9712 // C++ [basic.stc.dynamic.allocation]p1: 9713 // The return type shall be void*. The first parameter shall have type 9714 // std::size_t. 9715 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 9716 SizeTy, 9717 diag::err_operator_new_dependent_param_type, 9718 diag::err_operator_new_param_type)) 9719 return true; 9720 9721 // C++ [basic.stc.dynamic.allocation]p1: 9722 // The first parameter shall not have an associated default argument. 9723 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 9724 return SemaRef.Diag(FnDecl->getLocation(), 9725 diag::err_operator_new_default_arg) 9726 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 9727 9728 return false; 9729} 9730 9731static bool 9732CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 9733 // C++ [basic.stc.dynamic.deallocation]p1: 9734 // A program is ill-formed if deallocation functions are declared in a 9735 // namespace scope other than global scope or declared static in global 9736 // scope. 9737 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 9738 return true; 9739 9740 // C++ [basic.stc.dynamic.deallocation]p2: 9741 // Each deallocation function shall return void and its first parameter 9742 // shall be void*. 9743 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 9744 SemaRef.Context.VoidPtrTy, 9745 diag::err_operator_delete_dependent_param_type, 9746 diag::err_operator_delete_param_type)) 9747 return true; 9748 9749 return false; 9750} 9751 9752/// CheckOverloadedOperatorDeclaration - Check whether the declaration 9753/// of this overloaded operator is well-formed. If so, returns false; 9754/// otherwise, emits appropriate diagnostics and returns true. 9755bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 9756 assert(FnDecl && FnDecl->isOverloadedOperator() && 9757 "Expected an overloaded operator declaration"); 9758 9759 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 9760 9761 // C++ [over.oper]p5: 9762 // The allocation and deallocation functions, operator new, 9763 // operator new[], operator delete and operator delete[], are 9764 // described completely in 3.7.3. The attributes and restrictions 9765 // found in the rest of this subclause do not apply to them unless 9766 // explicitly stated in 3.7.3. 9767 if (Op == OO_Delete || Op == OO_Array_Delete) 9768 return CheckOperatorDeleteDeclaration(*this, FnDecl); 9769 9770 if (Op == OO_New || Op == OO_Array_New) 9771 return CheckOperatorNewDeclaration(*this, FnDecl); 9772 9773 // C++ [over.oper]p6: 9774 // An operator function shall either be a non-static member 9775 // function or be a non-member function and have at least one 9776 // parameter whose type is a class, a reference to a class, an 9777 // enumeration, or a reference to an enumeration. 9778 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 9779 if (MethodDecl->isStatic()) 9780 return Diag(FnDecl->getLocation(), 9781 diag::err_operator_overload_static) << FnDecl->getDeclName(); 9782 } else { 9783 bool ClassOrEnumParam = false; 9784 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 9785 ParamEnd = FnDecl->param_end(); 9786 Param != ParamEnd; ++Param) { 9787 QualType ParamType = (*Param)->getType().getNonReferenceType(); 9788 if (ParamType->isDependentType() || ParamType->isRecordType() || 9789 ParamType->isEnumeralType()) { 9790 ClassOrEnumParam = true; 9791 break; 9792 } 9793 } 9794 9795 if (!ClassOrEnumParam) 9796 return Diag(FnDecl->getLocation(), 9797 diag::err_operator_overload_needs_class_or_enum) 9798 << FnDecl->getDeclName(); 9799 } 9800 9801 // C++ [over.oper]p8: 9802 // An operator function cannot have default arguments (8.3.6), 9803 // except where explicitly stated below. 9804 // 9805 // Only the function-call operator allows default arguments 9806 // (C++ [over.call]p1). 9807 if (Op != OO_Call) { 9808 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(); 9809 Param != FnDecl->param_end(); ++Param) { 9810 if ((*Param)->hasDefaultArg()) 9811 return Diag((*Param)->getLocation(), 9812 diag::err_operator_overload_default_arg) 9813 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange(); 9814 } 9815 } 9816 9817 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 9818 { false, false, false } 9819#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 9820 , { Unary, Binary, MemberOnly } 9821#include "clang/Basic/OperatorKinds.def" 9822 }; 9823 9824 bool CanBeUnaryOperator = OperatorUses[Op][0]; 9825 bool CanBeBinaryOperator = OperatorUses[Op][1]; 9826 bool MustBeMemberOperator = OperatorUses[Op][2]; 9827 9828 // C++ [over.oper]p8: 9829 // [...] Operator functions cannot have more or fewer parameters 9830 // than the number required for the corresponding operator, as 9831 // described in the rest of this subclause. 9832 unsigned NumParams = FnDecl->getNumParams() 9833 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 9834 if (Op != OO_Call && 9835 ((NumParams == 1 && !CanBeUnaryOperator) || 9836 (NumParams == 2 && !CanBeBinaryOperator) || 9837 (NumParams < 1) || (NumParams > 2))) { 9838 // We have the wrong number of parameters. 9839 unsigned ErrorKind; 9840 if (CanBeUnaryOperator && CanBeBinaryOperator) { 9841 ErrorKind = 2; // 2 -> unary or binary. 9842 } else if (CanBeUnaryOperator) { 9843 ErrorKind = 0; // 0 -> unary 9844 } else { 9845 assert(CanBeBinaryOperator && 9846 "All non-call overloaded operators are unary or binary!"); 9847 ErrorKind = 1; // 1 -> binary 9848 } 9849 9850 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 9851 << FnDecl->getDeclName() << NumParams << ErrorKind; 9852 } 9853 9854 // Overloaded operators other than operator() cannot be variadic. 9855 if (Op != OO_Call && 9856 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 9857 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 9858 << FnDecl->getDeclName(); 9859 } 9860 9861 // Some operators must be non-static member functions. 9862 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 9863 return Diag(FnDecl->getLocation(), 9864 diag::err_operator_overload_must_be_member) 9865 << FnDecl->getDeclName(); 9866 } 9867 9868 // C++ [over.inc]p1: 9869 // The user-defined function called operator++ implements the 9870 // prefix and postfix ++ operator. If this function is a member 9871 // function with no parameters, or a non-member function with one 9872 // parameter of class or enumeration type, it defines the prefix 9873 // increment operator ++ for objects of that type. If the function 9874 // is a member function with one parameter (which shall be of type 9875 // int) or a non-member function with two parameters (the second 9876 // of which shall be of type int), it defines the postfix 9877 // increment operator ++ for objects of that type. 9878 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 9879 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 9880 bool ParamIsInt = false; 9881 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>()) 9882 ParamIsInt = BT->getKind() == BuiltinType::Int; 9883 9884 if (!ParamIsInt) 9885 return Diag(LastParam->getLocation(), 9886 diag::err_operator_overload_post_incdec_must_be_int) 9887 << LastParam->getType() << (Op == OO_MinusMinus); 9888 } 9889 9890 return false; 9891} 9892 9893/// CheckLiteralOperatorDeclaration - Check whether the declaration 9894/// of this literal operator function is well-formed. If so, returns 9895/// false; otherwise, emits appropriate diagnostics and returns true. 9896bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 9897 if (isa<CXXMethodDecl>(FnDecl)) { 9898 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 9899 << FnDecl->getDeclName(); 9900 return true; 9901 } 9902 9903 if (FnDecl->isExternC()) { 9904 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 9905 return true; 9906 } 9907 9908 bool Valid = false; 9909 9910 // This might be the definition of a literal operator template. 9911 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 9912 // This might be a specialization of a literal operator template. 9913 if (!TpDecl) 9914 TpDecl = FnDecl->getPrimaryTemplate(); 9915 9916 // template <char...> type operator "" name() is the only valid template 9917 // signature, and the only valid signature with no parameters. 9918 if (TpDecl) { 9919 if (FnDecl->param_size() == 0) { 9920 // Must have only one template parameter 9921 TemplateParameterList *Params = TpDecl->getTemplateParameters(); 9922 if (Params->size() == 1) { 9923 NonTypeTemplateParmDecl *PmDecl = 9924 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0)); 9925 9926 // The template parameter must be a char parameter pack. 9927 if (PmDecl && PmDecl->isTemplateParameterPack() && 9928 Context.hasSameType(PmDecl->getType(), Context.CharTy)) 9929 Valid = true; 9930 } 9931 } 9932 } else if (FnDecl->param_size()) { 9933 // Check the first parameter 9934 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 9935 9936 QualType T = (*Param)->getType().getUnqualifiedType(); 9937 9938 // unsigned long long int, long double, and any character type are allowed 9939 // as the only parameters. 9940 if (Context.hasSameType(T, Context.UnsignedLongLongTy) || 9941 Context.hasSameType(T, Context.LongDoubleTy) || 9942 Context.hasSameType(T, Context.CharTy) || 9943 Context.hasSameType(T, Context.WCharTy) || 9944 Context.hasSameType(T, Context.Char16Ty) || 9945 Context.hasSameType(T, Context.Char32Ty)) { 9946 if (++Param == FnDecl->param_end()) 9947 Valid = true; 9948 goto FinishedParams; 9949 } 9950 9951 // Otherwise it must be a pointer to const; let's strip those qualifiers. 9952 const PointerType *PT = T->getAs<PointerType>(); 9953 if (!PT) 9954 goto FinishedParams; 9955 T = PT->getPointeeType(); 9956 if (!T.isConstQualified() || T.isVolatileQualified()) 9957 goto FinishedParams; 9958 T = T.getUnqualifiedType(); 9959 9960 // Move on to the second parameter; 9961 ++Param; 9962 9963 // If there is no second parameter, the first must be a const char * 9964 if (Param == FnDecl->param_end()) { 9965 if (Context.hasSameType(T, Context.CharTy)) 9966 Valid = true; 9967 goto FinishedParams; 9968 } 9969 9970 // const char *, const wchar_t*, const char16_t*, and const char32_t* 9971 // are allowed as the first parameter to a two-parameter function 9972 if (!(Context.hasSameType(T, Context.CharTy) || 9973 Context.hasSameType(T, Context.WCharTy) || 9974 Context.hasSameType(T, Context.Char16Ty) || 9975 Context.hasSameType(T, Context.Char32Ty))) 9976 goto FinishedParams; 9977 9978 // The second and final parameter must be an std::size_t 9979 T = (*Param)->getType().getUnqualifiedType(); 9980 if (Context.hasSameType(T, Context.getSizeType()) && 9981 ++Param == FnDecl->param_end()) 9982 Valid = true; 9983 } 9984 9985 // FIXME: This diagnostic is absolutely terrible. 9986FinishedParams: 9987 if (!Valid) { 9988 Diag(FnDecl->getLocation(), diag::err_literal_operator_params) 9989 << FnDecl->getDeclName(); 9990 return true; 9991 } 9992 9993 // A parameter-declaration-clause containing a default argument is not 9994 // equivalent to any of the permitted forms. 9995 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 9996 ParamEnd = FnDecl->param_end(); 9997 Param != ParamEnd; ++Param) { 9998 if ((*Param)->hasDefaultArg()) { 9999 Diag((*Param)->getDefaultArgRange().getBegin(), 10000 diag::err_literal_operator_default_argument) 10001 << (*Param)->getDefaultArgRange(); 10002 break; 10003 } 10004 } 10005 10006 StringRef LiteralName 10007 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 10008 if (LiteralName[0] != '_') { 10009 // C++11 [usrlit.suffix]p1: 10010 // Literal suffix identifiers that do not start with an underscore 10011 // are reserved for future standardization. 10012 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved); 10013 } 10014 10015 return false; 10016} 10017 10018/// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 10019/// linkage specification, including the language and (if present) 10020/// the '{'. ExternLoc is the location of the 'extern', LangLoc is 10021/// the location of the language string literal, which is provided 10022/// by Lang/StrSize. LBraceLoc, if valid, provides the location of 10023/// the '{' brace. Otherwise, this linkage specification does not 10024/// have any braces. 10025Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 10026 SourceLocation LangLoc, 10027 StringRef Lang, 10028 SourceLocation LBraceLoc) { 10029 LinkageSpecDecl::LanguageIDs Language; 10030 if (Lang == "\"C\"") 10031 Language = LinkageSpecDecl::lang_c; 10032 else if (Lang == "\"C++\"") 10033 Language = LinkageSpecDecl::lang_cxx; 10034 else { 10035 Diag(LangLoc, diag::err_bad_language); 10036 return 0; 10037 } 10038 10039 // FIXME: Add all the various semantics of linkage specifications 10040 10041 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, 10042 ExternLoc, LangLoc, Language); 10043 CurContext->addDecl(D); 10044 PushDeclContext(S, D); 10045 return D; 10046} 10047 10048/// ActOnFinishLinkageSpecification - Complete the definition of 10049/// the C++ linkage specification LinkageSpec. If RBraceLoc is 10050/// valid, it's the position of the closing '}' brace in a linkage 10051/// specification that uses braces. 10052Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 10053 Decl *LinkageSpec, 10054 SourceLocation RBraceLoc) { 10055 if (LinkageSpec) { 10056 if (RBraceLoc.isValid()) { 10057 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 10058 LSDecl->setRBraceLoc(RBraceLoc); 10059 } 10060 PopDeclContext(); 10061 } 10062 return LinkageSpec; 10063} 10064 10065/// \brief Perform semantic analysis for the variable declaration that 10066/// occurs within a C++ catch clause, returning the newly-created 10067/// variable. 10068VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 10069 TypeSourceInfo *TInfo, 10070 SourceLocation StartLoc, 10071 SourceLocation Loc, 10072 IdentifierInfo *Name) { 10073 bool Invalid = false; 10074 QualType ExDeclType = TInfo->getType(); 10075 10076 // Arrays and functions decay. 10077 if (ExDeclType->isArrayType()) 10078 ExDeclType = Context.getArrayDecayedType(ExDeclType); 10079 else if (ExDeclType->isFunctionType()) 10080 ExDeclType = Context.getPointerType(ExDeclType); 10081 10082 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 10083 // The exception-declaration shall not denote a pointer or reference to an 10084 // incomplete type, other than [cv] void*. 10085 // N2844 forbids rvalue references. 10086 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 10087 Diag(Loc, diag::err_catch_rvalue_ref); 10088 Invalid = true; 10089 } 10090 10091 QualType BaseType = ExDeclType; 10092 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 10093 unsigned DK = diag::err_catch_incomplete; 10094 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 10095 BaseType = Ptr->getPointeeType(); 10096 Mode = 1; 10097 DK = diag::err_catch_incomplete_ptr; 10098 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 10099 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 10100 BaseType = Ref->getPointeeType(); 10101 Mode = 2; 10102 DK = diag::err_catch_incomplete_ref; 10103 } 10104 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 10105 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 10106 Invalid = true; 10107 10108 if (!Invalid && !ExDeclType->isDependentType() && 10109 RequireNonAbstractType(Loc, ExDeclType, 10110 diag::err_abstract_type_in_decl, 10111 AbstractVariableType)) 10112 Invalid = true; 10113 10114 // Only the non-fragile NeXT runtime currently supports C++ catches 10115 // of ObjC types, and no runtime supports catching ObjC types by value. 10116 if (!Invalid && getLangOpts().ObjC1) { 10117 QualType T = ExDeclType; 10118 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 10119 T = RT->getPointeeType(); 10120 10121 if (T->isObjCObjectType()) { 10122 Diag(Loc, diag::err_objc_object_catch); 10123 Invalid = true; 10124 } else if (T->isObjCObjectPointerType()) { 10125 // FIXME: should this be a test for macosx-fragile specifically? 10126 if (getLangOpts().ObjCRuntime.isFragile()) 10127 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 10128 } 10129 } 10130 10131 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 10132 ExDeclType, TInfo, SC_None, SC_None); 10133 ExDecl->setExceptionVariable(true); 10134 10135 // In ARC, infer 'retaining' for variables of retainable type. 10136 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 10137 Invalid = true; 10138 10139 if (!Invalid && !ExDeclType->isDependentType()) { 10140 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 10141 // C++ [except.handle]p16: 10142 // The object declared in an exception-declaration or, if the 10143 // exception-declaration does not specify a name, a temporary (12.2) is 10144 // copy-initialized (8.5) from the exception object. [...] 10145 // The object is destroyed when the handler exits, after the destruction 10146 // of any automatic objects initialized within the handler. 10147 // 10148 // We just pretend to initialize the object with itself, then make sure 10149 // it can be destroyed later. 10150 QualType initType = ExDeclType; 10151 10152 InitializedEntity entity = 10153 InitializedEntity::InitializeVariable(ExDecl); 10154 InitializationKind initKind = 10155 InitializationKind::CreateCopy(Loc, SourceLocation()); 10156 10157 Expr *opaqueValue = 10158 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 10159 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1); 10160 ExprResult result = sequence.Perform(*this, entity, initKind, 10161 MultiExprArg(&opaqueValue, 1)); 10162 if (result.isInvalid()) 10163 Invalid = true; 10164 else { 10165 // If the constructor used was non-trivial, set this as the 10166 // "initializer". 10167 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take()); 10168 if (!construct->getConstructor()->isTrivial()) { 10169 Expr *init = MaybeCreateExprWithCleanups(construct); 10170 ExDecl->setInit(init); 10171 } 10172 10173 // And make sure it's destructable. 10174 FinalizeVarWithDestructor(ExDecl, recordType); 10175 } 10176 } 10177 } 10178 10179 if (Invalid) 10180 ExDecl->setInvalidDecl(); 10181 10182 return ExDecl; 10183} 10184 10185/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 10186/// handler. 10187Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 10188 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 10189 bool Invalid = D.isInvalidType(); 10190 10191 // Check for unexpanded parameter packs. 10192 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 10193 UPPC_ExceptionType)) { 10194 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 10195 D.getIdentifierLoc()); 10196 Invalid = true; 10197 } 10198 10199 IdentifierInfo *II = D.getIdentifier(); 10200 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 10201 LookupOrdinaryName, 10202 ForRedeclaration)) { 10203 // The scope should be freshly made just for us. There is just no way 10204 // it contains any previous declaration. 10205 assert(!S->isDeclScope(PrevDecl)); 10206 if (PrevDecl->isTemplateParameter()) { 10207 // Maybe we will complain about the shadowed template parameter. 10208 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 10209 PrevDecl = 0; 10210 } 10211 } 10212 10213 if (D.getCXXScopeSpec().isSet() && !Invalid) { 10214 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 10215 << D.getCXXScopeSpec().getRange(); 10216 Invalid = true; 10217 } 10218 10219 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 10220 D.getLocStart(), 10221 D.getIdentifierLoc(), 10222 D.getIdentifier()); 10223 if (Invalid) 10224 ExDecl->setInvalidDecl(); 10225 10226 // Add the exception declaration into this scope. 10227 if (II) 10228 PushOnScopeChains(ExDecl, S); 10229 else 10230 CurContext->addDecl(ExDecl); 10231 10232 ProcessDeclAttributes(S, ExDecl, D); 10233 return ExDecl; 10234} 10235 10236Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 10237 Expr *AssertExpr, 10238 Expr *AssertMessageExpr, 10239 SourceLocation RParenLoc) { 10240 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr); 10241 10242 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 10243 return 0; 10244 10245 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 10246 AssertMessage, RParenLoc, false); 10247} 10248 10249Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 10250 Expr *AssertExpr, 10251 StringLiteral *AssertMessage, 10252 SourceLocation RParenLoc, 10253 bool Failed) { 10254 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 10255 !Failed) { 10256 // In a static_assert-declaration, the constant-expression shall be a 10257 // constant expression that can be contextually converted to bool. 10258 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 10259 if (Converted.isInvalid()) 10260 Failed = true; 10261 10262 llvm::APSInt Cond; 10263 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 10264 diag::err_static_assert_expression_is_not_constant, 10265 /*AllowFold=*/false).isInvalid()) 10266 Failed = true; 10267 10268 if (!Failed && !Cond) { 10269 llvm::SmallString<256> MsgBuffer; 10270 llvm::raw_svector_ostream Msg(MsgBuffer); 10271 AssertMessage->printPretty(Msg, 0, getPrintingPolicy()); 10272 Diag(StaticAssertLoc, diag::err_static_assert_failed) 10273 << Msg.str() << AssertExpr->getSourceRange(); 10274 Failed = true; 10275 } 10276 } 10277 10278 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 10279 AssertExpr, AssertMessage, RParenLoc, 10280 Failed); 10281 10282 CurContext->addDecl(Decl); 10283 return Decl; 10284} 10285 10286/// \brief Perform semantic analysis of the given friend type declaration. 10287/// 10288/// \returns A friend declaration that. 10289FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 10290 SourceLocation FriendLoc, 10291 TypeSourceInfo *TSInfo) { 10292 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 10293 10294 QualType T = TSInfo->getType(); 10295 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 10296 10297 // C++03 [class.friend]p2: 10298 // An elaborated-type-specifier shall be used in a friend declaration 10299 // for a class.* 10300 // 10301 // * The class-key of the elaborated-type-specifier is required. 10302 if (!ActiveTemplateInstantiations.empty()) { 10303 // Do not complain about the form of friend template types during 10304 // template instantiation; we will already have complained when the 10305 // template was declared. 10306 } else if (!T->isElaboratedTypeSpecifier()) { 10307 // If we evaluated the type to a record type, suggest putting 10308 // a tag in front. 10309 if (const RecordType *RT = T->getAs<RecordType>()) { 10310 RecordDecl *RD = RT->getDecl(); 10311 10312 std::string InsertionText = std::string(" ") + RD->getKindName(); 10313 10314 Diag(TypeRange.getBegin(), 10315 getLangOpts().CPlusPlus0x ? 10316 diag::warn_cxx98_compat_unelaborated_friend_type : 10317 diag::ext_unelaborated_friend_type) 10318 << (unsigned) RD->getTagKind() 10319 << T 10320 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc), 10321 InsertionText); 10322 } else { 10323 Diag(FriendLoc, 10324 getLangOpts().CPlusPlus0x ? 10325 diag::warn_cxx98_compat_nonclass_type_friend : 10326 diag::ext_nonclass_type_friend) 10327 << T 10328 << TypeRange; 10329 } 10330 } else if (T->getAs<EnumType>()) { 10331 Diag(FriendLoc, 10332 getLangOpts().CPlusPlus0x ? 10333 diag::warn_cxx98_compat_enum_friend : 10334 diag::ext_enum_friend) 10335 << T 10336 << TypeRange; 10337 } 10338 10339 // C++11 [class.friend]p3: 10340 // A friend declaration that does not declare a function shall have one 10341 // of the following forms: 10342 // friend elaborated-type-specifier ; 10343 // friend simple-type-specifier ; 10344 // friend typename-specifier ; 10345 if (getLangOpts().CPlusPlus0x && LocStart != FriendLoc) 10346 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 10347 10348 // If the type specifier in a friend declaration designates a (possibly 10349 // cv-qualified) class type, that class is declared as a friend; otherwise, 10350 // the friend declaration is ignored. 10351 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc); 10352} 10353 10354/// Handle a friend tag declaration where the scope specifier was 10355/// templated. 10356Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 10357 unsigned TagSpec, SourceLocation TagLoc, 10358 CXXScopeSpec &SS, 10359 IdentifierInfo *Name, SourceLocation NameLoc, 10360 AttributeList *Attr, 10361 MultiTemplateParamsArg TempParamLists) { 10362 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 10363 10364 bool isExplicitSpecialization = false; 10365 bool Invalid = false; 10366 10367 if (TemplateParameterList *TemplateParams 10368 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS, 10369 TempParamLists.data(), 10370 TempParamLists.size(), 10371 /*friend*/ true, 10372 isExplicitSpecialization, 10373 Invalid)) { 10374 if (TemplateParams->size() > 0) { 10375 // This is a declaration of a class template. 10376 if (Invalid) 10377 return 0; 10378 10379 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, 10380 SS, Name, NameLoc, Attr, 10381 TemplateParams, AS_public, 10382 /*ModulePrivateLoc=*/SourceLocation(), 10383 TempParamLists.size() - 1, 10384 TempParamLists.data()).take(); 10385 } else { 10386 // The "template<>" header is extraneous. 10387 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 10388 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 10389 isExplicitSpecialization = true; 10390 } 10391 } 10392 10393 if (Invalid) return 0; 10394 10395 bool isAllExplicitSpecializations = true; 10396 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 10397 if (TempParamLists[I]->size()) { 10398 isAllExplicitSpecializations = false; 10399 break; 10400 } 10401 } 10402 10403 // FIXME: don't ignore attributes. 10404 10405 // If it's explicit specializations all the way down, just forget 10406 // about the template header and build an appropriate non-templated 10407 // friend. TODO: for source fidelity, remember the headers. 10408 if (isAllExplicitSpecializations) { 10409 if (SS.isEmpty()) { 10410 bool Owned = false; 10411 bool IsDependent = false; 10412 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 10413 Attr, AS_public, 10414 /*ModulePrivateLoc=*/SourceLocation(), 10415 MultiTemplateParamsArg(), Owned, IsDependent, 10416 /*ScopedEnumKWLoc=*/SourceLocation(), 10417 /*ScopedEnumUsesClassTag=*/false, 10418 /*UnderlyingType=*/TypeResult()); 10419 } 10420 10421 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 10422 ElaboratedTypeKeyword Keyword 10423 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 10424 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 10425 *Name, NameLoc); 10426 if (T.isNull()) 10427 return 0; 10428 10429 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 10430 if (isa<DependentNameType>(T)) { 10431 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc()); 10432 TL.setElaboratedKeywordLoc(TagLoc); 10433 TL.setQualifierLoc(QualifierLoc); 10434 TL.setNameLoc(NameLoc); 10435 } else { 10436 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc()); 10437 TL.setElaboratedKeywordLoc(TagLoc); 10438 TL.setQualifierLoc(QualifierLoc); 10439 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc); 10440 } 10441 10442 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 10443 TSI, FriendLoc); 10444 Friend->setAccess(AS_public); 10445 CurContext->addDecl(Friend); 10446 return Friend; 10447 } 10448 10449 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 10450 10451 10452 10453 // Handle the case of a templated-scope friend class. e.g. 10454 // template <class T> class A<T>::B; 10455 // FIXME: we don't support these right now. 10456 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 10457 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 10458 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 10459 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc()); 10460 TL.setElaboratedKeywordLoc(TagLoc); 10461 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 10462 TL.setNameLoc(NameLoc); 10463 10464 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 10465 TSI, FriendLoc); 10466 Friend->setAccess(AS_public); 10467 Friend->setUnsupportedFriend(true); 10468 CurContext->addDecl(Friend); 10469 return Friend; 10470} 10471 10472 10473/// Handle a friend type declaration. This works in tandem with 10474/// ActOnTag. 10475/// 10476/// Notes on friend class templates: 10477/// 10478/// We generally treat friend class declarations as if they were 10479/// declaring a class. So, for example, the elaborated type specifier 10480/// in a friend declaration is required to obey the restrictions of a 10481/// class-head (i.e. no typedefs in the scope chain), template 10482/// parameters are required to match up with simple template-ids, &c. 10483/// However, unlike when declaring a template specialization, it's 10484/// okay to refer to a template specialization without an empty 10485/// template parameter declaration, e.g. 10486/// friend class A<T>::B<unsigned>; 10487/// We permit this as a special case; if there are any template 10488/// parameters present at all, require proper matching, i.e. 10489/// template <> template \<class T> friend class A<int>::B; 10490Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 10491 MultiTemplateParamsArg TempParams) { 10492 SourceLocation Loc = DS.getLocStart(); 10493 10494 assert(DS.isFriendSpecified()); 10495 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 10496 10497 // Try to convert the decl specifier to a type. This works for 10498 // friend templates because ActOnTag never produces a ClassTemplateDecl 10499 // for a TUK_Friend. 10500 Declarator TheDeclarator(DS, Declarator::MemberContext); 10501 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 10502 QualType T = TSI->getType(); 10503 if (TheDeclarator.isInvalidType()) 10504 return 0; 10505 10506 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 10507 return 0; 10508 10509 // This is definitely an error in C++98. It's probably meant to 10510 // be forbidden in C++0x, too, but the specification is just 10511 // poorly written. 10512 // 10513 // The problem is with declarations like the following: 10514 // template <T> friend A<T>::foo; 10515 // where deciding whether a class C is a friend or not now hinges 10516 // on whether there exists an instantiation of A that causes 10517 // 'foo' to equal C. There are restrictions on class-heads 10518 // (which we declare (by fiat) elaborated friend declarations to 10519 // be) that makes this tractable. 10520 // 10521 // FIXME: handle "template <> friend class A<T>;", which 10522 // is possibly well-formed? Who even knows? 10523 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 10524 Diag(Loc, diag::err_tagless_friend_type_template) 10525 << DS.getSourceRange(); 10526 return 0; 10527 } 10528 10529 // C++98 [class.friend]p1: A friend of a class is a function 10530 // or class that is not a member of the class . . . 10531 // This is fixed in DR77, which just barely didn't make the C++03 10532 // deadline. It's also a very silly restriction that seriously 10533 // affects inner classes and which nobody else seems to implement; 10534 // thus we never diagnose it, not even in -pedantic. 10535 // 10536 // But note that we could warn about it: it's always useless to 10537 // friend one of your own members (it's not, however, worthless to 10538 // friend a member of an arbitrary specialization of your template). 10539 10540 Decl *D; 10541 if (unsigned NumTempParamLists = TempParams.size()) 10542 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 10543 NumTempParamLists, 10544 TempParams.data(), 10545 TSI, 10546 DS.getFriendSpecLoc()); 10547 else 10548 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 10549 10550 if (!D) 10551 return 0; 10552 10553 D->setAccess(AS_public); 10554 CurContext->addDecl(D); 10555 10556 return D; 10557} 10558 10559Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 10560 MultiTemplateParamsArg TemplateParams) { 10561 const DeclSpec &DS = D.getDeclSpec(); 10562 10563 assert(DS.isFriendSpecified()); 10564 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 10565 10566 SourceLocation Loc = D.getIdentifierLoc(); 10567 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 10568 10569 // C++ [class.friend]p1 10570 // A friend of a class is a function or class.... 10571 // Note that this sees through typedefs, which is intended. 10572 // It *doesn't* see through dependent types, which is correct 10573 // according to [temp.arg.type]p3: 10574 // If a declaration acquires a function type through a 10575 // type dependent on a template-parameter and this causes 10576 // a declaration that does not use the syntactic form of a 10577 // function declarator to have a function type, the program 10578 // is ill-formed. 10579 if (!TInfo->getType()->isFunctionType()) { 10580 Diag(Loc, diag::err_unexpected_friend); 10581 10582 // It might be worthwhile to try to recover by creating an 10583 // appropriate declaration. 10584 return 0; 10585 } 10586 10587 // C++ [namespace.memdef]p3 10588 // - If a friend declaration in a non-local class first declares a 10589 // class or function, the friend class or function is a member 10590 // of the innermost enclosing namespace. 10591 // - The name of the friend is not found by simple name lookup 10592 // until a matching declaration is provided in that namespace 10593 // scope (either before or after the class declaration granting 10594 // friendship). 10595 // - If a friend function is called, its name may be found by the 10596 // name lookup that considers functions from namespaces and 10597 // classes associated with the types of the function arguments. 10598 // - When looking for a prior declaration of a class or a function 10599 // declared as a friend, scopes outside the innermost enclosing 10600 // namespace scope are not considered. 10601 10602 CXXScopeSpec &SS = D.getCXXScopeSpec(); 10603 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 10604 DeclarationName Name = NameInfo.getName(); 10605 assert(Name); 10606 10607 // Check for unexpanded parameter packs. 10608 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 10609 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 10610 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 10611 return 0; 10612 10613 // The context we found the declaration in, or in which we should 10614 // create the declaration. 10615 DeclContext *DC; 10616 Scope *DCScope = S; 10617 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 10618 ForRedeclaration); 10619 10620 // FIXME: there are different rules in local classes 10621 10622 // There are four cases here. 10623 // - There's no scope specifier, in which case we just go to the 10624 // appropriate scope and look for a function or function template 10625 // there as appropriate. 10626 // Recover from invalid scope qualifiers as if they just weren't there. 10627 if (SS.isInvalid() || !SS.isSet()) { 10628 // C++0x [namespace.memdef]p3: 10629 // If the name in a friend declaration is neither qualified nor 10630 // a template-id and the declaration is a function or an 10631 // elaborated-type-specifier, the lookup to determine whether 10632 // the entity has been previously declared shall not consider 10633 // any scopes outside the innermost enclosing namespace. 10634 // C++0x [class.friend]p11: 10635 // If a friend declaration appears in a local class and the name 10636 // specified is an unqualified name, a prior declaration is 10637 // looked up without considering scopes that are outside the 10638 // innermost enclosing non-class scope. For a friend function 10639 // declaration, if there is no prior declaration, the program is 10640 // ill-formed. 10641 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass(); 10642 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 10643 10644 // Find the appropriate context according to the above. 10645 DC = CurContext; 10646 while (true) { 10647 // Skip class contexts. If someone can cite chapter and verse 10648 // for this behavior, that would be nice --- it's what GCC and 10649 // EDG do, and it seems like a reasonable intent, but the spec 10650 // really only says that checks for unqualified existing 10651 // declarations should stop at the nearest enclosing namespace, 10652 // not that they should only consider the nearest enclosing 10653 // namespace. 10654 while (DC->isRecord() || DC->isTransparentContext()) 10655 DC = DC->getParent(); 10656 10657 LookupQualifiedName(Previous, DC); 10658 10659 // TODO: decide what we think about using declarations. 10660 if (isLocal || !Previous.empty()) 10661 break; 10662 10663 if (isTemplateId) { 10664 if (isa<TranslationUnitDecl>(DC)) break; 10665 } else { 10666 if (DC->isFileContext()) break; 10667 } 10668 DC = DC->getParent(); 10669 } 10670 10671 // C++ [class.friend]p1: A friend of a class is a function or 10672 // class that is not a member of the class . . . 10673 // C++11 changes this for both friend types and functions. 10674 // Most C++ 98 compilers do seem to give an error here, so 10675 // we do, too. 10676 if (!Previous.empty() && DC->Equals(CurContext)) 10677 Diag(DS.getFriendSpecLoc(), 10678 getLangOpts().CPlusPlus0x ? 10679 diag::warn_cxx98_compat_friend_is_member : 10680 diag::err_friend_is_member); 10681 10682 DCScope = getScopeForDeclContext(S, DC); 10683 10684 // C++ [class.friend]p6: 10685 // A function can be defined in a friend declaration of a class if and 10686 // only if the class is a non-local class (9.8), the function name is 10687 // unqualified, and the function has namespace scope. 10688 if (isLocal && D.isFunctionDefinition()) { 10689 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 10690 } 10691 10692 // - There's a non-dependent scope specifier, in which case we 10693 // compute it and do a previous lookup there for a function 10694 // or function template. 10695 } else if (!SS.getScopeRep()->isDependent()) { 10696 DC = computeDeclContext(SS); 10697 if (!DC) return 0; 10698 10699 if (RequireCompleteDeclContext(SS, DC)) return 0; 10700 10701 LookupQualifiedName(Previous, DC); 10702 10703 // Ignore things found implicitly in the wrong scope. 10704 // TODO: better diagnostics for this case. Suggesting the right 10705 // qualified scope would be nice... 10706 LookupResult::Filter F = Previous.makeFilter(); 10707 while (F.hasNext()) { 10708 NamedDecl *D = F.next(); 10709 if (!DC->InEnclosingNamespaceSetOf( 10710 D->getDeclContext()->getRedeclContext())) 10711 F.erase(); 10712 } 10713 F.done(); 10714 10715 if (Previous.empty()) { 10716 D.setInvalidType(); 10717 Diag(Loc, diag::err_qualified_friend_not_found) 10718 << Name << TInfo->getType(); 10719 return 0; 10720 } 10721 10722 // C++ [class.friend]p1: A friend of a class is a function or 10723 // class that is not a member of the class . . . 10724 if (DC->Equals(CurContext)) 10725 Diag(DS.getFriendSpecLoc(), 10726 getLangOpts().CPlusPlus0x ? 10727 diag::warn_cxx98_compat_friend_is_member : 10728 diag::err_friend_is_member); 10729 10730 if (D.isFunctionDefinition()) { 10731 // C++ [class.friend]p6: 10732 // A function can be defined in a friend declaration of a class if and 10733 // only if the class is a non-local class (9.8), the function name is 10734 // unqualified, and the function has namespace scope. 10735 SemaDiagnosticBuilder DB 10736 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 10737 10738 DB << SS.getScopeRep(); 10739 if (DC->isFileContext()) 10740 DB << FixItHint::CreateRemoval(SS.getRange()); 10741 SS.clear(); 10742 } 10743 10744 // - There's a scope specifier that does not match any template 10745 // parameter lists, in which case we use some arbitrary context, 10746 // create a method or method template, and wait for instantiation. 10747 // - There's a scope specifier that does match some template 10748 // parameter lists, which we don't handle right now. 10749 } else { 10750 if (D.isFunctionDefinition()) { 10751 // C++ [class.friend]p6: 10752 // A function can be defined in a friend declaration of a class if and 10753 // only if the class is a non-local class (9.8), the function name is 10754 // unqualified, and the function has namespace scope. 10755 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 10756 << SS.getScopeRep(); 10757 } 10758 10759 DC = CurContext; 10760 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 10761 } 10762 10763 if (!DC->isRecord()) { 10764 // This implies that it has to be an operator or function. 10765 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName || 10766 D.getName().getKind() == UnqualifiedId::IK_DestructorName || 10767 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) { 10768 Diag(Loc, diag::err_introducing_special_friend) << 10769 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 : 10770 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2); 10771 return 0; 10772 } 10773 } 10774 10775 // FIXME: This is an egregious hack to cope with cases where the scope stack 10776 // does not contain the declaration context, i.e., in an out-of-line 10777 // definition of a class. 10778 Scope FakeDCScope(S, Scope::DeclScope, Diags); 10779 if (!DCScope) { 10780 FakeDCScope.setEntity(DC); 10781 DCScope = &FakeDCScope; 10782 } 10783 10784 bool AddToScope = true; 10785 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 10786 TemplateParams, AddToScope); 10787 if (!ND) return 0; 10788 10789 assert(ND->getDeclContext() == DC); 10790 assert(ND->getLexicalDeclContext() == CurContext); 10791 10792 // Add the function declaration to the appropriate lookup tables, 10793 // adjusting the redeclarations list as necessary. We don't 10794 // want to do this yet if the friending class is dependent. 10795 // 10796 // Also update the scope-based lookup if the target context's 10797 // lookup context is in lexical scope. 10798 if (!CurContext->isDependentContext()) { 10799 DC = DC->getRedeclContext(); 10800 DC->makeDeclVisibleInContext(ND); 10801 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 10802 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 10803 } 10804 10805 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 10806 D.getIdentifierLoc(), ND, 10807 DS.getFriendSpecLoc()); 10808 FrD->setAccess(AS_public); 10809 CurContext->addDecl(FrD); 10810 10811 if (ND->isInvalidDecl()) { 10812 FrD->setInvalidDecl(); 10813 } else { 10814 if (DC->isRecord()) CheckFriendAccess(ND); 10815 10816 FunctionDecl *FD; 10817 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 10818 FD = FTD->getTemplatedDecl(); 10819 else 10820 FD = cast<FunctionDecl>(ND); 10821 10822 // Mark templated-scope function declarations as unsupported. 10823 if (FD->getNumTemplateParameterLists()) 10824 FrD->setUnsupportedFriend(true); 10825 } 10826 10827 return ND; 10828} 10829 10830void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 10831 AdjustDeclIfTemplate(Dcl); 10832 10833 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl); 10834 if (!Fn) { 10835 Diag(DelLoc, diag::err_deleted_non_function); 10836 return; 10837 } 10838 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 10839 // Don't consider the implicit declaration we generate for explicit 10840 // specializations. FIXME: Do not generate these implicit declarations. 10841 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization 10842 || Prev->getPreviousDecl()) && !Prev->isDefined()) { 10843 Diag(DelLoc, diag::err_deleted_decl_not_first); 10844 Diag(Prev->getLocation(), diag::note_previous_declaration); 10845 } 10846 // If the declaration wasn't the first, we delete the function anyway for 10847 // recovery. 10848 } 10849 Fn->setDeletedAsWritten(); 10850} 10851 10852void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 10853 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl); 10854 10855 if (MD) { 10856 if (MD->getParent()->isDependentType()) { 10857 MD->setDefaulted(); 10858 MD->setExplicitlyDefaulted(); 10859 return; 10860 } 10861 10862 CXXSpecialMember Member = getSpecialMember(MD); 10863 if (Member == CXXInvalid) { 10864 Diag(DefaultLoc, diag::err_default_special_members); 10865 return; 10866 } 10867 10868 MD->setDefaulted(); 10869 MD->setExplicitlyDefaulted(); 10870 10871 // If this definition appears within the record, do the checking when 10872 // the record is complete. 10873 const FunctionDecl *Primary = MD; 10874 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 10875 // Find the uninstantiated declaration that actually had the '= default' 10876 // on it. 10877 Pattern->isDefined(Primary); 10878 10879 if (Primary == Primary->getCanonicalDecl()) 10880 return; 10881 10882 CheckExplicitlyDefaultedSpecialMember(MD); 10883 10884 switch (Member) { 10885 case CXXDefaultConstructor: { 10886 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD); 10887 if (!CD->isInvalidDecl()) 10888 DefineImplicitDefaultConstructor(DefaultLoc, CD); 10889 break; 10890 } 10891 10892 case CXXCopyConstructor: { 10893 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD); 10894 if (!CD->isInvalidDecl()) 10895 DefineImplicitCopyConstructor(DefaultLoc, CD); 10896 break; 10897 } 10898 10899 case CXXCopyAssignment: { 10900 if (!MD->isInvalidDecl()) 10901 DefineImplicitCopyAssignment(DefaultLoc, MD); 10902 break; 10903 } 10904 10905 case CXXDestructor: { 10906 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD); 10907 if (!DD->isInvalidDecl()) 10908 DefineImplicitDestructor(DefaultLoc, DD); 10909 break; 10910 } 10911 10912 case CXXMoveConstructor: { 10913 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD); 10914 if (!CD->isInvalidDecl()) 10915 DefineImplicitMoveConstructor(DefaultLoc, CD); 10916 break; 10917 } 10918 10919 case CXXMoveAssignment: { 10920 if (!MD->isInvalidDecl()) 10921 DefineImplicitMoveAssignment(DefaultLoc, MD); 10922 break; 10923 } 10924 10925 case CXXInvalid: 10926 llvm_unreachable("Invalid special member."); 10927 } 10928 } else { 10929 Diag(DefaultLoc, diag::err_default_special_members); 10930 } 10931} 10932 10933static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 10934 for (Stmt::child_range CI = S->children(); CI; ++CI) { 10935 Stmt *SubStmt = *CI; 10936 if (!SubStmt) 10937 continue; 10938 if (isa<ReturnStmt>(SubStmt)) 10939 Self.Diag(SubStmt->getLocStart(), 10940 diag::err_return_in_constructor_handler); 10941 if (!isa<Expr>(SubStmt)) 10942 SearchForReturnInStmt(Self, SubStmt); 10943 } 10944} 10945 10946void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 10947 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 10948 CXXCatchStmt *Handler = TryBlock->getHandler(I); 10949 SearchForReturnInStmt(*this, Handler); 10950 } 10951} 10952 10953bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 10954 const CXXMethodDecl *Old) { 10955 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType(); 10956 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType(); 10957 10958 if (Context.hasSameType(NewTy, OldTy) || 10959 NewTy->isDependentType() || OldTy->isDependentType()) 10960 return false; 10961 10962 // Check if the return types are covariant 10963 QualType NewClassTy, OldClassTy; 10964 10965 /// Both types must be pointers or references to classes. 10966 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 10967 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 10968 NewClassTy = NewPT->getPointeeType(); 10969 OldClassTy = OldPT->getPointeeType(); 10970 } 10971 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 10972 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 10973 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 10974 NewClassTy = NewRT->getPointeeType(); 10975 OldClassTy = OldRT->getPointeeType(); 10976 } 10977 } 10978 } 10979 10980 // The return types aren't either both pointers or references to a class type. 10981 if (NewClassTy.isNull()) { 10982 Diag(New->getLocation(), 10983 diag::err_different_return_type_for_overriding_virtual_function) 10984 << New->getDeclName() << NewTy << OldTy; 10985 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 10986 10987 return true; 10988 } 10989 10990 // C++ [class.virtual]p6: 10991 // If the return type of D::f differs from the return type of B::f, the 10992 // class type in the return type of D::f shall be complete at the point of 10993 // declaration of D::f or shall be the class type D. 10994 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 10995 if (!RT->isBeingDefined() && 10996 RequireCompleteType(New->getLocation(), NewClassTy, 10997 diag::err_covariant_return_incomplete, 10998 New->getDeclName())) 10999 return true; 11000 } 11001 11002 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 11003 // Check if the new class derives from the old class. 11004 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 11005 Diag(New->getLocation(), 11006 diag::err_covariant_return_not_derived) 11007 << New->getDeclName() << NewTy << OldTy; 11008 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 11009 return true; 11010 } 11011 11012 // Check if we the conversion from derived to base is valid. 11013 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy, 11014 diag::err_covariant_return_inaccessible_base, 11015 diag::err_covariant_return_ambiguous_derived_to_base_conv, 11016 // FIXME: Should this point to the return type? 11017 New->getLocation(), SourceRange(), New->getDeclName(), 0)) { 11018 // FIXME: this note won't trigger for delayed access control 11019 // diagnostics, and it's impossible to get an undelayed error 11020 // here from access control during the original parse because 11021 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 11022 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 11023 return true; 11024 } 11025 } 11026 11027 // The qualifiers of the return types must be the same. 11028 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 11029 Diag(New->getLocation(), 11030 diag::err_covariant_return_type_different_qualifications) 11031 << New->getDeclName() << NewTy << OldTy; 11032 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 11033 return true; 11034 }; 11035 11036 11037 // The new class type must have the same or less qualifiers as the old type. 11038 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 11039 Diag(New->getLocation(), 11040 diag::err_covariant_return_type_class_type_more_qualified) 11041 << New->getDeclName() << NewTy << OldTy; 11042 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 11043 return true; 11044 }; 11045 11046 return false; 11047} 11048 11049/// \brief Mark the given method pure. 11050/// 11051/// \param Method the method to be marked pure. 11052/// 11053/// \param InitRange the source range that covers the "0" initializer. 11054bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 11055 SourceLocation EndLoc = InitRange.getEnd(); 11056 if (EndLoc.isValid()) 11057 Method->setRangeEnd(EndLoc); 11058 11059 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 11060 Method->setPure(); 11061 return false; 11062 } 11063 11064 if (!Method->isInvalidDecl()) 11065 Diag(Method->getLocation(), diag::err_non_virtual_pure) 11066 << Method->getDeclName() << InitRange; 11067 return true; 11068} 11069 11070/// \brief Determine whether the given declaration is a static data member. 11071static bool isStaticDataMember(Decl *D) { 11072 VarDecl *Var = dyn_cast_or_null<VarDecl>(D); 11073 if (!Var) 11074 return false; 11075 11076 return Var->isStaticDataMember(); 11077} 11078/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 11079/// an initializer for the out-of-line declaration 'Dcl'. The scope 11080/// is a fresh scope pushed for just this purpose. 11081/// 11082/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 11083/// static data member of class X, names should be looked up in the scope of 11084/// class X. 11085void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 11086 // If there is no declaration, there was an error parsing it. 11087 if (D == 0 || D->isInvalidDecl()) return; 11088 11089 // We should only get called for declarations with scope specifiers, like: 11090 // int foo::bar; 11091 assert(D->isOutOfLine()); 11092 EnterDeclaratorContext(S, D->getDeclContext()); 11093 11094 // If we are parsing the initializer for a static data member, push a 11095 // new expression evaluation context that is associated with this static 11096 // data member. 11097 if (isStaticDataMember(D)) 11098 PushExpressionEvaluationContext(PotentiallyEvaluated, D); 11099} 11100 11101/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 11102/// initializer for the out-of-line declaration 'D'. 11103void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 11104 // If there is no declaration, there was an error parsing it. 11105 if (D == 0 || D->isInvalidDecl()) return; 11106 11107 if (isStaticDataMember(D)) 11108 PopExpressionEvaluationContext(); 11109 11110 assert(D->isOutOfLine()); 11111 ExitDeclaratorContext(S); 11112} 11113 11114/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 11115/// C++ if/switch/while/for statement. 11116/// e.g: "if (int x = f()) {...}" 11117DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 11118 // C++ 6.4p2: 11119 // The declarator shall not specify a function or an array. 11120 // The type-specifier-seq shall not contain typedef and shall not declare a 11121 // new class or enumeration. 11122 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 11123 "Parser allowed 'typedef' as storage class of condition decl."); 11124 11125 Decl *Dcl = ActOnDeclarator(S, D); 11126 if (!Dcl) 11127 return true; 11128 11129 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 11130 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 11131 << D.getSourceRange(); 11132 return true; 11133 } 11134 11135 return Dcl; 11136} 11137 11138void Sema::LoadExternalVTableUses() { 11139 if (!ExternalSource) 11140 return; 11141 11142 SmallVector<ExternalVTableUse, 4> VTables; 11143 ExternalSource->ReadUsedVTables(VTables); 11144 SmallVector<VTableUse, 4> NewUses; 11145 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 11146 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 11147 = VTablesUsed.find(VTables[I].Record); 11148 // Even if a definition wasn't required before, it may be required now. 11149 if (Pos != VTablesUsed.end()) { 11150 if (!Pos->second && VTables[I].DefinitionRequired) 11151 Pos->second = true; 11152 continue; 11153 } 11154 11155 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 11156 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 11157 } 11158 11159 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 11160} 11161 11162void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 11163 bool DefinitionRequired) { 11164 // Ignore any vtable uses in unevaluated operands or for classes that do 11165 // not have a vtable. 11166 if (!Class->isDynamicClass() || Class->isDependentContext() || 11167 CurContext->isDependentContext() || 11168 ExprEvalContexts.back().Context == Unevaluated) 11169 return; 11170 11171 // Try to insert this class into the map. 11172 LoadExternalVTableUses(); 11173 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 11174 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 11175 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 11176 if (!Pos.second) { 11177 // If we already had an entry, check to see if we are promoting this vtable 11178 // to required a definition. If so, we need to reappend to the VTableUses 11179 // list, since we may have already processed the first entry. 11180 if (DefinitionRequired && !Pos.first->second) { 11181 Pos.first->second = true; 11182 } else { 11183 // Otherwise, we can early exit. 11184 return; 11185 } 11186 } 11187 11188 // Local classes need to have their virtual members marked 11189 // immediately. For all other classes, we mark their virtual members 11190 // at the end of the translation unit. 11191 if (Class->isLocalClass()) 11192 MarkVirtualMembersReferenced(Loc, Class); 11193 else 11194 VTableUses.push_back(std::make_pair(Class, Loc)); 11195} 11196 11197bool Sema::DefineUsedVTables() { 11198 LoadExternalVTableUses(); 11199 if (VTableUses.empty()) 11200 return false; 11201 11202 // Note: The VTableUses vector could grow as a result of marking 11203 // the members of a class as "used", so we check the size each 11204 // time through the loop and prefer indices (which are stable) to 11205 // iterators (which are not). 11206 bool DefinedAnything = false; 11207 for (unsigned I = 0; I != VTableUses.size(); ++I) { 11208 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 11209 if (!Class) 11210 continue; 11211 11212 SourceLocation Loc = VTableUses[I].second; 11213 11214 bool DefineVTable = true; 11215 11216 // If this class has a key function, but that key function is 11217 // defined in another translation unit, we don't need to emit the 11218 // vtable even though we're using it. 11219 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class); 11220 if (KeyFunction && !KeyFunction->hasBody()) { 11221 switch (KeyFunction->getTemplateSpecializationKind()) { 11222 case TSK_Undeclared: 11223 case TSK_ExplicitSpecialization: 11224 case TSK_ExplicitInstantiationDeclaration: 11225 // The key function is in another translation unit. 11226 DefineVTable = false; 11227 break; 11228 11229 case TSK_ExplicitInstantiationDefinition: 11230 case TSK_ImplicitInstantiation: 11231 // We will be instantiating the key function. 11232 break; 11233 } 11234 } else if (!KeyFunction) { 11235 // If we have a class with no key function that is the subject 11236 // of an explicit instantiation declaration, suppress the 11237 // vtable; it will live with the explicit instantiation 11238 // definition. 11239 bool IsExplicitInstantiationDeclaration 11240 = Class->getTemplateSpecializationKind() 11241 == TSK_ExplicitInstantiationDeclaration; 11242 for (TagDecl::redecl_iterator R = Class->redecls_begin(), 11243 REnd = Class->redecls_end(); 11244 R != REnd; ++R) { 11245 TemplateSpecializationKind TSK 11246 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind(); 11247 if (TSK == TSK_ExplicitInstantiationDeclaration) 11248 IsExplicitInstantiationDeclaration = true; 11249 else if (TSK == TSK_ExplicitInstantiationDefinition) { 11250 IsExplicitInstantiationDeclaration = false; 11251 break; 11252 } 11253 } 11254 11255 if (IsExplicitInstantiationDeclaration) 11256 DefineVTable = false; 11257 } 11258 11259 // The exception specifications for all virtual members may be needed even 11260 // if we are not providing an authoritative form of the vtable in this TU. 11261 // We may choose to emit it available_externally anyway. 11262 if (!DefineVTable) { 11263 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 11264 continue; 11265 } 11266 11267 // Mark all of the virtual members of this class as referenced, so 11268 // that we can build a vtable. Then, tell the AST consumer that a 11269 // vtable for this class is required. 11270 DefinedAnything = true; 11271 MarkVirtualMembersReferenced(Loc, Class); 11272 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 11273 Consumer.HandleVTable(Class, VTablesUsed[Canonical]); 11274 11275 // Optionally warn if we're emitting a weak vtable. 11276 if (Class->getLinkage() == ExternalLinkage && 11277 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) { 11278 const FunctionDecl *KeyFunctionDef = 0; 11279 if (!KeyFunction || 11280 (KeyFunction->hasBody(KeyFunctionDef) && 11281 KeyFunctionDef->isInlined())) 11282 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() == 11283 TSK_ExplicitInstantiationDefinition 11284 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable) 11285 << Class; 11286 } 11287 } 11288 VTableUses.clear(); 11289 11290 return DefinedAnything; 11291} 11292 11293void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 11294 const CXXRecordDecl *RD) { 11295 for (CXXRecordDecl::method_iterator I = RD->method_begin(), 11296 E = RD->method_end(); I != E; ++I) 11297 if ((*I)->isVirtual() && !(*I)->isPure()) 11298 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>()); 11299} 11300 11301void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 11302 const CXXRecordDecl *RD) { 11303 // Mark all functions which will appear in RD's vtable as used. 11304 CXXFinalOverriderMap FinalOverriders; 11305 RD->getFinalOverriders(FinalOverriders); 11306 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 11307 E = FinalOverriders.end(); 11308 I != E; ++I) { 11309 for (OverridingMethods::const_iterator OI = I->second.begin(), 11310 OE = I->second.end(); 11311 OI != OE; ++OI) { 11312 assert(OI->second.size() > 0 && "no final overrider"); 11313 CXXMethodDecl *Overrider = OI->second.front().Method; 11314 11315 // C++ [basic.def.odr]p2: 11316 // [...] A virtual member function is used if it is not pure. [...] 11317 if (!Overrider->isPure()) 11318 MarkFunctionReferenced(Loc, Overrider); 11319 } 11320 } 11321 11322 // Only classes that have virtual bases need a VTT. 11323 if (RD->getNumVBases() == 0) 11324 return; 11325 11326 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(), 11327 e = RD->bases_end(); i != e; ++i) { 11328 const CXXRecordDecl *Base = 11329 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl()); 11330 if (Base->getNumVBases() == 0) 11331 continue; 11332 MarkVirtualMembersReferenced(Loc, Base); 11333 } 11334} 11335 11336/// SetIvarInitializers - This routine builds initialization ASTs for the 11337/// Objective-C implementation whose ivars need be initialized. 11338void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 11339 if (!getLangOpts().CPlusPlus) 11340 return; 11341 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 11342 SmallVector<ObjCIvarDecl*, 8> ivars; 11343 CollectIvarsToConstructOrDestruct(OID, ivars); 11344 if (ivars.empty()) 11345 return; 11346 SmallVector<CXXCtorInitializer*, 32> AllToInit; 11347 for (unsigned i = 0; i < ivars.size(); i++) { 11348 FieldDecl *Field = ivars[i]; 11349 if (Field->isInvalidDecl()) 11350 continue; 11351 11352 CXXCtorInitializer *Member; 11353 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 11354 InitializationKind InitKind = 11355 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 11356 11357 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0); 11358 ExprResult MemberInit = 11359 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg()); 11360 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 11361 // Note, MemberInit could actually come back empty if no initialization 11362 // is required (e.g., because it would call a trivial default constructor) 11363 if (!MemberInit.get() || MemberInit.isInvalid()) 11364 continue; 11365 11366 Member = 11367 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 11368 SourceLocation(), 11369 MemberInit.takeAs<Expr>(), 11370 SourceLocation()); 11371 AllToInit.push_back(Member); 11372 11373 // Be sure that the destructor is accessible and is marked as referenced. 11374 if (const RecordType *RecordTy 11375 = Context.getBaseElementType(Field->getType()) 11376 ->getAs<RecordType>()) { 11377 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 11378 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 11379 MarkFunctionReferenced(Field->getLocation(), Destructor); 11380 CheckDestructorAccess(Field->getLocation(), Destructor, 11381 PDiag(diag::err_access_dtor_ivar) 11382 << Context.getBaseElementType(Field->getType())); 11383 } 11384 } 11385 } 11386 ObjCImplementation->setIvarInitializers(Context, 11387 AllToInit.data(), AllToInit.size()); 11388 } 11389} 11390 11391static 11392void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 11393 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid, 11394 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid, 11395 llvm::SmallSet<CXXConstructorDecl*, 4> &Current, 11396 Sema &S) { 11397 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(), 11398 CE = Current.end(); 11399 if (Ctor->isInvalidDecl()) 11400 return; 11401 11402 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 11403 11404 // Target may not be determinable yet, for instance if this is a dependent 11405 // call in an uninstantiated template. 11406 if (Target) { 11407 const FunctionDecl *FNTarget = 0; 11408 (void)Target->hasBody(FNTarget); 11409 Target = const_cast<CXXConstructorDecl*>( 11410 cast_or_null<CXXConstructorDecl>(FNTarget)); 11411 } 11412 11413 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 11414 // Avoid dereferencing a null pointer here. 11415 *TCanonical = Target ? Target->getCanonicalDecl() : 0; 11416 11417 if (!Current.insert(Canonical)) 11418 return; 11419 11420 // We know that beyond here, we aren't chaining into a cycle. 11421 if (!Target || !Target->isDelegatingConstructor() || 11422 Target->isInvalidDecl() || Valid.count(TCanonical)) { 11423 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI) 11424 Valid.insert(*CI); 11425 Current.clear(); 11426 // We've hit a cycle. 11427 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 11428 Current.count(TCanonical)) { 11429 // If we haven't diagnosed this cycle yet, do so now. 11430 if (!Invalid.count(TCanonical)) { 11431 S.Diag((*Ctor->init_begin())->getSourceLocation(), 11432 diag::warn_delegating_ctor_cycle) 11433 << Ctor; 11434 11435 // Don't add a note for a function delegating directly to itself. 11436 if (TCanonical != Canonical) 11437 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 11438 11439 CXXConstructorDecl *C = Target; 11440 while (C->getCanonicalDecl() != Canonical) { 11441 const FunctionDecl *FNTarget = 0; 11442 (void)C->getTargetConstructor()->hasBody(FNTarget); 11443 assert(FNTarget && "Ctor cycle through bodiless function"); 11444 11445 C = const_cast<CXXConstructorDecl*>( 11446 cast<CXXConstructorDecl>(FNTarget)); 11447 S.Diag(C->getLocation(), diag::note_which_delegates_to); 11448 } 11449 } 11450 11451 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI) 11452 Invalid.insert(*CI); 11453 Current.clear(); 11454 } else { 11455 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 11456 } 11457} 11458 11459 11460void Sema::CheckDelegatingCtorCycles() { 11461 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 11462 11463 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(), 11464 CE = Current.end(); 11465 11466 for (DelegatingCtorDeclsType::iterator 11467 I = DelegatingCtorDecls.begin(ExternalSource), 11468 E = DelegatingCtorDecls.end(); 11469 I != E; ++I) 11470 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 11471 11472 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI) 11473 (*CI)->setInvalidDecl(); 11474} 11475 11476namespace { 11477 /// \brief AST visitor that finds references to the 'this' expression. 11478 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 11479 Sema &S; 11480 11481 public: 11482 explicit FindCXXThisExpr(Sema &S) : S(S) { } 11483 11484 bool VisitCXXThisExpr(CXXThisExpr *E) { 11485 S.Diag(E->getLocation(), diag::err_this_static_member_func) 11486 << E->isImplicit(); 11487 return false; 11488 } 11489 }; 11490} 11491 11492bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 11493 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 11494 if (!TSInfo) 11495 return false; 11496 11497 TypeLoc TL = TSInfo->getTypeLoc(); 11498 FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL); 11499 if (!ProtoTL) 11500 return false; 11501 11502 // C++11 [expr.prim.general]p3: 11503 // [The expression this] shall not appear before the optional 11504 // cv-qualifier-seq and it shall not appear within the declaration of a 11505 // static member function (although its type and value category are defined 11506 // within a static member function as they are within a non-static member 11507 // function). [ Note: this is because declaration matching does not occur 11508 // until the complete declarator is known. - end note ] 11509 const FunctionProtoType *Proto = ProtoTL->getTypePtr(); 11510 FindCXXThisExpr Finder(*this); 11511 11512 // If the return type came after the cv-qualifier-seq, check it now. 11513 if (Proto->hasTrailingReturn() && 11514 !Finder.TraverseTypeLoc(ProtoTL->getResultLoc())) 11515 return true; 11516 11517 // Check the exception specification. 11518 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 11519 return true; 11520 11521 return checkThisInStaticMemberFunctionAttributes(Method); 11522} 11523 11524bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 11525 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 11526 if (!TSInfo) 11527 return false; 11528 11529 TypeLoc TL = TSInfo->getTypeLoc(); 11530 FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL); 11531 if (!ProtoTL) 11532 return false; 11533 11534 const FunctionProtoType *Proto = ProtoTL->getTypePtr(); 11535 FindCXXThisExpr Finder(*this); 11536 11537 switch (Proto->getExceptionSpecType()) { 11538 case EST_Uninstantiated: 11539 case EST_Unevaluated: 11540 case EST_BasicNoexcept: 11541 case EST_DynamicNone: 11542 case EST_MSAny: 11543 case EST_None: 11544 break; 11545 11546 case EST_ComputedNoexcept: 11547 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 11548 return true; 11549 11550 case EST_Dynamic: 11551 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(), 11552 EEnd = Proto->exception_end(); 11553 E != EEnd; ++E) { 11554 if (!Finder.TraverseType(*E)) 11555 return true; 11556 } 11557 break; 11558 } 11559 11560 return false; 11561} 11562 11563bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 11564 FindCXXThisExpr Finder(*this); 11565 11566 // Check attributes. 11567 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end(); 11568 A != AEnd; ++A) { 11569 // FIXME: This should be emitted by tblgen. 11570 Expr *Arg = 0; 11571 ArrayRef<Expr *> Args; 11572 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A)) 11573 Arg = G->getArg(); 11574 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A)) 11575 Arg = G->getArg(); 11576 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A)) 11577 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size()); 11578 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A)) 11579 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size()); 11580 else if (ExclusiveLockFunctionAttr *ELF 11581 = dyn_cast<ExclusiveLockFunctionAttr>(*A)) 11582 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size()); 11583 else if (SharedLockFunctionAttr *SLF 11584 = dyn_cast<SharedLockFunctionAttr>(*A)) 11585 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size()); 11586 else if (ExclusiveTrylockFunctionAttr *ETLF 11587 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) { 11588 Arg = ETLF->getSuccessValue(); 11589 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size()); 11590 } else if (SharedTrylockFunctionAttr *STLF 11591 = dyn_cast<SharedTrylockFunctionAttr>(*A)) { 11592 Arg = STLF->getSuccessValue(); 11593 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size()); 11594 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A)) 11595 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size()); 11596 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A)) 11597 Arg = LR->getArg(); 11598 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A)) 11599 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size()); 11600 else if (ExclusiveLocksRequiredAttr *ELR 11601 = dyn_cast<ExclusiveLocksRequiredAttr>(*A)) 11602 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size()); 11603 else if (SharedLocksRequiredAttr *SLR 11604 = dyn_cast<SharedLocksRequiredAttr>(*A)) 11605 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size()); 11606 11607 if (Arg && !Finder.TraverseStmt(Arg)) 11608 return true; 11609 11610 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 11611 if (!Finder.TraverseStmt(Args[I])) 11612 return true; 11613 } 11614 } 11615 11616 return false; 11617} 11618 11619void 11620Sema::checkExceptionSpecification(ExceptionSpecificationType EST, 11621 ArrayRef<ParsedType> DynamicExceptions, 11622 ArrayRef<SourceRange> DynamicExceptionRanges, 11623 Expr *NoexceptExpr, 11624 llvm::SmallVectorImpl<QualType> &Exceptions, 11625 FunctionProtoType::ExtProtoInfo &EPI) { 11626 Exceptions.clear(); 11627 EPI.ExceptionSpecType = EST; 11628 if (EST == EST_Dynamic) { 11629 Exceptions.reserve(DynamicExceptions.size()); 11630 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 11631 // FIXME: Preserve type source info. 11632 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 11633 11634 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 11635 collectUnexpandedParameterPacks(ET, Unexpanded); 11636 if (!Unexpanded.empty()) { 11637 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(), 11638 UPPC_ExceptionType, 11639 Unexpanded); 11640 continue; 11641 } 11642 11643 // Check that the type is valid for an exception spec, and 11644 // drop it if not. 11645 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 11646 Exceptions.push_back(ET); 11647 } 11648 EPI.NumExceptions = Exceptions.size(); 11649 EPI.Exceptions = Exceptions.data(); 11650 return; 11651 } 11652 11653 if (EST == EST_ComputedNoexcept) { 11654 // If an error occurred, there's no expression here. 11655 if (NoexceptExpr) { 11656 assert((NoexceptExpr->isTypeDependent() || 11657 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 11658 Context.BoolTy) && 11659 "Parser should have made sure that the expression is boolean"); 11660 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 11661 EPI.ExceptionSpecType = EST_BasicNoexcept; 11662 return; 11663 } 11664 11665 if (!NoexceptExpr->isValueDependent()) 11666 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0, 11667 diag::err_noexcept_needs_constant_expression, 11668 /*AllowFold*/ false).take(); 11669 EPI.NoexceptExpr = NoexceptExpr; 11670 } 11671 return; 11672 } 11673} 11674 11675/// IdentifyCUDATarget - Determine the CUDA compilation target for this function 11676Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) { 11677 // Implicitly declared functions (e.g. copy constructors) are 11678 // __host__ __device__ 11679 if (D->isImplicit()) 11680 return CFT_HostDevice; 11681 11682 if (D->hasAttr<CUDAGlobalAttr>()) 11683 return CFT_Global; 11684 11685 if (D->hasAttr<CUDADeviceAttr>()) { 11686 if (D->hasAttr<CUDAHostAttr>()) 11687 return CFT_HostDevice; 11688 else 11689 return CFT_Device; 11690 } 11691 11692 return CFT_Host; 11693} 11694 11695bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget, 11696 CUDAFunctionTarget CalleeTarget) { 11697 // CUDA B.1.1 "The __device__ qualifier declares a function that is... 11698 // Callable from the device only." 11699 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device) 11700 return true; 11701 11702 // CUDA B.1.2 "The __global__ qualifier declares a function that is... 11703 // Callable from the host only." 11704 // CUDA B.1.3 "The __host__ qualifier declares a function that is... 11705 // Callable from the host only." 11706 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) && 11707 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global)) 11708 return true; 11709 11710 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice) 11711 return true; 11712 11713 return false; 11714} 11715