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