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