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