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