SemaDeclCXX.cpp revision 239462
1//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements semantic analysis for C++ declarations. 11// 12//===----------------------------------------------------------------------===// 13 14#include "clang/Sema/SemaInternal.h" 15#include "clang/Sema/CXXFieldCollector.h" 16#include "clang/Sema/Scope.h" 17#include "clang/Sema/Initialization.h" 18#include "clang/Sema/Lookup.h" 19#include "clang/Sema/ScopeInfo.h" 20#include "clang/AST/ASTConsumer.h" 21#include "clang/AST/ASTContext.h" 22#include "clang/AST/ASTMutationListener.h" 23#include "clang/AST/CharUnits.h" 24#include "clang/AST/CXXInheritance.h" 25#include "clang/AST/DeclVisitor.h" 26#include "clang/AST/EvaluatedExprVisitor.h" 27#include "clang/AST/ExprCXX.h" 28#include "clang/AST/RecordLayout.h" 29#include "clang/AST/RecursiveASTVisitor.h" 30#include "clang/AST/StmtVisitor.h" 31#include "clang/AST/TypeLoc.h" 32#include "clang/AST/TypeOrdering.h" 33#include "clang/Sema/DeclSpec.h" 34#include "clang/Sema/ParsedTemplate.h" 35#include "clang/Basic/PartialDiagnostic.h" 36#include "clang/Lex/Preprocessor.h" 37#include "llvm/ADT/SmallString.h" 38#include "llvm/ADT/STLExtras.h" 39#include <map> 40#include <set> 41 42using namespace clang; 43 44//===----------------------------------------------------------------------===// 45// CheckDefaultArgumentVisitor 46//===----------------------------------------------------------------------===// 47 48namespace { 49 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 50 /// the default argument of a parameter to determine whether it 51 /// contains any ill-formed subexpressions. For example, this will 52 /// diagnose the use of local variables or parameters within the 53 /// default argument expression. 54 class CheckDefaultArgumentVisitor 55 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 56 Expr *DefaultArg; 57 Sema *S; 58 59 public: 60 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 61 : DefaultArg(defarg), S(s) {} 62 63 bool VisitExpr(Expr *Node); 64 bool VisitDeclRefExpr(DeclRefExpr *DRE); 65 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 66 bool VisitLambdaExpr(LambdaExpr *Lambda); 67 }; 68 69 /// VisitExpr - Visit all of the children of this expression. 70 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 71 bool IsInvalid = false; 72 for (Stmt::child_range I = Node->children(); I; ++I) 73 IsInvalid |= Visit(*I); 74 return IsInvalid; 75 } 76 77 /// VisitDeclRefExpr - Visit a reference to a declaration, to 78 /// determine whether this declaration can be used in the default 79 /// argument expression. 80 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 81 NamedDecl *Decl = DRE->getDecl(); 82 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 83 // C++ [dcl.fct.default]p9 84 // Default arguments are evaluated each time the function is 85 // called. The order of evaluation of function arguments is 86 // unspecified. Consequently, parameters of a function shall not 87 // be used in default argument expressions, even if they are not 88 // evaluated. Parameters of a function declared before a default 89 // argument expression are in scope and can hide namespace and 90 // class member names. 91 return S->Diag(DRE->getLocStart(), 92 diag::err_param_default_argument_references_param) 93 << Param->getDeclName() << DefaultArg->getSourceRange(); 94 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 95 // C++ [dcl.fct.default]p7 96 // Local variables shall not be used in default argument 97 // expressions. 98 if (VDecl->isLocalVarDecl()) 99 return S->Diag(DRE->getLocStart(), 100 diag::err_param_default_argument_references_local) 101 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 102 } 103 104 return false; 105 } 106 107 /// VisitCXXThisExpr - Visit a C++ "this" expression. 108 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 109 // C++ [dcl.fct.default]p8: 110 // The keyword this shall not be used in a default argument of a 111 // member function. 112 return S->Diag(ThisE->getLocStart(), 113 diag::err_param_default_argument_references_this) 114 << ThisE->getSourceRange(); 115 } 116 117 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) { 118 // C++11 [expr.lambda.prim]p13: 119 // A lambda-expression appearing in a default argument shall not 120 // implicitly or explicitly capture any entity. 121 if (Lambda->capture_begin() == Lambda->capture_end()) 122 return false; 123 124 return S->Diag(Lambda->getLocStart(), 125 diag::err_lambda_capture_default_arg); 126 } 127} 128 129void Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc, 130 CXXMethodDecl *Method) { 131 // If we have an MSAny spec already, don't bother. 132 if (!Method || ComputedEST == EST_MSAny) 133 return; 134 135 const FunctionProtoType *Proto 136 = Method->getType()->getAs<FunctionProtoType>(); 137 Proto = Self->ResolveExceptionSpec(CallLoc, Proto); 138 if (!Proto) 139 return; 140 141 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 142 143 // If this function can throw any exceptions, make a note of that. 144 if (EST == EST_MSAny || EST == EST_None) { 145 ClearExceptions(); 146 ComputedEST = EST; 147 return; 148 } 149 150 // FIXME: If the call to this decl is using any of its default arguments, we 151 // need to search them for potentially-throwing calls. 152 153 // If this function has a basic noexcept, it doesn't affect the outcome. 154 if (EST == EST_BasicNoexcept) 155 return; 156 157 // If we have a throw-all spec at this point, ignore the function. 158 if (ComputedEST == EST_None) 159 return; 160 161 // If we're still at noexcept(true) and there's a nothrow() callee, 162 // change to that specification. 163 if (EST == EST_DynamicNone) { 164 if (ComputedEST == EST_BasicNoexcept) 165 ComputedEST = EST_DynamicNone; 166 return; 167 } 168 169 // Check out noexcept specs. 170 if (EST == EST_ComputedNoexcept) { 171 FunctionProtoType::NoexceptResult NR = 172 Proto->getNoexceptSpec(Self->Context); 173 assert(NR != FunctionProtoType::NR_NoNoexcept && 174 "Must have noexcept result for EST_ComputedNoexcept."); 175 assert(NR != FunctionProtoType::NR_Dependent && 176 "Should not generate implicit declarations for dependent cases, " 177 "and don't know how to handle them anyway."); 178 179 // noexcept(false) -> no spec on the new function 180 if (NR == FunctionProtoType::NR_Throw) { 181 ClearExceptions(); 182 ComputedEST = EST_None; 183 } 184 // noexcept(true) won't change anything either. 185 return; 186 } 187 188 assert(EST == EST_Dynamic && "EST case not considered earlier."); 189 assert(ComputedEST != EST_None && 190 "Shouldn't collect exceptions when throw-all is guaranteed."); 191 ComputedEST = EST_Dynamic; 192 // Record the exceptions in this function's exception specification. 193 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(), 194 EEnd = Proto->exception_end(); 195 E != EEnd; ++E) 196 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E))) 197 Exceptions.push_back(*E); 198} 199 200void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) { 201 if (!E || ComputedEST == EST_MSAny) 202 return; 203 204 // FIXME: 205 // 206 // C++0x [except.spec]p14: 207 // [An] implicit exception-specification specifies the type-id T if and 208 // only if T is allowed by the exception-specification of a function directly 209 // invoked by f's implicit definition; f shall allow all exceptions if any 210 // function it directly invokes allows all exceptions, and f shall allow no 211 // exceptions if every function it directly invokes allows no exceptions. 212 // 213 // Note in particular that if an implicit exception-specification is generated 214 // for a function containing a throw-expression, that specification can still 215 // be noexcept(true). 216 // 217 // Note also that 'directly invoked' is not defined in the standard, and there 218 // is no indication that we should only consider potentially-evaluated calls. 219 // 220 // Ultimately we should implement the intent of the standard: the exception 221 // specification should be the set of exceptions which can be thrown by the 222 // implicit definition. For now, we assume that any non-nothrow expression can 223 // throw any exception. 224 225 if (Self->canThrow(E)) 226 ComputedEST = EST_None; 227} 228 229bool 230Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 231 SourceLocation EqualLoc) { 232 if (RequireCompleteType(Param->getLocation(), Param->getType(), 233 diag::err_typecheck_decl_incomplete_type)) { 234 Param->setInvalidDecl(); 235 return true; 236 } 237 238 // C++ [dcl.fct.default]p5 239 // A default argument expression is implicitly converted (clause 240 // 4) to the parameter type. The default argument expression has 241 // the same semantic constraints as the initializer expression in 242 // a declaration of a variable of the parameter type, using the 243 // copy-initialization semantics (8.5). 244 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 245 Param); 246 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 247 EqualLoc); 248 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1); 249 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, 250 MultiExprArg(*this, &Arg, 1)); 251 if (Result.isInvalid()) 252 return true; 253 Arg = Result.takeAs<Expr>(); 254 255 CheckImplicitConversions(Arg, EqualLoc); 256 Arg = MaybeCreateExprWithCleanups(Arg); 257 258 // Okay: add the default argument to the parameter 259 Param->setDefaultArg(Arg); 260 261 // We have already instantiated this parameter; provide each of the 262 // instantiations with the uninstantiated default argument. 263 UnparsedDefaultArgInstantiationsMap::iterator InstPos 264 = UnparsedDefaultArgInstantiations.find(Param); 265 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 266 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 267 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 268 269 // We're done tracking this parameter's instantiations. 270 UnparsedDefaultArgInstantiations.erase(InstPos); 271 } 272 273 return false; 274} 275 276/// ActOnParamDefaultArgument - Check whether the default argument 277/// provided for a function parameter is well-formed. If so, attach it 278/// to the parameter declaration. 279void 280Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 281 Expr *DefaultArg) { 282 if (!param || !DefaultArg) 283 return; 284 285 ParmVarDecl *Param = cast<ParmVarDecl>(param); 286 UnparsedDefaultArgLocs.erase(Param); 287 288 // Default arguments are only permitted in C++ 289 if (!getLangOpts().CPlusPlus) { 290 Diag(EqualLoc, diag::err_param_default_argument) 291 << DefaultArg->getSourceRange(); 292 Param->setInvalidDecl(); 293 return; 294 } 295 296 // Check for unexpanded parameter packs. 297 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 298 Param->setInvalidDecl(); 299 return; 300 } 301 302 // Check that the default argument is well-formed 303 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this); 304 if (DefaultArgChecker.Visit(DefaultArg)) { 305 Param->setInvalidDecl(); 306 return; 307 } 308 309 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 310} 311 312/// ActOnParamUnparsedDefaultArgument - We've seen a default 313/// argument for a function parameter, but we can't parse it yet 314/// because we're inside a class definition. Note that this default 315/// argument will be parsed later. 316void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 317 SourceLocation EqualLoc, 318 SourceLocation ArgLoc) { 319 if (!param) 320 return; 321 322 ParmVarDecl *Param = cast<ParmVarDecl>(param); 323 if (Param) 324 Param->setUnparsedDefaultArg(); 325 326 UnparsedDefaultArgLocs[Param] = ArgLoc; 327} 328 329/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 330/// the default argument for the parameter param failed. 331void Sema::ActOnParamDefaultArgumentError(Decl *param) { 332 if (!param) 333 return; 334 335 ParmVarDecl *Param = cast<ParmVarDecl>(param); 336 337 Param->setInvalidDecl(); 338 339 UnparsedDefaultArgLocs.erase(Param); 340} 341 342/// CheckExtraCXXDefaultArguments - Check for any extra default 343/// arguments in the declarator, which is not a function declaration 344/// or definition and therefore is not permitted to have default 345/// arguments. This routine should be invoked for every declarator 346/// that is not a function declaration or definition. 347void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 348 // C++ [dcl.fct.default]p3 349 // A default argument expression shall be specified only in the 350 // parameter-declaration-clause of a function declaration or in a 351 // template-parameter (14.1). It shall not be specified for a 352 // parameter pack. If it is specified in a 353 // parameter-declaration-clause, it shall not occur within a 354 // declarator or abstract-declarator of a parameter-declaration. 355 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 356 DeclaratorChunk &chunk = D.getTypeObject(i); 357 if (chunk.Kind == DeclaratorChunk::Function) { 358 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) { 359 ParmVarDecl *Param = 360 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param); 361 if (Param->hasUnparsedDefaultArg()) { 362 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens; 363 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 364 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation()); 365 delete Toks; 366 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0; 367 } else if (Param->getDefaultArg()) { 368 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 369 << Param->getDefaultArg()->getSourceRange(); 370 Param->setDefaultArg(0); 371 } 372 } 373 } 374 } 375} 376 377// MergeCXXFunctionDecl - Merge two declarations of the same C++ 378// function, once we already know that they have the same 379// type. Subroutine of MergeFunctionDecl. Returns true if there was an 380// error, false otherwise. 381bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 382 Scope *S) { 383 bool Invalid = false; 384 385 // C++ [dcl.fct.default]p4: 386 // For non-template functions, default arguments can be added in 387 // later declarations of a function in the same 388 // scope. Declarations in different scopes have completely 389 // distinct sets of default arguments. That is, declarations in 390 // inner scopes do not acquire default arguments from 391 // declarations in outer scopes, and vice versa. In a given 392 // function declaration, all parameters subsequent to a 393 // parameter with a default argument shall have default 394 // arguments supplied in this or previous declarations. A 395 // default argument shall not be redefined by a later 396 // declaration (not even to the same value). 397 // 398 // C++ [dcl.fct.default]p6: 399 // Except for member functions of class templates, the default arguments 400 // in a member function definition that appears outside of the class 401 // definition are added to the set of default arguments provided by the 402 // member function declaration in the class definition. 403 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 404 ParmVarDecl *OldParam = Old->getParamDecl(p); 405 ParmVarDecl *NewParam = New->getParamDecl(p); 406 407 bool OldParamHasDfl = OldParam->hasDefaultArg(); 408 bool NewParamHasDfl = NewParam->hasDefaultArg(); 409 410 NamedDecl *ND = Old; 411 if (S && !isDeclInScope(ND, New->getDeclContext(), S)) 412 // Ignore default parameters of old decl if they are not in 413 // the same scope. 414 OldParamHasDfl = false; 415 416 if (OldParamHasDfl && NewParamHasDfl) { 417 418 unsigned DiagDefaultParamID = 419 diag::err_param_default_argument_redefinition; 420 421 // MSVC accepts that default parameters be redefined for member functions 422 // of template class. The new default parameter's value is ignored. 423 Invalid = true; 424 if (getLangOpts().MicrosoftExt) { 425 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New); 426 if (MD && MD->getParent()->getDescribedClassTemplate()) { 427 // Merge the old default argument into the new parameter. 428 NewParam->setHasInheritedDefaultArg(); 429 if (OldParam->hasUninstantiatedDefaultArg()) 430 NewParam->setUninstantiatedDefaultArg( 431 OldParam->getUninstantiatedDefaultArg()); 432 else 433 NewParam->setDefaultArg(OldParam->getInit()); 434 DiagDefaultParamID = diag::warn_param_default_argument_redefinition; 435 Invalid = false; 436 } 437 } 438 439 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 440 // hint here. Alternatively, we could walk the type-source information 441 // for NewParam to find the last source location in the type... but it 442 // isn't worth the effort right now. This is the kind of test case that 443 // is hard to get right: 444 // int f(int); 445 // void g(int (*fp)(int) = f); 446 // void g(int (*fp)(int) = &f); 447 Diag(NewParam->getLocation(), DiagDefaultParamID) 448 << NewParam->getDefaultArgRange(); 449 450 // Look for the function declaration where the default argument was 451 // actually written, which may be a declaration prior to Old. 452 for (FunctionDecl *Older = Old->getPreviousDecl(); 453 Older; Older = Older->getPreviousDecl()) { 454 if (!Older->getParamDecl(p)->hasDefaultArg()) 455 break; 456 457 OldParam = Older->getParamDecl(p); 458 } 459 460 Diag(OldParam->getLocation(), diag::note_previous_definition) 461 << OldParam->getDefaultArgRange(); 462 } else if (OldParamHasDfl) { 463 // Merge the old default argument into the new parameter. 464 // It's important to use getInit() here; getDefaultArg() 465 // strips off any top-level ExprWithCleanups. 466 NewParam->setHasInheritedDefaultArg(); 467 if (OldParam->hasUninstantiatedDefaultArg()) 468 NewParam->setUninstantiatedDefaultArg( 469 OldParam->getUninstantiatedDefaultArg()); 470 else 471 NewParam->setDefaultArg(OldParam->getInit()); 472 } else if (NewParamHasDfl) { 473 if (New->getDescribedFunctionTemplate()) { 474 // Paragraph 4, quoted above, only applies to non-template functions. 475 Diag(NewParam->getLocation(), 476 diag::err_param_default_argument_template_redecl) 477 << NewParam->getDefaultArgRange(); 478 Diag(Old->getLocation(), diag::note_template_prev_declaration) 479 << false; 480 } else if (New->getTemplateSpecializationKind() 481 != TSK_ImplicitInstantiation && 482 New->getTemplateSpecializationKind() != TSK_Undeclared) { 483 // C++ [temp.expr.spec]p21: 484 // Default function arguments shall not be specified in a declaration 485 // or a definition for one of the following explicit specializations: 486 // - the explicit specialization of a function template; 487 // - the explicit specialization of a member function template; 488 // - the explicit specialization of a member function of a class 489 // template where the class template specialization to which the 490 // member function specialization belongs is implicitly 491 // instantiated. 492 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 493 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 494 << New->getDeclName() 495 << NewParam->getDefaultArgRange(); 496 } else if (New->getDeclContext()->isDependentContext()) { 497 // C++ [dcl.fct.default]p6 (DR217): 498 // Default arguments for a member function of a class template shall 499 // be specified on the initial declaration of the member function 500 // within the class template. 501 // 502 // Reading the tea leaves a bit in DR217 and its reference to DR205 503 // leads me to the conclusion that one cannot add default function 504 // arguments for an out-of-line definition of a member function of a 505 // dependent type. 506 int WhichKind = 2; 507 if (CXXRecordDecl *Record 508 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 509 if (Record->getDescribedClassTemplate()) 510 WhichKind = 0; 511 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 512 WhichKind = 1; 513 else 514 WhichKind = 2; 515 } 516 517 Diag(NewParam->getLocation(), 518 diag::err_param_default_argument_member_template_redecl) 519 << WhichKind 520 << NewParam->getDefaultArgRange(); 521 } else if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(New)) { 522 CXXSpecialMember NewSM = getSpecialMember(Ctor), 523 OldSM = getSpecialMember(cast<CXXConstructorDecl>(Old)); 524 if (NewSM != OldSM) { 525 Diag(NewParam->getLocation(),diag::warn_default_arg_makes_ctor_special) 526 << NewParam->getDefaultArgRange() << NewSM; 527 Diag(Old->getLocation(), diag::note_previous_declaration_special) 528 << OldSM; 529 } 530 } 531 } 532 } 533 534 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 535 // template has a constexpr specifier then all its declarations shall 536 // contain the constexpr specifier. 537 if (New->isConstexpr() != Old->isConstexpr()) { 538 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 539 << New << New->isConstexpr(); 540 Diag(Old->getLocation(), diag::note_previous_declaration); 541 Invalid = true; 542 } 543 544 if (CheckEquivalentExceptionSpec(Old, New)) 545 Invalid = true; 546 547 return Invalid; 548} 549 550/// \brief Merge the exception specifications of two variable declarations. 551/// 552/// This is called when there's a redeclaration of a VarDecl. The function 553/// checks if the redeclaration might have an exception specification and 554/// validates compatibility and merges the specs if necessary. 555void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 556 // Shortcut if exceptions are disabled. 557 if (!getLangOpts().CXXExceptions) 558 return; 559 560 assert(Context.hasSameType(New->getType(), Old->getType()) && 561 "Should only be called if types are otherwise the same."); 562 563 QualType NewType = New->getType(); 564 QualType OldType = Old->getType(); 565 566 // We're only interested in pointers and references to functions, as well 567 // as pointers to member functions. 568 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 569 NewType = R->getPointeeType(); 570 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 571 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 572 NewType = P->getPointeeType(); 573 OldType = OldType->getAs<PointerType>()->getPointeeType(); 574 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 575 NewType = M->getPointeeType(); 576 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 577 } 578 579 if (!NewType->isFunctionProtoType()) 580 return; 581 582 // There's lots of special cases for functions. For function pointers, system 583 // libraries are hopefully not as broken so that we don't need these 584 // workarounds. 585 if (CheckEquivalentExceptionSpec( 586 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 587 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 588 New->setInvalidDecl(); 589 } 590} 591 592/// CheckCXXDefaultArguments - Verify that the default arguments for a 593/// function declaration are well-formed according to C++ 594/// [dcl.fct.default]. 595void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 596 unsigned NumParams = FD->getNumParams(); 597 unsigned p; 598 599 bool IsLambda = FD->getOverloadedOperator() == OO_Call && 600 isa<CXXMethodDecl>(FD) && 601 cast<CXXMethodDecl>(FD)->getParent()->isLambda(); 602 603 // Find first parameter with a default argument 604 for (p = 0; p < NumParams; ++p) { 605 ParmVarDecl *Param = FD->getParamDecl(p); 606 if (Param->hasDefaultArg()) { 607 // C++11 [expr.prim.lambda]p5: 608 // [...] Default arguments (8.3.6) shall not be specified in the 609 // parameter-declaration-clause of a lambda-declarator. 610 // 611 // FIXME: Core issue 974 strikes this sentence, we only provide an 612 // extension warning. 613 if (IsLambda) 614 Diag(Param->getLocation(), diag::ext_lambda_default_arguments) 615 << Param->getDefaultArgRange(); 616 break; 617 } 618 } 619 620 // C++ [dcl.fct.default]p4: 621 // In a given function declaration, all parameters 622 // subsequent to a parameter with a default argument shall 623 // have default arguments supplied in this or previous 624 // declarations. A default argument shall not be redefined 625 // by a later declaration (not even to the same value). 626 unsigned LastMissingDefaultArg = 0; 627 for (; p < NumParams; ++p) { 628 ParmVarDecl *Param = FD->getParamDecl(p); 629 if (!Param->hasDefaultArg()) { 630 if (Param->isInvalidDecl()) 631 /* We already complained about this parameter. */; 632 else if (Param->getIdentifier()) 633 Diag(Param->getLocation(), 634 diag::err_param_default_argument_missing_name) 635 << Param->getIdentifier(); 636 else 637 Diag(Param->getLocation(), 638 diag::err_param_default_argument_missing); 639 640 LastMissingDefaultArg = p; 641 } 642 } 643 644 if (LastMissingDefaultArg > 0) { 645 // Some default arguments were missing. Clear out all of the 646 // default arguments up to (and including) the last missing 647 // default argument, so that we leave the function parameters 648 // in a semantically valid state. 649 for (p = 0; p <= LastMissingDefaultArg; ++p) { 650 ParmVarDecl *Param = FD->getParamDecl(p); 651 if (Param->hasDefaultArg()) { 652 Param->setDefaultArg(0); 653 } 654 } 655 } 656} 657 658// CheckConstexprParameterTypes - Check whether a function's parameter types 659// are all literal types. If so, return true. If not, produce a suitable 660// diagnostic and return false. 661static bool CheckConstexprParameterTypes(Sema &SemaRef, 662 const FunctionDecl *FD) { 663 unsigned ArgIndex = 0; 664 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 665 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(), 666 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) { 667 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 668 SourceLocation ParamLoc = PD->getLocation(); 669 if (!(*i)->isDependentType() && 670 SemaRef.RequireLiteralType(ParamLoc, *i, 671 diag::err_constexpr_non_literal_param, 672 ArgIndex+1, PD->getSourceRange(), 673 isa<CXXConstructorDecl>(FD))) 674 return false; 675 } 676 return true; 677} 678 679// CheckConstexprFunctionDecl - Check whether a function declaration satisfies 680// the requirements of a constexpr function definition or a constexpr 681// constructor definition. If so, return true. If not, produce appropriate 682// diagnostics and return false. 683// 684// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 685bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) { 686 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 687 if (MD && MD->isInstance()) { 688 // C++11 [dcl.constexpr]p4: 689 // The definition of a constexpr constructor shall satisfy the following 690 // constraints: 691 // - the class shall not have any virtual base classes; 692 const CXXRecordDecl *RD = MD->getParent(); 693 if (RD->getNumVBases()) { 694 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 695 << isa<CXXConstructorDecl>(NewFD) << RD->isStruct() 696 << RD->getNumVBases(); 697 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(), 698 E = RD->vbases_end(); I != E; ++I) 699 Diag(I->getLocStart(), 700 diag::note_constexpr_virtual_base_here) << I->getSourceRange(); 701 return false; 702 } 703 } 704 705 if (!isa<CXXConstructorDecl>(NewFD)) { 706 // C++11 [dcl.constexpr]p3: 707 // The definition of a constexpr function shall satisfy the following 708 // constraints: 709 // - it shall not be virtual; 710 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 711 if (Method && Method->isVirtual()) { 712 Diag(NewFD->getLocation(), diag::err_constexpr_virtual); 713 714 // If it's not obvious why this function is virtual, find an overridden 715 // function which uses the 'virtual' keyword. 716 const CXXMethodDecl *WrittenVirtual = Method; 717 while (!WrittenVirtual->isVirtualAsWritten()) 718 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 719 if (WrittenVirtual != Method) 720 Diag(WrittenVirtual->getLocation(), 721 diag::note_overridden_virtual_function); 722 return false; 723 } 724 725 // - its return type shall be a literal type; 726 QualType RT = NewFD->getResultType(); 727 if (!RT->isDependentType() && 728 RequireLiteralType(NewFD->getLocation(), RT, 729 diag::err_constexpr_non_literal_return)) 730 return false; 731 } 732 733 // - each of its parameter types shall be a literal type; 734 if (!CheckConstexprParameterTypes(*this, NewFD)) 735 return false; 736 737 return true; 738} 739 740/// Check the given declaration statement is legal within a constexpr function 741/// body. C++0x [dcl.constexpr]p3,p4. 742/// 743/// \return true if the body is OK, false if we have diagnosed a problem. 744static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 745 DeclStmt *DS) { 746 // C++0x [dcl.constexpr]p3 and p4: 747 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 748 // contain only 749 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(), 750 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) { 751 switch ((*DclIt)->getKind()) { 752 case Decl::StaticAssert: 753 case Decl::Using: 754 case Decl::UsingShadow: 755 case Decl::UsingDirective: 756 case Decl::UnresolvedUsingTypename: 757 // - static_assert-declarations 758 // - using-declarations, 759 // - using-directives, 760 continue; 761 762 case Decl::Typedef: 763 case Decl::TypeAlias: { 764 // - typedef declarations and alias-declarations that do not define 765 // classes or enumerations, 766 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt); 767 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 768 // Don't allow variably-modified types in constexpr functions. 769 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 770 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 771 << TL.getSourceRange() << TL.getType() 772 << isa<CXXConstructorDecl>(Dcl); 773 return false; 774 } 775 continue; 776 } 777 778 case Decl::Enum: 779 case Decl::CXXRecord: 780 // As an extension, we allow the declaration (but not the definition) of 781 // classes and enumerations in all declarations, not just in typedef and 782 // alias declarations. 783 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) { 784 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition) 785 << isa<CXXConstructorDecl>(Dcl); 786 return false; 787 } 788 continue; 789 790 case Decl::Var: 791 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration) 792 << isa<CXXConstructorDecl>(Dcl); 793 return false; 794 795 default: 796 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt) 797 << isa<CXXConstructorDecl>(Dcl); 798 return false; 799 } 800 } 801 802 return true; 803} 804 805/// Check that the given field is initialized within a constexpr constructor. 806/// 807/// \param Dcl The constexpr constructor being checked. 808/// \param Field The field being checked. This may be a member of an anonymous 809/// struct or union nested within the class being checked. 810/// \param Inits All declarations, including anonymous struct/union members and 811/// indirect members, for which any initialization was provided. 812/// \param Diagnosed Set to true if an error is produced. 813static void CheckConstexprCtorInitializer(Sema &SemaRef, 814 const FunctionDecl *Dcl, 815 FieldDecl *Field, 816 llvm::SmallSet<Decl*, 16> &Inits, 817 bool &Diagnosed) { 818 if (Field->isUnnamedBitfield()) 819 return; 820 821 if (Field->isAnonymousStructOrUnion() && 822 Field->getType()->getAsCXXRecordDecl()->isEmpty()) 823 return; 824 825 if (!Inits.count(Field)) { 826 if (!Diagnosed) { 827 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init); 828 Diagnosed = true; 829 } 830 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init); 831 } else if (Field->isAnonymousStructOrUnion()) { 832 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 833 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end(); 834 I != E; ++I) 835 // If an anonymous union contains an anonymous struct of which any member 836 // is initialized, all members must be initialized. 837 if (!RD->isUnion() || Inits.count(*I)) 838 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed); 839 } 840} 841 842/// Check the body for the given constexpr function declaration only contains 843/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 844/// 845/// \return true if the body is OK, false if we have diagnosed a problem. 846bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) { 847 if (isa<CXXTryStmt>(Body)) { 848 // C++11 [dcl.constexpr]p3: 849 // The definition of a constexpr function shall satisfy the following 850 // constraints: [...] 851 // - its function-body shall be = delete, = default, or a 852 // compound-statement 853 // 854 // C++11 [dcl.constexpr]p4: 855 // In the definition of a constexpr constructor, [...] 856 // - its function-body shall not be a function-try-block; 857 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block) 858 << isa<CXXConstructorDecl>(Dcl); 859 return false; 860 } 861 862 // - its function-body shall be [...] a compound-statement that contains only 863 CompoundStmt *CompBody = cast<CompoundStmt>(Body); 864 865 llvm::SmallVector<SourceLocation, 4> ReturnStmts; 866 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(), 867 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) { 868 switch ((*BodyIt)->getStmtClass()) { 869 case Stmt::NullStmtClass: 870 // - null statements, 871 continue; 872 873 case Stmt::DeclStmtClass: 874 // - static_assert-declarations 875 // - using-declarations, 876 // - using-directives, 877 // - typedef declarations and alias-declarations that do not define 878 // classes or enumerations, 879 if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt))) 880 return false; 881 continue; 882 883 case Stmt::ReturnStmtClass: 884 // - and exactly one return statement; 885 if (isa<CXXConstructorDecl>(Dcl)) 886 break; 887 888 ReturnStmts.push_back((*BodyIt)->getLocStart()); 889 continue; 890 891 default: 892 break; 893 } 894 895 Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt) 896 << isa<CXXConstructorDecl>(Dcl); 897 return false; 898 } 899 900 if (const CXXConstructorDecl *Constructor 901 = dyn_cast<CXXConstructorDecl>(Dcl)) { 902 const CXXRecordDecl *RD = Constructor->getParent(); 903 // DR1359: 904 // - every non-variant non-static data member and base class sub-object 905 // shall be initialized; 906 // - if the class is a non-empty union, or for each non-empty anonymous 907 // union member of a non-union class, exactly one non-static data member 908 // shall be initialized; 909 if (RD->isUnion()) { 910 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) { 911 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init); 912 return false; 913 } 914 } else if (!Constructor->isDependentContext() && 915 !Constructor->isDelegatingConstructor()) { 916 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 917 918 // Skip detailed checking if we have enough initializers, and we would 919 // allow at most one initializer per member. 920 bool AnyAnonStructUnionMembers = false; 921 unsigned Fields = 0; 922 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 923 E = RD->field_end(); I != E; ++I, ++Fields) { 924 if (I->isAnonymousStructOrUnion()) { 925 AnyAnonStructUnionMembers = true; 926 break; 927 } 928 } 929 if (AnyAnonStructUnionMembers || 930 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 931 // Check initialization of non-static data members. Base classes are 932 // always initialized so do not need to be checked. Dependent bases 933 // might not have initializers in the member initializer list. 934 llvm::SmallSet<Decl*, 16> Inits; 935 for (CXXConstructorDecl::init_const_iterator 936 I = Constructor->init_begin(), E = Constructor->init_end(); 937 I != E; ++I) { 938 if (FieldDecl *FD = (*I)->getMember()) 939 Inits.insert(FD); 940 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember()) 941 Inits.insert(ID->chain_begin(), ID->chain_end()); 942 } 943 944 bool Diagnosed = false; 945 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 946 E = RD->field_end(); I != E; ++I) 947 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed); 948 if (Diagnosed) 949 return false; 950 } 951 } 952 } else { 953 if (ReturnStmts.empty()) { 954 Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return); 955 return false; 956 } 957 if (ReturnStmts.size() > 1) { 958 Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return); 959 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 960 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return); 961 return false; 962 } 963 } 964 965 // C++11 [dcl.constexpr]p5: 966 // if no function argument values exist such that the function invocation 967 // substitution would produce a constant expression, the program is 968 // ill-formed; no diagnostic required. 969 // C++11 [dcl.constexpr]p3: 970 // - every constructor call and implicit conversion used in initializing the 971 // return value shall be one of those allowed in a constant expression. 972 // C++11 [dcl.constexpr]p4: 973 // - every constructor involved in initializing non-static data members and 974 // base class sub-objects shall be a constexpr constructor. 975 llvm::SmallVector<PartialDiagnosticAt, 8> Diags; 976 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) { 977 Diag(Dcl->getLocation(), diag::err_constexpr_function_never_constant_expr) 978 << isa<CXXConstructorDecl>(Dcl); 979 for (size_t I = 0, N = Diags.size(); I != N; ++I) 980 Diag(Diags[I].first, Diags[I].second); 981 return false; 982 } 983 984 return true; 985} 986 987/// isCurrentClassName - Determine whether the identifier II is the 988/// name of the class type currently being defined. In the case of 989/// nested classes, this will only return true if II is the name of 990/// the innermost class. 991bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 992 const CXXScopeSpec *SS) { 993 assert(getLangOpts().CPlusPlus && "No class names in C!"); 994 995 CXXRecordDecl *CurDecl; 996 if (SS && SS->isSet() && !SS->isInvalid()) { 997 DeclContext *DC = computeDeclContext(*SS, true); 998 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 999 } else 1000 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1001 1002 if (CurDecl && CurDecl->getIdentifier()) 1003 return &II == CurDecl->getIdentifier(); 1004 else 1005 return false; 1006} 1007 1008/// \brief Check the validity of a C++ base class specifier. 1009/// 1010/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 1011/// and returns NULL otherwise. 1012CXXBaseSpecifier * 1013Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 1014 SourceRange SpecifierRange, 1015 bool Virtual, AccessSpecifier Access, 1016 TypeSourceInfo *TInfo, 1017 SourceLocation EllipsisLoc) { 1018 QualType BaseType = TInfo->getType(); 1019 1020 // C++ [class.union]p1: 1021 // A union shall not have base classes. 1022 if (Class->isUnion()) { 1023 Diag(Class->getLocation(), diag::err_base_clause_on_union) 1024 << SpecifierRange; 1025 return 0; 1026 } 1027 1028 if (EllipsisLoc.isValid() && 1029 !TInfo->getType()->containsUnexpandedParameterPack()) { 1030 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 1031 << TInfo->getTypeLoc().getSourceRange(); 1032 EllipsisLoc = SourceLocation(); 1033 } 1034 1035 if (BaseType->isDependentType()) 1036 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1037 Class->getTagKind() == TTK_Class, 1038 Access, TInfo, EllipsisLoc); 1039 1040 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 1041 1042 // Base specifiers must be record types. 1043 if (!BaseType->isRecordType()) { 1044 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 1045 return 0; 1046 } 1047 1048 // C++ [class.union]p1: 1049 // A union shall not be used as a base class. 1050 if (BaseType->isUnionType()) { 1051 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 1052 return 0; 1053 } 1054 1055 // C++ [class.derived]p2: 1056 // The class-name in a base-specifier shall not be an incompletely 1057 // defined class. 1058 if (RequireCompleteType(BaseLoc, BaseType, 1059 diag::err_incomplete_base_class, SpecifierRange)) { 1060 Class->setInvalidDecl(); 1061 return 0; 1062 } 1063 1064 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 1065 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 1066 assert(BaseDecl && "Record type has no declaration"); 1067 BaseDecl = BaseDecl->getDefinition(); 1068 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 1069 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 1070 assert(CXXBaseDecl && "Base type is not a C++ type"); 1071 1072 // C++ [class]p3: 1073 // If a class is marked final and it appears as a base-type-specifier in 1074 // base-clause, the program is ill-formed. 1075 if (CXXBaseDecl->hasAttr<FinalAttr>()) { 1076 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 1077 << CXXBaseDecl->getDeclName(); 1078 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl) 1079 << CXXBaseDecl->getDeclName(); 1080 return 0; 1081 } 1082 1083 if (BaseDecl->isInvalidDecl()) 1084 Class->setInvalidDecl(); 1085 1086 // Create the base specifier. 1087 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1088 Class->getTagKind() == TTK_Class, 1089 Access, TInfo, EllipsisLoc); 1090} 1091 1092/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 1093/// one entry in the base class list of a class specifier, for 1094/// example: 1095/// class foo : public bar, virtual private baz { 1096/// 'public bar' and 'virtual private baz' are each base-specifiers. 1097BaseResult 1098Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 1099 bool Virtual, AccessSpecifier Access, 1100 ParsedType basetype, SourceLocation BaseLoc, 1101 SourceLocation EllipsisLoc) { 1102 if (!classdecl) 1103 return true; 1104 1105 AdjustDeclIfTemplate(classdecl); 1106 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 1107 if (!Class) 1108 return true; 1109 1110 TypeSourceInfo *TInfo = 0; 1111 GetTypeFromParser(basetype, &TInfo); 1112 1113 if (EllipsisLoc.isInvalid() && 1114 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 1115 UPPC_BaseType)) 1116 return true; 1117 1118 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 1119 Virtual, Access, TInfo, 1120 EllipsisLoc)) 1121 return BaseSpec; 1122 else 1123 Class->setInvalidDecl(); 1124 1125 return true; 1126} 1127 1128/// \brief Performs the actual work of attaching the given base class 1129/// specifiers to a C++ class. 1130bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 1131 unsigned NumBases) { 1132 if (NumBases == 0) 1133 return false; 1134 1135 // Used to keep track of which base types we have already seen, so 1136 // that we can properly diagnose redundant direct base types. Note 1137 // that the key is always the unqualified canonical type of the base 1138 // class. 1139 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 1140 1141 // Copy non-redundant base specifiers into permanent storage. 1142 unsigned NumGoodBases = 0; 1143 bool Invalid = false; 1144 for (unsigned idx = 0; idx < NumBases; ++idx) { 1145 QualType NewBaseType 1146 = Context.getCanonicalType(Bases[idx]->getType()); 1147 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 1148 1149 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 1150 if (KnownBase) { 1151 // C++ [class.mi]p3: 1152 // A class shall not be specified as a direct base class of a 1153 // derived class more than once. 1154 Diag(Bases[idx]->getLocStart(), 1155 diag::err_duplicate_base_class) 1156 << KnownBase->getType() 1157 << Bases[idx]->getSourceRange(); 1158 1159 // Delete the duplicate base class specifier; we're going to 1160 // overwrite its pointer later. 1161 Context.Deallocate(Bases[idx]); 1162 1163 Invalid = true; 1164 } else { 1165 // Okay, add this new base class. 1166 KnownBase = Bases[idx]; 1167 Bases[NumGoodBases++] = Bases[idx]; 1168 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) 1169 if (const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl())) 1170 if (RD->hasAttr<WeakAttr>()) 1171 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context)); 1172 } 1173 } 1174 1175 // Attach the remaining base class specifiers to the derived class. 1176 Class->setBases(Bases, NumGoodBases); 1177 1178 // Delete the remaining (good) base class specifiers, since their 1179 // data has been copied into the CXXRecordDecl. 1180 for (unsigned idx = 0; idx < NumGoodBases; ++idx) 1181 Context.Deallocate(Bases[idx]); 1182 1183 return Invalid; 1184} 1185 1186/// ActOnBaseSpecifiers - Attach the given base specifiers to the 1187/// class, after checking whether there are any duplicate base 1188/// classes. 1189void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases, 1190 unsigned NumBases) { 1191 if (!ClassDecl || !Bases || !NumBases) 1192 return; 1193 1194 AdjustDeclIfTemplate(ClassDecl); 1195 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), 1196 (CXXBaseSpecifier**)(Bases), NumBases); 1197} 1198 1199static CXXRecordDecl *GetClassForType(QualType T) { 1200 if (const RecordType *RT = T->getAs<RecordType>()) 1201 return cast<CXXRecordDecl>(RT->getDecl()); 1202 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>()) 1203 return ICT->getDecl(); 1204 else 1205 return 0; 1206} 1207 1208/// \brief Determine whether the type \p Derived is a C++ class that is 1209/// derived from the type \p Base. 1210bool Sema::IsDerivedFrom(QualType Derived, QualType Base) { 1211 if (!getLangOpts().CPlusPlus) 1212 return false; 1213 1214 CXXRecordDecl *DerivedRD = GetClassForType(Derived); 1215 if (!DerivedRD) 1216 return false; 1217 1218 CXXRecordDecl *BaseRD = GetClassForType(Base); 1219 if (!BaseRD) 1220 return false; 1221 1222 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this. 1223 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD); 1224} 1225 1226/// \brief Determine whether the type \p Derived is a C++ class that is 1227/// derived from the type \p Base. 1228bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) { 1229 if (!getLangOpts().CPlusPlus) 1230 return false; 1231 1232 CXXRecordDecl *DerivedRD = GetClassForType(Derived); 1233 if (!DerivedRD) 1234 return false; 1235 1236 CXXRecordDecl *BaseRD = GetClassForType(Base); 1237 if (!BaseRD) 1238 return false; 1239 1240 return DerivedRD->isDerivedFrom(BaseRD, Paths); 1241} 1242 1243void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 1244 CXXCastPath &BasePathArray) { 1245 assert(BasePathArray.empty() && "Base path array must be empty!"); 1246 assert(Paths.isRecordingPaths() && "Must record paths!"); 1247 1248 const CXXBasePath &Path = Paths.front(); 1249 1250 // We first go backward and check if we have a virtual base. 1251 // FIXME: It would be better if CXXBasePath had the base specifier for 1252 // the nearest virtual base. 1253 unsigned Start = 0; 1254 for (unsigned I = Path.size(); I != 0; --I) { 1255 if (Path[I - 1].Base->isVirtual()) { 1256 Start = I - 1; 1257 break; 1258 } 1259 } 1260 1261 // Now add all bases. 1262 for (unsigned I = Start, E = Path.size(); I != E; ++I) 1263 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 1264} 1265 1266/// \brief Determine whether the given base path includes a virtual 1267/// base class. 1268bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) { 1269 for (CXXCastPath::const_iterator B = BasePath.begin(), 1270 BEnd = BasePath.end(); 1271 B != BEnd; ++B) 1272 if ((*B)->isVirtual()) 1273 return true; 1274 1275 return false; 1276} 1277 1278/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 1279/// conversion (where Derived and Base are class types) is 1280/// well-formed, meaning that the conversion is unambiguous (and 1281/// that all of the base classes are accessible). Returns true 1282/// and emits a diagnostic if the code is ill-formed, returns false 1283/// otherwise. Loc is the location where this routine should point to 1284/// if there is an error, and Range is the source range to highlight 1285/// if there is an error. 1286bool 1287Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1288 unsigned InaccessibleBaseID, 1289 unsigned AmbigiousBaseConvID, 1290 SourceLocation Loc, SourceRange Range, 1291 DeclarationName Name, 1292 CXXCastPath *BasePath) { 1293 // First, determine whether the path from Derived to Base is 1294 // ambiguous. This is slightly more expensive than checking whether 1295 // the Derived to Base conversion exists, because here we need to 1296 // explore multiple paths to determine if there is an ambiguity. 1297 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1298 /*DetectVirtual=*/false); 1299 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths); 1300 assert(DerivationOkay && 1301 "Can only be used with a derived-to-base conversion"); 1302 (void)DerivationOkay; 1303 1304 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 1305 if (InaccessibleBaseID) { 1306 // Check that the base class can be accessed. 1307 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(), 1308 InaccessibleBaseID)) { 1309 case AR_inaccessible: 1310 return true; 1311 case AR_accessible: 1312 case AR_dependent: 1313 case AR_delayed: 1314 break; 1315 } 1316 } 1317 1318 // Build a base path if necessary. 1319 if (BasePath) 1320 BuildBasePathArray(Paths, *BasePath); 1321 return false; 1322 } 1323 1324 // We know that the derived-to-base conversion is ambiguous, and 1325 // we're going to produce a diagnostic. Perform the derived-to-base 1326 // search just one more time to compute all of the possible paths so 1327 // that we can print them out. This is more expensive than any of 1328 // the previous derived-to-base checks we've done, but at this point 1329 // performance isn't as much of an issue. 1330 Paths.clear(); 1331 Paths.setRecordingPaths(true); 1332 bool StillOkay = IsDerivedFrom(Derived, Base, Paths); 1333 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 1334 (void)StillOkay; 1335 1336 // Build up a textual representation of the ambiguous paths, e.g., 1337 // D -> B -> A, that will be used to illustrate the ambiguous 1338 // conversions in the diagnostic. We only print one of the paths 1339 // to each base class subobject. 1340 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 1341 1342 Diag(Loc, AmbigiousBaseConvID) 1343 << Derived << Base << PathDisplayStr << Range << Name; 1344 return true; 1345} 1346 1347bool 1348Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1349 SourceLocation Loc, SourceRange Range, 1350 CXXCastPath *BasePath, 1351 bool IgnoreAccess) { 1352 return CheckDerivedToBaseConversion(Derived, Base, 1353 IgnoreAccess ? 0 1354 : diag::err_upcast_to_inaccessible_base, 1355 diag::err_ambiguous_derived_to_base_conv, 1356 Loc, Range, DeclarationName(), 1357 BasePath); 1358} 1359 1360 1361/// @brief Builds a string representing ambiguous paths from a 1362/// specific derived class to different subobjects of the same base 1363/// class. 1364/// 1365/// This function builds a string that can be used in error messages 1366/// to show the different paths that one can take through the 1367/// inheritance hierarchy to go from the derived class to different 1368/// subobjects of a base class. The result looks something like this: 1369/// @code 1370/// struct D -> struct B -> struct A 1371/// struct D -> struct C -> struct A 1372/// @endcode 1373std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 1374 std::string PathDisplayStr; 1375 std::set<unsigned> DisplayedPaths; 1376 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 1377 Path != Paths.end(); ++Path) { 1378 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 1379 // We haven't displayed a path to this particular base 1380 // class subobject yet. 1381 PathDisplayStr += "\n "; 1382 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 1383 for (CXXBasePath::const_iterator Element = Path->begin(); 1384 Element != Path->end(); ++Element) 1385 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 1386 } 1387 } 1388 1389 return PathDisplayStr; 1390} 1391 1392//===----------------------------------------------------------------------===// 1393// C++ class member Handling 1394//===----------------------------------------------------------------------===// 1395 1396/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 1397bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, 1398 SourceLocation ASLoc, 1399 SourceLocation ColonLoc, 1400 AttributeList *Attrs) { 1401 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 1402 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 1403 ASLoc, ColonLoc); 1404 CurContext->addHiddenDecl(ASDecl); 1405 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 1406} 1407 1408/// CheckOverrideControl - Check C++11 override control semantics. 1409void Sema::CheckOverrideControl(Decl *D) { 1410 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 1411 1412 // Do we know which functions this declaration might be overriding? 1413 bool OverridesAreKnown = !MD || 1414 (!MD->getParent()->hasAnyDependentBases() && 1415 !MD->getType()->isDependentType()); 1416 1417 if (!MD || !MD->isVirtual()) { 1418 if (OverridesAreKnown) { 1419 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1420 Diag(OA->getLocation(), 1421 diag::override_keyword_only_allowed_on_virtual_member_functions) 1422 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 1423 D->dropAttr<OverrideAttr>(); 1424 } 1425 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1426 Diag(FA->getLocation(), 1427 diag::override_keyword_only_allowed_on_virtual_member_functions) 1428 << "final" << FixItHint::CreateRemoval(FA->getLocation()); 1429 D->dropAttr<FinalAttr>(); 1430 } 1431 } 1432 return; 1433 } 1434 1435 if (!OverridesAreKnown) 1436 return; 1437 1438 // C++11 [class.virtual]p5: 1439 // If a virtual function is marked with the virt-specifier override and 1440 // does not override a member function of a base class, the program is 1441 // ill-formed. 1442 bool HasOverriddenMethods = 1443 MD->begin_overridden_methods() != MD->end_overridden_methods(); 1444 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 1445 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 1446 << MD->getDeclName(); 1447} 1448 1449/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 1450/// function overrides a virtual member function marked 'final', according to 1451/// C++11 [class.virtual]p4. 1452bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 1453 const CXXMethodDecl *Old) { 1454 if (!Old->hasAttr<FinalAttr>()) 1455 return false; 1456 1457 Diag(New->getLocation(), diag::err_final_function_overridden) 1458 << New->getDeclName(); 1459 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 1460 return true; 1461} 1462 1463static bool InitializationHasSideEffects(const FieldDecl &FD) { 1464 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 1465 // FIXME: Destruction of ObjC lifetime types has side-effects. 1466 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 1467 return !RD->isCompleteDefinition() || 1468 !RD->hasTrivialDefaultConstructor() || 1469 !RD->hasTrivialDestructor(); 1470 return false; 1471} 1472 1473/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 1474/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 1475/// bitfield width if there is one, 'InitExpr' specifies the initializer if 1476/// one has been parsed, and 'InitStyle' is set if an in-class initializer is 1477/// present (but parsing it has been deferred). 1478Decl * 1479Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 1480 MultiTemplateParamsArg TemplateParameterLists, 1481 Expr *BW, const VirtSpecifiers &VS, 1482 InClassInitStyle InitStyle) { 1483 const DeclSpec &DS = D.getDeclSpec(); 1484 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 1485 DeclarationName Name = NameInfo.getName(); 1486 SourceLocation Loc = NameInfo.getLoc(); 1487 1488 // For anonymous bitfields, the location should point to the type. 1489 if (Loc.isInvalid()) 1490 Loc = D.getLocStart(); 1491 1492 Expr *BitWidth = static_cast<Expr*>(BW); 1493 1494 assert(isa<CXXRecordDecl>(CurContext)); 1495 assert(!DS.isFriendSpecified()); 1496 1497 bool isFunc = D.isDeclarationOfFunction(); 1498 1499 // C++ 9.2p6: A member shall not be declared to have automatic storage 1500 // duration (auto, register) or with the extern storage-class-specifier. 1501 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 1502 // data members and cannot be applied to names declared const or static, 1503 // and cannot be applied to reference members. 1504 switch (DS.getStorageClassSpec()) { 1505 case DeclSpec::SCS_unspecified: 1506 case DeclSpec::SCS_typedef: 1507 case DeclSpec::SCS_static: 1508 // FALL THROUGH. 1509 break; 1510 case DeclSpec::SCS_mutable: 1511 if (isFunc) { 1512 if (DS.getStorageClassSpecLoc().isValid()) 1513 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 1514 else 1515 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function); 1516 1517 // FIXME: It would be nicer if the keyword was ignored only for this 1518 // declarator. Otherwise we could get follow-up errors. 1519 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1520 } 1521 break; 1522 default: 1523 if (DS.getStorageClassSpecLoc().isValid()) 1524 Diag(DS.getStorageClassSpecLoc(), 1525 diag::err_storageclass_invalid_for_member); 1526 else 1527 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member); 1528 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1529 } 1530 1531 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 1532 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 1533 !isFunc); 1534 1535 Decl *Member; 1536 if (isInstField) { 1537 CXXScopeSpec &SS = D.getCXXScopeSpec(); 1538 1539 // Data members must have identifiers for names. 1540 if (!Name.isIdentifier()) { 1541 Diag(Loc, diag::err_bad_variable_name) 1542 << Name; 1543 return 0; 1544 } 1545 1546 IdentifierInfo *II = Name.getAsIdentifierInfo(); 1547 1548 // Member field could not be with "template" keyword. 1549 // So TemplateParameterLists should be empty in this case. 1550 if (TemplateParameterLists.size()) { 1551 TemplateParameterList* TemplateParams = TemplateParameterLists.get()[0]; 1552 if (TemplateParams->size()) { 1553 // There is no such thing as a member field template. 1554 Diag(D.getIdentifierLoc(), diag::err_template_member) 1555 << II 1556 << SourceRange(TemplateParams->getTemplateLoc(), 1557 TemplateParams->getRAngleLoc()); 1558 } else { 1559 // There is an extraneous 'template<>' for this member. 1560 Diag(TemplateParams->getTemplateLoc(), 1561 diag::err_template_member_noparams) 1562 << II 1563 << SourceRange(TemplateParams->getTemplateLoc(), 1564 TemplateParams->getRAngleLoc()); 1565 } 1566 return 0; 1567 } 1568 1569 if (SS.isSet() && !SS.isInvalid()) { 1570 // The user provided a superfluous scope specifier inside a class 1571 // definition: 1572 // 1573 // class X { 1574 // int X::member; 1575 // }; 1576 if (DeclContext *DC = computeDeclContext(SS, false)) 1577 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc()); 1578 else 1579 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 1580 << Name << SS.getRange(); 1581 1582 SS.clear(); 1583 } 1584 1585 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth, 1586 InitStyle, AS); 1587 assert(Member && "HandleField never returns null"); 1588 } else { 1589 assert(InitStyle == ICIS_NoInit); 1590 1591 Member = HandleDeclarator(S, D, move(TemplateParameterLists)); 1592 if (!Member) { 1593 return 0; 1594 } 1595 1596 // Non-instance-fields can't have a bitfield. 1597 if (BitWidth) { 1598 if (Member->isInvalidDecl()) { 1599 // don't emit another diagnostic. 1600 } else if (isa<VarDecl>(Member)) { 1601 // C++ 9.6p3: A bit-field shall not be a static member. 1602 // "static member 'A' cannot be a bit-field" 1603 Diag(Loc, diag::err_static_not_bitfield) 1604 << Name << BitWidth->getSourceRange(); 1605 } else if (isa<TypedefDecl>(Member)) { 1606 // "typedef member 'x' cannot be a bit-field" 1607 Diag(Loc, diag::err_typedef_not_bitfield) 1608 << Name << BitWidth->getSourceRange(); 1609 } else { 1610 // A function typedef ("typedef int f(); f a;"). 1611 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 1612 Diag(Loc, diag::err_not_integral_type_bitfield) 1613 << Name << cast<ValueDecl>(Member)->getType() 1614 << BitWidth->getSourceRange(); 1615 } 1616 1617 BitWidth = 0; 1618 Member->setInvalidDecl(); 1619 } 1620 1621 Member->setAccess(AS); 1622 1623 // If we have declared a member function template, set the access of the 1624 // templated declaration as well. 1625 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 1626 FunTmpl->getTemplatedDecl()->setAccess(AS); 1627 } 1628 1629 if (VS.isOverrideSpecified()) 1630 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context)); 1631 if (VS.isFinalSpecified()) 1632 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context)); 1633 1634 if (VS.getLastLocation().isValid()) { 1635 // Update the end location of a method that has a virt-specifiers. 1636 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 1637 MD->setRangeEnd(VS.getLastLocation()); 1638 } 1639 1640 CheckOverrideControl(Member); 1641 1642 assert((Name || isInstField) && "No identifier for non-field ?"); 1643 1644 if (isInstField) { 1645 FieldDecl *FD = cast<FieldDecl>(Member); 1646 FieldCollector->Add(FD); 1647 1648 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field, 1649 FD->getLocation()) 1650 != DiagnosticsEngine::Ignored) { 1651 // Remember all explicit private FieldDecls that have a name, no side 1652 // effects and are not part of a dependent type declaration. 1653 if (!FD->isImplicit() && FD->getDeclName() && 1654 FD->getAccess() == AS_private && 1655 !FD->hasAttr<UnusedAttr>() && 1656 !FD->getParent()->isDependentContext() && 1657 !InitializationHasSideEffects(*FD)) 1658 UnusedPrivateFields.insert(FD); 1659 } 1660 } 1661 1662 return Member; 1663} 1664 1665/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an 1666/// in-class initializer for a non-static C++ class member, and after 1667/// instantiating an in-class initializer in a class template. Such actions 1668/// are deferred until the class is complete. 1669void 1670Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc, 1671 Expr *InitExpr) { 1672 FieldDecl *FD = cast<FieldDecl>(D); 1673 assert(FD->getInClassInitStyle() != ICIS_NoInit && 1674 "must set init style when field is created"); 1675 1676 if (!InitExpr) { 1677 FD->setInvalidDecl(); 1678 FD->removeInClassInitializer(); 1679 return; 1680 } 1681 1682 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 1683 FD->setInvalidDecl(); 1684 FD->removeInClassInitializer(); 1685 return; 1686 } 1687 1688 ExprResult Init = InitExpr; 1689 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 1690 if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) { 1691 Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list) 1692 << /*at end of ctor*/1 << InitExpr->getSourceRange(); 1693 } 1694 Expr **Inits = &InitExpr; 1695 unsigned NumInits = 1; 1696 InitializedEntity Entity = InitializedEntity::InitializeMember(FD); 1697 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit 1698 ? InitializationKind::CreateDirectList(InitExpr->getLocStart()) 1699 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc); 1700 InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits); 1701 Init = Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits)); 1702 if (Init.isInvalid()) { 1703 FD->setInvalidDecl(); 1704 return; 1705 } 1706 1707 CheckImplicitConversions(Init.get(), InitLoc); 1708 } 1709 1710 // C++0x [class.base.init]p7: 1711 // The initialization of each base and member constitutes a 1712 // full-expression. 1713 Init = MaybeCreateExprWithCleanups(Init); 1714 if (Init.isInvalid()) { 1715 FD->setInvalidDecl(); 1716 return; 1717 } 1718 1719 InitExpr = Init.release(); 1720 1721 FD->setInClassInitializer(InitExpr); 1722} 1723 1724/// \brief Find the direct and/or virtual base specifiers that 1725/// correspond to the given base type, for use in base initialization 1726/// within a constructor. 1727static bool FindBaseInitializer(Sema &SemaRef, 1728 CXXRecordDecl *ClassDecl, 1729 QualType BaseType, 1730 const CXXBaseSpecifier *&DirectBaseSpec, 1731 const CXXBaseSpecifier *&VirtualBaseSpec) { 1732 // First, check for a direct base class. 1733 DirectBaseSpec = 0; 1734 for (CXXRecordDecl::base_class_const_iterator Base 1735 = ClassDecl->bases_begin(); 1736 Base != ClassDecl->bases_end(); ++Base) { 1737 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) { 1738 // We found a direct base of this type. That's what we're 1739 // initializing. 1740 DirectBaseSpec = &*Base; 1741 break; 1742 } 1743 } 1744 1745 // Check for a virtual base class. 1746 // FIXME: We might be able to short-circuit this if we know in advance that 1747 // there are no virtual bases. 1748 VirtualBaseSpec = 0; 1749 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 1750 // We haven't found a base yet; search the class hierarchy for a 1751 // virtual base class. 1752 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1753 /*DetectVirtual=*/false); 1754 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl), 1755 BaseType, Paths)) { 1756 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 1757 Path != Paths.end(); ++Path) { 1758 if (Path->back().Base->isVirtual()) { 1759 VirtualBaseSpec = Path->back().Base; 1760 break; 1761 } 1762 } 1763 } 1764 } 1765 1766 return DirectBaseSpec || VirtualBaseSpec; 1767} 1768 1769/// \brief Handle a C++ member initializer using braced-init-list syntax. 1770MemInitResult 1771Sema::ActOnMemInitializer(Decl *ConstructorD, 1772 Scope *S, 1773 CXXScopeSpec &SS, 1774 IdentifierInfo *MemberOrBase, 1775 ParsedType TemplateTypeTy, 1776 const DeclSpec &DS, 1777 SourceLocation IdLoc, 1778 Expr *InitList, 1779 SourceLocation EllipsisLoc) { 1780 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 1781 DS, IdLoc, InitList, 1782 EllipsisLoc); 1783} 1784 1785/// \brief Handle a C++ member initializer using parentheses syntax. 1786MemInitResult 1787Sema::ActOnMemInitializer(Decl *ConstructorD, 1788 Scope *S, 1789 CXXScopeSpec &SS, 1790 IdentifierInfo *MemberOrBase, 1791 ParsedType TemplateTypeTy, 1792 const DeclSpec &DS, 1793 SourceLocation IdLoc, 1794 SourceLocation LParenLoc, 1795 Expr **Args, unsigned NumArgs, 1796 SourceLocation RParenLoc, 1797 SourceLocation EllipsisLoc) { 1798 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs, 1799 RParenLoc); 1800 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 1801 DS, IdLoc, List, EllipsisLoc); 1802} 1803 1804namespace { 1805 1806// Callback to only accept typo corrections that can be a valid C++ member 1807// intializer: either a non-static field member or a base class. 1808class MemInitializerValidatorCCC : public CorrectionCandidateCallback { 1809 public: 1810 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 1811 : ClassDecl(ClassDecl) {} 1812 1813 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 1814 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 1815 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 1816 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 1817 else 1818 return isa<TypeDecl>(ND); 1819 } 1820 return false; 1821 } 1822 1823 private: 1824 CXXRecordDecl *ClassDecl; 1825}; 1826 1827} 1828 1829/// \brief Handle a C++ member initializer. 1830MemInitResult 1831Sema::BuildMemInitializer(Decl *ConstructorD, 1832 Scope *S, 1833 CXXScopeSpec &SS, 1834 IdentifierInfo *MemberOrBase, 1835 ParsedType TemplateTypeTy, 1836 const DeclSpec &DS, 1837 SourceLocation IdLoc, 1838 Expr *Init, 1839 SourceLocation EllipsisLoc) { 1840 if (!ConstructorD) 1841 return true; 1842 1843 AdjustDeclIfTemplate(ConstructorD); 1844 1845 CXXConstructorDecl *Constructor 1846 = dyn_cast<CXXConstructorDecl>(ConstructorD); 1847 if (!Constructor) { 1848 // The user wrote a constructor initializer on a function that is 1849 // not a C++ constructor. Ignore the error for now, because we may 1850 // have more member initializers coming; we'll diagnose it just 1851 // once in ActOnMemInitializers. 1852 return true; 1853 } 1854 1855 CXXRecordDecl *ClassDecl = Constructor->getParent(); 1856 1857 // C++ [class.base.init]p2: 1858 // Names in a mem-initializer-id are looked up in the scope of the 1859 // constructor's class and, if not found in that scope, are looked 1860 // up in the scope containing the constructor's definition. 1861 // [Note: if the constructor's class contains a member with the 1862 // same name as a direct or virtual base class of the class, a 1863 // mem-initializer-id naming the member or base class and composed 1864 // of a single identifier refers to the class member. A 1865 // mem-initializer-id for the hidden base class may be specified 1866 // using a qualified name. ] 1867 if (!SS.getScopeRep() && !TemplateTypeTy) { 1868 // Look for a member, first. 1869 DeclContext::lookup_result Result 1870 = ClassDecl->lookup(MemberOrBase); 1871 if (Result.first != Result.second) { 1872 ValueDecl *Member; 1873 if ((Member = dyn_cast<FieldDecl>(*Result.first)) || 1874 (Member = dyn_cast<IndirectFieldDecl>(*Result.first))) { 1875 if (EllipsisLoc.isValid()) 1876 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 1877 << MemberOrBase 1878 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 1879 1880 return BuildMemberInitializer(Member, Init, IdLoc); 1881 } 1882 } 1883 } 1884 // It didn't name a member, so see if it names a class. 1885 QualType BaseType; 1886 TypeSourceInfo *TInfo = 0; 1887 1888 if (TemplateTypeTy) { 1889 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 1890 } else if (DS.getTypeSpecType() == TST_decltype) { 1891 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 1892 } else { 1893 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 1894 LookupParsedName(R, S, &SS); 1895 1896 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 1897 if (!TyD) { 1898 if (R.isAmbiguous()) return true; 1899 1900 // We don't want access-control diagnostics here. 1901 R.suppressDiagnostics(); 1902 1903 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 1904 bool NotUnknownSpecialization = false; 1905 DeclContext *DC = computeDeclContext(SS, false); 1906 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 1907 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 1908 1909 if (!NotUnknownSpecialization) { 1910 // When the scope specifier can refer to a member of an unknown 1911 // specialization, we take it as a type name. 1912 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 1913 SS.getWithLocInContext(Context), 1914 *MemberOrBase, IdLoc); 1915 if (BaseType.isNull()) 1916 return true; 1917 1918 R.clear(); 1919 R.setLookupName(MemberOrBase); 1920 } 1921 } 1922 1923 // If no results were found, try to correct typos. 1924 TypoCorrection Corr; 1925 MemInitializerValidatorCCC Validator(ClassDecl); 1926 if (R.empty() && BaseType.isNull() && 1927 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 1928 Validator, ClassDecl))) { 1929 std::string CorrectedStr(Corr.getAsString(getLangOpts())); 1930 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts())); 1931 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 1932 // We have found a non-static data member with a similar 1933 // name to what was typed; complain and initialize that 1934 // member. 1935 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest) 1936 << MemberOrBase << true << CorrectedQuotedStr 1937 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr); 1938 Diag(Member->getLocation(), diag::note_previous_decl) 1939 << CorrectedQuotedStr; 1940 1941 return BuildMemberInitializer(Member, Init, IdLoc); 1942 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 1943 const CXXBaseSpecifier *DirectBaseSpec; 1944 const CXXBaseSpecifier *VirtualBaseSpec; 1945 if (FindBaseInitializer(*this, ClassDecl, 1946 Context.getTypeDeclType(Type), 1947 DirectBaseSpec, VirtualBaseSpec)) { 1948 // We have found a direct or virtual base class with a 1949 // similar name to what was typed; complain and initialize 1950 // that base class. 1951 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest) 1952 << MemberOrBase << false << CorrectedQuotedStr 1953 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr); 1954 1955 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec 1956 : VirtualBaseSpec; 1957 Diag(BaseSpec->getLocStart(), 1958 diag::note_base_class_specified_here) 1959 << BaseSpec->getType() 1960 << BaseSpec->getSourceRange(); 1961 1962 TyD = Type; 1963 } 1964 } 1965 } 1966 1967 if (!TyD && BaseType.isNull()) { 1968 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 1969 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 1970 return true; 1971 } 1972 } 1973 1974 if (BaseType.isNull()) { 1975 BaseType = Context.getTypeDeclType(TyD); 1976 if (SS.isSet()) { 1977 NestedNameSpecifier *Qualifier = 1978 static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 1979 1980 // FIXME: preserve source range information 1981 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType); 1982 } 1983 } 1984 } 1985 1986 if (!TInfo) 1987 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 1988 1989 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 1990} 1991 1992/// Checks a member initializer expression for cases where reference (or 1993/// pointer) members are bound to by-value parameters (or their addresses). 1994static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member, 1995 Expr *Init, 1996 SourceLocation IdLoc) { 1997 QualType MemberTy = Member->getType(); 1998 1999 // We only handle pointers and references currently. 2000 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers? 2001 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType()) 2002 return; 2003 2004 const bool IsPointer = MemberTy->isPointerType(); 2005 if (IsPointer) { 2006 if (const UnaryOperator *Op 2007 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) { 2008 // The only case we're worried about with pointers requires taking the 2009 // address. 2010 if (Op->getOpcode() != UO_AddrOf) 2011 return; 2012 2013 Init = Op->getSubExpr(); 2014 } else { 2015 // We only handle address-of expression initializers for pointers. 2016 return; 2017 } 2018 } 2019 2020 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) { 2021 // Taking the address of a temporary will be diagnosed as a hard error. 2022 if (IsPointer) 2023 return; 2024 2025 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary) 2026 << Member << Init->getSourceRange(); 2027 } else if (const DeclRefExpr *DRE 2028 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) { 2029 // We only warn when referring to a non-reference parameter declaration. 2030 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl()); 2031 if (!Parameter || Parameter->getType()->isReferenceType()) 2032 return; 2033 2034 S.Diag(Init->getExprLoc(), 2035 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr 2036 : diag::warn_bind_ref_member_to_parameter) 2037 << Member << Parameter << Init->getSourceRange(); 2038 } else { 2039 // Other initializers are fine. 2040 return; 2041 } 2042 2043 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here) 2044 << (unsigned)IsPointer; 2045} 2046 2047namespace { 2048 class UninitializedFieldVisitor 2049 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 2050 Sema &S; 2051 ValueDecl *VD; 2052 public: 2053 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 2054 UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context), 2055 S(S), VD(VD) { 2056 } 2057 2058 void HandleExpr(Expr *E) { 2059 if (!E) return; 2060 2061 // Expressions like x(x) sometimes lack the surrounding expressions 2062 // but need to be checked anyways. 2063 HandleValue(E); 2064 Visit(E); 2065 } 2066 2067 void HandleValue(Expr *E) { 2068 E = E->IgnoreParens(); 2069 2070 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 2071 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 2072 return; 2073 Expr *Base = E; 2074 while (isa<MemberExpr>(Base)) { 2075 ME = dyn_cast<MemberExpr>(Base); 2076 if (VarDecl *VarD = dyn_cast<VarDecl>(ME->getMemberDecl())) 2077 if (VarD->hasGlobalStorage()) 2078 return; 2079 Base = ME->getBase(); 2080 } 2081 2082 if (VD == ME->getMemberDecl() && isa<CXXThisExpr>(Base)) { 2083 S.Diag(ME->getExprLoc(), diag::warn_field_is_uninit); 2084 return; 2085 } 2086 } 2087 2088 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 2089 HandleValue(CO->getTrueExpr()); 2090 HandleValue(CO->getFalseExpr()); 2091 return; 2092 } 2093 2094 if (BinaryConditionalOperator *BCO = 2095 dyn_cast<BinaryConditionalOperator>(E)) { 2096 HandleValue(BCO->getCommon()); 2097 HandleValue(BCO->getFalseExpr()); 2098 return; 2099 } 2100 2101 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 2102 switch (BO->getOpcode()) { 2103 default: 2104 return; 2105 case(BO_PtrMemD): 2106 case(BO_PtrMemI): 2107 HandleValue(BO->getLHS()); 2108 return; 2109 case(BO_Comma): 2110 HandleValue(BO->getRHS()); 2111 return; 2112 } 2113 } 2114 } 2115 2116 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 2117 if (E->getCastKind() == CK_LValueToRValue) 2118 HandleValue(E->getSubExpr()); 2119 2120 Inherited::VisitImplicitCastExpr(E); 2121 } 2122 2123 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 2124 Expr *Callee = E->getCallee(); 2125 if (isa<MemberExpr>(Callee)) 2126 HandleValue(Callee); 2127 2128 Inherited::VisitCXXMemberCallExpr(E); 2129 } 2130 }; 2131 static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E, 2132 ValueDecl *VD) { 2133 UninitializedFieldVisitor(S, VD).HandleExpr(E); 2134 } 2135} // namespace 2136 2137MemInitResult 2138Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 2139 SourceLocation IdLoc) { 2140 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 2141 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 2142 assert((DirectMember || IndirectMember) && 2143 "Member must be a FieldDecl or IndirectFieldDecl"); 2144 2145 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 2146 return true; 2147 2148 if (Member->isInvalidDecl()) 2149 return true; 2150 2151 // Diagnose value-uses of fields to initialize themselves, e.g. 2152 // foo(foo) 2153 // where foo is not also a parameter to the constructor. 2154 // TODO: implement -Wuninitialized and fold this into that framework. 2155 Expr **Args; 2156 unsigned NumArgs; 2157 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2158 Args = ParenList->getExprs(); 2159 NumArgs = ParenList->getNumExprs(); 2160 } else { 2161 InitListExpr *InitList = cast<InitListExpr>(Init); 2162 Args = InitList->getInits(); 2163 NumArgs = InitList->getNumInits(); 2164 } 2165 2166 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc) 2167 != DiagnosticsEngine::Ignored) 2168 for (unsigned i = 0; i < NumArgs; ++i) 2169 // FIXME: Warn about the case when other fields are used before being 2170 // uninitialized. For example, let this field be the i'th field. When 2171 // initializing the i'th field, throw a warning if any of the >= i'th 2172 // fields are used, as they are not yet initialized. 2173 // Right now we are only handling the case where the i'th field uses 2174 // itself in its initializer. 2175 CheckInitExprContainsUninitializedFields(*this, Args[i], Member); 2176 2177 SourceRange InitRange = Init->getSourceRange(); 2178 2179 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 2180 // Can't check initialization for a member of dependent type or when 2181 // any of the arguments are type-dependent expressions. 2182 DiscardCleanupsInEvaluationContext(); 2183 } else { 2184 bool InitList = false; 2185 if (isa<InitListExpr>(Init)) { 2186 InitList = true; 2187 Args = &Init; 2188 NumArgs = 1; 2189 2190 if (isStdInitializerList(Member->getType(), 0)) { 2191 Diag(IdLoc, diag::warn_dangling_std_initializer_list) 2192 << /*at end of ctor*/1 << InitRange; 2193 } 2194 } 2195 2196 // Initialize the member. 2197 InitializedEntity MemberEntity = 2198 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0) 2199 : InitializedEntity::InitializeMember(IndirectMember, 0); 2200 InitializationKind Kind = 2201 InitList ? InitializationKind::CreateDirectList(IdLoc) 2202 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 2203 InitRange.getEnd()); 2204 2205 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs); 2206 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, 2207 MultiExprArg(*this, Args, NumArgs), 2208 0); 2209 if (MemberInit.isInvalid()) 2210 return true; 2211 2212 CheckImplicitConversions(MemberInit.get(), 2213 InitRange.getBegin()); 2214 2215 // C++0x [class.base.init]p7: 2216 // The initialization of each base and member constitutes a 2217 // full-expression. 2218 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 2219 if (MemberInit.isInvalid()) 2220 return true; 2221 2222 // If we are in a dependent context, template instantiation will 2223 // perform this type-checking again. Just save the arguments that we 2224 // received. 2225 // FIXME: This isn't quite ideal, since our ASTs don't capture all 2226 // of the information that we have about the member 2227 // initializer. However, deconstructing the ASTs is a dicey process, 2228 // and this approach is far more likely to get the corner cases right. 2229 if (CurContext->isDependentContext()) { 2230 // The existing Init will do fine. 2231 } else { 2232 Init = MemberInit.get(); 2233 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc); 2234 } 2235 } 2236 2237 if (DirectMember) { 2238 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 2239 InitRange.getBegin(), Init, 2240 InitRange.getEnd()); 2241 } else { 2242 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 2243 InitRange.getBegin(), Init, 2244 InitRange.getEnd()); 2245 } 2246} 2247 2248MemInitResult 2249Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 2250 CXXRecordDecl *ClassDecl) { 2251 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 2252 if (!LangOpts.CPlusPlus0x) 2253 return Diag(NameLoc, diag::err_delegating_ctor) 2254 << TInfo->getTypeLoc().getLocalSourceRange(); 2255 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 2256 2257 bool InitList = true; 2258 Expr **Args = &Init; 2259 unsigned NumArgs = 1; 2260 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2261 InitList = false; 2262 Args = ParenList->getExprs(); 2263 NumArgs = ParenList->getNumExprs(); 2264 } 2265 2266 SourceRange InitRange = Init->getSourceRange(); 2267 // Initialize the object. 2268 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 2269 QualType(ClassDecl->getTypeForDecl(), 0)); 2270 InitializationKind Kind = 2271 InitList ? InitializationKind::CreateDirectList(NameLoc) 2272 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 2273 InitRange.getEnd()); 2274 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs); 2275 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 2276 MultiExprArg(*this, Args,NumArgs), 2277 0); 2278 if (DelegationInit.isInvalid()) 2279 return true; 2280 2281 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 2282 "Delegating constructor with no target?"); 2283 2284 CheckImplicitConversions(DelegationInit.get(), InitRange.getBegin()); 2285 2286 // C++0x [class.base.init]p7: 2287 // The initialization of each base and member constitutes a 2288 // full-expression. 2289 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit); 2290 if (DelegationInit.isInvalid()) 2291 return true; 2292 2293 // If we are in a dependent context, template instantiation will 2294 // perform this type-checking again. Just save the arguments that we 2295 // received in a ParenListExpr. 2296 // FIXME: This isn't quite ideal, since our ASTs don't capture all 2297 // of the information that we have about the base 2298 // initializer. However, deconstructing the ASTs is a dicey process, 2299 // and this approach is far more likely to get the corner cases right. 2300 if (CurContext->isDependentContext()) 2301 DelegationInit = Owned(Init); 2302 2303 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 2304 DelegationInit.takeAs<Expr>(), 2305 InitRange.getEnd()); 2306} 2307 2308MemInitResult 2309Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 2310 Expr *Init, CXXRecordDecl *ClassDecl, 2311 SourceLocation EllipsisLoc) { 2312 SourceLocation BaseLoc 2313 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 2314 2315 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 2316 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 2317 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2318 2319 // C++ [class.base.init]p2: 2320 // [...] Unless the mem-initializer-id names a nonstatic data 2321 // member of the constructor's class or a direct or virtual base 2322 // of that class, the mem-initializer is ill-formed. A 2323 // mem-initializer-list can initialize a base class using any 2324 // name that denotes that base class type. 2325 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 2326 2327 SourceRange InitRange = Init->getSourceRange(); 2328 if (EllipsisLoc.isValid()) { 2329 // This is a pack expansion. 2330 if (!BaseType->containsUnexpandedParameterPack()) { 2331 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2332 << SourceRange(BaseLoc, InitRange.getEnd()); 2333 2334 EllipsisLoc = SourceLocation(); 2335 } 2336 } else { 2337 // Check for any unexpanded parameter packs. 2338 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 2339 return true; 2340 2341 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 2342 return true; 2343 } 2344 2345 // Check for direct and virtual base classes. 2346 const CXXBaseSpecifier *DirectBaseSpec = 0; 2347 const CXXBaseSpecifier *VirtualBaseSpec = 0; 2348 if (!Dependent) { 2349 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 2350 BaseType)) 2351 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 2352 2353 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 2354 VirtualBaseSpec); 2355 2356 // C++ [base.class.init]p2: 2357 // Unless the mem-initializer-id names a nonstatic data member of the 2358 // constructor's class or a direct or virtual base of that class, the 2359 // mem-initializer is ill-formed. 2360 if (!DirectBaseSpec && !VirtualBaseSpec) { 2361 // If the class has any dependent bases, then it's possible that 2362 // one of those types will resolve to the same type as 2363 // BaseType. Therefore, just treat this as a dependent base 2364 // class initialization. FIXME: Should we try to check the 2365 // initialization anyway? It seems odd. 2366 if (ClassDecl->hasAnyDependentBases()) 2367 Dependent = true; 2368 else 2369 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 2370 << BaseType << Context.getTypeDeclType(ClassDecl) 2371 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2372 } 2373 } 2374 2375 if (Dependent) { 2376 DiscardCleanupsInEvaluationContext(); 2377 2378 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 2379 /*IsVirtual=*/false, 2380 InitRange.getBegin(), Init, 2381 InitRange.getEnd(), EllipsisLoc); 2382 } 2383 2384 // C++ [base.class.init]p2: 2385 // If a mem-initializer-id is ambiguous because it designates both 2386 // a direct non-virtual base class and an inherited virtual base 2387 // class, the mem-initializer is ill-formed. 2388 if (DirectBaseSpec && VirtualBaseSpec) 2389 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 2390 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2391 2392 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec); 2393 if (!BaseSpec) 2394 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec); 2395 2396 // Initialize the base. 2397 bool InitList = true; 2398 Expr **Args = &Init; 2399 unsigned NumArgs = 1; 2400 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2401 InitList = false; 2402 Args = ParenList->getExprs(); 2403 NumArgs = ParenList->getNumExprs(); 2404 } 2405 2406 InitializedEntity BaseEntity = 2407 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 2408 InitializationKind Kind = 2409 InitList ? InitializationKind::CreateDirectList(BaseLoc) 2410 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 2411 InitRange.getEnd()); 2412 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs); 2413 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, 2414 MultiExprArg(*this, Args, NumArgs), 2415 0); 2416 if (BaseInit.isInvalid()) 2417 return true; 2418 2419 CheckImplicitConversions(BaseInit.get(), InitRange.getBegin()); 2420 2421 // C++0x [class.base.init]p7: 2422 // The initialization of each base and member constitutes a 2423 // full-expression. 2424 BaseInit = MaybeCreateExprWithCleanups(BaseInit); 2425 if (BaseInit.isInvalid()) 2426 return true; 2427 2428 // If we are in a dependent context, template instantiation will 2429 // perform this type-checking again. Just save the arguments that we 2430 // received in a ParenListExpr. 2431 // FIXME: This isn't quite ideal, since our ASTs don't capture all 2432 // of the information that we have about the base 2433 // initializer. However, deconstructing the ASTs is a dicey process, 2434 // and this approach is far more likely to get the corner cases right. 2435 if (CurContext->isDependentContext()) 2436 BaseInit = Owned(Init); 2437 2438 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 2439 BaseSpec->isVirtual(), 2440 InitRange.getBegin(), 2441 BaseInit.takeAs<Expr>(), 2442 InitRange.getEnd(), EllipsisLoc); 2443} 2444 2445// Create a static_cast\<T&&>(expr). 2446static Expr *CastForMoving(Sema &SemaRef, Expr *E) { 2447 QualType ExprType = E->getType(); 2448 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType); 2449 SourceLocation ExprLoc = E->getLocStart(); 2450 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 2451 TargetType, ExprLoc); 2452 2453 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 2454 SourceRange(ExprLoc, ExprLoc), 2455 E->getSourceRange()).take(); 2456} 2457 2458/// ImplicitInitializerKind - How an implicit base or member initializer should 2459/// initialize its base or member. 2460enum ImplicitInitializerKind { 2461 IIK_Default, 2462 IIK_Copy, 2463 IIK_Move 2464}; 2465 2466static bool 2467BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 2468 ImplicitInitializerKind ImplicitInitKind, 2469 CXXBaseSpecifier *BaseSpec, 2470 bool IsInheritedVirtualBase, 2471 CXXCtorInitializer *&CXXBaseInit) { 2472 InitializedEntity InitEntity 2473 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 2474 IsInheritedVirtualBase); 2475 2476 ExprResult BaseInit; 2477 2478 switch (ImplicitInitKind) { 2479 case IIK_Default: { 2480 InitializationKind InitKind 2481 = InitializationKind::CreateDefault(Constructor->getLocation()); 2482 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0); 2483 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, 2484 MultiExprArg(SemaRef, 0, 0)); 2485 break; 2486 } 2487 2488 case IIK_Move: 2489 case IIK_Copy: { 2490 bool Moving = ImplicitInitKind == IIK_Move; 2491 ParmVarDecl *Param = Constructor->getParamDecl(0); 2492 QualType ParamType = Param->getType().getNonReferenceType(); 2493 2494 Expr *CopyCtorArg = 2495 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 2496 SourceLocation(), Param, false, 2497 Constructor->getLocation(), ParamType, 2498 VK_LValue, 0); 2499 2500 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 2501 2502 // Cast to the base class to avoid ambiguities. 2503 QualType ArgTy = 2504 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 2505 ParamType.getQualifiers()); 2506 2507 if (Moving) { 2508 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 2509 } 2510 2511 CXXCastPath BasePath; 2512 BasePath.push_back(BaseSpec); 2513 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 2514 CK_UncheckedDerivedToBase, 2515 Moving ? VK_XValue : VK_LValue, 2516 &BasePath).take(); 2517 2518 InitializationKind InitKind 2519 = InitializationKind::CreateDirect(Constructor->getLocation(), 2520 SourceLocation(), SourceLocation()); 2521 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 2522 &CopyCtorArg, 1); 2523 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, 2524 MultiExprArg(&CopyCtorArg, 1)); 2525 break; 2526 } 2527 } 2528 2529 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 2530 if (BaseInit.isInvalid()) 2531 return true; 2532 2533 CXXBaseInit = 2534 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 2535 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 2536 SourceLocation()), 2537 BaseSpec->isVirtual(), 2538 SourceLocation(), 2539 BaseInit.takeAs<Expr>(), 2540 SourceLocation(), 2541 SourceLocation()); 2542 2543 return false; 2544} 2545 2546static bool RefersToRValueRef(Expr *MemRef) { 2547 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 2548 return Referenced->getType()->isRValueReferenceType(); 2549} 2550 2551static bool 2552BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 2553 ImplicitInitializerKind ImplicitInitKind, 2554 FieldDecl *Field, IndirectFieldDecl *Indirect, 2555 CXXCtorInitializer *&CXXMemberInit) { 2556 if (Field->isInvalidDecl()) 2557 return true; 2558 2559 SourceLocation Loc = Constructor->getLocation(); 2560 2561 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 2562 bool Moving = ImplicitInitKind == IIK_Move; 2563 ParmVarDecl *Param = Constructor->getParamDecl(0); 2564 QualType ParamType = Param->getType().getNonReferenceType(); 2565 2566 // Suppress copying zero-width bitfields. 2567 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0) 2568 return false; 2569 2570 Expr *MemberExprBase = 2571 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 2572 SourceLocation(), Param, false, 2573 Loc, ParamType, VK_LValue, 0); 2574 2575 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 2576 2577 if (Moving) { 2578 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 2579 } 2580 2581 // Build a reference to this field within the parameter. 2582 CXXScopeSpec SS; 2583 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 2584 Sema::LookupMemberName); 2585 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 2586 : cast<ValueDecl>(Field), AS_public); 2587 MemberLookup.resolveKind(); 2588 ExprResult CtorArg 2589 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 2590 ParamType, Loc, 2591 /*IsArrow=*/false, 2592 SS, 2593 /*TemplateKWLoc=*/SourceLocation(), 2594 /*FirstQualifierInScope=*/0, 2595 MemberLookup, 2596 /*TemplateArgs=*/0); 2597 if (CtorArg.isInvalid()) 2598 return true; 2599 2600 // C++11 [class.copy]p15: 2601 // - if a member m has rvalue reference type T&&, it is direct-initialized 2602 // with static_cast<T&&>(x.m); 2603 if (RefersToRValueRef(CtorArg.get())) { 2604 CtorArg = CastForMoving(SemaRef, CtorArg.take()); 2605 } 2606 2607 // When the field we are copying is an array, create index variables for 2608 // each dimension of the array. We use these index variables to subscript 2609 // the source array, and other clients (e.g., CodeGen) will perform the 2610 // necessary iteration with these index variables. 2611 SmallVector<VarDecl *, 4> IndexVariables; 2612 QualType BaseType = Field->getType(); 2613 QualType SizeType = SemaRef.Context.getSizeType(); 2614 bool InitializingArray = false; 2615 while (const ConstantArrayType *Array 2616 = SemaRef.Context.getAsConstantArrayType(BaseType)) { 2617 InitializingArray = true; 2618 // Create the iteration variable for this array index. 2619 IdentifierInfo *IterationVarName = 0; 2620 { 2621 SmallString<8> Str; 2622 llvm::raw_svector_ostream OS(Str); 2623 OS << "__i" << IndexVariables.size(); 2624 IterationVarName = &SemaRef.Context.Idents.get(OS.str()); 2625 } 2626 VarDecl *IterationVar 2627 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc, 2628 IterationVarName, SizeType, 2629 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc), 2630 SC_None, SC_None); 2631 IndexVariables.push_back(IterationVar); 2632 2633 // Create a reference to the iteration variable. 2634 ExprResult IterationVarRef 2635 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 2636 assert(!IterationVarRef.isInvalid() && 2637 "Reference to invented variable cannot fail!"); 2638 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take()); 2639 assert(!IterationVarRef.isInvalid() && 2640 "Conversion of invented variable cannot fail!"); 2641 2642 // Subscript the array with this iteration variable. 2643 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc, 2644 IterationVarRef.take(), 2645 Loc); 2646 if (CtorArg.isInvalid()) 2647 return true; 2648 2649 BaseType = Array->getElementType(); 2650 } 2651 2652 // The array subscript expression is an lvalue, which is wrong for moving. 2653 if (Moving && InitializingArray) 2654 CtorArg = CastForMoving(SemaRef, CtorArg.take()); 2655 2656 // Construct the entity that we will be initializing. For an array, this 2657 // will be first element in the array, which may require several levels 2658 // of array-subscript entities. 2659 SmallVector<InitializedEntity, 4> Entities; 2660 Entities.reserve(1 + IndexVariables.size()); 2661 if (Indirect) 2662 Entities.push_back(InitializedEntity::InitializeMember(Indirect)); 2663 else 2664 Entities.push_back(InitializedEntity::InitializeMember(Field)); 2665 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 2666 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context, 2667 0, 2668 Entities.back())); 2669 2670 // Direct-initialize to use the copy constructor. 2671 InitializationKind InitKind = 2672 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 2673 2674 Expr *CtorArgE = CtorArg.takeAs<Expr>(); 2675 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, 2676 &CtorArgE, 1); 2677 2678 ExprResult MemberInit 2679 = InitSeq.Perform(SemaRef, Entities.back(), InitKind, 2680 MultiExprArg(&CtorArgE, 1)); 2681 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 2682 if (MemberInit.isInvalid()) 2683 return true; 2684 2685 if (Indirect) { 2686 assert(IndexVariables.size() == 0 && 2687 "Indirect field improperly initialized"); 2688 CXXMemberInit 2689 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 2690 Loc, Loc, 2691 MemberInit.takeAs<Expr>(), 2692 Loc); 2693 } else 2694 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, 2695 Loc, MemberInit.takeAs<Expr>(), 2696 Loc, 2697 IndexVariables.data(), 2698 IndexVariables.size()); 2699 return false; 2700 } 2701 2702 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!"); 2703 2704 QualType FieldBaseElementType = 2705 SemaRef.Context.getBaseElementType(Field->getType()); 2706 2707 if (FieldBaseElementType->isRecordType()) { 2708 InitializedEntity InitEntity 2709 = Indirect? InitializedEntity::InitializeMember(Indirect) 2710 : InitializedEntity::InitializeMember(Field); 2711 InitializationKind InitKind = 2712 InitializationKind::CreateDefault(Loc); 2713 2714 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0); 2715 ExprResult MemberInit = 2716 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg()); 2717 2718 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 2719 if (MemberInit.isInvalid()) 2720 return true; 2721 2722 if (Indirect) 2723 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 2724 Indirect, Loc, 2725 Loc, 2726 MemberInit.get(), 2727 Loc); 2728 else 2729 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 2730 Field, Loc, Loc, 2731 MemberInit.get(), 2732 Loc); 2733 return false; 2734 } 2735 2736 if (!Field->getParent()->isUnion()) { 2737 if (FieldBaseElementType->isReferenceType()) { 2738 SemaRef.Diag(Constructor->getLocation(), 2739 diag::err_uninitialized_member_in_ctor) 2740 << (int)Constructor->isImplicit() 2741 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 2742 << 0 << Field->getDeclName(); 2743 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 2744 return true; 2745 } 2746 2747 if (FieldBaseElementType.isConstQualified()) { 2748 SemaRef.Diag(Constructor->getLocation(), 2749 diag::err_uninitialized_member_in_ctor) 2750 << (int)Constructor->isImplicit() 2751 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 2752 << 1 << Field->getDeclName(); 2753 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 2754 return true; 2755 } 2756 } 2757 2758 if (SemaRef.getLangOpts().ObjCAutoRefCount && 2759 FieldBaseElementType->isObjCRetainableType() && 2760 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None && 2761 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) { 2762 // ARC: 2763 // Default-initialize Objective-C pointers to NULL. 2764 CXXMemberInit 2765 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 2766 Loc, Loc, 2767 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 2768 Loc); 2769 return false; 2770 } 2771 2772 // Nothing to initialize. 2773 CXXMemberInit = 0; 2774 return false; 2775} 2776 2777namespace { 2778struct BaseAndFieldInfo { 2779 Sema &S; 2780 CXXConstructorDecl *Ctor; 2781 bool AnyErrorsInInits; 2782 ImplicitInitializerKind IIK; 2783 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 2784 SmallVector<CXXCtorInitializer*, 8> AllToInit; 2785 2786 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 2787 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 2788 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 2789 if (Generated && Ctor->isCopyConstructor()) 2790 IIK = IIK_Copy; 2791 else if (Generated && Ctor->isMoveConstructor()) 2792 IIK = IIK_Move; 2793 else 2794 IIK = IIK_Default; 2795 } 2796 2797 bool isImplicitCopyOrMove() const { 2798 switch (IIK) { 2799 case IIK_Copy: 2800 case IIK_Move: 2801 return true; 2802 2803 case IIK_Default: 2804 return false; 2805 } 2806 2807 llvm_unreachable("Invalid ImplicitInitializerKind!"); 2808 } 2809 2810 bool addFieldInitializer(CXXCtorInitializer *Init) { 2811 AllToInit.push_back(Init); 2812 2813 // Check whether this initializer makes the field "used". 2814 if (Init->getInit() && Init->getInit()->HasSideEffects(S.Context)) 2815 S.UnusedPrivateFields.remove(Init->getAnyMember()); 2816 2817 return false; 2818 } 2819}; 2820} 2821 2822/// \brief Determine whether the given indirect field declaration is somewhere 2823/// within an anonymous union. 2824static bool isWithinAnonymousUnion(IndirectFieldDecl *F) { 2825 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(), 2826 CEnd = F->chain_end(); 2827 C != CEnd; ++C) 2828 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext())) 2829 if (Record->isUnion()) 2830 return true; 2831 2832 return false; 2833} 2834 2835/// \brief Determine whether the given type is an incomplete or zero-lenfgth 2836/// array type. 2837static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 2838 if (T->isIncompleteArrayType()) 2839 return true; 2840 2841 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 2842 if (!ArrayT->getSize()) 2843 return true; 2844 2845 T = ArrayT->getElementType(); 2846 } 2847 2848 return false; 2849} 2850 2851static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 2852 FieldDecl *Field, 2853 IndirectFieldDecl *Indirect = 0) { 2854 2855 // Overwhelmingly common case: we have a direct initializer for this field. 2856 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) 2857 return Info.addFieldInitializer(Init); 2858 2859 // C++11 [class.base.init]p8: if the entity is a non-static data member that 2860 // has a brace-or-equal-initializer, the entity is initialized as specified 2861 // in [dcl.init]. 2862 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 2863 CXXCtorInitializer *Init; 2864 if (Indirect) 2865 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 2866 SourceLocation(), 2867 SourceLocation(), 0, 2868 SourceLocation()); 2869 else 2870 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 2871 SourceLocation(), 2872 SourceLocation(), 0, 2873 SourceLocation()); 2874 return Info.addFieldInitializer(Init); 2875 } 2876 2877 // Don't build an implicit initializer for union members if none was 2878 // explicitly specified. 2879 if (Field->getParent()->isUnion() || 2880 (Indirect && isWithinAnonymousUnion(Indirect))) 2881 return false; 2882 2883 // Don't initialize incomplete or zero-length arrays. 2884 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 2885 return false; 2886 2887 // Don't try to build an implicit initializer if there were semantic 2888 // errors in any of the initializers (and therefore we might be 2889 // missing some that the user actually wrote). 2890 if (Info.AnyErrorsInInits || Field->isInvalidDecl()) 2891 return false; 2892 2893 CXXCtorInitializer *Init = 0; 2894 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 2895 Indirect, Init)) 2896 return true; 2897 2898 if (!Init) 2899 return false; 2900 2901 return Info.addFieldInitializer(Init); 2902} 2903 2904bool 2905Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 2906 CXXCtorInitializer *Initializer) { 2907 assert(Initializer->isDelegatingInitializer()); 2908 Constructor->setNumCtorInitializers(1); 2909 CXXCtorInitializer **initializer = 2910 new (Context) CXXCtorInitializer*[1]; 2911 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 2912 Constructor->setCtorInitializers(initializer); 2913 2914 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 2915 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 2916 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 2917 } 2918 2919 DelegatingCtorDecls.push_back(Constructor); 2920 2921 return false; 2922} 2923 2924bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, 2925 CXXCtorInitializer **Initializers, 2926 unsigned NumInitializers, 2927 bool AnyErrors) { 2928 if (Constructor->isDependentContext()) { 2929 // Just store the initializers as written, they will be checked during 2930 // instantiation. 2931 if (NumInitializers > 0) { 2932 Constructor->setNumCtorInitializers(NumInitializers); 2933 CXXCtorInitializer **baseOrMemberInitializers = 2934 new (Context) CXXCtorInitializer*[NumInitializers]; 2935 memcpy(baseOrMemberInitializers, Initializers, 2936 NumInitializers * sizeof(CXXCtorInitializer*)); 2937 Constructor->setCtorInitializers(baseOrMemberInitializers); 2938 } 2939 2940 return false; 2941 } 2942 2943 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 2944 2945 // We need to build the initializer AST according to order of construction 2946 // and not what user specified in the Initializers list. 2947 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 2948 if (!ClassDecl) 2949 return true; 2950 2951 bool HadError = false; 2952 2953 for (unsigned i = 0; i < NumInitializers; i++) { 2954 CXXCtorInitializer *Member = Initializers[i]; 2955 2956 if (Member->isBaseInitializer()) 2957 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 2958 else 2959 Info.AllBaseFields[Member->getAnyMember()] = Member; 2960 } 2961 2962 // Keep track of the direct virtual bases. 2963 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 2964 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(), 2965 E = ClassDecl->bases_end(); I != E; ++I) { 2966 if (I->isVirtual()) 2967 DirectVBases.insert(I); 2968 } 2969 2970 // Push virtual bases before others. 2971 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 2972 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 2973 2974 if (CXXCtorInitializer *Value 2975 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) { 2976 Info.AllToInit.push_back(Value); 2977 } else if (!AnyErrors) { 2978 bool IsInheritedVirtualBase = !DirectVBases.count(VBase); 2979 CXXCtorInitializer *CXXBaseInit; 2980 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 2981 VBase, IsInheritedVirtualBase, 2982 CXXBaseInit)) { 2983 HadError = true; 2984 continue; 2985 } 2986 2987 Info.AllToInit.push_back(CXXBaseInit); 2988 } 2989 } 2990 2991 // Non-virtual bases. 2992 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 2993 E = ClassDecl->bases_end(); Base != E; ++Base) { 2994 // Virtuals are in the virtual base list and already constructed. 2995 if (Base->isVirtual()) 2996 continue; 2997 2998 if (CXXCtorInitializer *Value 2999 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) { 3000 Info.AllToInit.push_back(Value); 3001 } else if (!AnyErrors) { 3002 CXXCtorInitializer *CXXBaseInit; 3003 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3004 Base, /*IsInheritedVirtualBase=*/false, 3005 CXXBaseInit)) { 3006 HadError = true; 3007 continue; 3008 } 3009 3010 Info.AllToInit.push_back(CXXBaseInit); 3011 } 3012 } 3013 3014 // Fields. 3015 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(), 3016 MemEnd = ClassDecl->decls_end(); 3017 Mem != MemEnd; ++Mem) { 3018 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) { 3019 // C++ [class.bit]p2: 3020 // A declaration for a bit-field that omits the identifier declares an 3021 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 3022 // initialized. 3023 if (F->isUnnamedBitfield()) 3024 continue; 3025 3026 // If we're not generating the implicit copy/move constructor, then we'll 3027 // handle anonymous struct/union fields based on their individual 3028 // indirect fields. 3029 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default) 3030 continue; 3031 3032 if (CollectFieldInitializer(*this, Info, F)) 3033 HadError = true; 3034 continue; 3035 } 3036 3037 // Beyond this point, we only consider default initialization. 3038 if (Info.IIK != IIK_Default) 3039 continue; 3040 3041 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) { 3042 if (F->getType()->isIncompleteArrayType()) { 3043 assert(ClassDecl->hasFlexibleArrayMember() && 3044 "Incomplete array type is not valid"); 3045 continue; 3046 } 3047 3048 // Initialize each field of an anonymous struct individually. 3049 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 3050 HadError = true; 3051 3052 continue; 3053 } 3054 } 3055 3056 NumInitializers = Info.AllToInit.size(); 3057 if (NumInitializers > 0) { 3058 Constructor->setNumCtorInitializers(NumInitializers); 3059 CXXCtorInitializer **baseOrMemberInitializers = 3060 new (Context) CXXCtorInitializer*[NumInitializers]; 3061 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 3062 NumInitializers * sizeof(CXXCtorInitializer*)); 3063 Constructor->setCtorInitializers(baseOrMemberInitializers); 3064 3065 // Constructors implicitly reference the base and member 3066 // destructors. 3067 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 3068 Constructor->getParent()); 3069 } 3070 3071 return HadError; 3072} 3073 3074static void *GetKeyForTopLevelField(FieldDecl *Field) { 3075 // For anonymous unions, use the class declaration as the key. 3076 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 3077 if (RT->getDecl()->isAnonymousStructOrUnion()) 3078 return static_cast<void *>(RT->getDecl()); 3079 } 3080 return static_cast<void *>(Field); 3081} 3082 3083static void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 3084 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr()); 3085} 3086 3087static void *GetKeyForMember(ASTContext &Context, 3088 CXXCtorInitializer *Member) { 3089 if (!Member->isAnyMemberInitializer()) 3090 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 3091 3092 // For fields injected into the class via declaration of an anonymous union, 3093 // use its anonymous union class declaration as the unique key. 3094 FieldDecl *Field = Member->getAnyMember(); 3095 3096 // If the field is a member of an anonymous struct or union, our key 3097 // is the anonymous record decl that's a direct child of the class. 3098 RecordDecl *RD = Field->getParent(); 3099 if (RD->isAnonymousStructOrUnion()) { 3100 while (true) { 3101 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext()); 3102 if (Parent->isAnonymousStructOrUnion()) 3103 RD = Parent; 3104 else 3105 break; 3106 } 3107 3108 return static_cast<void *>(RD); 3109 } 3110 3111 return static_cast<void *>(Field); 3112} 3113 3114static void 3115DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef, 3116 const CXXConstructorDecl *Constructor, 3117 CXXCtorInitializer **Inits, 3118 unsigned NumInits) { 3119 if (Constructor->getDeclContext()->isDependentContext()) 3120 return; 3121 3122 // Don't check initializers order unless the warning is enabled at the 3123 // location of at least one initializer. 3124 bool ShouldCheckOrder = false; 3125 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) { 3126 CXXCtorInitializer *Init = Inits[InitIndex]; 3127 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order, 3128 Init->getSourceLocation()) 3129 != DiagnosticsEngine::Ignored) { 3130 ShouldCheckOrder = true; 3131 break; 3132 } 3133 } 3134 if (!ShouldCheckOrder) 3135 return; 3136 3137 // Build the list of bases and members in the order that they'll 3138 // actually be initialized. The explicit initializers should be in 3139 // this same order but may be missing things. 3140 SmallVector<const void*, 32> IdealInitKeys; 3141 3142 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 3143 3144 // 1. Virtual bases. 3145 for (CXXRecordDecl::base_class_const_iterator VBase = 3146 ClassDecl->vbases_begin(), 3147 E = ClassDecl->vbases_end(); VBase != E; ++VBase) 3148 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType())); 3149 3150 // 2. Non-virtual bases. 3151 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(), 3152 E = ClassDecl->bases_end(); Base != E; ++Base) { 3153 if (Base->isVirtual()) 3154 continue; 3155 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType())); 3156 } 3157 3158 // 3. Direct fields. 3159 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 3160 E = ClassDecl->field_end(); Field != E; ++Field) { 3161 if (Field->isUnnamedBitfield()) 3162 continue; 3163 3164 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field)); 3165 } 3166 3167 unsigned NumIdealInits = IdealInitKeys.size(); 3168 unsigned IdealIndex = 0; 3169 3170 CXXCtorInitializer *PrevInit = 0; 3171 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) { 3172 CXXCtorInitializer *Init = Inits[InitIndex]; 3173 void *InitKey = GetKeyForMember(SemaRef.Context, Init); 3174 3175 // Scan forward to try to find this initializer in the idealized 3176 // initializers list. 3177 for (; IdealIndex != NumIdealInits; ++IdealIndex) 3178 if (InitKey == IdealInitKeys[IdealIndex]) 3179 break; 3180 3181 // If we didn't find this initializer, it must be because we 3182 // scanned past it on a previous iteration. That can only 3183 // happen if we're out of order; emit a warning. 3184 if (IdealIndex == NumIdealInits && PrevInit) { 3185 Sema::SemaDiagnosticBuilder D = 3186 SemaRef.Diag(PrevInit->getSourceLocation(), 3187 diag::warn_initializer_out_of_order); 3188 3189 if (PrevInit->isAnyMemberInitializer()) 3190 D << 0 << PrevInit->getAnyMember()->getDeclName(); 3191 else 3192 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 3193 3194 if (Init->isAnyMemberInitializer()) 3195 D << 0 << Init->getAnyMember()->getDeclName(); 3196 else 3197 D << 1 << Init->getTypeSourceInfo()->getType(); 3198 3199 // Move back to the initializer's location in the ideal list. 3200 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 3201 if (InitKey == IdealInitKeys[IdealIndex]) 3202 break; 3203 3204 assert(IdealIndex != NumIdealInits && 3205 "initializer not found in initializer list"); 3206 } 3207 3208 PrevInit = Init; 3209 } 3210} 3211 3212namespace { 3213bool CheckRedundantInit(Sema &S, 3214 CXXCtorInitializer *Init, 3215 CXXCtorInitializer *&PrevInit) { 3216 if (!PrevInit) { 3217 PrevInit = Init; 3218 return false; 3219 } 3220 3221 if (FieldDecl *Field = Init->getMember()) 3222 S.Diag(Init->getSourceLocation(), 3223 diag::err_multiple_mem_initialization) 3224 << Field->getDeclName() 3225 << Init->getSourceRange(); 3226 else { 3227 const Type *BaseClass = Init->getBaseClass(); 3228 assert(BaseClass && "neither field nor base"); 3229 S.Diag(Init->getSourceLocation(), 3230 diag::err_multiple_base_initialization) 3231 << QualType(BaseClass, 0) 3232 << Init->getSourceRange(); 3233 } 3234 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 3235 << 0 << PrevInit->getSourceRange(); 3236 3237 return true; 3238} 3239 3240typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 3241typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 3242 3243bool CheckRedundantUnionInit(Sema &S, 3244 CXXCtorInitializer *Init, 3245 RedundantUnionMap &Unions) { 3246 FieldDecl *Field = Init->getAnyMember(); 3247 RecordDecl *Parent = Field->getParent(); 3248 NamedDecl *Child = Field; 3249 3250 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 3251 if (Parent->isUnion()) { 3252 UnionEntry &En = Unions[Parent]; 3253 if (En.first && En.first != Child) { 3254 S.Diag(Init->getSourceLocation(), 3255 diag::err_multiple_mem_union_initialization) 3256 << Field->getDeclName() 3257 << Init->getSourceRange(); 3258 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 3259 << 0 << En.second->getSourceRange(); 3260 return true; 3261 } 3262 if (!En.first) { 3263 En.first = Child; 3264 En.second = Init; 3265 } 3266 if (!Parent->isAnonymousStructOrUnion()) 3267 return false; 3268 } 3269 3270 Child = Parent; 3271 Parent = cast<RecordDecl>(Parent->getDeclContext()); 3272 } 3273 3274 return false; 3275} 3276} 3277 3278/// ActOnMemInitializers - Handle the member initializers for a constructor. 3279void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 3280 SourceLocation ColonLoc, 3281 CXXCtorInitializer **meminits, 3282 unsigned NumMemInits, 3283 bool AnyErrors) { 3284 if (!ConstructorDecl) 3285 return; 3286 3287 AdjustDeclIfTemplate(ConstructorDecl); 3288 3289 CXXConstructorDecl *Constructor 3290 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 3291 3292 if (!Constructor) { 3293 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 3294 return; 3295 } 3296 3297 CXXCtorInitializer **MemInits = 3298 reinterpret_cast<CXXCtorInitializer **>(meminits); 3299 3300 // Mapping for the duplicate initializers check. 3301 // For member initializers, this is keyed with a FieldDecl*. 3302 // For base initializers, this is keyed with a Type*. 3303 llvm::DenseMap<void*, CXXCtorInitializer *> Members; 3304 3305 // Mapping for the inconsistent anonymous-union initializers check. 3306 RedundantUnionMap MemberUnions; 3307 3308 bool HadError = false; 3309 for (unsigned i = 0; i < NumMemInits; i++) { 3310 CXXCtorInitializer *Init = MemInits[i]; 3311 3312 // Set the source order index. 3313 Init->setSourceOrder(i); 3314 3315 if (Init->isAnyMemberInitializer()) { 3316 FieldDecl *Field = Init->getAnyMember(); 3317 if (CheckRedundantInit(*this, Init, Members[Field]) || 3318 CheckRedundantUnionInit(*this, Init, MemberUnions)) 3319 HadError = true; 3320 } else if (Init->isBaseInitializer()) { 3321 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0)); 3322 if (CheckRedundantInit(*this, Init, Members[Key])) 3323 HadError = true; 3324 } else { 3325 assert(Init->isDelegatingInitializer()); 3326 // This must be the only initializer 3327 if (i != 0 || NumMemInits > 1) { 3328 Diag(MemInits[0]->getSourceLocation(), 3329 diag::err_delegating_initializer_alone) 3330 << MemInits[0]->getSourceRange(); 3331 HadError = true; 3332 // We will treat this as being the only initializer. 3333 } 3334 SetDelegatingInitializer(Constructor, MemInits[i]); 3335 // Return immediately as the initializer is set. 3336 return; 3337 } 3338 } 3339 3340 if (HadError) 3341 return; 3342 3343 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits); 3344 3345 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors); 3346} 3347 3348void 3349Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 3350 CXXRecordDecl *ClassDecl) { 3351 // Ignore dependent contexts. Also ignore unions, since their members never 3352 // have destructors implicitly called. 3353 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 3354 return; 3355 3356 // FIXME: all the access-control diagnostics are positioned on the 3357 // field/base declaration. That's probably good; that said, the 3358 // user might reasonably want to know why the destructor is being 3359 // emitted, and we currently don't say. 3360 3361 // Non-static data members. 3362 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(), 3363 E = ClassDecl->field_end(); I != E; ++I) { 3364 FieldDecl *Field = *I; 3365 if (Field->isInvalidDecl()) 3366 continue; 3367 3368 // Don't destroy incomplete or zero-length arrays. 3369 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 3370 continue; 3371 3372 QualType FieldType = Context.getBaseElementType(Field->getType()); 3373 3374 const RecordType* RT = FieldType->getAs<RecordType>(); 3375 if (!RT) 3376 continue; 3377 3378 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3379 if (FieldClassDecl->isInvalidDecl()) 3380 continue; 3381 if (FieldClassDecl->hasIrrelevantDestructor()) 3382 continue; 3383 // The destructor for an implicit anonymous union member is never invoked. 3384 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 3385 continue; 3386 3387 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 3388 assert(Dtor && "No dtor found for FieldClassDecl!"); 3389 CheckDestructorAccess(Field->getLocation(), Dtor, 3390 PDiag(diag::err_access_dtor_field) 3391 << Field->getDeclName() 3392 << FieldType); 3393 3394 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 3395 DiagnoseUseOfDecl(Dtor, Location); 3396 } 3397 3398 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 3399 3400 // Bases. 3401 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 3402 E = ClassDecl->bases_end(); Base != E; ++Base) { 3403 // Bases are always records in a well-formed non-dependent class. 3404 const RecordType *RT = Base->getType()->getAs<RecordType>(); 3405 3406 // Remember direct virtual bases. 3407 if (Base->isVirtual()) 3408 DirectVirtualBases.insert(RT); 3409 3410 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3411 // If our base class is invalid, we probably can't get its dtor anyway. 3412 if (BaseClassDecl->isInvalidDecl()) 3413 continue; 3414 if (BaseClassDecl->hasIrrelevantDestructor()) 3415 continue; 3416 3417 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 3418 assert(Dtor && "No dtor found for BaseClassDecl!"); 3419 3420 // FIXME: caret should be on the start of the class name 3421 CheckDestructorAccess(Base->getLocStart(), Dtor, 3422 PDiag(diag::err_access_dtor_base) 3423 << Base->getType() 3424 << Base->getSourceRange(), 3425 Context.getTypeDeclType(ClassDecl)); 3426 3427 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 3428 DiagnoseUseOfDecl(Dtor, Location); 3429 } 3430 3431 // Virtual bases. 3432 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 3433 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 3434 3435 // Bases are always records in a well-formed non-dependent class. 3436 const RecordType *RT = VBase->getType()->castAs<RecordType>(); 3437 3438 // Ignore direct virtual bases. 3439 if (DirectVirtualBases.count(RT)) 3440 continue; 3441 3442 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3443 // If our base class is invalid, we probably can't get its dtor anyway. 3444 if (BaseClassDecl->isInvalidDecl()) 3445 continue; 3446 if (BaseClassDecl->hasIrrelevantDestructor()) 3447 continue; 3448 3449 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 3450 assert(Dtor && "No dtor found for BaseClassDecl!"); 3451 CheckDestructorAccess(ClassDecl->getLocation(), Dtor, 3452 PDiag(diag::err_access_dtor_vbase) 3453 << VBase->getType(), 3454 Context.getTypeDeclType(ClassDecl)); 3455 3456 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 3457 DiagnoseUseOfDecl(Dtor, Location); 3458 } 3459} 3460 3461void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 3462 if (!CDtorDecl) 3463 return; 3464 3465 if (CXXConstructorDecl *Constructor 3466 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) 3467 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false); 3468} 3469 3470bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 3471 unsigned DiagID, AbstractDiagSelID SelID) { 3472 class NonAbstractTypeDiagnoser : public TypeDiagnoser { 3473 unsigned DiagID; 3474 AbstractDiagSelID SelID; 3475 3476 public: 3477 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID) 3478 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { } 3479 3480 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 3481 if (Suppressed) return; 3482 if (SelID == -1) 3483 S.Diag(Loc, DiagID) << T; 3484 else 3485 S.Diag(Loc, DiagID) << SelID << T; 3486 } 3487 } Diagnoser(DiagID, SelID); 3488 3489 return RequireNonAbstractType(Loc, T, Diagnoser); 3490} 3491 3492bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 3493 TypeDiagnoser &Diagnoser) { 3494 if (!getLangOpts().CPlusPlus) 3495 return false; 3496 3497 if (const ArrayType *AT = Context.getAsArrayType(T)) 3498 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 3499 3500 if (const PointerType *PT = T->getAs<PointerType>()) { 3501 // Find the innermost pointer type. 3502 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 3503 PT = T; 3504 3505 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 3506 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 3507 } 3508 3509 const RecordType *RT = T->getAs<RecordType>(); 3510 if (!RT) 3511 return false; 3512 3513 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 3514 3515 // We can't answer whether something is abstract until it has a 3516 // definition. If it's currently being defined, we'll walk back 3517 // over all the declarations when we have a full definition. 3518 const CXXRecordDecl *Def = RD->getDefinition(); 3519 if (!Def || Def->isBeingDefined()) 3520 return false; 3521 3522 if (!RD->isAbstract()) 3523 return false; 3524 3525 Diagnoser.diagnose(*this, Loc, T); 3526 DiagnoseAbstractType(RD); 3527 3528 return true; 3529} 3530 3531void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 3532 // Check if we've already emitted the list of pure virtual functions 3533 // for this class. 3534 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 3535 return; 3536 3537 CXXFinalOverriderMap FinalOverriders; 3538 RD->getFinalOverriders(FinalOverriders); 3539 3540 // Keep a set of seen pure methods so we won't diagnose the same method 3541 // more than once. 3542 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 3543 3544 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 3545 MEnd = FinalOverriders.end(); 3546 M != MEnd; 3547 ++M) { 3548 for (OverridingMethods::iterator SO = M->second.begin(), 3549 SOEnd = M->second.end(); 3550 SO != SOEnd; ++SO) { 3551 // C++ [class.abstract]p4: 3552 // A class is abstract if it contains or inherits at least one 3553 // pure virtual function for which the final overrider is pure 3554 // virtual. 3555 3556 // 3557 if (SO->second.size() != 1) 3558 continue; 3559 3560 if (!SO->second.front().Method->isPure()) 3561 continue; 3562 3563 if (!SeenPureMethods.insert(SO->second.front().Method)) 3564 continue; 3565 3566 Diag(SO->second.front().Method->getLocation(), 3567 diag::note_pure_virtual_function) 3568 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 3569 } 3570 } 3571 3572 if (!PureVirtualClassDiagSet) 3573 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 3574 PureVirtualClassDiagSet->insert(RD); 3575} 3576 3577namespace { 3578struct AbstractUsageInfo { 3579 Sema &S; 3580 CXXRecordDecl *Record; 3581 CanQualType AbstractType; 3582 bool Invalid; 3583 3584 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 3585 : S(S), Record(Record), 3586 AbstractType(S.Context.getCanonicalType( 3587 S.Context.getTypeDeclType(Record))), 3588 Invalid(false) {} 3589 3590 void DiagnoseAbstractType() { 3591 if (Invalid) return; 3592 S.DiagnoseAbstractType(Record); 3593 Invalid = true; 3594 } 3595 3596 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 3597}; 3598 3599struct CheckAbstractUsage { 3600 AbstractUsageInfo &Info; 3601 const NamedDecl *Ctx; 3602 3603 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 3604 : Info(Info), Ctx(Ctx) {} 3605 3606 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 3607 switch (TL.getTypeLocClass()) { 3608#define ABSTRACT_TYPELOC(CLASS, PARENT) 3609#define TYPELOC(CLASS, PARENT) \ 3610 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break; 3611#include "clang/AST/TypeLocNodes.def" 3612 } 3613 } 3614 3615 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 3616 Visit(TL.getResultLoc(), Sema::AbstractReturnType); 3617 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 3618 if (!TL.getArg(I)) 3619 continue; 3620 3621 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo(); 3622 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 3623 } 3624 } 3625 3626 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 3627 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 3628 } 3629 3630 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 3631 // Visit the type parameters from a permissive context. 3632 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 3633 TemplateArgumentLoc TAL = TL.getArgLoc(I); 3634 if (TAL.getArgument().getKind() == TemplateArgument::Type) 3635 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 3636 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 3637 // TODO: other template argument types? 3638 } 3639 } 3640 3641 // Visit pointee types from a permissive context. 3642#define CheckPolymorphic(Type) \ 3643 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 3644 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 3645 } 3646 CheckPolymorphic(PointerTypeLoc) 3647 CheckPolymorphic(ReferenceTypeLoc) 3648 CheckPolymorphic(MemberPointerTypeLoc) 3649 CheckPolymorphic(BlockPointerTypeLoc) 3650 CheckPolymorphic(AtomicTypeLoc) 3651 3652 /// Handle all the types we haven't given a more specific 3653 /// implementation for above. 3654 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 3655 // Every other kind of type that we haven't called out already 3656 // that has an inner type is either (1) sugar or (2) contains that 3657 // inner type in some way as a subobject. 3658 if (TypeLoc Next = TL.getNextTypeLoc()) 3659 return Visit(Next, Sel); 3660 3661 // If there's no inner type and we're in a permissive context, 3662 // don't diagnose. 3663 if (Sel == Sema::AbstractNone) return; 3664 3665 // Check whether the type matches the abstract type. 3666 QualType T = TL.getType(); 3667 if (T->isArrayType()) { 3668 Sel = Sema::AbstractArrayType; 3669 T = Info.S.Context.getBaseElementType(T); 3670 } 3671 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 3672 if (CT != Info.AbstractType) return; 3673 3674 // It matched; do some magic. 3675 if (Sel == Sema::AbstractArrayType) { 3676 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 3677 << T << TL.getSourceRange(); 3678 } else { 3679 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 3680 << Sel << T << TL.getSourceRange(); 3681 } 3682 Info.DiagnoseAbstractType(); 3683 } 3684}; 3685 3686void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 3687 Sema::AbstractDiagSelID Sel) { 3688 CheckAbstractUsage(*this, D).Visit(TL, Sel); 3689} 3690 3691} 3692 3693/// Check for invalid uses of an abstract type in a method declaration. 3694static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 3695 CXXMethodDecl *MD) { 3696 // No need to do the check on definitions, which require that 3697 // the return/param types be complete. 3698 if (MD->doesThisDeclarationHaveABody()) 3699 return; 3700 3701 // For safety's sake, just ignore it if we don't have type source 3702 // information. This should never happen for non-implicit methods, 3703 // but... 3704 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 3705 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 3706} 3707 3708/// Check for invalid uses of an abstract type within a class definition. 3709static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 3710 CXXRecordDecl *RD) { 3711 for (CXXRecordDecl::decl_iterator 3712 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) { 3713 Decl *D = *I; 3714 if (D->isImplicit()) continue; 3715 3716 // Methods and method templates. 3717 if (isa<CXXMethodDecl>(D)) { 3718 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 3719 } else if (isa<FunctionTemplateDecl>(D)) { 3720 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 3721 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 3722 3723 // Fields and static variables. 3724 } else if (isa<FieldDecl>(D)) { 3725 FieldDecl *FD = cast<FieldDecl>(D); 3726 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 3727 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 3728 } else if (isa<VarDecl>(D)) { 3729 VarDecl *VD = cast<VarDecl>(D); 3730 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 3731 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 3732 3733 // Nested classes and class templates. 3734 } else if (isa<CXXRecordDecl>(D)) { 3735 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 3736 } else if (isa<ClassTemplateDecl>(D)) { 3737 CheckAbstractClassUsage(Info, 3738 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 3739 } 3740 } 3741} 3742 3743/// \brief Perform semantic checks on a class definition that has been 3744/// completing, introducing implicitly-declared members, checking for 3745/// abstract types, etc. 3746void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 3747 if (!Record) 3748 return; 3749 3750 if (Record->isAbstract() && !Record->isInvalidDecl()) { 3751 AbstractUsageInfo Info(*this, Record); 3752 CheckAbstractClassUsage(Info, Record); 3753 } 3754 3755 // If this is not an aggregate type and has no user-declared constructor, 3756 // complain about any non-static data members of reference or const scalar 3757 // type, since they will never get initializers. 3758 if (!Record->isInvalidDecl() && !Record->isDependentType() && 3759 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 3760 !Record->isLambda()) { 3761 bool Complained = false; 3762 for (RecordDecl::field_iterator F = Record->field_begin(), 3763 FEnd = Record->field_end(); 3764 F != FEnd; ++F) { 3765 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 3766 continue; 3767 3768 if (F->getType()->isReferenceType() || 3769 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 3770 if (!Complained) { 3771 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 3772 << Record->getTagKind() << Record; 3773 Complained = true; 3774 } 3775 3776 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 3777 << F->getType()->isReferenceType() 3778 << F->getDeclName(); 3779 } 3780 } 3781 } 3782 3783 if (Record->isDynamicClass() && !Record->isDependentType()) 3784 DynamicClasses.push_back(Record); 3785 3786 if (Record->getIdentifier()) { 3787 // C++ [class.mem]p13: 3788 // If T is the name of a class, then each of the following shall have a 3789 // name different from T: 3790 // - every member of every anonymous union that is a member of class T. 3791 // 3792 // C++ [class.mem]p14: 3793 // In addition, if class T has a user-declared constructor (12.1), every 3794 // non-static data member of class T shall have a name different from T. 3795 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 3796 R.first != R.second; ++R.first) { 3797 NamedDecl *D = *R.first; 3798 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 3799 isa<IndirectFieldDecl>(D)) { 3800 Diag(D->getLocation(), diag::err_member_name_of_class) 3801 << D->getDeclName(); 3802 break; 3803 } 3804 } 3805 } 3806 3807 // Warn if the class has virtual methods but non-virtual public destructor. 3808 if (Record->isPolymorphic() && !Record->isDependentType()) { 3809 CXXDestructorDecl *dtor = Record->getDestructor(); 3810 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) 3811 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 3812 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 3813 } 3814 3815 // See if a method overloads virtual methods in a base 3816 /// class without overriding any. 3817 if (!Record->isDependentType()) { 3818 for (CXXRecordDecl::method_iterator M = Record->method_begin(), 3819 MEnd = Record->method_end(); 3820 M != MEnd; ++M) { 3821 if (!M->isStatic()) 3822 DiagnoseHiddenVirtualMethods(Record, *M); 3823 } 3824 } 3825 3826 // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member 3827 // function that is not a constructor declares that member function to be 3828 // const. [...] The class of which that function is a member shall be 3829 // a literal type. 3830 // 3831 // If the class has virtual bases, any constexpr members will already have 3832 // been diagnosed by the checks performed on the member declaration, so 3833 // suppress this (less useful) diagnostic. 3834 if (LangOpts.CPlusPlus0x && !Record->isDependentType() && 3835 !Record->isLiteral() && !Record->getNumVBases()) { 3836 for (CXXRecordDecl::method_iterator M = Record->method_begin(), 3837 MEnd = Record->method_end(); 3838 M != MEnd; ++M) { 3839 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) { 3840 switch (Record->getTemplateSpecializationKind()) { 3841 case TSK_ImplicitInstantiation: 3842 case TSK_ExplicitInstantiationDeclaration: 3843 case TSK_ExplicitInstantiationDefinition: 3844 // If a template instantiates to a non-literal type, but its members 3845 // instantiate to constexpr functions, the template is technically 3846 // ill-formed, but we allow it for sanity. 3847 continue; 3848 3849 case TSK_Undeclared: 3850 case TSK_ExplicitSpecialization: 3851 RequireLiteralType(M->getLocation(), Context.getRecordType(Record), 3852 diag::err_constexpr_method_non_literal); 3853 break; 3854 } 3855 3856 // Only produce one error per class. 3857 break; 3858 } 3859 } 3860 } 3861 3862 // Declare inherited constructors. We do this eagerly here because: 3863 // - The standard requires an eager diagnostic for conflicting inherited 3864 // constructors from different classes. 3865 // - The lazy declaration of the other implicit constructors is so as to not 3866 // waste space and performance on classes that are not meant to be 3867 // instantiated (e.g. meta-functions). This doesn't apply to classes that 3868 // have inherited constructors. 3869 DeclareInheritedConstructors(Record); 3870} 3871 3872void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) { 3873 for (CXXRecordDecl::method_iterator MI = Record->method_begin(), 3874 ME = Record->method_end(); 3875 MI != ME; ++MI) 3876 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) 3877 CheckExplicitlyDefaultedSpecialMember(*MI); 3878} 3879 3880/// Is the special member function which would be selected to perform the 3881/// specified operation on the specified class type a constexpr constructor? 3882static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 3883 Sema::CXXSpecialMember CSM, 3884 bool ConstArg) { 3885 Sema::SpecialMemberOverloadResult *SMOR = 3886 S.LookupSpecialMember(ClassDecl, CSM, ConstArg, 3887 false, false, false, false); 3888 if (!SMOR || !SMOR->getMethod()) 3889 // A constructor we wouldn't select can't be "involved in initializing" 3890 // anything. 3891 return true; 3892 return SMOR->getMethod()->isConstexpr(); 3893} 3894 3895/// Determine whether the specified special member function would be constexpr 3896/// if it were implicitly defined. 3897static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 3898 Sema::CXXSpecialMember CSM, 3899 bool ConstArg) { 3900 if (!S.getLangOpts().CPlusPlus0x) 3901 return false; 3902 3903 // C++11 [dcl.constexpr]p4: 3904 // In the definition of a constexpr constructor [...] 3905 switch (CSM) { 3906 case Sema::CXXDefaultConstructor: 3907 // Since default constructor lookup is essentially trivial (and cannot 3908 // involve, for instance, template instantiation), we compute whether a 3909 // defaulted default constructor is constexpr directly within CXXRecordDecl. 3910 // 3911 // This is important for performance; we need to know whether the default 3912 // constructor is constexpr to determine whether the type is a literal type. 3913 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 3914 3915 case Sema::CXXCopyConstructor: 3916 case Sema::CXXMoveConstructor: 3917 // For copy or move constructors, we need to perform overload resolution. 3918 break; 3919 3920 case Sema::CXXCopyAssignment: 3921 case Sema::CXXMoveAssignment: 3922 case Sema::CXXDestructor: 3923 case Sema::CXXInvalid: 3924 return false; 3925 } 3926 3927 // -- if the class is a non-empty union, or for each non-empty anonymous 3928 // union member of a non-union class, exactly one non-static data member 3929 // shall be initialized; [DR1359] 3930 // 3931 // If we squint, this is guaranteed, since exactly one non-static data member 3932 // will be initialized (if the constructor isn't deleted), we just don't know 3933 // which one. 3934 if (ClassDecl->isUnion()) 3935 return true; 3936 3937 // -- the class shall not have any virtual base classes; 3938 if (ClassDecl->getNumVBases()) 3939 return false; 3940 3941 // -- every constructor involved in initializing [...] base class 3942 // sub-objects shall be a constexpr constructor; 3943 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 3944 BEnd = ClassDecl->bases_end(); 3945 B != BEnd; ++B) { 3946 const RecordType *BaseType = B->getType()->getAs<RecordType>(); 3947 if (!BaseType) continue; 3948 3949 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 3950 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg)) 3951 return false; 3952 } 3953 3954 // -- every constructor involved in initializing non-static data members 3955 // [...] shall be a constexpr constructor; 3956 // -- every non-static data member and base class sub-object shall be 3957 // initialized 3958 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 3959 FEnd = ClassDecl->field_end(); 3960 F != FEnd; ++F) { 3961 if (F->isInvalidDecl()) 3962 continue; 3963 if (const RecordType *RecordTy = 3964 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 3965 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 3966 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg)) 3967 return false; 3968 } 3969 } 3970 3971 // All OK, it's constexpr! 3972 return true; 3973} 3974 3975static Sema::ImplicitExceptionSpecification 3976computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 3977 switch (S.getSpecialMember(MD)) { 3978 case Sema::CXXDefaultConstructor: 3979 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD); 3980 case Sema::CXXCopyConstructor: 3981 return S.ComputeDefaultedCopyCtorExceptionSpec(MD); 3982 case Sema::CXXCopyAssignment: 3983 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD); 3984 case Sema::CXXMoveConstructor: 3985 return S.ComputeDefaultedMoveCtorExceptionSpec(MD); 3986 case Sema::CXXMoveAssignment: 3987 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD); 3988 case Sema::CXXDestructor: 3989 return S.ComputeDefaultedDtorExceptionSpec(MD); 3990 case Sema::CXXInvalid: 3991 break; 3992 } 3993 llvm_unreachable("only special members have implicit exception specs"); 3994} 3995 3996static void 3997updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT, 3998 const Sema::ImplicitExceptionSpecification &ExceptSpec) { 3999 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 4000 ExceptSpec.getEPI(EPI); 4001 const FunctionProtoType *NewFPT = cast<FunctionProtoType>( 4002 S.Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(), 4003 FPT->getNumArgs(), EPI)); 4004 FD->setType(QualType(NewFPT, 0)); 4005} 4006 4007void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 4008 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 4009 if (FPT->getExceptionSpecType() != EST_Unevaluated) 4010 return; 4011 4012 // Evaluate the exception specification. 4013 ImplicitExceptionSpecification ExceptSpec = 4014 computeImplicitExceptionSpec(*this, Loc, MD); 4015 4016 // Update the type of the special member to use it. 4017 updateExceptionSpec(*this, MD, FPT, ExceptSpec); 4018 4019 // A user-provided destructor can be defined outside the class. When that 4020 // happens, be sure to update the exception specification on both 4021 // declarations. 4022 const FunctionProtoType *CanonicalFPT = 4023 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 4024 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 4025 updateExceptionSpec(*this, MD->getCanonicalDecl(), 4026 CanonicalFPT, ExceptSpec); 4027} 4028 4029static bool isImplicitCopyCtorArgConst(Sema &S, CXXRecordDecl *ClassDecl); 4030static bool isImplicitCopyAssignmentArgConst(Sema &S, CXXRecordDecl *ClassDecl); 4031 4032void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 4033 CXXRecordDecl *RD = MD->getParent(); 4034 CXXSpecialMember CSM = getSpecialMember(MD); 4035 4036 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 4037 "not an explicitly-defaulted special member"); 4038 4039 // Whether this was the first-declared instance of the constructor. 4040 // This affects whether we implicitly add an exception spec and constexpr. 4041 bool First = MD == MD->getCanonicalDecl(); 4042 4043 bool HadError = false; 4044 4045 // C++11 [dcl.fct.def.default]p1: 4046 // A function that is explicitly defaulted shall 4047 // -- be a special member function (checked elsewhere), 4048 // -- have the same type (except for ref-qualifiers, and except that a 4049 // copy operation can take a non-const reference) as an implicit 4050 // declaration, and 4051 // -- not have default arguments. 4052 unsigned ExpectedParams = 1; 4053 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 4054 ExpectedParams = 0; 4055 if (MD->getNumParams() != ExpectedParams) { 4056 // This also checks for default arguments: a copy or move constructor with a 4057 // default argument is classified as a default constructor, and assignment 4058 // operations and destructors can't have default arguments. 4059 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 4060 << CSM << MD->getSourceRange(); 4061 HadError = true; 4062 } 4063 4064 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 4065 4066 // Compute argument constness, constexpr, and triviality. 4067 bool CanHaveConstParam = false; 4068 bool Trivial; 4069 switch (CSM) { 4070 case CXXDefaultConstructor: 4071 Trivial = RD->hasTrivialDefaultConstructor(); 4072 break; 4073 case CXXCopyConstructor: 4074 CanHaveConstParam = isImplicitCopyCtorArgConst(*this, RD); 4075 Trivial = RD->hasTrivialCopyConstructor(); 4076 break; 4077 case CXXCopyAssignment: 4078 CanHaveConstParam = isImplicitCopyAssignmentArgConst(*this, RD); 4079 Trivial = RD->hasTrivialCopyAssignment(); 4080 break; 4081 case CXXMoveConstructor: 4082 Trivial = RD->hasTrivialMoveConstructor(); 4083 break; 4084 case CXXMoveAssignment: 4085 Trivial = RD->hasTrivialMoveAssignment(); 4086 break; 4087 case CXXDestructor: 4088 Trivial = RD->hasTrivialDestructor(); 4089 break; 4090 case CXXInvalid: 4091 llvm_unreachable("non-special member explicitly defaulted!"); 4092 } 4093 4094 QualType ReturnType = Context.VoidTy; 4095 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 4096 // Check for return type matching. 4097 ReturnType = Type->getResultType(); 4098 QualType ExpectedReturnType = 4099 Context.getLValueReferenceType(Context.getTypeDeclType(RD)); 4100 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 4101 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 4102 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 4103 HadError = true; 4104 } 4105 4106 // A defaulted special member cannot have cv-qualifiers. 4107 if (Type->getTypeQuals()) { 4108 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 4109 << (CSM == CXXMoveAssignment); 4110 HadError = true; 4111 } 4112 } 4113 4114 // Check for parameter type matching. 4115 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType(); 4116 bool HasConstParam = false; 4117 if (ExpectedParams && ArgType->isReferenceType()) { 4118 // Argument must be reference to possibly-const T. 4119 QualType ReferentType = ArgType->getPointeeType(); 4120 HasConstParam = ReferentType.isConstQualified(); 4121 4122 if (ReferentType.isVolatileQualified()) { 4123 Diag(MD->getLocation(), 4124 diag::err_defaulted_special_member_volatile_param) << CSM; 4125 HadError = true; 4126 } 4127 4128 if (HasConstParam && !CanHaveConstParam) { 4129 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 4130 Diag(MD->getLocation(), 4131 diag::err_defaulted_special_member_copy_const_param) 4132 << (CSM == CXXCopyAssignment); 4133 // FIXME: Explain why this special member can't be const. 4134 } else { 4135 Diag(MD->getLocation(), 4136 diag::err_defaulted_special_member_move_const_param) 4137 << (CSM == CXXMoveAssignment); 4138 } 4139 HadError = true; 4140 } 4141 4142 // If a function is explicitly defaulted on its first declaration, it shall 4143 // have the same parameter type as if it had been implicitly declared. 4144 // (Presumably this is to prevent it from being trivial?) 4145 if (!HasConstParam && CanHaveConstParam && First) 4146 Diag(MD->getLocation(), 4147 diag::err_defaulted_special_member_copy_non_const_param) 4148 << (CSM == CXXCopyAssignment); 4149 } else if (ExpectedParams) { 4150 // A copy assignment operator can take its argument by value, but a 4151 // defaulted one cannot. 4152 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 4153 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 4154 HadError = true; 4155 } 4156 4157 // Rebuild the type with the implicit exception specification added, if we 4158 // are going to need it. 4159 const FunctionProtoType *ImplicitType = 0; 4160 if (First || Type->hasExceptionSpec()) { 4161 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 4162 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI); 4163 ImplicitType = cast<FunctionProtoType>( 4164 Context.getFunctionType(ReturnType, &ArgType, ExpectedParams, EPI)); 4165 } 4166 4167 // C++11 [dcl.fct.def.default]p2: 4168 // An explicitly-defaulted function may be declared constexpr only if it 4169 // would have been implicitly declared as constexpr, 4170 // Do not apply this rule to members of class templates, since core issue 1358 4171 // makes such functions always instantiate to constexpr functions. For 4172 // non-constructors, this is checked elsewhere. 4173 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 4174 HasConstParam); 4175 if (isa<CXXConstructorDecl>(MD) && MD->isConstexpr() && !Constexpr && 4176 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 4177 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM; 4178 // FIXME: Explain why the constructor can't be constexpr. 4179 HadError = true; 4180 } 4181 // and may have an explicit exception-specification only if it is compatible 4182 // with the exception-specification on the implicit declaration. 4183 if (Type->hasExceptionSpec() && 4184 CheckEquivalentExceptionSpec( 4185 PDiag(diag::err_incorrect_defaulted_exception_spec) << CSM, 4186 PDiag(), ImplicitType, SourceLocation(), Type, MD->getLocation())) 4187 HadError = true; 4188 4189 // If a function is explicitly defaulted on its first declaration, 4190 if (First) { 4191 // -- it is implicitly considered to be constexpr if the implicit 4192 // definition would be, 4193 MD->setConstexpr(Constexpr); 4194 4195 // -- it is implicitly considered to have the same exception-specification 4196 // as if it had been implicitly declared, 4197 MD->setType(QualType(ImplicitType, 0)); 4198 4199 // Such a function is also trivial if the implicitly-declared function 4200 // would have been. 4201 MD->setTrivial(Trivial); 4202 } 4203 4204 if (ShouldDeleteSpecialMember(MD, CSM)) { 4205 if (First) { 4206 MD->setDeletedAsWritten(); 4207 } else { 4208 // C++11 [dcl.fct.def.default]p4: 4209 // [For a] user-provided explicitly-defaulted function [...] if such a 4210 // function is implicitly defined as deleted, the program is ill-formed. 4211 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 4212 HadError = true; 4213 } 4214 } 4215 4216 if (HadError) 4217 MD->setInvalidDecl(); 4218} 4219 4220namespace { 4221struct SpecialMemberDeletionInfo { 4222 Sema &S; 4223 CXXMethodDecl *MD; 4224 Sema::CXXSpecialMember CSM; 4225 bool Diagnose; 4226 4227 // Properties of the special member, computed for convenience. 4228 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg; 4229 SourceLocation Loc; 4230 4231 bool AllFieldsAreConst; 4232 4233 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 4234 Sema::CXXSpecialMember CSM, bool Diagnose) 4235 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose), 4236 IsConstructor(false), IsAssignment(false), IsMove(false), 4237 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()), 4238 AllFieldsAreConst(true) { 4239 switch (CSM) { 4240 case Sema::CXXDefaultConstructor: 4241 case Sema::CXXCopyConstructor: 4242 IsConstructor = true; 4243 break; 4244 case Sema::CXXMoveConstructor: 4245 IsConstructor = true; 4246 IsMove = true; 4247 break; 4248 case Sema::CXXCopyAssignment: 4249 IsAssignment = true; 4250 break; 4251 case Sema::CXXMoveAssignment: 4252 IsAssignment = true; 4253 IsMove = true; 4254 break; 4255 case Sema::CXXDestructor: 4256 break; 4257 case Sema::CXXInvalid: 4258 llvm_unreachable("invalid special member kind"); 4259 } 4260 4261 if (MD->getNumParams()) { 4262 ConstArg = MD->getParamDecl(0)->getType().isConstQualified(); 4263 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified(); 4264 } 4265 } 4266 4267 bool inUnion() const { return MD->getParent()->isUnion(); } 4268 4269 /// Look up the corresponding special member in the given class. 4270 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class, 4271 unsigned Quals) { 4272 unsigned TQ = MD->getTypeQualifiers(); 4273 // cv-qualifiers on class members don't affect default ctor / dtor calls. 4274 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 4275 Quals = 0; 4276 return S.LookupSpecialMember(Class, CSM, 4277 ConstArg || (Quals & Qualifiers::Const), 4278 VolatileArg || (Quals & Qualifiers::Volatile), 4279 MD->getRefQualifier() == RQ_RValue, 4280 TQ & Qualifiers::Const, 4281 TQ & Qualifiers::Volatile); 4282 } 4283 4284 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 4285 4286 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 4287 bool shouldDeleteForField(FieldDecl *FD); 4288 bool shouldDeleteForAllConstMembers(); 4289 4290 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 4291 unsigned Quals); 4292 bool shouldDeleteForSubobjectCall(Subobject Subobj, 4293 Sema::SpecialMemberOverloadResult *SMOR, 4294 bool IsDtorCallInCtor); 4295 4296 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 4297}; 4298} 4299 4300/// Is the given special member inaccessible when used on the given 4301/// sub-object. 4302bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 4303 CXXMethodDecl *target) { 4304 /// If we're operating on a base class, the object type is the 4305 /// type of this special member. 4306 QualType objectTy; 4307 AccessSpecifier access = target->getAccess();; 4308 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 4309 objectTy = S.Context.getTypeDeclType(MD->getParent()); 4310 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 4311 4312 // If we're operating on a field, the object type is the type of the field. 4313 } else { 4314 objectTy = S.Context.getTypeDeclType(target->getParent()); 4315 } 4316 4317 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 4318} 4319 4320/// Check whether we should delete a special member due to the implicit 4321/// definition containing a call to a special member of a subobject. 4322bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 4323 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR, 4324 bool IsDtorCallInCtor) { 4325 CXXMethodDecl *Decl = SMOR->getMethod(); 4326 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 4327 4328 int DiagKind = -1; 4329 4330 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 4331 DiagKind = !Decl ? 0 : 1; 4332 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 4333 DiagKind = 2; 4334 else if (!isAccessible(Subobj, Decl)) 4335 DiagKind = 3; 4336 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 4337 !Decl->isTrivial()) { 4338 // A member of a union must have a trivial corresponding special member. 4339 // As a weird special case, a destructor call from a union's constructor 4340 // must be accessible and non-deleted, but need not be trivial. Such a 4341 // destructor is never actually called, but is semantically checked as 4342 // if it were. 4343 DiagKind = 4; 4344 } 4345 4346 if (DiagKind == -1) 4347 return false; 4348 4349 if (Diagnose) { 4350 if (Field) { 4351 S.Diag(Field->getLocation(), 4352 diag::note_deleted_special_member_class_subobject) 4353 << CSM << MD->getParent() << /*IsField*/true 4354 << Field << DiagKind << IsDtorCallInCtor; 4355 } else { 4356 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 4357 S.Diag(Base->getLocStart(), 4358 diag::note_deleted_special_member_class_subobject) 4359 << CSM << MD->getParent() << /*IsField*/false 4360 << Base->getType() << DiagKind << IsDtorCallInCtor; 4361 } 4362 4363 if (DiagKind == 1) 4364 S.NoteDeletedFunction(Decl); 4365 // FIXME: Explain inaccessibility if DiagKind == 3. 4366 } 4367 4368 return true; 4369} 4370 4371/// Check whether we should delete a special member function due to having a 4372/// direct or virtual base class or non-static data member of class type M. 4373bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 4374 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 4375 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 4376 4377 // C++11 [class.ctor]p5: 4378 // -- any direct or virtual base class, or non-static data member with no 4379 // brace-or-equal-initializer, has class type M (or array thereof) and 4380 // either M has no default constructor or overload resolution as applied 4381 // to M's default constructor results in an ambiguity or in a function 4382 // that is deleted or inaccessible 4383 // C++11 [class.copy]p11, C++11 [class.copy]p23: 4384 // -- a direct or virtual base class B that cannot be copied/moved because 4385 // overload resolution, as applied to B's corresponding special member, 4386 // results in an ambiguity or a function that is deleted or inaccessible 4387 // from the defaulted special member 4388 // C++11 [class.dtor]p5: 4389 // -- any direct or virtual base class [...] has a type with a destructor 4390 // that is deleted or inaccessible 4391 if (!(CSM == Sema::CXXDefaultConstructor && 4392 Field && Field->hasInClassInitializer()) && 4393 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false)) 4394 return true; 4395 4396 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 4397 // -- any direct or virtual base class or non-static data member has a 4398 // type with a destructor that is deleted or inaccessible 4399 if (IsConstructor) { 4400 Sema::SpecialMemberOverloadResult *SMOR = 4401 S.LookupSpecialMember(Class, Sema::CXXDestructor, 4402 false, false, false, false, false); 4403 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 4404 return true; 4405 } 4406 4407 return false; 4408} 4409 4410/// Check whether we should delete a special member function due to the class 4411/// having a particular direct or virtual base class. 4412bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 4413 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 4414 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 4415} 4416 4417/// Check whether we should delete a special member function due to the class 4418/// having a particular non-static data member. 4419bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 4420 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 4421 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 4422 4423 if (CSM == Sema::CXXDefaultConstructor) { 4424 // For a default constructor, all references must be initialized in-class 4425 // and, if a union, it must have a non-const member. 4426 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 4427 if (Diagnose) 4428 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 4429 << MD->getParent() << FD << FieldType << /*Reference*/0; 4430 return true; 4431 } 4432 // C++11 [class.ctor]p5: any non-variant non-static data member of 4433 // const-qualified type (or array thereof) with no 4434 // brace-or-equal-initializer does not have a user-provided default 4435 // constructor. 4436 if (!inUnion() && FieldType.isConstQualified() && 4437 !FD->hasInClassInitializer() && 4438 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 4439 if (Diagnose) 4440 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 4441 << MD->getParent() << FD << FD->getType() << /*Const*/1; 4442 return true; 4443 } 4444 4445 if (inUnion() && !FieldType.isConstQualified()) 4446 AllFieldsAreConst = false; 4447 } else if (CSM == Sema::CXXCopyConstructor) { 4448 // For a copy constructor, data members must not be of rvalue reference 4449 // type. 4450 if (FieldType->isRValueReferenceType()) { 4451 if (Diagnose) 4452 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 4453 << MD->getParent() << FD << FieldType; 4454 return true; 4455 } 4456 } else if (IsAssignment) { 4457 // For an assignment operator, data members must not be of reference type. 4458 if (FieldType->isReferenceType()) { 4459 if (Diagnose) 4460 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 4461 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0; 4462 return true; 4463 } 4464 if (!FieldRecord && FieldType.isConstQualified()) { 4465 // C++11 [class.copy]p23: 4466 // -- a non-static data member of const non-class type (or array thereof) 4467 if (Diagnose) 4468 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 4469 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1; 4470 return true; 4471 } 4472 } 4473 4474 if (FieldRecord) { 4475 // Some additional restrictions exist on the variant members. 4476 if (!inUnion() && FieldRecord->isUnion() && 4477 FieldRecord->isAnonymousStructOrUnion()) { 4478 bool AllVariantFieldsAreConst = true; 4479 4480 // FIXME: Handle anonymous unions declared within anonymous unions. 4481 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(), 4482 UE = FieldRecord->field_end(); 4483 UI != UE; ++UI) { 4484 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 4485 4486 if (!UnionFieldType.isConstQualified()) 4487 AllVariantFieldsAreConst = false; 4488 4489 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 4490 if (UnionFieldRecord && 4491 shouldDeleteForClassSubobject(UnionFieldRecord, *UI, 4492 UnionFieldType.getCVRQualifiers())) 4493 return true; 4494 } 4495 4496 // At least one member in each anonymous union must be non-const 4497 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 4498 FieldRecord->field_begin() != FieldRecord->field_end()) { 4499 if (Diagnose) 4500 S.Diag(FieldRecord->getLocation(), 4501 diag::note_deleted_default_ctor_all_const) 4502 << MD->getParent() << /*anonymous union*/1; 4503 return true; 4504 } 4505 4506 // Don't check the implicit member of the anonymous union type. 4507 // This is technically non-conformant, but sanity demands it. 4508 return false; 4509 } 4510 4511 if (shouldDeleteForClassSubobject(FieldRecord, FD, 4512 FieldType.getCVRQualifiers())) 4513 return true; 4514 } 4515 4516 return false; 4517} 4518 4519/// C++11 [class.ctor] p5: 4520/// A defaulted default constructor for a class X is defined as deleted if 4521/// X is a union and all of its variant members are of const-qualified type. 4522bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 4523 // This is a silly definition, because it gives an empty union a deleted 4524 // default constructor. Don't do that. 4525 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst && 4526 (MD->getParent()->field_begin() != MD->getParent()->field_end())) { 4527 if (Diagnose) 4528 S.Diag(MD->getParent()->getLocation(), 4529 diag::note_deleted_default_ctor_all_const) 4530 << MD->getParent() << /*not anonymous union*/0; 4531 return true; 4532 } 4533 return false; 4534} 4535 4536/// Determine whether a defaulted special member function should be defined as 4537/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 4538/// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 4539bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 4540 bool Diagnose) { 4541 if (MD->isInvalidDecl()) 4542 return false; 4543 CXXRecordDecl *RD = MD->getParent(); 4544 assert(!RD->isDependentType() && "do deletion after instantiation"); 4545 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl()) 4546 return false; 4547 4548 // C++11 [expr.lambda.prim]p19: 4549 // The closure type associated with a lambda-expression has a 4550 // deleted (8.4.3) default constructor and a deleted copy 4551 // assignment operator. 4552 if (RD->isLambda() && 4553 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 4554 if (Diagnose) 4555 Diag(RD->getLocation(), diag::note_lambda_decl); 4556 return true; 4557 } 4558 4559 // For an anonymous struct or union, the copy and assignment special members 4560 // will never be used, so skip the check. For an anonymous union declared at 4561 // namespace scope, the constructor and destructor are used. 4562 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 4563 RD->isAnonymousStructOrUnion()) 4564 return false; 4565 4566 // C++11 [class.copy]p7, p18: 4567 // If the class definition declares a move constructor or move assignment 4568 // operator, an implicitly declared copy constructor or copy assignment 4569 // operator is defined as deleted. 4570 if (MD->isImplicit() && 4571 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 4572 CXXMethodDecl *UserDeclaredMove = 0; 4573 4574 // In Microsoft mode, a user-declared move only causes the deletion of the 4575 // corresponding copy operation, not both copy operations. 4576 if (RD->hasUserDeclaredMoveConstructor() && 4577 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) { 4578 if (!Diagnose) return true; 4579 UserDeclaredMove = RD->getMoveConstructor(); 4580 assert(UserDeclaredMove); 4581 } else if (RD->hasUserDeclaredMoveAssignment() && 4582 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) { 4583 if (!Diagnose) return true; 4584 UserDeclaredMove = RD->getMoveAssignmentOperator(); 4585 assert(UserDeclaredMove); 4586 } 4587 4588 if (UserDeclaredMove) { 4589 Diag(UserDeclaredMove->getLocation(), 4590 diag::note_deleted_copy_user_declared_move) 4591 << (CSM == CXXCopyAssignment) << RD 4592 << UserDeclaredMove->isMoveAssignmentOperator(); 4593 return true; 4594 } 4595 } 4596 4597 // Do access control from the special member function 4598 ContextRAII MethodContext(*this, MD); 4599 4600 // C++11 [class.dtor]p5: 4601 // -- for a virtual destructor, lookup of the non-array deallocation function 4602 // results in an ambiguity or in a function that is deleted or inaccessible 4603 if (CSM == CXXDestructor && MD->isVirtual()) { 4604 FunctionDecl *OperatorDelete = 0; 4605 DeclarationName Name = 4606 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 4607 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 4608 OperatorDelete, false)) { 4609 if (Diagnose) 4610 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 4611 return true; 4612 } 4613 } 4614 4615 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose); 4616 4617 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 4618 BE = RD->bases_end(); BI != BE; ++BI) 4619 if (!BI->isVirtual() && 4620 SMI.shouldDeleteForBase(BI)) 4621 return true; 4622 4623 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(), 4624 BE = RD->vbases_end(); BI != BE; ++BI) 4625 if (SMI.shouldDeleteForBase(BI)) 4626 return true; 4627 4628 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 4629 FE = RD->field_end(); FI != FE; ++FI) 4630 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() && 4631 SMI.shouldDeleteForField(*FI)) 4632 return true; 4633 4634 if (SMI.shouldDeleteForAllConstMembers()) 4635 return true; 4636 4637 return false; 4638} 4639 4640/// \brief Data used with FindHiddenVirtualMethod 4641namespace { 4642 struct FindHiddenVirtualMethodData { 4643 Sema *S; 4644 CXXMethodDecl *Method; 4645 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 4646 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 4647 }; 4648} 4649 4650/// \brief Member lookup function that determines whether a given C++ 4651/// method overloads virtual methods in a base class without overriding any, 4652/// to be used with CXXRecordDecl::lookupInBases(). 4653static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier, 4654 CXXBasePath &Path, 4655 void *UserData) { 4656 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 4657 4658 FindHiddenVirtualMethodData &Data 4659 = *static_cast<FindHiddenVirtualMethodData*>(UserData); 4660 4661 DeclarationName Name = Data.Method->getDeclName(); 4662 assert(Name.getNameKind() == DeclarationName::Identifier); 4663 4664 bool foundSameNameMethod = false; 4665 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 4666 for (Path.Decls = BaseRecord->lookup(Name); 4667 Path.Decls.first != Path.Decls.second; 4668 ++Path.Decls.first) { 4669 NamedDecl *D = *Path.Decls.first; 4670 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 4671 MD = MD->getCanonicalDecl(); 4672 foundSameNameMethod = true; 4673 // Interested only in hidden virtual methods. 4674 if (!MD->isVirtual()) 4675 continue; 4676 // If the method we are checking overrides a method from its base 4677 // don't warn about the other overloaded methods. 4678 if (!Data.S->IsOverload(Data.Method, MD, false)) 4679 return true; 4680 // Collect the overload only if its hidden. 4681 if (!Data.OverridenAndUsingBaseMethods.count(MD)) 4682 overloadedMethods.push_back(MD); 4683 } 4684 } 4685 4686 if (foundSameNameMethod) 4687 Data.OverloadedMethods.append(overloadedMethods.begin(), 4688 overloadedMethods.end()); 4689 return foundSameNameMethod; 4690} 4691 4692/// \brief See if a method overloads virtual methods in a base class without 4693/// overriding any. 4694void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 4695 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual, 4696 MD->getLocation()) == DiagnosticsEngine::Ignored) 4697 return; 4698 if (!MD->getDeclName().isIdentifier()) 4699 return; 4700 4701 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 4702 /*bool RecordPaths=*/false, 4703 /*bool DetectVirtual=*/false); 4704 FindHiddenVirtualMethodData Data; 4705 Data.Method = MD; 4706 Data.S = this; 4707 4708 // Keep the base methods that were overriden or introduced in the subclass 4709 // by 'using' in a set. A base method not in this set is hidden. 4710 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName()); 4711 res.first != res.second; ++res.first) { 4712 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first)) 4713 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 4714 E = MD->end_overridden_methods(); 4715 I != E; ++I) 4716 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl()); 4717 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first)) 4718 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl())) 4719 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl()); 4720 } 4721 4722 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) && 4723 !Data.OverloadedMethods.empty()) { 4724 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 4725 << MD << (Data.OverloadedMethods.size() > 1); 4726 4727 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) { 4728 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i]; 4729 Diag(overloadedMD->getLocation(), 4730 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 4731 } 4732 } 4733} 4734 4735void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 4736 Decl *TagDecl, 4737 SourceLocation LBrac, 4738 SourceLocation RBrac, 4739 AttributeList *AttrList) { 4740 if (!TagDecl) 4741 return; 4742 4743 AdjustDeclIfTemplate(TagDecl); 4744 4745 for (const AttributeList* l = AttrList; l; l = l->getNext()) { 4746 if (l->getKind() != AttributeList::AT_Visibility) 4747 continue; 4748 l->setInvalid(); 4749 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) << 4750 l->getName(); 4751 } 4752 4753 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 4754 // strict aliasing violation! 4755 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 4756 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 4757 4758 CheckCompletedCXXClass( 4759 dyn_cast_or_null<CXXRecordDecl>(TagDecl)); 4760} 4761 4762/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 4763/// special functions, such as the default constructor, copy 4764/// constructor, or destructor, to the given C++ class (C++ 4765/// [special]p1). This routine can only be executed just before the 4766/// definition of the class is complete. 4767void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 4768 if (!ClassDecl->hasUserDeclaredConstructor()) 4769 ++ASTContext::NumImplicitDefaultConstructors; 4770 4771 if (!ClassDecl->hasUserDeclaredCopyConstructor()) 4772 ++ASTContext::NumImplicitCopyConstructors; 4773 4774 if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveConstructor()) 4775 ++ASTContext::NumImplicitMoveConstructors; 4776 4777 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 4778 ++ASTContext::NumImplicitCopyAssignmentOperators; 4779 4780 // If we have a dynamic class, then the copy assignment operator may be 4781 // virtual, so we have to declare it immediately. This ensures that, e.g., 4782 // it shows up in the right place in the vtable and that we diagnose 4783 // problems with the implicit exception specification. 4784 if (ClassDecl->isDynamicClass()) 4785 DeclareImplicitCopyAssignment(ClassDecl); 4786 } 4787 4788 if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveAssignment()) { 4789 ++ASTContext::NumImplicitMoveAssignmentOperators; 4790 4791 // Likewise for the move assignment operator. 4792 if (ClassDecl->isDynamicClass()) 4793 DeclareImplicitMoveAssignment(ClassDecl); 4794 } 4795 4796 if (!ClassDecl->hasUserDeclaredDestructor()) { 4797 ++ASTContext::NumImplicitDestructors; 4798 4799 // If we have a dynamic class, then the destructor may be virtual, so we 4800 // have to declare the destructor immediately. This ensures that, e.g., it 4801 // shows up in the right place in the vtable and that we diagnose problems 4802 // with the implicit exception specification. 4803 if (ClassDecl->isDynamicClass()) 4804 DeclareImplicitDestructor(ClassDecl); 4805 } 4806} 4807 4808void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) { 4809 if (!D) 4810 return; 4811 4812 int NumParamList = D->getNumTemplateParameterLists(); 4813 for (int i = 0; i < NumParamList; i++) { 4814 TemplateParameterList* Params = D->getTemplateParameterList(i); 4815 for (TemplateParameterList::iterator Param = Params->begin(), 4816 ParamEnd = Params->end(); 4817 Param != ParamEnd; ++Param) { 4818 NamedDecl *Named = cast<NamedDecl>(*Param); 4819 if (Named->getDeclName()) { 4820 S->AddDecl(Named); 4821 IdResolver.AddDecl(Named); 4822 } 4823 } 4824 } 4825} 4826 4827void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 4828 if (!D) 4829 return; 4830 4831 TemplateParameterList *Params = 0; 4832 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) 4833 Params = Template->getTemplateParameters(); 4834 else if (ClassTemplatePartialSpecializationDecl *PartialSpec 4835 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 4836 Params = PartialSpec->getTemplateParameters(); 4837 else 4838 return; 4839 4840 for (TemplateParameterList::iterator Param = Params->begin(), 4841 ParamEnd = Params->end(); 4842 Param != ParamEnd; ++Param) { 4843 NamedDecl *Named = cast<NamedDecl>(*Param); 4844 if (Named->getDeclName()) { 4845 S->AddDecl(Named); 4846 IdResolver.AddDecl(Named); 4847 } 4848 } 4849} 4850 4851void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 4852 if (!RecordD) return; 4853 AdjustDeclIfTemplate(RecordD); 4854 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 4855 PushDeclContext(S, Record); 4856} 4857 4858void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 4859 if (!RecordD) return; 4860 PopDeclContext(); 4861} 4862 4863/// ActOnStartDelayedCXXMethodDeclaration - We have completed 4864/// parsing a top-level (non-nested) C++ class, and we are now 4865/// parsing those parts of the given Method declaration that could 4866/// not be parsed earlier (C++ [class.mem]p2), such as default 4867/// arguments. This action should enter the scope of the given 4868/// Method declaration as if we had just parsed the qualified method 4869/// name. However, it should not bring the parameters into scope; 4870/// that will be performed by ActOnDelayedCXXMethodParameter. 4871void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 4872} 4873 4874/// ActOnDelayedCXXMethodParameter - We've already started a delayed 4875/// C++ method declaration. We're (re-)introducing the given 4876/// function parameter into scope for use in parsing later parts of 4877/// the method declaration. For example, we could see an 4878/// ActOnParamDefaultArgument event for this parameter. 4879void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 4880 if (!ParamD) 4881 return; 4882 4883 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 4884 4885 // If this parameter has an unparsed default argument, clear it out 4886 // to make way for the parsed default argument. 4887 if (Param->hasUnparsedDefaultArg()) 4888 Param->setDefaultArg(0); 4889 4890 S->AddDecl(Param); 4891 if (Param->getDeclName()) 4892 IdResolver.AddDecl(Param); 4893} 4894 4895/// ActOnFinishDelayedCXXMethodDeclaration - We have finished 4896/// processing the delayed method declaration for Method. The method 4897/// declaration is now considered finished. There may be a separate 4898/// ActOnStartOfFunctionDef action later (not necessarily 4899/// immediately!) for this method, if it was also defined inside the 4900/// class body. 4901void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 4902 if (!MethodD) 4903 return; 4904 4905 AdjustDeclIfTemplate(MethodD); 4906 4907 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 4908 4909 // Now that we have our default arguments, check the constructor 4910 // again. It could produce additional diagnostics or affect whether 4911 // the class has implicitly-declared destructors, among other 4912 // things. 4913 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 4914 CheckConstructor(Constructor); 4915 4916 // Check the default arguments, which we may have added. 4917 if (!Method->isInvalidDecl()) 4918 CheckCXXDefaultArguments(Method); 4919} 4920 4921/// CheckConstructorDeclarator - Called by ActOnDeclarator to check 4922/// the well-formedness of the constructor declarator @p D with type @p 4923/// R. If there are any errors in the declarator, this routine will 4924/// emit diagnostics and set the invalid bit to true. In any case, the type 4925/// will be updated to reflect a well-formed type for the constructor and 4926/// returned. 4927QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 4928 StorageClass &SC) { 4929 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 4930 4931 // C++ [class.ctor]p3: 4932 // A constructor shall not be virtual (10.3) or static (9.4). A 4933 // constructor can be invoked for a const, volatile or const 4934 // volatile object. A constructor shall not be declared const, 4935 // volatile, or const volatile (9.3.2). 4936 if (isVirtual) { 4937 if (!D.isInvalidType()) 4938 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 4939 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 4940 << SourceRange(D.getIdentifierLoc()); 4941 D.setInvalidType(); 4942 } 4943 if (SC == SC_Static) { 4944 if (!D.isInvalidType()) 4945 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 4946 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 4947 << SourceRange(D.getIdentifierLoc()); 4948 D.setInvalidType(); 4949 SC = SC_None; 4950 } 4951 4952 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 4953 if (FTI.TypeQuals != 0) { 4954 if (FTI.TypeQuals & Qualifiers::Const) 4955 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 4956 << "const" << SourceRange(D.getIdentifierLoc()); 4957 if (FTI.TypeQuals & Qualifiers::Volatile) 4958 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 4959 << "volatile" << SourceRange(D.getIdentifierLoc()); 4960 if (FTI.TypeQuals & Qualifiers::Restrict) 4961 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 4962 << "restrict" << SourceRange(D.getIdentifierLoc()); 4963 D.setInvalidType(); 4964 } 4965 4966 // C++0x [class.ctor]p4: 4967 // A constructor shall not be declared with a ref-qualifier. 4968 if (FTI.hasRefQualifier()) { 4969 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 4970 << FTI.RefQualifierIsLValueRef 4971 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 4972 D.setInvalidType(); 4973 } 4974 4975 // Rebuild the function type "R" without any type qualifiers (in 4976 // case any of the errors above fired) and with "void" as the 4977 // return type, since constructors don't have return types. 4978 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 4979 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType()) 4980 return R; 4981 4982 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 4983 EPI.TypeQuals = 0; 4984 EPI.RefQualifier = RQ_None; 4985 4986 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(), 4987 Proto->getNumArgs(), EPI); 4988} 4989 4990/// CheckConstructor - Checks a fully-formed constructor for 4991/// well-formedness, issuing any diagnostics required. Returns true if 4992/// the constructor declarator is invalid. 4993void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 4994 CXXRecordDecl *ClassDecl 4995 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 4996 if (!ClassDecl) 4997 return Constructor->setInvalidDecl(); 4998 4999 // C++ [class.copy]p3: 5000 // A declaration of a constructor for a class X is ill-formed if 5001 // its first parameter is of type (optionally cv-qualified) X and 5002 // either there are no other parameters or else all other 5003 // parameters have default arguments. 5004 if (!Constructor->isInvalidDecl() && 5005 ((Constructor->getNumParams() == 1) || 5006 (Constructor->getNumParams() > 1 && 5007 Constructor->getParamDecl(1)->hasDefaultArg())) && 5008 Constructor->getTemplateSpecializationKind() 5009 != TSK_ImplicitInstantiation) { 5010 QualType ParamType = Constructor->getParamDecl(0)->getType(); 5011 QualType ClassTy = Context.getTagDeclType(ClassDecl); 5012 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 5013 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 5014 const char *ConstRef 5015 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 5016 : " const &"; 5017 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 5018 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 5019 5020 // FIXME: Rather that making the constructor invalid, we should endeavor 5021 // to fix the type. 5022 Constructor->setInvalidDecl(); 5023 } 5024 } 5025} 5026 5027/// CheckDestructor - Checks a fully-formed destructor definition for 5028/// well-formedness, issuing any diagnostics required. Returns true 5029/// on error. 5030bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 5031 CXXRecordDecl *RD = Destructor->getParent(); 5032 5033 if (Destructor->isVirtual()) { 5034 SourceLocation Loc; 5035 5036 if (!Destructor->isImplicit()) 5037 Loc = Destructor->getLocation(); 5038 else 5039 Loc = RD->getLocation(); 5040 5041 // If we have a virtual destructor, look up the deallocation function 5042 FunctionDecl *OperatorDelete = 0; 5043 DeclarationName Name = 5044 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 5045 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 5046 return true; 5047 5048 MarkFunctionReferenced(Loc, OperatorDelete); 5049 5050 Destructor->setOperatorDelete(OperatorDelete); 5051 } 5052 5053 return false; 5054} 5055 5056static inline bool 5057FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) { 5058 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 5059 FTI.ArgInfo[0].Param && 5060 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()); 5061} 5062 5063/// CheckDestructorDeclarator - Called by ActOnDeclarator to check 5064/// the well-formednes of the destructor declarator @p D with type @p 5065/// R. If there are any errors in the declarator, this routine will 5066/// emit diagnostics and set the declarator to invalid. Even if this happens, 5067/// will be updated to reflect a well-formed type for the destructor and 5068/// returned. 5069QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 5070 StorageClass& SC) { 5071 // C++ [class.dtor]p1: 5072 // [...] A typedef-name that names a class is a class-name 5073 // (7.1.3); however, a typedef-name that names a class shall not 5074 // be used as the identifier in the declarator for a destructor 5075 // declaration. 5076 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 5077 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 5078 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 5079 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 5080 else if (const TemplateSpecializationType *TST = 5081 DeclaratorType->getAs<TemplateSpecializationType>()) 5082 if (TST->isTypeAlias()) 5083 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 5084 << DeclaratorType << 1; 5085 5086 // C++ [class.dtor]p2: 5087 // A destructor is used to destroy objects of its class type. A 5088 // destructor takes no parameters, and no return type can be 5089 // specified for it (not even void). The address of a destructor 5090 // shall not be taken. A destructor shall not be static. A 5091 // destructor can be invoked for a const, volatile or const 5092 // volatile object. A destructor shall not be declared const, 5093 // volatile or const volatile (9.3.2). 5094 if (SC == SC_Static) { 5095 if (!D.isInvalidType()) 5096 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 5097 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 5098 << SourceRange(D.getIdentifierLoc()) 5099 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5100 5101 SC = SC_None; 5102 } 5103 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 5104 // Destructors don't have return types, but the parser will 5105 // happily parse something like: 5106 // 5107 // class X { 5108 // float ~X(); 5109 // }; 5110 // 5111 // The return type will be eliminated later. 5112 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 5113 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 5114 << SourceRange(D.getIdentifierLoc()); 5115 } 5116 5117 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 5118 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 5119 if (FTI.TypeQuals & Qualifiers::Const) 5120 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 5121 << "const" << SourceRange(D.getIdentifierLoc()); 5122 if (FTI.TypeQuals & Qualifiers::Volatile) 5123 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 5124 << "volatile" << SourceRange(D.getIdentifierLoc()); 5125 if (FTI.TypeQuals & Qualifiers::Restrict) 5126 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 5127 << "restrict" << SourceRange(D.getIdentifierLoc()); 5128 D.setInvalidType(); 5129 } 5130 5131 // C++0x [class.dtor]p2: 5132 // A destructor shall not be declared with a ref-qualifier. 5133 if (FTI.hasRefQualifier()) { 5134 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 5135 << FTI.RefQualifierIsLValueRef 5136 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 5137 D.setInvalidType(); 5138 } 5139 5140 // Make sure we don't have any parameters. 5141 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) { 5142 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 5143 5144 // Delete the parameters. 5145 FTI.freeArgs(); 5146 D.setInvalidType(); 5147 } 5148 5149 // Make sure the destructor isn't variadic. 5150 if (FTI.isVariadic) { 5151 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 5152 D.setInvalidType(); 5153 } 5154 5155 // Rebuild the function type "R" without any type qualifiers or 5156 // parameters (in case any of the errors above fired) and with 5157 // "void" as the return type, since destructors don't have return 5158 // types. 5159 if (!D.isInvalidType()) 5160 return R; 5161 5162 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 5163 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 5164 EPI.Variadic = false; 5165 EPI.TypeQuals = 0; 5166 EPI.RefQualifier = RQ_None; 5167 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI); 5168} 5169 5170/// CheckConversionDeclarator - Called by ActOnDeclarator to check the 5171/// well-formednes of the conversion function declarator @p D with 5172/// type @p R. If there are any errors in the declarator, this routine 5173/// will emit diagnostics and return true. Otherwise, it will return 5174/// false. Either way, the type @p R will be updated to reflect a 5175/// well-formed type for the conversion operator. 5176void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 5177 StorageClass& SC) { 5178 // C++ [class.conv.fct]p1: 5179 // Neither parameter types nor return type can be specified. The 5180 // type of a conversion function (8.3.5) is "function taking no 5181 // parameter returning conversion-type-id." 5182 if (SC == SC_Static) { 5183 if (!D.isInvalidType()) 5184 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 5185 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 5186 << SourceRange(D.getIdentifierLoc()); 5187 D.setInvalidType(); 5188 SC = SC_None; 5189 } 5190 5191 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId); 5192 5193 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 5194 // Conversion functions don't have return types, but the parser will 5195 // happily parse something like: 5196 // 5197 // class X { 5198 // float operator bool(); 5199 // }; 5200 // 5201 // The return type will be changed later anyway. 5202 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 5203 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 5204 << SourceRange(D.getIdentifierLoc()); 5205 D.setInvalidType(); 5206 } 5207 5208 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 5209 5210 // Make sure we don't have any parameters. 5211 if (Proto->getNumArgs() > 0) { 5212 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 5213 5214 // Delete the parameters. 5215 D.getFunctionTypeInfo().freeArgs(); 5216 D.setInvalidType(); 5217 } else if (Proto->isVariadic()) { 5218 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 5219 D.setInvalidType(); 5220 } 5221 5222 // Diagnose "&operator bool()" and other such nonsense. This 5223 // is actually a gcc extension which we don't support. 5224 if (Proto->getResultType() != ConvType) { 5225 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 5226 << Proto->getResultType(); 5227 D.setInvalidType(); 5228 ConvType = Proto->getResultType(); 5229 } 5230 5231 // C++ [class.conv.fct]p4: 5232 // The conversion-type-id shall not represent a function type nor 5233 // an array type. 5234 if (ConvType->isArrayType()) { 5235 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 5236 ConvType = Context.getPointerType(ConvType); 5237 D.setInvalidType(); 5238 } else if (ConvType->isFunctionType()) { 5239 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 5240 ConvType = Context.getPointerType(ConvType); 5241 D.setInvalidType(); 5242 } 5243 5244 // Rebuild the function type "R" without any parameters (in case any 5245 // of the errors above fired) and with the conversion type as the 5246 // return type. 5247 if (D.isInvalidType()) 5248 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo()); 5249 5250 // C++0x explicit conversion operators. 5251 if (D.getDeclSpec().isExplicitSpecified()) 5252 Diag(D.getDeclSpec().getExplicitSpecLoc(), 5253 getLangOpts().CPlusPlus0x ? 5254 diag::warn_cxx98_compat_explicit_conversion_functions : 5255 diag::ext_explicit_conversion_functions) 5256 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 5257} 5258 5259/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 5260/// the declaration of the given C++ conversion function. This routine 5261/// is responsible for recording the conversion function in the C++ 5262/// class, if possible. 5263Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 5264 assert(Conversion && "Expected to receive a conversion function declaration"); 5265 5266 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 5267 5268 // Make sure we aren't redeclaring the conversion function. 5269 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 5270 5271 // C++ [class.conv.fct]p1: 5272 // [...] A conversion function is never used to convert a 5273 // (possibly cv-qualified) object to the (possibly cv-qualified) 5274 // same object type (or a reference to it), to a (possibly 5275 // cv-qualified) base class of that type (or a reference to it), 5276 // or to (possibly cv-qualified) void. 5277 // FIXME: Suppress this warning if the conversion function ends up being a 5278 // virtual function that overrides a virtual function in a base class. 5279 QualType ClassType 5280 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 5281 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 5282 ConvType = ConvTypeRef->getPointeeType(); 5283 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 5284 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 5285 /* Suppress diagnostics for instantiations. */; 5286 else if (ConvType->isRecordType()) { 5287 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 5288 if (ConvType == ClassType) 5289 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 5290 << ClassType; 5291 else if (IsDerivedFrom(ClassType, ConvType)) 5292 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 5293 << ClassType << ConvType; 5294 } else if (ConvType->isVoidType()) { 5295 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 5296 << ClassType << ConvType; 5297 } 5298 5299 if (FunctionTemplateDecl *ConversionTemplate 5300 = Conversion->getDescribedFunctionTemplate()) 5301 return ConversionTemplate; 5302 5303 return Conversion; 5304} 5305 5306//===----------------------------------------------------------------------===// 5307// Namespace Handling 5308//===----------------------------------------------------------------------===// 5309 5310 5311 5312/// ActOnStartNamespaceDef - This is called at the start of a namespace 5313/// definition. 5314Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 5315 SourceLocation InlineLoc, 5316 SourceLocation NamespaceLoc, 5317 SourceLocation IdentLoc, 5318 IdentifierInfo *II, 5319 SourceLocation LBrace, 5320 AttributeList *AttrList) { 5321 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 5322 // For anonymous namespace, take the location of the left brace. 5323 SourceLocation Loc = II ? IdentLoc : LBrace; 5324 bool IsInline = InlineLoc.isValid(); 5325 bool IsInvalid = false; 5326 bool IsStd = false; 5327 bool AddToKnown = false; 5328 Scope *DeclRegionScope = NamespcScope->getParent(); 5329 5330 NamespaceDecl *PrevNS = 0; 5331 if (II) { 5332 // C++ [namespace.def]p2: 5333 // The identifier in an original-namespace-definition shall not 5334 // have been previously defined in the declarative region in 5335 // which the original-namespace-definition appears. The 5336 // identifier in an original-namespace-definition is the name of 5337 // the namespace. Subsequently in that declarative region, it is 5338 // treated as an original-namespace-name. 5339 // 5340 // Since namespace names are unique in their scope, and we don't 5341 // look through using directives, just look for any ordinary names. 5342 5343 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member | 5344 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag | 5345 Decl::IDNS_Namespace; 5346 NamedDecl *PrevDecl = 0; 5347 for (DeclContext::lookup_result R 5348 = CurContext->getRedeclContext()->lookup(II); 5349 R.first != R.second; ++R.first) { 5350 if ((*R.first)->getIdentifierNamespace() & IDNS) { 5351 PrevDecl = *R.first; 5352 break; 5353 } 5354 } 5355 5356 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 5357 5358 if (PrevNS) { 5359 // This is an extended namespace definition. 5360 if (IsInline != PrevNS->isInline()) { 5361 // inline-ness must match 5362 if (PrevNS->isInline()) { 5363 // The user probably just forgot the 'inline', so suggest that it 5364 // be added back. 5365 Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 5366 << FixItHint::CreateInsertion(NamespaceLoc, "inline "); 5367 } else { 5368 Diag(Loc, diag::err_inline_namespace_mismatch) 5369 << IsInline; 5370 } 5371 Diag(PrevNS->getLocation(), diag::note_previous_definition); 5372 5373 IsInline = PrevNS->isInline(); 5374 } 5375 } else if (PrevDecl) { 5376 // This is an invalid name redefinition. 5377 Diag(Loc, diag::err_redefinition_different_kind) 5378 << II; 5379 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 5380 IsInvalid = true; 5381 // Continue on to push Namespc as current DeclContext and return it. 5382 } else if (II->isStr("std") && 5383 CurContext->getRedeclContext()->isTranslationUnit()) { 5384 // This is the first "real" definition of the namespace "std", so update 5385 // our cache of the "std" namespace to point at this definition. 5386 PrevNS = getStdNamespace(); 5387 IsStd = true; 5388 AddToKnown = !IsInline; 5389 } else { 5390 // We've seen this namespace for the first time. 5391 AddToKnown = !IsInline; 5392 } 5393 } else { 5394 // Anonymous namespaces. 5395 5396 // Determine whether the parent already has an anonymous namespace. 5397 DeclContext *Parent = CurContext->getRedeclContext(); 5398 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 5399 PrevNS = TU->getAnonymousNamespace(); 5400 } else { 5401 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 5402 PrevNS = ND->getAnonymousNamespace(); 5403 } 5404 5405 if (PrevNS && IsInline != PrevNS->isInline()) { 5406 // inline-ness must match 5407 Diag(Loc, diag::err_inline_namespace_mismatch) 5408 << IsInline; 5409 Diag(PrevNS->getLocation(), diag::note_previous_definition); 5410 5411 // Recover by ignoring the new namespace's inline status. 5412 IsInline = PrevNS->isInline(); 5413 } 5414 } 5415 5416 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 5417 StartLoc, Loc, II, PrevNS); 5418 if (IsInvalid) 5419 Namespc->setInvalidDecl(); 5420 5421 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 5422 5423 // FIXME: Should we be merging attributes? 5424 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 5425 PushNamespaceVisibilityAttr(Attr, Loc); 5426 5427 if (IsStd) 5428 StdNamespace = Namespc; 5429 if (AddToKnown) 5430 KnownNamespaces[Namespc] = false; 5431 5432 if (II) { 5433 PushOnScopeChains(Namespc, DeclRegionScope); 5434 } else { 5435 // Link the anonymous namespace into its parent. 5436 DeclContext *Parent = CurContext->getRedeclContext(); 5437 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 5438 TU->setAnonymousNamespace(Namespc); 5439 } else { 5440 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 5441 } 5442 5443 CurContext->addDecl(Namespc); 5444 5445 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 5446 // behaves as if it were replaced by 5447 // namespace unique { /* empty body */ } 5448 // using namespace unique; 5449 // namespace unique { namespace-body } 5450 // where all occurrences of 'unique' in a translation unit are 5451 // replaced by the same identifier and this identifier differs 5452 // from all other identifiers in the entire program. 5453 5454 // We just create the namespace with an empty name and then add an 5455 // implicit using declaration, just like the standard suggests. 5456 // 5457 // CodeGen enforces the "universally unique" aspect by giving all 5458 // declarations semantically contained within an anonymous 5459 // namespace internal linkage. 5460 5461 if (!PrevNS) { 5462 UsingDirectiveDecl* UD 5463 = UsingDirectiveDecl::Create(Context, CurContext, 5464 /* 'using' */ LBrace, 5465 /* 'namespace' */ SourceLocation(), 5466 /* qualifier */ NestedNameSpecifierLoc(), 5467 /* identifier */ SourceLocation(), 5468 Namespc, 5469 /* Ancestor */ CurContext); 5470 UD->setImplicit(); 5471 CurContext->addDecl(UD); 5472 } 5473 } 5474 5475 ActOnDocumentableDecl(Namespc); 5476 5477 // Although we could have an invalid decl (i.e. the namespace name is a 5478 // redefinition), push it as current DeclContext and try to continue parsing. 5479 // FIXME: We should be able to push Namespc here, so that the each DeclContext 5480 // for the namespace has the declarations that showed up in that particular 5481 // namespace definition. 5482 PushDeclContext(NamespcScope, Namespc); 5483 return Namespc; 5484} 5485 5486/// getNamespaceDecl - Returns the namespace a decl represents. If the decl 5487/// is a namespace alias, returns the namespace it points to. 5488static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 5489 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 5490 return AD->getNamespace(); 5491 return dyn_cast_or_null<NamespaceDecl>(D); 5492} 5493 5494/// ActOnFinishNamespaceDef - This callback is called after a namespace is 5495/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 5496void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 5497 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 5498 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 5499 Namespc->setRBraceLoc(RBrace); 5500 PopDeclContext(); 5501 if (Namespc->hasAttr<VisibilityAttr>()) 5502 PopPragmaVisibility(true, RBrace); 5503} 5504 5505CXXRecordDecl *Sema::getStdBadAlloc() const { 5506 return cast_or_null<CXXRecordDecl>( 5507 StdBadAlloc.get(Context.getExternalSource())); 5508} 5509 5510NamespaceDecl *Sema::getStdNamespace() const { 5511 return cast_or_null<NamespaceDecl>( 5512 StdNamespace.get(Context.getExternalSource())); 5513} 5514 5515/// \brief Retrieve the special "std" namespace, which may require us to 5516/// implicitly define the namespace. 5517NamespaceDecl *Sema::getOrCreateStdNamespace() { 5518 if (!StdNamespace) { 5519 // The "std" namespace has not yet been defined, so build one implicitly. 5520 StdNamespace = NamespaceDecl::Create(Context, 5521 Context.getTranslationUnitDecl(), 5522 /*Inline=*/false, 5523 SourceLocation(), SourceLocation(), 5524 &PP.getIdentifierTable().get("std"), 5525 /*PrevDecl=*/0); 5526 getStdNamespace()->setImplicit(true); 5527 } 5528 5529 return getStdNamespace(); 5530} 5531 5532bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 5533 assert(getLangOpts().CPlusPlus && 5534 "Looking for std::initializer_list outside of C++."); 5535 5536 // We're looking for implicit instantiations of 5537 // template <typename E> class std::initializer_list. 5538 5539 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 5540 return false; 5541 5542 ClassTemplateDecl *Template = 0; 5543 const TemplateArgument *Arguments = 0; 5544 5545 if (const RecordType *RT = Ty->getAs<RecordType>()) { 5546 5547 ClassTemplateSpecializationDecl *Specialization = 5548 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 5549 if (!Specialization) 5550 return false; 5551 5552 Template = Specialization->getSpecializedTemplate(); 5553 Arguments = Specialization->getTemplateArgs().data(); 5554 } else if (const TemplateSpecializationType *TST = 5555 Ty->getAs<TemplateSpecializationType>()) { 5556 Template = dyn_cast_or_null<ClassTemplateDecl>( 5557 TST->getTemplateName().getAsTemplateDecl()); 5558 Arguments = TST->getArgs(); 5559 } 5560 if (!Template) 5561 return false; 5562 5563 if (!StdInitializerList) { 5564 // Haven't recognized std::initializer_list yet, maybe this is it. 5565 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 5566 if (TemplateClass->getIdentifier() != 5567 &PP.getIdentifierTable().get("initializer_list") || 5568 !getStdNamespace()->InEnclosingNamespaceSetOf( 5569 TemplateClass->getDeclContext())) 5570 return false; 5571 // This is a template called std::initializer_list, but is it the right 5572 // template? 5573 TemplateParameterList *Params = Template->getTemplateParameters(); 5574 if (Params->getMinRequiredArguments() != 1) 5575 return false; 5576 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 5577 return false; 5578 5579 // It's the right template. 5580 StdInitializerList = Template; 5581 } 5582 5583 if (Template != StdInitializerList) 5584 return false; 5585 5586 // This is an instance of std::initializer_list. Find the argument type. 5587 if (Element) 5588 *Element = Arguments[0].getAsType(); 5589 return true; 5590} 5591 5592static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 5593 NamespaceDecl *Std = S.getStdNamespace(); 5594 if (!Std) { 5595 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 5596 return 0; 5597 } 5598 5599 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 5600 Loc, Sema::LookupOrdinaryName); 5601 if (!S.LookupQualifiedName(Result, Std)) { 5602 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 5603 return 0; 5604 } 5605 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 5606 if (!Template) { 5607 Result.suppressDiagnostics(); 5608 // We found something weird. Complain about the first thing we found. 5609 NamedDecl *Found = *Result.begin(); 5610 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 5611 return 0; 5612 } 5613 5614 // We found some template called std::initializer_list. Now verify that it's 5615 // correct. 5616 TemplateParameterList *Params = Template->getTemplateParameters(); 5617 if (Params->getMinRequiredArguments() != 1 || 5618 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 5619 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 5620 return 0; 5621 } 5622 5623 return Template; 5624} 5625 5626QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 5627 if (!StdInitializerList) { 5628 StdInitializerList = LookupStdInitializerList(*this, Loc); 5629 if (!StdInitializerList) 5630 return QualType(); 5631 } 5632 5633 TemplateArgumentListInfo Args(Loc, Loc); 5634 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 5635 Context.getTrivialTypeSourceInfo(Element, 5636 Loc))); 5637 return Context.getCanonicalType( 5638 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 5639} 5640 5641bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) { 5642 // C++ [dcl.init.list]p2: 5643 // A constructor is an initializer-list constructor if its first parameter 5644 // is of type std::initializer_list<E> or reference to possibly cv-qualified 5645 // std::initializer_list<E> for some type E, and either there are no other 5646 // parameters or else all other parameters have default arguments. 5647 if (Ctor->getNumParams() < 1 || 5648 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 5649 return false; 5650 5651 QualType ArgType = Ctor->getParamDecl(0)->getType(); 5652 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 5653 ArgType = RT->getPointeeType().getUnqualifiedType(); 5654 5655 return isStdInitializerList(ArgType, 0); 5656} 5657 5658/// \brief Determine whether a using statement is in a context where it will be 5659/// apply in all contexts. 5660static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 5661 switch (CurContext->getDeclKind()) { 5662 case Decl::TranslationUnit: 5663 return true; 5664 case Decl::LinkageSpec: 5665 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 5666 default: 5667 return false; 5668 } 5669} 5670 5671namespace { 5672 5673// Callback to only accept typo corrections that are namespaces. 5674class NamespaceValidatorCCC : public CorrectionCandidateCallback { 5675 public: 5676 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 5677 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 5678 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 5679 } 5680 return false; 5681 } 5682}; 5683 5684} 5685 5686static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 5687 CXXScopeSpec &SS, 5688 SourceLocation IdentLoc, 5689 IdentifierInfo *Ident) { 5690 NamespaceValidatorCCC Validator; 5691 R.clear(); 5692 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(), 5693 R.getLookupKind(), Sc, &SS, 5694 Validator)) { 5695 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 5696 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts())); 5697 if (DeclContext *DC = S.computeDeclContext(SS, false)) 5698 S.Diag(IdentLoc, diag::err_using_directive_member_suggest) 5699 << Ident << DC << CorrectedQuotedStr << SS.getRange() 5700 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr); 5701 else 5702 S.Diag(IdentLoc, diag::err_using_directive_suggest) 5703 << Ident << CorrectedQuotedStr 5704 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr); 5705 5706 S.Diag(Corrected.getCorrectionDecl()->getLocation(), 5707 diag::note_namespace_defined_here) << CorrectedQuotedStr; 5708 5709 R.addDecl(Corrected.getCorrectionDecl()); 5710 return true; 5711 } 5712 return false; 5713} 5714 5715Decl *Sema::ActOnUsingDirective(Scope *S, 5716 SourceLocation UsingLoc, 5717 SourceLocation NamespcLoc, 5718 CXXScopeSpec &SS, 5719 SourceLocation IdentLoc, 5720 IdentifierInfo *NamespcName, 5721 AttributeList *AttrList) { 5722 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 5723 assert(NamespcName && "Invalid NamespcName."); 5724 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 5725 5726 // This can only happen along a recovery path. 5727 while (S->getFlags() & Scope::TemplateParamScope) 5728 S = S->getParent(); 5729 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 5730 5731 UsingDirectiveDecl *UDir = 0; 5732 NestedNameSpecifier *Qualifier = 0; 5733 if (SS.isSet()) 5734 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 5735 5736 // Lookup namespace name. 5737 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 5738 LookupParsedName(R, S, &SS); 5739 if (R.isAmbiguous()) 5740 return 0; 5741 5742 if (R.empty()) { 5743 R.clear(); 5744 // Allow "using namespace std;" or "using namespace ::std;" even if 5745 // "std" hasn't been defined yet, for GCC compatibility. 5746 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 5747 NamespcName->isStr("std")) { 5748 Diag(IdentLoc, diag::ext_using_undefined_std); 5749 R.addDecl(getOrCreateStdNamespace()); 5750 R.resolveKind(); 5751 } 5752 // Otherwise, attempt typo correction. 5753 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 5754 } 5755 5756 if (!R.empty()) { 5757 NamedDecl *Named = R.getFoundDecl(); 5758 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named)) 5759 && "expected namespace decl"); 5760 // C++ [namespace.udir]p1: 5761 // A using-directive specifies that the names in the nominated 5762 // namespace can be used in the scope in which the 5763 // using-directive appears after the using-directive. During 5764 // unqualified name lookup (3.4.1), the names appear as if they 5765 // were declared in the nearest enclosing namespace which 5766 // contains both the using-directive and the nominated 5767 // namespace. [Note: in this context, "contains" means "contains 5768 // directly or indirectly". ] 5769 5770 // Find enclosing context containing both using-directive and 5771 // nominated namespace. 5772 NamespaceDecl *NS = getNamespaceDecl(Named); 5773 DeclContext *CommonAncestor = cast<DeclContext>(NS); 5774 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 5775 CommonAncestor = CommonAncestor->getParent(); 5776 5777 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 5778 SS.getWithLocInContext(Context), 5779 IdentLoc, Named, CommonAncestor); 5780 5781 if (IsUsingDirectiveInToplevelContext(CurContext) && 5782 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 5783 Diag(IdentLoc, diag::warn_using_directive_in_header); 5784 } 5785 5786 PushUsingDirective(S, UDir); 5787 } else { 5788 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 5789 } 5790 5791 // FIXME: We ignore attributes for now. 5792 return UDir; 5793} 5794 5795void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 5796 // If the scope has an associated entity and the using directive is at 5797 // namespace or translation unit scope, add the UsingDirectiveDecl into 5798 // its lookup structure so qualified name lookup can find it. 5799 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()); 5800 if (Ctx && !Ctx->isFunctionOrMethod()) 5801 Ctx->addDecl(UDir); 5802 else 5803 // Otherwise, it is at block sope. The using-directives will affect lookup 5804 // only to the end of the scope. 5805 S->PushUsingDirective(UDir); 5806} 5807 5808 5809Decl *Sema::ActOnUsingDeclaration(Scope *S, 5810 AccessSpecifier AS, 5811 bool HasUsingKeyword, 5812 SourceLocation UsingLoc, 5813 CXXScopeSpec &SS, 5814 UnqualifiedId &Name, 5815 AttributeList *AttrList, 5816 bool IsTypeName, 5817 SourceLocation TypenameLoc) { 5818 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 5819 5820 switch (Name.getKind()) { 5821 case UnqualifiedId::IK_ImplicitSelfParam: 5822 case UnqualifiedId::IK_Identifier: 5823 case UnqualifiedId::IK_OperatorFunctionId: 5824 case UnqualifiedId::IK_LiteralOperatorId: 5825 case UnqualifiedId::IK_ConversionFunctionId: 5826 break; 5827 5828 case UnqualifiedId::IK_ConstructorName: 5829 case UnqualifiedId::IK_ConstructorTemplateId: 5830 // C++11 inheriting constructors. 5831 Diag(Name.getLocStart(), 5832 getLangOpts().CPlusPlus0x ? 5833 // FIXME: Produce warn_cxx98_compat_using_decl_constructor 5834 // instead once inheriting constructors work. 5835 diag::err_using_decl_constructor_unsupported : 5836 diag::err_using_decl_constructor) 5837 << SS.getRange(); 5838 5839 if (getLangOpts().CPlusPlus0x) break; 5840 5841 return 0; 5842 5843 case UnqualifiedId::IK_DestructorName: 5844 Diag(Name.getLocStart(), diag::err_using_decl_destructor) 5845 << SS.getRange(); 5846 return 0; 5847 5848 case UnqualifiedId::IK_TemplateId: 5849 Diag(Name.getLocStart(), diag::err_using_decl_template_id) 5850 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 5851 return 0; 5852 } 5853 5854 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 5855 DeclarationName TargetName = TargetNameInfo.getName(); 5856 if (!TargetName) 5857 return 0; 5858 5859 // Warn about using declarations. 5860 // TODO: store that the declaration was written without 'using' and 5861 // talk about access decls instead of using decls in the 5862 // diagnostics. 5863 if (!HasUsingKeyword) { 5864 UsingLoc = Name.getLocStart(); 5865 5866 Diag(UsingLoc, diag::warn_access_decl_deprecated) 5867 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 5868 } 5869 5870 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 5871 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 5872 return 0; 5873 5874 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 5875 TargetNameInfo, AttrList, 5876 /* IsInstantiation */ false, 5877 IsTypeName, TypenameLoc); 5878 if (UD) 5879 PushOnScopeChains(UD, S, /*AddToContext*/ false); 5880 5881 return UD; 5882} 5883 5884/// \brief Determine whether a using declaration considers the given 5885/// declarations as "equivalent", e.g., if they are redeclarations of 5886/// the same entity or are both typedefs of the same type. 5887static bool 5888IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2, 5889 bool &SuppressRedeclaration) { 5890 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) { 5891 SuppressRedeclaration = false; 5892 return true; 5893 } 5894 5895 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 5896 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) { 5897 SuppressRedeclaration = true; 5898 return Context.hasSameType(TD1->getUnderlyingType(), 5899 TD2->getUnderlyingType()); 5900 } 5901 5902 return false; 5903} 5904 5905 5906/// Determines whether to create a using shadow decl for a particular 5907/// decl, given the set of decls existing prior to this using lookup. 5908bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 5909 const LookupResult &Previous) { 5910 // Diagnose finding a decl which is not from a base class of the 5911 // current class. We do this now because there are cases where this 5912 // function will silently decide not to build a shadow decl, which 5913 // will pre-empt further diagnostics. 5914 // 5915 // We don't need to do this in C++0x because we do the check once on 5916 // the qualifier. 5917 // 5918 // FIXME: diagnose the following if we care enough: 5919 // struct A { int foo; }; 5920 // struct B : A { using A::foo; }; 5921 // template <class T> struct C : A {}; 5922 // template <class T> struct D : C<T> { using B::foo; } // <--- 5923 // This is invalid (during instantiation) in C++03 because B::foo 5924 // resolves to the using decl in B, which is not a base class of D<T>. 5925 // We can't diagnose it immediately because C<T> is an unknown 5926 // specialization. The UsingShadowDecl in D<T> then points directly 5927 // to A::foo, which will look well-formed when we instantiate. 5928 // The right solution is to not collapse the shadow-decl chain. 5929 if (!getLangOpts().CPlusPlus0x && CurContext->isRecord()) { 5930 DeclContext *OrigDC = Orig->getDeclContext(); 5931 5932 // Handle enums and anonymous structs. 5933 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 5934 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 5935 while (OrigRec->isAnonymousStructOrUnion()) 5936 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 5937 5938 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 5939 if (OrigDC == CurContext) { 5940 Diag(Using->getLocation(), 5941 diag::err_using_decl_nested_name_specifier_is_current_class) 5942 << Using->getQualifierLoc().getSourceRange(); 5943 Diag(Orig->getLocation(), diag::note_using_decl_target); 5944 return true; 5945 } 5946 5947 Diag(Using->getQualifierLoc().getBeginLoc(), 5948 diag::err_using_decl_nested_name_specifier_is_not_base_class) 5949 << Using->getQualifier() 5950 << cast<CXXRecordDecl>(CurContext) 5951 << Using->getQualifierLoc().getSourceRange(); 5952 Diag(Orig->getLocation(), diag::note_using_decl_target); 5953 return true; 5954 } 5955 } 5956 5957 if (Previous.empty()) return false; 5958 5959 NamedDecl *Target = Orig; 5960 if (isa<UsingShadowDecl>(Target)) 5961 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 5962 5963 // If the target happens to be one of the previous declarations, we 5964 // don't have a conflict. 5965 // 5966 // FIXME: but we might be increasing its access, in which case we 5967 // should redeclare it. 5968 NamedDecl *NonTag = 0, *Tag = 0; 5969 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 5970 I != E; ++I) { 5971 NamedDecl *D = (*I)->getUnderlyingDecl(); 5972 bool Result; 5973 if (IsEquivalentForUsingDecl(Context, D, Target, Result)) 5974 return Result; 5975 5976 (isa<TagDecl>(D) ? Tag : NonTag) = D; 5977 } 5978 5979 if (Target->isFunctionOrFunctionTemplate()) { 5980 FunctionDecl *FD; 5981 if (isa<FunctionTemplateDecl>(Target)) 5982 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl(); 5983 else 5984 FD = cast<FunctionDecl>(Target); 5985 5986 NamedDecl *OldDecl = 0; 5987 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) { 5988 case Ovl_Overload: 5989 return false; 5990 5991 case Ovl_NonFunction: 5992 Diag(Using->getLocation(), diag::err_using_decl_conflict); 5993 break; 5994 5995 // We found a decl with the exact signature. 5996 case Ovl_Match: 5997 // If we're in a record, we want to hide the target, so we 5998 // return true (without a diagnostic) to tell the caller not to 5999 // build a shadow decl. 6000 if (CurContext->isRecord()) 6001 return true; 6002 6003 // If we're not in a record, this is an error. 6004 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6005 break; 6006 } 6007 6008 Diag(Target->getLocation(), diag::note_using_decl_target); 6009 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 6010 return true; 6011 } 6012 6013 // Target is not a function. 6014 6015 if (isa<TagDecl>(Target)) { 6016 // No conflict between a tag and a non-tag. 6017 if (!Tag) return false; 6018 6019 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6020 Diag(Target->getLocation(), diag::note_using_decl_target); 6021 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 6022 return true; 6023 } 6024 6025 // No conflict between a tag and a non-tag. 6026 if (!NonTag) return false; 6027 6028 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6029 Diag(Target->getLocation(), diag::note_using_decl_target); 6030 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 6031 return true; 6032} 6033 6034/// Builds a shadow declaration corresponding to a 'using' declaration. 6035UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 6036 UsingDecl *UD, 6037 NamedDecl *Orig) { 6038 6039 // If we resolved to another shadow declaration, just coalesce them. 6040 NamedDecl *Target = Orig; 6041 if (isa<UsingShadowDecl>(Target)) { 6042 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 6043 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 6044 } 6045 6046 UsingShadowDecl *Shadow 6047 = UsingShadowDecl::Create(Context, CurContext, 6048 UD->getLocation(), UD, Target); 6049 UD->addShadowDecl(Shadow); 6050 6051 Shadow->setAccess(UD->getAccess()); 6052 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 6053 Shadow->setInvalidDecl(); 6054 6055 if (S) 6056 PushOnScopeChains(Shadow, S); 6057 else 6058 CurContext->addDecl(Shadow); 6059 6060 6061 return Shadow; 6062} 6063 6064/// Hides a using shadow declaration. This is required by the current 6065/// using-decl implementation when a resolvable using declaration in a 6066/// class is followed by a declaration which would hide or override 6067/// one or more of the using decl's targets; for example: 6068/// 6069/// struct Base { void foo(int); }; 6070/// struct Derived : Base { 6071/// using Base::foo; 6072/// void foo(int); 6073/// }; 6074/// 6075/// The governing language is C++03 [namespace.udecl]p12: 6076/// 6077/// When a using-declaration brings names from a base class into a 6078/// derived class scope, member functions in the derived class 6079/// override and/or hide member functions with the same name and 6080/// parameter types in a base class (rather than conflicting). 6081/// 6082/// There are two ways to implement this: 6083/// (1) optimistically create shadow decls when they're not hidden 6084/// by existing declarations, or 6085/// (2) don't create any shadow decls (or at least don't make them 6086/// visible) until we've fully parsed/instantiated the class. 6087/// The problem with (1) is that we might have to retroactively remove 6088/// a shadow decl, which requires several O(n) operations because the 6089/// decl structures are (very reasonably) not designed for removal. 6090/// (2) avoids this but is very fiddly and phase-dependent. 6091void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 6092 if (Shadow->getDeclName().getNameKind() == 6093 DeclarationName::CXXConversionFunctionName) 6094 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 6095 6096 // Remove it from the DeclContext... 6097 Shadow->getDeclContext()->removeDecl(Shadow); 6098 6099 // ...and the scope, if applicable... 6100 if (S) { 6101 S->RemoveDecl(Shadow); 6102 IdResolver.RemoveDecl(Shadow); 6103 } 6104 6105 // ...and the using decl. 6106 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 6107 6108 // TODO: complain somehow if Shadow was used. It shouldn't 6109 // be possible for this to happen, because...? 6110} 6111 6112/// Builds a using declaration. 6113/// 6114/// \param IsInstantiation - Whether this call arises from an 6115/// instantiation of an unresolved using declaration. We treat 6116/// the lookup differently for these declarations. 6117NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 6118 SourceLocation UsingLoc, 6119 CXXScopeSpec &SS, 6120 const DeclarationNameInfo &NameInfo, 6121 AttributeList *AttrList, 6122 bool IsInstantiation, 6123 bool IsTypeName, 6124 SourceLocation TypenameLoc) { 6125 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 6126 SourceLocation IdentLoc = NameInfo.getLoc(); 6127 assert(IdentLoc.isValid() && "Invalid TargetName location."); 6128 6129 // FIXME: We ignore attributes for now. 6130 6131 if (SS.isEmpty()) { 6132 Diag(IdentLoc, diag::err_using_requires_qualname); 6133 return 0; 6134 } 6135 6136 // Do the redeclaration lookup in the current scope. 6137 LookupResult Previous(*this, NameInfo, LookupUsingDeclName, 6138 ForRedeclaration); 6139 Previous.setHideTags(false); 6140 if (S) { 6141 LookupName(Previous, S); 6142 6143 // It is really dumb that we have to do this. 6144 LookupResult::Filter F = Previous.makeFilter(); 6145 while (F.hasNext()) { 6146 NamedDecl *D = F.next(); 6147 if (!isDeclInScope(D, CurContext, S)) 6148 F.erase(); 6149 } 6150 F.done(); 6151 } else { 6152 assert(IsInstantiation && "no scope in non-instantiation"); 6153 assert(CurContext->isRecord() && "scope not record in instantiation"); 6154 LookupQualifiedName(Previous, CurContext); 6155 } 6156 6157 // Check for invalid redeclarations. 6158 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous)) 6159 return 0; 6160 6161 // Check for bad qualifiers. 6162 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc)) 6163 return 0; 6164 6165 DeclContext *LookupContext = computeDeclContext(SS); 6166 NamedDecl *D; 6167 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 6168 if (!LookupContext) { 6169 if (IsTypeName) { 6170 // FIXME: not all declaration name kinds are legal here 6171 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 6172 UsingLoc, TypenameLoc, 6173 QualifierLoc, 6174 IdentLoc, NameInfo.getName()); 6175 } else { 6176 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 6177 QualifierLoc, NameInfo); 6178 } 6179 } else { 6180 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 6181 NameInfo, IsTypeName); 6182 } 6183 D->setAccess(AS); 6184 CurContext->addDecl(D); 6185 6186 if (!LookupContext) return D; 6187 UsingDecl *UD = cast<UsingDecl>(D); 6188 6189 if (RequireCompleteDeclContext(SS, LookupContext)) { 6190 UD->setInvalidDecl(); 6191 return UD; 6192 } 6193 6194 // The normal rules do not apply to inheriting constructor declarations. 6195 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) { 6196 if (CheckInheritingConstructorUsingDecl(UD)) 6197 UD->setInvalidDecl(); 6198 return UD; 6199 } 6200 6201 // Otherwise, look up the target name. 6202 6203 LookupResult R(*this, NameInfo, LookupOrdinaryName); 6204 6205 // Unlike most lookups, we don't always want to hide tag 6206 // declarations: tag names are visible through the using declaration 6207 // even if hidden by ordinary names, *except* in a dependent context 6208 // where it's important for the sanity of two-phase lookup. 6209 if (!IsInstantiation) 6210 R.setHideTags(false); 6211 6212 // For the purposes of this lookup, we have a base object type 6213 // equal to that of the current context. 6214 if (CurContext->isRecord()) { 6215 R.setBaseObjectType( 6216 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 6217 } 6218 6219 LookupQualifiedName(R, LookupContext); 6220 6221 if (R.empty()) { 6222 Diag(IdentLoc, diag::err_no_member) 6223 << NameInfo.getName() << LookupContext << SS.getRange(); 6224 UD->setInvalidDecl(); 6225 return UD; 6226 } 6227 6228 if (R.isAmbiguous()) { 6229 UD->setInvalidDecl(); 6230 return UD; 6231 } 6232 6233 if (IsTypeName) { 6234 // If we asked for a typename and got a non-type decl, error out. 6235 if (!R.getAsSingle<TypeDecl>()) { 6236 Diag(IdentLoc, diag::err_using_typename_non_type); 6237 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 6238 Diag((*I)->getUnderlyingDecl()->getLocation(), 6239 diag::note_using_decl_target); 6240 UD->setInvalidDecl(); 6241 return UD; 6242 } 6243 } else { 6244 // If we asked for a non-typename and we got a type, error out, 6245 // but only if this is an instantiation of an unresolved using 6246 // decl. Otherwise just silently find the type name. 6247 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 6248 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 6249 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 6250 UD->setInvalidDecl(); 6251 return UD; 6252 } 6253 } 6254 6255 // C++0x N2914 [namespace.udecl]p6: 6256 // A using-declaration shall not name a namespace. 6257 if (R.getAsSingle<NamespaceDecl>()) { 6258 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 6259 << SS.getRange(); 6260 UD->setInvalidDecl(); 6261 return UD; 6262 } 6263 6264 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 6265 if (!CheckUsingShadowDecl(UD, *I, Previous)) 6266 BuildUsingShadowDecl(S, UD, *I); 6267 } 6268 6269 return UD; 6270} 6271 6272/// Additional checks for a using declaration referring to a constructor name. 6273bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 6274 assert(!UD->isTypeName() && "expecting a constructor name"); 6275 6276 const Type *SourceType = UD->getQualifier()->getAsType(); 6277 assert(SourceType && 6278 "Using decl naming constructor doesn't have type in scope spec."); 6279 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 6280 6281 // Check whether the named type is a direct base class. 6282 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified(); 6283 CXXRecordDecl::base_class_iterator BaseIt, BaseE; 6284 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end(); 6285 BaseIt != BaseE; ++BaseIt) { 6286 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified(); 6287 if (CanonicalSourceType == BaseType) 6288 break; 6289 if (BaseIt->getType()->isDependentType()) 6290 break; 6291 } 6292 6293 if (BaseIt == BaseE) { 6294 // Did not find SourceType in the bases. 6295 Diag(UD->getUsingLocation(), 6296 diag::err_using_decl_constructor_not_in_direct_base) 6297 << UD->getNameInfo().getSourceRange() 6298 << QualType(SourceType, 0) << TargetClass; 6299 return true; 6300 } 6301 6302 if (!CurContext->isDependentContext()) 6303 BaseIt->setInheritConstructors(); 6304 6305 return false; 6306} 6307 6308/// Checks that the given using declaration is not an invalid 6309/// redeclaration. Note that this is checking only for the using decl 6310/// itself, not for any ill-formedness among the UsingShadowDecls. 6311bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 6312 bool isTypeName, 6313 const CXXScopeSpec &SS, 6314 SourceLocation NameLoc, 6315 const LookupResult &Prev) { 6316 // C++03 [namespace.udecl]p8: 6317 // C++0x [namespace.udecl]p10: 6318 // A using-declaration is a declaration and can therefore be used 6319 // repeatedly where (and only where) multiple declarations are 6320 // allowed. 6321 // 6322 // That's in non-member contexts. 6323 if (!CurContext->getRedeclContext()->isRecord()) 6324 return false; 6325 6326 NestedNameSpecifier *Qual 6327 = static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 6328 6329 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 6330 NamedDecl *D = *I; 6331 6332 bool DTypename; 6333 NestedNameSpecifier *DQual; 6334 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 6335 DTypename = UD->isTypeName(); 6336 DQual = UD->getQualifier(); 6337 } else if (UnresolvedUsingValueDecl *UD 6338 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 6339 DTypename = false; 6340 DQual = UD->getQualifier(); 6341 } else if (UnresolvedUsingTypenameDecl *UD 6342 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 6343 DTypename = true; 6344 DQual = UD->getQualifier(); 6345 } else continue; 6346 6347 // using decls differ if one says 'typename' and the other doesn't. 6348 // FIXME: non-dependent using decls? 6349 if (isTypeName != DTypename) continue; 6350 6351 // using decls differ if they name different scopes (but note that 6352 // template instantiation can cause this check to trigger when it 6353 // didn't before instantiation). 6354 if (Context.getCanonicalNestedNameSpecifier(Qual) != 6355 Context.getCanonicalNestedNameSpecifier(DQual)) 6356 continue; 6357 6358 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 6359 Diag(D->getLocation(), diag::note_using_decl) << 1; 6360 return true; 6361 } 6362 6363 return false; 6364} 6365 6366 6367/// Checks that the given nested-name qualifier used in a using decl 6368/// in the current context is appropriately related to the current 6369/// scope. If an error is found, diagnoses it and returns true. 6370bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 6371 const CXXScopeSpec &SS, 6372 SourceLocation NameLoc) { 6373 DeclContext *NamedContext = computeDeclContext(SS); 6374 6375 if (!CurContext->isRecord()) { 6376 // C++03 [namespace.udecl]p3: 6377 // C++0x [namespace.udecl]p8: 6378 // A using-declaration for a class member shall be a member-declaration. 6379 6380 // If we weren't able to compute a valid scope, it must be a 6381 // dependent class scope. 6382 if (!NamedContext || NamedContext->isRecord()) { 6383 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 6384 << SS.getRange(); 6385 return true; 6386 } 6387 6388 // Otherwise, everything is known to be fine. 6389 return false; 6390 } 6391 6392 // The current scope is a record. 6393 6394 // If the named context is dependent, we can't decide much. 6395 if (!NamedContext) { 6396 // FIXME: in C++0x, we can diagnose if we can prove that the 6397 // nested-name-specifier does not refer to a base class, which is 6398 // still possible in some cases. 6399 6400 // Otherwise we have to conservatively report that things might be 6401 // okay. 6402 return false; 6403 } 6404 6405 if (!NamedContext->isRecord()) { 6406 // Ideally this would point at the last name in the specifier, 6407 // but we don't have that level of source info. 6408 Diag(SS.getRange().getBegin(), 6409 diag::err_using_decl_nested_name_specifier_is_not_class) 6410 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange(); 6411 return true; 6412 } 6413 6414 if (!NamedContext->isDependentContext() && 6415 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 6416 return true; 6417 6418 if (getLangOpts().CPlusPlus0x) { 6419 // C++0x [namespace.udecl]p3: 6420 // In a using-declaration used as a member-declaration, the 6421 // nested-name-specifier shall name a base class of the class 6422 // being defined. 6423 6424 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 6425 cast<CXXRecordDecl>(NamedContext))) { 6426 if (CurContext == NamedContext) { 6427 Diag(NameLoc, 6428 diag::err_using_decl_nested_name_specifier_is_current_class) 6429 << SS.getRange(); 6430 return true; 6431 } 6432 6433 Diag(SS.getRange().getBegin(), 6434 diag::err_using_decl_nested_name_specifier_is_not_base_class) 6435 << (NestedNameSpecifier*) SS.getScopeRep() 6436 << cast<CXXRecordDecl>(CurContext) 6437 << SS.getRange(); 6438 return true; 6439 } 6440 6441 return false; 6442 } 6443 6444 // C++03 [namespace.udecl]p4: 6445 // A using-declaration used as a member-declaration shall refer 6446 // to a member of a base class of the class being defined [etc.]. 6447 6448 // Salient point: SS doesn't have to name a base class as long as 6449 // lookup only finds members from base classes. Therefore we can 6450 // diagnose here only if we can prove that that can't happen, 6451 // i.e. if the class hierarchies provably don't intersect. 6452 6453 // TODO: it would be nice if "definitely valid" results were cached 6454 // in the UsingDecl and UsingShadowDecl so that these checks didn't 6455 // need to be repeated. 6456 6457 struct UserData { 6458 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases; 6459 6460 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) { 6461 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 6462 Data->Bases.insert(Base); 6463 return true; 6464 } 6465 6466 bool hasDependentBases(const CXXRecordDecl *Class) { 6467 return !Class->forallBases(collect, this); 6468 } 6469 6470 /// Returns true if the base is dependent or is one of the 6471 /// accumulated base classes. 6472 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) { 6473 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 6474 return !Data->Bases.count(Base); 6475 } 6476 6477 bool mightShareBases(const CXXRecordDecl *Class) { 6478 return Bases.count(Class) || !Class->forallBases(doesNotContain, this); 6479 } 6480 }; 6481 6482 UserData Data; 6483 6484 // Returns false if we find a dependent base. 6485 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext))) 6486 return false; 6487 6488 // Returns false if the class has a dependent base or if it or one 6489 // of its bases is present in the base set of the current context. 6490 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext))) 6491 return false; 6492 6493 Diag(SS.getRange().getBegin(), 6494 diag::err_using_decl_nested_name_specifier_is_not_base_class) 6495 << (NestedNameSpecifier*) SS.getScopeRep() 6496 << cast<CXXRecordDecl>(CurContext) 6497 << SS.getRange(); 6498 6499 return true; 6500} 6501 6502Decl *Sema::ActOnAliasDeclaration(Scope *S, 6503 AccessSpecifier AS, 6504 MultiTemplateParamsArg TemplateParamLists, 6505 SourceLocation UsingLoc, 6506 UnqualifiedId &Name, 6507 TypeResult Type) { 6508 // Skip up to the relevant declaration scope. 6509 while (S->getFlags() & Scope::TemplateParamScope) 6510 S = S->getParent(); 6511 assert((S->getFlags() & Scope::DeclScope) && 6512 "got alias-declaration outside of declaration scope"); 6513 6514 if (Type.isInvalid()) 6515 return 0; 6516 6517 bool Invalid = false; 6518 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 6519 TypeSourceInfo *TInfo = 0; 6520 GetTypeFromParser(Type.get(), &TInfo); 6521 6522 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 6523 return 0; 6524 6525 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 6526 UPPC_DeclarationType)) { 6527 Invalid = true; 6528 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 6529 TInfo->getTypeLoc().getBeginLoc()); 6530 } 6531 6532 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration); 6533 LookupName(Previous, S); 6534 6535 // Warn about shadowing the name of a template parameter. 6536 if (Previous.isSingleResult() && 6537 Previous.getFoundDecl()->isTemplateParameter()) { 6538 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 6539 Previous.clear(); 6540 } 6541 6542 assert(Name.Kind == UnqualifiedId::IK_Identifier && 6543 "name in alias declaration must be an identifier"); 6544 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 6545 Name.StartLocation, 6546 Name.Identifier, TInfo); 6547 6548 NewTD->setAccess(AS); 6549 6550 if (Invalid) 6551 NewTD->setInvalidDecl(); 6552 6553 CheckTypedefForVariablyModifiedType(S, NewTD); 6554 Invalid |= NewTD->isInvalidDecl(); 6555 6556 bool Redeclaration = false; 6557 6558 NamedDecl *NewND; 6559 if (TemplateParamLists.size()) { 6560 TypeAliasTemplateDecl *OldDecl = 0; 6561 TemplateParameterList *OldTemplateParams = 0; 6562 6563 if (TemplateParamLists.size() != 1) { 6564 Diag(UsingLoc, diag::err_alias_template_extra_headers) 6565 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(), 6566 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc()); 6567 } 6568 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0]; 6569 6570 // Only consider previous declarations in the same scope. 6571 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 6572 /*ExplicitInstantiationOrSpecialization*/false); 6573 if (!Previous.empty()) { 6574 Redeclaration = true; 6575 6576 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 6577 if (!OldDecl && !Invalid) { 6578 Diag(UsingLoc, diag::err_redefinition_different_kind) 6579 << Name.Identifier; 6580 6581 NamedDecl *OldD = Previous.getRepresentativeDecl(); 6582 if (OldD->getLocation().isValid()) 6583 Diag(OldD->getLocation(), diag::note_previous_definition); 6584 6585 Invalid = true; 6586 } 6587 6588 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 6589 if (TemplateParameterListsAreEqual(TemplateParams, 6590 OldDecl->getTemplateParameters(), 6591 /*Complain=*/true, 6592 TPL_TemplateMatch)) 6593 OldTemplateParams = OldDecl->getTemplateParameters(); 6594 else 6595 Invalid = true; 6596 6597 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 6598 if (!Invalid && 6599 !Context.hasSameType(OldTD->getUnderlyingType(), 6600 NewTD->getUnderlyingType())) { 6601 // FIXME: The C++0x standard does not clearly say this is ill-formed, 6602 // but we can't reasonably accept it. 6603 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 6604 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 6605 if (OldTD->getLocation().isValid()) 6606 Diag(OldTD->getLocation(), diag::note_previous_definition); 6607 Invalid = true; 6608 } 6609 } 6610 } 6611 6612 // Merge any previous default template arguments into our parameters, 6613 // and check the parameter list. 6614 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 6615 TPC_TypeAliasTemplate)) 6616 return 0; 6617 6618 TypeAliasTemplateDecl *NewDecl = 6619 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 6620 Name.Identifier, TemplateParams, 6621 NewTD); 6622 6623 NewDecl->setAccess(AS); 6624 6625 if (Invalid) 6626 NewDecl->setInvalidDecl(); 6627 else if (OldDecl) 6628 NewDecl->setPreviousDeclaration(OldDecl); 6629 6630 NewND = NewDecl; 6631 } else { 6632 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 6633 NewND = NewTD; 6634 } 6635 6636 if (!Redeclaration) 6637 PushOnScopeChains(NewND, S); 6638 6639 ActOnDocumentableDecl(NewND); 6640 return NewND; 6641} 6642 6643Decl *Sema::ActOnNamespaceAliasDef(Scope *S, 6644 SourceLocation NamespaceLoc, 6645 SourceLocation AliasLoc, 6646 IdentifierInfo *Alias, 6647 CXXScopeSpec &SS, 6648 SourceLocation IdentLoc, 6649 IdentifierInfo *Ident) { 6650 6651 // Lookup the namespace name. 6652 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 6653 LookupParsedName(R, S, &SS); 6654 6655 // Check if we have a previous declaration with the same name. 6656 NamedDecl *PrevDecl 6657 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName, 6658 ForRedeclaration); 6659 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S)) 6660 PrevDecl = 0; 6661 6662 if (PrevDecl) { 6663 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 6664 // We already have an alias with the same name that points to the same 6665 // namespace, so don't create a new one. 6666 // FIXME: At some point, we'll want to create the (redundant) 6667 // declaration to maintain better source information. 6668 if (!R.isAmbiguous() && !R.empty() && 6669 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl()))) 6670 return 0; 6671 } 6672 6673 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition : 6674 diag::err_redefinition_different_kind; 6675 Diag(AliasLoc, DiagID) << Alias; 6676 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 6677 return 0; 6678 } 6679 6680 if (R.isAmbiguous()) 6681 return 0; 6682 6683 if (R.empty()) { 6684 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 6685 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 6686 return 0; 6687 } 6688 } 6689 6690 NamespaceAliasDecl *AliasDecl = 6691 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 6692 Alias, SS.getWithLocInContext(Context), 6693 IdentLoc, R.getFoundDecl()); 6694 6695 PushOnScopeChains(AliasDecl, S); 6696 return AliasDecl; 6697} 6698 6699namespace { 6700 /// \brief Scoped object used to handle the state changes required in Sema 6701 /// to implicitly define the body of a C++ member function; 6702 class ImplicitlyDefinedFunctionScope { 6703 Sema &S; 6704 Sema::ContextRAII SavedContext; 6705 6706 public: 6707 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method) 6708 : S(S), SavedContext(S, Method) 6709 { 6710 S.PushFunctionScope(); 6711 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated); 6712 } 6713 6714 ~ImplicitlyDefinedFunctionScope() { 6715 S.PopExpressionEvaluationContext(); 6716 S.PopFunctionScopeInfo(); 6717 } 6718 }; 6719} 6720 6721Sema::ImplicitExceptionSpecification 6722Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, 6723 CXXMethodDecl *MD) { 6724 CXXRecordDecl *ClassDecl = MD->getParent(); 6725 6726 // C++ [except.spec]p14: 6727 // An implicitly declared special member function (Clause 12) shall have an 6728 // exception-specification. [...] 6729 ImplicitExceptionSpecification ExceptSpec(*this); 6730 if (ClassDecl->isInvalidDecl()) 6731 return ExceptSpec; 6732 6733 // Direct base-class constructors. 6734 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 6735 BEnd = ClassDecl->bases_end(); 6736 B != BEnd; ++B) { 6737 if (B->isVirtual()) // Handled below. 6738 continue; 6739 6740 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 6741 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 6742 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 6743 // If this is a deleted function, add it anyway. This might be conformant 6744 // with the standard. This might not. I'm not sure. It might not matter. 6745 if (Constructor) 6746 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 6747 } 6748 } 6749 6750 // Virtual base-class constructors. 6751 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 6752 BEnd = ClassDecl->vbases_end(); 6753 B != BEnd; ++B) { 6754 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 6755 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 6756 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 6757 // If this is a deleted function, add it anyway. This might be conformant 6758 // with the standard. This might not. I'm not sure. It might not matter. 6759 if (Constructor) 6760 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 6761 } 6762 } 6763 6764 // Field constructors. 6765 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 6766 FEnd = ClassDecl->field_end(); 6767 F != FEnd; ++F) { 6768 if (F->hasInClassInitializer()) { 6769 if (Expr *E = F->getInClassInitializer()) 6770 ExceptSpec.CalledExpr(E); 6771 else if (!F->isInvalidDecl()) 6772 // DR1351: 6773 // If the brace-or-equal-initializer of a non-static data member 6774 // invokes a defaulted default constructor of its class or of an 6775 // enclosing class in a potentially evaluated subexpression, the 6776 // program is ill-formed. 6777 // 6778 // This resolution is unworkable: the exception specification of the 6779 // default constructor can be needed in an unevaluated context, in 6780 // particular, in the operand of a noexcept-expression, and we can be 6781 // unable to compute an exception specification for an enclosed class. 6782 // 6783 // We do not allow an in-class initializer to require the evaluation 6784 // of the exception specification for any in-class initializer whose 6785 // definition is not lexically complete. 6786 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD; 6787 } else if (const RecordType *RecordTy 6788 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 6789 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 6790 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 6791 // If this is a deleted function, add it anyway. This might be conformant 6792 // with the standard. This might not. I'm not sure. It might not matter. 6793 // In particular, the problem is that this function never gets called. It 6794 // might just be ill-formed because this function attempts to refer to 6795 // a deleted function here. 6796 if (Constructor) 6797 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 6798 } 6799 } 6800 6801 return ExceptSpec; 6802} 6803 6804CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 6805 CXXRecordDecl *ClassDecl) { 6806 // C++ [class.ctor]p5: 6807 // A default constructor for a class X is a constructor of class X 6808 // that can be called without an argument. If there is no 6809 // user-declared constructor for class X, a default constructor is 6810 // implicitly declared. An implicitly-declared default constructor 6811 // is an inline public member of its class. 6812 assert(!ClassDecl->hasUserDeclaredConstructor() && 6813 "Should not build implicit default constructor!"); 6814 6815 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 6816 CXXDefaultConstructor, 6817 false); 6818 6819 // Create the actual constructor declaration. 6820 CanQualType ClassType 6821 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 6822 SourceLocation ClassLoc = ClassDecl->getLocation(); 6823 DeclarationName Name 6824 = Context.DeclarationNames.getCXXConstructorName(ClassType); 6825 DeclarationNameInfo NameInfo(Name, ClassLoc); 6826 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 6827 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0, 6828 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 6829 Constexpr); 6830 DefaultCon->setAccess(AS_public); 6831 DefaultCon->setDefaulted(); 6832 DefaultCon->setImplicit(); 6833 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 6834 6835 // Build an exception specification pointing back at this constructor. 6836 FunctionProtoType::ExtProtoInfo EPI; 6837 EPI.ExceptionSpecType = EST_Unevaluated; 6838 EPI.ExceptionSpecDecl = DefaultCon; 6839 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI)); 6840 6841 // Note that we have declared this constructor. 6842 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 6843 6844 if (Scope *S = getScopeForContext(ClassDecl)) 6845 PushOnScopeChains(DefaultCon, S, false); 6846 ClassDecl->addDecl(DefaultCon); 6847 6848 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 6849 DefaultCon->setDeletedAsWritten(); 6850 6851 return DefaultCon; 6852} 6853 6854void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 6855 CXXConstructorDecl *Constructor) { 6856 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 6857 !Constructor->doesThisDeclarationHaveABody() && 6858 !Constructor->isDeleted()) && 6859 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 6860 6861 CXXRecordDecl *ClassDecl = Constructor->getParent(); 6862 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 6863 6864 ImplicitlyDefinedFunctionScope Scope(*this, Constructor); 6865 DiagnosticErrorTrap Trap(Diags); 6866 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) || 6867 Trap.hasErrorOccurred()) { 6868 Diag(CurrentLocation, diag::note_member_synthesized_at) 6869 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl); 6870 Constructor->setInvalidDecl(); 6871 return; 6872 } 6873 6874 SourceLocation Loc = Constructor->getLocation(); 6875 Constructor->setBody(new (Context) CompoundStmt(Loc)); 6876 6877 Constructor->setUsed(); 6878 MarkVTableUsed(CurrentLocation, ClassDecl); 6879 6880 if (ASTMutationListener *L = getASTMutationListener()) { 6881 L->CompletedImplicitDefinition(Constructor); 6882 } 6883} 6884 6885void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 6886 if (!D) return; 6887 AdjustDeclIfTemplate(D); 6888 6889 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D); 6890 6891 if (!ClassDecl->isDependentType()) 6892 CheckExplicitlyDefaultedMethods(ClassDecl); 6893} 6894 6895void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) { 6896 // We start with an initial pass over the base classes to collect those that 6897 // inherit constructors from. If there are none, we can forgo all further 6898 // processing. 6899 typedef SmallVector<const RecordType *, 4> BasesVector; 6900 BasesVector BasesToInheritFrom; 6901 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(), 6902 BaseE = ClassDecl->bases_end(); 6903 BaseIt != BaseE; ++BaseIt) { 6904 if (BaseIt->getInheritConstructors()) { 6905 QualType Base = BaseIt->getType(); 6906 if (Base->isDependentType()) { 6907 // If we inherit constructors from anything that is dependent, just 6908 // abort processing altogether. We'll get another chance for the 6909 // instantiations. 6910 return; 6911 } 6912 BasesToInheritFrom.push_back(Base->castAs<RecordType>()); 6913 } 6914 } 6915 if (BasesToInheritFrom.empty()) 6916 return; 6917 6918 // Now collect the constructors that we already have in the current class. 6919 // Those take precedence over inherited constructors. 6920 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...] 6921 // unless there is a user-declared constructor with the same signature in 6922 // the class where the using-declaration appears. 6923 llvm::SmallSet<const Type *, 8> ExistingConstructors; 6924 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(), 6925 CtorE = ClassDecl->ctor_end(); 6926 CtorIt != CtorE; ++CtorIt) { 6927 ExistingConstructors.insert( 6928 Context.getCanonicalType(CtorIt->getType()).getTypePtr()); 6929 } 6930 6931 DeclarationName CreatedCtorName = 6932 Context.DeclarationNames.getCXXConstructorName( 6933 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified()); 6934 6935 // Now comes the true work. 6936 // First, we keep a map from constructor types to the base that introduced 6937 // them. Needed for finding conflicting constructors. We also keep the 6938 // actually inserted declarations in there, for pretty diagnostics. 6939 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo; 6940 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap; 6941 ConstructorToSourceMap InheritedConstructors; 6942 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(), 6943 BaseE = BasesToInheritFrom.end(); 6944 BaseIt != BaseE; ++BaseIt) { 6945 const RecordType *Base = *BaseIt; 6946 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified(); 6947 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl()); 6948 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(), 6949 CtorE = BaseDecl->ctor_end(); 6950 CtorIt != CtorE; ++CtorIt) { 6951 // Find the using declaration for inheriting this base's constructors. 6952 // FIXME: Don't perform name lookup just to obtain a source location! 6953 DeclarationName Name = 6954 Context.DeclarationNames.getCXXConstructorName(CanonicalBase); 6955 LookupResult Result(*this, Name, SourceLocation(), LookupUsingDeclName); 6956 LookupQualifiedName(Result, CurContext); 6957 UsingDecl *UD = Result.getAsSingle<UsingDecl>(); 6958 SourceLocation UsingLoc = UD ? UD->getLocation() : 6959 ClassDecl->getLocation(); 6960 6961 // C++0x [class.inhctor]p1: The candidate set of inherited constructors 6962 // from the class X named in the using-declaration consists of actual 6963 // constructors and notional constructors that result from the 6964 // transformation of defaulted parameters as follows: 6965 // - all non-template default constructors of X, and 6966 // - for each non-template constructor of X that has at least one 6967 // parameter with a default argument, the set of constructors that 6968 // results from omitting any ellipsis parameter specification and 6969 // successively omitting parameters with a default argument from the 6970 // end of the parameter-type-list. 6971 CXXConstructorDecl *BaseCtor = *CtorIt; 6972 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor(); 6973 const FunctionProtoType *BaseCtorType = 6974 BaseCtor->getType()->getAs<FunctionProtoType>(); 6975 6976 for (unsigned params = BaseCtor->getMinRequiredArguments(), 6977 maxParams = BaseCtor->getNumParams(); 6978 params <= maxParams; ++params) { 6979 // Skip default constructors. They're never inherited. 6980 if (params == 0) 6981 continue; 6982 // Skip copy and move constructors for the same reason. 6983 if (CanBeCopyOrMove && params == 1) 6984 continue; 6985 6986 // Build up a function type for this particular constructor. 6987 // FIXME: The working paper does not consider that the exception spec 6988 // for the inheriting constructor might be larger than that of the 6989 // source. This code doesn't yet, either. When it does, this code will 6990 // need to be delayed until after exception specifications and in-class 6991 // member initializers are attached. 6992 const Type *NewCtorType; 6993 if (params == maxParams) 6994 NewCtorType = BaseCtorType; 6995 else { 6996 SmallVector<QualType, 16> Args; 6997 for (unsigned i = 0; i < params; ++i) { 6998 Args.push_back(BaseCtorType->getArgType(i)); 6999 } 7000 FunctionProtoType::ExtProtoInfo ExtInfo = 7001 BaseCtorType->getExtProtoInfo(); 7002 ExtInfo.Variadic = false; 7003 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(), 7004 Args.data(), params, ExtInfo) 7005 .getTypePtr(); 7006 } 7007 const Type *CanonicalNewCtorType = 7008 Context.getCanonicalType(NewCtorType); 7009 7010 // Now that we have the type, first check if the class already has a 7011 // constructor with this signature. 7012 if (ExistingConstructors.count(CanonicalNewCtorType)) 7013 continue; 7014 7015 // Then we check if we have already declared an inherited constructor 7016 // with this signature. 7017 std::pair<ConstructorToSourceMap::iterator, bool> result = 7018 InheritedConstructors.insert(std::make_pair( 7019 CanonicalNewCtorType, 7020 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0))); 7021 if (!result.second) { 7022 // Already in the map. If it came from a different class, that's an 7023 // error. Not if it's from the same. 7024 CanQualType PreviousBase = result.first->second.first; 7025 if (CanonicalBase != PreviousBase) { 7026 const CXXConstructorDecl *PrevCtor = result.first->second.second; 7027 const CXXConstructorDecl *PrevBaseCtor = 7028 PrevCtor->getInheritedConstructor(); 7029 assert(PrevBaseCtor && "Conflicting constructor was not inherited"); 7030 7031 Diag(UsingLoc, diag::err_using_decl_constructor_conflict); 7032 Diag(BaseCtor->getLocation(), 7033 diag::note_using_decl_constructor_conflict_current_ctor); 7034 Diag(PrevBaseCtor->getLocation(), 7035 diag::note_using_decl_constructor_conflict_previous_ctor); 7036 Diag(PrevCtor->getLocation(), 7037 diag::note_using_decl_constructor_conflict_previous_using); 7038 } 7039 continue; 7040 } 7041 7042 // OK, we're there, now add the constructor. 7043 // C++0x [class.inhctor]p8: [...] that would be performed by a 7044 // user-written inline constructor [...] 7045 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc); 7046 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create( 7047 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0), 7048 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true, 7049 /*ImplicitlyDeclared=*/true, 7050 // FIXME: Due to a defect in the standard, we treat inherited 7051 // constructors as constexpr even if that makes them ill-formed. 7052 /*Constexpr=*/BaseCtor->isConstexpr()); 7053 NewCtor->setAccess(BaseCtor->getAccess()); 7054 7055 // Build up the parameter decls and add them. 7056 SmallVector<ParmVarDecl *, 16> ParamDecls; 7057 for (unsigned i = 0; i < params; ++i) { 7058 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor, 7059 UsingLoc, UsingLoc, 7060 /*IdentifierInfo=*/0, 7061 BaseCtorType->getArgType(i), 7062 /*TInfo=*/0, SC_None, 7063 SC_None, /*DefaultArg=*/0)); 7064 } 7065 NewCtor->setParams(ParamDecls); 7066 NewCtor->setInheritedConstructor(BaseCtor); 7067 7068 ClassDecl->addDecl(NewCtor); 7069 result.first->second.second = NewCtor; 7070 } 7071 } 7072 } 7073} 7074 7075Sema::ImplicitExceptionSpecification 7076Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) { 7077 CXXRecordDecl *ClassDecl = MD->getParent(); 7078 7079 // C++ [except.spec]p14: 7080 // An implicitly declared special member function (Clause 12) shall have 7081 // an exception-specification. 7082 ImplicitExceptionSpecification ExceptSpec(*this); 7083 if (ClassDecl->isInvalidDecl()) 7084 return ExceptSpec; 7085 7086 // Direct base-class destructors. 7087 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 7088 BEnd = ClassDecl->bases_end(); 7089 B != BEnd; ++B) { 7090 if (B->isVirtual()) // Handled below. 7091 continue; 7092 7093 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) 7094 ExceptSpec.CalledDecl(B->getLocStart(), 7095 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 7096 } 7097 7098 // Virtual base-class destructors. 7099 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 7100 BEnd = ClassDecl->vbases_end(); 7101 B != BEnd; ++B) { 7102 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) 7103 ExceptSpec.CalledDecl(B->getLocStart(), 7104 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 7105 } 7106 7107 // Field destructors. 7108 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 7109 FEnd = ClassDecl->field_end(); 7110 F != FEnd; ++F) { 7111 if (const RecordType *RecordTy 7112 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) 7113 ExceptSpec.CalledDecl(F->getLocation(), 7114 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl()))); 7115 } 7116 7117 return ExceptSpec; 7118} 7119 7120CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 7121 // C++ [class.dtor]p2: 7122 // If a class has no user-declared destructor, a destructor is 7123 // declared implicitly. An implicitly-declared destructor is an 7124 // inline public member of its class. 7125 7126 // Create the actual destructor declaration. 7127 CanQualType ClassType 7128 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 7129 SourceLocation ClassLoc = ClassDecl->getLocation(); 7130 DeclarationName Name 7131 = Context.DeclarationNames.getCXXDestructorName(ClassType); 7132 DeclarationNameInfo NameInfo(Name, ClassLoc); 7133 CXXDestructorDecl *Destructor 7134 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 7135 QualType(), 0, /*isInline=*/true, 7136 /*isImplicitlyDeclared=*/true); 7137 Destructor->setAccess(AS_public); 7138 Destructor->setDefaulted(); 7139 Destructor->setImplicit(); 7140 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 7141 7142 // Build an exception specification pointing back at this destructor. 7143 FunctionProtoType::ExtProtoInfo EPI; 7144 EPI.ExceptionSpecType = EST_Unevaluated; 7145 EPI.ExceptionSpecDecl = Destructor; 7146 Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI)); 7147 7148 // Note that we have declared this destructor. 7149 ++ASTContext::NumImplicitDestructorsDeclared; 7150 7151 // Introduce this destructor into its scope. 7152 if (Scope *S = getScopeForContext(ClassDecl)) 7153 PushOnScopeChains(Destructor, S, false); 7154 ClassDecl->addDecl(Destructor); 7155 7156 AddOverriddenMethods(ClassDecl, Destructor); 7157 7158 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 7159 Destructor->setDeletedAsWritten(); 7160 7161 return Destructor; 7162} 7163 7164void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 7165 CXXDestructorDecl *Destructor) { 7166 assert((Destructor->isDefaulted() && 7167 !Destructor->doesThisDeclarationHaveABody() && 7168 !Destructor->isDeleted()) && 7169 "DefineImplicitDestructor - call it for implicit default dtor"); 7170 CXXRecordDecl *ClassDecl = Destructor->getParent(); 7171 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 7172 7173 if (Destructor->isInvalidDecl()) 7174 return; 7175 7176 ImplicitlyDefinedFunctionScope Scope(*this, Destructor); 7177 7178 DiagnosticErrorTrap Trap(Diags); 7179 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 7180 Destructor->getParent()); 7181 7182 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) { 7183 Diag(CurrentLocation, diag::note_member_synthesized_at) 7184 << CXXDestructor << Context.getTagDeclType(ClassDecl); 7185 7186 Destructor->setInvalidDecl(); 7187 return; 7188 } 7189 7190 SourceLocation Loc = Destructor->getLocation(); 7191 Destructor->setBody(new (Context) CompoundStmt(Loc)); 7192 Destructor->setImplicitlyDefined(true); 7193 Destructor->setUsed(); 7194 MarkVTableUsed(CurrentLocation, ClassDecl); 7195 7196 if (ASTMutationListener *L = getASTMutationListener()) { 7197 L->CompletedImplicitDefinition(Destructor); 7198 } 7199} 7200 7201/// \brief Perform any semantic analysis which needs to be delayed until all 7202/// pending class member declarations have been parsed. 7203void Sema::ActOnFinishCXXMemberDecls() { 7204 // Perform any deferred checking of exception specifications for virtual 7205 // destructors. 7206 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size(); 7207 i != e; ++i) { 7208 const CXXDestructorDecl *Dtor = 7209 DelayedDestructorExceptionSpecChecks[i].first; 7210 assert(!Dtor->getParent()->isDependentType() && 7211 "Should not ever add destructors of templates into the list."); 7212 CheckOverridingFunctionExceptionSpec(Dtor, 7213 DelayedDestructorExceptionSpecChecks[i].second); 7214 } 7215 DelayedDestructorExceptionSpecChecks.clear(); 7216} 7217 7218void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 7219 CXXDestructorDecl *Destructor) { 7220 assert(getLangOpts().CPlusPlus0x && 7221 "adjusting dtor exception specs was introduced in c++11"); 7222 7223 // C++11 [class.dtor]p3: 7224 // A declaration of a destructor that does not have an exception- 7225 // specification is implicitly considered to have the same exception- 7226 // specification as an implicit declaration. 7227 const FunctionProtoType *DtorType = Destructor->getType()-> 7228 getAs<FunctionProtoType>(); 7229 if (DtorType->hasExceptionSpec()) 7230 return; 7231 7232 // Replace the destructor's type, building off the existing one. Fortunately, 7233 // the only thing of interest in the destructor type is its extended info. 7234 // The return and arguments are fixed. 7235 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 7236 EPI.ExceptionSpecType = EST_Unevaluated; 7237 EPI.ExceptionSpecDecl = Destructor; 7238 Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI)); 7239 7240 // FIXME: If the destructor has a body that could throw, and the newly created 7241 // spec doesn't allow exceptions, we should emit a warning, because this 7242 // change in behavior can break conforming C++03 programs at runtime. 7243 // However, we don't have a body or an exception specification yet, so it 7244 // needs to be done somewhere else. 7245} 7246 7247/// \brief Builds a statement that copies/moves the given entity from \p From to 7248/// \c To. 7249/// 7250/// This routine is used to copy/move the members of a class with an 7251/// implicitly-declared copy/move assignment operator. When the entities being 7252/// copied are arrays, this routine builds for loops to copy them. 7253/// 7254/// \param S The Sema object used for type-checking. 7255/// 7256/// \param Loc The location where the implicit copy/move is being generated. 7257/// 7258/// \param T The type of the expressions being copied/moved. Both expressions 7259/// must have this type. 7260/// 7261/// \param To The expression we are copying/moving to. 7262/// 7263/// \param From The expression we are copying/moving from. 7264/// 7265/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 7266/// Otherwise, it's a non-static member subobject. 7267/// 7268/// \param Copying Whether we're copying or moving. 7269/// 7270/// \param Depth Internal parameter recording the depth of the recursion. 7271/// 7272/// \returns A statement or a loop that copies the expressions. 7273static StmtResult 7274BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 7275 Expr *To, Expr *From, 7276 bool CopyingBaseSubobject, bool Copying, 7277 unsigned Depth = 0) { 7278 // C++0x [class.copy]p28: 7279 // Each subobject is assigned in the manner appropriate to its type: 7280 // 7281 // - if the subobject is of class type, as if by a call to operator= with 7282 // the subobject as the object expression and the corresponding 7283 // subobject of x as a single function argument (as if by explicit 7284 // qualification; that is, ignoring any possible virtual overriding 7285 // functions in more derived classes); 7286 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 7287 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 7288 7289 // Look for operator=. 7290 DeclarationName Name 7291 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 7292 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 7293 S.LookupQualifiedName(OpLookup, ClassDecl, false); 7294 7295 // Filter out any result that isn't a copy/move-assignment operator. 7296 LookupResult::Filter F = OpLookup.makeFilter(); 7297 while (F.hasNext()) { 7298 NamedDecl *D = F.next(); 7299 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 7300 if (Method->isCopyAssignmentOperator() || 7301 (!Copying && Method->isMoveAssignmentOperator())) 7302 continue; 7303 7304 F.erase(); 7305 } 7306 F.done(); 7307 7308 // Suppress the protected check (C++ [class.protected]) for each of the 7309 // assignment operators we found. This strange dance is required when 7310 // we're assigning via a base classes's copy-assignment operator. To 7311 // ensure that we're getting the right base class subobject (without 7312 // ambiguities), we need to cast "this" to that subobject type; to 7313 // ensure that we don't go through the virtual call mechanism, we need 7314 // to qualify the operator= name with the base class (see below). However, 7315 // this means that if the base class has a protected copy assignment 7316 // operator, the protected member access check will fail. So, we 7317 // rewrite "protected" access to "public" access in this case, since we 7318 // know by construction that we're calling from a derived class. 7319 if (CopyingBaseSubobject) { 7320 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 7321 L != LEnd; ++L) { 7322 if (L.getAccess() == AS_protected) 7323 L.setAccess(AS_public); 7324 } 7325 } 7326 7327 // Create the nested-name-specifier that will be used to qualify the 7328 // reference to operator=; this is required to suppress the virtual 7329 // call mechanism. 7330 CXXScopeSpec SS; 7331 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 7332 SS.MakeTrivial(S.Context, 7333 NestedNameSpecifier::Create(S.Context, 0, false, 7334 CanonicalT), 7335 Loc); 7336 7337 // Create the reference to operator=. 7338 ExprResult OpEqualRef 7339 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS, 7340 /*TemplateKWLoc=*/SourceLocation(), 7341 /*FirstQualifierInScope=*/0, 7342 OpLookup, 7343 /*TemplateArgs=*/0, 7344 /*SuppressQualifierCheck=*/true); 7345 if (OpEqualRef.isInvalid()) 7346 return StmtError(); 7347 7348 // Build the call to the assignment operator. 7349 7350 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0, 7351 OpEqualRef.takeAs<Expr>(), 7352 Loc, &From, 1, Loc); 7353 if (Call.isInvalid()) 7354 return StmtError(); 7355 7356 return S.Owned(Call.takeAs<Stmt>()); 7357 } 7358 7359 // - if the subobject is of scalar type, the built-in assignment 7360 // operator is used. 7361 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 7362 if (!ArrayTy) { 7363 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From); 7364 if (Assignment.isInvalid()) 7365 return StmtError(); 7366 7367 return S.Owned(Assignment.takeAs<Stmt>()); 7368 } 7369 7370 // - if the subobject is an array, each element is assigned, in the 7371 // manner appropriate to the element type; 7372 7373 // Construct a loop over the array bounds, e.g., 7374 // 7375 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 7376 // 7377 // that will copy each of the array elements. 7378 QualType SizeType = S.Context.getSizeType(); 7379 7380 // Create the iteration variable. 7381 IdentifierInfo *IterationVarName = 0; 7382 { 7383 SmallString<8> Str; 7384 llvm::raw_svector_ostream OS(Str); 7385 OS << "__i" << Depth; 7386 IterationVarName = &S.Context.Idents.get(OS.str()); 7387 } 7388 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 7389 IterationVarName, SizeType, 7390 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 7391 SC_None, SC_None); 7392 7393 // Initialize the iteration variable to zero. 7394 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 7395 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 7396 7397 // Create a reference to the iteration variable; we'll use this several 7398 // times throughout. 7399 Expr *IterationVarRef 7400 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take(); 7401 assert(IterationVarRef && "Reference to invented variable cannot fail!"); 7402 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take(); 7403 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!"); 7404 7405 // Create the DeclStmt that holds the iteration variable. 7406 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 7407 7408 // Create the comparison against the array bound. 7409 llvm::APInt Upper 7410 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 7411 Expr *Comparison 7412 = new (S.Context) BinaryOperator(IterationVarRefRVal, 7413 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 7414 BO_NE, S.Context.BoolTy, 7415 VK_RValue, OK_Ordinary, Loc); 7416 7417 // Create the pre-increment of the iteration variable. 7418 Expr *Increment 7419 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType, 7420 VK_LValue, OK_Ordinary, Loc); 7421 7422 // Subscript the "from" and "to" expressions with the iteration variable. 7423 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc, 7424 IterationVarRefRVal, 7425 Loc)); 7426 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc, 7427 IterationVarRefRVal, 7428 Loc)); 7429 if (!Copying) // Cast to rvalue 7430 From = CastForMoving(S, From); 7431 7432 // Build the copy/move for an individual element of the array. 7433 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(), 7434 To, From, CopyingBaseSubobject, 7435 Copying, Depth + 1); 7436 if (Copy.isInvalid()) 7437 return StmtError(); 7438 7439 // Construct the loop that copies all elements of this array. 7440 return S.ActOnForStmt(Loc, Loc, InitStmt, 7441 S.MakeFullExpr(Comparison), 7442 0, S.MakeFullExpr(Increment), 7443 Loc, Copy.take()); 7444} 7445 7446/// Determine whether an implicit copy assignment operator for ClassDecl has a 7447/// const argument. 7448/// FIXME: It ought to be possible to store this on the record. 7449static bool isImplicitCopyAssignmentArgConst(Sema &S, 7450 CXXRecordDecl *ClassDecl) { 7451 if (ClassDecl->isInvalidDecl()) 7452 return true; 7453 7454 // C++ [class.copy]p10: 7455 // If the class definition does not explicitly declare a copy 7456 // assignment operator, one is declared implicitly. 7457 // The implicitly-defined copy assignment operator for a class X 7458 // will have the form 7459 // 7460 // X& X::operator=(const X&) 7461 // 7462 // if 7463 // -- each direct base class B of X has a copy assignment operator 7464 // whose parameter is of type const B&, const volatile B& or B, 7465 // and 7466 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 7467 BaseEnd = ClassDecl->bases_end(); 7468 Base != BaseEnd; ++Base) { 7469 // We'll handle this below 7470 if (S.getLangOpts().CPlusPlus0x && Base->isVirtual()) 7471 continue; 7472 7473 assert(!Base->getType()->isDependentType() && 7474 "Cannot generate implicit members for class with dependent bases."); 7475 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl(); 7476 if (!S.LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0)) 7477 return false; 7478 } 7479 7480 // In C++11, the above citation has "or virtual" added 7481 if (S.getLangOpts().CPlusPlus0x) { 7482 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 7483 BaseEnd = ClassDecl->vbases_end(); 7484 Base != BaseEnd; ++Base) { 7485 assert(!Base->getType()->isDependentType() && 7486 "Cannot generate implicit members for class with dependent bases."); 7487 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl(); 7488 if (!S.LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, 7489 false, 0)) 7490 return false; 7491 } 7492 } 7493 7494 // -- for all the nonstatic data members of X that are of a class 7495 // type M (or array thereof), each such class type has a copy 7496 // assignment operator whose parameter is of type const M&, 7497 // const volatile M& or M. 7498 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 7499 FieldEnd = ClassDecl->field_end(); 7500 Field != FieldEnd; ++Field) { 7501 QualType FieldType = S.Context.getBaseElementType(Field->getType()); 7502 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) 7503 if (!S.LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const, 7504 false, 0)) 7505 return false; 7506 } 7507 7508 // Otherwise, the implicitly declared copy assignment operator will 7509 // have the form 7510 // 7511 // X& X::operator=(X&) 7512 7513 return true; 7514} 7515 7516Sema::ImplicitExceptionSpecification 7517Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) { 7518 CXXRecordDecl *ClassDecl = MD->getParent(); 7519 7520 ImplicitExceptionSpecification ExceptSpec(*this); 7521 if (ClassDecl->isInvalidDecl()) 7522 return ExceptSpec; 7523 7524 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 7525 assert(T->getNumArgs() == 1 && "not a copy assignment op"); 7526 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers(); 7527 7528 // C++ [except.spec]p14: 7529 // An implicitly declared special member function (Clause 12) shall have an 7530 // exception-specification. [...] 7531 7532 // It is unspecified whether or not an implicit copy assignment operator 7533 // attempts to deduplicate calls to assignment operators of virtual bases are 7534 // made. As such, this exception specification is effectively unspecified. 7535 // Based on a similar decision made for constness in C++0x, we're erring on 7536 // the side of assuming such calls to be made regardless of whether they 7537 // actually happen. 7538 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 7539 BaseEnd = ClassDecl->bases_end(); 7540 Base != BaseEnd; ++Base) { 7541 if (Base->isVirtual()) 7542 continue; 7543 7544 CXXRecordDecl *BaseClassDecl 7545 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 7546 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 7547 ArgQuals, false, 0)) 7548 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign); 7549 } 7550 7551 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 7552 BaseEnd = ClassDecl->vbases_end(); 7553 Base != BaseEnd; ++Base) { 7554 CXXRecordDecl *BaseClassDecl 7555 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 7556 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 7557 ArgQuals, false, 0)) 7558 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign); 7559 } 7560 7561 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 7562 FieldEnd = ClassDecl->field_end(); 7563 Field != FieldEnd; 7564 ++Field) { 7565 QualType FieldType = Context.getBaseElementType(Field->getType()); 7566 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 7567 if (CXXMethodDecl *CopyAssign = 7568 LookupCopyingAssignment(FieldClassDecl, 7569 ArgQuals | FieldType.getCVRQualifiers(), 7570 false, 0)) 7571 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign); 7572 } 7573 } 7574 7575 return ExceptSpec; 7576} 7577 7578CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 7579 // Note: The following rules are largely analoguous to the copy 7580 // constructor rules. Note that virtual bases are not taken into account 7581 // for determining the argument type of the operator. Note also that 7582 // operators taking an object instead of a reference are allowed. 7583 7584 QualType ArgType = Context.getTypeDeclType(ClassDecl); 7585 QualType RetType = Context.getLValueReferenceType(ArgType); 7586 if (isImplicitCopyAssignmentArgConst(*this, ClassDecl)) 7587 ArgType = ArgType.withConst(); 7588 ArgType = Context.getLValueReferenceType(ArgType); 7589 7590 // An implicitly-declared copy assignment operator is an inline public 7591 // member of its class. 7592 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 7593 SourceLocation ClassLoc = ClassDecl->getLocation(); 7594 DeclarationNameInfo NameInfo(Name, ClassLoc); 7595 CXXMethodDecl *CopyAssignment 7596 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 7597 /*TInfo=*/0, /*isStatic=*/false, 7598 /*StorageClassAsWritten=*/SC_None, 7599 /*isInline=*/true, /*isConstexpr=*/false, 7600 SourceLocation()); 7601 CopyAssignment->setAccess(AS_public); 7602 CopyAssignment->setDefaulted(); 7603 CopyAssignment->setImplicit(); 7604 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment()); 7605 7606 // Build an exception specification pointing back at this member. 7607 FunctionProtoType::ExtProtoInfo EPI; 7608 EPI.ExceptionSpecType = EST_Unevaluated; 7609 EPI.ExceptionSpecDecl = CopyAssignment; 7610 CopyAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI)); 7611 7612 // Add the parameter to the operator. 7613 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 7614 ClassLoc, ClassLoc, /*Id=*/0, 7615 ArgType, /*TInfo=*/0, 7616 SC_None, 7617 SC_None, 0); 7618 CopyAssignment->setParams(FromParam); 7619 7620 // Note that we have added this copy-assignment operator. 7621 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 7622 7623 if (Scope *S = getScopeForContext(ClassDecl)) 7624 PushOnScopeChains(CopyAssignment, S, false); 7625 ClassDecl->addDecl(CopyAssignment); 7626 7627 // C++0x [class.copy]p19: 7628 // .... If the class definition does not explicitly declare a copy 7629 // assignment operator, there is no user-declared move constructor, and 7630 // there is no user-declared move assignment operator, a copy assignment 7631 // operator is implicitly declared as defaulted. 7632 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 7633 CopyAssignment->setDeletedAsWritten(); 7634 7635 AddOverriddenMethods(ClassDecl, CopyAssignment); 7636 return CopyAssignment; 7637} 7638 7639void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 7640 CXXMethodDecl *CopyAssignOperator) { 7641 assert((CopyAssignOperator->isDefaulted() && 7642 CopyAssignOperator->isOverloadedOperator() && 7643 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 7644 !CopyAssignOperator->doesThisDeclarationHaveABody() && 7645 !CopyAssignOperator->isDeleted()) && 7646 "DefineImplicitCopyAssignment called for wrong function"); 7647 7648 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 7649 7650 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) { 7651 CopyAssignOperator->setInvalidDecl(); 7652 return; 7653 } 7654 7655 CopyAssignOperator->setUsed(); 7656 7657 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator); 7658 DiagnosticErrorTrap Trap(Diags); 7659 7660 // C++0x [class.copy]p30: 7661 // The implicitly-defined or explicitly-defaulted copy assignment operator 7662 // for a non-union class X performs memberwise copy assignment of its 7663 // subobjects. The direct base classes of X are assigned first, in the 7664 // order of their declaration in the base-specifier-list, and then the 7665 // immediate non-static data members of X are assigned, in the order in 7666 // which they were declared in the class definition. 7667 7668 // The statements that form the synthesized function body. 7669 ASTOwningVector<Stmt*> Statements(*this); 7670 7671 // The parameter for the "other" object, which we are copying from. 7672 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 7673 Qualifiers OtherQuals = Other->getType().getQualifiers(); 7674 QualType OtherRefType = Other->getType(); 7675 if (const LValueReferenceType *OtherRef 7676 = OtherRefType->getAs<LValueReferenceType>()) { 7677 OtherRefType = OtherRef->getPointeeType(); 7678 OtherQuals = OtherRefType.getQualifiers(); 7679 } 7680 7681 // Our location for everything implicitly-generated. 7682 SourceLocation Loc = CopyAssignOperator->getLocation(); 7683 7684 // Construct a reference to the "other" object. We'll be using this 7685 // throughout the generated ASTs. 7686 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take(); 7687 assert(OtherRef && "Reference to parameter cannot fail!"); 7688 7689 // Construct the "this" pointer. We'll be using this throughout the generated 7690 // ASTs. 7691 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>(); 7692 assert(This && "Reference to this cannot fail!"); 7693 7694 // Assign base classes. 7695 bool Invalid = false; 7696 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 7697 E = ClassDecl->bases_end(); Base != E; ++Base) { 7698 // Form the assignment: 7699 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 7700 QualType BaseType = Base->getType().getUnqualifiedType(); 7701 if (!BaseType->isRecordType()) { 7702 Invalid = true; 7703 continue; 7704 } 7705 7706 CXXCastPath BasePath; 7707 BasePath.push_back(Base); 7708 7709 // Construct the "from" expression, which is an implicit cast to the 7710 // appropriately-qualified base type. 7711 Expr *From = OtherRef; 7712 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals), 7713 CK_UncheckedDerivedToBase, 7714 VK_LValue, &BasePath).take(); 7715 7716 // Dereference "this". 7717 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 7718 7719 // Implicitly cast "this" to the appropriately-qualified base type. 7720 To = ImpCastExprToType(To.take(), 7721 Context.getCVRQualifiedType(BaseType, 7722 CopyAssignOperator->getTypeQualifiers()), 7723 CK_UncheckedDerivedToBase, 7724 VK_LValue, &BasePath); 7725 7726 // Build the copy. 7727 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType, 7728 To.get(), From, 7729 /*CopyingBaseSubobject=*/true, 7730 /*Copying=*/true); 7731 if (Copy.isInvalid()) { 7732 Diag(CurrentLocation, diag::note_member_synthesized_at) 7733 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 7734 CopyAssignOperator->setInvalidDecl(); 7735 return; 7736 } 7737 7738 // Success! Record the copy. 7739 Statements.push_back(Copy.takeAs<Expr>()); 7740 } 7741 7742 // \brief Reference to the __builtin_memcpy function. 7743 Expr *BuiltinMemCpyRef = 0; 7744 // \brief Reference to the __builtin_objc_memmove_collectable function. 7745 Expr *CollectableMemCpyRef = 0; 7746 7747 // Assign non-static members. 7748 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 7749 FieldEnd = ClassDecl->field_end(); 7750 Field != FieldEnd; ++Field) { 7751 if (Field->isUnnamedBitfield()) 7752 continue; 7753 7754 // Check for members of reference type; we can't copy those. 7755 if (Field->getType()->isReferenceType()) { 7756 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 7757 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 7758 Diag(Field->getLocation(), diag::note_declared_at); 7759 Diag(CurrentLocation, diag::note_member_synthesized_at) 7760 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 7761 Invalid = true; 7762 continue; 7763 } 7764 7765 // Check for members of const-qualified, non-class type. 7766 QualType BaseType = Context.getBaseElementType(Field->getType()); 7767 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 7768 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 7769 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 7770 Diag(Field->getLocation(), diag::note_declared_at); 7771 Diag(CurrentLocation, diag::note_member_synthesized_at) 7772 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 7773 Invalid = true; 7774 continue; 7775 } 7776 7777 // Suppress assigning zero-width bitfields. 7778 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 7779 continue; 7780 7781 QualType FieldType = Field->getType().getNonReferenceType(); 7782 if (FieldType->isIncompleteArrayType()) { 7783 assert(ClassDecl->hasFlexibleArrayMember() && 7784 "Incomplete array type is not valid"); 7785 continue; 7786 } 7787 7788 // Build references to the field in the object we're copying from and to. 7789 CXXScopeSpec SS; // Intentionally empty 7790 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 7791 LookupMemberName); 7792 MemberLookup.addDecl(*Field); 7793 MemberLookup.resolveKind(); 7794 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType, 7795 Loc, /*IsArrow=*/false, 7796 SS, SourceLocation(), 0, 7797 MemberLookup, 0); 7798 ExprResult To = BuildMemberReferenceExpr(This, This->getType(), 7799 Loc, /*IsArrow=*/true, 7800 SS, SourceLocation(), 0, 7801 MemberLookup, 0); 7802 assert(!From.isInvalid() && "Implicit field reference cannot fail"); 7803 assert(!To.isInvalid() && "Implicit field reference cannot fail"); 7804 7805 // If the field should be copied with __builtin_memcpy rather than via 7806 // explicit assignments, do so. This optimization only applies for arrays 7807 // of scalars and arrays of class type with trivial copy-assignment 7808 // operators. 7809 if (FieldType->isArrayType() && !FieldType.isVolatileQualified() 7810 && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) { 7811 // Compute the size of the memory buffer to be copied. 7812 QualType SizeType = Context.getSizeType(); 7813 llvm::APInt Size(Context.getTypeSize(SizeType), 7814 Context.getTypeSizeInChars(BaseType).getQuantity()); 7815 for (const ConstantArrayType *Array 7816 = Context.getAsConstantArrayType(FieldType); 7817 Array; 7818 Array = Context.getAsConstantArrayType(Array->getElementType())) { 7819 llvm::APInt ArraySize 7820 = Array->getSize().zextOrTrunc(Size.getBitWidth()); 7821 Size *= ArraySize; 7822 } 7823 7824 // Take the address of the field references for "from" and "to". 7825 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get()); 7826 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get()); 7827 7828 bool NeedsCollectableMemCpy = 7829 (BaseType->isRecordType() && 7830 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()); 7831 7832 if (NeedsCollectableMemCpy) { 7833 if (!CollectableMemCpyRef) { 7834 // Create a reference to the __builtin_objc_memmove_collectable function. 7835 LookupResult R(*this, 7836 &Context.Idents.get("__builtin_objc_memmove_collectable"), 7837 Loc, LookupOrdinaryName); 7838 LookupName(R, TUScope, true); 7839 7840 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>(); 7841 if (!CollectableMemCpy) { 7842 // Something went horribly wrong earlier, and we will have 7843 // complained about it. 7844 Invalid = true; 7845 continue; 7846 } 7847 7848 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy, 7849 CollectableMemCpy->getType(), 7850 VK_LValue, Loc, 0).take(); 7851 assert(CollectableMemCpyRef && "Builtin reference cannot fail"); 7852 } 7853 } 7854 // Create a reference to the __builtin_memcpy builtin function. 7855 else if (!BuiltinMemCpyRef) { 7856 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc, 7857 LookupOrdinaryName); 7858 LookupName(R, TUScope, true); 7859 7860 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>(); 7861 if (!BuiltinMemCpy) { 7862 // Something went horribly wrong earlier, and we will have complained 7863 // about it. 7864 Invalid = true; 7865 continue; 7866 } 7867 7868 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy, 7869 BuiltinMemCpy->getType(), 7870 VK_LValue, Loc, 0).take(); 7871 assert(BuiltinMemCpyRef && "Builtin reference cannot fail"); 7872 } 7873 7874 ASTOwningVector<Expr*> CallArgs(*this); 7875 CallArgs.push_back(To.takeAs<Expr>()); 7876 CallArgs.push_back(From.takeAs<Expr>()); 7877 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc)); 7878 ExprResult Call = ExprError(); 7879 if (NeedsCollectableMemCpy) 7880 Call = ActOnCallExpr(/*Scope=*/0, 7881 CollectableMemCpyRef, 7882 Loc, move_arg(CallArgs), 7883 Loc); 7884 else 7885 Call = ActOnCallExpr(/*Scope=*/0, 7886 BuiltinMemCpyRef, 7887 Loc, move_arg(CallArgs), 7888 Loc); 7889 7890 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 7891 Statements.push_back(Call.takeAs<Expr>()); 7892 continue; 7893 } 7894 7895 // Build the copy of this field. 7896 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType, 7897 To.get(), From.get(), 7898 /*CopyingBaseSubobject=*/false, 7899 /*Copying=*/true); 7900 if (Copy.isInvalid()) { 7901 Diag(CurrentLocation, diag::note_member_synthesized_at) 7902 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 7903 CopyAssignOperator->setInvalidDecl(); 7904 return; 7905 } 7906 7907 // Success! Record the copy. 7908 Statements.push_back(Copy.takeAs<Stmt>()); 7909 } 7910 7911 if (!Invalid) { 7912 // Add a "return *this;" 7913 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 7914 7915 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get()); 7916 if (Return.isInvalid()) 7917 Invalid = true; 7918 else { 7919 Statements.push_back(Return.takeAs<Stmt>()); 7920 7921 if (Trap.hasErrorOccurred()) { 7922 Diag(CurrentLocation, diag::note_member_synthesized_at) 7923 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 7924 Invalid = true; 7925 } 7926 } 7927 } 7928 7929 if (Invalid) { 7930 CopyAssignOperator->setInvalidDecl(); 7931 return; 7932 } 7933 7934 StmtResult Body; 7935 { 7936 CompoundScopeRAII CompoundScope(*this); 7937 Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements), 7938 /*isStmtExpr=*/false); 7939 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 7940 } 7941 CopyAssignOperator->setBody(Body.takeAs<Stmt>()); 7942 7943 if (ASTMutationListener *L = getASTMutationListener()) { 7944 L->CompletedImplicitDefinition(CopyAssignOperator); 7945 } 7946} 7947 7948Sema::ImplicitExceptionSpecification 7949Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) { 7950 CXXRecordDecl *ClassDecl = MD->getParent(); 7951 7952 ImplicitExceptionSpecification ExceptSpec(*this); 7953 if (ClassDecl->isInvalidDecl()) 7954 return ExceptSpec; 7955 7956 // C++0x [except.spec]p14: 7957 // An implicitly declared special member function (Clause 12) shall have an 7958 // exception-specification. [...] 7959 7960 // It is unspecified whether or not an implicit move assignment operator 7961 // attempts to deduplicate calls to assignment operators of virtual bases are 7962 // made. As such, this exception specification is effectively unspecified. 7963 // Based on a similar decision made for constness in C++0x, we're erring on 7964 // the side of assuming such calls to be made regardless of whether they 7965 // actually happen. 7966 // Note that a move constructor is not implicitly declared when there are 7967 // virtual bases, but it can still be user-declared and explicitly defaulted. 7968 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 7969 BaseEnd = ClassDecl->bases_end(); 7970 Base != BaseEnd; ++Base) { 7971 if (Base->isVirtual()) 7972 continue; 7973 7974 CXXRecordDecl *BaseClassDecl 7975 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 7976 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 7977 0, false, 0)) 7978 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign); 7979 } 7980 7981 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 7982 BaseEnd = ClassDecl->vbases_end(); 7983 Base != BaseEnd; ++Base) { 7984 CXXRecordDecl *BaseClassDecl 7985 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 7986 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 7987 0, false, 0)) 7988 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign); 7989 } 7990 7991 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 7992 FieldEnd = ClassDecl->field_end(); 7993 Field != FieldEnd; 7994 ++Field) { 7995 QualType FieldType = Context.getBaseElementType(Field->getType()); 7996 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 7997 if (CXXMethodDecl *MoveAssign = 7998 LookupMovingAssignment(FieldClassDecl, 7999 FieldType.getCVRQualifiers(), 8000 false, 0)) 8001 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign); 8002 } 8003 } 8004 8005 return ExceptSpec; 8006} 8007 8008/// Determine whether the class type has any direct or indirect virtual base 8009/// classes which have a non-trivial move assignment operator. 8010static bool 8011hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) { 8012 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 8013 BaseEnd = ClassDecl->vbases_end(); 8014 Base != BaseEnd; ++Base) { 8015 CXXRecordDecl *BaseClass = 8016 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8017 8018 // Try to declare the move assignment. If it would be deleted, then the 8019 // class does not have a non-trivial move assignment. 8020 if (BaseClass->needsImplicitMoveAssignment()) 8021 S.DeclareImplicitMoveAssignment(BaseClass); 8022 8023 // If the class has both a trivial move assignment and a non-trivial move 8024 // assignment, hasTrivialMoveAssignment() is false. 8025 if (BaseClass->hasDeclaredMoveAssignment() && 8026 !BaseClass->hasTrivialMoveAssignment()) 8027 return true; 8028 } 8029 8030 return false; 8031} 8032 8033/// Determine whether the given type either has a move constructor or is 8034/// trivially copyable. 8035static bool 8036hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) { 8037 Type = S.Context.getBaseElementType(Type); 8038 8039 // FIXME: Technically, non-trivially-copyable non-class types, such as 8040 // reference types, are supposed to return false here, but that appears 8041 // to be a standard defect. 8042 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl(); 8043 if (!ClassDecl || !ClassDecl->getDefinition()) 8044 return true; 8045 8046 if (Type.isTriviallyCopyableType(S.Context)) 8047 return true; 8048 8049 if (IsConstructor) { 8050 if (ClassDecl->needsImplicitMoveConstructor()) 8051 S.DeclareImplicitMoveConstructor(ClassDecl); 8052 return ClassDecl->hasDeclaredMoveConstructor(); 8053 } 8054 8055 if (ClassDecl->needsImplicitMoveAssignment()) 8056 S.DeclareImplicitMoveAssignment(ClassDecl); 8057 return ClassDecl->hasDeclaredMoveAssignment(); 8058} 8059 8060/// Determine whether all non-static data members and direct or virtual bases 8061/// of class \p ClassDecl have either a move operation, or are trivially 8062/// copyable. 8063static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl, 8064 bool IsConstructor) { 8065 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 8066 BaseEnd = ClassDecl->bases_end(); 8067 Base != BaseEnd; ++Base) { 8068 if (Base->isVirtual()) 8069 continue; 8070 8071 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor)) 8072 return false; 8073 } 8074 8075 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 8076 BaseEnd = ClassDecl->vbases_end(); 8077 Base != BaseEnd; ++Base) { 8078 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor)) 8079 return false; 8080 } 8081 8082 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8083 FieldEnd = ClassDecl->field_end(); 8084 Field != FieldEnd; ++Field) { 8085 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor)) 8086 return false; 8087 } 8088 8089 return true; 8090} 8091 8092CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 8093 // C++11 [class.copy]p20: 8094 // If the definition of a class X does not explicitly declare a move 8095 // assignment operator, one will be implicitly declared as defaulted 8096 // if and only if: 8097 // 8098 // - [first 4 bullets] 8099 assert(ClassDecl->needsImplicitMoveAssignment()); 8100 8101 // [Checked after we build the declaration] 8102 // - the move assignment operator would not be implicitly defined as 8103 // deleted, 8104 8105 // [DR1402]: 8106 // - X has no direct or indirect virtual base class with a non-trivial 8107 // move assignment operator, and 8108 // - each of X's non-static data members and direct or virtual base classes 8109 // has a type that either has a move assignment operator or is trivially 8110 // copyable. 8111 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) || 8112 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) { 8113 ClassDecl->setFailedImplicitMoveAssignment(); 8114 return 0; 8115 } 8116 8117 // Note: The following rules are largely analoguous to the move 8118 // constructor rules. 8119 8120 QualType ArgType = Context.getTypeDeclType(ClassDecl); 8121 QualType RetType = Context.getLValueReferenceType(ArgType); 8122 ArgType = Context.getRValueReferenceType(ArgType); 8123 8124 // An implicitly-declared move assignment operator is an inline public 8125 // member of its class. 8126 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 8127 SourceLocation ClassLoc = ClassDecl->getLocation(); 8128 DeclarationNameInfo NameInfo(Name, ClassLoc); 8129 CXXMethodDecl *MoveAssignment 8130 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 8131 /*TInfo=*/0, /*isStatic=*/false, 8132 /*StorageClassAsWritten=*/SC_None, 8133 /*isInline=*/true, 8134 /*isConstexpr=*/false, 8135 SourceLocation()); 8136 MoveAssignment->setAccess(AS_public); 8137 MoveAssignment->setDefaulted(); 8138 MoveAssignment->setImplicit(); 8139 MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment()); 8140 8141 // Build an exception specification pointing back at this member. 8142 FunctionProtoType::ExtProtoInfo EPI; 8143 EPI.ExceptionSpecType = EST_Unevaluated; 8144 EPI.ExceptionSpecDecl = MoveAssignment; 8145 MoveAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI)); 8146 8147 // Add the parameter to the operator. 8148 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 8149 ClassLoc, ClassLoc, /*Id=*/0, 8150 ArgType, /*TInfo=*/0, 8151 SC_None, 8152 SC_None, 0); 8153 MoveAssignment->setParams(FromParam); 8154 8155 // Note that we have added this copy-assignment operator. 8156 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 8157 8158 // C++0x [class.copy]p9: 8159 // If the definition of a class X does not explicitly declare a move 8160 // assignment operator, one will be implicitly declared as defaulted if and 8161 // only if: 8162 // [...] 8163 // - the move assignment operator would not be implicitly defined as 8164 // deleted. 8165 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 8166 // Cache this result so that we don't try to generate this over and over 8167 // on every lookup, leaking memory and wasting time. 8168 ClassDecl->setFailedImplicitMoveAssignment(); 8169 return 0; 8170 } 8171 8172 if (Scope *S = getScopeForContext(ClassDecl)) 8173 PushOnScopeChains(MoveAssignment, S, false); 8174 ClassDecl->addDecl(MoveAssignment); 8175 8176 AddOverriddenMethods(ClassDecl, MoveAssignment); 8177 return MoveAssignment; 8178} 8179 8180void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 8181 CXXMethodDecl *MoveAssignOperator) { 8182 assert((MoveAssignOperator->isDefaulted() && 8183 MoveAssignOperator->isOverloadedOperator() && 8184 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 8185 !MoveAssignOperator->doesThisDeclarationHaveABody() && 8186 !MoveAssignOperator->isDeleted()) && 8187 "DefineImplicitMoveAssignment called for wrong function"); 8188 8189 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 8190 8191 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) { 8192 MoveAssignOperator->setInvalidDecl(); 8193 return; 8194 } 8195 8196 MoveAssignOperator->setUsed(); 8197 8198 ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator); 8199 DiagnosticErrorTrap Trap(Diags); 8200 8201 // C++0x [class.copy]p28: 8202 // The implicitly-defined or move assignment operator for a non-union class 8203 // X performs memberwise move assignment of its subobjects. The direct base 8204 // classes of X are assigned first, in the order of their declaration in the 8205 // base-specifier-list, and then the immediate non-static data members of X 8206 // are assigned, in the order in which they were declared in the class 8207 // definition. 8208 8209 // The statements that form the synthesized function body. 8210 ASTOwningVector<Stmt*> Statements(*this); 8211 8212 // The parameter for the "other" object, which we are move from. 8213 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 8214 QualType OtherRefType = Other->getType()-> 8215 getAs<RValueReferenceType>()->getPointeeType(); 8216 assert(OtherRefType.getQualifiers() == 0 && 8217 "Bad argument type of defaulted move assignment"); 8218 8219 // Our location for everything implicitly-generated. 8220 SourceLocation Loc = MoveAssignOperator->getLocation(); 8221 8222 // Construct a reference to the "other" object. We'll be using this 8223 // throughout the generated ASTs. 8224 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take(); 8225 assert(OtherRef && "Reference to parameter cannot fail!"); 8226 // Cast to rvalue. 8227 OtherRef = CastForMoving(*this, OtherRef); 8228 8229 // Construct the "this" pointer. We'll be using this throughout the generated 8230 // ASTs. 8231 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>(); 8232 assert(This && "Reference to this cannot fail!"); 8233 8234 // Assign base classes. 8235 bool Invalid = false; 8236 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 8237 E = ClassDecl->bases_end(); Base != E; ++Base) { 8238 // Form the assignment: 8239 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 8240 QualType BaseType = Base->getType().getUnqualifiedType(); 8241 if (!BaseType->isRecordType()) { 8242 Invalid = true; 8243 continue; 8244 } 8245 8246 CXXCastPath BasePath; 8247 BasePath.push_back(Base); 8248 8249 // Construct the "from" expression, which is an implicit cast to the 8250 // appropriately-qualified base type. 8251 Expr *From = OtherRef; 8252 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase, 8253 VK_XValue, &BasePath).take(); 8254 8255 // Dereference "this". 8256 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 8257 8258 // Implicitly cast "this" to the appropriately-qualified base type. 8259 To = ImpCastExprToType(To.take(), 8260 Context.getCVRQualifiedType(BaseType, 8261 MoveAssignOperator->getTypeQualifiers()), 8262 CK_UncheckedDerivedToBase, 8263 VK_LValue, &BasePath); 8264 8265 // Build the move. 8266 StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType, 8267 To.get(), From, 8268 /*CopyingBaseSubobject=*/true, 8269 /*Copying=*/false); 8270 if (Move.isInvalid()) { 8271 Diag(CurrentLocation, diag::note_member_synthesized_at) 8272 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 8273 MoveAssignOperator->setInvalidDecl(); 8274 return; 8275 } 8276 8277 // Success! Record the move. 8278 Statements.push_back(Move.takeAs<Expr>()); 8279 } 8280 8281 // \brief Reference to the __builtin_memcpy function. 8282 Expr *BuiltinMemCpyRef = 0; 8283 // \brief Reference to the __builtin_objc_memmove_collectable function. 8284 Expr *CollectableMemCpyRef = 0; 8285 8286 // Assign non-static members. 8287 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8288 FieldEnd = ClassDecl->field_end(); 8289 Field != FieldEnd; ++Field) { 8290 if (Field->isUnnamedBitfield()) 8291 continue; 8292 8293 // Check for members of reference type; we can't move those. 8294 if (Field->getType()->isReferenceType()) { 8295 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 8296 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 8297 Diag(Field->getLocation(), diag::note_declared_at); 8298 Diag(CurrentLocation, diag::note_member_synthesized_at) 8299 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 8300 Invalid = true; 8301 continue; 8302 } 8303 8304 // Check for members of const-qualified, non-class type. 8305 QualType BaseType = Context.getBaseElementType(Field->getType()); 8306 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 8307 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 8308 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 8309 Diag(Field->getLocation(), diag::note_declared_at); 8310 Diag(CurrentLocation, diag::note_member_synthesized_at) 8311 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 8312 Invalid = true; 8313 continue; 8314 } 8315 8316 // Suppress assigning zero-width bitfields. 8317 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 8318 continue; 8319 8320 QualType FieldType = Field->getType().getNonReferenceType(); 8321 if (FieldType->isIncompleteArrayType()) { 8322 assert(ClassDecl->hasFlexibleArrayMember() && 8323 "Incomplete array type is not valid"); 8324 continue; 8325 } 8326 8327 // Build references to the field in the object we're copying from and to. 8328 CXXScopeSpec SS; // Intentionally empty 8329 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 8330 LookupMemberName); 8331 MemberLookup.addDecl(*Field); 8332 MemberLookup.resolveKind(); 8333 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType, 8334 Loc, /*IsArrow=*/false, 8335 SS, SourceLocation(), 0, 8336 MemberLookup, 0); 8337 ExprResult To = BuildMemberReferenceExpr(This, This->getType(), 8338 Loc, /*IsArrow=*/true, 8339 SS, SourceLocation(), 0, 8340 MemberLookup, 0); 8341 assert(!From.isInvalid() && "Implicit field reference cannot fail"); 8342 assert(!To.isInvalid() && "Implicit field reference cannot fail"); 8343 8344 assert(!From.get()->isLValue() && // could be xvalue or prvalue 8345 "Member reference with rvalue base must be rvalue except for reference " 8346 "members, which aren't allowed for move assignment."); 8347 8348 // If the field should be copied with __builtin_memcpy rather than via 8349 // explicit assignments, do so. This optimization only applies for arrays 8350 // of scalars and arrays of class type with trivial move-assignment 8351 // operators. 8352 if (FieldType->isArrayType() && !FieldType.isVolatileQualified() 8353 && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) { 8354 // Compute the size of the memory buffer to be copied. 8355 QualType SizeType = Context.getSizeType(); 8356 llvm::APInt Size(Context.getTypeSize(SizeType), 8357 Context.getTypeSizeInChars(BaseType).getQuantity()); 8358 for (const ConstantArrayType *Array 8359 = Context.getAsConstantArrayType(FieldType); 8360 Array; 8361 Array = Context.getAsConstantArrayType(Array->getElementType())) { 8362 llvm::APInt ArraySize 8363 = Array->getSize().zextOrTrunc(Size.getBitWidth()); 8364 Size *= ArraySize; 8365 } 8366 8367 // Take the address of the field references for "from" and "to". We 8368 // directly construct UnaryOperators here because semantic analysis 8369 // does not permit us to take the address of an xvalue. 8370 From = new (Context) UnaryOperator(From.get(), UO_AddrOf, 8371 Context.getPointerType(From.get()->getType()), 8372 VK_RValue, OK_Ordinary, Loc); 8373 To = new (Context) UnaryOperator(To.get(), UO_AddrOf, 8374 Context.getPointerType(To.get()->getType()), 8375 VK_RValue, OK_Ordinary, Loc); 8376 8377 bool NeedsCollectableMemCpy = 8378 (BaseType->isRecordType() && 8379 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()); 8380 8381 if (NeedsCollectableMemCpy) { 8382 if (!CollectableMemCpyRef) { 8383 // Create a reference to the __builtin_objc_memmove_collectable function. 8384 LookupResult R(*this, 8385 &Context.Idents.get("__builtin_objc_memmove_collectable"), 8386 Loc, LookupOrdinaryName); 8387 LookupName(R, TUScope, true); 8388 8389 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>(); 8390 if (!CollectableMemCpy) { 8391 // Something went horribly wrong earlier, and we will have 8392 // complained about it. 8393 Invalid = true; 8394 continue; 8395 } 8396 8397 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy, 8398 CollectableMemCpy->getType(), 8399 VK_LValue, Loc, 0).take(); 8400 assert(CollectableMemCpyRef && "Builtin reference cannot fail"); 8401 } 8402 } 8403 // Create a reference to the __builtin_memcpy builtin function. 8404 else if (!BuiltinMemCpyRef) { 8405 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc, 8406 LookupOrdinaryName); 8407 LookupName(R, TUScope, true); 8408 8409 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>(); 8410 if (!BuiltinMemCpy) { 8411 // Something went horribly wrong earlier, and we will have complained 8412 // about it. 8413 Invalid = true; 8414 continue; 8415 } 8416 8417 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy, 8418 BuiltinMemCpy->getType(), 8419 VK_LValue, Loc, 0).take(); 8420 assert(BuiltinMemCpyRef && "Builtin reference cannot fail"); 8421 } 8422 8423 ASTOwningVector<Expr*> CallArgs(*this); 8424 CallArgs.push_back(To.takeAs<Expr>()); 8425 CallArgs.push_back(From.takeAs<Expr>()); 8426 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc)); 8427 ExprResult Call = ExprError(); 8428 if (NeedsCollectableMemCpy) 8429 Call = ActOnCallExpr(/*Scope=*/0, 8430 CollectableMemCpyRef, 8431 Loc, move_arg(CallArgs), 8432 Loc); 8433 else 8434 Call = ActOnCallExpr(/*Scope=*/0, 8435 BuiltinMemCpyRef, 8436 Loc, move_arg(CallArgs), 8437 Loc); 8438 8439 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 8440 Statements.push_back(Call.takeAs<Expr>()); 8441 continue; 8442 } 8443 8444 // Build the move of this field. 8445 StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType, 8446 To.get(), From.get(), 8447 /*CopyingBaseSubobject=*/false, 8448 /*Copying=*/false); 8449 if (Move.isInvalid()) { 8450 Diag(CurrentLocation, diag::note_member_synthesized_at) 8451 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 8452 MoveAssignOperator->setInvalidDecl(); 8453 return; 8454 } 8455 8456 // Success! Record the copy. 8457 Statements.push_back(Move.takeAs<Stmt>()); 8458 } 8459 8460 if (!Invalid) { 8461 // Add a "return *this;" 8462 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 8463 8464 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get()); 8465 if (Return.isInvalid()) 8466 Invalid = true; 8467 else { 8468 Statements.push_back(Return.takeAs<Stmt>()); 8469 8470 if (Trap.hasErrorOccurred()) { 8471 Diag(CurrentLocation, diag::note_member_synthesized_at) 8472 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 8473 Invalid = true; 8474 } 8475 } 8476 } 8477 8478 if (Invalid) { 8479 MoveAssignOperator->setInvalidDecl(); 8480 return; 8481 } 8482 8483 StmtResult Body; 8484 { 8485 CompoundScopeRAII CompoundScope(*this); 8486 Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements), 8487 /*isStmtExpr=*/false); 8488 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 8489 } 8490 MoveAssignOperator->setBody(Body.takeAs<Stmt>()); 8491 8492 if (ASTMutationListener *L = getASTMutationListener()) { 8493 L->CompletedImplicitDefinition(MoveAssignOperator); 8494 } 8495} 8496 8497/// Determine whether an implicit copy constructor for ClassDecl has a const 8498/// argument. 8499/// FIXME: It ought to be possible to store this on the record. 8500static bool isImplicitCopyCtorArgConst(Sema &S, CXXRecordDecl *ClassDecl) { 8501 if (ClassDecl->isInvalidDecl()) 8502 return true; 8503 8504 // C++ [class.copy]p5: 8505 // The implicitly-declared copy constructor for a class X will 8506 // have the form 8507 // 8508 // X::X(const X&) 8509 // 8510 // if 8511 // -- each direct or virtual base class B of X has a copy 8512 // constructor whose first parameter is of type const B& or 8513 // const volatile B&, and 8514 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 8515 BaseEnd = ClassDecl->bases_end(); 8516 Base != BaseEnd; ++Base) { 8517 // Virtual bases are handled below. 8518 if (Base->isVirtual()) 8519 continue; 8520 8521 CXXRecordDecl *BaseClassDecl 8522 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8523 // FIXME: This lookup is wrong. If the copy ctor for a member or base is 8524 // ambiguous, we should still produce a constructor with a const-qualified 8525 // parameter. 8526 if (!S.LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const)) 8527 return false; 8528 } 8529 8530 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 8531 BaseEnd = ClassDecl->vbases_end(); 8532 Base != BaseEnd; ++Base) { 8533 CXXRecordDecl *BaseClassDecl 8534 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8535 if (!S.LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const)) 8536 return false; 8537 } 8538 8539 // -- for all the nonstatic data members of X that are of a 8540 // class type M (or array thereof), each such class type 8541 // has a copy constructor whose first parameter is of type 8542 // const M& or const volatile M&. 8543 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8544 FieldEnd = ClassDecl->field_end(); 8545 Field != FieldEnd; ++Field) { 8546 QualType FieldType = S.Context.getBaseElementType(Field->getType()); 8547 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 8548 if (!S.LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const)) 8549 return false; 8550 } 8551 } 8552 8553 // Otherwise, the implicitly declared copy constructor will have 8554 // the form 8555 // 8556 // X::X(X&) 8557 8558 return true; 8559} 8560 8561Sema::ImplicitExceptionSpecification 8562Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) { 8563 CXXRecordDecl *ClassDecl = MD->getParent(); 8564 8565 ImplicitExceptionSpecification ExceptSpec(*this); 8566 if (ClassDecl->isInvalidDecl()) 8567 return ExceptSpec; 8568 8569 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 8570 assert(T->getNumArgs() >= 1 && "not a copy ctor"); 8571 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers(); 8572 8573 // C++ [except.spec]p14: 8574 // An implicitly declared special member function (Clause 12) shall have an 8575 // exception-specification. [...] 8576 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 8577 BaseEnd = ClassDecl->bases_end(); 8578 Base != BaseEnd; 8579 ++Base) { 8580 // Virtual bases are handled below. 8581 if (Base->isVirtual()) 8582 continue; 8583 8584 CXXRecordDecl *BaseClassDecl 8585 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8586 if (CXXConstructorDecl *CopyConstructor = 8587 LookupCopyingConstructor(BaseClassDecl, Quals)) 8588 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor); 8589 } 8590 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 8591 BaseEnd = ClassDecl->vbases_end(); 8592 Base != BaseEnd; 8593 ++Base) { 8594 CXXRecordDecl *BaseClassDecl 8595 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8596 if (CXXConstructorDecl *CopyConstructor = 8597 LookupCopyingConstructor(BaseClassDecl, Quals)) 8598 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor); 8599 } 8600 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8601 FieldEnd = ClassDecl->field_end(); 8602 Field != FieldEnd; 8603 ++Field) { 8604 QualType FieldType = Context.getBaseElementType(Field->getType()); 8605 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 8606 if (CXXConstructorDecl *CopyConstructor = 8607 LookupCopyingConstructor(FieldClassDecl, 8608 Quals | FieldType.getCVRQualifiers())) 8609 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor); 8610 } 8611 } 8612 8613 return ExceptSpec; 8614} 8615 8616CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 8617 CXXRecordDecl *ClassDecl) { 8618 // C++ [class.copy]p4: 8619 // If the class definition does not explicitly declare a copy 8620 // constructor, one is declared implicitly. 8621 8622 QualType ClassType = Context.getTypeDeclType(ClassDecl); 8623 QualType ArgType = ClassType; 8624 bool Const = isImplicitCopyCtorArgConst(*this, ClassDecl); 8625 if (Const) 8626 ArgType = ArgType.withConst(); 8627 ArgType = Context.getLValueReferenceType(ArgType); 8628 8629 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 8630 CXXCopyConstructor, 8631 Const); 8632 8633 DeclarationName Name 8634 = Context.DeclarationNames.getCXXConstructorName( 8635 Context.getCanonicalType(ClassType)); 8636 SourceLocation ClassLoc = ClassDecl->getLocation(); 8637 DeclarationNameInfo NameInfo(Name, ClassLoc); 8638 8639 // An implicitly-declared copy constructor is an inline public 8640 // member of its class. 8641 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 8642 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0, 8643 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 8644 Constexpr); 8645 CopyConstructor->setAccess(AS_public); 8646 CopyConstructor->setDefaulted(); 8647 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor()); 8648 8649 // Build an exception specification pointing back at this member. 8650 FunctionProtoType::ExtProtoInfo EPI; 8651 EPI.ExceptionSpecType = EST_Unevaluated; 8652 EPI.ExceptionSpecDecl = CopyConstructor; 8653 CopyConstructor->setType( 8654 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI)); 8655 8656 // Note that we have declared this constructor. 8657 ++ASTContext::NumImplicitCopyConstructorsDeclared; 8658 8659 // Add the parameter to the constructor. 8660 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 8661 ClassLoc, ClassLoc, 8662 /*IdentifierInfo=*/0, 8663 ArgType, /*TInfo=*/0, 8664 SC_None, 8665 SC_None, 0); 8666 CopyConstructor->setParams(FromParam); 8667 8668 if (Scope *S = getScopeForContext(ClassDecl)) 8669 PushOnScopeChains(CopyConstructor, S, false); 8670 ClassDecl->addDecl(CopyConstructor); 8671 8672 // C++11 [class.copy]p8: 8673 // ... If the class definition does not explicitly declare a copy 8674 // constructor, there is no user-declared move constructor, and there is no 8675 // user-declared move assignment operator, a copy constructor is implicitly 8676 // declared as defaulted. 8677 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) 8678 CopyConstructor->setDeletedAsWritten(); 8679 8680 return CopyConstructor; 8681} 8682 8683void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 8684 CXXConstructorDecl *CopyConstructor) { 8685 assert((CopyConstructor->isDefaulted() && 8686 CopyConstructor->isCopyConstructor() && 8687 !CopyConstructor->doesThisDeclarationHaveABody() && 8688 !CopyConstructor->isDeleted()) && 8689 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 8690 8691 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 8692 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 8693 8694 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor); 8695 DiagnosticErrorTrap Trap(Diags); 8696 8697 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) || 8698 Trap.hasErrorOccurred()) { 8699 Diag(CurrentLocation, diag::note_member_synthesized_at) 8700 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl); 8701 CopyConstructor->setInvalidDecl(); 8702 } else { 8703 Sema::CompoundScopeRAII CompoundScope(*this); 8704 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(), 8705 CopyConstructor->getLocation(), 8706 MultiStmtArg(*this, 0, 0), 8707 /*isStmtExpr=*/false) 8708 .takeAs<Stmt>()); 8709 CopyConstructor->setImplicitlyDefined(true); 8710 } 8711 8712 CopyConstructor->setUsed(); 8713 if (ASTMutationListener *L = getASTMutationListener()) { 8714 L->CompletedImplicitDefinition(CopyConstructor); 8715 } 8716} 8717 8718Sema::ImplicitExceptionSpecification 8719Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) { 8720 CXXRecordDecl *ClassDecl = MD->getParent(); 8721 8722 // C++ [except.spec]p14: 8723 // An implicitly declared special member function (Clause 12) shall have an 8724 // exception-specification. [...] 8725 ImplicitExceptionSpecification ExceptSpec(*this); 8726 if (ClassDecl->isInvalidDecl()) 8727 return ExceptSpec; 8728 8729 // Direct base-class constructors. 8730 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 8731 BEnd = ClassDecl->bases_end(); 8732 B != BEnd; ++B) { 8733 if (B->isVirtual()) // Handled below. 8734 continue; 8735 8736 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 8737 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8738 CXXConstructorDecl *Constructor = 8739 LookupMovingConstructor(BaseClassDecl, 0); 8740 // If this is a deleted function, add it anyway. This might be conformant 8741 // with the standard. This might not. I'm not sure. It might not matter. 8742 if (Constructor) 8743 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 8744 } 8745 } 8746 8747 // Virtual base-class constructors. 8748 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 8749 BEnd = ClassDecl->vbases_end(); 8750 B != BEnd; ++B) { 8751 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 8752 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8753 CXXConstructorDecl *Constructor = 8754 LookupMovingConstructor(BaseClassDecl, 0); 8755 // If this is a deleted function, add it anyway. This might be conformant 8756 // with the standard. This might not. I'm not sure. It might not matter. 8757 if (Constructor) 8758 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 8759 } 8760 } 8761 8762 // Field constructors. 8763 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 8764 FEnd = ClassDecl->field_end(); 8765 F != FEnd; ++F) { 8766 QualType FieldType = Context.getBaseElementType(F->getType()); 8767 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) { 8768 CXXConstructorDecl *Constructor = 8769 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers()); 8770 // If this is a deleted function, add it anyway. This might be conformant 8771 // with the standard. This might not. I'm not sure. It might not matter. 8772 // In particular, the problem is that this function never gets called. It 8773 // might just be ill-formed because this function attempts to refer to 8774 // a deleted function here. 8775 if (Constructor) 8776 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 8777 } 8778 } 8779 8780 return ExceptSpec; 8781} 8782 8783CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 8784 CXXRecordDecl *ClassDecl) { 8785 // C++11 [class.copy]p9: 8786 // If the definition of a class X does not explicitly declare a move 8787 // constructor, one will be implicitly declared as defaulted if and only if: 8788 // 8789 // - [first 4 bullets] 8790 assert(ClassDecl->needsImplicitMoveConstructor()); 8791 8792 // [Checked after we build the declaration] 8793 // - the move assignment operator would not be implicitly defined as 8794 // deleted, 8795 8796 // [DR1402]: 8797 // - each of X's non-static data members and direct or virtual base classes 8798 // has a type that either has a move constructor or is trivially copyable. 8799 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) { 8800 ClassDecl->setFailedImplicitMoveConstructor(); 8801 return 0; 8802 } 8803 8804 QualType ClassType = Context.getTypeDeclType(ClassDecl); 8805 QualType ArgType = Context.getRValueReferenceType(ClassType); 8806 8807 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 8808 CXXMoveConstructor, 8809 false); 8810 8811 DeclarationName Name 8812 = Context.DeclarationNames.getCXXConstructorName( 8813 Context.getCanonicalType(ClassType)); 8814 SourceLocation ClassLoc = ClassDecl->getLocation(); 8815 DeclarationNameInfo NameInfo(Name, ClassLoc); 8816 8817 // C++0x [class.copy]p11: 8818 // An implicitly-declared copy/move constructor is an inline public 8819 // member of its class. 8820 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 8821 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0, 8822 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 8823 Constexpr); 8824 MoveConstructor->setAccess(AS_public); 8825 MoveConstructor->setDefaulted(); 8826 MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor()); 8827 8828 // Build an exception specification pointing back at this member. 8829 FunctionProtoType::ExtProtoInfo EPI; 8830 EPI.ExceptionSpecType = EST_Unevaluated; 8831 EPI.ExceptionSpecDecl = MoveConstructor; 8832 MoveConstructor->setType( 8833 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI)); 8834 8835 // Add the parameter to the constructor. 8836 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 8837 ClassLoc, ClassLoc, 8838 /*IdentifierInfo=*/0, 8839 ArgType, /*TInfo=*/0, 8840 SC_None, 8841 SC_None, 0); 8842 MoveConstructor->setParams(FromParam); 8843 8844 // C++0x [class.copy]p9: 8845 // If the definition of a class X does not explicitly declare a move 8846 // constructor, one will be implicitly declared as defaulted if and only if: 8847 // [...] 8848 // - the move constructor would not be implicitly defined as deleted. 8849 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 8850 // Cache this result so that we don't try to generate this over and over 8851 // on every lookup, leaking memory and wasting time. 8852 ClassDecl->setFailedImplicitMoveConstructor(); 8853 return 0; 8854 } 8855 8856 // Note that we have declared this constructor. 8857 ++ASTContext::NumImplicitMoveConstructorsDeclared; 8858 8859 if (Scope *S = getScopeForContext(ClassDecl)) 8860 PushOnScopeChains(MoveConstructor, S, false); 8861 ClassDecl->addDecl(MoveConstructor); 8862 8863 return MoveConstructor; 8864} 8865 8866void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 8867 CXXConstructorDecl *MoveConstructor) { 8868 assert((MoveConstructor->isDefaulted() && 8869 MoveConstructor->isMoveConstructor() && 8870 !MoveConstructor->doesThisDeclarationHaveABody() && 8871 !MoveConstructor->isDeleted()) && 8872 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 8873 8874 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 8875 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 8876 8877 ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor); 8878 DiagnosticErrorTrap Trap(Diags); 8879 8880 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) || 8881 Trap.hasErrorOccurred()) { 8882 Diag(CurrentLocation, diag::note_member_synthesized_at) 8883 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl); 8884 MoveConstructor->setInvalidDecl(); 8885 } else { 8886 Sema::CompoundScopeRAII CompoundScope(*this); 8887 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(), 8888 MoveConstructor->getLocation(), 8889 MultiStmtArg(*this, 0, 0), 8890 /*isStmtExpr=*/false) 8891 .takeAs<Stmt>()); 8892 MoveConstructor->setImplicitlyDefined(true); 8893 } 8894 8895 MoveConstructor->setUsed(); 8896 8897 if (ASTMutationListener *L = getASTMutationListener()) { 8898 L->CompletedImplicitDefinition(MoveConstructor); 8899 } 8900} 8901 8902bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 8903 return FD->isDeleted() && 8904 (FD->isDefaulted() || FD->isImplicit()) && 8905 isa<CXXMethodDecl>(FD); 8906} 8907 8908/// \brief Mark the call operator of the given lambda closure type as "used". 8909static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) { 8910 CXXMethodDecl *CallOperator 8911 = cast<CXXMethodDecl>( 8912 *Lambda->lookup( 8913 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).first); 8914 CallOperator->setReferenced(); 8915 CallOperator->setUsed(); 8916} 8917 8918void Sema::DefineImplicitLambdaToFunctionPointerConversion( 8919 SourceLocation CurrentLocation, 8920 CXXConversionDecl *Conv) 8921{ 8922 CXXRecordDecl *Lambda = Conv->getParent(); 8923 8924 // Make sure that the lambda call operator is marked used. 8925 markLambdaCallOperatorUsed(*this, Lambda); 8926 8927 Conv->setUsed(); 8928 8929 ImplicitlyDefinedFunctionScope Scope(*this, Conv); 8930 DiagnosticErrorTrap Trap(Diags); 8931 8932 // Return the address of the __invoke function. 8933 DeclarationName InvokeName = &Context.Idents.get("__invoke"); 8934 CXXMethodDecl *Invoke 8935 = cast<CXXMethodDecl>(*Lambda->lookup(InvokeName).first); 8936 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(), 8937 VK_LValue, Conv->getLocation()).take(); 8938 assert(FunctionRef && "Can't refer to __invoke function?"); 8939 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take(); 8940 Conv->setBody(new (Context) CompoundStmt(Context, &Return, 1, 8941 Conv->getLocation(), 8942 Conv->getLocation())); 8943 8944 // Fill in the __invoke function with a dummy implementation. IR generation 8945 // will fill in the actual details. 8946 Invoke->setUsed(); 8947 Invoke->setReferenced(); 8948 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation())); 8949 8950 if (ASTMutationListener *L = getASTMutationListener()) { 8951 L->CompletedImplicitDefinition(Conv); 8952 L->CompletedImplicitDefinition(Invoke); 8953 } 8954} 8955 8956void Sema::DefineImplicitLambdaToBlockPointerConversion( 8957 SourceLocation CurrentLocation, 8958 CXXConversionDecl *Conv) 8959{ 8960 Conv->setUsed(); 8961 8962 ImplicitlyDefinedFunctionScope Scope(*this, Conv); 8963 DiagnosticErrorTrap Trap(Diags); 8964 8965 // Copy-initialize the lambda object as needed to capture it. 8966 Expr *This = ActOnCXXThis(CurrentLocation).take(); 8967 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take(); 8968 8969 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 8970 Conv->getLocation(), 8971 Conv, DerefThis); 8972 8973 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 8974 // behavior. Note that only the general conversion function does this 8975 // (since it's unusable otherwise); in the case where we inline the 8976 // block literal, it has block literal lifetime semantics. 8977 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 8978 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 8979 CK_CopyAndAutoreleaseBlockObject, 8980 BuildBlock.get(), 0, VK_RValue); 8981 8982 if (BuildBlock.isInvalid()) { 8983 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 8984 Conv->setInvalidDecl(); 8985 return; 8986 } 8987 8988 // Create the return statement that returns the block from the conversion 8989 // function. 8990 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get()); 8991 if (Return.isInvalid()) { 8992 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 8993 Conv->setInvalidDecl(); 8994 return; 8995 } 8996 8997 // Set the body of the conversion function. 8998 Stmt *ReturnS = Return.take(); 8999 Conv->setBody(new (Context) CompoundStmt(Context, &ReturnS, 1, 9000 Conv->getLocation(), 9001 Conv->getLocation())); 9002 9003 // We're done; notify the mutation listener, if any. 9004 if (ASTMutationListener *L = getASTMutationListener()) { 9005 L->CompletedImplicitDefinition(Conv); 9006 } 9007} 9008 9009/// \brief Determine whether the given list arguments contains exactly one 9010/// "real" (non-default) argument. 9011static bool hasOneRealArgument(MultiExprArg Args) { 9012 switch (Args.size()) { 9013 case 0: 9014 return false; 9015 9016 default: 9017 if (!Args.get()[1]->isDefaultArgument()) 9018 return false; 9019 9020 // fall through 9021 case 1: 9022 return !Args.get()[0]->isDefaultArgument(); 9023 } 9024 9025 return false; 9026} 9027 9028ExprResult 9029Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 9030 CXXConstructorDecl *Constructor, 9031 MultiExprArg ExprArgs, 9032 bool HadMultipleCandidates, 9033 bool RequiresZeroInit, 9034 unsigned ConstructKind, 9035 SourceRange ParenRange) { 9036 bool Elidable = false; 9037 9038 // C++0x [class.copy]p34: 9039 // When certain criteria are met, an implementation is allowed to 9040 // omit the copy/move construction of a class object, even if the 9041 // copy/move constructor and/or destructor for the object have 9042 // side effects. [...] 9043 // - when a temporary class object that has not been bound to a 9044 // reference (12.2) would be copied/moved to a class object 9045 // with the same cv-unqualified type, the copy/move operation 9046 // can be omitted by constructing the temporary object 9047 // directly into the target of the omitted copy/move 9048 if (ConstructKind == CXXConstructExpr::CK_Complete && 9049 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 9050 Expr *SubExpr = ((Expr **)ExprArgs.get())[0]; 9051 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent()); 9052 } 9053 9054 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 9055 Elidable, move(ExprArgs), HadMultipleCandidates, 9056 RequiresZeroInit, ConstructKind, ParenRange); 9057} 9058 9059/// BuildCXXConstructExpr - Creates a complete call to a constructor, 9060/// including handling of its default argument expressions. 9061ExprResult 9062Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 9063 CXXConstructorDecl *Constructor, bool Elidable, 9064 MultiExprArg ExprArgs, 9065 bool HadMultipleCandidates, 9066 bool RequiresZeroInit, 9067 unsigned ConstructKind, 9068 SourceRange ParenRange) { 9069 unsigned NumExprs = ExprArgs.size(); 9070 Expr **Exprs = (Expr **)ExprArgs.release(); 9071 9072 MarkFunctionReferenced(ConstructLoc, Constructor); 9073 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc, 9074 Constructor, Elidable, Exprs, NumExprs, 9075 HadMultipleCandidates, /*FIXME*/false, 9076 RequiresZeroInit, 9077 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 9078 ParenRange)); 9079} 9080 9081bool Sema::InitializeVarWithConstructor(VarDecl *VD, 9082 CXXConstructorDecl *Constructor, 9083 MultiExprArg Exprs, 9084 bool HadMultipleCandidates) { 9085 // FIXME: Provide the correct paren SourceRange when available. 9086 ExprResult TempResult = 9087 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor, 9088 move(Exprs), HadMultipleCandidates, false, 9089 CXXConstructExpr::CK_Complete, SourceRange()); 9090 if (TempResult.isInvalid()) 9091 return true; 9092 9093 Expr *Temp = TempResult.takeAs<Expr>(); 9094 CheckImplicitConversions(Temp, VD->getLocation()); 9095 MarkFunctionReferenced(VD->getLocation(), Constructor); 9096 Temp = MaybeCreateExprWithCleanups(Temp); 9097 VD->setInit(Temp); 9098 9099 return false; 9100} 9101 9102void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 9103 if (VD->isInvalidDecl()) return; 9104 9105 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 9106 if (ClassDecl->isInvalidDecl()) return; 9107 if (ClassDecl->hasIrrelevantDestructor()) return; 9108 if (ClassDecl->isDependentContext()) return; 9109 9110 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 9111 MarkFunctionReferenced(VD->getLocation(), Destructor); 9112 CheckDestructorAccess(VD->getLocation(), Destructor, 9113 PDiag(diag::err_access_dtor_var) 9114 << VD->getDeclName() 9115 << VD->getType()); 9116 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 9117 9118 if (!VD->hasGlobalStorage()) return; 9119 9120 // Emit warning for non-trivial dtor in global scope (a real global, 9121 // class-static, function-static). 9122 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 9123 9124 // TODO: this should be re-enabled for static locals by !CXAAtExit 9125 if (!VD->isStaticLocal()) 9126 Diag(VD->getLocation(), diag::warn_global_destructor); 9127} 9128 9129/// \brief Given a constructor and the set of arguments provided for the 9130/// constructor, convert the arguments and add any required default arguments 9131/// to form a proper call to this constructor. 9132/// 9133/// \returns true if an error occurred, false otherwise. 9134bool 9135Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 9136 MultiExprArg ArgsPtr, 9137 SourceLocation Loc, 9138 ASTOwningVector<Expr*> &ConvertedArgs, 9139 bool AllowExplicit) { 9140 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 9141 unsigned NumArgs = ArgsPtr.size(); 9142 Expr **Args = (Expr **)ArgsPtr.get(); 9143 9144 const FunctionProtoType *Proto 9145 = Constructor->getType()->getAs<FunctionProtoType>(); 9146 assert(Proto && "Constructor without a prototype?"); 9147 unsigned NumArgsInProto = Proto->getNumArgs(); 9148 9149 // If too few arguments are available, we'll fill in the rest with defaults. 9150 if (NumArgs < NumArgsInProto) 9151 ConvertedArgs.reserve(NumArgsInProto); 9152 else 9153 ConvertedArgs.reserve(NumArgs); 9154 9155 VariadicCallType CallType = 9156 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 9157 SmallVector<Expr *, 8> AllArgs; 9158 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 9159 Proto, 0, Args, NumArgs, AllArgs, 9160 CallType, AllowExplicit); 9161 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 9162 9163 DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size()); 9164 9165 CheckConstructorCall(Constructor, AllArgs.data(), AllArgs.size(), 9166 Proto, Loc); 9167 9168 return Invalid; 9169} 9170 9171static inline bool 9172CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 9173 const FunctionDecl *FnDecl) { 9174 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 9175 if (isa<NamespaceDecl>(DC)) { 9176 return SemaRef.Diag(FnDecl->getLocation(), 9177 diag::err_operator_new_delete_declared_in_namespace) 9178 << FnDecl->getDeclName(); 9179 } 9180 9181 if (isa<TranslationUnitDecl>(DC) && 9182 FnDecl->getStorageClass() == SC_Static) { 9183 return SemaRef.Diag(FnDecl->getLocation(), 9184 diag::err_operator_new_delete_declared_static) 9185 << FnDecl->getDeclName(); 9186 } 9187 9188 return false; 9189} 9190 9191static inline bool 9192CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 9193 CanQualType ExpectedResultType, 9194 CanQualType ExpectedFirstParamType, 9195 unsigned DependentParamTypeDiag, 9196 unsigned InvalidParamTypeDiag) { 9197 QualType ResultType = 9198 FnDecl->getType()->getAs<FunctionType>()->getResultType(); 9199 9200 // Check that the result type is not dependent. 9201 if (ResultType->isDependentType()) 9202 return SemaRef.Diag(FnDecl->getLocation(), 9203 diag::err_operator_new_delete_dependent_result_type) 9204 << FnDecl->getDeclName() << ExpectedResultType; 9205 9206 // Check that the result type is what we expect. 9207 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 9208 return SemaRef.Diag(FnDecl->getLocation(), 9209 diag::err_operator_new_delete_invalid_result_type) 9210 << FnDecl->getDeclName() << ExpectedResultType; 9211 9212 // A function template must have at least 2 parameters. 9213 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 9214 return SemaRef.Diag(FnDecl->getLocation(), 9215 diag::err_operator_new_delete_template_too_few_parameters) 9216 << FnDecl->getDeclName(); 9217 9218 // The function decl must have at least 1 parameter. 9219 if (FnDecl->getNumParams() == 0) 9220 return SemaRef.Diag(FnDecl->getLocation(), 9221 diag::err_operator_new_delete_too_few_parameters) 9222 << FnDecl->getDeclName(); 9223 9224 // Check the first parameter type is not dependent. 9225 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 9226 if (FirstParamType->isDependentType()) 9227 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 9228 << FnDecl->getDeclName() << ExpectedFirstParamType; 9229 9230 // Check that the first parameter type is what we expect. 9231 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 9232 ExpectedFirstParamType) 9233 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 9234 << FnDecl->getDeclName() << ExpectedFirstParamType; 9235 9236 return false; 9237} 9238 9239static bool 9240CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 9241 // C++ [basic.stc.dynamic.allocation]p1: 9242 // A program is ill-formed if an allocation function is declared in a 9243 // namespace scope other than global scope or declared static in global 9244 // scope. 9245 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 9246 return true; 9247 9248 CanQualType SizeTy = 9249 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 9250 9251 // C++ [basic.stc.dynamic.allocation]p1: 9252 // The return type shall be void*. The first parameter shall have type 9253 // std::size_t. 9254 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 9255 SizeTy, 9256 diag::err_operator_new_dependent_param_type, 9257 diag::err_operator_new_param_type)) 9258 return true; 9259 9260 // C++ [basic.stc.dynamic.allocation]p1: 9261 // The first parameter shall not have an associated default argument. 9262 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 9263 return SemaRef.Diag(FnDecl->getLocation(), 9264 diag::err_operator_new_default_arg) 9265 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 9266 9267 return false; 9268} 9269 9270static bool 9271CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 9272 // C++ [basic.stc.dynamic.deallocation]p1: 9273 // A program is ill-formed if deallocation functions are declared in a 9274 // namespace scope other than global scope or declared static in global 9275 // scope. 9276 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 9277 return true; 9278 9279 // C++ [basic.stc.dynamic.deallocation]p2: 9280 // Each deallocation function shall return void and its first parameter 9281 // shall be void*. 9282 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 9283 SemaRef.Context.VoidPtrTy, 9284 diag::err_operator_delete_dependent_param_type, 9285 diag::err_operator_delete_param_type)) 9286 return true; 9287 9288 return false; 9289} 9290 9291/// CheckOverloadedOperatorDeclaration - Check whether the declaration 9292/// of this overloaded operator is well-formed. If so, returns false; 9293/// otherwise, emits appropriate diagnostics and returns true. 9294bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 9295 assert(FnDecl && FnDecl->isOverloadedOperator() && 9296 "Expected an overloaded operator declaration"); 9297 9298 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 9299 9300 // C++ [over.oper]p5: 9301 // The allocation and deallocation functions, operator new, 9302 // operator new[], operator delete and operator delete[], are 9303 // described completely in 3.7.3. The attributes and restrictions 9304 // found in the rest of this subclause do not apply to them unless 9305 // explicitly stated in 3.7.3. 9306 if (Op == OO_Delete || Op == OO_Array_Delete) 9307 return CheckOperatorDeleteDeclaration(*this, FnDecl); 9308 9309 if (Op == OO_New || Op == OO_Array_New) 9310 return CheckOperatorNewDeclaration(*this, FnDecl); 9311 9312 // C++ [over.oper]p6: 9313 // An operator function shall either be a non-static member 9314 // function or be a non-member function and have at least one 9315 // parameter whose type is a class, a reference to a class, an 9316 // enumeration, or a reference to an enumeration. 9317 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 9318 if (MethodDecl->isStatic()) 9319 return Diag(FnDecl->getLocation(), 9320 diag::err_operator_overload_static) << FnDecl->getDeclName(); 9321 } else { 9322 bool ClassOrEnumParam = false; 9323 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 9324 ParamEnd = FnDecl->param_end(); 9325 Param != ParamEnd; ++Param) { 9326 QualType ParamType = (*Param)->getType().getNonReferenceType(); 9327 if (ParamType->isDependentType() || ParamType->isRecordType() || 9328 ParamType->isEnumeralType()) { 9329 ClassOrEnumParam = true; 9330 break; 9331 } 9332 } 9333 9334 if (!ClassOrEnumParam) 9335 return Diag(FnDecl->getLocation(), 9336 diag::err_operator_overload_needs_class_or_enum) 9337 << FnDecl->getDeclName(); 9338 } 9339 9340 // C++ [over.oper]p8: 9341 // An operator function cannot have default arguments (8.3.6), 9342 // except where explicitly stated below. 9343 // 9344 // Only the function-call operator allows default arguments 9345 // (C++ [over.call]p1). 9346 if (Op != OO_Call) { 9347 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(); 9348 Param != FnDecl->param_end(); ++Param) { 9349 if ((*Param)->hasDefaultArg()) 9350 return Diag((*Param)->getLocation(), 9351 diag::err_operator_overload_default_arg) 9352 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange(); 9353 } 9354 } 9355 9356 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 9357 { false, false, false } 9358#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 9359 , { Unary, Binary, MemberOnly } 9360#include "clang/Basic/OperatorKinds.def" 9361 }; 9362 9363 bool CanBeUnaryOperator = OperatorUses[Op][0]; 9364 bool CanBeBinaryOperator = OperatorUses[Op][1]; 9365 bool MustBeMemberOperator = OperatorUses[Op][2]; 9366 9367 // C++ [over.oper]p8: 9368 // [...] Operator functions cannot have more or fewer parameters 9369 // than the number required for the corresponding operator, as 9370 // described in the rest of this subclause. 9371 unsigned NumParams = FnDecl->getNumParams() 9372 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 9373 if (Op != OO_Call && 9374 ((NumParams == 1 && !CanBeUnaryOperator) || 9375 (NumParams == 2 && !CanBeBinaryOperator) || 9376 (NumParams < 1) || (NumParams > 2))) { 9377 // We have the wrong number of parameters. 9378 unsigned ErrorKind; 9379 if (CanBeUnaryOperator && CanBeBinaryOperator) { 9380 ErrorKind = 2; // 2 -> unary or binary. 9381 } else if (CanBeUnaryOperator) { 9382 ErrorKind = 0; // 0 -> unary 9383 } else { 9384 assert(CanBeBinaryOperator && 9385 "All non-call overloaded operators are unary or binary!"); 9386 ErrorKind = 1; // 1 -> binary 9387 } 9388 9389 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 9390 << FnDecl->getDeclName() << NumParams << ErrorKind; 9391 } 9392 9393 // Overloaded operators other than operator() cannot be variadic. 9394 if (Op != OO_Call && 9395 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 9396 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 9397 << FnDecl->getDeclName(); 9398 } 9399 9400 // Some operators must be non-static member functions. 9401 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 9402 return Diag(FnDecl->getLocation(), 9403 diag::err_operator_overload_must_be_member) 9404 << FnDecl->getDeclName(); 9405 } 9406 9407 // C++ [over.inc]p1: 9408 // The user-defined function called operator++ implements the 9409 // prefix and postfix ++ operator. If this function is a member 9410 // function with no parameters, or a non-member function with one 9411 // parameter of class or enumeration type, it defines the prefix 9412 // increment operator ++ for objects of that type. If the function 9413 // is a member function with one parameter (which shall be of type 9414 // int) or a non-member function with two parameters (the second 9415 // of which shall be of type int), it defines the postfix 9416 // increment operator ++ for objects of that type. 9417 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 9418 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 9419 bool ParamIsInt = false; 9420 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>()) 9421 ParamIsInt = BT->getKind() == BuiltinType::Int; 9422 9423 if (!ParamIsInt) 9424 return Diag(LastParam->getLocation(), 9425 diag::err_operator_overload_post_incdec_must_be_int) 9426 << LastParam->getType() << (Op == OO_MinusMinus); 9427 } 9428 9429 return false; 9430} 9431 9432/// CheckLiteralOperatorDeclaration - Check whether the declaration 9433/// of this literal operator function is well-formed. If so, returns 9434/// false; otherwise, emits appropriate diagnostics and returns true. 9435bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 9436 if (isa<CXXMethodDecl>(FnDecl)) { 9437 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 9438 << FnDecl->getDeclName(); 9439 return true; 9440 } 9441 9442 if (FnDecl->isExternC()) { 9443 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 9444 return true; 9445 } 9446 9447 bool Valid = false; 9448 9449 // This might be the definition of a literal operator template. 9450 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 9451 // This might be a specialization of a literal operator template. 9452 if (!TpDecl) 9453 TpDecl = FnDecl->getPrimaryTemplate(); 9454 9455 // template <char...> type operator "" name() is the only valid template 9456 // signature, and the only valid signature with no parameters. 9457 if (TpDecl) { 9458 if (FnDecl->param_size() == 0) { 9459 // Must have only one template parameter 9460 TemplateParameterList *Params = TpDecl->getTemplateParameters(); 9461 if (Params->size() == 1) { 9462 NonTypeTemplateParmDecl *PmDecl = 9463 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0)); 9464 9465 // The template parameter must be a char parameter pack. 9466 if (PmDecl && PmDecl->isTemplateParameterPack() && 9467 Context.hasSameType(PmDecl->getType(), Context.CharTy)) 9468 Valid = true; 9469 } 9470 } 9471 } else if (FnDecl->param_size()) { 9472 // Check the first parameter 9473 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 9474 9475 QualType T = (*Param)->getType().getUnqualifiedType(); 9476 9477 // unsigned long long int, long double, and any character type are allowed 9478 // as the only parameters. 9479 if (Context.hasSameType(T, Context.UnsignedLongLongTy) || 9480 Context.hasSameType(T, Context.LongDoubleTy) || 9481 Context.hasSameType(T, Context.CharTy) || 9482 Context.hasSameType(T, Context.WCharTy) || 9483 Context.hasSameType(T, Context.Char16Ty) || 9484 Context.hasSameType(T, Context.Char32Ty)) { 9485 if (++Param == FnDecl->param_end()) 9486 Valid = true; 9487 goto FinishedParams; 9488 } 9489 9490 // Otherwise it must be a pointer to const; let's strip those qualifiers. 9491 const PointerType *PT = T->getAs<PointerType>(); 9492 if (!PT) 9493 goto FinishedParams; 9494 T = PT->getPointeeType(); 9495 if (!T.isConstQualified() || T.isVolatileQualified()) 9496 goto FinishedParams; 9497 T = T.getUnqualifiedType(); 9498 9499 // Move on to the second parameter; 9500 ++Param; 9501 9502 // If there is no second parameter, the first must be a const char * 9503 if (Param == FnDecl->param_end()) { 9504 if (Context.hasSameType(T, Context.CharTy)) 9505 Valid = true; 9506 goto FinishedParams; 9507 } 9508 9509 // const char *, const wchar_t*, const char16_t*, and const char32_t* 9510 // are allowed as the first parameter to a two-parameter function 9511 if (!(Context.hasSameType(T, Context.CharTy) || 9512 Context.hasSameType(T, Context.WCharTy) || 9513 Context.hasSameType(T, Context.Char16Ty) || 9514 Context.hasSameType(T, Context.Char32Ty))) 9515 goto FinishedParams; 9516 9517 // The second and final parameter must be an std::size_t 9518 T = (*Param)->getType().getUnqualifiedType(); 9519 if (Context.hasSameType(T, Context.getSizeType()) && 9520 ++Param == FnDecl->param_end()) 9521 Valid = true; 9522 } 9523 9524 // FIXME: This diagnostic is absolutely terrible. 9525FinishedParams: 9526 if (!Valid) { 9527 Diag(FnDecl->getLocation(), diag::err_literal_operator_params) 9528 << FnDecl->getDeclName(); 9529 return true; 9530 } 9531 9532 // A parameter-declaration-clause containing a default argument is not 9533 // equivalent to any of the permitted forms. 9534 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 9535 ParamEnd = FnDecl->param_end(); 9536 Param != ParamEnd; ++Param) { 9537 if ((*Param)->hasDefaultArg()) { 9538 Diag((*Param)->getDefaultArgRange().getBegin(), 9539 diag::err_literal_operator_default_argument) 9540 << (*Param)->getDefaultArgRange(); 9541 break; 9542 } 9543 } 9544 9545 StringRef LiteralName 9546 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 9547 if (LiteralName[0] != '_') { 9548 // C++11 [usrlit.suffix]p1: 9549 // Literal suffix identifiers that do not start with an underscore 9550 // are reserved for future standardization. 9551 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved); 9552 } 9553 9554 return false; 9555} 9556 9557/// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 9558/// linkage specification, including the language and (if present) 9559/// the '{'. ExternLoc is the location of the 'extern', LangLoc is 9560/// the location of the language string literal, which is provided 9561/// by Lang/StrSize. LBraceLoc, if valid, provides the location of 9562/// the '{' brace. Otherwise, this linkage specification does not 9563/// have any braces. 9564Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 9565 SourceLocation LangLoc, 9566 StringRef Lang, 9567 SourceLocation LBraceLoc) { 9568 LinkageSpecDecl::LanguageIDs Language; 9569 if (Lang == "\"C\"") 9570 Language = LinkageSpecDecl::lang_c; 9571 else if (Lang == "\"C++\"") 9572 Language = LinkageSpecDecl::lang_cxx; 9573 else { 9574 Diag(LangLoc, diag::err_bad_language); 9575 return 0; 9576 } 9577 9578 // FIXME: Add all the various semantics of linkage specifications 9579 9580 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, 9581 ExternLoc, LangLoc, Language); 9582 CurContext->addDecl(D); 9583 PushDeclContext(S, D); 9584 return D; 9585} 9586 9587/// ActOnFinishLinkageSpecification - Complete the definition of 9588/// the C++ linkage specification LinkageSpec. If RBraceLoc is 9589/// valid, it's the position of the closing '}' brace in a linkage 9590/// specification that uses braces. 9591Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 9592 Decl *LinkageSpec, 9593 SourceLocation RBraceLoc) { 9594 if (LinkageSpec) { 9595 if (RBraceLoc.isValid()) { 9596 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 9597 LSDecl->setRBraceLoc(RBraceLoc); 9598 } 9599 PopDeclContext(); 9600 } 9601 return LinkageSpec; 9602} 9603 9604/// \brief Perform semantic analysis for the variable declaration that 9605/// occurs within a C++ catch clause, returning the newly-created 9606/// variable. 9607VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 9608 TypeSourceInfo *TInfo, 9609 SourceLocation StartLoc, 9610 SourceLocation Loc, 9611 IdentifierInfo *Name) { 9612 bool Invalid = false; 9613 QualType ExDeclType = TInfo->getType(); 9614 9615 // Arrays and functions decay. 9616 if (ExDeclType->isArrayType()) 9617 ExDeclType = Context.getArrayDecayedType(ExDeclType); 9618 else if (ExDeclType->isFunctionType()) 9619 ExDeclType = Context.getPointerType(ExDeclType); 9620 9621 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 9622 // The exception-declaration shall not denote a pointer or reference to an 9623 // incomplete type, other than [cv] void*. 9624 // N2844 forbids rvalue references. 9625 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 9626 Diag(Loc, diag::err_catch_rvalue_ref); 9627 Invalid = true; 9628 } 9629 9630 QualType BaseType = ExDeclType; 9631 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 9632 unsigned DK = diag::err_catch_incomplete; 9633 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 9634 BaseType = Ptr->getPointeeType(); 9635 Mode = 1; 9636 DK = diag::err_catch_incomplete_ptr; 9637 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 9638 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 9639 BaseType = Ref->getPointeeType(); 9640 Mode = 2; 9641 DK = diag::err_catch_incomplete_ref; 9642 } 9643 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 9644 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 9645 Invalid = true; 9646 9647 if (!Invalid && !ExDeclType->isDependentType() && 9648 RequireNonAbstractType(Loc, ExDeclType, 9649 diag::err_abstract_type_in_decl, 9650 AbstractVariableType)) 9651 Invalid = true; 9652 9653 // Only the non-fragile NeXT runtime currently supports C++ catches 9654 // of ObjC types, and no runtime supports catching ObjC types by value. 9655 if (!Invalid && getLangOpts().ObjC1) { 9656 QualType T = ExDeclType; 9657 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 9658 T = RT->getPointeeType(); 9659 9660 if (T->isObjCObjectType()) { 9661 Diag(Loc, diag::err_objc_object_catch); 9662 Invalid = true; 9663 } else if (T->isObjCObjectPointerType()) { 9664 // FIXME: should this be a test for macosx-fragile specifically? 9665 if (getLangOpts().ObjCRuntime.isFragile()) 9666 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 9667 } 9668 } 9669 9670 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 9671 ExDeclType, TInfo, SC_None, SC_None); 9672 ExDecl->setExceptionVariable(true); 9673 9674 // In ARC, infer 'retaining' for variables of retainable type. 9675 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 9676 Invalid = true; 9677 9678 if (!Invalid && !ExDeclType->isDependentType()) { 9679 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 9680 // C++ [except.handle]p16: 9681 // The object declared in an exception-declaration or, if the 9682 // exception-declaration does not specify a name, a temporary (12.2) is 9683 // copy-initialized (8.5) from the exception object. [...] 9684 // The object is destroyed when the handler exits, after the destruction 9685 // of any automatic objects initialized within the handler. 9686 // 9687 // We just pretend to initialize the object with itself, then make sure 9688 // it can be destroyed later. 9689 QualType initType = ExDeclType; 9690 9691 InitializedEntity entity = 9692 InitializedEntity::InitializeVariable(ExDecl); 9693 InitializationKind initKind = 9694 InitializationKind::CreateCopy(Loc, SourceLocation()); 9695 9696 Expr *opaqueValue = 9697 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 9698 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1); 9699 ExprResult result = sequence.Perform(*this, entity, initKind, 9700 MultiExprArg(&opaqueValue, 1)); 9701 if (result.isInvalid()) 9702 Invalid = true; 9703 else { 9704 // If the constructor used was non-trivial, set this as the 9705 // "initializer". 9706 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take()); 9707 if (!construct->getConstructor()->isTrivial()) { 9708 Expr *init = MaybeCreateExprWithCleanups(construct); 9709 ExDecl->setInit(init); 9710 } 9711 9712 // And make sure it's destructable. 9713 FinalizeVarWithDestructor(ExDecl, recordType); 9714 } 9715 } 9716 } 9717 9718 if (Invalid) 9719 ExDecl->setInvalidDecl(); 9720 9721 return ExDecl; 9722} 9723 9724/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 9725/// handler. 9726Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 9727 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 9728 bool Invalid = D.isInvalidType(); 9729 9730 // Check for unexpanded parameter packs. 9731 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 9732 UPPC_ExceptionType)) { 9733 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 9734 D.getIdentifierLoc()); 9735 Invalid = true; 9736 } 9737 9738 IdentifierInfo *II = D.getIdentifier(); 9739 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 9740 LookupOrdinaryName, 9741 ForRedeclaration)) { 9742 // The scope should be freshly made just for us. There is just no way 9743 // it contains any previous declaration. 9744 assert(!S->isDeclScope(PrevDecl)); 9745 if (PrevDecl->isTemplateParameter()) { 9746 // Maybe we will complain about the shadowed template parameter. 9747 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 9748 PrevDecl = 0; 9749 } 9750 } 9751 9752 if (D.getCXXScopeSpec().isSet() && !Invalid) { 9753 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 9754 << D.getCXXScopeSpec().getRange(); 9755 Invalid = true; 9756 } 9757 9758 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 9759 D.getLocStart(), 9760 D.getIdentifierLoc(), 9761 D.getIdentifier()); 9762 if (Invalid) 9763 ExDecl->setInvalidDecl(); 9764 9765 // Add the exception declaration into this scope. 9766 if (II) 9767 PushOnScopeChains(ExDecl, S); 9768 else 9769 CurContext->addDecl(ExDecl); 9770 9771 ProcessDeclAttributes(S, ExDecl, D); 9772 return ExDecl; 9773} 9774 9775Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 9776 Expr *AssertExpr, 9777 Expr *AssertMessageExpr, 9778 SourceLocation RParenLoc) { 9779 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr); 9780 9781 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 9782 return 0; 9783 9784 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 9785 AssertMessage, RParenLoc, false); 9786} 9787 9788Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 9789 Expr *AssertExpr, 9790 StringLiteral *AssertMessage, 9791 SourceLocation RParenLoc, 9792 bool Failed) { 9793 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 9794 !Failed) { 9795 // In a static_assert-declaration, the constant-expression shall be a 9796 // constant expression that can be contextually converted to bool. 9797 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 9798 if (Converted.isInvalid()) 9799 Failed = true; 9800 9801 llvm::APSInt Cond; 9802 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 9803 diag::err_static_assert_expression_is_not_constant, 9804 /*AllowFold=*/false).isInvalid()) 9805 Failed = true; 9806 9807 if (!Failed && !Cond) { 9808 llvm::SmallString<256> MsgBuffer; 9809 llvm::raw_svector_ostream Msg(MsgBuffer); 9810 AssertMessage->printPretty(Msg, 0, getPrintingPolicy()); 9811 Diag(StaticAssertLoc, diag::err_static_assert_failed) 9812 << Msg.str() << AssertExpr->getSourceRange(); 9813 Failed = true; 9814 } 9815 } 9816 9817 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 9818 AssertExpr, AssertMessage, RParenLoc, 9819 Failed); 9820 9821 CurContext->addDecl(Decl); 9822 return Decl; 9823} 9824 9825/// \brief Perform semantic analysis of the given friend type declaration. 9826/// 9827/// \returns A friend declaration that. 9828FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation Loc, 9829 SourceLocation FriendLoc, 9830 TypeSourceInfo *TSInfo) { 9831 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 9832 9833 QualType T = TSInfo->getType(); 9834 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 9835 9836 // C++03 [class.friend]p2: 9837 // An elaborated-type-specifier shall be used in a friend declaration 9838 // for a class.* 9839 // 9840 // * The class-key of the elaborated-type-specifier is required. 9841 if (!ActiveTemplateInstantiations.empty()) { 9842 // Do not complain about the form of friend template types during 9843 // template instantiation; we will already have complained when the 9844 // template was declared. 9845 } else if (!T->isElaboratedTypeSpecifier()) { 9846 // If we evaluated the type to a record type, suggest putting 9847 // a tag in front. 9848 if (const RecordType *RT = T->getAs<RecordType>()) { 9849 RecordDecl *RD = RT->getDecl(); 9850 9851 std::string InsertionText = std::string(" ") + RD->getKindName(); 9852 9853 Diag(TypeRange.getBegin(), 9854 getLangOpts().CPlusPlus0x ? 9855 diag::warn_cxx98_compat_unelaborated_friend_type : 9856 diag::ext_unelaborated_friend_type) 9857 << (unsigned) RD->getTagKind() 9858 << T 9859 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc), 9860 InsertionText); 9861 } else { 9862 Diag(FriendLoc, 9863 getLangOpts().CPlusPlus0x ? 9864 diag::warn_cxx98_compat_nonclass_type_friend : 9865 diag::ext_nonclass_type_friend) 9866 << T 9867 << SourceRange(FriendLoc, TypeRange.getEnd()); 9868 } 9869 } else if (T->getAs<EnumType>()) { 9870 Diag(FriendLoc, 9871 getLangOpts().CPlusPlus0x ? 9872 diag::warn_cxx98_compat_enum_friend : 9873 diag::ext_enum_friend) 9874 << T 9875 << SourceRange(FriendLoc, TypeRange.getEnd()); 9876 } 9877 9878 // C++0x [class.friend]p3: 9879 // If the type specifier in a friend declaration designates a (possibly 9880 // cv-qualified) class type, that class is declared as a friend; otherwise, 9881 // the friend declaration is ignored. 9882 9883 // FIXME: C++0x has some syntactic restrictions on friend type declarations 9884 // in [class.friend]p3 that we do not implement. 9885 9886 return FriendDecl::Create(Context, CurContext, Loc, TSInfo, FriendLoc); 9887} 9888 9889/// Handle a friend tag declaration where the scope specifier was 9890/// templated. 9891Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 9892 unsigned TagSpec, SourceLocation TagLoc, 9893 CXXScopeSpec &SS, 9894 IdentifierInfo *Name, SourceLocation NameLoc, 9895 AttributeList *Attr, 9896 MultiTemplateParamsArg TempParamLists) { 9897 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 9898 9899 bool isExplicitSpecialization = false; 9900 bool Invalid = false; 9901 9902 if (TemplateParameterList *TemplateParams 9903 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS, 9904 TempParamLists.get(), 9905 TempParamLists.size(), 9906 /*friend*/ true, 9907 isExplicitSpecialization, 9908 Invalid)) { 9909 if (TemplateParams->size() > 0) { 9910 // This is a declaration of a class template. 9911 if (Invalid) 9912 return 0; 9913 9914 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, 9915 SS, Name, NameLoc, Attr, 9916 TemplateParams, AS_public, 9917 /*ModulePrivateLoc=*/SourceLocation(), 9918 TempParamLists.size() - 1, 9919 (TemplateParameterList**) TempParamLists.release()).take(); 9920 } else { 9921 // The "template<>" header is extraneous. 9922 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 9923 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 9924 isExplicitSpecialization = true; 9925 } 9926 } 9927 9928 if (Invalid) return 0; 9929 9930 bool isAllExplicitSpecializations = true; 9931 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 9932 if (TempParamLists.get()[I]->size()) { 9933 isAllExplicitSpecializations = false; 9934 break; 9935 } 9936 } 9937 9938 // FIXME: don't ignore attributes. 9939 9940 // If it's explicit specializations all the way down, just forget 9941 // about the template header and build an appropriate non-templated 9942 // friend. TODO: for source fidelity, remember the headers. 9943 if (isAllExplicitSpecializations) { 9944 if (SS.isEmpty()) { 9945 bool Owned = false; 9946 bool IsDependent = false; 9947 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 9948 Attr, AS_public, 9949 /*ModulePrivateLoc=*/SourceLocation(), 9950 MultiTemplateParamsArg(), Owned, IsDependent, 9951 /*ScopedEnumKWLoc=*/SourceLocation(), 9952 /*ScopedEnumUsesClassTag=*/false, 9953 /*UnderlyingType=*/TypeResult()); 9954 } 9955 9956 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 9957 ElaboratedTypeKeyword Keyword 9958 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 9959 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 9960 *Name, NameLoc); 9961 if (T.isNull()) 9962 return 0; 9963 9964 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 9965 if (isa<DependentNameType>(T)) { 9966 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc()); 9967 TL.setElaboratedKeywordLoc(TagLoc); 9968 TL.setQualifierLoc(QualifierLoc); 9969 TL.setNameLoc(NameLoc); 9970 } else { 9971 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc()); 9972 TL.setElaboratedKeywordLoc(TagLoc); 9973 TL.setQualifierLoc(QualifierLoc); 9974 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc); 9975 } 9976 9977 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 9978 TSI, FriendLoc); 9979 Friend->setAccess(AS_public); 9980 CurContext->addDecl(Friend); 9981 return Friend; 9982 } 9983 9984 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 9985 9986 9987 9988 // Handle the case of a templated-scope friend class. e.g. 9989 // template <class T> class A<T>::B; 9990 // FIXME: we don't support these right now. 9991 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 9992 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 9993 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 9994 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc()); 9995 TL.setElaboratedKeywordLoc(TagLoc); 9996 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 9997 TL.setNameLoc(NameLoc); 9998 9999 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 10000 TSI, FriendLoc); 10001 Friend->setAccess(AS_public); 10002 Friend->setUnsupportedFriend(true); 10003 CurContext->addDecl(Friend); 10004 return Friend; 10005} 10006 10007 10008/// Handle a friend type declaration. This works in tandem with 10009/// ActOnTag. 10010/// 10011/// Notes on friend class templates: 10012/// 10013/// We generally treat friend class declarations as if they were 10014/// declaring a class. So, for example, the elaborated type specifier 10015/// in a friend declaration is required to obey the restrictions of a 10016/// class-head (i.e. no typedefs in the scope chain), template 10017/// parameters are required to match up with simple template-ids, &c. 10018/// However, unlike when declaring a template specialization, it's 10019/// okay to refer to a template specialization without an empty 10020/// template parameter declaration, e.g. 10021/// friend class A<T>::B<unsigned>; 10022/// We permit this as a special case; if there are any template 10023/// parameters present at all, require proper matching, i.e. 10024/// template <> template \<class T> friend class A<int>::B; 10025Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 10026 MultiTemplateParamsArg TempParams) { 10027 SourceLocation Loc = DS.getLocStart(); 10028 10029 assert(DS.isFriendSpecified()); 10030 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 10031 10032 // Try to convert the decl specifier to a type. This works for 10033 // friend templates because ActOnTag never produces a ClassTemplateDecl 10034 // for a TUK_Friend. 10035 Declarator TheDeclarator(DS, Declarator::MemberContext); 10036 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 10037 QualType T = TSI->getType(); 10038 if (TheDeclarator.isInvalidType()) 10039 return 0; 10040 10041 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 10042 return 0; 10043 10044 // This is definitely an error in C++98. It's probably meant to 10045 // be forbidden in C++0x, too, but the specification is just 10046 // poorly written. 10047 // 10048 // The problem is with declarations like the following: 10049 // template <T> friend A<T>::foo; 10050 // where deciding whether a class C is a friend or not now hinges 10051 // on whether there exists an instantiation of A that causes 10052 // 'foo' to equal C. There are restrictions on class-heads 10053 // (which we declare (by fiat) elaborated friend declarations to 10054 // be) that makes this tractable. 10055 // 10056 // FIXME: handle "template <> friend class A<T>;", which 10057 // is possibly well-formed? Who even knows? 10058 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 10059 Diag(Loc, diag::err_tagless_friend_type_template) 10060 << DS.getSourceRange(); 10061 return 0; 10062 } 10063 10064 // C++98 [class.friend]p1: A friend of a class is a function 10065 // or class that is not a member of the class . . . 10066 // This is fixed in DR77, which just barely didn't make the C++03 10067 // deadline. It's also a very silly restriction that seriously 10068 // affects inner classes and which nobody else seems to implement; 10069 // thus we never diagnose it, not even in -pedantic. 10070 // 10071 // But note that we could warn about it: it's always useless to 10072 // friend one of your own members (it's not, however, worthless to 10073 // friend a member of an arbitrary specialization of your template). 10074 10075 Decl *D; 10076 if (unsigned NumTempParamLists = TempParams.size()) 10077 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 10078 NumTempParamLists, 10079 TempParams.release(), 10080 TSI, 10081 DS.getFriendSpecLoc()); 10082 else 10083 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 10084 10085 if (!D) 10086 return 0; 10087 10088 D->setAccess(AS_public); 10089 CurContext->addDecl(D); 10090 10091 return D; 10092} 10093 10094Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 10095 MultiTemplateParamsArg TemplateParams) { 10096 const DeclSpec &DS = D.getDeclSpec(); 10097 10098 assert(DS.isFriendSpecified()); 10099 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 10100 10101 SourceLocation Loc = D.getIdentifierLoc(); 10102 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 10103 10104 // C++ [class.friend]p1 10105 // A friend of a class is a function or class.... 10106 // Note that this sees through typedefs, which is intended. 10107 // It *doesn't* see through dependent types, which is correct 10108 // according to [temp.arg.type]p3: 10109 // If a declaration acquires a function type through a 10110 // type dependent on a template-parameter and this causes 10111 // a declaration that does not use the syntactic form of a 10112 // function declarator to have a function type, the program 10113 // is ill-formed. 10114 if (!TInfo->getType()->isFunctionType()) { 10115 Diag(Loc, diag::err_unexpected_friend); 10116 10117 // It might be worthwhile to try to recover by creating an 10118 // appropriate declaration. 10119 return 0; 10120 } 10121 10122 // C++ [namespace.memdef]p3 10123 // - If a friend declaration in a non-local class first declares a 10124 // class or function, the friend class or function is a member 10125 // of the innermost enclosing namespace. 10126 // - The name of the friend is not found by simple name lookup 10127 // until a matching declaration is provided in that namespace 10128 // scope (either before or after the class declaration granting 10129 // friendship). 10130 // - If a friend function is called, its name may be found by the 10131 // name lookup that considers functions from namespaces and 10132 // classes associated with the types of the function arguments. 10133 // - When looking for a prior declaration of a class or a function 10134 // declared as a friend, scopes outside the innermost enclosing 10135 // namespace scope are not considered. 10136 10137 CXXScopeSpec &SS = D.getCXXScopeSpec(); 10138 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 10139 DeclarationName Name = NameInfo.getName(); 10140 assert(Name); 10141 10142 // Check for unexpanded parameter packs. 10143 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 10144 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 10145 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 10146 return 0; 10147 10148 // The context we found the declaration in, or in which we should 10149 // create the declaration. 10150 DeclContext *DC; 10151 Scope *DCScope = S; 10152 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 10153 ForRedeclaration); 10154 10155 // FIXME: there are different rules in local classes 10156 10157 // There are four cases here. 10158 // - There's no scope specifier, in which case we just go to the 10159 // appropriate scope and look for a function or function template 10160 // there as appropriate. 10161 // Recover from invalid scope qualifiers as if they just weren't there. 10162 if (SS.isInvalid() || !SS.isSet()) { 10163 // C++0x [namespace.memdef]p3: 10164 // If the name in a friend declaration is neither qualified nor 10165 // a template-id and the declaration is a function or an 10166 // elaborated-type-specifier, the lookup to determine whether 10167 // the entity has been previously declared shall not consider 10168 // any scopes outside the innermost enclosing namespace. 10169 // C++0x [class.friend]p11: 10170 // If a friend declaration appears in a local class and the name 10171 // specified is an unqualified name, a prior declaration is 10172 // looked up without considering scopes that are outside the 10173 // innermost enclosing non-class scope. For a friend function 10174 // declaration, if there is no prior declaration, the program is 10175 // ill-formed. 10176 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass(); 10177 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 10178 10179 // Find the appropriate context according to the above. 10180 DC = CurContext; 10181 while (true) { 10182 // Skip class contexts. If someone can cite chapter and verse 10183 // for this behavior, that would be nice --- it's what GCC and 10184 // EDG do, and it seems like a reasonable intent, but the spec 10185 // really only says that checks for unqualified existing 10186 // declarations should stop at the nearest enclosing namespace, 10187 // not that they should only consider the nearest enclosing 10188 // namespace. 10189 while (DC->isRecord() || DC->isTransparentContext()) 10190 DC = DC->getParent(); 10191 10192 LookupQualifiedName(Previous, DC); 10193 10194 // TODO: decide what we think about using declarations. 10195 if (isLocal || !Previous.empty()) 10196 break; 10197 10198 if (isTemplateId) { 10199 if (isa<TranslationUnitDecl>(DC)) break; 10200 } else { 10201 if (DC->isFileContext()) break; 10202 } 10203 DC = DC->getParent(); 10204 } 10205 10206 // C++ [class.friend]p1: A friend of a class is a function or 10207 // class that is not a member of the class . . . 10208 // C++11 changes this for both friend types and functions. 10209 // Most C++ 98 compilers do seem to give an error here, so 10210 // we do, too. 10211 if (!Previous.empty() && DC->Equals(CurContext)) 10212 Diag(DS.getFriendSpecLoc(), 10213 getLangOpts().CPlusPlus0x ? 10214 diag::warn_cxx98_compat_friend_is_member : 10215 diag::err_friend_is_member); 10216 10217 DCScope = getScopeForDeclContext(S, DC); 10218 10219 // C++ [class.friend]p6: 10220 // A function can be defined in a friend declaration of a class if and 10221 // only if the class is a non-local class (9.8), the function name is 10222 // unqualified, and the function has namespace scope. 10223 if (isLocal && D.isFunctionDefinition()) { 10224 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 10225 } 10226 10227 // - There's a non-dependent scope specifier, in which case we 10228 // compute it and do a previous lookup there for a function 10229 // or function template. 10230 } else if (!SS.getScopeRep()->isDependent()) { 10231 DC = computeDeclContext(SS); 10232 if (!DC) return 0; 10233 10234 if (RequireCompleteDeclContext(SS, DC)) return 0; 10235 10236 LookupQualifiedName(Previous, DC); 10237 10238 // Ignore things found implicitly in the wrong scope. 10239 // TODO: better diagnostics for this case. Suggesting the right 10240 // qualified scope would be nice... 10241 LookupResult::Filter F = Previous.makeFilter(); 10242 while (F.hasNext()) { 10243 NamedDecl *D = F.next(); 10244 if (!DC->InEnclosingNamespaceSetOf( 10245 D->getDeclContext()->getRedeclContext())) 10246 F.erase(); 10247 } 10248 F.done(); 10249 10250 if (Previous.empty()) { 10251 D.setInvalidType(); 10252 Diag(Loc, diag::err_qualified_friend_not_found) 10253 << Name << TInfo->getType(); 10254 return 0; 10255 } 10256 10257 // C++ [class.friend]p1: A friend of a class is a function or 10258 // class that is not a member of the class . . . 10259 if (DC->Equals(CurContext)) 10260 Diag(DS.getFriendSpecLoc(), 10261 getLangOpts().CPlusPlus0x ? 10262 diag::warn_cxx98_compat_friend_is_member : 10263 diag::err_friend_is_member); 10264 10265 if (D.isFunctionDefinition()) { 10266 // C++ [class.friend]p6: 10267 // A function can be defined in a friend declaration of a class if and 10268 // only if the class is a non-local class (9.8), the function name is 10269 // unqualified, and the function has namespace scope. 10270 SemaDiagnosticBuilder DB 10271 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 10272 10273 DB << SS.getScopeRep(); 10274 if (DC->isFileContext()) 10275 DB << FixItHint::CreateRemoval(SS.getRange()); 10276 SS.clear(); 10277 } 10278 10279 // - There's a scope specifier that does not match any template 10280 // parameter lists, in which case we use some arbitrary context, 10281 // create a method or method template, and wait for instantiation. 10282 // - There's a scope specifier that does match some template 10283 // parameter lists, which we don't handle right now. 10284 } else { 10285 if (D.isFunctionDefinition()) { 10286 // C++ [class.friend]p6: 10287 // A function can be defined in a friend declaration of a class if and 10288 // only if the class is a non-local class (9.8), the function name is 10289 // unqualified, and the function has namespace scope. 10290 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 10291 << SS.getScopeRep(); 10292 } 10293 10294 DC = CurContext; 10295 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 10296 } 10297 10298 if (!DC->isRecord()) { 10299 // This implies that it has to be an operator or function. 10300 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName || 10301 D.getName().getKind() == UnqualifiedId::IK_DestructorName || 10302 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) { 10303 Diag(Loc, diag::err_introducing_special_friend) << 10304 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 : 10305 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2); 10306 return 0; 10307 } 10308 } 10309 10310 // FIXME: This is an egregious hack to cope with cases where the scope stack 10311 // does not contain the declaration context, i.e., in an out-of-line 10312 // definition of a class. 10313 Scope FakeDCScope(S, Scope::DeclScope, Diags); 10314 if (!DCScope) { 10315 FakeDCScope.setEntity(DC); 10316 DCScope = &FakeDCScope; 10317 } 10318 10319 bool AddToScope = true; 10320 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 10321 move(TemplateParams), AddToScope); 10322 if (!ND) return 0; 10323 10324 assert(ND->getDeclContext() == DC); 10325 assert(ND->getLexicalDeclContext() == CurContext); 10326 10327 // Add the function declaration to the appropriate lookup tables, 10328 // adjusting the redeclarations list as necessary. We don't 10329 // want to do this yet if the friending class is dependent. 10330 // 10331 // Also update the scope-based lookup if the target context's 10332 // lookup context is in lexical scope. 10333 if (!CurContext->isDependentContext()) { 10334 DC = DC->getRedeclContext(); 10335 DC->makeDeclVisibleInContext(ND); 10336 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 10337 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 10338 } 10339 10340 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 10341 D.getIdentifierLoc(), ND, 10342 DS.getFriendSpecLoc()); 10343 FrD->setAccess(AS_public); 10344 CurContext->addDecl(FrD); 10345 10346 if (ND->isInvalidDecl()) { 10347 FrD->setInvalidDecl(); 10348 } else { 10349 if (DC->isRecord()) CheckFriendAccess(ND); 10350 10351 FunctionDecl *FD; 10352 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 10353 FD = FTD->getTemplatedDecl(); 10354 else 10355 FD = cast<FunctionDecl>(ND); 10356 10357 // Mark templated-scope function declarations as unsupported. 10358 if (FD->getNumTemplateParameterLists()) 10359 FrD->setUnsupportedFriend(true); 10360 } 10361 10362 return ND; 10363} 10364 10365void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 10366 AdjustDeclIfTemplate(Dcl); 10367 10368 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl); 10369 if (!Fn) { 10370 Diag(DelLoc, diag::err_deleted_non_function); 10371 return; 10372 } 10373 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 10374 // Don't consider the implicit declaration we generate for explicit 10375 // specializations. FIXME: Do not generate these implicit declarations. 10376 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization 10377 || Prev->getPreviousDecl()) && !Prev->isDefined()) { 10378 Diag(DelLoc, diag::err_deleted_decl_not_first); 10379 Diag(Prev->getLocation(), diag::note_previous_declaration); 10380 } 10381 // If the declaration wasn't the first, we delete the function anyway for 10382 // recovery. 10383 } 10384 Fn->setDeletedAsWritten(); 10385 10386 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl); 10387 if (!MD) 10388 return; 10389 10390 // A deleted special member function is trivial if the corresponding 10391 // implicitly-declared function would have been. 10392 switch (getSpecialMember(MD)) { 10393 case CXXInvalid: 10394 break; 10395 case CXXDefaultConstructor: 10396 MD->setTrivial(MD->getParent()->hasTrivialDefaultConstructor()); 10397 break; 10398 case CXXCopyConstructor: 10399 MD->setTrivial(MD->getParent()->hasTrivialCopyConstructor()); 10400 break; 10401 case CXXMoveConstructor: 10402 MD->setTrivial(MD->getParent()->hasTrivialMoveConstructor()); 10403 break; 10404 case CXXCopyAssignment: 10405 MD->setTrivial(MD->getParent()->hasTrivialCopyAssignment()); 10406 break; 10407 case CXXMoveAssignment: 10408 MD->setTrivial(MD->getParent()->hasTrivialMoveAssignment()); 10409 break; 10410 case CXXDestructor: 10411 MD->setTrivial(MD->getParent()->hasTrivialDestructor()); 10412 break; 10413 } 10414} 10415 10416void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 10417 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl); 10418 10419 if (MD) { 10420 if (MD->getParent()->isDependentType()) { 10421 MD->setDefaulted(); 10422 MD->setExplicitlyDefaulted(); 10423 return; 10424 } 10425 10426 CXXSpecialMember Member = getSpecialMember(MD); 10427 if (Member == CXXInvalid) { 10428 Diag(DefaultLoc, diag::err_default_special_members); 10429 return; 10430 } 10431 10432 MD->setDefaulted(); 10433 MD->setExplicitlyDefaulted(); 10434 10435 // If this definition appears within the record, do the checking when 10436 // the record is complete. 10437 const FunctionDecl *Primary = MD; 10438 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate) 10439 // Find the uninstantiated declaration that actually had the '= default' 10440 // on it. 10441 MD->getTemplateInstantiationPattern()->isDefined(Primary); 10442 10443 if (Primary == Primary->getCanonicalDecl()) 10444 return; 10445 10446 CheckExplicitlyDefaultedSpecialMember(MD); 10447 10448 switch (Member) { 10449 case CXXDefaultConstructor: { 10450 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD); 10451 if (!CD->isInvalidDecl()) 10452 DefineImplicitDefaultConstructor(DefaultLoc, CD); 10453 break; 10454 } 10455 10456 case CXXCopyConstructor: { 10457 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD); 10458 if (!CD->isInvalidDecl()) 10459 DefineImplicitCopyConstructor(DefaultLoc, CD); 10460 break; 10461 } 10462 10463 case CXXCopyAssignment: { 10464 if (!MD->isInvalidDecl()) 10465 DefineImplicitCopyAssignment(DefaultLoc, MD); 10466 break; 10467 } 10468 10469 case CXXDestructor: { 10470 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD); 10471 if (!DD->isInvalidDecl()) 10472 DefineImplicitDestructor(DefaultLoc, DD); 10473 break; 10474 } 10475 10476 case CXXMoveConstructor: { 10477 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD); 10478 if (!CD->isInvalidDecl()) 10479 DefineImplicitMoveConstructor(DefaultLoc, CD); 10480 break; 10481 } 10482 10483 case CXXMoveAssignment: { 10484 if (!MD->isInvalidDecl()) 10485 DefineImplicitMoveAssignment(DefaultLoc, MD); 10486 break; 10487 } 10488 10489 case CXXInvalid: 10490 llvm_unreachable("Invalid special member."); 10491 } 10492 } else { 10493 Diag(DefaultLoc, diag::err_default_special_members); 10494 } 10495} 10496 10497static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 10498 for (Stmt::child_range CI = S->children(); CI; ++CI) { 10499 Stmt *SubStmt = *CI; 10500 if (!SubStmt) 10501 continue; 10502 if (isa<ReturnStmt>(SubStmt)) 10503 Self.Diag(SubStmt->getLocStart(), 10504 diag::err_return_in_constructor_handler); 10505 if (!isa<Expr>(SubStmt)) 10506 SearchForReturnInStmt(Self, SubStmt); 10507 } 10508} 10509 10510void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 10511 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 10512 CXXCatchStmt *Handler = TryBlock->getHandler(I); 10513 SearchForReturnInStmt(*this, Handler); 10514 } 10515} 10516 10517bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 10518 const CXXMethodDecl *Old) { 10519 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType(); 10520 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType(); 10521 10522 if (Context.hasSameType(NewTy, OldTy) || 10523 NewTy->isDependentType() || OldTy->isDependentType()) 10524 return false; 10525 10526 // Check if the return types are covariant 10527 QualType NewClassTy, OldClassTy; 10528 10529 /// Both types must be pointers or references to classes. 10530 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 10531 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 10532 NewClassTy = NewPT->getPointeeType(); 10533 OldClassTy = OldPT->getPointeeType(); 10534 } 10535 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 10536 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 10537 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 10538 NewClassTy = NewRT->getPointeeType(); 10539 OldClassTy = OldRT->getPointeeType(); 10540 } 10541 } 10542 } 10543 10544 // The return types aren't either both pointers or references to a class type. 10545 if (NewClassTy.isNull()) { 10546 Diag(New->getLocation(), 10547 diag::err_different_return_type_for_overriding_virtual_function) 10548 << New->getDeclName() << NewTy << OldTy; 10549 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 10550 10551 return true; 10552 } 10553 10554 // C++ [class.virtual]p6: 10555 // If the return type of D::f differs from the return type of B::f, the 10556 // class type in the return type of D::f shall be complete at the point of 10557 // declaration of D::f or shall be the class type D. 10558 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 10559 if (!RT->isBeingDefined() && 10560 RequireCompleteType(New->getLocation(), NewClassTy, 10561 diag::err_covariant_return_incomplete, 10562 New->getDeclName())) 10563 return true; 10564 } 10565 10566 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 10567 // Check if the new class derives from the old class. 10568 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 10569 Diag(New->getLocation(), 10570 diag::err_covariant_return_not_derived) 10571 << New->getDeclName() << NewTy << OldTy; 10572 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 10573 return true; 10574 } 10575 10576 // Check if we the conversion from derived to base is valid. 10577 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy, 10578 diag::err_covariant_return_inaccessible_base, 10579 diag::err_covariant_return_ambiguous_derived_to_base_conv, 10580 // FIXME: Should this point to the return type? 10581 New->getLocation(), SourceRange(), New->getDeclName(), 0)) { 10582 // FIXME: this note won't trigger for delayed access control 10583 // diagnostics, and it's impossible to get an undelayed error 10584 // here from access control during the original parse because 10585 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 10586 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 10587 return true; 10588 } 10589 } 10590 10591 // The qualifiers of the return types must be the same. 10592 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 10593 Diag(New->getLocation(), 10594 diag::err_covariant_return_type_different_qualifications) 10595 << New->getDeclName() << NewTy << OldTy; 10596 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 10597 return true; 10598 }; 10599 10600 10601 // The new class type must have the same or less qualifiers as the old type. 10602 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 10603 Diag(New->getLocation(), 10604 diag::err_covariant_return_type_class_type_more_qualified) 10605 << New->getDeclName() << NewTy << OldTy; 10606 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 10607 return true; 10608 }; 10609 10610 return false; 10611} 10612 10613/// \brief Mark the given method pure. 10614/// 10615/// \param Method the method to be marked pure. 10616/// 10617/// \param InitRange the source range that covers the "0" initializer. 10618bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 10619 SourceLocation EndLoc = InitRange.getEnd(); 10620 if (EndLoc.isValid()) 10621 Method->setRangeEnd(EndLoc); 10622 10623 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 10624 Method->setPure(); 10625 return false; 10626 } 10627 10628 if (!Method->isInvalidDecl()) 10629 Diag(Method->getLocation(), diag::err_non_virtual_pure) 10630 << Method->getDeclName() << InitRange; 10631 return true; 10632} 10633 10634/// \brief Determine whether the given declaration is a static data member. 10635static bool isStaticDataMember(Decl *D) { 10636 VarDecl *Var = dyn_cast_or_null<VarDecl>(D); 10637 if (!Var) 10638 return false; 10639 10640 return Var->isStaticDataMember(); 10641} 10642/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 10643/// an initializer for the out-of-line declaration 'Dcl'. The scope 10644/// is a fresh scope pushed for just this purpose. 10645/// 10646/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 10647/// static data member of class X, names should be looked up in the scope of 10648/// class X. 10649void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 10650 // If there is no declaration, there was an error parsing it. 10651 if (D == 0 || D->isInvalidDecl()) return; 10652 10653 // We should only get called for declarations with scope specifiers, like: 10654 // int foo::bar; 10655 assert(D->isOutOfLine()); 10656 EnterDeclaratorContext(S, D->getDeclContext()); 10657 10658 // If we are parsing the initializer for a static data member, push a 10659 // new expression evaluation context that is associated with this static 10660 // data member. 10661 if (isStaticDataMember(D)) 10662 PushExpressionEvaluationContext(PotentiallyEvaluated, D); 10663} 10664 10665/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 10666/// initializer for the out-of-line declaration 'D'. 10667void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 10668 // If there is no declaration, there was an error parsing it. 10669 if (D == 0 || D->isInvalidDecl()) return; 10670 10671 if (isStaticDataMember(D)) 10672 PopExpressionEvaluationContext(); 10673 10674 assert(D->isOutOfLine()); 10675 ExitDeclaratorContext(S); 10676} 10677 10678/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 10679/// C++ if/switch/while/for statement. 10680/// e.g: "if (int x = f()) {...}" 10681DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 10682 // C++ 6.4p2: 10683 // The declarator shall not specify a function or an array. 10684 // The type-specifier-seq shall not contain typedef and shall not declare a 10685 // new class or enumeration. 10686 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 10687 "Parser allowed 'typedef' as storage class of condition decl."); 10688 10689 Decl *Dcl = ActOnDeclarator(S, D); 10690 if (!Dcl) 10691 return true; 10692 10693 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 10694 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 10695 << D.getSourceRange(); 10696 return true; 10697 } 10698 10699 return Dcl; 10700} 10701 10702void Sema::LoadExternalVTableUses() { 10703 if (!ExternalSource) 10704 return; 10705 10706 SmallVector<ExternalVTableUse, 4> VTables; 10707 ExternalSource->ReadUsedVTables(VTables); 10708 SmallVector<VTableUse, 4> NewUses; 10709 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 10710 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 10711 = VTablesUsed.find(VTables[I].Record); 10712 // Even if a definition wasn't required before, it may be required now. 10713 if (Pos != VTablesUsed.end()) { 10714 if (!Pos->second && VTables[I].DefinitionRequired) 10715 Pos->second = true; 10716 continue; 10717 } 10718 10719 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 10720 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 10721 } 10722 10723 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 10724} 10725 10726void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 10727 bool DefinitionRequired) { 10728 // Ignore any vtable uses in unevaluated operands or for classes that do 10729 // not have a vtable. 10730 if (!Class->isDynamicClass() || Class->isDependentContext() || 10731 CurContext->isDependentContext() || 10732 ExprEvalContexts.back().Context == Unevaluated) 10733 return; 10734 10735 // Try to insert this class into the map. 10736 LoadExternalVTableUses(); 10737 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 10738 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 10739 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 10740 if (!Pos.second) { 10741 // If we already had an entry, check to see if we are promoting this vtable 10742 // to required a definition. If so, we need to reappend to the VTableUses 10743 // list, since we may have already processed the first entry. 10744 if (DefinitionRequired && !Pos.first->second) { 10745 Pos.first->second = true; 10746 } else { 10747 // Otherwise, we can early exit. 10748 return; 10749 } 10750 } 10751 10752 // Local classes need to have their virtual members marked 10753 // immediately. For all other classes, we mark their virtual members 10754 // at the end of the translation unit. 10755 if (Class->isLocalClass()) 10756 MarkVirtualMembersReferenced(Loc, Class); 10757 else 10758 VTableUses.push_back(std::make_pair(Class, Loc)); 10759} 10760 10761bool Sema::DefineUsedVTables() { 10762 LoadExternalVTableUses(); 10763 if (VTableUses.empty()) 10764 return false; 10765 10766 // Note: The VTableUses vector could grow as a result of marking 10767 // the members of a class as "used", so we check the size each 10768 // time through the loop and prefer indices (which are stable) to 10769 // iterators (which are not). 10770 bool DefinedAnything = false; 10771 for (unsigned I = 0; I != VTableUses.size(); ++I) { 10772 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 10773 if (!Class) 10774 continue; 10775 10776 SourceLocation Loc = VTableUses[I].second; 10777 10778 bool DefineVTable = true; 10779 10780 // If this class has a key function, but that key function is 10781 // defined in another translation unit, we don't need to emit the 10782 // vtable even though we're using it. 10783 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class); 10784 if (KeyFunction && !KeyFunction->hasBody()) { 10785 switch (KeyFunction->getTemplateSpecializationKind()) { 10786 case TSK_Undeclared: 10787 case TSK_ExplicitSpecialization: 10788 case TSK_ExplicitInstantiationDeclaration: 10789 // The key function is in another translation unit. 10790 DefineVTable = false; 10791 break; 10792 10793 case TSK_ExplicitInstantiationDefinition: 10794 case TSK_ImplicitInstantiation: 10795 // We will be instantiating the key function. 10796 break; 10797 } 10798 } else if (!KeyFunction) { 10799 // If we have a class with no key function that is the subject 10800 // of an explicit instantiation declaration, suppress the 10801 // vtable; it will live with the explicit instantiation 10802 // definition. 10803 bool IsExplicitInstantiationDeclaration 10804 = Class->getTemplateSpecializationKind() 10805 == TSK_ExplicitInstantiationDeclaration; 10806 for (TagDecl::redecl_iterator R = Class->redecls_begin(), 10807 REnd = Class->redecls_end(); 10808 R != REnd; ++R) { 10809 TemplateSpecializationKind TSK 10810 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind(); 10811 if (TSK == TSK_ExplicitInstantiationDeclaration) 10812 IsExplicitInstantiationDeclaration = true; 10813 else if (TSK == TSK_ExplicitInstantiationDefinition) { 10814 IsExplicitInstantiationDeclaration = false; 10815 break; 10816 } 10817 } 10818 10819 if (IsExplicitInstantiationDeclaration) 10820 DefineVTable = false; 10821 } 10822 10823 // The exception specifications for all virtual members may be needed even 10824 // if we are not providing an authoritative form of the vtable in this TU. 10825 // We may choose to emit it available_externally anyway. 10826 if (!DefineVTable) { 10827 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 10828 continue; 10829 } 10830 10831 // Mark all of the virtual members of this class as referenced, so 10832 // that we can build a vtable. Then, tell the AST consumer that a 10833 // vtable for this class is required. 10834 DefinedAnything = true; 10835 MarkVirtualMembersReferenced(Loc, Class); 10836 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 10837 Consumer.HandleVTable(Class, VTablesUsed[Canonical]); 10838 10839 // Optionally warn if we're emitting a weak vtable. 10840 if (Class->getLinkage() == ExternalLinkage && 10841 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) { 10842 const FunctionDecl *KeyFunctionDef = 0; 10843 if (!KeyFunction || 10844 (KeyFunction->hasBody(KeyFunctionDef) && 10845 KeyFunctionDef->isInlined())) 10846 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() == 10847 TSK_ExplicitInstantiationDefinition 10848 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable) 10849 << Class; 10850 } 10851 } 10852 VTableUses.clear(); 10853 10854 return DefinedAnything; 10855} 10856 10857void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 10858 const CXXRecordDecl *RD) { 10859 for (CXXRecordDecl::method_iterator I = RD->method_begin(), 10860 E = RD->method_end(); I != E; ++I) 10861 if ((*I)->isVirtual() && !(*I)->isPure()) 10862 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>()); 10863} 10864 10865void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 10866 const CXXRecordDecl *RD) { 10867 // Mark all functions which will appear in RD's vtable as used. 10868 CXXFinalOverriderMap FinalOverriders; 10869 RD->getFinalOverriders(FinalOverriders); 10870 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 10871 E = FinalOverriders.end(); 10872 I != E; ++I) { 10873 for (OverridingMethods::const_iterator OI = I->second.begin(), 10874 OE = I->second.end(); 10875 OI != OE; ++OI) { 10876 assert(OI->second.size() > 0 && "no final overrider"); 10877 CXXMethodDecl *Overrider = OI->second.front().Method; 10878 10879 // C++ [basic.def.odr]p2: 10880 // [...] A virtual member function is used if it is not pure. [...] 10881 if (!Overrider->isPure()) 10882 MarkFunctionReferenced(Loc, Overrider); 10883 } 10884 } 10885 10886 // Only classes that have virtual bases need a VTT. 10887 if (RD->getNumVBases() == 0) 10888 return; 10889 10890 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(), 10891 e = RD->bases_end(); i != e; ++i) { 10892 const CXXRecordDecl *Base = 10893 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl()); 10894 if (Base->getNumVBases() == 0) 10895 continue; 10896 MarkVirtualMembersReferenced(Loc, Base); 10897 } 10898} 10899 10900/// SetIvarInitializers - This routine builds initialization ASTs for the 10901/// Objective-C implementation whose ivars need be initialized. 10902void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 10903 if (!getLangOpts().CPlusPlus) 10904 return; 10905 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 10906 SmallVector<ObjCIvarDecl*, 8> ivars; 10907 CollectIvarsToConstructOrDestruct(OID, ivars); 10908 if (ivars.empty()) 10909 return; 10910 SmallVector<CXXCtorInitializer*, 32> AllToInit; 10911 for (unsigned i = 0; i < ivars.size(); i++) { 10912 FieldDecl *Field = ivars[i]; 10913 if (Field->isInvalidDecl()) 10914 continue; 10915 10916 CXXCtorInitializer *Member; 10917 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 10918 InitializationKind InitKind = 10919 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 10920 10921 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0); 10922 ExprResult MemberInit = 10923 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg()); 10924 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 10925 // Note, MemberInit could actually come back empty if no initialization 10926 // is required (e.g., because it would call a trivial default constructor) 10927 if (!MemberInit.get() || MemberInit.isInvalid()) 10928 continue; 10929 10930 Member = 10931 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 10932 SourceLocation(), 10933 MemberInit.takeAs<Expr>(), 10934 SourceLocation()); 10935 AllToInit.push_back(Member); 10936 10937 // Be sure that the destructor is accessible and is marked as referenced. 10938 if (const RecordType *RecordTy 10939 = Context.getBaseElementType(Field->getType()) 10940 ->getAs<RecordType>()) { 10941 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 10942 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 10943 MarkFunctionReferenced(Field->getLocation(), Destructor); 10944 CheckDestructorAccess(Field->getLocation(), Destructor, 10945 PDiag(diag::err_access_dtor_ivar) 10946 << Context.getBaseElementType(Field->getType())); 10947 } 10948 } 10949 } 10950 ObjCImplementation->setIvarInitializers(Context, 10951 AllToInit.data(), AllToInit.size()); 10952 } 10953} 10954 10955static 10956void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 10957 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid, 10958 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid, 10959 llvm::SmallSet<CXXConstructorDecl*, 4> &Current, 10960 Sema &S) { 10961 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(), 10962 CE = Current.end(); 10963 if (Ctor->isInvalidDecl()) 10964 return; 10965 10966 const FunctionDecl *FNTarget = 0; 10967 CXXConstructorDecl *Target; 10968 10969 // We ignore the result here since if we don't have a body, Target will be 10970 // null below. 10971 (void)Ctor->getTargetConstructor()->hasBody(FNTarget); 10972 Target 10973= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget)); 10974 10975 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 10976 // Avoid dereferencing a null pointer here. 10977 *TCanonical = Target ? Target->getCanonicalDecl() : 0; 10978 10979 if (!Current.insert(Canonical)) 10980 return; 10981 10982 // We know that beyond here, we aren't chaining into a cycle. 10983 if (!Target || !Target->isDelegatingConstructor() || 10984 Target->isInvalidDecl() || Valid.count(TCanonical)) { 10985 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI) 10986 Valid.insert(*CI); 10987 Current.clear(); 10988 // We've hit a cycle. 10989 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 10990 Current.count(TCanonical)) { 10991 // If we haven't diagnosed this cycle yet, do so now. 10992 if (!Invalid.count(TCanonical)) { 10993 S.Diag((*Ctor->init_begin())->getSourceLocation(), 10994 diag::warn_delegating_ctor_cycle) 10995 << Ctor; 10996 10997 // Don't add a note for a function delegating directo to itself. 10998 if (TCanonical != Canonical) 10999 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 11000 11001 CXXConstructorDecl *C = Target; 11002 while (C->getCanonicalDecl() != Canonical) { 11003 (void)C->getTargetConstructor()->hasBody(FNTarget); 11004 assert(FNTarget && "Ctor cycle through bodiless function"); 11005 11006 C 11007 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget)); 11008 S.Diag(C->getLocation(), diag::note_which_delegates_to); 11009 } 11010 } 11011 11012 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI) 11013 Invalid.insert(*CI); 11014 Current.clear(); 11015 } else { 11016 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 11017 } 11018} 11019 11020 11021void Sema::CheckDelegatingCtorCycles() { 11022 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 11023 11024 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(), 11025 CE = Current.end(); 11026 11027 for (DelegatingCtorDeclsType::iterator 11028 I = DelegatingCtorDecls.begin(ExternalSource), 11029 E = DelegatingCtorDecls.end(); 11030 I != E; ++I) { 11031 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 11032 } 11033 11034 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI) 11035 (*CI)->setInvalidDecl(); 11036} 11037 11038namespace { 11039 /// \brief AST visitor that finds references to the 'this' expression. 11040 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 11041 Sema &S; 11042 11043 public: 11044 explicit FindCXXThisExpr(Sema &S) : S(S) { } 11045 11046 bool VisitCXXThisExpr(CXXThisExpr *E) { 11047 S.Diag(E->getLocation(), diag::err_this_static_member_func) 11048 << E->isImplicit(); 11049 return false; 11050 } 11051 }; 11052} 11053 11054bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 11055 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 11056 if (!TSInfo) 11057 return false; 11058 11059 TypeLoc TL = TSInfo->getTypeLoc(); 11060 FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL); 11061 if (!ProtoTL) 11062 return false; 11063 11064 // C++11 [expr.prim.general]p3: 11065 // [The expression this] shall not appear before the optional 11066 // cv-qualifier-seq and it shall not appear within the declaration of a 11067 // static member function (although its type and value category are defined 11068 // within a static member function as they are within a non-static member 11069 // function). [ Note: this is because declaration matching does not occur 11070 // until the complete declarator is known. - end note ] 11071 const FunctionProtoType *Proto = ProtoTL->getTypePtr(); 11072 FindCXXThisExpr Finder(*this); 11073 11074 // If the return type came after the cv-qualifier-seq, check it now. 11075 if (Proto->hasTrailingReturn() && 11076 !Finder.TraverseTypeLoc(ProtoTL->getResultLoc())) 11077 return true; 11078 11079 // Check the exception specification. 11080 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 11081 return true; 11082 11083 return checkThisInStaticMemberFunctionAttributes(Method); 11084} 11085 11086bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 11087 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 11088 if (!TSInfo) 11089 return false; 11090 11091 TypeLoc TL = TSInfo->getTypeLoc(); 11092 FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL); 11093 if (!ProtoTL) 11094 return false; 11095 11096 const FunctionProtoType *Proto = ProtoTL->getTypePtr(); 11097 FindCXXThisExpr Finder(*this); 11098 11099 switch (Proto->getExceptionSpecType()) { 11100 case EST_Uninstantiated: 11101 case EST_Unevaluated: 11102 case EST_BasicNoexcept: 11103 case EST_DynamicNone: 11104 case EST_MSAny: 11105 case EST_None: 11106 break; 11107 11108 case EST_ComputedNoexcept: 11109 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 11110 return true; 11111 11112 case EST_Dynamic: 11113 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(), 11114 EEnd = Proto->exception_end(); 11115 E != EEnd; ++E) { 11116 if (!Finder.TraverseType(*E)) 11117 return true; 11118 } 11119 break; 11120 } 11121 11122 return false; 11123} 11124 11125bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 11126 FindCXXThisExpr Finder(*this); 11127 11128 // Check attributes. 11129 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end(); 11130 A != AEnd; ++A) { 11131 // FIXME: This should be emitted by tblgen. 11132 Expr *Arg = 0; 11133 ArrayRef<Expr *> Args; 11134 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A)) 11135 Arg = G->getArg(); 11136 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A)) 11137 Arg = G->getArg(); 11138 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A)) 11139 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size()); 11140 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A)) 11141 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size()); 11142 else if (ExclusiveLockFunctionAttr *ELF 11143 = dyn_cast<ExclusiveLockFunctionAttr>(*A)) 11144 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size()); 11145 else if (SharedLockFunctionAttr *SLF 11146 = dyn_cast<SharedLockFunctionAttr>(*A)) 11147 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size()); 11148 else if (ExclusiveTrylockFunctionAttr *ETLF 11149 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) { 11150 Arg = ETLF->getSuccessValue(); 11151 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size()); 11152 } else if (SharedTrylockFunctionAttr *STLF 11153 = dyn_cast<SharedTrylockFunctionAttr>(*A)) { 11154 Arg = STLF->getSuccessValue(); 11155 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size()); 11156 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A)) 11157 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size()); 11158 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A)) 11159 Arg = LR->getArg(); 11160 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A)) 11161 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size()); 11162 else if (ExclusiveLocksRequiredAttr *ELR 11163 = dyn_cast<ExclusiveLocksRequiredAttr>(*A)) 11164 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size()); 11165 else if (SharedLocksRequiredAttr *SLR 11166 = dyn_cast<SharedLocksRequiredAttr>(*A)) 11167 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size()); 11168 11169 if (Arg && !Finder.TraverseStmt(Arg)) 11170 return true; 11171 11172 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 11173 if (!Finder.TraverseStmt(Args[I])) 11174 return true; 11175 } 11176 } 11177 11178 return false; 11179} 11180 11181void 11182Sema::checkExceptionSpecification(ExceptionSpecificationType EST, 11183 ArrayRef<ParsedType> DynamicExceptions, 11184 ArrayRef<SourceRange> DynamicExceptionRanges, 11185 Expr *NoexceptExpr, 11186 llvm::SmallVectorImpl<QualType> &Exceptions, 11187 FunctionProtoType::ExtProtoInfo &EPI) { 11188 Exceptions.clear(); 11189 EPI.ExceptionSpecType = EST; 11190 if (EST == EST_Dynamic) { 11191 Exceptions.reserve(DynamicExceptions.size()); 11192 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 11193 // FIXME: Preserve type source info. 11194 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 11195 11196 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 11197 collectUnexpandedParameterPacks(ET, Unexpanded); 11198 if (!Unexpanded.empty()) { 11199 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(), 11200 UPPC_ExceptionType, 11201 Unexpanded); 11202 continue; 11203 } 11204 11205 // Check that the type is valid for an exception spec, and 11206 // drop it if not. 11207 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 11208 Exceptions.push_back(ET); 11209 } 11210 EPI.NumExceptions = Exceptions.size(); 11211 EPI.Exceptions = Exceptions.data(); 11212 return; 11213 } 11214 11215 if (EST == EST_ComputedNoexcept) { 11216 // If an error occurred, there's no expression here. 11217 if (NoexceptExpr) { 11218 assert((NoexceptExpr->isTypeDependent() || 11219 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 11220 Context.BoolTy) && 11221 "Parser should have made sure that the expression is boolean"); 11222 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 11223 EPI.ExceptionSpecType = EST_BasicNoexcept; 11224 return; 11225 } 11226 11227 if (!NoexceptExpr->isValueDependent()) 11228 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0, 11229 diag::err_noexcept_needs_constant_expression, 11230 /*AllowFold*/ false).take(); 11231 EPI.NoexceptExpr = NoexceptExpr; 11232 } 11233 return; 11234 } 11235} 11236 11237/// IdentifyCUDATarget - Determine the CUDA compilation target for this function 11238Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) { 11239 // Implicitly declared functions (e.g. copy constructors) are 11240 // __host__ __device__ 11241 if (D->isImplicit()) 11242 return CFT_HostDevice; 11243 11244 if (D->hasAttr<CUDAGlobalAttr>()) 11245 return CFT_Global; 11246 11247 if (D->hasAttr<CUDADeviceAttr>()) { 11248 if (D->hasAttr<CUDAHostAttr>()) 11249 return CFT_HostDevice; 11250 else 11251 return CFT_Device; 11252 } 11253 11254 return CFT_Host; 11255} 11256 11257bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget, 11258 CUDAFunctionTarget CalleeTarget) { 11259 // CUDA B.1.1 "The __device__ qualifier declares a function that is... 11260 // Callable from the device only." 11261 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device) 11262 return true; 11263 11264 // CUDA B.1.2 "The __global__ qualifier declares a function that is... 11265 // Callable from the host only." 11266 // CUDA B.1.3 "The __host__ qualifier declares a function that is... 11267 // Callable from the host only." 11268 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) && 11269 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global)) 11270 return true; 11271 11272 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice) 11273 return true; 11274 11275 return false; 11276} 11277