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