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